当前位置:网站首页>代码复现CSRF攻击并解决它
代码复现CSRF攻击并解决它
2022-06-11 03:36:00 【kobe_OKOK_】
1 什么是CSRF?
From 百度百科:
CSRF跨站请求伪造(英语:Cross-site request forgery),也被称为 one-click attack 或者 session riding,通常缩写为 CSRF 或者 XSRF, 是一种挟制用户在当前已登录的Web应用程序上执行非本意的操作的攻击方法。跟跨网站脚本(XSS)相比,XSS 利用的是用户对指定网站的信任,CSRF 利用的是网站对用户网页浏览器的信任。
2 举个栗子
我们创建两个站点:
一个是正常的网站,没有防御CSRF攻击
另一个是黑客的网站,专门对没有CSRF的网站进行攻击的

2.1 正常站点
后端
- good.py
import random
from datetime import datetime
from flask import Flask, request, session, render_template, redirect, url_for, abort
from flask_cors import CORS
# 实例化app对象
app = Flask(__name__)
CORS(app) # 设置跨域
# 设置secret_key
app.secret_key = 'fsdafagasdghjkgahghasklkglashdgks'
@app.route('/', methods=['GET', 'POST'])
def index():
""" 网站首页 """
if request.method == 'GET':
return render_template('good.html')
to_user = request.form.get('to')
money = request.form.get('money')
csrf_token = request.form.get('csrf_token')
return f'{
session.get("user_id")}-在{
datetime.now()}成功向{
to_user}转了{
money}元。'
@app.route('/login', methods=['GET', 'POST'])
def login():
""" 登录页面 """
if request.method == 'GET':
return render_template('login.html')
user = request.form.get('user')
pwd = request.form.get('password')
if user == 'zhangsan' and pwd == '123':
session['user_id'] = 'zhangsan'
return redirect(url_for('index'))
@app.before_request
def check_login():
""" 访问网站首页需要先登录 """
user = session.get('user_id')
if not user and request.path != '/login':
return redirect(url_for('login'))
if __name__ == '__main__':
# 启动服务 运行在端口5001上
app.run(debug=True, port=5001)
前端
- good.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Good Site</title>
</head>
<body>
<h1>转账界面</h1>
<form method="post">
<label for="to">转账给: </label>
<input type="text" id="to" name="to">
<label for="money">金额</label>
<input type="text" id="money" name="money">
<input type="submit" value="提交">
</form>
</body>
</html>
- index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Good Site</title>
</head>
<body>
<h1>登录界面</h1>
<form method="post">
<label for="user">用户名: </label>
<input type="text" id="user" name="user">
<label for="password">密 码:</label>
<input type="text" id="password" name="password">
<input type="submit" value="提交">
</form>
</body>
</html>
- 简单的演示一下这个网站的功能:
登录界面输入用户名和密码,将用户信息保存到session中
登录成功之后跳转到转帐页面
输入之后点击提交,简单的打印一个日志。
2.2 正常站点
- 后端
bad.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('bad.html')
if __name__ == '__main__':
app.run(debug=True, port=5002)
- 前端
bad.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Bad Site</title>
</head>
<body>
<h1>这是恶意网站</h1>
<p>在你不推出正常网站的前提下,如果访问这个网站的话,就会面临CSRF攻击的风险</p>
<form method="post" action="http://127.0.0.1:5001">
<input type="hidden" id="to" name="to" value="黑客">
<input type="hidden" id="money" name="money" value="999999999">
<input type="submit" value="点我戳 100元现金红包">
</form>
</body>
</html>

