systemd service hardening: sandboxing what you already run
How to lock down a systemd service with the sandboxing directives that ship in the box, how to measure the result and check it is live, and where it sits next to a firewall and a hardened SSH setup.
Contents
Why this exists
In September 1975 Jerome Saltzer and Michael Schroeder published “The Protection of Information in Computer Systems,” a paper that set out eight design principles for secure systems. Most of them are still quoted. The best known is the principle of least privilege: “Every program and every user of the system should operate using the least set of privileges necessary to complete the job.” Their reasoning was about damage. A program that holds only what it needs can do only limited harm when it goes wrong, and fewer programs have to be trusted at all.
For most of the following thirty-five years, Unix daemons ignored the advice, mostly because the operating system gave them no practical way to follow it. A service ran as some user and could do whatever that user could do. The kernel grew the tools piece by piece: capabilities in Linux 2.2, mount namespaces in 2.4.19, seccomp in 2005 and its programmable form, seccomp-bpf, in 2012, written for the Chrome sandbox. Using them meant writing wrapper code. When Lennart Poettering and Kay Sievers began systemd in 2010, they made them lines in a unit file.
A firewall decides who reaches the service. SSH hardening decides who reaches the host. Neither says anything about what a service can do to the rest of the machine once it is running and, one day, compromised.
That gap matters because most of what you run does not need most of what it can touch. A metrics exporter has no business reading /home. A web app does not need to load kernel modules. A media server never writes to /etc. By default every one of them can, because a plain unit runs with the full ambient authority of its user.
systemd ships a long list of directives that take that authority away one piece at a time. They cost nothing to run, need no extra package, and most services never notice them. This is the cheapest hardening on the list, and the one people skip.
How it actually works
The kernel already has the primitives: namespaces, capabilities, seccomp, mount restrictions. Wiring them up by hand is miserable. systemd exposes them as unit options, applies them before the service’s process starts, and gives you one command to score the result.
Three ideas cover most of it.
Filesystem isolation mounts the host read-only for the service, hides directories it should never see, and hands back only the paths it writes to.
Privilege reduction drops Linux capabilities to the empty set, blocks privilege escalation, and refuses memory that is both writable and executable.
Kernel surface reduction filters system calls down to the ones a normal service uses, and blocks the address families and namespaces it will never open.
You do not need to understand each kernel feature to benefit. You need to know which directive maps to which “this service should never do that.”
Minimum useful config
Do not edit the packaged unit. Use a drop-in, so package updates leave your changes alone:
sudo systemctl edit myservice
That opens an override at /etc/systemd/system/myservice.service.d/override.conf. A sensible starting set:
[Service]
# Refuse setuid/setgid escalation for the process and everything it spawns
NoNewPrivileges=true
# Read-only view of the whole OS, private /tmp, home directories hidden
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
# Hand back only what the service actually writes to
ReadWritePaths=/var/lib/myservice
# Kernel is off-limits
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
# Drop every capability, then add back only what is needed (usually nothing)
CapabilityBoundingSet=
AmbientCapabilities=
# Syscall allow/deny list: allow the normal service set, drop the rest
SystemCallFilter=@system-service
SystemCallErrorNumber=EPERM
# Network families most services never need
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
RestrictNamespaces=true
MemoryDenyWriteExecute=true
Reload and restart:
sudo systemctl daemon-reload
sudo systemctl restart myservice
ProtectSystem=strict does the heavy lifting, and it is the one most likely to break something, because a service that quietly writes outside its data directory will now fail. That failure is the point. It tells you exactly which path to add to ReadWritePaths, and nothing else stays writable.
The empty CapabilityBoundingSet= is the bluntest line here. An empty assignment clears the set entirely, so even a service started as root keeps none of root’s special powers. A service that needs one, a DNS server binding port 53 for instance, gets it back by name (CapabilityBoundingSet=CAP_NET_BIND_SERVICE), and if it runs as an ordinary user rather than starting as root, names it in AmbientCapabilities= as well. Nothing else comes back.
Watching it work
systemd scores a unit’s exposure for you:
systemd-analyze security myservice
You get a table of directives and an overall number from 0 (locked down) to 10 (wide open). A stock third-party unit usually lands around 9. The config above typically pulls the same service under 3.
→ Overall exposure level for myservice.service: 2.4 OK 🙂
The number is a guide, not a grade. A high score on a service that only talks to localhost matters less than a low score on something exposed to the internet. Read the table as well as the total, and spend the effort where the reachable attack surface actually is.
A restriction written in a file is not yet a restriction in force. To see what a directive does, run a throwaway command under it:
sudo systemd-run --property=ProtectHome=true --pty ls /home
An empty listing is the sandbox doing its job. That transient unit shows the directive, though, not the service. To look through the running service’s own eyes, list the directory through its root in /proc, which shows the filesystem exactly as the process sees it, mount namespace included:
sudo ls /proc/$(systemctl show -p MainPID --value myservice)/root/home
If the drop-in took effect, that listing is empty too.
Gotchas worth knowing
ProtectSystem=strict breaks sloppy services on purpose. If a unit fails to start after you apply it, read journalctl -u myservice for the read-only-filesystem error, add that path to ReadWritePaths, and try again. Do not fall back to the weaker ProtectSystem=full without a real reason; it trades away most of the benefit.
SystemCallFilter changes how failures look. With SystemCallErrorNumber=EPERM, as in the config above, a blocked system call simply fails, and the service logs “Operation not permitted” or behaves oddly. Without that line, the kernel kills the process with SIGSYS the moment it makes the call. Either way, find the missing group and add it rather than removing the filter: systemd-analyze syscall-filter lists every group and its calls. @system-service already includes the common ones, @resources among them. A time-sync daemon, for instance, needs @clock, which it leaves out. Never allow @obsolete or @raw-io without a specific need.
MemoryDenyWriteExecute=true and just-in-time compilers do not mix. The systemd documentation says as much: the option is incompatible with programs that generate code at runtime. A service built on the JVM, Node.js or another JIT runtime may refuse to start or crash under it, and for those services the line has to go.
Containers already do some of this. If a service runs as a rootless Podman or Quadlet unit, it inherits its own namespaces and a default seccomp profile, so a few directives are redundant. The filesystem and capability options still apply to the container runtime itself and are worth keeping.
Test the actual workload as well as startup. A service can start clean and then fail the first time it opens a socket, forks a helper or writes a cache file. Exercise the real paths after hardening, watch the journal, and only then walk away.
Where it fits
The layers run from the outside in. The firewall denies inbound traffic by default and opens only the ports you serve. SSH hardening means keys only, no root login, no passwords. fail2ban bans the brute-force noise that gets past the first two. Service sandboxing assumes a service will eventually be compromised, and makes sure that when it is, it lands in an empty room.
The first three keep attackers out. This one decides how much they get when one of the others fails, and eventually one of them will. It is the difference between a compromised exporter reading a metric and a compromised exporter reading your home directory. Saltzer and Schroeder asked for it in 1975. The directives are already installed, and the only cost is the ten minutes it takes to write the drop-in and read the journal once.
Sources
- Saltzer, Jerome H., and Michael D. Schroeder. “The Protection of Information in Computer Systems.” Proceedings of the IEEE 63, no. 9 (September 1975): 1278 to 1308.
- systemd project. systemd.exec(5), systemd-analyze(1) and systemd-run(1) manual pages.
- Linux man-pages project. proc(5), on
/proc/[pid]/root. - Drewry, Will. “Dynamic seccomp policies (using BPF filters).” Linux kernel mailing list, January 2012.