Do I have to protect against cross domain request forgery? - asp.net

From my research, the proper way to protect against this is to set a NONCE with every GET request that returns a form and then check for the NONCE on the POST request. However, someone could still write a script to GET my form along with the NONCE and then POST it back with the NONCE.
Since this is such a widely known vulnerability, shouldn't browsers already take care of that by not allowing cross-domain ajax calls? If not, does ASP.NET MVC 4 already have a built-in mechanism to protect against this?

Those nonces are used for protecting against cross site request forgeries. A cross domain ajax call is not necessary to make that happen - and browsers do have protections against those. CSRF is a vulnerability because when a browser makes a call to your site, it sends the session information for your site, regardless of the page that told the browser to make the call. The browser can be told to make a get request to your site.com by including an img tag on evilsite.com that points to a page on your site.com. If when that get request is processed by yoursite.com you validate the nonce, there is no way that a drive by of evilsite.com would know the nonce. Similar things can be done for post requests as well.
This page seems to have some information about how to mitigate this in ASP.NEt MVC: http://www.asp.net/mvc/overview/security/xsrfcsrf-prevention-in-aspnet-mvc-and-web-pages
Cheers,
Stefan

Yes there is a built in mechanism. HtmlHelper.AntiForgeryToken, which can be used to help protect your application against cross-site request forgery. To use this feature, call the AntiForgeryToken method from a form and add the ValidateAntiForgeryTokenAttribute attribute to the action method that you want to protect.
CSHTML file:
#Html.AntiForgeryToken()
Controller:
[ValidateAntiForgeryToken]
public ActionResult Edit(User updatedUser)
You'll note that the token involves two safety measures -- a form field and a cookie:
To generate the anti-XSRF tokens, call the #Html.AntiForgeryToken()
method from an MVC view or #AntiForgery.GetHtml() from a Razor page.
The runtime will then perform the following steps:
If the current HTTP request already contains an anti-XSRF session
token (the anti-XSRF cookie __RequestVerificationToken), the security
token is extracted from it. If the HTTP request does not contain an
anti-XSRF session token or if extraction of the security token fails,
a new random anti-XSRF token will be generated.
An anti-XSRF field
token is generated using the security token from step (1) above and
the identity of the current logged-in user.
If a new anti-XSRF
token was generated in step (1), a new session token will be created
to contain it and will be added to the outbound HTTP cookies
collection. The field token from step (2) will be wrapped in an element, and this HTML markup will be the return
value of Html.AntiForgeryToken() or AntiForgery.GetHtml().
Reading:
XSRF/CSRF Prevention
Wikipedia CSRF

You should also take a look at the concept of stateless CSRF protection. There are 2 standard approaches to achieving this: the Encrypted Token Pattern and the Double Submit Cookie pattern. The Encrypted Token Pattern leverages a Rijndael-encrypted Token which contains a built-in nonce value that can’t be read by scripts, and is a very strong cryptographic structure.

Related

System.Web.Helpers.AntiForgery cookieToken

can anybody explain what exactly the cookieToken parameter is when I call the function in MVC: AntiForgery.Validate(cookieToken, formToken);
Is it possible to use the cookieToken as a Session identifier to identify the user and current session?
No.
ASP.Net generates a random Cross-site Request Forgery (CSRF) Token on every request (even for the same user). You can verify this by going to your website and looking at the source. There will be a hidden field "__RequestVerificationToken" that will contain a string of random letters and numbers. When you refresh the page it will randomly generate a new set of letters and numbers.
This is not to identify a user to a particular session, but to identify a user to a single request.
To read more on CSRF attacks to understand the purpose of this token, read OWASP's Top 10 on Cross-Site Request Forgery

How to format header WWW-Authenticate when authentication fails

