当前位置:网站首页>The role of cookies in XSS and CSRF defense

The role of cookies in XSS and CSRF defense

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

Cookies characteristic

  • Front end data storage
  • Backend pass http Head set
  • Pass on request http Head to back
  • The front end is readable and writable
  • Comply with homology ( agreement / domain name / port ) Strategy

Cookies Example

  • The server writes cookie
    ctx.cookies.set('userId', 1, {
          
        httpOnly: false,
        sameSite: 'strict'
    })
    
  • Client read cookies
    //  take cookie,  Get all of cookie
    document.cookie
    
  • Client side Settings cookie
    //  Direct use  =  You can add a new cookie It won't cover the original cookie
    document.cookie="name=joh";
    //  Here's an example of a mistake , Only in cookies Add the first value to the , That is to say name=joh, The following will not be added 
    document.cookie="name=joh;age=10";
    
  • Client delete cookie, Set the validity period to the past time or the current time
    document.cookie='name=joh; expires=' + (new Date()).toGMTString()
    

Cookies characteristic

  • domain name : cookie Where it works ( website )
  • The period of validity : cookie For how long
  • route : cookie It can work on url Which level of , Set the path. Only this path can be used cookie
  • http-only: Can only be http Agreement to use ( Request and receive ),js Out of commission
  • secure: Whether you are in https Used in the agreement , If it is , It's in http Cannot be used under the agreement

Cookies effect

  • Store personalization
  • Store the unique user ID when not logged in
  • Store credentials for logged in users
    • Front end submits user name and password
    • Back end authentication username and password
    • Backend pass http Header to set user credentials
    • During subsequent access, the backend verifies the user credentials first
  • Store other business data

About user voucher processing

1 ) adopt cookie Store user signatures

  • user ID( unsafe )

  • user ID+ Signature ( recommend )

  • nodejs Process user credentials in

    var crypt = {
          };
    const KEY  = '&SWLSWkssf**)?!swe^%$'; //  The more complicated the better 
    
    //  Provide encryption methods 
    crypt.cryptUserId = function(userId) {
          
        var crypto = require('crypto'); //  Encryption module 
        var sign = crypto.createHmac('sha256', KEY);
        sign.update(userId + ''); // update To sign , The argument is a string 
        return sign.digest('hex'); //  obtain 16 Binary signature 
    }
    
    module.exports = crypt;
    
  • nodejs After encryption is set in the response cookies Information

    const crypt = require('/path/to/crypt')
    
    //  The back end provides two cookies  After a signature userID namely sign,  One is pure userID
    //  Each request is made through the userID Calculate the relevant values and according to the same algorithm sign Compare to verify identity , The following will be handled 
    ctx.cookies.set('sign', crypt.cryptUserId(userId), {
          
        httpOnly: false,
        sameSite: 'strict'
    })
    ctx.cookies.set('userId', userId, {
          
        httpOnly: false,
        sameSite: 'strict'
    })
    
  • nodejs Verify user credentials in request

    const crypt = require('/path/to/crypt')
    
    var userId = ctx.cookies.get('userId')
    var sign = ctx.cookies.get('sign')
    var computedSign = crypt.cryptUserId(userId)
    //  Compare whether the two signatures are correct 
    if(computedSign != sign) {
          
        throw new Error(' The signature was tampered with ')
    }
    

2 ) adopt SessionId Handle

  • encapsulation session Method
// session The principle of is to put user data in memory 
//  By sending a random string to the front-end data ( identification ), The front end does not store any data 
//  When the current end requests again, it only needs to take this ID to find the data in the memory to identify the user 
//  Further, we can session Data persistence is stored in redis Wait for the database , Generally, it will not be stored in memory ( Limited capacity )
//  This is just session Implementation principle 
var session = {
    };
var cache = {
    };
session.set = function(userId, obj) {
    
    var sessionId = Math.random();
    if(!cache[sessionId]) {
    
        cache[sessionId].content = obj;
    }
    cache[sessionId].content = obj;
    return sessionId;
}

session.get = function(sessionId) {
    
    return cache[sessionId] && cache[sessionId].content;
}

module.exports = session;
  • Use session, Set up cookies
const session = require('/path/to/session')

session.set(user.id, {
    
    userId: user.id
})

ctx.cookies.set('sessionId', sessionId, {
    
    httpOnly: true,
    sameSite: 'strict'
})
  • Use session, Read cookies
const session = require('/path/to/session')
var sessionId = ctx.cookies.get('sessionId')
var sessionObj = session.get(sessionId)
if(!sessionObj || !sessionObj.userId) {
    
    throw new Error('session non-existent ')
}
var userId = sessionObj.userId

Cookies and XSS CSRF The relationship between

  • XSS May steal cookie Information , And then get the user's login status to simulate login , And can be modified cookie
    • Set up http-only Of cookie It won't be js Stealing , Prevent user accounts from being stolen
    • however XSS except cookie And do other bad things
  • CSRF Take advantage of the user's cookie, Embezzle information , But I can't read or write cookie, It is best to prevent third parties from using cookie( namely sameSite)

Cookies Security policy

  • Sign to prevent tampering
    • namely userID + sign Although there are public , But with verification protection
  • Private transformation ( encryption )
    • Hide information , It is the request and response of ciphertext directly
    • Internal decryption read / write
      var crypto = require('crypto')
      var KEY = 'SASDKLJFL245*^%$&*SSLlli12'
      
      //  To encrypt 
      var cipher = crypto.createCipher('des', KEY)
      var text = cipher.update(' Characters to be encrypted ', 'utf8', 'hex')
      text += cipher.final('hex')
      //  Output 
      console.log(text)
      //  Decrypt 
      var decipher = crypto.createDecipher('des', KEY)
      var originalText = decipher.update(text, 'hex', 'utf8')
      originalText += decipher.final('utf8')
      console.log(originalText)
      
  • http-only ( prevent XSS)
    • Only http Request read / write cookie,js Can't read cookie
  • secure
    • stay https Valid under the agreement
    • Prevent transmission eavesdropping
  • same-site
    • prevent CSRF attack

Related cases

  • A school administration website uses username As a unique user id , Very unsafe
  • some BBS The program uses the user ID As a unique identifier , Fake user login
原网站

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