What is a XSS

concept

Cross-site scripting (XSS) is a security vulnerability in Web applications that allows malicious Web users to embed code into pages intended for use by other users.

Once a Web application is not authenticated for security, these attacks can easily succeed. Streaking malicious code, can be imagined is very dangerous. These scripts can read cookies, session tokens, or other sensitive website information, or have malicious scripts rewrite HTML content.

classification

Generally speaking, XSS attacks can be classified into three types: storage (persistent), reflection (non-persistent), and DOM. The difference between DOM type XSS and the previous two types of XSS is that in DOM type XSS attack, taking out and executing malicious code is completed by the browser side, which belongs to the security vulnerability of front-end JavaScript itself, while the other two types of XSS belong to the security vulnerability of server side.

Type stored XSS

Stored, which means malicious snippets of code are permanently stored on the servers of the site being attacked. When the user enters the web page, the browser requests resources while the malicious script is transmitted back from the server and executed.

Reflective XSS

Reflective XSS usually was induced in user click click on a malicious link, or submit a form, or enter into a malicious web site, the content of the response may be inserted into the script, a and style, such as tag, due to the browser that this response from “trusted” on the server, so they will execute the script.

The DOM model XSS

DOM and reflective XSS attacks work in a similar way, but usually do not require a browser response to complete the attack. Typically, the user performs an action that causes the client code to be included in the page and executed accidentally, resulting in the DOM environment being maliciously modified.

Common hazards

  • throughdocument.cookieStealing cookie information
  • Using JS or CSS destroys the normal structure and style of the page, making it impossible for users to access the page normally
  • DOS attack: The use of reasonable client requests to occupy too many server resources, so that legitimate users cannot get a response from the server

Common scenarios

// This WILL run
div.innerHTML = '';
// This will, too
div.innerHTML = '<img src=x onerror="alert(\'XSS Attack\')">';
Copy the code
<img src=javascript:alert("XSS"/ >
Copy the code

Front end XSS defense posture

Enter the security

The front end can filter and escape submitted content, such as <> symbols representing HTML tags. However, the front end is not a complete solution to this problem, because the front end validation can be bypassed to simulate direct requests, so security policies need to be in place in the background.

function encode(str) {    
  if(! str || str.length ===0) return ' ';
  str = str.replace(/>/gm.'> ');
  str = str.replace(/</gm.'< ');
  str = str.replace(/"/gm.'" ');
  str = str.replace(/'/gm.'' ');    
  return str;
}
Copy the code

Insert the safety

Client-side XSS, also known as DOM-type XSS attacks, are usually caused by JavaScript performing unsafe operations. Such as innerHTML, document.write(), location.href, etc. by inserting code into the page. In cases where content security is not guaranteed, a more secure alternative is used.

textContentalternativeinnerHtml

For inserted content that does not contain tags, we use textContent inserts, where the content is escaped and the browser recognizes the content as text, so the inserted script cannot execute

var sanitizeHTML = function (str) {
	var temp = document.createElement('div');
	temp.textContent = str;
	return temp.innerHTML;
};
Copy the code

At this point, the insert operation becomes:

div.innerHTML = '<h1>' + sanitizeHTML('<img src=x onerror="alert(\'XSS Attack\')">') + '</h1>';
Copy the code

DOMPurify

For cases where you need to insert HTML directly, you can use third-party libraries like DOMPurify, JSXSS, etc. The principle is that you get “pure” HTML by removing all unsafe HTML content (tags).

const DOMPurify = require('dompurify') (window);
// Sanitize the review
return (<p dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(review)}} ></p>);
Copy the code

Resource security

HttpOnly

For cookies that do not need to be available to JavaScript but are only used for persistent server-side sessions, we set the HttpOnly flag to prevent malicious scripts from accessing user private data through document. Cookie.

Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; HttpOnly
Copy the code

CSP

Content Security Policy (CSP) can specify trusted Content sources by agreeing on a series of Security policies. A CSP-compliant browser will only execute scripts that load source files with whitelisted domain names, ignoring those other scripts (including inline scripts and event-manipulated HTML attributes).

  • use
// Disable outfield scripts<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self' ssl.google-analytics.com;">
Copy the code
  • Other examples
// All Content comes from the same source (excluding subdomain name) content-security-policy: default-src'self'// Trusted domain name content-security-policy: default-src'self'*. HTTP: / / trusted.com / / all Content through SSL way access to the Content of ws-security - Policy: default SRC - https://onlinebanking.jumbobank.comCopy the code

SRI

Subresource Integrity (SRI), a security feature that allows browsers to check whether the resources they acquire (e.g. from a CDN) have been tampered with, can be used to address XSS vulnerabilities caused by CDN resource contamination (malicious injection/replacement).

  • “Integrity” : indicates file fingerprint. A password hash uniquely identifies a block of data, and no two files have the same password hash. After the script is downloaded, the browser calculates its hash and compares the resulting values to those provided by Integrity. If not, the target script has been tampered with and the browser will not use it.

We often see this attribute when introducing resources:

< script SRC = "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>Copy the code

The site can be configured with CSP:

# specifies that all scripts must have integrity and be verified before they can be loaded
Content-Security-Policy: require-sri-for script;
# specifies that all stylesheets must have integrity and be verified before they can be loaded
Content-Security-Policy: require-sri-for style;
Copy the code

React XSS defense

The default escape

React allows content text to be escaped by default, reducing our own processing burden

<div>{ text }</div>
Copy the code

JSX

JSX calls the react.createElement () function at compile time to create the actual tag that tells React what to render next and a unique identifier $$typeof. React checks element.$$typeof. If the identity is missing or invalid, processing of the element is rejected.

{
  type: 'div',
  props: {
    children: 'text',
  },
  key: null,
  ref: null,
  $$typeof: Symbol.for('react.element')
}
Copy the code

The resources

  • Cross-site Scripting (Cross-site Scripting)
  • Content Security Policy (CSP)
  • Subresource Integrity
  • Preventing cross-site scripting attacks when using innerHTML in vanilla JavaScript
  • XSS attacks in React