Nginx user restriction checked with cookies - nginx

I'm working on a little PHP Service on my webserver for my clients. The concept is simple:
I'm making a website for a client of mine locally. I upload it onto my publicly accesible webserver. Now I don't want anybody to have access onto every website. So I made a login form (via password) with php and html. The userdata is saved in a MySQL Database.
So if a user gets the url of me (e.g. client.raphaelbernhart.at) there is a input field with a password to be filled out. Now if the user submits the password the php script checks is there is a user with this password and creates a session and cookie.
As the information (client websites) are most of the time not very sensitive I wanted to proof with the nginx configuration if a cookie is created at the clients computer and if the path (url) contains the username specified inside the cookie. My configuration for something like this would be:
location /client {
# Check if url contains auth cookie value
if ($request_uri != $cookie_auth){
return 401;
}
}
But this isn't working...
It would be greate if anybody could help me with this problem...thanks
Also I want to check if there is a administrator cookie created and then always send status 200.
Something like this:
# Check if url contains auth cookie value
if ($cookie_auth = "administrator"){
return 200;
}
But this isn't working to.

Try
location /client {
set $deny 1;
if ($uri ~ ^/client/$cookie_auth) {
set $deny '';
}
if ($cookie_auth = administrator) {
set $deny '';
}
if ($cookie_auth = '') {
set $deny 1;
}
if ($deny) {
return 401;
}
... # further processing
}

Related

WordPress wp-admin/includes/class-ftp.php FTP not able to login

I am using the following code in my file
require ABSPATH.'wp-admin/includes/class-ftp.php';
$ftp = new ftp();
$ftp->Verbose = TRUE;
$ftp->LocalEcho = TRUE;
if (!$ftp->SetServer(self::$form_vars['host']))
{
$ftp->quit();
die("Setting server failed\n");
}
if (!$ftp->connect())
{
die("Cannot connect\n");
}
if (!$ftp->login(self::$form_vars['user'], self::$form_vars['pass']))
{
die("Login failed\n");
$ftp->quit();
}
I am not able to login, it says Login Failed.
The same FTP works with Filezila. but not works using the script default wordprss ftp class.
It gives the following error also
GET < 421-Sorry, cleartext sessions and weak ciphers are not accepted on this server.
421 Please reconnect using TLS security mechanisms.
Any solution.

Symfony4, log out the user if the IP has changed

I want to log out the user if the IP has changed.
I managed to make it by creating a field lastLoginIp in the Users table, setting it in the onAuthenticationSuccess, and then checking in the User::isEqualTo() method:
if($user->getLastLoginIp() !== Utils::getIp()) {
return false;
}
The problem is that it broke impersonation, because of course the IP of the admin is different than the IP of the user.
How can this be implemented? (and the user must not get logged out if somebody impersonates him)
Why not skip ip check if is granted ROLE_PREVIOUS_ADMIN?
if ($this->security->isGranted('ROLE_PREVIOUS_ADMIN')) {
return true;
}

Can IIS require SSL client certificates without mapping them to a windows user?

I want to be able to map SSL client certificates to ASP.NET Identity users. I would like IIS to do as much of the work as possible (negotiating the client certificate and perhaps validating that it is signed by a trusted CA), but I don't want IIS to map the certificate to a Windows user. The client certificate is passed through to ASP.NET, where it is inspected and mapped to an ASP.NET Identity user, which is turned into a ClaimsPrincipal.
So far, the only way I have been able to get IIS to pass the client certificate through to ASP.NET is to enable iisClientCertificateMappingAuthentication and set up a many-to-one mapping to a Windows account (which is then never used for anything else.) Is there any way to get IIS to negotiate and pass the certificate through without this configuration step?
You do not have to use the iisClientCertificateMappingAuthentication. The client certificate is accessible in the HttpContext.
var clientCert = HttpContext.Request.ClientCertificate;
Either you enable RequireClientCertificate on the complete site or use a separate login-with-clientcertificate page.
Below is one way of doing this in ASP.NET MVC. Hopefully you can use parts of it to fit your exact situation.
First make sure you are allowed to set the SslFlags in web.config by turning on feature delegation.
Make site accept (but not require) Client Certificates
Set path to login-with-clientcertificate-page where client certificates will be required. In this case a User controller with a CertificateSignin action.
Create a login controller (pseudo-code)
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
[AllowAnonymous()]
public ActionResult CertificateSignIn()
{
//Get certificate
var clientCert = HttpContext.Request.ClientCertificate;
//Validate certificate
if (!clientCert.IsPresent || !clientCert.IsValid)
{
ViewBag.LoginFailedMessage = "The client certificate was not present or did not pass validation";
return View("Index");
}
//Call your "custom" ClientCertificate --> User mapping method.
string userId;
bool myCertificateMappingParsingResult = Helper.MyCertificateMapping(clientCert, out userId);
if (!myCertificateMappingParsingResult)
{
ViewBag.LoginFailedMessage = "Your client certificate did not map correctly";
}
else
{
//Use custom Membersip provider. Password is not needed!
if (Membership.ValidateUser(userId, null))
{
//Create authentication ticket
FormsAuthentication.SetAuthCookie(userId, false);
Response.Redirect("~/");
}
else
{
ViewBag.LoginFailedMessage = "Login failed!";
}
}
return View("Index");
}

