What is XSS?

XSS is known for cross-site Scripting, but it’s called CSS. Cascading Style Sheets (CSS) is well known, but X sounds like Cross, so change the name to XSS

Get to the point that XSS is a code injection attack, usually refers to the use of web development with holes, through clever method to inject malicious code instruction to the web page, the malicious code without filtering, code together with normal web site, the browser can’t distinguish what script is credible, lead to a malicious script is executed.

XSS is the most common Web application security vulnerability. As it is executed directly on the user’s terminal, malicious codes can directly obtain user information such as cookies and sessionIDS, thus compromising data security or using these information to impersonate users to launch the request defined by the attacker to the website.



XSS classification

According to attack sources, XXS attacks can be classified into storage, reflection and DOM attacks.

Storage type

Storage XSS attack steps:

  1. The attacker submits malicious code to the target websiteThe databaseIn the.
  2. The user opens the target site when the siteThe service sidewillMalicious codefromDatabase retrievalThe concatenation is returned to the browser in HTML.
  3. The user’s browser receives the response, parses it and executes it mixed in with malicious code.
  4. Malicious code steals user data and sends it to the attacker’s website, or impersonates the user’s behavior and calls the target website interface to perform the operations specified by the attacker.

A common scenario is that an attacker writes an article or comment on a community or forum that contains malicious JavaScript code. After the article or comment is published, all users who access the article or comment will execute the malicious JavaScript code in their browser. Such attacks are common on web features with user-saved data, such as forum posts and product reviews.

Example: When the user clicks the submit button to submit input information to the server, the server saves the input through the userInput variable.

<! -- HTML fragment -->
<h2>Tests stored XSS attacks</h2>
<input type="text" id="input">
<button id="btn">submit</button>   
<script type="text/javascript">
    const input = document.getElementById('input');
    const btn = document.getElementById('btn');
    let val;
    input.addEventListener('change'.(e) = > {
        val = e.target.value;
    }, false);
    btn.addEventListener('click'.(e) = > {
        fetch('http://localhost:8008/submit', {
            method: 'POST'.body: val
        });
    }, false);
</script>
Copy the code
/ / Nodejs code
const http = require('http');
let userInput = ' ';
function handleReequest(req, res) {
    const method = req.method;
    res.setHeader('Access-Control-Allow-Origin'.The '*');
    res.setHeader('Access-Control-Allow-Headers'.'Content-Type')
    if (method === 'POST' && req.url === '/submit') {
        let body = ' ';
        req.on('data'.chunk= > {
            body += chunk;
        });
        req.on('end'.() = > {
            if (body) {
                userInput = body;
            }
            res.end();
        });
    } else {
        res.writeHead(200, {'Content-Type': 'text/html; charset=UTF-8'}); res.write(userInput); res.end(); }}const server = new http.Server();
server.listen(8008.'127.0.0.1');
server.on('request', handleReequest);
Copy the code

As shown below:When the user passes http://localhost:8008/${id}When accessed, the server returns the content corresponding to the ID. If a user enters malicious script content, the malicious script will be executed on the browser side when other users access the content:

reflective

Attack steps of reflective XSS:

  1. The attacker structureMake a special URL, which contains malicious code.
  2. The userOpen the URL with malicious codeThe web siteThe service sideThe malicious code is taken from the URL, spliced together in HTML and returned to the browser.
  3. When the user’s browser receives the response, it parses it and executes the malicious code mixed in.
  4. Malicious code steals user data and sends it to the attacker’s website, or impersonates the user’s behavior and calls the target website interface to perform the operations specified by the attacker.

Example: The address of a malicious link points to http://127.0.0.1:8008//? Test = 1 & request = 2.

As shown below:Then, I start a simple Node service to handle the request for malicious links as follows:

// Create a nodeJS server
let http =require('http');

let app = http.createServer((req,res) = >{
	// req: request object, containing some query parameters, request body, request path, cookie request field..
	// res: response object
	res.writeHead(200, {'Content-Type': 'text/html; charset=UTF-8'});
	res.write('');
})

// Listen on the port
app.listen(8008.() = >{
	console.log('the server running at http://127.0.0.1:8008');
})
Copy the code

When a user clicks a malicious link, the page is redirected to the page prepared by the attacker, and the JS script is executed on the attacker’s page, resulting in a reflective XSS attack.

Reflective XSS vulnerabilities are common in functions that pass parameters through urls, such as website search, jump, etc.

Because users need to take the initiative to open malicious URL to take effect, attackers often combine a variety of means to induce users to click. Reflective XSS can also be triggered by the contents of a POST, but the trigger condition is more stringent (the form submission page needs to be constructed and the user is directed to click), so it is very rare.

The DOM model

DOM XSS attack steps:

  1. The attacker constructsSpecial URL, which contains malicious code.
  2. The user opens a URL with malicious code.
  3. The user’s browser receives the response and parses it.The front-end JavaScript takes the malicious code from the URL and executes it.
  4. Malicious code steals user data and sends it to the attacker’s website, or impersonates the user’s behavior and calls the target website interface to perform the operations specified by the attacker.

Such as:

<h2>Test dom-type XSS attacks</h2>
<input type="text" id="input">
<button id="btn">submit</button>  
<div id="div"></div>
<script type="text/javascript">
    const input = document.getElementById('input');
    const btn = document.getElementById('btn');
    const div = document.getElementById('div');
    let val;
    input.addEventListener('change'.(e) = > {
        val = e.target.value;
    }, false);
    btn.addEventListener('click'.() = > {
        div.innerHTML = `<a href=${val}> Malicious link </a> '
    }, false);
</script>
Copy the code

After clicking the submit button, a link is inserted on the current page with the address of the user’s input. If the user constructs:<a href onlick="alert(/ DOM XSS attack /)">At this point, the user clicks the generated link and the corresponding script is executed. The effect picture is as follows:URL parameter constructed in dom-type XSS attackDon’t send it to the server, can achieve the effect of bypassing WAF and avoiding the detection of the server, and the malicious code is taken out and executed by the browserSecurity holes in the front-end JavaScript itselfAnd theStorage XSS and reflection XSSBelong to theSecurity vulnerabilities on the server.



Hazards of XSS attacks

  1. Embezzle cookies to achieve passwer-less login, steal all kinds of user accounts, such as machine login accounts, user online banking accounts, all kinds of administrator accounts
  2. Cooperate with CSRF attacks to complete malicious requests and control enterprise data, including the ability to read, tamper with, add, and delete sensitive enterprise data
  3. Illegal money transfers, forced e-mails
  4. Control the victim’s machine to launch attacks on other sites
  5. Using JS or CSS to destroy the normal structure and style of the page;



XSS attack prevention

XSS attacks have two main elements:

  1. The attackerSubmitting malicious code.
  2. Browser executionMalicious code.

The input filter

  1. Filtering input from the front end and then submitting it to the back end does not prevent an attacker from submitting malicious code once they bypass the front end and construct the request directly.
  2. The back end filters the input before writing it to the database, and there’s a problem with that. If the user input is escaped, the front end will display the escaped content, which may be HTML directly, which may be returned by the backing, to the value of the JS variable, and the front end will get the escaped string

So, input filtering can solve certain XSS problems in some cases, but it introduces a lot of uncertainty and garble, so we want to protect against XSS by preventing browsers from executing malicious code.

Reliable input validation for all user-submitted content. These submissions include urls, query keywords, HTTP headers, POST data, and so on. Only accept characters within the length range you specify, in the appropriate format, that you want. Block, filter, or ignore anything else.

Protects against stored and reflective XSS attacks

Both stored and reflective XSS attacks are executed by the browser after malicious code is taken out by the server and inserted into the response HTML. The attacker deliberately writes “data” embedded in the code.

There are two common practices:

  1. Change to pure front-end rendering, separating code from data.
  2. Fully escape HTML.

Pure front-end rendering process:

  1. The browser first loads a static HTML that does not contain any business-related data.
  2. The browser then executes the JavaScript in the HTML.
  3. JavaScript loads the business data through Ajax and calls the DOM API to update it to the page.

We explicitly tell the browser whether to set the following content:.innertext,.setAttribute,.style, etc. This way the browser can tell what type of code it is about to execute and can’t easily be fooled. However, for pages with high performance requirements or SEO requirements, we still face the problem of concatenated HTML

If concatenating HTML is necessary, you need to use a suitable escape library to adequately escape the insertion points of the HTML template. Make sure the HTML you receive is properly formatted, contains only minimal, secure tags (absolutely no JavaScript), and strips out any references to remote content (especially stylesheets and JavaScript). For more security, use httpOnly cookies. Try to avoid concatenating HTML

Prevents DOM XSS attacks

Avoid inline event, if use Vue/React technology stack, and do not use the v – HTML/dangerouslySetInnerHTML function, on the front end render phase avoid innerHTML, outerHTML XSS concerns.

Inline event listeners in the DOM, such as location, onClick, onError, onload, onmouseover, etc. JavaScript eval(), setTimeout(), setInterval(), etc., can all run strings as code. It is important to avoid concatenating untrusted data in strings.

In addition, httpOnly, CSP, X-XSS-protection, Secure Cookie, and so on can also play an effective defense.



At the end


References:

  • Juejin. Cn/post / 684490…
  • www.doit.com.cn/article/200…
  • Juejin. Cn/post / 684490…
  • Juejin. Cn/post / 684490…
  • Juejin. Cn/post / 684490…