How can I safely go through an arbitrarily deep path to webapp (in this case, a check box)?

I have a form that submits a string to my Flask application when submitting the form. The string is the path to the file, so I want to make sure that it does not contain anything contrary, for example ../../../etc/passwd . Werkzeug, which uses Flask, has a convenient feature called secure_filename that removes nasty things from file names. Unfortunately, when supplying the full path, such as templates/example.html , it converts / to _ , so we get templates_example.html .

It seems reasonable to split the path into levels, so I send the templates and example.html separately, and then combine them on the server again. This works great, except that the path can be arbitrarily deep. I could just connect dir1/dir2/dir3/dir4 and hope no one gets deeper than dir4 , but that seems dumb.

What is the correct way to handle validation of paths of unknown depth? Confirm differently? Send data in different ways? Encode the path in different ways and then decode it on the server?

+6
source share
2 answers

You can use werkzeug.routing.PathConverter to handle arbitrary paths as follows:

 from flask import Flask app = Flask(__name__) @app.route("/arbitrary/<path:my_path>") def arbitrary_path(my_path): return my_path if __name__ == "__main__": app.run() 

With the simplified sample above, you can see that if you visit http://127.0.0.1:5000/arbitrary/dir1/dir2/dir3/dir4 , it will return dir1/dir2/dir3/dir4 , and if you visit http://127.0.0.1:5000/arbitrary/dir1/dir2/dir3/dir4/dir5/dir6/dir7/dir8/dir9/dir10 dir1/dir2/dir3/dir4/dir5/dir6/dir7/dir8/dir9/dir10 , it will return dir1/dir2/dir3/dir4/dir5/dir6/dir7/dir8/dir9/dir10

+2
source

In situations such as this flag, safe_join , which raises 404 if the user tries to leave the path:

 >>> 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 
+8
source

Source: https://habr.com/ru/post/895087/


All Articles