top of page

Double Submit Cookie Pattern

  • Writer: Sankalpa H.T.S
    Sankalpa H.T.S
  • Oct 11, 2019
  • 2 min read

Updated: Oct 13, 2019

The goal of this article is to present an implementation of the "double submit cookie" pattern used to mitigate Cross-Site Request Forgery (CSRF) attacks. The proposed implementation is suitable for projects using the PHP language and JS as backend technology.


When a user authenticates to a site, the site should generate a (cryptographically strong) pseudo-random value and set it as a cookie on the user’s machine separate from the session ID. The server does not have to save this value in any way, that's why this pattern is also called Stateless CSRF Defense.


The site then requires that every transaction request include this random value as a hidden form value (or another request parameter). A cross-origin attacker cannot read any data sent from the server or modify cookie values, per the same-origin policy.


In Synchronizer token pattern, both are saved in server-side storage, But in Double Submit Cookies pattern, they are stored in the browser as browser cookies. This is the main difference between these two approaches.



ree
The flow of the double submit cookies pattern

Let’s look at a sample project,


This application is developed using PHP & JS.( Github link - click here)

  • User login. I used hardcoded user credentials for demonstration purposes.


ree
Login screen

ree
Providing login credentials
  • Upon login, generate session identifier and set a cookie in the browser. At the same time, generate the CSRF token for the session and set a cookie in the browser. The CSRF token value is not stored on the server-side.


login.php

ree
token.php

  • Implement a webpage that has an HTML form. The method is POST and action is another URL on the website.

ree
home.php

  • When the HTML form is loaded, run a javascript which reads the CSRF token cookie value in the browser and add a hidden field to the HTML form modifying the DOM.

ree
script.js

  • When the form is submitted to the action, the CSRF token cookie will be submitted and also in the form body, the CSRF token value will be submitted.

ree
Csrf token value in the hidden field in the form

  • In the web page that accepts the form submission (the URL of the action), obtain the CSRF token received in the cookie and also in the message body. Compare the two values received and if they match, show a success message. If not show an error message.

ree
result.php

ree
Result page

ree
Change the csrf value into false value by inspecting the home page

ree
Result page

The source link of the sample project:


Conclusion


The Double Submit Cookie Pattern techniques described in this scenario are viable and worth a thought for any application that contains useful data.

References



 
 
 

Comments


bottom of page