GWT Sessions and XSRF - the optimal solution? - security

Ok, first I was a bit confused when reading
Remember - you must never rely on the sessionID sent to your server in
the cookie header ; look only at the sessionID that your GWT app sends
explicitly in the payload of messages to your server.
at https://code.google.com/p/google-web-toolkit-incubator/wiki/LoginSecurityFAQ because I didn't understand the nature of XSRF completely and thought: why does it matter how the id gets transmitted?
Then I read http://www.gwtproject.org/doc/latest/DevGuideSecurityRpcXsrf.html and now I understand that XSRF works despite NOT knowing the cookie content (your browser just attaches it to the request, so you exploit your browser's knowledge of the cookie's content - although the browser does not tell 'YOU' or the attacker about the content. The cookie content itself remains uncompromised by that attack). So any proof of knowing the cookie's content validates that the request is not part of XSRF.
I don't like the solution as implemented by GWT (http://www.gwtproject.org/doc/latest/DevGuideSecurityRpcXsrf.html) because it needs a separate call to the server. Please tell me if my ansatz is secure and if I understand the XSRF stuff correctly:
To prevent XSRF, I just copy the session ID contained within the cookie into some non-standard HTTP header field, ie. "X-MY-GWT-SESSION-ID: $sessionId", when doing RPC calls.
That way, I do not need to make any additional calls during app startup because session validation is already done during delivery of the gwt app by destroying the cookie if the session is not valid any more (see How can delete information from cookies?).
So here is the complete security implementation:
registration: client submits cleartext credentials via RPC call to the server, which in turn stores the password using a hash during registration in the server's database (How can I hash a password in Java?)
login: client sends cleartext pwd via https+RPC, check password on server, if ok: store and return (via https) random UUID. That UUID is the shared secret stored on server and client that is used to identify the authenticated user over possibly many browser sessions to avoid requiring the user to log in each time he visits the site.
server sets cookie expiry time to 0 if session is not valid any more so that the client clears the session id and the GWT app detects that it needs to re-authenticate.
on server side only accept session UUIDs sent through a special HTTP header field to prevent XSRF
handle invalidated sessions on client side (either no session cookie or RPC request produced auth failure)
to prevent re-authentication shortly after gwt app loading, the server side devlivery mechanism (ie. index.jsp) deletes the cookie some time before the timeout actually happens - delivering a page and asking for authentication a few seconds later is a bit dumb.
Example sources for the GWT part can be found there: https://stackoverflow.com/a/6319911/1050755. The solution bsaically uses GWT XSRF classes, but embeds the MD5-hashed session ID directly into the web page instead of getting the token via a separate RPC call. The client actually never calls any cookie-related code and the server has only embedded a request.getSession().getId() call into the jsp page.
Any comments, suggestions, critique? Do I miss something important?

