CSRF
zKing 2018-11-26 Web 安全
摘要
全名为:Cross Site Request Forgy 跨站请求伪造
# 攻击原理
- B 网站向 A 网站请求
- 带 A 网站 Cookies
- 不访问 A 网站前端
- referer 为 B 网站
# 防御措施
# 禁止带三方网站带 Cookie
在 Cookie 里使用 same-site 属性
ctx.cookies.set('test','cookies', {
httpOnly: true,
overwrite: false,
sameSite: 'strict',
});
# 在前端页面加入验证信息
- 使用验证码或者token
- npm上有好用的验证码模块
svg-captcha
- 所谓的token就是随机的字符串,在使用token的时候,需要表单上和Cookie上的token。使用ajax的时候,可以把token放在meta中
这里以“使用验证码来做防御方案”为例
cnpm install svg-captcha -D
const svgCaptcha = require('svg-captcha');
module.exports = (ctx) => {
let codeConfig = {
size: 5, // 验证码长度
ignoreChars: '0o1i', // 验证码字符中排除 0o1i
noise: 2, // 干扰线条的数量
height: 44
}
let captcha = svgCaptcha.create(codeConfig);
ctx.cookies.set('captcha',captcha.text);
ctx.response.type = "svg";
ctx.response.body = captcha.data;
};
# 通过获取 http 的 referer 头部属性进行判断
由于 http 的 referer
头部属性可以被伪造,所以这里就不再过多描述