Cross Site Request Forgery (CSRF) (2024)

Author: KirstenS
Contributor(s): Dave Wichers, Davisnw, Paul Petefish, Adar Weidman, Michael Brooks, Ahsan Mir, Dc, D0ubl3 h3lix, Jim Manico, Robert Gilbert, Tgondrom, Pawel Krawczyk, Brandt, A V Minhaz, Kevin Lorenzo, Andrew Smith, Christina Schelin, Ari Elias-Bachrach, Sarciszewski, kingthorin, Ben Spatafora, Krishna Madala

Overview

Cross-Site Request Forgery (CSRF) is an attack that forces an end userto execute unwanted actions on a web application in which they’recurrently authenticated. With a little help of social engineering(such as sending a link via email or chat), an attacker may trick theusers of a web application into executing actions of the attacker’schoosing. If the victim is a normal user, a successful CSRF attack canforce the user to perform state changing requests like transferringfunds, changing their email address, and so forth. If the victim is anadministrative account, CSRF can compromise the entire web application.

How to Review Code for CSRF Vulnerabilities

See the OWASP Code ReviewGuide article on how toreview code for CSRFvulnerabilities.

How to Test for CSRF Vulnerabilities

See the OWASP Testing Guide article on how totest for CSRF vulnerabilities.

How to Prevent CSRF Vulnerabilities

See the CSRF Prevention CheatSheet for prevention measures.

Listen to the OWASP Top Ten CSRFPodcast.

Most frameworks have built-in CSRF support such asJoomla,Spring,Struts,Ruby onRails,.NETand others.

Use OWASP CSRF Guard toadd CSRF protection to your Java applications. You can useCSRFProtector Project to protectyour PHP applications or any project deployed using Apache Server.

John Melton also has an excellent blogpostdescribing how to use the native anti-CSRF functionality of the OWASPESAPI.

Description

CSRF is an attack that tricks the victim into submitting a maliciousrequest. It inherits the identity and privileges of the victim toperform an undesired function on the victim’s behalf (though note thatthis is not true of login CSRF, a special form of the attack describedbelow). For most sites, browser requests automatically include anycredentials associated with the site, such as the user’s sessioncookie, IP address, Windows domain credentials, and so forth.Therefore, if the user is currently authenticated to the site, the sitewill have no way to distinguish between the forged request sent by thevictim and a legitimate request sent by the victim.

CSRF attacks target functionality that causes a state change on theserver, such as changing the victim’s email address or password, orpurchasing something. Forcing the victim to retrieve data doesn’tbenefit an attacker because the attacker doesn’t receive the response,the victim does. As such, CSRF attacks target state-changing requests.

An attacker can use CSRF to obtain the victim’s private data via aspecial form of the attack, known as login CSRF. The attacker forcesa non-authenticated user to log in to an account the attacker controls.If the victim does not realize this, they may add personal data—such ascredit card information—to the account. The attacker can then log backinto the account to view this data, along with the victim’s activityhistory on the web application.

It’s sometimes possible to store the CSRF attack on the vulnerable siteitself. Such vulnerabilities are called “stored CSRF flaws”. This can beaccomplished by simply storing an IMG or IFRAME tag in a field thataccepts HTML, or by a more complex cross-site scripting attack. If theattack can store a CSRF attack in the site, the severity of the attackis amplified. In particular, the likelihood is increased because thevictim is more likely to view the page containing the attack than somerandom page on the Internet. The likelihood is also increased becausethe victim is sure to be authenticated to the site already.

Synonyms

CSRF attacks are also known by a number of other names, including XSRF,“Sea Surf”, Session Riding, Cross-Site Reference Forgery, and HostileLinking. Microsoft refers to this type of attack as a One-Click attackin their threat modeling process and many places in their onlinedocumentation.

Prevention measures that do NOT work

A number of flawed ideas for defending against CSRF attacks have beendeveloped over time. Here are a few that we recommend you avoid.

Using a secret cookie

Remember that all cookies, even the secret ones, will be submittedwith every request. All authentication tokens will be submittedregardless of whether or not the end-user was tricked into submittingthe request. Furthermore, session identifiers are simply used by theapplication container to associate the request with a specific sessionobject. The session identifier does not verify that the end-userintended to submit the request.

Only accepting POST requests

Applications can be developed to only accept POST requests for theexecution of business logic. The misconception is that since theattacker cannot construct a malicious link, a CSRF attack cannot beexecuted. Unfortunately, this logic is incorrect. There are numerousmethods in which an attacker can trick a victim into submitting a forgedPOST request, such as a simple form hosted in an attacker’s Website withhidden values. This form can be triggered automatically by JavaScript orcan be triggered by the victim who thinks the form will do somethingelse.

Multi-Step Transactions

Multi-Step transactions are not an adequate prevention of CSRF. As longas an attacker can predict or deduce each step of the completedtransaction, then CSRF is possible.

URL Rewriting

This might be seen as a useful CSRF prevention technique as the attackercannot guess the victim’s session ID. However, the user’s session ID isexposed in the URL. We don’t recommend fixing one security flaw byintroducing another.

HTTPS

HTTPS by itself does nothing to defend against CSRF.

However, HTTPS should be considered a prerequisite for any preventativemeasures to be trustworthy.

Validating the Referrer Header

This doesn’t work in practice because the referrer header can be easily spoofed by an attacker. Additionally, some users or browsers might not send the referrer header due to privacy settings or policies, leading to falsepositives. Moreover, there are situations where the referrer can be null, such as when a user navigates to a site from a bookmark or any other resource without a traditional url. In these scenarios, legitimate requests could be mistaken as potential CSRF attacks, which would result in more potential false positive flags.

Examples

How does the attack work?

There are numerous ways in which an end user can be tricked into loadinginformation from or submitting information to a web application. Inorder to execute an attack, we must first understand how to generate avalid malicious request for our victim to execute. Let us consider thefollowing example: Alice wishes to transfer $100 to Bob using thebank.com web application that is vulnerable to CSRF. Maria, anattacker, wants to trick Alice into sending the money to Maria instead.The attack will comprise the following steps:

  1. Building an exploit URL or script
  2. Tricking Alice into executing the action with Social Engineering

GET scenario

If the application was designed to primarily use GET requests totransfer parameters and execute actions, the money transfer operationmight be reduced to a request like:

GET http://bank.com/transfer.do?acct=BOB&amount=100 HTTP/1.1

Maria now decides to exploit this web application vulnerability usingAlice as the victim. Maria first constructs the following exploit URLwhich will transfer $100,000 from Alice’s account to Maria’s account. Mariatakes the original command URL and replaces the beneficiary name withherself, raising the transfer amount significantly at the same time:

http://bank.com/transfer.do?acct=MARIA&amount=100000

The social engineering aspect of theattack tricks Alice into loading this URL when Alice is logged into thebank application. This is usually done with one of the followingtechniques:

  • sending an unsolicited email with HTML content
  • planting an exploit URL or script on pages that are likely to be visited by the victim while they are also doing online banking

The exploit URL can be disguised as an ordinary link, encouraging thevictim to click it:

<a href="http://bank.com/transfer.do?acct=MARIA&amount=100000">View my Pictures!</a>

Or as a 0x0 fake image:

<img src="http://bank.com/transfer.do?acct=MARIA&amount=100000" width="0" height="0" border="0">

If this image tag were included in the email, Alice wouldn’t seeanything. However, the browser will still submit the request tobank.com without any visual indication that the transfer has takenplace.

A real life example of CSRF attack on an application using GET was auTorrentexploitfrom 2008 that was used on a mass scale to download malware.

POST scenario

The only difference between GET and POST attacks is how the attack isbeing executed by the victim. Let’s assume the bank now uses POST andthe vulnerable request looks like this:

POST http://bank.com/transfer.do HTTP/1.1acct=BOB&amount=100

Such a request cannot be delivered using standard A or IMG tags, but canbe delivered using a FORM tags:

<form action="http://bank.com/transfer.do" method="POST"><input type="hidden" name="acct" value="MARIA"/><input type="hidden" name="amount" value="100000"/><input type="submit" value="View my pictures"/></form>

This form will require the user to click on the submit button, but thiscan be also executed automatically using JavaScript:

<body onload="document.forms[0].submit()"><form...

Other HTTP methods

Modern web application APIs frequently use other HTTP methods, such asPUT or DELETE. Let’s assume the vulnerable bank uses PUT that takes aJSON block as an argument:

