Double Submit Cookie for Cross-Site Request Forgery Prevention

Ruween Iddagoda
3 min readFeb 21, 2022

One of the extensively used alternatives for Synchronizer Token Pattern, for protection against Cross-Site Request Forgery, is the Double Submit Cookie.

Double Submitting cookies, as the name suggest, is sending an arbitrary unique generated value, both as a cookie and a POST data, where the server compares the two to verify and differentiate between legitimate users and impersonators.

Overview

When a user logs into the system, a session is created and a session ID is set as a cookie, alongside another cookie will be created containing a CSRF token.

Then, the token value will be extracted from the cookie and will be placed in a hidden input field in the HTML, and will be used to verify submitted forms by comparing the POST data with the actual cookie data.

The reason behind using two separate cookies is that, it allows the main cookie to be marked as HttpOnly, thus making it inaccessible to JavaScript. Also making it arguably harder for an attacker to penetrate.

Double Submit Cookie mitigates CSRF

The Following is a implementation of a Double Submit Cookie in a Web Application. (Source Code — GitHub)

Explanation of the Code

The main program is quite similar to previous example used in the Synchronizer Token Pattern. (More on that here)

Token::generate()

Token generation function is the same as my previous example, with the only difference being the fact that the generated token is passed into a cookie.

Ajax call to obtain the cookie

document.cookie.match function will return the cookie with the name, “csrf”. And if that cookie matches cookie[2] then it’s passed into the element with the id of “csrf”, which is the hidden input filed.

Obtaining CSRF cookie Flow Chart

Finally, In the process.php the POST data will be compared with the cookie data as seen below. If it matches, the session is valid and the requested task will execute.

comparing POST data with cookie values

Once completed make sure to empty out the csrf cookie.

Cleaning the CSRF cookie

Even after implementing a Double Submit Cookie Protection to a Web Application, it can still be susceptible to CSRF attacks due to;

  • Potential Cross-Site Scripting vulnerabilities in sub domains, which can introduce poisoned cookies in upper domains
  • Cookies with sensitive server metadata are not being flagged as HTTPOnly

Therefore, it’s crucial to identify any other loop holes that may exist within the system and secure them as well.

--

--