Is exposing a session's CSRF-protection token safe? - ajax

Django comes with CSRF protection middleware, which generates a unique per-session token for use in forms. It scans all incoming POST requests for the correct token, and rejects the request if the token is missing or invalid.
I'd like to use AJAX for some POST requests, but said requests don't have the CSRF token availabnle. The pages have no <form> elements to hook into and I'd rather not muddy up the markup inserting the token as a hidden value. I figure a good way to do this is to expose a vew like /get-csrf-token/ to return the user's token, relying on browser's cross-site scripting rules to prevent hostile sites from requesting it.
Is this a good idea? Are there better ways to protect against CSRF attacks while still allowing AJAX requests?

UPDATE: The below was true, and should be true if all browsers and plugins were properly implemented. Unfortunately, we now know that they aren't, and that certain combinations of browser plugins and redirects can allow an attacker to provide arbitrary headers on a cross-domain request. Unfortunately, this means that even AJAX requests with the "X-Requested-With: XMLHttpRequest" header must now be CSRF-protected. As a result, Django no longer exempts Ajax requests from CSRF protection.
Original Answer
It's worth mentioning that protecting AJAX requests from CSRF is unnecessary, since browsers do not allow cross-site AJAX requests. In fact, the Django CSRF middleware now automatically exempts AJAX requests from CSRF token scanning.
This is only valid if you are actually checking the X-Requested-With header server-side for the "XMLHttpRequest" value (which Django does), and only exempting real AJAX requests from CSRF scanning.

If you know you're going to need the CSRF token for AJAX requests, you can always embed it in the HTML somewhere; then you can find it through Javascript by traversing the DOM. This way, you'll still have access to the token, but you're not exposing it via an API.
To put it another way: do it through Django's templates -- not through the URL dispatcher. It's much more secure this way.

Cancel that, I was wrong. (See comments.) You can prevent the exploit by ensuring your JSON follows the spec: Always make sure you return an object literal as the top-level object. (I can't guarantee there won't be further exploits. Imagine a browser providing access to the failed code in its window.onerror events!)
You can't rely on cross-site-scripting rules to keep AJAX responses private. For example, if you return the CSRF token as JSON, a malicious site could redefine the String or Array constructor and request the resource.
bigmattyh is correct: You need to embed the token somewhere in the markup. Alternatively, you could reject any POSTs that do have a referer that doesn't match. That way, only people with overzealous software firewalls will be vulnerable to CSRF.

Related

Is it safe to set an anti-CSRF token on $http for Ajax requests?

It seems creating and handling anti-CSRF tokens for Ajax calls in an Angular application is non-trivial and some are getting around the problem by applying a single token to every Ajax call. For example here.
The solution is quite neat. We just generate the token on the server and send it along with the first loaded page after sign-in. Then we ensure it goes out with all future requests like this:
$http.defaults.headers.common['RequestVerificationToken'] = 'token should go here';
But I am concerned this may simplify the job of an attacker. They need only get hold of $http in order to make any valid request. Is this the case? Is this method safe? Is there a 'best practice' regarding Ajax requests and CSRF?
Angular automatically does this for you.
Read Cross Site Request Forgery (XSRF) Protection section.
DOCS
I also suggest you read up CSRF, and what it is, if malicious script is already in your page it does not need to do cross-site requests to pose as the victim.

Is a CSRF token needed for "AJAX"-only "application/json"-only POSTs?