这是一个黑客网站,一般这种网站都会植入一些广告,点击广告之后:
你的正常站点的cookie就会被这个恶意的网站所利用,然后你的账号就会被刷空
3 解决方案:
3.1 设置请求头referer
referer是请求头里面的一个属性,会记录当前访问的站点从哪个站点跳转过来的,
以我们这个站点来说,这个referer就是从login界面过来的,我们可以检查这个属性,如果不是来自于我们的站点,那么就不给访问权限。
这种方式不做过多的介绍,因为这个实际中用的比较少
3.2 设置csrf_token
设置csrf token的原理是这样的:
通过get请求给用户表单,生成一个随机的字符串,发送到表单的一个隐藏字段,当用户下次发送post请求的时候,需要携带这个字符串,后端接收到这个csrf token之后与之前get请求创建的token进行比较,如果不相同,那么说明是恶意请求,如果相同,那么可以接受请求。
下面为我们的正常站点加上csrf_token
- 后端修改
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
# 生成随机字符串
_csrf_token = random.randint(10000000, 99999999)
# 将随机字符串保存到session中
session['csrf_token'] = _csrf_token
# 返回html界面,并把csrf_token返回回去
return render_template('good.html', csrf_token=_csrf_token)
to_user = request.form.get('to')
money = request.form.get('money')
# 获取post返回的值
csrf_token = request.form.get('csrf_token')
# 如果post返回的值与创建的字符串不相同
if str(csrf_token) != str(session.get('csrf_token')):
# 抛异常
abort(403)
return f'{
session.get("user_id")}-在{
datetime.now()}成功向{
to_user}转了{
money}元。'
- 前端修改
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Good Site</title>
</head>
<body>
<h1>转账界面</h1>
<form method="post">
<input type="hidden" name="csrf_token" value="{
{ csrf_token }}">
<label for="to">转账给: </label>
<input type="text" id="to" name="to">
<label for="money">金额</label>
<input type="text" id="money" name="money">
<input type="submit" value="提交">
</form>
</body>
这时候正常网站访问是可以的,黑客网站访问是会拒绝的

边栏推荐
- thinkphp3.2.3反序列化利用链分析
- ARM开发板方案与厂商分析
- Lianyirong (passed)
- [cnn]| translation invariance
- /The world of 10 recommended websites for learning programming has entered the era of the Internet. According to a recently released Internet trends 2016 report, China has become a leader in the Inter
- Understand single chip microcomputer drive 8080lcd
- Picking peaches (double pointer)
- [数据集]|无人机视角
- J. Balanced Tree
- Writing shell scripts using vscode
猜你喜欢

基于SSM的大学生社团管理系统

Kirin V10 installation of tongweb7.0

OpenGl第十章 投光物

After the installation of Damon database is completed, query whether it is case sensitive

Shopping and retail backstage management system of chain supermarket based on SSM framework

基于SSM框架的学生在线教育教学课程管理系统
![[elt.zip] openharmony paper Club - multi tier storage hierarchical data compression](/img/28/ec83b2ebb1f0772acdec443525c26d.png)
[elt.zip] openharmony paper Club - multi tier storage hierarchical data compression

Student online education and teaching course management system based on SSM framework

1_ Attribute management function

pmm监控oracle
随机推荐
Tweenmax colorful ball bouncing animation
Why is vfly, a high-end brand of Yadi that does not live up to its name, not high-end?
VIM quickly select a method / function
openssl enc 加解密
Run Skynet for the first time
大厂外包or自研公司?测试人找工作怎么选?
Technology Pro strength evaluation: comprehensive PK of high-end massage chair market, who is worthy of the machine king?
Promise use
什麼樣的人才是幸福的?
Lvgl Chinese font production
联易融一面(已过)
SQL查询连续三天登录的用户
【ELT.ZIP】OpenHarmony啃论文俱乐部——数据高通量无损压缩方案
/10个值得推荐的学习编程的网站 世界已经进入了互联网的时代。据最近发布的一篇《2016年互联网趋势》报告显示,中国已成为互联网市场的领导者,中国互联网用户的数量达到了6.68亿。可以预见,有
OpenGL第十一章 多光源
OpenGl第十章 投光物
OpenGL Chapter 7 basic lighting
如何做编程知识投资及减少知识失效的影响
Pthread in the multithreaded Trilogy
【ELT.ZIP】OpenHarmony啃论文俱乐部——快速随机访问字符串压缩