Get around CSFR token for iOS app - ruby-on-rails

I am developing an iOS app for a RoR api (my co-worker made it). I am trying to develop the login portion, but while testing the api in POSTMan, I noticed it requires a CSRF token. Is there a way to get around doing an api call to get the CSRF?
Side note: I am using AFNetworking 2.0

There are a couple things you can do:
You can launch a GET request before you do the post, and retrieve the sessions CSRF token. Then submit the POST form with an authenticity_token parameter as the proper CSRF token. You can embed the original token anywhere in the view with the rails helper form_authenticity_token, or just get it from the sign up form's hidden tag. (This is my favorite option)
You can make a secondary loggin-in action on your site that is actually a GET request in and of itself. It's not too dangerous to bypass the CRSF token here because anyone should have access to log in. This has the advantage of keeping CRSF for any other action you may need, but it wouldn't work for actions that need more security.
You can make your iOS page consist of a UIWebView. I'm not sure if this will suit your needs, but it would have the proper CSRF token and you can remove the UIWebView after submitting. It's kind of like option 1, but bulkier.
Good luck!

Easiest fix is to change the server side to not authenticate the CSRF token. Here's an example of using a different controller for your API.
class Api::BaseController < ApplicationController
skip_before_filter :verify_authenticity_token
end
In general, your API is either going to require authentication for API calls (in which case you should have your own authentication, or OAuth, or any number of authentication mechanisms) or isn't (in which case it's a publicly accessible API and CSRF doesn't matter). There a few other threads here and here that discuss it.
From another answer on SO (go upvote it!):
CSRF attacks rely on cookies being implicitly sent with all requests to a particular domain. If your API endpoints do not allow cookie-based authentication, you should be good.

Related

Why should spring postOnly be false for Logout to work?

what does postOnly mean in below property
grails.plugin.springsecurity.logout.postOnly=false?
Why should it be false for Logout to work? Tried making the logout feature work by making it true. But it did not work. What is the reason behind making it false?
For starters, please read the plugin documentation - the 2.x docs are here and the 3.x docs are here.
The plugin defaults to requiring a POST request to logout, but using the config setting you reference you can make your application more convenient to use but less secure by allowing GET or POST requests.
GET requests (e.g. regular links) are supposed to be for actions that read data. A strict REST API requires that GET requests be read-only and also idempotent, but obviously in a regular web app this is too strict. But in general it's best to use links and GET requests to request information, and POST/PUT/DELETE/etc. requests to make changes.
If you include a logout link that uses GET to make the request, it's possible for someone using XSS or similar attacks to trick your browser into logging you out. This isn't a severe vulnerability and requiring POST doesn't make it significantly harder for an attacker but it does raise the bar.
With the default configuration all you need to do is replace a logout link with a simple form that POSTs to that same url (and you can optionally use CSS to style the submit button like a link if you want). If you're comfortable with allowing users to logout with a GET request, change the setting to false and any request to that url will work.
Once you make it true as below
grails.plugin.springsecurity.logout.postOnly=true
the request method type should be POST only i.e. you can't use GET method.
So, change the logout call to POST type in this case.
You may also look at How to customize Grails Spring Security Core 2 login / logout controller and views?
By default Spring Security requires logout to use a POST request to provide CSRF protection. For more on CSRF see Wikipedia.
what does postOnly mean in below property
I means you grails will only logout a user if you send a POST request to the logout url.
Why should it be false for Logout to work?
It's mainly for CSRF protection.
It is considered best practice to use an HTTP POST on any action that
changes state (i.e. log out) to protect against CSRF attacks. If you
really want to use an HTTP GET, you can use logoutRequestMatcher(new
AntPathRequestMatcher(logoutUrl, "GET"));
Additionally, modern browsers like chrome will preload links in a page before the user tries to access them to make them fast. This means if you make your logout link accept GET requests, chrome might log you out even if you don't want to.

Rails 4 skipping protect_from_forgery for API actions

