Flask模擬實(shí)現(xiàn)CSRF攻擊的方法
CSRF
CSRF全拼為Cross Site Request Forgery,譯為跨站請(qǐng)求偽造。
CSRF指攻擊者盜用了你的身份,以你的名義發(fā)送惡意請(qǐng)求。
包括:以你名義發(fā)送郵件,發(fā)消息,盜取你的賬號(hào),甚至于購(gòu)買(mǎi)商品,虛擬貨幣轉(zhuǎn)賬......
造成的問(wèn)題:個(gè)人隱私泄露以及財(cái)產(chǎn)安全。
CSRF攻擊示意圖
客戶端訪問(wèn)服務(wù)器時(shí)沒(méi)有同服務(wù)器做安全驗(yàn)證

防止 CSRF
1.在客戶端向后端請(qǐng)求界面數(shù)據(jù)的時(shí)候,后端會(huì)往響應(yīng)中的 cookie 中設(shè)置 csrf_token 的值
2.在 Form 表單中添加一個(gè)隱藏的的字段,值也是 csrf_token
3.在用戶點(diǎn)擊提交的時(shí)候,會(huì)帶上這兩個(gè)值向后臺(tái)發(fā)起請(qǐng)求
4.后端接受到請(qǐng)求,以會(huì)以下幾件事件: •從 cookie中取出 csrf_token
- 從 表單數(shù)據(jù)中取出來(lái)隱藏的 csrf_token 的值
- 進(jìn)行對(duì)比
5.如果比較之后兩值一樣,那么代表是正常的請(qǐng)求,如果沒(méi)取到或者比較不一樣,代表不是正常的請(qǐng)求,不執(zhí)行下一步操作
代碼演示
未進(jìn)行 csrf 校驗(yàn)的 WebA
后端代碼實(shí)現(xiàn)
from flask import Flask, render_template, make_response
from flask import redirect
from flask import request
from flask import url_for
app = Flask(__name__)
@app.route('/', methods=["POST", "GET"])
def index():
if request.method == "POST":
# 取到表單中提交上來(lái)的參數(shù)
username = request.form.get("username")
password = request.form.get("password")
if not all([username, password]):
print('參數(shù)錯(cuò)誤')
else:
print(username, password)
if username == 'laowang' and password == '1234':
# 狀態(tài)保持,設(shè)置用戶名到cookie中表示登錄成功
response = redirect(url_for('transfer'))
response.set_cookie('username', username)
return response
else:
print('密碼錯(cuò)誤')
return render_template('temp_login.html')
@app.route('/transfer', methods=["POST", "GET"])
def transfer():
# 從cookie中取到用戶名
username = request.cookies.get('username', None)
# 如果沒(méi)有取到,代表沒(méi)有登錄
if not username:
return redirect(url_for('index'))
if request.method == "POST":
to_account = request.form.get("to_account")
money = request.form.get("money")
print('假裝執(zhí)行轉(zhuǎn)操作,將當(dāng)前登錄用戶的錢(qián)轉(zhuǎn)賬到指定賬戶')
return '轉(zhuǎn)賬 %s 元到 %s 成功' % (money, to_account)
# 渲染轉(zhuǎn)換頁(yè)面
response = make_response(render_template('temp_transfer.html'))
return response
if __name__ == '__main__':
app.run(debug=True, port=9000)
前端登錄頁(yè)面代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登錄</title> </head> <body> <h1>我是網(wǎng)站A,登錄頁(yè)面</h1> <form method="post"> <label>用戶名:</label><input type="text" name="username" placeholder="請(qǐng)輸入用戶名"><br/> <label>密碼:</label><input type="password" name="password" placeholder="請(qǐng)輸入密碼"><br/> <input type="submit" value="登錄"> </form> </body> </html>
前端轉(zhuǎn)賬頁(yè)面代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>轉(zhuǎn)賬</title> </head> <body> <h1>我是網(wǎng)站A,轉(zhuǎn)賬頁(yè)面</h1> <form method="post"> <label>賬戶:</label><input type="text" name="to_account" placeholder="請(qǐng)輸入要轉(zhuǎn)賬的賬戶"><br/> <label>金額:</label><input type="number" name="money" placeholder="請(qǐng)輸入轉(zhuǎn)賬金額"><br/> <input type="submit" value="轉(zhuǎn)賬"> </form> </body> </html>
運(yùn)行測(cè)試,如果在未登錄的情況下,不能直接進(jìn)入轉(zhuǎn)賬頁(yè)面,測(cè)試轉(zhuǎn)賬是成功的
攻擊網(wǎng)站B的代碼
后端代碼實(shí)現(xiàn)
from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('temp_index.html')
if __name__ == '__main__':
app.run(debug=True, port=8000)
前端代碼實(shí)現(xiàn)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>我是網(wǎng)站B</h1> <form method="post" action="http://127.0.0.1:9000/transfer"> <input type="hidden" name="to_account" value="999999"> <input type="hidden" name="money" value="190000" hidden> <input type="submit" value="點(diǎn)擊領(lǐng)取優(yōu)惠券"> </form> </body> </html>
運(yùn)行測(cè)試,在用戶登錄網(wǎng)站A的情況下,點(diǎn)擊網(wǎng)站B的按鈕,可以實(shí)現(xiàn)偽造訪問(wèn)
在網(wǎng)站A中模擬實(shí)現(xiàn) csrf_token 校驗(yàn)的流程
添加生成 csrf_token 的函數(shù)
# 生成 csrf_token 函數(shù) def generate_csrf(): return bytes.decode(base64.b64encode(os.urandom(48)))
在渲染轉(zhuǎn)賬頁(yè)面的,做以下幾件事情:
- 生成 csrf_token 的值
- 在返回轉(zhuǎn)賬頁(yè)面的響應(yīng)里面設(shè)置 csrf_token 到 cookie 中
- 將 csrf_token 保存到表單的隱藏字段中
@app.route('/transfer', methods=["POST", "GET"])
def transfer():
...
# 生成 csrf_token 的值
csrf_token = generate_csrf()
# 渲染轉(zhuǎn)換頁(yè)面,傳入 csrf_token 到模板中
response = make_response(render_template('temp_transfer.html', csrf_token=csrf_token))
# 設(shè)置csrf_token到cookie中,用于提交校驗(yàn)
response.set_cookie('csrf_token', csrf_token)
return response
在轉(zhuǎn)賬模板表單中添加 csrf_token 隱藏字段
<form method="post">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<label>賬戶:</label><input type="text" name="to_account" placeholder="請(qǐng)輸入要轉(zhuǎn)賬的賬戶"><br/>
<label>金額:</label><input type="number" name="money" placeholder="請(qǐng)輸入轉(zhuǎn)賬金額"><br/>
<input type="submit" value="轉(zhuǎn)賬">
</form>
運(yùn)行測(cè)試,進(jìn)入到轉(zhuǎn)賬頁(yè)面之后,查看 cookie 和 html 源代碼

