Skip to content

Sandboxing a systemd service — score it, harden it, decode the denials

Use systemd-analyze security to score a unit, then harden it in waves through a drop-in override — ProtectSystem, CapabilityBoundingSet, SystemCallFilter — and read the exact sandbox denial out of the journal when the service stops starting.

Most third-party daemons ship a service unit that does nothing but name a binary. It runs as root, sees the whole filesystem, holds every Linux capability, and can make every syscall the kernel offers — none of which a program that reads /proc and answers HTTP on one port actually needs. systemd can take almost all of it away with two dozen directives, without patching the daemon and without editing the file the package manager owns. The part nobody writes down is the loop in the middle: you will over-tighten, the service will refuse to start, and the fix depends entirely on telling a seccomp kill from a read-only mount from a missing address family. This guide covers the measuring, the tightening, and — mostly — the decoding.

What you’ll accomplish

  • Score a unit with systemd-analyze security and read the per-directive table it prints as a worklist, not a verdict.
  • Try a directive on a throwaway process with systemd-run before committing it to a unit people depend on.
  • Apply hardening in three waves through a drop-in override, so a package upgrade never silently undoes your work.
  • Recognise the four denial signatures — 226/NAMESPACE, 31/SYS, Read-only file system, address family not supported — and map each one back to the directive that caused it.
  • Leave behind a unit whose exposure score you can assert in CI with --threshold, and a record of which directives you deliberately did not apply.

Prerequisites

  • systemd 240 or newer for the security verb itself. The per-directive table and --json= output matured through 246, --threshold= arrived in 248, and offline analysis of a unit file you have not installed yet arrived in 250. Check with systemctl --version.
  • A caveat worth checking before you plan a rollout: RHEL, AlmaLinux and Rocky 8 ship systemd 239, which has no systemd-analyze security at all. The directives still work there; only the scoring tool is missing. RHEL 9 (252), Debian 12 (252), Debian 13, and Ubuntu 22.04/24.04 all have it.
  • root or sudo, and a unit that already starts and works. Hardening is a second pass over something functional.
  • auditd installed if you want ausyscall for translating syscall numbers. Not required — there is a fallback below.

This guide uses node_exporter.service as the worked example: a Go daemon installed from an upstream tarball with a hand-written unit, which is exactly the shape that scores worst. Substitute your own unit name throughout. If your distribution packages the same daemon, its unit is probably already partly hardened and your starting score will be lower.

How it works

None of this is a container. systemd applies these settings in the child process between fork() and exec(), using the same kernel primitives a container runtime uses: it unshares a mount namespace and remounts paths read-only or empty, it trims the capability bounding set, it sets PR_SET_NO_NEW_PRIVS, and it installs a seccomp BPF program. By the time your binary’s main() runs, the restrictions are already in place and cannot be lifted by the process itself.

That has one consequence that shapes the whole workflow: the sandbox fails before your daemon can log anything. A unit that dies to a namespace error never emitted a line of application output, which is why people conclude the daemon is broken when the unit configuration is what broke.

Cycle diagram of the systemd hardening loop — measure the exposure score, add one wave of directives to a drop-in, reload and restart, re-score and exercise the workload, with a failure branch that reads the denial from the journal before looping back

systemd-analyze security reads the settings back out of the loaded unit and assigns each missing protection a weight, summing them into an exposure number from 0 to 10. It is a heuristic with opinions — it will happily give a high score to a unit that is perfectly safe in context, and it cannot tell you whether the daemon still works. Treat the number as a prompt, never as a result.

Step-by-step

1. Score the host, then the unit. With no argument the tool ranks every loaded service, which is the fastest way to find what is worth your afternoon.

systemd-analyze security --no-pager | head -6
UNIT                                 EXPOSURE PREDICATE HAPPY
node_exporter.service                     9.6 UNSAFE    😨
dbus.service                              9.5 UNSAFE    😨
sshd.service                              9.6 UNSAFE    😨
systemd-udevd.service                     7.0 MEDIUM    😐
systemd-journald.service                  4.5 OK        🙂

