[issue39420] Windows: convertenviron() doesn't parse environment variables properly

STINNER Victor report at bugs.python.org
Wed Jan 22 10:10:19 EST 2020


New submission from STINNER Victor <vstinner at python.org>:

os.environ is created by convertenviron() of posixmodule.c. The Windows implementation calls _wgetenv(L"") to initialize _wenviron, and then parses the _wenviron string.

The _wenviron string is parsed by search for the first "=" character to split between the variable name and the variable value. For example, "USER=vstinner" is parsed as name="USER" and value="vstinner".

The problem is that the _wputenv() function allows to insert variable names containing the "=" character (but reject names starting with "=" character). Python can inherit an environment with a name containing "=".

One solution can be to use GetEnvironmentStringsW() which uses null characters to separate variable name and variable value. It returns a string like "name1\0value1\0name2\0value2\0\0": the string ends with a null character as well, to mark the end of the list.

https://docs.microsoft.com/en-us/windows/win32/api/processenv/nf-processenv-getenvironmentstrings?redirectedfrom=MSDN

Python 3.8 *explicitly* rejects variable names containing "=", at least on Windows, likely to workaround this issue. But another program can inject such variable in the environment.

Example with a Python modified to not reject explicitly "=" in the varaible name:
---
import subprocess, os, sys
os.putenv("victor=", "secret")
code = """import os; print(f"victor: {os.getenv('victor')!r}"); print(f"victor=: {os.getenv('victor=')!r}")"""
subprocess.run([sys.executable, "-c", code])
---

Output:
---
victor: '=secret'
victor=: None
---

Expected output:
---
victor: None
victor=: '=secret'
---

----------
components: Library (Lib)
messages: 360473
nosy: vstinner
priority: normal
severity: normal
status: open
title: Windows: convertenviron() doesn't parse environment variables properly
versions: Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue39420>
_______________________________________


More information about the Python-bugs-list mailing list