PromptOtherOpen

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: Prompt

systemd 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; --json and --dropin outputs (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 service
  • references/checks-and-codes.md - every finding code, its severity and the fix
  • templates/unit-review.md - the review summary to send back, with the corrected unit and the rollout steps
  • examples/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 start
  • examples/worker.service - a mostly hardened worker with DynamicUser, StateDirectory and LoadCredential
  • examples/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-test

Files 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=yes or 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 security is 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/*.conf in 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-reload after 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.target only 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 enable starts 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 show and the unit file (mode 0644).
  • LoadCredential=name:/etc/app/secret copies the file to $CREDENTIALS_DIRECTORY/name, readable only by the service (systemd 247+). SetCredentialEncrypted= / systemd-creds for encrypted ones (250+).
  • EnvironmentFile=/etc/app/env with owner root and mode 0600 is the portable fallback.
  • Command-line secrets are visible in ps and /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 app and User=app, Group=app.
  • Port below 1024 as non-root: AmbientCapabilities=CAP_NET_BIND_SERVICE and CapabilityBoundingSet=CAP_NET_BIND_SERVICE. CAP_SYS_ADMIN is almost root - never for a web app.

Sandboxing options (what they block, when they break)

OptionBlocksBreaks when
NoNewPrivileges=yessetuid binaries, privilege gain on execthe service runs sudo/ping/setuid helpers
ProtectSystem=strictwrites anywhere except /dev, /proc, /sys, and the listed pathsthe 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=yesother services' /tmpanother process shares files through /tmp
PrivateDevices=yesraw devices (/dev/sda, /dev/mem)the service needs GPUs, serial ports or USB
ProtectKernelTunables/Modules/Logs=yes/proc/sys writes, module loading, kernel logthe service tunes sysctls or loads modules
ProtectControlGroups=yescgroup writescontainer runtimes
ProtectClock / ProtectHostname=yesclock and hostname changesNTP clients, hostname tools
RestrictSUIDSGID=yescreating setuid filesinstallers
RestrictNamespaces=yescreating namespacescontainer tools, Chromium sandbox
RestrictRealtime=yesrealtime schedulingaudio servers
LockPersonality=yeschanging the execution domainalmost never
MemoryDenyWriteExecute=yeswritable+executable memoryJIT 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-serviceuncommon syscalls (mount, kexec, ptrace ...)low-level tools; check the journal for SIGSYS
SystemCallArchitectures=native32-bit syscall ABI tricks32-bit binaries
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6netlink, packet, bluetooth socketstools that read routing tables (add AF_NETLINK)
UMask=0077world-readable new filesother 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

CodeSeverityCheckFix
SD01high (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
SD02high: no ExecStart, several ExecStart for a non-oneshot; low: command not an absolute pathExecStart sanityone absolute ExecStart; empty ExecStart= first in a drop-in to replace it
SD03highsecret-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 lineLoadCredential= or EnvironmentFile= with mode 0600; rotate the leaked secret
SD04medium: 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 limitrestart policyRestart=on-failure, RestartSec=5s
SD05medium: After= and Wants= of network-online.target not paired; low: obsolete syslog.target / network.serviceorderingadd the missing half
SD06medium if exposure >= 5, else lowsandboxing options missing (weighted exposure score)the --dropin output, tested step by step
SD07high: CAP_SYS_ADMIN, CAP_SYS_MODULE, CAP_SYS_PTRACE, CAP_SYS_RAWIO; medium: CAP_DAC_OVERRIDE, CAP_NET_ADMIN, CAP_SETUID/SETGID; low: othersdangerous capabilities in AmbientCapabilities / CapabilityBoundingSetkeep only what is needed
SD08high: 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 sectionsystemd logs a warning and ignores the linefix the spelling (suggestion shown)
SD09mediumdirective in the wrong section (StartLimitBurst in [Service], WantedBy in [Service], old StartLimitInterval)move it
SD10high: pipes, redirects, &&, ;, & or $( ) in an Exec line without /bin/sh -c; medium: nohup / --daemon with Type=simple/exec; low: Type=forking without PIDFilesystemd does not use a shella script, sh -c, or foreground mode
SD11medium: no WantedBy/RequiredBy/Alias; low: WantedBy=default.target or graphical.target for a system serviceenable at bootWantedBy=multi-user.target
SD12medium: TimeoutStopSec=infinity/0, KillMode=none; low: KillMode=processstop behaviourTimeoutStopSec=30s, KillMode=mixed
SD13lowthe same single-value key twice in one filekeep one
SD14high: 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/RuntimeDirectoryoptions that break the servicemove the app, add the write path, drop the option
SD15infono MemoryMax/MemoryHigh/TasksMax/CPUQuotaadd 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

#ProblemWhy it mattersFix
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

  1. Rotate the leaked secrets; put the new ones in /etc/<name>/ (mode 0600).
  2. systemd-analyze verify /etc/systemd/system/<unit>
  3. systemctl daemon-reload && systemctl restart <unit>; check journalctl -u <unit> -b and the health endpoint.
  4. systemd-analyze security <unit> - expect <exposure>.
  5. 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

UnitDescriptionTypeRuns asRestartExposure (0-10)HighMediumLowInfo
examples/webapp.service + examples/webapp-override.confShop API (Node.js)simplerootalways8.1 UNSAFE9421
examples/worker.serviceThumbnail workerexecDynamicUseron-failure1.2 OK0010

examples/webapp.service + examples/webapp-override.conf

Verdict: 9 high finding(s) - fix before deploying

SevCodeWhereFindingFix
highSD01examples/webapp.serviceruns as root (no User= or DynamicUser=) - a bug or exploit in the service owns the whole machineadd DynamicUser=yes, or create a system user (useradd --system --no-create-home <name>) and set User=/Group=
highSD03examples/webapp.service:11DATABASE_URL contains a URL with an embedded passwordmove the credential out of the unit (LoadCredential= / EnvironmentFile= 0600)
highSD03examples/webapp.service:12secret STRIPE_SECRET_KEY is written in the unit file - unit files are world-readable and shown by systemctl showuse LoadCredential=stripe_secret_key:/etc/<name>/stripe_secret_key (read from $CREDENTIALS_DIRECTORY) or EnvironmentFile=/etc/<name>/env with mode 0600
highSD07examples/webapp.service:17grants CAP_SYS_ADMIN - close to full rootremove it; to bind ports below 1024 only CAP_NET_BIND_SERVICE is needed
highSD08examples/webapp-override.conf:5invalid 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
highSD08examples/webapp.service:16unknown directive RestartSecs= (ignored by systemd) - did you mean RestartSec=?rename to RestartSec=
highSD10examples/webapp.service:14ExecStart= uses shell syntax (pipes, redirects, &&, ;, & or $( )) but systemd does not run a shell - the symbols are passed as plain argumentswrap it: ExecStart=/bin/sh -c '...' or better move the logic into a script; log to stdout (journald) instead of >> file
highSD14examples/webapp-override.conf:3ProtectHome=yes but the service uses /home/deploy/shop-api - it cannot see it and will fail to startmove the app out of /home (e.g. /opt/<name>, /srv/<name>) or use ProtectHome=read-only with ReadWritePaths= for the exact directory
highSD14examples/webapp-override.conf:4MemoryDenyWriteExecute=yes with a JIT runtime (/usr/bin/node) - it will crash on startremove MemoryDenyWriteExecute= for this service
mediumSD05examples/webapp.service:4After=network-online.target without Wants=network-online.target - the ordering does nothing unless something else pulls the target inadd Wants=network-online.target
mediumSD06examples/webapp.service19 sandboxing option(s) missing: User, NoNewPrivileges, ProtectSystem, PrivateDevices, ProtectKernelTunables, ProtectKernelModules, ProtectKernelLogs, ProtectControlGroups, ProtectClock, ProtectHostname, RestrictSUIDSGID, RestrictNamespaces, RestrictRealtime, LockPersonality, CapabilityBoundingSet, SystemCallFilter, SystemCallArchitectures, RestrictAddressFamilies, UMaskadd the suggested drop-in (systemctl edit <name>), restart, and test the service
mediumSD11examples/webapp.serviceno [Install] WantedBy= - systemctl enable does nothing, so the service will not start at bootadd [Install] WantedBy=multi-user.target
mediumSD12examples/webapp.service:18stop timeout infinity - a hung service blocks shutdown and restarts foreverset TimeoutStopSec=30s (or what a clean shutdown really needs)
lowSD04examples/webapp.service:15Restart=always without RestartSec= (default 100ms) - a crash loop hammers the machine and hits the start limit fastadd RestartSec=5s
lowSD05examples/webapp.service:4After=syslog.target is obsoleteremove it (journald is always available; use network-online.target)
infoSD15examples/webapp.serviceno resource limits (MemoryMax=, TasksMax=, CPUQuota=) - a leak can starve the hostadd 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)

SevCodeWhereFindingFix
lowSD06examples/worker.service6 sandboxing option(s) missing: ProtectKernelLogs, ProtectClock, ProtectHostname, RestrictRealtime, MemoryDenyWriteExecute, UMaskadd 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.