2. Read the per-directive table, not the total. Naming a unit prints every setting the tool knows about, with what it costs you.

systemd-analyze security node_exporter.service | head -6
  NAME                                  DESCRIPTION                                       EXPOSURE
✗ PrivateNetwork=                       Service has access to the host's network               0.5
✗ User=/DynamicUser=                    Service runs as root user                              0.4
✗ CapabilityBoundingSet=~CAP_SYS_ADMIN  Service has administrator privileges                   0.3
✗ SystemCallFilter=~@swap               Service does not filter system calls                   0.2
✗ ProtectHome=                          Service has full access to home directories            0.2

Read down the EXPOSURE column and start at the top. Note the first line: PrivateNetwork= is worth 0.5 and you cannot use it, because the daemon serves HTTP. That is the tool being opinionated rather than correct, and it is why the number will never reach zero for a network service.

3. Try a directive before you commit it. systemd-run gives you a transient unit with whatever properties you name, so you can find out what a setting actually does to a shell without touching a real service.

sudo systemd-run --pty --property=ProtectSystem=strict --property=PrivateTmp=yes /bin/bash
Running as unit: run-u4207.service
Press ^] three times within 1s to disconnect TTY.

Inside that shell, prove the sandbox is real before you trust it:

touch /etc/probe && echo unexpected || echo "blocked as designed"
touch: cannot touch '/etc/probe': Read-only file system
blocked as designed

Type exit to leave. Nothing persists — the transient unit disappears.

4. Create the drop-in, never touch the vendor unit. A drop-in is a fragment merged on top of the shipped file. Package upgrades replace the shipped file and leave your fragment alone, which is the entire point.

sudo mkdir -p /etc/systemd/system/node_exporter.service.d
sudo tee /etc/systemd/system/node_exporter.service.d/10-hardening.conf >/dev/null <<'EOF'
[Service]
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
NoNewPrivileges=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectKernelLogs=true
ProtectControlGroups=true
ProtectHostname=true
ProtectClock=true
StateDirectory=node_exporter
EOF
sudo systemctl daemon-reload
systemctl cat node_exporter.service | tail -4
ProtectHostname=true
ProtectClock=true
StateDirectory=node_exporter

systemctl cat prints the merged view with each source file named, so it is also how you confirm the drop-in was found at all. systemctl edit node_exporter.service opens the same file in an editor if you prefer.

That first wave is the highest value for the lowest risk. ProtectSystem=strict makes the entire filesystem read-only apart from /dev, /proc and /sys; StateDirectory= then carves back a writable, correctly-owned /var/lib/node_exporter. ProtectKernelTunables= makes /proc/sys and /sys read-only, ProtectKernelModules= blocks module loading, and ProtectKernelLogs= cuts off dmesg and /dev/kmsg.

5. Restart and re-score before adding anything else. One wave, one restart, one score. Batching all three waves is how you end up with a broken service and no idea which line did it.

sudo systemctl restart node_exporter.service && systemd-analyze security node_exporter.service | tail -1
→ Overall exposure level for node_exporter.service: 6.4 MEDIUM 😐

6. Add the second wave — privileges, devices, and address families. Append to the same file, then reload and restart again.

[Service]
CapabilityBoundingSet=
AmbientCapabilities=
PrivateDevices=true
RestrictNamespaces=true
RestrictRealtime=true
RestrictSUIDSGID=true
LockPersonality=true
MemoryDenyWriteExecute=true
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK

An empty CapabilityBoundingSet= drops every capability permanently. If your daemon binds a port below 1024 you need CapabilityBoundingSet=CAP_NET_BIND_SERVICE and the same value in AmbientCapabilities= — the bounding set alone caps what it may hold, the ambient set is what it actually gets. PrivateDevices=true replaces /dev with a minimal private instance holding little more than null, zero, random and urandom.

AF_NETLINK in that list is deliberate. Anything reading interface statistics, routes or ethtool data from the kernel — node_exporter’s netdev and netclass collectors among them — opens a netlink socket, and omitting the family produces a failure that looks like a network problem, not a sandbox one.

7. Add the third wave — the syscall filter — with kills turned into errors first. This is the one that will break something, so make the break diagnosable.

[Service]
SystemCallArchitectures=native
SystemCallFilter=@system-service
SystemCallFilter=~@privileged @resources
SystemCallErrorNumber=EPERM

@system-service is systemd’s curated allow-list for ordinary daemons; the ~ line subtracts two groups on top of it. SystemCallArchitectures=native blocks the 32-bit compat syscall table, a long-standing way around a filter covering only the native one. SystemCallErrorNumber=EPERM turns a blocked call into a returned error instead of an instant SIGSYS, which often lets a daemon log a real message on its way down. Take that line back out once tuning is finished — a kill is the safer default.

To see what you just subtracted, ask systemd rather than guessing:

systemd-analyze syscall-filter @resources | head -6
@resources
# Alter resource limits
    ioprio_set
    mbind
    migrate_pages
    move_pages

8. Catch the break and read the denial. Restart, and this time assume it fails.

sudo systemctl daemon-reload && sudo systemctl restart node_exporter.service
systemctl status node_exporter.service --no-pager | head -8
● node_exporter.service - Prometheus Node Exporter
     Loaded: loaded (/etc/systemd/system/node_exporter.service; enabled)
    Drop-In: /etc/systemd/system/node_exporter.service.d
             └─10-hardening.conf
     Active: failed (Result: signal)
    Process: 5182 ExecStart=/usr/local/bin/node_exporter (code=killed, signal=SYS)
   Main PID: 5182 (code=killed, signal=SYS)

signal=SYS is unambiguous: seccomp. The kernel logs which syscall, if auditing is active:

sudo journalctl -k -b --no-pager | grep -m1 'type=1326'
kernel: audit: type=1326 audit(1754136003.412:97): pid=5182 comm="node_exporter" exe="/usr/local/bin/node_exporter" sig=31 arch=c000003e syscall=302 compat=0 ip=0x47b1e6 code=0x0

Translate the number with auditd installed:

ausyscall 302
prlimit64

Without it, grep -w 302 /usr/include/asm/unistd_64.h gives the same answer. prlimit64 is in @resources, and it is what a Go daemon calls when it raises its own file-descriptor limit at startup. Stop subtracting that group — but note that SystemCallFilter= is a list-valued setting, so a new line appends rather than replaces. Reset it with an empty assignment first, or your relaxation will have no effect:

SystemCallFilter=
SystemCallFilter=@system-service
SystemCallFilter=~@privileged

Mixing positive and negative lines to re-admit one call is possible, but the ordering rules are easy to get wrong; dropping the whole group is the change you can still reason about in six months.

Table diagram mapping four sandbox denial signatures from the journal to the systemd directive that caused each one and the change that fixes it

Validate it works

A low score on a dead service is worse than a high score on a working one. Check all four of these.

Confirm what systemd actually loaded, rather than what you think you wrote:

systemctl show node_exporter.service -p ProtectSystem -p NoNewPrivileges -p RestrictAddressFamilies
ProtectSystem=strict
NoNewPrivileges=yes
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK

An empty value means the directive was ignored — usually a typo, or a systemd too old to know the name.

Exercise the daemon the way its clients do. For an exporter that means scraping it and counting metrics, not just seeing active:

curl -fsS http://127.0.0.1:9100/metrics | grep -c '^node_'
1247

A sharp drop in that count versus the pre-hardening value means a collector is silently failing — which is exactly what a missing AF_NETLINK or an over-tight ProcSubset= looks like.

Sweep the journal for denials after real traffic, not just after the restart:

sudo journalctl -u node_exporter.service --since "10 min ago" -p warning --no-pager
-- No entries --

Assert the score so it cannot regress. --threshold= exits non-zero when exposure is above the number you name, which makes it usable in a CI job or a config-management check:

systemd-analyze security --threshold=4 node_exporter.service >/dev/null; echo "exit=$?"
exit=0

Troubleshooting

status=226/NAMESPACE and the daemon logs nothing. systemd could not build the mount namespace, so the process never started. The usual cause is a path named in ReadWritePaths=, BindPaths= or ReadOnlyPaths= that does not exist — systemd will not create it for you. The other cause is an unprivileged container or LXC guest where the mount operations are not permitted at all; there, add PrivateMounts=no and accept that the filesystem directives are unavailable. The reason is usually one line above in journalctl -u <unit> -b.

Read-only file system from a daemon that used to work. ProtectSystem=strict is doing its job and the daemon writes somewhere you did not account for. Prefer StateDirectory=, LogsDirectory=, CacheDirectory= and RuntimeDirectory= over a raw ReadWritePaths= — they create the directory with the right owner and mode, and survive a DynamicUser= UID change.

address family not supported by protocol in the daemon’s own log. RestrictAddressFamilies= is missing a family. AF_NETLINK for anything reading kernel interface or routing state, AF_PACKET for raw capture, AF_UNIX for local sockets. The symptom points the wrong way: it reads as a connectivity failure long before anyone suspects the unit file.

The service starts but half its work silently stops. On a monitoring agent this is nearly always ProtectProc=invisible or ProcSubset=pid. Both are good directives for a web application and exactly wrong for anything whose job is reading /proc — ProcSubset=pid hides /proc/meminfo, /proc/stat and /proc/diskstats entirely. PrivateDevices=true causes the same shape of problem for a backup agent or SMART poller opening raw device nodes. Applying a directive the scoring tool rewards to a service that needs what it blocks is the most common self-inflicted outage here.

MemoryDenyWriteExecute=true and the process dies at startup. Any runtime that generates code at execution time needs a mapping that is writable and then executable: the JVM, Node/V8, LuaJIT, .NET tiered compilation, PyPy. Drop the directive for those workloads. The score cost is around 0.2 and the alternative is a service that does not run.

The drop-in appears to do nothing. Check three things, in order: the directory is <unit-name>.service.d including the .service suffix, the file ends in .conf, and the fragment contains a [Service] header. Then confirm with systemctl cat, which lists every file it merged. For a template unit, the directory is foo@.service.d for all instances or foo@bar.service.d for one.

When this is the wrong approach

If the daemon already runs in a container, the runtime supplies namespaces, a dropped capability set and a seccomp profile at its own layer. Hardening the unit that launches the runtime tightens the wrong process and can conflict with what the runtime expects to do. Harden the container’s profile instead. Podman’s Quadlet is the interesting middle case, since the unit and the container are described in one file — see Podman Quadlet systemd units for how the two layers divide.

These directives are also not mandatory access control. They restrict what a process can do; they say nothing about which specific files it may read within the paths it can still reach. If your requirement is per-path policy — a compliance control that names files, or confinement for a service whose whole job is filesystem access — AppArmor profiles or SELinux is the right tool, and the two compose fine with unit sandboxing.

Do not chase 0.0. Past a point the remaining exposure is PrivateNetwork= on a network service, RootDirectory= on a daemon that reads the host, and DynamicUser= on something that needs a stable UID. Those are not deficiencies, they are the service’s purpose. A unit in the low single digits, with a comment explaining the directives you refused and why, beats a lower number nobody can safely change.

And for a oneshot unit that runs two seconds a day, the exposure window barely exists — spend the effort on daemons that hold open sockets. The authoritative references are the systemd.exec man page and the systemd-analyze man page, which documents the scoring weights themselves.

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.