当前位置:网站首页>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
边栏推荐
- P5482 [jloi2011] inequality system, cckk
- 哐哐英雄Clunky Hero v0.96中文版
- MOS tube from entry to mastery
- Possible causes of processing chain loading error -process chain loading error
- 小知识——let const var的区别
- flex:1不等分的问题
- jvm内存溢出练习记录
- 浅析子组件自定义属性问题
- This article takes you to understand gaussdb (DWS) [Gauss is not a mathematician this time]
- 腾亚精工深交所上市:市值26亿 第一季扣非后净利降42%
猜你喜欢

三维数字沙盘展示具备哪些应用优势

Nacos配置中心实战,盘古微服务开发标配组件

redis中的string类型是怎么组织的?

What are the application advantages of 3D digital sand table display

对象的实例化和访问

Multi engine database management tool DataGrid 2022.1.5 Chinese version

The most complete knowledge summary, which must be read by beginners

What are the preparations for building your own website

【基础知识】~ 稳压二极管、三极管、放大电路、逻辑门晶体管数量、FPGA 器件结温范围、FPGA 加载方式、施密特触发器、C 语言结构化编程、中断向量地址、寄生效应、上拉电阻的作用

本科毕设CTF平台-MarsCTF
随机推荐
[buuctf.reverse] 109_ [FlareOn6]FlareBear,110_ [INSHack2018]Tricky-Part1
自己建设网站需要做哪些准备
Quartz multiple schedulers + thread pool mode to schedule tasks separately
第三章运输层
集丰照明|没有副光斑的射灯简直了,小山丘完美
What are the application advantages of 3D digital sand table display
Master tape editing tool Wavelab 11 Pro
flutter 弹窗flutter_easyloading
【SystemVerilog 之数据类型】~ 数据类型、Logic 类型、数组
首家BMW i品牌专属体验店开业,全面展示宝马电动产品的魅力
Is it safe for CICC fortune to open an account
[buuctf.reverse] 105_ [FlareOn6]Memecat Battlestation
处理链加载数据出错的可能原因-process chain loading error
数据资产管理:企业的数据资产怎么盘?
Execution engine - (compiler, JIT)
Protobuf介绍以及简单使用
[buuctf.reverse] 105_[FlareOn6]Memecat Battlestation
本科毕设CTF平台-MarsCTF
Ref reference usage
MySQL learning notes - Part 3 - indexes, stored procedures and functions, views, triggers