44. Path Injection and File-Based Exploits
Path injection allows attackers to access files outside intended directories using .. or absolute paths.
Insecure Example
filename = input("Enter file: ")
with open(filename) as f:
print(f.read())
Secure Example
import os
base = "/srv/app/data"
filename = input("Enter file: ")
full = os.path.abspath(os.path.join(base, filename))
if not full.startswith(base):
raise PermissionError("Invalid file path")
with open(full, "r", encoding="utf-8") as f:
print(f.read())
✅ Lesson: Canonicalize and validate paths against a trusted base directory before accessing files.