cd /news/ai-agents/eliminating-toctou-path-traversal-in… · home › topics › ai-agents › article
[ARTICLE · art-158818] src=dev.to ↗ pub= topic=ai-agents verified=true sentiment=↑ positive

Eliminating TOCTOU Path Traversal in Python with Kernel-Enforced Containment and Lean 4 Formal Verification

A developer built PathFence, a zero-dependency, pure-Python path containment library that replaces the standard realpath-then-open idiom with kernel-enforced confinement using openat2 with RESOLVE_BENEATH and RESOLVE_NO_SYMLINKS on Linux 5.6+, component-by-component openat with O_NOFOLLOW on macOS and older Linux, and reparse-point inspection on Windows. The library's decision function is formally verified in Lean 4, with theorems specifying exactly when a path is allowed, and a command-line tool exposes the proven function to any language. The author notes PathFence is v0.1.0, experimental, has had no human security review, and is not a sandbox because its decision is lexical.

by read5 min views8 publishedOct 27, 2026

When building AI agents, MCP servers, archive extractors, or multi-tenant web backends, confining file operations to a designated directory is critical.

Yet the standard Python idiom for path validation—normalizing with os.path.realpath() or Path.resolve(), checking a string prefix, and then calling open()—is fundamentally vulnerable to TOCTOU race conditions.

To solve this without requiring C extensions or sacrificing performance, I built PathFence: a zero-dependency, pure-Python path containment library backed by OS kernel primitives and mathematically verified in Lean 4.

A path-confinement check for tools that let an AI agent (or any untrusted caller) read and write files, written and proven in Lean 4.

You give it the directories the caller may use, optionally directories inside them it may not use and a requested path. It answers allow (with the resolved path, and the allowed root it is under) deny (with the resolved path) or reject (with a reason). Lean theorems state exactly when it allows, and a command-line tool makes the proven function usable from any language.

$ pathfence check --allow /tmp/allowed_dir -- /tmp/allowed_dir_malicious/secret ../x a/../b
{"input":"/tmp/allowed_dir_malicious/secret","decision":"deny","path":"/tmp/allowed_dir_malicious/secret"}
{"input":"../x","decision":"reject","reason":"escapes"}
{"input":"a/../b","decision":"allow","path":"/tmp/allowed_dir/b","root":"/tmp/allowed_dir","rel":"b"}

Status: v0.1.0, experimental. No human security review yet.

PathFence is not a sandbox. The decision is lexical. It looks only at the path string, never at the file system. A symlink, a race between the check and the open, a hard link, a mount or a case-insensitive file system…

Consider the classic validation pattern found in thousands of production codebases:

real_root = os.path.realpath(root)
real_target = os.path.realpath(os.path.join(root, untrusted_path))
if not real_target.startswith(real_root + os.sep):
    raise PermissionError("Path traversal detected")

with open(real_target, "rb") as f:
    data = f.read()

Between the moment os.path.realpath() inspects the filesystem and the moment open() resolves the path again in the kernel, a local attacker or concurrent process can replace an intermediate directory with a symlink pointing to /etc or another sensitive location. Because the check and the use are two separate operations on path strings, the containment guarantee evaporates under concurrency.

sequenceDiagram
    participant App as Python Process
    participant Kernel as OS Kernel / VFS
    participant Attacker as Concurrent Attacker

    App->>Kernel: 1. realpath("/sandbox/work/data.txt")
    Kernel-->>App: "/sandbox/work/data.txt" - Prefix OK
    Attacker->>Kernel: 2. rename & symlink "/sandbox/work" -> "/etc"
    App->>Kernel: 3. open("/sandbox/work/passwd")
    Kernel-->>App: Returns file descriptor for /etc/passwd!

PathFence shifts the root of trust from mutable path strings to pinned directory file descriptors. Every operation resolves relative to an open directory handle using OS-level flags that forbid symlink traversal and upward escape at the kernel level.

