TRENDING
A person sweeping a metal detector across a wet sandy beach with a sea fort on the horizon
November 22, 2026
How to Write YARA Rules With YARA-X to Hunt Malicious Python .pth Startup Files and Measure False Positives Before You Trust Them
A peeling black-and-white metal door standing ajar, with a dark empty hall and bright windows beyond
November 22, 2026
AWS’s “Found a Zero-Day on Their Own” Post Never Names the Product; the Advisory Behind Its Link Shows a Server That Ships With No Login, a README Now Saying Keep It Off the Internet, and a Fix Merged October 19 That PyPI and Docker Hub Still Do Not Carry
A hand paging through index cards in an open wooden library card-catalog drawer labeled Agriculture, with a second drawer open below to the right
November 22, 2026
Microsoft Tells Customers Unauthorized Parties Read Admin Email Addresses and Tenant Metadata Through an Entra Connect Health Flaw Introduced July 23, but Gives No Tenant Count or Start Date, and Its Own Docs Send Tenant Security Notices to the Same Kinds of Contacts
Swimmers in separate lanes of a blue swimming pool, seen from above the water, with lane lines running across the picture
November 22, 2026
How to Size a PostgreSQL Connection Pool in Python: Find Where Throughput Stops Growing, Split max_connections Across Workers, and Stop Slow Handlers From Hoarding Connections
Workers in caps lean over a 1913 Ford assembly line, each assembling parts as they pass on the moving line
November 22, 2026
OpenAI’s Performance Factory Turns Regression Response Into a Task Queue for Agents, but Its Numbers Stop at 600 Root-Caused Cases in 1,700 Investigations and a 70% Grade on 100 Suggestions, and in a Toy World Each of Its Reviewer’s Two Counterfactual Questions Can Return a Confident Wrong Answer
22 Nov 2026
SXZ.io SXZ.io
  • Home
Search the Site
Popular Searches:
Technology Amazon AI
Recent Posts
The sun setting over the sea behind a pyramid-shaped stone monument at Cape Soya, the northernmost point of Japan
How to Retire an API Endpoint in FastAPI: Send Deprecation and Sunset Headers, Find the Clients Still Calling It, Schedule Brownouts, and Block an Early Removal With oasdiff
November 22, 2026
Brass sextant in an open wooden case inside a museum display, an instrument for measuring the angle to the horizon
MIT Technology Review’s “Most Misunderstood Graph” Update Reports METR’s Judgment Findings Mostly Fairly, but It Never Says Each Point Is a 50% Success Rate or Gives the New 3.6-Month Doubling Time and 2.1 to 4.9 Month Range, and It Credits OpenAI With a Comparison METR Built
November 22, 2026
Brass telescope on a wooden tripod inside a white observatory dome with the roof slit open to the sky
Rackspace Says Leaked Credentials Let an Intruder Act as Legitimate Users in Some Spot Customer Organizations and Reach Their Kubernetes Secrets, a Platform9 Co-Founder Names a Breached Observability System as the Root Cause, and the Status Page Says Only “System Maintenance Operations”
November 22, 2026
SXZ.io SXZ.io
  • Home

Categories

Articles 310 Posts
News 316 Posts
Learning Hub 282 Posts
Home/Articles/OpenAI’s Codex Sandbox Post Turns Agent Safety Into a Permission Profile That Reproduces on Windows, but Protected Folders That Do Not Exist Yet Can Be Created by the Sandboxed Command, and Hard Links Made Beforehand Carry Writes Past the Workspace
Articles

OpenAI’s Codex Sandbox Post Turns Agent Safety Into a Permission Profile That Reproduces on Windows, but Protected Folders That Do Not Exist Yet Can Be Created by the Sandboxed Command, and Hard Links Made Beforehand Carry Writes Past the Workspace

Running the post’s dev profile through the real Codex 0.170.0 sandbox on Windows 11 confirmed its documented blocks, but missing protected folders and hard links made beforehand are two gaps it does...

November 18, 2026 17 Min Read
64

OpenAI’s November 18 engineering post “Inside the Codex sandbox”, by Michael Bolin, explains how Codex runs the commands a model asks for on a developer’s own machine. A permission profile says which paths a command may read, write or never touch and which network traffic it may send. Each operating system then enforces the profile with its own mechanism: Seatbelt on macOS, bubblewrap plus seccomp on Linux, and on Windows a new Microsoft library called MXC. The post is unusually concrete. It prints a worked dev profile, shows a codex sandbox command for testing it, and links to the source. That makes it checkable, so I checked it.

Table Of Content

  • What the post claims
  • The defaults and the stated trade-offs
  • The worked profile and the network options
  • Per-system enforcement and the test command
  • How I tested it
  • What reproduced
  • Filesystem rules
  • Network rules
  • Processes that outlive the command
  • Two gaps the post does not mention
  • A protected folder that does not exist yet is not protected
  • Why it matters
  • What the code does on each system
  • Hard links keep their own permissions
  • What the source adds that the post leaves out
  • Linux deny globs are a capped snapshot
  • The seccomp filter is broader than the post’s example
  • The post’s source links are permalinks
  • Limits of this check
  • What I would do with this
  • The lab kit
  • lab.py
  • probe.py
  • matrix.py
  • net.py
  • Sources

