Wednesday, September 5, 2018

Double Submit Cookie Pattern


Previously, in my last blog post I discussed about the Synchronizer Tokens Pattern as one of the solutions for the Cross Site Request Forgery attack on Web Applications. Today, let's look at the Double Submit Cookie Pattern to prevent from CSRF attack. 

Upon the user login, when a user authenticates to a site, the site should generate a session identifier and set a cookie in the browser. At the same time, it generates the cryptographically strong random value or the CSRF token for the session and set it as a cookie on the user's machine separate from the session id. 

Here unlike the Synchronizer Token Pattern server does not have to store this CSRF token value anyway, that is why this pattern is sometime also called Stateless CSRF Defense. The site then requires that, every request include this random value (CSRF token) as a hidden form value. A cross-origin attacker cannot read any data sent from the server or modify the cookies value. Here the client is just retrieve the CSRF cookie from the response and add it into a special header to all the requests. Sever job is here to create the CSRF cookie and for each request check that the CSRF cookie and the CSRF header of the request are matching.

Following example shows what happens in this security pattern.



As you can see the message flow of the diagram, let's say John provides his credentials to go through the authentications process.Then server will create a new session and unique session id for this legitimate user after validating user credentials.

Same as the Synchronizer Token Pattern, at the login phase server will create a CSRF token for this particular session. This Cookie value cannot be set as HttpOnly because client needs to be able to access this since server has no records of this generated token.The difference here is, server is not going to  keep record and store the CSRF token in server side. Instead, server will send the CSRF token in the response and forget it. (But in Synchronizer Token Pattern server has to keep and store all the tokens. Imagine there are one billion of users, then the server storage needs to store one billion of record or even more, because one user can have multiple sessions)

Now let's say John wants to update his status on Facebook and he browses that updates status page. Then this request is sent to the server and there the session cookie goes, so server knows that is John who is logged in. Then the server sends the updateStatus.html page as the response in return.

Now what happens is, let say that HTML has some text box and a submit button where user can type the status and clicks on the button. After that on form submit event, it will send a POST request for getting the status updated. When that HTML form is loaded in the browser, internally it runs Java Script which reads the CSRF cookie value in the browser and embed a hidden field to the HTML by modifying the DOM (Document Object Model). 

Then the web page accepts this form submission, obtain the CSRF token received in the cookie and also in the message body. Later on it compares two values received and if they match, the request will be satisfied and status will get update. Simply this is how Double Submit Cookie Pattern works.

Will an attacker able to perform this ??

In a scenario like, an attacker hosts the same web page in attacker.com.But the cookies are owned by facebook.com. So the attacker cannot access those from being in a different domain. Only if web page runs under the facebook.com domain, that javascript can read the cookies and embed the value into page source. That means a cross-domain attacker cannot read any data sent from the server or access cookie values under the same-origin policy. Therefore attacker fails here to perform this action.

Now lets move into the sample application developed for explain this security pattern.


Sample Application


This sample application is developed using PHP and you can find the uploaded Github source code from here . 

The application is mainly consists of three main screens which are login page, update status page and updated results page. Now starting from the login page let's discuss the implementation flow of the Double Submit Cookie Pattern using this simple application.

The login page is as follows. First you need to login to the application by entering username and password. For the demonstration purpose here I have hard coded the credentials. You can enter user credentials as follows.

Username: admin
Password : admin






index.html

Here, at the login, if the user is successfully authenticated it will generate the session cookie and CSRF cookie. After logging in, you can observe above mentioned cookies being added to your browser.

Application Cookies 

Below HTML page is for you to write your status.




As you can see updateStatus.html file below, you can observe how session cookie and CSRF cookies are stored on the browser. These cookies have one year expiration time and they are accessible from anywhere. Java Script is there to retrieve the CSRF token value from the CSRF cookie set on the browser. The DOM will be modified with that value retrieved from the CSRF cookie.


updateStatus.html 

Below HTML page shows the updated status.











results.html

As you can see in results.html, CSRF cookie value and the CSRF value embedded in hidden field are sent to the token.php by invoking checkToken() function.

 token.php

If checkToken() in token.php returns true, that means CSRF token values are matched and status get update.

You can find the full implementation of this sample application at, 

Synchronizer Token Pattern

Previously in my last blog post (Cross Site Request Forgery) I discussed about what is CSRF attack on Web Applications and today I am going to explain the Synchronizer Token Pattern in this blog post as one of the identified solutions for this CSRF security attack. 

Now let's assume all the state changing operations are done through POST, PUT, DELETE requests and anyway session cookie is going with these requests. But assume we expect user to send some specific token along with the request and only if that token is received Facebook server will validate the token and allow the request to be processed.

