systemd Unit Hardening Basics
Practical sandboxing directives for long-running services, with a verification loop.
Why bother
A service that only needs its own data directory should not be able to read /home. systemd gives you that restriction cheaply and reversibly.
Baseline directives
Start with the filesystem surface:
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=/var/lib/myapp
Add capability and namespace restrictions:
NoNewPrivileges=true
PrivateDevices=true
ProtectKernelTunables=true
ProtectKernelModules=true
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
Verify, do not assume
Apply one group at a time, then systemctl daemon-reload and restart. Watch journalctl -u myapp -f for permission errors. systemd-analyze security myapp scores the unit and names the remaining exposures.
Common breakages
Apps that write beside their binary need ReadWritePaths widened. Apps resolving DNS over unusual sockets trip RestrictAddressFamilies. Anything needing raw device access fights PrivateDevices.
Finish with a score target
Aim for the lowest exposure score the application tolerates, and record which directive forced each exception.