anti-CSRF token and Javascript - ajax

I'm trying to protect an application (php and lots of JS) from CSRF.
I want to use tokens.
A lot of operations are done with AJAX, so I have to pass the token in Javascript.
If I want to generate 1 token per session or per page load it's simple - I generate new token, put it somewhere in a DOM and then find it with Javascript and send to the processing side.
But what if I want to use new token for every operation?
I was thinking about doing an ajax call to regenerate token and then pass the result to processing page.
Does this increase security risk?
I was thinking about luring user to page with script which would ask for token and then use it to make the request but then again cross domain Javascript is forbidden.
Can it be done with flash?
Maybe another approach for protecting ajax calls from CSRF?
Thanks!

There are several techniques, which when used together provide a sufficient CSRF protection.
Unique Token
A single, session-specific token is good enough for most applications. Just make sure that your site doesn't have any XSS vulnerabilities, otherwise any kind of token technique you employ is a waste.
AJAX call to regenerate the token is a bad idea. Who will guard the guards? If the AJAX call itself is vulnerable to CSRF, it kind of defeats the purpose. Multiple tokens with AJAX are in general bad idea. It forces you to serialize your requests i.e. only one AJAX request is allowed at a time. If you are willing to live with that limitation, you can perhaps piggyback token for the second AJAX call in response to the first request.
Personally, I think it is better to re-authenticate the user for critical transactions, and protect the remaining transactions with the session-specific token.
Custom HTTP header
You can add a custom HTTP header to each of your requests, and check its presence on the server side. The actual key/value doesn't need to be secret, the server just needs to ensure it exists in the incoming request.
This approach is good enough to protect CSRF in newer versions of the browsers, however its possible too work-around this if your user has older version for Flash Player.
Checking Referrer
Checking for the Referrer header is also good to protect CSRF in the newer browsers. Its not possible to spoof this header, though it was possible in older versions of Flash. So, while it is not foolproof, it still adds some protection.
Solving Captcha
Forcing the user to solve a captcha is also effective against CSRF. Its inconvenient as hell, but pretty effective. This is perhaps the only CSRF protection that works even if you have XSS vulnerabilities.
Summary
Use a session based token, but re-authenticate for high value transactions
Add a custom http header, and also check for referrer. Both are not foolproof by themselves, but don't hurt

Related

How to make Web Api secure against CSRF attacks in ASP.NET?

Consider a web application that consists of only HTML and JS for Front end and that communicates with a Web API.
I am trying to protect my application against CSRF attacks and for that I have took reference of this article.
Using the methods in this article, I am able to generate Anti CSRF tokens and pass it to the client. However it depends on first AJAX call that must happen before making regular CRUD operation calls.
With this approach, I need some clarity on few things as well as some alternatives if any. Consider a client visits this web application (which is protected by AJAX based Anti CSRF token), and keeping his session open, he visits a malicious website that contains page that makes the same AJAX calls to get CSRF tokens (assume that attacker is aware of this process), I suppose he can use the headers to make unintended calls thus resulting in an attack.
So how can I protect my application against these?
Please provide more detail regarding this, or if its misleading then help me by providing correct details so that I can tackle it better.
First of all you should use an encrypted communication with the server so the attacker won't be able to read any header data.
If your attacker uses the same calls as you do, he is not be able to guess the anti XSRF token that you use in your calls. A new token is generated for every call to your API. I hope this page helps you with some details:
https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet
I think if we use token based authentication, client have to pass authentication token in each request. And if client do not store it in browser cache and store it in localStorage then browser will not send token in call automatically. And if our service receive any request without auth token then it will discard the request.

Does custom security HTTP headers violate separation of concerns

