Skip to main content

18. Avoiding Path Traversal Attacks

Never trust file paths from user input. Attackers can escape directories using ../.

Insecure Example

filename = input("Enter file to read: ")
with open(filename) as f:
print(f.read())

Secure Example

import os

def safe_open(base_dir, filename):
safe_path = os.path.abspath(os.path.join(base_dir, filename))
if not safe_path.startswith(base_dir):
raise PermissionError("Path traversal detected.")
with open(safe_path, "r", encoding="utf-8") as f:
return f.read()

print(safe_open("/home/user/data", "report.txt"))

Lesson: Restrict file access to a known base directory and validate all paths.