Analysis and Prevention of XSS

Source: Internet
Author: User

XSS, also known as Cross site Scripting, is the focus of XSS not across sites, but in the execution of scripts. With the development of Web front-end applications, XSS vulnerabilities are especially easy to be overlooked by developers and can eventually lead to leaks of personal information. Today, there is still no unified way to detect XSS vulnerabilities, but for front-end developers, still can be avoided in some subtle, so this article will be combined with the author's learning and experience to summarize the solution and avoid some of the scenarios, and briefly from the WebKit kernel analysis browser kernel for XSS to avoid the effort, Learn about the underlying infrastructure's contribution to preventing XSS.

Types and characteristics of XSS

The goal of XSS is to have the JS files of other sites run on the target site, which occurs primarily during the page rendering phase. Some unintended scripting behavior occurred at this stage, either from user input or from other JS files outside the domain. The origin of XSS originates from user input, so XSS is divided into three types based on the form of user input data, when XSS is triggered, and whether there is a back-end server involvement, namely, reflective XSS, persistent XSS, and Dom XSS.

Reflection Type XSS

Reflective XSS, as the name implies, is the process of "reflection." The triggering of a reflective XSS has a backend involvement, and the reason why XSS is triggered is because the backend parses the data URI encoding of the user's XSS-type script or script in front-end input, and the backend resolves the user input processing and returns to the front end, which is parsed by the browser to trigger an XSS vulnerability. Therefore, if you want to avoid reflective XSS, you must need the coordination of the backend, in the back-end parsing the front-end data when the relevant string detection and escape processing, while the front-end may also be for the user's data to do Excape escape, to ensure the reliability of the data source.

E.x.
localhost/test.php

<?php echo $_GET[‘name‘] ?>

If the page is accessed through Localhost/test.php?name=alert (document.cookie), then the processing of the backend server causes the occurrence of reflective XSS.

Similarly, strings encoded by passing in the data URI can also cause XSS, such as Localhost/test.php?name=data:text/html;charset=utf-8;base64, Phnjcmlwdd5hbgvydchkb2n1bwvudc5jb29rawuppc9zy3jpchq+ will cause the same problem. The encoded string is "alert (document.cookie)" after decoding.

Long-lasting XSS

Persistent XSS still requires a service-side engagement, which differs from reflective XSS in the persistence of XSS code (hard disk, database). In the case of reflective XSS, the back-end server simply saves the XSS code in memory and does not persist, so the user is required to enter the relevant XSS code each time the reflective XSS is triggered, whereas persistent XSS only enters the relevant XSS code for the first time, and is saved in the database. When the next time the data from the database is not added in the front end of the string detection and Excape transcoding, will cause XSS, and due to the vulnerability of the hidden and persistent characteristics of large-scale applications developed by many people and cross-application data acquisition caused by a wide range of XSS vulnerabilities, particularly harmful. This requires developers to develop a good sense of web front-end security, not only can not trust the user's input, and can not fully trust the data stored in the database (that is, the back-end developers ignore the data security detection). There is no good solution for persistent XSS, which can only be guaranteed by the developer. Of course, the rules are developed by developers, if the user experience is ignored, you can develop a rigorous set of input rules, related keywords and input types (such as data URI detection, prohibit input) detection and suppression, as far as possible to avoid the possibility of users to find XSS vulnerability, from the source processing.

DOM XSS

DOM XSS is triggered entirely in the front-end browser, without the involvement of the server, so this is the "site" of the front-end development engineer and deserves our attention.

E.x.
Localhost/test.html

<script>eval(‘alert(location.hash.slice("1"))‘);</script>

If you access Localhost/test.html#document.cookie, it triggers the simplest dom XSS that can compromise very large. It has no server-side participation, only by the user's input and unsafe script execution, of course, in this case is simply the simplest case, if the user input string "or text/html format data URI, it is more difficult to detect, but also more harmful, hackers easier to operate.

Therefore, the prevention of Dom XSS requires front-end developers to be wary of all user input data, so that the data excape escape, while minimizing the direct output of HTML content; no eval, new Function, SetTimeout and other more hack way to parse the external station data and Execute JS script, prohibit inline event handler, if you need to get the results of the outbound script in consideration of security, you can use the front-end sandbox (set up an empty iframe execution script, The IFRAME cannot manipulate the current Document Object model), and the worker thread is done in a way that guarantees the security of the DOM.

XSS Prevention

XSS vulnerabilities are difficult to detect, but for web security still needs to be avoided, this section will address three types of XSS vulnerabilities and provide more enlightening advice from other perspectives.

For reflective XSS, also mentioned in the corresponding subsection, the need for the service side and the front-end joint prevention, for the user input data parsing and escaping, for the front-end development, is good at using escape, for the data URI content to do regular judgment, prohibit the user input non-display information, such as MIME type " Text/html,text/plain "type of content.
For storage-type XSS, processing is still similar to reflective XSS.
For Dom XSS, you need to be cautious. Because the cause of XSS is the input of the user, in the front-end, you need to pay special attention to the following user input sources:


