Skip to content

fix: refuse a save-script destination another local user can steer - #4584

Draft
thymikee wants to merge 10 commits into
mainfrom
fix/save-script-ancestor-redirect
Draft

thymikee wants to merge 10 commits into
mainfrom
fix/save-script-ancestor-redirect

Conversation

@thymikee

@thymikee thymikee commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Closes #4565.

open --save-script=<path> resolved the destination by name, so a second local user who could write any directory on the way to it could replace that component, or leave a symbolic link there before the entry was created, and move the recording wherever they chose. Both the local writer and the remote staging path had it.

Node exposes no openat, renameat, linkat or mkdirat, so a publisher cannot resolve a destination relative to a verified directory handle, and no re-check closes a race with a local attacker. The window is closed by permissions: a destination is accepted only when no other non-root local user can modify any directory the publish traverses. Once that holds, nobody can swap a component out or plant one, so the path the rule judged is the path the publish reaches.

Every directory the kernel steps into is judged, not only the final real path. Each existing prefix of the spelled parent is expanded link by link, and the directory holding each link target is judged with it. One realpath is not enough: a plain directory under a shared one can hold a link into a private destination, so the destination looks private while the ground it stands on is shared, and a link whose target is another link never names the directory crossed in between. .. stays in the path it was spelled with, so <dir>/shared/work/../x is judged as the walk the kernel performs, with work in it.

A destination is refused under script_ancestor_untrusted when a traversed directory is owned by neither you nor root (foreign_owned); is writable by other (world_writable) or by a group that is not your own private group (shared_group_writable); is where the entry would be created while others may also add entries (shared_parent); or holds a link another user could have planted or could replace (planted_link).

Root-owned system aliases such as macOS /tmp and /var keep working. The remote route creates the missing parent before it asks, so both routes answer about the directory the entry is really made in. The publisher also compares the destination directory's dev:ino: defense in depth, not the thing that closes the window. Scripts are created 0600 locally as well as remotely.

The private-group exception for the Ubuntu and Debian group-writable home now fails closed: both database files must be readable, the gid must be this process's primary group, and EVERY record carrying that number is read, since all their members hold write — ada:x:1000: beside team:x:1000:grace reaches grace.

What sits outside the guarantee is named in the ADR and the guide: access control lists are consulted ahead of the mode bits and are not read, ownership on a network mount is the server's to give, and a mount can appear over a checked directory. The promise is that no other local user can steer where the recording is written; it is not a promise that nobody else can read it.

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 6.32 MB 6.32 MB +5.6 kB
Package (unpacked) 6.32 MB 6.32 MB +5.6 kB
Package (download) 1.92 MB 1.92 MB +1.9 kB

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 22.9 ms 23.0 ms +0.1 ms
CLI --help 43.5 ms 44.7 ms +1.2 ms

@thymikee

Copy link
Copy Markdown
Member Author

I found two confirmed gaps in the new ancestry rule at 02cfd69, and one docs claim that is wrong. CI is failing on the CodeQL alert described below, and there are no conflicts. The ancestry rule and the docs need to change before this can merge.