I'm implementing a REST API that also provides functionality for authenticating users. Authentication requires an user to send a POST request with the following data in the body:
{
"userOrEmail": "spook",
"passowrd": "Test1234"
}
If the username and password match, the user gets back a token from the server, while if they don't, the server returns 401 Unauthorized, with the following header:
WWW-Authenticate: Credentials realm="http://localhost:9000/auth/users/credentials"
Is that header acceptable? realm contains the location where the user can try to authenticate again.
It appears to be acceptable, but maybe not optimal except under very specific conditions. From RFC1945:
The realm value (case-sensitive), in combination with the canonical root URL of the server being accessed, defines the protection space. These realms allow the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme and/or authorization database. The realm value is a string, generally assigned by the origin server, which may have additional semantics specific to the authentication scheme.
So, you can, but I might be paranoid about multiple applications using the same authentication and inadvertently cross-authenticating if they were to share the same realm name. Better would be to isolate the realm by application, just to be on the safe side.
No, it's not acceptable.
a) There is no authentication scheme called "credentials".
b) The purpose of the "realm" parameter is different.

Is there a default http request header to identify the user making a request?

In the data model behind my RESTful API there are several entities with the CreatedBy/ModifiedBy fields. The only access to this data is through my API, and as such, the fields should be populated with the user id of the user making the request to my API.
I have considered either adding these fields to the models exposed by my API or expecting a request header containing the user id on all PUT/POST/DELETE requests. I would be interested in any opinions as to which approach is best, or any other approach.
I like the idea of providing it in the header since it is necessary for every request and I am wondering if there is a standard request header to contain the information, or a common x-header.
I have seen the from request header; however, it seems to be defined as the email address of the user making the request and I need to pass the user id.
In our current implementation, we use the authorization header to authenticate the calling application with the API, and not for a specific user.
Which header would you use to pass information to identify the user making a request?
You can extend the Authorization header to add your own parameters. Both the Digest and OAuth authorization schemes support parameters. The Basic scheme already have the user credentials readable. Something like:
Authorization: OAuth realm="Photos",
oauth_consumer_key="dpf43f3p2l4k3l03",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="137131200",
oauth_nonce="wIjqoS",
oauth_callback="http%3A%2F%2Fprinter.example.com%2Fready",
oauth_signature="74KNZJeDHnMBp0EMJ9ZHt%2FXKycU%3D",
xoauth_user_guid="alganet"
Yahoo! does something similar with their OAuth implementation, but in another context.
http://developer.yahoo.com/oauth/guide/oauth-accesstoken.html.
However, if these fields are shown or exposed somehow in your public API, they belong to RESTful resources and should be represented always in the body, not the headers. If you GET the username in the message body, you should POST the username using the message body as well.
Assuming you can use HttpClient
HttpClient client = HttpClientManager.getNewClient();
HttpMethod get = new GetMethod(...);
get.addRequestHeader("x-newHeader", "value");
more here
OR using URLConnection using setRequestParameter

CSRF Protection for non form post requests

Implementing CSRF tokens in hidden form fields is the standard protection for CSRF for form post requests.
However, how would you implement this for GET requests? Or ajax requests that POST json data instead of x-www-form-urlencoded for the request body? Are these types of things all handled on a case by case ad hoc basis?
OWASP says this about CSRF and GET requests:
The ideal solution is to only include the CSRF token in POST requests
and modify server-side actions that have state changing affect to only
respond to POST requests. This is in fact what the RFC 2616 requires
for GET requests. If sensitive server-side actions are guaranteed to
only ever respond to POST requests, then there is no need to include
the token in GET requests.
Also, OWASP notes:
Many implementations of this control include the challenge token in
GET (URL) requests [...] while this control does help mitigate the risk
of CSRF attacks, the unique per-session token is being exposed for GET
requests. 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
Referrer headers if the protected site links to an external site.
The trouble here is that if a user's token is leaked, you're still vulnerable - and it's all too easy to leak the token. I'm not sure that there's a good answer to your question that doesn't involve converting all of those GET requests to POST requests.
It's worth noting that the Viewstate feature in ASP.NET WebForms does offer some protection against CSRF, though it's very limited - in fact, it also only protects POSTback requests.
To state this more simply, you shouldn't use a GET request as an entry point to any function that does something beyond return a read only resource for a browser to render. So don't have an AJAX script make a GET based call to a URL like transferMoney.aspx?fromAcct=xyz&toAcct=abc&amount=20.
The HTTP specification states explicitly that HTTP GET requests should not have side effects. It's considered best practice to keep your GET requests idempotent whenever possible.
I've written an article about protecting ASP.NET MVC against CSRF, it spells out a practical approach to applying the AntiForgeryToken to POST controller methods on your site.
It depends on the CSRF-protection pattern you're applying. First off, CSRF applies to endpoints that change state. If you're GET requests change state, then I advise that you modify them to POSTs. Having said that, it is a valid point.
The ideal place to persist Tokens is in the AUTH Header. This is the lowest common denominator across FORM-POSTs, AJAX and GET requests. You could of course store the Token in a Cookie, but there is a vulnerability in this design when applied to a multi-domain site.
You can parse the Token from a hidden field during FORM-POST without issue. Not much point in changing that. Assuming that your GET requests are invoked with AJAX, you can leverage JQuery's ajaxSetup method to automatically insert the Token on every AJAX request:
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "TOKEN " + myToken);
}
});
There is a relatively new pattern gaining traction called the Encrypted Token Pattern. It's described in detail here, and also on the official OWASP CSRF Cheat Sheet. There is also a working implementation called ARMOR, which may offer you the flexbility you're looking for across various types of requests.

