systemd Service Sandboxing
PrivateTmp, PrivateNetwork, ProtectSystem, NoNewPrivileges, and systemd-analyze security.
Overview
systemd provides a rich set of sandboxing directives that restrict what a service can access, without writing custom seccomp profiles or AppArmor rules. These directives use the same Linux kernel primitives as containers: namespaces (private views of kernel resources), seccomp (system-call filtering), cgroups (resource limits) and capabilities (root's power split into separate privileges). The difference is that you configure them declaratively in the unit file.
Effective sandboxing follows least privilege: each service should have exactly the access it needs and nothing more. A compromised web server that cannot access /home/, /root, or the network (if it only serves static files) has a severely limited blast radius.
Core Sandboxing Directives
The directives fall into three groups, and a hardened unit usually takes something from each.
Filesystem isolation
The first group decides which parts of the filesystem the service can see and change.
- PrivateTmp=yes gives the service its own private /tmp and /var/tmp. Other services cannot access its temp files.
- ProtectSystem=strict mounts the entire filesystem read-only for the service, except the API filesystems /dev, /proc and /sys. That includes /usr, /boot and /etc, so the service cannot modify system files.
- ProtectHome=yes makes /home, /root and /run/user inaccessible.
- ReadOnlyPaths= makes specific paths read-only.
- ReadWritePaths= grants write access back to specific paths, and is used together with ProtectSystem=strict.
Privilege isolation
The second group limits what the process may become, whatever files it can reach.
- NoNewPrivileges=yes means the service cannot gain new privileges through setuid binaries or file capabilities. This single directive blocks a large class of privilege escalation attacks.
- User= and Group= run the service as a non-root user.
- CapabilityBoundingSet= restricts which capabilities the service can ever hold.
Network isolation
The third group cuts the service off from the network.
- PrivateNetwork=yes gives the service its own network namespace with only a loopback interface. It cannot make outbound connections, and nothing outside can reach a port it listens on.
Key concepts
- PrivateTmp=yes
- ProtectSystem=strict
- ProtectHome=yes
- NoNewPrivileges=yes
- PrivateNetwork=yes
- systemd-analyze security
Interview questions
- How do you harden a systemd service unit for a web application? Show the unit file directives.
- What does systemd-analyze security show and how do you use it to improve a unit?
Sign up free to read the full topic
More Linux topics
Start free on Cariara · Coding problems · System design studio