Synchronizer Token Pattern is used this security token method to prevent form the CSRF attack on Web Applications. Following diagram will simply show how this security pattern works.


As the diagram shows, let's say John needs to log in to Facebook and he enters his account credentials (username and password). After John entering his credentials, server will authenticate the user and create a Session Id for the particular session. Additionally what happens in Synchronizer Token Pattern is, server generates a random token which we call as a CSRF token. At the login process server will generate, store and keep this token at server side in the user session. Browser even does not know anything about this CSRF token. Only Session Id will come along with the session cookie and store at the browser's cookie storage.

Now user is logged in successfully and browser has the session id. Let say John wants to update his status on Facebook and he browses that update status page. Then this request is sent to the sever and there the session cookie goes, so server knows that is john who is logged in.Then server sends the response updateStatus.html page in return. 


Now what happens is, let say that HTML page has some text box and a button where user can type the status and clicks on the button, that will send a POST request for getting the status updated. When that HTML page get rendered in the browser, internally this page knows that it has a form and some JavaScript (JS). That JavaScript knows there is a HTML form and user will make some POST request. So, what that JS does is, when this page loads in the browser, that will make an Ajax request to some URL (facebook.com/getToken) in the website. This Ajax call contains the session cookie. Hence along with that request session id will go because the path and domain is matched. So server knows this is a valid user who is making the request after checking the session id. Then server will send the corresponding CSRF token along with the response of that Ajax call. This whole process is done by JS embedded into the page.


When JS receives the CSRF token, it modifies the DOM (Document Object Model), get the source and embed a hidden field on from submit. User doesn't see this is happening when page loads. So, user types the status and click on the submit button. It will send another POST request to update the status of the page. With this request, session cookie, status value in the body and the CSRF token also go. Now server receives this request. Whenever POST, PUT or DELETE request comes server knows that it needs to protect the token. So first server will check the cookie is received in the header. Then server checks is it a legitimate cookie or John is a valid user. After that it checks the request body and get the CSRF token. Then sever checks if that token matches with the previously stored session's token. If it matches only John is a legitimate, the request will be satisfied and status will get update. Simply this is how Synchronizer Token Pattern works on Web Applications.


Will an attacker able to perform this?? 

In a scenario like, if the attacker creates his own website (e.g. attacker.com) would attacker be able to make an AJAX call and get the CSRF token ? From attacker.com to facebook.com/getToken, is a cross domain AJAX call where actual user and attacker in two different domains. By default cross domain AJAX calls are not possible. So this attackers's call will fail and an attacker will not be able to obtain the CSRF token. Since the token is unavailable in the request body, the server will not complete the action. Therefore CSRF is prevented.

Now lets move into the sample application developed for explain this security pattern.

Sample Application

This sample application is developed using PHP and you can find the uploaded Github source code from here
The application is mainly consists of three main screens which are login page, update status page and updated results page. Now starting from the login page let's discuss the implementation flow of the Synchronizer Token Pattern using this simple application.

The login page is as follows. First you need to login to the application by entering username and password. For the demonstration purpose here I have hard coded the credentials. You can enter user credentials as follows.

Username: admin
Password : admin


index.html

This login form submits user credentials through a POST method. At the login process, if the user is authenticated, unique Session Id  and the CSRF token will be created along with this session. Upon login, generated session identifier set as a cookie in the browser and at the same time, this CSRF token is stored against the session identifier at server side. For the demonstration purpose here I store CSRF token in a text file called Token.txt. 






























































































updateStatus.html

Here, what internally happens is, updateStatus.html contains the simple PHP code snippets to validate the user credentials. Then it makes an Ajax call to generate the CSRF token to csrf_token_generator.php. This Ajax call contains the session id and upon the Ajax call, server will send the corresponding CSRF token along with the response. This is where token embeds into a hidden field on form submit. User doesn't see this is happening when page loads. So, user types the status and click on the Update button. It will send another POST request to update the status of the page. 

In below screen you can observe the CSRF token value has been added to the hidden field when the form loads. 


























csrf_token_generator.php

This php file is used to generate the CSRF token and it sets corresponding the session id. Here, openssl_randon_pseudo_bytes() is used to generate the 32bit long csrf token. In order to use this function you have to have openssl installed. Otherwise it will give you an error. The generated value then converted into it's base64 value using base64_encode() function in order to make it more secure. 

The POST request that user makes to update the status contains this generated CSRF token and the session cookie. Then server checks the cookie header for session id and request body for get the CSRF token. 

Then server calls checkToken() function to confirm whether the token is matched or not with previously stored session's token. In this sample application token.php is contained this check function which takes csrf token and session id as two input parameters and return true if the received parameters are matching with the values that are stored previously in Token.txt.

token.php


Tokens.txt

