Reputation: 75663
How can I check a user-supplied path is sanitised?
I want to ensure it has no wildcards nor any shenanigans. Right now, I'm checking that it is not escaping the correct folder so:
if os.path.commonprefix([os.path.abspath(path),os.getcwd()]) != os.getcwd():
# raise error etc..
But like all self-written security check code, I want it held up to better scrutiny! And it doesn't address that the path is actually legal after all that.
I will then be using the path to create assets and such.
Upvotes: 0
Views: 311
Reputation: 298432
You could use Werkzeug's secure_filename
:
werkzeug.utils.secure_filename(filename)
Pass it a filename and it will return a secure version of it. This filename can then safely be stored on a regular file system and passed to
os.path.join()
. The filename returned is an ASCII only string for maximum portability.On windows system the function also makes sure that the file is not named after one of the special device files.
>>> secure_filename("My cool movie.mov") 'My_cool_movie.mov' >>> secure_filename("../../../etc/passwd") 'etc_passwd' >>> secure_filename(u'i contain cool \xfcml\xe4uts.txt') 'i_contain_cool_umlauts.txt'
Upvotes: 4