Are JSON web services vulnerable to CSRF attacks?

I am building a web service that exclusively uses JSON for its request and response content (i.e., no form encoded payloads).
Is a web service vulnerable to CSRF attack if the following are true?
Any POST request without a top-level JSON object, e.g., {"foo":"bar"}, will be rejected with a 400. For example, a POST request with the content 42 would be thus rejected.
Any POST request with a content-type other than application/json will be rejected with a 400. For example, a POST request with content-type application/x-www-form-urlencoded would be thus rejected.
All GET requests will be Safe, and thus not modify any server-side data.
Clients are authenticated via a session cookie, which the web service gives them after they provide a correct username/password pair via a POST with JSON data, e.g. {"username":"user#example.com", "password":"my password"}.
Ancillary question: Are PUT and DELETE requests ever vulnerable to CSRF? I ask because it seems that most (all?) browsers disallow these methods in HTML forms.
EDIT: Added item #4.
EDIT: Lots of good comments and answers so far, but no one has offered a specific CSRF attack to which this web service is vulnerable.
Forging arbitrary CSRF requests with arbitrary media types is effectively only possible with XHR, because a form’s method is limited to GET and POST and a form’s POST message body is also limited to the three formats application/x-www-form-urlencoded, multipart/form-data, and text/plain. However, with the form data encoding text/plain it is still possible to forge requests containing valid JSON data.
So the only threat comes from XHR-based CSRF attacks. And those will only be successful if they are from the same origin, so basically from your own site somehow (e. g. XSS). Be careful not to mistake disabling CORS (i.e. not setting Access-Control-Allow-Origin: *) as a protection. CORS simply prevents clients from reading the response. The whole request is still sent and processed by the server.
Yes, it is possible. You can setup an attacker server which will send back a 307 redirect to the target server to the victim machine. You need to use flash to send the POST instead of using Form.
Reference: https://bugzilla.mozilla.org/show_bug.cgi?id=1436241
It also works on Chrome.
It is possible to do CSRF on JSON based Restful services using Ajax. I tested this on an application (using both Chrome and Firefox).
You have to change the contentType to text/plain and the dataType to JSON in order to avaoid a preflight request. Then you can send the request, but in order to send sessiondata, you need to set the withCredentials flag in your ajax request.
I discuss this in more detail here (references are included):
http://wsecblog.blogspot.be/2016/03/csrf-with-json-post-via-ajax.html
I have some doubts concerning point 3. Although it can be considered safe as it does not alter the data on the server side, the data can still be read, and the risk is that they can be stolen.
http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx/
Is a web service vulnerable to CSRF attack if the following are true?
Yes. It's still HTTP.
Are PUT and DELETE requests ever vulnerable to CSRF?
Yes
it seems that most (all?) browsers disallow these methods in HTML forms
Do you think that a browser is the only way to make an HTTP request?

Resources