I've been implementing a Rails 4 application with an API. I want to be able to call the API from mobile phones and the webapp itself. I came across this note while researching protect_from_forgery:
It's important to remember that XML or JSON requests are also affected and if you're building an API you'll need something like:
class ApplicationController < ActionController::Base
protect_from_forgery
skip_before_action :verify_authenticity_token, if: :json_request?
protected
def json_request?
request.format.json?
end
end
I was thinking of doing this, but I have some reservations/questions:
This solution seems to leave the CSRF hole open because now an attacker could craft a link with an onclick javascript that posts JSON?
Would checking for an API token be a reasonable substitute? i.e., what if instead of skipping the authenticity check, allowing it to fail the check and recover in handle_unverified_request if the api token is present and correct for current user?
Or maybe I should just make the webapp and mobile devices send the CSRF token in the HTTP headers? Is that safe? How would the mobile phone even obtain the CSRF token, given that it isn't rendering HTML forms to begin with?
Edit for clarification:
I am more concerned about the webapp user clicking a crafted CSRF link. The mobile users are authenticated, authorized, an have an API key, so I am not concerned about them. But by enabling CSRF protection for the webapp users, the mobile users are blocked from using the protected API. I want to know the correct strategy for handling this, and I don't believe the Rails documentation gives the right answer.
An attacker could CURL at your controllers all they like, but if your API requires authentication, they wont get anywhere.
Making the API consumers send a CSRF is not really what CSRF does. To do this you'd need to implement a type of knocking mechanism where your client hits an authorization endpoint first to get the code (aka CSRF) and then submit it in the POST. this sucks for mobile clients because it uses their bandwidth, power, and is laggy.
And anyway, is it actually forgery (i.e. the F in CSRF) if its an authorized client hitting your controller after all?
Sending the CSRF token in an HTTP header is indeed a common approach. It ensures that the client has somehow obtained a valid token. For example, a crafted CSRF link will be sent with credential cookies but the header will not include the CSRF token. Your own javascript on the client will have access to domain cookies and will be able to copy the token from a cookie to the header on all XHR requests.
AngularJS follows this approach, as explained here.
As for your first two questions:
This solution seems to leave the CSRF hole open...
Indeed, which is why you should not disable the CSRF token also in your API.
Would checking for an API token be a reasonable substitute? ...
Probably not. Take into consideration the following (from OWASP):
CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referer headers if the protected site links to an external site.
General recommendation: Don't try to invent the wheel. OWASP has a page called REST Security Cheat Sheet as well as the one I linked to before. You can follow the Angular approach (copying the token from a cookie to a header on each XHR request) and for regular non-ajax forms, be sure to use only POST and a hidden field as is normally done in CSRF protection of static server forms.

Is it safe to disable CSRF-protection for an authenticated POST endpoint in Rails?

