gh-57684: Add -P cmdline option and PYTHONSAFEPATH env var (#31542)

Add the -P command line option and the PYTHONSAFEPATH environment
variable to not prepend a potentially unsafe path to sys.path.

* Add sys.flags.safe_path flag.
* Add PyConfig.safe_path member.
* Programs/_bootstrap_python.c uses config.safe_path=0.
* Update subprocess._optim_args_from_interpreter_flags() to handle
  the -P command line option.
* Modules/getpath.py sets safe_path to 1 if a "._pth" file is
  present.
This commit is contained in:
Victor Stinner 2022-05-06 01:34:11 +02:00 • committed by GitHub
parent f6dd14c653
commit ada8b6d1b1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 174 additions and 35 deletions

View file

@ -71,6 +71,7 @@ main(int argc, char **argv)
config.parse_argv = 1;
// add current script dir to sys.path
config.isolated = 0;
config.safe_path = 0;
#ifdef MS_WINDOWS
status = PyConfig_SetArgv(&config, argc, argv);

View file

@ -676,6 +676,8 @@ static int test_init_from_config(void)
Py_FrozenFlag = 0;
config.pathconfig_warnings = 0;
config.safe_path = 1;
config._isolated_interpreter = 1;
init_from_config_clear(&config);
@ -742,6 +744,7 @@ static void set_most_env_vars(void)
putenv("PYTHONFAULTHANDLER=1");
putenv("PYTHONIOENCODING=iso8859-1:replace");
putenv("PYTHONPLATLIBDIR=env_platlibdir");
putenv("PYTHONSAFEPATH=1");
}
@ -823,6 +826,10 @@ static int test_init_isolated_flag(void)
Py_IsolatedFlag = 0;
config.isolated = 1;
// These options are set to 1 by isolated=1
config.safe_path = 0;
config.use_environment = 1;
config.user_site_directory = 1;
config_set_program_name(&config);
set_all_env_vars();
@ -901,6 +908,7 @@ static int test_preinit_dont_parse_argv(void)
wchar_t *argv[] = {L"python3",
L"-E",
L"-I",
L"-P",
L"-X", L"dev",
L"-X", L"utf8",
L"script.py"};
@ -934,7 +942,7 @@ static int test_preinit_parse_argv(void)
/* Pre-initialize implicitly using argv: make sure that -X dev
is used to configure the allocation in preinitialization */
wchar_t *argv[] = {L"python3", L"-X", L"dev", L"script.py"};
wchar_t *argv[] = {L"python3", L"-X", L"dev", L"-P", L"script.py"};
config_set_argv(&config, Py_ARRAY_LENGTH(argv), argv);
config_set_program_name(&config);
init_from_config_clear(&config);