I downloaded the current Codex CLI release (0.170.0), put the post’s dev profile into a throwaway CODEX_HOME, and pushed 22 filesystem, network and link operations, plus a process test, through codex sandbox on Windows 11 in MXC-only mode. I also read the open-source implementation at commit 9d8ca1d. Nearly everything the post describes reproduced, down to the proxy’s refusal of unlisted domains. Two behaviors it does not mention are the exceptions:

  • On Windows, the built-in protection for .git, .codex, .agents and .aws only covers folders that already exist. In a workspace without them, the sandboxed command created all four.
  • Hard links keep their own permissions. Two hard links made before the run let a sandboxed command change a file inside .git and a file outside the workspace.

What the post claims

The post’s design choice is to use the host’s own sandboxing facilities rather than a container or a virtual machine. In its words, “Instead of moving computation to a separate environment to provide isolation, Codex uses each platform’s sandboxing facilities to constrain commands running in the user’s existing environment.” Its worked example is an iOS build: a container could not run the Mac toolchain or the simulator.

The defaults and the stated trade-offs

For a Git repository, the built-in :workspace profile “Allows writes within the workspace, while keeping directories such as .git and .codex read-only.” The stated purpose is “preventing direct changes to .codex/config.toml or Git hooks under .git/hooks.” Reads are broad on purpose, so “sensitive files elsewhere on the machine may also remain readable (such as config files containing API keys).” Network access is off. The post then concedes that “harmful actions are still possible”: an agent could plant code in a locally installed package such as node_modules/prettier that an editor runs later, outside the sandbox.

The worked profile and the network options

The post’s dev profile extends :workspace, adds write access to ~/build-cache, makes .vscode and .devcontainer read-only, and denies **/*.env and secrets. For the network there are three options: none, full direct access, or a proxy that applies domain rules. A comment in one of the post’s snippets matters for what follows: “If neither local config nor managed requirements enable the proxy, this profile allows direct network access; domain rules are not enforced.”

Per-system enforcement and the test command

On Windows the post says OpenAI is “currently replacing” its existing sandbox with one built on MXC, to avoid the elevated setup and the persistent state the old one leaves (ACLs, firewall rules, sandbox users, control plane files). Of codex sandbox it says the command is “commonly used to test out the profile, ensuring that the sandbox prevents the behavior it was designed to block.” That is what I did.

How I tested it

The machine runs Windows 11 (build 10.0.26100.9974). The binary is the Windows x64 asset of release rust-v0.170.0, published November 18 at 03:40 UTC. MXC is opt-in in this release: the crate’s README says “windows.sandbox = "mxc" is strict” and that features.prefer_mxc is default-off, while codex sandbox --help still describes a “Windows restricted token sandbox.” So every run passed -c windows.sandbox="mxc". The README also says the MXC wrapper “never invokes MXC’s AppContainer dispatcher, edits host ACLs, creates sandbox users, runs setup, or requests elevation,” which is why I was willing to run it here.

Everything lives in one folder: a throwaway CODEX_HOME holding the post’s profile, a workspace, a folder outside the workspace, and a TCP service on 127.0.0.1 that runs outside the sandbox. I swapped ~/build-cache for an absolute path inside that folder so the test would not touch my user profile. The probe script runs inside the sandbox and prints one line per operation. The full kit is at the end of this article.

What I did not do: run an agent session, or test macOS or Linux. The post says the codex sandbox command exposes Codex’s sandboxing mechanism with “the same configuration language and platform-specific enforcement,” but I have not run the harness path. The 0.170.0 binary was published about 16 hours before the commit I read, so I diffed the MXC policy file at the tag against that commit: the differences are SDK type renames (for example ExecutionRequest became ContainerRequest), and the block that builds the protected-path carve-outs is identical in both.

What reproduced

Filesystem rules

The block below is the probe’s output for the post’s dev profile, in a workspace that has .git, .codex, .vscode, secrets and several .env files. Eight operations succeeded and fourteen were refused.

write src/new.txt: OK
overwrite .vscode/settings.json: FAIL PermissionError [Errno 13] Permission denied: '.vscode\\
write .git/hooks/pre-commit: FAIL PermissionError [Errno 13] Permission denied: '.git\\hoo
overwrite existing .codex/config.toml: FAIL PermissionError [Errno 13] Permission denied: '.codex\\c
create .agents/skill.md (no .agents yet): OK
create .aws/credentials (no .aws yet): OK
read secrets/key.txt: FAIL PermissionError [Errno 13] Permission denied: 'secrets\\
read config/dev.env: FAIL PermissionError [Errno 13] Permission denied: 'config\\d
read .env: FAIL PermissionError [Errno 13] Permission denied: '.env'
read config/dir.env/a.txt (dir matches glob): FAIL PermissionError [Errno 13] Permission denied: 'config\\d
create config/new.env, read it back: OK 'NEW=1'
rename config/prod.env: FAIL PermissionError [WinError 5] Access is denied: 'config/p
read <outside>/fakehome/.aws/credentials: OK 'aws_secret_access_'
write <outside>/x.txt: FAIL PermissionError [Errno 13] Permission denied: 'C:\\Claud
write <outside>/build-cache/x.txt: OK
connect 1.1.1.1:443: FAIL PermissionError [WinError 10013] An attempt was made to
connect 127.0.0.1 (service outside): FAIL PermissionError [WinError 10013] An attempt was made to
resolve example.com: FAIL gaierror [Errno 11001] getaddrinfo failed
mklink /J jct <outside>/target: FAIL OSError Access is denied.
os.link(.git/config, src/newalias): FAIL PermissionError [WinError 5] Access is denied: '.git/con
append via old hard link src/alias_gitconfig: OK
append via old hard link node_modules/pkg/index.js: OK
What the post says What happened
The profile makes .vscode read-only, the post’s own VS Code example Overwriting .vscode/settings.json raised PermissionError (macOS prints “Operation not permitted” in the post)
.git and .codex stay read-only A hook write under .git/hooks and an overwrite of an existing .codex/config.toml were both refused
Deny rules for secrets and **/*.env secrets/key.txt, config/dev.env, .env and a directory named dir.env were refused, and so was renaming a denied file
“New paths that match the glob are not automatically added while the command is running” A config/new.env created during the command could be read back
Broad reads, with the caveat about secrets elsewhere A fake .aws/credentials outside the workspace was readable
Writes only in the workspace and granted paths A write next to the workspace was refused; the granted build-cache folder accepted one
Aliases get the stricter permission (the post covers symlinks and junctions) Creating a junction, or a hard link to .git/config, from inside the sandbox was refused

