Skip to content

Commit 6d07b8d

Browse files
jaracoclaude
andcommitted
Validate namespace package names during legacy wheel installation
Entries in a wheel's namespace_packages.txt were split on '.' and passed straight to os.path.join, which interprets its arguments as paths. An entry that is absolute, drive-qualified, or UNC therefore discarded the destination egg directory entirely and placed a fixed-content __init__.py at a path chosen by the wheel. The report framed this as Windows-only, but only the drive-letter form is; an absolute POSIX path escapes just as readily. Namespace entries are now validated as dotted module names on every platform, with a containment check as defense in depth. This sink is reachable only through the deprecated setup_requires mechanism when setup() is invoked outside a PEP 517 frontend. The setuptools build backend disables setup_requires installation in every hook, so it does not reach it. Ref GHSA-xmj3-9gf7-h52w. Co-Authored-By: Claude Opus 5 <[email protected]>
1 parent 8419f00 commit 6d07b8d

3 files changed

Lines changed: 105 additions & 2 deletions

File tree

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
``Wheel.install_as_egg`` no longer creates namespace package directories
2+
outside of the destination egg directory. Entries in a wheel's
3+
``namespace_packages.txt`` were split on ``.`` and passed straight to
4+
``os.path.join``, so an entry that was absolute, drive-qualified, or UNC
5+
discarded the destination and placed an ``__init__.py`` at a path chosen by
6+
the wheel. Namespace entries are now validated as dotted module names on
7+
every platform -- see GHSA-xmj3-9gf7-h52w.
8+
9+
This code path is reached only by the deprecated ``setup_requires``
10+
mechanism when ``setup()`` is invoked outside a PEP 517 frontend; the
11+
setuptools build backend never reaches it.

‎setuptools/tests/test_wheel.py‎

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from packaging.tags import parse_tag
2020

2121
from setuptools._importlib import metadata
22-
from setuptools.wheel import Wheel
22+
from setuptools.wheel import Wheel, _resolve_namespace_dir
2323

2424
from .contexts import tempdir
2525
from .textwrap import DALS
@@ -687,3 +687,57 @@ def build_wheel(extra_file_defs=None, **kwargs):
687687
if sys.platform != 'win32':
688688
# Editable file mode has no effect on Windows
689689
assert oct(stat.S_IMODE(script_sh.stat().st_mode)) == "0o777"
690+
691+
692+
@pytest.mark.parametrize(
693+
"mod",
694+
[
695+
pytest.param('/tmp/outside', id='posix_absolute'),
696+
pytest.param(r'C:\Windows', id='drive_qualified'),
697+
pytest.param(r'\\server\share', id='unc'),
698+
pytest.param('foo/../../evil', id='separators'),
699+
pytest.param('..', id='parent'),
700+
pytest.param('', id='empty'),
701+
],
702+
)
703+
def test_namespace_package_escape(tmp_path, mod):
704+
"""
705+
A namespace entry that is not a dotted module name must be rejected
706+
rather than resolved as a path (GHSA-xmj3-9gf7-h52w).
707+
"""
708+
with pytest.raises(ValueError, match='invalid namespace package name'):
709+
_resolve_namespace_dir(str(tmp_path), mod)
710+
711+
712+
def test_namespace_package_resolves_dotted_name(tmp_path):
713+
expected = tmp_path / 'ns' / 'pkg'
714+
assert _resolve_namespace_dir(str(tmp_path), 'ns.pkg') == str(expected)
715+
716+
717+
def test_install_as_egg_rejects_namespace_escape(tmp_path):
718+
"""
719+
An attacker-controlled ``namespace_packages.txt`` must not create files
720+
outside the destination egg directory.
721+
"""
722+
outside = tmp_path / 'outside'
723+
outside.mkdir()
724+
dest = tmp_path / 'destination'
725+
726+
whl = tmp_path / 'demo_pkg-1.0-py3-none-any.whl'
727+
dist_info = 'demo_pkg-1.0.dist-info'
728+
with zipfile.ZipFile(whl, 'w') as zf:
729+
zf.writestr(
730+
f'{dist_info}/WHEEL',
731+
'Wheel-Version: 1.0\nGenerator: test\n'
732+
'Root-Is-Purelib: true\nTag: py3-none-any\n',
733+
)
734+
zf.writestr(
735+
f'{dist_info}/METADATA',
736+
'Metadata-Version: 2.1\nName: demo-pkg\nVersion: 1.0\n',
737+
)
738+
zf.writestr(f'{dist_info}/namespace_packages.txt', f'{outside}\n')
739+
740+
with pytest.raises(ValueError, match='invalid namespace package name'):
741+
Wheel(str(whl)).install_as_egg(str(dest))
742+
743+
assert not (outside / '__init__.py').exists()

‎setuptools/wheel.py‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,44 @@ def disable_info_traces() -> Iterator[None]:
7979
log.set_threshold(saved)
8080

8181

82+
def _resolve_namespace_dir(destination_eggdir, mod):
83+
r"""
84+
Return the directory for namespace package `mod` under `destination_eggdir`.
85+
86+
`mod` is a dotted module name, so every component must be an identifier.
87+
``os.path.join`` interprets its arguments as paths, so a component that is
88+
absolute, drive-qualified, or UNC discards `destination_eggdir` entirely,
89+
and one containing a separator escapes it (GHSA-xmj3-9gf7-h52w). Only
90+
Windows treats a drive letter that way, but an absolute POSIX path escapes
91+
just as readily, so the name is validated on every platform.
92+
93+
>>> _resolve_namespace_dir('dest', 'ns.pkg') == os.path.join('dest', 'ns', 'pkg')
94+
True
95+
>>> _resolve_namespace_dir('dest', '/tmp/outside')
96+
Traceback (most recent call last):
97+
...
98+
ValueError: invalid namespace package name: '/tmp/outside'
99+
>>> _resolve_namespace_dir('dest', r'C:\Windows')
100+
Traceback (most recent call last):
101+
...
102+
ValueError: invalid namespace package name: 'C:\\Windows'
103+
"""
104+
parts = mod.split('.')
105+
106+
if not all(part.isidentifier() for part in parts):
107+
raise ValueError(f"invalid namespace package name: {mod!r}")
108+
109+
dest = os.path.join(destination_eggdir, *parts)
110+
111+
# Belt and braces: confirm the result really does resolve within the egg
112+
# directory, catching an escape through a symlink already present in it.
113+
root = os.path.realpath(destination_eggdir)
114+
if not os.path.realpath(dest).startswith(os.path.join(root, '')):
115+
raise ValueError(f"invalid namespace package name: {mod!r}")
116+
117+
return dest
118+
119+
82120
class Wheel:
83121
def __init__(self, filename) -> None:
84122
match = WHEEL_NAME(os.path.basename(filename))
@@ -253,7 +291,7 @@ def _fix_namespace_packages(egg_info, destination_eggdir):
253291
namespace_packages = _read_utf8_with_fallback(namespace_packages).split()
254292

255293
for mod in namespace_packages:
256-
mod_dir = os.path.join(destination_eggdir, *mod.split('.'))
294+
mod_dir = _resolve_namespace_dir(destination_eggdir, mod)
257295
mod_init = os.path.join(mod_dir, '__init__.py')
258296
if not os.path.exists(mod_dir):
259297
os.mkdir(mod_dir)

0 commit comments

Comments
 (0)