简体   繁体   中英

HTTP(S) request security using random headers

I understand that CSRF is a major security concern for HTTP(S)-based applications.

From the looks of it, most frameworks send the CSRF token as part of the request body. However, in my case that is somewhat inelegant for several reasons; most importantly I don't want to mess with the transport layer which might send POST requests in many different formats, not necessarily all are JSON or x-www-form-urlencoded .

As a solution, I was thinking of a much less intrusive alternative; particularly, I am generating a random header: A randomized header name (common prefix), containing a random CSRF token.

Is there any security (or other kind of) risk to that?

You could just set the X-Requested-With header and then check for this server side. Many frameworks, like JQuery, add this automatically to AJAX requests.

X-Requested-With is a de-facto standard for indicating that the request is made via AJAX.

You do not need a random token as it is not possible for this header to be sent cross domain without the server opting in via CORS.

Therefore, setting and checking a non-standard header is a valid way to protect against CSRF.

The OWASP CSRF Prevention Cheat Sheet does not mention it, however it does mention checking the Origin header. However, the logic for this is not straightforward as many browsers do not send Origin for same origin requests.

Also this only works for AJAX requests. With a normal form POST it is not possible to add extra headers. Also, in the past there have been bugs with plugins like Flash that allowed any header to be set enabling an attacker to use Flash to make a cross-domain request. However, issues like these have long since been patched.

If you want a token as well as part of a defence in depth strategy, you could adapt X-Requested-With to include a random token that you then check. eg X-Requested-With: XMLHttpRequest;0123456789ABCDEF .

Then token could simply be a cookie value created just for CSRF prevention purposes (generated with a cryptographically secure algorithm and entropy source of course).

Is there any security (or other kind of) risk to that?

There is no: as soon as you can pass it from the client and check on the server - you're fine

Also, how often should I refresh the CSRF token? Do I need a new one for every request, or every few requests, or once per site-visit and day, or...?

Generally you should not refresh it at all. If it's generated using cryptographically strong random number generator - you can have one per session. What important is that it was not possible to guess it, so it should not derive from any known data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM