Cybersecurity Path Traversal
Use a server-owned identifier map instead of accepting a filesystem path.
How it works
Path traversal occurs when an input path escapes its intended area. Normalising a path does not automatically enforce an access policy; symlinks, platform separators and race conditions complicate generic file access. For a small fixed download set, accept an opaque identifier and map it to a trusted resource. Check user permission separately before reading the file.
Run the code
Save the complete source as path-traversal.py in a separate learning folder, then run python path-traversal.py. The reviewed runtime is Python 3.12.14 with the standard library; no third-party packages are required. These are local examples, not browser playground programs. Apache, MySQL and PHP are not needed.
Example
downloads = {"guide": "volunteer-guide.pdf", "terms": "lending-terms.pdf"}
def select_download(identifier):
if identifier not in downloads:
raise ValueError("unknown download")
return downloads[identifier]
assert select_download("guide") == "volunteer-guide.pdf"
for value in ["../private.txt", "..\\private.txt", "/etc/passwd"]:
try:
select_download(value)
except ValueError:
continue
raise AssertionError(value)
print("known ID selected; three path inputs rejected")
Expected result
known ID selected; three path inputs rejected
No submitted string becomes a filesystem path. The values in the map are application-owned and the example reads no files. For uploads or user-generated resources, use a storage abstraction, per-object authorisation and a carefully tested resolver rather than extending this tiny mapping into an unrestricted file browser.
Technical reference: OWASP Cheat Sheet Series. Check the guidance for your actual platform and deployment.