Difference between revisions of "Cross-Site Request Forgery (CSRF)"

From OWASP
Jump to: navigation, search
m (formatting)
(Undo revision 237090 by Hblankenship (talk) breaks page rendering on mobile)
 
(20 intermediate revisions by 11 users not shown)
Line 2: Line 2:
  
 
[[Category:OWASP ASDR Project]]
 
[[Category:OWASP ASDR Project]]
<br>
 
  
 
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}'''
 
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}'''
  
 
==Overview==
 
==Overview==
CSRF is an attack which forces an end user to execute unwanted actions on a web application in which he/she is currently authenticated. With a little help of social engineering (like sending a link via email/chat), an attacker may trick the users of a web application into executing actions of the attacker's choosing. A successful CSRF exploit can compromise end user data and operation in case of normal user. If the targeted end user is the administrator account, this can compromise the entire web application.
+
 
 +
Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request. With a little help of social engineering (such as sending a link via email or chat), an attacker may trick the users of a web application into executing actions of the attacker's choosing. If the victim is a normal user, a successful CSRF attack can force the user to perform state changing requests like transferring funds, changing their email address, and so forth. If the victim is an administrative account, CSRF can compromise the entire web application.
  
 
==Related Security Activities==
 
==Related Security Activities==
Line 13: Line 13:
 
===How to Review Code for CSRF Vulnerabilities===
 
===How to Review Code for CSRF Vulnerabilities===
  
See the [[:Category:OWASP Code Review Project|OWASP Code Review Guide]] article on how to [[Reviewing code for Cross-Site Request Forgery issues |Reviewing code for CSRF]] Vulnerabilities.
+
See the [[:Category:OWASP Code Review Project|OWASP Code Review Guide]] article on how to [[Reviewing code for Cross-Site Request Forgery issues|review code for CSRF vulnerabilities]].
  
 
===How to Test for CSRF Vulnerabilities===
 
===How to Test for CSRF Vulnerabilities===
  
See the [[:Category:OWASP Testing Project|OWASP Testing Guide]] article on how to [[Testing for CSRF  (OWASP-SM-005) |Test for CSRF]] Vulnerabilities.
+
See the [[:Category:OWASP Testing Project|OWASP Testing Guide]] article on how to [[Testing_for_CSRF_(OTG-SESS-005)|test for CSRF vulnerabilities]].
  
 
===How to Prevent CSRF Vulnerabilities===
 
===How to Prevent CSRF Vulnerabilities===
  
