fyh*_*ang 2 python security user-input web-applications flask
我在Python/Flask Web应用程序中使用用户提供的名称作为路径组件:例如,用户创建一个名为"hello"的项目,提示我的Web应用程序创建一个名为"data/hello /"的文件夹来存储文件用户将上传.我想知道如何清理用户提供的名称,以便例如用户不能输入"../hello"并且在不同的目录中创建文件夹.我能想出的最好的基于路径名的解决方案是这样的:
import os.path
rpath = os.path.relpath(input_path)
safepath = rpath[rpath.index('../'):]
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来确保我的网络应用程序不访问目录之外的data文件?谢谢!
Werkzeug提供secure_filename了帮助,Flask文档中提供了一个示例
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename) #Sanitised here
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('uploaded_file',
filename=filename))
Run Code Online (Sandbox Code Playgroud)