diff --git a/CHANGELOG.md b/CHANGELOG.md index a3bf39ae8..0da47b086 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ - CI: bun is pinned to 1.4.5 in every workflow and in the integration-suite images instead of `latest`, the `pull_request_target` workflow pins `actions/github-script` by commit, and translate-docs reads its `languages` input from `env:` and accepts only supported codes. The input used to run as shell, including in the job holding the translation credentials. The ts-sdk release preflight reads `github.ref` from `env:` too, where a crafted branch name could skip its branch check (#1056) - Harden the Codex system hooks. The hooks failproofai writes into `/etc/codex/config.toml` now run `/opt/failproofai-codex/codex-hook`, a short root-owned script that hands each event to the failproofai of the account that set the hooks up, one line per account. Install and every `failproofai update` check that the config itself, the script, the directories above them, the `sh`, `id` and `cat` it runs, and each account's own failproofai can be changed only by root or that account; a block that fails is taken out, and an account that fails is taken out of the script. `update` rewrites a block from an earlier version to use the script, which needs sudo; an account the block does not run for gets a notice instead of a failed update. Uninstalling takes out only your account (#1061) - An install of failproofai fetches one third-party package, `sql.js`, pinned to an exact version with no dependencies or install script of its own; everything else it uses is compiled into its bundles at build time from `bun.lock`. It used to declare six caret ranges, so each `npm install -g failproofai` or `npx failproofai` resolved them, and posthog-node's own ranges under them, afresh: a malicious in-range release (posthog-node was hit by Shai-Hulud 2.0 in November 2025) reached every install made after it was published, and its install script ran there. posthog-node, yaml, smol-toml, jsonc-parser and html-to-image are devDependencies now, since nothing loaded them from `node_modules` at run time, so the pin holds whichever package manager installs failproofai, and an install downloads about 1.2 MB less. `bun run build` now fails first if a runtime dependency is a range, has dependencies of its own or an install script, if a bundle leaves a package external that the install would not carry, or if the package itself gains an install script, a peer dependency or an optional dependency other than the daemon packages (#1059) +- Harden the privileged service install. Every file failproofai writes as root (the systemd unit, the launchd plist, Codex's system config and the daemon's copy under `/opt`) now reaches root as bytes on stdin and is checked against its SHA-256 before it is put in place; the daemon's copy is also held to the digest the build recorded, and a daemon binary that is a symbolic link is refused. `sudo` and every program it runs are named by absolute path from `/usr/bin`, `/bin`, `/usr/sbin` and `/sbin` and start with a minimal environment, the credential prompt included. The commands printed when sudo is not available do the same, run as printed, and on macOS carry the plist itself (#1060) - The always-on guard (`block-failproofai-commands`) now protects failproofai's installed code, not only its state. A user-scope hook runs the package `which failproofai` found, which under nvm, Homebrew, Volta, bun, pnpm, yarn or the npx cache the agent's own user can write, so a Write of `process.exit(0)` over `dist/cli.mjs` turned every later hook into an allow. File-tool writes to `node_modules/failproofai/…`, pnpm's `.pnpm/failproofai@…`, the daemon's `@failproofai/failproofaid-*` package, or the `…/bin/failproofai` and `…/pnpm/failproofai` entry a hook runs are now denied, including through a symlink, and so are shell commands that name those paths literally. The protected paths match case-insensitively, because macOS volumes are case-insensitive by default (FailproofAI/agenteye#1796, #1050) - A session pause whose recorded start is more than a minute in the future, or later than its latest renewal, is no longer honoured. The 8-hour ceiling was measured from that start, which comes from the same owner-writable file, so a hand-written pause dated 2100 stayed live until 2100. `failproofai config --resume --all` now also removes pause files that are not honoured yet, and exits 1 instead of reporting success when one cannot be removed (FailproofAI/agenteye#1796, #1050) diff --git a/CLAUDE.md b/CLAUDE.md index f1b02bc83..6976c9625 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1010,6 +1010,21 @@ Three consequences, all handled explicitly rather than assumed: anything; when it fails, the install writes nothing and returns the exact commands to run, classified as `needs_root`. `sudo -n`, never interactive — a password prompt fired from under the wizard's TUI is unreadable. +- **Root is never handed a path the user can write.** Every file written as root (unit, + plist, Codex's `/etc/codex/config.toml`, the `/opt` binary) goes through + `writePrivilegedFile()`: the bytes go to `PRIVILEGED_INSTALL_SCRIPT` on stdin with their + SHA-256 as an argument, and root checks them in a hidden `mktemp` file beside the + destination before it sets the mode and renames. On Linux the `/opt` binary is read by + the CLI, as the user, with `O_NOFOLLOW`, and checked before the install tears anything + down; on macOS root writes only the plist, which runs the user's own copy as that user. + No `sudo install `: root installs only bytes it has + verified. The printed `needs_root` recipe carries the same digests. +- **Nor a program found through PATH.** `sudo` and everything it runs come from + `src/hooks/system-command.ts`, which looks only in `/usr/bin`, `/bin`, `/usr/sbin` and + `/sbin` and starts them with `privilegedEnv()` (root's PATH, the caller's locale and the + settings sudo authenticates with). PATH is the user's to change. Printed commands use + `sudoCommandLine()`, which returns null rather than a bare name where root's directories + lack sudo or the program; callers then print what to do instead of a command. - **A system unit has no login environment.** `resolveWorkerCommand()` uses `process.execPath`, not a bare `node`: the single most common Node install is nvm, whose binary lives under `~/.nvm/versions/node/*/bin` and is on no system PATH. A bare `node` diff --git a/__tests__/helpers/system-command-stand-in.ts b/__tests__/helpers/system-command-stand-in.ts new file mode 100644 index 000000000..87dfa3a0d --- /dev/null +++ b/__tests__/helpers/system-command-stand-in.ts @@ -0,0 +1,49 @@ +/** + * A stand-in for `src/hooks/system-command` in tests that drive the privileged + * service install with `node:child_process` mocked. + * + * The install looks sudo and the programs it runs up in root's own directories + * on the machine running the tests, before any mocked command is called. A + * machine may lack some of them (launchctl on Linux, systemctl on a Mac or in a + * container, sudo itself), so where one is missing a path stands in for it; + * these tests never run them. Everything else is the real module. A test can + * also hide a program, to see what the install does where root has none. + * + * vi.doMock("../../src/hooks/system-command", async (importOriginal) => + * standInSystemCommand(await importOriginal())); + */ +import type * as SystemCommandModule from "../../src/hooks/system-command"; + +type SystemCommand = typeof SystemCommandModule; + +/** Programs the tests' sudo mocks answer for without running them. */ +const STOOD_IN = new Set(["sudo", "systemctl", "launchctl"]); + +/** On globalThis, because `vi.resetModules` evaluates this file afresh for each importer. */ +const HIDDEN_KEY = "__failproofaiHiddenSystemPrograms"; + +/** Programs to report as absent from root's directories, for the current test. */ +export function hiddenSystemPrograms(): Set { + const store = globalThis as Record; + if (!(store[HIDDEN_KEY] instanceof Set)) store[HIDDEN_KEY] = new Set(); + return store[HIDDEN_KEY] as Set; +} + +export function standInSystemCommand(actual: SystemCommand): SystemCommand { + const systemCommandPath = (name: string): string | null => { + if (hiddenSystemPrograms().has(name)) return null; + return actual.systemCommandPath(name) ?? (STOOD_IN.has(name) ? `/usr/bin/${name}` : null); + }; + const requireSystemCommand = (name: string): string => { + const path = systemCommandPath(name); + if (!path) throw new Error(`${name} was not found in ${actual.SYSTEM_BIN_DIRS.join(", ")}`); + return path; + }; + const sudoPath = (): string | null => systemCommandPath("sudo"); + const sudoCommandLine = (command: string, ...args: string[]): string | null => { + const sudo = sudoPath(); + const program = systemCommandPath(command); + return sudo && program ? [sudo, program, ...args].join(" ") : null; + }; + return { ...actual, systemCommandPath, requireSystemCommand, sudoPath, sudoCommandLine }; +} diff --git a/__tests__/hooks/daemon-privileged-install.test.ts b/__tests__/hooks/daemon-privileged-install.test.ts new file mode 100644 index 000000000..0388dcc27 --- /dev/null +++ b/__tests__/hooks/daemon-privileged-install.test.ts @@ -0,0 +1,644 @@ +// @vitest-environment node +/** + * Everything root writes for the daemon service (the systemd unit, the launchd + * plist, the copy of the binary under /opt) must reach root as bytes, never as + * a path the user can write, and must land exactly as failproofai produced it; + * and sudo, and every program it runs, must be named by absolute path rather + * than found through PATH. + * + * The install tests stand in for sudo with a mock that runs each privileged + * command as this (unprivileged) user, after changing any file under the + * user's home or temp directory that the command names: root must be handed + * none, so none of those changes may reach what is installed. No real sudo + * runs anywhere in this file, and nothing outside its scratch directory is + * written. + */ +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { execFileSync as realExecFileSync, type ExecFileSyncOptions } from "node:child_process"; +import { createHash } from "node:crypto"; +import { + existsSync, + lstatSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + statSync, + symlinkSync, + unlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir, userInfo } from "node:os"; +import { basename, dirname, resolve } from "node:path"; +import { installedBinaryPath } from "../../src/hooks/daemon-download"; +import { logsDir } from "../../src/hooks/fp-home"; +import { shellQuote } from "../../src/hooks/shell-quote"; +import packageJson from "../../package.json"; +import { hiddenSystemPrograms, standInSystemCommand } from "../helpers/system-command-stand-in"; + +vi.mock("../../src/hooks/hook-logger", () => ({ + hookLogWarn: vi.fn(), + hookLogInfo: vi.fn(), +})); + +type DaemonService = typeof import("../../src/hooks/daemon-service"); +type SystemCommand = typeof import("../../src/hooks/system-command"); + +const isRoot = typeof process.getuid === "function" && process.getuid() === 0; +const sha256 = (bytes: Buffer | string) => createHash("sha256").update(bytes).digest("hex"); + +/** What the managed daemon binary holds. */ +const BINARY = "#!/bin/sh\nexec sleep infinity\n"; +/** Some file other than the ones failproofai wrote. */ +const OTHER = "the content of some other file\n"; +/** What a file failproofai wrote is changed to. */ +const CHANGED = "changed after failproofai wrote it\n"; +const WORKER = "'/usr/bin/node' '/pkg/dist/worker.mjs'"; +const CLI = "'/usr/bin/node' '/pkg/dist/cli.mjs'"; + +const ENV_KEYS = [ + "PATH", + "HOME", + "TMPDIR", + "SUDO_ASKPASS", + "FAILPROOFAI_HOME", + "FAILPROOFAI_SYSTEMD_DIR", + "FAILPROOFAI_SYSTEM_BIN_DIR", + "FAILPROOFAI_LAUNCHD_DIR", + "FAILPROOFAI_DAEMON_BINARY", + "FAILPROOFAI_PACKAGE_ROOT", + "FAILPROOFAI_WORKER_CMD", + "FAILPROOFAI_CLI_CMD", + "FAILPROOFAI_NO_DOWNLOAD", +] as const; + +/** Every regular file under `dir`, recursively. */ +function filesUnder(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const path = resolve(dir, entry.name); + if (entry.isDirectory()) return filesUnder(path); + return entry.isFile() ? [path] : []; + }); +} + +/** Imported where used, so a test that does not need it still runs on its own. */ +async function systemCommand(): Promise { + return import("../../src/hooks/system-command"); +} + +// Meaningless as root, where nothing goes through sudo. +describe.skipIf(isRoot)("privileged service install: root is handed bytes, never a user path", () => { + const originalPlatform = process.platform; + const saved = new Map(); + let scratch: string; + /** The user's home and temp directory: anything running as the user can change them. */ + let home: string; + let userTmp: string; + /** Stands in for the directories only root can write. */ + let rootDir: string; + let otherPath: string; + + function setPlatform(platform: NodeJS.Platform) { + Object.defineProperty(process, "platform", { value: platform }); + } + + beforeEach(() => { + for (const key of ENV_KEYS) saved.set(key, process.env[key]); + scratch = mkdtempSync(resolve(tmpdir(), "fpai-priv-install-")); + // A space in the home, as on many Macs: every path in a recipe is quoted. + home = resolve(scratch, "first last"); + userTmp = resolve(scratch, "user-tmp"); + rootDir = resolve(scratch, "root"); + for (const dir of [home, userTmp, resolve(rootDir, "systemd"), resolve(rootDir, "LaunchDaemons")]) { + mkdirSync(dir, { recursive: true }); + } + otherPath = resolve(rootDir, "other"); + writeFileSync(otherPath, OTHER); + + process.env.HOME = home; + process.env.TMPDIR = userTmp; + process.env.FAILPROOFAI_HOME = resolve(home, ".failproofai"); + process.env.FAILPROOFAI_SYSTEMD_DIR = resolve(rootDir, "systemd"); + process.env.FAILPROOFAI_SYSTEM_BIN_DIR = resolve(rootDir, "opt"); + process.env.FAILPROOFAI_LAUNCHD_DIR = resolve(rootDir, "LaunchDaemons"); + process.env.FAILPROOFAI_WORKER_CMD = WORKER; + process.env.FAILPROOFAI_CLI_CMD = CLI; + // Nothing here may reach the network. + process.env.FAILPROOFAI_NO_DOWNLOAD = "1"; + delete process.env.FAILPROOFAI_DAEMON_BINARY; + delete process.env.FAILPROOFAI_PACKAGE_ROOT; + vi.resetModules(); + }); + + afterEach(() => { + hiddenSystemPrograms().clear(); + vi.doUnmock("node:child_process"); + vi.doUnmock("../../src/hooks/system-command"); + vi.doUnmock("../../package.json"); + vi.resetModules(); + setPlatform(originalPlatform); + for (const [key, value] of saved) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + rmSync(scratch, { recursive: true, force: true }); + }); + + /** The binary failproofai installed for this version, under the user's home. */ + function writeManagedBinary(): string { + const path = installedBinaryPath(); + expect(path.startsWith(`${home}/`)).toBe(true); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, BINARY, { mode: 0o755 }); + return path; + } + + /** The arguments of a privileged command that name something under the user's home or temp directory. */ + function userWritable(argv: readonly string[]): string[] { + return argv.filter((arg) => arg.startsWith(`${home}/`) || arg.startsWith(`${userTmp}/`)); + } + + interface RootCall { + /** How sudo itself was named. */ + sudo: string; + /** What it was asked to run, `-n` taken off. */ + argv: string[]; + input?: Buffer; + env?: NodeJS.ProcessEnv; + } + type BeforeRoot = (call: RootCall, options: ExecFileSyncOptions) => void; + + /** + * Stands in for sudo: runs each privileged command as this user, after + * `beforeRoot` has had its turn. `elevate: false` is a machine where sudo + * cannot run anything; `warmUp: true` one where it can only after `sudo -v`. + * `onElevate` runs at each `sudo -n true`, the check made just before the + * install starts copying. `hide` names programs root's directories are to + * lack. Programs the machine lacks are stood in for (see the helper). + */ + function mockSudo( + opts: { + beforeRoot?: BeforeRoot; + elevate?: boolean; + warmUp?: boolean; + onElevate?: () => void; + hide?: string[]; + } = {}, + ): RootCall[] { + const calls: RootCall[] = []; + let warm = !opts.warmUp; + for (const name of opts.hide ?? []) hiddenSystemPrograms().add(name); + vi.doMock("../../src/hooks/system-command", async (importOriginal) => + standInSystemCommand(await importOriginal()), + ); + vi.doMock("node:child_process", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + execFileSync: (cmd: string, args: readonly string[] = [], options: ExecFileSyncOptions = {}) => { + if (basename(cmd) === "sudo") { + const argv = args[0] === "-n" ? args.slice(1) : [...args]; + const call: RootCall = { + sudo: cmd, + argv, + input: Buffer.isBuffer(options.input) ? options.input : undefined, + env: options.env, + }; + calls.push(call); + if (opts.elevate === false) throw new Error("sudo: a password is required"); + if (argv[0] === "-v") { + warm = true; + return Buffer.alloc(0); + } + if (!warm) throw new Error("sudo: a password is required"); + if (argv.length === 1 && basename(argv[0]) === "true") { + opts.onElevate?.(); + return Buffer.alloc(0); + } + opts.beforeRoot?.(call, options); + switch (basename(argv[0])) { + case "install": + case "mv": + case "rm": + case "sh": + return actual.execFileSync(argv[0], argv.slice(1), options); + case "systemctl": + case "restorecon": + return Buffer.alloc(0); + case "launchctl": + return Buffer.from(argv[1] === "print" ? "state = running\n" : ""); + default: + throw new Error(`unexpected privileged command: ${argv.join(" ")}`); + } + } + if (basename(cmd) === "systemctl" && args[0] === "is-active") return Buffer.from("active\n"); + throw new Error(`unexpected command: ${cmd} ${args.join(" ")}`); + }, + }; + }); + return calls; + } + + /** + * Before each privileged command, every file under the user's home or temp + * directory that the command names is changed: replaced by a link to OTHER, + * or rewritten. + */ + function changeUserFiles(how: "link" | "rewrite"): BeforeRoot { + return (call) => { + for (const path of userWritable(call.argv)) { + if (!existsSync(path) || !lstatSync(path).isFile()) continue; + if (how === "link") { + unlinkSync(path); + symlinkSync(otherPath, path); + } else { + writeFileSync(path, CHANGED); + } + } + }; + } + + async function loadService(): Promise { + return import("../../src/hooks/daemon-service"); + } + + const changes: ("link" | "rewrite")[] = ["link", "rewrite"]; + describe.each(changes)("while user files are changed (%s)", (how) => { + it("linux: the unit and the /opt binary are exactly what failproofai produced", async () => { + setPlatform("linux"); + const managed = writeManagedBinary(); + const calls = mockSudo({ beforeRoot: changeUserFiles(how) }); + const svc = await loadService(); + const target = svc.systemBinaryTarget(managed)!; + expect(target.startsWith(`${rootDir}/`)).toBe(true); + + expect(await svc.installDaemonService()).toEqual({ installed: true }); + + // Root was handed nothing under the user's home or temp directory. + expect(calls.flatMap((call) => userWritable(call.argv))).toEqual([]); + expect(readFileSync(target, "utf8")).toBe(BINARY); + expect(statSync(target).mode & 0o777).toBe(0o755); + const unitPath = svc.daemonServiceFilePath()!; + expect(readFileSync(unitPath, "utf8")).toBe(svc.systemdUnitContents(target, WORKER, CLI)); + expect(statSync(unitPath).mode & 0o777).toBe(0o644); + // Nothing staged is left beside either. + expect(readdirSync(dirname(unitPath))).toEqual([basename(unitPath)]); + expect(readdirSync(dirname(target))).toEqual([basename(target)]); + expect(filesUnder(rootDir).filter((p) => p !== otherPath).map((p) => readFileSync(p, "utf8"))).not.toContain( + OTHER, + ); + }, 20_000); + + it("macOS: the plist is exactly what failproofai rendered, and launchd loads it after it is in place", async () => { + setPlatform("darwin"); + const managed = writeManagedBinary(); + const calls = mockSudo({ beforeRoot: changeUserFiles(how) }); + const svc = await loadService(); + + expect(await svc.installDaemonService()).toEqual({ installed: true }); + + expect(calls.flatMap((call) => userWritable(call.argv))).toEqual([]); + const plistPath = svc.daemonServiceFilePath()!; + expect(plistPath).toBe( + resolve(rootDir, "LaunchDaemons", `ai.failproof.failproofaid.${userInfo().username}.plist`), + ); + expect(readFileSync(plistPath, "utf8")).toBe(svc.launchdPlistContents(managed, logsDir(), WORKER, CLI)); + expect(statSync(plistPath).mode & 0o777).toBe(0o644); + expect(readdirSync(dirname(plistPath))).toEqual([basename(plistPath)]); + const write = calls.findIndex((call) => basename(call.argv[0]) === "sh" && call.argv.includes(plistPath)); + const load = calls.findIndex((call) => basename(call.argv[0]) === "launchctl" && call.argv[1] === "load"); + expect(write).toBeGreaterThanOrEqual(0); + expect(load).toBeGreaterThan(write); + }, 20_000); + }); + + it("linux: refuses a daemon binary that is a symbolic link, copies nothing and stops nothing", async () => { + setPlatform("linux"); + const managed = installedBinaryPath(); + mkdirSync(dirname(managed), { recursive: true }); + symlinkSync(otherPath, managed); + // A daemon from an older install that a successful install would retire. + const legacyUnit = resolve(home, ".config", "systemd", "user", "failproofaid.service"); + mkdirSync(dirname(legacyUnit), { recursive: true }); + writeFileSync(legacyUnit, "[Unit]\n"); + mockSudo(); + const svc = await loadService(); + + const result = await svc.installDaemonService(); + + expect(result.installed).toBe(false); + expect(result.reason).toMatch(/symbolic link/); + // Refused before anything was torn down. + expect(existsSync(legacyUnit)).toBe(true); + expect(filesUnder(rootDir).filter((p) => p !== otherPath).map((p) => readFileSync(p, "utf8"))).not.toContain( + OTHER, + ); + expect(existsSync(svc.daemonServiceFilePath()!)).toBe(false); + }); + + it("linux: installs under /opt only the binary bytes this build recorded, even if the file changes once checked", async () => { + setPlatform("linux"); + writeManagedBinary(); + // The digest a published build records for its own platform binary. + const arch = process.arch === "arm64" ? "arm64" : "x64"; + const manifest = { ...packageJson, failproofaidBinaries: { [`linux-${arch}`]: sha256(BINARY) } }; + vi.doMock("../../package.json", () => ({ ...manifest, default: manifest })); + // Checked once before the install starts copying, then changed. + mockSudo({ onElevate: () => writeFileSync(installedBinaryPath(), CHANGED) }); + const svc = await loadService(); + + const result = await svc.installDaemonService(); + + expect(result.installed).toBe(false); + expect(result.reason).toMatch(/expects [0-9a-f]{64}/); + expect(filesUnder(rootDir).filter((p) => p !== otherPath)).toEqual([]); + }); + + it("never runs a sudo or a program that PATH finds first, credential warm-up included, and gives sudo root's PATH", async () => { + setPlatform("linux"); + writeManagedBinary(); + // Programs of the same names first on PATH, in a directory the user owns. + // Each leaves a mark if it ever runs. + const planted = resolve(home, ".local", "bin"); + const marks = resolve(scratch, "marks"); + mkdirSync(planted, { recursive: true }); + mkdirSync(marks); + const names = ["sudo", "install", "mv", "rm", "sh", "systemctl", "restorecon", "true", "mktemp", "cat", "chmod", "sha256sum"]; + for (const name of names) { + writeFileSync(resolve(planted, name), `#!/bin/sh\n: > '${resolve(marks, name)}'\nexit 1\n`, { mode: 0o755 }); + } + process.env.PATH = `${planted}:${process.env.PATH ?? ""}`; + process.env.SUDO_ASKPASS = resolve(planted, "sudo"); + const calls = mockSudo({ warmUp: true }); + const sys = await systemCommand(); + const svc = await loadService(); + + // The wizard's warm-up: the one place the user types their password. + expect(svc.primeElevation()).toBe(true); + expect(calls.some((call) => call.argv[0] === "-v")).toBe(true); + expect(await svc.installDaemonService()).toEqual({ installed: true }); + + expect(readdirSync(marks)).toEqual([]); + for (const call of calls) { + expect(call.sudo).toBe(sys.requireSystemCommand("sudo")); + if (call.argv[0] !== "-v") expect(sys.SYSTEM_BIN_DIRS).toContain(dirname(call.argv[0])); + expect(call.env?.PATH).toBe(sys.SYSTEM_PATH); + expect(call.env).not.toHaveProperty("SUDO_ASKPASS"); + } + }, 20_000); + + const alterations: [string, (bytes: Buffer) => Buffer][] = [ + ["appended to", (bytes) => Buffer.concat([bytes, Buffer.from(CHANGED)])], + ["substituted for", () => Buffer.from(CHANGED)], + ]; + describe.each(alterations)("bytes %s what failproofai sent on the way to root", (_what, alter) => { + it("are refused, and the destination keeps what it had", async () => { + const dest = resolve(rootDir, "systemd", "x.service"); + writeFileSync(dest, "previous\n"); + mockSudo({ + beforeRoot: (_call, options) => { + if (Buffer.isBuffer(options.input)) options.input = alter(options.input); + }, + }); + const { writePrivilegedFile } = await loadService(); + + expect(() => writePrivilegedFile(dest, "[Unit]\nDescription=x\n")).toThrow(/do not match sha256/); + expect(readFileSync(dest, "utf8")).toBe("previous\n"); + expect(readdirSync(dirname(dest))).toEqual(["x.service"]); + }); + }); + + it("refuses a relative destination or a mode that is not octal, before anything runs", async () => { + const calls = mockSudo(); + const { writePrivilegedFile } = await loadService(); + expect(() => writePrivilegedFile("etc/x.service", "x\n")).toThrow(/relative path/); + expect(() => writePrivilegedFile(resolve(rootDir, "x"), "x\n", "u+s")).toThrow(/mode/); + expect(calls).toEqual([]); + }); + + describe("the manual recipe printed when sudo is not available", () => { + /** + * A stand-in sudo, at a path of its own: it runs the command as this user, + * and does nothing for the service managers. + */ + function fakeSudo(): string { + const dir = resolve(scratch, "fake-bin"); + mkdirSync(dir, { recursive: true }); + const path = resolve(dir, "sudo"); + writeFileSync( + path, + [ + "#!/bin/sh", + "while [ $# -gt 0 ]; do case $1 in -*) shift ;; *) break ;; esac; done", + 'case "${1##*/}" in systemctl|launchctl|restorecon) exit 0 ;; esac', + 'exec "$@"', + "", + ].join("\n"), + { mode: 0o755 }, + ); + return path; + } + + async function printedRecipe(platform: NodeJS.Platform): Promise<{ recipe: string; svc: DaemonService }> { + setPlatform(platform); + mockSudo({ elevate: false }); + const svc = await loadService(); + const result = await svc.installDaemonService(); + expect(result.installed).toBe(false); + expect(result.reason).toMatch(/root privileges are required/); + const marker = "To install by hand, run:\n"; + expect(result.reason).toContain(marker); + return { recipe: result.reason!.slice(result.reason!.indexOf(marker) + marker.length), svc }; + } + + /** + * Runs the recipe as pasted, with the stand-in in place of every sudo it + * names. Refuses to run one that still names a real sudo. + */ + async function runRecipe(recipe: string): Promise<{ status: number; stderr: string }> { + const sudo = (await systemCommand()).sudoPath(); + if (!sudo) throw new Error("no sudo to stand in for: the recipe would not have been printed"); + const stand = fakeSudo(); + const runnable = recipe.split(`${sudo} `).join(`${stand} `); + expect(runnable).not.toContain(sudo); + try { + realExecFileSync("/bin/sh", ["-c", runnable], { + env: { ...process.env, PATH: `${dirname(stand)}:/usr/bin:/bin` }, + stdio: ["ignore", "ignore", "pipe"], + timeout: 30_000, + }); + return { status: 0, stderr: "" }; + } catch (err) { + const e = err as { status?: number | null; stderr?: Buffer }; + return { status: e.status ?? -1, stderr: e.stderr?.toString() ?? "" }; + } + } + + it("linux: installs exactly the binary and unit the install would, run as printed", async () => { + const managed = writeManagedBinary(); + const { recipe, svc } = await printedRecipe("linux"); + const sys = await systemCommand(); + const target = svc.systemBinaryTarget(managed)!; + // Rendered before the recipe runs, as the recipe's own copy was. + const unit = svc.systemdUnitContents(target, WORKER, CLI); + + // Root reads the binary from stdin; the user's shell opens it. + expect(recipe).toContain(`< '${managed}'`); + expect(recipe).not.toMatch(/sudo (install -m|tee|cp) /); + // sudo and the programs it runs, by absolute path. + expect(recipe).toContain(sys.sudoCommandLine("systemctl", "daemon-reload")!); + + expect(await runRecipe(recipe)).toEqual({ status: 0, stderr: "" }); + expect(readFileSync(target, "utf8")).toBe(BINARY); + expect(statSync(target).mode & 0o777).toBe(0o755); + expect(readFileSync(svc.daemonServiceFilePath()!, "utf8")).toBe(unit); + }); + + it("linux: stops before any unit is written when the binary changed after it was printed", async () => { + const managed = writeManagedBinary(); + const { recipe, svc } = await printedRecipe("linux"); + + writeFileSync(managed, CHANGED); + const { status, stderr } = await runRecipe(recipe); + + expect(status).not.toBe(0); + expect(stderr).toMatch(/do not match sha256/); + expect(existsSync(svc.systemBinaryTarget(managed)!)).toBe(false); + expect(existsSync(svc.daemonServiceFilePath()!)).toBe(false); + }); + + // Never a bare name: whoever pastes a printed command would look it up + // through their own PATH. + const missing: [NodeJS.Platform, string][] = [ + ["linux", "sudo"], + ["darwin", "sudo"], + ["linux", "systemctl"], + ]; + it.each(missing)("%s, without %s in root's directories: prints no command to run as root", async (platform, hide) => { + writeManagedBinary(); + setPlatform(platform); + mockSudo({ elevate: false, hide: [hide] }); + const svc = await loadService(); + const sys = await systemCommand(); + + const result = await svc.installDaemonService(); + + expect(result.installed).toBe(false); + expect(result.reason).toMatch(/root privileges are required/); + expect(result.reason).toContain(`No manual steps could be prepared: ${sys.NO_PRINTED_COMMAND_REASON}`); + expect(result.reason).not.toContain("failproofai_install"); + expect(svc.daemonRestartCommand()).toBeNull(); + if (platform === "darwin") expect(svc.daemonStatusCommand()).toBeNull(); + }); + + const updateHints: [string, string[]][] = [ + ["with sudo in root's directories", []], + ["without", ["sudo"]], + ]; + it.each(updateHints)("update's needs-root hint %s names no bare sudo", async (_label, hide) => { + setPlatform("linux"); + mockSudo({ hide }); + const svc = await loadService(); + const sys = await systemCommand(); + + const result = await svc.refreshDaemonToCliVersion({ + status: () => "running", + interactive: () => false, + install: async () => ({ installed: false, reason: "root privileges are required to install it" }), + }); + + const sudo = sys.sudoPath(); + expect(result.lines[1]).toBe( + sudo + ? ` Run \`${sudo} -v\` and then \`failproofai update\` again.` + : ` No sudo was found in ${sys.SYSTEM_BIN_DIRS.join(", ")}, so failproofai cannot install its service here.`, + ); + expect(Boolean(sudo)).toBe(hide.length === 0); + }); + + it("macOS: carries the plist inline and installs exactly it, run as printed", async () => { + const managed = writeManagedBinary(); + const { recipe, svc } = await printedRecipe("darwin"); + const plist = svc.launchdPlistContents(managed, logsDir(), WORKER, CLI); + + // Single-quoted, never a here-document: zsh (the macOS default) expands + // `!` in a here-document's body, and the plist has ` { + /** Whether root's fixed PATH has `tool`. */ + function has(tool: string): boolean { + try { + realExecFileSync("/bin/sh", ["-c", `PATH=/usr/bin:/bin:/usr/sbin:/sbin; command -v ${tool}`], { + stdio: "ignore", + }); + return true; + } catch { + return false; + } + } + + // Each later branch is forced by naming the tools before it as ones no + // system has: Linux runners have all three, macOS has the last two. + const NONE = "command -v failproofai-no-such-tool"; + const variants: [string, (script: string) => string][] = [ + ["sha256sum", (s) => s], + ["shasum", (s) => s.replace("command -v sha256sum", NONE)], + ["openssl", (s) => s.replace("command -v sha256sum", NONE).replace("command -v shasum", NONE)], + ]; + + let dir: string; + beforeEach(() => { + dir = mkdtempSync(resolve(tmpdir(), "fpai-priv-script-")); + }); + afterEach(() => { + rmSync(dir, { recursive: true, force: true }); + }); + + function run(script: string, dest: string, digest: string, mode: string, input: Buffer): void { + realExecFileSync("/bin/sh", ["-c", script, "failproofai-install", dest, digest, mode], { + input, + stdio: ["pipe", "ignore", "pipe"], + }); + } + + for (const [tool, edit] of variants) { + it.skipIf(!has(tool))(`with ${tool}: installs exactly the bytes, with the mode, and refuses any others`, async () => { + const { PRIVILEGED_INSTALL_SCRIPT } = await import("../../src/hooks/daemon-service"); + const script = edit(PRIVILEGED_INSTALL_SCRIPT); + if (tool !== "sha256sum") expect(script).not.toContain("command -v sha256sum"); + // Binary-safe: a NUL, a lone CR, no trailing newline. + const bytes = Buffer.from([0, 1, 2, 255, 13, 10, 65]); + const dest = resolve(dir, "file"); + + run(script, dest, sha256(bytes), "0640", bytes); + expect(readFileSync(dest).equals(bytes)).toBe(true); + expect(statSync(dest).mode & 0o777).toBe(0o640); + + expect(() => + run(script, resolve(dir, "other"), sha256(bytes), "0640", Buffer.concat([bytes, Buffer.from("x")])), + ).toThrow(); + expect(() => run(script, dest, sha256(bytes), "0640", Buffer.from("x"))).toThrow(); + // The refused writes left nothing behind, and the earlier file as it was. + expect(readdirSync(dir)).toEqual(["file"]); + expect(readFileSync(dest).equals(bytes)).toBe(true); + }); + } + + it("never contains a single quote, so a recipe can quote it verbatim", async () => { + const { PRIVILEGED_INSTALL_SCRIPT } = await import("../../src/hooks/daemon-service"); + expect(PRIVILEGED_INSTALL_SCRIPT).not.toContain("'"); + }); +}); diff --git a/__tests__/hooks/daemon-service.test.ts b/__tests__/hooks/daemon-service.test.ts index 6dd7c5967..5988b9dd0 100644 --- a/__tests__/hooks/daemon-service.test.ts +++ b/__tests__/hooks/daemon-service.test.ts @@ -1,10 +1,13 @@ // @vitest-environment node import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { tmpdir, userInfo } from "node:os"; -import { dirname, resolve } from "node:path"; +import { basename, dirname, resolve } from "node:path"; import { binDir } from "../../src/hooks/fp-home"; +import { SYSTEM_BIN_DIRS, sudoPath } from "../../src/hooks/system-command"; +import { standInSystemCommand } from "../helpers/system-command-stand-in"; import { startedAtFromMonotonic, waitForDaemonRunning } from "../../src/hooks/daemon-service"; import * as svc from "../../src/hooks/daemon-service"; import { version as pkgVersion } from "../../package.json"; @@ -240,13 +243,22 @@ describe("hooks/daemon-service", () => { // first's daemon (UserName, ExecStart under their ~/.failproofai/bin, // their log paths) and their uninstall deleted it. setPlatform("darwin"); - const { daemonServiceFilePath, daemonStatusCommand } = await import("../../src/hooks/daemon-service"); - const user = userInfo().username; - - expect(daemonServiceFilePath()).toBe( - `/Library/LaunchDaemons/ai.failproof.failproofaid.${user}.plist`, + // The status hint names launchctl by absolute path, and a Linux runner + // has none: stand one in. + vi.doMock("../../src/hooks/system-command", async (importOriginal) => + standInSystemCommand(await importOriginal()), ); - expect(daemonStatusCommand()).toContain(`system/ai.failproof.failproofaid.${user}`); + try { + const { daemonServiceFilePath, daemonStatusCommand } = await import("../../src/hooks/daemon-service"); + const user = userInfo().username; + + expect(daemonServiceFilePath()).toBe( + `/Library/LaunchDaemons/ai.failproof.failproofaid.${user}.plist`, + ); + expect(daemonStatusCommand()).toContain(`system/ai.failproof.failproofaid.${user}`); + } finally { + vi.doUnmock("../../src/hooks/system-command"); + } }); it("writes a unit that runs as the user, starts at boot, and knows where HOME is", async () => { @@ -412,10 +424,16 @@ describe("hooks/daemon-service", () => { // Every privileged command fails the way a machine without // passwordless sudo fails. Nothing may be written, and the reason // has to be actionable rather than an errno. + // sudo and the programs it runs are looked up on this machine; any it + // lacks (systemctl on a Mac) gets a stand-in path. None of them runs. + vi.doMock("../../src/hooks/system-command", async (importOriginal) => + standInSystemCommand(await importOriginal()), + ); vi.doMock("node:child_process", async (importOriginal) => ({ ...(await importOriginal()), execFileSync: (cmd: string) => { - if (cmd === "sudo") throw new Error("sudo: a password is required"); + // By absolute path now (system-command.ts), never a bare `sudo`. + if (basename(cmd) === "sudo") throw new Error("sudo: a password is required"); throw new Error(`nothing else should run before elevation succeeds, but got: ${cmd}`); }, })); @@ -436,6 +454,7 @@ describe("hooks/daemon-service", () => { existsSync(resolve(process.env.FAILPROOFAI_SYSTEMD_DIR!, `failproofaid@${userInfo().username}.service`)), ).toBe(false); } finally { + vi.doUnmock("../../src/hooks/system-command"); vi.doUnmock("node:child_process"); vi.resetModules(); } @@ -463,10 +482,17 @@ describe("hooks/daemon-service", () => { // read the same as root or not. async function runUninstall(opts: { failOn?: string } = {}): Promise<{ ran: string[]; root: string; unit: string }> { const ran: string[] = []; + // The install names sudo and each program by absolute path, looked up + // on this machine; none of them runs here, so any the machine lacks + // gets a stand-in path rather than failing the lookup. + vi.doMock("../../src/hooks/system-command", async (importOriginal) => + standInSystemCommand(await importOriginal()), + ); vi.doMock("node:child_process", async (importOriginal) => ({ ...(await importOriginal()), execFileSync: (cmd: string, args: string[] = []) => { - const line = (cmd === "sudo" ? args.slice(1) : [cmd, ...args]).join(" "); + const [program, ...rest] = basename(cmd) === "sudo" ? args.slice(1) : [cmd, ...args]; + const line = [basename(program), ...rest].join(" "); ran.push(line); if (opts.failOn && line.startsWith(opts.failOn)) throw new Error("sudo: a password is required"); return ""; @@ -480,6 +506,7 @@ describe("hooks/daemon-service", () => { await uninstallDaemonService(); return { ran, root: daemonSystemBinaryDir()!, unit: daemonServiceFilePath()! }; } finally { + vi.doUnmock("../../src/hooks/system-command"); vi.doUnmock("node:child_process"); vi.resetModules(); } @@ -590,10 +617,16 @@ describe("hooks/daemon-service", () => { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, "#!/bin/sh\n", { mode: 0o755 }); setPlatform("linux"); + // sudo and the programs it runs are looked up on this machine; any it + // lacks (systemctl on a Mac) gets a stand-in path. None of them runs. + vi.doMock("../../src/hooks/system-command", async (importOriginal) => + standInSystemCommand(await importOriginal()), + ); vi.doMock("node:child_process", async (importOriginal) => ({ ...(await importOriginal()), execFileSync: (cmd: string) => { - if (cmd === "sudo") throw new Error("sudo: a password is required"); + // By absolute path now (system-command.ts), never a bare `sudo`. + if (basename(cmd) === "sudo") throw new Error("sudo: a password is required"); throw new Error(`nothing else should run before elevation succeeds, but got: ${cmd}`); }, })); @@ -602,15 +635,24 @@ describe("hooks/daemon-service", () => { const { installDaemonService, systemBinaryTarget, daemonSystemBinaryDir } = await import( "../../src/hooks/daemon-service" ); + // The same lookups the install used (stand-ins included). + const sys = await import("../../src/hooks/system-command"); const target = systemBinaryTarget(path)!; const result = await installDaemonService(); expect(result.installed).toBe(false); expect(path).toContain(" "); - expect(result.reason).toContain(`sudo install -d -m 0755 '${dirname(target)}'`); - expect(result.reason).toContain(`sudo install -m 0755 '${path}' '${target}'`); - expect(result.reason).toContain(`sudo restorecon -R '${daemonSystemBinaryDir()}'`); + expect(result.reason).toContain(sys.sudoCommandLine("install", "-d", "-m", "0755", `'${dirname(target)}'`)!); + // The binary reaches root on stdin, from a `<` the user's own shell + // opens, with the digest root checks it against. + const digest = createHash("sha256").update("#!/bin/sh\n").digest("hex"); + expect(result.reason).toContain(`failproofai_install '${target}' ${digest} 0755 < '${path}'`); + // Only where root's own directories have restorecon (every SELinux system). + if (sys.systemCommandPath("restorecon")) { + expect(result.reason).toContain(sys.sudoCommandLine("restorecon", "-R", `'${daemonSystemBinaryDir()}'`)!); + } } finally { + vi.doUnmock("../../src/hooks/system-command"); vi.doUnmock("node:child_process"); vi.resetModules(); } @@ -1523,7 +1565,9 @@ describe("refreshDaemonToCliVersion", () => { expect(result.lines).toEqual([ `✕ failproofaid ${version} was not installed: root privileges are required. The previous daemon is untouched.`, - " Run `sudo -v` and then `failproofai update` again.", + sudoPath() + ? ` Run \`${sudoPath()} -v\` and then \`failproofai update\` again.` + : ` No sudo was found in ${SYSTEM_BIN_DIRS.join(", ")}, so failproofai cannot install its service here.`, ]); expect(result.lines.join("\n")).not.toMatch(/failproofai config|\[Unit\]|sudo tee/); }); diff --git a/__tests__/hooks/system-command.test.ts b/__tests__/hooks/system-command.test.ts new file mode 100644 index 000000000..806cf4913 --- /dev/null +++ b/__tests__/hooks/system-command.test.ts @@ -0,0 +1,97 @@ +// @vitest-environment node +/** + * Programs failproofai runs as root are found in root's own directories, never + * through PATH, and start with root's PATH rather than the caller's + * environment. + */ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, resolve } from "node:path"; +import { + NO_PRINTED_COMMAND_REASON, + SYSTEM_BIN_DIRS, + SYSTEM_PATH, + privilegedEnv, + requireSystemCommand, + sudoCommandLine, + sudoPath, + systemCommandPath, +} from "../../src/hooks/system-command"; + +const KEYS = ["PATH", "SUDO_ASKPASS", "BASH_ENV", "LANG", "TERM", "SSH_AUTH_SOCK", "KRB5CCNAME"] as const; + +describe("system-command", () => { + const saved = new Map(); + let planted: string; + + beforeEach(() => { + for (const key of KEYS) saved.set(key, process.env[key]); + // Programs of the same names first on PATH. + planted = mkdtempSync(resolve(tmpdir(), "fpai-planted-")); + for (const name of ["sudo", "sh", "failproofai-only-on-path"]) { + writeFileSync(resolve(planted, name), "#!/bin/sh\nexit 1\n", { mode: 0o755 }); + } + process.env.PATH = `${planted}:${process.env.PATH ?? ""}`; + }); + + afterEach(() => { + for (const [key, value] of saved) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + rmSync(planted, { recursive: true, force: true }); + }); + + it("finds a program only in root's own directories, never through PATH", () => { + expect(SYSTEM_BIN_DIRS).toEqual(["/usr/bin", "/bin", "/usr/sbin", "/sbin"]); + expect(SYSTEM_PATH).toBe("/usr/bin:/bin:/usr/sbin:/sbin"); + + const sh = systemCommandPath("sh"); + expect(sh).not.toBeNull(); + expect(SYSTEM_BIN_DIRS).toContain(dirname(sh!)); + const sudo = systemCommandPath("sudo"); + if (sudo) expect(SYSTEM_BIN_DIRS).toContain(dirname(sudo)); + expect(sudo).not.toBe(resolve(planted, "sudo")); + + // Only on PATH: not found at all, rather than found there. + expect(systemCommandPath("failproofai-only-on-path")).toBeNull(); + expect(() => requireSystemCommand("failproofai-only-on-path")).toThrow(/not found in \/usr\/bin, \/bin/); + // A name, never a path. + expect(systemCommandPath("../bin/sh")).toBeNull(); + expect(systemCommandPath(`${planted}/sudo`)).toBeNull(); + }); + + it("starts privileged commands with root's PATH and what sudo itself uses, nothing else", () => { + process.env.SUDO_ASKPASS = resolve(planted, "sudo"); + process.env.BASH_ENV = resolve(planted, "sh"); + process.env.LANG = "C.UTF-8"; + process.env.TERM = "xterm-256color"; + // What PAM modules authenticate sudo with on some fleets. + process.env.SSH_AUTH_SOCK = "/run/user/1000/ssh-agent.socket"; + process.env.KRB5CCNAME = "KCM:"; + + const env = privilegedEnv(); + + expect(env.PATH).toBe(SYSTEM_PATH); + expect(env.LANG).toBe("C.UTF-8"); + expect(env.TERM).toBe("xterm-256color"); + expect(env.SSH_AUTH_SOCK).toBe("/run/user/1000/ssh-agent.socket"); + expect(env.KRB5CCNAME).toBe("KCM:"); + expect(env).not.toHaveProperty("SUDO_ASKPASS"); + expect(env).not.toHaveProperty("BASH_ENV"); + const allowed = ["PATH", "TERM", "LANG", "LC_ALL", "LC_CTYPE", "LC_MESSAGES", "SSH_AUTH_SOCK", "KRB5CCNAME"]; + expect(Object.keys(env).every((key) => allowed.includes(key))).toBe(true); + }); + + it("prints sudo and the program by absolute path, and nothing where root's directories lack either", () => { + const sudo = sudoPath(); + expect(sudo).toBe(systemCommandPath("sudo")); + expect(sudoCommandLine("sh", "-c", "'true'")).toBe(sudo ? `${sudo} ${systemCommandPath("sh")} -c 'true'` : null); + // Never a bare name: the program below is only on PATH. + expect(sudoCommandLine("failproofai-only-on-path", "-x")).toBeNull(); + expect(NO_PRINTED_COMMAND_REASON).toBe( + "sudo or the program it would run is not in /usr/bin, /bin, /usr/sbin, /sbin, so no command to run as root is printed", + ); + }); +}); diff --git a/__tests__/hooks/uninstall-cli.test.ts b/__tests__/hooks/uninstall-cli.test.ts index 795d0808e..7d9b1dcaa 100644 --- a/__tests__/hooks/uninstall-cli.test.ts +++ b/__tests__/hooks/uninstall-cli.test.ts @@ -15,6 +15,8 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { mkdtempSync, rmSync, existsSync, writeFileSync, mkdirSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { NO_PRINTED_COMMAND_REASON, sudoCommandLine } from "../../src/hooks/system-command"; +import { hiddenSystemPrograms } from "../helpers/system-command-stand-in"; /** Call order across the mocked modules, which is the actual thing under test. */ const calls: string[] = []; @@ -46,6 +48,14 @@ vi.mock("../../src/hooks/agent-skill", () => ({ }), })); +// sudo and the programs it runs are named by absolute path, looked up on this +// machine; any it lacks (systemctl on a Mac) gets a stand-in path. See the helper. +vi.mock("../../src/hooks/system-command", async (importOriginal) => + (await import("../helpers/system-command-stand-in")).standInSystemCommand( + await importOriginal(), + ), +); + vi.mock("../../src/hooks/daemon-service", () => ({ isDaemonSupportedPlatform: () => true, daemonServiceFilePath: () => servicePath, @@ -224,8 +234,9 @@ describe("hooks/uninstall-cli", () => { expect(res.exitCode).toBe(1); const out = res.lines.join("\n"); expect(out).toMatch(/still there/); - expect(out).toMatch(/sudo systemctl disable --now failproofaid@tester\.service/); - expect(out).toMatch(/sudo rm -f/); + // sudo and each program by absolute path, as failproofai runs them itself. + expect(out).toContain(sudoCommandLine("systemctl", "disable", "--now", "failproofaid@tester.service")); + expect(out).toContain(sudoCommandLine("rm", "-f")); // Enforcement is still off even though cleanup was incomplete. expect(calls[0]).toBe("setDaemonConfigured(false)"); }); @@ -417,14 +428,32 @@ describe("hooks/uninstall-cli — who decides the daemon's fate", () => { expect(at).toBeGreaterThanOrEqual(0); expect(res.lines.slice(at + 1, at + 7)).toEqual([ " Remove it as root:", - " sudo systemctl disable --now failproofaid@tester.service", - ` sudo rm -f '${servicePath}'`, - " sudo systemctl daemon-reload", + ` ${sudoCommandLine("systemctl", "disable", "--now", "failproofaid@tester.service")}`, + ` ${sudoCommandLine("rm", "-f", `'${servicePath}'`)}`, + ` ${sudoCommandLine("systemctl", "daemon-reload")}`, // The root-owned copy the unit ran, outside HOME for SELinux. - ` sudo rm -rf '${stagedDir}'`, + ` ${sudoCommandLine("rm", "-rf", `'${stagedDir}'`)}`, " Check it with systemctl status failproofaid@tester", ]); }); + + it("prints no command, only what to remove, where root's directories have no sudo", async () => { + // A bare `sudo` would be whatever the PATH of whoever pastes it finds first. + hiddenSystemPrograms().add("sudo"); + try { + serviceExists = false; + const { runUninstallCommand } = await import("../../src/hooks/uninstall-cli"); + const res = await runUninstallCommand({ yes: true }); + + const out = res.lines.join("\n"); + expect(res.exitCode).toBe(1); + expect(out).toContain(`Remove ${servicePath} as root (${NO_PRINTED_COMMAND_REASON}).`); + expect(out).not.toContain("Remove it as root:"); + expect(out).not.toMatch(/`sudo /); + } finally { + hiddenSystemPrograms().clear(); + } + }); }); describe("hooks/uninstall-cli — a staged daemon binary with no unit", () => { @@ -480,7 +509,7 @@ describe("hooks/uninstall-cli — a staged daemon binary with no unit", () => { const res = await runUninstallCommand({ yes: true }); expect(res.exitCode).toBe(1); - expect(res.lines.join("\n")).toContain(`sudo rm -rf '${stagedDir}'`); + expect(res.lines.join("\n")).toContain(sudoCommandLine("rm", "-rf", `'${stagedDir}'`)); expect(res.lines.join("\n")).not.toContain("Removed the failproofaid binary"); }); }); diff --git a/src/hooks/cloud-enrollment-cli.ts b/src/hooks/cloud-enrollment-cli.ts index 61f9039c1..8b83ed3ff 100644 --- a/src/hooks/cloud-enrollment-cli.ts +++ b/src/hooks/cloud-enrollment-cli.ts @@ -138,7 +138,8 @@ function daemonWarning(status: ReturnType): string[] ? [" A daemon is running and policy is being pulled."] : ["! No daemon is answering, so nothing is being pulled right now."]), " Its service state needs elevation to read, so it is not shown above.", - ...(check ? [` Check it with: sudo ${check}`] : []), + // The command carries its own sudo: a LaunchDaemon cannot be read without it. + ...(check ? [` Check it with: ${check}`] : []), ]; } // A daemon started by hand is invisible to the service manager but is diff --git a/src/hooks/daemon-service.ts b/src/hooks/daemon-service.ts index c48dd56d8..4fb780b15 100644 --- a/src/hooks/daemon-service.ts +++ b/src/hooks/daemon-service.ts @@ -8,30 +8,44 @@ * relationship it already has with `manager.ts`'s `installHooks()`. */ import { HEALTH_PROBE_SOURCE } from "./health-probe"; +import { createHash } from "node:crypto"; import { + closeSync, + constants as fsConstants, existsSync, + fstatSync, mkdirSync, - mkdtempSync, + openSync, readFileSync, readdirSync, realpathSync, statSync, - writeFileSync, unlinkSync, - rmSync, } from "node:fs"; -import { homedir, tmpdir, userInfo } from "node:os"; +import { homedir, userInfo } from "node:os"; import { dirname, resolve } from "node:path"; import { execFileSync } from "node:child_process"; import { hookLogWarn } from "./hook-logger"; import { + binaryDigestMismatch, downloadFailproofaidBinary, + expectedNpmBinaryDigest, installFromNpmPackage, installedBinaryMismatch, installedBinaryPath, } from "./daemon-download"; import { logsDir } from "./fp-home"; import { shellQuote, shellQuotedWords } from "./shell-quote"; +import { + NO_PRINTED_COMMAND_REASON, + SYSTEM_BIN_DIRS, + SYSTEM_PATH, + privilegedEnv, + requireSystemCommand, + sudoCommandLine, + sudoPath, + systemCommandPath, +} from "./system-command"; import { version } from "../../package.json"; import { readVersionFile, updateConfig, writeVersionFile } from "./fp-config"; @@ -578,31 +592,28 @@ function selinuxEnabled(): boolean { * unit should start. Privileged; throws when the copy fails, which the caller * reports as a failed install before any unit is written. * - * Staged under a temp name and renamed into place, so a reinstall of the same - * version never writes into the file a running daemon was started from. + * The bytes are read here, as the user, and handed to root on stdin by + * {@link writePrivilegedFile}; root is never given the binary's path, which is + * in a directory the user owns. Root installs exactly the bytes read here, and + * reading them as the user reaches nothing the user could not read anyway. + * O_NOFOLLOW refuses a link outright: the managed binary is a regular file + * failproofai wrote itself. + * + * Staged under a temp name and renamed into place by the privileged write, so + * a reinstall of the same version never writes into the file a running daemon + * was started from. * * `restorecon` afterwards, because a new file inherits the label of the * directory it is created in, not the one the policy assigns to its path: the * directories `install -d` creates under `/opt` (`usr_t`) come out `usr_t` * too, never the `bin_t` the policy names for them. */ -function stageSystemBinary(binaryPath: string): string { +function stageSystemBinary(binaryPath: string, bytes?: Buffer): string { const target = systemBinaryTarget(binaryPath); if (!target) return binaryPath; - const dir = systemBinaryDir(); - const staging = `${target}.${process.pid}.tmp`; - runPrivileged("install", ["-d", "-m", "0755", dir]); - try { - runPrivileged("install", ["-m", "0755", binaryPath, staging]); - runPrivileged("mv", ["-f", staging, target]); - } catch (err) { - try { - runPrivileged("rm", ["-f", staging]); - } catch { - /* best-effort */ - } - throw err; - } + const data = bytes ?? readDaemonBinaryForRoot(binaryPath); + runPrivileged("install", ["-d", "-m", "0755", systemBinaryDir()]); + writePrivilegedFile(target, data, "0755"); if (selinuxEnabled()) { const root = systemBinaryRoot(); try { @@ -659,8 +670,17 @@ function launchdLabel(user: string = serviceUser()): string { return `ai.failproof.failproofaid.${user}`; } +/** + * `/Library/LaunchDaemons`, redirectable for tests ONLY, like the systemd unit + * directory: it lets a Linux runner drive the macOS install end to end against + * a scratch directory, with launchctl stubbed, instead of not at all. + */ +function launchdDaemonDir(): string { + return process.env.FAILPROOFAI_LAUNCHD_DIR || "/Library/LaunchDaemons"; +} + function launchdPlistPath(user: string = serviceUser()): string { - return `/Library/LaunchDaemons/${launchdLabel(user)}.plist`; + return resolve(launchdDaemonDir(), `${launchdLabel(user)}.plist`); } /** The pre-1.0.0-beta.1 LaunchAgent. */ @@ -674,7 +694,7 @@ function legacyLaunchAgentPlistPath(): string { * leaving it would leave two daemons racing for one socket. */ function legacySharedLaunchDaemonPath(): string { - return "/Library/LaunchDaemons/ai.failproof.failproofaid.plist"; + return resolve(launchdDaemonDir(), "ai.failproof.failproofaid.plist"); } /** @@ -697,7 +717,7 @@ export function daemonStatusCommand(): string | null { if (!isDaemonSupportedPlatform()) return null; return process.platform === "linux" ? `systemctl status ${systemdUnitName()}` - : `sudo launchctl print system/${launchdLabel()}`; + : sudoCommandLine("launchctl", "print", `system/${launchdLabel()}`); } /** @@ -712,8 +732,8 @@ export function daemonStatusCommand(): string | null { export function daemonRestartCommand(): string | null { if (!isDaemonSupportedPlatform()) return null; return process.platform === "linux" - ? `sudo systemctl restart ${systemdUnitName()}` - : `sudo launchctl kickstart -k system/${launchdLabel()}`; + ? sudoCommandLine("systemctl", "restart", systemdUnitName()) + : sudoCommandLine("launchctl", "kickstart", "-k", `system/${launchdLabel()}`); } /** @@ -733,12 +753,20 @@ export function daemonRestartCommand(): string | null { * * `stdio: "inherit"` so the prompt and the typed password go straight to the * real terminal. The timeout is generous because a human is typing. + * + * sudo by absolute path, like every privileged command here (see + * `system-command.ts`): this is where the user types their password, so it is + * the system's own sudo, whatever PATH says. */ export function primeElevation(): boolean { if (typeof process.getuid === "function" && process.getuid() === 0) return true; if (canElevate()) return true; // NOPASSWD, or already primed try { - execFileSync("sudo", ["-v"], { stdio: "inherit", timeout: SUDO_PROMPT_TIMEOUT_MS }); + execFileSync(requireSystemCommand("sudo"), ["-v"], { + stdio: "inherit", + timeout: SUDO_PROMPT_TIMEOUT_MS, + env: privilegedEnv(), + }); return canElevate(); } catch { // Wrong password, no sudo rights, or the user pressed ctrl-C. All of them @@ -759,13 +787,29 @@ export function primeElevation(): boolean { export function canElevate(): boolean { if (typeof process.getuid === "function" && process.getuid() === 0) return true; try { - execFileSync("sudo", ["-n", "true"], { stdio: "ignore", timeout: SERVICE_CMD_TIMEOUT_MS }); + execFileSync(requireSystemCommand("sudo"), ["-n", requireSystemCommand("true")], { + stdio: "ignore", + timeout: SERVICE_CMD_TIMEOUT_MS, + env: privilegedEnv(), + }); return true; } catch { return false; } } +/** + * The command and arguments that run `command args` as root: the program + * itself when this process already is root, through `sudo -n` otherwise. Both + * by absolute path from root's own directories, never through PATH (see + * `system-command.ts`). Throws when either cannot be found there. + */ +function elevatedCommand(command: string, args: string[]): [string, string[]] { + const program = command.startsWith("/") ? command : requireSystemCommand(command); + if (typeof process.getuid === "function" && process.getuid() === 0) return [program, args]; + return [requireSystemCommand("sudo"), ["-n", program, ...args]]; +} + /** * Runs one privileged command, non-interactively. * @@ -775,36 +819,150 @@ export function canElevate(): boolean { * instead — it keeps working exactly as it did, on the in-process path. */ export function runPrivileged(command: string, args: string[]): void { - const root = typeof process.getuid === "function" && process.getuid() === 0; - const [cmd, argv] = root ? [command, args] : ["sudo", ["-n", command, ...args]]; - execFileSync(cmd, argv, { stdio: "ignore", timeout: SERVICE_CMD_TIMEOUT_MS }); + const [cmd, argv] = elevatedCommand(command, args); + execFileSync(cmd, argv, { stdio: "ignore", timeout: SERVICE_CMD_TIMEOUT_MS, env: privilegedEnv() }); +} + +/** The shell root runs the install script with. Absolute: no PATH lookup picks it. */ +const SYSTEM_SH = "/bin/sh"; + +/** + * How long one privileged write may take. Bounded like every other privileged + * call, but well above SERVICE_CMD_TIMEOUT_MS: the daemon binary is tens of + * megabytes, streamed through sudo. + */ +const PRIVILEGED_WRITE_TIMEOUT_MS = 60_000; + +/** + * What root runs to put a file in place: + * `sh -c SCRIPT failproofai-install `, with the + * file's bytes on stdin. Exported so tests can run it. + * + * The rules it exists for: root installs only bytes it has verified, and never + * opens a path the user can write. The bytes arrive on stdin, not as a file + * staged where the user could reach it. A pipe is not a private channel either, + * so root hashes what it received, in a file only root can reach, against the + * digest on its own command line, and only then sets the mode and renames the + * file over the destination. + * + * - PATH is fixed, like every privileged command's (see `system-command.ts`): + * the programs root runs here are root's own. + * - The temp file comes from `mktemp`, which creates it exclusively and never + * through an existing link, beside the destination in a directory only root + * can write, so the rename that publishes it is atomic. It is hidden, so a + * leftover is never read as a unit by systemd or as a job by launchd. + * - The digest tool is whichever the OS has: coreutils `sha256sum` on Linux, + * `shasum -a 256` on macOS, `openssl` as a last resort. + * - There is no single quote in it, so the manual recipe quotes it verbatim. + */ +export const PRIVILEGED_INSTALL_SCRIPT = [ + "set -eu", + `PATH=${SYSTEM_PATH}`, + "export PATH", + "umask 077", + "dest=$1 want=$2 mode=$3 tmp=", + 'cleanup() { [ -z "$tmp" ] || rm -f "$tmp"; }', + "trap cleanup EXIT", + 'trap "exit 1" HUP INT TERM', + 'tmp=$(mktemp "${dest%/*}/.${dest##*/}.XXXXXX")', + 'cat >"$tmp"', + 'if command -v sha256sum >/dev/null 2>&1; then got=$(sha256sum <"$tmp")', + 'elif command -v shasum >/dev/null 2>&1; then got=$(shasum -a 256 <"$tmp")', + 'else got=$(openssl dgst -sha256 -r <"$tmp")', + "fi", + 'if [ "${got%% *}" != "$want" ]; then', + ' echo "refusing to install $dest: the bytes received do not match sha256 $want" >&2', + " exit 1", + "fi", + 'chmod "$mode" "$tmp"', + 'mv -f "$tmp" "$dest"', + "tmp=", + "", +].join("\n"); + +function sha256Hex(bytes: Buffer): string { + return createHash("sha256").update(bytes).digest("hex"); +} + +/** + * Installs a file into a root-owned location with `mode`, because the caller + * is not root and cannot write there directly. The bytes go to root on stdin + * and are checked against their digest before they land; see + * {@link PRIVILEGED_INSTALL_SCRIPT}. The file is renamed over `destination` + * only once its mode is set, so it is never briefly world-writable and never + * half-written: a failed write leaves the previous file in place. + */ +export function writePrivilegedFile(destination: string, contents: string | Buffer, mode = "0644"): void { + // Both are command-line words for root, never shell text, but a relative + // path would land somewhere unintended and chmod also takes symbolic modes. + if (!destination.startsWith("/")) throw new Error(`refusing to write a relative path as root: ${destination}`); + if (!/^[0-7]{3,4}$/.test(mode)) throw new Error(`refusing to write ${destination} with mode ${JSON.stringify(mode)}`); + const bytes = typeof contents === "string" ? Buffer.from(contents, "utf8") : contents; + const args = ["-c", PRIVILEGED_INSTALL_SCRIPT, "failproofai-install", destination, sha256Hex(bytes), mode]; + try { + const [cmd, argv] = elevatedCommand(SYSTEM_SH, args); + execFileSync(cmd, argv, { + input: bytes, + stdio: ["pipe", "ignore", "pipe"], + timeout: PRIVILEGED_WRITE_TIMEOUT_MS, + env: privilegedEnv(), + }); + } catch (err) { + // The script's own refusal, or sudo's, is on stderr. The error's message + // would otherwise lead with the whole script. + const e = err as { stderr?: Buffer | string; code?: string; status?: number | null }; + const why = + e.stderr?.toString().trim() || + e.code || + (typeof e.status === "number" ? `exit status ${e.status}` : err instanceof Error ? err.message : String(err)); + throw new Error(`could not write ${destination} as root: ${why}`); + } +} + +/** + * The daemon binary's bytes as root will install them: read once, and held to + * the digest this build recorded for the managed copy when it carries one + * (`expectedNpmBinaryDigest`). `ensureFailproofaidBinary` checks the file + * before the install starts, but what reaches root is this read, so the check + * is made again on these very bytes. + */ +function readDaemonBinaryForRoot(binaryPath: string): Buffer { + const bytes = readRegularFileNoFollow(binaryPath); + const key = platformKey(); + if (key && binaryPath === installedBinaryPath()) { + const mismatch = binaryDigestMismatch(expectedNpmBinaryDigest(key), bytes, binaryPath); + if (mismatch) throw new Error(mismatch); + } + return bytes; } /** - * Installs a file into a root-owned location via a temp file, because the - * caller is not root and cannot write there directly. `install -m` sets the - * mode in the same step, so the file is never briefly world-writable. + * Reads a regular file, refusing a symbolic link or anything else in its + * place. Used for the one file whose bytes go to root: what root installs is + * then exactly what this process read, as the user. */ -export function writePrivilegedFile(destination: string, contents: string, mode = "0644"): void { - // mkdtempSync, not a name built from pid + timestamp in the shared tmpdir. - // That name is guessable, and `writeFileSync` follows a symlink already - // sitting at the path — so on a multi-user box another local user could - // pre-create it and have `install` copy content they control into - // /etc/systemd/system as root. mkdtemp gives a 0700 directory with a name - // they cannot predict, so there is nothing to pre-create. - const stagingDir = mkdtempSync(resolve(tmpdir(), "failproofaid-stage-")); - const staging = resolve(stagingDir, "service-definition"); +function readRegularFileNoFollow(path: string): Buffer { + let fd: number; try { - writeFileSync(staging, contents, "utf8"); - // Installed beside the destination and renamed over it: `install` onto - // the destination unlinks the old file before copying, so a copy that - // failed part-way left no definition (launchd then cannot load the job - // at boot). A rename within one directory is atomic. - const sibling = `${destination}.failproofai-new`; - runPrivileged("install", ["-m", mode, staging, sibling]); - runPrivileged("mv", ["-f", sibling, destination]); + // O_NONBLOCK so that a FIFO in its place is opened and refused below, + // rather than blocking this process until something writes to it. + fd = openSync(path, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK); + } catch (err) { + const code = (err as NodeJS.ErrnoException).code; + // ELOOP is how O_NOFOLLOW reports a link (EMLINK on FreeBSD). + if (code === "ELOOP" || code === "EMLINK") { + throw new Error( + `refusing to copy ${path}: it is a symbolic link. To run a binary of your own, ` + + "set FAILPROOFAI_DAEMON_BINARY to its real path", + ); + } + throw err; + } + try { + if (!fstatSync(fd).isFile()) throw new Error(`refusing to copy ${path}: it is not a regular file`); + return readFileSync(fd); } finally { - rmSync(stagingDir, { recursive: true, force: true }); + closeSync(fd); } } @@ -1023,45 +1181,111 @@ export interface DaemonInstallResult { reason?: string; } +/** The shell function the manual recipe defines once and sends every root write through. */ +const RECIPE_WRITE_FN = "failproofai_install"; + /** - * The privileged commands an install performs — returned verbatim so a - * machine that cannot elevate can be told exactly what to run rather than - * just that something failed. + * The recipe step that writes `contents` to `destination` as root, carried + * inline and checked against its digest by the same script the automatic + * install runs. + * + * A single-quoted `printf`, not a here-document: an interactive shell expands + * history (`!`) in a here-document's body (zsh, the macOS default, does) but + * never inside single quotes, and the plist's `/dev/null || true; }`, - ] - : []; - return [ - ...stage, - `sudo tee ${systemdUnitPath()} <<'EOF'\n${systemdUnitContents(target ?? binaryPath, workerCmd, cliCmd)}EOF`, - "sudo systemctl daemon-reload", - `sudo systemctl enable ${systemdUnitName()}`, + const steps: string[] = []; + if (target) { + const digest = sha256Hex(readDaemonBinaryForRoot(binaryPath)); + steps.push( + // Quoted: a home directory may hold a space, and an unquoted path + // splits into words that stop this `&&`-chained recipe before the + // unit is ever written. + recipeCommand("install", "-d", "-m", "0755", shellQuote(systemBinaryDir())), + `${RECIPE_WRITE_FN} ${shellQuote(target)} ${digest} 0755 < ${shellQuote(binaryPath)}`, + ); + // Only where root's directories have it: SELinux systems always do, and a + // bare name would leave sudo to find one. + if (systemCommandPath("restorecon")) { + steps.push(`{ ${recipeCommand("restorecon", "-R", shellQuote(systemBinaryRoot()))} 2>/dev/null || true; }`); + } + } + steps.push( + recipeWriteInline(systemdUnitPath(), systemdUnitContents(target ?? binaryPath, workerCmd, cliCmd), "0644"), + recipeCommand("systemctl", "daemon-reload"), + recipeCommand("systemctl", "enable", systemdUnitName()), // `restart`, not `enable --now`, for the reason the install path gives: // `--now` does nothing to an already-active unit, and these commands are // handed to someone whose daemon may well be running — an upgrade is the // most likely reason they are reading them. - `sudo systemctl restart ${systemdUnitName()}`, - ]; + recipeCommand("systemctl", "restart", systemdUnitName()), + ); + return renderRecipe(steps); + } + // The same order as the install: the log directory the plist names, the + // plist, then unload and load, since a plain `load` of a label launchd + // already has is a no-op. + const plistPath = launchdPlistPath(); + const logDir = logsDir(); + return renderRecipe([ + `mkdir -p ${shellQuote(logDir)}`, + recipeWriteInline(plistPath, launchdPlistContents(binaryPath, logDir, workerCmd, cliCmd), "0644"), + `{ ${recipeCommand("launchctl", "unload", shellQuote(plistPath))} 2>/dev/null || true; }`, + recipeCommand("launchctl", "load", "-w", shellQuote(plistPath)), + ]); +} + +/** The manual-install half of the needs-root reason. Never throws. */ +function manualInstallSteps(binaryPath: string, workerCmd: string | null, cliCmd: string | null): string { + try { + return `To install by hand, run:\n${daemonInstallRecipe(binaryPath, workerCmd, cliCmd)}`; + } catch (err) { + return `No manual steps could be prepared: ${err instanceof Error ? err.message : String(err)}.`; } - return [ - `sudo tee ${launchdPlistPath()} < the plist failproofai config would write`, - `sudo launchctl load -w ${launchdPlistPath()}`, - ]; } /** @@ -1120,11 +1344,25 @@ export async function installDaemonService(): Promise { reason: "root privileges are required to install the failproofaid system service, and sudo credentials were not available. " + "Re-run `failproofai config` and approve the sudo prompt — do NOT run the CLI itself under sudo, which would " + - "configure root's account instead of yours. To install by hand: " + - daemonInstallCommands(binaryPath, workerCmd, cliCmd).join(" && "), + "configure root's account instead of yours. " + + manualInstallSteps(binaryPath, workerCmd, cliCmd), }; } + // The bytes root will install under /opt, read and checked BEFORE anything + // is torn down below: a binary that is refused must leave whatever daemon + // runs now still running. + let stagedBytes: Buffer | undefined; + if (process.platform === "linux" && systemBinaryTarget(binaryPath)) { + try { + stagedBytes = readDaemonBinaryForRoot(binaryPath); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + hookLogWarn(`daemon service install failed: ${msg}`); + return { installed: false, reason: msg }; + } + } + // A daemon left over from a pre-1.0.0-beta.1 install holds the same // singleton lock the new one needs, so the system unit would start, lose // the flock race, and leave the machine fail-closed against a daemon that @@ -1136,7 +1374,7 @@ export async function installDaemonService(): Promise { if (process.platform === "linux") { // Before the unit is written, so a copy that fails leaves the previous // unit and the daemon it runs untouched. See `systemBinaryDir()`. - execPath = stageSystemBinary(binaryPath); + execPath = stageSystemBinary(binaryPath, stagedBytes); writePrivilegedFile(systemdUnitPath(), systemdUnitContents(execPath, workerCmd, cliCmd)); runPrivileged("systemctl", ["daemon-reload"]); // `enable` for boot persistence, then `restart` — NOT `enable --now`. @@ -1764,9 +2002,9 @@ export async function ensureDaemonServiceCurrent(): Promise // What to put back if this goes wrong, and from which point. Set BEFORE the // step that can leave the machine changed, not after it succeeds: on Linux - // `writePrivilegedFile` is an `install` copy straight onto the unit path, so - // a failure part-way through leaves a truncated unit behind, and on macOS - // the unload has already stopped the daemon before anything is written. + // the new unit is in place the moment `writePrivilegedFile` renames it there, + // whatever happens to the reload after it, and on macOS the unload has + // already stopped the daemon before anything is written. let previous: string | null = null; try { @@ -1938,12 +2176,17 @@ export async function refreshDaemonToCliVersion( // and names this command: get sudo, then run it again. Never "run the CLI // under sudo" — that would configure root's account instead of this one. const needsRoot = /root privileges are required/.test(result.reason ?? ""); + // Only a sudo from root's own directories is named; with none there, a + // bare `sudo` would be whatever the user's PATH finds first. + const sudo = sudoPath(); return { ok: false, lines: needsRoot ? [ `✕ failproofaid ${version} was not installed: root privileges are required. The previous daemon is untouched.`, - " Run `sudo -v` and then `failproofai update` again.", + sudo + ? ` Run \`${sudo} -v\` and then \`failproofai update\` again.` + : ` No sudo was found in ${SYSTEM_BIN_DIRS.join(", ")}, so failproofai cannot install its service here.`, ] : [ `✕ failproofaid ${version} could not be installed: ${(result.reason ?? "unknown reason").replace(/\.$/, "")}. ` + @@ -2163,16 +2406,12 @@ export function daemonServiceStatus(): DaemonServiceStatus { // running daemon read as dead, and the wizard then demanded a password to // unload and reload a service that was fine. if (!root && !canElevate()) return "unknown"; - const args = ["print", `system/${launchdLabel()}`]; - const out = root - ? execFileSync("launchctl", args, { - stdio: ["ignore", "pipe", "ignore"], - timeout: SERVICE_CMD_TIMEOUT_MS, - }).toString() - : execFileSync("sudo", ["-n", "launchctl", ...args], { - stdio: ["ignore", "pipe", "ignore"], - timeout: SERVICE_CMD_TIMEOUT_MS, - }).toString(); + const [cmd, argv] = elevatedCommand("launchctl", ["print", `system/${launchdLabel()}`]); + const out = execFileSync(cmd, argv, { + stdio: ["ignore", "pipe", "ignore"], + timeout: SERVICE_CMD_TIMEOUT_MS, + env: privilegedEnv(), + }).toString(); // `state = running` is launchd's own wording; a loaded-but-dead job // prints `state = not running` and must not read as healthy. return /state\s*=\s*running/.test(out) ? "running" : "stopped"; diff --git a/src/hooks/manager.ts b/src/hooks/manager.ts index d75810bcf..a826eb215 100644 --- a/src/hooks/manager.ts +++ b/src/hooks/manager.ts @@ -41,6 +41,7 @@ import type { ResolvedPack } from "./pack-manifest"; import { hasInstalledRegexPacks, readInstalledPacks } from "./pack-manifest"; import { packPolicyParamKey } from "./policy-evaluator"; import { probeDaemonPolicyEvaluation } from "./daemon-service"; +import { NO_PRINTED_COMMAND_REASON, sudoPath } from "./system-command"; import { keepAgentSelectionTrue } from "./agent-selection"; import { INDENT, colorsEnabled, optsFor, printBlock, screenKit, type ScreenKitOpts } from "./tui"; @@ -1160,11 +1161,15 @@ export async function removeHooks(policyNames?: string[], scope: HookScope | "al } } else if (system.status === "failed") { // Non-interactive by design (this also runs from the dashboard), so - // the fix is to prime sudo and come back. + // the fix is to prime sudo and come back. Only a sudo from root's own + // directories is named: a bare one is whatever PATH finds first. + const sudo = sudoPath(); for (const line of screenKit(optsFor(process.stdout)).notice( "caution", `failproofai's Codex hooks are still in ${system.path}: ${system.reason}.\n` + - "Run `sudo -v`, then this command again.", + (sudo + ? `Run \`${sudo} -v\`, then this command again.` + : `Remove failproofai's block from ${system.path} as root (${NO_PRINTED_COMMAND_REASON}).`), )) { say(line); } diff --git a/src/hooks/system-command.ts b/src/hooks/system-command.ts new file mode 100644 index 000000000..71937a0a6 --- /dev/null +++ b/src/hooks/system-command.ts @@ -0,0 +1,90 @@ +/** + * How failproofai names the programs it runs as root: by absolute path, from + * root's own directories, with a minimal environment. Never through PATH. + * + * PATH and the rest of the caller's environment belong to the user, and sudo + * may look programs up in that PATH too. Root's programs, and the sudo the user + * types their password into, come from root's own directories instead. + */ +import { accessSync, constants as fsConstants, statSync } from "node:fs"; + +/** Root's own program directories, in lookup order. */ +export const SYSTEM_BIN_DIRS: readonly string[] = ["/usr/bin", "/bin", "/usr/sbin", "/sbin"]; + +/** The PATH every privileged command runs with. */ +export const SYSTEM_PATH = SYSTEM_BIN_DIRS.join(":"); + +/** + * The absolute path of a system program such as `sudo`, `systemctl`, + * `launchctl` or `install`, from {@link SYSTEM_BIN_DIRS} only, or null when + * none of them has it. + */ +export function systemCommandPath(name: string): string | null { + if (!/^[A-Za-z0-9._-]+$/.test(name)) return null; + for (const dir of SYSTEM_BIN_DIRS) { + const candidate = `${dir}/${name}`; + try { + if (!statSync(candidate).isFile()) continue; + accessSync(candidate, fsConstants.X_OK); + return candidate; + } catch { + // Not in this directory: try the next. + } + } + return null; +} + +/** {@link systemCommandPath}, or an error that says where it looked. */ +export function requireSystemCommand(name: string): string { + const path = systemCommandPath(name); + if (!path) throw new Error(`${name} was not found in ${SYSTEM_BIN_DIRS.join(", ")}`); + return path; +} + +/** + * The caller's settings sudo itself may need: the terminal type and locale for + * its prompt, and the SSH agent socket and Kerberos credential cache that PAM + * modules such as pam_ssh_agent_auth and pam_sss_gss authenticate with. None of + * them names code to run. + */ +const PASSED_THROUGH = ["TERM", "LANG", "LC_ALL", "LC_CTYPE", "LC_MESSAGES", "SSH_AUTH_SOCK", "KRB5CCNAME"] as const; + +/** + * The environment every privileged command starts with: root's PATH, plus the + * few settings above that sudo's own prompt and authentication use. Nothing + * else of the caller's reaches sudo or what it runs: no PATH, no loader or + * shell variables, no `SUDO_ASKPASS` or `SUDO_PROMPT`. + */ +export function privilegedEnv(): NodeJS.ProcessEnv { + const env: Record = { PATH: SYSTEM_PATH }; + for (const key of PASSED_THROUGH) { + const value = process.env[key]; + if (value) env[key] = value; + } + // Cast rather than padded: this project's ambient types (Next.js) declare + // NODE_ENV required on every ProcessEnv, and a privileged command needs none. + return env as NodeJS.ProcessEnv; +} + +/** + * Why no command to run as root is printed, where a caller would have printed + * one: a printed bare name is looked up by whoever runs it (their shell's PATH, + * or sudo's), which is the lookup this module exists to avoid. + */ +export const NO_PRINTED_COMMAND_REASON = `sudo or the program it would run is not in ${SYSTEM_BIN_DIRS.join(", ")}, so no command to run as root is printed`; + +/** `sudo` as printed for someone to run: its absolute path, or null where root's directories have none. */ +export function sudoPath(): string | null { + return systemCommandPath("sudo"); +} + +/** + * A privileged command as printed for someone to run: `sudo` and the program + * by absolute path, or null where root's directories lack either; never a bare + * name. `args` are pasted as given, so the caller quotes them. + */ +export function sudoCommandLine(command: string, ...args: string[]): string | null { + const sudo = sudoPath(); + const program = systemCommandPath(command); + return sudo && program ? [sudo, program, ...args].join(" ") : null; +} diff --git a/src/hooks/uninstall-cli.ts b/src/hooks/uninstall-cli.ts index 9e58dc97d..158e4225f 100644 --- a/src/hooks/uninstall-cli.ts +++ b/src/hooks/uninstall-cli.ts @@ -49,6 +49,7 @@ import { listInstallableIds, getIntegration } from "./integrations"; import type { IntegrationType } from "./types"; import { removeHooks } from "./manager"; import { shellQuote } from "./shell-quote"; +import { NO_PRINTED_COMMAND_REASON, sudoCommandLine } from "./system-command"; import { installedAgentSkillDirs, removeAgentSkill } from "./agent-skill"; import { CODEX_MANAGED_BEGIN, CODEX_MANAGED_END, codexSystemConfigPath, codexSystemHooksPresent } from "./codex-system-hooks"; import { optsFor, screenKit, type RenderOpts } from "./tui"; @@ -360,10 +361,15 @@ export async function runUninstallCommand(opts: UninstallOptions = {}): Promise< // "still there, here is what to run as root" path below. elevateOnce(); // What to run as root when the removal could not elevate, and where to look. - const byHand = (servicePath: string): string => - "\nRemove it as root:\n" + - manualServiceRemoval(servicePath).map((step) => ` \`${step}\``).join("\n") + - (daemonStatusCommand() ? `\nCheck it with \`${daemonStatusCommand()}\`` : ""); + const byHand = (servicePath: string): string => { + const steps = manualServiceRemoval(servicePath); + return ( + (steps + ? "\nRemove it as root:\n" + steps.map((step) => ` \`${step}\``).join("\n") + : `\nRemove ${servicePath} as root (${NO_PRINTED_COMMAND_REASON}).`) + + (daemonStatusCommand() ? `\nCheck it with \`${daemonStatusCommand()}\`` : "") + ); + }; try { await uninstallDaemonService(); // uninstallDaemonService is best-effort by contract — it warns and @@ -375,9 +381,10 @@ export async function runUninstallCommand(opts: UninstallOptions = {}): Promise< byHand(found.servicePath), ); } else if (found.stagedBinaryDir && existsSync(found.stagedBinaryDir)) { + const removal = sudoCommandLine("rm", "-rf", shellQuote(found.stagedBinaryDir)); failures.push( `The failproofaid binary in ${found.stagedBinaryDir} is still there, most often because sudo was not available.` + - `\nRemove it as root:\n \`sudo rm -rf ${shellQuote(found.stagedBinaryDir)}\``, + (removal ? `\nRemove it as root:\n \`${removal}\`` : `\nRemove it as root (${NO_PRINTED_COMMAND_REASON}).`), ); } else if (found.serviceInstalled) { lines.push(kit.ok("Stopped and removed the failproofaid service.")); @@ -429,21 +436,29 @@ export async function runUninstallCommand(opts: UninstallOptions = {}): Promise< return { exitCode: 0, lines, planLines, purged }; } -/** The exact commands to finish a service removal that could not elevate. The - * paths are quoted: these are pasted into a root shell, and an unquoted path - * holding a space would make `rm -rf` remove something else. */ -function manualServiceRemoval(servicePath: string): string[] { +/** The exact commands to finish a service removal that could not elevate, or + * null where root's directories lack sudo or a program they name (see + * system-command.ts: a printed bare name is looked up through the user's + * PATH). The paths are quoted: these are pasted into a root shell, and an + * unquoted path holding a space would make `rm -rf` remove something else. */ +function manualServiceRemoval(servicePath: string): string[] | null { + const steps: (string | null)[] = []; if (process.platform === "darwin") { - return [`sudo launchctl unload -w ${shellQuote(servicePath)}`, `sudo rm -f ${shellQuote(servicePath)}`]; + steps.push( + sudoCommandLine("launchctl", "unload", "-w", shellQuote(servicePath)), + sudoCommandLine("rm", "-f", shellQuote(servicePath)), + ); + } else { + const unit = servicePath.split("/").pop() ?? servicePath; + const binDir = daemonSystemBinaryDir(); + steps.push( + sudoCommandLine("systemctl", "disable", "--now", unit), + sudoCommandLine("rm", "-f", shellQuote(servicePath)), + sudoCommandLine("systemctl", "daemon-reload"), + ...(binDir ? [sudoCommandLine("rm", "-rf", shellQuote(binDir))] : []), + ); } - const unit = servicePath.split("/").pop() ?? servicePath; - const binDir = daemonSystemBinaryDir(); - return [ - `sudo systemctl disable --now ${unit}`, - `sudo rm -f ${shellQuote(servicePath)}`, - `sudo systemctl daemon-reload`, - ...(binDir ? [`sudo rm -rf ${shellQuote(binDir)}`] : []), - ]; + return steps.every((step): step is string => step !== null) ? steps : null; } /** What `daemonServiceStatus()` says, for the status line the CLI prints. */