Debian Codegraph @

src/build/_compat/tarfile.py

raw
1 from __future__ import annotations
2
3
4 __lazy_modules__ = [
5 'pathlib',
6 'tarfile',
7 ]
8
9 import sys
10 import tarfile
11
12 from pathlib import Path
13
14
15 # Per https://peps.python.org/pep-0706/, the "data" filter became the default
16 # in Python 3.14. The first series of releases with the filter had a broken
17 # filter that could not process symlinks correctly, so the patch releases that
18 # fixed it are the lower bounds here.
19 _HAS_DATA_FILTER = (
20 (3, 10, 13) <= sys.version_info < (3, 11) or (3, 11, 5) <= sys.version_info < (3, 12) or sys.version_info >= (3, 12)
21 )
22
23
24 # On runtimes that ship the stdlib ``data`` filter we delegate to it; the fallback branch is
25 # only reached on 3.10.0-3.10.12 / 3.11.0-3.11.4 and validates each member manually before extraction.
26 if _HAS_DATA_FILTER:
27
28 def safe_extractall(tar: tarfile.TarFile, path: Path | str) -> None: # pragma: no cover
29 """Extract every member of ``tar`` into ``path`` via the PEP 706 ``data`` filter."""
30 tar.extractall(path, filter='data')
31
32 else:
33
34 def safe_extractall(tar: tarfile.TarFile, path: Path | str) -> None: # pragma: no cover
35 """Validate every member of ``tar``, then extract into ``path``.
36
37 Reached on 3.10.0-3.10.12 / 3.11.0-3.11.4 where the stdlib ``data`` filter is missing. Device or special files,
38 paths that escape ``path``, and symlinks/hardlinks whose targets resolve outside ``path`` are rejected before
39 any write hits the disk.
40
41 """
42 base = Path(path).resolve()
43 for member in tar.getmembers():
44 _validate_safe_member(member, base)
45 tar.extractall(path) # noqa: S202
46
47
48 def _validate_safe_member(member: tarfile.TarInfo, base: Path) -> None:
49 if member.ischr() or member.isblk() or member.isfifo():
50 msg = f'refusing to extract special device file {member.name!r}'
51 raise tarfile.TarError(msg)
52 target = (base / member.name).resolve(strict=False)
53 if not target.is_relative_to(base):
54 msg = f'refusing to extract {member.name!r}: path escapes destination'
55 raise tarfile.TarError(msg)
56 if member.issym() or member.islnk():
57 link_base = target.parent if member.issym() else base
58 link_target = (link_base / member.linkname).resolve(strict=False)
59 if not link_target.is_relative_to(base):
60 msg = f'refusing to extract {member.name!r}: link target escapes destination'
61 raise tarfile.TarError(msg)
62
63
64 __all__ = [
65 'safe_extractall',
66 ]