Service Hardening Guide
Properly configured services reduce attack surface and limit damage from compromises.
Systemd Security Features
Service Sandboxing
# Example: /etc/systemd/system/myapp.service.d/override.conf
[Service]
# User and group
User=myapp
Group=myapp
DynamicUser=true
# Filesystem access
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=/var/lib/myapp
# Network isolation
PrivateNetwork=false
RestrictAddressFamilies=AF_INET AF_INET6
# Process isolation
NoNewPrivileges=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
# Capabilities
CapabilityBoundingSet=
AmbientCapabilities=
# System call filtering
SystemCallFilter=@system-service
SystemCallArchitectures=nativeKey Directives Explained
| Directive | Effect |
|---|---|
| ProtectSystem=strict | Read-only /usr, /boot, /etc |
| ProtectHome=true | Inaccessible home directories |
| PrivateTmp=true | Private /tmp namespace |
| NoNewPrivileges=true | No privilege escalation |
| DynamicUser=true | Automatic unprivileged user |
Analyze Service Security
# Check security exposure
systemd-analyze security
# Detailed analysis of specific service
systemd-analyze security nginx.service
# Score interpretation:
# 0.0-2.0 = Excellent
# 2.0-4.0 = Good
# 4.0-6.0 = Needs improvement
# 6.0+ = ExposedCommon Service Hardening
Nginx Hardening
# /etc/systemd/system/nginx.service.d/security.conf
[Service]
ProtectSystem=full
ProtectHome=true
PrivateTmp=true
NoNewPrivileges=true
ProtectKernelTunables=true
ProtectKernelModules=true
CapabilityBoundingSet=CAP_NET_BIND_SERVICEDatabase Hardening (PostgreSQL)
# /etc/systemd/system/postgresql.service.d/security.conf
[Service]
ProtectSystem=full
ProtectHome=true
PrivateTmp=true
PrivateDevices=true
NoNewPrivileges=true
ProtectKernelTunables=true
ProtectControlGroups=true
ReadWritePaths=/var/lib/postgresql /var/run/postgresqlService Accounts
# Create service account
sudo useradd -r -s /usr/sbin/nologin -d /nonexistent myservice
# Verify no login shell
grep myservice /etc/passwd
# myservice:x:999:999::/nonexistent:/usr/sbin/nologin
# Set file ownership
sudo chown -R myservice:myservice /opt/myservice
sudo chmod 750 /opt/myserviceResource Limits
# /etc/systemd/system/myapp.service.d/limits.conf
[Service]
# CPU limits
CPUQuota=50%
# Memory limits
MemoryMax=512M
MemoryHigh=400M
# Process limits
LimitNPROC=64
TasksMax=100
# File descriptor limits
LimitNOFILE=1024
# Prevent OOM killer from killing
OOMScoreAdjust=-500Reload and Verify
# Reload systemd
sudo systemctl daemon-reload
# Restart service
sudo systemctl restart myapp
# Verify settings applied
systemctl show myapp --property=ProtectSystem,ProtectHome,NoNewPrivileges - services
- systemd
- hardening
- security
- sandboxing