Secure cookies available via HTTP - php

I noticed something earlier today while inspecting cookies on some of my subdomains that surprised me a little. Although I have set PHP to use only secure cookies, they are nonetheless available using HTTP.
My root domain and most of my subdomains are HTTPS. In fact, they are essentially HTTPS only. I haven't enabled HSTS because I have subdomains that are HTTP only and do not support HTTPS. (Essentially, my domains are either HTTPS only or HTTP only, not both.) While navigating to these subdomains, I noticed the cookies set by the root domain show up in the browser developer tools, and are seemingly sent on requests to the server.
I'd prefer this not happen because a) it's insecure and b) the server handling these subdomains does squat with these cookies so sending them at all is an unnecessary risk that could compromise the main applications.
The weird thing is my cookies are already secure. All cookies are set like so:
setCookie("my_cookie", $cookieValue, $expires, '/', $domain, true, true);
At the top of my session manager, I also have:
session_set_cookie_params(3600, '/', '.example.com', true, true);
The last trues are secure and httpOnly. One would think this makes them HTTP-only:
HTTPS: Cookie with "Secure" will be returned only on HTTPS connections
Reading cookies via HTTPS that were set using HTTP
To ensure that the session cookie is sent only on HTTPS connections,
you can use the function session_set_cookie_params() before starting
the session: https://stackoverflow.com/a/6531754/6110631
A cookie with the Secure attribute is sent to the server only with an
encrypted request over the HTTPS protocol, never with unsecured HTTP,
and therefore can't easily be accessed by a man-in-the-middle
attacker. Insecure sites (with http: in the URL) can't set cookies
with the Secure attribute. However, do not assume that Secure prevents
all access to sensitive information in cookies; for example, it can be
read by someone with access to the client's hard disk.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Secure_and_HttpOnly_cookies
But lo and behold, all cookies that I set on the root domain continue to be available on my HTTP-only subdomains. Using the developer tools, any changes with cookies in the root domain continue to be reflected on HTTP-only subdomains!
I intentionally set the cookie as .domain to make it available on all subdomains, since they all share session information and enable SSO (the HTTPS domains, that is). However, I would think that with the secure flag, this would still prevent the cookies from being available on HTTP-only subdomains. Does one of these parameters take precedence over another? (I would think secure would).
Why is this not working as intended? It seems that because the cookies are available, even though I have secure and httpOnly, the cookies could be stolen from an unencrypted HTTP connection. Is it that the cookies are not actually sent, but the browser (erroneously) displays them as present anyways, or is there a real security risk here?

The browser developer tools seems to make a distinction between displaying cookies that may be available on a domain and those that are actually sent in the request - that is to say, the developer tools will show cookies for a subdomain even if they are never sent on requests to the server.
Here's an example of a request to the root domain:
:authority: example.com
:method: GET
:path: /account
:scheme: https
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cache-control: max-age=0
cookie: [cookies redacted]
dnt: 1
referer: [redacted]
upgrade-insecure-requests: 1
user-agent: [redacted]
Here's an example of a request to an HTTP-only subdomain:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Cache-Control: max-age=0
Connection: keep-alive
DNT: 1
Host: subdomain.example.com
If-Modified-Since: Wed, 27 May 2020 20:51:35 GMT
If-None-Match: "6c5-5a6a760afe782-gzip"
Upgrade-Insecure-Requests: 1
User-Agent: [redacted]
As one can see, cookies are not sent with the second request. However, if you examine the cookies on both domains in the browser, you can see the browser displays them regardless:
This can be a source of confusion, but examining the request headers shows that the browser does indeed refrain from sending the secure cookies on insecure requests.

Related

Set-Cookie header not creating cookie in test environment

I have a local testing application mimicking the host test.mywebsite.com on port 4200.
It makes a call to api.test.mywebsite.com (also locally hosted) to /login
The request passes, the server returns 200 and some information, and along with it it sets this header which I see in the response headers:
Set-Cookie: refreshToken={JWT here}; expires=Sun, 23-May-2021 20:38:32 GMT; Max-Age=1296000; path=/; domain=.test.mywebsite.com; HttpOnly
This doesn't get stored in my browser (either Chrome or Firefox) and I'm trying to figure out why.
Here's some more information about my setup if needed:
Angular server using ng serve --host=test.mywebsite.com to get the test frontend up on http://test.mywebsite.com:4200
Kubernetes backend running on localhost (with my hosts file redirecting api.test.mywebsite.com to 127.0.0.1) which directs the request to a PHP pod that creates the cookie using this code:
setcookie(
"refreshToken", // name
$refreshJWT->token, // token
$refreshJWT->expiration, // expires in 15 days
'/', // path
".".$refreshJWT->domain, // domain
($refreshJWT->environmentType === "test") ? false : true, // security
true // httponly
);
I fear it's something painfully simple or an oversight somewhere, but can't for the life of me find out what. The only thing I can think of would be the port not matching with the cookie host, but as far as I know cookie domains are port-agnostic. I've tried adding :4200 to the end of the cookie domain anyway and still have the same problem.
Update: setcookie() returns true, so there's no output previous to setting the header.
Update2: I deployed it to a staging server and the problem still occurs despite no DNS trickery or proxies going on.
Update3: I've narrowed it down to a combination of my api server's Access-Control-Allow-Origin header, and my JS' use of withCredentials
My Access-Control-Allow-Origin is set to *. If I send the request withCredentials as false, it returns the body to the JS but refuses the cookie. If I set withCredentials to true, it sets the cookie but refuses to allow the JS to read the body.
I found out the reason, for anyone who may be stumbling on this:
The first problems was while my requests were going through and returning 200, the cookie was not being set because I didn't agree to receive a cookie on the frontend. To agree to cookies on the frontend, I had to use withCredentials.
The second problem was on the backend, I didn't explicitly send the header Access-Control-Allow-Credentials This would allow both front and backend to agree to a cookie exchange.
The third problem was my backend had a wildcard set for Access-Control-Allow-Origin, which my browser requires to match the current host exactly if withCredentials is used.
It makes a call to api.test.mywebsite.com
...
domain=.test.mywebsite.com
These need to be the same hostname

XSRF-Token in Laravel

I implement login in laravel on login request there is two token generate one in body and another one is in header cookie.
When i remove value of body token it's show page expired error but when I remove value of xsrf-token it's not shows any error and login getting succesfull
POST /login HTTP/1.1
Host: <host>
Content-Length: 513
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
Origin: <Origin Address>
Content-Type: application/x-www-form-urlencoded
User-Agent:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Cookie: XSRF-TOKEN=<token>; laravel_session=<session token>
Connection: close
_token=<token>&userName=<userName>&password=<Password>
Anyone help me to explain this both token. and why page is not getting expired on remove value of xsrf-token value using burpusite tool.
as mentioned in laravel document:
Laravel makes it easy to protect your application from cross-site
request forgery (CSRF) attacks. Cross-site request forgeries are a
type of malicious exploit whereby unauthorized commands are performed
on behalf of an authenticated user.
also:
Laravel stores the current CSRF token in an encrypted XSRF-TOKEN
cookie that is included with each response generated by the framework.
You can use the cookie value to set the X-XSRF-TOKEN request header.
This cookie is primarily sent as a convenience since some JavaScript frameworks and libraries, like Angular and Axios, automatically place its value in the X-XSRF-TOKEN header on same-origin requests.

Mediawiki login cancelled to prevent session hijacking