If I understand correctly, there's no need for a CSRF token if you're only allowing JSON as application/json from an "AJAX" (really AJAJ for JSON) form, right?
If someone tries to post to the form from another page using some nifty POST-to-iFrame hack it will be application/x-www-form-urlencoded, you can throw it out immediately.
If someone tries to post to the form using AJAJ, it will only succeed if OPTIONS has the CORS headers that allow it.
Conclusion: unless you're using CORS you're safe from CSRF as when you're using application/json instead of application/x-www-form-urlencoded.
Any contradictions I'm not considering?
Have a look at this Sec.SE question and answer. In short: you are correct (presently), but it's probably not a good idea to rely on this behavior, so use tokens anyway.
2022 Update
So much has changed - such as fetch giving more control to requests.
Yes, it's still dangerous
It is possible to do a cross-site JSON POST that includes cookies.
(the attacker can't see the response, but they can POST successfully)
CSRF is necessary by default.
Yes, it's easy to mitigate
Same-Site Cookies
There's now a same-site cookie option. Using this correctly makes it completely unnecessary to use CSRF tokens at all.
API Tokens
Completely abandoning Cookies in favor of per-request API tokens, such as the well-standardized JWT, will make CSRF attacks impossible.
This is best done by separating token routes from cookie routes, such as:
/api/account/xxxx for authenticated JSON API
/api/assets/xxxx for <img src="xxxx" /> and other assets that should not have a token in the URL and must therefore rely on cookies

Same origin Policy and CORS (Cross-origin resource sharing)

I was trying to understand CORS. As per my understanding, it is a security mechanism implemented in browsers to avoid any AJAX request to domain other than the one open by the user (specified in the URL).
Now, due to this limitation many CORS was implemented to enable websites to do cross origin request. but as per my understanding implementing CORS defy the security purpose of the "Same Origin Policy" (SOP).
CORS is just to provide extra control over which request server wants to serve. Maybe it can avoid spammers.
From Wikipedia:
To initiate a cross-origin request, a browser sends the request with
an Origin HTTP header. The value of this header is the site that
served the page. For example, suppose a page on
http://www.social-network.example attempts to access a user's data
in online-personal-calendar.example. If the user's browser implements
CORS, the following request header would be sent:
Origin: http://www.social-network.example
If online-personal-calendar.example allows the request, it sends an
Access-Control-Allow-Origin header in its response. The value of the
header indicates what origin sites are allowed. For example, a
response to the previous request would contain the following:
Access-Control-Allow-Origin: http://www.social-network.example
If the server does not allow the cross-origin request, the browser
will deliver an error to social-network.example page instead of
the online-personal-calendar.example response.
To allow access to all pages, a server can send the following response
header:
Access-Control-Allow-Origin: *
However, this might not be appropriate for situations in which
security is a concern.
What am I missing here? what is the the intend of CORS to secure the server vs secure the client.
Same-origin policy
What is it?
The same-origin policy is a security measure standardized among browsers. The "origin" mostly refers to a "domain". It prevents different origins from interacting with each other, to prevent attacks such as Cross Site Request Forgery.
How does a CSRF attack work?
Browsers allow websites to store information on a client's computer, in the form of cookies. These cookies have some information attached to them, like the name of the cookie, when it was created, when it will expire, who set the cookie etc. A cookie looks something like this:
Cookie: cookiename=chocolate; Domain=.bakery.example; Path=/ [// ;otherDdata]
So this is a chocolate cookie, which should be accessible from http://bakery.example and all of its subdomains.
This cookie might contain some sensitive data. In this case, that data is... chocolate. Highly sensitive, as you can see.
So the browser stores this cookie. And whenever the user makes a request to a domain on which this cookie is accessible, the cookie would be sent to the server for that domain. Happy server.
This is a good thing. Super cool way for the server to store and retrieve information on and from the client-side.
But the problem is that this allows http://malicious-site.example to send those cookies to http://bakery.example, without the user knowing! For example, consider the following scenario:
# malicious-site.example/attackpage
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://bakery.example/order/new?deliveryAddress="address of malicious user"');
xhr.send();
If you visit the malicious site, and the above code executes, and same-origin policy was not there, the malicious user would place an order on behalf of you, and get the order at his place... and you might not like this.
This happened because your browser sent your chocolate cookie to http://bakery.example, which made http://bakery.example think that you are making the request for the new order, knowingly. But you aren't.
This is, in plain words, a CSRF attack. A forged request was made across sites. "Cross Site Request Forgery". And it would not work, thanks to the same-origin policy.
How does Same-origin policy solve this?
It stops the malicious-site.example from making requests to other domains. Simple.
In other words, the browser would not allow any site to make a request to any other site. It would prevent different origins from interacting with each other through such requests, like AJAX.
However, resource loading from other hosts like images, scripts, stylesheets, iframes, form submissions etc. are not subject to this limitation. We need another wall to protect our bakery from malicious site, by using CSRF Tokens.
CSRF Tokens
As stated, malicious site can still do something like this without violating the same-origin policy:
<img src='http://bakery.example/order/new?deliveryAddress="address of malicious user"'/>
And the browser will try to load an image from that URL, resulting in a GET request to that URL sending all the cookies. To stop this from happening, we need some server side protection.
Basically, we attach a random, unique token of suitable entropy to the user's session, store it on the server, and also send it to the client with the form. When the form is submitted, client sends that token along with the request, and server verifies if that token is valid or not.
Now that we have done this, and malicious website sends the request again, it will always fail since there is no feasible way for the malicious website to know the token for user's session.
CORS
When required, the policy can be circumvented, when cross site requests are required. This is known as CORS. Cross Origin Resource Sharing.
This works by having the "domains" tell the browser to chill, and allow such requests. This "telling" thing can be done by passing a header. Something like:
Access-Control-Allow-Origin: //comma separated allowed origins list, or just *
So if http://bakery.example passes this header to the browser, and the page creating the request to http://bakery.example is present in the origin list, then the browser will let the request go, along with the cookies.
There are rules according to which the origin is defined1. For example, different ports for the same domain are not the same origin. So the browser might decline this request if the ports are different. As always, our dear Internet Explorer is the exception to this. IE treats all ports the same way. This is non-standard and no other browser behaves this way. Do not rely on this.
JSONP
JSON with Padding is just a way to circumvent same-origin policy, when CORS is not an option. This is risky and a bad practice. Avoid using this.
What this technique involves is making a request to the other server like following:
<script src="http://badbakery.example/jsonpurl?callback=cake"></script>
Since same-origin policy does not prevent this2 request, the response of this request will be loaded into the page.
This URL would most probably respond with JSON content. But just including that JSON content on the page is not gonna help. It would result in an error, ofcourse. So http://badbakery.example accepts a callback parameter, and modifies the JSON data, sending it wrapped in whatever is passed to the callback parameter.
So instead of returning,
{ user: "vuln", acc: "B4D455" }
which is invalid JavaScript throwing an error, it would return,
cake({user: "vuln", acc:"B4D455"});
which is valid JavaScript, it would get executed, and probably get stored somewhere according to the cake function, so that the rest of the JavaScript on the page can use the data.
This is mostly used by APIs to send data to other domains. Again, this is a bad practice, can be risky, and should be strictly avoided.
Why is JSONP bad?
First of all, it is very much limited. You can't handle any errors if the request fails (at-least not in a sane way). You can't retry the request, etc.
It also requires you to have a cake function in the global scope which is not very good. May the cooks save you if you need to execute multiple JSONP requests with different callbacks. This is solved by temporary functions by various libraries but is still a hackish way of doing something hackish.
Finally, you are inserting random JavaScript code in the DOM. If you aren't 100% sure that the remote service will return safe cakes, you can't rely on this.
References
1. https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy#Definition_of_an_origin
2. https://www.w3.org/Security/wiki/Same_Origin_Policy#Details
Other worthy reads
http://scarybeastsecurity.blogspot.dk/2009/12/generic-cross-browser-cross-domain.html
https://www.rfc-editor.org/rfc/rfc3986 (sorry :p)
https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)
The Same Origin Policy (SOP) is the policy browsers implement to prevent vulnerabilities via Cross Site Scripting (XSS). This is mainly for protecting the server, as there are many occasions when a server can be dealing with authentication, cookies, sessions, etc.
The Cross Origin Resource Sharing (CORS) is one of the few techniques for relaxing the SOP. Because SOP is "on" by default, setting CORS at the server-side will allow a request to be sent to the server via an XMLHttpRequest even if the request was sent from a different domain. This becomes useful if your server was intended to serve requests from other domains (e.g. if you are providing an API).
I hope this clears up the distinction between SOP and CORS and the purposes of each.

CSRF and Ajax: Do I need protection?

Do I need to use csrf tokens in my ajax requests?
I think that someone tricking my users to execute malicious ajax requests from another site, to my site, will fail because of the origin policy, which is handled by the browser, am I right?
I don't care about duplicated requests when using ajax, I'm only asking about the attacks.
Am I at risk if I don't use csrf in my ajax requests?
As per my research,
We can reduce the vulnerability by using POST request(for the request which will take side affect). But thing is that we can forge the POST request as well with form submission, cause same origin policy will not applies plain html for submissions. But it applies to request which are getting generated with JS.
So if you use ajax POST request and you are safe if you are using JSON payload.
Cause url encoded payload(POST request) can be forged with form submission from other sites.
If you use JSON, as it is not possible to send plain text pay load(with out urlform encoded) with html form submission you are safe. Because with ajax POST request if you use urlform encoded data payload it can be forged with POST form submission.
This is how we solved the problem with CSRF token in Ajax requests
http://mylifewithjava.blogspot.com/2010/11/implicit-csrf-protection-of-ajax_22.html
The fact that you are using Ajax doesn't mean that others have to as well. Your server won't be able to distinguish a request made by XHR from one made by <form> submission. (Yes XHR usually adds a header identifying itself, but this is not hard to spoof.)
So yes, you do need to consider CSRF attacks.
Edit
Django have a POC, which is why they and Ruby on Rails now implement CSRF protection on AJAX requests.
Once again, please check your facts before downvoting, and explain what the downvote is for.

How can AJAX validate user?

When user is on the page you can use session or cookies to check who is he.
But when AJAX is used, for example, for sending an answer, sending page have no contact with user. How can it check is it real registered user, or just spambot sending this by headers?
What is the common practice for AJAX user validation?
AJAX requests contain the same cookies like regular requests. Besides that you can send any arguments like session IDs with the AJAX request.
Actually, for the server it makes absolutely no difference if a request is made through an XmlHttpRequest object or not. Most frameworks add an X-Requested-With: XMLHttpRequest header though but that's completely optional.
So.. whatever means you use to pass your session data, simply ensure it's also available to the script called with your AJAX request:
If you have a session id passed via GET/POST, include it in your request's arguments.
If cookies are needed, ensure they are send to the file. If it's in the same folder like the current file or a descendant of it you are usually safe. If it's on another (sub-)domain you might get problems - not only with cookies but alsowith cross-domain AJAX which usually isn't allowed due to the same-origin policy browsers have.

Resources