Path traversal (ARCH2103)
Key python.security.path-traversal · Severity error · Category security · CWE CWE-22
Building a file path from untrusted input without normalization lets an attacker use ../ to escape the intended directory and reach arbitrary files.
Incorrect
Section titled “Incorrect”import os
def read_file(name): with open(os.path.join("/var/data", name)) as f: return f.read()Correct
Section titled “Correct”import os
BASE = "/var/data"
def read_file(name): path = os.path.realpath(os.path.join(BASE, name)) if not path.startswith(BASE + os.sep): raise ValueError("invalid path") with open(path) as f: return f.read()Normalize the path and verify the result stays within the allowed root directory.