<?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=Yozo</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=Yozo"/>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php/Special:Contributions/Yozo"/>
		<updated>2026-06-02T04:46:27Z</updated>
		<subtitle>User contributions</subtitle>
		<generator>MediaWiki 1.27.2</generator>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=IOS_Developer_Cheat_Sheet&amp;diff=218386</id>
		<title>IOS Developer Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=IOS_Developer_Cheat_Sheet&amp;diff=218386"/>
				<updated>2016-06-29T12:08:01Z</updated>
		
		<summary type="html">&lt;p&gt;Yozo: &amp;quot;IP number&amp;quot; changed to &amp;quot;IP address&amp;quot;, aligned to &amp;quot;Mac address&amp;quot; (-:&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
= Introduction  =&lt;br /&gt;
 __TOC__{{TOC hidden}}&lt;br /&gt;
This document is written for iOS app developers and is intended to provide a set of basic pointers to vital aspects of developing secure apps for Apple’s iOS operating system. It follows the [https://www.owasp.org/index.php/OWASP_Mobile_Security_Project OWASP Mobile Top 10 Risks] list.&lt;br /&gt;
&lt;br /&gt;
= Basics =&lt;br /&gt;
From a user perspective, two of the best things one can do to protect her iOS device are: enable strong passwords, and [https://www.owasp.org/index.php/Mobile_Jailbreaking_Cheat_Sheet refrain from jailbreaking the device]. For developers, both of these issues are problematic, as they are not verifiable within an app’s sandbox environment. (Apple previously had an API for testing devices to see if they are jailbroken, but that API was deprecated in 2010.) For enterprises, strong passwords, along with dozens of other security configuration attributes can be managed and enforced via a Mobile Device Management (MDM) product. Small businesses and individuals with multiple devices can use Apple’s iPhone Configuration Utility (http://www.apple.com/support/iphone/enterprise/) and Apple Configurator (available in the Mac App Store) to build secure configuration profiles and deploy them on multiple devices.&lt;br /&gt;
&lt;br /&gt;
= Remediation’s to OWASP Mobile Top 10 Risks =&lt;br /&gt;
&lt;br /&gt;
== Insecure Data Storage (M1) ==&lt;br /&gt;
Without a doubt, the biggest risk faced by mobile device consumers comes from a lost or stolen device. The information stored on the device is thus exposed to anyone who finds or steals another person’s device. It is largely up to the apps on the device to provide adequate protection of any data they store. Apple’s iOS provides several mechanisms for protecting data. These built in protections are quite adequate for most consumer-grade information. For more stringent security requirements (e.g., financial data), additional protections beyond those provided by Apple can be built into an application.&lt;br /&gt;
=== Remediations ===&lt;br /&gt;
In general, an app should store locally only the data that is required to perform its functional tasks. This includes side channel data such as system logging (see M8 below). For any form of sensitive data, storing plaintext data storage in an app’s sandbox (e.g., ~/Documents/* ) should always be avoided. Consumer-grade sensitive data should be stored in secure containers using Apple-provided APIs.&lt;br /&gt;
* Small amounts of consumer grade sensitive data, such as user authentication credentials, session tokens, etc., can be securely stored in the device’s Keychain (see Keychain Services Reference in Apple’s iOS Developer Library).&lt;br /&gt;
* For larger, or more general types of consumer-grade data, Apple’s File Protection mechanism can safely be used (see NSData Class Reference for protection options).&lt;br /&gt;
* More data that exceeds normal consumer-grade sensitivity, if it absolutely must be stored locally, consider using a third party container encryption API that is not encumbered by the inherent weaknesses in Apple’s encryption (e.g., keying tied to user’s device passcode, which is often a 4-digit PIN). Freely available examples include SQLcipher (see http://sqlcipher.net). In doing this, proper key management is of utmost importance -- and beyond the scope of this document.&lt;br /&gt;
* For items stored in the keychain leverage the most secure API designation, kSecAttrAccessibleWhenUnlocked (now the default in iOS 5/6)&lt;br /&gt;
* Avoid using NSUserDefaults to store sensitive pieces of information&lt;br /&gt;
* Be aware that all data/entities using NSManagedObects will be stored in an unencrypted database file.&lt;br /&gt;
&lt;br /&gt;
== Weak Server Side Controls (M2) ==&lt;br /&gt;
Although most server side controls are in fact necessary to handle on the server side — and as such we refer the reader to the [[Web Service Security Cheat Sheet]]—there are several things that can be done on the mobile that aid in the work to be done on the server.&lt;br /&gt;
=== Remediations ===&lt;br /&gt;
Design and implement the mobile client and the server to support a common set of security requirements. For example, information deemed sensitive on the server should be handled with equivalent due caution on the client side.&lt;br /&gt;
Perform positive input validation and canonicalization on all client-side input data. Use regular expressions and other mechanisms to ensure that only allowable data may enter the application at the client end.&lt;br /&gt;
Perform output encoding on untrusted data where feasible.&lt;br /&gt;
&lt;br /&gt;
== Insufficient Transport Layer Protection (M3) ==&lt;br /&gt;
Exposing sensitive data to eavesdropping attacks is a common issue with all networked applications, and iOS mobile apps are no exception.&lt;br /&gt;
=== Remediations ===&lt;br /&gt;
Design and implement all apps under the assumption that they will be used on the most wide-open Wi-Fi networks on the planet.&lt;br /&gt;
Make an inventory of all app data that must be protected while in transit. (Protections should include confidentiality as well as integrity.) The inventory should include authentication tokens, session tokens, as well as application data directly.&lt;br /&gt;
Ensure SSL/TLS encryption is used when transmitting or receiving all inventoried data. (See CFNetwork Programming Guide.)&lt;br /&gt;
Ensure your app only accepts properly validated SSL certificates. (CA chain validation is routinely disabled in testing environments; ensure your app has removed any such code prior to public release.)&lt;br /&gt;
Verify through dynamic testing that all inventoried data is adequately protected throughout the operation of the app.&lt;br /&gt;
Verify through dynamic testing that forged, self-signed, etc., certificates cannot be accepted by the app under any circumstances.&lt;br /&gt;
&lt;br /&gt;
== Client Side Injection (M4) ==&lt;br /&gt;
Data injection attacks are as real in mobile apps as they are in web apps, although the attack scenarios tend to differ (e.g., exploiting URL schemes to send premium text messages or toll phone calls).&lt;br /&gt;
=== Remediations ===&lt;br /&gt;
In general, follow the same rules as a web app for input validation and output escaping.&lt;br /&gt;
Canonicalize and positively validate all data input.&lt;br /&gt;
Use parameterized queries, even for local SQLite/SQLcipher calls. &lt;br /&gt;
When using URL schemes, take extra care in validating and accepting input, as any app on the device is able to call a URL scheme.&lt;br /&gt;
When building a hybrid web/mobile app, keep the native/local capabilities of the app to a bare minimum required. That is, maintain control of all UIWebView content and pages, and prevent the user from accessing arbitrary, untrusted web content.&lt;br /&gt;
== Poor Authorization and Authentication (M5) ==&lt;br /&gt;
Although largely a server side control, some mobile features (e.g., unique device identifiers) and common uses can exacerbate the problems surrounding securely authenticating and authorizing users and other entities.&lt;br /&gt;
=== Remediations ===&lt;br /&gt;
In general follow the same rules as a web app for authentication and authorization.&lt;br /&gt;
Never use a device identifier (e.g., UDID , IP address, MAC address, IMEI) to identify a user or session.&lt;br /&gt;
Avoid when possible “out-of-band” authentication tokens sent to the same device as the user is using to log in (e.g., SMS to the same iPhone).&lt;br /&gt;
Implement strong server side authentication, authorization, and session management (control # 4.1-4.6).&lt;br /&gt;
Authenticate all API calls to paid resources (control 8.4).&lt;br /&gt;
== Improper Session Handling (M6) ==&lt;br /&gt;
Similarly, session handling is in general, principally a server task, but mobile devices tend to amplify traditional problems in unforeseen ways. For example, on mobile devices, “sessions” often last far longer than on traditional web applications.&lt;br /&gt;
=== Remediations ===&lt;br /&gt;
For the most part, follow sound session management practices as you would for a web application, with a few twists that are specific to mobile devices.&lt;br /&gt;
Never use a device identifier (e.g., UDID, IP address, MAC address, IMEI) to identify a session. (Control 1.13)&lt;br /&gt;
Use only tokens that can be quickly revoked in the event of a lost/stolen device, or compromised session.&lt;br /&gt;
Protect the confidentiality and integrity of session tokens at all times (e.g., always use SSL/TLS when transmitting).&lt;br /&gt;
Use only trustworthy sources for generating sessions.&lt;br /&gt;
== Security Decisions via Untrusted Inputs (M7) ==&lt;br /&gt;
While iOS does not give apps many channels for communicating among themselves, some exist—and can be abused by an attacker via data injection attacks, malicious apps, etc.&lt;br /&gt;
=== Remediations ===&lt;br /&gt;
The combination of input validation, output escaping, and authorization controls can be used against these weaknesses.&lt;br /&gt;
Canonicalize and positively validate all input data, particularly at boundaries between apps.&lt;br /&gt;
When using URL schemes, take extra care in validating and accepting input, as any app on the device is able to call a URL scheme.&lt;br /&gt;
Contextually escape all untrusted data output, so that it cannot change the intent of the output itself.&lt;br /&gt;
Verify the caller is permitted to access any requested resources. If appropriate, prompt the user to allow/disallow access to the requested resource.&lt;br /&gt;
== Side Channel Data Leakage (M8) ==&lt;br /&gt;
Side channels refer here to data I/O generally used for administrative or non-functional (directly) purposes, such as web caches (used to optimize browser speed), keystroke logs (used for spell checking), and similar. Apple’s iOS presents several opportunities for side channel data to inadvertently leak from an app, and that data is often available to anyone who has found or stolen a victim’s device. Most of these can be controlled programmatically in an app.&lt;br /&gt;
=== Remediations ===&lt;br /&gt;
Design and implement all apps under the assumption that the user’s device will be lost or stolen.&lt;br /&gt;
Start by identifying all potential side channel data present on a device. These sources should include, at a bare minimum: web caches, keystroke logs, screen shots, system logs, and cut-and-paste buffers. Be sure to include any third party libraries used.&lt;br /&gt;
Never include sensitive data (e.g., credentials, tokens, PII) in system logs.&lt;br /&gt;
Control iOS’s screenshot behavior to prevent sensitive app data from being captured when an app is minimized.&lt;br /&gt;
Disable keystroke logging for the most sensitive data, to prevent it from being stored in plaintext on the device.&lt;br /&gt;
Disable cut-and-paste buffer for the most sensitive data, to prevent it from being leaked outside of the app.&lt;br /&gt;
Dynamically test the app, including its data stores and communications channels, to verify that no sensitive data is being inappropriately transmitted or stored.&lt;br /&gt;
== Broken Cryptography (M9) ==&lt;br /&gt;
Although the vast majority of cryptographic weaknesses in software result from poor key management, all aspects of a crypto system should be carefully designed and implemented. Mobile apps are no different in that regard.&lt;br /&gt;
=== Remediations ===&lt;br /&gt;
Never “hard code” or store cryptographic keys where an attacker can trivially recover them. This includes plaintext data files, properties files, and compiled binaries.&lt;br /&gt;
Use secure containers for storing crypto keys; alternately, build a secure key exchange system where the key is controlled by a secure server, and never stored locally on the mobile device.&lt;br /&gt;
Use only strong crypto algorithms and implementations, including key generation tools, hashes, etc.&lt;br /&gt;
Use platform crypto APIs when feasible; use trusted third party code when not.&lt;br /&gt;
Consumer-grade sensitive data should be stored in secure containers using Apple-provided APIs.&lt;br /&gt;
* Small amounts of data, such as user authentication credentials, session tokens, etc., can be securely stored in the device’s Keychain (see Keychain Services Reference in Apple’s iOS Developer Library).&lt;br /&gt;
* For larger, or more general types of data, Apple’s File Protection mechanism can safely be used (see NSData Class Reference for protection options).&lt;br /&gt;
To more securely protect static data, consider using a third party encryption API that is not encumbered by the inherent weaknesses in Apple’s encryption (e.g., keying tied to user’s device passcode, which is often a 4-digit PIN). Freely available examples include SQLcipher (see http://sqlcipher.net).&lt;br /&gt;
&lt;br /&gt;
== Sensitive Information Disclosure (M10) ==&lt;br /&gt;
All sorts of sensitive data can leak out of iOS apps. Among other things to remember at all times, each app’s compiled binary code is available on the device, and can be reverse engineered by a determined adversary.&lt;br /&gt;
=== Remediations ===&lt;br /&gt;
Anything that must truly remain private should not reside on the mobile device; keep private information (e.g., algorithms, proprietary information) on the server.&lt;br /&gt;
If private information must be present on a mobile device, ensure it remains in process memory and is never unprotected if it is stored on the device.&lt;br /&gt;
Never hard code or otherwise trivially store passwords, session tokens, etc.&lt;br /&gt;
Strip binaries prior to shipping, and be aware that compiled executable files can still be reverse engineered.&lt;br /&gt;
&lt;br /&gt;
= References and Further Reading =&lt;br /&gt;
&lt;br /&gt;
OWASP Top 10 Mobile Risks presentation, Appsec USA, Minneapolis, MN, 23 Sept 2011. Jack Mannino, Mike Zusman, and Zach Lanier.&lt;br /&gt;
&lt;br /&gt;
“iOS Security”, Apple, October 2014 https://www.apple.com/business/docs/iOS_Security_Guide_Oct_2014.pdf&lt;br /&gt;
&lt;br /&gt;
“Deploying iPhone and iPad: Apple Configurator”, Apple, March 2012, http://images.apple.com/iphone/business/docs/iOS_Apple_Configurator_Mar12.pdf &lt;br /&gt;
&lt;br /&gt;
“iPhone OS: Enterprise Deployment Guide”, Apple, 2010, http://manuals.info.apple.com/en_US/Enterprise_Deployment_Guide.pdf &lt;br /&gt;
&lt;br /&gt;
“iPhone in Business”, Apple resources, http://www.apple.com/iphone/business/resources/ &lt;br /&gt;
&lt;br /&gt;
Apple iOS Developer website.&lt;br /&gt;
&lt;br /&gt;
&amp;quot;iOS Application (in)Security&amp;quot;, MDSec - May 2012, http://www.mdsec.co.uk/research/iOS_Application_Insecurity_wp_v1.0_final.pdf&lt;br /&gt;
&lt;br /&gt;
= Authors and Primary Editors =&lt;br /&gt;
&lt;br /&gt;
Ken van Wyk ken[at]krvw.com&lt;br /&gt;
&lt;br /&gt;
Contributors: Jason.Haddix@hp.com&lt;br /&gt;
&lt;br /&gt;
== Other Cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yozo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=DOM_based_XSS_Prevention_Cheat_Sheet&amp;diff=218379</id>
		<title>DOM based XSS Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=DOM_based_XSS_Prevention_Cheat_Sheet&amp;diff=218379"/>
				<updated>2016-06-29T10:13:53Z</updated>
		
		<summary type="html">&lt;p&gt;Yozo: should be typo...&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
= Introduction  =&lt;br /&gt;
 __TOC__{{TOC hidden}}&lt;br /&gt;
&lt;br /&gt;
When looking at XSS (Cross-Site Scripting), there are three generally recognized forms of [[XSS]].  [[XSS#Stored_and_Reflected_XSS_Attacks | Reflected, Stored]], and [[DOM Based XSS]].  The [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheatsheet]] does an excellent job of addressing Reflected and Stored XSS. This cheatsheet addresses DOM (Document Object Model) based XSS and is an extension (and assumes comprehension of) the [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheatsheet]].&lt;br /&gt;
&lt;br /&gt;
In order to understand DOM based XSS, one needs to see the fundamental difference between Reflected and Stored XSS when compared to DOM based XSS. The primary difference is where the attack is injected into the application. Reflected and Stored XSS are server side injection issues while DOM based XSS is a client (browser) side injection issue. All of this code originates on the server, which means it is the application owner's responsibility to make it safe from XSS, regardless of the type of XSS flaw it is. Also, XSS attacks always &amp;lt;b&amp;gt;execute&amp;lt;/b&amp;gt; in the browser. The difference between Reflected/Stored XSS is where the attack is added or injected into the application. With Reflected/Stored the attack is injected into the application during server-side processing of requests where untrusted input is dynamically added to HTML. For DOM XSS, the attack is injected into the application during runtime in the client directly.&lt;br /&gt;
&lt;br /&gt;
When a browser is rendering HTML and any other associated content like CSS, JavaScript, etc. it identifies various rendering contexts for the different kinds of input and follows different rules for each 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 which make creating consistent rules for mitigating vulnerabilities in various contexts difficult.   The complication is compounded by the differing meanings and treatment of encoded values within each subcontext (HTML, HTML attribute, URL, and CSS) within the execution context.&lt;br /&gt;
&lt;br /&gt;
For the purposes of this article, we refer to the HTML, HTML attribute, URL, and CSS contexts as subcontexts because each of these contexts can be reached and set within a JavaScript execution context.  In JavaScript code, the main context is JavaScript but with the right tags and context closing characters, an attacker can try to attack the other 4 contexts using equivalent JavaScript DOM methods.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The following is an example vulnerability which occurs in the JavaScript context and HTML subcontext:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 var x = '&amp;lt;%= taintedVar %&amp;gt;';&lt;br /&gt;
 var d = document.createElement('div');&lt;br /&gt;
 d.innerHTML = x;&lt;br /&gt;
 document.body.appendChild(d);&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Let’s look at the individual subcontexts of the execution context in turn.&lt;br /&gt;
&lt;br /&gt;
==RULE #1 - HTML Escape then JavaScript Escape Before Inserting Untrusted Data into HTML Subcontext within the Execution Context==&lt;br /&gt;
&lt;br /&gt;
There are several methods and attributes which can be used to directly render HTML content within JavaScript.  These methods constitute the HTML Subcontext within the Execution Context. If these methods are provided with untrusted input, then an XSS vulnerability could result. For example:&lt;br /&gt;
&lt;br /&gt;
===Example Dangerous HTML Methods===&lt;br /&gt;
====Attributes====&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 element.innerHTML = &amp;quot;&amp;lt;HTML&amp;gt; Tags and markup&amp;quot;;&lt;br /&gt;
 element.outerHTML = &amp;quot;&amp;lt;HTML&amp;gt; Tags and markup&amp;quot;;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Methods====&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 document.write(&amp;quot;&amp;lt;HTML&amp;gt; Tags and markup&amp;quot;);&lt;br /&gt;
 document.writeln(&amp;quot;&amp;lt;HTML&amp;gt; Tags and markup&amp;quot;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Guideline===&lt;br /&gt;
To make dynamic updates to HTML in the DOM safe, we recommend a) HTML encoding, and then b) JavaScript encoding all untrusted input, as shown in these examples:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 element.innerHTML = &amp;quot;&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%&amp;gt;&amp;quot;;&lt;br /&gt;
 element.outerHTML = &amp;quot;&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%&amp;gt;&amp;quot;;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 document.write(&amp;quot;&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%&amp;gt;&amp;quot;);&lt;br /&gt;
 document.writeln(&amp;quot;&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%&amp;gt;&amp;quot;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note: The Encoder.encodeForHTML() and Encoder.encodeForJS() are just notional encoders. Various options for actual encoders are listed later in this document.&lt;br /&gt;
&lt;br /&gt;
== RULE #2 - JavaScript Escape Before Inserting Untrusted Data into HTML Attribute Subcontext within the Execution Context ==&lt;br /&gt;
&lt;br /&gt;
The HTML attribute *subcontext* within the *execution* context is divergent from the standard encoding rules. This is because the rule to HTML attribute encode in an HTML attribute rendering context is necessary in order to mitigate attacks which try to exit out of an HTML attributes or try to add additional attributes which could lead to XSS.  When you are in a DOM execution context you only need to JavaScript encode HTML attributes which do not execute code (attributes other than event handler, CSS, and URL attributes).&lt;br /&gt;
&lt;br /&gt;
For example, the general rule is to HTML Attribute encode untrusted data (data from the database, HTTP request, user, back-end system, etc.) placed in an HTML Attribute.  This is the appropriate step to take when outputting data in a rendering context, however using HTML Attribute encoding in an execution context will break the application display of data.&lt;br /&gt;
&lt;br /&gt;
=== SAFE but BROKEN example===&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = document.createElement(&amp;quot;input&amp;quot;);&lt;br /&gt;
 x.setAttribute(&amp;quot;name&amp;quot;, &amp;quot;company_name&amp;quot;);&lt;br /&gt;
 // In the following line of code, companyName represents untrusted user input&lt;br /&gt;
 // The Encoder.encodeForHTMLAttr() is unnecessary and causes double-encoding&lt;br /&gt;
 x.setAttribute(&amp;quot;value&amp;quot;, '&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForHTMLAttr(companyName))%&amp;gt;'); &lt;br /&gt;
 var form1 = document.forms[0];&lt;br /&gt;
 form1.appendChild(x);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The problem is that if companyName had the value “Johnson &amp;amp; Johnson”.  What would be displayed in the input text field would be “Johnson &amp;amp;amp;amp; Johnson”.  The appropriate encoding to use in the above case would be only JavaScript encoding to disallow an attacker from closing out the single quotes and in-lining code, or escaping to HTML and opening a new script tag.&lt;br /&gt;
&lt;br /&gt;
===SAFE and FUNCTIONALLY CORRECT example===&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = document.createElement(&amp;quot;input&amp;quot;);&lt;br /&gt;
 x.setAttribute(&amp;quot;name&amp;quot;, &amp;quot;company_name&amp;quot;);&lt;br /&gt;
 x.setAttribute(&amp;quot;value&amp;quot;, '&amp;lt;%=Encoder.encodeForJS(companyName)%&amp;gt;');&lt;br /&gt;
 var form1 = document.forms[0];&lt;br /&gt;
 form1.appendChild(x);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It is important to note that when setting an HTML attribute which does not execute code, the value is set directly within the object attribute of the HTML element so there is no concerns with injecting up.&lt;br /&gt;
&lt;br /&gt;
==RULE #3 - Be Careful when Inserting Untrusted Data into the Event Handler and JavaScript code Subcontexts within an Execution Context==&lt;br /&gt;
&lt;br /&gt;
Putting dynamic data within JavaScript code is especially dangerous because JavaScript encoding has different semantics for JavaScript encoded data when compared to other encodings.  In many cases, JavaScript encoding does not stop attacks within an execution context.  For example, a JavaScript encoded string will execute even though it is JavaScript encoded.&lt;br /&gt;
&lt;br /&gt;
Therefore, the primary recommendation is to &amp;lt;u&amp;gt;avoid including untrusted data in this context&amp;lt;/u&amp;gt;. If you must, the following examples describe some approaches that do and do not work.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = document.createElement(&amp;quot;a&amp;quot;);&lt;br /&gt;
 x.href=&amp;quot;#&amp;quot;;&lt;br /&gt;
 // In the line of code below, the encoded data on the right (the second argument to setAttribute) &lt;br /&gt;
 // is an example of untrusted data that was properly JavaScript encoded but still executes.&lt;br /&gt;
 x.setAttribute(&amp;quot;onclick&amp;quot;, &amp;quot;\u0061\u006c\u0065\u0072\u0074\u0028\u0032\u0032\u0029&amp;quot;);&lt;br /&gt;
 var y = document.createTextNode(&amp;quot;Click To Test&amp;quot;);&lt;br /&gt;
 x.appendChild(y);&lt;br /&gt;
 document.body.appendChild(x);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The setAttribute(&amp;lt;i&amp;gt;name_string&amp;lt;/i&amp;gt;,&amp;lt;i&amp;gt;value_string&amp;lt;/i&amp;gt;) method is dangerous because it implicitly coerces the  &amp;lt;i&amp;gt;value_string&amp;lt;/i&amp;gt; into the DOM attribute datatype of &amp;lt;i&amp;gt;name_string&amp;lt;/i&amp;gt;.  In the case above, the attribute name is an JavaScript event handler, so the attribute value is implicitly converted to JavaScript code and evaluated.  In the case above, JavaScript encoding does not mitigate against DOM based XSS.  Other JavaScript methods which take code as a string types will have a similar problem as outline above (setTimeout, setInterval, new Function, etc.).  This is in stark contrast to JavaScript encoding in the event handler attribute of a HTML tag (HTML parser) where JavaScript encoding mitigates against XSS.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
&amp;lt;!-- Does NOT work  --&amp;gt;&lt;br /&gt;
&amp;lt;a id=&amp;quot;bb&amp;quot; href=&amp;quot;#&amp;quot; onclick=&amp;quot;\u0061\u006c\u0065\u0072\u0074\u0028\u0031\u0029&amp;quot;&amp;gt; Test Me&amp;lt;/a&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
An alternative to using Element.setAttribute(...) to set DOM attributes is to set the attribute directly.  Directly setting event handler attributes will allow JavaScript encoding to mitigate against DOM based XSS. Please note, it is always dangerous design to put untrusted data directly into a command execution context.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
    &amp;lt;a id=&amp;quot;bb&amp;quot; href=&amp;quot;#&amp;quot;&amp;gt; Test Me&amp;lt;/a&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
            //The following does NOT work because the event handler is being set to a string.  &amp;quot;alert(7)&amp;quot; is JavaScript encoded.&lt;br /&gt;
            document.getElementById(&amp;quot;bb&amp;quot;).onclick = &amp;quot;\u0061\u006c\u0065\u0072\u0074\u0028\u0037\u0029&amp;quot;;&lt;br /&gt;
            &lt;br /&gt;
            //The following does NOT work because the event handler is being set to a string.&lt;br /&gt;
            document.getElementById(&amp;quot;bb&amp;quot;).onmouseover = &amp;quot;testIt&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
            //The following does NOT work because of the encoded &amp;quot;(&amp;quot; and &amp;quot;)&amp;quot;. &amp;quot;alert(77)&amp;quot; is JavaScript encoded.&lt;br /&gt;
            document.getElementById(&amp;quot;bb&amp;quot;).onmouseover = \u0061\u006c\u0065\u0072\u0074\u0028\u0037\u0037\u0029;&lt;br /&gt;
&lt;br /&gt;
            //The following does NOT work because of the encoded &amp;quot;;&amp;quot;. &amp;quot;testIt;testIt&amp;quot; is JavaScript encoded.&lt;br /&gt;
            document.getElementById(&amp;quot;bb&amp;quot;).onmouseover = \u0074\u0065\u0073\u0074\u0049\u0074\u003b\u0074\u0065\u0073\u0074\u0049\u0074;&lt;br /&gt;
      &lt;br /&gt;
            //The following DOES WORK because the encoded value is a valid variable name or function reference.  &amp;quot;testIt&amp;quot; is JavaScript encoded&lt;br /&gt;
            document.getElementById(&amp;quot;bb&amp;quot;).onmouseover = \u0074\u0065\u0073\u0074\u0049\u0074;&lt;br /&gt;
&lt;br /&gt;
            function testIt() {&lt;br /&gt;
                &lt;br /&gt;
                alert(&amp;quot;I was called.&amp;quot;);&lt;br /&gt;
            }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There are other places in JavaScript where JavaScript encoding is accepted as valid executable code.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 for ( var \u0062=0; \u0062 &amp;lt; 10; \u0062++){&lt;br /&gt;
     \u0064\u006f\u0063\u0075\u006d\u0065\u006e\u0074                  &lt;br /&gt;
     .\u0077\u0072\u0069\u0074\u0065\u006c\u006e&lt;br /&gt;
     (&amp;quot;\u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064&amp;quot;);&lt;br /&gt;
 }&lt;br /&gt;
 \u0077\u0069\u006e\u0064\u006f\u0077&lt;br /&gt;
 .\u0065\u0076\u0061\u006c&lt;br /&gt;
 \u0064\u006f\u0063\u0075\u006d\u0065\u006e\u0074&lt;br /&gt;
 .\u0077\u0072\u0069\u0074\u0065(111111111);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var s = &amp;quot;\u0065\u0076\u0061\u006c&amp;quot;;&lt;br /&gt;
 var t = &amp;quot;\u0061\u006c\u0065\u0072\u0074\u0028\u0031\u0031\u0029&amp;quot;;&lt;br /&gt;
 window[s](t);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Because JavaScript is based on an international standard (ECMAScript), JavaScript encoding enables the support of international characters in programming constructs and variables in addition to alternate string representations (string escapes).  &lt;br /&gt;
&lt;br /&gt;
However the opposite is the case with HTML encoding.  HTML tag elements are well defined and do not support alternate representations of the same tag.  So HTML encoding cannot be used to allow the developer to have alternate representations of the &amp;lt;code&amp;gt;&amp;lt;a&amp;gt;&amp;lt;/code&amp;gt; tag for example.&lt;br /&gt;
&lt;br /&gt;
===HTML Encoding’s Disarming Nature===&lt;br /&gt;
&lt;br /&gt;
In general, HTML encoding serves to castrate HTML tags which are placed in HTML and HTML attribute contexts.&lt;br /&gt;
Working example (no HTML encoding):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;a href=&amp;quot;...&amp;quot; &amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Normally encoded example (Does Not Work – DNW):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;amp;amp;#x3c;a href=... &amp;amp;amp;#x3e;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
HTML encoded example to highlight a fundamental difference with JavaScript encoded values (DNW):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;&amp;amp;amp;#x61; href=...&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If HTML encoding followed the same semantics as JavaScript encoding.  The line above could have possibily worked to render a link.  This difference makes JavaScript encoding a less viable weapon in our fight against XSS.&lt;br /&gt;
&lt;br /&gt;
==RULE #4 - JavaScript Escape Before Inserting Untrusted Data into the CSS Attribute Subcontext within the Execution Context==&lt;br /&gt;
&lt;br /&gt;
Normally executing JavaScript from a CSS context required either passing &amp;lt;code&amp;gt;javascript:attackCode()&amp;lt;/code&amp;gt; to the CSS url() method or invoking the CSS expression() method passing JavaScript code to be directly executed.  From my experience, calling the expression() function from an execution context (JavaScript) has been disabled.  In order to mitigate against the CSS url() method, ensure that you are URL encoding the data passed to the CSS url() method.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 document.body.style.backgroundImage = &amp;quot;url(&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForURL(companyName))%&amp;gt;)&amp;quot;;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
TODO: We have not been able to get the expression() function working from DOM JavaScript code.  Need some help.&lt;br /&gt;
&lt;br /&gt;
== RULE #5 - URL Escape then JavaScript Escape Before Inserting Untrusted Data into URL Attribute Subcontext within the Execution Context ==&lt;br /&gt;
&lt;br /&gt;
The logic which parses URLs in both execution and rendering contexts looks to be the same.  Therefore there is little change in the encoding rules for URL attributes in an execution (DOM) context.&lt;br /&gt;
&lt;br /&gt;
 var x = document.createElement(&amp;quot;a&amp;quot;);&lt;br /&gt;
 x.setAttribute(&amp;quot;href&amp;quot;, '&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForURL(userRelativePath))%&amp;gt;');&lt;br /&gt;
 var y = document.createTextElement(&amp;quot;Click Me To Test&amp;quot;);&lt;br /&gt;
 x.appendChild(y);&lt;br /&gt;
 document.body.appendChild(x);&lt;br /&gt;
&lt;br /&gt;
If you utilize fully qualified URLs then this will break the links as the colon in the protocol identifier (“http:” or “javascript:”) will be URL encoded preventing the “http” and “javascript” protocols from being invoked.&lt;br /&gt;
&lt;br /&gt;
== RULE #6 - Populate the DOM using safe JavaScript functions or properties ==&lt;br /&gt;
&lt;br /&gt;
The most fundamental safe way to populate the DOM with untrusted data is to use the safe assignment property, textContent. Here is an example of safe usage.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 element.textContent = &amp;quot;&amp;lt;%=untrustedData%&amp;gt;&amp;quot;;  //does not executes code&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Guidelines for Developing Secure Applications Utilizing JavaScript=&lt;br /&gt;
&lt;br /&gt;
DOM based XSS is extremely difficult to mitigate against because of its large attack surface and lack of standardization across browsers.  The guidelines below are an attempt to provide guidelines for developers when developing Web based JavaScript applications (Web 2.0) such that they can avoid XSS.&lt;br /&gt;
&lt;br /&gt;
1. Untrusted data should only be treated as displayable text.  Never treat untrusted data as code or markup within JavaScript code. &amp;lt;br/&amp;gt;&lt;br /&gt;
2. Always JavaScript encode and delimit untrusted data as quoted strings when entering the application (Jim Manico and Robert Hansen) &amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = &amp;quot;&amp;lt;%=encodedJavaScriptData%&amp;gt;&amp;quot;;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
3. Use &amp;lt;code&amp;gt;document.createElement(&amp;quot;...&amp;quot;), element.setAttribute(&amp;quot;...&amp;quot;,&amp;quot;value&amp;quot;), element.appendChild(...)&amp;lt;/code&amp;gt;, etc. to build dynamic interfaces.  Please note, element.setAttribute is only safe for a limited number of attributes. Dangerous attributes include any attribute that is a command execution context, such as onclick or onblur. Examples of safe attributes includes align, alink, alt, bgcolor, border, cellpadding, cellspacing, class, color, cols, colspan, coords, dir, face, height, hspace, ismap, lang, marginheight, marginwidth, multiple, nohref, noresize, noshade, nowrap, ref, rel, rev, rows, rowspan, scrolling, shape, span, summary, tabindex, title, usemap, valign, value, vlink, vspace, width.&amp;lt;br/&amp;gt;&lt;br /&gt;
4. Avoid use of HTML rendering methods:&amp;lt;br/&amp;gt;&lt;br /&gt;
#&amp;lt;code&amp;gt;element.innerHTML = &amp;quot;...&amp;quot;; &amp;lt;/code&amp;gt;&lt;br /&gt;
#&amp;lt;code&amp;gt;element.outerHTML = &amp;quot;...&amp;quot;; &amp;lt;/code&amp;gt;&lt;br /&gt;
#&amp;lt;code&amp;gt;document.write(...); &amp;lt;/code&amp;gt;&lt;br /&gt;
#&amp;lt;code&amp;gt;document.writeln(...); &amp;lt;/code&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
5. Understand the dataflow of untrusted data through your JavaScript code.  If you do have to use the methods above remember to HTML and then JavaScript encode the untrusted data (Stefano Di Paola).&amp;lt;br/&amp;gt;&lt;br /&gt;
6. There are numerous methods which implicitly eval() data passed to it.  Make sure that any untrusted data passed to these methods is delimited with string delimiters and enclosed within a closure or JavaScript encoded to N-levels based on usage, and wrapped in a custom function.  Ensure to follow step 4 above to make sure that the untrusted data is not sent to dangerous methods within the custom function or handle it by adding an extra layer of encoding.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Utilizing an Enclosure (as suggested by Gaz)&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The example that follows illustrates using closures to avoid double JavaScript encoding.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 setTimeout((function(param) { return function() {&lt;br /&gt;
          customFunction(param);&lt;br /&gt;
          }&lt;br /&gt;
 })(&amp;quot;&amp;lt;%=Encoder.encodeForJS(untrustedData)%&amp;gt;&amp;quot;), y);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The other alternative is using N-levels of encoding.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;N-Levels of Encoding&amp;lt;/b&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If your code looked like the following, you would need to only double JavaScript encode input data.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 setTimeout(&amp;quot;customFunction('&amp;lt;%=doubleJavaScriptEncodedData%&amp;gt;', y)&amp;quot;);&lt;br /&gt;
 function customFunction (firstName, lastName)&lt;br /&gt;
       alert(&amp;quot;Hello&amp;quot; + firstName + &amp;quot; &amp;quot; + lastNam);&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;doubleJavaScriptEncodedData&amp;lt;/code&amp;gt; has its first layer of JavaScript encoding reversed (upon execution) in the single quotes.  Then the implicit &amp;lt;code&amp;gt;eval()&amp;lt;/code&amp;gt; of &amp;lt;code&amp;gt;setTimeout()&amp;lt;/code&amp;gt; reverses another layer of JavaScript encoding to pass the correct value to &amp;lt;code&amp;gt;customFunction&amp;lt;/code&amp;gt;.  The reason why you only need to double JavaScript encode is that the &amp;lt;code&amp;gt;customFunction&amp;lt;/code&amp;gt; function did not itself pass the input to another method which implicitly or explicitly called &amp;lt;code&amp;gt;eval()&amp;lt;/code&amp;gt;.  If &amp;quot;firstName&amp;quot; was passed to another JavaScript method which implicitly or explicitly called eval() then &amp;lt;code&amp;gt;&amp;lt;%=doubleJavaScriptEncodedData%&amp;gt;&amp;lt;/code&amp;gt; above would need to be changed to &amp;lt;code&amp;gt;&amp;lt;%=tripleJavaScriptEncodedData%&amp;gt;&amp;lt;/code&amp;gt;.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
An important implementation note is that if the JavaScript code tries to utilize the double or triple encoded data in string comparisons, the value may be interpreted as different values based on the number of evals() the data has passed through before being passed to the if comparison and the number of times the value was JavaScript encoded.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If &amp;quot;A&amp;quot; is double JavaScript encoded then the following if check will return false.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = &amp;quot;doubleJavaScriptEncodedA&amp;quot;;  //\u005c\u0075\u0030\u0030\u0034\u0031&lt;br /&gt;
 if (x == &amp;quot;A&amp;quot;) {&lt;br /&gt;
    alert(&amp;quot;x is A&amp;quot;);&lt;br /&gt;
 } else if (x == &amp;quot;\u0041&amp;quot;) {&lt;br /&gt;
    alert(&amp;quot;This is what pops&amp;quot;);&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This brings up an interesting design point.  Ideally, the correct way to apply encoding and avoid the problem stated above is to server-side encode for the output context where data is introduced into the application.  Then client-side encode (using a JavaScript encoding library such as ESAPI4JS) for the individual subcontext (DOM methods) which untrusted data is passed to.  ESAPI4JS (located at http://bit.ly/9hRTLH) and jQuery Encoder (located at https://github.com/chrisisbeef/jquery-encoder/blob/master/src/main/javascript/org/owasp/esapi/jquery/encoder.js) are two client side encoding libraries developed by Chris Schmidt.&amp;lt;br/&amp;gt;&lt;br /&gt;
Here are some examples of how they are used:&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var input = &amp;quot;&amp;lt;%=Encoder.encodeForJS(untrustedData)%&amp;gt;&amp;quot;;  //server-side encoding&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 window.location = ESAPI4JS.encodeForURL(input);  //URL encoding is happening in JavaScript&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 document.writeln(ESAPI4JS.encodeForHTML(input));  //HTML encoding is happening in JavaScript&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It has been well noted by the group that any kind of reliance on a JavaScript library for encoding would be problematic as the JavaScript library could be subverted by attackers.  One option is to wait till ECMAScript 5 so the JavaScript library could support immutable properties.&amp;lt;br/&amp;gt;&lt;br /&gt;
Another option provided by Gaz (Gareth) was to use a specific code construct to limit mutability with anonymous clousures.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
An example follows:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 function escapeHTML(str) {&lt;br /&gt;
      str = str + &amp;quot;''&amp;quot;;&lt;br /&gt;
      var out = &amp;quot;''&amp;quot;;&lt;br /&gt;
      for(var i=0; i&amp;lt;str.length; i++) {&lt;br /&gt;
          if(str[i] === '&amp;lt;') {&lt;br /&gt;
              out += '&amp;amp;amp;lt;';&lt;br /&gt;
          } else if(str[i] === '&amp;gt;') {&lt;br /&gt;
              out += '&amp;amp;amp;gt;';&lt;br /&gt;
          } else if(str[i] === &amp;quot;'&amp;quot;) {&lt;br /&gt;
              out += '&amp;amp;amp;#39;'; &lt;br /&gt;
          } else if(str[i] === '&amp;quot;') {&lt;br /&gt;
              out += '&amp;amp;amp;quot;';                        &lt;br /&gt;
          } else {&lt;br /&gt;
              out += str[i];&lt;br /&gt;
          }&lt;br /&gt;
      }&lt;br /&gt;
      return out;                    &lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br/&amp;gt;Chris Schmidt has put together another implementation of a JavaScript encoder at http://yet-another-dev.blogspot.com/2011/02/client-side-contextual-encoding-for.html.  &amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
6. Limit the usage of dynamic untrusted data to right side operations.  And be aware of data which may be passed to the application which look like code (eg. &amp;lt;code&amp;gt;location&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;eval()&amp;lt;/code&amp;gt;).  (Achim)&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = &amp;quot;&amp;lt;%=properly encoded data for flow%&amp;gt;&amp;quot;;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you want to change different object attributes based on user input use a level of indirection.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of: &amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 window[userData] = &amp;quot;moreUserData&amp;quot;;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Do the following instead:&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 if (userData===&amp;quot;location&amp;quot;) {&lt;br /&gt;
    window.location = &amp;quot;static/path/or/properly/url/encoded/value&amp;quot;;&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
7. When URL encoding in DOM be aware of character set issues as the character set in JavaScript DOM is not clearly defined (Mike Samuel).&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
8. Limit access to properties objects when using object[x] accessors. (Mike Samuel).  In other words use a level of indirection between untrusted input and specified object properties.&amp;lt;br/&amp;gt;&lt;br /&gt;
Here is an example of the problem when using map types:&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var myMapType = {};&lt;br /&gt;
 myMapType[&amp;lt;%=untrustedData%&amp;gt;] = &amp;quot;moreUntrustedData&amp;quot;;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Although the developer writing the code above was trying to add additional keyed elements to the &amp;lt;code&amp;gt;myMapType&amp;lt;/code&amp;gt; object.  This could be used by an attacker to subvert internal and external attributes of the &amp;lt;code&amp;gt;myMapType&amp;lt;/code&amp;gt; object.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
9. Run your JavaScript in a ECMAScript 5 canopy or sand box to make it harder for your JavaScript API to be compromised (Gareth Heyes and John Stevens).&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
10. Don’t &amp;lt;code&amp;gt;eval()&amp;lt;/code&amp;gt; JSON to convert it to native JavaScript objects.  Instead use &amp;lt;code&amp;gt;JSON.toJSON()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;JSON.parse()&amp;lt;/code&amp;gt; (Chris Schmidt).&lt;br /&gt;
&lt;br /&gt;
=  Common Problems Associated with Mitigating DOM Based XSS =&lt;br /&gt;
==Complex Contexts==&lt;br /&gt;
In many cases the context isn’t always straightforward to discern.&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;a href=&amp;quot;javascript:myFunction('&amp;lt;%=untrustedData%&amp;gt;', 'test');&amp;quot;&amp;gt;Click Me&amp;lt;/a&amp;gt;&lt;br /&gt;
 ...&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 Function myFunction (url,name) {&lt;br /&gt;
     window.location = url;&lt;br /&gt;
 }&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, untrusted data started in the rendering URL context (&amp;lt;code&amp;gt;href&amp;lt;/code&amp;gt; attribute of an &amp;lt;code&amp;gt;&amp;lt;a&amp;gt;&amp;lt;/code&amp;gt; tag) then changed to a JavaScript execution context (&amp;lt;code&amp;gt;javascript:&amp;lt;/code&amp;gt; protocol handler) which passed the untrusted data to an execution URL subcontext (&amp;lt;code&amp;gt;window.location&amp;lt;/code&amp;gt; of myFunction).  Because the data was introduced in JavaScript code and passed to a URL subcontext the appropriate server-side encoding would be the following:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;a href=&amp;quot;javascript:myFunction('&amp;lt;%=Encoder.encodeForJS( &amp;amp;#x21a9;&lt;br /&gt;
               Encoder.encodeForURL(untrustedData))%&amp;gt;', 'test');&amp;quot;&amp;gt;Click Me&amp;lt;/a&amp;gt;&lt;br /&gt;
 ...&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Or if you were using ECMAScript 5 with an immutable JavaScript client-side encoding libraries you could do the following:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;amp;lt;!--server side URL encoding has been removed.  Now only JavaScript encoding on server side. --&amp;gt;&lt;br /&gt;
 &amp;lt;a href=&amp;quot;javascript:myFunction('&amp;lt;%=Encoder.encodeForJS(untrustedData)%&amp;gt;', 'test');&amp;quot;&amp;gt;Click Me&amp;lt;/a&amp;gt;&lt;br /&gt;
 ...&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 Function myFunction (url,name) {&lt;br /&gt;
     var encodedURL = ESAPI4JS.encodeForURL(url);  //URL encoding using client-side scripts&lt;br /&gt;
     window.location = encodedURL;&lt;br /&gt;
 }&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Inconsistencies of Encoding Libraries ==&lt;br /&gt;
There are a number of open source encoding libraries out there:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#[[ESAPI]]&lt;br /&gt;
#Apache Commons String Utils&lt;br /&gt;
#Jtidy&lt;br /&gt;
#Your company’s custom implementation.&lt;br /&gt;
&lt;br /&gt;
Some work on a black list while others ignore important characters like “&amp;lt;” and “&amp;gt;”.  ESAPI is one of the few which works on a whitelist and encodes all non-alphanumeric characters.&lt;br /&gt;
It is important to use an encoding library that understands which characters can be used to exploit vulnerabilies in their respective contexts. Misconceptions abound related to the proper encoding that is required.&lt;br /&gt;
&lt;br /&gt;
==Encoding Misconceptions==&lt;br /&gt;
Many security training curriculums and papers advocate the blind usage of HTML encoding to resolve XSS.  This logically seems to be prudent advice as the JavaScript parser does not understand HTML encoding.  However, if the pages returned from your web application utilize a content type of “text/xhtml” or the file type extension of “*.xhtml” then HTML encoding may not work to mitigate against XSS.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example: &amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 &amp;amp;amp;#x61;lert(1);&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt; &lt;br /&gt;
&lt;br /&gt;
The HTML encoded value above is still executable.  If that isn’t enough to keep in mind, you have to remember that encodings are lost when you retrieve them using the value attribute of a DOM element. &amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Let’s look at the sample page and script:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;form name=&amp;quot;myForm&amp;quot; ...&amp;gt;&lt;br /&gt;
   &amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;lName&amp;quot; value=&amp;quot;&amp;lt;%=Encoder.encodeForHTML(last_name)%&amp;gt;&amp;quot;&amp;gt;&lt;br /&gt;
 ...&lt;br /&gt;
 &amp;lt;/form&amp;gt;&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 var x = document.myForm.lName.value;  //when the value is retrieved the encoding is reversed&lt;br /&gt;
 document.writeln(x);  //any code passed into lName is now executable.&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally there is the problem that certain methods in JavaScript which are usually safe can be unsafe in certain contexts.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Usually Safe Methods==&lt;br /&gt;
&lt;br /&gt;
One example of an attribute which is thought to be safe is innerText.  Some papers or guides advocate its use as an alternative to innerHTML to mitigate against XSS in innerHTML.  However, depending on the tag which innerText is applied, code can be executed. Also note, innerText is non standard and is not supported in FireFox&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 var tag = document.createElement(&amp;quot;script&amp;quot;);&lt;br /&gt;
 tag.innerText = &amp;quot;&amp;lt;%=untrustedData%&amp;gt;&amp;quot;;  //executes code&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Authors and Contributing Editors  =&lt;br /&gt;
&lt;br /&gt;
Jim Manico - jim[at]owasp.org&amp;lt;br/&amp;gt;&lt;br /&gt;
Abraham Kang - abraham.kang[at]owasp.org&amp;lt;br/&amp;gt;&lt;br /&gt;
Gareth (Gaz) Heyes&amp;lt;br/&amp;gt;&lt;br /&gt;
Stefano Di Paola&amp;lt;br/&amp;gt;&lt;br /&gt;
Achim Hoffmann - achim[at]owasp.org&amp;lt;br/&amp;gt;&lt;br /&gt;
Robert (RSnake) Hansen&amp;lt;br/&amp;gt;&lt;br /&gt;
Mario Heiderich&amp;lt;br/&amp;gt;&lt;br /&gt;
John Steven&amp;lt;br/&amp;gt;&lt;br /&gt;
Chris (Chris BEEF) Schmidt&amp;lt;br/&amp;gt;&lt;br /&gt;
Mike Samuel&amp;lt;br/&amp;gt;&lt;br /&gt;
Jeremy Long&amp;lt;br/&amp;gt;&lt;br /&gt;
Eduardo (SirDarkCat) Alberto Vela Nava&amp;lt;br/&amp;gt;&lt;br /&gt;
Jeff Williams - jeff.williams[at]owasp.org &amp;lt;br/&amp;gt;&lt;br /&gt;
Erlend Oftedal&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;padding-left:25px;width:300px;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
&lt;br /&gt;
== Other Cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yozo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=DOM_based_XSS_Prevention_Cheat_Sheet&amp;diff=218378</id>
		<title>DOM based XSS Prevention Cheat Sheet</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=DOM_based_XSS_Prevention_Cheat_Sheet&amp;diff=218378"/>
				<updated>2016-06-29T10:06:08Z</updated>
		
		<summary type="html">&lt;p&gt;Yozo: garbage removed.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt; __NOTOC__&lt;br /&gt;
&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;padding: 0;margin:0;margin-top:10px;text-align:left;&amp;quot; |-&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
= Introduction  =&lt;br /&gt;
 __TOC__{{TOC hidden}}&lt;br /&gt;
&lt;br /&gt;
When looking at XSS (Cross-Site Scripting), there are three generally recognized forms of [[XSS]].  [[XSS#Stored_and_Reflected_XSS_Attacks | Reflected, Stored]], and [[DOM Based XSS]].  The [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheatsheet]] does an excellent job of addressing Reflected and Stored XSS. This cheatsheet addresses DOM (Document Object Model) based XSS and is an extension (and assumes comprehension of) the [[XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | XSS Prevention Cheatsheet]].&lt;br /&gt;
&lt;br /&gt;
In order to understand DOM based XSS, one needs to see the fundamental difference between Reflected and Stored XSS when compared to DOM based XSS. The primary difference is where the attack is injected into the application. Reflected and Stored XSS are server side injection issues while DOM based XSS is a client (browser) side injection issue. All of this code originates on the server, which means it is the application owner's responsibility to make it safe from XSS, regardless of the type of XSS flaw it is. Also, XSS attacks always &amp;lt;b&amp;gt;execute&amp;lt;/b&amp;gt; in the browser. The difference between Reflected/Stored XSS is where the attack is added or injected into the application. With Reflected/Stored the attack is injected into the application during server-side processing of requests where untrusted input is dynamically added to HTML. For DOM XSS, the attack is injected into the application during runtime in the client directly.&lt;br /&gt;
&lt;br /&gt;
When a browser is rendering HTML and any other associated content like CSS, JavaScript, etc. it identifies various rendering contexts for the different kinds of input and follows different rules for each 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 which make creating consistent rules for mitigating vulnerabilities in various contexts difficult.   The complication is compounded by the differing meanings and treatment of encoded values within each subcontext (HTML, HTML attribute, URL, and CSS) within the execution context.&lt;br /&gt;
&lt;br /&gt;
For the purposes of this article, we refer to the HTML, HTML attribute, URL, and CSS contexts as subcontexts because each of these contexts can be reached and set within a JavaScript execution context.  In JavaScript code, the main context is JavaScript but with the right tags and context closing characters, an attacker can try to attack the other 4 contexts using equivalent JavaScript DOM methods.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The following is an example vulnerability which occurs in the JavaScript context and HTML subcontext:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 var x = '&amp;lt;%= taintedVar %&amp;gt;';&lt;br /&gt;
 var d = document.createElement('div');&lt;br /&gt;
 d.innerHTML = x;&lt;br /&gt;
 document.body.appendChild(d);&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Let’s look at the individual subcontexts of the execution context in turn.&lt;br /&gt;
&lt;br /&gt;
==RULE #1 - HTML Escape then JavaScript Escape Before Inserting Untrusted Data into HTML Subcontext within the Execution Context==&lt;br /&gt;
&lt;br /&gt;
There are several methods and attributes which can be used to directly render HTML content within JavaScript.  These methods constitute the HTML Subcontext within the Execution Context. If these methods are provided with untrusted input, then an XSS vulnerability could result. For example:&lt;br /&gt;
&lt;br /&gt;
===Example Dangerous HTML Methods===&lt;br /&gt;
====Attributes====&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 element.innerHTML = &amp;quot;&amp;lt;HTML&amp;gt; Tags and markup&amp;quot;;&lt;br /&gt;
 element.outerHTML = &amp;quot;&amp;lt;HTML&amp;gt; Tags and markup&amp;quot;;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Methods====&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 document.write(&amp;quot;&amp;lt;HTML&amp;gt; Tags and markup&amp;quot;);&lt;br /&gt;
 document.writeln(&amp;quot;&amp;lt;HTML&amp;gt; Tags and markup&amp;quot;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Guideline===&lt;br /&gt;
To make dynamic updates to HTML in the DOM safe, we recommend a) HTML encoding, and then b) JavaScript encoding all untrusted input, as shown in these examples:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 element.innerHTML = &amp;quot;&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%&amp;gt;&amp;quot;;&lt;br /&gt;
 element.outerHTML = &amp;quot;&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%&amp;gt;&amp;quot;;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 document.write(&amp;quot;&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%&amp;gt;&amp;quot;);&lt;br /&gt;
 document.writeln(&amp;quot;&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))%&amp;gt;&amp;quot;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note: The Encoder.encodeForHTML() and Encoder.encodeForJS() are just notional encoders. Various options for actual encoders are listed later in this document.&lt;br /&gt;
&lt;br /&gt;
== RULE #2 - JavaScript Escape Before Inserting Untrusted Data into HTML Attribute Subcontext within the Execution Context ==&lt;br /&gt;
&lt;br /&gt;
The HTML attribute *subcontext* within the *execution* context is divergent from the standard encoding rules. This is because the rule to HTML attribute encode in an HTML attribute rendering context is necessary in order to mitigate attacks which try to exit out of an HTML attributes or try to add additional attributes which could lead to XSS.  When you are in a DOM execution context you only need to JavaScript encode HTML attributes which do not execute code (attributes other than event handler, CSS, and URL attributes).&lt;br /&gt;
&lt;br /&gt;
For example, the general rule is to HTML Attribute encode untrusted data (data from the database, HTTP request, user, back-end system, etc.) placed in an HTML Attribute.  This is the appropriate step to take when outputting data in a rendering context, however using HTML Attribute encoding in an execution context will break the application display of data.&lt;br /&gt;
&lt;br /&gt;
=== SAFE but BROKEN example===&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = document.createElement(&amp;quot;input&amp;quot;);&lt;br /&gt;
 x.setAttribute(&amp;quot;name&amp;quot;, &amp;quot;company_name&amp;quot;);&lt;br /&gt;
 // In the following line of code, companyName represents untrusted user input&lt;br /&gt;
 // The Encoder.encodeForHTMLAttr() is unnecessary and causes double-encoding&lt;br /&gt;
 x.setAttribute(&amp;quot;value&amp;quot;, '&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForHTMLAttr(companyName))%&amp;gt;'); &lt;br /&gt;
 var form1 = document.forms[0];&lt;br /&gt;
 form1.appendChild(x);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The problem is that if companyName had the value “Johnson &amp;amp; Johnson”.  What would be displayed in the input text field would be “Johnson &amp;amp;amp;amp; Johnson”.  The appropriate encoding to use in the above case would be only JavaScript encoding to disallow an attacker from closing out the single quotes and in-lining code, or escaping to HTML and opening a new script tag.&lt;br /&gt;
&lt;br /&gt;
===SAFE and FUNCTIONALLY CORRECT example===&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = document.createElement(&amp;quot;input&amp;quot;);&lt;br /&gt;
 x.setAttribute(&amp;quot;name&amp;quot;, &amp;quot;company_name&amp;quot;);&lt;br /&gt;
 x.setAttribute(&amp;quot;value&amp;quot;, '&amp;lt;%=Encoder.encodeForJS(companyName)%&amp;gt;');&lt;br /&gt;
 var form1 = document.forms[0];&lt;br /&gt;
 form1.appendChild(x);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It is important to note that when setting an HTML attribute which does not execute code, the value is set directly within the object attribute of the HTML element so there is no concerns with injecting up.&lt;br /&gt;
&lt;br /&gt;
==RULE #3 - Be Careful when Inserting Untrusted Data into the Event Handler and JavaScript code Subcontexts within an Execution Context==&lt;br /&gt;
&lt;br /&gt;
Putting dynamic data within JavaScript code is especially dangerous because JavaScript encoding has different semantics for JavaScript encoded data when compared to other encodings.  In many cases, JavaScript encoding does not stop attacks within an execution context.  For example, a JavaScript encoded string will execute even though it is JavaScript encoded.&lt;br /&gt;
&lt;br /&gt;
Therefore, the primary recommendation is to &amp;lt;u&amp;gt;avoid including untrusted data in this context&amp;lt;/u&amp;gt;. If you must, the following examples describe some approaches that do and do not work.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = document.createElement(&amp;quot;a&amp;quot;);&lt;br /&gt;
 x.href=&amp;quot;#&amp;quot;;&lt;br /&gt;
 // In the line of code below, the encoded data on the right (the second argument to setAttribute) &lt;br /&gt;
 // is an example of untrusted data that was properly JavaScript encoded but still executes.&lt;br /&gt;
 x.setAttribute(&amp;quot;onclick&amp;quot;, &amp;quot;\u0061\u006c\u0065\u0072\u0074\u0028\u0032\u0032\u0029&amp;quot;);&lt;br /&gt;
 var y = document.createTextNode(&amp;quot;Click To Test&amp;quot;);&lt;br /&gt;
 x.appendChild(y);&lt;br /&gt;
 document.body.appendChild(x);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The setAttribute(&amp;lt;i&amp;gt;name_string&amp;lt;/i&amp;gt;,&amp;lt;i&amp;gt;value_string&amp;lt;/i&amp;gt;) method is dangerous because it implicitly coerces the  &amp;lt;i&amp;gt;string_value&amp;lt;/i&amp;gt; into the DOM attribute datatype of &amp;lt;i&amp;gt;name_string&amp;lt;/i&amp;gt;.  In the case above, the attribute name is an JavaScript event handler, so the attribute value is implicitly converted to JavaScript code and evaluated.  In the case above, JavaScript encoding does not mitigate against DOM based XSS.  Other JavaScript methods which take code as a string types will have a similar problem as outline above (setTimeout, setInterval, new Function, etc.).  This is in stark contrast to JavaScript encoding in the event handler attribute of a HTML tag (HTML parser) where JavaScript encoding mitigates against XSS.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
&amp;lt;!-- Does NOT work  --&amp;gt;&lt;br /&gt;
&amp;lt;a id=&amp;quot;bb&amp;quot; href=&amp;quot;#&amp;quot; onclick=&amp;quot;\u0061\u006c\u0065\u0072\u0074\u0028\u0031\u0029&amp;quot;&amp;gt; Test Me&amp;lt;/a&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
An alternative to using Element.setAttribute(...) to set DOM attributes is to set the attribute directly.  Directly setting event handler attributes will allow JavaScript encoding to mitigate against DOM based XSS. Please note, it is always dangerous design to put untrusted data directly into a command execution context.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
    &amp;lt;a id=&amp;quot;bb&amp;quot; href=&amp;quot;#&amp;quot;&amp;gt; Test Me&amp;lt;/a&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
            //The following does NOT work because the event handler is being set to a string.  &amp;quot;alert(7)&amp;quot; is JavaScript encoded.&lt;br /&gt;
            document.getElementById(&amp;quot;bb&amp;quot;).onclick = &amp;quot;\u0061\u006c\u0065\u0072\u0074\u0028\u0037\u0029&amp;quot;;&lt;br /&gt;
            &lt;br /&gt;
            //The following does NOT work because the event handler is being set to a string.&lt;br /&gt;
            document.getElementById(&amp;quot;bb&amp;quot;).onmouseover = &amp;quot;testIt&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
            //The following does NOT work because of the encoded &amp;quot;(&amp;quot; and &amp;quot;)&amp;quot;. &amp;quot;alert(77)&amp;quot; is JavaScript encoded.&lt;br /&gt;
            document.getElementById(&amp;quot;bb&amp;quot;).onmouseover = \u0061\u006c\u0065\u0072\u0074\u0028\u0037\u0037\u0029;&lt;br /&gt;
&lt;br /&gt;
            //The following does NOT work because of the encoded &amp;quot;;&amp;quot;. &amp;quot;testIt;testIt&amp;quot; is JavaScript encoded.&lt;br /&gt;
            document.getElementById(&amp;quot;bb&amp;quot;).onmouseover = \u0074\u0065\u0073\u0074\u0049\u0074\u003b\u0074\u0065\u0073\u0074\u0049\u0074;&lt;br /&gt;
      &lt;br /&gt;
            //The following DOES WORK because the encoded value is a valid variable name or function reference.  &amp;quot;testIt&amp;quot; is JavaScript encoded&lt;br /&gt;
            document.getElementById(&amp;quot;bb&amp;quot;).onmouseover = \u0074\u0065\u0073\u0074\u0049\u0074;&lt;br /&gt;
&lt;br /&gt;
            function testIt() {&lt;br /&gt;
                &lt;br /&gt;
                alert(&amp;quot;I was called.&amp;quot;);&lt;br /&gt;
            }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
There are other places in JavaScript where JavaScript encoding is accepted as valid executable code.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 for ( var \u0062=0; \u0062 &amp;lt; 10; \u0062++){&lt;br /&gt;
     \u0064\u006f\u0063\u0075\u006d\u0065\u006e\u0074                  &lt;br /&gt;
     .\u0077\u0072\u0069\u0074\u0065\u006c\u006e&lt;br /&gt;
     (&amp;quot;\u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064&amp;quot;);&lt;br /&gt;
 }&lt;br /&gt;
 \u0077\u0069\u006e\u0064\u006f\u0077&lt;br /&gt;
 .\u0065\u0076\u0061\u006c&lt;br /&gt;
 \u0064\u006f\u0063\u0075\u006d\u0065\u006e\u0074&lt;br /&gt;
 .\u0077\u0072\u0069\u0074\u0065(111111111);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
or&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var s = &amp;quot;\u0065\u0076\u0061\u006c&amp;quot;;&lt;br /&gt;
 var t = &amp;quot;\u0061\u006c\u0065\u0072\u0074\u0028\u0031\u0031\u0029&amp;quot;;&lt;br /&gt;
 window[s](t);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Because JavaScript is based on an international standard (ECMAScript), JavaScript encoding enables the support of international characters in programming constructs and variables in addition to alternate string representations (string escapes).  &lt;br /&gt;
&lt;br /&gt;
However the opposite is the case with HTML encoding.  HTML tag elements are well defined and do not support alternate representations of the same tag.  So HTML encoding cannot be used to allow the developer to have alternate representations of the &amp;lt;code&amp;gt;&amp;lt;a&amp;gt;&amp;lt;/code&amp;gt; tag for example.&lt;br /&gt;
&lt;br /&gt;
===HTML Encoding’s Disarming Nature===&lt;br /&gt;
&lt;br /&gt;
In general, HTML encoding serves to castrate HTML tags which are placed in HTML and HTML attribute contexts.&lt;br /&gt;
Working example (no HTML encoding):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;a href=&amp;quot;...&amp;quot; &amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Normally encoded example (Does Not Work – DNW):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;amp;amp;#x3c;a href=... &amp;amp;amp;#x3e;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
HTML encoded example to highlight a fundamental difference with JavaScript encoded values (DNW):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;&amp;amp;amp;#x61; href=...&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If HTML encoding followed the same semantics as JavaScript encoding.  The line above could have possibily worked to render a link.  This difference makes JavaScript encoding a less viable weapon in our fight against XSS.&lt;br /&gt;
&lt;br /&gt;
==RULE #4 - JavaScript Escape Before Inserting Untrusted Data into the CSS Attribute Subcontext within the Execution Context==&lt;br /&gt;
&lt;br /&gt;
Normally executing JavaScript from a CSS context required either passing &amp;lt;code&amp;gt;javascript:attackCode()&amp;lt;/code&amp;gt; to the CSS url() method or invoking the CSS expression() method passing JavaScript code to be directly executed.  From my experience, calling the expression() function from an execution context (JavaScript) has been disabled.  In order to mitigate against the CSS url() method, ensure that you are URL encoding the data passed to the CSS url() method.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 document.body.style.backgroundImage = &amp;quot;url(&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForURL(companyName))%&amp;gt;)&amp;quot;;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
TODO: We have not been able to get the expression() function working from DOM JavaScript code.  Need some help.&lt;br /&gt;
&lt;br /&gt;
== RULE #5 - URL Escape then JavaScript Escape Before Inserting Untrusted Data into URL Attribute Subcontext within the Execution Context ==&lt;br /&gt;
&lt;br /&gt;
The logic which parses URLs in both execution and rendering contexts looks to be the same.  Therefore there is little change in the encoding rules for URL attributes in an execution (DOM) context.&lt;br /&gt;
&lt;br /&gt;
 var x = document.createElement(&amp;quot;a&amp;quot;);&lt;br /&gt;
 x.setAttribute(&amp;quot;href&amp;quot;, '&amp;lt;%=Encoder.encodeForJS(Encoder.encodeForURL(userRelativePath))%&amp;gt;');&lt;br /&gt;
 var y = document.createTextElement(&amp;quot;Click Me To Test&amp;quot;);&lt;br /&gt;
 x.appendChild(y);&lt;br /&gt;
 document.body.appendChild(x);&lt;br /&gt;
&lt;br /&gt;
If you utilize fully qualified URLs then this will break the links as the colon in the protocol identifier (“http:” or “javascript:”) will be URL encoded preventing the “http” and “javascript” protocols from being invoked.&lt;br /&gt;
&lt;br /&gt;
== RULE #6 - Populate the DOM using safe JavaScript functions or properties ==&lt;br /&gt;
&lt;br /&gt;
The most fundamental safe way to populate the DOM with untrusted data is to use the safe assignment property, textContent. Here is an example of safe usage.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 element.textContent = &amp;quot;&amp;lt;%=untrustedData%&amp;gt;&amp;quot;;  //does not executes code&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Guidelines for Developing Secure Applications Utilizing JavaScript=&lt;br /&gt;
&lt;br /&gt;
DOM based XSS is extremely difficult to mitigate against because of its large attack surface and lack of standardization across browsers.  The guidelines below are an attempt to provide guidelines for developers when developing Web based JavaScript applications (Web 2.0) such that they can avoid XSS.&lt;br /&gt;
&lt;br /&gt;
1. Untrusted data should only be treated as displayable text.  Never treat untrusted data as code or markup within JavaScript code. &amp;lt;br/&amp;gt;&lt;br /&gt;
2. Always JavaScript encode and delimit untrusted data as quoted strings when entering the application (Jim Manico and Robert Hansen) &amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = &amp;quot;&amp;lt;%=encodedJavaScriptData%&amp;gt;&amp;quot;;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
3. Use &amp;lt;code&amp;gt;document.createElement(&amp;quot;...&amp;quot;), element.setAttribute(&amp;quot;...&amp;quot;,&amp;quot;value&amp;quot;), element.appendChild(...)&amp;lt;/code&amp;gt;, etc. to build dynamic interfaces.  Please note, element.setAttribute is only safe for a limited number of attributes. Dangerous attributes include any attribute that is a command execution context, such as onclick or onblur. Examples of safe attributes includes align, alink, alt, bgcolor, border, cellpadding, cellspacing, class, color, cols, colspan, coords, dir, face, height, hspace, ismap, lang, marginheight, marginwidth, multiple, nohref, noresize, noshade, nowrap, ref, rel, rev, rows, rowspan, scrolling, shape, span, summary, tabindex, title, usemap, valign, value, vlink, vspace, width.&amp;lt;br/&amp;gt;&lt;br /&gt;
4. Avoid use of HTML rendering methods:&amp;lt;br/&amp;gt;&lt;br /&gt;
#&amp;lt;code&amp;gt;element.innerHTML = &amp;quot;...&amp;quot;; &amp;lt;/code&amp;gt;&lt;br /&gt;
#&amp;lt;code&amp;gt;element.outerHTML = &amp;quot;...&amp;quot;; &amp;lt;/code&amp;gt;&lt;br /&gt;
#&amp;lt;code&amp;gt;document.write(...); &amp;lt;/code&amp;gt;&lt;br /&gt;
#&amp;lt;code&amp;gt;document.writeln(...); &amp;lt;/code&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
5. Understand the dataflow of untrusted data through your JavaScript code.  If you do have to use the methods above remember to HTML and then JavaScript encode the untrusted data (Stefano Di Paola).&amp;lt;br/&amp;gt;&lt;br /&gt;
6. There are numerous methods which implicitly eval() data passed to it.  Make sure that any untrusted data passed to these methods is delimited with string delimiters and enclosed within a closure or JavaScript encoded to N-levels based on usage, and wrapped in a custom function.  Ensure to follow step 4 above to make sure that the untrusted data is not sent to dangerous methods within the custom function or handle it by adding an extra layer of encoding.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Utilizing an Enclosure (as suggested by Gaz)&amp;lt;/b&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The example that follows illustrates using closures to avoid double JavaScript encoding.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 setTimeout((function(param) { return function() {&lt;br /&gt;
          customFunction(param);&lt;br /&gt;
          }&lt;br /&gt;
 })(&amp;quot;&amp;lt;%=Encoder.encodeForJS(untrustedData)%&amp;gt;&amp;quot;), y);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The other alternative is using N-levels of encoding.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;N-Levels of Encoding&amp;lt;/b&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If your code looked like the following, you would need to only double JavaScript encode input data.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 setTimeout(&amp;quot;customFunction('&amp;lt;%=doubleJavaScriptEncodedData%&amp;gt;', y)&amp;quot;);&lt;br /&gt;
 function customFunction (firstName, lastName)&lt;br /&gt;
       alert(&amp;quot;Hello&amp;quot; + firstName + &amp;quot; &amp;quot; + lastNam);&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;doubleJavaScriptEncodedData&amp;lt;/code&amp;gt; has its first layer of JavaScript encoding reversed (upon execution) in the single quotes.  Then the implicit &amp;lt;code&amp;gt;eval()&amp;lt;/code&amp;gt; of &amp;lt;code&amp;gt;setTimeout()&amp;lt;/code&amp;gt; reverses another layer of JavaScript encoding to pass the correct value to &amp;lt;code&amp;gt;customFunction&amp;lt;/code&amp;gt;.  The reason why you only need to double JavaScript encode is that the &amp;lt;code&amp;gt;customFunction&amp;lt;/code&amp;gt; function did not itself pass the input to another method which implicitly or explicitly called &amp;lt;code&amp;gt;eval()&amp;lt;/code&amp;gt;.  If &amp;quot;firstName&amp;quot; was passed to another JavaScript method which implicitly or explicitly called eval() then &amp;lt;code&amp;gt;&amp;lt;%=doubleJavaScriptEncodedData%&amp;gt;&amp;lt;/code&amp;gt; above would need to be changed to &amp;lt;code&amp;gt;&amp;lt;%=tripleJavaScriptEncodedData%&amp;gt;&amp;lt;/code&amp;gt;.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
An important implementation note is that if the JavaScript code tries to utilize the double or triple encoded data in string comparisons, the value may be interpreted as different values based on the number of evals() the data has passed through before being passed to the if comparison and the number of times the value was JavaScript encoded.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If &amp;quot;A&amp;quot; is double JavaScript encoded then the following if check will return false.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = &amp;quot;doubleJavaScriptEncodedA&amp;quot;;  //\u005c\u0075\u0030\u0030\u0034\u0031&lt;br /&gt;
 if (x == &amp;quot;A&amp;quot;) {&lt;br /&gt;
    alert(&amp;quot;x is A&amp;quot;);&lt;br /&gt;
 } else if (x == &amp;quot;\u0041&amp;quot;) {&lt;br /&gt;
    alert(&amp;quot;This is what pops&amp;quot;);&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This brings up an interesting design point.  Ideally, the correct way to apply encoding and avoid the problem stated above is to server-side encode for the output context where data is introduced into the application.  Then client-side encode (using a JavaScript encoding library such as ESAPI4JS) for the individual subcontext (DOM methods) which untrusted data is passed to.  ESAPI4JS (located at http://bit.ly/9hRTLH) and jQuery Encoder (located at https://github.com/chrisisbeef/jquery-encoder/blob/master/src/main/javascript/org/owasp/esapi/jquery/encoder.js) are two client side encoding libraries developed by Chris Schmidt.&amp;lt;br/&amp;gt;&lt;br /&gt;
Here are some examples of how they are used:&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var input = &amp;quot;&amp;lt;%=Encoder.encodeForJS(untrustedData)%&amp;gt;&amp;quot;;  //server-side encoding&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 window.location = ESAPI4JS.encodeForURL(input);  //URL encoding is happening in JavaScript&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 document.writeln(ESAPI4JS.encodeForHTML(input));  //HTML encoding is happening in JavaScript&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It has been well noted by the group that any kind of reliance on a JavaScript library for encoding would be problematic as the JavaScript library could be subverted by attackers.  One option is to wait till ECMAScript 5 so the JavaScript library could support immutable properties.&amp;lt;br/&amp;gt;&lt;br /&gt;
Another option provided by Gaz (Gareth) was to use a specific code construct to limit mutability with anonymous clousures.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
An example follows:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 function escapeHTML(str) {&lt;br /&gt;
      str = str + &amp;quot;''&amp;quot;;&lt;br /&gt;
      var out = &amp;quot;''&amp;quot;;&lt;br /&gt;
      for(var i=0; i&amp;lt;str.length; i++) {&lt;br /&gt;
          if(str[i] === '&amp;lt;') {&lt;br /&gt;
              out += '&amp;amp;amp;lt;';&lt;br /&gt;
          } else if(str[i] === '&amp;gt;') {&lt;br /&gt;
              out += '&amp;amp;amp;gt;';&lt;br /&gt;
          } else if(str[i] === &amp;quot;'&amp;quot;) {&lt;br /&gt;
              out += '&amp;amp;amp;#39;'; &lt;br /&gt;
          } else if(str[i] === '&amp;quot;') {&lt;br /&gt;
              out += '&amp;amp;amp;quot;';                        &lt;br /&gt;
          } else {&lt;br /&gt;
              out += str[i];&lt;br /&gt;
          }&lt;br /&gt;
      }&lt;br /&gt;
      return out;                    &lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br/&amp;gt;Chris Schmidt has put together another implementation of a JavaScript encoder at http://yet-another-dev.blogspot.com/2011/02/client-side-contextual-encoding-for.html.  &amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
6. Limit the usage of dynamic untrusted data to right side operations.  And be aware of data which may be passed to the application which look like code (eg. &amp;lt;code&amp;gt;location&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;eval()&amp;lt;/code&amp;gt;).  (Achim)&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var x = &amp;quot;&amp;lt;%=properly encoded data for flow%&amp;gt;&amp;quot;;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you want to change different object attributes based on user input use a level of indirection.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Instead of: &amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 window[userData] = &amp;quot;moreUserData&amp;quot;;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Do the following instead:&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 if (userData===&amp;quot;location&amp;quot;) {&lt;br /&gt;
    window.location = &amp;quot;static/path/or/properly/url/encoded/value&amp;quot;;&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
7. When URL encoding in DOM be aware of character set issues as the character set in JavaScript DOM is not clearly defined (Mike Samuel).&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
8. Limit access to properties objects when using object[x] accessors. (Mike Samuel).  In other words use a level of indirection between untrusted input and specified object properties.&amp;lt;br/&amp;gt;&lt;br /&gt;
Here is an example of the problem when using map types:&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 var myMapType = {};&lt;br /&gt;
 myMapType[&amp;lt;%=untrustedData%&amp;gt;] = &amp;quot;moreUntrustedData&amp;quot;;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Although the developer writing the code above was trying to add additional keyed elements to the &amp;lt;code&amp;gt;myMapType&amp;lt;/code&amp;gt; object.  This could be used by an attacker to subvert internal and external attributes of the &amp;lt;code&amp;gt;myMapType&amp;lt;/code&amp;gt; object.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
9. Run your JavaScript in a ECMAScript 5 canopy or sand box to make it harder for your JavaScript API to be compromised (Gareth Heyes and John Stevens).&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
10. Don’t &amp;lt;code&amp;gt;eval()&amp;lt;/code&amp;gt; JSON to convert it to native JavaScript objects.  Instead use &amp;lt;code&amp;gt;JSON.toJSON()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;JSON.parse()&amp;lt;/code&amp;gt; (Chris Schmidt).&lt;br /&gt;
&lt;br /&gt;
=  Common Problems Associated with Mitigating DOM Based XSS =&lt;br /&gt;
==Complex Contexts==&lt;br /&gt;
In many cases the context isn’t always straightforward to discern.&amp;lt;br/&amp;gt;&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;a href=&amp;quot;javascript:myFunction('&amp;lt;%=untrustedData%&amp;gt;', 'test');&amp;quot;&amp;gt;Click Me&amp;lt;/a&amp;gt;&lt;br /&gt;
 ...&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 Function myFunction (url,name) {&lt;br /&gt;
     window.location = url;&lt;br /&gt;
 }&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, untrusted data started in the rendering URL context (&amp;lt;code&amp;gt;href&amp;lt;/code&amp;gt; attribute of an &amp;lt;code&amp;gt;&amp;lt;a&amp;gt;&amp;lt;/code&amp;gt; tag) then changed to a JavaScript execution context (&amp;lt;code&amp;gt;javascript:&amp;lt;/code&amp;gt; protocol handler) which passed the untrusted data to an execution URL subcontext (&amp;lt;code&amp;gt;window.location&amp;lt;/code&amp;gt; of myFunction).  Because the data was introduced in JavaScript code and passed to a URL subcontext the appropriate server-side encoding would be the following:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;a href=&amp;quot;javascript:myFunction('&amp;lt;%=Encoder.encodeForJS( &amp;amp;#x21a9;&lt;br /&gt;
               Encoder.encodeForURL(untrustedData))%&amp;gt;', 'test');&amp;quot;&amp;gt;Click Me&amp;lt;/a&amp;gt;&lt;br /&gt;
 ...&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Or if you were using ECMAScript 5 with an immutable JavaScript client-side encoding libraries you could do the following:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;amp;lt;!--server side URL encoding has been removed.  Now only JavaScript encoding on server side. --&amp;gt;&lt;br /&gt;
 &amp;lt;a href=&amp;quot;javascript:myFunction('&amp;lt;%=Encoder.encodeForJS(untrustedData)%&amp;gt;', 'test');&amp;quot;&amp;gt;Click Me&amp;lt;/a&amp;gt;&lt;br /&gt;
 ...&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 Function myFunction (url,name) {&lt;br /&gt;
     var encodedURL = ESAPI4JS.encodeForURL(url);  //URL encoding using client-side scripts&lt;br /&gt;
     window.location = encodedURL;&lt;br /&gt;
 }&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Inconsistencies of Encoding Libraries ==&lt;br /&gt;
There are a number of open source encoding libraries out there:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#[[ESAPI]]&lt;br /&gt;
#Apache Commons String Utils&lt;br /&gt;
#Jtidy&lt;br /&gt;
#Your company’s custom implementation.&lt;br /&gt;
&lt;br /&gt;
Some work on a black list while others ignore important characters like “&amp;lt;” and “&amp;gt;”.  ESAPI is one of the few which works on a whitelist and encodes all non-alphanumeric characters.&lt;br /&gt;
It is important to use an encoding library that understands which characters can be used to exploit vulnerabilies in their respective contexts. Misconceptions abound related to the proper encoding that is required.&lt;br /&gt;
&lt;br /&gt;
==Encoding Misconceptions==&lt;br /&gt;
Many security training curriculums and papers advocate the blind usage of HTML encoding to resolve XSS.  This logically seems to be prudent advice as the JavaScript parser does not understand HTML encoding.  However, if the pages returned from your web application utilize a content type of “text/xhtml” or the file type extension of “*.xhtml” then HTML encoding may not work to mitigate against XSS.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example: &amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 &amp;amp;amp;#x61;lert(1);&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt; &lt;br /&gt;
&lt;br /&gt;
The HTML encoded value above is still executable.  If that isn’t enough to keep in mind, you have to remember that encodings are lost when you retrieve them using the value attribute of a DOM element. &amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Let’s look at the sample page and script:&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;form name=&amp;quot;myForm&amp;quot; ...&amp;gt;&lt;br /&gt;
   &amp;lt;input type=&amp;quot;text&amp;quot; name=&amp;quot;lName&amp;quot; value=&amp;quot;&amp;lt;%=Encoder.encodeForHTML(last_name)%&amp;gt;&amp;quot;&amp;gt;&lt;br /&gt;
 ...&lt;br /&gt;
 &amp;lt;/form&amp;gt;&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 var x = document.myForm.lName.value;  //when the value is retrieved the encoding is reversed&lt;br /&gt;
 document.writeln(x);  //any code passed into lName is now executable.&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally there is the problem that certain methods in JavaScript which are usually safe can be unsafe in certain contexts.&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Usually Safe Methods==&lt;br /&gt;
&lt;br /&gt;
One example of an attribute which is thought to be safe is innerText.  Some papers or guides advocate its use as an alternative to innerHTML to mitigate against XSS in innerHTML.  However, depending on the tag which innerText is applied, code can be executed. Also note, innerText is non standard and is not supported in FireFox&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
 &amp;lt;script&amp;gt;&lt;br /&gt;
 var tag = document.createElement(&amp;quot;script&amp;quot;);&lt;br /&gt;
 tag.innerText = &amp;quot;&amp;lt;%=untrustedData%&amp;gt;&amp;quot;;  //executes code&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Authors and Contributing Editors  =&lt;br /&gt;
&lt;br /&gt;
Jim Manico - jim[at]owasp.org&amp;lt;br/&amp;gt;&lt;br /&gt;
Abraham Kang - abraham.kang[at]owasp.org&amp;lt;br/&amp;gt;&lt;br /&gt;
Gareth (Gaz) Heyes&amp;lt;br/&amp;gt;&lt;br /&gt;
Stefano Di Paola&amp;lt;br/&amp;gt;&lt;br /&gt;
Achim Hoffmann - achim[at]owasp.org&amp;lt;br/&amp;gt;&lt;br /&gt;
Robert (RSnake) Hansen&amp;lt;br/&amp;gt;&lt;br /&gt;
Mario Heiderich&amp;lt;br/&amp;gt;&lt;br /&gt;
John Steven&amp;lt;br/&amp;gt;&lt;br /&gt;
Chris (Chris BEEF) Schmidt&amp;lt;br/&amp;gt;&lt;br /&gt;
Mike Samuel&amp;lt;br/&amp;gt;&lt;br /&gt;
Jeremy Long&amp;lt;br/&amp;gt;&lt;br /&gt;
Eduardo (SirDarkCat) Alberto Vela Nava&amp;lt;br/&amp;gt;&lt;br /&gt;
Jeff Williams - jeff.williams[at]owasp.org &amp;lt;br/&amp;gt;&lt;br /&gt;
Erlend Oftedal&lt;br /&gt;
| valign=&amp;quot;top&amp;quot;  style=&amp;quot;padding-left:25px;width:300px;border-right: 1px dotted gray;padding-right:25px;&amp;quot; |&lt;br /&gt;
&lt;br /&gt;
== Other Cheatsheets ==&lt;br /&gt;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yozo</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Clickjacking_Defense_Cheat_Sheet&amp;diff=218354</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=218354"/>
				<updated>2016-06-29T08:59:05Z</updated>
		
		<summary type="html">&lt;p&gt;Yozo: typo(symantics)&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;div style=&amp;quot;width:100%;height:160px;border:0,margin:0;overflow: hidden;&amp;quot;&amp;gt;[[File:Cheatsheets-header.jpg|link=]]&amp;lt;/div&amp;gt;&lt;br /&gt;
&amp;lt;br/&amp;gt;Last revision (mm/dd/yy): '''{{REVISIONMONTH}}/{{REVISIONDAY}}/{{REVISIONYEAR}}''' &lt;br /&gt;
= Introduction  =&lt;br /&gt;
 __TOC__{{TOC hidden}}&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 Content Security Policy frame-ancestors directive =&lt;br /&gt;
The frame-ancestors directive can be used in a Content-Security-Policy HTTP response header 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;
frame-ancestors allows a site to authorize multiple domains using the normal Content Security Policy semantics.&lt;br /&gt;
&lt;br /&gt;
See https://w3c.github.io/webappsec-csp/document/#directive-frame-ancestors for further details&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Limitations ===&lt;br /&gt;
* '''Browser support:''' frame-ancestors is not supported by all the major browsers yet.&lt;br /&gt;
* '''X-Frame-Options takes priority:''' [https://w3c.github.io/webappsec/specs/content-security-policy/#frame-ancestors-and-frame-options Section 7.7.1 of the CSP Spec] says X-Frame-Options should be ignored if frame-ancestors is specified, but Chrome 40 &amp;amp; Firefox 35 ignore the frame-ancestors directive and follow the X-Frame-Options header instead.&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;
Set the x-frame-options header for all responses containing HTML content. The possible values are &amp;quot;DENY&amp;quot; or &amp;quot;SAMEORIGIN&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
    DENY will block any site (regardless of domain) from framing the content.&lt;br /&gt;
    SAMEORIGIN will block all sites from framing the content, except sites within the same domain.&lt;br /&gt;
&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 header:&lt;br /&gt;
* &amp;lt;b&amp;gt;DENY&amp;lt;/b&amp;gt;, which prevents any domain from framing the content. The &amp;quot;DENY&amp;quot; setting is recommended unless a specific need has been identified for framing.&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) '''Check Limitations Below''' this will fail open if the browser does not support it.&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;[http://blog.chromium.org/2010/01/security-in-depth-new-security-features.html 4.1.249.1042]&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;[https://code.google.com/p/chromium/issues/detail?id=129139 Not supported/Bug reported]&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;[https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options?redirectlocale=en-US&amp;amp;redirectslug=The_X-FRAME-OPTIONS_response_header 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;[http://blogs.msdn.com/b/ie/archive/2009/01/27/ie8-security-part-vii-clickjacking-defenses.aspx 8.0]&amp;lt;/td&amp;gt; &amp;lt;td&amp;gt;[http://erlend.oftedal.no/blog/tools/xframeoptions/ 9.0]&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;[http://www.opera.com/docs/specs/presto26/#network 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;[http://www.zdnet.com/blog/security/apple-safari-jumbo-patch-50-vulnerabilities-fixed/3541 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;
* [http://erlend.oftedal.no/blog/tools/xframeoptions/ X-Frame-Options Compatibility Test] - Check this for the LATEST browser support info for the X-Frame-Options header&lt;br /&gt;
&lt;br /&gt;
=== Implementation ===&lt;br /&gt;
&lt;br /&gt;
To implement this protection, you need to add the X-Frame-Options HTTP Response header to any page that you want to protect from being clickjacked via framebusting. One way to do this is to add the HTTP Response 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;
=== Common Defense Mistakes ===&lt;br /&gt;
Meta-tags that attempt to apply the X-Frame-Options directive DO NOT WORK. For example, &amp;lt;meta http-equiv=&amp;quot;X-Frame-Options&amp;quot; content=&amp;quot;deny&amp;quot;&amp;gt;) will not work. You must apply the X-FRAME-OPTIONS directive as HTTP Response Header as described above.&lt;br /&gt;
&lt;br /&gt;
=== Limitations ===&lt;br /&gt;
&lt;br /&gt;
* '''Per-page policy specification''' 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;
* '''Problems with multi-domain sites''' 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;
* '''ALLOW-FROM browser support''' The ALLOW-FROM option is a relatively recent addition (circa 2012) and may not be supported by all browsers yet.  BE CAREFUL ABOUT DEPENDING ON ALLOW-FROM. If you apply it and the browser does not support it, then you will have NO clickjacking defense in place.&lt;br /&gt;
* '''Multiple options not supported''' There is no way to allow the current site and a 3rd party site to frame the same response -- browsers only honour one X-Frame-Options header and only one value on that header.&lt;br /&gt;
* '''Nested Frames don't work with SAMEORIGIN and ALLOW-FROM''' In the following situation, the http://framed.invalid/child frame does not load because ALLOW-FROM applies to the top-level browsing context, not that of the immediate parent. The solution is to use ALLOW-FROM in both the parent and child frames (but this prevents the child frame loading if the //framed.invalid/parent page is loaded as the top level document).&lt;br /&gt;
 +-//friendlysite.invalid-----------------------+&lt;br /&gt;
 |                                              |&lt;br /&gt;
 | +-//framed.invalid/parent------------------+ |&lt;br /&gt;
 | |                                          | |&lt;br /&gt;
 | | ALLOW-FROM http://friendlysite.invalid | |&lt;br /&gt;
 | |                                          | |&lt;br /&gt;
 | | +-//framed.invalid/child--------+        | |&lt;br /&gt;
 | | |                               |        | |&lt;br /&gt;
 | | | SAMEORIGIN                    |        | |&lt;br /&gt;
 | | |                               |        | |&lt;br /&gt;
 | | +-------------------------------+        | |&lt;br /&gt;
 | +------------------------------------------+ |&lt;br /&gt;
 +----------------------------------------------+&lt;br /&gt;
* '''X-Frame-Options Deprecated''' While the X-Frame-Options header is supported by the major browsers, it was never standardized and has been deprecated in favour of the frame-ancestors directive from the CSP Level 2 specification.&lt;br /&gt;
* '''Proxies''' 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;
= Insecure Non-Working Scripts DO NOT USE =&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;
&lt;br /&gt;
{{Cheatsheet_Navigation_Body}}&lt;br /&gt;
&lt;br /&gt;
[[Category:Cheatsheets]]&lt;/div&gt;</summary>
		<author><name>Yozo</name></author>	</entry>

	</feed>