Network rules

I ran the same network probe under three configurations. A is the post’s proxy setup, with features.network_proxy = true, domain rules and the dev profile. B is the same rules without the feature flag. C is the profile exactly as the post prints it, with no [network] table.

== A. network enabled + domain rules + features.network_proxy = true ==
proxy variables: 22; HTTP_PROXY=http://127.0.0.1:61255; PIP_PROXY set: True
GET http://example.com/ -> HTTP 200
GET http://evil.example/ -> HTTP 403 x-proxy-error=blocked-by-denylist body='{"status":"blocked","host":"evil.example","reason":"denied","decision"'
GET http://www.iana.org/ -> HTTP 403 x-proxy-error=blocked-by-allowlist body='{"status":"blocked","host":"www.iana.org","reason":"not_allowed","deci'
direct 1.1.1.1:80: PermissionError 10013
direct local service: connected

== B. the same rules WITHOUT features.network_proxy ==
proxy variables: 0; HTTP_PROXY=None; PIP_PROXY set: False
GET http://example.com/ -> HTTP 200
GET http://evil.example/ -> URLError
GET http://www.iana.org/ -> HTTP 200
direct 1.1.1.1:80: connected
direct local service: connected

== C. the dev profile as in the post, no [network] table ==
proxy variables: 0; HTTP_PROXY=None; PIP_PROXY set: False
GET http://example.com/ -> URLError
GET http://evil.example/ -> URLError
GET http://www.iana.org/ -> URLError
direct 1.1.1.1:80: PermissionError 10013
direct local service: PermissionError 10013
A: flag and rules B: rules, no flag C: no network table
Proxy variables injected 22, including PIP_PROXY 0 0
Allow-listed example.com HTTP 200 HTTP 200 failed
Denied evil.example 403, blocked-by-denylist failed (not a real domain, so this says nothing about the rule) failed
Unlisted www.iana.org 403, blocked-by-allowlist HTTP 200 failed
Direct connection to 1.1.1.1:80 refused (WinError 10013) connected refused
Local service on 127.0.0.1 connected connected refused

The post’s description holds. In A the proxy answers with a JSON body naming the host and the reason, plus an x-proxy-error header, and a direct socket is refused. The list of injected variables matches the post’s “standard environment variables such as HTTP_PROXY, HTTPS_PROXY, and ALL_PROXY” plus “well-known application-specific environment variables (such as PIP_PROXY)”; it also holds NPM_CONFIG_PROXY, YARN_HTTP_PROXY, DOCKER_HTTP_PROXY and BUNDLE_HTTP_PROXY. The port is chosen per run (61255 here), not the 3128 and 8081 that appear in the post’s Seatbelt snippet, which are the defaults in the proxy’s config.rs.

B confirms the post’s own comment: with the rules but without the flag, an unlisted domain was reached directly and a raw socket connected, so the rules did nothing. The wording of the Windows section needs one qualifier. “MXC blocks direct external connections while allowing host-loopback connections, including access to the proxy. Other local services remain reachable.” That held in A and B, but in C, a profile with no network table, even the local service was refused, and name resolution failed too.

Processes that outlive the command

The post says each child inherits the sandbox, “even to descendants that outlive the original process.” On MXC I could not find a descendant that outlives it. The probe starts a child that writes a marker, sleeps four seconds and writes a second marker, then exits after 1.5 seconds.

parent exits now (codex sandbox returned after 1.8 s)
  c1.txt (child started): True | c2.txt (child finished 4 s later): False