graph TD
    Input["pathfence.safe_open / Workspace"] --> Lex["Lexical Normalization & Windows Reserved Name Check"]
    Lex --> Platform{"Platform Kernel Strategy"}
    Platform -->|Linux 5.6+| Openat2["openat2 syscall + RESOLVE_BENEATH / NO_SYMLINKS"]
    Platform -->|macOS / Older Linux| StepWalk["Component-by-component openat + O_NOFOLLOW + fstat"]
    Platform -->|Windows| WinHandle["Reparse Point Inspection + GetFinalPathNameByHandleW"]
    Openat2 --> Result["Verified File Descriptor / Stream"]
    StepWalk --> Result["Verified File Descriptor / Stream"]
    WinHandle --> Result["Verified File Descriptor / Stream"]

On modern Linux kernels, PathFence invokes the openat2(2) syscall directly via ctypes with four strict resolution flags:

RESOLVE_BENEATH: Prevents resolution from escaping above the root directory file descriptor.RESOLVE_NO_SYMLINKS: Rejects all symbolic links anywhere in the path. RESOLVE_NO_MAGICLINKS: Blocks procfs magic-link traversal such as /proc/self/fd/*. RESOLVE_NO_XDEV: Prevents crossing mount-point boundaries. O_NOFOLLOW Walk On macOS, BSD, and older Linux kernels, PathFence pins the root directory with O_RDONLY | O_DIRECTORY | O_NOFOLLOW and walks each path segment one at a time using openat(..., O_NOFOLLOW). At each step, it verifies fstat device and inode identities to detect concurrent directory replacement.

On Windows, PathFence blocks reserved device names such as CON, PRN, AUX, NUL, COM1- COM9, and LPT1- LPT9, NTFS Alternate Data Streams containing :, trailing dots or spaces, and UNC/device prefixes. It inspects FSCTL_GET_REPARSE_POINT to reject junctions and mount points, and verifies the final handle path via GetFinalPathNameByHandleW.

Unit tests and fuzzing can catch bugs, but they cannot prove the absence of edge cases across infinite path combinations. PathFence includes a complete formal specification written in Lean 4 under the formal/ directory.

We model path components, depth tracking, lexical normalization, and step-by-step directory resolution, proving 15 theorems with zero sorry placeholders and zero custom axioms:

Theorem Verified Security Property
normalize_rejects_escape Any component sequence whose cumulative depth drops below zero is strictly rejected.
normalize_preserves_containment Every accepted path resolves strictly within the subtree rooted at the pinned base.
symlink_free_walk_stays_in_root Inductive proof that a symlink-free O_NOFOLLOW walk can never transition outside the root boundary.
normalize_idempotent Normalizing an already normalized path yields the exact same result.
beneath_composable Sub-workspaces created via subworkspace() transitively preserve parent containment guarantees.

Beyond opening files, Workspace confines the entire file lifecycle—including mkdir, unlink, rmdir, rename, listdir, and crash-safe atomic_write—inside the pinned boundary.

import pathfence
from pathfence import Workspace

with pathfence.safe_open("/var/sandbox", "notes/hello.txt", "r") as f:
    print(f.read())

with Workspace("/var/sandbox") as ws:
    ws.mkdir("output", exist_ok=True)
    ws.atomic_write("output/result.json", b'{"status": "verified"}')

    with ws.subworkspace("output") as sub:
        data = sub.read_bytes("result.json")

Because PathFence uses direct syscall bindings in pure Python, security comes with virtually zero latency penalty. Benchmarked over 100,000 iterations on Linux 6.8:

openat2 fast pathrealpath + open at 3.9 μs PathFence requires Python 3.9+ and has zero runtime dependencies.

pip install pathfence

Check out the repository, inspect the Lean 4 proofs in formal/, and let me know your thoughts in the comments!

$ pathfence check --allow /tmp/allowed_dir -- /tmp/allowed_dir_malicious/secret ../x a/../b
{"input":"/tmp/allowed_dir_malicious/secret","decision":"deny","path":"/tmp/allowed_dir_malicious/secret"}
{"input":"../x","decision":"reject","reason":"escapes"}
{"input":"a/../b","decision":"allow","path":"/tmp/allowed_dir/b","root":"/tmp/allowed_dir","rel":"b"}
── more in #ai-agents 4 stories · sorted by recency
── more on @pathfence 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/eliminating-toctou-p…] indexed:0 read:5min 2026-10-27 · —