xss

XSS stands for Cross Site Script, shortened to XSS to avoid conflicts with style CSS

Cross – site scripting attack.

XSS attacks generally refer to the use of malicious scripting code to tamper with web pages to obtain users’ private information.

XSS classification

  • reflective

    Reflection is the script that injects malicious code into the web page through url parameters. Now we start a server that displays who is welcome based on the value of user in the query string

// The reflection type of the URL is to inject scripts into the page, which is less harmful
let http = require('http');
let queryString = require('querystring');
let server = http.createServer((req,res) = >{
    let query=req.url.split("?") [1];
    let queryObj =  queryString.parse(query);
    res.setHeader('Content-Type'.'text/html; charset=utf8');
    res.end(` welcome${queryObj.user}
    `)
})
server.listen(80, () = > {console.log("Server started successfully!")})Copy the code

But if you say localhost/? User = the page will be injected with a script, depending on the injected script, the attacker can use this to obtain important information such as the user’s cookie.

  • Storage type

    Compared with the reflection type, the stored XSS attack is more harmful. It writes the XSS attack script to the database, and the user is attacked every time it is invoked from the database.

    Scenarios are mostly when users enter comments and post articles.

    For simplicity, assume that data has been written to the database via network requests, and the back end returns the data to be inserted into the DOM node

    <input type="text">
        <button>submit</button>
        <div class="showData"></div>
        <script>
            let Dinput = document.querySelector('input');
            let showDiv = document.querySelector('.showData');
            let btn = document.querySelector('button');
            btn.addEventListener('click',putData);
            function putData(){ 
                let xhr = new XMLHttpRequest();
                xhr.open('POST'.'/'.true);
                xhr.onreadystatechange=function(){
                    if(xhr.readyState==4&&xhr.status==200) {let divDom = document.createElement('div')
                        divDom.innerHTML = xhr.response;
                        showDiv.appendChild(divDom); 
                    }
                }
                xhr.send(Dinput.value);       
            }
    Copy the code

    Note: Because Google Chrome automatically filters XSS attacks, there are no pop-ups here

Injection point of XSS attack

  1. HTML node content
<div>{{content}}// Through the template engine injection</div>
Copy the code
  1. HTML attributes
< img SRC = "{{img path}}" > / / if img path = '1 "onerror = < script > < / script >"' / / results < img SRC = "1" onerror = < script > < / script > "" >Copy the code
  1. Javascript code that has variables injected by the background
<script>
let data = "{{content}}";
// If content=' hello '; alert(1)" '
/ / the result
data = "hello"; alert(1)"";
</script>
Copy the code
  1. The rich text

Rich text needs to keep HTML at risk of XSS attacks

XSS solution

  1. In the response header set (X-XXS-Protection,1), using the browser’s own interception
  2. Escape character content
  • Escape”&lt;And >&gt;Avoid tampering with node content
  • Escape the double quotes&quto;The single quotes& # 39;, the blank space& # 32(Spaces do not need to be escaped if the code is quoted)
  • Escape diagonal\ \To avoid js content being commented
  1. Rich text content filtering

Rich text content is best filtered when it is uploaded to the server

Generally, there are two types: reserving some labels and attributes by whitelist and escaping labels and attributes by blacklist

If there are too many tags and attributes, you can use a whitelist to reserve some tags and attributes

var whiteList = {// Store the whitelist
	'img': ['src']}var xssFilter = function(html){
    var cheerio =  require("cheerio");
    var $ = cheerio.load(html);// Use cheerio to parse HTML on the server
    $(The '*').each(function(index,elem){
        if(! whiteList[elem.name]){// If the label does not exist in the whitelist, delete it
			$(elem).remove();
            return;
        }
        for(var attr in elem.attribs){// Not whitelist attributes, delete
            if(whiteList[elem.name].indexOf(attr)===- 1) {$(elem). Attr (attr,null); }}})return $.html()
}
Copy the code

csrf

CSRF stands for Cross Site Request Forgy

CSRF attack mode

Suppose I now have A web site A, when the administrator login, also have local administrator privileges of cookies, send the request at this time http://localhost:80/delete can delete articles,

let http = require('http');
let data = "I am the article.";
let server = http.createServer((req,res) = >{
  let path = req.url.split("?") [0];
  res.setHeader('Content-Type'.'text/html;; charset=utf8');
  if(path=='/login'){
      res.setHeader('Set-Cookie'.'user=admin');
      res.writeHeader(302, {'location':'/'});
        res.end();
  }
  if(path=="/"){
      res.write(' go to CSRF ')
      res.end(data);

  }
  if(path=="/delete") {// When the user logs in, the article can be deleted
     if(req.headers.cookie=='user=admin'){
         data="";
         res.writeHeader(302, {'location':'/'});
        res.end();
     }else{
        res.writeHeader(302, {'location':'/'});
        res.end();
     }
  }
})
server.listen(80, () = > {console.log("Server started successfully!")})Copy the code

So LET me build a CSRF website

< img SRC = “http://localhost:80/delete” to delete A site article with pictures

let http = require('http');
let server = http.createServer((req,res) = >{
    res.setHeader('Content-Type'.'text/html; charset=utf8');
    res.end(Welcome to CSRF ` < div > website < div > < img SRC = "http://localhost:80/delete" > `)
})
server.listen(8080, () = > {console.log("Server started successfully!")})Copy the code

When the administrator enters site D, the 10th article in site A is deleted

Although the IMG SRC link is initiated on the CSRF website, the URL path is the same as website A, so you can get the cookie

How do I defend against CSRF attacks

CSRF features:

  1. CSRF’s website carries the cookie of the target website
  2. CSRF attacks do not access the front end of the target website
  3. Referer is the CSRF website

According to these characteristics, we can have corresponding countermeasures:

  1. Prohibit third-party websites from carrying cookiesres.setHeader('Set-Cookie','sameSite=strict')
  2. Every time a user initiates a request, a captcha is used, but the experience is not good
  3. Set the token on the page
<input type='hidden' value=123456>SetHeader (' set-cookie ','token=123456'); // This can be done because the CSRF attack cannot get the token value in the input of the target websiteCopy the code
  1. When the referer is not from this site, the request is rejected

conclusion

To prevent XSS:

  1. In the response header set (X-XXS-Protection,1), using the browser to intercept the content of escape characters
  2. Escape character
  3. Rich text is filtered by whitelist or blacklist

Prevent CSRF:

  1. Prohibit third-party websites from carrying cookiesres.setHeader('Set-Cookie','sameSite=strict')
  2. Every time a user initiates a request, a captcha is used, but the experience is not good
  3. Set the token on the page
  4. When the referer is not from this site, the request is rejected

conclusion

The article is not easy to write, passing greatly they feel good point praise.

Author: Hu Zhiwu

Time: 2019/6/15

If there are any mistakes or omissions in this article, please correct them

If need to reprint, please indicate the source