December 1, 2026

systemd service hardening is the difference between “my service got compromised” and “the attacker hit a wall.” Every directive here has a specific threat model. This is not theoretical – these are configurations running on production systems facing real attacks.

The Hardening Philosophy

Default deny, explicit allow. Every capability, every filesystem access, every network port must be justified.

Defense in depth. No single directive stops all attacks. Layer them.

Test before deploying. A hardened service that does not start is a denial of service.

The Hardening Template

# /etc/systemd/system/myapp.service
[Unit]
Description=My Hardened Application
Documentation=https://docs.example.com/hardening
After=network-online.target
Wants=network-online.target

[Service]
# ============ EXECUTION ============
Type=notify
ExecStart=/opt/myapp/bin/myapp
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5s
StartLimitIntervalSec=60
StartLimitBurst=3

# ============ PRIVILEGE REDUCTION ============
# Run as non-root user (MANDATORY)
User=myapp
Group=myapp
DynamicUser=yes
# DynamicUser=yes creates transient user/group, no /etc/passwd entry needed

# No new privileges - prevents setuid/setgid escalation
NoNewPrivileges=yes

# Capability bounding set - start with NONE
CapabilityBoundingSet=
# Add only what you NEED:
# CAP_NET_BIND_SERVICE - bind to ports < 1024
# CAP_DAC_OVERRIDE - bypass file permissions (avoid if possible)
# CAP_CHOWN - change file ownership (avoid)
# Example for web server on port 80:
# CapabilityBoundingSet=CAP_NET_BIND_SERVICE

# ============ FILESYSTEM ISOLATION ============
# Mount namespace isolation
PrivateTmp=yes
# Creates private /tmp and /var/tmp per service

PrivateDevices=yes
# No access to /dev/sda, /dev/mem, etc.

ProtectSystem=strict
# /usr, /boot, /etc read-only
# Use ReadWritePaths for exceptions

ProtectHome=yes
# /home, /root, /run/user inaccessible

ProtectKernelTunables=yes
# /proc/sys, /sys/kernel, /sys/firmware read-only

ProtectKernelModules=yes
# Module loading denied

ProtectKernelLogs=yes
# Kernel log (dmesg) access denied

ProtectControlGroups=yes
# cgroup filesystem read-only

ProtectProc=invisible
# /proc/ invisible
# Options: no|invisible|default

ProtectClock=yes
# clock_settime(), adjtimex() denied

RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
# Only allow needed socket families
# Remove AF_INET6 if IPv6 not needed
# Remove AF_INET if no network needed

RestrictNamespaces=yes
# unshare(), clone(CLONE_NEW*) denied
# Breaks: containers, some sandboxing

RestrictRealtime=yes
# Realtime scheduling (SCHED_FIFO/RR) denied

RestrictSUIDSGID=yes
# setuid/setgid programs denied

LockPersonality=yes
# personality(2) syscall denied

MemoryDenyWriteExecute=yes
# Writable + executable memory denied
# Breaks: JIT compilers (V8, JVM, PyPy)
# If needed: MemoryDenyWriteExecute=no

# ============ FILESYSTEM ACCESS CONTROL ============
# Read-only root filesystem
RootDirectory=/opt/myapp
# Or use: RootImage=/opt/myapp.img (loopback mount)

# Explicit read-only paths (default with ProtectSystem=strict)
ReadOnlyPaths=/etc /usr /boot

# Explicit read-write paths (MINIMIZE THESE)
ReadWritePaths=/var/lib/myapp /var/log/myapp /run/myapp

# Bind mounts for specific directories
BindPaths=/etc/myapp:/etc/myapp:ro
BindPaths=/var/lib/myapp:/var/lib/myapp

# Temporary filesystem for runtime data
RuntimeDirectory=myapp
RuntimeDirectoryMode=0750
# Creates /run/myapp owned by service user

StateDirectory=myapp
StateDirectoryMode=0750
# Creates /var/lib/myapp owned by service user

CacheDirectory=myapp
CacheDirectoryMode=0750
# Creates /var/cache/myapp owned by service user

LogsDirectory=myapp
LogsDirectoryMode=0750
# Creates /var/log/myapp owned by service user

ConfigurationDirectory=myapp
ConfigurationDirectoryMode=0750
# Creates /etc/myapp owned by service user

