Running an internal API webhook or telemetry collector as root or an unconstrained shell user means a single remote code execution flaw gives attackers read access to SSH keys, nginx TLS private keys, and neighboring databases. Modern Linux distributions include rich kernel-level sandboxing right inside systemd unit files via cgroups, mount namespaces, and seccomp filters.
1. Auditing Current Exposure with systemd-analyze
Before editing any unit file, ask systemd to score your service's current exposure level from 0.0 (tightly isolated) to 10.0 (wide open):
systemd-analyze security my-app.service
2. Hardened Unit File Template for Web Backends
Even without Docker, a handful of declarative options lock the daemon to read-only system mounts and a single writable state directory:
[Unit]
Description=OrangeVPN Contact Relay Worker
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
DynamicUser=yes
StateDirectory=orangevpn-worker
WorkingDirectory=/opt/orangevpn-worker
ExecStart=/opt/orangevpn-worker/worker
# Privilege & Filesystem Isolation
NoNewPrivileges=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/var/lib/orangevpn-worker
CapabilityBoundingSet=
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
SystemCallFilter=@system-service
SystemCallErrorNumber=EPERM
Restart=on-failure
RestartSec=3s
[Install]
WantedBy=multi-user.target
3. Common Pitfalls When Rolling Out Strict Isolation
- Forgetting
StateDirectory=withDynamicUser=yes: Ephemeral UIDs should never write directly into arbitrary/var/wwwpaths owned bywww-data; let systemd create/var/lib/orangevpn-workerwith correct ownership automatically. - Blocking DNS or Unix sockets: Omitting
AF_UNIXfromRestrictAddressFamiliesbreaks local glibc NSS resolution (systemd-resolved) and local Redis/PostgreSQL sockets. - Binding privileged ports below 1024: If an API must bind port 80 or 443 directly without an Nginx reverse proxy in front, add
AmbientCapabilities=CAP_NET_BIND_SERVICEand list onlyCapabilityBoundingSet=CAP_NET_BIND_SERVICErather than granting full root privileges.
4. Directive-by-Directive Blast Radius Reference
| systemd Directive | Kernel Isolation Mechanism | What It Blocks |
|---|---|---|
ProtectSystem=strict |
Read-only bind mount namespace | Tampering with /etc, /usr, Nginx configs, or binaries |
ProtectHome=yes |
Empty tmpfs / inaccessible mount | Reading SSH keys or personal tokens under /home and /root |
NoNewPrivileges=yes |
Kernel PR_SET_NO_NEW_PRIVS |
Escalation via setuid binaries such as sudo or su |
MemoryMax=512M |
cgroup v2 memory accounting | Runaway memory leaks starving Nginx or database daemons |
Verify changes cleanly in staging via systemctl daemon-reload && systemctl restart my-app && systemd-analyze security my-app, watching journalctl -u my-app -f during health checks.