Skip to content

Lesson 5 of 9 · 28m

Service Hardening with systemd Sandboxing

Practical sandbox directives — users, filesystem restrictions, capabilities, syscalls, and namespaces — with a rollout strategy that does not break production.

systemd's hardening directives are the cheapest security boundary most operators never use. You do not need containers for every service; often the daemon needs a user, a writable state directory, one port, and nothing else. The goal is to make compromise boring.

Start with identity and filesystem scope

[Service]
User=metrics
Group=metrics
StateDirectory=metrics
RuntimeDirectory=metrics
UMask=0027
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
ReadWritePaths=/var/lib/metrics

ProtectSystem=strict mounts the filesystem read-only except explicitly writable paths. StateDirectory=metrics creates /var/lib/metrics with correct ownership. Be precise: if the service writes only there, do not make /var writable.

Reduce ambient authority

NoNewPrivileges=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictSUIDSGID=yes
LockPersonality=yes
RestrictRealtime=yes
SystemCallFilter=@system-service

NoNewPrivileges=yes prevents setuid escalation. SystemCallFilter=@system-service permits a broad server-oriented syscall set while blocking obviously irrelevant operations. Test the real workload; systemd versions differ, especially around io_uring and newer syscalls.

Capabilities deserve care. If a web service only needs port 443 without root:

User=wwwsvc
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE

AmbientCapabilities grants the capability to the non-root process; the bounding set prevents acquiring more. Do not hand out CAP_SYS_ADMIN as a convenience — in practice it is close to root.

Network and process visibility

PrivateUsers=yes
PrivateDevices=yes
ProtectProc=invisible
ProcSubset=pid
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6

PrivateUsers=yes creates a user namespace and can break file ownership assumptions. Address-family restrictions stop exploit paths that expect netlink, raw sockets, or other protocol families to exist.

Roll out like a security engineer

systemd-analyze security metrics-api.service scores exposure and suggests directives. Do not paste the entire output into production. Add a small batch, run integration tests, exercise failure paths, then repeat. Common breakage includes unexpected write paths, blocked io_uring, missing devices, and UID mapping surprises.

Field notes

  • DynamicUser=yes is excellent for stateless daemons; persistent files need StateDirectory because the UID is allocated dynamically.
  • ProtectSystem=full is weaker than strict; know which one you copied.
  • Sandboxing contains blast radius; it does not replace patching or authentication.
  • If the application is already in a container, still harden the container service itself.

Was this lesson helpful?

Sign in to rate