The child started and never finished. The README explains why: MXC “creates its child suspended, assigns a kill-on-close job before resuming it.” For a Windows user, the practical effect is that a background process started by a sandboxed command ends with the command.

Two gaps the post does not mention

A protected folder that does not exist yet is not protected

The post lists .git and .codex as read-only and gives the reason: the agent must not edit .codex/config.toml or Git hooks. Its own example is hedged with “Assuming .vscode already exists.” The protection turns out to depend on that condition for all four built-in names. In the first probe output above, .codex and .git existed and writes were refused, while .agents and .aws did not exist and the sandboxed command created both. Under the built-in :workspace profile in a workspace with none of the four, every attempt succeeded:

create .git/hooks/post-checkout: OK
create .codex/config.toml: OK
create .agents/skill.md: OK
create .aws/credentials: OK

After I created .codex, .agents and .aws as empty folders and ran git init, every attempt was refused:

create .git/hooks/post-checkout: FAIL PermissionError
create .codex/config.toml: FAIL PermissionError
create .agents/skill.md: FAIL PermissionError
create .aws/credentials: FAIL PermissionError

Why it matters

The Codex docs say project .codex/ directories carry “project-local config, hooks, and rules,” and that “Codex loads project .codex/ layers only when you trust the project.” A .codex/config.toml created by a sandboxed command is therefore the file the protection exists to prevent. I did not try to plant a config that Codex then loads, so I can say only that the first step is not blocked on this build. For .git, in a workspace that was not yet a repository the command created .git/hooks/post-checkout.

What the code does on each system

On Windows, policy.rs in the mxc-sandbox crate turns each protected name into a plain path, root.join(name), and removes those paths from the writable grants. The same file creates missing parents for deny paths and marks them with a .chatgptcreated sentinel, and its tests cover missing deny paths. I found no equivalent step for a missing read-only name. On Linux, the bubblewrap code documents the opposite approach: “Mounting /dev/null on the first missing component prevents the sandboxed process from creating the protected path hierarchy.” On macOS, the Seatbelt builder excludes from each writable root any path that matches ^<root>/<name>(/.*)?$, a pattern that does not depend on the folder existing. I read those two but could not run them. If they behave as written, Windows MXC is the one platform where the sentence “keeping directories such as .git and .codex read-only” depends on the folders already being there.

Hard links keep their own permissions

The post says that when path spellings or symlink and junction aliases refer to the same path, MXC applies the stricter permission. It does not mention hard links. The crate’s README does: “Hard-link names retain independent path permissions. An allowed name can read or modify the same file as a denied or read-only name; we do not tighten all names to an object-wide restriction.”

The probe confirms it. Before the run I created two hard links outside the sandbox: src/alias_gitconfig pointing at .git/config, and node_modules/pkg/index.js pointing at a file in a folder outside the workspace. Appending through either name worked, and afterward both target files had changed, including the one outside the workspace.

after the run, seen from outside the sandbox:
  .git/config changed: True
  <outside>/store/index.js changed: True
  fsutil hardlink list node_modules/pkg/index.js:
    <lab>\outside\store\index.js
    <lab>\ws\node_modules\pkg\index.js

The sandbox did refuse to create a new hard link to .git/config, so the trigger is a link that already exists. Package managers do this on purpose. pnpm’s own motivation page says “All remaining dependencies are fetched and hard linked from the store to node_modules,” and that “All the files are saved in a single place on the disk.” The post’s warning about node_modules/prettier then has a harder edge: a write that the workspace rules allow can land in the shared store file, and so in every project that links it. Whether your installs are hard-linked depends on the package manager and the file system, so check rather than assume. On Windows, fsutil hardlink list <file> lists every name for a file, as in the output above. On Linux and macOS the link count in ls -l is the equivalent signal (not run here).

What the source adds that the post leaves out

Linux deny globs are a capped snapshot

The post says deny globs are expanded to concrete paths before each command. In bwrap.rs the expansion returns existing regular files only, reports a fatal error beyond MAX_UNREADABLE_GLOB_MATCHES (8,192), refuses a pattern with no non-root directory prefix, and leaves the scan depth uncapped unless glob_scan_max_depth is set. The docs describe that setting as one that “Limits deny-read glob expansion on Linux, WSL, and native Windows.” On Windows I measured a glob matching a directory, which fits the post’s “matching files and directories.”

The seccomp filter is broader than the post’s example

The post names “connect(2) and bind(2)” as examples of blocked network calls. In seccomp.rs the no-network mode denies connect, accept, accept4, bind, listen, sendto, sendmmsg, recvmmsg, getsockopt, setsockopt and more, and allows socket only for AF_UNIX. Separately it denies ptrace, process_vm_readv, process_vm_writev, request_key and the three io_uring calls. The comments give the reasons: request_key “can invoke host helpers that perform network requests outside the sandbox’s network namespace and proxy policy,” and “io_uring can create AF_VSOCK sockets without a socket() syscall.” That is stronger than the post suggests.

The post’s source links are permalinks

The post links seven code locations pinned at six commits between September 30 and November 2, plus two pull requests merged in March. Five of the cited ranges still match verbatim at the commit I read, with line numbers shifted (the exec_command spec moved from line 483 to line 275). Two changed: the Seatbelt argument builder and the seccomp installer. Read the links as history and use the current files for behavior.

Limits of this check

  • Windows only, through codex sandbox rather than an agent session, on one machine and build, from a non-interactive session.
  • On this machine git.exe, Git for Windows’ bash.exe and powershell.exe all exited with code 0xC0000142 inside the sandbox, while cmd, python and curl.exe ran. I did not find out why, and the README says Win32k calls and desktop handles remain available for PowerShell startup, so treat it as a note about this setup. It is not part of the kit.
  • The macOS and Linux statements come from reading code at commit 9d8ca1d, not from running it.
  • MXC is opt-in in 0.170.0 and the post describes the transition as in progress, so these gaps may change before it becomes the default.

What I would do with this

These are my suggestions, not OpenAI’s. Each of the first two was checked in the lab.

  1. On Windows with MXC, create .codex, .agents and .aws as empty folders, and initialize the repository so .git exists, in every workspace root. The last step of the matrix shows the four built-in names refused once they exist. I expect the same for read-only folders you add in your own profile, but I did not test that.
  2. List hard links in any tree you give an agent write access to, and count package-manager stores as part of that tree.
  3. Test your own profile the way the post suggests, but include the missing-path, rename and link cases, and repeat it on every operating system your team uses.
  4. If you rely on domain rules, enable features.network_proxy. Without it, configuration B shows the rules do nothing.
  5. Keep the post’s own framing in view: the sandbox is one layer, and the node_modules/prettier case it describes is outside what any profile can express. For other work on the same question, see our look at agent sandboxing on Kubernetes, the file sandbox in an agent harness, and parallel agents in separate git worktrees.

The lab kit

Four small files reproduce everything above on a Windows machine whose build supports MXC. Put them in one folder. Set CODEX_EXE to the Codex CLI binary and LAB_PYTHON to a Python 3 interpreter, then run python matrix.py and python net.py. Everything the lab creates goes under a run folder beside the scripts. Run it only with the MXC setting: the strict mode never falls back to the older sandbox that needs setup, and it fails closed if the machine cannot provide MXC. fsutil hardlink list needs an administrator prompt.

lab.py

# lab.py
"""lab.py: helpers for running `codex sandbox` in MXC-only mode on Windows."""
import os, pathlib, subprocess

KIT = pathlib.Path(__file__).resolve().parent
LAB = KIT / "run"                       # everything the lab creates lives here
CODEX = os.environ.get("CODEX_EXE", str(KIT / "codex.exe"))
HOME = LAB / "codex_home"               # throwaway CODEX_HOME
WS = LAB / "ws"                         # workspace root (cwd of every sandboxed command)
OUTSIDE = LAB / "outside"               # a folder outside the workspace
PY = os.environ.get("LAB_PYTHON", "python")


def config(extra=""):
    """The post's `dev` profile. `windows.sandbox = "mxc"` is strict: no setup, no users, no fallback."""
    return f'''default_permissions = "dev"

[windows]
sandbox = "mxc"

[permissions.dev]
extends = ":workspace"

[permissions.dev.filesystem]
"{(OUTSIDE / "build-cache").as_posix()}" = "write"

[permissions.dev.filesystem.":workspace_roots"]
".devcontainer" = "read"
".vscode" = "read"
"**/*.env" = "deny"
"secrets" = "deny"
{extra}'''


def write_config(text):
    HOME.mkdir(parents=True, exist_ok=True)
    (HOME / "config.toml").write_text(text, encoding="utf-8", newline="\n")


def rmtree(path):
    if path.exists():
        subprocess.run(["cmd", "/c", "rmdir", "/s", "/q", str(path)], capture_output=True)


def sandbox(args, profile="dev", cwd=None, env=None, timeout=120):
    """codex sandbox -C <cwd> -c windows.sandbox="mxc" -P <profile> -- <args>"""
    e = dict(os.environ, CODEX_HOME=str(HOME), **(env or {}))
    cmd = [CODEX, "sandbox", "-C", str(cwd or WS), "-c", 'windows.sandbox="mxc"', "-P", profile, "--", *args]
    p = subprocess.run(cmd, capture_output=True, text=True, env=e, timeout=timeout,
                       cwd=str(cwd or WS), encoding="utf-8", errors="replace")
    return p.returncode, scrub(p.stdout), scrub(p.stderr)


def scrub(text):
    return text.replace(str(LAB), "<lab>").replace(LAB.as_posix(), "<lab>")

probe.py

# probe.py
"""probe.py: runs INSIDE `codex sandbox` (cwd = workspace). One line per operation."""
import os, pathlib, socket, subprocess, sys, time

OUTSIDE = pathlib.Path(os.environ["PROBE_OUTSIDE"])
PORT = int(os.environ.get("PROBE_PORT", "0"))


def write(path, text="x\n", mode="w"):
    p = pathlib.Path(path)
    p.parent.mkdir(parents=True, exist_ok=True)
    with open(p, mode) as fh:
        fh.write(text)


def read(path):
    return repr(pathlib.Path(path).read_text().strip()[:18])


def new_env_then_read():
    write("config/new.env", "NEW=1\n")
    return read("config/new.env")


