Resource Center  >  Blog

Cross-Site Request Forgery (CSRF): Impact, Examples, and Prevention

Publication:
April 4, 2022
Author:
Nera Besic

Cross-site Request Forgery (CSRF/XSRF), also known as Sea Surf or Session Riding is a web security vulnerability that tricks a web browser into executing an unwanted action. Accordingly, the attacker abuses the trust that a web application has for the victim’s browser. It allows an attacker to partly bypass the same-origin policy, which is meant to prevent different websites from interfering with each other.

This is part of an extensive series of guides about application security

What is the Impact of CSRF Attacks?

When a website sends a data request to another website on behalf of a user along with the user’s session cookie, an attacker can launch a Cross-Site Request Forgery Attack, which abuses a trustful relationship between the victim’s browser and the webserver.

In some cases, depending on the type of action, the attacker can gain full control of the user’s account. If the compromised user has a privileged role within the application, the attacker might be able to take full control of all the application’s functionality and data, which is devastating to both the business and the user. The result can be data theft, unauthorized fund transfers, damaged client relationships, changed passwords and many more.

How Does Cross-site Request Forgery Work?

how does cross-site request forgery csrf work

When a user tries to access a site, the browser often automatically includes the credentials in the request, to make the login process more convenient. These credentials may include the user’s session cookie, basic authentication credentials, IP address, and Windows domain credentials. 

The risk inherent in this mechanism is that attackers can easily impersonate the user. Once a user passes the site’s identity verification, the site cannot differentiate between a forged request and a legitimate user request.

In a CSRF attack, an attacker assumes the victim’s identity, and uses it to perform actions on behalf of the user, without their consent. Attackers typically follow this process:

  1. They use social engineering techniques to persuade the victim to click a link via email, chat message, or similar form of communication. 
  2. Either the malicious link itself, or a web page the user visits, triggers a request to the targeted site
  3. The request supposedly comes from the user, and takes advantage of the fact that the user is already signed into the website. 
  4. The website acknowledges the request and performs the attacker’s requested action, without the user’s knowledge or consent.

CSRF attacks typically attempt to change server state, but can also be used to gain access to sensitive data. If an attacker successfully performs a CSRF attack against the victim’s account, they can transfer funds, purchase a product, modify account information such as the shipping address, modify the password, or any other action available when the user is signed in.

CSRF Attack Example

The following example shows how a typical GET request for a $5,000 bank transfer might look like:

GET https://abank.com/transfer.do?account=RandPerson&amount=$5000 HTTP/1.1

An attacker can modify the script so it will result in a $5,000 transfer to their personal account The malicious request might look like:

GET https://abank.com/transfer.do?account=SomeAttacker&amount=$5000 HTTP/1.1

Afterwards, the attacker is able to embed the request into a harmless-looking hyperlink:

<a href="https://abank.com/transfer.do?account=SomeAttacker&amount=$5000">Click for more information</a>

The next step is to distribute the hyperlink via email to a massive number of bank clients. Those who are logged into their bank account and click on this link will unintentionally initiate the $5,000 transfer.

If the bank’s website is only using POST requests, it’s not possible to frame malicious requests using a <a> href tag. However, the attack can be delivered in a <form> tag.

This is how such a form may look, and it can even be a self submitting form:

<body onload="document.forms[0].submit()>
<form id=”csrf” action="https://abank.com/transfer.do" method="POST">
<input type="hidden" name="account" value="SomeAttacker"/>
<input type="hidden" name="amount" value="$5000"/>
</form>
</body>

Because the form above does not have a submit button, it will be triggered without a user’s knowledge and consent. Instead, the button is replaced by only one line of javascript:

document.getElementById('csrf').submit();

What are CSRF Tokens?

A CSRF token is a unique, unpredictable secret value generated by a server-side application, and sent to the client for inclusion in subsequent HTTP requests issued by the client. After the token is issued, when the client makes a request, the server checks to see if the request contains the expected token, and rejects it if the token is missing or invalid.

CSRF tokens can prevent CSRF attacks, because they prevent attackers from forming fully valid HTTP requests, which they can feed to a victim. The attacker cannot determine or predict the value of the user’s CSRF token, so any request they generate should not be accepted by the application.

Common CSRF Vulnerabilities: Weaknesses in CSRF Token Implementations

Some of the most common CSRF vulnerabilities are caused by errors in the CSRF token verification process. Make sure your CSRF process does not have any of these weaknesses.

Validation depends on presence of token

In some applications, the verification process is skipped if the token does not exist. This means that the attacker only needs to find code containing token information, and remove it, and token validation is not performed by the application.

CSRF token is not associated with user session

Some applications maintain a pool of tokens, and as long as a token from the pool is used, it is accepted. However, the application does not tie specific tokens to specific users. An attacker only needs to obtain at least one token from the pool, and can use it to impersonate any user.

Token validation changes with HTTP method

In some applications, using the GET method instead of the POST method will cause CSRF validation not to work properly. The attacker simply needs to switch from POST to GET, and easily bypass the verification process.

CSRF token is copied to the cookie

Some applications do not keep a record of tokens that are already in use. Instead, they copy the request parameters associated with each token into the user’s cookie. In this setup, the attacker can create a cookie that contains a token using the application’s expected format, place it in the user’s browser, and then execute a CSRF attack. The request sent by the user’s browser will be validated, because it will match the malicious cookie provided by the attacker.

