Does my code prevent directory traversal?

前端 未结 3 1557
无人共我
无人共我 2021-02-02 14:00

Is the following code snippet from a Python WSGI app safe from directory traversal? It reads a file name passed as parameter and returns the named file.

file_nam         


        
3条回答
  •  -上瘾入骨i
    2021-02-02 14:19

    There's a much simpler solution here:

    relative_path = os.path.relpath(path, start=self.test_directory)
    has_dir_traversal = relative_path.startswith(os.pardir)
    

    relpath takes care of normalising path for us. And if the relative path starts with .., then you don't allow it.

提交回复
热议问题