Path Traversal, File Access, and Containment
Use a directory tree to follow a filename into a file operation, including parent paths, absolute paths, and links.
You’re reading a preview. Premium includes the full lesson and specialist practice. View the full curriculum.
A log viewer should open files in its own log directory. A request supplies the filename. What happens when that filename is ../private/marker.txt?
training/
logs/ ← intended directory
today.log
private/
marker.txt ← outside that directory
Path traversal means a file selection escapes the area the caller may use. Joining a directory and a name does not by itself prove where the final operation goes.
We'll start with a normal log read, then inspect parent components, absolute paths, and links. A link can point somewhere different from the path's appearance, so we'll keep the actual file operation in view.
Identify the file operation and permission boundary
A path can select a read, write, overwrite, delete, archive destination, template, or executable include. These have different consequences. A log handler using open(...).read() proves a read path; it does not automatically prove code execution. Operating-system permissions constrain which objects the service can access but do not replace the application's narrower product policy.
# Unsafe original log-reader outline.
filename = request.args['file']
path = os.path.join(LOG_ROOT, filename)
with open(path, 'r', encoding='utf-8') as stream:
return stream.read()
Relative parent components can leave a directory. On relevant platforms, an absolute later component can replace earlier joined components. Windows drive, separator, and UNC semantics differ from POSIX. Review the actual target platform and decoding layers rather than assuming one slash replacement is universal.
Trace selection, resolution, and use under explicit filesystem assumptions.
Select. A filename is a proposed filesystem selector.
name = request.args["file"]
Resolve. Absolute paths, parent components, and links can change the actual target.
candidate = root / name
resolved = candidate.resolve()
Use. The actual operation must remain within the authorized object set under the race model.
checked object == opened object
authorized scope == consumed scope
Review question: Containment is about the object actually used, not a reassuring string prefix.