Search code examples
djangocsrfdjango-csrf

Why do we need both the csrftoken cookie and the HTML form's hidden input's csrfmiddlewaretoken value?


I'm trying to learn about security. I am curious about why, in Django, when submitting a form (a POST), there are 2 separate elements that contain the same csrf token value:

  • The csrftoken cookie: {'csrftoken': '1effe96056e91a8f58461ad56c0d4ddc', ...

  • The form's hidden csrfmiddlewaretoken: <QueryDict: {u'csrfmiddlewaretoken': [u'1effe96056e91a8f58461ad56c0d4ddc'], ...

If Django is inserting the hidden csrf field/value to the form when it sends it to the browser (GET), and expects the same value back when receiving the POST, then why is it necessary to also set a cookie?

A more general question, if either of them was missing (form, cookie), could you provide a scenario that explains how this could be exploited (security attack)?

By the way, I ran a couple of simple tests to make sure that Django was checking the validity of each one separately and indeed it is:

  • If I change the form's csrf value before doing the POST, I get this debug error back:

    CSRF token missing or incorrect

  • If I delete the csrf cookie before doing the POST, I get a different error back:

    CSRF cookie not set.

I'm just familiar with basic csrf concepts and want to learn how django helps protect against these types of attacks.


Solution

  • From Jeff Atwood's blog entry:

    Preventing CSRF and XSRF Attacks (Oct 14, 2008)

    The original post

    The Felten and Zeller paper (pdf) recommends the "double-submitted cookie" method to prevent XSRF:

    When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. The site should require every form submission to include this pseudorandom value as a form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An attacker cannot read any data sent from the server or modify cookie values, per the same-origin policy. This means that while an attacker can send any value he wants with the form, he will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the pseudorandom value.

    The advantage of this approach is that it requires no server state; you simply set the cookie value once, then every HTTP POST checks to ensure that one of the submitted values contains the exact same cookie value. Any difference between the two means a possible XSRF attack.