To explain you to more, here I will show you two alerts containing the session id and CSRF token coming with the update status POST request. You can see those two are matching with session id and CSRF token stored inside the Token.txt. 




Now let's look at how we can observe updated status. Here, results.php is the place where this checkToken() function  is invoked and display the updated status upon the token validation.






results.php

You can find the full implementation of this sample application at,

https://github.com/TharakaMadushanki/Prevent-CSRF-Attack---Synchronizer-Token-Pattern

Drawback of the Synchronizer Token Pattern is server has to keep and store all the tokens.Imagine there are one billion of users, then the server storage needs to store one billion of record or even more, because one user can have multiple sessions. 

In my next blog post, I will be discussing how Double Submit Cookie pattern is used to prevent from the CSRF attack and you can find it from here.


Tuesday, September 4, 2018

Cross Site Request Forgery (CSRF)


Cross Site Request Forgery is a vulnerability and a common attack that tricks a user into executing an unwanted action (such as sending a link via chat) in a web application. CSRF attack can force the user to perform state changing requests or operations in systems like unfriend a friend in Facebook, upload a photo or status in Facebook, changing email addresses and so forth.

In this blog post I am discussing on what is CSRF attack and how we can prevent from this attack in web applications. In addition to that, I will be discussing on two major security patterns , which we can implement for preventing CSRF attack in my onfall blog posts.

What is CSRF?

There are few ways in which an end user can be tricked into loading information from or submitting information to a web application by attacker. Following diagram will simply explain to you what is CSRF by using a real-world example.





* session-id is used to identify the intended user

If the Facebook was designed to use GET request to unfriend a friend, the unfriend request looks like this:



Below I have explained the ways in which an end user can be tricked by the attacker with respect to the given example.

1. Building an exploit URL


As the diagram shows, let's say John needs to log in to his Facebook account. Normally what he does is he simply enters his Username and Password to get in on Facebook. After John entering his credentials on Facebook, it will authenticate John and create a Session Id for his new Session if only John is a valid user. Later on this session Id will be used to identify the John uniquely. This session Id will come along with the session cookie and store at the browser's cookie storage. 

Let's say John wants to unfriend Sam from his Facebook friend list. Simply he can go to the Facebook page and click on the link to unfriend the Sam. But imagine an attacker prepares that URL (shorten the URL using a URL shorter into https://goo.gl/124qa) to unfriend the Sam from John's account and send that link to the john via chat. 


Assume while you are browsing on Facebook you get a chat message from this Attacker. So, John does not know about that URL and he clicks on it. John's browser is making this request unintentionally (by converting that shorten URL into http://www.facebook.com/user/unfriend? id=Sam) and Sam will be removed from his Facebook account. This is how attacker tricks a user to into execute an unwanted action and this problem is known as the Cross Site Request Forgery.

2. Planting a fake image on page that is likely to be visited by the user

Let say attacker does not need to send this link through a chat to John. Attacker hosts a website (e.g. gossip.com) and in there attacker has this image element.

http://gossip.com

Attacker


Assume somehow John visits this gossip.com and when this page loads hidden image will be tried to get loaded. Since this is not an actual image and this contains the link for unfriend Sam fro the John's Facebook account, when this request fires from the John's browser unknowingly Sam will be removed from his Facebook account. This problem is known as the Cross-Site Request Forgery.

How we can prevent from CSRF attack?

As the fundamental rule of preventing from CSRF attack, never implement any state changing operations in the system through GET requests. State changing operation is any operation that modifies data or behavior of the system.

Modify data à update status, update cover photo in Facebook 

Modify behavior à shutting down a server and sending it to a different state

Let's assume the Facebook now implements a POST request and the vulnerable request looks like this:


Anyone who sends a post request and if the session cookie comes along it will be accepted and then the data does not go as query parameter but in the body. So, can we solve this problem using a POST method instead of using GET method or attacker can still trick the user? Such a request cannot be delivered using a standard Anchor tags or Img tags as discussed earlier, but can be delivered using a FORM tag:

Now let say gossip.com has below form:









This form requires the user to click on the submit button, but this can be also executed automatically using JavaScript or some jQuery on page. So, still attacker can trick the user. The actual reason is the session cookie goes with the request. Because browser does not know whether this a legitimate user or an attacker, browser checks only the action. So, browser selects all eligible cookies to send along the request. Facebook also does not know whether this is an actual user or not (anyway it is actual user's browser) and Facebook will proceed that action. So, still we cannot solve this problem actually in this way.

So, to prevent from this CSRF attack security problem there are two major security patterns that we can implement. 
        
       1.   Synchronizer Token Pattern
       2.   Double Submit Cookie Pattern

 I will be discussing these security patterns in my next blog posts.