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)

References

Top Articles
Latest Posts
Article information

Author: The Hon. Margery Christiansen

Last Updated:

Views: 6035

Rating: 5 / 5 (50 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: The Hon. Margery Christiansen

Birthday: 2000-07-07

Address: 5050 Breitenberg Knoll, New Robert, MI 45409

Phone: +2556892639372

Job: Investor Mining Engineer

Hobby: Sketching, Cosplaying, Glassblowing, Genealogy, Crocheting, Archery, Skateboarding

Introduction: My name is The Hon. Margery Christiansen, I am a bright, adorable, precious, inexpensive, gorgeous, comfortable, happy person who loves writing and wants to share my knowledge and understanding with you.