Django CSRF protection forces to set "Vary: Cookie" header that leads to inefficient cache
Asked Answered
L

2

6

Django's CsrfViewMiddleware sets "Vary: Cookie" header, that means that cache system will take into account not only page URL but also user's Cookies that are unique for each user. So pages don't cache once for all users, but for each user. And in my case I have very loaded site, and such behaviour does not satisfy me.

  • Do I have right view on this issue, or I'm wrong?
  • Can I turn off setting "Vary: Cookie" header without turning off CSRF protection?
Lipetsk answered 12/8, 2015 at 7:48 Comment(2)
You can turn it off, but it will produce horrible consequences: each user connected through some caching server or proxy will have same CSRF token as other users connected through that server.Palomino
Turning of Vary: Cookie basically allows any site to bypass your CSRF protection, because they have the same token as the victim.Outhaul
C
4

Yes, you have the right view on this issue. When you use Django's CSRF-protection for a view, not only are the cookies unique for each user, but also the page content because every CSRF-protected form has a hidden field csrftoken.

You could work around this issue by setting the value of the csrftoken field to match the cookie on the client side with JavaScript, but this is not provided out of the box by Django.

However, you will have to ensure that:

  1. your users actually does get a unique CSRF token somehow
  2. as noted by @patrys, CSRF tokens are never accidentally shared between users through the cache (e.g. by stripping Cookie headers from responses)

There are several opportunities to shoot yourself in the foot and make your site susceptible to CSRF attacks.

Chirpy answered 12/8, 2015 at 11:43 Comment(1)
Django re-sets the CSRF cookie with each response so any cached response will likely also contain the Set-Cookie header.Loy
L
1

It will compromise your site's security if multiple users access the site through a caching proxy.

The proxy will see that the response does not depend on the cookies and will serve the same response (along with the same CSRF token in the contained hidden field and in cookie headers) to all its users.

Since all users share the same secret, they are now all open to each other's cross-site resource forgery attacks.

Also it's very likely that each view will end up being cached with a different CSRF token and accessing such URLs in parallel (in a different tab, in an iframe or using AJAX) will overwrite user's cookies and thus make it impossible to submit a POST request.

Loy answered 12/8, 2015 at 11:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.