I have just set up a MediaWiki 1.29.0 page on an AS400 IBM i machine. I am using MariaDB as a database. I am using PHP 5.5.37
Every time I try to log into an account, I get the error:
There seems to be a problem with your login session; this action has been canceled as a precaution against session hijacking. Go back to the previous page, reload that page and then try again.
Obviously, the behavior I'm looking for is to log in.
I've tried:
changing $wgMainCacheType and $wgSessionCacheType to various permutations of CACHE_NONE, CACHE_ACCEL, CACHE_DB, and CACHE_ANYTHING.
creating a tmp directory and setting its permissions.
rebuilding my LocalSettings.php file.
setting session.referer_check=off in php.ini
I've checked and I know my cookies are enabled (I'm able to call document.cookie; and get data back).
This question has been asked before here, and the linked questions within, but no solutions fixed my problem. They also deal with an older version of WikiMedia, though I don't know if that makes a difference in this instance.
EDIT: I am also getting the same behavior when I try to create a new account. However, I am able to navigate the wiki, create pages, and edit pages without any sort of error.
Here is my request header:
Cache-Control: private, must-revalidate, max-age=0
Connection: close
Content-language: en
Content-Type: text/html; charset=UTF-8
Date: Thu, 10 Aug 2017 13:48:36 GMT
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Link: </<path>/resources/assets/logo.png?88d75>;rel=preload;as=image
Server: Apache
Set-Cookie: ZDEDebuggerPresent=php,phtml,php3; path=/
Set-Cookie: <wikiname>_session=n7gs0ct99ck5i2juq0togto9q7bfou6u; path=/; secure; httponly
Transfer-Encoding: chunked
Vary: Accept-Encoding,Cookie
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-Powered-By: PHP/5.5.37 ZendServer/8.5.5
X-UA-Compatible: IE=Edge
Here is my response header:
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie:ZDEDebuggerPresent=php,phtml,php3
Host:tdidev:10080
Referer:http://<wikiepath>/index.php?title=Special:UserLogin&retirnto=Main+Page
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36
I've finally found the issue to my problem. By default, MediaWiki passes the <wikiname>_session cookie with the secure flag set. Taken from OWASP:
The secure flag is an option that can be set by the application server when sending a new cookie to the user within an HTTP Response. The purpose of the secure flag is to prevent cookies from being observed by unauthorized parties due to the transmission of a the cookie in clear text.
To accomplish this goal, browsers which support the secure flag will only send cookies with the secure flag when the request is going to a HTTPS page. Said in another way, the browser will not send a cookie with the secure flag set over an unencrypted HTTP request.
So my MediaWiki installation correctly creates and caches a session token, and it even still passes it through the response header. However, since my browser sees an http instead of https, that's as far as the token gets. The Set-Cookie line is simply ignored.
There is a setting in php.ini called session.cookie_secure, but MediaWiki ignores this flag.
Instead, the solution was to add this line to the bottom of my localSettings.php file:
$wgCookieSecure = false;
I had something similar happen on a different application, when the sessionId was being updated out of sequence.
So normally you request a login form, and it creates a session with a sessionId, and stores this somewhere.
Then you submit the form, it ties that into the original sessionId, checks your authentication, and either logs in the original session, or creates you a new one, and updates yours (normally with a HTTP Set-Cookie command you can see in the Network log).
But you can follow everything, by looking at the sessionId in your current cookies, and any token on the form (to prevent replays), and checking it against either your /tmp/php-session-xxx file (maybe in /var/lib/php) or whatever database it's storing the session in.
What tipped me off to my problem was identifing that by the time I was about to submit a form, with a particular sessionid, that sessionid, was no-longer valid. Hence I failed the replay checks, and I got an error similar to yours. It turned out in my case it was to do with the databases replicating in a way that didn't match how they were being accessed downstream so I could attempt to access a session, that hadn't been created yet.
Looking at all your code, the sessionIds don't match. wpTokenLogin starts with 510a85 but your wiki session in SetCookie starts with n7gs0c and in your log it talks about 6ov933... So assuming you copied/pasted from different attempts, you need to run through it yourself from a clean state and check that everything looks like it's using the same session. If not, try to figure out what's happening to the session you have (if it's created/changed) or why you're not getting the right one, if it's created but never passed out to you properly.
That said, I just took at look at the client side of logging into our own inhouse version of mediawiki, and wpLoginToken, wikidb_session and JSESSIONID don't match either (although I'd expect one of them to show up in the wiki log, which I don't have access too).
If you have to, grep the source for the error message you're finding, and insert error_log(__FILE__.':'.__LINE__.' '.var_export(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), true)); to find out work back up the stack, to see what didn't match, to generate the error.
This is an ongoing problem with MediaWiki, and is the result of your password being incorrectly entered, or MediaWiki failed to write SOMETHING during the login process (database, cookie, disk file, whatever). In my case, I was using the $wgReadOnly variable to make the wiki read-only. I found that I had to use $wgMainCacheType = CACHE_MEMCACHED for my system to work properly.
See: https://www.mediawiki.org/wiki/Manual:Memcached

How to retrieve attempted $_SERVER['REMOTE_USER'] from URL when no authentication is required

Normally when a publicly-accessible directory requires basic HTTP authentication, the value of $_SERVER['HTTP_AUTHORIZATION'] and/or $_SERVER['REMOTE_USER'] (or $_SERVER['PHP_AUTH_USER'], etc) will be set and accessible to PHP once a valid username/password combination have been provided to the server.
For example, if http://www.example.com/members requires basic authentication, and a user successfully authenticates using the credentials myusername and mypassword by manually typing http://myusername:mypassword#www.example.com/members into their browser, the value of $_SERVER['HTTP_AUTHORIZATION'] would be something like:
Basic bXl1c2VybmFtZTpteXBhc3N3b3Jk
... and the value of $_SERVER['REMOTE_USER'] would simply be:
myusername
However if authentication is not required in the same directory, but the URL is still visited with the username/password inside of it, the values of the username/password don't seem to be set anywhere (running PHP 5.3.10 as CGI/FastCGI on Apache/2.2.22).
From within PHP (and/or .htaccess if necessary), when no authentication is required, is there a way to retrieve the values of the username (and/or password) that have been provided by a visitor who manually added them to the URL?
TLDR; As far as I can see that information is never sent to server so I claim it's not possible.
The way http authentication works if you have it set is that server sends a request for user/pass if it's not already set, and browser then adds that information in encoded form to a Authorization header and sends it to the server along with the request.
As specified in RFC 2617, describing Basic and Digest authentication mechanisms For basic authentication, server sends HTTP 401 Not Authorized status and WWW-Authenticate header fields to request this information. (RFC 2617, Access Authentication Framework)
With tests one can see that if authentication is never configured on the server to be required, server won't request authentication information from browser, and browser won't add user/pass information into the request. RFC does not mandate browser (user agent) to not pass that information, but says instead
A user agent that wishes to authenticate itself with an origin
server--usually, but not necessarily, after receiving a 401
(Unauthorized)--MAY do so by including an Authorization header field
with the request.
In practice, if you watch the sent headers you can see that if this information is requested by the server, it's sent in encoded form using Authorization header like specified by the RFC. However, if you're not using any authentication the request you send just doesn't seem to contain that information in any form. I've confirmed this with IE, Firefox and Chrome browsers myself.
If you want to test this yourself for your setup, this can be done for example using netcat like this:
First, run netcat on your server:
nc -l 8888
Then issue a request from your browser to http://testvalue:testvalue#yourdomain:8888/
As a result, observe from netcat output all the information that get sent to server, something like this:
GET / HTTP/1.1
Host: yourdomain:8888
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
There is no information about user or password anywhere. I claim that unless the server requests it, it won't be there.
The addition of user and password in a url using http(s)://user:pass#site.com has been disabled by at least Internet Explorer for several years now, as far as i know.
https://support.microsoft.com/en-us/kb/834489
So I am not sure if what you are trying to reach is even usefull. I think the browsers dont even pass that part of the url on anymore.

Use session data on websocket handshake

If a logged in user navigates to a certain area of the site which is to use WebSockets, How can I grab that session Id so I can identify him on the server?
My server is basically an endless while loop which holds information about all connected users and stuff, so in order to grab that id I figured the only suitable moment is at the handshake, but unfortunately the handshake's request headers contain no cookie data:
Request Headers
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.5
Cache-Control: no-cache
Connection: keep-alive, Upgrade
DNT: 1
Host: 192.168.1.2:9300
Origin: http://localhost
Pragma: no-cache
Sec-WebSocket-Key: 5C7zarsxeh1kdcAIdjQezg==
Sec-WebSocket-Version: 13
Upgrade: websocket
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64;
rv:27.0) Gecko/20100101 Firefox/27.0
So how can I really grab that id? I thought I could somehow force javascript to send cookie data along with that request but any self-respecting website in 2014 will have httpOnly session cookies so that wont work out. Any help is greatly appreciated!
Here's a link for the server I'm using: https://github.com/Flynsarmy/PHPWebSocket-Chat/blob/master/class.PHPWebSocket.php (thanks to accepted answer)
http only cookies as well as secure cookies work fine with websocket.
Some websocket modules have chosen to ignore cookies in the request, so you need to read the specs of the module.
Try: websocket node: https://github.com/Worlize/WebSocket-Node.
Make sure to use the secure websocket protocol as wss://xyz.com
Update:
Also, chrome will not show the cookies in the "inspect element" Network tab.
In node try dumping the request, something like:
wsServer.on('request', function(request) {
console.log(request);
console.log(request.cookies); // works in websocket node
}
If you see the cookies somewhere in the log...you've got it.
If you're using secure-only cookies, you need to be in secure web sockets: wss://
Update2:
The cookies are passed in the initial request. Chrome does not show it (all the time) as sometimes it shows provisional headers which omits cookie information.
It is up to the websocket server to do 'something' with the cookies and attach them to each request.
Looking at the code of your server: https://github.com/Flynsarmy/PHPWebSocket-Chat/blob/master/class.PHPWebSocket.php I do not see the word "cookie" anywhere, so it is not being nicely packaged and attached to each websocket connection. I could be wrong, that's why you might want to contact the developer and see if the whole header is being attached to each connection and how to access it.
This I can say for certain: If you're using secure cookies then cookies will not be transmitted unless you use the secure websocket wss://mysite.com. Plain ws://mysite.com will not work.
Also, cookies will only be transmitted in the request if the domain is the same as the webpage.

Categories