Skip to content

Commit dad645d

Browse files
vstinnergpsheadethanfurmanEclips4
committed
[3.14] gh-161705: Prevent shadowing stdlib in gzip/tarfile/zipfile CLI (#161706) (#161719)
gh-161705: Prevent shadowing stdlib in gzip/tarfile/zipfile CLI (#161706) Remove sys.path[0] in gzip, tarfile and zipfile command line interface to prevent shadowing standard library modules from extracted files. * Add sys._path0 variable. * pymain_sys_path_add_path0() sets sys._path0. * Add runpy._remove_sys_path0(). * gzip, tarfile and zipfile main functions now call _remove_sys_path0() to prevent shadowing stdlib modules from extracted files. Backport to 3.11: add test.support.make_clean_env() function and add Py_NewRef(Py_None) in sysmodule.c. (cherry picked from commit e891a91) Co-authored-by: Gregory P. Smith <[email protected]> Co-authored-by: Ethan Furman <[email protected]> Co-authored-by: Kirill Podoprigora <[email protected]> (cherry picked from commit 8aa5d65)
1 parent e34c7bb commit dad645d

15 files changed

Lines changed: 206 additions & 21 deletions

File tree

‎Doc/c-api/init_config.rst‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -561,8 +561,8 @@ PyConfig
561561
562562
.. c:member:: int safe_path
563563
564-
If equals to zero, ``Py_RunMain()`` prepends a potentially unsafe path to
565-
:data:`sys.path` at startup:
564+
If equals to zero, ``Py_RunMain()`` prepends a potentially unsafe
565+
:data:`sys._path0` to :data:`sys.path` at startup:
566566
567567
* If :c:member:`argv[0] <PyConfig.argv>` is equal to ``L"-m"``
568568
(``python -m module``), prepend the current working directory.

‎Doc/library/sys.rst‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1279,6 +1279,24 @@ always available.
12791279
* Module :mod:`site` This describes how to use .pth files to
12801280
extend :data:`sys.path`.
12811281

1282+
.. data:: _path0
1283+
1284+
Path prepended to :data:`sys.path` at Python startup:
1285+
1286+
* Current directory if running a module
1287+
with ``python -m module`` command line.
1288+
* Script's directory if running a script
1289+
with ``python script.py``.
1290+
* Otherwise an empty string, which means the current working directory,
1291+
for ``python -c code`` or ``python`` (REPL) command line.
1292+
1293+
If :option:`-P` or :option:`-I` command line options are used or if
1294+
:envvar:`PYTHONSAFEPATH` environment variable is used, :data:`sys._path0` is
1295+
``None`` and :data:`sys.path` is left unchanged.
1296+
1297+
.. versionadded:: next
1298+
1299+
12821300
.. data:: path_hooks
12831301

12841302
A list of callables that take a path argument to try to create a

‎Doc/using/cmdline.rst‎

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -300,10 +300,12 @@ Miscellaneous options
300300
Run Python in isolated mode. This also implies :option:`-E`, :option:`-P`
301301
and :option:`-s` options.
302302

303-
In isolated mode :data:`sys.path` contains neither the script's directory nor
304-
the user's site-packages directory. All ``PYTHON*`` environment
305-
variables are ignored, too. Further restrictions may be imposed to prevent
306-
the user from injecting malicious code.
303+
In isolated mode, Python does not prepend the potentially unsafe path
304+
:data:`sys._path0` to :data:`sys.path`, and ignores all ``PYTHON*``
305+
environment variables, e.g. :envvar:`PYTHONPATH` and :envvar:`PYTHONHOME`,
306+
that might be set.
307+
Further restrictions may be imposed to prevent the user from injecting
308+
malicious code.
307309

308310
.. versionadded:: 3.4
309311

@@ -331,14 +333,8 @@ Miscellaneous options
331333

332334
.. option:: -P
333335

334-
Don't prepend a potentially unsafe path to :data:`sys.path`:
335-
336-
* ``python -m module`` command line: Don't prepend the current working
337-
directory.
338-
* ``python script.py`` command line: Don't prepend the script's directory.
339-
If it's a symbolic link, resolve symbolic links.
340-
* ``python -c code`` and ``python`` (REPL) command lines: Don't prepend an
341-
empty string, which means the current working directory.
336+
Don't prepend the potentially unsafe path :data:`sys._path0` to
337+
:data:`sys.path`.
342338

343339
See also the :envvar:`PYTHONSAFEPATH` environment variable, and :option:`-E`
344340
and :option:`-I` (isolated) options.
@@ -635,7 +631,9 @@ conflict.
635631
.. envvar:: PYTHONSAFEPATH
636632

637633
If this is set to a non-empty string, don't prepend a potentially unsafe
638-
path to :data:`sys.path`: see the :option:`-P` option for details.
634+
path :data:`sys._path0` to :data:`sys.path`.
635+
636+
See also the :option:`-P` option.
639637

640638
.. versionadded:: 3.11
641639

‎Lib/gzip.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,11 @@ def decompress(data):
618618

619619
def main():
620620
from argparse import ArgumentParser
621+
import runpy
622+
623+
# Prevent shadowing a stdlib module from the extracted file
624+
runpy._remove_sys_path0()
625+
621626
parser = ArgumentParser(description=
622627
"A simple command line interface for the gzip module: act like gzip, "
623628
"but do not delete the input file.")

‎Lib/runpy.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,26 @@ def run_path(path_name, init_globals=None, run_name=None):
314314
pass
315315

316316

317+
def _remove_sys_path0():
318+
"""
319+
Remove sys._path0 from sys.path. Do nothing if sys._path0 is
320+
sys._stdlib_dir or if it has already been removed. Similar to using -P
321+
(safe path) command line option.
322+
"""
323+
path0 = sys._path0
324+
if path0 is None:
325+
return
326+
327+
if path0 == sys._stdlib_dir:
328+
return
329+
330+
# Remove all path0 copies, not only the first one.
331+
# We are intentionally not trying to normalize & match alternate
332+
# representations of path0, this is only intended to remove copies
333+
# of the exact value the runtime itself may have added.
334+
sys.path[:] = [path for path in sys.path if path != path0]
335+
336+
317337
if __name__ == "__main__":
318338
# Run the module specified as the next command line argument
319339
if len(sys.argv) < 2:

‎Lib/tarfile.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2975,6 +2975,10 @@ def is_tarfile(name):
29752975

29762976
def main():
29772977
import argparse
2978+
import runpy
2979+
2980+
# Prevent shadowing stdlib modules from extracted files
2981+
runpy._remove_sys_path0()
29782982

29792983
description = 'A simple command-line interface for tarfile module.'
29802984
parser = argparse.ArgumentParser(description=description)

‎Lib/test/support/__init__.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2289,3 +2289,13 @@ def control_characters_c0() -> list[str]:
22892289
C0 control characters defined as the byte range 0x00-0x1F, and 0x7F.
22902290
"""
22912291
return [chr(c) for c in range(0x00, 0x20)] + ["\x7F"]
2292+
2293+
2294+
def make_clean_env() -> dict[str, str]:
2295+
clean_env = os.environ.copy()
2296+
for k in clean_env.copy():
2297+
if k.startswith("PYTHON"):
2298+
clean_env.pop(k)
2299+
clean_env.pop("FORCE_COLOR", None)
2300+
clean_env.pop("NO_COLOR", None)
2301+
return clean_env

‎Lib/test/test_runpy.py‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
import unittest
1414
import warnings
1515
from test.support import no_tracing, verbose, requires_subprocess, requires_resource
16+
from test import support
17+
from test.support import os_helper
1618
from test.support.import_helper import forget, make_legacy_pyc, unload
1719
from test.support.os_helper import create_empty_file, temp_dir
1820
from test.support.script_helper import make_script, make_zip_script
@@ -835,5 +837,95 @@ def test_pymain_run_module(self):
835837
self.assertSigInt(["-m", ham.stem], cwd=ham.parent)
836838

837839

840+
class MiscTests(unittest.TestCase):
841+
def test_remove_sys_path0(self):
842+
# Check that all path0 copies are removed
843+
PATH0 = '/path/zero'
844+
STDLIB_PATH = '/to/stdlib'
845+
OTHER_PATH = '/other/path'
846+
sys_path = [PATH0, STDLIB_PATH, PATH0, '', OTHER_PATH, PATH0]
847+
expected = [STDLIB_PATH, '', OTHER_PATH]
848+
with (support.swap_attr(sys, '_stdlib_dir', STDLIB_PATH),
849+
support.swap_attr(sys, '_path0', PATH0),
850+
support.swap_attr(sys, 'path', sys_path)):
851+
runpy._remove_sys_path0()
852+
self.assertEqual(sys.path, expected)
853+
854+
# Calling it twice does nothing
855+
runpy._remove_sys_path0()
856+
self.assertEqual(sys.path, expected)
857+
858+
# Do nothing if sys._path0 is sys._stdlib_dir
859+
sys_path = ['', STDLIB_PATH, OTHER_PATH]
860+
expected = sys_path.copy()
861+
with (support.swap_attr(sys, '_stdlib_dir', STDLIB_PATH),
862+
support.swap_attr(sys, '_path0', STDLIB_PATH),
863+
support.swap_attr(sys, 'path', sys_path)):
864+
runpy._remove_sys_path0()
865+
self.assertEqual(sys.path, expected)
866+
867+
# Do nothing if sys._path0 is None
868+
sys_path = ['', STDLIB_PATH, OTHER_PATH]
869+
expected = sys_path.copy()
870+
with (support.swap_attr(sys, '_stdlib_dir', STDLIB_PATH),
871+
support.swap_attr(sys, '_path0', None),
872+
support.swap_attr(sys, 'path', sys_path)):
873+
runpy._remove_sys_path0()
874+
self.assertEqual(sys.path, expected)
875+
876+
def run_python(self, *args, PYTHONPATH=None):
877+
cmd = [sys.executable, *args]
878+
env = support.make_clean_env()
879+
if PYTHONPATH:
880+
env['PYTHONPATH'] = PYTHONPATH
881+
proc = subprocess.run(cmd, text=True, stderr=subprocess.PIPE, env=env)
882+
self.assertEqual(proc.returncode, 0, proc.stderr)
883+
884+
@support.requires_subprocess()
885+
def test_remove_sys_path0_run_python(self):
886+
CODE = textwrap.dedent("""
887+
import runpy, sys
888+
889+
# Remove sys.path[0]
890+
orig_path = sys.path.copy()
891+
path0 = sys._path0
892+
runpy._remove_sys_path0()
893+
894+
if path0 is not None and path0 in sys.path:
895+
raise Exception(f"path0 {path0!r} found in sys.path {sys.path!r}")
896+
if not sys.flags.safe_path:
897+
if sys.path == orig_path:
898+
raise Exception("sys.path was not changed")
899+
else:
900+
if sys.path != orig_path:
901+
raise Exception("sys.path was changed")
902+
903+
# Calling it twice must do nothing
904+
clean_path = sys.path.copy()
905+
runpy._remove_sys_path0()
906+
if sys.path != clean_path:
907+
raise Exception("sys.path was changed")
908+
""")
909+
910+
# Test "python -c code"
911+
self.run_python('-c', CODE)
912+
self.run_python('-P', '-c', CODE)
913+
914+
with tempfile.TemporaryDirectory() as tmpdir:
915+
name = 'test_remove_sys_path0'
916+
filename = os.path.join(tmpdir, f'{name}.py')
917+
with open(filename, 'w') as fp:
918+
fp.write(CODE)
919+
920+
# Test "python script.py"
921+
self.run_python(filename)
922+
self.run_python('-P', filename)
923+
924+
with os_helper.change_cwd(tmpdir):
925+
# Test "python -m module"
926+
self.run_python('-m', name)
927+
self.run_python('-P', '-m', name, PYTHONPATH=tmpdir)
928+
929+
838930
if __name__ == "__main__":
839931
unittest.main()

‎Lib/test/test_sys.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1186,6 +1186,15 @@ def test_stdlib_dir(self):
11861186
self.assertEqual(os.path.normpath(sys._stdlib_dir),
11871187
os.path.normpath(expected))
11881188

1189+
def test_path(self):
1190+
self.assertIsInstance(sys.path, list)
1191+
for path in sys.path:
1192+
self.assertIsInstance(path, str)
1193+
1194+
def test_path0(self):
1195+
self.assertTrue(sys._path0 is None or isinstance(sys._path0, str),
1196+
sys._path0)
1197+
11891198

11901199
@test.support.cpython_only
11911200
class UnraisableHookTest(unittest.TestCase):

‎Lib/test/test_zipfile.py‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,16 @@ def get_files(test):
5151
yield f
5252
test.assertFalse(f.closed)
5353

54+
55+
@contextlib.contextmanager
56+
def save_restore_sys_path():
57+
old_path = sys.path.copy()
58+
try:
59+
yield
60+
finally:
61+
sys.path[:] = old_path
62+
63+
5464
class AbstractTestsWithSourceFile:
5565
@classmethod
5666
def setUpClass(cls):
@@ -4017,17 +4027,18 @@ def test_write_with_metadata_encoding(self):
40174027
def test_cli_with_metadata_encoding(self):
40184028
errmsg = "Non-conforming encodings not supported with -c."
40194029
args = ["--metadata-encoding=shift_jis", "-c", "nonesuch", "nonesuch"]
4020-
with captured_stdout() as stdout:
4021-
with captured_stderr() as stderr:
4030+
with (captured_stdout() as stdout,
4031+
captured_stderr() as stderr,
4032+
save_restore_sys_path()):
40224033
self.assertRaises(SystemExit, zipfile.main, args)
40234034
self.assertEqual(stdout.getvalue(), "")
40244035
self.assertIn(errmsg, stderr.getvalue())
40254036

4026-
with captured_stdout() as stdout:
4037+
with captured_stdout() as stdout, save_restore_sys_path():
40274038
zipfile.main(["--metadata-encoding=shift_jis", "-t", TESTFN])
40284039
listing = stdout.getvalue()
40294040

4030-
with captured_stdout() as stdout:
4041+
with captured_stdout() as stdout, save_restore_sys_path():
40314042
zipfile.main(["--metadata-encoding=shift_jis", "-l", TESTFN])
40324043
listing = stdout.getvalue()
40334044
for name in self.file_names:
@@ -4046,7 +4057,9 @@ def test_cli_with_metadata_encoding_extract(self):
40464057
except UnicodeEncodeError:
40474058
self.skipTest(f'cannot encode file name {fn!r}')
40484059

4049-
zipfile.main(["--metadata-encoding=shift_jis", "-e", TESTFN, TESTFN2])
4060+
with save_restore_sys_path():
4061+
zipfile.main(["--metadata-encoding=shift_jis", "-e",
4062+
TESTFN, TESTFN2])
40504063
listing = os.listdir(TESTFN2)
40514064
for name in self.file_names:
40524065
self.assertIn(name, listing)

0 commit comments

Comments
 (0)