Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding CSRF in Django; hidden field in form and the CSRFCookie

Tags:

django

csrf

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?

like image 941
damon Avatar asked Mar 30 '12 03:03

damon


2 Answers

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.

like image 112
Todd Avatar answered Oct 23 '22 06:10

Todd


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.

like image 1
JonasVautherin Avatar answered Oct 23 '22 08:10

JonasVautherin