def rename_then_read():
    os.rename("config/prod.env", "config/prod.env.bak")
    return read("config/prod.env.bak")


def local_service():
    s = socket.create_connection(("127.0.0.1", PORT), 4)
    s.sendall(b"PING")
    reply = s.recv(8)
    s.close()
    return reply


def mklink_junction():
    p = subprocess.run(["cmd", "/c", "mklink", "/J", "jct", str(OUTSIDE / "target")], capture_output=True, text=True)
    if p.returncode:
        raise OSError((p.stdout + p.stderr).strip())


OPS = [
    ("write src/new.txt", lambda: write("src/new.txt")),
    ("overwrite .vscode/settings.json", lambda: write(".vscode/settings.json", "{}\n")),
    ("write .git/hooks/pre-commit", lambda: write(".git/hooks/pre-commit", "#!/bin/sh\n")),
    ("overwrite existing .codex/config.toml", lambda: write(".codex/config.toml", "x = 1\n")),
    ("create .agents/skill.md (no .agents yet)", lambda: write(".agents/skill.md")),
    ("create .aws/credentials (no .aws yet)", lambda: write(".aws/credentials")),
    ("read secrets/key.txt", lambda: read("secrets/key.txt")),
    ("read config/dev.env", lambda: read("config/dev.env")),
    ("read .env", lambda: read(".env")),
    ("read config/dir.env/a.txt (dir matches glob)", lambda: read("config/dir.env/a.txt")),
    ("create config/new.env, read it back", new_env_then_read),
    ("rename config/prod.env", rename_then_read),
    ("read <outside>/fakehome/.aws/credentials", lambda: read(OUTSIDE / "fakehome" / ".aws" / "credentials")),
    ("write <outside>/x.txt", lambda: write(OUTSIDE / "x.txt")),
    ("write <outside>/build-cache/x.txt", lambda: write(OUTSIDE / "build-cache" / "x.txt")),
    ("connect 1.1.1.1:443", lambda: socket.create_connection(("1.1.1.1", 443), 4).close()),
    ("connect 127.0.0.1 (service outside)", local_service),
    ("resolve example.com", lambda: socket.getaddrinfo("example.com", 443)[0][4][0]),
    ("mklink /J jct <outside>/target", mklink_junction),
    ("os.link(.git/config, src/newalias)", lambda: os.link(".git/config", "src/newalias")),
    ("append via old hard link src/alias_gitconfig", lambda: write("src/alias_gitconfig", "# TAMPERED\n", "a")),
    ("append via old hard link node_modules/pkg/index.js", lambda: write("node_modules/pkg/index.js", "// TAMPERED\n", "a")),
]


def main():
    for name, fn in OPS:
        try:
            r = fn()
            print(f"{name}: OK" + (f" {r}" if r is not None else ""))
        except Exception as e:  # noqa: BLE001
            print(f"{name}: FAIL {type(e).__name__} {str(e).splitlines()[0][:40] if str(e) else ''}".rstrip())


def child():
    """Start a child that writes a marker, sleeps 4 s, then writes a second marker; exit after 1.5 s."""
    code = ("import time,pathlib;pathlib.Path('src/c1.txt').write_text('s');time.sleep(4);"
            "pathlib.Path('src/c2.txt').write_text('f')")
    subprocess.Popen([sys.executable, "-c", code], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
                     stderr=subprocess.DEVNULL)
    time.sleep(1.5)
    print("parent exits now")


def protected():
    """Which of the four protected names can this command create?  (run in a workspace that has none of them)"""
    for name in (".git/hooks/post-checkout", ".codex/config.toml", ".agents/skill.md", ".aws/credentials"):
        try:
            write(name)
            print(f"create {name}: OK")
        except Exception as e:  # noqa: BLE001
            print(f"create {name}: FAIL {type(e).__name__}")


if __name__ == "__main__":
    {"child": child, "protected": protected}.get(sys.argv[1] if len(sys.argv) > 1 else "", main)()

matrix.py

# matrix.py
"""matrix.py: build the fixtures, run probe.py under the post's dev profile, then check what changed."""
import os, pathlib, socket, subprocess, sys, threading, time
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from lab import *

PROBE = str(pathlib.Path(__file__).resolve().parent / "probe.py")


def fixtures(with_protected=True):
    rmtree(WS)
    for d in (".vscode", ".devcontainer", "secrets", "config/dir.env", "src", "node_modules/pkg"):
        (WS / d).mkdir(parents=True)
    (WS / ".vscode/settings.json").write_text("{}\n")
    (WS / "secrets/key.txt").write_text("TOP-SECRET\n")
    (WS / "config/dev.env").write_text("DEV=1\n")
    (WS / "config/prod.env").write_text("PROD=1\n")
    (WS / "config/dir.env/a.txt").write_text("in a dir\n")
    (WS / ".env").write_text("ROOT=1\n")
    (WS / "src/app.txt").write_text("hello\n")
    if with_protected:
        subprocess.run(["git", "init", "-q", str(WS)], check=True)
        (WS / ".codex").mkdir()
        (WS / ".codex/config.toml").write_text("model = 'x'\n")


