What is XSS

Cross-site scripting (commonly referred to as XSS) is a type of web application security vulnerability attack called code injection. It allows malicious users to inject code into a web page, affecting other users when they view it. Such attacks often involve HTML and client-side scripting languages.

XSS can be divided into three types: reflection, storage and DOM-based

How to attack

XSS attacks websites by modifying HTML nodes or executing JS code.

For example, get some parameters from a URL

<! -- http://www.domain.com?name=<script>alert(1)</script> -->
<div>{{name}}</div>
Copy the code

The above URL input might change the HTML to

, which would add an executable script to the page out of thin air. This type of attack is reflective attack, or DOM-based attack.

There is another scenario, such as writing an article that contains an attack code , and it is possible that all users browsing the article will be attacked. This type of attack is storage attack, which can also be said to be DOM-based attack, and this attack is broader.

How to defense

The most common approach is to escape input and output, such as quotes, Angle brackets, and slashes

function escape(str) {
  str = str.replace(/&/g.'& ')
  str = str.replace(/</g.'< ')
  str = str.replace(/>/g.'> ')
  str = str.replace(/"/g.'&quto; ')
  str = str.replace(/'/g.'& # 39; ')
  str = str.replace(/`/g.'the & # 96; ')
  str = str.replace(/\//g.'/ ')
  return str
}
Copy the code

By escaping, the attack code becomes

// -> < script> alert(1)< / script>
escape('<script>alert(1)</script>')
Copy the code

For displaying rich text, it is not possible to escape all characters as this would filter out the required format. In this case, whitelist filtering is usually adopted. You can also filter through the blacklist. However, because there are too many tags and tag attributes to be filtered, whitelist filtering is recommended.

var xss = require('xss')
var html = xss('

XSS Demo

'
) // ->

XSS Demo

< script> alert("xss"); < /script>
console.log(html) Copy the code

The above example uses JS-XSS. You can see that the H1 tag is kept in the output and the script tag is filtered