CSRF(Cross-Site Request Forgery)跨站请求伪造,是一种网络安全攻击,其目标是利用被攻击者在某个网站的身份(通常是通过 cookie 认证)来伪造被攻击者的请求,以执行某些未经授权的操作。
攻击步骤通常包括以下几个阶段:
演示代码:github - csrf-demo
项目目录如下:
其中业务后端 CsrfController.java 代码为:
package com.fhb.csrfdemo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@RestController
@RequestMapping("/")
public class CsrfController {
@GetMapping("/trans")
public String trans(HttpServletRequest request, String name, Integer money) {
HttpSession session = request.getSession();
Object people = session.getAttribute("people");
if (people == null) return "没有登录";
System.out.println("给" + name + "转账" + money + "元");
return "转账成功";
}
@GetMapping("/login")
public String login(HttpServletRequest request) {
HttpSession session = request.getSession();
session.setAttribute("people", "people");
return "登录成功";
}
}
业务前端代码较为简单,代码为:
doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Documenttitle>
head>
<body>
<h1>CSRF 攻击测试h1>
<button onclick="trans()">转账button>
<button onclick="login()">登录button>
<a href="http://localhost:18080">恶意链接a>
body>
<script lang="js">
async function trans() {
const response = await fetch("/trans?name=fhb&money=100");
const info = await response.text();
alert(info);
}
async function login() {
const response = await fetch("/login");
const info = await response.text();
alert(info);
}
script>
html>
恶意网站仅为一个 html 文件:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
head>
<body>
<h1>CSRF攻击软件h1>
<img src="http://localhost:8080/trans?name=fff&money=10" alt="xxx" srcset="">
body>
<script>
script>
html>
启动 java 程序 CsrfDemoApplication,该 Spring Boot 服务将在 8080 端口提供服务;
通过 npm 安装 http-server,进入 malicious-web 文件夹, 通过 http-server . -p 18080
启动攻击者网站;
业务网站 ui 如下:
通过 http://localhost:8080 访问目标网站。