# ============ NETWORK ISOLATION ============
# Private network namespace (no host network access)
# PrivateNetwork=yes
# BREAKS: Most network services - use IPAddressAllow/Deny instead

# Restrict IP access (alternative to PrivateNetwork)
IPAddressDeny=any
IPAddressAllow=10.0.0.0/8 192.168.0.0/16
# Only allow specific subnets

# Or restrict by port
# IPAddressAllow=10.0.0.0/8:80,443

# ============ RESOURCE LIMITS ============
# CPU
CPUQuota=200%
CPUWeight=100
# CPUQuota=200% = 2 CPU cores max
# CPUWeight=100 = default priority (1-10000)

# Memory
MemoryLimit=512M
MemorySwapMax=512M
MemoryHigh=400M
# MemoryLimit = hard limit (OOM kill)
# MemoryHigh = soft limit (throttle)
# MemorySwapMax = swap limit

# I/O
IOWeight=100
IOReadBandwidthMax=/dev/nvme0n1 100M
IOWriteBandwidthMax=/dev/nvme0n1 50M
# Per-device bandwidth limits

# Tasks
TasksMax=1000
# Max threads/processes (prevents fork bombs)

# File descriptors
LimitNOFILE=65535
# Open file limit

# ============ LOGGING ============
StandardOutput=journal
StandardError=journal
SyslogIdentifier=myapp
LogLevelMax=info
LogRateLimitIntervalSec=30s
LogRateLimitBurst=1000

# ============ SECURITY HARDENING (Advanced) ============
# Seccomp syscall filter
SystemCallFilter=@system-service
SystemCallErrorNumber=EPERM
# @system-service = safe default set
# Add: SystemCallFilter=@system-service open read write close
# Remove: SystemCallFilter=~@clock @module @obsolete @debug

# AppArmor profile (if available)
# AppArmorProfile=myapp-profile

# SELinux context (if available)
# SELinuxContext=system_u:system_r:myapp_t:s0

# ============ SERVICE-SPECIFIC OVERRIDES ============
# For services needing JIT (Node.js, Java, PyPy):
# MemoryDenyWriteExecute=no

# For services binding to privileged ports (< 1024):
# CapabilityBoundingSet=CAP_NET_BIND_SERVICE
# AmbientCapabilities=CAP_NET_BIND_SERVICE

# For services needing raw sockets (ping, traceroute):
# CapabilityBoundingSet=CAP_NET_RAW
# AmbientCapabilities=CAP_NET_RAW

# For services needing filesystem ACLs:
# CapabilityBoundingSet=CAP_DAC_OVERRIDE

# For services needing to change file ownership:
# CapabilityBoundingSet=CAP_CHOWN

[Install]
WantedBy=multi-user.target

Directive Deep Dive

DynamicUser=yes (Game Changer)

DynamicUser=yes
User=myapp

What it does:

  • Creates user/group at service start
  • Removes at service stop
  • No /etc/passwd entry
  • Home directory: /var/lib/myapp (via StateDirectory)
  • UID/GID allocated from 61184-65519 range

Benefits:

  • No persistent attack surface
  • Automatic cleanup
  • Works with RootDirectory/RootImage

Caveats:

  • Cannot use with User= numeric UID
  • Files created persist but owned by numeric UID
  • Logs show numeric UID, not name

ProtectSystem=strict + ReadWritePaths

ProtectSystem=strict
ReadWritePaths=/var/lib/myapp /var/log/myapp /run/myapp

Levels:

  • no - No protection (default)
  • full - /usr, /boot, /etc read-only
  • strict - Full + /etc read-only

Always pair with ReadWritePaths. Services need somewhere to write.

PrivateTmp=yes (Essential)

PrivateTmp=yes

What it does: Mount namespace with private /tmp, /var/tmp.

Attack prevented: Symlink attacks in /tmp, data leakage between services.

Cost: Negligible. Always enable.

CapabilityBoundingSet= (Start Empty)

CapabilityBoundingSet=

Default: All capabilities allowed (except those dropped by kernel).

Strategy: Start empty, add only what breaks.

Common needs:

Capability Use Case
CAP_NET_BIND_SERVICE Port < 1024
CAP_NET_RAW Raw sockets (ping)
CAP_DAC_OVERRIDE Bypass file perms
CAP_CHOWN Change ownership
CAP_SYS_RESOURCE Resource limits
CAP_SYS_NICE Nice priority
CAP_SYS_ADMIN AVOID - near root