Disclaimer: I'm not a security expert.
Actually, if you obtain your xsrf token by an RPC call, then you're subject to XSRF, as an attacker could possibly forge both requests (this is very unlikely though, because it would have to read the response of the first call, which is most of the time prohibited by the cross-origin nature of the request and/or the way it has to be executed).
So ideally you'll make your xsrf token available to the GWT app through any mean.
You'll generally want your session cookie to be unaccessible through scripts (HttpOnly flag), so you'll need to find another way of passing the value (e.g. write it in the HTML host page that's delivered to the browser –as a JS variable, or a special HTML attribute on a special HTML element–, and read it there with GWT, either through Dictionary, JSNI or the DOM).
Also, you'll probably want to use both the cookie and the request header to validate the request (they must match), or you might be vulnerable to session fixation attacks (would probably need an XSS vulnerability too to make it truly useful)

Related

Do I need to use CSRF tokens in a cookie-based API?

I have an API in Next.js (NextAuth.js) that only the frontend will be using. It uses cookies for authentication. My question is could a malicious website change the user's data using CSRF? Should I implement CSRF tokens or can I prevent malicious websites from changing the data without it?
If authentication is based on something that the browser sends automatically with requests (like cookies), then yes, you most likely need protection against CSRF.
You can try it yourself: set up a server on one origin (eg. localhost:3000), and an attacker page on another (eg. localhost:8080, it's the same as a different domain, controlled by an attacker). Now log in to your app on :3000, and on your attacker origin make a page that will post to :3000 something that changes data. You will see that while :8080 will not receive the response (because of the same origin policy), :3000 will indeed receive and process the request. It will also receive cookies set for :3000, regardless of where the user is making the request from.
For mitigation, you can implement the synchronizer token pattern (csrf tokens), double submit, or you can decide to rely on the SameSite property of cookies, which are not supported by old browsers, but are supported by fairly recent ones, so there is some risk, depending on who your users are.

Is it necessary to generate anti-XSRF/CSRF token in server side?

Almost all doc about anti-CSRF mechanism states that CSRF token should be generated in server side. However, I'm wondering whether it is necessary.
I want to implement anti-CSRF in these steps:
There is no server-side-generated CSRF token;
In browser side, on every AJAX or form submission, our JavaScript generates a random string as token. This token is written into cookie csrf before actual AJAX or form submission happens; and the token is added to parameter as _csrf.
In server side, each request is supposed to have cookie csrf and submitted argument _csrf. These two values are compared. If they are different, it means it is a CSRF attack.
The server side doesn't need to issue CSRF token, just do the checking; and the token is totally generated in browser side. Of course, this is only for anti-CSRF. There should be authentication process in server side to validate user id.
It sounds a valid solution for CSRF, but I'm not sure why there is no documentation about this approach.
Is there any fault in this anti-CSRF mechanism?
As far as I understood, what you want to do is to create your anti-CSRF on the client side, store it in a cookie and also add it as a request parameter, so when the server reads your request, just verifies that your CSRF token cookie and parameter matches, and it decides if it's a valid request or not.
The reason to generate the anti-forgery token on the server side, is that the server will create that token and only the server will know the correct value, so if that parameter is slightly tampered on the client side, it will not be identical to the one stored in the server, and that will be enough to flag the request as a cross site request forgery attack.
Any client-side generated data can be tampered by an attacker and because of that, you can't rely on that information, for example, in your approach, you create a random value in your client side and you assign that value to your CSRF cookie and to your _csrf parameter, let's say that your value is "h246drvhd4t2cd98", but since you're only verifying that your 2 variables from the client side have the same value, an attacker can easily just create his CSRF cookie and variable with a value like "I'mByPassingThis" on both of them and your server will flag it as a valid request, so you're not getting security at all.
On the other hand, if the token is generated in the server, the attacker has no way to know the expected value, and that value will be different on every request, so the attacker's best approach will be just to try to guess it, which should be virtually impossible, unless you're using a predictable random number generator on the server side.
Also, if you want to create your own anti-forgery token mechanism, you need to take into consideration to use a cryptographically secure pseudo random number generator, but honestly, you should not bother with that, since the current server-generation process is just what you need (assuming that your framework has a built-in mechanism for this, if not, then you still need to make sure that you're using a cryptographically secure pseudo random number generator to generate your anti-forgery tokens).
Remember to never trust user's submitted information. Since it can always can be tampered, you always need to perform a double-check in the server side, and in this case, generating your anti-forgery token in the server is what allows you to double-check to verify the integrity of the submitted anti-forgery token.
I suggest to use this approach, I have used on a large scale project:
From: https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#use-of-custom-request-headers
Use of Custom Request Headers
Adding CSRF tokens, a double submit cookie and value, an encrypted token, or other defense that involves changing the UI can frequently be complex or otherwise problematic. An alternate defense that is particularly well suited for AJAX or API endpoints is the use of a custom request header. This defense relies on the same-origin policy (SOP) restriction that only JavaScript can be used to add a custom header, and only within its origin. By default, browsers do not allow JavaScript to make cross origin requests with custom headers.
If this is the case for your system, you can simply verify the presence of this header and value on all your server side AJAX endpoints in order to protect against CSRF attacks. This approach has the double advantage of usually requiring no UI changes and not introducing any server side state, which is particularly attractive to REST services. You can always add your own custom header and value if that is preferred.
This technique obviously works for AJAX calls and you have to still need protect tags with approaches described in this document such as tokens. Also, CORS configuration should also be robust to make this solution work effectively (as custom headers for requests coming from other domains trigger a pre-flight CORS check).
So, instead of sending the token through a request body parameter, you could store and send to the server with a request header parameter.

Send Cookie on every request to identify user?

I'm not getting my head around the whole session-management thing.
I've now implemented this to take care for the login process and also this example to protect my services from XSRF attacks.
But now that I'm having it I wonder:
If I turn on SSL, is the cookie sent before a secure connection is built up? So is this session ID (the cookie) ever secure?
Is it save to send the cookie on each request to identify the user? E.g. if a user wants to view his/her settings, to make sure it's not a fake request that tries to retrieve the settings from another user. Is it clear what I mean by that? I would send the session ID on each request, compare it to the session ID in my database and if the request-token (XSRF securiy) is fine I execute the request - or is that too much overhead?
I'm still not quite confident if what I'm doing here is 100% correct and I want to make sure that I don't unnecessarily break any security measures I've spent time implementing.
SSL or TLS connections are established before the HTTP request is sent over the wire, so data in the request is encrypted.
I'm not sure I understand your second question, but a lot of web applications use cookie based authentication to identify the user. As cookies are automatically sent to the website, you have to protect yourself against CSRF attacks.

Can I disable a cookie from being sent automatically with server requests?

I'm fairly new to website development. I'm working on a site where the user logs in with username/password, and gets a sessionID from the server in response. This sessionID is sent back to the server (and a new one returned) with each request.
I'd like the site to work properly if the user opens it in multiple tabs or windows. i.e. once logged in at one tab, opening a members-only URL in another tab works without loggin in. (And, logging out in one tab logs out from all.) I see no way of doing this without storing the latest sessionID in a cookie. That way the latest sessionID can be "shared" among all tabs.
However I am starting to read up on cookies, and some of the security threats. I was unaware that cookies were sent with every request. I don't need to send my cookie to the server, ever. The sessionID is added to the xhr request's headers -- not read as a cookie. So I'm wondering if there is a way to disable sending of this cookie. My only purpose for it is to allow multiple tabs/windows in the same browser to share the same session.
I was reading up on the path parameter for cookies. Apparently this can be used to restrict when the cookie is sent to a server? What if I set the path to something that would never be used? Would this prevent the cookie from ever being sent out automatically? I only want to access it from JavaScript.
A coworker has put a lot of safeguards into the server-side of this application, which I won't go into here. So this question is just about what client-side precautions I can and should take, particularly with cookies, for optimal security. If there is a better way to allow a members-only site to work properly with multiple tabs open at once, I'm all ears.
I discovered just now that in HTML 5 there is local storage, which stores key/value pairs much like a cookie, but is not sent with every server request. Since it's supported in every browser except IE 7 and earlier, I'll be switching to this to enable sharing data between tabs when available, and use cookies instead on IE 7 and earlier.
The sessionID is stored in a cookie already there's no need to manage it. Because the HTTP protocol is stateless the only way to maintain state is through a cookie. What happens when you set a session value the server will look up the dictionary of items associated with that cookie id (session Id).
What is meant by stateless is that between requests HTTP does not know if your still alive or have closed your browser. Therefore with each request the browser will attach all cookie values to the request on the domain. SessionId is stored in the cookie automatically when they go to your site. The Server then uses that value to look up anything you've set in the users session.
Depending on which programming language and/or server you're using the session could be handled differently but that's usually abstracted away from the programmer.
Now with respect to sessions, there are a number of different things that make them insecure. For example if an attacker were able to get their hands on your session cookie value they could replay that cookie and take over your session. So sessions aren't a terribly secure way of storing user information. Instead what most people do is create an encrypted cookie value with the users details, the cookie could be a "session cookie" meaning as soon as the user closes their browser window the cookie is thrown away from the browser. The encrypted cookie contains user information and role information as well as some identifier (usually the clients ip address) to verify that the user who is submitting the request is the same user the cookie was issued to. In most programming languages there are tools that help in abstracting that away as well (such as the ASP.NET membership provider model).
Check out some details on the HTTP protocol and HTTP cookies on Wikipedia first
http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol
http://en.wikipedia.org/wiki/HTTP_cookie
and check out the membership provider model on ASP.NET, it's a really good tool for helping to secure your site.
http://msdn.microsoft.com/en-us/library/sx3h274z(v=vs.100).aspx
Preventing the browser sending cookies seems to defeat the object of using cookies in the first place.
If you don't want the sessionID to be sent with each request, why set the cookie? A better solution would be to use a custom response header that you send from the server to the browser - this will then be under your control and will not be sent automatically with all browser requests. You are using request headers to send your sessionID anyway so you could receive them from the server using a custom header and read this into your JavaScript from each XHR.

How to set up XSRF protection in web apps?

I am a web application newbie. I know that XSRF protection questions have been asked in SO but the questions have been specific to a particular language (RoR/Python for example) or a library (jQuery). I would like to know how I can implement XSRF protection in my web application.
My understanding is that XSRF protection relies to using a unique random token that must be authenticated when a HTTP request is made. I have the following questions:
When should the authentication token be initialized? Should it be set on page load (i.e. GET request)?
Where should the token be initialized? Should they be set in input fields, cookies or request headers? How is this random value generated? How do I persist this value in order to be used for comparison?
When should the authentication token be verified? How does I compare authentication tokens? How do I compare these tokens with the token that I have persisted?
Is there a difference in the set up for a synchronous form request versus an AJAX request?
When should the authentication token be initialized?
The first time, during a session, that the user arrives at a page containing any form that you wish to protect from CSRF attacks.
Should it be set on page load (i.e. GET request)?
It should be embedded in the form when the HTML for it is generated.
Should they be set in input fields, cookies or request headers?
Hidden inputs.
Using a cookie would miss the point (which is that it comes from the page and does not persist in the browser). Extra headers can only work when using XHR, use a general approach.
How is this random value generated?
With a random number generator
How do I persist this value in order to be used for comparison?
Sessions
When should the authentication token be verified?
As part of the authorization step.
How does I compare authentication tokens? How do I compare these tokens with the token that I have persisted?
if ( $request->paramaters->{csrf} eq $session->data->{csrf} )
Is there a difference in the set up for a synchronous form request versus an AJAX request?
No. You still have a session and you still have a piece of the POST data being the token.
I'm not going to talk about a specific solution that you must follow as there are many, I'll talk about the main idea instead and you could implement it however you want.
The key idea to prevent XSRF is to store a random token in a place where code from other domains cannot access (such as a cookie). You could generate this token on server side and instruct the browser to store it locally for the entire session. (don't need to persist anything on server side)
Whenever you perform a request, send:
the token in your storage (if you use cookie, the browser will send it automatically).
the same token as the stored one in your request (whether as a header or in body using hidden field depending on how server code gets it)
On server side, the server will check for a match.
A sample code in jquery (with jquery cookie plugin):
$.ajax({
url:"someurl",
data:{token:$.cookie('token')}
});
The ability to read the cookie proves that this is from your domain, not external domains
There are various ways to implement this mechanism (don't need to stick to a specific solution) as long as they stick the the main idea:
Storing a secret token on browser in a place code from other domains cannot read it.
Send the secret token and the same token from browser to your server. The ability to send that same token proves that this is not a XSRF request.
How do I persist this value in order to be used for comparison?
We could store it as a cookie or as a session variable. Personally, I prefer cookie because:
Reduce memory consumption on server side.
We don't need to include that token in every generated HTML file in order for the browser to send it back.
Is there a difference in the set up for a synchronous form request
versus an AJAX request?
No, as long as you could prove this is not a XSRF request by sending the same token in the request. It does not matter where token is (a hidden field, a custom header,..). In case of Form, people usually send it as a hidden field.

Resources