Cross-site Request Forgery(CSRF) protection via Synchronizer Token Patterns and Double Submit Cookies Patterns

What is Cross-site Request Forgery(CSRF)

Cross-Site Request Forgery (CSRF) is a type of attack outlined in the OWASP Top 10 that occurs when a malicious website, email, blog, instant message, or program causes a user’s web browser to perform an unwanted action on a trusted site for which the user is currently authenticated (logged in). The impact of a successful CSRF attack is limited to the capabilities exposed by the vulnerable application. For example, this attack could result in a transfer of funds, changing a password, or purchasing an item in the user's context. In effect, CSRF attacks are used by an attacker to make a target system perform a function via the target's browser without knowledge of the target user, at least until the unauthorized transaction has been committed.

At the most basic level, the reason for a CSRF is that browser's do not understand how to distinguish if an action was performed on purposely by a user (like say by clicking a button on a form, or clicking a hyperlink etc.) or if the user unknowingly performed the action (like say user visited a page from some domain, say bad.com, and bad.com sent a request to good.com/some_action while the user was already logged into good.com).

Practical Scenario

Let’s look at how the attack described above would work in a bit more detail. First, let’s assume that I’m logged into my account on examplebank.com, which allows for standard online banking features, including transferring funds to another account. Normally when the user is logged into the website, a session will be created.


Now let’s say I happen to visit somemalicioussite.com. It just so happens that this site is trying to attack people who bank with examplebank.com and has set up a CSRF attack on its site. So when the user is logged in, the attacker will send some auto-submitting forms to the target site. The attack will transfer $1,500.00 to account number 123456789. Somewhere on somemalicioussite.com, attackers have added this line of code:


<iframe src="//www.abc.com/%3Ca%20href%3D"http://examplebank.com/app/transferFunds?amount=1500&destinationAccount=123456789">

Upon loading that iframe, my browser will send that request to examplebank.com, which my browser has already logged in as me. The request will be processed and send $1,500.00 to account 123456789.

So now he can put this iframe in any of his websites and on loading the page which contains this iframe will make us to auto submit the form to the banking application and the action will be successful if the user is logged into the banking application.


How it effects

Impacts of successful CSRF exploits vary greatly based on the privileges of each victim. When targeting a normal user, a successful CSRF attack can compromise end-user data and their associated functions. If the targeted end user is an administrator account, a CSRF attack can compromise the entire web application. Sites that are more likely to be attacked by CSRF are community websites (social networking, email) or sites that have high dollar value accounts associated with them (banks, stock brokerages, bill pay services). Utilizing social engineering, an attacker can embed malicious HTML or JavaScript code into an email or website to request a specific 'task URL'. The task then executes with or without the user's knowledge.

Cross-site Request Forgery(CSRF) protection Methods

How users can protect themselves from CSRF Attack

1. Logging Out whenever not needed:


CSRF requires the user to be logged in to perform the attack. So by logging out from the website whenever it’s not required will secure you from the CSRF attack.

2.  Changing Default Passwords: 

Most Attackers will perform the CSRF attack using the default password provided by the websites. The default passwords will remain the same for all the users until the user changes it.

3. Using different Browsers:

Most CSRF targets require the victim to have an active session on the website in order for the attack to work. One way users can protect themselves from CSRF attacks is to use one browser for browsing sensitive, trusted sites and another for general browsing. For instance, a corporate user might use Microsoft Internet Explorer to browse his/her corporate intranet, and Firefox to browse the Internet.

Using Token Based Authentication:

Instead of using the sessions for authorization the web developer can use the token-based authentication where the tokens will be verified on each and every request.

Synchronizer (CSRF) Tokens

There are a number of CSRF prevention techniques in popular usage. One of the most common methods is to implement CSRF tokens with the Synchronizer Token Pattern by appending unpredictable tokens to each request to ensure the validity of the source. The server application must then verify that each sensitive HTTP request contains the correct token. With this defense enabled, a successful attack would require the malicious actor to guess the randomly generated token – a near impossible task.
Any state changing operation requires a secure random token (e.g., CSRF token) to prevent CSRF attacks.
Characteristics of a CSRF Token
  • Unique per user session
  • Large random value
  • Generated by a cryptographically secure random number generator
The CSRF token is added as a hidden field for forms or within the URL if the state changing operation occurs via a POST, The server rejects the requested action if the CSRF token fails validation.
This article explains how to protect from Cross-site Request Forgery (CSRF) using Synchronizer Token Patterns. You can find the code from here. Steps of the process are described in GitHub page.