在執(zhí)行轉(zhuǎn)賬邏輯之前進(jìn)行 csrf_token 的校驗(yàn)
if request.method == "POST":
to_account = request.form.get("to_account")
money = request.form.get("money")
# 取出表單中的 csrf_token
form_csrf_token = request.form.get("csrf_token")
# 取出 cookie 中的 csrf_token
cookie_csrf_token = request.cookies.get("csrf_token")
# 進(jìn)行對(duì)比
if cookie_csrf_token != form_csrf_token:
return 'token校驗(yàn)失敗,可能是非法操作'
print('假裝執(zhí)行轉(zhuǎn)操作,將當(dāng)前登錄用戶的錢(qián)轉(zhuǎn)賬到指定賬戶')
return '轉(zhuǎn)賬 %s 元到 %s 成功' % (money, to_account)
運(yùn)行測(cè)試,用戶直接在網(wǎng)站 A 操作沒(méi)有問(wèn)題,再去網(wǎng)站B進(jìn)行操作,發(fā)現(xiàn)轉(zhuǎn)賬不成功,因?yàn)榫W(wǎng)站 B 獲取不到表單中的 csrf_token 的隱藏字段,而且瀏覽器有同源策略,網(wǎng)站B是獲取不到網(wǎng)站A的 cookie 的,所以就解決了跨站請(qǐng)求偽造的問(wèn)題
在 Flask 項(xiàng)目中解決 CSRF 攻擊
在 Flask 中, Flask-wtf 擴(kuò)展有一套完善的 csrf 防護(hù)體系,對(duì)于我們開(kāi)發(fā)者來(lái)說(shuō),使用起來(lái)非常簡(jiǎn)單
在 FlaskForm 中實(shí)現(xiàn)校驗(yàn)
設(shè)置應(yīng)用程序的 secret_key
用于加密生成的 csrf_token 的值
app.secret_key = "#此處可以寫(xiě)隨機(jī)字符串#"
在模板的表單中添加以下代碼
<form method="post">
{{ form.csrf_token() }}
{{ form.username.label }} {{ form.username }}<br/>
{{ form.password.label }} {{ form.password }}<br/>
{{ form.password2.label }} {{ form.password2 }}<br/>
{{ form.submit }}
</form>
渲染出來(lái)的前端頁(yè)面為:

設(shè)置完畢,cookie 中的 csrf_token 不需要我們關(guān)心,會(huì)自動(dòng)幫我們?cè)O(shè)置
單獨(dú)使用
設(shè)置應(yīng)用程序的 secret_key
用于加密生成的 csrf_token 的值
app.secret_key = "#此處可以寫(xiě)隨機(jī)字符串#"
導(dǎo)入 flask_wtf.csrf 中的 CSRFProtect 類,進(jìn)行初始化,并在初始化的時(shí)候關(guān)聯(lián) app
from flask.ext.wtf import CSRFProtect CSRFProtect(app)
如果模板中有表單,不需要做任何事。與之前一樣:
<form method="post">
{{ form.csrf_token }}
...
</form>
但如果模板中沒(méi)有表單,你仍需要 CSRF 令牌:
<form method="post" action="/">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
</form>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家?!?/p>
相關(guān)文章
對(duì)numpy數(shù)據(jù)寫(xiě)入文件的方法講解
今天小編就為大家分享一篇對(duì)numpy數(shù)據(jù)寫(xiě)入文件的方法講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-07-07
python opencv鼠標(biāo)畫(huà)矩形框之cv2.rectangle()函數(shù)
鼠標(biāo)操作屬于用戶接口設(shè)計(jì),以前一直使用Qt來(lái)做,但是如果只需要簡(jiǎn)單的鼠標(biāo),鍵盤(pán)操作,直接調(diào)用opencv庫(kù)的函數(shù)也未嘗不可,下面這篇文章主要給大家介紹了關(guān)于python opencv鼠標(biāo)畫(huà)矩形框cv2.rectangle()函數(shù)的相關(guān)資料,需要的朋友可以參考下2021-10-10
Python自動(dòng)化處理手機(jī)驗(yàn)證碼
手機(jī)驗(yàn)證碼是一種常見(jiàn)的身份驗(yàn)證手段,廣泛應(yīng)用于用戶注冊(cè)、登錄、交易確認(rèn)等場(chǎng)景,下面我們來(lái)看看如何使用Python自動(dòng)化處理手機(jī)驗(yàn)證碼吧2025-02-02
Python必備基礎(chǔ)之閉包和裝飾器知識(shí)總結(jié)
都2021年了Python的閉包和裝飾器難道你還不會(huì)?今天就帶大家詳細(xì)總結(jié)一下Python閉包和裝飾器的相關(guān)知識(shí),需要的朋友可以參考下2021-06-06
TensorFlow設(shè)置日志級(jí)別的幾種方式小結(jié)
今天小編就為大家分享一篇TensorFlow設(shè)置日志級(jí)別的幾種方式小結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02
django 鏈接多個(gè)數(shù)據(jù)庫(kù) 并使用原生sql實(shí)現(xiàn)
這篇文章主要介紹了django 鏈接多個(gè)數(shù)據(jù)庫(kù) 并使用原生sql實(shí)現(xiàn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03
使用Python實(shí)現(xiàn)壓縮pptx的功能
當(dāng)處理大型PPTX文件時(shí),其中包含許多高分辨率照片時(shí),文件大小可能會(huì)顯著增加,為了解決這個(gè)問(wèn)題,我們可以使用Python編程語(yǔ)言和python-pptx庫(kù)來(lái)壓縮PPTX文件中的照片,下面我們就來(lái)看看具體操作吧2024-02-02