With Meteor, how to login from remote server?

I'm trying to use 2 servers using DDP.connect.
My subscription works well, but methods called using Meteor.call needs the user to be authenticated.
How can i connect the user to the remote server ?
You can authenticate this way:
var DDPConnection = DDP.connect(<url>);
DDPConnection.call("login", {
"password":"qwerty",
"user" : {
"email":"email#email.com"
}
},
function(err,result) {
//Check result
}
);
Check out my other answer on the different login options depending on the setup you have/want to use.

How to detect server-side whether cookies are disabled

How can I detect on the server (server-side) whether cookies in the browser are disabled? Is it possible?
Detailed explanation: I am processing an HTTP request on the server. I want to set a cookie via the Set-Cookie header. I need to know at that time whether the cookie will be set by the client browser or my request to set the cookie will be ignored.
Send a redirect response with the cookie set; when processing the (special) redirected URL test for the cookie - if it's there redirect to normal processing, otherwise redirect to an error state.
Note that this can only tell you the browser permitted the cookie to be set, but not for how long. My FF allows me to force all cookies to "session" mode, unless the site is specifically added to an exception list - such cookies will be discarded when FF shuts down regardless of the server specified expiry. And this is the mode I run FF in always.
You can use Javascript to accomplish that
Library:
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
function areCookiesEnabled() {
var r = false;
createCookie("testing", "Hello", 1);
if (readCookie("testing") != null) {
r = true;
eraseCookie("testing");
}
return r;
}
Code to run:
alert(areCookiesEnabled());
Remember
This only works if Javascript is enabled!
I dont think there are direct ways to check. The best way is to store a value in the cookie and try to read them and decide whether cookies are enabled or not.
The below answer was written a long time ago. Now, for better or worse, due to laws in various countries it has become either good practice - or a legal requirement - not to require cookies except where necessary, at least until the user has had a chance to consent to such mechanisms.
It's a good idea to only do this when the user is trying to do something that initiates a session, such as logging in, or adding something to their cart. Otherwise, depending on how you handle it, you're potentially blocking access to your entire site for users - or bots - that don't support cookies.
First, the server checks the login data as normal - if the login data is wrong the user receives that feedback as normal. If it's right, then the server immediately responds with a cookie and a redirect to a page which is designed to check for that cookie - which may just be the same URL but with some flag added to the query string. If that second page doesn't receive the cookie, then the user receives a message stating that they cannot log in because cookies are disabled on their browser.
If you're following the Post-Redirect-Get pattern for your login form already, then this setting and checking of the cookie does not add any additional requests - the cookie can be set during the existing redirect, and checked by the destination that loads after the redirect.
Now for why I only do a cookie test after a user-initiated action other than on every page load. I have seen sites implement a cookie test on every single page, not realising that this is going to have effects on things like search engines trying to crawl the site. That is, if a user has cookies enabled, then the test cookie is set once, so they only have to endure a redirect on the first page they request and from then on there are no redirects. However, for any browser or other user-agent, like a search engine, that doesn't return cookies, every single page could simply result in a redirect.
Another method of checking for cookie support is with Javascript - this way, no redirect is necessarily needed - you can write a cookie and read it back virtually immediately to see if it was stored and then retrieved. The downside to this is it runs in script on the client side - ie if you still want the message about whether cookies are supported to get back to the server, then you still have to organise that - such as with an Ajax call.
For my own application, I implement some protection for 'Login CSRF' attacks, a variant of CSRF attacks, by setting a cookie containing a random token on the login screen before the user logs in, and checking that token when the user submits their login details. Read more about Login CSRF from Google. A side effect of this is that the moment they do log in, I can check for the existence of that cookie - an extra redirect is not necessary.
Try to store something into a cookie, and then read it. If you don't get what you expect, then cookies are probably disabled.
I always used this:
navigator.cookieEnabled
According to w3schools "The cookieEnabled property is supported in all major browsers.".
However, this works for me when i am using forms, where i can instruct the browser to send the additional information.
check this code , it' will help you .
<?php
session_start();
function visitor_is_enable_cookie() {
$cn = 'cookie_is_enabled';
if (isset($_COOKIE[$cn]))
return true;
elseif (isset($_SESSION[$cn]) && $_SESSION[$cn] === false)
return false;
// saving cookie ... and after it we have to redirect to get this
setcookie($cn, '1');
// redirect to get the cookie
if(!isset($_GET['nocookie']))
header("location: ".$_SERVER['REQUEST_URI'].'?nocookie') ;
// cookie isn't availble
$_SESSION[$cn] = false;
return false;
}
var_dump(visitor_is_enable_cookie());
NodeJS - Server Side - Cookie Check Redirect
Middleware - Express Session/Cookie Parser
Dependencies
var express = require('express'),
cookieParser = require('cookie-parser'),
expressSession = require('express-session')
Middleware
return (req, res, next) => {
if(req.query.cookie && req.cookies.cookies_enabled)
return res.redirect('https://yourdomain.io' + req.path)
if(typeof(req.cookies.cookies_enabled) === 'undefined' && typeof(req.query.cookie) === 'undefined') {
return res.cookie('cookies_enabled', true, {
path: '/',
domain: '.yourdomain.io',
maxAge: 900000,
httpOnly: true,
secure: process.env.NODE_ENV ? true : false
}).redirect(req.url + '?cookie=1')
}
if(typeof(req.cookies.cookies_enabled) === 'undefined') {
var target_page = 'https://yourdomain.io' + (req.url ? req.url : '')
res.send('You must enable cookies to view this site.<br/>Once enabled, click here.')
res.end()
return
}
next()
}
The question whether cookies are "enabled" is too boolean. My browser (Opera) has a per-site cookie setting. Furthermore, that setting is not yes/no. The most useful form is in fact "session-only", ignoring the servers' expiry date. If you test it directly after setting, it will be there. Tomorrow, it won't.
Also, since it's a setting you can change, even testing whether cookies do remain only tells you about the setting when you tested. I might have decided to accept that one cookie, manually. If I keep being spammed, I can (and at times, will) just turn off cookies for that site.
If you only want to check if session cookies (cookies that exist for the lifetime of the session) are enabled, set your session mode to AutoDetect in your web.config file, then the Asp.Net framework will write a cookie to the client browser called AspxAutoDetectCookieSupport. You can then look for this cookie in the Request.Cookies collection to check if session cookies are enabled on the client.
E.g. in your web.config file set:
<sessionState cookieless="AutoDetect" />
Then check if cookies are enabled on the client with:
if (Request.Cookies["AspxAutoDetectCookieSupport"] != null) { ... }
Sidenote: By default this is set to UseDeviceProfile, which will attempt to write cookies to the client so long as the client supports them, even if cookies are disabled. I find it slightly odd that this is the default option as it seems sort of pointless - sessions won't work with cookies disabled in the client browser with it set to UseDeviceProfile, and if you support cookieless mode for clients that don't support cookies, then why not use AutoDetect and support cookieless mode for clients that have them disabled...
I'm using a much more simplified version of "balexandre"'s answer above. It tries to set, and read a session cookie for the sole purpose of determining if cookies are enabled. And yes, this requires that JavaScript is enabled as well. So you may want a tag in there if you care to have one.
<script>
// Cookie detection
document.cookie = "testing=cookies_enabled; path=/";
if(document.cookie.indexOf("testing=cookies_enabled") < 0)
{
// however you want to handle if cookies are disabled
alert("Cookies disabled");
}
</script>
<noscript>
<!-- However you like handling your no JavaScript message -->
<h1>This site requires JavaScript.</h1>
</noscript>
The cookieEnabled property returns a Boolean value that specifies whether or not cookies are enabled in the browser
<script>
if (navigator.cookieEnabled) {
// Cookies are enabled
}
else {
// Cookies are disabled
}
</script>
<?php session_start();
if(SID!=null){
echo "Please enable cookie";
}
?>
Use navigator.CookieEnabled for cookies enabled(it will return true of false) and the Html tag noscript. By the way navigator.cookieEnabled is javascript so don't type it in as HTML

Resources