I have a form that sends a string to my Flask app when the form is posted. The string is a filepath, so I'd like to make sure it doesn't contain anything nasty, like ../../../etc/passwd
. Werkzeug, which Flask uses, has a handy function called secure_filename
that strips nasty stuff out of filenames. Unfortunately, when fed a full path like templates/example.html
, it converts the /
to _
, so we end up with templates_example.html
.
It seems sensible, then, to split the path up into levels, so I send templates
and example.html
separately and then join them together again on the server. This works great, except that the path can be arbitrarily deep. I could just string together dir1/dir2/dir3/dir4
and hope that nobody every goes deeper than dir4
, but that seems dumb.
What's the right way to handle validation of paths of unknown depth? Validate differently? Send the data differently? Encode the path differently, then decode it on the server?
You can use werkzeug.routing.PathConverter to handle arbitrary paths like so:
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 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