Public: anyone can read this; the crew can change it.
Forges sharing a machine each get a cgroup and a sandbox, so no neighbour starves or reads another #16938
Check · Review · Land · Live done — Landed and live in production.
mason/forge:mason/16856-forges-sharing-a-machine-each-get-a-cgro → main 0 commits fork
9 files
changed +245
−25
docs/features/landlock-floor.md +11 −2
| @@ -21,8 +21,17 @@ holds the work instead, with no root and no namespace. | ||
| 21 | 21 | `reads are not hidden`, and what that kernel did not enforce. |
| 22 | 22 | - **Checks.** Under bubblewrap the step command is also wrapped in Landlock (stacked, inside the |
| 23 | 23 | cell). With no cell, the check step is held by Landlock alone, writing its checkout, its home and |
| 24 | a temp directory of its own (not the machine's `/tmp`); the log line names the ABI and says reads | |
| 25 | are open. | |
| 24 | a temp directory of its own (not the machine's `/tmp`); the log line names the ABI and says what | |
| 25 | reads stay open. Its reads are held too: the forge's data directory (its database, its key, every | |
| 26 | other check's checkout, a neighbour's files) is not readable, only the check's own directories | |
| 27 | and the install cache under it. Landlock only adds rights, so the plan (`readRootsAround`) grants | |
| 28 | every sibling along the way to the hidden path instead of `/`; a hidden path's parent cannot be | |
| 29 | listed, a link is never granted, and hidden paths are planned by their real name (one that cannot | |
| 30 | be resolved fails the plan). No other process's `/proc/<pid>` is readable (its environment and | |
| 31 | open files are the forge's own); the step's own is. A check can write `/dev/null`. This holds | |
| 32 | checks only: hosted child forges on a host with Landlock and no bubblewrap are not yet held this | |
| 33 | way (`hide` and `keep` exist in the plan for it); under bubblewrap they are covered by the | |
| 34 | mounts and cgroups. | |
| 26 | 35 | - **Never silent.** The kernel's ABI is probed; rights it lacks are dropped and named. UDP is never |
| 27 | 36 | covered before ABI 10 and every record says so. |
| 28 | 37 | - `FORGE_LANDLOCK=off` declines the floor on purpose. |
src/apps/process.ts +3 −3
| @@ -10,7 +10,7 @@ | ||
| 10 | 10 | * app, not to a shell that would swallow it. |
| 11 | 11 | */ |
| 12 | 12 | |
| 13 | import { landlockArgv, landlockPlan } from "../sandbox/landlock.ts"; | |
| 13 | import { type LandlockWant, landlockArgv, landlockPlan } from "../sandbox/landlock.ts"; | |
| 14 | 14 | import type { AppManifest } from "./manifest.ts"; |
| 15 | 15 | import type { EnvName } from "./data.ts"; |
| 16 | 16 | import { envPull } from "./data.ts"; |
| @@ -391,7 +391,7 @@ export async function runStep( | ||
| 391 | 391 | * Where no cell can be made: the Landlock floor the plain child is exec-wrapped in (#16835). |
| 392 | 392 | * Writable: its directory and `writable`; read-only elsewhere. |
| 393 | 393 | */ |
| 394 | floor?: { readonly abi: number; readonly writable: readonly string[] } | undefined; | |
| 394 | floor?: (Pick<LandlockWant, "writable" | "hide" | "keep"> & { readonly abi: number }) | undefined; | |
| 395 | 395 | /** |
| 396 | 396 | * Set for a build step (install, test): its limits. The time is the |
| 397 | 397 | * step's bound, and a stop by any limit is one line saying which. |
| @@ -422,7 +422,7 @@ export async function runStep( | ||
| 422 | 422 | let proc: ReturnType<typeof Bun.spawn<"ignore", "pipe", "pipe">>; |
| 423 | 423 | try { |
| 424 | 424 | const plain = ["/bin/sh", "-c", command]; |
| 425 | const floored = options.floor === undefined ? plain : landlockArgv(landlockPlan(options.floor.abi, { writable: options.floor.writable }), plain); | |
| 425 | const floored = options.floor === undefined ? plain : landlockArgv(landlockPlan(options.floor.abi, options.floor), plain); | |
| 426 | 426 | proc = Bun.spawn(backgroundArgv(cell?.argv(command) ?? floored), { |
| 427 | 427 | cwd: options.cwd, |
| 428 | 428 | env: cell?.env(options.env) ?? options.env, |
src/checks/floor.ts added +16
| @@ -0,0 +1,16 @@ | ||
| 1 | /** | |
| 2 | * What a check with no cell is held by: the Landlock floor around its own directories (#16856). | |
| 3 | */ | |
| 4 | import { checkInstallCache } from "./install.ts"; | |
| 5 | import type { LandlockWant } from "../sandbox/landlock.ts"; | |
| 6 | ||
| 7 | /** | |
| 8 | * The floor for a check run in `dir`: it writes its checkout, its home and a temp directory of its | |
| 9 | * own (never the machine's /tmp, which other users share) and `/dev/null`, so `2>/dev/null` works. | |
| 10 | * The forge's data (its database, its key, every other check's checkout) is not its to read; its | |
| 11 | * own directories and the install cache stay. | |
| 12 | */ | |
| 13 | export function checkFloor(abi: number, dir: string, dataDir: string, repoId: string): Pick<LandlockWant, "writable" | "hide" | "keep"> & { abi: number } { | |
| 14 | const own = [dir, `${dir}.home`, `${dir}.tmp`]; | |
| 15 | return { abi, writable: [...own, "/dev/null"], hide: [dataDir], keep: [...own, checkInstallCache(dataDir, repoId)] }; | |
| 16 | } |
src/checks/run_tier.ts +6 −7
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | |
| 2 | import { CHECK_FLOOR_ENV, READS_OPEN } from "../sandbox/landlock.ts"; | |
| 2 | import { checkFloor } from "./floor.ts"; | |
| 3 | import { CHECK_FLOOR_ENV, READS_PARTLY } from "../sandbox/landlock.ts"; | |
| 3 | 4 | import { probeLandlock } from "../sandbox/landlock_probe.ts"; |
| 4 | 5 | import { cellHides } from "../spawn/hosted-mark.ts"; |
| 5 | 6 | import { forgeApiKey } from "../crew/runner_env.ts"; |
| @@ -208,7 +209,7 @@ async function runTierOnce(lane: LaneState, x: Execution, sample: (green: LentGr | ||
| 208 | 209 | write("placement: job skipped, this cluster names no egress gate for a Job (FORGE_CHECKS_EGRESS_GATE)"); |
| 209 | 210 | // A Job is its own boundary: no cell here, the cluster and its gate hold it. |
| 210 | 211 | const cells = job === undefined ? await cellsAvailable() : undefined; |
| 211 | let floor: { abi: number; writable: string[] } | undefined; | |
| 212 | let floor: ReturnType<typeof checkFloor> | undefined; | |
| 212 | 213 | if (cells !== undefined) { |
| 213 | 214 | if (x.runId !== undefined) |
| 214 | 215 | noteRunProgress(app.db, x.runId, { |
| @@ -219,10 +220,8 @@ async function runTierOnce(lane: LaneState, x: Execution, sample: (green: LentGr | ||
| 219 | 220 | // (#16835). |
| 220 | 221 | const held = await probeLandlock(); |
| 221 | 222 | if (held.ok) { |
| 222 | // The checkout, its home and a temp directory of this check's own: never the machine's | |
| 223 | // /tmp, which other users share. | |
| 224 | floor = { abi: held.abi, writable: [dir, `${dir}.home`, `${dir}.tmp`] }; | |
| 225 | const note = `${held.note}; ${READS_OPEN}`; | |
| 223 | floor = checkFloor(held.abi, dir, app.config.dataDir, repo.id); | |
| 224 | const note = `${held.note}; ${READS_PARTLY}`; | |
| 226 | 225 | if (x.runId !== undefined) noteRunProgress(app.db, x.runId, { sandbox: { enforced: true, note } }); |
| 227 | 226 | write(`no cell here: ${cells.reason}; the check step is held by ${note}`); |
| 228 | 227 | } else write(`uncontained here: ${cells.reason}; ${held.reason}; the check runs unrestricted`); |
| @@ -262,7 +261,7 @@ async function runTierOnce(lane: LaneState, x: Execution, sample: (green: LentGr | ||
| 262 | 261 | const cellCpus = resolveLimits("step", manifest.limits).cpus; |
| 263 | 262 | const shardCpus = checkShardCpus(cellCpus); |
| 264 | 263 | write(shardsLine(shardsInForce(app.db, shardCpus, x.tier === "verify"))); |
| 265 | if (floor !== undefined) for (const path of floor.writable) mkdirSync(path, { recursive: true }); | |
| 264 | if (floor !== undefined) for (const path of floor.writable.filter((p) => !p.startsWith("/dev/"))) mkdirSync(path, { recursive: true }); | |
| 266 | 265 | const env = childEnv({ |
| 267 | 266 | // The shard count an admin set (`core/capacity.ts`), else the |
| 268 | 267 | // default sized to what this check's cell holds, never the pod's. |
src/sandbox/landlock.ts +96 −5
| @@ -13,6 +13,8 @@ | ||
| 13 | 13 | * arrived in ABI 10), so every run record says it is not. |
| 14 | 14 | */ |
| 15 | 15 | |
| 16 | import { lstatSync, readdirSync, realpathSync } from "node:fs"; | |
| 17 | ||
| 16 | 18 | /** Filesystem access bits, by the ABI that introduced them (include/uapi/linux/landlock.h). */ |
| 17 | 19 | const FS_BITS: readonly (readonly [string, number, number])[] = [ |
| 18 | 20 | ["execute", 0, 1], ["write_file", 1, 1], ["read_file", 2, 1], ["read_dir", 3, 1], |
| @@ -31,6 +33,13 @@ export interface LandlockWant { | ||
| 31 | 33 | readonly writable: readonly string[]; |
| 32 | 34 | /** TCP connect allowed to these ports only; undefined leaves TCP unconfined. */ |
| 33 | 35 | readonly connect?: readonly number[] | undefined; |
| 36 | /** | |
| 37 | * Paths whose contents are not readable at all (a neighbour forge's data, the host's own). The | |
| 38 | * rest of the machine stays readable, except `keep`: places under a hidden path that are shown | |
| 39 | * again (a forge's own directory). | |
| 40 | */ | |
| 41 | readonly hide?: readonly string[] | undefined; | |
| 42 | readonly keep?: readonly string[] | undefined; | |
| 34 | 43 | } |
| 35 | 44 | |
| 36 | 45 | export interface LandlockPlan { |
| @@ -43,12 +52,18 @@ export interface LandlockPlan { | ||
| 43 | 52 | readonly writable: readonly string[]; |
| 44 | 53 | /** Allowed connect ports; meaningful only when `handledNet` is not 0. */ |
| 45 | 54 | readonly connect: readonly number[]; |
| 55 | /** | |
| 56 | * Where reads are allowed, when some path is hidden: Landlock only adds, so "everything but" is | |
| 57 | * every sibling along the way to a hidden path. Empty means the whole filesystem (`/`). | |
| 58 | */ | |
| 59 | readonly readRoots: readonly string[]; | |
| 46 | 60 | /** What was asked for and the kernel cannot hold: never silent. */ |
| 47 | 61 | readonly stripped: readonly string[]; |
| 48 | 62 | } |
| 49 | 63 | |
| 50 | 64 | /** The plan for `want` on a kernel of `abi`: what the kernel lacks is dropped and named. */ |
| 51 | 65 | export function landlockPlan(abi: number, want: LandlockWant): LandlockPlan { |
| 66 | if (!validWant(want)) throw new Error("landlock: unsafe request"); | |
| 52 | 67 | const stripped: string[] = []; |
| 53 | 68 | let handledFs = 0; |
| 54 | 69 | for (const [, bit, since] of FS_BITS) if (abi >= since) handledFs |= 1 << bit; |
| @@ -62,12 +77,84 @@ export function landlockPlan(abi: number, want: LandlockWant): LandlockPlan { | ||
| 62 | 77 | let scoped = 0; |
| 63 | 78 | if (abi >= 6) scoped = SCOPE_ABSTRACT_UNIX | SCOPE_SIGNAL; |
| 64 | 79 | else stripped.push("abstract-socket and signal scope (needs ABI 6)"); |
| 65 | return { abi, handledFs, handledNet, scoped, writable: want.writable, connect: want.connect ?? [], stripped }; | |
| 80 | const hide = (want.hide ?? []).map(resolveHidden); | |
| 81 | const readRoots = hide.length === 0 ? [] : readRootsAround(hide, (want.keep ?? []).flatMap(resolveKept)); | |
| 82 | return { abi, handledFs, handledNet, scoped, writable: want.writable, connect: want.connect ?? [], readRoots, stripped }; | |
| 83 | } | |
| 84 | ||
| 85 | /** | |
| 86 | * A hidden path by its real name: reached through a link (`/data` -> `/mnt/x`), the walk would | |
| 87 | * grant the real place as an ordinary sibling. A path that cannot be resolved cannot be hidden, so | |
| 88 | * it throws: the plan fails closed rather than quietly leaving it readable. | |
| 89 | */ | |
| 90 | function resolveHidden(path: string): string { | |
| 91 | try { | |
| 92 | return realpathSync(path); | |
| 93 | } catch { | |
| 94 | throw new Error(`landlock: cannot resolve hidden path ${path}`); | |
| 95 | } | |
| 96 | } | |
| 97 | ||
| 98 | /** A kept path by its real name; one that is not there grants nothing, so it is left out. */ | |
| 99 | function resolveKept(path: string): string[] { | |
| 100 | try { | |
| 101 | return [realpathSync(path)]; | |
| 102 | } catch { | |
| 103 | return []; | |
| 104 | } | |
| 105 | } | |
| 106 | ||
| 107 | const isLink = (path: string): boolean => { | |
| 108 | try { | |
| 109 | return lstatSync(path).isSymbolicLink(); | |
| 110 | } catch { | |
| 111 | return true; | |
| 112 | } | |
| 113 | }; | |
| 114 | ||
| 115 | /** The entries of a directory, or none where it cannot be read. */ | |
| 116 | const listDir = (dir: string): string[] => { | |
| 117 | try { | |
| 118 | return readdirSync(dir); | |
| 119 | } catch { | |
| 120 | return []; | |
| 121 | } | |
| 122 | }; | |
| 123 | ||
| 124 | /** | |
| 125 | * Every place to read so that nothing under `hide` can be: the siblings of each step on the way | |
| 126 | * to a hidden path, then `keep`. A hidden directory's parent itself cannot be listed (only what is | |
| 127 | * beneath its other entries), which is the price of a floor that has no mounts. | |
| 128 | */ | |
| 129 | export function readRootsAround(hide: readonly string[], keep: readonly string[], list: (dir: string) => string[] = listDir, link: (path: string) => boolean = isLink): string[] { | |
| 130 | const roots = new Set<string>(); | |
| 131 | descend("/", hide.map((h) => h.replace(/\/+$/, "")), roots, list, link); | |
| 132 | for (const path of keep) roots.add(path); | |
| 133 | return [...roots].sort(); | |
| 134 | } | |
| 135 | ||
| 136 | /** Adds to `roots` each entry of `dir` that holds no hidden path, and descends into the ones that do. */ | |
| 137 | function descend(dir: string, rest: readonly string[], roots: Set<string>, list: (dir: string) => string[], link: (path: string) => boolean): void { | |
| 138 | // `rest` are the hidden paths at or under `dir`. | |
| 139 | for (const name of list(dir)) { | |
| 140 | const path = dir === "/" ? `/${name}` : `${dir}/${name}`; | |
| 141 | // Another process's /proc/<pid> (environ, cmdline, fd/) is the forge's own tokens and open | |
| 142 | // files, same user: only what is not a process stays. The helper adds its own pid. | |
| 143 | if (dir === "/proc" && /^\d+$/.test(name)) continue; | |
| 144 | const below = rest.filter((h) => h === path || h.startsWith(`${path}/`)); | |
| 145 | // A link is never a root: its target is granted by its own place, and a link granted would | |
| 146 | // open whatever it names, hidden or not. | |
| 147 | if (below.length === 0) { | |
| 148 | if (path === "/proc" && !link(path)) descend(path, [], roots, list, link); | |
| 149 | else if (!link(path)) roots.add(path); | |
| 150 | } else if (!below.includes(path)) descend(path, below, roots, list, link); | |
| 151 | } | |
| 66 | 152 | } |
| 67 | 153 | |
| 68 | 154 | /** The sentence a run records: the ABI that applied and what it does not cover. */ |
| 69 | 155 | export function landlockNote(plan: LandlockPlan): string { |
| 70 | 156 | const held = ["filesystem read-only outside the workspace"]; |
| 157 | if (plan.readRoots.length > 0) held.push("the host's and its neighbours' directories not readable"); | |
| 71 | 158 | if (plan.handledNet !== 0) held.push(`tcp connect to port${plan.connect.length === 1 ? "" : "s"} ${plan.connect.join(",")} only`); |
| 72 | 159 | if (plan.scoped !== 0) held.push("signals and abstract sockets scoped"); |
| 73 | 160 | const gaps = [...plan.stripped, "udp (not covered before ABI 10)"]; |
| @@ -84,11 +171,15 @@ export const CHECK_FLOOR_ENV = "FORGE_CHECK_FLOOR"; | ||
| 84 | 171 | /** What a floor used alone, with no bubblewrap above it, leaves open: said wherever it is named. */ |
| 85 | 172 | export const READS_OPEN = "reads are not hidden (the whole filesystem stays readable) and tcp is not confined"; |
| 86 | 173 | |
| 174 | /** What a floor that hides the forge's data leaves open: said wherever it is named. */ | |
| 175 | export const READS_PARTLY = "the forge's data is not readable, the rest of the machine stays readable, and tcp is not confined"; | |
| 176 | ||
| 177 | const absolute = (p: string): boolean => p.startsWith("/") && !p.includes("\0"); | |
| 178 | const realPort = (n: number): boolean => Number.isInteger(n) && n > 0 && n < 65536; | |
| 179 | ||
| 87 | 180 | /** Whether `want` is a safe request: absolute paths without NUL, real ports. */ |
| 88 | 181 | export function validWant(want: LandlockWant): boolean { |
| 89 | const path = (p: string): boolean => p.startsWith("/") && !p.includes("\0"); | |
| 90 | const port = (n: number): boolean => Number.isInteger(n) && n > 0 && n < 65536; | |
| 91 | return want.writable.every(path) && (want.connect ?? []).every(port); | |
| 182 | return want.writable.every(absolute) && (want.connect ?? []).every(realPort) && (want.hide ?? []).every(absolute) && (want.keep ?? []).every(absolute); | |
| 92 | 183 | } |
| 93 | 184 | |
| 94 | 185 | /** The helper's own path, next to this module. */ |
| @@ -99,6 +190,6 @@ export const HELPER = new URL("./landlock_helper.ts", import.meta.url).pathname; | ||
| 99 | 190 | * is not safe throws, so a request is never turned into a weaker one. |
| 100 | 191 | */ |
| 101 | 192 | export function landlockArgv(plan: LandlockPlan, argv: readonly string[], bun: string = process.execPath): string[] { |
| 102 | if (!validWant({ writable: plan.writable, connect: plan.connect })) throw new Error("landlock: unsafe plan"); | |
| 193 | if (![...plan.writable, ...plan.readRoots].every(absolute) || !plan.connect.every(realPort)) throw new Error("landlock: unsafe plan"); | |
| 103 | 194 | return [bun, HELPER, JSON.stringify(plan), "--", ...argv]; |
| 104 | 195 | } |
src/sandbox/landlock_helper.ts +6 −3
| @@ -43,7 +43,7 @@ if (process.argv[2] === "--abi") { | ||
| 43 | 43 | const split = process.argv.indexOf("--"); |
| 44 | 44 | if (split < 3 || split === process.argv.length - 1) die("usage: <plan> -- <command…>"); |
| 45 | 45 | const plan = JSON.parse(process.argv[2]!) as { |
| 46 | abi: number; handledFs: number; handledNet: number; scoped: number; writable: string[]; connect: number[]; | |
| 46 | abi: number; handledFs: number; handledNet: number; scoped: number; writable: string[]; connect: number[]; readRoots?: string[]; | |
| 47 | 47 | }; |
| 48 | 48 | const command = process.argv.slice(split + 1); |
| 49 | 49 | |
| @@ -60,7 +60,7 @@ function allow(path: string, access: number): void { | ||
| 60 | 60 | const fd = libc.open(ptr(cstr(path)), O_PATH_CLOEXEC); |
| 61 | 61 | if (fd < 0) { |
| 62 | 62 | // A writable place that is not there grants nothing; a read root that is not there is an error. |
| 63 | if (access === (plan.handledFs & READ)) die(`cannot open ${path}`); | |
| 63 | if (path === "/") die(`cannot open ${path}`); | |
| 64 | 64 | return; |
| 65 | 65 | } |
| 66 | 66 | // A file takes only the rights that mean something for one (the kernel refuses the rest). |
| @@ -75,7 +75,10 @@ function allow(path: string, access: number): void { | ||
| 75 | 75 | // execute, write_file, read_file, truncate, ioctl_dev |
| 76 | 76 | const FILE_RIGHTS = (1 << 0) | (1 << 1) | (1 << 2) | (1 << 14) | (1 << 15); |
| 77 | 77 | const READ = (1 << 0) | (1 << 2) | (1 << 3); |
| 78 | allow("/", plan.handledFs & READ); | |
| 78 | // Hidden paths leave no single root: each place that stays readable is its own rule. | |
| 79 | for (const root of plan.readRoots?.length ? plan.readRoots : ["/"]) allow(root, plan.handledFs & READ); | |
| 80 | // Where reads are narrowed, /proc is too: this process's own entry is read, no other's. | |
| 81 | if (plan.readRoots?.length) allow(`/proc/${process.pid}`, plan.handledFs & READ); | |
| 79 | 82 | for (const path of plan.writable) allow(path, plan.handledFs); |
| 80 | 83 | // struct landlock_net_port_attr: u64 allowed_access, u64 port. |
| 81 | 84 | for (const port of plan.connect) { |
test/check-floor.test.ts added +28
| @@ -0,0 +1,28 @@ | ||
| 1 | import { expect, test } from "bun:test"; | |
| 2 | import { checkFloor } from "../src/checks/floor.ts"; | |
| 3 | import { checkInstallCache } from "../src/checks/install.ts"; | |
| 4 | import { landlockPlan } from "../src/sandbox/landlock.ts"; | |
| 5 | import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; | |
| 6 | import { tmpdir } from "node:os"; | |
| 7 | import { join } from "node:path"; | |
| 8 | ||
| 9 | test("the floor a check with no cell is held by hides the forge's data and keeps its own places (#16856)", () => { | |
| 10 | const floor = checkFloor(6, "/d/checks/x", "/d", "r.1"); | |
| 11 | expect(floor.hide).toEqual(["/d"]); | |
| 12 | expect(floor.keep).toEqual(["/d/checks/x", "/d/checks/x.home", "/d/checks/x.tmp", checkInstallCache("/d", "r.1")]); | |
| 13 | expect(floor.writable).toEqual(["/d/checks/x", "/d/checks/x.home", "/d/checks/x.tmp", "/dev/null"]); | |
| 14 | }); | |
| 15 | ||
| 16 | test("that floor, handed to the plan runStep makes, narrows reads and keeps the check's directory", () => { | |
| 17 | const data = mkdtempSync(join(tmpdir(), "floor-data-")); | |
| 18 | try { | |
| 19 | const dir = join(data, "checks", "x"); | |
| 20 | mkdirSync(dir, { recursive: true }); | |
| 21 | const plan = landlockPlan(6, checkFloor(6, dir, data, "r.1")); | |
| 22 | expect(plan.readRoots).toContain(dir); | |
| 23 | expect(plan.readRoots).not.toContain(data); | |
| 24 | expect(plan.readRoots.some((r) => r.startsWith("/proc/") && /^\/proc\/\d+$/.test(r))).toBe(false); | |
| 25 | } finally { | |
| 26 | rmSync(data, { recursive: true }); | |
| 27 | } | |
| 28 | }); |
test/landlock-real.test.ts +3 −3
| @@ -47,16 +47,16 @@ describe("stacked under a real cell", () => { | ||
| 47 | 47 | describe("a check with no cell is held by the floor", () => { |
| 48 | 48 | const f = checksForge("forge-floor-"); |
| 49 | 49 | const outside = join(tmp, "outside"); |
| 50 | test.skipIf(!kernel.ok)("it writes its checkout and temp, is refused elsewhere, and the log says reads are open", async () => { | |
| 50 | test.skipIf(!kernel.ok)("it writes its checkout and temp, is refused elsewhere, and the log says what reads stay open", async () => { | |
| 51 | 51 | const was = { cells: process.env["FORGE_CELLS"], landlock: process.env["FORGE_LANDLOCK"] }; |
| 52 | 52 | process.env["FORGE_CELLS"] = "off"; |
| 53 | 53 | delete process.env["FORGE_LANDLOCK"]; |
| 54 | 54 | try { |
| 55 | 55 | mkdirSync(outside, { recursive: true }); |
| 56 | const command = `echo a > inside && echo b > "$TMPDIR/t" && case "$TMPDIR" in *.tmp) ;; *) exit 3;; esac; if sh -c 'echo c > ${outside}/f' 2>/dev/null; then exit 4; fi`; | |
| 56 | const command = `echo a > inside && echo b > "$TMPDIR/t" && case "$TMPDIR" in *.tmp) ;; *) exit 3;; esac; if sh -c 'echo c > ${outside}/f' 2>/dev/null; then exit 4; fi; if sh -c 'cat ${f.dataDir}/forge.db' >/dev/null 2>&1; then exit 5; fi; if sh -c 'cat /proc/${process.pid}/environ' >/dev/null 2>&1; then exit 6; fi`; | |
| 57 | 57 | const made = await f.slowCheck(command, "floor check"); |
| 58 | 58 | const run = await f.settled((r) => r.id === made); |
| 59 | expect(readRunLog(f.dataDir, run.id).lines.join("\n")).toContain("reads are not hidden"); | |
| 59 | expect(readRunLog(f.dataDir, run.id).lines.join("\n")).toContain("the forge's data is not readable"); | |
| 60 | 60 | expect(run.state).toBe("ok"); |
| 61 | 61 | expect(existsSync(join(outside, "f"))).toBe(false); |
| 62 | 62 | } finally { |
test/landlock.test.ts +76 −2
| @@ -1,8 +1,8 @@ | ||
| 1 | 1 | import { describe, expect, test } from "bun:test"; |
| 2 | import { mkdtempSync, readFileSync, rmSync } from "node:fs"; | |
| 2 | import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; | |
| 3 | 3 | import { tmpdir } from "node:os"; |
| 4 | 4 | import { join } from "node:path"; |
| 5 | import { NET_CONNECT_TCP, SCOPE_SIGNAL, landlockArgv, landlockNote, landlockPlan, validWant } from "../src/sandbox/landlock.ts"; | |
| 5 | import { NET_CONNECT_TCP, SCOPE_SIGNAL, landlockArgv, landlockNote, landlockPlan, readRootsAround, validWant } from "../src/sandbox/landlock.ts"; | |
| 6 | 6 | import { parseAbi, probeLandlock } from "../src/sandbox/landlock_probe.ts"; |
| 7 | 7 | |
| 8 | 8 | describe("landlockPlan", () => { |
| @@ -31,6 +31,47 @@ describe("landlockPlan", () => { | ||
| 31 | 31 | }); |
| 32 | 32 | }); |
| 33 | 33 | |
| 34 | describe("reads around a hidden path", () => { | |
| 35 | const tree: Record<string, string[]> = { "/": ["usr", "data", "etc"], "/data": ["forge.db", "children"], "/data/children": ["a", "b"] }; | |
| 36 | const list = (dir: string): string[] => tree[dir] ?? []; | |
| 37 | test("every sibling on the way to it is a root, it and its keep are not, unless kept", () => { | |
| 38 | expect(readRootsAround(["/data"], [], list, () => false)).toEqual(["/etc", "/usr"]); | |
| 39 | expect(readRootsAround(["/data"], ["/data/children/a"], list, () => false)).toEqual(["/data/children/a", "/etc", "/usr"]); | |
| 40 | expect(readRootsAround(["/data/children"], ["/data/children/a"], list, () => false)).toEqual(["/data/children/a", "/data/forge.db", "/etc", "/usr"]); | |
| 41 | }); | |
| 42 | test("a link is never a root: it would open whatever it names", () => { | |
| 43 | expect(readRootsAround(["/data"], [], list, (path) => path === "/etc")).toEqual(["/usr"]); | |
| 44 | }); | |
| 45 | test("a plan without a hidden path reads the whole filesystem, and says so in the note only when it hides", () => { | |
| 46 | expect(landlockPlan(6, { writable: [] }).readRoots).toEqual([]); | |
| 47 | expect(landlockNote(landlockPlan(6, { writable: [], hide: [tmpdir()] }))).toContain("neighbours' directories not readable"); | |
| 48 | expect(validWant({ writable: [], hide: ["rel"] })).toBe(false); | |
| 49 | }); | |
| 50 | }); | |
| 51 | ||
| 52 | describe("/proc and hidden paths that cannot be resolved", () => { | |
| 53 | test("no other process's /proc entry is a read root; what is not a process stays", () => { | |
| 54 | const tree: Record<string, string[]> = { "/": ["usr", "proc", "data"], "/proc": ["1", "4242", "sys", "cpuinfo", "self"] }; | |
| 55 | const roots = readRootsAround(["/data"], [], (dir) => tree[dir] ?? [], (path) => path === "/proc/self"); | |
| 56 | expect(roots).toEqual(["/proc/cpuinfo", "/proc/sys", "/usr"]); | |
| 57 | }); | |
| 58 | test("a hidden path that is not there fails the plan instead of leaving it readable", () => { | |
| 59 | expect(() => landlockPlan(6, { writable: [], hide: ["/nonexistent-forge-data"] })).toThrow("cannot resolve hidden path"); | |
| 60 | }); | |
| 61 | test("a hidden path reached through a link is planned by its real name", () => { | |
| 62 | const base = mkdtempSync(join(tmpdir(), "ll-link-")); | |
| 63 | try { | |
| 64 | mkdirSync(join(base, "real", "kept"), { recursive: true }); | |
| 65 | symlinkSync(join(base, "real"), join(base, "alias")); | |
| 66 | const plan = landlockPlan(6, { writable: [], hide: [join(base, "alias")], keep: [join(base, "alias", "kept")] }); | |
| 67 | expect(plan.readRoots).toContain(join(realpathSync(base), "real", "kept")); | |
| 68 | expect(plan.readRoots.some((r) => r.endsWith("/alias"))).toBe(false); | |
| 69 | } finally { | |
| 70 | rmSync(base, { recursive: true }); | |
| 71 | } | |
| 72 | }); | |
| 73 | }); | |
| 74 | ||
| 34 | 75 | describe("landlockArgv", () => { |
| 35 | 76 | test("puts the plan and the command behind the helper", () => { |
| 36 | 77 | const argv = landlockArgv(landlockPlan(6, { writable: ["/w"] }), ["sh", "-c", "true"], "bun"); |
| @@ -59,6 +100,22 @@ test("parseAbi takes a positive integer only", () => { | ||
| 59 | 100 | // The kernel is the judge: skipped (and so named) where this host has no Landlock. |
| 60 | 101 | const probe = process.platform === "linux" ? await probeLandlock({}) : { ok: false as const, reason: "not linux" }; |
| 61 | 102 | describe.skipIf(!probe.ok)("on this kernel", () => { |
| 103 | test("a hidden data directory reached through a link stays hidden, and no other process's environ is readable", () => { | |
| 104 | if (!probe.ok) return; | |
| 105 | const base = mkdtempSync(join(tmpdir(), "ll-alias-")); | |
| 106 | try { | |
| 107 | mkdirSync(join(base, "real")); | |
| 108 | writeFileSync(join(base, "real", "forge.db"), "db\n"); | |
| 109 | symlinkSync(join(base, "real"), join(base, "data")); | |
| 110 | const plan = landlockPlan(probe.abi, { writable: ["/dev/null"], hide: [join(base, "data")] }); | |
| 111 | const read = (path: string): string => `cat ${path} >/dev/null 2>&1 && echo open || echo refused`; | |
| 112 | const script = [read(join(base, "data", "forge.db")), read(join(base, "real", "forge.db")), read(`/proc/${process.pid}/environ`), read("/proc/$$/environ"), read("/proc/sys/kernel/ostype")].join("; "); | |
| 113 | const run = Bun.spawnSync(landlockArgv(plan, ["/bin/sh", "-c", script]), { stdout: "pipe", stderr: "pipe" }); | |
| 114 | expect(run.stdout.toString().split("\n")).toEqual(["refused", "refused", "refused", "open", "open", ""]); | |
| 115 | } finally { | |
| 116 | rmSync(base, { recursive: true }); | |
| 117 | } | |
| 118 | }); | |
| 62 | 119 | test("the helper writes where allowed, is refused elsewhere, and the command still runs", () => { |
| 63 | 120 | if (!probe.ok) return; |
| 64 | 121 | const ok = mkdtempSync(join(tmpdir(), "ll-ok-")); |
| @@ -76,6 +133,23 @@ describe.skipIf(!probe.ok)("on this kernel", () => { | ||
| 76 | 133 | rmSync(no, { recursive: true }); |
| 77 | 134 | } |
| 78 | 135 | }); |
| 136 | test("a forge's floor reads its own directory and not its neighbour's, nor the parent's files", () => { | |
| 137 | if (!probe.ok) return; | |
| 138 | const parent = mkdtempSync(join(tmpdir(), "ll-parent-")); | |
| 139 | try { | |
| 140 | const [mine, theirs] = [join(parent, "children", "alpha"), join(parent, "children", "beta")]; | |
| 141 | for (const dir of [mine, theirs]) mkdirSync(dir, { recursive: true }); | |
| 142 | writeFileSync(join(mine, "f"), "alpha\n"); | |
| 143 | writeFileSync(join(theirs, "f"), "beta\n"); | |
| 144 | writeFileSync(join(parent, "secret.key"), "key\n"); | |
| 145 | const plan = landlockPlan(probe.abi, { writable: [mine], hide: [parent], keep: [mine] }); | |
| 146 | const read = (path: string): string => `cat ${path} 2>&1 | sed "s/^cat: .*Permission denied/refused/"`; | |
| 147 | const run = Bun.spawnSync(landlockArgv(plan, ["/bin/sh", "-c", [read(join(mine, "f")), read(join(theirs, "f")), read(join(parent, "secret.key"))].join("; ")]), { stdout: "pipe", stderr: "pipe" }); | |
| 148 | expect(run.stdout.toString().split("\n")).toEqual(["alpha", "refused", "refused", ""]); | |
| 149 | } finally { | |
| 150 | rmSync(parent, { recursive: true }); | |
| 151 | } | |
| 152 | }); | |
| 79 | 153 | test("a plan the kernel refuses exits 126 and never runs the command", () => { |
| 80 | 154 | const plan = { ...landlockPlan(1, { writable: [] }), handledFs: 1 << 30 }; |
| 81 | 155 | const run = Bun.spawnSync(landlockArgv(plan, ["/bin/echo", "ran"]), { stdout: "pipe", stderr: "pipe" }); |
new above
offline