csrf跨站攻击
什么是csrf跨站攻击?
- 简单来讲,就是利用浏览器同站会自动携带cookie的特点,实现攻击。
- 常见的中招方式多见于,不法分子伪造某个官网,而你
不小心点了进去,这时问题就大了。虽然不法分子不能直接拿到你的cookie信息,但他可以伪造请求,在你完全不知情的情况下,拿你的cookie去发送评论等操作。
那么,什么是同站?
- 简单理解即域名相同
例子
后端跨域设置:
res.setHeader("Access-Control-Allow-Headers", "token, name, content-type")
res.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5501")
res.setHeader("Access-Control-Allow-Methods", "PUT, GET,post")
res.setHeader("Access-Control-Allow-Credentials", true) // 表示允许跨域请求携带cookie
后端cookie参数设置:
router.get("/login", (req, res, next) => {
if (req.query.loginId === "admin" && req.query.loginPwd === "123456") {
res.cookie("token", req.query.loginId, {
domain: "127.0.0.1",
path: "/",
maxAge: 1000 * 60 * 60 * 24, /* 1天过期 */
signed: true, //生成带加密的cookie
sameSite: "None", //无论是否同站都携带cookie
httpOnly: false //设置为false,可以通过document.cookie获取cookie
})
res.send("登录成功")
} else {
res.send("登录失败")
}
})
router.get("/csrf", (req, res, next) => {
console.log("csrf-get");
res.send("success")
})
前端发送请求:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>模拟csrf攻击</title>
</head>
<body>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.7.2/axios.min.js"></script>
<button onclick="login()">Login</button>
<button onclick="csrf()">csrf</button>
<script>
const instance = axios.create({
withCredentials: true, // 表示跨域请求时是否携带cookie
});
function login() {
instance.get("http://127.0.0.1:1122/login?loginId=admin&loginPwd=123456"
).then(res => {
console.log(res);
})
}
async function csrf(){
const result = await instance.get("http://127.0.0.1:1122/csrf")
console.log(result);
}
</script>
</body>
</html>
浏览器策略:
http://127.0.0.1:5501/和http://127.0.0.1:1122/存在跨域问题,由于withCredentials: true设置,所以跨域也会自动携带cookie【是否携带cookie还得看same-site配置】。
- 这时候,不法分子通过模拟该网站发送个链接给你,你打开并且点击操作了。
- 都用内网不太好举例子,这里在内网ip上引入了服务器的一张照片,服务器ip下存储着一个cookie。
same-site:None; Secure:true; 跨站也可以携带cookie
same-site:Lax; 默认值,表示同站携带cookie这时候是不会携带cookie发送请求的,因为图片链接与网页链接不同站
smae-site:Strict; 表示同站并且协议一致的情况下携带cookie与same-site:Lax;一致都是不会携带cookie的。
总结:cookie的配置same-site:None; Secure:true;避免使用该种方式,漏洞较大,很容易造成csrf攻击