Document. Url
Location.hash,
Location.research,
Document.referrer (This should be especially noted here, although the referrer property can be used to avoid csrf, but can trigger XSS attacks),
XHR return value (cross-domain return value),
form forms and various input boxes

For the above input sources, it is necessary to do relative detection and escape. After getting the data from the input sources above, there may be a variety of DOM operations or purely JS calculations, which are the culprits that really trigger XSS:


1, direct output HTML content
Document.body.innerHTML = ...
Document.body.outterHTML = ...
document.write ()
2,html Tag Inline Script


3, execute script directly
Eval
New Function () {}
SetTimeout ()
Window.execscript ()
4. Open a new page triggering XSS (including reflective XSS and persistent XSS)
window.open ()
Location.href = ...
Location.hash = ...

When manipulating the DOM, you need to pay particular attention to the above operations and string escapes for possible XSS needs. Of course, some of the operations are completely avoidable: for innerHTML splicing operations, you need to abandon jquery-chained operations and use front-end templates such as arttemplate, or you can choose to use reliable data rendered by the backend to ensure both performance and security For HTML tags Embedded js, you need to completely avoid, this is a very low fault tolerance implementation, directly execute the script and parse the data, you need to avoid the eval and new Funciton operations, instead of Json.parse, IFRAME sandbox and webworker execution , and XSS for opening a new page will require the developer to take control of itself.

An additional attempt

The above mentioned is only the corresponding XSS avoidance scheme, but if you look at the global, standing in the browser angle, it will become more steady. At this stage, most browsers support multiple security policies, such as sandbox mechanisms, cross-domain mechanisms, cross-document messages, and CSPs. Here, we focus on the CSP (content security Policy), also known as the Contents Secure Protocol (CSP), which uses the HTTP header of the service-side response to develop the loading domain of web-related resources, which are limited to JS files, CSS files, image, IFrame, Fonts and other objects (such as object, applets).

The CSP is made by the server via the HTTP header, with a total of three types for historical reasons, three of which are only compatibility differences, and for Chrome, we only need to focus on the Content-security-policy head. The CSP header defines the following rules:
Content-security-policy: Name value; Name value; Name value;

The specific instruction name is as follows:


Specification of instruction values such as:

Therefore, if we want to avoid XSS attacks, we can qualify the source domain of the script, such as:
Content-security-policy:default-src ' self ' ajax.googleapis.com;
This way, other scripts that are not in the domain and in the ajax.googleapis.com domain are not loaded, and XSS is avoided.

One thing to emphasize here is that the default CSP prohibits execution of script blocks, suppresses inline event handlers, suppresses inline styles, and disables eval and new functions. For inline script code blocks and inline styles, the header of the CSP can be set, such as content-security-policy:default-src ' self '; Script-src ' Unsafe-inline ';.

The CSP has a directive to note that Report-uri, which sends the error message proactively to the modified CGI (Sevlet), is used for the administrator's unified control. The Report-uri property will be covered later in this article.

XSS components in the WebKit

XSS attacks occur mainly in the rendering of the page, when the browser's rendering engine gets to the page and start parsing, it is possible to perform security checks at this stage, the specific time node is after lexical analysis for each token filter.

In WebKit, after the token is parsed by htmldocumentparser, it is filtered using xssauditor, which is executed in Filtertoken, not only for token name, but also for the monitoring focus. In the WebKit to use the blacklist mechanism, focusing on ",,," to do a key troubleshooting, when the relevant hidden trouble, generate relevant information Xssinfo, by Xssauditordelegate class sent to the corresponding CGI, the address of the CGI is the command value in the CSP Report-uri, Of course, you can also manually set this value.

By default, Xssauditor is enabled, but there are a variety of xssauditor when it discovers XSS behavior, which can be configured, which involves HTTP header x-xss-protection. The head is not a specification for the Xssauditor and IETF, and is a non-standard implementation that customizes the related behavior of the header by assigning a value to it.

By default, Xssauditor is in rewrite mode (JS code is in non-executable state), that is x-xss-protection:1, if you want to disable Xssauditor, you can x-xss-protection:0 When set to X-xss-protection:1;mode=block, the page will be blocked when the xssauditor is in effect, and a blank page is presented to the user; if set to x-xss-protection:1;report= ..., The relevant statistics are sent to the Report-uri defined in the CSP. Xssauditor cannot completely avoid XSS, but after all, it provides a layer of checking on the browser level, guaranteeing its reliability from the HTML tag.

Summarize

XSS vulnerabilities are difficult to find, but as developers need to avoid creating XSS vulnerabilities in detail, and for the use of CSP specifications and WebKit xssauditor mechanisms, we should not rely on them to solve XSS, after all, not all pages can tolerate the strict CSP, The xssauditor mechanism is also for Chrome only, and there are multiple bypass bypass checks, such as through various HTML entity encodings, URL encodings, and JS encodings. Therefore, we still need people-oriented, standardize development habits, improve the Web front-end security awareness.

Analysis and Prevention of XSS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.