I'm finding myself in a situation where I could provide a much nicer user experience if I could disable CSRF token checking for an endpoint in my rails app.
The endpoint is a create action (routed to by POST /whatever), that's behind a devise :authenticate! filter.
Would I open myself up to any additional security risks by disabling the CSRF-protection for that specific endpoint, or can I safely rely on the authentication before_filter to stop the kind of malicious requests that the CSRF token protects against?
Following is a bit more detailed explanation as to why I want to do this if anyone is interested.
My use case is that I basically want to create something very similar to the Facebook likebutton, but this button (unlike the Facebook counterpart) is commonly going to occur multiple times on the same page.
The CSRF protection works fine except for the case where the user visits the page with empty cookies.
In this case rails generates a new session for each of the X number of requests since they are all cookie-less. And, of course, for each new session a new CSRF token is generated and returned in the response to the iframe.
Since the browser only keeps one cookie for the domain, any subsequent requests from each of the iframes will be mapped to the same session, and thus all of the CSRF tokens (except one) are invalid.
The mapping to a single session is nice since the user can be prompted to log in once, and then be mapped to the same log in for each of the subsequent buttons presses – without having to reload the page.
A compromise would be to respond with a 401 Unauthorized, but preserve the session of the rejected request (by overriding handle_unverified_request). This would trigger the sign in popup again, but this time an instant redirect occurs since the user is already signed in.
It would, of course, be best to avoid that flash of the sign in popup window, and thus I'd like to disable the CSRF protection all together for just the create action.
Authenticated requests are precisely what CSRF is about.
What CSRF means is that the attacker convinces the user's browser to make a request. For example you visit a page hosted by an attacker that has a form that looks like
<form action="http://www.yourapp.com/some_action">
#for parameters here
</action>
And some javascript on the page that auto submits the form. If the user is already logged in to your app, then this request will pass any cookie based authentication checks. However the attacker doesn't know the csrf token.
For an unauthenticated request, csrf serves no purpose - the attacker can just go ahead and make the request anyway - they don't need to hijack the victim's credentials.
So, short version: disabling csrf protection will leave you vulnerable to csrf style attacks.
What CSRF is really about is making sure the form contains a parameter that an attacker can't fake. The session is an easy place to store such a value but I imagine you could come up with alternatives. For example if the user can't control any of the parameters in the form, you could add another parameter which would be a signature of all the other parameters in the form (possibly with some sort of timestamp or nonce to prevent replay attacks). Upon receiving the request you can tell whether the request is from a form you generated by verifying the signature.
Be very careful about this sort of stuff as it is easy to get wrong (and even the big boys get it wrong sometimes.

How to pass the CSRF token between rails applications

Our rails3 application talks to another rails application exposed as REST functions. We get the following warning post migration to rails3 on all POST calls made to the REST services.
WARNING: Can't verify CSRF token authenticity
How should we pass the csrf token on the wire when we make a POST call to the REST services, the ApplicationController has protect_from_forgery method and the call also lands on the handle_unverified_request call. We use HTTP basic auth to authenticate and it seems to work fine. What should we do to resolve this issue.
Ok now I'll give it a shot to answer your question.
CSRF tokens are "session dependent" this means the user must share a session with the application he is communicating with. This means a request must have been made before he submits the actual form which is the case for standard HTML forms where the form is displayed before it is submitted so there's room to generate a CSRF token for this user.
Let's call the Application which serves the UI Button App1 and the one hosting the REST Service App2.
The User shares a session with App1 and gets the UI Button served by App1. Once the user clicks the button a request to App1 is made, and App1 makes a request to the REST Service of App2.
Conclusion: The user doesn't share a session with App2 but your App1 has a session with App2. This concludes in two things:
The User is not vulnerable to Cross-Site-Forgery on App2 because he doesn't have a session on that server. So if I post a something like <img src="http://app2.com/rest-service/destroy> here, App2 wouldn't recognise me because I don't share a session with App2 and nothing happens.
You can implement your own security measures on the REST Service to secure it from the public:
Authentication by HTTP Basic Auth
Authentication by an API Key
....
This means you can drop the CSRF protection on the REST Service and stay on the safe side as long as user's can't make direct calls via AJAX etc.
Addition
CSRF protects your site from submitted forms that do not come from your origin (actually this applies to POSTed forms only since they usually manipulate data.
The big scenario is: I'm the attacker and I'd like to update your users account name to "Mr. Potatoe" the way I'd do that is to place a hidden form on my website which gets POSTed to Yourdomain.com/account with a hidden field like account[name]="Mr. Potatoe". Now what happens without CSRF protection? My browser submits the form, and sends the authentication cookie with it and my name is now "Mr. Potatoe". What happens with CSRF protection? My browsers submits the form and sends the cookie but the form has no CSRF token so the request gets rejected. Now is there a way as attacker to get the CSRF token under these circumstances? The answer is no. Maybe you ask yourself....
What if I place a hidden iframe on my site which points to Yourdomain.com/account/edit and just copy the hidden field containing the token? - Answer: It won't work because of same origin policy, you can't read whats inside an iframe if its content doesn't come from your domain.
What if I make an AJAX call in the background to get the token? Answer: It won't work because using pure AJAX you are bound to the same origin policy as well.
Now let's get to the point: I can't send a hidden AJAX call from my page to yours to harm your user who is on my site.
What does it mean? You can implement a before filter which checks if request.xhr? is true or whether the user agent is something like "My REST Client XY" because this can't be forged by a cross site request in a >>browser<<. So if this is the case you can ignore/disable the CSRF protection.
By the way if you want to make an AJAX request within your site you can get the CSRF token like this:
var token = $('meta[name="csrf-token"]').attr('content');
See the Rails UJS Script: https://github.com/rails/jquery-ujs/blob/master/src/rails.js#L81
NOTE: this only protects you from cross site forgery and nothing else....

Rails API design without disabling CSRF protection

Back in February 2011, Rails was changed to require the CSRF token for all non-GET requests, even those for an API endpoint. I understand the explanation for why this is an important change for browser requests, but that blog post does not offer any advice for how an API should handle the change.
I am not interested in disabling CSRF protection for certain actions.
How are APIs supposed to deal with this change? Is the expectation that an API client makes a GET request to the API to get a CSRF token, then includes that token in every request during that session?
It appears that the token does not change from one POST to another. Is it safe to assume that the token will not change for the duration of the session?
I don't relish the extra error handling when the session expires, but I suppose it is better than having to GET a token before every POST/PUT/DELETE request.
Old question but security is important enough that I feel it deserves a complete answer. As discussed in this question there are still some risk of CSRF even with APIs. Yes browsers are supposed to guard against this by default, but as you don't have complete control of the browser and plugins the user has installed, it's should still be considered a best practice to protect against CSRF in your API.
The way I've seen it done sometimes is to parse the CSRF meta tag from the HTML page itself. I don't really like this though as it doesn't fit well with the way a lot of single page + API apps work today and I feel the CSRF token should be sent in every request regardless of whether it's HTML, JSON or XML.
So I'd suggest instead passing a CSRF token as a cookie or header value via an after filter for all requests. The API can simply re-submit that back as a header value of X-CSRF-Token which Rails already checks.
This is how I did it with AngularJS:
# In my ApplicationController
after_filter :set_csrf_cookie
def set_csrf_cookie
if protect_against_forgery?
cookies['XSRF-TOKEN'] = form_authenticity_token
end
end
AngularJS automatically looks for a cookie named XSRF-TOKEN but feel free to name it anything you want for your purposes. Then when you submit a POST/PUT/DELETE you should to set the header property X-CSRF-Token which Rails automatically looks for.
Unfortunately, AngualrJS already sends back the XSRF-TOKEN cookie in a header value of X-XSRF-TOKEN. It's easy to override Rails' default behaviour to accomodate this in ApplicationController like this:
protected
def verified_request?
super || form_authenticity_token == request.headers['X-XSRF-TOKEN']
end
For Rails 4.2 there is a built in helper now for validating CSRF that should be used.
protected
def verified_request?
super || valid_authenticity_token?(session, request.headers['X-XSRF-TOKEN'])
end
I hope that's helpful.
EDIT: In a discussion on this for a Rails pull-request I submitted it came out that passing the CSRF token through the API for login is a particularly bad practice (e.g., someone could create third-party login for your site that uses user credentials instead of tokens). So cavet emptor. It's up to you to decide how concerned you are about that for your application. In this case you could still use the above approach but only send back the CSRF cookie to a browser that already has an authenticated session and not for every request. This will prevent submitting a valid login without using the CSRF meta tag.
Rails works with the 'secure by default' convention. Cross-Site or Cross-Session Request Forgery requires a user to have a browser and another trusted website. This is not relevant for APIs, since they don't run in the browser and don't maintain any session. Therefore, you should disable CSRF for APIs.
Of course, you should protect your API by requiring HTTP Authentication or a custom implemented API token or OAuth solution.

Resources