6

I am writing down my understanding of the CSRF protection mechanism in Django. Please correct me if it is faulty.

The csrfViewMiddleware creates a unique string and stores it in a hidden field 'csrfmiddlewaretoken' of a form originating from the host. Since a malicious website mimicking this form will not know about the value of this field, it cannot use it.

When someone tries to POST the form, the website checks the 'csrfmiddlewaretoken' field and its value. If it is wrong or not set, then a csrf attack is detected.

But then, what exactly is the CSRFCookie? The doc says the unique value is set in CSRFCookie and also in the hidden field.This is where I am confused. Does a cookie get sent to the browser with the unique string embedded?

damon
  • 8,127
  • 17
  • 69
  • 114

2 Answers2

5

Django assigns an authenticated user a CSRF token that is stored in a cookie. The value in this cookie is read every time a user makes a request that is considered "unsafe" (namely POST, PUT, DELETE) in order to validate that the user, not a malicious third-party, is making the request.

The CSRF tag you place in a form actually grabs the CSRF token from the cookie and then passes it in as a POST variable when you submit a form.

Todd
  • 922
  • 7
  • 19
  • So only an authenticated user's browser gets this token and not everyone who visits the site.Is that correct? – damon Mar 30 '12 at 03:46
  • Not sure how Django handles it exactly - it may protect all users regardless of authentication status. Basically any action that has the ability to change some facet of your app should have CSRF protection. – Todd Mar 30 '12 at 03:49
1

With my current understanding, I am not entirely satisfied with the validated answer.

You can find my version here.

To summarize, the CSRFCookie is "safe", in the sense that the attacker cannot access it because of the same-origin policy. The browser will send this value automatically. Now, your form must also send this value (e.g. in a hidden field). This means that your form must know this value, and it can get it from the cookie.

The attacker cannot get the token from the cookie, and therefore cannot forge a malicious code that contains the token.

What is important, in the end, is that the user can send a csrf token, and that the server can verify it. Using a cookie is a convenient way of doing this, but this could be implemented differently (e.g. the server could save the CSRF tokens for each session, for instance).

I am not a specialist, but this is how I understand it. Hope it helps.

Community
  • 1
  • 1
JonasVautherin
  • 7,297
  • 6
  • 49
  • 95