write_config(config())
(OUTSIDE / "build-cache").mkdir(parents=True, exist_ok=True)
(OUTSIDE / "fakehome/.aws").mkdir(parents=True, exist_ok=True)
(OUTSIDE / "fakehome/.aws/credentials").write_text("aws_secret_access_key = FAKE\n")
(OUTSIDE / "target").mkdir(exist_ok=True)
(OUTSIDE / "store").mkdir(exist_ok=True)
(OUTSIDE / "store/index.js").write_text("module.exports = 1;\n")
for stale in (OUTSIDE / "x.txt", OUTSIDE / "build-cache/x.txt"):
    stale.unlink(missing_ok=True)

# a local TCP service OUTSIDE the sandbox
srv = socket.socket()
srv.bind(("127.0.0.1", 0))
srv.listen(5)


def serve():
    while True:
        try:
            c, _ = srv.accept()
            c.recv(8)
            c.sendall(b"PONG")
            c.close()
        except OSError:
            return


threading.Thread(target=serve, daemon=True).start()
env = {"PROBE_OUTSIDE": str(OUTSIDE), "PROBE_PORT": str(srv.getsockname()[1])}

print("== 1. the post's dev profile, one workspace with .git and .codex present ==")
fixtures()
os.link(WS / ".git/config", WS / "src/alias_gitconfig")             # hard links made OUTSIDE the sandbox
os.link(OUTSIDE / "store/index.js", WS / "node_modules/pkg/index.js")
rc, out, err = sandbox([PY, PROBE], env=env)
print(out.rstrip() or err[:600])
print("after the run, seen from outside the sandbox:")
print("  .git/config changed:", "TAMPERED" in (WS / ".git/config").read_text())
print("  <outside>/store/index.js changed:", "TAMPERED" in (OUTSIDE / "store/index.js").read_text())
print("  fsutil hardlink list node_modules/pkg/index.js:")
fs = subprocess.run(["fsutil", "hardlink", "list", str(WS / "node_modules/pkg/index.js")], capture_output=True, text=True)
for line in fs.stdout.split():
    print("   ", scrub(line))

print("\n== 2. a detached child versus the command that started it ==")
fixtures()
t = time.time()
rc, out, err = sandbox([PY, PROBE, "child"], env=env)
print(out.strip(), f"(codex sandbox returned after {time.time() - t:.1f} s)")
time.sleep(5)
print("  c1.txt (child started):", (WS / "src/c1.txt").exists(), "| c2.txt (child finished 4 s later):", (WS / "src/c2.txt").exists())

for label, profile, make in (("3. built-in :workspace, workspace without the four protected names", ":workspace", False),):
    print(f"\n== {label} ==")
    fixtures(with_protected=make)
    rc, out, err = sandbox([PY, PROBE, "protected"], profile=profile, env=env)
    print(out.rstrip() or err[:400])

print("\n== 4. same profile after pre-creating the four names as empty folders ==")
fixtures(with_protected=False)
subprocess.run(["git", "init", "-q", str(WS)], check=True)
for d in (".codex", ".agents", ".aws"):
    (WS / d).mkdir()
rc, out, err = sandbox([PY, PROBE, "protected"], profile=":workspace", env=env)
print(out.rstrip() or err[:400])

net.py

# net.py
"""net.py: the post's network profile, tested from inside the sandbox under three configurations."""
import os, pathlib, socket, sys, threading, time, urllib.error, urllib.request

HERE = pathlib.Path(__file__).resolve()
RULES = '''
[permissions.dev.network]
enabled = true

[permissions.dev.network.domains]
"*.openai.com" = "allow"
"example.com" = "allow"
"localhost" = "allow"
"127.0.0.1" = "allow"
"::1" = "allow"
"evil.example" = "deny"
'''
FLAG = '''
[features]
network_proxy = true
'''


def inside():
    port = int(os.environ["PROBE_PORT"])
    names = sorted(k for k in os.environ if "PROXY" in k.upper())
    print(f"proxy variables: {len(names)}; HTTP_PROXY={os.environ.get('HTTP_PROXY')}; PIP_PROXY set: {'PIP_PROXY' in names}")

    def get(url):
        try:
            return f"HTTP {urllib.request.urlopen(url, timeout=12).status}"
        except urllib.error.HTTPError as e:
            return f"HTTP {e.code} x-proxy-error={e.headers.get('x-proxy-error')} body={e.read(70).decode()!r}"
        except Exception as e:  # noqa: BLE001
            return type(e).__name__
    for host in ("example.com", "evil.example", "www.iana.org"):
        print(f"GET http://{host}/ -> {get(f'http://{host}/')}")
    for label, addr in (("1.1.1.1:80", ("1.1.1.1", 80)), ("local service", ("127.0.0.1", port))):
        try:
            s = socket.create_connection(addr, 4)
            s.sendall(b"PING")
            print(f"direct {label}: connected")
            s.close()
        except Exception as e:  # noqa: BLE001
            print(f"direct {label}: {type(e).__name__} {getattr(e, 'winerror', '')}")


