tecywiz121 / iron-dsc-csrf

Iron middleware providing CSRF protection.
MIT License
1 stars 1 forks source link

Use HMAC instead of Double-Submit cookie #1

Open balasanjay opened 6 years ago

balasanjay commented 6 years ago

The Double-Submit cookie is vulnerable if the attacker can write cookies on your domain. For instance, an attacker can write COOKIE=abc123 and then send a request to server.com/delete_account?xsrf_token=abc123.

How does an attacker write cookies on your domain? The simplest way is to compromise a related website. e.g. if your website is hosted on foo.herokuapp.com, they can register a website at foo-exploit.herokuapp.com that sets the COOKIE on .herokuapp.com. Or a more sophisticated attacker (say one with access to your Wifi network) could make you insecurely load "http://server.com" (assuming you don't have HSTS), and then respond with a Set-Cookie header.

A better approach is to mint tokens using a HMAC with a secret key that is only known to the server. See https://godoc.org/golang.org/x/net/xsrftoken for an example of the implementation of this; although two improvements I would make over that library is to a) support straightforward key rotation (e.g. it'll try validating the HMAC with all keys, but only minting an HMAC using the first key), and b) don't say that the userID is optional. If users use the same value for all requests, then bad things happen (an attackers XSRF token is valid for the attacked user).

There's also a hybrid mode where you can avoid the userID. Essentially, you store value x in the cookie, and the XSRF-token itself is HMAC(server_only_secret_key, x). That way, even if the attacker does "COOKIE=abc123", they won't be able to compute the HMAC. Basically, x here would take the place of the userID.

balasanjay commented 6 years ago

Actually, on second thought, my hybrid mode suggestion is still vulnerable; since the attacker can read their own value of the cookie, and get their own xsrf token. They can then just write the victim's COOKIE to their own cookie value and use their own xsrf token as the victim's xsrf token value.

I think you really do need a notion of userID, to bind the XSRF token to the authenticated user.

tecywiz121 commented 6 years ago

I started by using an HMAC based approach (the cookie crate supports signed cookies out of the box). Without including a user identifier, an attacker could replay any valid CSRF token for any other user. Including a user identifier wouldn't protect anonymous users.

The whole cookie approach doesn't work well without SSL enforced by HSTS.