我有一个表单,当表单发布时,它会向我的 Flask 应用程序发送一个字符串。该字符串是一个文件路径,所以我想确保它不包含任何讨厌的东西,比如 ../../../etc/passwd
。 Flask 使用的 Werkzeug 有一个名为 secure_filename
的方便函数,可以从文件名中去除讨厌的东西。不幸的是,当输入像 templates/example.html
这样的完整路径时,它将 /
转换为 _
,所以我们最终得到 templates_example.html
.
那么,将路径分成多个级别似乎是明智的,所以我分别发送了 templates
和 example.html
,然后在服务器上再次将它们连接在一起。这很好用,除了路径可以任意深。我可以将 dir1/dir2/dir3/dir4
串在一起,并希望没有人比 dir4
更深入,但这看起来很愚蠢。
处理未知深度路径验证的正确方法是什么?验证不同?以不同方式发送数据?对路径进行不同的编码,然后在服务器上对其进行解码?
最佳答案
对于这种情况,Flask 有 safe_join
,如果用户试图离开路径,它会引发 404:
>>> safe_join('/foo/bar', 'test')
'/foo/bar/test'
>>> safe_join('/foo/bar', 'test/../other_test')
'/foo/bar/other_test'
>>> safe_join('/foo/bar', 'test/../../../etc/htpassw')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mitsuhiko/Development/flask/flask/helpers.py", line 432, in safe_join
raise NotFound()
werkzeug.exceptions.NotFound: 404: Not Found
关于python - 我怎样才能安全地将任意深度的路径传递给 web 应用程序(在本例中为 Flask)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7069753/