if __name__ == "__main__":
    if sys.argv[1:] == ["inside"]:
        inside()
        sys.exit()
    sys.path.insert(0, str(HERE.parent))
    from lab import *
    (OUTSIDE / "build-cache").mkdir(parents=True, exist_ok=True)
    WS.mkdir(parents=True, exist_ok=True)
    srv = socket.socket()
    srv.bind(("127.0.0.1", 0))
    srv.listen(5)

    def serve():
        while True:
            try:
                c, _ = srv.accept()
                c.sendall(b"PONG")
                c.close()
            except OSError:
                return
    threading.Thread(target=serve, daemon=True).start()
    env = {"PROBE_PORT": str(srv.getsockname()[1])}
    for title, extra in (("A. network enabled + domain rules + features.network_proxy = true", FLAG + RULES),
                         ("B. the same rules WITHOUT features.network_proxy", RULES),
                         ("C. the dev profile as in the post, no [network] table", "")):
        write_config(config(extra))
        rc, out, err = sandbox([PY, str(HERE), "inside"], env=env)
        print(f"== {title} ==")
        print(out.rstrip() or err[:500])
        print()

Sources

  • OpenAI, Inside the Codex sandbox
  • Codex release rust-v0.170.0, and the repository at commit 9d8ca1d: mxc-sandbox README, policy.rs, seatbelt.rs, bwrap.rs, seccomp.rs, network-proxy config.rs
  • Codex docs: permissions and config basics
  • pnpm, Motivation
  • Microsoft, MXC and its configuration schema, both linked from the post

Tags:

AI Agent SecurityCodexHard LinksOpenAISandboxingWindows

Share

A single steel fish hook hanging from a thread against a soft green blurred background
Previous Post

Microsoft’s agent-framework Carried a Credential Stealer on PyPI for 39 Minutes, Wiz Points to a Compromised Release-Pipeline Certificate, and 22 Hours Later PyPI Still Listed an Account Created That Day on 14 Microsoft Projects

A clear plastic reel of brown magnetic recording tape on a black background, shown face on with its three spokes
Next Post

How to Recover PostgreSQL 18 to the Moment Before a Bad DELETE: WAL Archiving, pg_basebackup, Point-in-Time Recovery, and a Restore Drill You Can Test

No Comment! Be the first one.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Latest
22 Nov
How to Retire an API Endpoint in FastAPI: Send Deprecation and Sunset Headers, Find the Clients Still Calling It, Schedule Brownouts, and Block an Early Removal With oasdiff
22 Nov
MIT Technology Review’s “Most Misunderstood Graph” Update Reports METR’s Judgment Findings Mostly Fairly, but It Never Says Each Point Is a 50% Success Rate or Gives the New 3.6-Month Doubling Time and 2.1 to 4.9 Month Range, and It Credits OpenAI With a Comparison METR Built
Trending
November 22, 2026
How to Retire an API Endpoint in FastAPI: Send Deprecation and Sunset Headers, Find the Clients Still Calling It, Schedule Brownouts, and Block an Early Removal With oasdiff
November 22, 2026
MIT Technology Review’s “Most Misunderstood Graph” Update Reports METR’s Judgment Findings Mostly Fairly, but It Never Says Each Point Is a 50% Success Rate or Gives the New 3.6-Month Doubling Time and 2.1 to 4.9 Month Range, and It Credits OpenAI With a Comparison METR Built
November 22, 2026
Rackspace Says Leaked Credentials Let an Intruder Act as Legitimate Users in Some Spot Customer Organizations and Reach Their Kubernetes Secrets, a Platform9 Co-Founder Names a Breached Observability System as the Root Cause, and the Status Page Says Only “System Maintenance Operations”
November 21, 2026
How to Write YARA Rules With YARA-X to Hunt Malicious Python .pth Startup Files and Measure False Positives Before You Trust Them
November 21, 2026
AWS’s “Found a Zero-Day on Their Own” Post Never Names the Product; the Advisory Behind Its Link Shows a Server That Ships With No Login, a README Now Saying Keep It Off the Internet, and a Fix Merged October 19 That PyPI and Docker Hub Still Do Not Carry
November 21, 2026
Microsoft Tells Customers Unauthorized Parties Read Admin Email Addresses and Tenant Metadata Through an Entra Connect Health Flaw Introduced July 23, but Gives No Tenant Count or Start Date, and Its Own Docs Send Tenant Security Notices to the Same Kinds of Contacts

Related Posts

Blue-lit server racks in a modern data center, illustrating the compute infrastructure behind the AI boom.
Articles

The AI Boom Is Spending Real Money Before Proving Real Returns

June 7, 2026
Technician working with a laptop beside server racks, representing enterprise AI retrieval infrastructure
Articles

Google’s Agentic RAG Push Makes Enterprise AI Less of a One-Shot Guess

June 7, 2026
A person with a laptop and smartphone, representing digital attention and AI-assisted work
Articles

AI Chatbots Are Making Attention a Design Problem

June 7, 2026
A customer-support representative wearing a headset against a dark studio background.
Articles

The Meta AI Support Hack Was a Plain Old Authorization Failure

June 7, 2026
SXZ.io SXZ.io
  • [email protected]

Categories

Articles
Learning Hub
News

All Rights Reserved by SXZ.io ©2026