From 5c70956f78274b2dad60aa99bb450eef482d3331 Mon Sep 17 00:00:00 2001 From: Bobban Rydh Date: Tue, 6 Oct 2026 22:48:50 +0200 Subject: [PATCH] Linux agent unit: keep only the root powers it uses; make unit files readable The systemd unit now bounds the agent's capabilities to the three jobs it does as root -- reading every user's crontab (DAC_OVERRIDE, DAC_READ_SEARCH), running "crontab -l -u" (SETUID, SETGID) and naming the program behind each socket (SYS_PTRACE) -- and adds ProtectClock, ProtectHostname, MemoryDenyWriteExecute and DevicePolicy=closed. It does not use PrivateDevices, which would hide /dev/log (crontab logs each read there), nor anything that hides other processes or users, since the agent needs both. The installer's umask 077 (for the token file) also left the unit files readable by root only; they now get chmod 644, so "systemctl cat" works for any user. The test renders the unit through the installer's own heredoc, so a stray backtick or $ would show up, and pins the capability list: tightening it silently drops tasks or process names. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 3 +- agent/linux/install.sh | 14 ++++++++ server/test/hardening.test.ts | 67 +++++++++++++++++++++++++++++++---- 3 files changed, 76 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index a448fae..62a9ece 100644 --- a/README.md +++ b/README.md @@ -221,7 +221,8 @@ hostnames; å, ä and ö become a, a and o. **Agents and what the server connects to** — the agents only push: the server replies "received" and nothing more, so it has no way to make a server run anything. Each server has its own token (kept only as a hash), which can do one thing: replace that server's own report. The Linux agent hands its token to curl on standard input and keeps its payload in a private temporary directory, so neither is visible -to other users on the machine, and its systemd unit runs with the usual restrictions (no new privileges, read-only system, private /tmp). +to other users on the machine, and its systemd unit runs with the usual restrictions (no new privileges, read-only system, private /tmp) and keeps only the three +root powers the agent uses — reading every user's crontab, switching user to list it, and seeing which program owns each socket. On Windows the agent's folder is limited to SYSTEM and Administrators. The agent endpoint checks the token before it reads a report, takes reports of several MB, and trims overlong text rather than rejecting the whole report. **After upgrading, re-run the install one-liner on each server** to pick this up — an installed agent keeps its own copy of the script and doesn't update itself. diff --git a/agent/linux/install.sh b/agent/linux/install.sh index 04f12e3..2b1e096 100644 --- a/agent/linux/install.sh +++ b/agent/linux/install.sh @@ -91,6 +91,14 @@ ExecStart=$INSTALL_DIR/homelab-manager-agent.sh # The agent only reads (crontabs, timers, /proc, listening sockets) and makes one HTTPS request, but it runs as root. These # keep a bug in it, or in anything it parses, from being able to change the system. It still sees every process, which is # how it names the program behind each listening port. Directives an older systemd doesn't know are ignored. +# +# Of root's powers it keeps only what it uses: to read every user's crontab (DAC_OVERRIDE, DAC_READ_SEARCH), to run +# the command that lists one user's crontab, which switches user and group (SETUID, SETGID), and to see which program owns each socket (SYS_PTRACE). +# If a change here ever makes a report lose tasks, this line is the first thing to look at. +CapabilityBoundingSet=CAP_DAC_OVERRIDE CAP_DAC_READ_SEARCH CAP_SYS_PTRACE CAP_SETUID CAP_SETGID +# Not PrivateDevices=: that would also hide /dev/log, which crontab writes to each time the agent reads a crontab. This stops it +# opening hardware devices all the same. +DevicePolicy=closed UMask=0077 NoNewPrivileges=yes PrivateTmp=yes @@ -100,6 +108,9 @@ ProtectKernelTunables=yes ProtectKernelModules=yes ProtectKernelLogs=yes ProtectControlGroups=yes +ProtectClock=yes +ProtectHostname=yes +MemoryDenyWriteExecute=yes RestrictSUIDSGID=yes RestrictRealtime=yes RestrictNamespaces=yes @@ -121,6 +132,9 @@ Persistent=true WantedBy=timers.target EOF +# The umask above is for the token file. Unit files hold nothing secret and are meant to be readable (systemctl cat, as any user). +chmod 644 "$SYSTEMD_DIR/homelab-manager-agent.service" "$SYSTEMD_DIR/homelab-manager-agent.timer" + systemctl daemon-reload systemctl enable --now homelab-manager-agent.timer diff --git a/server/test/hardening.test.ts b/server/test/hardening.test.ts index 22c503f..8217fe7 100644 --- a/server/test/hardening.test.ts +++ b/server/test/hardening.test.ts @@ -334,14 +334,67 @@ describe("Linux agent", () => { assert.match(text, /curl .* -K -/, "curl should read its config (with the token) from stdin"); }); - test("the systemd unit is locked down", () => { - const text = readFileSync(installScript, "utf8"); - const unit = text.slice(text.indexOf("[Service]"), text.indexOf("EOF", text.indexOf("[Service]"))); - for (const directive of ["NoNewPrivileges=yes", "PrivateTmp=yes", "ProtectSystem=strict", "ProtectHome=read-only", "ProtectKernelTunables=yes", "ProtectControlGroups=yes", "LockPersonality=yes", "RestrictAddressFamilies="]) { - assert.ok(unit.includes(directive), `missing ${directive}`); + test("the systemd unit, as the installer writes it, is locked down and keeps what the agent needs", { skip: !haveBash }, async () => { + // Run the installer's own heredoc, so a stray $, backtick or backslash in the unit shows up here exactly as it would on a server. + const text = readFileSync(installScript, "utf8").replace(/\r\n/g, "\n"); + const start = text.indexOf('cat > "$SYSTEMD_DIR/homelab-manager-agent.service" < 0 && end > start, "the unit's heredoc wasn't found in install.sh"); + const out = mkdtempSync(join(tmpdir(), "hm-unit-")); + try { + writeFileSync(join(out, "render.sh"), `set -euo pipefail\nCONFIG_DIR=/etc\nINSTALL_DIR=/usr/local/bin\nSYSTEMD_DIR=$(cygpath -u "$OUT_DIR" 2>/dev/null || echo "$OUT_DIR")\n${text.slice(start, end)}`); + const r = await run("bash", [posix(join(out, "render.sh"))], { ...process.env, OUT_DIR: posix(out) }); + assert.equal(r.status, 0, r.stderr); + assert.equal(r.stdout.trim(), "", "rendering the unit ran a command (a backtick or $( ) in the heredoc?)"); + + const rendered = readFileSync(join(out, "homelab-manager-agent.service"), "utf8"); + const settings = new Map(); + for (const line of rendered.split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("#") && !l.startsWith("["))) { + const eq = line.indexOf("="); + assert.ok(eq > 0, `not a Key=Value line: ${JSON.stringify(line)}`); + settings.set(line.slice(0, eq), line.slice(eq + 1)); + } + + // The two intended expansions, and nothing else turned into something unexpected. + assert.equal(settings.get("EnvironmentFile"), "/etc/homelab-manager-agent.env"); + assert.equal(settings.get("ExecStart"), "/usr/local/bin/homelab-manager-agent.sh"); + assert.doesNotMatch(rendered, /[`\\]/); + + for (const [key, value] of Object.entries({ + UMask: "0077", NoNewPrivileges: "yes", PrivateTmp: "yes", ProtectSystem: "strict", ProtectHome: "read-only", + ProtectKernelTunables: "yes", ProtectKernelModules: "yes", ProtectKernelLogs: "yes", ProtectControlGroups: "yes", + ProtectClock: "yes", ProtectHostname: "yes", MemoryDenyWriteExecute: "yes", RestrictSUIDSGID: "yes", + RestrictRealtime: "yes", RestrictNamespaces: "yes", LockPersonality: "yes", DevicePolicy: "closed", + })) { + assert.equal(settings.get(key), value, key); + } + assert.equal(settings.get("RestrictAddressFamilies"), "AF_UNIX AF_INET AF_INET6 AF_NETLINK"); + + // Of root's powers only these three jobs are kept: read every user's crontab, switch user for `crontab -l -u`, and name the + // program behind each socket. Tightening this further silently drops tasks or process names; loosening it undoes the point. + assert.deepEqual( + new Set((settings.get("CapabilityBoundingSet") ?? "").split(/\s+/)), + new Set(["CAP_DAC_OVERRIDE", "CAP_DAC_READ_SEARCH", "CAP_SYS_PTRACE", "CAP_SETUID", "CAP_SETGID"]), + ); + + // It has to keep seeing every process (that is how it names the program behind a listening port), real user IDs (for + // crontab -l -u), and /dev/log (crontab writes to it each time the agent reads a crontab). + for (const key of ["ProtectProc", "ProcSubset", "PrivateUsers", "PrivateDevices"]) assert.equal(settings.has(key), false, `${key} would break the agent`); + } finally { + try { + rmSync(out, { recursive: true, force: true }); + } catch { + // best effort + } } - // It has to keep seeing every process: that is how it names the program behind a listening port. - assert.doesNotMatch(unit, /ProtectProc|ProcSubset/); + }); + + test("unit files are made readable by everyone (the umask above them is for the token file)", () => { + const text = readFileSync(installScript, "utf8").replace(/\r\n/g, "\n"); + assert.match(text, /chmod 644 "\$SYSTEMD_DIR\/homelab-manager-agent\.service" "\$SYSTEMD_DIR\/homelab-manager-agent\.timer"/); + // ...and it comes after both files are written and before systemd is asked to read them. + const chmodAt = text.indexOf('chmod 644 "$SYSTEMD_DIR'); + assert.ok(chmodAt > text.indexOf("homelab-manager-agent.timer\" < {