Practical technical guides / Security

Bind Output Files Before Untrusted Tools Can Swap Their Paths

Writing a result through its pathname after untrusted work runs lets that work redirect the write with a link. Open first, refuse extra links, verify identity, write through the handle.

By Sandeep Belgavi · Published 2026-11-13

Writing a result through its pathname after untrusted work runs lets that work redirect the write with a link. Open first, refuse extra links, verify identity, write through the handle.

A write at the end of a job

Many tools follow the same shape: take an output path as an argument, do some work, then write the result to the path. A report generator, a code formatter, a build step, an agent runner asked to save its final answer. The write happens last, through the pathname, after the work is done.

That shape is unsafe whenever the work can touch the directory the output lives in. If anything that runs during the job can replace the output path with a symbolic link or a hard link to another file, the final write follows the new name and overwrites the other file, with the permissions of the tool, not of whatever made the swap. This is a time-of-check to time-of-use problem, and it is old. What is new is how often the "work" is now code an agent wrote and ran in a sandbox that shares a working directory with the tool.

Codex CLI rust-v0.168.0, released on 13 November 2026, includes a fix for exactly this in codex exec --output-last-message. Pull request 58974, merged on 2 November, says the option wrote through a pathname after tools finished, allowing sandbox activity to redirect the final write by replacing that path with a symlink. The fix opens the destination before starting the agent and keeps the handle until the final write; rejects symlinks, Windows reparse points and multiply linked files; and verifies that the pathname still identifies the bound file before truncating and after writing. This guide generalises that pattern and reproduces the failure on a local filesystem.

Why the late write is dangerous

The tool's write is a privileged act in a small way: it can write anywhere the tool's user can. The untrusted work is constrained, perhaps to the project directory, perhaps by a sandbox profile that allows writes only under the working tree. If the output path is inside the working tree, the untrusted work can control what that path names when the tool finally opens it. A sandbox that forbids writing to ~/.bashrc does not stop the sandboxed code from making out.md a link to ~/.bashrc and letting the unsandboxed tool do the write.

Three ways to redirect a pathname:

  • Replace it with a symbolic link to the target. Opening the path follows the link by default.
  • Replace it with a hard link to the target. There is no link to follow: the path now names the target file itself, and the two names are indistinguishable.
  • Rename the target onto the path, or rename the path's parent directory and put another in its place.

Reproducing it

The companion example runs in a temporary directory on the local disk. It creates a settings file for the fictional Belgavi's Book Store, store-settings.conf containing refund_limit=50, and a job that writes a summary of CASE-9050 to result.md. The untrusted work replaces result.md with a hard link to the settings file. Hard links need no special privilege on NTFS or on Linux; symbolic links need extra privilege on Windows, so the recorded run on Windows uses hard links.

Two writers are compared. The late writer does the work, then opens result.md and writes. The bound writer opens result.md first, keeps the descriptor, does the work, checks the path still names the same file, and writes through the descriptor.

scenario               writer        settings file afterwards     result
link planted earlier   late_write    "Summary for CASE-9050"      overwritten
link planted earlier   bound_write   "refund_limit=50"            refused: 2 links
relink during work     late_write    "Summary for CASE-9050"      overwritten
relink during work     bound_write   "refund_limit=50"            attack failed

The planted case is the one the Codex pull request's tests describe across consecutive invocations: a link left by one run waits for the next. The bound writer refuses because the file it opened has two names. In the relink case on Windows, the attack itself fails: Windows refused to delete the output file while the bound writer held it open, with error 32, "being used by another process". That is a property of the platform's default sharing mode, not of the code, and on Linux the unlink would succeed. There, the identity check is what catches it: the path no longer names the file that was opened.

The pattern

Open early. Open the output before any untrusted work starts, so that what you hold is the file the path named at a moment you controlled. On Linux and macOS, add O_NOFOLLOW so that a symbolic link at the final component fails the open, and O_CREAT | O_EXCL if the file should not exist yet; on Windows, check for reparse points.

Refuse multiple links. After opening, fstat the descriptor; a regular output file should have exactly one link. A count above one means another name points at the same data, which is how a hard-link redirect looks.

Verify identity before writing. After the work, stat the pathname without following links and compare its device and inode with the descriptor's. If the path was removed or replaced, refuse.

Write through the descriptor. Truncate and write the open handle, not the path. Check again after writing if you also report the path to someone else.

import os

def open_bound(path):
    flags = os.O_WRONLY | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0)
    fd = os.open(path, flags, 0o600)
    st = os.fstat(fd)
    if st.st_nlink > 1:
        os.close(fd)
        raise UnsafeOutput(f"{path} has {st.st_nlink} links")
    return fd, st

def bound_write(path, work, text):
    fd, opened = open_bound(path)
    try:
        work()
        now = os.stat(path, follow_symlinks=False)
        if (now.st_dev, now.st_ino) != (opened.st_dev, opened.st_ino):
            raise UnsafeOutput(f"{path} now names a different file")
        os.ftruncate(fd, 0)
        os.write(fd, text.encode())
    finally:
        os.close(fd)

Two things the snippet does not solve. A swap of a parent directory needs directory-relative opens, openat with a held directory descriptor, which Python exposes through the dir_fd parameter on Unix-like systems. And streams such as standard output, FIFOs and devices are legitimate destinations that do not behave like regular files; the Codex pull request explicitly preserves inherited Unix output streams, FIFOs, devices and the Windows NUL device while applying the checks to ordinary files.

Alternatives

Write outside the untrusted tree. If the output directory is one the sandboxed work cannot write to, the race disappears. This is the strongest fix when you control the layout.

Write to a fresh temporary file in a directory you own and rename it into place at the end. The rename is atomic, but renaming onto a path that the untrusted work controls still lets it choose what you replace, so do the rename into a directory the work cannot write.

Return the result over a pipe or standard output and let the caller decide where it goes.

Failure modes

  • A tool writes its final output through a pathname inside a sandboxed working directory.
  • A check with os.path.exists or islink before the work, then an open after it.
  • A hard-link redirect, which no symlink check can see.
  • An output path in a shared temporary directory, where any local user can plant a link first.
  • Error messages that fail open: if the check fails, the tool falls back to writing anyway.

What stays deterministic

The output binding belongs to the host process, before and after the agent runs. The agent never chooses the output path at run time, and nothing the agent does can change which file the host writes. Treat every file the sandboxed work can reach as untrusted input to the host's final step.

Verify it

Run the companion example on your platform; its seven tests cover a plain run, the planted link, the relink, an identity change and a removed output. For your own tool, add a test that plants a hard link and, on Linux and macOS, a symbolic link at the output path before the job, and another that replaces it during the job, and assert the target file is unchanged and the tool exits with an error.

Run the example yourself

The late and bound writers, the planted-link and relink scenarios recorded on Windows NTFS, and seven tests. Companion code on GitHub; its README lists the prerequisites, exact commands, expected output and limits.

Primary references and authorship

Sources read 2026-11-13. Original explanation and synthetic examples by Sandeep Belgavi. Views are my own and do not represent any employer, past or present.