The synchronizer token pattern requires the generating of random tokens that are associated with the user's current session. These tokens are then inserted within the HTML forms and links associated with sensitive server-side operations. When the user wishes to invoke these sensitive operations, the HTTP request should include this csrf token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a csrf token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. The inclusion of a required security token in HTTP requests associated with sensitive business functions helps mitigate CSRF attacks as successful exploitation assumes the attacker knows the randomly generated token for the target victim's session. This is analogous to the attacker being able to guess the target victim's session identifier. The following synopsis describes a general approach to incorporate csrf tokens within the request.

Normally when the user is logged into the website, a session will be created. When session creation a Web application formulates a request (by generating a link or form that causes a request when submitted or clicked by the user), the application should include a hidden input parameter with a common name such as "token". 



As shown in Fig.1, Ajax is used to call the csrf.php file  ( Fig.2) to get the generated CSRF token value and put it inside the hidden textfield in the HTML form ( Fig.3).
Since Cross-domain Ajax calls are not allowed. This prevents from attacker to server making Ajax calls. (Malicious page is running in attacker's website, it can only make ajax calls within attacker's domain. not the server.)
Fig 1. Ajax Call


Fig 2. csrf.php to get generated CSRF Token




 Fig.3 Hidden textfield in the HTML form

The value of the token must be randomly generated such that it cannot be guessed by an attacker. To generate a sufficiently long random token, 256-bit BASE64 encoded algorithm is used. Developers that choose this generation algorithm must make sure that there are randomness and uniqueness utilized in the data that is hashed to generate the random token.




The text file called Tokens.txt 


Generates the csrf token. Also, it sets a browser cookie with the value of session_id. After that CSRF token value will be stored in a text file called Tokens.txt along with its session_id.

In general, developers need only generate this token once for the current session. After the initial generation of this token, the value is stored in the session token store (here we save it in a text file) and is utilized for each subsequent request until the session expires. When a request is issued by the end-user, the server-side component must verify the existence and validity of the token in the request as compared to the token found in the session.


The checkToken function which gets two parameters (CSRF token and session id) and returns true if the given parameters match with the values that are stored inside the text file.

 If the token was not found within the request or the value provided does not match the value within the session,
then the request should be aborted, the token should be reset and the event logged as a potential CSRF attack in progress. Otherwise, If the returned value of the checkToken function is true, the user can view his/her updated post.


 Summary

After user logs in the token is generated in server side against sessionID & client can request the token & send it with all state changing operations in HTTP body of the message. Then the server will validate the token and then only server complete the action.



Double Submit Cookie

This article explains how to protect from Cross-site Request Forgery (CSRF) using Double Submit Cookies Patterns. You can find the code from here. Steps of the process are described in GitHub page.

If storing the CSRF token in session is problematic, an alternative defense is the use of a double submit cookie. A Double Submit cookie is defined as sending a random value in both a cookie and as a request parameter, with the server verifying if the cookie value and request value match. In double-submitted cookie pattern, two cookies (for the session and for the CSRF token) are stored in the browser. 
Create Session and Csrf Cookie

This pattern is also called as Stateless CSRF Defense since the server site does not have to save this value in any way, thus avoiding the server-side state.

When a user authenticates to a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine separate from the session id. The site does not have to save this value in any way, thus avoiding the server-side state. The site then requires that every transaction request include this random value as a hidden form value (or other request parameters).
When the user submits a secure form, this token is extracted from the cookie and is set as a hidden input field in the HTML. This cookie cannot be set as HttpOnly as the clientside script, requires to access this because in this scenario, the token endpoint does not exist and the server has no record of the generated token for this session. The server will validate the token sent as a form parameter against the cookie value and authorize the action to be completed.
(Attackers cannot get csrf cookie within his domain. So csrf token which is in the body cannot be sent to the server with the request. Then Csrf prevention is achieved)


A cross-origin 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 force a victim to send any value he wants with a malicious CSRF request, the attacker will be unable to modify or read the value stored in the cookie. Since the cookie value and the request parameter or form value must be the same, the attacker will be unable to successfully force the submission of a request with the random CSRF value.


When the UI and the function service reside in different hosts, the Double Submit Cookie guard turns difficult to implement because the UI body and the Set-Cookie response header will be generated as part of different requests to different processes. The Set-Cookie response header would need to be induced by a request from the client javascript. In that case, making sure that both the UI and the service request came from a client serviced by the same UI origin appears as difficult as the original issue.

Summary

After user logs in to the website, the token value is set in the user's browser as a cookie apart from the session cookie. These cookie values should be sent in HTTP header along with all state-changing operations. (Server should receive both cookie and the header for validation.) 


Note: If this pattern is implemented, we have to make sure the application is fully XSS-resistant if the application is in a subdomain &  cookie cannot be set as HttpOnly

Comments

Popular posts from this blog

What is Emma ?

DAA SIMULATOR