How-To Guide

Hardening systemd Service Units for Production

Lock down Linux daemons using DynamicUser, ProtectSystem=strict, capability bounding sets, memory caps, and systemd-analyze security scoring.

On this page

  1. Why Default Unit Files Leave Hosts Exposed
  2. Isolating Filesystem, Identity, and Privileges
  3. Handling Low Ports and JIT Runtime Nuances
  4. Logging, Watchdogs, and Rollout Gotchas
  5. Auditing Exposure with systemd-analyze

Why Default Unit Files Leave Hosts Exposed

A minimal systemd service file containing only [Unit], ExecStart=/usr/local/bin/worker, and WantedBy=multi-user.target starts the binary as root with unrestricted access to /etc, /home, raw network sockets, kernel modules, and all host RAM. If a dependency vulnerability allows arbitrary file reads, command injection, or uncontrolled memory allocation, the compromise immediately spans the entire virtual machine.

Modern systemd provides kernel-enforced sandboxing primitives—namespaces, seccomp-BPF syscall filters, Linux capability bounding, and cgroup v2 resource ceilings—directly inside declarative .service directives. You get container-grade process isolation with zero Docker daemon overhead. Before deploying to production, you can draft hardened [Unit], [Service], and [Install] sections interactively in the Interactive Systemd Unit Generator.

Isolating Filesystem, Identity, and Privileges

Start by shedding root identity and making the entire root filesystem read-only from the daemon’s perspective. If your service does not need static UID permissions shared with other hosts over NFS, DynamicUser=yes allocates an ephemeral unprivileged UID/GID on every start and couples cleanly with StateDirectory=, CacheDirectory=, and LogsDirectory=. Note that ProtectSystem=strict mounts the entire filesystem hierarchy read-only except /dev, /proc, and /sys, so you must explicitly list writable directories (or let StateDirectory= manage /var/lib/private/<name> automatically).

[Unit]
Description=Webhook Ingestion Worker
Documentation=https://internal.example.com/runbooks/webhook-worker
After=network-online.target postgresql.service
Wants=network-online.target

[Service]
Type=exec
DynamicUser=yes
StateDirectory=webhook-worker
LogsDirectory=webhook-worker
RuntimeDirectory=webhook-worker
WorkingDirectory=/var/lib/webhook-worker

ExecStart=/usr/local/bin/webhook-worker --config /etc/webhook-worker/config.toml
ExecReload=/bin/kill -HUP $MAINPID
TimeoutStopSec=30s
KillMode=mixed
Restart=on-failure
RestartSec=3s

# Filesystem & kernel mount isolation
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectKernelLogs=yes
ProtectControlGroups=yes
ProtectClock=yes
ProtectHostname=yes
ReadOnlyPaths=/etc/webhook-worker

# Privilege & syscall lockdown
NoNewPrivileges=yes
CapabilityBoundingSet=
AmbientCapabilities=
LockPersonality=yes
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
MemoryDenyWriteExecute=yes
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
SystemCallArchitectures=native
SystemCallFilter=@system-service
SystemCallFilter=~@privileged @resources

# Cgroup v2 resource & fd caps
MemoryHigh=768M
MemoryMax=1G
CPUQuota=200%
TasksMax=128
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target

Notice several critical design choices in this unit:

  • Type=exec instead of Type=simple: Type=simple marks the service active the instant fork() returns, even if the binary fails immediately due to a missing shared library. Type=exec waits until execve() itself succeeds, catching broken binary paths during systemctl start.
  • KillMode=mixed: Sends SIGTERM strictly to the main process first so your graceful shutdown hook drains in-flight requests, and sends SIGKILL to lingering child workers only if TimeoutStopSec=30s expires.
  • MemoryHigh paired with MemoryMax: MemoryHigh triggers kernel memory pressure throttling and garbage collection early at 768 MiB, while MemoryMax=1G enforces a hard OOM boundary inside the service’s cgroup so a memory leak never invokes the host-wide OOM killer against PostgreSQL.

Handling Low Ports and JIT Runtime Nuances

Two requirements often trip engineers during hardening: binding privileged ports (80 or 443) and running JIT-compiled runtimes (Node.js V8, Java HotSpot, Python with ctypes, or WebAssembly). If a reverse proxy or API server truly must bind port 443 directly without running as root, grant solely CAP_NET_BIND_SERVICE instead of keeping full root:

[Service]
User=api-edge
Group=api-edge
NoNewPrivileges=yes
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
AmbientCapabilities=CAP_NET_BIND_SERVICE
# Required for V8/JVM JIT compilers that map RWX memory pages
MemoryDenyWriteExecute=no
# Restrict to IPv4, IPv6, and local Unix domain sockets
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX

Watch closely for MemoryDenyWriteExecute=yes: it sets seccomp/memory rules forbidding writable+executable (W^X) anonymous memory mappings. Static native binaries written in Go or Rust thrive with MemoryDenyWriteExecute=yes, whereas Node.js (V8), Deno, and JVM runtimes crash immediately on startup unless you set MemoryDenyWriteExecute=no.

When distributing API keys or TLS private keys to hardened units, avoid storing plaintext credentials inside world-readable environment files (EnvironmentFile=) because any local user querying /proc/<pid>/environ or running systemctl show can inspect environment settings depending on host permissions. Instead, use LoadCredentialEncrypted= or LoadCredential=db_pass:/etc/credstore/db_pass paired with systemd-creds, which mounts secrets inside a private read-only tmpfs directory readable strictly by the service’s UID via $CREDENTIALS_DIRECTORY and strips them automatically when the unit stops.

Logging, Watchdogs, and Rollout Gotchas

Keep these six operational realities in mind before rolling hardened units onto production fleets:

  • Restart storm masking broken configs: Writing Restart=always without StartLimitIntervalSec and StartLimitBurst (or keeping RestartSec=3s too low) spins failed binaries endlessly in logs. Note that in modern systemd, StartLimitIntervalSec and StartLimitBurst live under [Unit], whereas RestartSec lives under [Service].
  • DynamicUser=yes breaking pre-existing static files: If an Ansible playbook previously chowned /etc/webhook-worker/secrets.env to a fixed numeric UID and mode 0600, an ephemeral DynamicUser cannot read it. Either switch secret delivery to LoadCredential= or keep a static dedicated system user.
  • Missing AF_NETLINK for Go DNS/interface lookups: Go programs inspecting network interfaces at startup or certain DNS resolvers occasionally require AF_NETLINK inside RestrictAddressFamilies=. Always test under realistic traffic in staging.
  • Overwriting distro defaults cleanly via drop-ins: Avoid editing vendor files in /lib/systemd/system/ directly because package upgrades overwrite them. Create overrides cleanly via systemctl edit myservice.service inside /etc/systemd/system/myservice.service.d/hardening.conf.
  • Silent PrivateTmp=yes surprises: Sidecar scripts expecting to exchange files through /tmp/shared.sock cannot see across separate PrivateTmp mount namespaces. Switch inter-process sockets to RuntimeDirectory= (/run/myservice/) instead.
  • Journal flood throttling hiding crash reasons: Under LogRateLimitIntervalSec defaults, noisy crash loops can suppress the initial panic stack trace; configure LogRateLimitBurst=1000 on critical services or emit structured JSON to StandardOutput=journal so journalctl -u myservice -o json-pretty stays intact.

Auditing Exposure with systemd-analyze

Never guess whether a sandboxing directive actually parsed or tightened your posture. Draft your baseline unit in the Interactive Systemd Unit Generator, install it on a staging VM, and run systemd-analyze to inspect syntax, ordering cycles, and quantitative exposure scores:

# 1. Reload daemon definitions and validate unit syntax
sudo systemctl daemon-reload
sudo systemd-analyze verify /etc/systemd/system/webhook-worker.service

# 2. Audit kernel exposure score (aim below 2.0 SAFE)
sudo systemd-analyze security webhook-worker.service

# 3. Verify graceful stop and non-root runtime UID
sudo systemctl restart webhook-worker.service
systemctl show -p MainPID,UID,MemoryCurrent webhook-worker.service
sudo systemctl stop webhook-worker.service

Check that systemd-analyze security reports SAFE (score below 2.0), verify journal logs show zero SECCOMP (SIGSYS) kills during load testing, and confirm systemctl stop exits cleanly with status 0 well inside TimeoutStopSec. Whenever upgrading a hardened unit across Debian or RHEL minor releases, re-run systemd-analyze security because newer systemd versions introduce stricter kernel checks that may adjust baseline weights. Finally, include systemd-analyze verify inside your packaging CI pipeline so malformed directives or broken unit dependencies are caught long before deployment.

FAQ

What does NoNewPrivileges=yes prevent even if an application runs as a non-root user?
NoNewPrivileges sets the kernel PR_SET_NO_NEW_PRIVS bit so child processes spawned by the service can never elevate privileges via setuid/setgid binaries such as sudo or filesystem capabilities, blocking common local privilege escalation chains.
How do DynamicUser=yes services persist state across restarts without a fixed /etc/passwd entry?
When combined with StateDirectory=myservice, systemd automatically creates /var/lib/private/myservice, assigns transient UID ownership on startup, and restores ownership seamlessly on subsequent launches without leaving stale accounts behind.
Why can SystemCallFilter=@system-service break interpreters like Node.js or Java if tuned too tightly?
JIT runtimes and Go/JVM threads rely on clone, mprotect, and futex variations. Always include @system-service and exclude ~@privileged and ~@resources rather than hand-crafting minimal syscall allowlists without staging soak tests.

Related Examples

Interactive Tools for This Topic