当前位置:网站首页>About CSP and its implementation

About CSP and its implementation

2022-06-09 11:34:00 Johnny, me

CSP

  • Content Security Policy Content security policy
  • produce XSS The reason for the attack is that the user data is executed as a program
  • Escape substitution is not very formal , But it is most suitable for XSS Solutions for
  • Except for escape substitution , Let's talk about CSP, It is a browser and web Standard setting
  • CSP Used to specify what is executable , What is not executable
  • We just need to mark the user input as non executable , There will be no harm
  • CSP yes HTTP head , It specifies which sources can be restricted , such as :
    • child-src connect-src default-src
    • font-src frame-src img-src
    • manifest-src media-src object-src
    • script-src style-src worker-src
  • For one of these , such as script Script , We can specify which are trusted , What's not believable , It defines many sources
    • <host-source> <scheme-source> ‘self’
    • ‘unsafe-inline’ ‘unsafe-eval’ ‘none’
    • ‘nonce-<base64-value>’ <hash-source>
    • ‘strict-dynamic’
  • For details, please refer to :https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CSP
  • Specific usage can be set HTTP head , Such as :
    ctx.set(`Content-Security-Policy`, `script-src 'self'`)
    
  • What if we want to execute a piece of code in our page ?
  • We can use nonce Parameters , On our page and HTTP A random one on the head nonce, So the attacker has nothing to do
  • For example, the script in the front page template
    <!-- pug  template engine  -->
    script(none='123456')
        var a = 1;
        console.log(a);
    
  • On the back-end response header
    ctx.set(`Content-Security-Policy`, `script-src 'self' 'nonce-123456'`)
    
  • there 123456 You can dynamically set a random string parameter , In this case, the front and rear ends remain nonce Unified
  • Each time the page is refreshed, a new random string is retrieved
  • You can also use one of the following methods to deal with
    //  Back end encryption 
    var content = ` The script code to be encrypted is written here `;
    var crypto = require('crypto');
    var hash = crypto.createHash('sha256');
    hash.update(content);
    var str = hash.digest('base64');
    console.log(str); //  This paragraph str The code is the encrypted script code , Is a hash value 
    
  • It USES sha256 The encryption algorithm of computes the hash value
  • We can set... On the response header
    ctx.set(`Content-Security-Policy`, `script-src 'self' 'sha256- Fill in the above calculated str A variable's value '`)
    
  • On the page template , The code format and content should be consistent with the encryption
    <!-- pug  template engine  -->
    script
         The script code to be encrypted is written here 
    
原网站

版权声明
本文为[Johnny, me]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091046492076.html