Systemd unit files are the backbone of modern Linux service management, but poorly configured units create security vulnerabilities and reliability issues. From missing restart policies to running services as root without sandboxing, there are many common mistakes that a structured analysis can catch. This guide covers systemd unit file security hardening and automated linting.
Anatomy of a Service Unit File
A well-structured systemd service file has three sections:
[Unit]
Description=My Application Server
After=network.target postgresql.service
Wants=postgresql.service
[Service]
Type=simple
User=myapp
Group=myapp
ExecStart=/usr/local/bin/myapp --config /etc/myapp.conf
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
Each section serves a specific purpose: [Unit] for dependencies, [Service] for execution, and [Install] for enablement.
Security Hardening Directives
Systemd provides powerful sandboxing capabilities that most services underutilize:
[Service]
ProtectSystem=strict # Read-only filesystem (except /dev, /proc, /sys)
ProtectHome=true # No access to /home, /root, /run/user
PrivateTmp=true # Isolated /tmp namespace
NoNewPrivileges=true # Cannot gain new privileges
PrivateDevices=true # No access to physical devices
ProtectKernelModules=true # Cannot load kernel modules
ProtectKernelTunables=true # Cannot modify sysctl
RestrictSUIDSGID=true # Cannot create SUID/SGID files
MemoryDenyWriteExecute=true # No writable+executable memory
SystemCallFilter=@system-service # Whitelist system calls
Automated Unit File Analysis
Our unit file analyzer checks for security hardening, missing directives, and best practices:
pip install dargslan-systemd-unit
dargslan-unit lint myapp.service # Lint for issues
dargslan-unit security myapp.service # Security score (0-100%)
dargslan-unit report # Scan all unit files
Common Unit File Mistakes
- No Restart policy — Service crashes silently without recovery
- Running as root — Unnecessarily broad privileges
- Type=forking without PIDFile — Systemd cannot track the main process
- Missing After= dependencies — Service starts before dependencies are ready
- No security sandboxing — Service has full system access
Best Practices
- Always set
Restart=on-failurefor production services - Use a dedicated user (
User=) instead of root - Enable at least ProtectSystem, ProtectHome, PrivateTmp, and NoNewPrivileges
- Use
systemd-analyze security myapp.serviceto check your score - Set resource limits with MemoryMax, CPUQuota, TasksMax
Download our free Systemd Unit File Cheat Sheet for essential directives. For comprehensive Linux administration, explore our Linux & DevOps eBooks.