Apply Restrictive TAR Extraction Policies
Core idea
TAR members can include regular files, directories, links and special files. In Python 3.13, explicitly request filter="data" for intended data extraction rather than depending on the default. Extraction filters were introduced in 3.12 and can be backported. A data filter reduces path and metadata hazards but does not guarantee safe handling of hostile input.
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) import tarfile from io import BytesIO b = BytesIO() with tarfile.open(fileobj=b, mode="w") as t: info = tarfile.TarInfo("note.txt") info.size = 2 t.addfile(info, BytesIO(b"ok")) b.seek(0) with tarfile.open(fileobj=b) as t: t.extractall(root, filter="data") print((root / "note.txt").read_text(encoding="utf-8"))The example creates its own regular-file archive and extracts into a fresh private directory.
Inspect a link without extracting
import tarfileinfo = tarfile.TarInfo("alias")info.type = tarfile.SYMTYPEinfo.linkname = "note.txt"print(info.isfile(), info.issym())A regular-file-only policy rejects this member; no filesystem link is created.
Common mistake
Do not fall back to fully trusted extraction when filters are unavailable. Inspect every member, disallow unnecessary links and special files, impose resource limits outside the extractor and clean up partial results. A private directory alone is insufficient.
Practice
Construct two TarInfo values, a regular file and a symbolic link; write a predicate allowing only regular files with expected names. Do not extract the link.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
TAR extraction boundaries
Check your understanding of tar extraction safety.
What is printed?
import tarfileprint(tarfile.TarInfo("x").isfile())What is printed?
import tarfilet=tarfile.TarInfo("folder")t.type=tarfile.DIRTYPEprint(t.isdir(),t.isfile())Which filter should be requested explicitly for ordinary data extraction on Python 3.13?
What remains necessary even with the data filter?