Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Option from "effect/Option";
4import * as Path from "effect/Path";
5import * as Schema from "effect/Schema";
6import * as ChildProcess from "effect/process/ChildProcess";
7import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
8
9import * as ProcessRunner from "../processRunner.ts";
10import { BOOT_SERVICE_UNIT_FILE } from "./bootService.ts";
11import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts";
12
13const PROTECT_DROP_IN = "90-t3code-protect.conf";
14const SYSTEM_UNIT_DIR = "/etc/systemd/system";
15export const REMOTE_ACCESS_UNITS = ["tailscaled.service", "ssh.service", "sshd.service"];
16
17// Covers app.slice (the server's 1536M) and init.scope (the user manager's 256M).
18const USER_CHAIN_LOW = "MemoryLow=2G";
19// Near the floor, but unlike -1000 the kernel can still kill it as a last resort.
20const PROTECTED_OOM_SCORE = "OOMScoreAdjust=-900";
21
22export interface DropIn {
23 readonly unit: string;
24 readonly path: string;
25 readonly contents: string;
26 /** Host-wide, so undo keeps it while another user's protection remains. */
27 readonly shared?: boolean;
28}
29
30export interface ProtectionPlan {
31 readonly systemUnitDir: string;
32 /** Written through sudo. */
33 readonly system: ReadonlyArray<DropIn>;
34 /**
35 * Written before the manager's own score drops. Unset, a user manager hands
36 * its services its own score plus 100: -800 once it runs at -900.
37 */
38 readonly managerDefaults: DropIn;
39 readonly user: ReadonlyArray<DropIn>;
40 /** System units whose running main process takes its configured OOM score at once. */
41 readonly oomUnits: ReadonlyArray<string>;
42}
43
44const dropIn = (
45 directory: string,
46 unit: string,
47 section: string,
48 properties: ReadonlyArray<string>,
49 shared = false,
50): DropIn => ({
51 unit,
52 path: `${directory}/${unit}.d/${PROTECT_DROP_IN}`,
53 contents: [`[${section}]`, ...properties, ""].join("\n"),
54 ...(shared ? { shared } : {}),
55});
56
57/**
58 * Memory protection only reaches the server when every ancestor cgroup grants
59 * it, and only root can grant it on user.slice and the user manager.
60 */
61export function protectionPlan(input: {
62 readonly uid: number;
63 readonly userUnitDir: string;
64 readonly remoteAccessUnits: ReadonlyArray<string>;
65 readonly systemUnitDir?: string;
66}): ProtectionPlan {
67 const manager = `user@${input.uid}.service`;
68 const remote = input.remoteAccessUnits;
69 const systemUnitDir = input.systemUnitDir ?? SYSTEM_UNIT_DIR;
70 const system = (unit: string, section: string, properties: ReadonlyArray<string>) =>
71 dropIn(systemUnitDir, unit, section, properties);
72 const shared = (unit: string, section: string, properties: ReadonlyArray<string>) =>
73 dropIn(systemUnitDir, unit, section, properties, true);
74 const user = (unit: string, section: string, properties: ReadonlyArray<string>) =>
75 dropIn(input.userUnitDir, unit, section, properties);
76 return {
77 systemUnitDir,
78 system: [
79 shared("user.slice", "Slice", [USER_CHAIN_LOW]),
80 system(`user-${input.uid}.slice`, "Slice", [USER_CHAIN_LOW]),
81 system(manager, "Service", [USER_CHAIN_LOW, PROTECTED_OOM_SCORE]),
82 ...(remote.length > 0 ? [shared("system.slice", "Slice", ["MemoryLow=512M"])] : []),
83 ...remote.map((unit) => shared(unit, "Service", ["MemoryLow=256M", PROTECTED_OOM_SCORE])),
84 ],
85 managerDefaults: {
86 unit: "user.conf",
87 path: `${input.userUnitDir.replace(/\/user$/, "")}/user.conf.d/${PROTECT_DROP_IN}`,
88 contents: "[Manager]\nDefaultOOMScoreAdjust=200\n",
89 },
90 user: [
91 user("app.slice", "Slice", ["MemoryLow=1536M"]),
92 user("init.scope", "Scope", ["MemoryLow=256M"]),
93 user(BOOT_SERVICE_UNIT_FILE, "Service", [PROTECTED_OOM_SCORE]),
94 ],
95 oomUnits: [manager, ...remote],
96 };
97}
98
99const quoteShell = (value: string) => `'${value.replaceAll("'", `'\\''`)}'`;
100const directoryOf = (file: string) => file.slice(0, file.lastIndexOf("/"));
101
102export function renderPrivilegedScript(plan: ProtectionPlan, mode: "apply" | "undo"): string {
103 const lines = ["set -e"];
104 const remove = (dropIns: ReadonlyArray<DropIn>, indent = "") => {
105 for (const { path } of dropIns) {
106 lines.push(
107 `${indent}rm -f ${quoteShell(path)}`,
108 `${indent}rmdir ${quoteShell(directoryOf(path))} 2>/dev/null || true`,
109 );
110 }
111 };
112 if (mode === "apply") {
113 for (const { path, contents } of plan.system) {
114 lines.push(
115 `mkdir -p ${quoteShell(directoryOf(path))}`,
116 `cat >${quoteShell(path)} <<'T3CODE_PROTECT'`,
117 contents.trimEnd(),
118 "T3CODE_PROTECT",
119 );
120 }
121 } else {
122 remove(plan.system.filter((dropIn) => dropIn.shared !== true));
123 const otherUsers = `${quoteShell(plan.systemUnitDir)}/user@*.service.d/${PROTECT_DROP_IN}`;
124 lines.push(`set -- ${otherUsers}`, 'if [ ! -e "$1" ]; then');
125 remove(
126 plan.system.filter((dropIn) => dropIn.shared === true),
127 " ",
128 );
129 lines.push("fi");
130 }
131 lines.push(
132 "systemctl daemon-reload",
133 // OOMScoreAdjust applies at exec; this gives running main processes the configured score.
134 `for unit in ${plan.oomUnits.map(quoteShell).join(" ")}; do`,
135 ' pid=$(systemctl show --property=MainPID --value "$unit")',
136 ' if [ "${pid:-0}" -gt 0 ]; then',
137 ' systemctl show --property=OOMScoreAdjust --value "$unit" >"/proc/$pid/oom_score_adj" || true',
138 " fi",
139 "done",
140 "",
141 );
142 return lines.join("\n");
143}
144
145export class ServiceProtectionError extends Schema.TaggedError<ServiceProtectionError>()(
146 "ServiceProtectionError",
147 {
148 step: Schema.String,
149 exitCode: Schema.optional(Schema.Number),
150 cause: Schema.optional(Schema.Defect()),
151 },
152) {
153 override get message(): string {
154 return this.exitCode === undefined
155 ? `Could not ${this.step}.`
156 : `Could not ${this.step} (exit code ${this.exitCode}).`;
157 }
158}
159
160function parseUnits(text: string): Array<Map<string, string>> {
161 return text
162 .split(/\n\s*\n/)
163 .map(
164 (block) =>
165 new Map(
166 block
167 .split("\n")
168 .filter((line) => line.includes("="))
169 .map((line) => [line.slice(0, line.indexOf("=")), line.slice(line.indexOf("=") + 1)]),
170 ),
171 )
172 .filter((values) => values.size > 0);
173}
174
175/** Loaded remote-access units by canonical name, so an alias such as sshd.service counts once. */
176export function loadedRemoteAccessUnits(systemctlShow: string): ReadonlyArray<string> {
177 const units = parseUnits(systemctlShow)
178 .filter((values) => values.get("LoadState") === "loaded")
179 .map((values) => values.get("Id") ?? "")
180 .filter((id) => REMOTE_ACCESS_UNITS.includes(id));
181 return [...new Set(units)];
182}
183
184const run = Effect.fn("ServiceProtection.run")(function* (
185 step: string,
186 command: string,
187 args: ReadonlyArray<string>,
188) {
189 const runner = yield* ProcessRunner.ProcessRunner;
190 const result = yield* runner
191 .run({ command, args, timeout: "30 seconds" })
192 .pipe(Effect.mapError((cause) => new ServiceProtectionError({ step, cause })));
193 if (result.code !== 0) {
194 return yield* new ServiceProtectionError({ step, exitCode: Number(result.code) });
195 }
196 return result.stdout;
197});
198
199const userSettingsError = (cause: unknown) =>
200 new ServiceProtectionError({ step: "change systemd user settings", cause });
201
202/** Undefined when there is no systemd system manager to ask. */
203export const detectRemoteAccessUnits = run("list remote-access services", "systemctl", [
204 "show",
205 "--property=Id,LoadState",
206 ...REMOTE_ACCESS_UNITS,
207]).pipe(
208 Effect.map(loadedRemoteAccessUnits),
209 Effect.option,
210 Effect.map(Option.getOrUndefined),
211 Effect.withSpan("ServiceProtection.detectRemoteAccessUnits"),
212);
213
214const reloadUserManager = Effect.andThen(
215 run("reload systemd user units", "systemctl", ["--user", "daemon-reload"]),
216 run("restore systemd-oomd's watch", "/bin/sh", ["-c", RESTORE_OOMD_WATCH_SCRIPT]).pipe(
217 Effect.ignore,
218 ),
219);
220
221const writeDropIns = Effect.fn("ServiceProtection.writeDropIns")(function* (
222 dropIns: ReadonlyArray<DropIn>,
223) {
224 const fs = yield* FileSystem.FileSystem;
225 for (const { path, contents } of dropIns) {
226 yield* fs.makeDirectory(directoryOf(path), { recursive: true });
227 yield* fs.writeFileString(path, contents);
228 }
229}, Effect.mapError(userSettingsError));
230
231const removeDropIns = Effect.fn("ServiceProtection.removeDropIns")(function* (
232 dropIns: ReadonlyArray<DropIn>,
233) {
234 const fs = yield* FileSystem.FileSystem;
235 for (const { path } of dropIns) {
236 yield* fs.remove(path, { force: true });
237 yield* fs.remove(directoryOf(path)).pipe(Effect.ignore);
238 }
239}, Effect.mapError(userSettingsError));
240
241const runPrivileged = Effect.fn("ServiceProtection.runPrivileged")(function* (script: string) {
242 const step = "change the system's service settings";
243 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
244 const exitCode = yield* spawner
245 .exitCode(
246 // Effect detaches children on POSIX by default; sudo then has no controlling
247 // terminal and cannot ask for a password.
248 ChildProcess.make("sudo", ["/bin/sh", "-c", script], {
249 detached: false,
250 stdin: "inherit",
251 stdout: "inherit",
252 stderr: "inherit",
253 }),
254 )
255 .pipe(Effect.mapError((cause) => new ServiceProtectionError({ step, cause })));
256 if (exitCode !== 0) {
257 return yield* new ServiceProtectionError({ step, exitCode: Number(exitCode) });
258 }
259});
260
261export const applyProtection = Effect.fn("ServiceProtection.apply")(function* (
262 plan: ProtectionPlan,
263) {
264 const fs = yield* FileSystem.FileSystem;
265 const hadManagerDefaults = yield* fs
266 .exists(plan.managerDefaults.path)
267 .pipe(Effect.orElseSucceed(() => false));
268 yield* writeDropIns([plan.managerDefaults]);
269 // A partial run may already have lowered the manager; its default must then stay.
270 const manager = plan.system.find(({ unit }) => unit.startsWith("user@"));
271 const rollBack = Effect.gen(function* () {
272 if (hadManagerDefaults) return;
273 if (manager !== undefined && (yield* fs.exists(manager.path))) return;
274 yield* removeDropIns([plan.managerDefaults]);
275 }).pipe(Effect.ignore);
276 yield* runPrivileged(renderPrivilegedScript(plan, "apply")).pipe(Effect.tapError(() => rollBack));
277 yield* writeDropIns(plan.user);
278 yield* reloadUserManager;
279});
280
281export const removeProtection = Effect.fn("ServiceProtection.remove")(function* (
282 plan: ProtectionPlan,
283) {
284 yield* removeDropIns(plan.user);
285 yield* reloadUserManager;
286 if (plan.system.length > 0) yield* runPrivileged(renderPrivilegedScript(plan, "undo"));
287 yield* removeDropIns([plan.managerDefaults]);
288 yield* reloadUserManager;
289});
290
291/** The plan narrowed to drop-ins that exist, for undo. */
292export const installedProtection = Effect.fn("ServiceProtection.installed")(function* (
293 plan: ProtectionPlan,
294) {
295 const fs = yield* FileSystem.FileSystem;
296 const exists = (dropIn: DropIn) => fs.exists(dropIn.path).pipe(Effect.orElseSucceed(() => false));
297 const system = yield* Effect.filter(plan.system, exists);
298 const user = yield* Effect.filter(plan.user, exists);
299 const managerDefaults = yield* exists(plan.managerDefaults);
300 return system.length + user.length === 0 && !managerDefaults
301 ? undefined
302 : { ...plan, system, user };
303});
304
305/**
306 * False when the kernel lacks the memory cgroup controller (Raspberry Pi OS
307 * disables it by default), so only OOM scores can apply. True when unknown.
308 */
309export const memoryControllerAvailable = Effect.gen(function* () {
310 const fs = yield* FileSystem.FileSystem;
311 const controllers = yield* fs
312 .readFileString("/sys/fs/cgroup/cgroup.controllers")
313 .pipe(Effect.option);
314 return Option.match(controllers, {
315 onNone: () => true,
316 onSome: (text) => text.split(/\s+/).includes("memory"),
317 });
318}).pipe(Effect.withSpan("ServiceProtection.memoryControllerAvailable"));
319
320export interface ServiceProtectionState {
321 readonly memoryControllerAvailable: boolean;
322 /** The first cgroup from the top that grants the server no memory protection. */
323 readonly unprotected: string | undefined;
324 readonly oomScoreAdj: number | undefined;
325 readonly setByProtect: boolean;
326}
327
328/** Reads what the kernel applies to the running service, whoever configured it. */
329export const readProtection = Effect.fn("ServiceProtection.read")(function* (userUnitDir: string) {
330 const fs = yield* FileSystem.FileSystem;
331 const path = yield* Path.Path;
332 const shown = yield* run("read the service's cgroup", "systemctl", [
333 "--user",
334 "show",
335 BOOT_SERVICE_UNIT_FILE,
336 "--property=ControlGroup,MainPID",
337 ]).pipe(Effect.option);
338 if (Option.isNone(shown)) return undefined;
339 const values = parseUnits(shown.value)[0] ?? new Map<string, string>();
340 const controlGroup = (values.get("ControlGroup") ?? "").split("/").filter(Boolean);
341 if (controlGroup.length === 0) return undefined;
342 const read = (file: string) =>
343 fs.readFileString(file).pipe(
344 Effect.map((text) => text.trim()),
345 Effect.orElseSucceed(() => ""),
346 );
347 const memoryController = yield* memoryControllerAvailable;
348 let unprotected: string | undefined;
349 const grants = (value: string) => value !== "" && value !== "0";
350 const depths = memoryController ? controlGroup.length : 0;
351 for (let depth = 1; depth <= depths && unprotected === undefined; depth++) {
352 const directory = path.join("/sys/fs/cgroup", ...controlGroup.slice(0, depth));
353 const low = yield* read(path.join(directory, "memory.low"));
354 const min = yield* read(path.join(directory, "memory.min"));
355 if (!grants(low) && !grants(min)) unprotected = controlGroup[depth - 1];
356 }
357 const pid = Number(values.get("MainPID") ?? 0);
358 const score = pid > 0 ? yield* read(`/proc/${pid}/oom_score_adj`) : "";
359 return {
360 memoryControllerAvailable: memoryController,
361 unprotected,
362 oomScoreAdj: score === "" ? undefined : Number(score),
363 setByProtect: yield* fs
364 .exists(path.join(userUnitDir, `${BOOT_SERVICE_UNIT_FILE}.d`, PROTECT_DROP_IN))
365 .pipe(Effect.orElseSucceed(() => false)),
366 } satisfies ServiceProtectionState;
367});