====== Security - XSS (Cross Site Scripting) - Preventing XSS ====== ===== Methods of preventing XSS ===== Recall that an XSS attack is a type of code injection: user input is mistakenly interpreted as malicious program code. In order to prevent this type of code injection, secure input handling is needed. For a web developer, there are two fundamentally different ways of performing secure input handling: * **Encoding**, which escapes the user input so that the browser interprets it only as data, not as code. * **Validation**, which filters the user input so that the browser interprets it as code without malicious commands. While these are fundamentally different methods of preventing XSS, they share several common features that are important to understand when using either of them: * **Context**// Secure input handling needs to be performed differently depending on where in a page the user input is inserted.// * **Inbound-outbound**// Secure input handling can be performed either when your website receives the input (inbound) or right before your website inserts the input into a page (outbound).// * **Client-server**// Secure input handling can be performed either on the client-side or on the server-side, both of which are needed under different circumstances.// Before explaining in detail how encoding and validation work, we will describe each of these points. ==== Input handling contexts ==== There are many contexts in a web page where user input might be inserted. For each of these, specific rules must be followed so that the user input cannot break out of its context and be interpreted as malicious code. Below are the most common contexts: ^Context^Example code^ |HTML element content|
userInput
| |HTML attribute value|| |URL query value|http://example.com/?parameter=userInput| |CSS value|color: userInput| |JavaScript value|var name = "userInput";| === Why context matters === In all of the contexts described, an XSS vulnerability would arise if user input were inserted before first being encoded or validated. An attacker would then be able to inject malicious code by simply inserting the closing delimiter for that context and following it with the malicious code. For example, if at some point a website inserts user input directly into an HTML attribute, an attacker would be able to inject a malicious script by beginning his input with a quotation mark, as shown below: |Application code|| |Malicious string|">">| This could be prevented by simply removing all quotation marks in the user input, and everything would be fine—but only in this context. If the same input were inserted into another context, the closing delimiter would be different and injection would become possible. For this reason, secure input handling always needs to be tailored to the context where the user input will be inserted. ==== Inbound/outbound input handling ==== Instinctively, it might seem that XSS can be prevented by encoding or validating all user input as soon as your website receives it. This way, any malicious strings should already have been neutralized whenever they are included in a page, and the scripts generating HTML will not have to concern themselves with secure input handling. The problem is that, as described previously, user input can be inserted into several contexts in a page. There is no easy way of determining when user input arrives which context it will eventually be inserted into, and the same user input often needs to be inserted into different contexts. Relying on inbound input handling to prevent XSS is thus a very brittle solution that will be prone to errors. (The deprecated [[http://php.net/manual/en/security.magicquotes.php|"magic quotes"]] feature of PHP is an example of such a solution.) Instead, outbound input handling should be your primary line of defense against XSS, because it can take into account the specific context that user input will be inserted into. That being said, inbound validation can still be used to add a secondary layer of protection, as we will describe later. ==== Where to perform secure input handling ==== In most modern web applications, user input is handled by both server-side code and client-side code. In order to protect against all types of XSS, secure input handling must be performed in both the server-side code and the client-side code. * In order to protect against traditional XSS, secure input handling must be performed in server-side code. This is done using any language supported by the server. * In order to protect against DOM-based XSS where the server never receives the malicious string (such as the fragment identifier attack described earlier), secure input handling must be performed in client-side code. This is done using JavaScript. Now that we have explained why context matters, why the distinction between inbound and outbound input handling is important, and why secure input handling needs to be performed in both client-side code and server-side code, we will go on to explain how the two types of secure input handling (encoding and validation) are actually performed. ===== Encoding ===== Encoding is the act of escaping user input so that the browser interprets it only as data, not as code. The most recognizable type of encoding in web development is HTML escaping, which converts characters like < and > into < and >, respectively. The following pseudocode is an example of how user input could be encoded using HTML escaping and then inserted into a page by a server-side script: print "" print "Latest comment: " print encodeHtml(userInput) print "" If the user input were the string , the resulting HTML would be as follows: Latest comment: <script>...</script> Because all characters with special meaning have been escaped, the browser will not parse any part of the user input as HTML. ==== Encoding in client-side and server-side code ==== When performing encoding in your client-side code, the language used is always JavaScript, which has built-in functions that encode data for different contexts. When performing encoding in your server-side code, you rely on the functions available in your server-side language or framework. Due to the large number of languages and frameworks available, this tutorial will not cover the details of encoding in any specific server-side language or framework. However, familiarity with the encoding functions used on the client-side in JavaScript is useful when writing server-side code as well. === Encoding on the server-side === ^Language^Encoding^ |asp|Server.HTMLEncode(string)| |c#|Server.URLEncode()| |php|htmlentities($str);| |php|rawurlencode($str);| |php|urlencode($str);| === Encoding on the client-side === When encoding user input on the client-side using JavaScript, there are several built-in methods and properties that automatically encode all data in a context-aware manner: ^Context^Method/property^ |HTML element content|node.textContent = userInput| |HTML attribute value|element.setAttribute(attribute, userInput)// or// element[attribute] = userInput| |URL query value|window.encodeURIComponent(userInput)| |CSS value|element.style.property = userInput| The last context mentioned above (JavaScript values) is not included in this list, because JavaScript provides no built-in way of encoding data to be included in JavaScript source code. ==== Limitations of encoding ==== Even with encoding, it will be possible to input malicious strings into some contexts. A notable example of this is when user input is used to provide URLs, such as in the example below: document.querySelector('a').href = userInput Although assigning a value to the href property of an anchor element automatically encodes it so that it becomes nothing more than an attribute value, this in itself does not prevent the attacker from inserting a URL beginning with "javascript:". When the link is clicked, whatever JavaScript is embedded inside the URL will be executed. Encoding is also an inadequate solution when you actually want the user to define part of a page's code. An example is a user profile page where the user can define custom HTML. If this custom HTML were encoded, the profile page could consist only of plain text. In situations like these, encoding has to be complemented with validation, which we will describe next. ===== Validation ===== Validation is the act of filtering user input so that all malicious parts of it are removed, without necessarily removing all code in it. One of the most recognizable types of validation in web development is allowing some HTML elements (such as and ) but disallowing others (such as With a properly defined CSP policy, the browser would not load and execute malicious‑script.js because http://attacker/ would not be in the set of trusted sources. Even though the website failed to securely handle user input in this case, the CSP policy prevented the vulnerability from causing any harm. Even if the attacker had injected the script code inline rather than linking to an external file, a properly defined CSP policy disallowing inline JavaScript would also have prevented the vulnerability from causing any harm. ==== How to enable CSP ==== By default, browsers do not enforce CSP. To enable CSP on your website, pages must be served with an additional HTTP header: Content‑Security‑Policy. Any page served with this header will have its security policy respected by the browser loading it, provided that the browser supports CSP. Since the security policy is sent with every HTTP response, it is possible for a server to set its policy on a page-by-page basis. The same policy can be applied to an entire website by providing the same CSP header in every response. The value of the Content‑Security‑Policy header is a string defining one or more security policies that will take effect on your website. The syntax of this string will be described next. The example headers in this section use newlines and indentation for clarity; this should not be present in an actual header. ==== Syntax of CSP ==== The syntax of a CSP header is as follows: Content‑Security‑Policy: directive source‑expression, source‑expression, ...; directive ...; ... This syntax is made up of two elements: * **Directives** are strings specifying a type of resource, taken from a predefined list. * **Source expressions** are patterns describing one or more servers that resources can be downloaded from. For every directive, the given source expressions define which sources can be used to download resources of the respective type. === Directives === The directives that can be used in a CSP header are as follows: * connect‑src * font‑src * frame‑src * img‑src * media‑src * object‑src * script‑src * style‑src In addition to these, the special directive default‑src can be used to provide a default value for all directives that have not been included in the header. === Source expressions === The syntax of a source expression is as follows: * protocol://host‑name:port‑number// The host name can start with *., which means that any subdomain of the provided host name will be allowed. Similarly, the port number can be *, which means that all ports will be allowed. Additionally, the protocol and port number can be omitted. Finally, a protocol can be given by itself, which makes it possible to require that all resources be loaded using HTTPS. In addition to the syntax above, a source expression can alternatively be one of four keywords with special meaning (quotes included): * **'none'**// Allows no resources.// * **'self'**// Allows resources from the host that served the page.// * **'unsafe‑inline**'// Allows resources embedded in the page, such as inline