If a daemon on your host is compromised, the blast radius is whatever that process can reach: the whole filesystem, every kernel tunable, every syscall, every capability the unit inherited. systemd can shrink that reach dramatically with a set of per-unit directives that build a lightweight sandbox around the process — read-only filesystem views, a private /tmp, a dropped capability set, a syscall allow-list — without touching the daemon’s own code. This guide walks through adding those directives to an existing unit as an override drop-in, then scoring the result with systemd-analyze security so you can see the exposure surface shrink measurably. You are in the right place if you have a service that works but runs with far more privilege than it needs.
What you’ll accomplish
- Measure a unit’s current exposure with
systemd-analyze securityand read the score honestly (0 = safe, 10 = fully exposed). - Add filesystem, kernel, and namespace protections as a
systemctl editdrop-in — no edits to the packaged unit file. - Restrict the process to a syscall allow-list and a minimal capability set so a compromise cannot escalate.
- Re-score the unit and confirm the daemon still starts, serves traffic, and logs no sandbox denials.
- End with a unit whose exposure score has dropped from the 8–10 range into the low single digits, with every change reversible in one command.
Prerequisites
- systemd 247 or newer. Most directives here landed years earlier, but a few (
ProtectClock,ProtectHostname, the richer@system-servicesyscall group) are more complete on recent releases. Check withsystemctl --version. - A distribution that ships
systemd-analyze security— Debian 11+, Ubuntu 20.04+, RHEL/Rocky/Alma 8+, Fedora, recent Arch and openSUSE all qualify. rootorsudo, since you are editing units under/etc/systemd/system/.- An existing service unit that already works. Hardening is a second pass over a running daemon, not a substitute for getting it running first.
A note on version drift: if a directive your config uses does not exist in the running systemd, the unit logs a warning and ignores it (or, for a few, refuses to load). Always re-score and restart after each change rather than adding everything at once.
How it works
systemd does not run your daemon in a container, but it uses the same kernel primitives containers do: mount namespaces, seccomp filters, capability bounding sets, and namespace isolation. Each directive you add wraps one more restriction layer around the process before exec(). The filesystem directives (ProtectSystem, ProtectHome, PrivateTmp) build a private mount namespace where most paths are read-only or absent. NoNewPrivileges and CapabilityBoundingSet cap what privileges the process can ever hold. SystemCallFilter installs a seccomp BPF program that kills the process (or returns EPERM) on any syscall outside the allow-list. RestrictAddressFamilies narrows which socket families the process can open.
The layers are independent and additive — you can adopt them one at a time, and each one that sticks lowers the exposure score. The diagram below shows the model: the daemon in the center, each directive a concentric ring that a compromised process would have to break through.
systemd-analyze security reads all of this back out of the loaded unit and assigns each directive a weighted score, summing to an overall exposure number. It is an opinionated heuristic, not a proof of safety, but it is an excellent worklist: it tells you exactly which protections are missing and how much each is worth.
Step-by-step
1. Score the unit as it stands today. Pick a real unit — this guide uses myapp.service as the placeholder; substitute your own. The overview line at the bottom is the number to watch.
systemd-analyze security myapp.service
→ Overall exposure level for myapp.service: 9.6 UNSAFE 😨
A fresh, unhardened unit typically lands between 8 and 10. Run the same command with no argument to see every service on the host ranked, which is a fast way to find the worst offenders.
2. Open a drop-in override. Never edit the packaged .service file — a package upgrade will overwrite it. systemctl edit creates a drop-in under /etc/systemd/system/myapp.service.d/override.conf that layers on top of the shipped unit.
systemctl edit myapp.service
This opens an editor on an empty override. Everything below goes under a [Service] header.
3. Add the filesystem and kernel protections first. These are the highest-value, lowest-risk directives. Paste this block into the override:
[Service]
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
NoNewPrivileges=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
ProtectClock=true
RestrictSUIDSGID=true
StateDirectory=myapp
ProtectSystem=strict mounts the entire filesystem read-only except /dev, /proc, and /sys. Because most daemons need somewhere to write, StateDirectory=myapp carves out a writable, service-owned /var/lib/myapp for you. If your daemon writes elsewhere, you will add ReadWritePaths= in a moment.
4. Reload and restart, then re-score. Every override change needs a daemon reload before it takes effect.
systemctl daemon-reload
systemctl restart myapp.service
systemctl is-active myapp.service
active
If it says active, re-score:
systemd-analyze security myapp.service
→ Overall exposure level for myapp.service: 5.8 MEDIUM 😐
If instead the service failed, jump to Troubleshooting — a ProtectSystem=strict failure almost always means a missing writable path.
5. Add the capability and network restrictions. Run systemctl edit myapp.service again and append to the same [Service] block:
CapabilityBoundingSet=
AmbientCapabilities=
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
RestrictNamespaces=true
LockPersonality=true
MemoryDenyWriteExecute=true
An empty CapabilityBoundingSet= drops every Linux capability. If your daemon binds a port below 1024, that needs CAP_NET_BIND_SERVICE — set CapabilityBoundingSet=CAP_NET_BIND_SERVICE and AmbientCapabilities=CAP_NET_BIND_SERVICE instead of leaving both empty. RestrictAddressFamilies here allows Unix sockets and IPv4/IPv6; drop AF_INET6 if the daemon is IPv4-only.
6. Tighten the syscall surface with an allow-list. This is the single most valuable directive and the one most likely to need tuning. @system-service is systemd’s curated group of syscalls a normal service needs; the ~ prefixes below then subtract dangerous families on top of it.
SystemCallFilter=@system-service
SystemCallFilter=~@privileged @resources
SystemCallArchitectures=native
SystemCallErrorNumber=EPERM
SystemCallArchitectures=native blocks the compat (32-bit) syscall table, a common seccomp-bypass vector. SystemCallErrorNumber=EPERM makes a blocked call fail with an error the process can handle rather than being killed outright, which makes tuning far less painful.
7. Reload, restart, and score the hardened unit.
systemctl daemon-reload
systemctl restart myapp.service
systemd-analyze security myapp.service
→ Overall exposure level for myapp.service: 2.1 OK 🙂
A score in the low single digits is a realistic, sustainable target for most daemons. Chasing 0.0 usually means adding DynamicUser=yes and PrivateUsers=true, which are covered in Troubleshooting because they interact with file ownership.
Validate it works
Scoring low is meaningless if the daemon no longer does its job. Verify all three of these before you call it done.
Confirm the service is running and healthy. Check the unit state and hit the daemon the way its clients do (an HTTP probe, a socket connect, a CLI health command — whatever fits):
systemctl status myapp.service --no-pager
curl -fsS http://127.0.0.1:8080/healthz
● myapp.service - My Application
Active: active (running) since ...
ok
Watch the journal for sandbox denials. A syscall or path blocked by the sandbox shows up plainly in the log. Run this right after a restart and after exercising the daemon’s real workload:
journalctl -u myapp.service --since "5 min ago" -p warning
Look for lines containing Operation not permitted, Read-only file system, or seccomp. No such lines means the sandbox is not getting in the daemon’s way. For deeper coverage on keeping that journal trustworthy, see protecting journald.
Re-run the score one final time and record it in the unit’s comments or your change log, so the next person knows the hardening was deliberate and measured.
Troubleshooting
Service fails immediately after ProtectSystem=strict. The daemon is writing to a path that is now read-only. The journal will say Read-only file system. Find the path it wants and grant it explicitly with ReadWritePaths=/var/log/myapp (or move the write target under the StateDirectory). Prefer StateDirectory=, LogsDirectory=, and CacheDirectory= over raw ReadWritePaths= — they create the directory with correct ownership automatically.
The process is killed on startup or under load after SystemCallFilter. The allow-list is too tight for something the daemon actually does — GC, threading, or a runtime feature. Because you set SystemCallErrorNumber=EPERM, most failures now surface as errors rather than a SIGSYS kill, but not all. Temporarily add SystemCallFilter=@pkey or the specific family, or loosen to SystemCallFilter=@system-service with no subtraction, restart, and confirm. Then re-add subtractions one at a time.
DynamicUser=yes breaks file ownership. A dynamic user gets a UID allocated at start time that changes across reboots, so any files it wrote as itself become unreadable next boot unless they live under a StateDirectory/LogsDirectory (systemd remaps those). If your daemon needs a stable UID for files it shares with other processes, do not use DynamicUser — create a fixed system user instead. See sudoers-safe-configuration for the companion topic of not handing that user more than it needs.
MemoryDenyWriteExecute=true breaks a JIT runtime. Anything that compiles code at runtime — the JVM, V8/Node, LuaJIT, some Python extensions, .NET tiered compilation — needs writable-then-executable memory, which this directive forbids. The daemon will crash or refuse to start. Drop MemoryDenyWriteExecute for those workloads; the score cost is small and the alternative is a broken service.
A directive is silently ignored. If the score does not move after adding a directive, your systemd may be too old to support it. Confirm with systemctl show myapp.service -p <Directive> and check systemctl --version against the directive’s documented minimum.
When this is the wrong approach
If the daemon already runs inside a container, the container runtime is providing most of these boundaries (namespaces, dropped capabilities, a seccomp profile) at the container level — layering unit hardening on top of the runtime is usually redundant and can conflict with how the orchestrator expects to manage the process. Harden the container’s profile instead.
For a very short-lived unit — a oneshot that runs for milliseconds, or a timer-triggered job — the exposure window is small and the tuning cost may not be worth it; spend the effort on the long-running daemons that are actually exposed. And if your systemd predates the directives you need (anything before 247 is increasingly limited), do not try to backport the behavior with fragile wrappers — upgrade the base OS or accept a more modest score. For the broader unit-writing patterns that this hardening sits on top of, see systemd service management and production unit patterns. The authoritative reference for every directive named here is the systemd.exec man page, and the scoring tool is documented in systemd-analyze.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.