SystemCallFilter= (Seccomp)

SystemCallFilter=@system-service
SystemCallErrorNumber=EPERM

Profiles:

  • @system-service - Network services (recommended start)
  • @default - Minimal
  • @file-system - File operations
  • @network-io - Network I/O
  • @clock - Time operations
  • @module - Kernel modules
  • @obsolete - Deprecated syscalls
  • @debug - Debugging
  • @privileged - Privileged operations

Custom example:

SystemCallFilter=@system-service ~@clock @module @obsolete @debug @privileged
# Allow @system-service, DENY clock, module, obsolete, debug, privileged

Testing:

# Dry-run mode (logs violations but allows)
SystemCallFilter=@system-service
SystemCallErrorNumber=EPERM
SystemCallLog=yes

# Check logs
journalctl -u myapp -f | grep SECCOMP

IPAddressAllow/Deny (Network Policy)

IPAddressDeny=any
IPAddressAllow=10.0.0.0/8 192.168.1.0/24

Alternatives to PrivateNetwork=yes (which breaks most services).

Port-specific:

IPAddressAllow=10.0.0.0/8:80,443,5432
IPAddressAllow=192.168.1.100:22

Localhost only:

IPAddressAllow=localhost
IPAddressDeny=any

Resource Limits (DoS Prevention)

MemoryLimit=512M
MemoryHigh=400M
TasksMax=1000
LimitNOFILE=65535
CPUQuota=200%

MemoryLimit vs MemoryHigh:

  • MemoryHigh: Throttle, reclaim, slow down
  • MemoryLimit: OOM kill

Set both. MemoryHigh gives warning before kill.

Real-World Examples

PostgreSQL

[Service]
Type=notify
User=postgres
DynamicUser=no
CapabilityBoundingSet=CAP_DAC_OVERRIDE CAP_SETGID CAP_SETUID
ProtectSystem=strict
ReadWritePaths=/var/lib/postgresql /var/log/postgresql /run/postgresql /tmp
PrivateTmp=yes
ProtectHome=yes
NoNewPrivileges=yes
MemoryLimit=4G
MemoryHigh=3G
TasksMax=5000
LimitNOFILE=100000

Redis

[Service]
Type=notify
User=redis
DynamicUser=yes
CapabilityBoundingSet=
ProtectSystem=strict
ReadWritePaths=/var/lib/redis /var/log/redis /run/redis
PrivateTmp=yes
ProtectHome=yes
NoNewPrivileges=yes
PrivateNetwork=no
IPAddressAllow=10.0.0.0/8
IPAddressDeny=any
MemoryLimit=2G
MemoryHigh=1500M

Nginx

[Service]
Type=notify
User=nginx
DynamicUser=yes
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
AmbientCapabilities=CAP_NET_BIND_SERVICE
ProtectSystem=strict
ReadWritePaths=/var/lib/nginx /var/log/nginx /run/nginx /var/cache/nginx
PrivateTmp=yes
ProtectHome=yes
NoNewPrivileges=yes
PrivateNetwork=no
IPAddressAllow=0.0.0.0/0:80,443
IPAddressDeny=any
MemoryLimit=512M
MemoryHigh=400M

Node.js Application

[Service]
Type=notify
DynamicUser=yes
CapabilityBoundingSet=
ProtectSystem=strict
ReadWritePaths=/var/lib/myapp /var/log/myapp /run/myapp
PrivateTmp=yes
ProtectHome=yes
NoNewPrivileges=yes
MemoryDenyWriteExecute=no
PrivateNetwork=no
IPAddressAllow=10.0.0.0/8:3000
IPAddressDeny=any
MemoryLimit=1G
MemoryHigh=800M
CPUQuota=200%

Go Application

[Service]
Type=notify
DynamicUser=yes
CapabilityBoundingSet=
ProtectSystem=strict
ReadWritePaths=/var/lib/myapp /var/log/myapp /run/myapp
PrivateTmp=yes
ProtectHome=yes
NoNewPrivileges=yes
MemoryDenyWriteExecute=yes
PrivateNetwork=no
IPAddressAllow=10.0.0.0/8:8080
IPAddressDeny=any
MemoryLimit=256M
MemoryHigh=200M
CPUQuota=100%

Testing Your Hardening

