Constrain Paths and Archive Members to a Controlled Root
Core idea
Path containment means that a resolved target lies within an authorized directory. For a private tree without concurrent hostile changes, resolve the root and candidate and check is_relative_to before access. Reject absolute user paths and restrict accepted names. For tar archives on Python 3.13, explicitly request filter="data"; it reduces dangerous extraction behavior but does not guarantee safety or resource limits.
from pathlib import Pathfrom tempfile import TemporaryDirectorywith TemporaryDirectory() as tmp: root = (Path(tmp) / 'files').resolve() root.mkdir() def allowed(name): p = Path(name) return not p.is_absolute() and (root / p).resolve().is_relative_to(root) print(allowed('report.txt')) print(allowed('../outside.txt'))Containment is checked on resolved path components, not a string prefix. No outside file is accessed.
Expected output:
TrueFalseExtract one known tiny archive
import io, tarfilefrom pathlib import Pathfrom tempfile import TemporaryDirectorystream = io.BytesIO()with tarfile.open(fileobj=stream, mode='w') as archive: info = tarfile.TarInfo('note.txt') info.size = 2 archive.addfile(info, io.BytesIO(b'ok'))stream.seek(0)with TemporaryDirectory() as tmp: with tarfile.open(fileobj=stream, mode='r:') as archive: archive.extractall(tmp, filter='data') print((Path(tmp) / 'note.txt').read_text(encoding='utf-8'))The locally created archive has one ordinary file. The explicit data filter is used even for this trusted fixture.
Expected output:
okCommon mistake
A prefix check is not path containment. resolve followed by open is vulnerable to filesystem changes between checking and use; use stronger OS-level containment in adversarial trees. Untrusted archive extraction also requires limits, link policy and isolation.
Practice
Test your private-root guard with a normal name and a rejected parent-relative path without opening rejected paths. Design extraction quotas for member count and total size.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Path and archive traversal
Check your understanding of path and archive traversal.
What is printed?
from pathlib import PurePosixPathprint(PurePosixPath("/data/a").is_relative_to("/data"))What is printed?
from pathlib import PurePosixPathprint(PurePosixPath("/database/a").is_relative_to("/data"))Does tarfile data filtering enforce total extracted size?
What is a limitation of resolving then opening a path?