gpt4 book ai didi

python - Flask 防止表单注入(inject)

转载 作者:行者123 更新时间:2023-12-01 03:58:37 24 4
gpt4 key购买 nike

python/flask如何阻止外来形式注入(inject)?

考虑以下 mwe:

应用程序.py

from flask import Flask, request, render template

app = Flask(__name__)

@app.route('/', methods=['GET','POST'])
def helloworld():
if request.method == 'GET':
return render_template('index.html')
if request.method == 'POST':
print(request.form['info'])

## do something with the info, like write to a database

return 'nothing'

if __name__ == '__main__':
app.run(debug=True)

模板/index.html

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript' src="{{ url_for('static', filename='js/fire.js') }}"></script>
</head>

<body>
<p>Hello world!</p>
</body>
</html>

静态/js/fire.js

$(document).click(function() {

// post data to flask

$.post('/', {'info': 'test'});

return false;

};

我的问题是:

  1. 可以从国外网站注入(inject)吗?追问:这怎么办? (例如,也许通过发布到我的网站网址的表单?)
  2. 如果可以注入(inject),我可以在 app.py 脚本中做什么来阻止注入(inject)?

编辑

这是一个非常基本的脚本,可用于针对上述 Flask 应用程序测试注入(inject)。接受的答案会阻止此脚本:

<!DOCTYPE html>
<html>
<body>

<h2>Malicious Form Injection</h2>

<form action='http://127.0.0.1:5000/' method='post'>
Input 1:<br>
<input name="info" value="mal1"><br>
<input type="submit" value="Submit">
</form>


</body>
</html>

最佳答案

app.py

from flask import Flask, request, render template
from flask_wtf.csrf import CSRFProtect

app = Flask(__name__)

CSRFProtect(app)

app.config['SECRET_KEY'] = 'somethignrandom'

@app.route('/', methods=['GET','POST'])
def helloworld():
if request.method == 'GET':
return render_template('index.html')
if request.method == 'POST': # anything post will autocheck csrf
print(request.form['info'])

## do something with the info, like write to a database

return 'nothing'

if __name__ == '__main__':
app.run(debug=True)

无需将 key 传递给 html 模板,因为 CSRFProtect 会自动传递 key 。

模板/index.html

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<meta name='csrf-token' content="{{ csrf_token() }}">
<script type='text/javascript' src="{{ url_for('static', filename='js/fire.js') }}"></script>

</head>

<body>
<p>Hello world!</p>
</body>
</html>

脚本.js

$(document).click(function() {

// post data to flask

$.post('/', {'info': 'test', '_csrf_token':$('meta[name="csrf-token"]').attr('content')});

return false;

};

关于python - Flask 防止表单注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59448482/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com