This Python tutorial explains Detect and Avoid Path Traversal Vulnerabilities. Follow the example, inspect the output, and practise an input change so you understand the behavior rather than simply copying the syntax.
What This Feature Does
Prevent user-supplied filenames from escaping an intended storage directory.
Path traversal occurs when untrusted components such as ../ or symlinks lead outside an allowed directory. Resolve the candidate against a trusted base, verify it is under that base, and still consider symlink races when operating in attacker-writable directories.
When to Use It
This technique belongs to pathlib and file paths. It is useful when the input, operation and expected outcome are known. Start with a small controlled example before integrating it into a larger workflow.
Step-by-Step Python Example
Read the code once before running it. Notice which values are inputs, which function or method performs the work, and whether the result is returned or stored by changing an existing object.
from pathlib import Path
storage_root = (Path.cwd() / "safe-uploads").resolve()
requested_name = "../private.txt"
candidate_path = (storage_root / requested_name).resolve()
try:
candidate_path.relative_to(storage_root)
except ValueError:
print("Rejected path outside the upload directory")
Understanding the Code
- First, the imports make pathlib available. They provide the filesystem, data or standard-library functions used later.
- Find the call (Path.cwd() / "safe-uploads").resolve(). Its parameters determine the specific operation demonstrated in the title.
- Its purpose is to prevent user-supplied filenames from escaping an intended storage directory. Compare this description against the result printed by the program.
- The try/except section demonstrates how an expected error is handled, rather than allowing the example to stop unexpectedly.
- The print() expressions display a checkable outcome. Print values and exception names are not substitutes for the program result itself.
Expected Output
Rejected path outside the upload directory
The output is the observable result of the sample operation. Compare its value and type with the explanation, not just whether the program runs.
Important Details and Edge Cases
For security-critical file opening, use OS-specific directory-descriptor APIs and restrictive permissions.
Before applying this to real documents, check whether the method reads data, creates a new file, moves it, or overwrites an existing file. Work in a disposable test directory first and handle OSError-related failures in applications.
Practice: Try It Yourself
Test both a normal filename and a traversal attempt against an allowed base.
Begin by copying the example into a separate practice file. Change one input at a time, run it again, and describe why the result changed. If the exercise writes or deletes files, keep it inside a temporary test folder.
Official Python Documentation
For the complete reference, see the Python standard library documentation.
Common Beginner Mistakes
- Checking only whether the string starts with an allowed folder name instead of testing path components.
- Believing a resolve-and-check step alone eliminates symlink race conditions in hostile directories.
- Before applying this to real documents, check whether the method reads data, creates a new file, moves it, or overwrites an existing file. Work in a disposable test directory first and handle OSError-related failures in applications.
Key Takeaways
- Prevent user-supplied filenames from escaping an intended storage directory.
- Path traversal occurs when untrusted components such as ../ or symlinks lead outside an allowed directory. Resolve the candidate against a trusted base, verify it is under that base, and still consider symlink races when operating in.
- Avoid this common pitfall: Checking only whether the string starts with an allowed folder name instead of testing path components.