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
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=execinstead ofType=simple:Type=simplemarks the service active the instantfork()returns, even if the binary fails immediately due to a missing shared library.Type=execwaits untilexecve()itself succeeds, catching broken binary paths duringsystemctl start.KillMode=mixed: SendsSIGTERMstrictly to the main process first so your graceful shutdown hook drains in-flight requests, and sendsSIGKILLto lingering child workers only ifTimeoutStopSec=30sexpires.MemoryHighpaired withMemoryMax:MemoryHightriggers kernel memory pressure throttling and garbage collection early at 768 MiB, whileMemoryMax=1Genforces 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=alwayswithoutStartLimitIntervalSecandStartLimitBurst(or keepingRestartSec=3stoo low) spins failed binaries endlessly in logs. Note that in modernsystemd,StartLimitIntervalSecandStartLimitBurstlive under[Unit], whereasRestartSeclives under[Service]. DynamicUser=yesbreaking pre-existing static files: If an Ansible playbook previouslychowned/etc/webhook-worker/secrets.envto a fixed numeric UID and mode0600, an ephemeralDynamicUsercannot read it. Either switch secret delivery toLoadCredential=or keep a static dedicated system user.- Missing
AF_NETLINKfor Go DNS/interface lookups: Go programs inspecting network interfaces at startup or certain DNS resolvers occasionally requireAF_NETLINKinsideRestrictAddressFamilies=. 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 viasystemctl edit myservice.serviceinside/etc/systemd/system/myservice.service.d/hardening.conf. - Silent
PrivateTmp=yessurprises: Sidecar scripts expecting to exchange files through/tmp/shared.sockcannot see across separatePrivateTmpmount namespaces. Switch inter-process sockets toRuntimeDirectory=(/run/myservice/) instead. - Journal flood throttling hiding crash reasons: Under
LogRateLimitIntervalSecdefaults, noisy crash loops can suppress the initial panic stack trace; configureLogRateLimitBurst=1000on critical services or emit structured JSON toStandardOutput=journalsojournalctl -u myservice -o json-prettystays 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.
Interactive Tools for This Topic
Report a problem with this articleOpens a pre-filled issue on GitHub.