From 070d8866b9a5823fbd88170b61077fec42ca8772 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 16 Nov 2026 10:30:49 +0100 Subject: [PATCH 01/10] fix(host-kit): refuse a script destination another local user can steer 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 --- packages/host-kit/src/file.ts | 3 + .../src/internal/atomic-file-ancestry.test.ts | 315 ++++++++++++++++++ packages/host-kit/src/internal/atomic-file.ts | 250 ++++++++++++++ 3 files changed, 568 insertions(+) create mode 100644 packages/host-kit/src/internal/atomic-file-ancestry.test.ts diff --git a/packages/host-kit/src/file.ts b/packages/host-kit/src/file.ts index fd0b251e09..8779eccfb5 100644 --- a/packages/host-kit/src/file.ts +++ b/packages/host-kit/src/file.ts @@ -1,7 +1,10 @@ export { + assertPrivateScriptDestination, isAtomicPublishTemporaryPath, + publishDirectoryIdentity, publishDurableFileSync, publishFileSync, + publishScriptFileSync, type DurableFilePublishMode, } from './internal/atomic-file.ts'; export { diff --git a/packages/host-kit/src/internal/atomic-file-ancestry.test.ts b/packages/host-kit/src/internal/atomic-file-ancestry.test.ts new file mode 100644 index 0000000000..9445f855dc --- /dev/null +++ b/packages/host-kit/src/internal/atomic-file-ancestry.test.ts @@ -0,0 +1,315 @@ +import { afterEach, expect, test, vi } from 'vitest'; +import fs from 'node:fs'; +// oxlint-disable-next-line no-restricted-imports -- the fixture's private group is named after os.userInfo()'s user, not a scratch path +import os from 'node:os'; +import path from 'node:path'; +import { AppError } from '@agent-device/kernel/errors'; +import { mkdtempForTestSync } from './tmp-dir.fixtures.ts'; +import { + assertPrivateScriptDestination, + privateGroupIds, + publishDirectoryIdentity, + publishScriptFileSync, +} from './atomic-file.ts'; + +const skipOnWindows = process.platform === 'win32' ? test.skip : test; + +/** The group database a test stands in for `/etc/group` and `/etc/passwd`. */ +type Database = Readonly<{ groups: readonly string[]; passwd: readonly string[] }>; + +const realReadFileSync = fs.readFileSync; +const currentUser = os.userInfo().username; + +/** This process's ids. Windows has neither, and every test that uses them is skipped there. */ +const currentUid = process.getuid?.() ?? -1; +const currentGid = process.getgid?.() ?? -1; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +/** + * Serves `database` for the two group files and the real host for everything else, so the + * private-group decision is the fixture's and not the CI image's user list. + */ +function serveGroupDatabase(database: Database): void { + vi.spyOn(fs, 'readFileSync').mockImplementation(((file: unknown, options?: unknown) => { + if (file === '/etc/group') return `${database.groups.join('\n')}\n`; + if (file === '/etc/passwd') return `${database.passwd.join('\n')}\n`; + return realReadFileSync(file as never, options as never) as never; + }) as typeof fs.readFileSync); +} + +/** This host's user with a group of their own, and a team group that holds someone else. */ +function hostDatabase(privateGid: number, sharedGid: number): Database { + return { + groups: ['root:x:0:root', `${currentUser}:x:${privateGid}:`, `team:x:${sharedGid}:ada`], + passwd: [`root:x:0:0`, `${currentUser}:x:${currentUid}:${privateGid}:`], + }; +} + +function root(): string { + return fs.realpathSync(mkdtempForTestSync('host-kit-ancestry-')); +} + +/** A directory carrying `mode` and `gid`, so the rule reads the group the test chose. */ +function directoryWith(directory: string, mode: number, gid = currentGid): string { + fs.mkdirSync(directory); + fs.chownSync(directory, currentUid, gid); + fs.chmodSync(directory, mode); + return directory; +} + +function publish(destination: string, parentIdentity?: string): void { + publishScriptFileSync({ + destination, + contents: 'context\n', + ...(parentIdentity === undefined ? {} : { parentIdentity }), + }); +} + +function expectUntrusted(run: () => void, exposure: string, ancestor: string): void { + expectRefusal(run, 'script_ancestor_untrusted', exposure, ancestor); +} + +function expectUntrustedReplaced(run: () => void, ancestor: string): void { + expectRefusal(run, 'script_ancestry_replaced', 'parent_replaced', ancestor); +} + +function expectRefusal(run: () => void, reason: string, exposure: string, ancestor: string): void { + let details: Record | undefined; + try { + run(); + } catch (error) { + expect(error).toBeInstanceOf(AppError); + details = (error as AppError).details as Record; + } + expect(details).toMatchObject({ reason, exposure, ancestor }); +} + +// --- a chain another local user can act inside is refused --- + +skipOnWindows('publishes to a chain only this user can write', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const workflows = path.join(root(), 'workflows'); + fs.mkdirSync(workflows); + + publish(path.join(workflows, 'journey.ad')); + + expect(fs.readFileSync(path.join(workflows, 'journey.ad'), 'utf8')).toBe('context\n'); +}); + +skipOnWindows('refuses a destination under a world-writable directory', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const shared = directoryWith(path.join(root(), 'shared'), 0o777); + const destination = path.join(shared, 'journey.ad'); + + expectUntrusted(() => publish(destination), 'world_writable', shared); + expect(fs.existsSync(destination)).toBe(false); +}); + +skipOnWindows('refuses a world-writable ancestor above the parent', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const shared = directoryWith(path.join(root(), 'shared'), 0o777); + const work = path.join(shared, 'work'); + fs.mkdirSync(work); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(work, 'journey.ad')), + 'world_writable', + shared, + ); +}); + +skipOnWindows('refuses a destination under a group-writable shared directory', () => { + const gid = currentGid; + serveGroupDatabase(hostDatabase(4321, gid)); + const team = directoryWith(path.join(root(), 'team'), 0o775, gid); + const sub = path.join(team, 'sub'); + fs.mkdirSync(sub); + + expectUntrusted(() => publish(path.join(sub, 'journey.ad')), 'shared_group_writable', team); + expect(fs.readdirSync(sub)).toEqual([]); +}); + +// --- the Ubuntu and Debian private-group home keeps working --- + +skipOnWindows('publishes to a group-writable home directory of a private group', () => { + const gid = currentGid; + serveGroupDatabase(hostDatabase(gid, 4321)); + const home = directoryWith(path.join(root(), 'home'), 0o775, gid); + + publish(path.join(home, 'journey.ad')); + + expect(fs.readFileSync(path.join(home, 'journey.ad'), 'utf8')).toBe('context\n'); +}); + +skipOnWindows("refuses the same mode and group once the group is not the user's own", () => { + const gid = currentGid; + serveGroupDatabase(hostDatabase(4321, gid)); + const home = directoryWith(path.join(root(), 'home'), 0o775, gid); + + expectUntrusted(() => publish(path.join(home, 'journey.ad')), 'shared_group_writable', home); +}); + +skipOnWindows('publishes to a setgid group-writable private-group home', () => { + const gid = currentGid; + serveGroupDatabase(hostDatabase(gid, 4321)); + const home = directoryWith(path.join(root(), 'home'), 0o2775, gid); + + publish(path.join(home, 'journey.ad')); + + expect(fs.existsSync(path.join(home, 'journey.ad'))).toBe(true); +}); + +// --- a sticky shared directory is safe, except through a link planted in it --- + +skipOnWindows('publishes to a destination under a sticky world-writable directory', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const shared = directoryWith(path.join(root(), 'shared'), 0o1777); + + publish(path.join(shared, 'journey.ad')); + + expect(fs.existsSync(path.join(shared, 'journey.ad'))).toBe(true); +}); + +skipOnWindows('refuses a symbolic link planted in a directory others can write', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const directory = root(); + const shared = directoryWith(path.join(directory, 'shared'), 0o1777); + const attacker = path.join(directory, 'attacker'); + fs.mkdirSync(attacker); + fs.symlinkSync(attacker, path.join(shared, 'work')); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(shared, 'work', 'journey.ad')), + 'planted_link', + path.join(shared, 'work'), + ); + expect(fs.readdirSync(attacker)).toEqual([]); +}); + +skipOnWindows('follows a symbolic link inside a directory only this user can write', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const directory = root(); + const real = path.join(directory, 'real'); + fs.mkdirSync(real); + fs.symlinkSync(real, path.join(directory, 'link')); + + publish(path.join(directory, 'link', 'journey.ad')); + + expect(fs.existsSync(path.join(real, 'journey.ad'))).toBe(true); +}); + +// --- the destination directory swapped out while the file was staged --- + +skipOnWindows('refuses a parent replaced by name while the file was staged', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const directory = root(); + const staged = path.join(directory, 'work'); + fs.mkdirSync(staged); + const parentIdentity = publishDirectoryIdentity(staged); + const destination = path.join(staged, 'journey.ad'); + fs.rmSync(staged, { recursive: true }); + const replaced = path.join(directory, 'work'); + fs.mkdirSync(replaced); + + expectUntrustedReplaced(() => publish(destination, parentIdentity), replaced); + expect(fs.readdirSync(replaced)).toEqual([]); +}); + +skipOnWindows('re-checks the chain after staging the file, before the entry is created', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const directory = root(); + const staged = path.join(directory, 'work'); + fs.mkdirSync(staged); + const destination = path.join(staged, 'journey.ad'); + const writeFileSync = fs.writeFileSync; + // The window a second local user races: the file is staged, the entry is not created yet. + vi.spyOn(fs, 'writeFileSync').mockImplementation(((file: unknown, ...rest: unknown[]) => { + const result = (writeFileSync as (...args: unknown[]) => unknown)(file, ...rest); + fs.rmSync(staged, { recursive: true, force: true }); + fs.mkdirSync(staged); + fs.chmodSync(staged, 0o777); + return result; + }) as typeof fs.writeFileSync); + + expectUntrustedReplaced(() => publish(destination), staged); + expect(fs.readdirSync(staged)).toEqual([]); +}); + +skipOnWindows('publishes into the parent the captured identity still names', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const staged = path.join(root(), 'work'); + fs.mkdirSync(staged); + + publish(path.join(staged, 'journey.ad'), publishDirectoryIdentity(staged)); + + expect(fs.existsSync(path.join(staged, 'journey.ad'))).toBe(true); +}); + +// --- privateGroupIds: the one group shape the exception admits --- + +const ADA = { uid: 1000, name: 'ada' }; + +function database(groups: readonly string[], passwd: readonly string[]) { + return { groups, passwd }; +} + +test('treats the group named after the user, holding only them, as private', () => { + const ids = privateGroupIds( + database(['ada:x:1000:', 'staff:x:20:root'], ['ada:x:1000:1000:', 'root:x:0:0']), + ADA, + ); + expect([...ids]).toEqual([1000]); +}); + +test('treats a group as private when only its primary-group link names the user', () => { + const ids = privateGroupIds( + database(['ada:x:1000:', 'staff:x:20:'], ['root:x:0:0', 'ada:x:1000:1000:']), + ADA, + ); + expect([...ids]).toEqual([1000]); +}); + +test('still treats a group as private with root among its members', () => { + const ids = privateGroupIds( + database(['ada:x:1000:root', 'staff:x:20:'], ['ada:x:1000:1000:', 'root:x:0:0']), + ADA, + ); + expect([...ids]).toEqual([1000]); +}); + +test('treats the group named after the user as shared once another user is a member', () => { + const ids = privateGroupIds( + database( + ['ada:x:1000:grace', 'staff:x:20:'], + ['ada:x:1000:1000:', 'grace:x:1001:1001:', 'root:x:0:0'], + ), + ADA, + ); + expect([...ids]).toEqual([]); +}); + +test('treats the group named after the user as shared once another user has it as primary group', () => { + const ids = privateGroupIds( + database(['ada:x:1000:', 'staff:x:20:'], ['ada:x:1000:1000:', 'grace:x:1001:1000:']), + ADA, + ); + expect([...ids]).toEqual([]); +}); + +test('never treats another group name as private, however few members it lists', () => { + const ids = privateGroupIds(database(['team:x:4321:', 'ada:x:1000:'], ['ada:x:1000:1000:']), ADA); + expect([...ids]).toEqual([1000]); +}); + +test('treats an unreadable group database as having no private group', () => { + expect([...privateGroupIds(database([], []), ADA)]).toEqual([]); +}); + +test('gives a caller without a full identity no private group', () => { + const groups = database(['ada:x:1000:'], ['ada:x:1000:1000:']); + expect([...privateGroupIds(groups, { uid: undefined, name: 'ada' })]).toEqual([]); + expect([...privateGroupIds(groups, { uid: 1000, name: undefined })]).toEqual([]); +}); diff --git a/packages/host-kit/src/internal/atomic-file.ts b/packages/host-kit/src/internal/atomic-file.ts index bb00b26944..f05b8550b3 100644 --- a/packages/host-kit/src/internal/atomic-file.ts +++ b/packages/host-kit/src/internal/atomic-file.ts @@ -1,6 +1,8 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; +import os from 'node:os'; import path from 'node:path'; +import { AppError } from '@agent-device/kernel/errors'; import { emitDiagnostic } from './diagnostics.ts'; export type AtomicPublishMode = 'replace' | 'link-exclusive'; @@ -42,6 +44,41 @@ export function publishFileSync(options: { }); } +/** + * Publishes a session script, and nothing else, from a same-directory temporary sibling. + * + * This is `publishFileSync` plus the destination-ancestry rule (#4565): the chain is refused before + * anything is written, and it is checked again immediately before the link or rename, so a directory + * swapped in by another local user while the file was staged never receives the script. + * + * `parentIdentity` is what {@link publishDirectoryIdentity} returned for a parent the caller created or + * checked before it staged this file. + */ +export function publishScriptFileSync(options: { + destination: string; + contents: string; + mode?: number; + publish?: AtomicPublishMode; + parentIdentity?: string; +}): void { + const expected = + options.parentIdentity ?? publishDirectoryIdentity(path.dirname(options.destination)); + withAtomicPublishTempPathSync(options.destination, (temporaryPath) => { + assertPrivateScriptDestination(options.destination, expected); + fs.writeFileSync( + temporaryPath, + options.contents, + options.mode === undefined ? 'utf8' : { encoding: 'utf8', mode: options.mode }, + ); + assertPrivateScriptDestination(options.destination, expected); + if (options.publish === 'link-exclusive') { + fs.linkSync(temporaryPath, options.destination); + } else { + fs.renameSync(temporaryPath, options.destination); + } + }); +} + export type DurableFilePublishMode = 'replace' | 'link-exclusive'; /** Publishes complete UTF-8 contents with a durable file and directory fence. */ @@ -148,6 +185,219 @@ export function isAtomicPublishTemporaryPath(value: unknown, destination: string return name.startsWith(`.${path.basename(destination)}.`) && name.endsWith('.tmp'); } +/** + * Refuses a script destination when another local user can write a directory on the way to it (#4565). + * + * Node exposes no `openat` or `renameat`, so a publisher cannot resolve a destination relative to a + * directory handle. What remains is to refuse every chain a second local user can act inside: a + * directory they can write is one where they can replace a component of this path, or create one before + * this client does, so the script lands where they choose, or they take it from a directory they own. + * + * The rule reads each component with `lstat`, so a symbolic link is judged as the link it is and is + * never mistaken for the directory its target names: + * + * - A component's mode decides. The sticky bit cancels the exposure: it stops anyone but an entry's + * owner or root from removing or replacing that entry, which is how a shared team directory is made + * safe, and why the hint names it. + * - Otherwise a component writable by anyone other than this user is refused, except a group-writable + * one whose group is this user's own private group: Ubuntu and Debian set up every home directory + * that way, often group-writable, and those have to stay usable. + * - A symbolic link whose own directory others can create entries in is refused whatever it points at: + * it may be one they planted, and its target is theirs to choose. The sticky bit does not help here, + * because it guards entries that already exist. + * + * An absent or non-directory component is left alone: the filesystem refuses a publish through it. On + * Windows, access is an ACL rather than a mode, so this is a no-op there. + * + * `parentIdentity` is what {@link publishDirectoryIdentity} returned for the parent the caller created + * or checked before it staged this file. Whoever owns a directory above it can open that directory to + * others, swap the parent for one of their own while the file is staged, and close it again, and only + * the identity catches that. + */ +export function assertPrivateScriptDestination(destination: string, parentIdentity?: string): void { + if (process.platform === 'win32') return; + const parent = path.dirname(path.resolve(destination)); + if (parentIdentity !== undefined && publishDirectoryIdentity(parent) !== parentIdentity) { + throw scriptAncestryFailure(destination, parent, 'parent_replaced'); + } + const privateGids = lazyPrivateGroupIds(); + for (const ancestor of directoryChain(parent)) { + const link = lstatIfPresentSync(ancestor); + if (!link) continue; + if (link.isSymbolicLink() && othersCreateEntriesIn(path.dirname(ancestor), privateGids)) { + throw scriptAncestryFailure(destination, ancestor, 'planted_link'); + } + const directory = link.isSymbolicLink() ? statDirectoryChain(ancestor) : link; + if (!directory?.isDirectory()) continue; + const exposure = untrustedWritableExposure(directory, privateGids()); + if (exposure) throw scriptAncestryFailure(destination, ancestor, exposure); + } +} + +/** + * One directory's identity on its filesystem, for a caller that must publish into the same one it + * created or checked. `undefined` when the directory is absent or is not a directory. + */ +export function publishDirectoryIdentity(directory: string): string | undefined { + if (process.platform === 'win32') return 'windows'; + const stats = statDirectoryChain(directory); + return stats ? `${stats.dev}:${stats.ino}` : undefined; +} + +/** The group and passwd records the private-group exception reads, in `/etc/group` field order. */ +type HostGroupDatabase = Readonly<{ + groups: readonly string[]; + passwd: readonly string[]; +}>; + +/** + * The private group of `current`, in the one shape the exception admits: the group named after them. + * + * Ubuntu and Debian create one group per user, named after them, and set up that user's home directory + * with it, often group-writable. Such a home is shared with no other local user, so it stays a valid + * script destination. Every other group name stays outside the exception: this host's own records + * cannot bound it, because macOS lists only part of `staff` in `/etc/group` while every local user + * holds it, and a name service can add members to a group this machine cannot read. + * + * Membership comes from both places a member can appear: the group's own member list, and the users + * whose primary group is this one. A member who is neither `current` nor root disqualifies the group. + */ +export function privateGroupIds( + database: HostGroupDatabase, + current: Readonly<{ uid: number | undefined; name: string | undefined }>, +): Set { + const privateIds = new Set(); + if (current.uid === undefined || current.name === undefined) return privateIds; + const uidByName = new Map(); + const primaryMembers = new Map(); + for (const line of database.passwd) { + const [name, , rawUid, rawGid] = line.split(':'); + const uid = Number(rawUid); + const gid = Number(rawGid); + if (!name || !Number.isInteger(uid) || !Number.isInteger(gid)) continue; + uidByName.set(name, uid); + primaryMembers.set(gid, [...(primaryMembers.get(gid) ?? []), name]); + } + for (const line of database.groups) { + const [name, , rawGid, rawMembers] = line.split(':'); + const gid = Number(rawGid); + if (name !== current.name || !Number.isInteger(gid)) continue; + const supplementary = (rawMembers ?? '').split(',').filter((member) => member.length > 0); + const ids = [...supplementary, ...(primaryMembers.get(gid) ?? [])].map((member) => + uidByName.get(member), + ); + if (ids.every((id) => id === current.uid || id === 0)) privateIds.add(gid); + } + return privateIds; +} + +/** This host's private groups, read from the group database the first time the chain meets one. */ +function lazyPrivateGroupIds(): () => ReadonlySet { + let cached: ReadonlySet | undefined; + return () => + (cached ??= privateGroupIds( + { groups: readSystemFile('/etc/group'), passwd: readSystemFile('/etc/passwd') }, + { uid: process.getuid?.(), name: readCurrentUser() }, + )); +} + +function readCurrentUser(): string | undefined { + try { + return os.userInfo().username; + } catch { + return undefined; + } +} + +/** Every directory from `directory` up to the filesystem root, nearest first. */ +function directoryChain(directory: string): string[] { + const chain: string[] = []; + let current = directory; + for (;;) { + chain.push(current); + const parent = path.dirname(current); + if (parent === current) return chain; + current = parent; + } +} + +/** Why other local users can write in this directory, or `undefined` when only this user and root can. */ +function untrustedWritableExposure( + stats: fs.Stats, + privateGids: ReadonlySet, +): AncestryExposure | undefined { + if (stats.mode & 0o1000) return undefined; + if (stats.mode & 0o002) return 'world_writable'; + if (stats.mode & 0o020 && !privateGids.has(stats.gid)) return 'shared_group_writable'; + return undefined; +} + +/** Whether other local users can create an entry here: how a component becomes their symbolic link. */ +function othersCreateEntriesIn(directory: string, privateGids: () => ReadonlySet): boolean { + const stats = statDirectoryChain(directory); + if (!stats) return false; + if (stats.mode & 0o002) return true; + return Boolean(stats.mode & 0o020) && !privateGids().has(stats.gid); +} + +type AncestryExposure = + | 'world_writable' + | 'shared_group_writable' + | 'planted_link' + | 'parent_replaced'; + +function scriptAncestryFailure( + destination: string, + ancestor: string, + exposure: AncestryExposure, +): AppError { + const writableByOthers = exposure !== 'parent_replaced'; + return new AppError( + 'COMMAND_FAILED', + writableByOthers + ? `Refusing to save the script under ${ancestor}: another local user can write that part of the path.` + : `The directory for ${destination} changed while the script was staged, so the script was not saved.`, + { + reason: writableByOthers ? 'script_ancestor_untrusted' : 'script_ancestry_replaced', + exposure, + path: destination, + ancestor, + hint: writableByOthers + ? `Save the script under a directory only you can write, or share ${ancestor} safely with the sticky bit (chmod +t) and keep symbolic links out of the path.` + : 'Re-record with open --save-script, or save under a directory nobody else can write.', + }, + ); +} + +function readSystemFile(file: string): string[] { + try { + return fs.readFileSync(file, 'utf8').split('\n'); + } catch { + return []; + } +} + +/** `lstat` where absence is `undefined`; any other failure propagates. */ +function lstatIfPresentSync(pathname: string): fs.Stats | undefined { + try { + return fs.lstatSync(pathname); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; + throw error; + } +} + +/** `stat` of the directory a path names, or `undefined` when it is absent or is not a directory. */ +function statDirectoryChain(pathname: string): fs.Stats | undefined { + let stats: fs.Stats | undefined; + try { + stats = fs.statSync(pathname); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; + throw error; + } + return stats.isDirectory() ? stats : undefined; +} function assertSafeDestination(destination: string): void { const stats = lstatIfPresent(destination); if (stats?.isSymbolicLink()) { From 4fb1e78c2b152fbfc426ee7437e2e79610539c7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 16 Nov 2026 10:30:52 +0100 Subject: [PATCH 02/10] fix(daemon): apply the destination rule to a local script save 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 --- .../session-script-writer-ancestry.test.ts | 140 ++++++++++++++++++ .../daemon/src/core/session-script-writer.ts | 9 +- 2 files changed, 146 insertions(+), 3 deletions(-) create mode 100644 packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts diff --git a/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts b/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts new file mode 100644 index 0000000000..80198713c3 --- /dev/null +++ b/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts @@ -0,0 +1,140 @@ +import { expect, test } from 'vitest'; +import fs from 'node:fs'; +// oxlint-disable-next-line no-restricted-imports -- the private-group fixture is named after os.userInfo()'s user, not a scratch path +import os from 'node:os'; +import path from 'node:path'; +import { createLiveTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; +import { SessionScriptWriter } from '../session-script-writer.ts'; +import { makeAuthoringSession } from '../../__tests__/support/session-factories.ts'; + +const hostCwd = createLiveTestHostEnvironment().cwd; +const skipOnWindows = process.platform === 'win32' ? test.skip : test; + +/** The private-group exception is decided by this host's group database. */ +function groupDatabaseMatchesHost(gid: number): boolean { + try { + const name = os.userInfo().username; + const groups = fs.readFileSync('/etc/group', 'utf8').split('\n'); + const passwd = fs.readFileSync('/etc/passwd', 'utf8').split('\n'); + const line = groups.find((entry) => entry.split(':')[0] === name); + if (!line || Number(line.split(':')[2]) !== gid) return false; + const extra = (line.split(':')[3] ?? '').split(',').filter(Boolean); + return ( + extra.every((member) => member === name || member === 'root') && + passwd.every((entry) => { + const [user, , , primary] = entry.split(':'); + return Number(primary) !== gid || user === name || user === 'root'; + }) + ); + } catch { + return false; + } +} + +function action(command: string): { + ts: number; + command: string; + positionals: string[]; + flags: Record; +} { + return { ts: Date.now(), command, positionals: ['Demo'], flags: {} }; +} + +function recordingTo(destination: string) { + return makeAuthoringSession('journey', { + scriptPublication: { + kind: 'authoring', + status: 'armed', + target: { kind: 'explicit', path: destination, force: false }, + }, + actions: [action('open')], + }); +} + +function root(): string { + return fs.realpathSync(mkdtempForTestSync('agent-device-script-ancestry-')); +} + +function sharedDirectory(directory: string, mode: number): string { + fs.mkdirSync(directory); + fs.chmodSync(directory, mode); + return directory; +} + +function refusal(result: ReturnType): Record { + expect(result.written).toBe(false); + if (result.written || !result.error) throw new Error('expected a refused write'); + return result.error.details as Record; +} + +skipOnWindows('an ordinary recording saves under a chain only this user can write', () => { + const destination = path.join(root(), 'workflows', 'journey.ad'); + const writer = new SessionScriptWriter(path.join(root(), 'sessions'), hostCwd); + + const result = writer.write(recordingTo(destination)); + + expect(result.written).toBe(true); + expect(fs.readFileSync(destination, 'utf8')).toContain('open'); +}); + +skipOnWindows('a recording refuses a destination under a world-writable directory', () => { + const shared = sharedDirectory(path.join(root(), 'shared'), 0o777); + const destination = path.join(shared, 'journey.ad'); + const writer = new SessionScriptWriter(path.join(root(), 'sessions'), hostCwd); + + const details = refusal(writer.write(recordingTo(destination))); + + expect(details).toMatchObject({ + reason: 'script_ancestor_untrusted', + exposure: 'world_writable', + }); + expect(fs.existsSync(destination)).toBe(false); +}); + +skipOnWindows('a recording refuses an ancestor swapped out for a symbolic link', () => { + const directory = root(); + const shared = sharedDirectory(path.join(directory, 'shared'), 0o1777); + const attacker = path.join(directory, 'attacker'); + fs.mkdirSync(attacker); + fs.symlinkSync(attacker, path.join(shared, 'work')); + const destination = path.join(shared, 'work', 'journey.ad'); + const writer = new SessionScriptWriter(path.join(directory, 'sessions'), hostCwd); + + const details = refusal(writer.write(recordingTo(destination))); + + expect(details).toMatchObject({ reason: 'script_ancestor_untrusted', exposure: 'planted_link' }); + expect(fs.readdirSync(attacker)).toEqual([]); +}); + +skipOnWindows('a recording refuses an ancestor swapped out for a writable directory', () => { + const directory = root(); + const work = path.join(directory, 'work'); + fs.mkdirSync(work); + const destination = path.join(work, 'journey.ad'); + // Another local user replaces the destination directory by name before this write runs. + fs.rmSync(work, { recursive: true }); + fs.mkdirSync(work); + fs.chmodSync(work, 0o777); + const writer = new SessionScriptWriter(path.join(directory, 'sessions'), hostCwd); + + const details = refusal(writer.write(recordingTo(destination))); + + expect(details).toMatchObject({ + reason: 'script_ancestor_untrusted', + exposure: 'world_writable', + }); + expect(fs.readdirSync(work)).toEqual([]); +}); + +skipOnWindows('a recording still saves to a group-writable private-group home', () => { + const gid = process.getgid?.(); + if (gid === undefined || !groupDatabaseMatchesHost(gid)) return; + const home = path.join(root(), 'home'); + fs.mkdirSync(home); + fs.chmodSync(home, 0o775); + const writer = new SessionScriptWriter(path.join(root(), 'sessions'), hostCwd); + + const result = writer.write(recordingTo(path.join(home, 'journey.ad'))); + + expect(result.written).toBe(true); +}); diff --git a/packages/daemon/src/core/session-script-writer.ts b/packages/daemon/src/core/session-script-writer.ts index be5050e645..c4abbd5618 100644 --- a/packages/daemon/src/core/session-script-writer.ts +++ b/packages/daemon/src/core/session-script-writer.ts @@ -19,7 +19,7 @@ import { stripRecordedRefGeneration, } from '@agent-device/ad-script'; import { expandSessionPath, safeSessionName } from '@agent-device/host-kit/session-paths'; -import { publishFileSync } from '@agent-device/host-kit/file'; +import { publishDirectoryIdentity, publishScriptFileSync } from '@agent-device/host-kit/file'; import type { SessionState } from './session-state.ts'; import { NO_SCRIPT_PUBLICATION, @@ -143,6 +143,7 @@ export class SessionScriptWriter { scriptPath, script: prepared.script, force: options?.force, + parentIdentity: publishDirectoryIdentity(scriptDir), ...(remote ? { mode: 0o600 } : {}), }); // COMMITTED: idempotent guard above + teardown's abort/tombstone routing. @@ -302,13 +303,15 @@ function publishHealedScriptAtomically(params: { script: string; force?: boolean; mode?: number; + parentIdentity?: string; }): void { - const { scriptPath, script, force, mode } = params; + const { scriptPath, script, force, mode, parentIdentity } = params; try { - publishFileSync({ + publishScriptFileSync({ destination: scriptPath, contents: script, publish: force ? 'replace' : 'link-exclusive', + ...(parentIdentity === undefined ? {} : { parentIdentity }), ...(mode === undefined ? {} : { mode }), }); } catch (error) { From 1dc9b712be9aabe22be7e4efd598838d1adcf5c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 16 Nov 2026 10:30:55 +0100 Subject: [PATCH 03/10] fix(remote): refuse an unsafe script destination before it is downloaded 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 --- .../daemon-artifacts-script-download.test.ts | 85 +++++++++++++++++++ .../remote/src/session-script-destination.ts | 78 ++++++++++++++--- test/wire-compat/ledger.json | 2 +- 3 files changed, 154 insertions(+), 11 deletions(-) diff --git a/packages/remote/src/__tests__/daemon-artifacts-script-download.test.ts b/packages/remote/src/__tests__/daemon-artifacts-script-download.test.ts index 8fe6668d8d..585cf53d74 100644 --- a/packages/remote/src/__tests__/daemon-artifacts-script-download.test.ts +++ b/packages/remote/src/__tests__/daemon-artifacts-script-download.test.ts @@ -465,6 +465,91 @@ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0).each([ }, ); +test.skipIf(process.platform === 'win32').each([ + { + name: 'a symbolic link planted where the script should land', + plant: (root: string) => { + const shared = path.join(root, 'shared'); + fs.mkdirSync(shared); + fs.chmodSync(shared, 0o1777); + const attacker = path.join(root, 'attacker'); + fs.mkdirSync(attacker); + fs.symlinkSync(attacker, path.join(shared, 'work')); + return { + destination: path.join(shared, 'work', 'journey.ad'), + untouched: attacker, + }; + }, + }, + { + name: 'a world-writable directory', + plant: (root: string) => { + const shared = path.join(root, 'shared'); + fs.mkdirSync(shared); + fs.chmodSync(shared, 0o777); + return { destination: path.join(shared, 'journey.ad'), untouched: shared }; + }, + }, +])('a remote recording refuses a destination under $name', async ({ plant }) => { + const root = fs.realpathSync(mkdtempForTestSync('script-ancestry-')); + const stateDir = path.join(root, 'state'); + const { destination, untouched } = plant(root); + const baseUrl = await artifactServer({ v1: { body: 'open Demo\n' } }); + + const { response } = await open(baseUrl, stateDir, destination); + + expect(response).toEqual( + expect.objectContaining({ + ok: true, + data: expect.objectContaining({ + scriptDeliveryFailure: expect.objectContaining({ + cause: 'script_ancestor_untrusted', + }), + }), + }), + ); + expect(fs.existsSync(destination)).toBe(false); + expect(fs.readdirSync(untouched)).toEqual([]); +}); + +test.skipIf(process.platform === 'win32')( + 'a remote recording refuses a destination whose directory was swapped while the version downloaded', + async () => { + const root = fs.realpathSync(mkdtempForTestSync('script-ancestry-')); + const stateDir = path.join(root, 'state'); + const work = path.join(root, 'work'); + fs.mkdirSync(work); + const destination = path.join(work, 'journey.ad'); + const baseUrl = await artifactServer({ v1: { body: 'open Demo\n' } }); + const realOpen = fs.promises.open.bind(fs.promises); + // The replacement is a private directory, so only the parent's identity can catch it. The swap + // happens once the staged file is open: after the parent's identity was captured. + const spyOpen = vi.spyOn(fs.promises, 'open').mockImplementation(async (file, ...rest) => { + const handle = await realOpen(file as never, ...(rest as unknown as never[])); + fs.rmSync(work, { recursive: true, force: true }); + fs.mkdirSync(work); + return handle; + }); + + let response: DaemonResponse; + try { + response = (await open(baseUrl, stateDir, destination)).response; + } finally { + spyOpen.mockRestore(); + } + + expect(response).toEqual( + expect.objectContaining({ + ok: true, + data: expect.objectContaining({ + scriptDeliveryFailure: expect.objectContaining({ cause: 'script_ancestry_replaced' }), + }), + }), + ); + expect(fs.readdirSync(work)).toEqual([]); + }, +); + test('retiring a record removes the staging a crashed download left behind', async () => { const { stateDir, destination } = journey(); const baseUrl = await artifactServer({ v1: { body: 'open Demo\n' } }); diff --git a/packages/remote/src/session-script-destination.ts b/packages/remote/src/session-script-destination.ts index a91c1bca70..bd416b5247 100644 --- a/packages/remote/src/session-script-destination.ts +++ b/packages/remote/src/session-script-destination.ts @@ -8,9 +8,16 @@ import type { ScriptDeliveryFailure, } from '@agent-device/kernel/contracts'; import { readResponseWarnings } from '@agent-device/kernel/success-text'; +import { AppError } from '@agent-device/kernel/errors'; import { assertScriptArtifactsCapability } from '@agent-device/daemon-contracts/daemon-resolution'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; -import { acquireProcessLock, publishFileSync, withProcessLock } from '@agent-device/host-kit/file'; +import { + acquireProcessLock, + assertPrivateScriptDestination, + publishDirectoryIdentity, + publishFileSync, + withProcessLock, +} from '@agent-device/host-kit/file'; import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; import type { DaemonArtifactEndpoint, downloadRemoteArtifact } from './daemon-artifacts.ts'; @@ -191,13 +198,18 @@ async function publishScriptVersion( return { published: undefined }; } if ((revision as number) <= record.revision) return { published: record.destination }; - const directory = path.dirname(record.destination); const pending = { named: false }; let staging: string | undefined; try { - await fs.promises.mkdir(directory, { recursive: true }); - staging = await withRecordLock(file, async () => allocateStaging(file, directory)); - if (!staging) return { published: undefined }; + // Asked before anything is created, so a destination another local user can steer leaves no + // directory behind (#4565). + assertPrivateScriptDestination(record.destination); + await fs.promises.mkdir(path.dirname(record.destination), { recursive: true }); + const allocated = await withRecordLock(file, async () => + allocateStaging(file, record.destination), + ); + staging = allocated?.staging; + if (!staging || !allocated) return { published: undefined }; const staged = path.join(staging, 'script.ad'); await context.download({ ...endpoint, @@ -206,7 +218,13 @@ async function publishScriptVersion( requestScope: req.meta, privateFile: { maxBytes: MAX_SCRIPT_BYTES }, }); - const version = { revision: revision as number, staging, staged, pending }; + const version = { + revision: revision as number, + staging, + staged, + parentIdentity: allocated.parentIdentity, + pending, + }; return { published: await withRecordLock(file, async () => publishStaged(file, version)) }; } catch (error) { const closing = req.command === 'close'; @@ -223,18 +241,29 @@ async function publishScriptVersion( } } -/** Creates a staging directory and lists it in the record before any script bytes reach it. */ -function allocateStaging(file: string, directory: string): string | undefined { +/** + * Creates a staging directory beside the destination and lists it in the record before any script + * bytes reach it, and reports the destination directory's identity so the publish can confirm it is + * still the same one. Refuses an ancestor another local user can write (#4565), so nothing is + * downloaded into a directory they control. + */ +function allocateStaging( + file: string, + destination: string, +): { staging: string; parentIdentity: string | undefined } | undefined { const record = readRecord(file); if (!record) return undefined; + assertPrivateScriptDestination(destination); + const directory = path.dirname(destination); const staging = fs.mkdtempSync(path.join(directory, '.agent-device-script-')); + const parentIdentity = publishDirectoryIdentity(directory); try { writeRecord(file, { ...record, staging: [...(record.staging ?? []), staging] }); } catch (error) { fs.rmSync(staging, { recursive: true, force: true }); throw error; } - return staging; + return { staging, parentIdentity }; } /** @@ -275,10 +304,11 @@ function publishStaged( revision: number; staging: string; staged: string; + parentIdentity: string | undefined; pending: { named: boolean }; }>, ): string | undefined { - const { revision, staging, staged, pending } = version; + const { revision, staging, staged, parentIdentity, pending } = version; const record = readRecord(file); if (!record) return undefined; let current = settlePublishing(record); @@ -289,6 +319,9 @@ function publishStaged( current = withoutStaging(current, record.publishing.staging); } if (revision <= current.revision) return current.destination; + // Re-asked here, under the record lock and right before the entry is created: whoever could write + // an ancestor while the version was downloaded cannot move it now (#4565). + assertPrivateScriptDestination(current.destination, parentIdentity); const publishing = { revision, file: fileIdentity(staged) ?? 'missing', staging }; // A second name keeps the inode on disk after the rename while the record may name it. fs.linkSync(staged, `${staged}.anchor`); @@ -329,6 +362,19 @@ function scriptDeliveryFailure( ): ScriptDeliveryFailure { // Only the exclusive link of the first version can find an existing entry. const exists = (error as NodeJS.ErrnoException | undefined)?.code === 'EEXIST'; + const refusal = scriptAncestryRefusal(error); + if (refusal) { + return { + reason: 'script_delivery_failed', + cause: refusal, + publicationId, + message: + error instanceof AppError + ? error.message + : `The remote script could not be saved to ${destination}.`, + hint: error instanceof AppError ? (error.details?.hint ?? '') : '', + }; + } const recovery = closing ? 'The session is closed, so no later version follows.' : 'The next recorded action or close delivers the full recording again.'; @@ -349,6 +395,18 @@ function scriptDeliveryFailure( }; } +/** + * The typed reason a destination-ancestry refusal reported (#4565), so a caller can tell an unsafe + * destination from a download that failed. Anything else is `undefined`. + */ +function scriptAncestryRefusal(error: unknown): string | undefined { + if (!(error instanceof AppError)) return undefined; + const reason = error.details?.reason; + return reason === 'script_ancestor_untrusted' || reason === 'script_ancestry_replaced' + ? reason + : undefined; +} + function recordPath( stateDir: string, baseUrl: string, diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 0eba21ea2f..38d5f93531 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -213,7 +213,7 @@ "packages/daemon-contracts/src/daemon-resolution.ts#readDaemonCapabilities": "sha256:e410d36be74d307f7e5d8ddae63af5aae77f8eef77951ce9eeb7724f2fefae88", "packages/remote/src/daemon-artifacts.ts#downloadResponseArtifacts": "sha256:42d78f01311e3e0c5f9099ef72e3c6258241e66204747aa176a55cd5191a2145", "packages/remote/src/session-script-destination.ts#SessionScriptDelivery": "sha256:741fafbb8e2b43e2e967b2f4206f1d60017a636f63e3cde68b6258fd4efefa18", - "packages/remote/src/session-script-destination.ts#publishScriptVersion": "sha256:9d6ceb538019c0ce30813fcf98d2484c5abc2d8fd7a3dfdd4141cf6430f086ff", + "packages/remote/src/session-script-destination.ts#publishScriptVersion": "sha256:3406b96e254e85cd3e3f23b8b644f40d8d7268b2066696ff21516dabfa8ca14c", "packages/remote/src/session-script-destination.ts#PublishOutcome": "sha256:a4ae6fc3298d3c560719591372edddbfa83ce749f4cf3f3e2ed1d8369313bd2d", "packages/remote/src/session-script-destination.ts#sendRemoteScriptOpen": "sha256:10ab07a6f276c7b03996c6b46fa218e03e7b1d21e2c95df5515dfb88095416b6", "packages/remote/src/session-script-destination.ts#RemoteEndpoint": "sha256:9c48e8e0ee14a25b85ebd930243fd263134836b35ecda55fb927919911263c15" From 13535e1aff27e42fe7256796ffcd931efc608d65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 16 Nov 2026 10:30:58 +0100 Subject: [PATCH 04/10] docs: say which directories a script save accepts 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 --- docs/adr/0016-active-session-script-publication.md | 7 ++++++- website/docs/docs/remote-proxy.md | 2 ++ website/docs/docs/replay-e2e.md | 3 +++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/docs/adr/0016-active-session-script-publication.md b/docs/adr/0016-active-session-script-publication.md index a7f4c2937b..531066f407 100644 --- a/docs/adr/0016-active-session-script-publication.md +++ b/docs/adr/0016-active-session-script-publication.md @@ -207,7 +207,12 @@ It adds no state name, command, or flag: A batch whose steps would close an armed remote recording is refused before any step runs (`remote_script_batch_close_unsupported`), because a batch delivers no script versions from its steps. - The daemon reports the `script-artifacts` capability in `/health`, through a proxy in its upstream health; the client refuses a remote `--save-script` before dispatch without it. -The destination keeps local `--save-script` semantics: the client creates a missing parent directory and checks no ancestor ownership, so another local user who can write an ancestor directory can redirect the file, locally and remotely alike (#4565). +The destination keeps local `--save-script` semantics (#4565): the client creates a missing parent directory, and neither the daemon nor the client publishes through a directory another local user can write. +Before staging, and again immediately before the link or rename, the publisher walks each component of the destination with `lstat` and refuses it under a typed reason when its mode is writable by group or other without the sticky bit, unless that group is the current user's own private group: Ubuntu and Debian set up every home directory that way, often group-writable, and those keep working. +A symbolic link whose own directory others can create entries in is refused whatever it points at, because that link may be one they planted; the sticky bit does not excuse it, because it guards entries that already exist. +The publisher also captures the destination directory's identity before it stages the file and compares it before publishing, so a parent swapped out by name during the download or the temp write never receives the script. +Node exposes no `openat` or `renameat`, so publishing relative to a verified directory handle is not available without native code; the refusal plus the identity re-check is the non-native rule that closes the same window. +A local write fails with `script_ancestor_untrusted` or `script_ancestry_replaced`; a remote version keeps its command's success and carries that reason as the `scriptDeliveryFailure` cause. Known limitation (#4564): the RPC response is the contract for `scriptDeliveryFailure`; the SDK, CLI, and MCP results do not carry it yet, the SDK close drops its warnings, and a batch delivers no step script versions. Rejected: a remote `session save-script` download, because it added a second publication path and a retry protocol. Rejected: delivery only at close, because a session that an external owner closes would lose its recording. diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 2cfffa7015..6cafe0224d 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -108,6 +108,8 @@ Outside a macOS app lease, a fresh `open --save-script=` records the sessi your machine. Each response that records an action returns a `session-script` artifact, and the client replaces the file with it. `close` returns the final script. The client writes only to the path that its own `open` named. If the file already exists, `open` fails unless you pass `--force`. +Every directory on the way to that path must be one that only you and root can write; see +[Record a replay script](replay-e2e.md#record-a-replay-script). The daemon must report the `script-artifacts` capability in its `/health` response; through a proxy, the upstream daemon's health response must report it. Otherwise `open --save-script` is refused before the session starts. diff --git a/website/docs/docs/replay-e2e.md b/website/docs/docs/replay-e2e.md index 5a96d58ea4..fab424778f 100644 --- a/website/docs/docs/replay-e2e.md +++ b/website/docs/docs/replay-e2e.md @@ -71,6 +71,9 @@ agent-device open Settings --platform ios --session e2e --save-script ./workflow ``` - Missing parent directories are created. +- Every directory on the way to the script must be one that only you and root can write. Another local user who can write such a directory can replace a directory on the path, or leave a symbolic link there, before the script is moved into place. The script then lands where they choose. +- A shared team directory is safe once it has the sticky bit (`chmod +t`): it stops anyone but an entry's owner or root from replacing that entry. A group-writable home directory of your own private group, the shape Ubuntu and Debian create, is accepted. A symbolic link inside a directory others can write is refused, whatever it points at. +- A refused destination names the directory at fault. A local `close` fails and keeps its bytes. A remote recording keeps its success and reports `script_ancestor_untrusted` as the `scriptDeliveryFailure` cause, and the next recorded action or `close` repeats the refusal. Choosing a directory nobody else can write, or adding the sticky bit, clears it. - With a local daemon, the script is written on the daemon host when the session closes. - With a remote daemon, outside a macOS app lease, the path is on your machine. The file appears when `open` returns, and each later recorded action in the session replaces it with the recording so far. `close` writes the final script there. A session that another process closes keeps the version from the last action. - A bare remote `open --save-script` writes `recording-.ad` in your working directory. From 2315e8383e56f53044e6f2a61dbb6db49f74e1de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 16 Nov 2026 10:50:00 +0100 Subject: [PATCH 05/10] test: carry the script publish through the wire and ownership gates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .../__tests__/atomic-publish-ownership.test.ts | 12 +++++++++++- test/wire-compat/closure-policy.ts | 2 ++ test/wire-compat/ledger.json | 1 + 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/packages/daemon/src/server/__tests__/atomic-publish-ownership.test.ts b/packages/daemon/src/server/__tests__/atomic-publish-ownership.test.ts index 5629f2cc37..17ff81c0fb 100644 --- a/packages/daemon/src/server/__tests__/atomic-publish-ownership.test.ts +++ b/packages/daemon/src/server/__tests__/atomic-publish-ownership.test.ts @@ -23,11 +23,21 @@ const PROCESS_LOCK_SOURCE = new URL( test('simple same-directory publishers use the shared atomic publish owner', () => { for (const sourcePath of SIMPLE_PUBLISHERS) { const source = fs.readFileSync(sourcePath, 'utf8'); - assert.match(source, /publishFileSync/); + assert.match(source, /publish(?:Script)?FileSync/); assert.doesNotMatch(source, /fs\.(?:writeFileSync|renameSync)\s*\(/); } }); +// A session script is published through the ancestry-owning entry point, not the plain one: the plain +// one writes to a destination another local user could have steered (#4565). +test('the session script publisher uses the destination-ancestry owner', () => { + const source = fs.readFileSync( + new URL('../../core/session-script-writer.ts', import.meta.url), + 'utf8', + ); + assert.match(source, /publishScriptFileSync/); +}); + // The process lock publishes a file and reclaims a directory, which are two different // claims of ownership: only the first belongs to the publication owners above. test('the process lock publishes its owner record without publishing files by hand', () => { diff --git a/test/wire-compat/closure-policy.ts b/test/wire-compat/closure-policy.ts index 84a93c1a70..5e1533e455 100644 --- a/test/wire-compat/closure-policy.ts +++ b/test/wire-compat/closure-policy.ts @@ -49,6 +49,8 @@ export const WIRE_CLOSURE_WAIVERS: Readonly> = { 'Server-side narrowing of the listed kernel DaemonRequest; the declaration that fixes the shape is packages/kernel/src/contracts.ts#DaemonRequest.', 'packages/contracts/src/daemon-wire-request.ts#DaemonWireRequest': 'Client-side narrowing of the listed kernel DaemonRequest (token and session required, flags typed as CommandFlags); the declaration that fixes the shape is packages/kernel/src/contracts.ts#DaemonRequest.', + 'packages/remote/src/session-script-destination.ts#PublishOutcome': + "The CLIENT'S OWN result of one publish attempt: the published path, or a failure plus the local error object behind it. Only the failure half is ever serialized, into `data.scriptDeliveryFailure`, and that payload is the listed packages/kernel/src/contracts.ts#ScriptDeliveryFailure; the `error` member is a local unknown thrown value that never reaches the peer.", 'packages/remote/src/upload-stream.ts#UploadStreamProgressOptions': 'Byte-progress callback options for local upload rendering. The bytes counted are digested through the request/response declarations; these options never cross the wire.', 'packages/remote/src/upload-progress.ts#UploadProgressSink': diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 38d5f93531..cece9d2bd2 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -33,6 +33,7 @@ "packages/kernel/src/contracts.ts#RESPONSE_LEVELS": "sha256:cef29c3b56c299e35a7fee8058b90dc4a6f65a46a420e4f11f77c8ca7d0359c8", "packages/kernel/src/contracts.ts#ResponseCost": "sha256:2a44de54e8b5c886b36da1500e22d634ec7e12961d2c93b689d2b1aa8c15f186", "packages/kernel/src/contracts.ts#ResponseLevel": "sha256:c7329d28e745b5e69b86aa1a686befa314b98248afbe5e0e2d7d395f0d777f9b", + "packages/kernel/src/contracts.ts#ScriptDeliveryFailure": "sha256:186881f8b2e6a0227a6d1a2c802d8f7356fee39d4137800a0c9fa65401aa2765", "packages/kernel/src/contracts.ts#SESSION_ISOLATION_MODES": "sha256:3d4b3048e22bb0ceccc98cf8fd93a87a1a1e2dad96fa03cffff6d0ecedb58689", "packages/kernel/src/contracts.ts#SessionIsolationMode": "sha256:beea941fe57b000902da28af15a27aa18d0c957408209e3ec372fcf7f605fa7c", "packages/kernel/src/contracts.ts#SESSION_RUNTIME_PLATFORMS": "sha256:6164fc8ca226b5beb3ba52a8dddd3c11633a8accec58b9f8972c44c8339a1bf7", From 48a519b2078f63a2de700a6ab598035cbfb5b329 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 16 Nov 2026 11:46:17 +0100 Subject: [PATCH 06/10] fix(host-kit): judge a script destination by ownership and its real path 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 --- .../0016-active-session-script-publication.md | 12 +- .../session-script-writer-ancestry.test.ts | 166 ++++++-- .../session-store-teardown-script.test.ts | 5 +- .../daemon/src/core/session-script-writer.ts | 10 +- packages/host-kit/src/file.ts | 8 + .../src/internal/atomic-file-ancestry.test.ts | 375 ++++++++++++++---- packages/host-kit/src/internal/atomic-file.ts | 347 +++++++++++----- .../daemon-artifacts-script-download.test.ts | 2 +- website/docs/docs/remote-proxy.md | 2 +- website/docs/docs/replay-e2e.md | 9 +- 10 files changed, 699 insertions(+), 237 deletions(-) diff --git a/docs/adr/0016-active-session-script-publication.md b/docs/adr/0016-active-session-script-publication.md index 531066f407..65f8f822e8 100644 --- a/docs/adr/0016-active-session-script-publication.md +++ b/docs/adr/0016-active-session-script-publication.md @@ -207,11 +207,13 @@ It adds no state name, command, or flag: A batch whose steps would close an armed remote recording is refused before any step runs (`remote_script_batch_close_unsupported`), because a batch delivers no script versions from its steps. - The daemon reports the `script-artifacts` capability in `/health`, through a proxy in its upstream health; the client refuses a remote `--save-script` before dispatch without it. -The destination keeps local `--save-script` semantics (#4565): the client creates a missing parent directory, and neither the daemon nor the client publishes through a directory another local user can write. -Before staging, and again immediately before the link or rename, the publisher walks each component of the destination with `lstat` and refuses it under a typed reason when its mode is writable by group or other without the sticky bit, unless that group is the current user's own private group: Ubuntu and Debian set up every home directory that way, often group-writable, and those keep working. -A symbolic link whose own directory others can create entries in is refused whatever it points at, because that link may be one they planted; the sticky bit does not excuse it, because it guards entries that already exist. -The publisher also captures the destination directory's identity before it stages the file and compares it before publishing, so a parent swapped out by name during the download or the temp write never receives the script. -Node exposes no `openat` or `renameat`, so publishing relative to a verified directory handle is not available without native code; the refusal plus the identity re-check is the non-native rule that closes the same window. +The destination keeps local `--save-script` semantics (#4565): the client creates a missing parent directory, and neither the daemon nor the client publishes through a directory another local user can change. The rule closes the window with PERMISSIONS, not with timing. +A destination is accepted only when no other non-root local user can modify any directory on its fully resolved chain. Each directory must be owned by the current user or by root, and its mode must keep its contents closed to others. Once that holds, nobody can swap a component out or plant one, so the path that was judged is the path the publish reaches; nothing depends on when a directory was judged. +The chain is resolved first, so a symbolic link's target is judged under the same rule. A link is refused when another user could have placed it or could replace it: in a directory where others may add entries, only a link owned by the current user or root and held by the sticky bit is trusted. Root-owned system aliases (macOS `/tmp` to `/private/tmp`, `/var` to `/private/var`) keep working. +The sticky bit excuses a directory the chain passes THROUGH, because it stops anyone but an entry's owner or root from replacing that entry; it never excuses creating the destination inside that directory, because anyone could create that name first. A group-writable directory the current user owns is accepted when its group is that user's own private group, which is the shape Ubuntu and Debian give home directories; this is the one place the rule reads `/etc/group` and `/etc/passwd`, and it fails closed when either file is unreadable. Residual limitation: a name service (LDAP or an NSS module) can add a member holding that primary GID without it appearing in `/etc/passwd`, so such a host can be refused a group-writable directory it appears to own. The fallback is a directory only the user can write. +The script file is created 0600, locally and remotely alike, so a recording is not world-readable in a directory that is merely shared. +The publisher compares the destination directory's captured `dev:ino` before publishing. The ownership rule above already excludes anyone able to swap that directory, so the comparison is defense in depth against a host whose ownership or modes moved during the download, not the check that closes the window. +Node exposes no `openat` or `renameat`, so publishing relative to a verified directory handle is not available without native code; the permissions rule is what substitutes for it. A local write fails with `script_ancestor_untrusted` or `script_ancestry_replaced`; a remote version keeps its command's success and carries that reason as the `scriptDeliveryFailure` cause. Known limitation (#4564): the RPC response is the contract for `scriptDeliveryFailure`; the SDK, CLI, and MCP results do not carry it yet, the SDK close drops its warnings, and a batch delivers no step script versions. Rejected: a remote `session save-script` download, because it added a second publication path and a retry protocol. diff --git a/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts b/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts index 80198713c3..b8121b051a 100644 --- a/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts +++ b/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts @@ -1,4 +1,4 @@ -import { expect, test } from 'vitest'; +import { afterEach, expect, test, vi } from 'vitest'; import fs from 'node:fs'; // oxlint-disable-next-line no-restricted-imports -- the private-group fixture is named after os.userInfo()'s user, not a scratch path import os from 'node:os'; @@ -10,25 +10,44 @@ import { makeAuthoringSession } from '../../__tests__/support/session-factories. const hostCwd = createLiveTestHostEnvironment().cwd; const skipOnWindows = process.platform === 'win32' ? test.skip : test; -/** The private-group exception is decided by this host's group database. */ -function groupDatabaseMatchesHost(gid: number): boolean { - try { - const name = os.userInfo().username; - const groups = fs.readFileSync('/etc/group', 'utf8').split('\n'); - const passwd = fs.readFileSync('/etc/passwd', 'utf8').split('\n'); - const line = groups.find((entry) => entry.split(':')[0] === name); - if (!line || Number(line.split(':')[2]) !== gid) return false; - const extra = (line.split(':')[3] ?? '').split(',').filter(Boolean); - return ( - extra.every((member) => member === name || member === 'root') && - passwd.every((entry) => { - const [user, , , primary] = entry.split(':'); - return Number(primary) !== gid || user === name || user === 'root'; - }) - ); - } catch { - return false; - } +const realReadFileSync = fs.readFileSync; +const currentUser = os.userInfo().username; + +/** This process's ids. Windows has neither, and every test that uses them is skipped there. */ +const currentUid = process.getuid?.() ?? -1; +const currentGid = process.getgid?.() ?? -1; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +/** + * Serves `groups` and `passwd` for the two group files and the real host for everything else, so the + * private-group decision is the fixture's and this file's assertions run on every POSIX host instead of + * only on one whose `/etc/group` happens to agree. + */ +function serveGroupDatabase(groups: readonly string[], passwd: readonly string[]): void { + vi.spyOn(fs, 'readFileSync').mockImplementation(((file: unknown, options?: unknown) => { + if (file === '/etc/group') return `${groups.join('\n')}\n`; + if (file === '/etc/passwd') return `${passwd.join('\n')}\n`; + return realReadFileSync(file as never, options as never) as never; + }) as typeof fs.readFileSync); +} + +/** This host's user owning `currentGid` alone, plus a team group that holds someone else. */ +function privateGroupDatabase(): void { + serveGroupDatabase( + ['root:x:0:root', `${currentUser}:x:${currentGid}:`, 'team:x:4321:ada'], + ['root:x:0:0', `${currentUser}:x:${currentUid}:${currentGid}:`], + ); +} + +/** The same ids, with this host's group named after somebody else, so it is not private. */ +function foreignGroupNameDatabase(): void { + serveGroupDatabase( + ['root:x:0:root', `${currentUser}:x:${currentGid + 1}:`, 'team:x:4321:ada'], + ['root:x:0:0', `${currentUser}:x:${currentUid}:${currentGid}:`], + ); } function action(command: string): { @@ -61,6 +80,18 @@ function sharedDirectory(directory: string, mode: number): string { return directory; } +/** A scratch directory in this host's own primary group, at `mode`. */ +function homeDirectory(directory: string, mode: number): string { + fs.mkdirSync(directory); + fs.chownSync(directory, currentUid, currentGid); + fs.chmodSync(directory, mode); + return directory; +} + +function writerFor(directory: string): SessionScriptWriter { + return new SessionScriptWriter(path.join(directory, 'sessions'), hostCwd); +} + function refusal(result: ReturnType): Record { expect(result.written).toBe(false); if (result.written || !result.error) throw new Error('expected a refused write'); @@ -68,21 +99,31 @@ function refusal(result: ReturnType): Record { - const destination = path.join(root(), 'workflows', 'journey.ad'); - const writer = new SessionScriptWriter(path.join(root(), 'sessions'), hostCwd); + const directory = root(); + const destination = path.join(directory, 'workflows', 'journey.ad'); - const result = writer.write(recordingTo(destination)); + const result = writerFor(directory).write(recordingTo(destination)); expect(result.written).toBe(true); expect(fs.readFileSync(destination, 'utf8')).toContain('open'); }); +skipOnWindows('a recording saves a script no other local user can read', () => { + const directory = root(); + const destination = path.join(directory, 'workflows', 'journey.ad'); + + const result = writerFor(directory).write(recordingTo(destination)); + + expect(result.written).toBe(true); + expect(fs.lstatSync(destination).mode & 0o777).toBe(0o600); +}); + skipOnWindows('a recording refuses a destination under a world-writable directory', () => { - const shared = sharedDirectory(path.join(root(), 'shared'), 0o777); + const directory = root(); + const shared = sharedDirectory(path.join(directory, 'shared'), 0o777); const destination = path.join(shared, 'journey.ad'); - const writer = new SessionScriptWriter(path.join(root(), 'sessions'), hostCwd); - const details = refusal(writer.write(recordingTo(destination))); + const details = refusal(writerFor(directory).write(recordingTo(destination))); expect(details).toMatchObject({ reason: 'script_ancestor_untrusted', @@ -91,21 +132,58 @@ skipOnWindows('a recording refuses a destination under a world-writable director expect(fs.existsSync(destination)).toBe(false); }); +skipOnWindows('a recording refuses a destination inside a directory another user owns', () => { + const directory = root(); + const foreign = path.join(directory, 'foreign'); + fs.mkdirSync(foreign); + fs.chmodSync(foreign, 0o755); + const destination = path.join(foreign, 'journey.ad'); + // The directory is this test user's own, so the rule is run as somebody else: a real second local + // user looking at a directory they cannot own but can read. + vi.spyOn(process, 'getuid').mockReturnValue(currentUid === 65534 ? 65535 : 65534); + + const details = refusal(writerFor(directory).write(recordingTo(destination))); + + expect(details).toMatchObject({ + reason: 'script_ancestor_untrusted', + exposure: 'foreign_owned', + ancestor: foreign, + }); + expect(fs.existsSync(destination)).toBe(false); +}); + skipOnWindows('a recording refuses an ancestor swapped out for a symbolic link', () => { const directory = root(); - const shared = sharedDirectory(path.join(directory, 'shared'), 0o1777); + const shared = sharedDirectory(path.join(directory, 'shared'), 0o777); const attacker = path.join(directory, 'attacker'); fs.mkdirSync(attacker); fs.symlinkSync(attacker, path.join(shared, 'work')); const destination = path.join(shared, 'work', 'journey.ad'); - const writer = new SessionScriptWriter(path.join(directory, 'sessions'), hostCwd); - const details = refusal(writer.write(recordingTo(destination))); + const details = refusal(writerFor(directory).write(recordingTo(destination))); expect(details).toMatchObject({ reason: 'script_ancestor_untrusted', exposure: 'planted_link' }); expect(fs.readdirSync(attacker)).toEqual([]); }); +skipOnWindows('a recording refuses an ancestor whose target is a writable directory', () => { + const directory = root(); + const shared = sharedDirectory(path.join(directory, 'shared'), 0o777); + const privateWork = path.join(shared, 'private'); + fs.mkdirSync(privateWork); + fs.symlinkSync(privateWork, path.join(directory, 'link')); + const destination = path.join(directory, 'link', 'journey.ad'); + + const details = refusal(writerFor(directory).write(recordingTo(destination))); + + expect(details).toMatchObject({ + reason: 'script_ancestor_untrusted', + exposure: 'world_writable', + ancestor: shared, + }); + expect(fs.readdirSync(privateWork)).toEqual([]); +}); + skipOnWindows('a recording refuses an ancestor swapped out for a writable directory', () => { const directory = root(); const work = path.join(directory, 'work'); @@ -115,9 +193,8 @@ skipOnWindows('a recording refuses an ancestor swapped out for a writable direct fs.rmSync(work, { recursive: true }); fs.mkdirSync(work); fs.chmodSync(work, 0o777); - const writer = new SessionScriptWriter(path.join(directory, 'sessions'), hostCwd); - const details = refusal(writer.write(recordingTo(destination))); + const details = refusal(writerFor(directory).write(recordingTo(destination))); expect(details).toMatchObject({ reason: 'script_ancestor_untrusted', @@ -127,14 +204,27 @@ skipOnWindows('a recording refuses an ancestor swapped out for a writable direct }); skipOnWindows('a recording still saves to a group-writable private-group home', () => { - const gid = process.getgid?.(); - if (gid === undefined || !groupDatabaseMatchesHost(gid)) return; - const home = path.join(root(), 'home'); - fs.mkdirSync(home); - fs.chmodSync(home, 0o775); - const writer = new SessionScriptWriter(path.join(root(), 'sessions'), hostCwd); + privateGroupDatabase(); + const directory = root(); + const home = homeDirectory(path.join(directory, 'home'), 0o775); + const destination = path.join(home, 'journey.ad'); - const result = writer.write(recordingTo(path.join(home, 'journey.ad'))); + const result = writerFor(directory).write(recordingTo(destination)); expect(result.written).toBe(true); + expect(fs.readFileSync(destination, 'utf8')).toContain('open'); +}); + +skipOnWindows("a recording refuses the same home once the group is not this user's own", () => { + foreignGroupNameDatabase(); + const directory = root(); + const home = homeDirectory(path.join(directory, 'home'), 0o775); + + const details = refusal(writerFor(directory).write(recordingTo(path.join(home, 'journey.ad')))); + + expect(details).toMatchObject({ + reason: 'script_ancestor_untrusted', + exposure: 'shared_group_writable', + ancestor: home, + }); }); diff --git a/packages/daemon/src/core/__tests__/session-store-teardown-script.test.ts b/packages/daemon/src/core/__tests__/session-store-teardown-script.test.ts index 7bff2bfb17..b7a4a0ece5 100644 --- a/packages/daemon/src/core/__tests__/session-store-teardown-script.test.ts +++ b/packages/daemon/src/core/__tests__/session-store-teardown-script.test.ts @@ -81,7 +81,8 @@ test.skipIf(process.platform === 'win32')( expect(fs.statSync(result.path).mode & 0o777).toBe(0o600); } expect(localWrite).toMatchObject({ written: true, path: local }); - const umask = process.umask(); - expect(fs.statSync(local).mode & 0o777).toBe(0o666 & ~umask); + // A recording is a transcript of what someone did on this machine, so the caller's own file is + // private too, whatever the umask would have allowed (#4565). + expect(fs.statSync(local).mode & 0o777).toBe(0o600); }, ); diff --git a/packages/daemon/src/core/session-script-writer.ts b/packages/daemon/src/core/session-script-writer.ts index c4abbd5618..9b60e608aa 100644 --- a/packages/daemon/src/core/session-script-writer.ts +++ b/packages/daemon/src/core/session-script-writer.ts @@ -144,7 +144,6 @@ export class SessionScriptWriter { script: prepared.script, force: options?.force, parentIdentity: publishDirectoryIdentity(scriptDir), - ...(remote ? { mode: 0o600 } : {}), }); // COMMITTED: idempotent guard above + teardown's abort/tombstone routing. if (repairArmed) { @@ -166,8 +165,9 @@ export class SessionScriptWriter { /** * A remote recording's caller downloads each version once, so every version, the close-time - * script included, gets a fresh private (0600) file in a private (0700) directory that only the - * daemon user can read. + * script included, gets a fresh file of its own in a private (0700) directory that only the daemon + * user can enter. The file itself is private (0600) like every other published script, which + * `publishScriptFileSync` decides. */ private remoteScriptPath(): string { const directory = path.join(this.sessionsDir, 'remote-scripts'); @@ -302,17 +302,15 @@ function publishHealedScriptAtomically(params: { scriptPath: string; script: string; force?: boolean; - mode?: number; parentIdentity?: string; }): void { - const { scriptPath, script, force, mode, parentIdentity } = params; + const { scriptPath, script, force, parentIdentity } = params; try { publishScriptFileSync({ destination: scriptPath, contents: script, publish: force ? 'replace' : 'link-exclusive', ...(parentIdentity === undefined ? {} : { parentIdentity }), - ...(mode === undefined ? {} : { mode }), }); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; diff --git a/packages/host-kit/src/file.ts b/packages/host-kit/src/file.ts index 8779eccfb5..31f9b39988 100644 --- a/packages/host-kit/src/file.ts +++ b/packages/host-kit/src/file.ts @@ -1,11 +1,19 @@ export { assertPrivateScriptDestination, isAtomicPublishTemporaryPath, + othersCreateEntriesIn, + privateGroupId, publishDirectoryIdentity, publishDurableFileSync, publishFileSync, publishScriptFileSync, + untrustedAncestryExposure, + untrustedLinkExposure, + type DirectoryAuthority, type DurableFilePublishMode, + type LinkAuthority, + type ScriptAncestryExposure, + type ScriptDestinationTrust, } from './internal/atomic-file.ts'; export { lstatIfPresent, diff --git a/packages/host-kit/src/internal/atomic-file-ancestry.test.ts b/packages/host-kit/src/internal/atomic-file-ancestry.test.ts index 9445f855dc..4d624b8a35 100644 --- a/packages/host-kit/src/internal/atomic-file-ancestry.test.ts +++ b/packages/host-kit/src/internal/atomic-file-ancestry.test.ts @@ -7,15 +7,22 @@ import { AppError } from '@agent-device/kernel/errors'; import { mkdtempForTestSync } from './tmp-dir.fixtures.ts'; import { assertPrivateScriptDestination, - privateGroupIds, + othersCreateEntriesIn, + privateGroupId, publishDirectoryIdentity, publishScriptFileSync, + untrustedAncestryExposure, + untrustedLinkExposure, + type DirectoryAuthority, } from './atomic-file.ts'; const skipOnWindows = process.platform === 'win32' ? test.skip : test; /** The group database a test stands in for `/etc/group` and `/etc/passwd`. */ -type Database = Readonly<{ groups: readonly string[]; passwd: readonly string[] }>; +type Database = Readonly<{ + groups: readonly string[] | undefined; + passwd: readonly string[] | undefined; +}>; const realReadFileSync = fs.readFileSync; const currentUser = os.userInfo().username; @@ -34,8 +41,14 @@ afterEach(() => { */ function serveGroupDatabase(database: Database): void { vi.spyOn(fs, 'readFileSync').mockImplementation(((file: unknown, options?: unknown) => { - if (file === '/etc/group') return `${database.groups.join('\n')}\n`; - if (file === '/etc/passwd') return `${database.passwd.join('\n')}\n`; + if (file === '/etc/group') { + if (!database.groups) throw new Error('simulated unreadable group file'); + return `${database.groups.join('\n')}\n`; + } + if (file === '/etc/passwd') { + if (!database.passwd) throw new Error('simulated unreadable passwd file'); + return `${database.passwd.join('\n')}\n`; + } return realReadFileSync(file as never, options as never) as never; }) as typeof fs.readFileSync); } @@ -48,11 +61,19 @@ function hostDatabase(privateGid: number, sharedGid: number): Database { }; } +/** The database of a host whose group files cannot be read at all. */ +function unreadableDatabases(): Database { + return { groups: undefined, passwd: undefined }; +} + function root(): string { return fs.realpathSync(mkdtempForTestSync('host-kit-ancestry-')); } -/** A directory carrying `mode` and `gid`, so the rule reads the group the test chose. */ +/** + * A directory carrying `mode` and `gid`, so the rule reads the group the test chose. The group is set + * explicitly because a scratch directory inherits one from its parent, not necessarily this user's. + */ function directoryWith(directory: string, mode: number, gid = currentGid): string { fs.mkdirSync(directory); fs.chownSync(directory, currentUid, gid); @@ -60,6 +81,15 @@ function directoryWith(directory: string, mode: number, gid = currentGid): strin return directory; } +/** + * Runs the rule as a different local user, so the ownership checks are exercised against real + * directories owned by this test's actual user. Nothing else about the process moves: the modes stay + * what they are on disk. + */ +function asAnotherLocalUser(): void { + vi.spyOn(process, 'getuid').mockReturnValue(currentUid === 65534 ? 65535 : 65534); +} + function publish(destination: string, parentIdentity?: string): void { publishScriptFileSync({ destination, @@ -87,7 +117,11 @@ function expectRefusal(run: () => void, reason: string, exposure: string, ancest expect(details).toMatchObject({ reason, exposure, ancestor }); } -// --- a chain another local user can act inside is refused --- +function modeOf(pathname: string): number { + return fs.lstatSync(pathname).mode & 0o777; +} + +// --- a directory another user owns, or that others can write, is refused --- skipOnWindows('publishes to a chain only this user can write', () => { serveGroupDatabase(hostDatabase(currentGid, 4321)); @@ -99,6 +133,17 @@ skipOnWindows('publishes to a chain only this user can write', () => { expect(fs.readFileSync(path.join(workflows, 'journey.ad'), 'utf8')).toBe('context\n'); }); +skipOnWindows('creates the script so that only this user can read it', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const workflows = path.join(root(), 'workflows'); + fs.mkdirSync(workflows); + const destination = path.join(workflows, 'journey.ad'); + + publish(destination); + + expect(modeOf(destination)).toBe(0o600); +}); + skipOnWindows('refuses a destination under a world-writable directory', () => { serveGroupDatabase(hostDatabase(currentGid, 4321)); const shared = directoryWith(path.join(root(), 'shared'), 0o777); @@ -108,23 +153,21 @@ skipOnWindows('refuses a destination under a world-writable directory', () => { expect(fs.existsSync(destination)).toBe(false); }); -skipOnWindows('refuses a world-writable ancestor above the parent', () => { +skipOnWindows('refuses a destination created inside a directory others can add entries to', () => { serveGroupDatabase(hostDatabase(currentGid, 4321)); - const shared = directoryWith(path.join(root(), 'shared'), 0o777); - const work = path.join(shared, 'work'); - fs.mkdirSync(work); + const shared = directoryWith(path.join(root(), 'shared'), 0o777 | 0o1000); expectUntrusted( - () => assertPrivateScriptDestination(path.join(work, 'journey.ad')), - 'world_writable', + () => assertPrivateScriptDestination(path.join(shared, 'journey.ad')), + 'shared_parent', shared, ); + expect(fs.existsSync(path.join(shared, 'journey.ad'))).toBe(false); }); skipOnWindows('refuses a destination under a group-writable shared directory', () => { - const gid = currentGid; - serveGroupDatabase(hostDatabase(4321, gid)); - const team = directoryWith(path.join(root(), 'team'), 0o775, gid); + serveGroupDatabase(hostDatabase(4321, currentGid)); + const team = directoryWith(path.join(root(), 'team'), 0o775, currentGid); const sub = path.join(team, 'sub'); fs.mkdirSync(sub); @@ -132,6 +175,36 @@ skipOnWindows('refuses a destination under a group-writable shared directory', ( expect(fs.readdirSync(sub)).toEqual([]); }); +// --- ownership decides, not the mode alone --- + +skipOnWindows('refuses a private-mode directory another user owns, whatever the mode', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const work = directoryWith(path.join(root(), 'foreign'), 0o755); + asAnotherLocalUser(); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(work, 'journey.ad')), + 'foreign_owned', + work, + ); +}); + +skipOnWindows('refuses a directory its owner opened up while the file was staged', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const work = path.join(root(), 'work'); + fs.mkdirSync(work); + const destination = path.join(work, 'journey.ad'); + const realWriteFileSync = fs.writeFileSync; + vi.spyOn(fs, 'writeFileSync').mockImplementation(((file: unknown, ...rest: unknown[]) => { + const result = (realWriteFileSync as (...args: unknown[]) => unknown)(file, ...rest); + fs.chmodSync(work, 0o777); + return result; + }) as typeof fs.writeFileSync); + + expectUntrusted(() => publish(destination), 'world_writable', work); + expect(fs.readdirSync(work)).toEqual([]); +}); + // --- the Ubuntu and Debian private-group home keeps working --- skipOnWindows('publishes to a group-writable home directory of a private group', () => { @@ -145,9 +218,15 @@ skipOnWindows('publishes to a group-writable home directory of a private group', }); skipOnWindows("refuses the same mode and group once the group is not the user's own", () => { - const gid = currentGid; - serveGroupDatabase(hostDatabase(4321, gid)); - const home = directoryWith(path.join(root(), 'home'), 0o775, gid); + serveGroupDatabase(hostDatabase(4321, currentGid)); + const home = directoryWith(path.join(root(), 'home'), 0o775, currentGid); + + expectUntrusted(() => publish(path.join(home, 'journey.ad')), 'shared_group_writable', home); +}); + +skipOnWindows('refuses the same mode and group once the group database cannot be read', () => { + serveGroupDatabase(unreadableDatabases()); + const home = directoryWith(path.join(root(), 'home'), 0o775, currentGid); expectUntrusted(() => publish(path.join(home, 'journey.ad')), 'shared_group_writable', home); }); @@ -162,21 +241,24 @@ skipOnWindows('publishes to a setgid group-writable private-group home', () => { expect(fs.existsSync(path.join(home, 'journey.ad'))).toBe(true); }); -// --- a sticky shared directory is safe, except through a link planted in it --- +// --- a link is judged as the link it is, and its target is judged too --- -skipOnWindows('publishes to a destination under a sticky world-writable directory', () => { +skipOnWindows('follows a symbolic link inside a directory only this user can write', () => { serveGroupDatabase(hostDatabase(currentGid, 4321)); - const shared = directoryWith(path.join(root(), 'shared'), 0o1777); + const directory = root(); + const real = path.join(directory, 'real'); + fs.mkdirSync(real); + fs.symlinkSync(real, path.join(directory, 'link')); - publish(path.join(shared, 'journey.ad')); + publish(path.join(directory, 'link', 'journey.ad')); - expect(fs.existsSync(path.join(shared, 'journey.ad'))).toBe(true); + expect(fs.existsSync(path.join(real, 'journey.ad'))).toBe(true); }); -skipOnWindows('refuses a symbolic link planted in a directory others can write', () => { +skipOnWindows('refuses a symbolic link planted in a directory others can add entries to', () => { serveGroupDatabase(hostDatabase(currentGid, 4321)); const directory = root(); - const shared = directoryWith(path.join(directory, 'shared'), 0o1777); + const shared = directoryWith(path.join(directory, 'shared'), 0o777); const attacker = path.join(directory, 'attacker'); fs.mkdirSync(attacker); fs.symlinkSync(attacker, path.join(shared, 'work')); @@ -189,18 +271,88 @@ skipOnWindows('refuses a symbolic link planted in a directory others can write', expect(fs.readdirSync(attacker)).toEqual([]); }); -skipOnWindows('follows a symbolic link inside a directory only this user can write', () => { +skipOnWindows('refuses a symbolic link whose target is a directory others can write', () => { serveGroupDatabase(hostDatabase(currentGid, 4321)); const directory = root(); - const real = path.join(directory, 'real'); - fs.mkdirSync(real); - fs.symlinkSync(real, path.join(directory, 'link')); + const shared = directoryWith(path.join(directory, 'shared'), 0o777); + const privateWork = path.join(shared, 'private'); + fs.mkdirSync(privateWork); + fs.symlinkSync(privateWork, path.join(directory, 'link')); - publish(path.join(directory, 'link', 'journey.ad')); + expectUntrusted( + () => assertPrivateScriptDestination(path.join(directory, 'link', 'journey.ad')), + 'world_writable', + shared, + ); +}); - expect(fs.existsSync(path.join(real, 'journey.ad'))).toBe(true); +skipOnWindows( + 'refuses a symbolic link another local user owns in a sticky shared directory', + () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const shared = directoryWith(path.join(root(), 'shared'), 0o1777); + const attacker = path.join(root(), 'attacker'); + fs.mkdirSync(attacker); + fs.symlinkSync(attacker, path.join(shared, 'work')); + asAnotherLocalUser(); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(shared, 'work', 'journey.ad')), + 'planted_link', + path.join(shared, 'work'), + ); + }, +); + +skipOnWindows('keeps working through a root-owned alias whose target is sticky', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const directory = root(); + const alias = path.join(directory, 'alias'); + const target = path.join(directory, 'target'); + fs.mkdirSync(target); + fs.chmodSync(target, 0o1777); + fs.symlinkSync(target, alias); + const work = path.join(alias, 'work'); + fs.mkdirSync(work); + fs.chmodSync(work, 0o700); + + publish(path.join(work, 'journey.ad')); + + expect(fs.existsSync(path.join(target, 'work', 'journey.ad'))).toBe(true); }); +skipOnWindows('publishes through the host root-owned system alias /tmp', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // macOS reaches `/private/tmp` through `/tmp`, and Linux mounts `/tmp` directly. Either way the + // script lands in a sticky root-owned directory, so the alias must not be what ends the publish. + if (!fs.existsSync('/tmp') || !fs.lstatSync('/tmp').isSymbolicLink()) return; + const work = fs.mkdtempSync('/tmp/agent-device-ancestry-'); + fs.chmodSync(work, 0o700); + const destination = path.join(work, 'journey.ad'); + try { + publish(destination); + expect(fs.readFileSync(destination, 'utf8')).toBe('context\n'); + } finally { + fs.rmSync(work, { recursive: true, force: true }); + } +}); + +skipOnWindows( + 'publishes to a scratch path spelled through a system alias, not resolved away', + () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // The scratch root of `root()` is the resolved path. This one keeps whatever alias the host spells + // its temporary directory with, which is the shape a caller actually passes. + const directory = mkdtempForTestSync('host-kit-ancestry-alias-'); + expect(fs.realpathSync(directory)).not.toBe(directory); + const destination = path.join(directory, 'journey.ad'); + + publish(destination); + + expect(fs.readFileSync(destination, 'utf8')).toBe('context\n'); + }, +); + // --- the destination directory swapped out while the file was staged --- skipOnWindows('refuses a parent replaced by name while the file was staged', () => { @@ -225,7 +377,6 @@ skipOnWindows('re-checks the chain after staging the file, before the entry is c fs.mkdirSync(staged); const destination = path.join(staged, 'journey.ad'); const writeFileSync = fs.writeFileSync; - // The window a second local user races: the file is staged, the entry is not created yet. vi.spyOn(fs, 'writeFileSync').mockImplementation(((file: unknown, ...rest: unknown[]) => { const result = (writeFileSync as (...args: unknown[]) => unknown)(file, ...rest); fs.rmSync(staged, { recursive: true, force: true }); @@ -248,68 +399,146 @@ skipOnWindows('publishes into the parent the captured identity still names', () expect(fs.existsSync(path.join(staged, 'journey.ad'))).toBe(true); }); -// --- privateGroupIds: the one group shape the exception admits --- +// --- untrustedAncestryExposure: what makes one directory unsafe to publish inside --- -const ADA = { uid: 1000, name: 'ada' }; +const OWN = { uid: currentUid, gid: currentGid, mode: 0o755 }; +const TRUST = { uid: currentUid, privateGid: currentGid }; -function database(groups: readonly string[], passwd: readonly string[]) { - return { groups, passwd }; +function directoryOf(overrides: Partial): DirectoryAuthority { + return { ...OWN, ...overrides }; } -test('treats the group named after the user, holding only them, as private', () => { - const ids = privateGroupIds( - database(['ada:x:1000:', 'staff:x:20:root'], ['ada:x:1000:1000:', 'root:x:0:0']), - ADA, +test('refuses a directory another user owns even in private mode', () => { + expect(untrustedAncestryExposure(directoryOf({ uid: 65534 }), TRUST)).toBe('foreign_owned'); +}); + +test('refuses a directory that is world-writable', () => { + expect(untrustedAncestryExposure(directoryOf({ mode: 0o777 }), TRUST)).toBe('world_writable'); +}); + +test('refuses a directory that is group-writable by a group that is not this user', () => { + expect(untrustedAncestryExposure(directoryOf({ gid: 4321, mode: 0o775 }), TRUST)).toBe( + 'shared_group_writable', ); - expect([...ids]).toEqual([1000]); }); -test('treats a group as private when only its primary-group link names the user', () => { - const ids = privateGroupIds( - database(['ada:x:1000:', 'staff:x:20:'], ['root:x:0:0', 'ada:x:1000:1000:']), - ADA, +test('accepts a directory group-writable by this user', () => { + expect(untrustedAncestryExposure(directoryOf({ mode: 0o775 }), TRUST)).toBeUndefined(); +}); + +test('accepts a root-owned directory and a directory this user owns', () => { + expect(untrustedAncestryExposure(directoryOf({ uid: 0 }), TRUST)).toBeUndefined(); + expect(untrustedAncestryExposure(directoryOf({}), TRUST)).toBeUndefined(); +}); + +test('accepts a sticky shared directory for passing through, in any ownership', () => { + expect(untrustedAncestryExposure(directoryOf({ mode: 0o1777 }), TRUST)).toBeUndefined(); + expect(untrustedAncestryExposure(directoryOf({ uid: 65534, mode: 0o1777 }), TRUST)).toBe( + 'foreign_owned', ); - expect([...ids]).toEqual([1000]); }); -test('still treats a group as private with root among its members', () => { - const ids = privateGroupIds( - database(['ada:x:1000:root', 'staff:x:20:'], ['ada:x:1000:1000:', 'root:x:0:0']), - ADA, +// --- untrustedLinkExposure: which link on the path belongs to somebody else --- + +test('accepts a link in a directory only this user or root can add entries to', () => { + const link = { uid: currentUid }; + expect(untrustedLinkExposure(link, directoryOf({ mode: 0o755 }), TRUST)).toBeUndefined(); + expect(untrustedLinkExposure(link, directoryOf({ mode: 0o775 }), TRUST)).toBeUndefined(); +}); + +test('refuses a link in a shared directory unless the sticky bit and its owner hold it in place', () => { + expect(untrustedLinkExposure({ uid: currentUid }, directoryOf({ mode: 0o777 }), TRUST)).toBe( + 'planted_link', ); - expect([...ids]).toEqual([1000]); + expect(untrustedLinkExposure({ uid: 65534 }, directoryOf({ mode: 0o1777 }), TRUST)).toBe( + 'planted_link', + ); +}); + +test('accepts a link this user or root owns in a sticky shared directory', () => { + const sticky = directoryOf({ mode: 0o1777 }); + expect(untrustedLinkExposure({ uid: currentUid }, sticky, TRUST)).toBeUndefined(); + expect(untrustedLinkExposure({ uid: 0 }, sticky, TRUST)).toBeUndefined(); }); -test('treats the group named after the user as shared once another user is a member', () => { - const ids = privateGroupIds( - database( - ['ada:x:1000:grace', 'staff:x:20:'], - ['ada:x:1000:1000:', 'grace:x:1001:1001:', 'root:x:0:0'], +// --- othersCreateEntriesIn: where another local user could claim the entry --- + +test('names a directory others can add entries in, sticky bit or no sticky bit', () => { + expect(othersCreateEntriesIn(directoryOf({ mode: 0o777 }), TRUST)).toBe(true); + expect(othersCreateEntriesIn(directoryOf({ mode: 0o1777 }), TRUST)).toBe(true); + expect(othersCreateEntriesIn(directoryOf({ gid: 4321, mode: 0o775 }), TRUST)).toBe(true); +}); + +test('names no directory whose group is this user', () => { + expect(othersCreateEntriesIn(directoryOf({ mode: 0o775 }), TRUST)).toBe(false); + expect(othersCreateEntriesIn(directoryOf({ mode: 0o1775 }), TRUST)).toBe(false); + expect(othersCreateEntriesIn(directoryOf({ mode: 0o755 }), TRUST)).toBe(false); +}); + +// --- privateGroupId: the one group shape the exception admits --- + +const ADA = { uid: 1000, gid: 1000, name: 'ada' }; + +function database(groups: readonly string[] | undefined, passwd: readonly string[] | undefined) { + return { groups, passwd }; +} + +const PRIVATE = ['ada:x:1000:', 'staff:x:20:root']; +const PRIVATE_PASSWD = ['ada:x:1000:1000:', 'root:x:0:0']; + +test('admits the group named after the user, holding only them, as their primary group', () => { + expect(privateGroupId(database(PRIVATE, PRIVATE_PASSWD), ADA)).toBe(1000); +}); + +test('admits it with root named among its members', () => { + expect( + privateGroupId(database(['ada:x:1000:root'], ['ada:x:1000:1000:', 'root:x:0:0']), ADA), + ).toBeUndefined(); +}); + +test('refuses it once another user is a member', () => { + expect( + privateGroupId( + database(['ada:x:1000:grace'], ['ada:x:1000:1000:', 'grace:x:1001:1001:', 'root:x:0:0']), + ADA, ), - ADA, - ); - expect([...ids]).toEqual([]); + ).toBeUndefined(); }); -test('treats the group named after the user as shared once another user has it as primary group', () => { - const ids = privateGroupIds( - database(['ada:x:1000:', 'staff:x:20:'], ['ada:x:1000:1000:', 'grace:x:1001:1000:']), - ADA, - ); - expect([...ids]).toEqual([]); +test('refuses it once another user has it as their primary group', () => { + expect( + privateGroupId(database(['ada:x:1000:'], ['ada:x:1000:1000:', 'grace:x:1001:1000:']), ADA), + ).toBeUndefined(); +}); + +test('refuses a group that is not the primary group of the user, however few members it lists', () => { + expect(privateGroupId(database(['ada:x:4321:'], ['ada:x:1000:1000:']), ADA)).toBeUndefined(); +}); + +test('refuses a group that does not carry the name of the user', () => { + expect(privateGroupId(database(['team:x:1000:'], ['ada:x:1000:1000:']), ADA)).toBeUndefined(); +}); + +test('refuses it when the group file cannot be read', () => { + expect(privateGroupId(database(undefined, PRIVATE_PASSWD), ADA)).toBeUndefined(); +}); + +test('refuses it when the passwd file cannot be read', () => { + expect(privateGroupId(database(PRIVATE, undefined), ADA)).toBeUndefined(); }); -test('never treats another group name as private, however few members it lists', () => { - const ids = privateGroupIds(database(['team:x:4321:', 'ada:x:1000:'], ['ada:x:1000:1000:']), ADA); - expect([...ids]).toEqual([1000]); +test('refuses it when the user has no passwd record', () => { + expect(privateGroupId(database(PRIVATE, ['root:x:0:0']), ADA)).toBeUndefined(); }); -test('treats an unreadable group database as having no private group', () => { - expect([...privateGroupIds(database([], []), ADA)]).toEqual([]); +test('refuses it when the passwd record names another uid or gid', () => { + const other = { uid: 1002, gid: 1000, name: 'ada' }; + expect(privateGroupId(database(PRIVATE, PRIVATE_PASSWD), other)).toBeUndefined(); }); test('gives a caller without a full identity no private group', () => { - const groups = database(['ada:x:1000:'], ['ada:x:1000:1000:']); - expect([...privateGroupIds(groups, { uid: undefined, name: 'ada' })]).toEqual([]); - expect([...privateGroupIds(groups, { uid: 1000, name: undefined })]).toEqual([]); + const groups = database(PRIVATE, PRIVATE_PASSWD); + expect(privateGroupId(groups, { uid: undefined, gid: 1000, name: 'ada' })).toBeUndefined(); + expect(privateGroupId(groups, { uid: 1000, gid: undefined, name: 'ada' })).toBeUndefined(); + expect(privateGroupId(groups, { uid: 1000, gid: 1000, name: undefined })).toBeUndefined(); }); diff --git a/packages/host-kit/src/internal/atomic-file.ts b/packages/host-kit/src/internal/atomic-file.ts index f05b8550b3..daa90aaf74 100644 --- a/packages/host-kit/src/internal/atomic-file.ts +++ b/packages/host-kit/src/internal/atomic-file.ts @@ -48,8 +48,8 @@ export function publishFileSync(options: { * Publishes a session script, and nothing else, from a same-directory temporary sibling. * * This is `publishFileSync` plus the destination-ancestry rule (#4565): the chain is refused before - * anything is written, and it is checked again immediately before the link or rename, so a directory - * swapped in by another local user while the file was staged never receives the script. + * anything is staged, and it is judged again immediately before the link or rename. The file is created + * private, because a recording is a transcript of what someone did on this machine. * * `parentIdentity` is what {@link publishDirectoryIdentity} returned for a parent the caller created or * checked before it staged this file. @@ -61,15 +61,12 @@ export function publishScriptFileSync(options: { publish?: AtomicPublishMode; parentIdentity?: string; }): void { + const mode = options.mode ?? 0o600; const expected = options.parentIdentity ?? publishDirectoryIdentity(path.dirname(options.destination)); withAtomicPublishTempPathSync(options.destination, (temporaryPath) => { assertPrivateScriptDestination(options.destination, expected); - fs.writeFileSync( - temporaryPath, - options.contents, - options.mode === undefined ? 'utf8' : { encoding: 'utf8', mode: options.mode }, - ); + fs.writeFileSync(temporaryPath, options.contents, { encoding: 'utf8', mode }); assertPrivateScriptDestination(options.destination, expected); if (options.publish === 'link-exclusive') { fs.linkSync(temporaryPath, options.destination); @@ -186,33 +183,41 @@ export function isAtomicPublishTemporaryPath(value: unknown, destination: string } /** - * Refuses a script destination when another local user can write a directory on the way to it (#4565). + * Refuses a script destination unless every directory on its fully resolved chain is one no other + * non-root local user can change (#4565). * * Node exposes no `openat` or `renameat`, so a publisher cannot resolve a destination relative to a - * directory handle. What remains is to refuse every chain a second local user can act inside: a - * directory they can write is one where they can replace a component of this path, or create one before - * this client does, so the script lands where they choose, or they take it from a directory they own. + * directory handle. The window is closed by PERMISSIONS instead of by timing: once no other non-root + * user can add or remove an entry in any directory on the chain, nobody can swap a component out or + * plant one, so the path this rule judged is the path the publish reaches. Nothing here depends on when + * the directory was judged, and no re-check is what makes the write safe. + * + * The existing prefix of the destination is resolved once, and every directory of that resolved chain + * is judged, so a symbolic link's target is judged too: `/home/me/link` standing for a shared directory + * is refused for the same reason that directory would be if the caller had spelled it out. Each + * directory then has to satisfy: * - * The rule reads each component with `lstat`, so a symbolic link is judged as the link it is and is - * never mistaken for the directory its target names: + * - It is owned by this user or by root. A directory another user owns is theirs to chmod, to empty, and + * to repopulate, whatever its mode says today. + * - Its mode opens its contents to nobody else. The sticky bit is the one exception, and only for + * passing THROUGH a directory: it stops anyone but an entry's owner or root from removing or replacing + * that entry, which is how macOS `/tmp` and `/var` stay usable. It cannot refuse a NEW entry by name, + * so nothing may be created inside a directory others can add entries to; that is asked separately. + * - A symbolic link the path passes through is one others could not have planted or swapped: in a + * directory where they can add entries, it stands there only because the sticky bit and its owner + * hold it in place. * - * - A component's mode decides. The sticky bit cancels the exposure: it stops anyone but an entry's - * owner or root from removing or replacing that entry, which is how a shared team directory is made - * safe, and why the hint names it. - * - Otherwise a component writable by anyone other than this user is refused, except a group-writable - * one whose group is this user's own private group: Ubuntu and Debian set up every home directory - * that way, often group-writable, and those have to stay usable. - * - A symbolic link whose own directory others can create entries in is refused whatever it points at: - * it may be one they planted, and its target is theirs to choose. The sticky bit does not help here, - * because it guards entries that already exist. + * A group-writable directory this user owns stays acceptable when its group is this user's own private + * group, the shape Ubuntu and Debian give every home directory. {@link privateGroupId} says what that + * takes to establish, and what it cannot. * - * An absent or non-directory component is left alone: the filesystem refuses a publish through it. On - * Windows, access is an ACL rather than a mode, so this is a no-op there. + * A component that exists and is neither a directory nor a link is left alone: the filesystem refuses a + * publish through it. On Windows, access is an ACL rather than a mode, so this is a no-op there. * * `parentIdentity` is what {@link publishDirectoryIdentity} returned for the parent the caller created - * or checked before it staged this file. Whoever owns a directory above it can open that directory to - * others, swap the parent for one of their own while the file is staged, and close it again, and only - * the identity catches that. + * or checked before it staged this file. The rule above already excludes anyone who could swap that + * parent, so the comparison is defense in depth against a host whose ownership or modes moved meanwhile; + * it is not what closes the window. */ export function assertPrivateScriptDestination(destination: string, parentIdentity?: string): void { if (process.platform === 'win32') return; @@ -220,20 +225,78 @@ export function assertPrivateScriptDestination(destination: string, parentIdenti if (parentIdentity !== undefined && publishDirectoryIdentity(parent) !== parentIdentity) { throw scriptAncestryFailure(destination, parent, 'parent_replaced'); } - const privateGids = lazyPrivateGroupIds(); + const trust = readScriptTrust(); + assertNoPlantedLink(destination, parent, trust); + const existing = deepestExistingDirectory(parent); + if (existing.real === undefined) return; + const chain = directoryChain(existing.real); + for (const ancestor of chain) { + const stats = statDirectoryChain(ancestor); + if (!stats) continue; + const exposure = untrustedAncestryExposure(stats, trust); + if (exposure) throw scriptAncestryFailure(destination, ancestor, exposure); + } + // The script entry is created inside the deepest directory that exists, or below it through + // directories that do not exist yet. Where other local users can add entries, one of them can add + // this entry first and the recording is theirs, so the creation has to be refused. + const deepest = statDirectoryChain(existing.real); + if (deepest && othersCreateEntriesIn(deepest, trust)) { + throw scriptAncestryFailure(destination, existing.real, 'shared_parent'); + } +} + +/** + * Refuses a symbolic link on the spelled path that another local user could have put there, or could + * replace. The link's target is judged through the resolved chain, so this only asks whether the link + * itself is stable: + * + * - In a directory others cannot add entries in, a link nobody but this user or root can write is not + * something they can plant or swap. + * - In a directory others CAN add entries in, the sticky bit is what protects an entry that already + * exists: it stops anyone but the entry's owner or root from removing or replacing it. Without the + * sticky bit, any of them can unlink this link and plant one pointing wherever they choose. + */ +function assertNoPlantedLink( + destination: string, + parent: string, + trust: ScriptDestinationTrust, +): void { for (const ancestor of directoryChain(parent)) { const link = lstatIfPresentSync(ancestor); - if (!link) continue; - if (link.isSymbolicLink() && othersCreateEntriesIn(path.dirname(ancestor), privateGids)) { - throw scriptAncestryFailure(destination, ancestor, 'planted_link'); - } - const directory = link.isSymbolicLink() ? statDirectoryChain(ancestor) : link; - if (!directory?.isDirectory()) continue; - const exposure = untrustedWritableExposure(directory, privateGids()); + if (!link?.isSymbolicLink()) continue; + const home = lstatIfPresentSync(path.dirname(ancestor)); + if (!home) continue; + const exposure = untrustedLinkExposure( + { uid: link.uid }, + { uid: home.uid, gid: home.gid, mode: home.mode }, + trust, + ); if (exposure) throw scriptAncestryFailure(destination, ancestor, exposure); } } +/** + * The real path of the deepest directory `directory` names or leads to, or `undefined` when nothing of it + * exists to judge. A component that exists but resolves to nothing (a dangling link) is stepped over like + * one that is absent, so the walk never stops with nothing checked. + */ +function deepestExistingDirectory(directory: string): Readonly<{ real: string | undefined }> { + let current = directory; + for (;;) { + if (lstatIfPresentSync(current) !== undefined) { + try { + const real = fs.realpathSync(current); + if (statDirectoryChain(real)) return { real }; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + } + } + const parent = path.dirname(current); + if (parent === current) return { real: undefined }; + current = parent; + } +} + /** * One directory's identity on its filesystem, for a caller that must publish into the same one it * created or checked. `undefined` when the directory is absent or is not a directory. @@ -246,59 +309,68 @@ export function publishDirectoryIdentity(directory: string): string | undefined /** The group and passwd records the private-group exception reads, in `/etc/group` field order. */ type HostGroupDatabase = Readonly<{ - groups: readonly string[]; - passwd: readonly string[]; + /** `undefined` when the file could not be read, which is not the same as a file with no records. */ + groups: readonly string[] | undefined; + passwd: readonly string[] | undefined; }>; /** - * The private group of `current`, in the one shape the exception admits: the group named after them. + * The single group the private-group exception admits, or `undefined` when nothing was established. * * Ubuntu and Debian create one group per user, named after them, and set up that user's home directory - * with it, often group-writable. Such a home is shared with no other local user, so it stays a valid - * script destination. Every other group name stays outside the exception: this host's own records - * cannot bound it, because macOS lists only part of `staff` in `/etc/group` while every local user - * holds it, and a name service can add members to a group this machine cannot read. + * with it, often group-writable and owned by that user. Such a home is shared with no other local user, + * so it stays a valid script destination. Every other group stays outside the exception, and the rule + * fails closed wherever completeness cannot be established: * - * Membership comes from both places a member can appear: the group's own member list, and the users - * whose primary group is this one. A member who is neither `current` nor root disqualifies the group. + * - Both database files must have been READ. An unreadable file is not an empty one, and an empty + * member list proves nothing. + * - The group must be the one this process holds as its PRIMARY group, which `getgid` answers from the + * kernel rather than from a file, and it must carry this user's name. + * - The group's own member list may name nobody but this user. macOS lists only part of `staff` in + * `/etc/group` while every local user holds it, so a name that is not this user's ends the claim + * rather than being looked up and forgiven. + * - No other record in the passwd file may hold this group as its primary group, and the caller's own + * record must exist there with this uid and this gid. + * + * What this cannot establish: a name service (LDAP, NSS modules) can add a user whose primary group is + * this gid without that user ever appearing in `/etc/passwd`. A host configured that way can still be + * refused a group-writable destination it appears to own, which is the residual limitation the + * documentation names; the caller's fallback is a directory only they can write. */ -export function privateGroupIds( +export function privateGroupId( database: HostGroupDatabase, - current: Readonly<{ uid: number | undefined; name: string | undefined }>, -): Set { - const privateIds = new Set(); - if (current.uid === undefined || current.name === undefined) return privateIds; - const uidByName = new Map(); - const primaryMembers = new Map(); - for (const line of database.passwd) { - const [name, , rawUid, rawGid] = line.split(':'); - const uid = Number(rawUid); - const gid = Number(rawGid); - if (!name || !Number.isInteger(uid) || !Number.isInteger(gid)) continue; - uidByName.set(name, uid); - primaryMembers.set(gid, [...(primaryMembers.get(gid) ?? []), name]); - } - for (const line of database.groups) { - const [name, , rawGid, rawMembers] = line.split(':'); - const gid = Number(rawGid); - if (name !== current.name || !Number.isInteger(gid)) continue; - const supplementary = (rawMembers ?? '').split(',').filter((member) => member.length > 0); - const ids = [...supplementary, ...(primaryMembers.get(gid) ?? [])].map((member) => - uidByName.get(member), - ); - if (ids.every((id) => id === current.uid || id === 0)) privateIds.add(gid); - } - return privateIds; + current: Readonly<{ uid: number | undefined; gid: number | undefined; name: string | undefined }>, +): number | undefined { + const { uid, gid, name } = current; + if (uid === undefined || gid === undefined || name === undefined) return undefined; + if (!database.groups || !database.passwd) return undefined; + const record = database.groups.find((line) => line.split(':')[0] === name); + if (!record) return undefined; + const [, , rawGid, rawMembers = ''] = record.split(':'); + const privateGid = Number(rawGid); + if (!Number.isInteger(privateGid) || privateGid !== gid) return undefined; + const members = rawMembers.split(',').filter((member) => member.length > 0); + if (members.some((member) => member !== name)) return undefined; + const own = database.passwd.find((line) => line.split(':')[0] === name); + if (!own) return undefined; + const [, , ownUid, ownGid] = own.split(':'); + if (Number(ownUid) !== uid || Number(ownGid) !== gid) return undefined; + const sharesPrimary = database.passwd.some((line) => { + const [other, , , otherGid] = line.split(':'); + return other !== name && Number(otherGid) === gid; + }); + return sharesPrimary ? undefined : gid; } -/** This host's private groups, read from the group database the first time the chain meets one. */ -function lazyPrivateGroupIds(): () => ReadonlySet { - let cached: ReadonlySet | undefined; - return () => - (cached ??= privateGroupIds( +/** This process's identity and the private group its host databases establish, if any. */ +function readScriptTrust(): ScriptDestinationTrust { + return { + uid: process.getuid?.() ?? -1, + privateGid: privateGroupId( { groups: readSystemFile('/etc/group'), passwd: readSystemFile('/etc/passwd') }, - { uid: process.getuid?.(), name: readCurrentUser() }, - )); + { uid: process.getuid?.(), gid: process.getgid?.(), name: readCurrentUser() }, + ), + }; } function readCurrentUser(): string | undefined { @@ -321,59 +393,120 @@ function directoryChain(directory: string): string[] { } } -/** Why other local users can write in this directory, or `undefined` when only this user and root can. */ -function untrustedWritableExposure( - stats: fs.Stats, - privateGids: ReadonlySet, -): AncestryExposure | undefined { - if (stats.mode & 0o1000) return undefined; - if (stats.mode & 0o002) return 'world_writable'; - if (stats.mode & 0o020 && !privateGids.has(stats.gid)) return 'shared_group_writable'; +/** + * The two ways a directory can be unsafe for a destination: someone else can change what is in it, or + * someone else can create the entry the destination names. + * + * `foreign_owned` — some other user owns it and can chmod, empty, or repopulate it whatever its mode. + * `world_writable` / `shared_group_writable` — its mode opens its contents to others. + * `shared_parent` — nobody else can change what is in it today, but they can add the missing entry. + * `planted_link` — a symbolic link someone else could have put in place of a directory. + * `parent_replaced` — the directory the caller staged against is not the one it was. + */ +export type ScriptAncestryExposure = + | 'foreign_owned' + | 'world_writable' + | 'shared_group_writable' + | 'shared_parent' + | 'planted_link' + | 'parent_replaced'; + +/** What this process can rely on when it judges a directory: its identity and its private group. */ +export type ScriptDestinationTrust = Readonly<{ + uid: number; + privateGid: number | undefined; +}>; + +/** The fields of a directory the ancestry rule reads, so the decision is testable without a filesystem. */ +export type DirectoryAuthority = Readonly<{ uid: number; gid: number; mode: number }>; + +/** + * Whether this directory is one this user can rely on a destination being inside of, and why not if it + * is not. + * + * Ownership is asked first: a directory another user owns is theirs to chmod, to empty, and to + * repopulate whatever its mode says today, and no race is needed to do it. Then the mode, because + * group- or other-writable contents are open to those users directly. The sticky bit is the one mode + * exception, and it is sound only for PASSING THROUGH a directory: it stops anyone but an entry's owner + * or root from removing or replacing that entry, so the entries already on the path hold. It cannot + * refuse a NEW entry by name, so {@link othersCreateEntriesIn} is asked separately before anything is + * created inside. + */ +export function untrustedAncestryExposure( + directory: DirectoryAuthority, + trust: ScriptDestinationTrust, +): ScriptAncestryExposure | undefined { + if (directory.uid !== 0 && directory.uid !== trust.uid) return 'foreign_owned'; + if (directory.mode & 0o1000) return undefined; + if (directory.mode & 0o002) return 'world_writable'; + if (directory.mode & 0o020 && directory.gid !== trust.privateGid) return 'shared_group_writable'; return undefined; } -/** Whether other local users can create an entry here: how a component becomes their symbolic link. */ -function othersCreateEntriesIn(directory: string, privateGids: () => ReadonlySet): boolean { - const stats = statDirectoryChain(directory); - if (!stats) return false; - if (stats.mode & 0o002) return true; - return Boolean(stats.mode & 0o020) && !privateGids().has(stats.gid); +/** + * Whether other local users can add an entry here, which is how the destination's own name, or a + * directory below it, becomes theirs. The sticky bit is deliberately not consulted: it protects entries + * that already exist and cannot refuse a new one. + */ +export function othersCreateEntriesIn( + directory: DirectoryAuthority, + trust: ScriptDestinationTrust, +): boolean { + if (directory.mode & 0o002) return true; + return Boolean(directory.mode & 0o020) && directory.gid !== trust.privateGid; } -type AncestryExposure = - | 'world_writable' - | 'shared_group_writable' - | 'planted_link' - | 'parent_replaced'; +/** The fields of a symbolic link the ancestry rule reads. */ +export type LinkAuthority = Readonly<{ uid: number }>; + +/** + * Whether a symbolic link on the path is one another local user could have put there, or could replace, + * and whose target is therefore theirs to choose. + * + * Where nobody but this user or root can add entries, a link cannot appear or change behind this rule. + * Where others CAN add entries, the sticky bit is the only thing holding an existing entry in place: it + * stops anyone but the entry's owner or root from unlinking and replacing it, so a link this user or root + * owns stands, and one anybody else owns does not — it may be theirs, and without the sticky bit any of + * them can swap it for one pointing wherever they like. + */ +export function untrustedLinkExposure( + link: LinkAuthority, + home: DirectoryAuthority, + trust: ScriptDestinationTrust, +): ScriptAncestryExposure | undefined { + if (!othersCreateEntriesIn(home, trust)) return undefined; + if (home.mode & 0o1000 && (link.uid === 0 || link.uid === trust.uid)) return undefined; + return 'planted_link'; +} function scriptAncestryFailure( destination: string, ancestor: string, - exposure: AncestryExposure, + exposure: ScriptAncestryExposure, ): AppError { - const writableByOthers = exposure !== 'parent_replaced'; + const replaced = exposure === 'parent_replaced'; return new AppError( 'COMMAND_FAILED', - writableByOthers - ? `Refusing to save the script under ${ancestor}: another local user can write that part of the path.` - : `The directory for ${destination} changed while the script was staged, so the script was not saved.`, + replaced + ? `The directory for ${destination} changed while the script was staged, so the script was not saved.` + : `Refusing to save the script under ${ancestor}: another local user owns or can write that part of the path.`, { - reason: writableByOthers ? 'script_ancestor_untrusted' : 'script_ancestry_replaced', + reason: replaced ? 'script_ancestry_replaced' : 'script_ancestor_untrusted', exposure, path: destination, ancestor, - hint: writableByOthers - ? `Save the script under a directory only you can write, or share ${ancestor} safely with the sticky bit (chmod +t) and keep symbolic links out of the path.` - : 'Re-record with open --save-script, or save under a directory nobody else can write.', + hint: replaced + ? 'Re-record with open --save-script, or save under a directory nobody else can write.' + : 'Save the script under a directory you own that only you can write, and keep the path out of directories other users own.', }, ); } -function readSystemFile(file: string): string[] { +function readSystemFile(file: string): string[] | undefined { try { return fs.readFileSync(file, 'utf8').split('\n'); } catch { - return []; + return undefined; } } diff --git a/packages/remote/src/__tests__/daemon-artifacts-script-download.test.ts b/packages/remote/src/__tests__/daemon-artifacts-script-download.test.ts index 585cf53d74..1ba50bc410 100644 --- a/packages/remote/src/__tests__/daemon-artifacts-script-download.test.ts +++ b/packages/remote/src/__tests__/daemon-artifacts-script-download.test.ts @@ -471,7 +471,7 @@ test.skipIf(process.platform === 'win32').each([ plant: (root: string) => { const shared = path.join(root, 'shared'); fs.mkdirSync(shared); - fs.chmodSync(shared, 0o1777); + fs.chmodSync(shared, 0o777); const attacker = path.join(root, 'attacker'); fs.mkdirSync(attacker); fs.symlinkSync(attacker, path.join(shared, 'work')); diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 6cafe0224d..892d611545 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -108,7 +108,7 @@ Outside a macOS app lease, a fresh `open --save-script=` records the sessi your machine. Each response that records an action returns a `session-script` artifact, and the client replaces the file with it. `close` returns the final script. The client writes only to the path that its own `open` named. If the file already exists, `open` fails unless you pass `--force`. -Every directory on the way to that path must be one that only you and root can write; see +Every directory on the way to that path must be one that no other local user can change; see [Record a replay script](replay-e2e.md#record-a-replay-script). The daemon must report the `script-artifacts` capability in its `/health` response; through a proxy, the upstream daemon's health response must report it. Otherwise `open --save-script` is diff --git a/website/docs/docs/replay-e2e.md b/website/docs/docs/replay-e2e.md index fab424778f..4d556aa43b 100644 --- a/website/docs/docs/replay-e2e.md +++ b/website/docs/docs/replay-e2e.md @@ -70,10 +70,11 @@ To choose the output file, pass a path to `--save-script`: agent-device open Settings --platform ios --session e2e --save-script ./workflows/e2e-settings.ad ``` -- Missing parent directories are created. -- Every directory on the way to the script must be one that only you and root can write. Another local user who can write such a directory can replace a directory on the path, or leave a symbolic link there, before the script is moved into place. The script then lands where they choose. -- A shared team directory is safe once it has the sticky bit (`chmod +t`): it stops anyone but an entry's owner or root from replacing that entry. A group-writable home directory of your own private group, the shape Ubuntu and Debian create, is accepted. A symbolic link inside a directory others can write is refused, whatever it points at. -- A refused destination names the directory at fault. A local `close` fails and keeps its bytes. A remote recording keeps its success and reports `script_ancestor_untrusted` as the `scriptDeliveryFailure` cause, and the next recorded action or `close` repeats the refusal. Choosing a directory nobody else can write, or adding the sticky bit, clears it. +- Missing parent directories are created. The script file itself is created so that only you can read it. +- Every directory on the way to the script must be one that no other local user can change. Each must be owned by you or by root, and its permissions must keep its contents closed to everyone else. Another local user who owns such a directory, or who can write in it, can replace a directory on the path or leave a symbolic link there, and the script then lands where they choose. +- The whole real path is checked, so a symbolic link to a shared directory is refused too. A link is refused if another user could have placed it, or could replace it: in a directory where others may add entries, only a link you or root own, held in place by the sticky bit, is trusted. Root-owned system links such as macOS `/tmp` and `/var` keep working. +- A directory may pass through a shared directory that carries the sticky bit (`chmod +t`), because that bit stops anyone but an entry's owner or root from replacing it. The script is never created *inside* such a directory: there, anyone could create your file's name first. A group-writable directory you own is accepted when its group is your own private group, the shape Ubuntu and Debian create for home directories. +- A refused destination names the directory at fault. A local `close` fails and keeps its bytes. A remote recording keeps its success and reports `script_ancestor_untrusted` as the `scriptDeliveryFailure` cause, and the next recorded action or `close` repeats the refusal. Choose a directory you own that only you can write. - With a local daemon, the script is written on the daemon host when the session closes. - With a remote daemon, outside a macOS app lease, the path is on your machine. The file appears when `open` returns, and each later recorded action in the session replaces it with the recording so far. `close` writes the final script there. A session that another process closes keeps the version from the last action. - A bare remote `open --save-script` writes `recording-.ad` in your working directory. From e30b44e71705400da460f66bb94fba599ae0c42c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 16 Nov 2026 12:14:44 +0100 Subject: [PATCH 07/10] fix(host-kit): keep foreign ground out of a script destination chain 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 `/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 --- .../0016-active-session-script-publication.md | 2 +- .../src/internal/atomic-file-ancestry.test.ts | 226 +++++++++++++++--- packages/host-kit/src/internal/atomic-file.ts | 54 ++++- website/docs/docs/replay-e2e.md | 2 +- 4 files changed, 245 insertions(+), 39 deletions(-) diff --git a/docs/adr/0016-active-session-script-publication.md b/docs/adr/0016-active-session-script-publication.md index 65f8f822e8..b553319129 100644 --- a/docs/adr/0016-active-session-script-publication.md +++ b/docs/adr/0016-active-session-script-publication.md @@ -210,7 +210,7 @@ It adds no state name, command, or flag: The destination keeps local `--save-script` semantics (#4565): the client creates a missing parent directory, and neither the daemon nor the client publishes through a directory another local user can change. The rule closes the window with PERMISSIONS, not with timing. A destination is accepted only when no other non-root local user can modify any directory on its fully resolved chain. Each directory must be owned by the current user or by root, and its mode must keep its contents closed to others. Once that holds, nobody can swap a component out or plant one, so the path that was judged is the path the publish reaches; nothing depends on when a directory was judged. The chain is resolved first, so a symbolic link's target is judged under the same rule. A link is refused when another user could have placed it or could replace it: in a directory where others may add entries, only a link owned by the current user or root and held by the sticky bit is trusted. Root-owned system aliases (macOS `/tmp` to `/private/tmp`, `/var` to `/private/var`) keep working. -The sticky bit excuses a directory the chain passes THROUGH, because it stops anyone but an entry's owner or root from replacing that entry; it never excuses creating the destination inside that directory, because anyone could create that name first. A group-writable directory the current user owns is accepted when its group is that user's own private group, which is the shape Ubuntu and Debian give home directories; this is the one place the rule reads `/etc/group` and `/etc/passwd`, and it fails closed when either file is unreadable. Residual limitation: a name service (LDAP or an NSS module) can add a member holding that primary GID without it appearing in `/etc/passwd`, so such a host can be refused a group-writable directory it appears to own. The fallback is a directory only the user can write. +The sticky bit excuses a directory the chain passes THROUGH, when this user or root owns it, because it stops anyone but an entry's owner or root from replacing that entry; a sticky directory another user owns is refused, because those bits shield other users from that owner rather than the reverse. It never excuses creating the destination inside that directory, because anyone could create that name first. A group-writable directory the current user owns is accepted when its group is that user's own private group, which is the shape Ubuntu and Debian give home directories; this is the one place the rule reads `/etc/group` and `/etc/passwd`, and it fails closed when either file is unreadable. Residual limitation: a name service (LDAP or an NSS module) can add a member holding that primary GID without it appearing in `/etc/passwd`, so such a host can be refused a group-writable directory it appears to own. The fallback is a directory only the user can write. The script file is created 0600, locally and remotely alike, so a recording is not world-readable in a directory that is merely shared. The publisher compares the destination directory's captured `dev:ino` before publishing. The ownership rule above already excludes anyone able to swap that directory, so the comparison is defense in depth against a host whose ownership or modes moved during the download, not the check that closes the window. Node exposes no `openat` or `renameat`, so publishing relative to a verified directory handle is not available without native code; the permissions rule is what substitutes for it. diff --git a/packages/host-kit/src/internal/atomic-file-ancestry.test.ts b/packages/host-kit/src/internal/atomic-file-ancestry.test.ts index 4d624b8a35..efdb75704d 100644 --- a/packages/host-kit/src/internal/atomic-file-ancestry.test.ts +++ b/packages/host-kit/src/internal/atomic-file-ancestry.test.ts @@ -26,6 +26,9 @@ type Database = Readonly<{ const realReadFileSync = fs.readFileSync; const currentUser = os.userInfo().username; +/** The unmocked `stat` calls, so a second fixture here never wraps the first one's mock. */ +const realLstatSync = fs.lstatSync.bind(fs); +const realStatSync = fs.statSync.bind(fs); /** This process's ids. Windows has neither, and every test that uses them is skipped there. */ const currentUid = process.getuid?.() ?? -1; @@ -66,6 +69,26 @@ function unreadableDatabases(): Database { return { groups: undefined, passwd: undefined }; } +/** + * Reports `owners` for the named paths and the real host for everything else, so the ownership rule is + * the fixture's and not the CI image's directory tree. Only the ids move: modes and inode numbers stay + * what they are on disk. A real foreign owner would need privileges this test does not have. + */ +function serveOwnership(owners: Readonly>): void { + const withUid = (stats: fs.Stats, pathname: string): fs.Stats => { + const uid = owners[pathname]; + if (uid === undefined || stats.uid === uid) return stats; + return Object.assign(Object.create(Object.getPrototypeOf(stats)), stats, { uid }) as fs.Stats; + }; + vi.spyOn(fs, 'lstatSync').mockImplementation(((pathname: never, ...rest: never[]) => + withUid(realLstatSync(pathname, ...rest), String(pathname))) as typeof fs.lstatSync); + vi.spyOn(fs, 'statSync').mockImplementation(((pathname: never, ...rest: never[]) => + withUid(realStatSync(pathname, ...rest), String(pathname))) as typeof fs.statSync); +} + +/** Some other local user, not this one and not root. */ +const FOREIGN_UID = 65534; + function root(): string { return fs.realpathSync(mkdtempForTestSync('host-kit-ancestry-')); } @@ -177,10 +200,10 @@ skipOnWindows('refuses a destination under a group-writable shared directory', ( // --- ownership decides, not the mode alone --- -skipOnWindows('refuses a private-mode directory another user owns, whatever the mode', () => { +skipOnWindows('refuses a directory another user owns, whatever the mode', () => { serveGroupDatabase(hostDatabase(currentGid, 4321)); const work = directoryWith(path.join(root(), 'foreign'), 0o755); - asAnotherLocalUser(); + serveOwnership({ [work]: FOREIGN_UID }); expectUntrusted( () => assertPrivateScriptDestination(path.join(work, 'journey.ad')), @@ -189,6 +212,87 @@ skipOnWindows('refuses a private-mode directory another user owns, whatever the ); }); +skipOnWindows( + 'refuses a sticky directory another user owns, since both bits shield others from them', + () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // The reviewer's case: a teammate runs `chmod 1777` on a directory of THEIRS. The sticky bit keeps me + // from deleting their entries; it does nothing to stop them replacing mine. + const team = directoryWith(path.join(root(), 'team'), 0o1777); + serveOwnership({ [team]: FOREIGN_UID }); + const work = path.join(team, 'work'); + fs.mkdirSync(work); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(work, 'journey.ad')), + 'foreign_owned', + team, + ); + }, +); + +skipOnWindows( + 'refuses a recordings directory another local user created first in a sticky /tmp', + () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // `mkdir -p /tmp/recordings` is the shape: `/tmp` is sticky so nobody can touch anyone else's entry, + // and whoever creates that directory first owns it. The owner can rename it aside and put their own in + // place, whatever its mode says, so the destination has to be refused. + const systemTmp = directoryWith(path.join(root(), 'tmp'), 0o1777); + const recordings = path.join(systemTmp, 'recordings'); + fs.mkdirSync(recordings); + fs.chmodSync(recordings, 0o755); + serveOwnership({ [systemTmp]: 0, [recordings]: FOREIGN_UID }); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(recordings, 'journey.ad')), + 'foreign_owned', + recordings, + ); + }, +); + +skipOnWindows('refuses a link standing in a private-mode directory another user owns', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // The third input the reviewer names. `/teammate` is theirs at 0755, `link` is a component of my + // path, and the target is a directory of mine nothing could object to. Nothing about the target chain + // looks wrong: the exposure is that the OWNER of the directory the link stands in can rename that + // component and leave one of their own there, pointing wherever they like. + const directory = root(); + const teammate = directoryWith(path.join(directory, 'teammate'), 0o755); + serveOwnership({ [teammate]: FOREIGN_UID }); + const mine = directoryWith(path.join(directory, 'mine'), 0o700); + fs.symlinkSync(mine, path.join(teammate, 'link')); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(teammate, 'link', 'journey.ad')), + 'planted_link', + path.join(teammate, 'link'), + ); + expect(fs.readdirSync(mine)).toEqual([]); +}); + +skipOnWindows('judges the directories a .. in the path walks through', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // `/shared/work/../x/journey.ad` is a path a caller can pass. Resolving it first answers + // `/shared/x/journey.ad`, which is a DIFFERENT directory from the one that receives the file: + // the kernel walks `work` into the link's target and steps back from THERE, so the entry is created + // beside that target. The rule has to judge the components it walked, so the link is refused here. + const directory = root(); + const shared = directoryWith(path.join(directory, 'shared'), 0o777); + const published = directoryWith(path.join(directory, 'published'), 0o700); + const attacker = path.join(published, 'attacker'); + fs.mkdirSync(attacker); + fs.symlinkSync(attacker, path.join(shared, 'work')); + + expectUntrusted( + () => assertPrivateScriptDestination(`${shared}/work/../x/journey.ad`), + 'planted_link', + path.join(shared, 'work'), + ); + expect(fs.readdirSync(attacker)).toEqual([]); +}); + skipOnWindows('refuses a directory its owner opened up while the file was staged', () => { serveGroupDatabase(hostDatabase(currentGid, 4321)); const work = path.join(root(), 'work'); @@ -271,6 +375,29 @@ skipOnWindows('refuses a symbolic link planted in a directory others can add ent expect(fs.readdirSync(attacker)).toEqual([]); }); +skipOnWindows('refuses a private link whose target chain is a shared directory', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // `~/rec -> /srv/team/rec`, with `/srv/team` open to the team. The link itself is this user's own in + // their own home, so nothing about it looks wrong; only the resolved chain shows the destination + // would sit in ground the whole team can write. + const directory = root(); + const home = path.join(directory, 'home'); + fs.mkdirSync(home); + const srv = path.join(directory, 'srv'); + const team = path.join(srv, 'team'); + fs.mkdirSync(team, { recursive: true }); + fs.chmodSync(team, 0o777); + const rec = path.join(team, 'rec'); + fs.mkdirSync(rec); + fs.symlinkSync(rec, path.join(home, 'rec')); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(home, 'rec', 'journey.ad')), + 'world_writable', + team, + ); +}); + skipOnWindows('refuses a symbolic link whose target is a directory others can write', () => { serveGroupDatabase(hostDatabase(currentGid, 4321)); const directory = root(); @@ -321,11 +448,11 @@ skipOnWindows('keeps working through a root-owned alias whose target is sticky', expect(fs.existsSync(path.join(target, 'work', 'journey.ad'))).toBe(true); }); -skipOnWindows('publishes through the host root-owned system alias /tmp', () => { +skipOnWindows('publishes under the host root-owned system temporary directory', () => { serveGroupDatabase(hostDatabase(currentGid, 4321)); - // macOS reaches `/private/tmp` through `/tmp`, and Linux mounts `/tmp` directly. Either way the - // script lands in a sticky root-owned directory, so the alias must not be what ends the publish. - if (!fs.existsSync('/tmp') || !fs.lstatSync('/tmp').isSymbolicLink()) return; + // macOS reaches `/private/tmp` through `/tmp`, Linux mounts `/tmp` directly. Both are sticky and + // root-owned, and the script is created in a private directory under it, so neither spelling may + // stop the publish. const work = fs.mkdtempSync('/tmp/agent-device-ancestry-'); fs.chmodSync(work, 0o700); const destination = path.join(work, 'journey.ad'); @@ -337,21 +464,33 @@ skipOnWindows('publishes through the host root-owned system alias /tmp', () => { } }); -skipOnWindows( - 'publishes to a scratch path spelled through a system alias, not resolved away', - () => { - serveGroupDatabase(hostDatabase(currentGid, 4321)); - // The scratch root of `root()` is the resolved path. This one keeps whatever alias the host spells - // its temporary directory with, which is the shape a caller actually passes. - const directory = mkdtempForTestSync('host-kit-ancestry-alias-'); - expect(fs.realpathSync(directory)).not.toBe(directory); - const destination = path.join(directory, 'journey.ad'); +skipOnWindows('publishes to a path spelled through an alias of the directory that holds it', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // The caller passes a path whose parent is a link, in a chain only this user can write. The alias + // leads somewhere legal, so the publish follows it instead of refusing it. + const directory = root(); + const real = path.join(directory, 'workflows'); + fs.mkdirSync(real); + fs.symlinkSync(real, path.join(directory, 'current')); + const destination = path.join(directory, 'current', 'journey.ad'); - publish(destination); + publish(destination); - expect(fs.readFileSync(destination, 'utf8')).toBe('context\n'); - }, -); + expect(fs.readFileSync(path.join(real, 'journey.ad'), 'utf8')).toBe('context\n'); +}); + +skipOnWindows('publishes to a scratch path exactly as the host spelled it', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // The scratch root keeps the host's own spelling of its temporary directory: an alias on macOS, where + // `/var` stands for `/private/var`, and no alias at all on Linux. Neither spelling may stop a publish, + // so this asserts the outcome rather than what the host happens to name. + const directory = mkdtempForTestSync('host-kit-ancestry-spelled-'); + const destination = path.join(directory, 'journey.ad'); + + publish(destination); + + expect(fs.readFileSync(destination, 'utf8')).toBe('context\n'); +}); // --- the destination directory swapped out while the file was staged --- @@ -362,12 +501,16 @@ skipOnWindows('refuses a parent replaced by name while the file was staged', () fs.mkdirSync(staged); const parentIdentity = publishDirectoryIdentity(staged); const destination = path.join(staged, 'journey.ad'); + // The replacement is a link to another real directory. Removing the directory and creating the same + // name again is not enough to make the two differ: a filesystem may hand back the inode it just + // freed, and the identity would match by luck. + const elsewhere = path.join(directory, 'elsewhere'); + fs.mkdirSync(elsewhere); fs.rmSync(staged, { recursive: true }); - const replaced = path.join(directory, 'work'); - fs.mkdirSync(replaced); + fs.symlinkSync(elsewhere, staged); - expectUntrustedReplaced(() => publish(destination, parentIdentity), replaced); - expect(fs.readdirSync(replaced)).toEqual([]); + expectUntrustedReplaced(() => publish(destination, parentIdentity), staged); + expect(fs.readdirSync(elsewhere)).toEqual([]); }); skipOnWindows('re-checks the chain after staging the file, before the entry is created', () => { @@ -376,17 +519,20 @@ skipOnWindows('re-checks the chain after staging the file, before the entry is c const staged = path.join(directory, 'work'); fs.mkdirSync(staged); const destination = path.join(staged, 'journey.ad'); + const attacker = path.join(directory, 'attacker'); + fs.mkdirSync(attacker); const writeFileSync = fs.writeFileSync; vi.spyOn(fs, 'writeFileSync').mockImplementation(((file: unknown, ...rest: unknown[]) => { const result = (writeFileSync as (...args: unknown[]) => unknown)(file, ...rest); + // The directory the file was staged in is gone and its name is somebody else's now. A filesystem + // hands back a freed inode, so the swap has to be to a directory that is really another one. fs.rmSync(staged, { recursive: true, force: true }); - fs.mkdirSync(staged); - fs.chmodSync(staged, 0o777); + fs.symlinkSync(attacker, staged); return result; }) as typeof fs.writeFileSync); expectUntrustedReplaced(() => publish(destination), staged); - expect(fs.readdirSync(staged)).toEqual([]); + expect(fs.readdirSync(attacker)).toEqual([]); }); skipOnWindows('publishes into the parent the captured identity still names', () => { @@ -408,8 +554,13 @@ function directoryOf(overrides: Partial): DirectoryAuthority return { ...OWN, ...overrides }; } -test('refuses a directory another user owns even in private mode', () => { - expect(untrustedAncestryExposure(directoryOf({ uid: 65534 }), TRUST)).toBe('foreign_owned'); +test('refuses a directory another user owns, whatever its mode', () => { + expect(untrustedAncestryExposure(directoryOf({ uid: 65534, mode: 0o700 }), TRUST)).toBe( + 'foreign_owned', + ); + expect(untrustedAncestryExposure(directoryOf({ uid: 65534, mode: 0o755 }), TRUST)).toBe( + 'foreign_owned', + ); }); test('refuses a directory that is world-writable', () => { @@ -431,11 +582,18 @@ test('accepts a root-owned directory and a directory this user owns', () => { expect(untrustedAncestryExposure(directoryOf({}), TRUST)).toBeUndefined(); }); -test('accepts a sticky shared directory for passing through, in any ownership', () => { +test('accepts a sticky directory this user or root owns for passing through', () => { + expect(untrustedAncestryExposure(directoryOf({ uid: 0, mode: 0o1777 }), TRUST)).toBeUndefined(); expect(untrustedAncestryExposure(directoryOf({ mode: 0o1777 }), TRUST)).toBeUndefined(); +}); + +test('refuses a sticky directory another user owns, since both bits shield others FROM that owner', () => { expect(untrustedAncestryExposure(directoryOf({ uid: 65534, mode: 0o1777 }), TRUST)).toBe( 'foreign_owned', ); + expect(untrustedAncestryExposure(directoryOf({ uid: 65534, mode: 0o2775 }), TRUST)).toBe( + 'foreign_owned', + ); }); // --- untrustedLinkExposure: which link on the path belongs to somebody else --- @@ -475,6 +633,16 @@ test('names no directory whose group is this user', () => { expect(othersCreateEntriesIn(directoryOf({ mode: 0o755 }), TRUST)).toBe(false); }); +test('names a directory another user owns, whatever its mode', () => { + expect(othersCreateEntriesIn(directoryOf({ uid: 65534, mode: 0o755 }), TRUST)).toBe(true); + expect(othersCreateEntriesIn(directoryOf({ uid: 65534, mode: 0o1777 }), TRUST)).toBe(true); +}); + +test('names no directory this user or root owns that others cannot write', () => { + expect(othersCreateEntriesIn(directoryOf({ uid: 0, mode: 0o755 }), TRUST)).toBe(false); + expect(othersCreateEntriesIn(directoryOf({ uid: 0, mode: 0o1777 }), TRUST)).toBe(true); +}); + // --- privateGroupId: the one group shape the exception admits --- const ADA = { uid: 1000, gid: 1000, name: 'ada' }; diff --git a/packages/host-kit/src/internal/atomic-file.ts b/packages/host-kit/src/internal/atomic-file.ts index daa90aaf74..ce61e0b9f3 100644 --- a/packages/host-kit/src/internal/atomic-file.ts +++ b/packages/host-kit/src/internal/atomic-file.ts @@ -198,7 +198,8 @@ export function isAtomicPublishTemporaryPath(value: unknown, destination: string * directory then has to satisfy: * * - It is owned by this user or by root. A directory another user owns is theirs to chmod, to empty, and - * to repopulate, whatever its mode says today. + * to repopulate, whatever its mode says today, and both the sticky bit and the group bits shield other + * users FROM that owner rather than the reverse. * - Its mode opens its contents to nobody else. The sticky bit is the one exception, and only for * passing THROUGH a directory: it stops anyone but an entry's owner or root from removing or replacing * that entry, which is how macOS `/tmp` and `/var` stay usable. It cannot refuse a NEW entry by name, @@ -221,7 +222,7 @@ export function isAtomicPublishTemporaryPath(value: unknown, destination: string */ export function assertPrivateScriptDestination(destination: string, parentIdentity?: string): void { if (process.platform === 'win32') return; - const parent = path.dirname(path.resolve(destination)); + const parent = spelledParent(destination); if (parentIdentity !== undefined && publishDirectoryIdentity(parent) !== parentIdentity) { throw scriptAncestryFailure(destination, parent, 'parent_replaced'); } @@ -229,8 +230,7 @@ export function assertPrivateScriptDestination(destination: string, parentIdenti assertNoPlantedLink(destination, parent, trust); const existing = deepestExistingDirectory(parent); if (existing.real === undefined) return; - const chain = directoryChain(existing.real); - for (const ancestor of chain) { + for (const ancestor of directoryChain(existing.real)) { const stats = statDirectoryChain(ancestor); if (!stats) continue; const exposure = untrustedAncestryExposure(stats, trust); @@ -245,6 +245,20 @@ export function assertPrivateScriptDestination(destination: string, parentIdenti } } +/** + * The parent of `destination` as it was spelled, made absolute but never normalized. + * + * `path.resolve` folds a `..` away, which is the one simplification this rule may not make: the kernel + * does not make it either, so `.../work/../x` lands an entry beside the target of a link named `work`. + * The chain that walk produces is what gets judged. + */ +function spelledParent(destination: string): string { + if (path.isAbsolute(destination)) return parentDirectory(destination); + // A relative destination reaches the filesystem through the working directory, the same way + // `path.resolve` names it, and the walk above is what the kernel performs from there. + return parentDirectory(path.resolve(destination)); +} + /** * Refuses a symbolic link on the spelled path that another local user could have put there, or could * replace. The link's target is judged through the resolved chain, so this only asks whether the link @@ -291,7 +305,7 @@ function deepestExistingDirectory(directory: string): Readonly<{ real: string | if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; } } - const parent = path.dirname(current); + const parent = parentDirectory(current); if (parent === current) return { real: undefined }; current = parent; } @@ -387,12 +401,27 @@ function directoryChain(directory: string): string[] { let current = directory; for (;;) { chain.push(current); - const parent = path.dirname(current); + const parent = parentDirectory(current); if (parent === current) return chain; current = parent; } } +/** + * The parent of `directory`, as the kernel sees it, or the same path when there is no parent. + * + * `path.dirname` is not usable here: it normalizes, so it folds a `..` segment away. That is the one + * simplification this rule may not make. Where `work` is a symbolic link, `.../work/../x` is a real + * path that lands beside the link's TARGET, so the rule has to see `.../work` in the chain and judge + * the link that stands there. Only a trailing separator is dropped, in linear time. + */ +function parentDirectory(directory: string): string { + const trimmed = directory.endsWith('/') ? directory.slice(0, -1) : directory; + const separator = trimmed.lastIndexOf('/'); + if (separator < 0) return trimmed; + return separator === 0 ? '/' : trimmed.slice(0, separator); +} + /** * The two ways a directory can be unsafe for a destination: someone else can change what is in it, or * someone else can create the entry the destination names. @@ -445,13 +474,18 @@ export function untrustedAncestryExposure( /** * Whether other local users can add an entry here, which is how the destination's own name, or a - * directory below it, becomes theirs. The sticky bit is deliberately not consulted: it protects entries - * that already exist and cannot refuse a new one. + * directory below it, becomes theirs. + * + * A directory somebody else owns counts: they can create, rename, or replace any entry in it whatever + * its mode says, sticky bit included, since both of those protect other people's entries from them, not + * their own. The sticky bit is otherwise deliberately not consulted here — it cannot refuse a NEW entry + * by name. */ export function othersCreateEntriesIn( directory: DirectoryAuthority, trust: ScriptDestinationTrust, ): boolean { + if (directory.uid !== 0 && directory.uid !== trust.uid) return true; if (directory.mode & 0o002) return true; return Boolean(directory.mode & 0o020) && directory.gid !== trust.privateGid; } @@ -468,6 +502,10 @@ export type LinkAuthority = Readonly<{ uid: number }>; * stops anyone but the entry's owner or root from unlinking and replacing it, so a link this user or root * owns stands, and one anybody else owns does not — it may be theirs, and without the sticky bit any of * them can swap it for one pointing wherever they like. + * + * A component the path steps back over with `..` is asked as a directory rather than as a link: there + * the caller is not publishing through it, only walking across it, and the directory it lands in is + * judged on its own. */ export function untrustedLinkExposure( link: LinkAuthority, diff --git a/website/docs/docs/replay-e2e.md b/website/docs/docs/replay-e2e.md index 4d556aa43b..e3acf9d478 100644 --- a/website/docs/docs/replay-e2e.md +++ b/website/docs/docs/replay-e2e.md @@ -73,7 +73,7 @@ agent-device open Settings --platform ios --session e2e --save-script ./workflow - Missing parent directories are created. The script file itself is created so that only you can read it. - Every directory on the way to the script must be one that no other local user can change. Each must be owned by you or by root, and its permissions must keep its contents closed to everyone else. Another local user who owns such a directory, or who can write in it, can replace a directory on the path or leave a symbolic link there, and the script then lands where they choose. - The whole real path is checked, so a symbolic link to a shared directory is refused too. A link is refused if another user could have placed it, or could replace it: in a directory where others may add entries, only a link you or root own, held in place by the sticky bit, is trusted. Root-owned system links such as macOS `/tmp` and `/var` keep working. -- A directory may pass through a shared directory that carries the sticky bit (`chmod +t`), because that bit stops anyone but an entry's owner or root from replacing it. The script is never created *inside* such a directory: there, anyone could create your file's name first. A group-writable directory you own is accepted when its group is your own private group, the shape Ubuntu and Debian create for home directories. +- A directory you or root own may still be passed through when it carries the sticky bit (`chmod +t`) and is open to others, because that bit stops anyone but an entry's owner or root from replacing an entry: macOS `/tmp` works this way. A sticky directory owned by somebody else is refused — both bits shield other users from its owner, not the owner from you. The script is never created *inside* a directory others may add entries to: there, anyone could create your file's name first. A group-writable directory you own is accepted when its group is your own private group, the shape Ubuntu and Debian create for home directories. - A refused destination names the directory at fault. A local `close` fails and keeps its bytes. A remote recording keeps its success and reports `script_ancestor_untrusted` as the `scriptDeliveryFailure` cause, and the next recorded action or `close` repeats the refusal. Choose a directory you own that only you can write. - With a local daemon, the script is written on the daemon host when the session closes. - With a remote daemon, outside a macOS app lease, the path is on your machine. The file appears when `open` returns, and each later recorded action in the session replaces it with the recording so far. `close` writes the final script there. A session that another process closes keeps the version from the last action. From 450a915cb1a49627bad8d2d84ace90910b78c9b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 16 Nov 2026 12:22:50 +0100 Subject: [PATCH 08/10] test(daemon): refuse a recording under a directory another user owns 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 --- .../session-script-writer-ancestry.test.ts | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts b/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts index b8121b051a..38e579911e 100644 --- a/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts +++ b/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts @@ -152,6 +152,49 @@ skipOnWindows('a recording refuses a destination inside a directory another user expect(fs.existsSync(destination)).toBe(false); }); +skipOnWindows('a recording refuses a directory another user made sticky and owns', () => { + const directory = root(); + // `chmod 1777` on a directory of THEIRS: the sticky bit keeps me from clearing their entries, and does + // nothing to stop them renaming the component my path runs through. + const team = path.join(directory, 'team'); + fs.mkdirSync(team); + fs.chmodSync(team, 0o1777); + const destination = path.join(team, 'journey.ad'); + vi.spyOn(process, 'getuid').mockReturnValue(currentUid === 65534 ? 65535 : 65534); + + const details = refusal(writerFor(directory).write(recordingTo(destination))); + + expect(details).toMatchObject({ + reason: 'script_ancestor_untrusted', + exposure: 'foreign_owned', + ancestor: team, + }); + expect(fs.readdirSync(team)).toEqual([]); +}); + +skipOnWindows('a recording refuses a shared directory another user claimed first', () => { + const directory = root(); + // The `mkdir -p /recordings` shape in a sticky shared directory: whoever creates it owns it, + // and the owner can swap it for one of their own whenever they like. + const tmp = path.join(directory, 'tmp'); + fs.mkdirSync(tmp); + fs.chmodSync(tmp, 0o1777); + const recordings = path.join(tmp, 'recordings'); + fs.mkdirSync(recordings); + fs.chmodSync(recordings, 0o755); + const destination = path.join(recordings, 'journey.ad'); + vi.spyOn(process, 'getuid').mockReturnValue(currentUid === 65534 ? 65535 : 65534); + + const details = refusal(writerFor(directory).write(recordingTo(destination))); + + expect(details).toMatchObject({ + reason: 'script_ancestor_untrusted', + exposure: 'foreign_owned', + ancestor: recordings, + }); + expect(fs.readdirSync(recordings)).toEqual([]); +}); + skipOnWindows('a recording refuses an ancestor swapped out for a symbolic link', () => { const directory = root(); const shared = sharedDirectory(path.join(directory, 'shared'), 0o777); From 546303c389a52df9533633618496dda38c8e2d48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 16 Nov 2026 13:11:42 +0100 Subject: [PATCH 09/10] fix(host-kit): judge every directory a script destination walks through 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 --- .../0016-active-session-script-publication.md | 17 +- .../session-script-writer-ancestry.test.ts | 52 ++++++ .../atomic-publish-ownership.test.ts | 13 +- packages/host-kit/src/file.ts | 8 - .../src/internal/atomic-file-ancestry.test.ts | 80 +++++++- packages/host-kit/src/internal/atomic-file.ts | 176 +++++++++++++----- .../daemon-artifacts-script-download.test.ts | 93 +++++++++ .../remote/src/session-script-destination.ts | 6 +- test/wire-compat/ledger.json | 2 +- website/docs/docs/remote-proxy.md | 7 +- website/docs/docs/replay-e2e.md | 8 +- 11 files changed, 382 insertions(+), 80 deletions(-) diff --git a/docs/adr/0016-active-session-script-publication.md b/docs/adr/0016-active-session-script-publication.md index b553319129..22ae230118 100644 --- a/docs/adr/0016-active-session-script-publication.md +++ b/docs/adr/0016-active-session-script-publication.md @@ -208,12 +208,23 @@ It adds no state name, command, or flag: - The daemon reports the `script-artifacts` capability in `/health`, through a proxy in its upstream health; the client refuses a remote `--save-script` before dispatch without it. The destination keeps local `--save-script` semantics (#4565): the client creates a missing parent directory, and neither the daemon nor the client publishes through a directory another local user can change. The rule closes the window with PERMISSIONS, not with timing. -A destination is accepted only when no other non-root local user can modify any directory on its fully resolved chain. Each directory must be owned by the current user or by root, and its mode must keep its contents closed to others. Once that holds, nobody can swap a component out or plant one, so the path that was judged is the path the publish reaches; nothing depends on when a directory was judged. -The chain is resolved first, so a symbolic link's target is judged under the same rule. A link is refused when another user could have placed it or could replace it: in a directory where others may add entries, only a link owned by the current user or root and held by the sticky bit is trusted. Root-owned system aliases (macOS `/tmp` to `/private/tmp`, `/var` to `/private/var`) keep working. -The sticky bit excuses a directory the chain passes THROUGH, when this user or root owns it, because it stops anyone but an entry's owner or root from replacing that entry; a sticky directory another user owns is refused, because those bits shield other users from that owner rather than the reverse. It never excuses creating the destination inside that directory, because anyone could create that name first. A group-writable directory the current user owns is accepted when its group is that user's own private group, which is the shape Ubuntu and Debian give home directories; this is the one place the rule reads `/etc/group` and `/etc/passwd`, and it fails closed when either file is unreadable. Residual limitation: a name service (LDAP or an NSS module) can add a member holding that primary GID without it appearing in `/etc/passwd`, so such a host can be refused a group-writable directory it appears to own. The fallback is a directory only the user can write. +A destination is accepted only when no other non-root local user can modify any directory the publish traverses. Each directory must be owned by the current user or by root, and its mode must keep its contents closed to others. Once that holds, nobody can swap a component out or plant one, so the path that was judged is the path the publish reaches; nothing depends on when a directory was judged. +Every directory the kernel traverses is judged, not only the final chain. Each existing prefix of the spelled path is expanded link by link, and the directory holding each link target is judged with it. Resolving only the final path is not enough: a plain directory under a shared one can hold a link to a private destination, so the final chain looks private while the ground the link stands on is shared, and a link whose target is another link never names the directory stepped through in between. Both are refused. A `..` component is judged too: it leaves a directory that is on the traversed chain whatever path it ends up spelling. +A symbolic link is refused when another user could have placed it or could replace it: in a directory where others may add entries, only a link owned by the current user or root and held by the sticky bit is trusted. Root-owned system aliases (macOS `/tmp` to `/private/tmp`, `/var` to `/private/var`) keep working. +The sticky bit excuses a directory the chain passes THROUGH, when this user or root owns it, because it stops anyone but an entry's owner or root from replacing that entry; a sticky directory another user owns is refused, because those bits shield other users from that owner rather than the reverse. It never excuses creating the destination inside that directory, because anyone could create that name first. A group-writable directory the current user owns is accepted when its group is that user's own private group, which is the shape Ubuntu and Debian give home directories; this is the one place the rule reads `/etc/group` and `/etc/passwd`, and it fails closed when either file is unreadable. EVERY group record carrying that numeric gid is read, because a directory group-writable by gid 1000 is writable by the members of each group that holds the number, however it is named: `ada:x:1000:` beside `team:x:1000:grace` reaches grace. Residual limitation, stated plainly because it cuts both ways: the two files are only this machine's own view, so a name service (LDAP or an NSS module) can hold a member of that gid, or a second group with the number, that never appears in them. Such a host can be refused a group-writable directory it genuinely owns, and it can also be accepted for one the name service has opened to someone else, because the rule cannot see that member. The fallback on such a host is a directory only the user can write, at any mode. The script file is created 0600, locally and remotely alike, so a recording is not world-readable in a directory that is merely shared. The publisher compares the destination directory's captured `dev:ino` before publishing. The ownership rule above already excludes anyone able to swap that directory, so the comparison is defense in depth against a host whose ownership or modes moved during the download, not the check that closes the window. Node exposes no `openat` or `renameat`, so publishing relative to a verified directory handle is not available without native code; the permissions rule is what substitutes for it. + +### What the guarantee does not cover + +The rule judges ownership bits, mode bits and link shape. Three things sit outside it, and no combination of them is a reason to expect confidentiality: + +- **ACLs.** macOS and Linux filesystem ACLs are consulted ahead of the mode bits, and the rule does not read them. A directory at 0700 can still grant `everyone` write through an ACL, letting another user plant or swap a component; a 0600 file can still inherit an `everyone` read entry, so the file's mode is not a promise about who can read it. Checking ACLs is deliberately not implemented. Callers who need that guarantee on such a host choose the destination's permissions and ACLs together. +- **Network filesystems.** NFS, SMB and FUSE mounts answer ownership, mode and link questions however the server pleases, and an unverified server can change any of them while the publish runs. Uids on a mount are usually not the uids on this host either. A script destination on a network mount is outside the guarantee. +- **Bind mounts and mounts in general.** A directory can be mounted over another after the judgment, and the publish writes into whatever stands there. The `dev:ino` comparison notices a replaced destination directory on the same route that captured its identity; it cannot notice a mount that was already there and was never judged. + +So the guarantee is: on a local filesystem with no ACLs on the traversed directories, no other non-root local user can steer where the recording is written or create that file. It is not a promise that nobody else can read the file. A local write fails with `script_ancestor_untrusted` or `script_ancestry_replaced`; a remote version keeps its command's success and carries that reason as the `scriptDeliveryFailure` cause. Known limitation (#4564): the RPC response is the contract for `scriptDeliveryFailure`; the SDK, CLI, and MCP results do not carry it yet, the SDK close drops its warnings, and a batch delivers no step script versions. Rejected: a remote `session save-script` download, because it added a second publication path and a retry protocol. diff --git a/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts b/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts index 38e579911e..5ffbde82a9 100644 --- a/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts +++ b/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts @@ -246,6 +246,58 @@ skipOnWindows('a recording refuses an ancestor swapped out for a writable direct expect(fs.readdirSync(work)).toEqual([]); }); +skipOnWindows('a recording refuses a private link standing on shared ground two levels up', () => { + // `/shared` is 0777 and not sticky, `/shared/mine` is 0700, and `mine/rec` links to a + // private directory. Every directory the destination's real path names is private, so only judging + // each prefix the kernel traverses sees that another local user owns the ground under `mine` and `rec`. + const directory = root(); + const shared = path.join(directory, 'shared'); + fs.mkdirSync(shared); + fs.chmodSync(shared, 0o777); + const mine = path.join(shared, 'mine'); + fs.mkdirSync(mine); + fs.chmodSync(mine, 0o700); + const privateWork = path.join(directory, 'private'); + fs.mkdirSync(privateWork); + fs.symlinkSync(privateWork, path.join(mine, 'rec')); + const destination = path.join(mine, 'rec', 'journey.ad'); + + const details = refusal(writerFor(directory).write(recordingTo(destination))); + + expect(details).toMatchObject({ + reason: 'script_ancestor_untrusted', + exposure: 'world_writable', + ancestor: shared, + }); + expect(fs.readdirSync(privateWork)).toEqual([]); +}); + +skipOnWindows('a recording refuses a chain that leaves a shared directory through a link', () => { + // `~/rec -> /srv/team/relay -> ~/chosen`. The team ground is 0777, and any teammate can swap the + // `relay` link for a target of their own, though the destination's real path never names it. + const directory = root(); + const home = path.join(directory, 'home'); + fs.mkdirSync(home); + const team = path.join(directory, 'srv', 'team'); + fs.mkdirSync(team, { recursive: true }); + fs.chmodSync(team, 0o777); + const chosen = path.join(directory, 'chosen'); + fs.mkdirSync(chosen); + fs.chmodSync(chosen, 0o700); + fs.symlinkSync(chosen, path.join(team, 'relay')); + fs.symlinkSync(path.join(team, 'relay'), path.join(home, 'rec')); + const destination = path.join(home, 'rec', 'journey.ad'); + + const details = refusal(writerFor(directory).write(recordingTo(destination))); + + expect(details).toMatchObject({ + reason: 'script_ancestor_untrusted', + exposure: 'world_writable', + ancestor: team, + }); + expect(fs.readdirSync(chosen)).toEqual([]); +}); + skipOnWindows('a recording still saves to a group-writable private-group home', () => { privateGroupDatabase(); const directory = root(); diff --git a/packages/daemon/src/server/__tests__/atomic-publish-ownership.test.ts b/packages/daemon/src/server/__tests__/atomic-publish-ownership.test.ts index 17ff81c0fb..9acb41916d 100644 --- a/packages/daemon/src/server/__tests__/atomic-publish-ownership.test.ts +++ b/packages/daemon/src/server/__tests__/atomic-publish-ownership.test.ts @@ -28,15 +28,10 @@ test('simple same-directory publishers use the shared atomic publish owner', () } }); -// A session script is published through the ancestry-owning entry point, not the plain one: the plain -// one writes to a destination another local user could have steered (#4565). -test('the session script publisher uses the destination-ancestry owner', () => { - const source = fs.readFileSync( - new URL('../../core/session-script-writer.ts', import.meta.url), - 'utf8', - ); - assert.match(source, /publishScriptFileSync/); -}); +// Which entry point the session script publisher dispatches through is proven by behaviour, not by its +// source text: `packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts` drives a real +// write and expects the typed ancestry refusals and the 0600 file, which only the destination-ancestry +// owner (`publishScriptFileSync`, #4565) produces. // The process lock publishes a file and reclaims a directory, which are two different // claims of ownership: only the first belongs to the publication owners above. diff --git a/packages/host-kit/src/file.ts b/packages/host-kit/src/file.ts index 31f9b39988..8779eccfb5 100644 --- a/packages/host-kit/src/file.ts +++ b/packages/host-kit/src/file.ts @@ -1,19 +1,11 @@ export { assertPrivateScriptDestination, isAtomicPublishTemporaryPath, - othersCreateEntriesIn, - privateGroupId, publishDirectoryIdentity, publishDurableFileSync, publishFileSync, publishScriptFileSync, - untrustedAncestryExposure, - untrustedLinkExposure, - type DirectoryAuthority, type DurableFilePublishMode, - type LinkAuthority, - type ScriptAncestryExposure, - type ScriptDestinationTrust, } from './internal/atomic-file.ts'; export { lstatIfPresent, diff --git a/packages/host-kit/src/internal/atomic-file-ancestry.test.ts b/packages/host-kit/src/internal/atomic-file-ancestry.test.ts index efdb75704d..fb08a57f3b 100644 --- a/packages/host-kit/src/internal/atomic-file-ancestry.test.ts +++ b/packages/host-kit/src/internal/atomic-file-ancestry.test.ts @@ -272,6 +272,51 @@ skipOnWindows('refuses a link standing in a private-mode directory another user expect(fs.readdirSync(mine)).toEqual([]); }); +skipOnWindows('refuses a private link standing on shared ground two levels up', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // `/shared` is 0777 and not sticky, `/shared/mine` is mine at 0700, and `mine/rec` is a + // link to my private directory. The final chain is all mine, and the link stands in ground only I can + // write, so neither the link rule nor the resolved-final-chain rule sees anything wrong. What they miss + // is that another local user owns the ground `mine` and `rec` stand on: they rename `mine` aside and + // put their own there, with a `rec` of their choosing. + const directory = root(); + const shared = directoryWith(path.join(directory, 'shared'), 0o777); + const mine = directoryWith(path.join(shared, 'mine'), 0o700); + const privateWork = directoryWith(path.join(directory, 'private'), 0o700); + fs.symlinkSync(privateWork, path.join(mine, 'rec')); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(mine, 'rec', 'journey.ad')), + 'world_writable', + shared, + ); + expect(fs.readdirSync(privateWork)).toEqual([]); +}); + +skipOnWindows('refuses a chain that leaves a shared directory through an intermediate link', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // `~/rec -> /srv/team/relay`, and `relay` is a link back into a directory of mine. Every directory the + // final chain names is trusted; the walk still passes through `/srv/team`, which the team can write, + // and its owner — or any teammate — can swap `relay` for a target of their own. + const directory = root(); + const home = path.join(directory, 'home'); + fs.mkdirSync(home); + const srv = path.join(directory, 'srv'); + const team = path.join(srv, 'team'); + fs.mkdirSync(team, { recursive: true }); + fs.chmodSync(team, 0o777); + const chosen = directoryWith(path.join(directory, 'chosen'), 0o700); + fs.symlinkSync(chosen, path.join(team, 'relay')); + fs.symlinkSync(path.join(team, 'relay'), path.join(home, 'rec')); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(home, 'rec', 'journey.ad')), + 'world_writable', + team, + ); + expect(fs.readdirSync(chosen)).toEqual([]); +}); + skipOnWindows('judges the directories a .. in the path walks through', () => { serveGroupDatabase(hostDatabase(currentGid, 4321)); // `/shared/work/../x/journey.ad` is a path a caller can pass. Resolving it first answers @@ -658,9 +703,42 @@ test('admits the group named after the user, holding only them, as their primary expect(privateGroupId(database(PRIVATE, PRIVATE_PASSWD), ADA)).toBe(1000); }); -test('admits it with root named among its members', () => { +test('admits root named among the members, the account the whole rule trusts', () => { expect( privateGroupId(database(['ada:x:1000:root'], ['ada:x:1000:1000:', 'root:x:0:0']), ADA), + ).toBe(1000); +}); + +test('refuses a second group carrying the same gid when it lists another user', () => { + // `ada:x:1000:` looks private on its own, and the group named after the user is the only one the + // exception used to read. A directory group-writable by gid 1000 is writable by grace too, because + // `team` carries the same number. + expect( + privateGroupId( + database( + ['ada:x:1000:', 'team:x:1000:grace'], + ['ada:x:1000:1000:', 'grace:x:1001:1001:', 'root:x:0:0'], + ), + ADA, + ), + ).toBeUndefined(); +}); + +test('admits a second group carrying the same gid when it reaches nobody else', () => { + expect( + privateGroupId( + database(['ada:x:1000:', 'ada-alias:x:1000:'], ['ada:x:1000:1000:', 'root:x:0:0']), + ADA, + ), + ).toBe(1000); +}); + +test('refuses it once a second group sharing the gid has another user as its primary group', () => { + expect( + privateGroupId( + database(['ada:x:1000:', 'team:x:1000:'], ['ada:x:1000:1000:', 'grace:x:1001:1000:']), + ADA, + ), ).toBeUndefined(); }); diff --git a/packages/host-kit/src/internal/atomic-file.ts b/packages/host-kit/src/internal/atomic-file.ts index ce61e0b9f3..8917796e6b 100644 --- a/packages/host-kit/src/internal/atomic-file.ts +++ b/packages/host-kit/src/internal/atomic-file.ts @@ -228,20 +228,101 @@ export function assertPrivateScriptDestination(destination: string, parentIdenti } const trust = readScriptTrust(); assertNoPlantedLink(destination, parent, trust); - const existing = deepestExistingDirectory(parent); - if (existing.real === undefined) return; - for (const ancestor of directoryChain(existing.real)) { - const stats = statDirectoryChain(ancestor); + const traversed = traversedDirectories(parent); + if (traversed.paths.length === 0) return; + for (const directory of traversed.paths) { + const stats = statDirectoryChain(directory); if (!stats) continue; const exposure = untrustedAncestryExposure(stats, trust); - if (exposure) throw scriptAncestryFailure(destination, ancestor, exposure); + if (exposure) throw scriptAncestryFailure(destination, directory, exposure); } // The script entry is created inside the deepest directory that exists, or below it through // directories that do not exist yet. Where other local users can add entries, one of them can add // this entry first and the recording is theirs, so the creation has to be refused. - const deepest = statDirectoryChain(existing.real); + const deepest = statDirectoryChain(traversed.deepest); if (deepest && othersCreateEntriesIn(deepest, trust)) { - throw scriptAncestryFailure(destination, existing.real, 'shared_parent'); + throw scriptAncestryFailure(destination, traversed.deepest, 'shared_parent'); + } +} + +/** Link hops one destination walk expands before it stops, in step with the kernel's own limit. */ +const MAX_SYMLINK_HOPS = 40; + +/** + * Every directory the kernel traverses to reach `parent`, judged nearest-first, without duplicates, and + * the deepest one that exists. + * + * Resolving only the deepest existing ancestor is not enough, and neither is one `realpath` of a path + * that runs through links: + * + * - A component that is a plain directory is traversed as it stands, so a link inside it can lead + * anywhere, and the directories above that plain component are reached by the publish even though the + * final chain looks entirely private: `/shared` at 0777 with `/shared/mine` at 0700 and + * `mine/rec` a link to a private directory names only trusted directories at its destination, while + * another local user owns the ground `mine` and `rec` stand on and can rename `mine` aside. So EVERY + * existing prefix of the spelled path is resolved, and the chain under each resolution is judged. + * - Where one link leads into another, `realpathSync` answers with the LAST target and names none of the + * directories stepped through on the way: `~/rec -> /srv/team/relay -> ~/chosen` reaches a private + * directory, and the team ground `relay` stands on never appears in the answer, though any teammate + * can swap that link for a target of their own. So a link hop also judges the directory holding its + * target, and the walk continues into the target. + */ +function traversedDirectories( + parent: string, +): Readonly<{ paths: readonly string[]; deepest: string }> { + const seen = new Set(); + const paths: string[] = []; + let deepest: string | undefined; + for (const prefix of directoryChain(parent)) { + let current = prefix; + // Each hop replaces one link with its target, so a link cycle cannot run the walk forever. The + // operating system applies a limit of the same order and refuses the publish when it is exceeded. + for (let hop = 0; hop <= MAX_SYMLINK_HOPS; hop += 1) { + const stats = lstatIfPresentSync(current); + if (stats === undefined) break; + if (!stats.isSymbolicLink()) { + const real = resolvedDirectory(current); + if (real === undefined) break; + deepest ??= real; + for (const ancestor of directoryChain(real)) { + if (seen.has(ancestor)) continue; + seen.add(ancestor); + paths.push(ancestor); + } + break; + } + const target = linkTarget(current); + // The kernel steps INTO the directory the target names, so that directory and everything above it + // are traversed whatever this link eventually resolves to. + const home = resolvedDirectory(parentDirectory(target)); + if (home !== undefined) { + for (const ancestor of directoryChain(home)) { + if (seen.has(ancestor)) continue; + seen.add(ancestor); + paths.push(ancestor); + } + } + current = target; + } + } + return { paths, deepest: deepest ?? parent }; +} + +/** Where a symbolic link points, made absolute the way the kernel reads it. */ +function linkTarget(link: string): string { + const target = fs.readlinkSync(link); + return path.isAbsolute(target) ? target : `${parentDirectory(link)}/${target}`; +} + +/** The directory `path` names once every link in it is expanded, or `undefined` when it is absent. */ +function resolvedDirectory(pathname: string): string | undefined { + if (lstatIfPresentSync(pathname) === undefined) return undefined; + try { + const real = fs.realpathSync(pathname); + return statDirectoryChain(real) ? real : undefined; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; + throw error; } } @@ -278,7 +359,7 @@ function assertNoPlantedLink( for (const ancestor of directoryChain(parent)) { const link = lstatIfPresentSync(ancestor); if (!link?.isSymbolicLink()) continue; - const home = lstatIfPresentSync(path.dirname(ancestor)); + const home = lstatIfPresentSync(parentDirectory(ancestor)); if (!home) continue; const exposure = untrustedLinkExposure( { uid: link.uid }, @@ -289,28 +370,6 @@ function assertNoPlantedLink( } } -/** - * The real path of the deepest directory `directory` names or leads to, or `undefined` when nothing of it - * exists to judge. A component that exists but resolves to nothing (a dangling link) is stepped over like - * one that is absent, so the walk never stops with nothing checked. - */ -function deepestExistingDirectory(directory: string): Readonly<{ real: string | undefined }> { - let current = directory; - for (;;) { - if (lstatIfPresentSync(current) !== undefined) { - try { - const real = fs.realpathSync(current); - if (statDirectoryChain(real)) return { real }; - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; - } - } - const parent = parentDirectory(current); - if (parent === current) return { real: undefined }; - current = parent; - } -} - /** * One directory's identity on its filesystem, for a caller that must publish into the same one it * created or checked. `undefined` when the directory is absent or is not a directory. @@ -338,18 +397,22 @@ type HostGroupDatabase = Readonly<{ * * - Both database files must have been READ. An unreadable file is not an empty one, and an empty * member list proves nothing. - * - The group must be the one this process holds as its PRIMARY group, which `getgid` answers from the - * kernel rather than from a file, and it must carry this user's name. - * - The group's own member list may name nobody but this user. macOS lists only part of `staff` in - * `/etc/group` while every local user holds it, so a name that is not this user's ends the claim - * rather than being looked up and forgiven. - * - No other record in the passwd file may hold this group as its primary group, and the caller's own - * record must exist there with this uid and this gid. + * - The gid must be the one this process holds as its PRIMARY group, which `getgid` answers from the + * kernel rather than from a file, and at least one record carrying that gid must bear this user's name. + * - EVERY record carrying that gid is read, because a directory group-writable by gid 1000 is writable + * by the members of each group holding the number, however they are named: `ada:x:1000:` beside + * `team:x:1000:grace` reaches grace. Any of them naming a member who is neither this user nor root + * ends the claim, without lookup or forgiveness — macOS lists only part of `staff` in `/etc/group` + * while every local user holds it. + * - No other passwd record may hold this gid as its primary group, and the caller's own record must + * exist there with this uid and this gid. * - * What this cannot establish: a name service (LDAP, NSS modules) can add a user whose primary group is - * this gid without that user ever appearing in `/etc/passwd`. A host configured that way can still be - * refused a group-writable destination it appears to own, which is the residual limitation the - * documentation names; the caller's fallback is a directory only they can write. + * What this cannot establish, stated plainly because it cuts BOTH ways: the two files are only this + * machine's own view. A name service (LDAP, an NSS module) can hold a member of this gid, or a second + * group with the number, that never appears in `/etc/passwd` or `/etc/group`. Such a host can be + * refused a group-writable directory it genuinely owns, and it can also be ACCEPTED for one the name + * service has opened to someone else — this rule cannot see that member and so cannot refuse it. The + * caller's answer on a name-service host is a directory only they can write, at any mode. */ export function privateGroupId( database: HostGroupDatabase, @@ -358,24 +421,37 @@ export function privateGroupId( const { uid, gid, name } = current; if (uid === undefined || gid === undefined || name === undefined) return undefined; if (!database.groups || !database.passwd) return undefined; - const record = database.groups.find((line) => line.split(':')[0] === name); - if (!record) return undefined; - const [, , rawGid, rawMembers = ''] = record.split(':'); - const privateGid = Number(rawGid); - if (!Number.isInteger(privateGid) || privateGid !== gid) return undefined; - const members = rawMembers.split(',').filter((member) => member.length > 0); - if (members.some((member) => member !== name)) return undefined; const own = database.passwd.find((line) => line.split(':')[0] === name); if (!own) return undefined; const [, , ownUid, ownGid] = own.split(':'); if (Number(ownUid) !== uid || Number(ownGid) !== gid) return undefined; + // EVERY record carrying this gid decides together: a directory group-writable by gid 1000 is writable + // by the members of each of them, however they are named. A group named after the user buys the + // exception only while no other record sharing the number reaches another user. + let namedForUser = false; + for (const line of database.groups) { + const [groupName, , rawGid, rawMembers = ''] = line.split(':'); + const recordGid = Number(rawGid); + if (rawGid === '' || !Number.isInteger(recordGid) || recordGid !== gid) continue; + if (groupName === name) namedForUser = true; + const members = rawMembers.split(',').filter((member) => member.length > 0); + if (members.some((member) => !memberIsTrusted(member, database, name))) return undefined; + } + if (!namedForUser) return undefined; const sharesPrimary = database.passwd.some((line) => { - const [other, , , otherGid] = line.split(':'); - return other !== name && Number(otherGid) === gid; + const [other, , rawOtherUid, rawOtherGid] = line.split(':'); + return other !== name && Number(rawOtherGid) === gid && Number(rawOtherUid) !== 0; }); return sharesPrimary ? undefined : gid; } +/** Whether a member of a candidate private group is the user or root, the two accounts the rule trusts. */ +function memberIsTrusted(member: string, database: HostGroupDatabase, name: string): boolean { + if (member === name) return true; + const record = database.passwd?.find((line) => line.split(':')[0] === member); + return record !== undefined && Number(record.split(':')[2]) === 0; +} + /** This process's identity and the private group its host databases establish, if any. */ function readScriptTrust(): ScriptDestinationTrust { return { diff --git a/packages/remote/src/__tests__/daemon-artifacts-script-download.test.ts b/packages/remote/src/__tests__/daemon-artifacts-script-download.test.ts index 1ba50bc410..a737885e2d 100644 --- a/packages/remote/src/__tests__/daemon-artifacts-script-download.test.ts +++ b/packages/remote/src/__tests__/daemon-artifacts-script-download.test.ts @@ -465,6 +465,99 @@ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0).each([ }, ); +test.skipIf(process.platform === 'win32')( + 'a remote recording creates a missing parent in a sticky directory and publishes there', + async () => { + // `open --save-script /tmp/rec/journey.ad` with `rec` absent is the ordinary shape, and `/tmp` is + // sticky. Judging the chain before the parent exists asks the question about `/tmp` and refuses a + // recording the local writer accepts, so the parent is created first on both routes (#4565). + const root = fs.realpathSync(mkdtempForTestSync('script-ancestry-mkdir-')); + const stateDir = path.join(root, 'state'); + const sticky = path.join(root, 'tmp'); + fs.mkdirSync(sticky); + fs.chmodSync(sticky, 0o1777); + const destination = path.join(sticky, 'recordings', 'journey.ad'); + const baseUrl = await artifactServer({ v1: { body: 'open Demo\n' } }); + + const { response } = await open(baseUrl, stateDir, destination); + + expect(response).toEqual( + expect.objectContaining({ + ok: true, + data: expect.not.objectContaining({ scriptDeliveryFailure: expect.anything() }), + }), + ); + expect(fs.readFileSync(destination, 'utf8')).toBe('open Demo\n'); + }, +); + +test.skipIf(process.platform === 'win32')( + 'a remote recording refuses a private link standing on shared ground two levels up', + async () => { + const root = fs.realpathSync(mkdtempForTestSync('script-ancestry-traverse-')); + const stateDir = path.join(root, 'state'); + const shared = path.join(root, 'shared'); + fs.mkdirSync(shared); + fs.chmodSync(shared, 0o777); + const mine = path.join(shared, 'mine'); + fs.mkdirSync(mine); + fs.chmodSync(mine, 0o700); + const privateWork = path.join(root, 'private'); + fs.mkdirSync(privateWork); + fs.symlinkSync(privateWork, path.join(mine, 'rec')); + const destination = path.join(mine, 'rec', 'journey.ad'); + const baseUrl = await artifactServer({ v1: { body: 'open Demo\n' } }); + + const { response } = await open(baseUrl, stateDir, destination); + + expect(response).toEqual( + expect.objectContaining({ + ok: true, + data: expect.objectContaining({ + scriptDeliveryFailure: expect.objectContaining({ + cause: 'script_ancestor_untrusted', + }), + }), + }), + ); + expect(fs.readdirSync(privateWork)).toEqual([]); + }, +); + +test.skipIf(process.platform === 'win32')( + 'a remote recording refuses a chain that leaves a shared directory through a link', + async () => { + const root = fs.realpathSync(mkdtempForTestSync('script-ancestry-relay-')); + const stateDir = path.join(root, 'state'); + const home = path.join(root, 'home'); + fs.mkdirSync(home); + const team = path.join(root, 'srv', 'team'); + fs.mkdirSync(team, { recursive: true }); + fs.chmodSync(team, 0o777); + const chosen = path.join(root, 'chosen'); + fs.mkdirSync(chosen); + fs.chmodSync(chosen, 0o700); + fs.symlinkSync(chosen, path.join(team, 'relay')); + fs.symlinkSync(path.join(team, 'relay'), path.join(home, 'rec')); + const destination = path.join(home, 'rec', 'journey.ad'); + const baseUrl = await artifactServer({ v1: { body: 'open Demo\n' } }); + + const { response } = await open(baseUrl, stateDir, destination); + + expect(response).toEqual( + expect.objectContaining({ + ok: true, + data: expect.objectContaining({ + scriptDeliveryFailure: expect.objectContaining({ + cause: 'script_ancestor_untrusted', + }), + }), + }), + ); + expect(fs.readdirSync(chosen)).toEqual([]); + }, +); + test.skipIf(process.platform === 'win32').each([ { name: 'a symbolic link planted where the script should land', diff --git a/packages/remote/src/session-script-destination.ts b/packages/remote/src/session-script-destination.ts index bd416b5247..6b79ac0a5d 100644 --- a/packages/remote/src/session-script-destination.ts +++ b/packages/remote/src/session-script-destination.ts @@ -201,9 +201,9 @@ async function publishScriptVersion( const pending = { named: false }; let staging: string | undefined; try { - // Asked before anything is created, so a destination another local user can steer leaves no - // directory behind (#4565). - assertPrivateScriptDestination(record.destination); + // The missing parent is created first, so this route judges the chain at the same point the local + // writer does: the rule needs the directory the entry is really created in, which does not exist + // until this line has run (#4565). await fs.promises.mkdir(path.dirname(record.destination), { recursive: true }); const allocated = await withRecordLock(file, async () => allocateStaging(file, record.destination), diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index cece9d2bd2..64bb24943c 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -214,7 +214,7 @@ "packages/daemon-contracts/src/daemon-resolution.ts#readDaemonCapabilities": "sha256:e410d36be74d307f7e5d8ddae63af5aae77f8eef77951ce9eeb7724f2fefae88", "packages/remote/src/daemon-artifacts.ts#downloadResponseArtifacts": "sha256:42d78f01311e3e0c5f9099ef72e3c6258241e66204747aa176a55cd5191a2145", "packages/remote/src/session-script-destination.ts#SessionScriptDelivery": "sha256:741fafbb8e2b43e2e967b2f4206f1d60017a636f63e3cde68b6258fd4efefa18", - "packages/remote/src/session-script-destination.ts#publishScriptVersion": "sha256:3406b96e254e85cd3e3f23b8b644f40d8d7268b2066696ff21516dabfa8ca14c", + "packages/remote/src/session-script-destination.ts#publishScriptVersion": "sha256:cc3b263e1a19cb76256217395f81f54e4fffa6a5755693e1efef1e5e931d50f6", "packages/remote/src/session-script-destination.ts#PublishOutcome": "sha256:a4ae6fc3298d3c560719591372edddbfa83ce749f4cf3f3e2ed1d8369313bd2d", "packages/remote/src/session-script-destination.ts#sendRemoteScriptOpen": "sha256:10ab07a6f276c7b03996c6b46fa218e03e7b1d21e2c95df5515dfb88095416b6", "packages/remote/src/session-script-destination.ts#RemoteEndpoint": "sha256:9c48e8e0ee14a25b85ebd930243fd263134836b35ecda55fb927919911263c15" diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 892d611545..aae60264a0 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -108,8 +108,11 @@ Outside a macOS app lease, a fresh `open --save-script=` records the sessi your machine. Each response that records an action returns a `session-script` artifact, and the client replaces the file with it. `close` returns the final script. The client writes only to the path that its own `open` named. If the file already exists, `open` fails unless you pass `--force`. -Every directory on the way to that path must be one that no other local user can change; see -[Record a replay script](replay-e2e.md#record-a-replay-script). +Every directory the write travels through must be one that no other local user can change; see +[Record a replay script](replay-e2e.md#record-a-replay-script). That check reads owners, permission +bits and link shape on your machine, so an access control list, a network mount, or a mount that +appears over a checked directory is outside it: the file is written at mode `0600`, but that is not +a promise that nobody else can read it. Choose a directory only you can write. The daemon must report the `script-artifacts` capability in its `/health` response; through a proxy, the upstream daemon's health response must report it. Otherwise `open --save-script` is refused before the session starts. diff --git a/website/docs/docs/replay-e2e.md b/website/docs/docs/replay-e2e.md index e3acf9d478..40d03dd9f5 100644 --- a/website/docs/docs/replay-e2e.md +++ b/website/docs/docs/replay-e2e.md @@ -70,10 +70,12 @@ To choose the output file, pass a path to `--save-script`: agent-device open Settings --platform ios --session e2e --save-script ./workflows/e2e-settings.ad ``` -- Missing parent directories are created. The script file itself is created so that only you can read it. -- Every directory on the way to the script must be one that no other local user can change. Each must be owned by you or by root, and its permissions must keep its contents closed to everyone else. Another local user who owns such a directory, or who can write in it, can replace a directory on the path or leave a symbolic link there, and the script then lands where they choose. +- Missing parent directories are created. The script file is created at mode `0600`, so its own permissions open it to nobody but you. What those permissions do not settle for you is listed under the limits below. +- Every directory the write travels through must be one that no other local user can change. Each must be owned by you or by root, and its permissions must keep its contents closed to everyone else. Another local user who owns such a directory, or who can write in it, can replace a directory on the path or leave a symbolic link there, and the script then lands where they choose. +- Directories between the path you typed and where it ends are checked too, not only the final result. A plain directory that is open to others can hold a link into a private directory, so the destination looks private while the ground the link stands on is shared, and a link that points at another link passes through a directory the final path never names. Both are refused. A `..` segment is checked too, including the directory it steps back out of. - The whole real path is checked, so a symbolic link to a shared directory is refused too. A link is refused if another user could have placed it, or could replace it: in a directory where others may add entries, only a link you or root own, held in place by the sticky bit, is trusted. Root-owned system links such as macOS `/tmp` and `/var` keep working. -- A directory you or root own may still be passed through when it carries the sticky bit (`chmod +t`) and is open to others, because that bit stops anyone but an entry's owner or root from replacing an entry: macOS `/tmp` works this way. A sticky directory owned by somebody else is refused — both bits shield other users from its owner, not the owner from you. The script is never created *inside* a directory others may add entries to: there, anyone could create your file's name first. A group-writable directory you own is accepted when its group is your own private group, the shape Ubuntu and Debian create for home directories. +- A directory you or root own may still be passed through when it carries the sticky bit (`chmod +t`) and is open to others, because that bit stops anyone but an entry's owner or root from replacing an entry: macOS `/tmp` works this way. A sticky directory owned by somebody else is refused — both bits shield other users from its owner, not the owner from you. The script is never created *inside* a directory others may add entries to: there, anyone could create your file's name first. A group-writable directory you own is accepted when its group is your own private group, the shape Ubuntu and Debian create for home directories. Every group carrying that group number is considered, so a second group with the same number that lists somebody else closes this exception. +- Limits. The checks read owners, permission bits and link shape, and three things sit outside them. An access control list is consulted before the permission bits, so a directory at `0700` can still grant everyone write through an ACL, and a file at `0600` can still grant everyone read; the checks do not read ACLs. On a network mount (NFS, SMB, FUSE), ownership and mode are whatever the server answers, and the user ids there are usually not the ones on this machine. A mount can also appear over a checked directory. So these checks mean that no other local user can steer where the recording is written on a local filesystem without ACLs on that path; they are not a promise that nobody else can read the file. On a host like that, choose a directory only you can write. - A refused destination names the directory at fault. A local `close` fails and keeps its bytes. A remote recording keeps its success and reports `script_ancestor_untrusted` as the `scriptDeliveryFailure` cause, and the next recorded action or `close` repeats the refusal. Choose a directory you own that only you can write. - With a local daemon, the script is written on the daemon host when the session closes. - With a remote daemon, outside a macOS app lease, the path is on your machine. The file appears when `open` returns, and each later recorded action in the session replaces it with the recording so far. `close` writes the final script there. A session that another process closes keeps the version from the last action. From 4964b4420444a84ce4fd5c2467c652c530cff048 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 16 Nov 2026 14:10:29 +0100 Subject: [PATCH 10/10] fix(host-kit): walk a script destination the way the kernel resolves it 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 --- .../0016-active-session-script-publication.md | 13 +- .../session-script-writer-ancestry.test.ts | 119 ++++- .../__tests__/session-script-writer.test.ts | 5 +- .../daemon/src/core/session-script-writer.ts | 43 +- .../atomic-publish-ownership.test.ts | 5 - .../__tests__/session-close-script.test.ts | 6 +- .../src/internal/atomic-file-ancestry.test.ts | 354 ++++++++----- .../atomic-file-private-group.test.ts | 134 +++++ packages/host-kit/src/internal/atomic-file.ts | 499 +++++++++++------- .../daemon-artifacts-script-download.test.ts | 104 ++++ .../test-kit/src/host-ownership.fixtures.ts | 27 + packages/test-kit/src/index.ts | 1 + website/docs/docs/replay-e2e.md | 6 +- 13 files changed, 937 insertions(+), 379 deletions(-) create mode 100644 packages/host-kit/src/internal/atomic-file-private-group.test.ts create mode 100644 packages/test-kit/src/host-ownership.fixtures.ts diff --git a/docs/adr/0016-active-session-script-publication.md b/docs/adr/0016-active-session-script-publication.md index 22ae230118..211c771bcf 100644 --- a/docs/adr/0016-active-session-script-publication.md +++ b/docs/adr/0016-active-session-script-publication.md @@ -209,9 +209,14 @@ It adds no state name, command, or flag: The destination keeps local `--save-script` semantics (#4565): the client creates a missing parent directory, and neither the daemon nor the client publishes through a directory another local user can change. The rule closes the window with PERMISSIONS, not with timing. A destination is accepted only when no other non-root local user can modify any directory the publish traverses. Each directory must be owned by the current user or by root, and its mode must keep its contents closed to others. Once that holds, nobody can swap a component out or plant one, so the path that was judged is the path the publish reaches; nothing depends on when a directory was judged. -Every directory the kernel traverses is judged, not only the final chain. Each existing prefix of the spelled path is expanded link by link, and the directory holding each link target is judged with it. Resolving only the final path is not enough: a plain directory under a shared one can hold a link to a private destination, so the final chain looks private while the ground the link stands on is shared, and a link whose target is another link never names the directory stepped through in between. Both are refused. A `..` component is judged too: it leaves a directory that is on the traversed chain whatever path it ends up spelling. -A symbolic link is refused when another user could have placed it or could replace it: in a directory where others may add entries, only a link owned by the current user or root and held by the sticky bit is trusted. Root-owned system aliases (macOS `/tmp` to `/private/tmp`, `/var` to `/private/var`) keep working. -The sticky bit excuses a directory the chain passes THROUGH, when this user or root owns it, because it stops anyone but an entry's owner or root from replacing that entry; a sticky directory another user owns is refused, because those bits shield other users from that owner rather than the reverse. It never excuses creating the destination inside that directory, because anyone could create that name first. A group-writable directory the current user owns is accepted when its group is that user's own private group, which is the shape Ubuntu and Debian give home directories; this is the one place the rule reads `/etc/group` and `/etc/passwd`, and it fails closed when either file is unreadable. EVERY group record carrying that numeric gid is read, because a directory group-writable by gid 1000 is writable by the members of each group that holds the number, however it is named: `ada:x:1000:` beside `team:x:1000:grace` reaches grace. Residual limitation, stated plainly because it cuts both ways: the two files are only this machine's own view, so a name service (LDAP or an NSS module) can hold a member of that gid, or a second group with the number, that never appears in them. Such a host can be refused a group-writable directory it genuinely owns, and it can also be accepted for one the name service has opened to someone else, because the rule cannot see that member. The fallback on such a host is a directory only the user can write, at any mode. +The walk emulates the kernel's own path resolution, because that is the set of directories that has to be safe. It starts at `/` (or at the process's resolved working directory for a relative spelling) with the spelled components on a queue, and takes one component at a time: `.` is skipped; `..` moves to the parent of the directory PHYSICALLY stood in, never to the parent of the spelled string; any other component is looked up with `lstat` inside that directory. A directory is judged and entered. A symbolic link is judged where it physically stands and its target's components go on the front of the queue, restarting from `/` for an absolute target. An absent component ends the walk, and the directory stood in is where the entry is created. Nothing calls `realpath`: it answers only with the final directory, so every directory stepped through on the way can disappear from the answer, and a JS `realpath` simplifies `..` lexically while the kernel applies it to the link's target. +Three shapes this closes, each of which an earlier shape of the rule accepted: +- 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: `rec -> shared/relay/sub`, `shared` at 0777 and not sticky, `shared/relay -> chosen`. Judging each lookup catches `shared`. +- A link inside a link target hides its own directory, and a followed link's owner was never asked: `~/rec -> /tmp/relay -> ~/chosen`, `relay` another user's file in sticky `/tmp`. Every followed link is judged with `untrustedLinkExposure` against the directory that holds it, at any depth, so spelling the target directly and arriving through a link answer the same way. +- `..` applies to the directory the walk is in: with `home/work -> priv/x` and `priv/y` at 0777, `home/work/../y` lands in `priv/y`, not in the private `home/y` the normalized spelling names. +A link hop count is kept and refused at `link_loop_exceeded` below the limit the kernel applies (macOS 32, Linux 40), so a walk that ran out of hops is a refusal rather than a pass, and a loop can never be trusted. A component that is neither a directory nor a link is refused as `not_a_directory`: the kernel cannot travel through it either. Root-owned system aliases (macOS `/tmp` to `/private/tmp`, `/var` to `/private/var`) keep working. +The sticky bit excuses a directory the walk passes THROUGH, when this user or root owns it, because it stops anyone but an entry's owner or root from replacing that entry; a sticky directory another user owns is refused, because those bits shield other users from that owner rather than the reverse. It never excuses creating the destination inside that directory, because anyone could create that name first. The link's own mode is never consulted: a link's bits say nothing about access on Linux, so what is judged is the directory the walk lands in, plus the ownership of the link and of the directory that holds it. +A group-writable directory the current user owns is accepted when its group is that user's own private group, which is the shape Ubuntu and Debian give home directories. This is the one place the rule reads `/etc/group` and `/etc/passwd`, and it is admitted only where those two files can be shown to be the whole story: `/etc/nsswitch.conf` must exist, be readable, and list `files` as the only source for both `passwd` and `group`. `systemd` is not admitted either, because `systemd-userdbd` answers membership from records those files never show. Otherwise the exception is refused and a group-writable directory is treated as shared. Every group record carrying that numeric gid is then read, because a directory group-writable by gid 1000 is writable by the members of each group that holds the number, however it is named: `ada:x:1000:` beside `team:x:1000:grace` reaches grace. The script file is created 0600, locally and remotely alike, so a recording is not world-readable in a directory that is merely shared. The publisher compares the destination directory's captured `dev:ino` before publishing. The ownership rule above already excludes anyone able to swap that directory, so the comparison is defense in depth against a host whose ownership or modes moved during the download, not the check that closes the window. Node exposes no `openat` or `renameat`, so publishing relative to a verified directory handle is not available without native code; the permissions rule is what substitutes for it. @@ -224,7 +229,7 @@ The rule judges ownership bits, mode bits and link shape. Three things sit outsi - **Network filesystems.** NFS, SMB and FUSE mounts answer ownership, mode and link questions however the server pleases, and an unverified server can change any of them while the publish runs. Uids on a mount are usually not the uids on this host either. A script destination on a network mount is outside the guarantee. - **Bind mounts and mounts in general.** A directory can be mounted over another after the judgment, and the publish writes into whatever stands there. The `dev:ino` comparison notices a replaced destination directory on the same route that captured its identity; it cannot notice a mount that was already there and was never judged. -So the guarantee is: on a local filesystem with no ACLs on the traversed directories, no other non-root local user can steer where the recording is written or create that file. It is not a promise that nobody else can read the file. +So the guarantee is: on a local filesystem with no ACLs on the directories the walk judges, no other non-root local user can steer where the recording is written or create that file. It is not a promise that nobody else can read the file. A local write fails with `script_ancestor_untrusted` or `script_ancestry_replaced`; a remote version keeps its command's success and carries that reason as the `scriptDeliveryFailure` cause. Known limitation (#4564): the RPC response is the contract for `scriptDeliveryFailure`; the SDK, CLI, and MCP results do not carry it yet, the SDK close drops its warnings, and a batch delivers no step script versions. Rejected: a remote `session save-script` download, because it added a second publication path and a retry protocol. diff --git a/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts b/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts index 5ffbde82a9..19578d277a 100644 --- a/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts +++ b/packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts @@ -1,9 +1,12 @@ import { afterEach, expect, test, vi } from 'vitest'; import fs from 'node:fs'; -// oxlint-disable-next-line no-restricted-imports -- the private-group fixture is named after os.userInfo()'s user, not a scratch path -import os from 'node:os'; import path from 'node:path'; -import { createLiveTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; +import { + FOREIGN_UID, + createLiveTestHostEnvironment, + mkdtempForTestSync, + serveHostOwnership, +} from '@agent-device/test-kit'; import { SessionScriptWriter } from '../session-script-writer.ts'; import { makeAuthoringSession } from '../../__tests__/support/session-factories.ts'; @@ -11,7 +14,8 @@ const hostCwd = createLiveTestHostEnvironment().cwd; const skipOnWindows = process.platform === 'win32' ? test.skip : test; const realReadFileSync = fs.readFileSync; -const currentUser = os.userInfo().username; +/** The account the fixtures name for this process, the same one the rule reads back out of passwd. */ +const currentUser = process.env.USER ?? ''; /** This process's ids. Windows has neither, and every test that uses them is skipped there. */ const currentUid = process.getuid?.() ?? -1; @@ -30,6 +34,8 @@ function serveGroupDatabase(groups: readonly string[], passwd: readonly string[] vi.spyOn(fs, 'readFileSync').mockImplementation(((file: unknown, options?: unknown) => { if (file === '/etc/group') return `${groups.join('\n')}\n`; if (file === '/etc/passwd') return `${passwd.join('\n')}\n`; + // The private-group exception is admitted only where the host's own databases are the whole story. + if (file === '/etc/nsswitch.conf') return 'passwd: files\ngroup: files\n'; return realReadFileSync(file as never, options as never) as never; }) as typeof fs.readFileSync); } @@ -144,11 +150,7 @@ skipOnWindows('a recording refuses a destination inside a directory another user const details = refusal(writerFor(directory).write(recordingTo(destination))); - expect(details).toMatchObject({ - reason: 'script_ancestor_untrusted', - exposure: 'foreign_owned', - ancestor: foreign, - }); + expect(details).toMatchObject({ reason: 'script_ancestor_untrusted', exposure: 'foreign_owned' }); expect(fs.existsSync(destination)).toBe(false); }); @@ -164,11 +166,7 @@ skipOnWindows('a recording refuses a directory another user made sticky and owns const details = refusal(writerFor(directory).write(recordingTo(destination))); - expect(details).toMatchObject({ - reason: 'script_ancestor_untrusted', - exposure: 'foreign_owned', - ancestor: team, - }); + expect(details).toMatchObject({ reason: 'script_ancestor_untrusted', exposure: 'foreign_owned' }); expect(fs.readdirSync(team)).toEqual([]); }); @@ -187,11 +185,7 @@ skipOnWindows('a recording refuses a shared directory another user claimed first const details = refusal(writerFor(directory).write(recordingTo(destination))); - expect(details).toMatchObject({ - reason: 'script_ancestor_untrusted', - exposure: 'foreign_owned', - ancestor: recordings, - }); + expect(details).toMatchObject({ reason: 'script_ancestor_untrusted', exposure: 'foreign_owned' }); expect(fs.readdirSync(recordings)).toEqual([]); }); @@ -205,7 +199,11 @@ skipOnWindows('a recording refuses an ancestor swapped out for a symbolic link', const details = refusal(writerFor(directory).write(recordingTo(destination))); - expect(details).toMatchObject({ reason: 'script_ancestor_untrusted', exposure: 'planted_link' }); + // The shared ground itself is the first exposure: anyone can rename `work` aside there, sticky or not. + expect(details).toMatchObject({ + reason: 'script_ancestor_untrusted', + exposure: 'world_writable', + }); expect(fs.readdirSync(attacker)).toEqual([]); }); @@ -298,6 +296,87 @@ skipOnWindows('a recording refuses a chain that leaves a shared directory throug expect(fs.readdirSync(chosen)).toEqual([]); }); +skipOnWindows('a recording refuses the directory a .. steps back into', () => { + // `home/work -> priv/x`, and `priv/y` at 0777 while `home/y` is private. Normalizing the spelling first + // answers `home/y`, so it accepts a write that the kernel lands in `priv/y`, where any local user can + // take the recording. + const directory = root(); + const home = path.join(directory, 'home'); + fs.mkdirSync(home); + fs.chmodSync(home, 0o700); + const priv = path.join(directory, 'priv'); + const privX = path.join(priv, 'x'); + fs.mkdirSync(privX, { recursive: true }); + const privY = path.join(priv, 'y'); + fs.mkdirSync(privY); + fs.chmodSync(privY, 0o777); + fs.mkdirSync(path.join(home, 'y')); + fs.symlinkSync(privX, path.join(home, 'work')); + const destination = `${home}/work/../y/journey.ad`; + + const details = refusal(writerFor(directory).write(recordingTo(destination))); + + expect(details).toMatchObject({ + reason: 'script_ancestor_untrusted', + exposure: 'world_writable', + ancestor: privY, + }); + expect(fs.readdirSync(privY)).toEqual([]); +}); + +skipOnWindows('a recording refuses the ground a link target crosses on the way in', () => { + // `home/rec -> /shared/relay/sub`, with `shared` at 0777 and not sticky and `shared/relay` a link + // into a directory of mine. Every directory at the destination looks private; only walking the target + // component by component shows that getting there crossed `shared`, where any other local user can swap + // `relay` for one of their own. + const directory = root(); + const shared = sharedDirectory(path.join(directory, 'shared'), 0o777); + const relayTarget = path.join(directory, 'chosen'); + fs.mkdirSync(relayTarget); + fs.chmodSync(relayTarget, 0o700); + fs.symlinkSync(relayTarget, path.join(shared, 'relay')); + const sub = path.join(relayTarget, 'sub'); + fs.mkdirSync(sub); + const home = path.join(directory, 'home'); + fs.mkdirSync(home); + fs.chmodSync(home, 0o700); + fs.symlinkSync(path.join(shared, 'relay', 'sub'), path.join(home, 'rec')); + const destination = path.join(home, 'rec', 'journey.ad'); + + const details = refusal(writerFor(directory).write(recordingTo(destination))); + + expect(details).toMatchObject({ + reason: 'script_ancestor_untrusted', + exposure: 'world_writable', + ancestor: shared, + }); + expect(fs.readdirSync(relayTarget)).toEqual(['sub']); +}); + +skipOnWindows('a recording refuses a link another local user owns on the way in', () => { + // `~/rec -> /tmp/relay -> ~/chosen`, with `relay` another user's file in a sticky shared + // directory: they can unlink it and leave one of their own, and the second hop is theirs to choose. + const directory = root(); + const home = path.join(directory, 'home'); + fs.mkdirSync(home); + const chosen = path.join(directory, 'chosen'); + fs.mkdirSync(chosen); + const relay = path.join(directory, 'relay'); + fs.symlinkSync(chosen, relay); + const tmp = path.join(directory, 'tmp'); + fs.mkdirSync(tmp); + fs.chmodSync(tmp, 0o1777); + fs.renameSync(relay, path.join(tmp, 'relay')); + fs.symlinkSync(path.join(tmp, 'relay'), path.join(home, 'rec')); + const destination = path.join(home, 'rec', 'journey.ad'); + serveHostOwnership({ [path.join(tmp, 'relay')]: FOREIGN_UID }); + + const details = refusal(writerFor(directory).write(recordingTo(destination))); + + expect(details).toMatchObject({ reason: 'script_ancestor_untrusted', exposure: 'planted_link' }); + expect(fs.readdirSync(chosen)).toEqual([]); +}); + skipOnWindows('a recording still saves to a group-writable private-group home', () => { privateGroupDatabase(); const directory = root(); diff --git a/packages/daemon/src/core/__tests__/session-script-writer.test.ts b/packages/daemon/src/core/__tests__/session-script-writer.test.ts index 054b1ce2e0..7d0ae670d3 100644 --- a/packages/daemon/src/core/__tests__/session-script-writer.test.ts +++ b/packages/daemon/src/core/__tests__/session-script-writer.test.ts @@ -696,8 +696,11 @@ test('an ordinary (non-repair) recording now refuses an existing target too (beh test('an ordinary recording returns a filesystem write failure as a typed error, never a quiet skip', () => { const root = mkdtempForTestSync('agent-device-script-writer-ordinary-fs-failure-'); const writer = new SessionScriptWriter(path.join(root, 'sessions'), hostCwd); + // A directory this user owns but cannot write: the ancestry rule has nothing to refuse there, so the + // failure the caller sees is the filesystem's own, not an ancestry verdict. const blocker = path.join(root, 'blocker'); - fs.writeFileSync(blocker, ''); + fs.mkdirSync(blocker); + fs.chmodSync(blocker, 0o500); const outPath = path.join(blocker, 'flow.ad'); const session = makeAuthoringSession('default', { scriptPublication: authoringPublication('armed', { path: outPath }), diff --git a/packages/daemon/src/core/session-script-writer.ts b/packages/daemon/src/core/session-script-writer.ts index 9b60e608aa..0d26cfed63 100644 --- a/packages/daemon/src/core/session-script-writer.ts +++ b/packages/daemon/src/core/session-script-writer.ts @@ -232,21 +232,40 @@ function handleSessionScriptWriteFailure(params: { return { written: false, error: toOrdinaryWriteFailure(error, scriptPath) }; } -function toOrdinaryWriteFailure(error: unknown, scriptPath: string | undefined): AppError { - if (error instanceof AppError) return error; +/** + * A filesystem failure that has to reach the caller as its own typed error: an ordinary recording + * carries `script_write_failed` with the path it could not be written to, and both name what was being + * written, because the same writer publishes a recording and a healed repair. + */ +function toScriptWriteFailure( + error: unknown, + scriptPath: string | undefined, + subject: Readonly<{ noun: string; hint: string; reportsPath?: boolean }>, +): AppError { const detail = error instanceof Error ? error.message : String(error); + const where = scriptPath === undefined ? '' : ` to ${scriptPath}`; return new AppError( 'COMMAND_FAILED', - `Failed to write the session script${scriptPath ? ` to ${scriptPath}` : ''}: ${detail}`, + `Failed to write the ${subject.noun}${where}: ${detail}`, { - reason: 'script_write_failed', - ...(scriptPath ? { path: scriptPath } : {}), - hint: 'Check the target path and its permissions, then re-record with open --save-script.', + ...(subject.reportsPath === true && scriptPath !== undefined + ? { reason: 'script_write_failed' as const, path: scriptPath } + : {}), + hint: subject.hint, }, error, ); } +function toOrdinaryWriteFailure(error: unknown, scriptPath: string | undefined): AppError { + if (error instanceof AppError) return error; + return toScriptWriteFailure(error, scriptPath, { + noun: 'session script', + reportsPath: true, + hint: 'Check the target path and its permissions, then re-record with open --save-script.', + }); +} + /** * ADR 0012 decision 6 (BLOCKER 2c): normalizes a repair-commit failure into a * distinct, surfaceable AppError. A no-clobber refusal or a bare-`@ref` failure @@ -256,14 +275,10 @@ function toOrdinaryWriteFailure(error: unknown, scriptPath: string | undefined): */ function toRepairCommitFailure(error: unknown, scriptPath: string | undefined): AppError { if (error instanceof AppError) return error; - const detail = error instanceof Error ? error.message : String(error); - return new AppError( - 'COMMAND_FAILED', - `Failed to write the healed script${scriptPath ? ` to ${scriptPath}` : ''}: ${detail}`, - { - hint: 'The repair transaction completed but the healed .ad could not be published; check the target path and permissions, then retry close --save-script.', - }, - ); + return toScriptWriteFailure(error, scriptPath, { + noun: 'healed script', + hint: 'The repair transaction completed but the healed .ad could not be published; check the target path and permissions, then retry close --save-script.', + }); } /** diff --git a/packages/daemon/src/server/__tests__/atomic-publish-ownership.test.ts b/packages/daemon/src/server/__tests__/atomic-publish-ownership.test.ts index 9acb41916d..84a5d57d70 100644 --- a/packages/daemon/src/server/__tests__/atomic-publish-ownership.test.ts +++ b/packages/daemon/src/server/__tests__/atomic-publish-ownership.test.ts @@ -28,11 +28,6 @@ test('simple same-directory publishers use the shared atomic publish owner', () } }); -// Which entry point the session script publisher dispatches through is proven by behaviour, not by its -// source text: `packages/daemon/src/core/__tests__/session-script-writer-ancestry.test.ts` drives a real -// write and expects the typed ancestry refusals and the 0600 file, which only the destination-ancestry -// owner (`publishScriptFileSync`, #4565) produces. - // The process lock publishes a file and reclaims a directory, which are two different // claims of ownership: only the first belongs to the publication owners above. test('the process lock publishes its owner record without publishing files by hand', () => { diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-script.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-script.test.ts index 0b38fb0b83..42466b9f80 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-script.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-script.test.ts @@ -195,9 +195,11 @@ test('#1533: an ordinary armed authoring session still publishes on bare close', test('ordinary close reports a filesystem failure of its script write instead of a quiet success', () => { const root = mkdtempForTestSync('agent-device-session-close-script-fs-'); roots.push(root); - // A regular file where the target directory must be: publishing into it fails with ENOTDIR. + // A directory this user owns but cannot write: publishing into it fails with EACCES, and the ancestry + // rule has nothing to refuse there, so the caller sees the filesystem's own failure. const blocker = path.join(root, 'blocker'); - fs.writeFileSync(blocker, ''); + fs.mkdirSync(blocker); + fs.chmodSync(blocker, 0o500); const targetPath = path.join(blocker, 'flow.ad'); const { req, ref, sessionStore } = setup( 'fs-failure', diff --git a/packages/host-kit/src/internal/atomic-file-ancestry.test.ts b/packages/host-kit/src/internal/atomic-file-ancestry.test.ts index fb08a57f3b..54314a81ac 100644 --- a/packages/host-kit/src/internal/atomic-file-ancestry.test.ts +++ b/packages/host-kit/src/internal/atomic-file-ancestry.test.ts @@ -1,18 +1,16 @@ import { afterEach, expect, test, vi } from 'vitest'; import fs from 'node:fs'; -// oxlint-disable-next-line no-restricted-imports -- the fixture's private group is named after os.userInfo()'s user, not a scratch path -import os from 'node:os'; import path from 'node:path'; import { AppError } from '@agent-device/kernel/errors'; import { mkdtempForTestSync } from './tmp-dir.fixtures.ts'; import { assertPrivateScriptDestination, othersCreateEntriesIn, - privateGroupId, publishDirectoryIdentity, publishScriptFileSync, untrustedAncestryExposure, untrustedLinkExposure, + MAX_SCRIPT_PATH_LINK_HOPS, type DirectoryAuthority, } from './atomic-file.ts'; @@ -22,10 +20,16 @@ const skipOnWindows = process.platform === 'win32' ? test.skip : test; type Database = Readonly<{ groups: readonly string[] | undefined; passwd: readonly string[] | undefined; + /** `undefined` means "only files"; an empty array means "the file cannot be read". */ + nsswitch?: readonly string[] | undefined; }>; const realReadFileSync = fs.readFileSync; -const currentUser = os.userInfo().username; +/** + * The account the fixture's databases name for this process. `readCurrentUser()` reads it from + * `passwdFile` below, so the fixture and the rule agree without a second host lookup. + */ +const currentUser = process.env.USER ?? ''; /** The unmocked `stat` calls, so a second fixture here never wraps the first one's mock. */ const realLstatSync = fs.lstatSync.bind(fs); const realStatSync = fs.statSync.bind(fs); @@ -52,15 +56,24 @@ function serveGroupDatabase(database: Database): void { if (!database.passwd) throw new Error('simulated unreadable passwd file'); return `${database.passwd.join('\n')}\n`; } + if (file === '/etc/nsswitch.conf') return nsswitchContents(database.nsswitch); return realReadFileSync(file as never, options as never) as never; }) as typeof fs.readFileSync); } +/** The name-service lines of the fixture host: `files` only, unless the test asks for more. */ +function nsswitchContents(sources: readonly string[] | undefined): string { + if (sources === undefined) return 'passwd: files\ngroup: files\n'; + if (sources.length === 0) throw new Error('simulated unreadable nsswitch.conf'); + return `${sources.join('\n')}\n`; +} + /** This host's user with a group of their own, and a team group that holds someone else. */ function hostDatabase(privateGid: number, sharedGid: number): Database { return { groups: ['root:x:0:root', `${currentUser}:x:${privateGid}:`, `team:x:${sharedGid}:ada`], passwd: [`root:x:0:0`, `${currentUser}:x:${currentUid}:${privateGid}:`], + nsswitch: undefined, }; } @@ -104,15 +117,6 @@ function directoryWith(directory: string, mode: number, gid = currentGid): strin return directory; } -/** - * Runs the rule as a different local user, so the ownership checks are exercised against real - * directories owned by this test's actual user. Nothing else about the process moves: the modes stay - * what they are on disk. - */ -function asAnotherLocalUser(): void { - vi.spyOn(process, 'getuid').mockReturnValue(currentUid === 65534 ? 65535 : 65534); -} - function publish(destination: string, parentIdentity?: string): void { publishScriptFileSync({ destination, @@ -266,8 +270,8 @@ skipOnWindows('refuses a link standing in a private-mode directory another user expectUntrusted( () => assertPrivateScriptDestination(path.join(teammate, 'link', 'journey.ad')), - 'planted_link', - path.join(teammate, 'link'), + 'foreign_owned', + teammate, ); expect(fs.readdirSync(mine)).toEqual([]); }); @@ -317,25 +321,196 @@ skipOnWindows('refuses a chain that leaves a shared directory through an interme expect(fs.readdirSync(chosen)).toEqual([]); }); -skipOnWindows('judges the directories a .. in the path walks through', () => { +skipOnWindows('judges the directory a .. steps back into', () => { serveGroupDatabase(hostDatabase(currentGid, 4321)); - // `/shared/work/../x/journey.ad` is a path a caller can pass. Resolving it first answers - // `/shared/x/journey.ad`, which is a DIFFERENT directory from the one that receives the file: - // the kernel walks `work` into the link's target and steps back from THERE, so the entry is created - // beside that target. The rule has to judge the components it walked, so the link is refused here. + // `/private/link` points at `/elsewhere/dir`, and the caller spells `/link/../x`. + // The kernel walks `link` into its target and steps back from THERE, so the entry is created in + // `/elsewhere`, not in `/private`. Normalizing the spelling first would answer + // `/private/x` and judge the wrong directory: `` is open to others, `` is not. + const directory = root(); + const privateHome = directoryWith(path.join(directory, 'private'), 0o700); + const elsewhere = directoryWith(path.join(directory, 'elsewhere'), 0o777); + const dir = path.join(elsewhere, 'dir'); + fs.mkdirSync(dir); + fs.symlinkSync(dir, path.join(privateHome, 'link')); + + expectUntrusted( + () => assertPrivateScriptDestination(`${privateHome}/link/../x/journey.ad`), + 'world_writable', + elsewhere, + ); + expect(fs.readdirSync(dir)).toEqual([]); +}); + +skipOnWindows('refuses the ground under a link that leads into a shared directory', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // `/shared` is 0777 and not sticky, `/home/rec` is a link spelled `shared/mine/relay/subdir` + // whose `relay` is a link back into a private directory. Nothing at the destination looks wrong: the + // final chain is `/shared/mine/chosen/subdir`, and every one of those is private-looking. What + // the walk sees is that getting there crossed `/shared`, where any other local user can rename + // `mine` aside and put their own `relay` under it. const directory = root(); const shared = directoryWith(path.join(directory, 'shared'), 0o777); - const published = directoryWith(path.join(directory, 'published'), 0o700); - const attacker = path.join(published, 'attacker'); - fs.mkdirSync(attacker); - fs.symlinkSync(attacker, path.join(shared, 'work')); + const mine = directoryWith(path.join(shared, 'mine'), 0o700); + const chosen = directoryWith(path.join(directory, 'chosen'), 0o700); + fs.symlinkSync(chosen, path.join(mine, 'relay')); + const home = directoryWith(path.join(directory, 'home'), 0o700); + fs.symlinkSync(path.join(shared, 'mine', 'relay', 'subdir'), path.join(home, 'rec')); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(home, 'rec', 'journey.ad')), + 'world_writable', + shared, + ); + expect(fs.readdirSync(chosen)).toEqual([]); +}); + +skipOnWindows('refuses the spelled spelling of a link the walk also follows', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // The same target reached two ways has to answer the same way: spelling the shared directory out is + // refused, so arriving at it through a link cannot be accepted. + const directory = root(); + const shared = directoryWith(path.join(directory, 'shared'), 0o777); + const home = directoryWith(path.join(directory, 'home'), 0o700); + const work = path.join(home, 'work'); + fs.mkdirSync(work); + fs.symlinkSync(shared, path.join(home, 'rec')); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(home, 'rec', 'journey.ad')), + 'world_writable', + shared, + ); + expectUntrusted( + () => assertPrivateScriptDestination(path.join(shared, 'journey.ad')), + 'world_writable', + shared, + ); +}); + +skipOnWindows('applies .. to the directory the walk is in, not to the spelling', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // `home/work -> priv/x`, `priv/y` is open to others, `home/y` is private. A lexical simplification of + // the spelling answers `home/y`, which is safe, so it accepts a write that lands in `priv/y`, where any + // local user can take the file. The kernel steps into the link and steps back from its TARGET. + const directory = root(); + const home = directoryWith(path.join(directory, 'home'), 0o700); + const priv = directoryWith(path.join(directory, 'priv'), 0o700); + const privX = path.join(priv, 'x'); + fs.mkdirSync(privX); + const privY = directoryWith(path.join(priv, 'y'), 0o777); + fs.mkdirSync(path.join(home, 'y')); + fs.symlinkSync(privX, path.join(home, 'work')); expectUntrusted( - () => assertPrivateScriptDestination(`${shared}/work/../x/journey.ad`), + () => assertPrivateScriptDestination(`${home}/work/../y/journey.ad`), + 'world_writable', + privY, + ); + expect(fs.readdirSync(privY)).toEqual([]); +}); + +skipOnWindows('refuses a link whose target stands in ground another local user owns', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // `~/rec -> /tmp/relay -> ~/chosen`, and `relay` is another user's file in a sticky shared + // directory. Sticky or not, they can unlink it and put one of their own there, so the second hop is + // theirs to choose. The judgment the expanded hop used to skip is the one on the link itself. + const directory = root(); + const home = directoryWith(path.join(directory, 'home'), 0o700); + const chosen = directoryWith(path.join(directory, 'chosen'), 0o700); + const tmp = directoryWith(path.join(directory, 'tmp'), 0o1777); + const relay = path.join(tmp, 'relay'); + fs.symlinkSync(chosen, relay); + serveOwnership({ [tmp]: 0, [relay]: FOREIGN_UID }); + fs.symlinkSync(relay, path.join(home, 'rec')); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(home, 'rec', 'journey.ad')), 'planted_link', - path.join(shared, 'work'), + relay, + ); + expect(fs.readdirSync(chosen)).toEqual([]); +}); + +skipOnWindows('follows a link whatever mode it carries, judging the directory it lands in', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + // A link's own mode means nothing for access: the kernel reads its target. An alias at 0777 leading to + // a directory only this user can write is therefore safe, and the refusal has to come from the + // directory, not from the link's bits. + const directory = root(); + const real = directoryWith(path.join(directory, 'real'), 0o700); + const alias = path.join(directory, 'current'); + fs.symlinkSync(real, alias); + // `lchmod` on a link is what a mode-carrying alias looks like; where the host reports one mode for all + // links, as Linux does, the walk has to be moved by the directory it lands in either way. + try { + fs.lchmodSync(alias, 0o777); + } catch { + /* this host gives every link the same mode */ + } + + publish(path.join(alias, 'journey.ad')); + + expect(fs.readFileSync(path.join(real, 'journey.ad'), 'utf8')).toBe('context\n'); +}); + +skipOnWindows('refuses a link loop instead of trusting where the walk ran out', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const directory = root(); + const work = directoryWith(path.join(directory, 'work'), 0o700); + const loop = path.join(work, 'loop'); + fs.symlinkSync(loop, loop); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(loop, 'journey.ad')), + 'link_loop_exceeded', + loop, + ); + expect(fs.readdirSync(work)).toEqual(['loop']); +}); + +skipOnWindows('follows exactly as many link hops as the walk allows, and refuses one more', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const directory = root(); + const work = directoryWith(path.join(directory, 'work'), 0o700); + const real = directoryWith(path.join(directory, 'real'), 0o700); + // `link0 -> link1 -> ... -> `, so the walk expands `count` links to reach the destination. + const chain = (count: number): string => { + let next = real; + for (let hop = count - 1; hop >= 0; hop -= 1) { + const link = path.join(work, `link${hop}`); + fs.rmSync(link, { force: true }); + fs.symlinkSync(next, link); + next = link; + } + return next; + }; + + publish(path.join(chain(MAX_SCRIPT_PATH_LINK_HOPS), 'journey.ad')); + expect(fs.existsSync(path.join(real, 'journey.ad'))).toBe(true); + fs.rmSync(path.join(real, 'journey.ad'), { force: true }); + + expectUntrusted( + () => + assertPrivateScriptDestination(path.join(chain(MAX_SCRIPT_PATH_LINK_HOPS + 1), 'journey.ad')), + 'link_loop_exceeded', + path.join(work, `link${MAX_SCRIPT_PATH_LINK_HOPS}`), + ); + expect(fs.readdirSync(real)).toEqual([]); +}); + +skipOnWindows('refuses a path component that cannot carry a publish', () => { + serveGroupDatabase(hostDatabase(currentGid, 4321)); + const directory = root(); + const work = directoryWith(path.join(directory, 'work'), 0o700); + const blocker = path.join(work, 'blocker'); + fs.writeFileSync(blocker, 'not a directory\n'); + + expectUntrusted( + () => assertPrivateScriptDestination(path.join(blocker, 'journey.ad')), + 'not_a_directory', + blocker, ); - expect(fs.readdirSync(attacker)).toEqual([]); }); skipOnWindows('refuses a directory its owner opened up while the file was staged', () => { @@ -404,8 +579,10 @@ skipOnWindows('follows a symbolic link inside a directory only this user can wri expect(fs.existsSync(path.join(real, 'journey.ad'))).toBe(true); }); -skipOnWindows('refuses a symbolic link planted in a directory others can add entries to', () => { +skipOnWindows('refuses a link planted in a directory others can add entries to', () => { serveGroupDatabase(hostDatabase(currentGid, 4321)); + // The shared ground is refused where the walk enters it, one step before the link inside it: that + // directory is itself the exposure, since anyone can rename `work` aside as well as plant it. const directory = root(); const shared = directoryWith(path.join(directory, 'shared'), 0o777); const attacker = path.join(directory, 'attacker'); @@ -414,8 +591,8 @@ skipOnWindows('refuses a symbolic link planted in a directory others can add ent expectUntrusted( () => assertPrivateScriptDestination(path.join(shared, 'work', 'journey.ad')), - 'planted_link', - path.join(shared, 'work'), + 'world_writable', + shared, ); expect(fs.readdirSync(attacker)).toEqual([]); }); @@ -462,17 +639,23 @@ skipOnWindows( 'refuses a symbolic link another local user owns in a sticky shared directory', () => { serveGroupDatabase(hostDatabase(currentGid, 4321)); - const shared = directoryWith(path.join(root(), 'shared'), 0o1777); - const attacker = path.join(root(), 'attacker'); + // The link's OWNER is the whole question, so it is the fixture's: root holds the sticky directory and + // somebody else owns the link. Moving only the caller's uid would decide the test by the accident of + // who runs the suite, and would say nothing when the suite runs as root. + const directory = root(); + const shared = directoryWith(path.join(directory, 'shared'), 0o1777); + const attacker = path.join(directory, 'attacker'); fs.mkdirSync(attacker); - fs.symlinkSync(attacker, path.join(shared, 'work')); - asAnotherLocalUser(); + const link = path.join(shared, 'work'); + fs.symlinkSync(attacker, link); + serveOwnership({ [shared]: 0, [link]: FOREIGN_UID }); expectUntrusted( () => assertPrivateScriptDestination(path.join(shared, 'work', 'journey.ad')), 'planted_link', - path.join(shared, 'work'), + link, ); + expect(fs.readdirSync(attacker)).toEqual([]); }, ); @@ -687,104 +870,3 @@ test('names no directory this user or root owns that others cannot write', () => expect(othersCreateEntriesIn(directoryOf({ uid: 0, mode: 0o755 }), TRUST)).toBe(false); expect(othersCreateEntriesIn(directoryOf({ uid: 0, mode: 0o1777 }), TRUST)).toBe(true); }); - -// --- privateGroupId: the one group shape the exception admits --- - -const ADA = { uid: 1000, gid: 1000, name: 'ada' }; - -function database(groups: readonly string[] | undefined, passwd: readonly string[] | undefined) { - return { groups, passwd }; -} - -const PRIVATE = ['ada:x:1000:', 'staff:x:20:root']; -const PRIVATE_PASSWD = ['ada:x:1000:1000:', 'root:x:0:0']; - -test('admits the group named after the user, holding only them, as their primary group', () => { - expect(privateGroupId(database(PRIVATE, PRIVATE_PASSWD), ADA)).toBe(1000); -}); - -test('admits root named among the members, the account the whole rule trusts', () => { - expect( - privateGroupId(database(['ada:x:1000:root'], ['ada:x:1000:1000:', 'root:x:0:0']), ADA), - ).toBe(1000); -}); - -test('refuses a second group carrying the same gid when it lists another user', () => { - // `ada:x:1000:` looks private on its own, and the group named after the user is the only one the - // exception used to read. A directory group-writable by gid 1000 is writable by grace too, because - // `team` carries the same number. - expect( - privateGroupId( - database( - ['ada:x:1000:', 'team:x:1000:grace'], - ['ada:x:1000:1000:', 'grace:x:1001:1001:', 'root:x:0:0'], - ), - ADA, - ), - ).toBeUndefined(); -}); - -test('admits a second group carrying the same gid when it reaches nobody else', () => { - expect( - privateGroupId( - database(['ada:x:1000:', 'ada-alias:x:1000:'], ['ada:x:1000:1000:', 'root:x:0:0']), - ADA, - ), - ).toBe(1000); -}); - -test('refuses it once a second group sharing the gid has another user as its primary group', () => { - expect( - privateGroupId( - database(['ada:x:1000:', 'team:x:1000:'], ['ada:x:1000:1000:', 'grace:x:1001:1000:']), - ADA, - ), - ).toBeUndefined(); -}); - -test('refuses it once another user is a member', () => { - expect( - privateGroupId( - database(['ada:x:1000:grace'], ['ada:x:1000:1000:', 'grace:x:1001:1001:', 'root:x:0:0']), - ADA, - ), - ).toBeUndefined(); -}); - -test('refuses it once another user has it as their primary group', () => { - expect( - privateGroupId(database(['ada:x:1000:'], ['ada:x:1000:1000:', 'grace:x:1001:1000:']), ADA), - ).toBeUndefined(); -}); - -test('refuses a group that is not the primary group of the user, however few members it lists', () => { - expect(privateGroupId(database(['ada:x:4321:'], ['ada:x:1000:1000:']), ADA)).toBeUndefined(); -}); - -test('refuses a group that does not carry the name of the user', () => { - expect(privateGroupId(database(['team:x:1000:'], ['ada:x:1000:1000:']), ADA)).toBeUndefined(); -}); - -test('refuses it when the group file cannot be read', () => { - expect(privateGroupId(database(undefined, PRIVATE_PASSWD), ADA)).toBeUndefined(); -}); - -test('refuses it when the passwd file cannot be read', () => { - expect(privateGroupId(database(PRIVATE, undefined), ADA)).toBeUndefined(); -}); - -test('refuses it when the user has no passwd record', () => { - expect(privateGroupId(database(PRIVATE, ['root:x:0:0']), ADA)).toBeUndefined(); -}); - -test('refuses it when the passwd record names another uid or gid', () => { - const other = { uid: 1002, gid: 1000, name: 'ada' }; - expect(privateGroupId(database(PRIVATE, PRIVATE_PASSWD), other)).toBeUndefined(); -}); - -test('gives a caller without a full identity no private group', () => { - const groups = database(PRIVATE, PRIVATE_PASSWD); - expect(privateGroupId(groups, { uid: undefined, gid: 1000, name: 'ada' })).toBeUndefined(); - expect(privateGroupId(groups, { uid: 1000, gid: undefined, name: 'ada' })).toBeUndefined(); - expect(privateGroupId(groups, { uid: 1000, gid: 1000, name: undefined })).toBeUndefined(); -}); diff --git a/packages/host-kit/src/internal/atomic-file-private-group.test.ts b/packages/host-kit/src/internal/atomic-file-private-group.test.ts new file mode 100644 index 0000000000..440c702e31 --- /dev/null +++ b/packages/host-kit/src/internal/atomic-file-private-group.test.ts @@ -0,0 +1,134 @@ +// privateGroupId: the one group shape the destination-ancestry rule admits, and what a name service +// does to that claim. Both are pure decisions over host account records, so they are judged here rather +// than through a filesystem. + +import { expect, test } from 'vitest'; +import { nameServiceListsOnlyFiles, privateGroupId } from './atomic-file.ts'; + +const ADA = { uid: 1000, gid: 1000, name: 'ada' }; + +const FILES = ['passwd: files', 'group: files']; + +function database(groups: readonly string[] | undefined, passwd: readonly string[] | undefined) { + return { groups, passwd, nsswitch: FILES }; +} + +const PRIVATE = ['ada:x:1000:', 'staff:x:20:root']; +const PRIVATE_PASSWD = ['ada:x:1000:1000:', 'root:x:0:0']; + +test('admits the group named after the user, holding only them, as their primary group', () => { + expect(privateGroupId(database(PRIVATE, PRIVATE_PASSWD), ADA)).toBe(1000); +}); + +test('admits root named among the members, the account the whole rule trusts', () => { + expect( + privateGroupId(database(['ada:x:1000:root'], ['ada:x:1000:1000:', 'root:x:0:0']), ADA), + ).toBe(1000); +}); + +test('refuses a second group carrying the same gid when it lists another user', () => { + // `ada:x:1000:` looks private on its own, and the group named after the user is the only one the + // exception used to read. A directory group-writable by gid 1000 is writable by grace too, because + // `team` carries the same number. + expect( + privateGroupId( + database( + ['ada:x:1000:', 'team:x:1000:grace'], + ['ada:x:1000:1000:', 'grace:x:1001:1001:', 'root:x:0:0'], + ), + ADA, + ), + ).toBeUndefined(); +}); + +test('admits a second group carrying the same gid when it reaches nobody else', () => { + expect( + privateGroupId( + database(['ada:x:1000:', 'ada-alias:x:1000:'], ['ada:x:1000:1000:', 'root:x:0:0']), + ADA, + ), + ).toBe(1000); +}); + +test('refuses it once a second group sharing the gid has another user as its primary group', () => { + expect( + privateGroupId( + database(['ada:x:1000:', 'team:x:1000:'], ['ada:x:1000:1000:', 'grace:x:1001:1000:']), + ADA, + ), + ).toBeUndefined(); +}); + +test('refuses it once another user is a member', () => { + expect( + privateGroupId( + database(['ada:x:1000:grace'], ['ada:x:1000:1000:', 'grace:x:1001:1001:', 'root:x:0:0']), + ADA, + ), + ).toBeUndefined(); +}); + +test('refuses it once another user has it as their primary group', () => { + expect( + privateGroupId(database(['ada:x:1000:'], ['ada:x:1000:1000:', 'grace:x:1001:1000:']), ADA), + ).toBeUndefined(); +}); + +test('refuses a group that is not the primary group of the user, however few members it lists', () => { + expect(privateGroupId(database(['ada:x:4321:'], ['ada:x:1000:1000:']), ADA)).toBeUndefined(); +}); + +test('refuses a group that does not carry the name of the user', () => { + expect(privateGroupId(database(['team:x:1000:'], ['ada:x:1000:1000:']), ADA)).toBeUndefined(); +}); + +test('refuses it when the group file cannot be read', () => { + expect(privateGroupId(database(undefined, PRIVATE_PASSWD), ADA)).toBeUndefined(); +}); + +test('refuses it when the passwd file cannot be read', () => { + expect(privateGroupId(database(PRIVATE, undefined), ADA)).toBeUndefined(); +}); + +test('refuses it when the user has no passwd record', () => { + expect(privateGroupId(database(PRIVATE, ['root:x:0:0']), ADA)).toBeUndefined(); +}); + +test('refuses it when the passwd record names another uid or gid', () => { + const other = { uid: 1002, gid: 1000, name: 'ada' }; + expect(privateGroupId(database(PRIVATE, PRIVATE_PASSWD), other)).toBeUndefined(); +}); + +test('refuses it when /etc/nsswitch.conf cannot be read', () => { + expect( + privateGroupId({ groups: PRIVATE, passwd: PRIVATE_PASSWD, nsswitch: undefined }, ADA), + ).toBeUndefined(); +}); + +test('refuses it when nsswitch.conf adds a name service to either database', () => { + const withNameService = (databaseLines: string[]) => + privateGroupId({ groups: PRIVATE, passwd: PRIVATE_PASSWD, nsswitch: databaseLines }, ADA); + + expect(withNameService(['passwd: files ldap', 'group: files'])).toBeUndefined(); + expect(withNameService(['passwd: files', 'group: files sss'])).toBeUndefined(); + // `systemd` is the default on some distributions and is still refused: userdbd answers membership from + // records these two files never show. + expect(withNameService(['passwd: files systemd', 'group: files systemd'])).toBeUndefined(); + expect(withNameService(['passwd: files', 'group:'])).toBeUndefined(); + expect(withNameService(['# no database lines here'])).toBeUndefined(); +}); + +test('admits a name service line that names only files, actions and comments aside', () => { + expect( + nameServiceListsOnlyFiles(['passwd: [NOTFOUND=return] files # local only', 'group: files']), + ).toBe(true); + expect(nameServiceListsOnlyFiles(['passwd: files', 'group: files db'])).toBe(false); + expect(nameServiceListsOnlyFiles(undefined)).toBe(false); +}); + +test('gives a caller without a full identity no private group', () => { + const groups = database(PRIVATE, PRIVATE_PASSWD); + expect(privateGroupId(groups, { uid: undefined, gid: 1000, name: 'ada' })).toBeUndefined(); + expect(privateGroupId(groups, { uid: 1000, gid: undefined, name: 'ada' })).toBeUndefined(); + expect(privateGroupId(groups, { uid: 1000, gid: 1000, name: undefined })).toBeUndefined(); +}); diff --git a/packages/host-kit/src/internal/atomic-file.ts b/packages/host-kit/src/internal/atomic-file.ts index 8917796e6b..1adabb0a20 100644 --- a/packages/host-kit/src/internal/atomic-file.ts +++ b/packages/host-kit/src/internal/atomic-file.ts @@ -1,6 +1,5 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; -import os from 'node:os'; import path from 'node:path'; import { AppError } from '@agent-device/kernel/errors'; import { emitDiagnostic } from './diagnostics.ts'; @@ -57,16 +56,14 @@ export function publishFileSync(options: { export function publishScriptFileSync(options: { destination: string; contents: string; - mode?: number; publish?: AtomicPublishMode; parentIdentity?: string; }): void { - const mode = options.mode ?? 0o600; const expected = options.parentIdentity ?? publishDirectoryIdentity(path.dirname(options.destination)); withAtomicPublishTempPathSync(options.destination, (temporaryPath) => { assertPrivateScriptDestination(options.destination, expected); - fs.writeFileSync(temporaryPath, options.contents, { encoding: 'utf8', mode }); + fs.writeFileSync(temporaryPath, options.contents, { encoding: 'utf8', mode: SCRIPT_FILE_MODE }); assertPrivateScriptDestination(options.destination, expected); if (options.publish === 'link-exclusive') { fs.linkSync(temporaryPath, options.destination); @@ -76,6 +73,9 @@ export function publishScriptFileSync(options: { }); } +/** A recording holds literals a `fill` did not parameterize (ADR 0017), so it is written private. */ +const SCRIPT_FILE_MODE = 0o600; + export type DurableFilePublishMode = 'replace' | 'link-exclusive'; /** Publishes complete UTF-8 contents with a durable file and directory fence. */ @@ -227,149 +227,184 @@ export function assertPrivateScriptDestination(destination: string, parentIdenti throw scriptAncestryFailure(destination, parent, 'parent_replaced'); } const trust = readScriptTrust(); - assertNoPlantedLink(destination, parent, trust); - const traversed = traversedDirectories(parent); - if (traversed.paths.length === 0) return; - for (const directory of traversed.paths) { - const stats = statDirectoryChain(directory); - if (!stats) continue; - const exposure = untrustedAncestryExposure(stats, trust); - if (exposure) throw scriptAncestryFailure(destination, directory, exposure); - } - // The script entry is created inside the deepest directory that exists, or below it through + const walk = walkParent(destination, trust); + if (walk.reject !== undefined) throw walk.reject; + // The script entry is created inside the deepest directory the walk reached, or below it through // directories that do not exist yet. Where other local users can add entries, one of them can add // this entry first and the recording is theirs, so the creation has to be refused. - const deepest = statDirectoryChain(traversed.deepest); + const deepest = statDirectoryChain(walk.deepest); if (deepest && othersCreateEntriesIn(deepest, trust)) { - throw scriptAncestryFailure(destination, traversed.deepest, 'shared_parent'); + throw scriptAncestryFailure(destination, walk.deepest, 'shared_parent'); } } -/** Link hops one destination walk expands before it stops, in step with the kernel's own limit. */ -const MAX_SYMLINK_HOPS = 40; +/** + * The parent of `destination`, made absolute but never normalized. + * + * `path.resolve` folds a `..` away, which is the one simplification this may not make: the kernel does + * not make it either, so `.../work/../x` lands its entry beside the target of the link named `work`. The + * spelled components are what the walk resolves; a relative destination keeps its relative spelling and + * starts from the working directory, which is how it reaches the filesystem. + */ +function spelledParent(destination: string): string { + if (path.isAbsolute(destination)) return path.dirname(destination); + const parent = path.dirname(destination); + return parent === '.' ? '' : parent; +} + +/** + * Where the walk stands: a directory it has already judged and physically reached, plus the names still + * to resolve. `deepest` is the directory the entry is created in when the walk stops here. + */ +type WalkState = Readonly<{ + deepest: string; + authority: DirectoryAuthority; + /** Path components left to resolve, nearest first. */ + queue: readonly string[]; + /** Link targets expanded so far. */ + hops: number; +}>; + +type WalkStep = + | Readonly<{ kind: 'reject'; path: string; exposure: ScriptAncestryExposure }> + | Readonly<{ kind: 'stop'; deepest: string }> + | Readonly<{ kind: 'stand'; state: WalkState }>; + +/** A walk that ended: the deepest directory reached, or the typed refusal. */ +type WalkOutcome = Readonly<{ reject: AppError | undefined; deepest: string }>; /** - * Every directory the kernel traverses to reach `parent`, judged nearest-first, without duplicates, and - * the deepest one that exists. + * Walks the spelled parent exactly as the kernel resolves a path, judging every step, and refuses at the + * first step another local user could steer. * - * Resolving only the deepest existing ancestor is not enough, and neither is one `realpath` of a path - * that runs through links: + * No `realpath` is involved anywhere. `realpathSync` answers only with the FINAL directory, so any + * directory the resolution stepped through can vanish from the answer, and from the judgment, whenever a + * link leads on to another link, or a spelled prefix names a plain directory whose ground is shared. + * Instead each component is resolved against the directory physically reached: * - * - A component that is a plain directory is traversed as it stands, so a link inside it can lead - * anywhere, and the directories above that plain component are reached by the publish even though the - * final chain looks entirely private: `/shared` at 0777 with `/shared/mine` at 0700 and - * `mine/rec` a link to a private directory names only trusted directories at its destination, while - * another local user owns the ground `mine` and `rec` stand on and can rename `mine` aside. So EVERY - * existing prefix of the spelled path is resolved, and the chain under each resolution is judged. - * - Where one link leads into another, `realpathSync` answers with the LAST target and names none of the - * directories stepped through on the way: `~/rec -> /srv/team/relay -> ~/chosen` reaches a private - * directory, and the team ground `relay` stands on never appears in the answer, though any teammate - * can swap that link for a target of their own. So a link hop also judges the directory holding its - * target, and the walk continues into the target. + * - `.` is skipped; `..` moves to the parent of the directory physically stood in, which is judged like + * any other directory. Neither one is a name that has to exist. + * - Any other component is lstat'ed in that directory. An absent component ends the walk, because the + * publish creates what is missing below here. + * - A directory is judged and entered. + * - A symbolic link is judged itself, against the directory that physically holds it, and its target's + * components go in front of the queue — restarting from `/` for an absolute target. Hops are counted + * against {@link MAX_SCRIPT_PATH_LINK_HOPS}, and crossing it is refused rather than trusted. + * - A component that is neither a directory nor a link cannot carry a publish, and is refused. + * + * A relative destination starts from the process's resolved working directory: the caller already stands + * there, and the walk cannot step above it. */ -function traversedDirectories( - parent: string, -): Readonly<{ paths: readonly string[]; deepest: string }> { - const seen = new Set(); - const paths: string[] = []; - let deepest: string | undefined; - for (const prefix of directoryChain(parent)) { - let current = prefix; - // Each hop replaces one link with its target, so a link cycle cannot run the walk forever. The - // operating system applies a limit of the same order and refuses the publish when it is exceeded. - for (let hop = 0; hop <= MAX_SYMLINK_HOPS; hop += 1) { - const stats = lstatIfPresentSync(current); - if (stats === undefined) break; - if (!stats.isSymbolicLink()) { - const real = resolvedDirectory(current); - if (real === undefined) break; - deepest ??= real; - for (const ancestor of directoryChain(real)) { - if (seen.has(ancestor)) continue; - seen.add(ancestor); - paths.push(ancestor); - } - break; - } - const target = linkTarget(current); - // The kernel steps INTO the directory the target names, so that directory and everything above it - // are traversed whatever this link eventually resolves to. - const home = resolvedDirectory(parentDirectory(target)); - if (home !== undefined) { - for (const ancestor of directoryChain(home)) { - if (seen.has(ancestor)) continue; - seen.add(ancestor); - paths.push(ancestor); - } - } - current = target; - } +function walkParent(destination: string, trust: ScriptDestinationTrust): WalkOutcome { + let step = startWalk(spelledParent(destination), trust); + // Every step consumes a component, and every link hop counts against a fixed limit, so this ends. + for (;;) { + if (step.kind === 'reject') return { reject: refusalAt(destination, step), deepest: '/' }; + if (step.kind === 'stop') return { reject: undefined, deepest: step.deepest }; + const { state } = step; + if (state.queue.length === 0) return { reject: undefined, deepest: state.deepest }; + step = stepWalk(state, trust); } - return { paths, deepest: deepest ?? parent }; } -/** Where a symbolic link points, made absolute the way the kernel reads it. */ -function linkTarget(link: string): string { - const target = fs.readlinkSync(link); - return path.isAbsolute(target) ? target : `${parentDirectory(link)}/${target}`; +function refusalAt( + destination: string, + step: Readonly<{ path: string; exposure: ScriptAncestryExposure }>, +): AppError { + return scriptAncestryFailure(destination, step.path, step.exposure); } -/** The directory `path` names once every link in it is expanded, or `undefined` when it is absent. */ -function resolvedDirectory(pathname: string): string | undefined { - if (lstatIfPresentSync(pathname) === undefined) return undefined; - try { - const real = fs.realpathSync(pathname); - return statDirectoryChain(real) ? real : undefined; - } catch (error) { - if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; - throw error; - } +/** The first state: `/` for an absolute spelling, the resolved working directory otherwise. */ +function startWalk(parent: string, trust: ScriptDestinationTrust): WalkStep { + const queue = pathComponents(parent); + // A relative destination starts from the working directory as the kernel sees it, symlink-free: the + // caller already stands there, so it is where the walk starts rather than a step it has to earn. + if (parent !== '' && !path.isAbsolute(parent)) return standIn(path.resolve(''), queue, trust, 0); + return standIn('/', queue, trust, 0); } -/** - * The parent of `destination` as it was spelled, made absolute but never normalized. - * - * `path.resolve` folds a `..` away, which is the one simplification this rule may not make: the kernel - * does not make it either, so `.../work/../x` lands an entry beside the target of a link named `work`. - * The chain that walk produces is what gets judged. - */ -function spelledParent(destination: string): string { - if (path.isAbsolute(destination)) return parentDirectory(destination); - // A relative destination reaches the filesystem through the working directory, the same way - // `path.resolve` names it, and the walk above is what the kernel performs from there. - return parentDirectory(path.resolve(destination)); +/** Judges `directory` and stands the walk there, or refuses it. */ +function standIn( + directory: string, + queue: readonly string[], + trust: ScriptDestinationTrust, + hops: number, +): WalkStep { + const stats = statDirectoryChain(directory); + if (stats === undefined) return { kind: 'reject', path: directory, exposure: 'not_a_directory' }; + const authority: DirectoryAuthority = { uid: stats.uid, gid: stats.gid, mode: stats.mode }; + const exposure = untrustedAncestryExposure(authority, trust); + if (exposure) return { kind: 'reject', path: directory, exposure }; + return { kind: 'stand', state: { deepest: directory, authority, queue, hops } }; +} + +/** The names of `directory`, with every `.` resolved away the way the kernel resolves it. */ +function pathComponents(directory: string): string[] { + return directory.split('/').filter((component) => component.length > 0 && component !== '.'); +} + +/** Advances one component of the queue. */ +function stepWalk(state: WalkState, trust: ScriptDestinationTrust): WalkStep { + const [component, ...rest] = state.queue; + if (component === undefined) return { kind: 'stop', deepest: state.deepest }; + // `..` is the parent of the directory PHYSICALLY stood in, not of the spelling: where `work` is a link, + // `.../work/../x` steps back from the link's target and lands beside it. + if (component === '..') return standIn(path.dirname(state.deepest), rest, trust, state.hops); + return stepIntoEntry(state, component, rest, trust); +} + +/** Resolves one named entry inside the directory the walk stands in. */ +function stepIntoEntry( + state: WalkState, + component: string, + rest: readonly string[], + trust: ScriptDestinationTrust, +): WalkStep { + const entry = path.join(state.deepest, component); + const stats = lstatIfPresentSync(entry); + // Nothing below here exists yet, so the publish creates it inside the directory the walk reached. + if (stats === undefined) return { kind: 'stop', deepest: state.deepest }; + if (stats.isSymbolicLink()) return stepThroughLink(state, entry, stats, rest, trust); + return standIn(entry, rest, trust, state.hops); } /** - * Refuses a symbolic link on the spelled path that another local user could have put there, or could - * replace. The link's target is judged through the resolved chain, so this only asks whether the link - * itself is stable: - * - * - In a directory others cannot add entries in, a link nobody but this user or root can write is not - * something they can plant or swap. - * - In a directory others CAN add entries in, the sticky bit is what protects an entry that already - * exists: it stops anyone but the entry's owner or root from removing or replacing it. Without the - * sticky bit, any of them can unlink this link and plant one pointing wherever they choose. + * One hop. The link is judged where it physically stands: inside a directory others may add entries to, + * only a link this user or root owns, held by the sticky bit, is theirs to keep. Its target's components + * then enter the queue, because the kernel steps into them next. */ -function assertNoPlantedLink( - destination: string, - parent: string, +function stepThroughLink( + state: WalkState, + link: string, + stats: fs.Stats, + rest: readonly string[], trust: ScriptDestinationTrust, -): void { - for (const ancestor of directoryChain(parent)) { - const link = lstatIfPresentSync(ancestor); - if (!link?.isSymbolicLink()) continue; - const home = lstatIfPresentSync(parentDirectory(ancestor)); - if (!home) continue; - const exposure = untrustedLinkExposure( - { uid: link.uid }, - { uid: home.uid, gid: home.gid, mode: home.mode }, - trust, - ); - if (exposure) throw scriptAncestryFailure(destination, ancestor, exposure); +): WalkStep { + const exposure = untrustedLinkExposure({ uid: stats.uid }, state.authority, trust); + if (exposure) return { kind: 'reject', path: link, exposure }; + if (state.hops >= MAX_SCRIPT_PATH_LINK_HOPS) { + return { kind: 'reject', path: link, exposure: 'link_loop_exceeded' }; } + const target = fs.readlinkSync(link); + const queue = [ + ...pathComponents(path.isAbsolute(target) ? target : path.join(state.deepest, target)), + ...rest, + ]; + // An absolute target restarts the walk at the root; a relative one continues from where the walk is. + const home = path.isAbsolute(target) ? '/' : state.deepest; + return standIn(home, queue, trust, state.hops + 1); } +/** + * How many link targets one destination walk expands before it refuses. + * + * Kept BELOW the smallest limit the supported kernels apply to a path of their own (macOS 32, Linux 40), + * so this rule always reaches its own limit first and answers with its own typed reason. The walk counts + * hops rather than letting the kernel answer `ELOOP`, because a walk that ran out of hops has NOT + * established where the entry lands, and that is a refusal, not a pass. + */ +export const MAX_SCRIPT_PATH_LINK_HOPS = 30; + /** * One directory's identity on its filesystem, for a caller that must publish into the same one it * created or checked. `undefined` when the directory is absent or is not a directory. @@ -380,11 +415,75 @@ export function publishDirectoryIdentity(directory: string): string | undefined return stats ? `${stats.dev}:${stats.ino}` : undefined; } -/** The group and passwd records the private-group exception reads, in `/etc/group` field order. */ +/** The host files the private-group exception reads, in `/etc/group` field order. */ type HostGroupDatabase = Readonly<{ /** `undefined` when the file could not be read, which is not the same as a file with no records. */ groups: readonly string[] | undefined; passwd: readonly string[] | undefined; + /** `/etc/nsswitch.conf`, which says whether the two files above are the whole story. */ + nsswitch: readonly string[] | undefined; +}>; + +/** One `group:` or `passwd:` line of `/etc/nsswitch.conf`, or `undefined` when none was found. */ +type NsswitchLine = Readonly<{ database: string; sources: readonly string[] }>; + +/** + * Whether `/etc/nsswitch.conf` establishes that the group and passwd files are the whole story. + * + * `files` is the only source admitted. `systemd` is deliberately NOT admitted, even though it is the + * default on some distributions: `systemd-userdbd` answers group membership from user records the two + * files never see, which is exactly the member this rule could not read. Bracketed actions such as + * `[NOTFOUND=return]` steer a lookup and add no source, so they are ignored. A missing line, an + * unparseable line, or an unreadable file establishes nothing, and the exception is refused. + */ +export function nameServiceListsOnlyFiles(nsswitch: readonly string[] | undefined): boolean { + if (nsswitch === undefined) return false; + for (const database of ['passwd', 'group']) { + const line = nsswitchLine(nsswitch, database); + if (line === undefined) return false; + if (!line.sources.every((source) => source === 'files')) return false; + if (line.sources.length === 0) return false; + } + return true; +} + +function nsswitchLine(lines: readonly string[], database: string): NsswitchLine | undefined { + for (const raw of lines) { + const source = (raw.split('#')[0] ?? '').trimStart(); + const [name, ...rest] = source.split(/[\s:]+/); + if (name !== database) continue; + // A bracketed action steers a lookup and lists no source. + const sources = rest.filter((token) => token.length > 0 && !token.startsWith('[')); + return { database, sources }; + } + return undefined; +} + +/** One `/etc/group` record. A line without a numeric gid cannot be used to judge membership. */ +type GroupRecord = Readonly<{ name: string; gid: number; members: readonly string[] }>; + +/** One `/etc/passwd` record. */ +type PasswdRecord = Readonly<{ name: string; uid: number; gid: number }>; + +function parseGroupRecord(line: string): GroupRecord | undefined { + const [name, , rawGid, rawMembers = ''] = line.split(':'); + const gid = Number(rawGid); + if (name === undefined || name === '' || rawGid === '' || !Number.isInteger(gid)) + return undefined; + return { name, gid, members: rawMembers.split(',').filter((member) => member.length > 0) }; +} + +function parsePasswdRecord(line: string): PasswdRecord | undefined { + const [name, , rawUid, rawGid] = line.split(':'); + if (name === undefined || name === '') return undefined; + return { name, uid: Number(rawUid), gid: Number(rawGid) }; +} + +/** This process's own account: the uid and primary gid the kernel reports, and the name it maps to. */ +type CurrentAccount = Readonly<{ + uid: number | undefined; + gid: number | undefined; + name: string | undefined; }>; /** @@ -395,6 +494,9 @@ type HostGroupDatabase = Readonly<{ * so it stays a valid script destination. Every other group stays outside the exception, and the rule * fails closed wherever completeness cannot be established: * + * - `/etc/nsswitch.conf` must exist, be readable, and name `files` as the ONLY source for both `passwd` + * and `group`. Otherwise a name service could hold a member no file shows, and nothing here could see + * it. {@link nameServiceListsOnlyFiles} says what a name service may say. * - Both database files must have been READ. An unreadable file is not an empty one, and an empty * member list proves nothing. * - The gid must be the one this process holds as its PRIMARY group, which `getgid` answers from the @@ -406,106 +508,113 @@ type HostGroupDatabase = Readonly<{ * while every local user holds it. * - No other passwd record may hold this gid as its primary group, and the caller's own record must * exist there with this uid and this gid. - * - * What this cannot establish, stated plainly because it cuts BOTH ways: the two files are only this - * machine's own view. A name service (LDAP, an NSS module) can hold a member of this gid, or a second - * group with the number, that never appears in `/etc/passwd` or `/etc/group`. Such a host can be - * refused a group-writable directory it genuinely owns, and it can also be ACCEPTED for one the name - * service has opened to someone else — this rule cannot see that member and so cannot refuse it. The - * caller's answer on a name-service host is a directory only they can write, at any mode. */ export function privateGroupId( database: HostGroupDatabase, - current: Readonly<{ uid: number | undefined; gid: number | undefined; name: string | undefined }>, + current: CurrentAccount, ): number | undefined { + if (!nameServiceListsOnlyFiles(database.nsswitch)) return undefined; + const records = parseHostGroupDatabase(database); + if (records === undefined) return undefined; + return admittedPrivateGid(records, current); +} + +/** The host's two databases, parsed, or `undefined` when either file could not be read. */ +type HostAccounts = Readonly<{ + groups: readonly GroupRecord[]; + passwd: readonly PasswdRecord[]; +}>; + +function parseHostGroupDatabase(database: HostGroupDatabase): HostAccounts | undefined { + if (!database.groups || !database.passwd) return undefined; + return { + groups: database.groups.flatMap((line) => { + const record = parseGroupRecord(line); + return record === undefined ? [] : [record]; + }), + passwd: database.passwd.flatMap((line) => { + const record = parsePasswdRecord(line); + return record === undefined ? [] : [record]; + }), + }; +} + +/** The decision the parsed databases allow: this gid, when it is the caller's own private group. */ +function admittedPrivateGid(accounts: HostAccounts, current: CurrentAccount): number | undefined { const { uid, gid, name } = current; if (uid === undefined || gid === undefined || name === undefined) return undefined; - if (!database.groups || !database.passwd) return undefined; - const own = database.passwd.find((line) => line.split(':')[0] === name); - if (!own) return undefined; - const [, , ownUid, ownGid] = own.split(':'); - if (Number(ownUid) !== uid || Number(ownGid) !== gid) return undefined; + const own = accounts.passwd.find((record) => record.name === name); + if (own === undefined || own.uid !== uid || own.gid !== gid) return undefined; + const carrying = accounts.groups.filter((record) => record.gid === gid); + if (!carrying.some((record) => record.name === name)) return undefined; // EVERY record carrying this gid decides together: a directory group-writable by gid 1000 is writable - // by the members of each of them, however they are named. A group named after the user buys the - // exception only while no other record sharing the number reaches another user. - let namedForUser = false; - for (const line of database.groups) { - const [groupName, , rawGid, rawMembers = ''] = line.split(':'); - const recordGid = Number(rawGid); - if (rawGid === '' || !Number.isInteger(recordGid) || recordGid !== gid) continue; - if (groupName === name) namedForUser = true; - const members = rawMembers.split(',').filter((member) => member.length > 0); - if (members.some((member) => !memberIsTrusted(member, database, name))) return undefined; - } - if (!namedForUser) return undefined; - const sharesPrimary = database.passwd.some((line) => { - const [other, , rawOtherUid, rawOtherGid] = line.split(':'); - return other !== name && Number(rawOtherGid) === gid && Number(rawOtherUid) !== 0; - }); + // by the members of each of them, however they are named. + const reachesAnybodyElse = carrying.some((record) => + record.members.some((member) => !memberIsTrusted(member, accounts, name)), + ); + if (reachesAnybodyElse) return undefined; + const sharesPrimary = accounts.passwd.some( + (record) => record.name !== name && record.gid === gid && record.uid !== 0, + ); return sharesPrimary ? undefined : gid; } /** Whether a member of a candidate private group is the user or root, the two accounts the rule trusts. */ -function memberIsTrusted(member: string, database: HostGroupDatabase, name: string): boolean { +function memberIsTrusted(member: string, accounts: HostAccounts, name: string): boolean { if (member === name) return true; - const record = database.passwd?.find((line) => line.split(':')[0] === member); - return record !== undefined && Number(record.split(':')[2]) === 0; + const record = accounts.passwd.find((other) => other.name === member); + return record !== undefined && record.uid === 0; +} + +/** + * The account name this process's uid maps to, read from the host account database. The name comes from + * the same file the group records come from, so a caller standing in for that file and this name stays in + * agreement. No `os.userInfo()`: that answers from a different source than the records being judged. + */ +function readCurrentUser( + passwd: readonly string[] | undefined, + uid: number | undefined, +): string | undefined { + if (passwd === undefined || uid === undefined) return undefined; + for (const line of passwd) { + const record = parsePasswdRecord(line); + if (record?.uid === uid) return record.name; + } + return undefined; } /** This process's identity and the private group its host databases establish, if any. */ function readScriptTrust(): ScriptDestinationTrust { + const passwd = readSystemFile('/etc/passwd'); + const uid = process.getuid?.(); return { - uid: process.getuid?.() ?? -1, + uid: uid ?? -1, privateGid: privateGroupId( - { groups: readSystemFile('/etc/group'), passwd: readSystemFile('/etc/passwd') }, - { uid: process.getuid?.(), gid: process.getgid?.(), name: readCurrentUser() }, + { + groups: readSystemFile('/etc/group'), + passwd, + nsswitch: readSystemFile(NSSWITCH_FILE), + }, + { uid, gid: process.getgid?.(), name: readCurrentUser(passwd, uid) }, ), }; } -function readCurrentUser(): string | undefined { - try { - return os.userInfo().username; - } catch { - return undefined; - } -} - -/** Every directory from `directory` up to the filesystem root, nearest first. */ -function directoryChain(directory: string): string[] { - const chain: string[] = []; - let current = directory; - for (;;) { - chain.push(current); - const parent = parentDirectory(current); - if (parent === current) return chain; - current = parent; - } -} - -/** - * The parent of `directory`, as the kernel sees it, or the same path when there is no parent. - * - * `path.dirname` is not usable here: it normalizes, so it folds a `..` segment away. That is the one - * simplification this rule may not make. Where `work` is a symbolic link, `.../work/../x` is a real - * path that lands beside the link's TARGET, so the rule has to see `.../work` in the chain and judge - * the link that stands there. Only a trailing separator is dropped, in linear time. - */ -function parentDirectory(directory: string): string { - const trimmed = directory.endsWith('/') ? directory.slice(0, -1) : directory; - const separator = trimmed.lastIndexOf('/'); - if (separator < 0) return trimmed; - return separator === 0 ? '/' : trimmed.slice(0, separator); -} +/** The file that says which sources the host looks in for accounts and groups. */ +const NSSWITCH_FILE = '/etc/nsswitch.conf'; /** - * The two ways a directory can be unsafe for a destination: someone else can change what is in it, or - * someone else can create the entry the destination names. + * The ways a step of the walk can be unsafe: somebody else can change what is in that directory, they + * can create the entry the destination names, they can put the link there, or the step cannot be trusted + * at all. * * `foreign_owned` — some other user owns it and can chmod, empty, or repopulate it whatever its mode. * `world_writable` / `shared_group_writable` — its mode opens its contents to others. * `shared_parent` — nobody else can change what is in it today, but they can add the missing entry. - * `planted_link` — a symbolic link someone else could have put in place of a directory. + * `planted_link` — a symbolic link another user could have put in place of a directory, or could replace. + * `link_loop_exceeded` — the walk expanded as many links as the kernel allows, so where it lands is not + * established. A loop is refused, never trusted. + * `not_a_directory` — a step of the path is something a publish cannot travel through. * `parent_replaced` — the directory the caller staged against is not the one it was. */ export type ScriptAncestryExposure = @@ -514,6 +623,8 @@ export type ScriptAncestryExposure = | 'shared_group_writable' | 'shared_parent' | 'planted_link' + | 'link_loop_exceeded' + | 'not_a_directory' | 'parent_replaced'; /** What this process can rely on when it judges a directory: its identity and its private group. */ diff --git a/packages/remote/src/__tests__/daemon-artifacts-script-download.test.ts b/packages/remote/src/__tests__/daemon-artifacts-script-download.test.ts index a737885e2d..7a7a6305ad 100644 --- a/packages/remote/src/__tests__/daemon-artifacts-script-download.test.ts +++ b/packages/remote/src/__tests__/daemon-artifacts-script-download.test.ts @@ -6,10 +6,12 @@ import type { DaemonWireRequest } from '@agent-device/contracts/command'; import type { DaemonArtifact, DaemonResponse } from '@agent-device/kernel/contracts'; import * as file from '@agent-device/host-kit/file'; import { + FOREIGN_UID, closeLoopbackServer, createTestHostEnvironment, listenOnLoopback, mkdtempForTestSync, + serveHostOwnership, } from '@agent-device/test-kit'; import { AppError } from '@agent-device/kernel/errors'; import { materializeRemoteArtifacts } from '../daemon-artifacts.ts'; @@ -491,6 +493,108 @@ test.skipIf(process.platform === 'win32')( }, ); +test.skipIf(process.platform === 'win32')( + 'a remote recording refuses the ground a link target crosses on the way in', + async () => { + // `rec -> /shared/relay/sub`, `shared` at 0777 and not sticky, `shared/relay -> /chosen`. + const root = fs.realpathSync(mkdtempForTestSync('script-ancestry-target-')); + const stateDir = path.join(root, 'state'); + const shared = path.join(root, 'shared'); + fs.mkdirSync(shared); + fs.chmodSync(shared, 0o777); + const chosen = path.join(root, 'chosen'); + fs.mkdirSync(chosen); + fs.chmodSync(chosen, 0o700); + fs.symlinkSync(chosen, path.join(shared, 'relay')); + const sub = path.join(chosen, 'sub'); + fs.mkdirSync(sub); + const home = path.join(root, 'home'); + fs.mkdirSync(home); + fs.symlinkSync(path.join(shared, 'relay', 'sub'), path.join(home, 'rec')); + const destination = path.join(home, 'rec', 'journey.ad'); + const baseUrl = await artifactServer({ v1: { body: 'open Demo\n' } }); + + const { response } = await open(baseUrl, stateDir, destination); + + expect(response).toEqual( + expect.objectContaining({ + ok: true, + data: expect.objectContaining({ + scriptDeliveryFailure: expect.objectContaining({ cause: 'script_ancestor_untrusted' }), + }), + }), + ); + expect(fs.readdirSync(sub)).toEqual([]); + }, +); + +test.skipIf(process.platform === 'win32')( + 'a remote recording refuses a link another local user owns on the way in', + async () => { + // `~/rec -> /tmp/relay -> ~/chosen`, `relay` another user's file in a sticky shared directory. + const root = fs.realpathSync(mkdtempForTestSync('script-ancestry-hopowner-')); + const stateDir = path.join(root, 'state'); + const home = path.join(root, 'home'); + fs.mkdirSync(home); + const chosen = path.join(root, 'chosen'); + fs.mkdirSync(chosen); + const tmp = path.join(root, 'tmp'); + fs.mkdirSync(tmp); + fs.chmodSync(tmp, 0o1777); + const relay = path.join(tmp, 'relay'); + fs.symlinkSync(chosen, relay); + fs.symlinkSync(relay, path.join(home, 'rec')); + serveHostOwnership({ [relay]: FOREIGN_UID }); + const destination = path.join(home, 'rec', 'journey.ad'); + const baseUrl = await artifactServer({ v1: { body: 'open Demo\n' } }); + + const { response } = await open(baseUrl, stateDir, destination); + + expect(response).toEqual( + expect.objectContaining({ + ok: true, + data: expect.objectContaining({ + scriptDeliveryFailure: expect.objectContaining({ cause: 'script_ancestor_untrusted' }), + }), + }), + ); + expect(fs.readdirSync(chosen)).toEqual([]); + }, +); + +test.skipIf(process.platform === 'win32')( + 'a remote recording refuses the directory a .. steps back into', + async () => { + // `home/work -> priv/x`, `priv/y` at 0777: the write lands in `priv/y`, not in the `home/y` the + // normalized spelling names. + const root = fs.realpathSync(mkdtempForTestSync('script-ancestry-dotdot-')); + const stateDir = path.join(root, 'state'); + const home = path.join(root, 'home'); + fs.mkdirSync(home); + const priv = path.join(root, 'priv'); + const privX = path.join(priv, 'x'); + fs.mkdirSync(privX, { recursive: true }); + const privY = path.join(priv, 'y'); + fs.mkdirSync(privY); + fs.chmodSync(privY, 0o777); + fs.symlinkSync(privX, path.join(home, 'work')); + const destination = `${home}/work/../y/journey.ad`; + const baseUrl = await artifactServer({ v1: { body: 'open Demo\n' } }); + + const { response } = await open(baseUrl, stateDir, destination); + + expect(response).toEqual( + expect.objectContaining({ + ok: true, + data: expect.objectContaining({ + scriptDeliveryFailure: expect.objectContaining({ cause: 'script_ancestor_untrusted' }), + }), + }), + ); + expect(fs.readdirSync(privY)).toEqual([]); + }, +); + test.skipIf(process.platform === 'win32')( 'a remote recording refuses a private link standing on shared ground two levels up', async () => { diff --git a/packages/test-kit/src/host-ownership.fixtures.ts b/packages/test-kit/src/host-ownership.fixtures.ts new file mode 100644 index 0000000000..ae945c1966 --- /dev/null +++ b/packages/test-kit/src/host-ownership.fixtures.ts @@ -0,0 +1,27 @@ +import fs from 'node:fs'; +import { vi } from 'vitest'; + +/** Some other local user: not the one running the suite, and not root. */ +export const FOREIGN_UID = 65534; + +/** + * Reports the ids in `owners` for the paths named there, and the real host for every other path, so an + * ownership rule is decided by the fixture rather than by the account the suite happens to run under. + * + * Only the ids move: modes and inode numbers stay what they are on disk. A real foreign owner needs + * privileges a test does not have — an unprivileged process cannot `chown` to another uid — and moving + * the CALLER's uid instead decides the test by which directories the scratch tree happens to sit under. + */ +export function serveHostOwnership(owners: Readonly>): void { + const realLstat = fs.lstatSync.bind(fs); + const realStat = fs.statSync.bind(fs); + const reuid = (stats: fs.Stats, pathname: string): fs.Stats => { + const uid = owners[pathname]; + if (uid === undefined || stats.uid === uid) return stats; + return Object.assign(Object.create(Object.getPrototypeOf(stats)), stats, { uid }) as fs.Stats; + }; + vi.spyOn(fs, 'lstatSync').mockImplementation(((pathname: never, ...rest: never[]) => + reuid(realLstat(pathname, ...rest), String(pathname))) as typeof fs.lstatSync); + vi.spyOn(fs, 'statSync').mockImplementation(((pathname: never, ...rest: never[]) => + reuid(realStat(pathname, ...rest), String(pathname))) as typeof fs.statSync); +} diff --git a/packages/test-kit/src/index.ts b/packages/test-kit/src/index.ts index 5d74593d59..fbd6c01e3e 100644 --- a/packages/test-kit/src/index.ts +++ b/packages/test-kit/src/index.ts @@ -122,6 +122,7 @@ export { unavailableDeploymentSnapshotAndShutdownOperationFacts, } from './runtime-operation-facts.ts'; export { createTestRuntimeStateHandle, type TestRuntimeStateHandle } from './runtime-state.ts'; +export { FOREIGN_UID, serveHostOwnership } from './host-ownership.fixtures.ts'; export { buildNodes } from './snapshot-builders.ts'; export { bottomTabsRealCaptureFixture, diff --git a/website/docs/docs/replay-e2e.md b/website/docs/docs/replay-e2e.md index 40d03dd9f5..15139a6863 100644 --- a/website/docs/docs/replay-e2e.md +++ b/website/docs/docs/replay-e2e.md @@ -72,9 +72,9 @@ agent-device open Settings --platform ios --session e2e --save-script ./workflow - Missing parent directories are created. The script file is created at mode `0600`, so its own permissions open it to nobody but you. What those permissions do not settle for you is listed under the limits below. - Every directory the write travels through must be one that no other local user can change. Each must be owned by you or by root, and its permissions must keep its contents closed to everyone else. Another local user who owns such a directory, or who can write in it, can replace a directory on the path or leave a symbolic link there, and the script then lands where they choose. -- Directories between the path you typed and where it ends are checked too, not only the final result. A plain directory that is open to others can hold a link into a private directory, so the destination looks private while the ground the link stands on is shared, and a link that points at another link passes through a directory the final path never names. Both are refused. A `..` segment is checked too, including the directory it steps back out of. -- The whole real path is checked, so a symbolic link to a shared directory is refused too. A link is refused if another user could have placed it, or could replace it: in a directory where others may add entries, only a link you or root own, held in place by the sticky bit, is trusted. Root-owned system links such as macOS `/tmp` and `/var` keep working. -- A directory you or root own may still be passed through when it carries the sticky bit (`chmod +t`) and is open to others, because that bit stops anyone but an entry's owner or root from replacing an entry: macOS `/tmp` works this way. A sticky directory owned by somebody else is refused — both bits shield other users from its owner, not the owner from you. The script is never created *inside* a directory others may add entries to: there, anyone could create your file's name first. A group-writable directory you own is accepted when its group is your own private group, the shape Ubuntu and Debian create for home directories. Every group carrying that group number is considered, so a second group with the same number that lists somebody else closes this exception. +- The check follows the path the way the system does, one name at a time, and judges every directory it looks a name up in. So a plain directory that is open to others cannot hide a link into a private destination (`rec -> shared/relay/sub`, where `shared/relay` is itself a link), and a link inside a link cannot hide the directory it crosses. A `..` is applied to the directory the walk actually reached, not to the text you typed: where `work` is a link, `work/../x` lands beside the link's target, and that is the directory judged. Following more links than the system allows is refused rather than trusted. +- Every symbolic link the path follows is checked wherever it leads, at any depth, not only the ones you typed. A link is refused if another user could have placed it, or could replace it: in a directory where others may add entries, only a link you or root own, held in place by the sticky bit, is trusted. Its own permission bits are not consulted: on Linux every link reports the same mode. Root-owned system links such as macOS `/tmp` and `/var` keep working. +- A directory you or root own may still be passed through when it carries the sticky bit (`chmod +t`) and is open to others, because that bit stops anyone but an entry's owner or root from replacing an entry: macOS `/tmp` works this way. A sticky directory owned by somebody else is refused — both bits shield other users from its owner, not the owner from you. The script is never created *inside* a directory others may add entries to: there, anyone could create your file's name first. A group-writable directory you own is accepted when its group is your own private group, the shape Ubuntu and Debian create for home directories, and only where `/etc/nsswitch.conf` shows that `/etc/group` and `/etc/passwd` are the whole story: a name service could hold a member those files never show. Every group carrying that group number is considered, so a second group with the same number that lists somebody else closes this exception. - Limits. The checks read owners, permission bits and link shape, and three things sit outside them. An access control list is consulted before the permission bits, so a directory at `0700` can still grant everyone write through an ACL, and a file at `0600` can still grant everyone read; the checks do not read ACLs. On a network mount (NFS, SMB, FUSE), ownership and mode are whatever the server answers, and the user ids there are usually not the ones on this machine. A mount can also appear over a checked directory. So these checks mean that no other local user can steer where the recording is written on a local filesystem without ACLs on that path; they are not a promise that nobody else can read the file. On a host like that, choose a directory only you can write. - A refused destination names the directory at fault. A local `close` fails and keeps its bytes. A remote recording keeps its success and reports `script_ancestor_untrusted` as the `scriptDeliveryFailure` cause, and the next recorded action or `close` repeats the refusal. Choose a directory you own that only you can write. - With a local daemon, the script is written on the daemon host when the session closes.