1. Dry Run (Analyze)

# Analyze service without starting
systemd-analyze security myapp.service

# Output: exposure level (0-10), list of hardening features
# Target: exposure < 3

2. Verify Directives Applied

# Show effective configuration
systemctl show myapp.service | grep -E '(Capability|Protect|Private|Restrict|Memory|CPU|IPAddress|SystemCall)'

# Check specific directive
systemctl show myapp.service -p CapabilityBoundingSet
systemctl show myapp.service -p ProtectSystem

3. Test Startup

# Start and check status
systemctl start myapp
systemctl status myapp

# Check logs for violations
journalctl -u myapp -f

4. Penetration Test

# Try to escalate from service context
systemd-run --user --scope --pty /bin/bash
# Then try:
# cat /etc/shadow
# nsenter -t 1 -m
# mount -o remount,rw /
# iptables -L

Migration Strategy

Phase 1: Baseline (Week 1)

# Minimal hardening - almost never breaks
PrivateTmp=yes
ProtectHome=yes
ProtectSystem=full
NoNewPrivileges=yes
PrivateDevices=yes

Phase 2: Filesystem (Week 2)

ProtectSystem=strict
ReadWritePaths=/var/lib/myapp /var/log/myapp /run/myapp
RuntimeDirectory=myapp
StateDirectory=myapp
LogsDirectory=myapp

Phase 3: Capabilities (Week 3)

CapabilityBoundingSet=
# Add back one by one as needed
DynamicUser=yes

Phase 4: Network (Week 4)

IPAddressDeny=any
IPAddressAllow=

Phase 5: Syscalls (Week 5)

SystemCallFilter=@system-service
SystemCallErrorNumber=EPERM
SystemCallLog=yes
# Monitor logs, adjust

Phase 6: Resources (Week 6)

MemoryLimit=...
MemoryHigh=...
CPUQuota=...
TasksMax=...

Common Breakages and Fixes

Symptom Cause Fix
"Permission denied" on config ProtectSystem=strict Add ReadWritePaths=/etc/myapp
"Cannot bind to port 80" No NET_BIND_SERVICE CapabilityBoundingSet=CAP_NET_BIND_SERVICE
"JIT compilation failed" MemoryDenyWriteExecute=yes MemoryDenyWriteExecute=no
"Container won't start" RestrictNamespaces=yes RestrictNamespaces=no (or specific)
"DNS resolution fails" IPAddressDeny=any IPAddressAllow=10.0.0.0/8:53
"Fork bomb kills host" No TasksMax TasksMax=1000
"OOM killed unexpectedly" MemoryLimit too low Increase MemoryLimit, set MemoryHigh
"setuid binary fails" RestrictSUIDSGID=yes RestrictSUIDSGID=no (or fix binary)

Verification Checklist

Before deploying to production:

  • [ ] systemd-analyze security myapp.service shows exposure <= 2
  • [ ] Service starts: systemctl start myapp
  • [ ] Service restarts: systemctl restart myapp
  • [ ] Service survives reload: systemctl reload myapp
  • [ ] Logs show no SECCOMP violations (if SystemCallLog=yes)
  • [ ] Application functions correctly (run test suite)
  • [ ] Memory usage under MemoryHigh under load
  • [ ] CPU usage under CPUQuota under load
  • [ ] Network connectivity to allowed hosts works
  • [ ] Network connectivity to denied hosts fails
  • [ ] File writes to ReadWritePaths work
  • [ ] File writes to ReadOnlyPaths fail
  • [ ] No capabilities in CapabilityBoundingSet are unused
  • [ ] Documentation updated with hardening rationale

Summary

systemd hardening is not optional for production services. The baseline:

# MANDATORY for every service
PrivateTmp=yes
ProtectHome=yes
ProtectSystem=strict
NoNewPrivileges=yes
PrivateDevices=yes
CapabilityBoundingSet=
DynamicUser=yes
ReadWritePaths=/var/lib/myapp /var/log/myapp /run/myapp
MemoryLimit=512M
MemoryHigh=400M
TasksMax=1000

Then add service-specific requirements. Every directive you add reduces the attack surface. Every directive you skip is a risk you accept.

The goal is not "unhackable" - that does not exist. The goal is "when (not if) this service is compromised, the blast radius is contained to this service's data directory."

Leave a Reply

Your email address will not be published. Required fields are marked *