How can I securely pass an arbitrarily deep path to a webapp (Flask, in this case)? How can I securely pass an arbitrarily deep path to a webapp (Flask, in this case)? flask flask

How can I securely pass an arbitrarily deep path to a webapp (Flask, in this case)?


For situations like this Flask has safe_join which raises 404 if a user attempts 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


You can use werkzeug.routing.PathConverter to handle arbitrary paths like so:

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

With the oversimplified 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 it will return dir1/dir2/dir3/dir4/dir5/dir6/dir7/dir8/dir9/dir10