|
|
(173 intermediate revisions by 13 users not shown) |
Line 1: |
Line 1: |
− | = Introduction = | + | __NOTOC__ |
| + | <div style="width:100%;height:160px;border:0,margin:0;overflow: hidden;">[[File:Cheatsheets-header.jpg|link=]]</div> |
| | | |
− | When looking at XSS (Cross Site Scripting) there are three generally recognized forms of XSS. Reflected, Persisted, and DOM based XSS. The [http://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet XSS Prevention Cheatsheet] has done an excellent job of addressing Reflected and Persisted XSS. This cheatsheet will address DOM (Document Object Model) based XSS and is an extension (as assumes comprehension of) the the [http://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet XSS Prevention Cheatsheet] .
| + | The Cheat Sheet Series project has been moved to [https://github.com/OWASP/CheatSheetSeries GitHub]! |
| | | |
− | In order to understand DOM based XSS one needs to see the fundamental difference between reflected and persisted XSS when compared to DOM based XSS. Reflected and persisted XSS exist in a higher level rendering context and DOM based XSS is primarily found in a lower level execution context. A rendering context is associated with the parsing of HTML tags and their attributes. The HTML parser of the rendering context dictates how data is presented and laid out on the page and can be further broken down into the standard contexts of HTML, HTML attribute, URL, and CSS. The JavaScript or VBScript parser of an execution context is associated with the parsing and execution of script code. Each parser has distinct and separate semantics in the way they can possibly execute script code (XSS) which make creating consistent rules for mitigating both rendering and execution based contexts difficult. The complication is compounded by the differing meanings and treatment of encoded values within each sub context (HTML, HTML attribute, URL, and CSS) within the execution context. One consistency, however, is the need to JavaScript encode in additional encodings required for the sub context in the execution context. Let’s look at the individual sub contexts of the execution context in turn.
| + | Please visit [https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html DOM based XSS Prevention Cheat Sheet] to see the latest version of the cheat sheet. |
− | | |
− | = HTML Sub Context within the Execution Context =
| |
− | | |
− | There are several methods and attributes which can be used to directly render HTML execution content within JavaScript.
| |
− | Attributes
| |
− | | |
− | <code>element.innerHTML = “<HTML> Tags and markup”;</code><br/>
| |
− | <code>element.outerHTML = “<HTML> Tags and markup”;</code><br/>
| |
− | <b>Methods</b>
| |
− | <code>document.write(“<HTML> Tags and markup”);</code><br/>
| |
− | <code>document.writeln(“<HTML> Tags and markup”);</code><br/>
| |
− | Guideline
| |
− | In a pure HTMLexecution context (not HTML Attribute) use HTML and JavaScript encoding to mitigate against attacks.
| |
− | <code>
| |
− | element.innerHTML = “<%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%>”;
| |
− | element.outerHTML = “<%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%>”;
| |
− | </code>
| |
− | Methods
| |
− | <code>
| |
− | document.write(“<%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%>”);
| |
− | document.writeln(“<%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%>”);
| |
− | </code>
| |
− | | |
− | == RULE #0 - Never Insert Untrusted Data Except in Allowed Locations ==
| |
− | | |
− | The first rule is to '''deny all''' - don't put untrusted data into your HTML document unless it is within one of the slots defined in Rule #1 through Rule #5. The reason for Rule #0 is that there are so many strange contexts within HTML that the list of escaping rules gets very complicated. We can't think of any good reason to put untrusted data in these contexts.
| |
− | | |
− | <script>'''...NEVER PUT UNTRUSTED DATA HERE...'''</script> directly in a script
| |
− |
| |
− | <!--'''...NEVER PUT UNTRUSTED DATA HERE...'''--> inside an HTML comment
| |
− |
| |
− | <div '''...NEVER PUT UNTRUSTED DATA HERE...'''=test /> in an attribute name
| |
− |
| |
− | <'''NEVER PUT UNTRUSTED DATA HERE...''' href="/test" /> in a tag name
| |
− | | |
− | Most importantly, never accept actual JavaScript code from an untrusted source and then run it. For example, a parameter named "callback" that contains a JavaScript code snippet. No amount of escaping can fix that.
| |
− | | |
− | == RULE #1 - HTML Escape Before Inserting Untrusted Data into HTML Element Content ==
| |
− | | |
− | Rule #1 is for when you want to put untrusted data directly into the HTML body somewhere. This includes inside normal tags like div, p, b, td, etc. Most web frameworks have a method for HTML escaping for the characters detailed below. However, this is '''absolutely not sufficient for other HTML contexts.''' You need to implement the other rules detailed here as well.
| |
− | | |
− | <body>'''...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...'''</body>
| |
− |
| |
− | <div>'''...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...'''</div>
| |
− |
| |
− | any other normal HTML elements
| |
− | | |
− | Escape the following characters with HTML entity encoding to prevent switching into any execution context, such as script, style, or event handlers. Using hex entities is recommended in the spec. In addition to the 5 characters significant in XML (&, <, >, ", '), the forward slash is included as it helps to end an HTML entity.
| |
− | | |
− | & --> &amp;
| |
− | < --> &lt;
| |
− | > --> &gt;
| |
− | " --> &quot;
| |
− | ' --> &#x27; ' is not recommended
| |
− | / --> &#x2F; forward slash is included as it helps end an HTML entity
| |
− | | |
− | See the [http://code.google.com/p/owasp-esapi-java/source/browse/trunk/src/main/java/org/owasp/esapi/codecs/HTMLEntityCodec.java ESAPI reference implementation] of HTML entity escaping and unescaping.
| |
− | | |
− | String safe = ESAPI.encoder().encodeForHTML( request.getParameter( "input" ) );
| |
− | | |
− | | |
− | == RULE #2 - Attribute Escape Before Inserting Untrusted Data into HTML Common Attributes ==
| |
− | | |
− | Rule #2 is for putting untrusted data into typical attribute values like width, name, value, etc. This should not be used for complex attributes like href, src, style, or any of the event handlers like onmouseover. It is extremely important that event handler attributes should follow Rule #3 for HTML JavaScript Data Values.
| |
− | | |
− | <div attr='''...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...'''>content</div> inside UNquoted attribute
| |
− |
| |
− | <div attr=''''...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...''''>content</div> inside single quoted attribute
| |
− |
| |
− | <div attr="'''...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...'''">content</div> inside double quoted attribute
| |
− | | |
− | Except for alphanumeric characters, escape all characters with ASCII values less than 256 with the &#xHH; format (or a named entity if available) to prevent switching out of the attribute. The reason this rule is so broad is that developers frequently leave attributes unquoted. Properly quoted attributes can only be escaped with the corresponding quote. Unquoted attributes can be broken out of with many characters, including [space] % * + , - / ; < = > ^ and |.
| |
− | | |
− | See the [http://code.google.com/p/owasp-esapi-java/source/browse/trunk/src/main/java/org/owasp/esapi/codecs/HTMLEntityCodec.java ESAPI reference implementation] of HTML entity escaping and unescaping.
| |
− | | |
− | String safe = ESAPI.encoder().encodeForHTMLAttribute( request.getParameter( "input" ) );
| |
− | | |
− | | |
− | == RULE #3 - JavaScript Escape Before Inserting Untrusted Data into HTML JavaScript Data Values ==
| |
− | | |
− | Rule #3 concerns the JavaScript event handlers that are specified on various HTML elements. The only safe place to put untrusted data into these event handlers as a quoted "data value." Including untrusted data inside any other code block is quite dangerous, as it is very easy to switch into an execution context, so use with caution.
| |
− | | |
− | <script>alert(''''...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...'''')</script> inside a quoted string
| |
− |
| |
− | <script>x=''''...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...''''</script> one side of a quoted expression
| |
− |
| |
− | <div onmouseover="x=''''...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...''''"</div> inside quoted event handler
| |
− | | |
− | Please note there are some JavaScript functions that can never safely use untrusted data as input - <b>EVEN IF JAVASCRIPT ESCAPED</b>! | |
− | | |
− | For example:
| |
− | <script>
| |
− | window.setInterval(''''...EVEN IF YOU ESCAPE UNTRUSTED DATA YOU ARE XSSED HERE...'''');
| |
− | </script>
| |
− | | |
− | Except for alphanumeric characters, escape all characters less than 256 with the \xHH format to prevent switching out of the data value into the script context or into another attribute. Do not use any escaping shortcuts like \" because the quote character may be matched by the HTML attribute parser which runs first. If an event handler is quoted, breaking out requires the corresponding quote. The reason this rule is so broad is that developers frequently leave event handler attributes unquoted. Properly quoted attributes can only be escaped with the corresponding quote. Unquoted attributes can be broken out of with many characters including [space] % * + , - / ; < = > ^ and |. Also, a </script> closing tag will close a script block even though it is inside a quoted string because the HTML parser runs before the JavaScript parser.
| |
− | | |
− | See the [http://code.google.com/p/owasp-esapi-java/source/browse/trunk/src/main/java/org/owasp/esapi/codecs/JavaScriptCodec.java ESAPI reference implementation] of JavaScript escaping and unescaping.
| |
− | | |
− | String safe = ESAPI.encoder().encodeForJavaScript( request.getParameter( "input" ) );
| |
− | | |
− | == RULE #4 - CSS Escape Before Inserting Untrusted Data into HTML Style Property Values ==
| |
− | | |
− | Rule #4 is for when you want to put untrusted data into a stylesheet or a style tag. CSS is surprisingly powerful, and can be used for numerous attacks. Therefore, it's important that you only use untrusted data in a property '''value''' and not into other places in style data. You should stay away from putting untrusted data into complex properties like url, behavior, and custom (-moz-binding). You should also not put untrusted data into IE’s expression property value which allows JavaScript.
| |
− | | |
− | <style>selector { property : '''...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...'''; } </style> property value<br/>
| |
− | <style>selector { property : "'''...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...'''"; } </style> property value<br/>
| |
− | <span style="property : '''...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...'''">text</style> property value
| |
− | | |
− | Except for alphanumeric characters, escape all characters with ASCII values less than 256 with the \HH escaping format. Do not use any escaping shortcuts like \" because the quote character may be matched by the HTML attribute parser which runs first. Prevent switching out of the property value and into another property or attribute. Also prevent switching into an expression or other property value that allows scripting. If attribute is quoted, breaking out requires the corresponding quote. All attributes should be quoted but your encoding should be strong enough to prevent XSS when untrusted data is placed in unquoted contexts. Unquoted attributes can be broken out of with many characters including [space] % * + , - / ; < = > ^ and |. Also, the </style> tag will close the style block even though it is inside a quoted string because the HTML parser runs before the JavaScript parser. Please note that we recommend aggressive CSS encoding to prevent XSS attacks for both quoted and unquoted attributes.
| |
− | | |
− | See the [http://code.google.com/p/owasp-esapi-java/source/browse/trunk/src/main/java/org/owasp/esapi/codecs/CSSCodec.java ESAPI reference implementation] of CSS escaping and unescaping.
| |
− | | |
− | String safe = ESAPI.encoder().encodeForCSS( request.getParameter( "input" ) );
| |
− | | |
− | == RULE #5 - URL Escape Before Inserting Untrusted Data into HTML URL Parameter Values ==
| |
− | | |
− | Rule #5 is for when you want to put untrusted data into HTTP GET parameter value.
| |
− | | |
− | <a href="http://www.somesite.com?test='''...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE..."'''>link</a >
| |
− | | |
− | Except for alphanumeric characters, escape all characters with ASCII values less than 256 with the %HH escaping format. Including untrusted data in data: URLs should not be allowed as there is no good way to disable attacks with escaping to prevent switching out of the URL. All attributes should be quoted. Unquoted attributes can be broken out of with many characters including [space] % * + , - / ; < = > ^ and |. Note that entity encoding is useless in this context.
| |
− | | |
− | See the [http://code.google.com/p/owasp-esapi-java/source/browse/trunk/src/main/java/org/owasp/esapi/codecs/PercentCodec.java ESAPI reference implementation] of URL escaping and unescaping.
| |
− | | |
− | String safe = ESAPI.encoder().encodeForURL( request.getParameter( "input" ) );
| |
− | | |
− | WARNING: Do not encode complete or relative URL's with URL encoding! If untrusted input is meant to be placed into href, src or other URL-based attributes, it should be validated to make sure it does not point to an unexpected protocol, especially Javascript links. URL's should then be encoded based on the context of display like any other piece of data. For example, user driven URL's in HREF links should be attribute encoded. For example:
| |
− | | |
− | String userURL = request.getParameter( "userURL" )
| |
− | boolean isValidURL = ESAPI.validator().isValidInput("URLContext", userURL, "URL", 255, false);
| |
− | if (isValidURL) {
| |
− | <a href="<%=encoder.encodeForHTMLAttribute(userURL)%>">link</a>
| |
− | }
| |
− | | |
− | == RULE #6 - Use an HTML Policy engine to validate or clean user-driven HTML in an outbound way ==
| |
− | | |
− | import org.owasp.validator.html.*;
| |
− | Policy policy = Policy.getInstance(POLICY_FILE_LOCATION);
| |
− | AntiSamy as = new AntiSamy();
| |
− | CleanResults cr = as.scan(dirtyInput, policy);
| |
− | MyUserDAO.storeUserProfile(cr.getCleanHTML()); // some custom function
| |
− | | |
− | == RULE #7 - Prevent DOM-based XSS ==
| |
− | | |
− | For details on what DOM-based XSS is, and defenses against this type of XSS flaw, please see the OWASP article on [[DOM_Based_XSS | DOM-based XSS]].
| |
− | | |
− | = Encoding Information =
| |
− | [http://code.google.com/p/owasp-development-guide/wiki/WebAppSecDesignGuide_D6 OWASP Development Guide]
| |
− | | |
− | = Additional XSS Defense (HTTPOnly cookie flag)=
| |
− | | |
− | Preventing all XSS flaws in an application is hard, as you can see. To help mitigate the impact of an XSS flaw on your site, OWASP also recommends you set the HTTPOnly flag on your session cookie and any custom cookies you have that are not accessed by any Javascript you wrote. This cookie flag is typically on by default in .NET apps, but in other languages you have to set it manually.
| |
− | | |
− | For more details on the HTTPOnly cookie flag, including what it does, and how to use it, see the OWASP article on [[HTTPOnly]].
| |
− | | |
− | =Related Articles=
| |
− | | |
− | '''XSS Attack Cheat Sheet'''
| |
− | | |
− | The following article describes how to exploit different kinds of XSS Vulnerabilities that this article was created to help you avoid:
| |
− | | |
− | * RSnake: "XSS Cheat Sheet" - http://ha.ckers.org/xss.html
| |
− | | |
− | '''Description of XSS Vulnerabilities'''
| |
− | | |
− | * OWASP article on [[XSS]] Vulnerabilities
| |
− | | |
− | '''How to Review Code for Cross-site scripting Vulnerabilities'''
| |
− | | |
− | * [[:Category:OWASP Code Review Project|OWASP Code Review Guide]] article on [[Reviewing Code for Cross-site scripting]] Vulnerabilities
| |
− | | |
− | '''How to Test for Cross-site scripting Vulnerabilities'''
| |
− | | |
− | * [[:Category:OWASP Testing Project|OWASP Testing Guide]] article on [[Testing for Cross site scripting]] Vulnerabilities
| |
− | | |
− | {{Cheatsheet_Navigation}}
| |
− | | |
− | = Authors and Primary Editors =
| |
− | | |
− | Jeff Williams - jeff.williams[at]aspectsecurity.com
| |
− | | |
− | Jim Manico - jim[at]manico.net
| |
− | | |
− | [[Category:OWASP Application Security Verification Standard Project]]
| |
− | [[Category:OWASP Enterprise Security API]]
| |
− | [[Category:How To]]
| |
− | [[Category:Cheatsheets]]
| |