Does custom application specific, security related HTTP headers violate separation of concerns, is it considered a bad practice? I realize using custom header to control the service would tightly couple the client with the service implementation. Or in this case, to control the security framework behavior. The context where I planned using the custom header is the following:
We are using token based authentication, where token has a fixed lifetime, and new token is issued each time authenticated client calls the web API. SPA client may call the server with AJAX in two contexts
User action (navigation and submit)
Automatic refresh (current view re-fetches data at fixed intervals)
Now, if user leaves the page open, the session never expires, as new token is generated for each automatic fetch. Somehow, we need to differentiate user action from automatic refresh in the server side, and issue new token only for user actions.
I realize Websocket based refresh would be one solution, but we have decided to stick with timed AJAX call due specific matters. Another solution would be to provide token refresh as a separate endpoint, but this would violate the DRY principle from client's perspective, and would be more cumbersome to setup with Spring Security.
Only remaining option is to embed the user/automated information in the request itself, and using a header seems a viable option here. A presence of certain header would prevent the token refresh. Easy to implement with a few lines of code.
I'm only concerned, if this couples the client too much with the service implementation. Technically, it doesn't couple client with the service, but the preceding security filter, thus leaking security concerns in the user interface. Ideally security stuff should be transparent to user interface, so new client could be coded without knowing anything about security (especially when cookies are used).
In the other hand, this solution isn't destructive or mutative. It's an optional feature. By client utilizing it, security is enhanced, but in either case never reduced (from the perspective of server, as it is). Now the question is, what principles using a optional header to enhance security is violating, and is it a valid solution in this context?
In my option the security should be maximized transparently, but I don't see how to not leak security concerns in the client in this situation.
It sounds like you're using your own home-built custom Token Authentication solution here. This is not a good idea.
I'll take a moment to explain WHY you don't want to do what you're proposing, and then what the better option is.
First off -- the problem that you're trying to solve here is that you don't want a user to remain logged into your site forever if they leave a tab open. The reason you need to fix this is because right now, you're assigning a new Access Token on EVERY REQUEST from the user.
The correct solution to handling the above problem is to have two types of token.
An Access Token that has a very short lifetime (let's say: 1 hour), and a Refresh Token that has a longer lifetime (let's say: 24 hours).
The way this should work is that:
When the user first authenticates to your service, the Access and Refresh tokens are generated with their respective timeouts.
These tokens are both set in HTTP cookies that the client-side JS cannot access.
From this point on, every time your user's browser makes a request to your service, you'll parse out the Access token from the cookie, check to see if it's valid, then allow the request.
If the Access token is no longer valid (if it has expired), you'll then parse out the Refresh token from the cookie, and see if that is valid.
If the Refresh token is valid, you'll generate a NEW Access token with another 1 hour lifetime, and override the old Access token cookie with the new on.
If the Refresh token is invalid, you'll simply return a 301 redirect to the login page of your app, forcing the user to manually re-authenticate again.
This flow has a number of benefits:
There is a maximum session length, which is technical (duration of Refresh token + duration of Access token) -- aka: 25 hours in this example.
Access tokens are short lived, which means that if a token is somehow compromised, attackers can't use it for very long to impersonate the user.
What's nice about the above flow is that it is a web authorization standard: OAuth2.
The OAuth2 Password Grant flow does EXACTLY what you're describing. It generates both types of tokens, handles 'refreshing' tokens, handles the entire thing from start to finish in a safe, standards-compliant way.
What I'd highly recommend you do is implement an OAuth2 library on both your server and client, which will take care of these needs for you.
Now -- regarding the tokens, most OAuth2 implementations now-a-days will generate tokens as JSON Web Tokens. These are cryptographically signed tokens that provide a number of security benefits.
Anyhow: I hope this was helpful! I author several popular authentication libraries in Python, Node, and Go -- so this comes from my direct experience working with these protocols over the last several years.

Does it make sense to put antiforgerytoken in _Layout.cshtml?