The rule trusts a directory from its mode bits and group only. untrustedWritableExposure and othersCreateEntriesIn never compare stats.uid with the current uid or root. Three real inputs pass. A sticky directory owned by another user (a teammate's chmod 1777 team) is exempted, yet its owner can rename or remove any entry. A 0755 directory owned by someone else that holds a component of your path lets that user rename the component and plant a symlink. An attacker-owned directory in sticky /tmp (for example /tmp/recordings, created before your mkdir -p) is silently accepted. The owner can also grant you write through a macOS ACL that mode bits do not show, or chmod it from 0777 to 0755 between the staging write and the second check. In each case the script is published into or under a directory another local user owns, which is the exposure #4565 closes. The rule should be: a component is trusted only when its owner is the current uid or root, and only then do the sticky and private-group rules apply. Please put that in untrustedWritableExposure (return an owner exposure before the sticky exemption) and make othersCreateEntriesIn treat such a directory as one others can create entries in. Host-kit tests that fake stats.uid should prove it, as the test file already does for the group database.

A symlink component can also bypass the rule. When the link's own parent is private, line 230 stats only the final target, and the walk continues up the lexical chain, so the ancestors of the real target are never checked. With ~/rec -> /srv/team/rec and /srv/team at 0775 group team without sticky, a teammate can swap /srv/team/rec for a link to a directory you can write, or for their own directory. Writing to /srv/team/rec/journey.ad directly is refused, but going through the link is not, so the docs sentence that a symbolic link inside a writable directory is refused is false here. The rule should be: every directory the kernel traverses to reach the destination's parent passes the ownership and mode test. Please keep the lexical lstat walk for planted links and also walk fs.realpathSync of the deepest existing ancestor. That also covers /tmp/shared/work/../x/journey.ad, where the lexical normalization hides a planted work link. A test with a private link whose target sits under a 0777 or 0775-shared directory should prove it. The existing test at atomic-file-ancestry.test.ts:192 shows only that a link is followed.

The docs misstate sticky semantics. replay-e2e.md:75 says a sticky team directory is safe, but the directory's owner can still rename and remove entries. Line 74 and remote-proxy.md:111 ("only you and root can write") describe a guarantee the code enforces from mode bits only, and the scriptAncestryFailure hint and the assertPrivateScriptDestination JSDoc repeat it. Once the owner check lands, please say that a sticky directory is accepted only when you or root own it, and that every directory must be owned by you or root. Fix the hint and the JSDoc in the same change.

Not blocking, take or leave: the local writer runs mkdirSync before any ancestry check (session-script-writer.ts:138) while the remote path asserts first, so a refused destination can leave a directory behind; the 'swapped ancestor' writer test (session-script-writer-ancestry.test.ts:109) repeats the world-writable branch and no test drives a swap after the identity is captured on the local route; privateGroupIds reads only /etc/group and /etc/passwd, so an LDAP or sssd private group is refused as shared; remote re-declares the two ancestry reason literals that host-kit owns and statDirectoryChain stats a single path; and atomic-publish-ownership.test.ts asserts source text.

The CodeQL alert on the quadratic /\/+$/ in session-script-destination.ts:420 still applies and fails the check, and this PR adds that file from #4511, so it counts against the PR even though it is outside the #4565 delta. Trimming slashes with new URL(baseUrl) or a loop clears it: #4584 (comment). The Coverage result has no captured failure. The new host-kit win32 and catch branches may trip a patch-coverage gate; the failing job log should show which.

Before merge, the ancestry rule should trust only directories owned by you or root, follow the resolved chain of any symlink, and the docs and hint should match. The CodeQL alert should be cleared too.

thymikee and others added 8 commits November 16, 2026 12:23
A publish resolved the destination by name, so a second local user who
could write any directory on the way to it could replace that component,
or leave a symbolic link there before the entry was created, and move the
saved script wherever they chose.

`publishScriptFileSync` now asks first: `assertPrivateScriptDestination`
walks each component with `lstat` and refuses the chain under
`script_ancestor_untrusted` when a directory is writable by other, or by
a group that is not this user's own private group, unless the sticky bit
cancels the exposure. A symbolic link whose own directory others can
create entries in is refused whatever it points at. Ubuntu and Debian set
up every home directory as group-writable and owned by the user's private
group, so that shape is admitted, and `privateGroupIds` is exported so
the membership rule is testable on its own.

The caller also captures the parent's `dev:ino` before staging, and the
publish compares it before the link or rename, so a parent swapped out by
name while the file was written refuses under `script_ancestry_replaced`
instead of receiving the script. Node exposes no `openat` or `renameat`,
so publishing relative to a verified directory handle needs native code;
this is the rule that closes the same window without it.

Refs #4565

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The writer now publishes with `publishScriptFileSync`, and hands it the
identity of the directory it created, so a `--save-script` path with a
directory another local user can write refuses instead of landing the
recording there, and a parent replaced by name while the recording was
staged never receives it. A refusal is reported with the reason the rule
chose, and a refused destination is created by nothing.

Refs #4565

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A remote recording staged the version beside the destination and renamed
it into place, so an ancestor another local user could write steered both
the download and the entry.

`allocateStaging` now asks the destination rule before it creates
anything, so a refused path leaves no directory behind, and it reports
the destination directory's identity. `publishStaged` re-asks under the
record lock, immediately before the entry is created, so whoever could
write an ancestor while the version was downloaded cannot move it now.

The command keeps its success and carries the refusal's typed reason as
the `scriptDeliveryFailure` cause, so a caller can tell an unsafe
destination from a download that failed.

Refs #4565

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The replay guide states the destination rule for `--save-script`: every
directory on the way must be one only the user and root can write, why a
sticky shared team directory and a group-writable home of the user's own
private group are accepted, and why a symbolic link inside a directory
others can write is refused whatever it targets. Each surface's outcome
is stated: a local `close` fails and keeps its bytes, a remote recording
keeps its success and reports the reason as the `scriptDeliveryFailure`
cause, and the next recorded action repeats the refusal. The remote proxy
page points at that rule instead of repeating it, and ADR 0016 records the
rule, the private-group exception, the parent-identity re-check, and why
publishing relative to a directory handle was not available.

Refs #4565

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The daemon RPC manifest reached `PublishOutcome` through
`publishScriptVersion` and could not place it, so the outcome type the
client builds now carries a waiver naming the payload half it serializes,
and `ScriptDeliveryFailure` — the field a peer actually parses — is listed
with it. `publishScriptVersion`'s digest moves with the destination rule.

The same-directory publisher guard read the shared atomic publish owner by
name, so the script writer's new entry point failed it. The guard now
accepts either owner and states separately that the session script uses the
ancestry-owning one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Three ways through the destination rule stayed open.

Ownership was never asked, so a directory another user owned passed at
0755, and its owner could open it up or replace the subtree whenever they
liked; the sticky bit excused a directory whatever its ownership. The rule
now requires every directory on the chain to be owned by this user or by
root, and keeps the writability rule on top of that. A sticky shared
directory is still trusted for passing through, and the link rule requires
a link there to be owned by this user or root; nothing is created inside a
directory others can add entries to, so a shared parent no longer receives
the entry.

A symbolic link's target escaped the walk entirely: a link in the user's
own home pointing at a world-writable directory was judged only as the
link. The existing prefix is now resolved once and the whole resolved
chain is judged, so the shared target is refused; root-owned system
aliases such as macOS /tmp and /var keep working.

The private-group exception assumed a membership it could not prove. It
now fails closed: both database files must have been read, the group must
be this process's primary group and carry this user's name, its member
list may name nobody else, and no other passwd record may hold it as its
primary group. A name service that can add a member without touching
/etc/passwd is named as the limitation it is.

A published script is created 0600 locally as well as remotely, so a
recording is not world-readable in a directory that is merely shared.

Refs #4565

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Three ways through the ownership rule stayed open, and the identity check
was described as the thing that closes a race.

Ownership is now asked before the mode. `othersCreateEntriesIn` treats a
directory another user owns as theirs whatever its mode, so a link that
stands in their private-mode component is refused: they can rename that
component and leave one of their own there. A sticky bit excuses a
directory only when this user or root owns it, because both the sticky bit
and the group bits shield other users FROM an owner rather than the
reverse.

The chain keeps the `..` segments it was spelled with, so
`<dir>/shared/work/../x` is judged as the walk the kernel performs, with
the link named `work` in it, instead of the directory `path.resolve` names
after folding the `..` away; the fold points at a directory that receives
nothing.

The documentation and the refusal hint now say what the rule does:
a directory is accepted when this user or root owns it and its mode keeps
its contents closed to others, and the destination is never created where
others may add entries. The hint names ownership as well as writability.

Three ancestry tests were macOS-only in effect: an assertion that the
scratch root must differ from its real path cannot hold where `/tmp` is a
real directory, and two identity checks passed only because the filesystem
handed back a just-freed inode. The alias case now builds the alias it
needs, and a replaced parent is replaced with a directory that really is
another one.

Refs #4565

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Two shapes the rule has to refuse at the writer, not only in the rule
itself: a directory its owner made sticky with `chmod 1777`, where the
sticky bit shields other users from that owner rather than the reverse,
and a shared directory somebody else created first under `mkdir -p`.
Both run as a second local user, because handing a directory to another
uid needs privileges a test does not have.

Refs #4565

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@thymikee
thymikee force-pushed the fix/save-script-ancestor-redirect branch from 3f17db5 to 450a915 Compare November 16, 2026 11:25
@thymikee

thymikee commented Nov 16, 2026 •

Copy link
Copy Markdown
Member Author

Thanks for the update. At 450a915 the CodeQL alert on the trailing-slash regex is gone, and all 21 checks pass. Two defects remain in the destination checks, and there are no conflicts. Both are traced from the source.

The new rule no longer judges every directory the path traverses, so atomic-file.ts:278 accepts destinations that the earlier revision refused. The spelled walk skips every component that is not a link, and the realpath walk covers only the final resolved chain. For example, take <root>/shared (0777, not sticky), <root>/shared/mine (0700, mine) and mine/rec as a link to ~/private. The destination <root>/shared/mine/rec/journey.ad passes. Another local user can rename mine and plant their own rec. The same gap exists for a directory reached through an intermediate link, and for a foreign-owned grand-ancestor of a link. This breaks the promise in replay-e2e.md:74 and remote-proxy.md:111, for both the local writer and the remote client. The rule should be that every directory the kernel traverses to reach the parent passes untrustedAncestryExposure. Enumerating them means taking directoryChain(fs.realpathSync(P)) for every existing prefix P of the spelled parent, deduplicating, and judging each entry. The current deepest-realpath walk becomes the last iteration, and assertNoPlantedLink keeps the link-stability rule. Please add a host-kit test for the 0777 shared / 0700 mine / rec link case that expects world_writable at <root>/shared, and a second test where the shared directory is an intermediate link's target. I assumed a same-parent rename needs write access on the parent only. That holds for Linux rename(2); macOS is unconfirmed.

The remote client refuses a path the local writer accepts. session-script-destination.ts:206 runs assertPrivateScriptDestination before the missing parent is created at :207. For open --save-script /tmp/rec/journey.ad with rec absent, the deepest existing directory is /tmp, so the new shared_parent rule fails the version with script_ancestor_untrusted, and every later version repeats it. The local writer creates the directory first (session-script-writer.ts:137), so it accepts the same path. This contradicts replay-e2e.md:73 and ADR 0016, and a remote recording to a fresh directory under /tmp is never delivered. Both routes should apply the rule at the same point relative to creating missing parents. The smallest fix is to drop the pre-mkdir assert at :206, because allocateStaging at :256 already judges after the mkdir and refuses a directory that another user created first. If you prefer to refuse before mkdir on both routes, please say so in the docs, since that reverses the promise that missing parents are created. Please add a remote test for a missing parent under a sticky directory that this user or root owns.

Not blocking, and you can take or leave these: the test at atomic-file-ancestry.test.ts:661 is named 'admits it with root named among its members' but asserts .toBeUndefined(), which means privateGroupId refuses it, so rename it or admit root; file.ts:4 exports othersCreateEntriesIn, privateGroupId, untrustedAncestryExposure, untrustedLinkExposure and four types that nothing outside host-kit uses, so keeping only assertPrivateScriptDestination, publishDirectoryIdentity and publishScriptFileSync would be enough; and the daemon test 'a recording refuses a directory another user made sticky and owns' (session-script-writer-ancestry.test.ts:155) puts the destination directly in the 1777 directory, which the old shared_parent rule already refused, so it could put the destination in a subdirectory and fake only the sticky directory's uid, or be dropped as a duplicate of the host-kit case.

The code-scanning thread on the trailing-slash regex no longer applies, because the regex is gone at this head, so please resolve it: #4584 (comment)

A destination was judged only along the real path of its deepest existing ancestor, so a plain
directory under a shared one hid a link into a private destination, and one link into another link
named none of the ground it crossed. Every existing prefix is now expanded link by link and each
directory it steps into is judged. The remote route creates the missing parent before it asks, so
both routes answer about the directory the entry is really made in. The private-group exception now
reads every group record carrying that gid, because all of their members hold write. Access control
lists, network filesystems and mounts are named as outside the guarantee.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@thymikee

Copy link
Copy Markdown
Member Author

Head 546303c389 addresses both reviews.

Traversed directories. assertPrivateScriptDestination now judges every directory the kernel steps into, not the real path of the deepest existing ancestor alone. Each existing prefix of the spelled parent is expanded link by link, and the directory holding each link target is judged with it. Two cases that passed before now refuse, on the local writer and on the remote route: a plain directory under a 0777 one holding a link into a private destination, and ~/rec -> /srv/team/relay -> ~/chosen. Directories left through .. are judged as before.

Remote ordering. The remote client judged the chain before mkdir, so it refused the ordinary --save-script /tmp/rec/journey.ad shape while the local writer accepted it. The pre-mkdir call is gone; the check runs where the entry is really made, covered by a sticky-directory case.

Groups. privateGroupId now reads EVERY record carrying the numeric gid, not only the one named after the user, so ada:x:1000: beside team:x:1000:grace refuses. A duplicate-GID refusal, a same-gid alias admission, and a second-group primary refusal are covered. The residual risk is stated as reaching both ways: a name-service member can cause unsafe acceptance, not only refusal.

Scope of the claim. No ACL code. ADR 0016, the guide, and the remote page now name macOS and POSIX ACLs, network filesystems and mounts as outside the guarantee, and the unconditional confidentiality line is gone: the file is written 0600, that is not a promise about who can read it.

Hardening. The source-text check for the publisher entry point is deleted; the writer tests drive a real write and expect the typed refusals, so they cover dispatch by behaviour. The @agent-device/host-kit/file barrel keeps admission, identity capture and publication, and drops the six rule internals only its own tests used.

Checks: pnpm typecheck, pnpm lint, pnpm check:layering, pnpm check:production-exports, pnpm check:daemon-wire-compat, pnpm check:doc-links, pnpm check:doc-prose, pnpm check:adr-citations pass; the ancestry suites pass locally (106). Each new test fails on 450a915.

@thymikee

Copy link
Copy Markdown
Member Author

Thanks for the update. At 546303c the link to a last-component target such as rec -> shared/relay is now refused, and the trailing-slash regex is gone. Three ways to steer the destination still pass the rule, so the problem from the earlier review is not fully closed.

First, traversedDirectories judges only realpath(dirname(target)) for a link hop, so a link in the middle of the target path hides its directory. With home/rec -> <root>/shared/relay/sub, shared at 0777 and not sticky, and shared/relay -> home/chosen, the destination home/rec/journey.ad is accepted, and so is ../shared/relay/sub. Any local user who can write shared can swap relay between the check and the rename, on both the local writer and the remote client. This is the #4565 exposure and it contradicts the docs and ADR 0016. The rule should be that every directory where the kernel looks up a name, including the components of every link target at any depth, passes untrustedAncestryExposure. A walk that expands link targets component by component enumerates them; a realpath of the target's dirname does not. Please add a host-kit, daemon and remote test with rec -> shared/relay/sub that expects world_writable at shared.

Second, link stability is asked only by assertNoPlantedLink on the spelled path. Hop links are followed but their owner is never checked. Take ~/rec -> /tmp/relay, where another user created /tmp/relay in sticky /tmp pointing at ~/chosen. The spelled link is in a private home and passes, and /private/tmp is sticky and root-owned, so the foreign link is never asked. Spelling /tmp/relay/journey.ad directly is refused with planted_link, so one route gets two answers. The owner can replace the link after the check and redirect the publish. The rule should be that every link the kernel follows, spelled, hop, or inside a target, passes untrustedLinkExposure against the directory that holds it, judged in the same walk that enumerates directories. Please add a test that fakes the uid of a hop link in a sticky directory, as the existing tests fake ownership. I confirmed this from the code path only, because I could not create a link owned by another uid without root.

Third, resolvedDirectory uses JS fs.realpathSync, which folds .. lexically, while the kernel applies .. to the link's target. With home/work -> priv/x, priv/y at 0777 and home/y at 0700, the destination <root>/home/work/../y/journey.ad judges home/y and is accepted, yet the file is created in priv/y. Spelling priv/y/journey.ad directly is refused with world_writable. Absolute --save-script paths reach the rule unnormalized, so both routes are affected, and this breaks the .. claim in replay-e2e.md and ADR 0016. The rule should be that .. applies to the directory the walk is actually in, never to the spelled string. Please add a test with the home/work/../y shape that expects world_writable at priv/y.

Could one component walker replace assertNoPlantedLink, traversedDirectories, resolvedDirectory, linkTarget and the realpath calls? Start at / with the spelled components on a queue. For each component, judge the current directory with untrustedAncestryExposure, deduplicated. On .., move to parentDirectory(current). Otherwise lstat current/name: judge a link with untrustedLinkExposure against current, count one hop, and put its target components at the front of the queue, resetting to / for an absolute target. A directory becomes current, and an absent entry stops the walk with current as deepest. Then ask othersCreateEntriesIn(deepest). That one loop closes all three by construction and needs no realpath.

The Repo Guards & Compatibility check fails in Run Fallow audit on complexity of traversedDirectories (cognitive 35) and privateGroupId (cognitive 17), both added or rewritten in this delta. All checks passed at the earlier head. The one-walker design would also clear the first. There are no conflicts.

The github-advanced-security thread on the trailing-slash regex no longer applies: parentDirectory now uses endsWith/lastIndexOf, so it can be resolved.

Not blocking, take or leave: the four-line comment at atomic-publish-ownership.test.ts:31 that points to another test file can be deleted.

The shapes above were probed against the head atomic-file.ts on macOS.

Before merge, the two link walks need to become one kernel-lookup walk that judges every looked-up directory and every followed link, with the three regression shapes added and the Fallow audit passing.

The destination rule resolved each existing prefix with `realpathSync` and
judged the chains it got back, so a directory the resolution stepped through
could leave the answer: a link in the middle of a target hid its directory, a
followed link's owner was never asked, and a `..` was applied to the spelling
rather than to the link's target. `assertNoPlantedLink` covered only the links
in the spelled path, so an expanded hop skipped the check.

One walker now replaces `traversedDirectories`, `assertNoPlantedLink`,
`resolvedDirectory`, `linkTarget`, `parentDirectory` and every `realpath` call.
It starts at `/`, or at the process's resolved working directory for a relative
spelling, and resolves the spelled components one at a time: `.` is skipped,
`..` moves to the parent of the directory physically stood in, any other name is
lstat'ed there. A directory is judged and entered; a link is judged itself
against the directory that holds it, and its target's components go on the
front of the queue. Hop count is refused as `link_loop_exceeded` below the
kernel's own limit, so a walk that ran out of hops is a refusal, and a step that
cannot be travelled through is refused as `not_a_directory`.

The private-group exception now fails closed: it is admitted only when
`/etc/nsswitch.conf` exists, is readable, and lists `files` as the only source
for `passwd` and `group`, because a name service can hold a member the two
files never show. `systemd` is refused for the same reason. The account name is
read from the passwd database the rule judges rather than from a second host
lookup, and the script file mode is fixed at `0600`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
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.

--save-script destination can be redirected by other local users who can write an ancestor directory

2 participants