CSRF Prevention: Beyond CSRF Tokens

The basic way to prevent CSRF is to implement CSRF tokens, while avoiding the weaknesses we described in the previous section. Here are additional ways you can prevent CSRF attacks.

Use Advanced Validation Techniques to Reduce CSRF

An attacker can initiate a CSRF attack when all the parameters used in the form are identified. Hence, in order to prevent a CSRF attack, you can add an additional parameter with an additional value that the attacker is unaware of, but the server requires validation.  

The most widely used prevention technique for CSRF attacks is known as an anti-CSRF token, or synchronizer token. When a user makes some authenticated request by submitting a form, a random token should be included in that request. Then the website will verify the occurrence of this token before processing the sent request and if the token is missing or the value is incorrect, the request will be rejected and the attacker won’t be able to launch a CSRF attack.

The SameSite cookie attribute, which is defined in RFC 6265 bis, attempts to mitigate CSRF attacks. The attribute tells the browser when it is okay to send cookies with cross-site requests. The SameSite cookie attribute comes with three possible values – Strict, Lax, or None
The majority of mobile browsers and all desktop browsers support this attribute.

The Strict value can tell the browser not to send a cookie to the site during a cross-site browsing session. This includes a session that follows a regular link. For example, when a user logs in to GitHub and browses a private GitHub project hosted by a corporation, the browser does not send a session cookie to GitHub, restricting access to the project. 

If there is no need to allow external sites to link to transactional pages, you can use the Strict flag. However, if you need to create a balance between usability and security, enabling users directed by external links to maintain logged-in sessions – you should use the default Lax value. Generally, cross-site requests granted during Lax mode are considered safe HTTP methods.   

Here are two example of cookies using the SameSite cookie attribute:

Set-Cookie: JSESSIONID=xxxxx; SameSite=Strict
Set-Cookie: JSESSIONID=xxxxx; SameSite=Lax

User Interaction Based CSRF Defense

Generally, defense mechanisms that require user intervention can negatively impact the user experience. However, in some cases, such as financial transactions, it is appropriate and required to implement this type of technique. For example, you can add a CAPTCHA, which helps validate that it is indeed a human user rather than a robot.

A one-time token can also ensure that it is the user and not an attacker using a logged-in session. The token is usually sent to the email address or phone number of the user, validating with the information previously provided by the user. Additionally, you can introduce re-authentication, which can help differentiate between a CSRF session and a real user.

Login CSRF

Many developers ignore CSRF vulnerabilities in an application’s login form. This is because the user is not yet authenticated at this stage, so developers assume that there is no risk of CSRF. However, this assumption is not always correct. Attackers can perform login CSRF attacks, which can have varying impacts depending on the application.

Login CSRF attacks can be mitigated by creating a pre-session (starting a session before user authentication) and requesting the token in the login form. 

It is difficult to mitigate login CSRF if you cannot trust subdomains (for example, if you allow your users to define their own subdomains). In these cases, you can use strict subdomain and path-level referrer header verification to reduce CSRF risk on login forms.

Conduct Regular Web Application Security Tests to Identify CSRF

Even if vulnerabilities in web applications with CSRF attacks are successfully addressed, application updates and code changes may expose your application to CSRF in the future. Web application security testing helps you continuously scan and test for potential security weaknesses in web applications, including CSRF vulnerabilities.

Bright helps automate the detection and remediation of many vulnerabilities including CSRF, early in the development process, across web applications and APIs. 

By shifting DAST scans left, and integrating them into the SDLC, developers and application security professionals can detect vulnerabilities early, and remediate them before they appear in production. Bright completes scans in minutes and achieves zero false positives, by automatically validating every vulnerability. This allows developers to adopt the solution and use it throughout the development lifecycle. 

Scan any web app, or REST, SOAP and GraphQL APIs to prevent CSRF vulnerabilities: try Bright free

See Additional Guides on Key Application Security Topics

Together with our content partners, we have authored in-depth guides on several other topics that can also be useful as you explore the world of application security.

Vulnerability Management-NN

Authored by Bright Security

API Security

Authored by Bright Security

SSRF

Authored by Bright Security

Related Articles:

Related topics

The practice of running DAST in production environments presents multiple risks and challenges that can actually hinder your security goals. Here’s why you should think twice before running DAST scans on a live production system.

See more

What Are Vulnerability Assessment Tools?  Vulnerability assessment tools are specialized software designed to identify, classify, and prioritize vulnerabilities in computer

See more

Secure coding refers to the practice of writing software code in a manner that minimizes vulnerabilities and guards against potential

See more

Stop CSRF Attacks with Dynamic Testing

  • Test all application URLs for CSRF flaws
  • Get actionable remediation guidance
  • Zero false positives
See Our Dynamic Application Security Testing (DAST) in Action
and eliminate CSRF

Stop CSRF Attacks with Dynamic Testing

Discover CSRF flaws and thousands of other vulnerabilities – and fix them fast.

  • Scan web and mobile applications
  • Scan all API formats
  • Zero false positives
  • Scan every build
  • Scan from CLI
  • Developer friendly
See Next-Gen Dynamic Application Security Testing (DAST) in Action
and eliminate CSRF

Protect your apps against CSRF attacks. Run a security scan with every build

  • Easily and quickly find & fix security bugs

  • Automate it in your build pipeline

  • No false positives

  • Scan any target: web apps & APIs