I'm developing an ASP.NET MVC application and I'm planing to protect each non GET request (POST, PUT, DELETE, etc...) with AntiForegeryToken.
I've implemented an extension of the classical AntiForgery verification based on the [__RequestVerificationToken] sent in the header. This because most of my calls are async ($.ajax()) and it turns out easier for me to send the hidden field value that way.
Does it make sense to put one single #Html.AntiForgeryToken() in the _Layout.cshtml (template for all pages) and always refer to that one only ?
I've tryed to understand what wolud be different beteen this option and putting it in each form (that I don't use much since my requests are pretty much all async), but I haven't.
Can anyone clear this to me ?
Thanks
Lorenzo
You can put it in your _Layout.cshtml and generate a single token when the page is rendered, that's fine.
While there is a very slight security benefit of using a different token for every request, if your token has enough entropy (and the standard token generated by #Html.AntiForgeryToken() does), then it is practically infeasible for an attacker to guess the token even during the time of a user session. So one token per user session is still considered secure in most cases.
Actually, trying to use a new token for each request leads to all kinds of bugs in a Javascript heavy application, because the browser needs a non-neglectible time to actually change things like a cookie value or to send a request, and frequent ajax requests will lead to a race condition and you will have hard to debug bugs around token mismatches.
ASP.NET MVC still focuses on traditional form-based applications in this regard, and while you can use it to prevent CSRF in modern Javascript-heavy apps with some tweaks (like a custom attribute to actually verify a token sent in request headers), you do have to write some custom code to do that. Hopefully Microsoft will add built in support in future versions.
UPDATE
After implementing the solution with #Html.AntiForgeryToken() directly in Template page (_Layout.cshtml) I found out a possible problem bound to the use of custom Claims. The problem happens during re-validation of UserIdentity. As a reference I'll leave the link to another post in which I've been dealing with that and added there the wotrkaround for those who choose the same implementation.
Custom Claims lost on Identity re validation
Hope it helps !

Secure Token Passing in Ajax in a Highly Cached Environment

Greetings SO Community!
I'm trying to think through a security issue with an ajax process in a highly cached environment, and could use some advice. My situation is this:
The users of the site are not logged in.
The site pages are highly cached (via akamai).
I have a service API that is to be accessed via AJAX from pages within my domain.
I need to protect that API from being used outside of my domain.
I can check the incoming "host" in the headers to see if the ajax request came from my domain, but that seems insecure, as such headers could be spoofed. Also, it seems to me that the usual token passing scheme will not work for me because my pages are cached, so I don't have the opportunity to inject tokens unique to the user/request (e.g. as described here: How can I restrict access to some PHP pages only from pages within my website?). Clearly, it's insecure to make a token request via ajax after page load, so I'm not sure how to make this happen. I suppose I could generate a shared use token that loads with the page and has a lifetime twice that of my maximum page cache life, but it seems like there must be a better way!
What are you trying to accomplish? Are you trying to prevent cross site request forgery or someone\something from using your API that is not the javascript you served to the user?
The former is accomplished via tokens that are stored in the source of the page. You can make it hard to conduct an XSRF attack by having tokens in the source ( or some code that creates tokens). Unfortunately, unless you can get unique data per user/request into the source, someone can always just grab your source and reverse engineer the token. Then they can forge requests. The general rule is don't worry about it unless the user is loged in because the attacker could just go to the page themselves.
The later(preventing unauthorized use) is impossible in anycase. An attacker can always make an account, strip the tokens/keys/credentials she needs, and then use some API on their server.

XSRF protection in an AJAX style app

We're currently developing an entirely AJAX based app that will interact with the server via a RESTful API. I've considered potential schemes to protect against XSRF attacks against the API.
User authenticates and receives a
session cookie, which is also
double-submitted with each request.
We implement an OAuth consumer in
Javascript, retrieve a token when
the user logs in, and sign all
requests with that token.
I'm leaning toward the OAuth approach, mainly because I'd like to provide 3rd party access to our API and I'd rather not have to implement two authentication schemes.
Is there any reason why an OAuth consumer would not work in this situation?
Most AJAX libraries will set an additional header "X-Requested-With: XMLHttpRequest", which is difficult to fake in a basic XSRF attack (though possible if combined with XSS). Verifying that this header exists is a good defense-in-depth strategy if you expect all your requests to be AJAX.
Use a two-step request, the first asking for the server an unpredictible token, the second asking for the real action with the token.
As the attacker can't predict the token, and can't read it (same origin policy) he can't give a valid token in the second query.
But be careful to not leak tokens (learn about capturing json using when they affect value to a global variable and so on) and read :
http://www.google.com/search?q=xsrf+defence
The easiest way to prevent XSRF it to check the referer of every RESTful request to make sure the request is coming from the same domain. The session cookie is important for keeping state, but it will not defend against XSRF becuase it will also be sent with a forged request. Its common to see referer based XSRF protection system on embedded network hardware with limited memory requirements, Motorola uses this method on most of their hardware. This isn't the most secure XSRF protection, token based protection is better but both systems can still be bypassed with XSS. The biggest problem with token based XSRF protection is that it takes alot of time to go back and fix every request and you will probably miss a few requests.
Make sure to read up on the same origin policy and to scan your site for xss. You should also read the OWASP Top 10 for 2010 A3-Broken Authentication and Session Management.

Resources