PUT http://bank.com/transfer.do HTTP/1.1{ "acct":"BOB", "amount":100 }

Such requests can be executed with JavaScript embedded into an exploitpage:

<script>function put() { var x = new XMLHttpRequest(); x.open("PUT","http://bank.com/transfer.do",true); x.setRequestHeader("Content-Type", "application/json"); x.send(JSON.stringify({"acct":"BOB", "amount":100})); }</script><body onload="put()">

Fortunately, this request will not be executed by modern webbrowsers thanks to same-origin policyrestrictions. This restriction is enabled by default unless the targetweb site explicitly opens up cross-origin requests from the attacker’s(or everyone’s) origin by usingCORSwith the following header:

Access-Control-Allow-Origin: *

  • Cross-site Scripting (XSS)
  • Cross Site History Manipulation (XSHM)

Related Controls

  • Add a per-request nonce to the URL and all forms in addition to the standard session. This is also referred to as “form keys”. Many frameworks (e.g., Drupal.org 4.7.4+) either have or are starting to include this type of protection “built-in” to every form so the programmer does not need to code this protection manually.
  • Add a hash (session id, function name, server-side secret) to all forms.
  • For .NET, add a session identifier to ViewState with MAC (described in detail in the DotNet Security Cheat Sheet).
  • Checking the referrer header in the client’s HTTP request can prevent CSRF attacks. Ensuring that the HTTP request has come from the original site means that attacks from other sites will not function. It is very common to see referrer header checks used on embedded network hardware due to memory limitations.
    • XSS can be used to bypass both referrer and token based checks simultaneously. For instance, the Samy worm used an XMLHttpRequest to obtain the CSRF token to forge requests.
  • “Although CSRF is fundamentally a problem with the web application, not the user, users can help protect their accounts at poorly designed sites by logging off the site before visiting another, or clearing their browser’s cookies at the end of each browser session.” –http://en.wikipedia.org/wiki/Cross-site_request_forgery#_note-1

References

“This paper serves as a living document for Cross-Site Request Forgery issues. This document will serve as a repository of information from existing papers, talks, and mailing list postings and will be updated as new information is discovered.”*

  • Testing for CSRF
    • CSRF (aka Session riding) paper from the OWASP Testing Guide project.
  • CSRF Vulnerability: A ‘Sleeping Giant’
    • Overview Paper
  • Client Side Protection against Session Riding
    • Martin Johns and Justus Winter’s interesting paper and presentation for the 4th OWASP AppSec Conference which described potential techniques that browsers could adopt to automatically provide CSRF protection - PDF paper
  • OWASP CSRF Guard
    • J2EE, .NET, and PHP Filters which append a unique request token to each form and link in the HTML response in order to provide universal coverage against CSRF throughout your entire application.
  • OWASP CSRF Protector
    • Anti CSRF method to mitigate CSRF in web applications. Currently implemented as a PHP library & Apache 2.x.x module
  • A Most-Neglected Fact About Cross Site Request Forgery (CSRF)
    • Aung Khant, http://yehg.net, explained the danger and impact of CSRF with imperiling scenarios.
  • Pinata-CSRF-Tool: CSRF POC tool
    • Pinata makes it easy to create Proof of Concept CSRF pages. Assists in Application Vulnerability Assessment.
Cross Site Request Forgery (CSRF) (2024)

FAQs

What is the solution to prevent Cross-Site Request Forgery CSRF )? ›

Signed Double-Submit Cookie (RECOMMENDED)

The most secure implementation of the Double Submit Cookie pattern is the Signed Double-Submit Cookie, which uses a secret key known only to the server. This ensures that an attacker cannot create and inject their own, known, CSRF token into the victim's authenticated session.

Why is Cross-Site Request Forgery CSRF difficult to detect? ›

Therefore, if the user is currently authenticated to the site, the site will have no way to distinguish between the forged request sent by the victim and a legitimate request sent by the victim.

What is an example of Cross-Site Request Forgery CSRF? ›

Cross site request forgery (CSRF) is a vulnerability where an attacker performs actions while impersonating another user. For example, transferring funds to an attacker's account, changing a victim's email address, or they could even just redirect a pizza to an attacker's address!

What's the most effective measure to take against a Cross-Site Request Forgery CSRF )? ›

Common defences against CSRF

