CVE-2025-68146: filelock has TOCTOU race condition that allows symlink attacks during lock file creation
Impact
A Time-of-Check-Time-of-Use (TOCTOU) race condition allows local attackers to corrupt or truncate arbitrary user files through symlink attacks. The vulnerability exists in both Unix and Windows lock file creation where filelock checks if a file exists before opening it with OTRUNC. An attacker can create a symlink pointing to a victim file in the time gap between the check and open, causing os.open() to follow the symlink and truncate the target file.
Who is impacted:
All users of filelock on Unix, Linux, macOS, and Windows systems. The vulnerability cascades to dependent libraries:
- virtualenv users: Configuration files can be overwritten with virtualenv metadata, leaking sensitive paths - PyTorch users: CPU ISA cache or model checkpoints can be corrupted, causing crashes or ML pipeline failures - poetry/tox users: through using virtualenv or filelock on their own.
Attack requires local filesystem access and ability to create symlinks (standard user permissions on Unix; Developer Mode on Windows 10+). Exploitation succeeds within 1-3 attempts when lock file paths are predictable.
Patches
Fixed in version 3.20.1.
Unix/Linux/macOS fix: Added ONOFOLLOW flag to os.open() in UnixFileLock.\acquire() to prevent symlink following.
Windows fix: Added GetFileAttributesW API check to detect reparse points (symlinks/junctions) before opening files in WindowsFileLock.\acquire().
Users should upgrade to filelock 3.20.1 or later immediately.
Workarounds
If immediate upgrade is not possible:
1. Use SoftFileLock instead of UnixFileLock/WindowsFileLock (note: different locking semantics, may not be suitable for all use cases) 2. Ensure lock file directories have restrictive permissions (chmod 0700) to prevent untrusted users from creating symlinks 3. Monitor lock file directories for suspicious symlinks before running trusted applications
Warning: These workarounds provide only partial mitigation. The race condition remains exploitable. Upgrading to version 3.20.1 is strongly recommended.
Technical Details: How the Exploit Works
The Vulnerable Code Pattern
Unix/Linux/macOS (src/filelock/unix.py:39-44):
python def acquire(self) -> None: ensuredirectoryexists(self.lockfile) openflags = os.ORDWR | os.OTRUNC # (1) Prepare to truncate if not Path(self.lockfile).exists(): # (2) CHECK: Does file exist? openflags |= os.OCREAT fd = os.open(self.lockfile, openflags, ...) # (3) USE: Open and truncate
Windows (src/filelock/windows.py:19-28):
python def acquire(self) -> None: raiseonnotwritablefile(self.lockfile) # (1) Check writability ensuredirectoryexists(self.lockfile) flags = os.ORDWR | os.OCREAT | os.OTRUNC # (2) Prepare to truncate fd = os.open(self.lockfile, flags, ...) # (3) Open and truncate
The Race Window
The vulnerability exists in the gap between operations:
Unix variant:
Time Victim Thread Attacker Thread ---- ------------- --------------- T0 Check: lockfile exists? → False T1 ↓ RACE WINDOW T2 Create symlink: lock → victimfile T3 Open lockfile with OTRUNC → Follows symlink → Opens victimfile → Truncates victimfile to 0 bytes! ☠️
Windows variant:
Time Victim Thread Attacker Thread ---- ------------- --------------- T0 Check: lockfile writable? T1 ↓ RACE WINDOW T2 Create symlink: lock → victimfile T3 Open lockfile with OTRUNC → Follows symlink/junction → Opens victimfile → Truncates victimfile to 0 bytes! ☠️
Step-by-Step Attack Flow
1. Attacker Setup:
python Attacker identifies target application using filelock lockpath = "/tmp/myapp.lock" # Predictable lock path victimfile = "/home/victim/.ssh/config" # High-value target
2. Attacker Creates Race Condition:
python import os import threading
def attackerthread(): # Remove any existing lock file try: os.unlink(lockpath) except FileNotFoundError: pass
# Create symlink pointing to victim file os.symlink(victimfile, lockpath) print(f"[Attacker] Created: {lockpath} → {victimfile}")
Launch attack threading.Thread(target=attackerthread).start()
3. Victim Application Runs:
python from filelock import UnixFileLock
Normal application code lock = UnixFileLock("/tmp/myapp.lock") lock.acquire() # ← VULNERABILITY TRIGGERED HERE At this point, /home/victim/.ssh/config is now 0 bytes!
4. What Happens Inside os.open():
On Unix systems, when os.open() is called:
c // Linux kernel behavior (simplified) int open(const char pathname, int flags) { struct file f = pathlookup(pathname); // Resolves symlinks by default!
if (flags & OTRUNC) { truncatefile(f); // ← Truncates the TARGET of the symlink }
return filedescriptor; }
Without ONOFOLLOW flag, the kernel follows the symlink and truncates the target file.
Why the Attack Succeeds Reliably
Timing Characteristics:
- Check operation (Path.exists()): ~100-500 nanoseconds - Symlink creation (os.symlink()): ~1-10 microseconds - Race window: ~1-5 microseconds (very small but exploitable) - Thread scheduling quantum: ~1-10 milliseconds
Success factors:
1. Tight loop: Running attack in a loop hits the race window within 1-3 attempts 2. CPU scheduling: Modern OS thread schedulers frequently context-switch during I/O operations 3. No synchronization: No atomic file creation prevents the race 4. Symlink speed: Creating symlinks is extremely fast (metadata-only operation)
Real-World Attack Scenarios
Scenario 1: virtualenv Exploitation
python Victim runs: python -m venv /tmp/myenv Attacker racing to create: os.symlink("/home/victim/.bashrc", "/tmp/myenv/pyvenv.cfg")
Result: /home/victim/.bashrc overwritten with: home = /usr/bin/python3 include-system-site-packages = false version = 3.11.2 ← Original .bashrc contents LOST + virtualenv metadata LEAKED to attacker
Scenario 2: PyTorch Cache Poisoning
python Victim runs: import torch PyTorch checks CPU capabilities, uses filelock on cache Attacker racing to create: os.symlink("/home/victim/.torch/compiledmodel.pt", "/home/victim/.cache/torch/cpuisacheck.lock")
Result: Trained ML model checkpoint truncated to 0 bytes Impact: Weeks of training lost, ML pipeline DoS
Why Standard Defenses Don't Help
File permissions don't prevent this:
- Attacker doesn't need write access to victimfile - os.open() with OTRUNC follows symlinks using the victim's permissions - The victim process truncates its own file
Directory permissions help but aren't always feasible:
- Lock files often created in shared /tmp directory (mode 1777) - Applications may not control lock file location - Many apps use predictable paths in user-writable directories
File locking doesn't prevent this:
- The truncation happens during the open() call, before any lock is acquired - fcntl.flock() only prevents concurrent lock acquisition, not symlink attacks
Exploitation Proof-of-Concept Results
From empirical testing with the provided PoCs:
Simple Direct Attack (filelocksimplepoc.py):
- Success rate: 33% per attempt (1 in 3 tries) - Average attempts to success: 2.1 - Target file reduced to 0 bytes in \<100ms
virtualenv Attack (weaponizedvirtualenv.py):
- Success rate: ~90% on first attempt (deterministic timing) - Information leaked: File paths, Python version, system configuration - Data corruption: Complete loss of original file contents
PyTorch Attack (weaponizedpytorch.py):
- Success rate: 25-40% per attempt - Impact: Application crashes, model loading failures - Recovery: Requires cache rebuild or model retraining
Discovered and reported by: George Tsigourakos (@tsigouris007)
Other sources
filelock has TOCTOU race condition that allows symlink attacks during lock file creation
— Microsoft
filelock is a platform-independent file lock for Python. In versions prior to 3.20.1, a Time-of-Check-Time-of-Use (TOCTOU) race condition allows local attackers to corrupt or truncate arbitrary user files through symlink attacks. The vulnerability exists in both Unix and Windows lock file creation where filelock checks if a file exists before opening it with OTRUNC. An attacker can create a symlink pointing to a victim file in the time gap between the check and open, causing os.open() to follow the symlink and truncate the target file. All users of filelock on Unix, Linux, macOS, and Windows systems are impacted. The vulnerability cascades to dependent libraries. The attack requires local filesystem access and ability to create symlinks (standard user permissions on Unix; Developer Mode on Windows 10+). Exploitation succeeds within 1-3 attempts when lock file paths are predictable. The issue is fixed in version 3.20.1. If immediate upgrade is not possible, use SoftFileLock instead of UnixFileLock/WindowsFileLock (note: different locking semantics, may not be suitable for all use cases); ensure lock file directories have restrictive permissions (chmod 0700) to prevent untrusted users from creating symlinks; and/or monitor lock file directories for suspicious symlinks before running trusted applications. These workarounds provide only partial mitigation. The race condition remains exploitable. Upgrading to version 3.20.1 is strongly recommended.
— NVD
Affected Software
Remediation
Recommended actions to resolve this vulnerability, in priority order.
- Upgrade
Upgrade
pip/filelockto a version that resolves this vulnerability.Fixed in 3.20.1 - Configuration
Set filesystem permissions of directories where lock files are created (for example /tmp or application cache directories) to 0700 (chmod 0700) to prevent untrusted users from creating symlinks.
lock file directory permissions = 0700 - Configuration
If immediate upgrade to 3.20.1 is not possible, configure your application to use SoftFileLock instead of UnixFileLock/WindowsFileLock (note: SoftFileLock has different locking semantics and may not be suitable for all use cases).
pip/filelock lock_class = SoftFileLock - Compensating control
Monitor lock file directories for suspicious symlinks before running trusted applications; alert on or remove unexpected symlinks and investigate recent changes to those directories.
- Operational
If files, caches, or model checkpoints were corrupted or truncated by this issue, rebuild affected caches or retrain/restore affected models and restore any overwritten configuration files from backups.
Event History
Frequently Asked Questions
What is the severity of CVE-2025-68146?
CVE-2025-68146 has a moderate severity due to the potential for local attackers to corrupt or truncate files.
How do I fix CVE-2025-68146?
To mitigate CVE-2025-68146, upgrade filelock to version 3.20.1 or later.
What types of systems are affected by CVE-2025-68146?
CVE-2025-68146 affects both Unix and Windows systems using vulnerable versions of the filelock library.
What is a TOCTOU race condition as related to CVE-2025-68146?
A TOCTOU race condition in CVE-2025-68146 allows an attacker to exploit the timing of file checks to alter files unexpectedly.
Are there any known exploits for CVE-2025-68146?
As of now, there are no publicly known exploits specifically targeting CVE-2025-68146.