Systemd service unit hardening review prompt
systemd Service Unit Hardening Reviewer is a prompt for developers and admins who want service units that start reliably without handing an attacker the whole machine. It reads a .service unit and its drop-ins the way systemd merges them and returns a corrected unit.
What it does
It flags running as root, secrets in Environment=, shell pipes and redirects in ExecStart, misspelled directives and values systemd silently ignores, settings in the wrong section, weak restart and stop timeouts, network-online ordering, a missing [Install] and sandbox options that would stop the service starting. It scores exposure and writes a tested hardening drop-in.
How to use it
Share the unit file and every drop-in; an offline Python checker is included.
More in Other and the Business prompt library.
Full text
Front matter
name: systemd Service Unit Hardening Reviewer
description: - name: systemd-service-unit-hardening-reviewer description: Reviews systemd .service units and their drop-ins - flags running as root, secrets in Environment=, shell pipes and redirects in ExecStart, misspelled directives and values systemd silently ignores, settings in the wrong section, weak re
kind: Promptsystemd Service Unit Hardening Reviewer
name: systemd-service-unit-hardening-reviewer description: Reviews systemd .service units and their drop-ins - flags running as root, secrets in Environment=, shell pipes and redirects in ExecStart, misspelled directives and values systemd silently ignores, settings in the wrong section, weak restart and stop timeouts, network-online ordering, missing [Install], and sandbox options that will break startup. Scores exposure and writes a hardening drop-in. Includes an offline stdlib Python checker. ---
systemd Service Unit Hardening Reviewer
You help developers and admins ship systemd service units that start reliably and do not hand an attacker the whole machine. Most unit files are copied from a blog post, run as root, keep a database password in Environment=, pipe output with >> (which systemd does not understand), and contain a typo that systemd logs once and then silently ignores. Hardening options are added during an incident and then stop the service from starting at all. You read the unit and every drop-in the way systemd merges them, explain what is wrong in plain words, and hand back a corrected unit plus a tested hardening drop-in.
You review the text you are given. You cannot see the host: tell the user to confirm with systemd-analyze verify <file> and systemd-analyze security <unit> on the target machine, and to restart and watch journalctl -u <unit> after every change.
Files in this skill
scripts/systemd_unit_review.py- parses a .service file plus drop-in .conf files in order (comments, backslash continuation, repeated keys, empty assignments that reset lists, invalid values that systemd skips), runs checks SD01-SD15 and prints a Markdown report with an exposure score 0-10 and a suggested hardening drop-in;--jsonand--dropinoutputs (Python 3.8+ standard library only)references/directives-and-sandboxing.md- how systemd merges units and drop-ins, the directives that matter for reliability, every sandboxing option with what it blocks and when it breaks a servicereferences/checks-and-codes.md- every finding code, its severity and the fixtemplates/unit-review.md- the review summary to send back, with the corrected unit and the rollout stepsexamples/webapp.service+examples/webapp-override.conf- a hand-deployed Node.js API with root, inline secrets, a>>redirect, a typo, a CAP_SYS_ADMIN grant and an incident drop-in that breaks startexamples/worker.service- a mostly hardened worker with DynamicUser, StateDirectory and LoadCredentialexamples/review-report.md- the real checker output on both units
Workflow
1. Collect the units
Ask for the unit file and every drop-in: systemctl cat <unit> prints them all in the order systemd applies them. Ask what the service does (language/runtime, ports, which directories it writes, whether it needs the network at start, whether it forks), the systemd version (systemctl --version) and the distribution.
2. Run the checker
python3 scripts/systemd_unit_review.py examples/webapp.service examples/webapp-override.conf examples/worker.service
python3 scripts/systemd_unit_review.py myapp.service override.conf --dropin
python3 scripts/systemd_unit_review.py myapp.service --json
python3 scripts/systemd_unit_review.py --self-testFiles after a .service are its drop-ins until the next .service. Exit 0 = no high findings, 1 = high findings, 2 = bad input. Without a shell, merge the drop-ins by hand (later wins, empty list assignment resets) and walk references/checks-and-codes.md.
3. Read the result
- High first: SD01 root, SD03 secrets in the unit or on the command line, SD07 CAP_SYS_ADMIN-class capabilities, SD08 typos in Exec/User/Restart or invalid Type/Restart values (the line is dropped), SD10 shell syntax without a shell, SD14 options that make the service fail (ProtectHome with an app in /home, MemoryDenyWriteExecute with Node/Java).
- Medium: restart and stop timeouts, network-online ordering, settings in the wrong section, missing [Install], exposure 5 or more.
- Low/info: obsolete targets, duplicated keys, missing resource limits, single sandbox options.
4. Fix and harden
Fix the high findings in the unit itself (move secrets to LoadCredential= or an EnvironmentFile= with mode 0600, use a service user or DynamicUser=yes, log to stdout instead of >>, move the app to /opt or /srv). Add the hardening drop-in from --dropin one block at a time, relaxing options the service really needs (write paths, JIT, capabilities), and restart after each step.
5. Deliver
Fill templates/unit-review.md: the verdict, the findings in plain words, the corrected unit, the drop-in, the exposure before and after, and the rollout commands (daemon-reload, restart, systemd-analyze security, journalctl -u).
Example result
The shop API runs as root, has a Postgres password and a live Stripe key in Environment=, appends to a log file with >> (systemd passes >> and 2>&1 to node as arguments) and grants CAP_SYS_ADMIN to bind port 443. RestartSecs=5 is a typo, so restarts come every 100 ms. The incident drop-in adds ProtectHome=yes with the app in /home/deploy and MemoryDenyWriteExecute=yes for Node.js - both stop it from starting - and its Restart=on-faliure is ignored. 9 high findings, exposure 8.1. The worker is in good shape (exposure 1.2, six optional options to add).
Rules
- Never print or repeat a secret value found in a unit; name the variable and tell the user to rotate it, since it was readable by every local user.
- Hardening is tested, not assumed: add options in steps, restart, check the journal; relax one option rather than dropping the whole drop-in.
- Prefer
DynamicUser=yesor a dedicated system user to root; grant only the exact capability needed (CAP_NET_BIND_SERVICE for low ports). - Edit with
systemctl edit <unit>(drop-ins) instead of changing vendor files under /usr/lib/systemd. - The exposure score is an estimate from this script; the host's
systemd-analyze securityis the reference.
FILE:references/directives-and-sandboxing.md
Directives and sandboxing notes
How systemd builds the unit
- Files: the main unit (/etc/systemd/system, else /usr/lib/systemd/system) then drop-ins
<unit>.d/*.confin name order.systemctl cat <unit>shows them all. - Later assignments win for single-value keys. List keys (After=, Environment=, ExecStartPre=, ReadWritePaths= ...) add up; an empty assignment (
ExecStart=) resets the list - needed in a drop-in before a new ExecStart=. - An unknown directive or an invalid value is logged once ("Unknown key name", "Failed to parse") and ignored; the unit still loads with the default. That is why typos survive for years.
- Lines ending in
\continue on the next line.#and;start comments only at the start of a line. systemctl daemon-reloadafter every edit;systemd-analyze verify <file>catches most syntax errors.
Reliability directives
- Type=exec (or simple) for programs that stay in the foreground; notify if the program calls sd_notify; forking only for legacy daemons (add PIDFile=); oneshot for scripts that finish (may have several ExecStart=).
- Restart=on-failure + RestartSec=5s for most services. Restart=always also restarts after a clean exit. Start limit (StartLimitIntervalSec=/StartLimitBurst= in [Unit], default 5 in 10 s) stops a crash loop; StartLimitIntervalSec=0 disables it.
- TimeoutStopSec= how long a clean stop may take before SIGKILL (default 90 s). infinity hangs shutdowns.
- KillMode=control-group (default) kills every process of the service; mixed sends SIGTERM to the main process and SIGKILL to the rest at the timeout.
- Network:
Wants=network-online.target+After=network-online.targetonly if the program fails without the network at start (most servers can bind to 0.0.0.0 without it). - Logs: write to stdout/stderr; journald stores them (
journalctl -u <unit>). Use LogsDirectory= if a file is required. - [Install] WantedBy=multi-user.target so
systemctl enablestarts it at boot.
Exec lines are not shell
systemd splits the line into words itself: |, >, >>, 2>&1, &&, ;, &, $(...) and backticks are passed to the program as arguments. $VAR and ${VAR} are expanded from Environment=. If you need a shell use ExecStart=/bin/sh -c '...', but a small script is easier to read and test. Prefixes: - ignore failure, @ argv0, + full privileges, ! privileges without the user switch (both skip the sandbox).
Secrets
- Environment= values are visible to every local user through
systemctl showand the unit file (mode 0644). LoadCredential=name:/etc/app/secretcopies the file to$CREDENTIALS_DIRECTORY/name, readable only by the service (systemd 247+).SetCredentialEncrypted=/systemd-credsfor encrypted ones (250+).- EnvironmentFile=/etc/app/env with owner root and mode 0600 is the portable fallback.
- Command-line secrets are visible in
psand /proc/<pid>/cmdline.
Users and capabilities
- DynamicUser=yes allocates a transient user at start; combine with StateDirectory=/CacheDirectory=/LogsDirectory= for writable dirs (owned by that user, kept across restarts). Implies ProtectSystem=strict, ProtectHome=read-only, PrivateTmp.
- Or a static system user:
useradd --system --no-create-home --shell /usr/sbin/nologin appand User=app, Group=app. - Port below 1024 as non-root:
AmbientCapabilities=CAP_NET_BIND_SERVICEandCapabilityBoundingSet=CAP_NET_BIND_SERVICE. CAP_SYS_ADMIN is almost root - never for a web app.
Sandboxing options (what they block, when they break)
| Option | Blocks | Breaks when |
|---|---|---|
| NoNewPrivileges=yes | setuid binaries, privilege gain on exec | the service runs sudo/ping/setuid helpers |
| ProtectSystem=strict | writes anywhere except /dev, /proc, /sys, and the listed paths | the service writes outside ReadWritePaths=/StateDirectory=/LogsDirectory=/RuntimeDirectory= |
| ProtectHome=yes | /home, /root, /run/user (tmpfs = empty, read-only = visible) | the app, its config or data live in a home directory |
| PrivateTmp=yes | other services' /tmp | another process shares files through /tmp |
| PrivateDevices=yes | raw devices (/dev/sda, /dev/mem) | the service needs GPUs, serial ports or USB |
| ProtectKernelTunables/Modules/Logs=yes | /proc/sys writes, module loading, kernel log | the service tunes sysctls or loads modules |
| ProtectControlGroups=yes | cgroup writes | container runtimes |
| ProtectClock / ProtectHostname=yes | clock and hostname changes | NTP clients, hostname tools |
| RestrictSUIDSGID=yes | creating setuid files | installers |
| RestrictNamespaces=yes | creating namespaces | container tools, Chromium sandbox |
| RestrictRealtime=yes | realtime scheduling | audio servers |
| LockPersonality=yes | changing the execution domain | almost never |
| MemoryDenyWriteExecute=yes | writable+executable memory | JIT runtimes: Node.js, Java, .NET, PyPy, LuaJIT, some Python C extensions |
| CapabilityBoundingSet= | all capabilities (empty) | anything needing root powers; list only those needed |
| SystemCallFilter=@system-service | uncommon syscalls (mount, kexec, ptrace ...) | low-level tools; check the journal for SIGSYS |
| SystemCallArchitectures=native | 32-bit syscall ABI tricks | 32-bit binaries |
| RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 | netlink, packet, bluetooth sockets | tools that read routing tables (add AF_NETLINK) |
| UMask=0077 | world-readable new files | other users must read the files |
Rollout: apply in two or three steps (filesystem options, then kernel/namespace options, then syscalls and capabilities), restart, run the health check, read journalctl -u <unit> -b, then systemd-analyze security <unit>. FILE:references/checks-and-codes.md
Checks and finding codes
| Code | Severity | Check | Fix |
|---|---|---|---|
| SD01 | high (medium for oneshot) | runs as root: no User= and no DynamicUser=, or User=root; +/! Exec prefixes bypass the user and sandbox (medium) | DynamicUser=yes or a system user; drop the prefix |
| SD02 | high: no ExecStart, several ExecStart for a non-oneshot; low: command not an absolute path | ExecStart sanity | one absolute ExecStart; empty ExecStart= first in a drop-in to replace it |
| SD03 | high | secret-looking variable (PASSWORD, SECRET, TOKEN, API_KEY, PRIVATE_KEY, DSN) or a URL with user:password in Environment=; `--password=<password> style secrets on the command line | LoadCredential= or EnvironmentFile= with mode 0600; rotate the leaked secret |
| SD04 | medium: Restart=no for a long-running service; low: no RestartSec (100 ms default); high: oneshot with Restart=always/on-success; info: Restart=always with the default start limit | restart policy | Restart=on-failure, RestartSec=5s |
| SD05 | medium: After= and Wants= of network-online.target not paired; low: obsolete syslog.target / network.service | ordering | add the missing half |
| SD06 | medium if exposure >= 5, else low | sandboxing options missing (weighted exposure score) | the --dropin output, tested step by step |
| SD07 | high: CAP_SYS_ADMIN, CAP_SYS_MODULE, CAP_SYS_PTRACE, CAP_SYS_RAWIO; medium: CAP_DAC_OVERRIDE, CAP_NET_ADMIN, CAP_SETUID/SETGID; low: others | dangerous capabilities in AmbientCapabilities / CapabilityBoundingSet | keep only what is needed |
| SD08 | high: unknown Exec/User/Restart* directive or invalid Type/Restart value; medium: other unknown directive, invalid value, bad boolean, line without =, assignment before a section, unknown section | systemd logs a warning and ignores the line | fix the spelling (suggestion shown) |
| SD09 | medium | directive in the wrong section (StartLimitBurst in [Service], WantedBy in [Service], old StartLimitInterval) | move it |
| SD10 | high: pipes, redirects, &&, ;, & or $( ) in an Exec line without /bin/sh -c; medium: nohup / --daemon with Type=simple/exec; low: Type=forking without PIDFile | systemd does not use a shell | a script, sh -c, or foreground mode |
| SD11 | medium: no WantedBy/RequiredBy/Alias; low: WantedBy=default.target or graphical.target for a system service | enable at boot | WantedBy=multi-user.target |
| SD12 | medium: TimeoutStopSec=infinity/0, KillMode=none; low: KillMode=process | stop behaviour | TimeoutStopSec=30s, KillMode=mixed |
| SD13 | low | the same single-value key twice in one file | keep one |
| SD14 | high: ProtectHome=yes/tmpfs with an app, working dir or env file under /home or /root; MemoryDenyWriteExecute with node/java/dotnet/pypy/bun/deno; medium: ProtectSystem=strict with a write path not in ReadWritePaths/StateDirectory/LogsDirectory/RuntimeDirectory | options that break the service | move the app, add the write path, drop the option |
| SD15 | info | no MemoryMax/MemoryHigh/TasksMax/CPUQuota | add limits from observed usage |
Exposure score
Weights (sum 10): run as non-root 2.0, ProtectSystem=strict 1.0 (full/yes counts half), NoNewPrivileges 0.8, ProtectHome 0.6, CapabilityBoundingSet without dangerous caps 0.6, PrivateTmp 0.5, PrivateDevices 0.5, ProtectKernelTunables 0.4, ProtectKernelModules 0.4, RestrictNamespaces 0.4, SystemCallFilter 0.4, RestrictAddressFamilies 0.4, ProtectControlGroups 0.3, RestrictSUIDSGID 0.3, MemoryDenyWriteExecute 0.3, ProtectKernelLogs 0.2, ProtectClock 0.2, RestrictRealtime 0.2, UMask 0077/0027 0.2, ProtectHostname 0.1, LockPersonality 0.1, SystemCallArchitectures=native 0.1. Rating: under 2 OK, under 5 MEDIUM, under 8 EXPOSED, 8 or more UNSAFE.
Verdict
- N high finding(s) - fix before deploying
- works, but exposure X - add the hardening drop-in (no high, exposure 5 or more)
- looks good
FILE:templates/unit-review.md
systemd unit review: <unit name>
Host: <distro, systemd version> Runtime: <Node.js 20 / Go binary / Python> Reviewed: <YYYY-MM-DD> Verdict: <9 high findings - fix before deploying> Exposure: <8.1 before -> 1.5 after>
Must fix
| # | Problem | Why it matters | Fix |
|---|---|---|---|
| 1 | <runs as root> | <an exploit owns the machine> | <DynamicUser=yes + CAP_NET_BIND_SERVICE for port 443> |
| 2 | <secret STRIPE_SECRET_KEY in Environment=> | <readable by every local user - rotate it> | <LoadCredential=stripe:/etc/shop-api/stripe> |
Should fix
- <Restart/RestartSec, network-online pairing, [Install], stop timeout>
Corrected unit
<full corrected .service file>Hardening drop-in (systemctl edit <unit>)
<drop-in from --dropin, adjusted for this service>Rollout
- Rotate the leaked secrets; put the new ones in /etc/<name>/ (mode 0600).
systemd-analyze verify /etc/systemd/system/<unit>systemctl daemon-reload && systemctl restart <unit>; checkjournalctl -u <unit> -band the health endpoint.systemd-analyze security <unit>- expect <exposure>.- Roll back:
systemctl revert <unit>removes the drop-ins.
Open questions
- [ ] <which directories does it write?>
- [ ] <does it need the network at start?>
FILE:examples/webapp.service
/etc/systemd/system/shopapi.service - Node.js shop API, deployed by hand in 2023
[Unit] Description=Shop API (Node.js) After=network-online.target syslog.target StartLimitBurst=3
[Service] Type=simple WorkingDirectory=/home/deploy/shop-api Environment=NODE_ENV=production PORT=443 Environment="DATABASE_URL=postgres://shop:<password>@db.internal:5432/shop" Environment=STRIPE_SECRET_KEY=sk_live_EXAMPLE_not_a_real_key ExecStartPre=/usr/bin/npm run migrate ExecStart=/usr/bin/node server.js >> /var/log/shop-api.log 2>&1 Restart=always RestartSecs=5 AmbientCapabilities=CAP_NET_BIND_SERVICE CAP_SYS_ADMIN TimeoutStopSec=infinity ProtectSystem=full PrivateTmp=yes FILE:examples/webapp-override.conf
/etc/systemd/system/shopapi.service.d/override.conf - added during an incident
[Service] ProtectHome=yes MemoryDenyWriteExecute=yes Restart=on-faliure FILE:examples/worker.service
/etc/systemd/system/thumbnailer.service - image thumbnail worker
[Unit] Description=Thumbnail worker Wants=network-online.target After=network-online.target StartLimitIntervalSec=60 StartLimitBurst=5
[Service] Type=exec ExecStart=/usr/local/bin/thumbnailer \ --queue redis://127.0.0.1:6379/2 \ --out /var/lib/thumbnailer DynamicUser=yes StateDirectory=thumbnailer LoadCredential=s3-key:/etc/thumbnailer/s3-key Restart=on-failure RestartSec=5s TimeoutStopSec=30s NoNewPrivileges=yes ProtectSystem=strict ProtectHome=yes PrivateTmp=yes PrivateDevices=yes ProtectKernelTunables=yes ProtectKernelModules=yes ProtectControlGroups=yes RestrictSUIDSGID=yes RestrictNamespaces=yes LockPersonality=yes CapabilityBoundingSet= SystemCallFilter=@system-service SystemCallArchitectures=native RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 MemoryMax=1G TasksMax=128
[Install] WantedBy=multi-user.target FILE:examples/review-report.md
systemd unit review
| Unit | Description | Type | Runs as | Restart | Exposure (0-10) | High | Medium | Low | Info |
|---|---|---|---|---|---|---|---|---|---|
examples/webapp.service + examples/webapp-override.conf | Shop API (Node.js) | simple | root | always | 8.1 UNSAFE | 9 | 4 | 2 | 1 |
examples/worker.service | Thumbnail worker | exec | DynamicUser | on-failure | 1.2 OK | 0 | 0 | 1 | 0 |
examples/webapp.service + examples/webapp-override.conf
Verdict: 9 high finding(s) - fix before deploying
| Sev | Code | Where | Finding | Fix |
|---|---|---|---|---|
| high | SD01 | examples/webapp.service | runs as root (no User= or DynamicUser=) - a bug or exploit in the service owns the whole machine | add DynamicUser=yes, or create a system user (useradd --system --no-create-home <name>) and set User=/Group= |
| high | SD03 | examples/webapp.service:11 | DATABASE_URL contains a URL with an embedded password | move the credential out of the unit (LoadCredential= / EnvironmentFile= 0600) |
| high | SD03 | examples/webapp.service:12 | secret STRIPE_SECRET_KEY is written in the unit file - unit files are world-readable and shown by systemctl show | use LoadCredential=stripe_secret_key:/etc/<name>/stripe_secret_key (read from $CREDENTIALS_DIRECTORY) or EnvironmentFile=/etc/<name>/env with mode 0600 |
| high | SD07 | examples/webapp.service:17 | grants CAP_SYS_ADMIN - close to full root | remove it; to bind ports below 1024 only CAP_NET_BIND_SERVICE is needed |
| high | SD08 | examples/webapp-override.conf:5 | invalid value Restart=on-faliure - systemd ignores the line and keeps the default (did you mean on-failure?) | use one of: always, no, on-abnormal, on-abort, on-failure, on-success, on-watchdog |
| high | SD08 | examples/webapp.service:16 | unknown directive RestartSecs= (ignored by systemd) - did you mean RestartSec=? | rename to RestartSec= |
| high | SD10 | examples/webapp.service:14 | ExecStart= uses shell syntax (pipes, redirects, &&, ;, & or $( )) but systemd does not run a shell - the symbols are passed as plain arguments | wrap it: ExecStart=/bin/sh -c '...' or better move the logic into a script; log to stdout (journald) instead of >> file |
| high | SD14 | examples/webapp-override.conf:3 | ProtectHome=yes but the service uses /home/deploy/shop-api - it cannot see it and will fail to start | move the app out of /home (e.g. /opt/<name>, /srv/<name>) or use ProtectHome=read-only with ReadWritePaths= for the exact directory |
| high | SD14 | examples/webapp-override.conf:4 | MemoryDenyWriteExecute=yes with a JIT runtime (/usr/bin/node) - it will crash on start | remove MemoryDenyWriteExecute= for this service |
| medium | SD05 | examples/webapp.service:4 | After=network-online.target without Wants=network-online.target - the ordering does nothing unless something else pulls the target in | add Wants=network-online.target |
| medium | SD06 | examples/webapp.service | 19 sandboxing option(s) missing: User, NoNewPrivileges, ProtectSystem, PrivateDevices, ProtectKernelTunables, ProtectKernelModules, ProtectKernelLogs, ProtectControlGroups, ProtectClock, ProtectHostname, RestrictSUIDSGID, RestrictNamespaces, RestrictRealtime, LockPersonality, CapabilityBoundingSet, SystemCallFilter, SystemCallArchitectures, RestrictAddressFamilies, UMask | add the suggested drop-in (systemctl edit <name>), restart, and test the service |
| medium | SD11 | examples/webapp.service | no [Install] WantedBy= - systemctl enable does nothing, so the service will not start at boot | add [Install] WantedBy=multi-user.target |
| medium | SD12 | examples/webapp.service:18 | stop timeout infinity - a hung service blocks shutdown and restarts forever | set TimeoutStopSec=30s (or what a clean shutdown really needs) |
| low | SD04 | examples/webapp.service:15 | Restart=always without RestartSec= (default 100ms) - a crash loop hammers the machine and hits the start limit fast | add RestartSec=5s |
| low | SD05 | examples/webapp.service:4 | After=syslog.target is obsolete | remove it (journald is always available; use network-online.target) |
| info | SD15 | examples/webapp.service | no resource limits (MemoryMax=, TasksMax=, CPUQuota=) - a leak can starve the host | add MemoryMax= and TasksMax= sized from normal usage |
Suggested drop-in (test after applying; relax an option if the service needs it):
# /etc/systemd/system/<name>.service.d/hardening.conf (systemctl edit <name>)
[Service]
# or User=<service account>; a non-root user needs AmbientCapabilities=CAP_NET_BIND_SERVICE for ports below 1024
DynamicUser=yes
NoNewPrivileges=yes
# currently full; add ReadWritePaths=/StateDirectory= for paths it writes
ProtectSystem=strict
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectKernelLogs=yes
ProtectControlGroups=yes
ProtectClock=yes
ProtectHostname=yes
RestrictSUIDSGID=yes
RestrictNamespaces=yes
RestrictRealtime=yes
LockPersonality=yes
# empty = no capabilities; or list only what you need, e.g. CAP_NET_BIND_SERVICE
CapabilityBoundingSet=
SystemCallFilter=@system-service
SystemCallArchitectures=native
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
UMask=0077
# then: systemctl daemon-reload && systemctl restart <name> && systemd-analyze security <name>examples/worker.service
Verdict: looks good (exposure 1.2)
| Sev | Code | Where | Finding | Fix |
|---|---|---|---|---|
| low | SD06 | examples/worker.service | 6 sandboxing option(s) missing: ProtectKernelLogs, ProtectClock, ProtectHostname, RestrictRealtime, MemoryDenyWriteExecute, UMask | add the suggested drop-in (systemctl edit <name>), restart, and test the service |
Suggested drop-in (test after applying; relax an option if the service needs it):
# /etc/systemd/system/<name>.service.d/hardening.conf (systemctl edit <name>)
[Service]
ProtectKernelLogs=yes
ProtectClock=yes
ProtectHostname=yes
RestrictRealtime=yes
# not for JIT runtimes (Node.js, Java, .NET, PyPy)
MemoryDenyWriteExecute=yes
UMask=0077
# then: systemctl daemon-reload && systemctl restart <name> && systemd-analyze security <name>Exposure is this script's weighted estimate, not the systemd-analyze number; run systemd-analyze security <unit> and systemd-analyze verify <file> on the target host to confirm. FILE:scripts/systemd_unit_review.py #!/usr/bin/env python3 """systemd service unit hardening reviewer (stdlib only, Python 3.8+).
Reads one or more systemd .service unit files (and drop-in .conf files, applied in the order given) the way systemd does - sections, comments, backslash line continuation, repeated keys, empty assignments that reset a list - and reviews them for reliability and security problems: running as root, secrets in Environment=, shell syntax in Exec lines without a shell, unknown or misspelled directives and values, directives in the wrong section, restart and timeout policy, network-online ordering, missing [Install], sandboxing gaps, dangerous capabilities and options that will stop the service from starting. Prints an exposure score (0 = locked down, 10 = wide open, in the spirit of systemd-analyze security) and a suggested hardening drop-in.
Usage: systemd_unit_review.py UNIT.service [DROPIN.conf ...] [--json] [--dropin] systemd_unit_review.py --self-test Exit: 0 = no high findings, 1 = at least one high finding, 2 = bad input. """ import argparse, difflib, json, re, sys
SEV = {"high": 0, "medium": 1, "low": 2, "info": 3}
The text continues at the source. Read the rest.
Source and license
Source: https://github.com/f/prompts.chat/blob/main/prompts/02885.md
Author: f, prompts.chat prompt library. License: CC0-1.0.
Shown here with formatting for the web. Keep the author and license notice when you reuse it.
Related entries
There are more like this in the members library
The Business prompt library holds 3,008 entries. Members can search all of them by meaning and read every one in full.