When attempting to perform a sensitive action, such as submitting a form, the client must include the correct CSRF token in the request. This makes it very difficult for an attacker to construct a valid request on behalf of the victim.

What is the strongest defense against CSRF attacks? ›

The most robust way to defend against CSRF attacks is to include a CSRF token within relevant requests. The token must meet the following criteria: Unpredictable with high entropy, as for session tokens in general. Tied to the user's session.

How do you solve CSRF problems? ›

6 Ways to Solving the “CSRF Token Mismatch Error”
  1. Clear Cookies from the Browser. ...
  2. Make Sure CSRF Tokens are Generated and Passed Correctly. ...
  3. Check if the Session and CSRF Token Has Expired. ...
  4. Check for JavaScript Errors in the Console. ...
  5. Consider Using Double Submit Cookies as an Additional Check.
Feb 2, 2024

Is CSRF still an issue? ›

The Lax configuration is more user friendly, however still allows the possibility for CSRF attacks, since applications may implement sensitive actions using GET requests or may honour requests that use an unexpected request method (i.e. they were expecting POST but will still process a GET request).

What are the most common results of a Cross-Site Request Forgery? ›

A successful CSRF attack can be devastating for both the business and user. It can result in damaged client relationships, unauthorized fund transfers, changed passwords and data theft—including stolen session cookies.

How common are CSRF attacks? ›

Cross-Site Request Forgery (CSRF) is an ingenious form of web exploit. An attacker tricks a victim's browser into performing an unwanted action on a website where the victim is authenticated. CSRF attacks accounted for almost 5% of all application layer attacks in 2022.

What are the risks of cross-site request forgery? ›

While the potential impact against a regular user is substantial, a successful CSRF attack against an administrative account can compromise an entire server, potentially resulting in complete takeover of a web application, API, or other service.

What threat does a cross-site request forgery present? ›

Cross-Site Request Forgery (CSRF) is an attack that forces authenticated users to submit a request to a Web application against which they are currently authenticated. CSRF attacks exploit the trust a Web application has in an authenticated user.

Can CSRF be spoofed? ›

Spoofing the Anti-CSRF Token: When tokens are generated using weak or no cryptography, an attacker may potentially generate spoofed tokens that impersonates other user in order to bypass CSRF protection.

Why are CSRF attacks difficult to detect? ›

CSRF attacks can be challenging to detect because they exploit the trust between a user's browser and a website. The malicious requests sent by attackers appear legitimate, as they carry the user's session data.

How can Cross-Site Request Forgery CSRF attacks be prevented? ›

This CSRF protection method is called the synchronizer token pattern. It protects the form against Cross-site Request Forgery attacks because an attacker would also need to guess the token to successfully trick a victim into sending a valid request.

What are the benefits of CSRF? ›

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.

What is a prevention mechanism for CSRF attacks? ›

The most popular method to prevent Cross-site Request Forgery is to use a challenge token that is associated with a particular user and that is sent as a hidden value in every state-changing form in the web app.

What protects against CSRF? ›

A CSRF token is a secure random token (e.g., synchronizer token or challenge token) that is used to prevent CSRF attacks. The token needs to be unique per user session and should be of large random value to make it difficult to guess. A CSRF secure application assigns a unique CSRF token for every user session.

Which of these security mechanisms can prevent CSRF attacks? ›

Implementing anti-CSRF tokens is one of the most effective measures to prevent CSRF attacks. Each user session should include a unique token that is embedded in forms or included in API requests. The token must be unpredictable and bound to the user's session.

Which headers can help prevent XSS and CSRF attacks? ›

To prevent XSS in HTTP responses that aren't intended to contain any HTML or JavaScript, you can use the Content-Type and X-Content-Type-Options headers to ensure that browsers interpret the responses in the way you intend.

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Arline Emard IV

Last Updated:

Views: 5569

Rating: 4.1 / 5 (52 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Arline Emard IV

Birthday: 1996-07-10

Address: 8912 Hintz Shore, West Louie, AZ 69363-0747

Phone: +13454700762376

Job: Administration Technician

Hobby: Paintball, Horseback riding, Cycling, Running, Macrame, Playing musical instruments, Soapmaking

Introduction: My name is Arline Emard IV, I am a cheerful, gorgeous, colorful, joyous, excited, super, inquisitive person who loves writing and wants to share my knowledge and understanding with you.