Skip to content
Advertisement

How to prevent directory traversal attack from Python code

I need to prevent from directory traversal attack from my code using Python. My code is below:

JavaScript

Here I need user is running like http://127.0.0.1:8000/createfile/?param=../../../../../../../../etc/passwd this it should prevent the directory traversal attack.

Advertisement

Answer

Suppose the user content is all located in

JavaScript

Ending with / is important as heinrichj mentions to ensure the check below matches against a specific directory.

You need to verify the final request is in there:

JavaScript

If the requested path is allowed to be the save_dir itself, you would also need to allow entry if os.path.realpath(requested_path)+'/' == safe_dir.

I encourage you to make sure all stuff you want accessible by the user in one place.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement