Sandboxing a Service
By default a service runs as root, sees the whole filesystem, can write to /etc and /usr, can load kernel modules and can open any socket. If an attacker gets code execution in that app, they own the server. systemd can take most of that away with a few lines in the unit, using the same kernel features containers use (namespaces, capabilities, seccomp), without any container runtime.
The first five lines
These settings fit almost every service and break almost none:
[Service]
User=inventory # or DynamicUser=yes
NoNewPrivileges=yes # setuid binaries and file capabilities can't raise privileges
ProtectSystem=strict # the whole filesystem is read-only for the service...
ReadWritePaths=/var/lib/inventory # ...except what it really writes
ProtectHome=yes # /home, /root and /run/user look empty
PrivateTmp=yes # its own /tmp and /var/tmp, invisible to others| Setting | Effect |
|---|---|
User= / DynamicUser=yes |
run unprivileged; DynamicUser allocates a throwaway UID at start and implies several protections |
ProtectSystem= |
full: /usr, /boot, /etc read-only; strict: everything read-only except /dev, /proc, /sys and ReadWritePaths= |
StateDirectory=inventory |
creates /var/lib/inventory owned by the service user and makes it writable (also LogsDirectory=, CacheDirectory=, RuntimeDirectory=) |
PrivateDevices=yes |
a minimal /dev without disks or hardware |
ProtectKernelTunables=, ProtectKernelModules=, ProtectKernelLogs=, ProtectControlGroups=, ProtectClock= |
no writing to /proc/sys, loading modules, reading the kernel log, changing cgroups or the clock |
CapabilityBoundingSet= |
which root capabilities may ever be used; empty = none. AmbientCapabilities=CAP_NET_BIND_SERVICE lets a non-root service bind port 443 |
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX |
only these socket types |
SystemCallFilter=@system-service |
a seccomp allow list of the syscalls normal services need |
IPAddressAllow= / IPAddressDeny= |
per-service network allow lists |
Measuring exposure
systemd-analyze security scores a unit from 0 (locked down) to 10 (fully exposed) by checking about 80 settings. On a live server it reads the loaded units; --offline=true scores a unit file, which is what you want before deploying. A plain unit:
cat > web.service <<'EOF'
[Service]
ExecStart=/usr/bin/python3 -m http.server 8000
EOF
systemd-analyze security --offline=true ./web.service | grep -E 'User=|NoNewPrivileges=|ProtectSystem=|PrivateTmp=|Overall' | sed 's/ \+/ /g'✗ User=/DynamicUser= Service runs as root user 0.4
✗ NoNewPrivileges= Service processes may acquire new privileges 0.2
✗ ProtectSystem= Service has full access to the OS file hierarchy 0.2
✗ PrivateTmp= Service has access to other software's temporary files 0.2
→ Overall exposure level for web.service: 9.4 UNSAFE :-{
Now the same app with the protections above (it only serves files and needs no capabilities, no devices and no write access):
cat > web.service <<'EOF'
[Service]
ExecStart=/usr/bin/python3 -m http.server 8000
DynamicUser=yes
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectKernelLogs=yes
ProtectControlGroups=yes
ProtectClock=yes
ProtectHostname=yes
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
LockPersonality=yes
MemoryDenyWriteExecute=yes
RestrictAddressFamilies=AF_INET AF_INET6
CapabilityBoundingSet=
SystemCallArchitectures=native
SystemCallFilter=@system-service
SystemCallFilter=~@privileged @resources
UMask=0077
EOF
systemd-analyze verify ./web.service && echo "unit file: OK"
systemd-analyze security --offline=true ./web.service | grep -E '^✗|Overall' | sed 's/ \+/ /g'unit file: OK
✗ RootDirectory=/RootImage= Service runs within the host's root directory 0.1
✗ RestrictAddressFamilies=~AF_(INET|INET6) Service may allocate Internet sockets 0.3
✗ ProtectProc= Service has full access to process tree (/proc hidepid=) 0.2
✗ ProcSubset= Service has full access to non-process /proc files (/proc subset=) 0.1
✗ PrivateNetwork= Service has access to the host's network 0.5
✗ PrivateUsers= Service has access to other users 0.2
✗ DeviceAllow= Service has a device ACL with some special devices: char-rtc:r 0.1
✗ IPAddressDeny= Service does not define an IP address allow list 0.2
→ Overall exposure level for web.service: 1.4 OK :-)
From 9.4 to 1.4. Some of the remaining ✗ lines could still be added (ProtectProc=invisible, ProcSubset=pid, PrivateUsers=yes, an IPAddressAllow= list); others would break the app (it serves HTTP, so PrivateNetwork= stays off). Don't chase a score of 0; chase "nothing the app doesn't need".
A gate in CI
--threshold= makes the command fail when the exposure is above a limit (on a 0–100 scale, so 50 means 5.0). That turns the score into a check you can run on every unit file in a repository:
printf '[Service]\nExecStart=/usr/bin/python3 -m http.server 8000\n' > plain.service
printf '[Service]\nExecStart=/usr/bin/python3 -m http.server 8000\nDynamicUser=yes\nProtectSystem=strict\nPrivateTmp=yes\nNoNewPrivileges=yes\nCapabilityBoundingSet=\nPrivateDevices=yes\nProtectKernelTunables=yes\nProtectKernelModules=yes\nProtectControlGroups=yes\nRestrictNamespaces=yes\nSystemCallFilter=@system-service\n' > better.service
for u in plain.service better.service; do
if systemd-analyze security --offline=true --threshold=60 "./$u" > /dev/null; then echo "PASS $u"; else echo "FAIL $u"; fi
systemd-analyze security --offline=true "./$u" | grep Overall
doneFAIL plain.service
→ Overall exposure level for plain.service: 9.4 UNSAFE :-{
PASS better.service
→ Overall exposure level for better.service: 2.8 OK :-)
Rolling it out without breaking things
Sandboxing errors look like application bugs: Read-only file system, Permission denied, Operation not permitted, or a process killed with SIGSYS by the seccomp filter. Add settings in a drop-in (Drop-ins & Overrides), a few at a time, and watch the journal:
$ sudo systemctl edit inventory # add ProtectSystem=strict, ReadWritePaths=/var/lib/inventory
$ sudo systemctl restart inventory
$ journalctl -u inventory -n 3 --no-pager
Jan 15 11:02:17 web1 inventory[5120]: error: open /var/cache/inventory/index.db: read-only file system
Jan 15 11:02:17 web1 systemd[1]: inventory.service: Main process exited, code=exited, status=1/FAILURE
Jan 15 11:02:17 web1 systemd[1]: inventory.service: Failed with result 'exit-code'.The fix is CacheDirectory=inventory (or ReadWritePaths=/var/cache/inventory), not removing ProtectSystem=. For a seccomp kill, the journal shows code=killed, status=31/SYS; the audit log names the syscall.
Go further: seccomp, AppArmor, SELinux and Rootless Containers applies the same kernel features to containers.
Test yourself
What does ProtectSystem=strict do?
- Blocks network access
- Mounts the whole filesystem read-only for the service, except paths listed in ReadWritePaths= and the state/cache/log directories
- Runs the service as nobody
- Enables SELinux
A non-root service must listen on port 443. Which setting allows exactly that?
- User=root
- AmbientCapabilities=CAP_NET_BIND_SERVICE (with the same capability in the bounding set)
- PrivateNetwork=yes
- NoNewPrivileges=no
Why use systemd-analyze security --offline=true in CI?
- It is faster than verify
- It scores a unit file without a running systemd, and
--thresholdturns the score into a pass/fail check - It applies the hardening automatically
- It scans the app's code