See the [http://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet OWASP CSRF Prevention Cheat Sheet] for prevention measures.
+
See the [[CSRF Prevention Cheat Sheet]] for prevention measures.
  
 
Listen to the [http://www.owasp.org/download/jmanico/owasp_podcast_69.mp3 OWASP Top Ten CSRF Podcast].
 
Listen to the [http://www.owasp.org/download/jmanico/owasp_podcast_69.mp3 OWASP Top Ten CSRF Podcast].
 +
 +
Most frameworks have built-in CSRF support such as [http://docs.joomla.org/How_to_add_CSRF_anti-spoofing_to_forms Joomla], [http://blog.eyallupu.com/2012/04/csrf-defense-in-spring-mvc-31.html Spring], [http://web.securityinnovation.com/appsec-weekly/blog/bid/84318/Cross-Site-Request-Forgery-CSRF-Prevention-Using-Struts-2 Struts], [http://guides.rubyonrails.org/security.html#cross-site-request-forgery-csrf Ruby on Rails], [http://www.troyhunt.com/2010/11/owasp-top-10-for-net-developers-part-5.html .NET] and others.
 +
 +
Use [[:Category:OWASP_CSRFGuard_Project|OWASP CSRF Guard]] to add CSRF protection to your Java applications. You can use [[CSRFProtector Project]] to protect your php applications or any project deployed using Apache Server. There is a [[.Net CSRF Guard]] at OWASP as well, but it's old and doesn't look complete.
  
 
John Melton also has an [http://www.jtmelton.com/2010/05/16/the-owasp-top-ten-and-esapi-part-6-cross-site-request-forgery-csrf/ excellent blog post] describing how to use the native anti-CSRF functionality of the [http://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API OWASP ESAPI].
 
John Melton also has an [http://www.jtmelton.com/2010/05/16/the-owasp-top-ten-and-esapi-part-6-cross-site-request-forgery-csrf/ excellent blog post] describing how to use the native anti-CSRF functionality of the [http://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API OWASP ESAPI].
  
 
==Description==
 
==Description==
Cross-Site Request Forgery (CSRF) is an attack that tricks the victim into loading a page that contains a malicious request. It is malicious in the sense that it inherits the identity and privileges of the victim to perform an undesired function on the victim's behalf, like change the victim's e-mail address, home address, or password, or purchase something. CSRF attacks generally target functions that cause a state change on the server but can also be used to access sensitive data.
 
  
For most sites, browsers will automatically include with such requests any credentials associated with the site, such as the user's session cookie, basic auth credentials, IP address, Windows domain credentials, etc. Therefore, if the user is currently authenticated to the site, the site will have no way to distinguish this from a legitimate user request.
+
CSRF is an attack that tricks the victim into submitting a malicious request. It inherits the identity and privileges of the victim to perform an undesired function on the victim's behalf. For most sites, browser requests automatically include any credentials associated with the site, such as the user's session cookie, IP address, Windows domain credentials, and so forth. 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.
 +
 
 +
CSRF attacks target functionality that causes a state change on the server, such as changing the victim's email address or password, or purchasing something. Forcing the victim to retrieve data doesn't benefit an attacker because the attacker doesn't receive the response, the victim does. As such, CSRF attacks target state-changing requests.
 +
 
 +
It's sometimes possible to store the CSRF attack on the vulnerable site itself. Such vulnerabilities are called "stored CSRF flaws". This can be accomplished by simply storing an IMG or IFRAME tag in a field that accepts HTML, or by a more complex cross-site scripting attack. If the attack can store a CSRF attack in the site, the severity of the attack is amplified. In particular, the likelihood is increased because the victim is more likely to view the page containing the attack than some random page on the Internet.  The likelihood is also increased because the 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 Hostile Linking. Microsoft refers to this type of attack as a One-Click attack in their threat modeling process and many places in their online documentation.
 +
 
 +
=== Prevention measures that do '''NOT''' work ===
 +
 
 +
== Using a secret cookie ==
 +
Remember that all cookies, even the ''secret'' ones, will be submitted with every request. All authentication tokens will be submitted regardless of whether or not the end-user was tricked into submitting the request. Furthermore, session identifiers are simply used by the application container to associate the request with a specific session object. The session identifier does not verify that the end-user intended to submit the request.
 +
 
 +
== Only accepting POST requests ==
 +
Applications can be developed to only accept POST requests for the execution of business logic. The misconception is that since the attacker cannot construct a malicious link, a CSRF attack cannot be executed. Unfortunately, this logic is incorrect. There are numerous methods in which an attacker can trick a victim into submitting a forged POST request, such as a simple form hosted in an attacker's Website with hidden values. This form can be triggered automatically by JavaScript or can be triggered by the victim who thinks the form will do something else.
 +
 
 +
A number of flawed ideas for defending against CSRF attacks have been developed over time. Here are a few that we recommend you avoid.
 +
 
 +
== Multi-Step Transactions ==
 +
 
 +
Multi-Step transactions are not an adequate prevention of CSRF. As long as an attacker can predict or deduce each step of the completed transaction, then CSRF is possible.
  
In this way, the attacker can make the victim perform actions that they didn't intend to, such as logout, purchase item, change account information, retrieve account information, or any other function provided by the vulnerable website.
+
== URL Rewriting ==
  
Sometimes, it is possible to store the CSRF attack on the vulnerable site itself. Such vulnerabilities are called Stored CSRF flaws. This can be accomplished by simply storing an IMG or IFRAME tag in a field that accepts HTML, or by a more complex cross-site scripting attack. If the attack can store a CSRF attack in the site, the severity of the attack is amplified. In particular, the likelihood is increased because the victim is more likely to view the page containing the attack than some random page on the Internet. The likelihood is also increased because the victim is sure to be authenticated to the site already.
+
This might be seen as a useful CSRF prevention technique as the attacker cannot guess the victim's session ID. However, the user’s session ID is exposed in the URL. We don't recommend fixing one security flaw by introducing another.
  
Synonyms: CSRF attacks are also known by a number of other names, including XSRF, "Sea Surf", Session Riding, Cross-Site Reference Forgery, Hostile Linking. Microsoft refers to this type of attack as a One-Click attack in their threat modeling process and many places in their online documentation.
+
== HTTPS ==
  
===Prevention measures that do '''NOT''' work===
+
HTTPS by itself does nothing to defend against CSRF.
;Using a secret cookie
 
:Remember that all cookies, even the ''secret'' ones, will be submitted with every request. All authentication tokens will be submitted regardless of whether or not the end-user was tricked into submitting the request. Furthermore, session identifiers are simply used by the application container to associate the request with a specific session object. The session identifier does not verify that the end-user intended to submit the request.
 
  
;Only accepting POST requests
+
However, HTTPS should be considered a prerequisite for any preventative measures to be trustworthy.
:Applications can be developed to only accept POST requests for the execution of business logic. The misconception is that since the attacker cannot construct a malicious link, a CSRF attack cannot be executed. Unfortunately, this logic is incorrect. There are numerous methods in which an attacker can trick a victim into submitting a forged POST request, such as a simple form hosted in attacker's website with hidden values. This form can be triggered automatically by JavaScript or can be triggered by the victim who thinks form will do something else.
 
  
<!--==Risk Factors==
 
TBD
 
-->
 
 
==Examples==
 
==Examples==
  
 
===How does the attack work?===
 
===How does the attack work?===
There are numerous ways in which an end-user can be tricked into loading information from or submitting information to a web application. In order to execute an attack, we must first understand how to generate a malicious request for our victim to execute. Let us consider the following example: Alice wishes to transfer $100 to Bob using ''bank.com'' web application that is vulnerable to CSRF. Maria, an attacker, wants to trick Alice to send the money to her instead. The attack will comprise of the following steps:
 
  
* building an exploit URL or script,
+
There are numerous ways in which an end user can be tricked into loading information from or submitting information to a web application. In order to execute an attack, we must first understand how to generate a valid malicious request for our victim to execute. Let us consider the following example: Alice wishes to transfer $100 to Bob using the ''bank.com'' web application that is vulnerable to CSRF. Maria, an attacker, wants to trick Alice into sending the money to her instead. The attack will comprise the following steps:
* tricking Alice into executing it with [[Social Engineering]]
+
 
 +
# building an exploit URL or script
 +
# tricking Alice into executing the action with [[Social Engineering|social engineering]]
  
 
====GET scenario====
 
====GET scenario====
If the application was designed to primarily use GET requrests to transfer parameters and execute actions, the money transfer operation might be reduced to such request:
+
 
 +
If the application was designed to primarily use GET requests to transfer parameters and execute actions, the money transfer operation might be reduced to a request like:
  
 
  GET <nowiki>http://bank.com/transfer.do?acct=BOB&amount=100</nowiki> HTTP/1.1
 
  GET <nowiki>http://bank.com/transfer.do?acct=BOB&amount=100</nowiki> HTTP/1.1
Line 65: Line 86:
 
  <nowiki>http://bank.com/transfer.do?acct=MARIA&amount=100000</nowiki>
 
  <nowiki>http://bank.com/transfer.do?acct=MARIA&amount=100000</nowiki>
  
The [[Social Engineering]] part of the attack will be now to trick Alice to load this URL when she's logged into the bank. This is usually done with one of the following techniques:
+
The [[Social Engineering|social engineering]] aspect of the attack tricks Alice into loading this URL when she's logged into the bank application. This is usually done with one of the following techniques:
  
 
* sending an unsolicited email with HTML content
 
* sending an unsolicited email with HTML content
* planting exploit URL or script on pages that are likely to be visited by the victim.
+
* 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 either as ordinary link, encouraging the victim to click it:
+
The exploit URL can be disguised as an ordinary link, encouraging the victim to click it:
  
 
  <nowiki><a href="http://bank.com/transfer.do?acct=MARIA&amount=100000">View my Pictures!</a></nowiki>
 
  <nowiki><a href="http://bank.com/transfer.do?acct=MARIA&amount=100000">View my Pictures!</a></nowiki>
  
Or by a 1x1 fake image:
+
Or as a 0x0 fake image:
  
  <nowiki><img src="http://bank.com/transfer.do?acct=MARIA&amount=100000" width="1" height="1" border="0"></nowiki>
+
  <nowiki><img src="http://bank.com/transfer.do?acct=MARIA&amount=100000" width="0" height="0" border="0"></nowiki>
  
If this image tag were included in the email, Alice would only see a little box indicating that the browser could not render the image. However, the browser ''will still'' submit the request to bank.com without any visual indication that the transfer has taken place.
+
If this image tag were included in the email, Alice wouldn't see anything. However, the browser ''will still'' submit the request to bank.com without any visual indication that the transfer has taken place.
  
A real life example of CSRF attack on application using GET was [http://jeremiahgrossman.blogspot.co.uk/2008/04/utorrent-csrf-stallown3d1.html uTorrent exploit] from 2008 that was used on mass scale to download malware.
+
A real life example of CSRF attack on an application using GET was a [https://www.ghacks.net/2008/01/17/dos-vulnerability-in-utorrent-and-bittorrent/ uTorrent exploit] from 2008 that was used on a mass scale to download malware.
  
 
====POST scenario====
 
====POST scenario====
The only difference when POST requests are being is how the attack is being executed by the victim. Let's assume the bank now uses POST and the vulnerable request looks like this:
+
 
 +
The only difference between GET and POST attacks is how the attack is being executed by the victim. Let's assume the bank now uses POST and the vulnerable request looks like this:
  
 
  POST <nowiki>http://bank.com/transfer.do</nowiki> HTTP/1.1
 
  POST <nowiki>http://bank.com/transfer.do</nowiki> HTTP/1.1
Line 89: Line 111:
 
  acct=BOB&amount=100
 
  acct=BOB&amount=100
  
Such request cannot be delivered using standard A or IMG tags, but can be delivered using FORM tag:
+
Such a request cannot be delivered using standard A or IMG tags, but can be delivered using a FORM tag:
  
  <form action="<nowiki>http://bank.com/transfer.do</nowiki>" method="POST">
+
  <form action="&lt;nowiki&gt;http://bank.com/transfer.do&lt;/nowiki&gt;" method="POST">
 
  <input type="hidden" name="acct" value="MARIA"/>
 
  <input type="hidden" name="acct" value="MARIA"/>
  <input type="hidden" name=amount" value="100000"/>
+
  <input type="hidden" name="amount" value="100000"/>
 
  <input type="submit" value="View my pictures"/>
 
  <input type="submit" value="View my pictures"/>
 
  </form>
 
  </form>
  
This form will require user clicking the submit button, but this can be also executed automatically using JavaScript:
+
This form will require the user to click on the submit button, but this can be also executed automatically using JavaScript:
  
 
  <body onload="document.forms[0].submit()">
 
  <body onload="document.forms[0].submit()">
Line 103: Line 125:
 
   
 
   
 
====Other HTTP methods====
 
====Other HTTP methods====
Modern web application APIs are frequently using other HTTP methods such as PUT or DELETE. Let's assume the vulnerable bank uses PUT method that takes JSON block as an argument:
 
  
  PUT http://bank.com/transfer.do HTTP/1.1
+
Modern web application APIs frequently use other HTTP methods, such as PUT or DELETE. Let's assume the vulnerable bank uses PUT that takes a JSON block as an argument:
 +
 
 +
  PUT <nowiki>http://bank.com/transfer.do</nowiki> HTTP/1.1
 
   
 
   
  {"acct":"BOB", "amount":100}
+
  { "acct":"BOB", "amount":100 }
  
 
Such requests can be executed with JavaScript embedded into an exploit page:
 
Such requests can be executed with JavaScript embedded into an exploit page:
Line 114: Line 137:
 
  function put() {
 
  function put() {
 
  var x = new XMLHttpRequest();
 
  var x = new XMLHttpRequest();
  x.open("PUT","http://bank.com/transfer.do",true);
+
  x.open("PUT","<nowiki>http://bank.com/transfer.do</nowiki>",true);
 
  x.setRequestHeader("Content-Type", "application/json");  
 
  x.setRequestHeader("Content-Type", "application/json");  
  x.send(JSON.stringify('{"acct":"BOB", "amount":100}'));  
+
  x.send(JSON.stringify({"acct":"BOB", "amount":100}));  
 
  }
 
  }
 
  </script>
 
  </script>
 
  <body onload="put()">
 
  <body onload="put()">
  
Fortunately, this request will be '''not''' executed by modern web browsers thanks to [[Single Origin Policy]] restrictions. This restriction will be however enabled only if the target web site does not explicitly open up their [[HTML5 Security Cheat Sheet#Cross_Origin_Resource_Sharing|CORS]] with the following header:
+
Fortunately, this request will '''not''' be executed by modern web browsers thanks to [[Same-Origin Policy|same-origin policy]] restrictions. This restriction is enabled by default unless the target web site explicitly opens up cross-origin requests from the attacker's (or everyone's) origin by using [[HTML5 Security Cheat Sheet#Cross_Origin_Resource_Sharing|CORS]] with the following header:
  
 
  Access-Control-Allow-Origin: *
 
  Access-Control-Allow-Origin: *
Line 129: Line 152:
 
-->
 
-->
 
==Related [[Attacks]]==
 
==Related [[Attacks]]==
 +
 
* [[Cross-site Scripting (XSS)]]
 
* [[Cross-site Scripting (XSS)]]
 
* [[Cross Site History Manipulation (XSHM)]]
 
* [[Cross Site History Manipulation (XSHM)]]
Line 136: Line 160:
  
 
==Related [[Controls]]==
 
==Related [[Controls]]==
* Add a per-request nonce to URL and all forms in addition to the standard session. This is also referred to as "form keys". Many frameworks (ex, 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.  
+
 
* TBD: Add a per-session nonce to URL and all forms
+
* 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.
* TBD: Add a hash(session id, function name, server-side secret) to URL and all forms
+
* Add a hash (session id, function name, server-side secret) to all forms.
* TBD: .NET - add session identifier to ViewState with MAC
+
* For .NET, add a session identifier to ViewState with MAC (described in detail in [[Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Viewstate_(ASP.NET) | the CSRF Prevention Cheat Sheet]]).
* Checking the referrer in the client's HTTP request will prevent CSRF attacks. By ensuring the HTTP request have come from the original site means that the attacks from other sites will not function. It is very common to see referrer 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 Sammy Worm used an XHR to obtain the CSRF token to forge requests.
+
* 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.
* "Although cross-site request forgery 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
+
** XSS can be used to bypass both referrer and token based checks simultaneously. For instance, the [http://en.wikipedia.org/wiki/Samy_%28computer_worm%29 Samy worm] used an [[XHR]] 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
 
* [[Tokenizing]]
 
* [[Tokenizing]]
  
 
==References==
 
==References==
 +
 +
* OWASP [[Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet]]
 +
 
* [http://www.cgisecurity.com/articles/csrf-faq.shtml The Cross-Site Request Forgery (CSRF/XSRF) FAQ]
 
* [http://www.cgisecurity.com/articles/csrf-faq.shtml The Cross-Site Request Forgery (CSRF/XSRF) FAQ]
 
: ''quote: "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."''
 
: ''quote: "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 (OWASP-SM-005)|Testing for CSRF]]
 
* [[Testing for CSRF (OWASP-SM-005)|Testing for CSRF]]
: CSRF (aka Session riding) paper from the OWASP Testing Guide project (need to integrate)
+
: CSRF (aka Session riding) paper from the OWASP Testing Guide project.
  
 
* [http://www.darkreading.com/document.asp?doc_id=107651&WT.svl=news1_2 CSRF Vulnerability: A 'Sleeping Giant']
 
* [http://www.darkreading.com/document.asp?doc_id=107651&WT.svl=news1_2 CSRF Vulnerability: A 'Sleeping Giant']
Line 160: Line 188:
 
: 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.
 
: 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.
  
* [http://yehg.net/lab/pr0js/view.php/A_Most-Neglected_Fact_About_CSRF.pdf A Most-Neglected Fact About Cross Site Request Forgery (CSRF) ]
+
* [[CSRFProtector_Project | OWASP CSRF Protector]]
 +
: Anti CSRF method to mitigate CSRF in web applications. Currently implemented as a PHP library & Apache 2.x.x module
 +
 
 +
* [http://yehg.net/lab/pr0js/view.php/A_Most-Neglected_Fact_About_CSRF.pdf 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.
 
: Aung Khant, http://yehg.net, explained the danger and impact of CSRF with imperiling scenarios.
  
Line 167: Line 198:
  
 
* [http://code.google.com/p/pinata-csrf-tool/ Pinata-CSRF-Tool: CSRF POC tool]
 
* [http://code.google.com/p/pinata-csrf-tool/ Pinata-CSRF-Tool: CSRF POC tool]
: Pinata makes it easy to create Proof of Concept CSRF pages. Assists in Application Vulnerability Assessment.
+
: Pinata makes it easy to create Proof of Concept CSRF pages. Assists in Application Vulnerability Assessment. [[Category:Exploitation of Authentication]] [[Category:Embedded Malicious Code]] [[Category:Spoofing]] [[Category:Attack]]
 
 
[[Category:Exploitation of Authentication]]
 
[[Category:Embedded Malicious Code]]
 
[[Category:Spoofing]]
 
[[Category: Attack]]
 

Latest revision as of 15:52, 6 March 2018

This is an Attack. To view all attacks, please see the Attack Category page.

Last revision (mm/dd/yy): 03/6/2018

Overview

Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request. With a little help of social engineering (such as sending a link via email or chat), an attacker may trick the users of a web application into executing actions of the attacker's choosing. If the victim is a normal user, a successful CSRF attack can force the user to perform state changing requests like transferring funds, changing their email address, and so forth. If the victim is an administrative account, CSRF can compromise the entire web application.

Related Security Activities

How to Review Code for CSRF Vulnerabilities

See the OWASP Code Review Guide article on how to review code for CSRF vulnerabilities.

How to Test for CSRF Vulnerabilities

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

How to Prevent CSRF Vulnerabilities

See the CSRF Prevention Cheat Sheet for prevention measures.

Listen to the OWASP Top Ten CSRF Podcast.

Most frameworks have built-in CSRF support such as Joomla, Spring, Struts, Ruby on Rails, .NET and others.

Use OWASP CSRF Guard to add CSRF protection to your Java applications. You can use CSRFProtector Project to protect your php applications or any project deployed using Apache Server. There is a .Net CSRF Guard at OWASP as well, but it's old and doesn't look complete.

John Melton also has an excellent blog post describing how to use the native anti-CSRF functionality of the OWASP ESAPI.

Description

CSRF is an attack that tricks the victim into submitting a malicious request. It inherits the identity and privileges of the victim to perform an undesired function on the victim's behalf. For most sites, browser requests automatically include any credentials associated with the site, such as the user's session cookie, IP address, Windows domain credentials, and so forth. 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.

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

It's sometimes possible to store the CSRF attack on the vulnerable site itself. Such vulnerabilities are called "stored CSRF flaws". This can be accomplished by simply storing an IMG or IFRAME tag in a field that accepts HTML, or by a more complex cross-site scripting attack. If the attack can store a CSRF attack in the site, the severity of the attack is amplified. In particular, the likelihood is increased because the victim is more likely to view the page containing the attack than some random page on the Internet. The likelihood is also increased because the 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 Hostile Linking. Microsoft refers to this type of attack as a One-Click attack in their threat modeling process and many places in their online documentation.

Prevention measures that do NOT work

Using a secret cookie

Remember that all cookies, even the secret ones, will be submitted with every request. All authentication tokens will be submitted regardless of whether or not the end-user was tricked into submitting the request. Furthermore, session identifiers are simply used by the application container to associate the request with a specific session object. The session identifier does not verify that the end-user intended to submit the request.

Only accepting POST requests

Applications can be developed to only accept POST requests for the execution of business logic. The misconception is that since the attacker cannot construct a malicious link, a CSRF attack cannot be executed. Unfortunately, this logic is incorrect. There are numerous methods in which an attacker can trick a victim into submitting a forged POST request, such as a simple form hosted in an attacker's Website with hidden values. This form can be triggered automatically by JavaScript or can be triggered by the victim who thinks the form will do something else.

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

Multi-Step Transactions

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

URL Rewriting

This might be seen as a useful CSRF prevention technique as the attacker cannot guess the victim's session ID. However, the user’s session ID is exposed in the URL. We don't recommend fixing one security flaw by introducing another.

HTTPS

HTTPS by itself does nothing to defend against CSRF.

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

Examples

How does the attack work?

There are numerous ways in which an end user can be tricked into loading information from or submitting information to a web application. In order to execute an attack, we must first understand how to generate a valid malicious request for our victim to execute. Let us consider the following example: Alice wishes to transfer $100 to Bob using the bank.com web application that is vulnerable to CSRF. Maria, an attacker, wants to trick Alice into sending the money to her 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 to transfer parameters and execute actions, the money transfer operation might 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 using Alice as her victim. Maria first constructs the following exploit URL which will transfer $100,000 from Alice's account to her account. She takes the original command URL and replaces the beneficiary name with herself, raising the transfer amount significantly at the same time:

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

The social engineering aspect of the attack tricks Alice into loading this URL when she's logged into the bank application. This is usually done with one of the following techniques:

  • 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 the victim 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 see anything. However, the browser will still submit the request to bank.com without any visual indication that the transfer has taken place.

A real life example of CSRF attack on an application using GET was a uTorrent exploit from 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 is being executed by the victim. Let's assume the bank now uses POST and the vulnerable request looks like this:

POST http://bank.com/transfer.do HTTP/1.1

acct=BOB&amount=100

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

<form action="<nowiki>http://bank.com/transfer.do</nowiki>" 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 this can 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 as PUT or DELETE. Let's assume the vulnerable bank uses PUT that takes a JSON 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 exploit page:

<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 web browsers thanks to same-origin policy restrictions. This restriction is enabled by default unless the target web site explicitly opens up cross-origin requests from the attacker's (or everyone's) origin by using CORS with the following header:

Access-Control-Allow-Origin: *

Related Attacks

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 CSRF Prevention 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 XHR 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
  • Tokenizing

References

quote: "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."
CSRF (aka Session riding) paper from the OWASP Testing Guide project.
Overview Paper
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
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.
Anti CSRF method to mitigate CSRF in web applications. Currently implemented as a PHP library & Apache 2.x.x module
Aung Khant, http://yehg.net, explained the danger and impact of CSRF with imperiling scenarios.
The OWASP CSRFTester gives developers the ability to test their applications for CSRF flaws.
Pinata makes it easy to create Proof of Concept CSRF pages. Assists in Application Vulnerability Assessment.