防止瓶型注射

问题描述 投票:2回答:1

python / flask如何阻止异物注入?

请考虑以下mwe:

app.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)

templates / 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>

static / js / fire.js

$(document).click(function() {

    // post data to flask

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

    return false;

};

我的问题是:

  1. 可以从国外网站进行注入吗?后续行动:这怎么办? (例如,也许通过发布到我的网站网址的表单?)
  2. 如果可以进行注入,我该如何在app.py脚本中阻止注入?

编辑

这里是一个非常基本的脚本,可用于针对上述烧瓶应用程序测试进样。接受的答案将阻止此脚本:

<!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>
python jquery flask csrf
1个回答
2
投票
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)
不需要将密钥传递给html模板,因为CSRFProtect将自动传递密钥。

templates / 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>
script.js

$(document).click(function() { // post data to flask $.post('/', {'info': 'test', '_csrf_token':$('meta[name="csrf-token"]').attr('content')}); return false; };

© www.soinside.com 2019 - 2024. All rights reserved.