Skip to content

Instantly share code, notes, and snippets.

@kousu
Created April 5, 2021 09:31
Show Gist options
  • Save kousu/bf5610187b608d79d415b1436091ab2d to your computer and use it in GitHub Desktop.
Save kousu/bf5610187b608d79d415b1436091ab2d to your computer and use it in GitHub Desktop.
Sanitize a file path against directory traversal in python
import os.path
def sanitize_path(path):
"""
Sanitize a path against directory traversals
Based on https://stackoverflow.com/questions/13939120/sanitizing-a-file-path-in-python.
>>> sanitize_path('../test')
'test'
>>> sanitize_path('../../test')
'test'
>>> sanitize_path('../../abc/../test')
'test'
>>> sanitize_path('../../abc/../test/fixtures')
'test/fixtures'
>>> sanitize_path('../../abc/../.test/fixtures')
'.test/fixtures'
>>> sanitize_path('/test/foo')
'test/foo'
>>> sanitize_path('./test/bar')
'test/bar'
>>> sanitize_path('.test/baz')
'.test/baz'
>>> sanitize_path('qux')
'qux'
"""
# - pretending to chroot to the current directory
# - cancelling all redundant paths (/.. = /)
# - making the path relative
return os.path.relpath(os.path.join("/", path), "/")
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment