Most Linux services still run with far more privilege than they need, because a unit file that only says ExecStart= gives the process root, the whole filesystem, every capability and every system call. systemd ships a sandboxing toolkit that can confine almost any daemon through unit file directives alone, with no change to the application code. This guide explains how identity and privilege work for systemd services, which directives matter most, how to measure exposure with systemd-analyze security, how to hand secrets to a service without environment variables, and how to roll hardening out without breaking production. It is written for Linux administrators, platform engineers and security engineers who own server baselines.
This is an independent guide from NHI Mgmt Group, based on the systemd project's public documentation as of November 2026. It is not sponsored or reviewed by the systemd project. Product features change, so confirm settings against the systemd project's current documentation.
Key takeaways
- Every service is a non-human identity. The
User=,Group=and capability settings in a unit define what that workload can do if it is compromised, so treat each unit as an identity with an owner and a least-privilege profile. - Start with the cheap, high-value directives.
NoNewPrivileges=yes,ProtectSystem=strict,ProtectHome=yes,PrivateTmp=yes,PrivateDevices=yesand an empty or minimalCapabilityBoundingSet=remove most of the attack surface for typical daemons. - Measure before and after.
systemd-analyze securitygives each unit an exposure level from 0.0 to 10.0, and--offlinewith--thresholdlets you gate unit files in CI. - Use credentials, not environment variables, for secrets.
LoadCredential=andLoadCredentialEncrypted=place secrets in a per-unit directory that only the service user can read and that child processes do not inherit. - Drop-in files make hardening reversible. Apply directives through
/etc/systemd/system/<unit>.d/hardening.confso vendor units stay untouched and a rollback is one file removal andsystemctl daemon-reload.
How identity and access work in systemd
systemd (PID 1) starts each service from a unit file and decides, before execve(), which user the process runs as, which namespaces it gets, which capabilities it keeps and which system calls the kernel will allow. The security properties of the running daemon are therefore mostly set in the unit, not in the binary.
- Default identity is root: system services run as
rootunlessUser=is set. A service that only listens on a high port and reads a config file almost never needs root. - Static service users:
User=andGroup=select an account from the system user database. Names must be 1 to 31 characters. These accounts usually have anologinshell and no password; see the Linux Service Accounts and Keytab Management Guide for how to inventory them. - Dynamic users:
DynamicUser=yesallocates a UID and GID from the range 61184 to 65519 when the unit starts and releases it when it stops. It also impliesNoNewPrivileges=,RestrictSUIDSGID=,RemoveIPC=,ProtectSystem=strict,ProtectHome=read-onlyand a disconnectedPrivateTmp=. Persistent data goes inStateDirectory=, which systemd creates under/var/lib/privateand chowns to the dynamic user. - Capabilities: root's power is split into capabilities such as
CAP_NET_BIND_SERVICE,CAP_SYS_ADMINandCAP_DAC_OVERRIDE.CapabilityBoundingSet=limits what the process can ever hold;AmbientCapabilities=grants specific capabilities to a non-root user. See the Linux Capabilities Guide. - Namespaces and cgroups: the
Private*andProtect*directives build mount, network, IPC and user namespaces around the process, and resource-control directives use cgroup v2 and cgroup BPF. See the Linux Namespaces and cgroups Security Guide.
Admin roles and privileged access
Whoever can write unit files or call systemctl as root controls what runs as root at boot. That makes unit management a privileged function, and also a well-known persistence route: ATT&CK lists malicious unit creation as T1543.002 Systemd Service and timer abuse as T1053.006 Systemd Timers. The Persistence Techniques Guide covers the attacker side; this section covers who should hold the keys.
| Capability | Where it lives | Who should hold it | Control |
|---|---|---|---|
| Create or edit system units | /etc/systemd/system/, /run/systemd/system/ | Configuration management service account, break-glass admins | Root only; changes through Git and configuration management; file integrity monitoring on these paths |
| Vendor units | /usr/lib/systemd/system/ (or /lib/systemd/system/) | Package manager only | Do not edit; override with drop-ins so upgrades do not silently revert hardening |
| Start, stop, restart services | systemctl via D-Bus and polkit | Service owners for their own units | Narrow polkit rules or sudo entries per unit rather than blanket systemctl * |
| Per-user services and lingering | ~/.config/systemd/user/, loginctl enable-linger | Usually nobody on servers | Disable lingering for interactive users; review /var/lib/systemd/linger/ |
| Transient units | systemd-run | Admins for troubleshooting | Log and alert; transient units leave no file on disk |
A sudo rule such as systemctl restart * is effectively root, because systemctl edit or a crafted unit name can run arbitrary commands. Grant per-unit verbs only, and see the sudo and sudoers Security Guide and the Unix and Linux Privileged Access Guide.
The sandboxing directives that matter
The table groups the directives by what they protect. Values shown are the hardened setting most services tolerate; test each against your workload.
| Directive | Hardened value | Effect | Typical breakage |
|---|---|---|---|
NoNewPrivileges= | yes | Process and children cannot gain privileges through setuid binaries or file capabilities on execve() | Services that shell out to sudo, ping with setuid, or mail helpers |
ProtectSystem= | strict | Whole filesystem read-only except /dev, /proc, /sys and paths in ReadWritePaths= or StateDirectory=-family settings | Writes to undeclared log, cache or PID paths |
ProtectHome= | yes (or read-only, tmpfs) | Hides /home, /root and /run/user | Services that read user dotfiles or SSH keys |
PrivateTmp= | yes | Private /tmp and /var/tmp, removing shared-temp attacks between services | Two services that exchange files via /tmp |
PrivateDevices= | yes | Minimal /dev; removes CAP_MKNOD and CAP_SYS_RAWIO, blocks the @raw-io system calls, sets DevicePolicy=closed | Hardware agents, backup tools using raw disks |
PrivateNetwork= | yes for offline jobs | New network namespace with only lo | Anything that needs the network, including DNS |
CapabilityBoundingSet= | Empty, or only what is needed (for example CAP_NET_BIND_SERVICE) | Upper bound on capabilities the process can ever hold | Daemons that bind low ports or change UID themselves |
ProtectKernelTunables=, ProtectKernelModules=, ProtectKernelLogs=, ProtectControlGroups= | yes | Read-only /proc/sys and /sys, no module loading, no kernel log ring buffer, read-only cgroup tree | Monitoring agents and container runtimes |
ProtectClock=, ProtectHostname= | yes | Blocks changes to system clock and hostname | Time sync daemons |
ProtectProc=, ProcSubset= | invisible, pid | Hides other users' processes in /proc (needs User= or DynamicUser=); pid hides non-process files | ProcSubset=pid is often too strict for general programs |
RestrictAddressFamilies= | AF_UNIX AF_INET AF_INET6 | Blocks netlink, packet and other socket families | Tools that use netlink for routing or audit |
RestrictNamespaces= | yes | Service cannot create new namespaces, closing a common route to kernel bugs | Browsers, container tools, sandboxes of their own |
SystemCallFilter=, SystemCallArchitectures= | @system-service plus ~@privileged @resources; native | seccomp allow-list of system call groups; blocks non-native ABIs | Unusual system calls; set SystemCallErrorNumber=EPERM while tuning |
MemoryDenyWriteExecute=, LockPersonality=, RestrictRealtime=, RestrictSUIDSGID= | yes | No writable and executable memory, fixed execution domain, no realtime scheduling, no creation of setuid files | JIT runtimes (Java, Node.js, .NET) fail with MemoryDenyWriteExecute= |
UMask= | 0077 or 0027 | New files not world-readable (system default is 0022) | Files another group must read |
Caveats from the manual: several directives are silently skipped where the kernel feature is unavailable (for example RestrictRealtime= without seccomp, ProtectProc= without per-mount hidepid=, PrivateNetwork= without namespace support), and ProtectSystem= cannot guarantee protection in every case. A privileged process can undo path restrictions, so pair them with CapabilityBoundingSet=~CAP_SYS_ADMIN and SystemCallFilter=~@mount. Treat sandboxing as defence in depth, not as a replacement for patching.
Network and resource limits
- IPAddressDeny= and IPAddressAllow=: per-unit IP filtering through cgroup BPF. An address matching the allow list is allowed, otherwise a deny match blocks it, otherwise it is allowed.
IPAddressDeny=anywith a short allow list gives a service its own egress firewall. - SocketBindAllow= and SocketBindDeny=: limit which ports the service may
bind(), up to 128 entries each; changing network namespace does not bypass them. - RestrictNetworkInterfaces=: allow or deny specific interfaces;
lomust be listed explicitly. - TasksMax=, MemoryMax=, CPUQuota=: contain fork bombs and runaway memory. The manual recommends
MemoryHigh=as the main control andMemoryMax=as the last resort. - DevicePolicy= and DeviceAllow=:
closedallows only standard pseudo devices such as/dev/nulland/dev/urandom;strictallows only what you list.
These BPF-based controls need kernel and container-manager support for cgroup BPF and may have no effect without it, so confirm them on each platform.
Integrations, API tokens and service accounts
Services hold database passwords, API keys, TLS private keys and Kerberos keytabs. The common pattern of Environment=DB_PASSWORD=... or an EnvironmentFile= is best replaced with credentials: environment variables are inherited by every child process, appear in /proc/<pid>/environ to anyone who can read it, and unit files themselves are world-readable. Reading credentials from process memory and files is catalogued as T1003.007 Proc Filesystem and T1552.001 Credentials In Files.
| Method | How secrets are stored | Inherited by children | Use for |
|---|---|---|---|
Environment= in the unit | Plain text in a world-readable unit file | Yes | Non-secret configuration only |
EnvironmentFile= | Plain text file, permissions set by you | Yes | Legacy only; migrate away |
LoadCredential= | Copied at start from a file or AF_UNIX socket into $CREDENTIALS_DIRECTORY | No | Secrets already protected on disk or supplied by an agent |
LoadCredentialEncrypted= / SetCredentialEncrypted= | AES256-GCM ciphertext, key from TPM2, /var/lib/systemd/credential.secret or both | No | Secrets at rest on the host, bound to that machine |
- How credentials behave: for system services the directory is
/run/credentials/<unit>; reference it as%dor$CREDENTIALS_DIRECTORYrather than hard-coding the path. Access is limited to the service user, data is immutable while the service runs, it is kept in non-swappable memory where possible, it is released when the unit stops, and there is a combined 1 MB limit per service. - Encrypting:
systemd-creds encrypt --name=dbpass plaintext.txt dbpass.credproduces a file forLoadCredentialEncrypted=;-pprints aSetCredentialEncrypted=line to embed in the unit. With a TPM2 and persistent/var, the default binds the credential to that hardware and installation, so a copied disk image cannot decrypt it. - Where the secret comes from: for rotation, have a secrets manager agent write to a socket or file that
LoadCredential=reads, then restart the unit. See the Secrets Management Guide. - Ownership: record each unit's service user, the credentials it loads, the owner and the rotation date in your NHI inventory. See the Service Account Security Guide.
Logging and detection
Hardening reduces impact; detection catches the attacker who adds a new unit or tampers with an existing one.
| Signal | Source | Why it matters |
|---|---|---|
New or changed files in /etc/systemd/system/, /run/systemd/system/, /usr/lib/systemd/system/, user unit directories | auditd watch rules (-w /etc/systemd/system -p wa), file integrity monitoring | T1543.002 persistence; drop-ins can silently remove hardening |
.timer units created outside configuration management | Same watches plus systemctl list-timers --all baselines | T1053.006 scheduled execution |
systemd-run and systemctl daemon-reload by interactive users | auditd execve rules, shell history, PAM session logs | Transient units leave no file to find later |
Service crashes after hardening (status=31/SYS, EPERM, Read-only file system) | journalctl -u <unit>, kernel audit log for seccomp (type SECCOMP) | Distinguishes a missing permission from an exploit attempt |
| Exposure regressions | Scheduled systemd-analyze security output shipped to your SIEM | Package upgrades and new drop-ins can raise exposure |
| Lingering enabled for a user | Files in /var/lib/systemd/linger/ | User services that survive logout on a server |
For the auditd side see the Linux Logging and auditd for Defenders Guide, and for response the Linux Detection and Response Guide.
Metrics that show it is working
- Exposure distribution: median and worst
systemd-analyze securityexposure across long-running services, tracked per release. - Root services: percentage of long-running services with no
User=orDynamicUser=. - Capability coverage: percentage of units with an explicit
CapabilityBoundingSet=andNoNewPrivileges=yes. - Secrets in environment: count of units using
Environment=orEnvironmentFile=for secrets (target zero). - Unmanaged unit changes: unit file changes not traced to a configuration management commit (target zero).
Hardening baseline
A drop-in that most network daemons tolerate, applied with systemctl edit <unit> or written to /etc/systemd/system/<unit>.d/10-hardening.conf:
[Service]
User=svc-example
NoNewPrivileges=yes
ProtectSystem=strict
ReadWritePaths=/var/lib/example
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectKernelLogs=yes
ProtectControlGroups=yes
ProtectClock=yes
ProtectHostname=yes
ProtectProc=invisible
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
LockPersonality=yes
CapabilityBoundingSet=
SystemCallArchitectures=native
SystemCallFilter=@system-service
SystemCallFilter=~@privileged @resources
UMask=0027
LoadCredential=db.pass:/etc/example/creds/db.pass
Rollout in phases
- Inventory and score: run
systemd-analyze securitywith no arguments on representative hosts. Rank services by exposure and by how reachable they are (network listeners first). - Pick the identity: move each service off root to a dedicated static user or
DynamicUser=yes. Static users suit services that share files with other components; dynamic users suit self-contained daemons with aStateDirectory=. - Apply tier 1 in a test ring:
NoNewPrivileges,ProtectSystem=strictwith explicitReadWritePaths=,ProtectHome,PrivateTmp,PrivateDevices, the kernelProtect*set. Run functional tests and watch the journal. - Apply tier 2: capability bounding, address families, namespaces and the system call filter. Use
SystemCallErrorNumber=EPERMso blocked calls fail rather than kill the process, read the audit log, then decide whether to allow the call or keep it blocked. - Move secrets to credentials: replace environment secrets with
LoadCredential=or encrypted credentials and adjust the application to read$CREDENTIALS_DIRECTORY. - Gate in CI: run
systemd-analyze verifyandsystemd-analyze security --offline=yes --threshold=<n>against unit files in the repository; a--security-policy=JSON file can reweight or disable checks to match your standard. - Roll out by ring and keep rollback simple: pilot, then 10 per cent, then all. Rollback is removing the drop-in and running
systemctl daemon-reloadandsystemctl restart <unit>; keep the previous drop-in in Git.
Choosing the right strictness
- Internet-facing daemons and parsers: go to tier 2 in full; these are where exploits land.
- Agents that legitimately need privilege (EDR, backup, monitoring): you will not reach a low score. Apply what does not break them, document the exceptions and compensate with monitoring.
- JIT runtimes: skip
MemoryDenyWriteExecute=but keep the rest. - Containers: container runtimes provide their own namespaces and seccomp profiles; systemd hardening applies to the runtime and host services, not to processes inside containers. See the Container Security Guide.
- Small estates: start with the baseline drop-in on the five most exposed services. Large estates: ship drop-ins through configuration management with a per-service exception register and CI gating.
Common misconfigurations
- Editing vendor units in place: changes under
/usr/lib/systemd/system/are overwritten at the next package update, silently reverting hardening. Use drop-ins. - Hardening while still running as root:
ProtectProc=does not affect root, and a root process withCAP_SYS_ADMINcan undo mount restrictions. TheUser=change is the foundation. - Broad ReadWritePaths:
ReadWritePaths=/varor/etccancels most of the value ofProtectSystem=strict. List exact directories, or useStateDirectory=,CacheDirectory=andLogsDirectory=. - Secrets in Environment= or world-readable EnvironmentFile=: the most common finding, and the one that turns a read-only bug into credential theft.
- Trusting the score blindly: the exposure level only measures sandboxing systemd itself applies; a service that drops privileges internally can score badly but be fine, and vice versa. Read the per-setting output.
- Blanket systemctl sudo rules: letting operators run any
systemctlverb on any unit as root hands them a root shell.
Framework mapping
| Framework | Reference | How systemd hardening supports it |
|---|---|---|
| NIST SP 800-53 Rev. 5 | AC-6 Least Privilege; CM-7 Least Functionality; SC-39 Process Isolation; CM-6 Configuration Settings | Non-root users, capability bounding, namespaces and system call filters; settings held as code |
| NIST SP 800-53 Rev. 5 | IA-5 Authenticator Management; SC-28 Protection of Information at Rest | Encrypted, host-bound credentials instead of plain-text secrets |
| NIST CSF 2.0 | PR.PS-01; PR.AA-05; DE.CM-09 | Configuration management, least-privilege access, monitoring of runtime environments |
| CIS Controls v8.1 | Control 4 Secure Configuration of Enterprise Assets and Software | Hardened service configuration as part of the server baseline |
| ISO/IEC 27001:2022 Annex A | A.8.2 Privileged access rights; A.8.9 Configuration management | Who may change units; baseline drop-ins under change control |
| MITRE ATT&CK | T1543.002, T1053.006, T1068, T1003.007, T1552.001 | Detection of unit tampering; sandboxing limits privilege escalation and credential reads after compromise |
Practitioner checklist
- Run
systemd-analyze securityon each server build and record the exposure of every long-running service. - Give every service a non-root identity: a dedicated static user with a
nologinshell orDynamicUser=yes. - Apply the baseline drop-in to network-facing services first, through configuration management, never by editing vendor units.
- Set an explicit
CapabilityBoundingSet=andNoNewPrivileges=yeson every unit that does not need to escalate. - Replace
Environment=andEnvironmentFile=secrets withLoadCredential=or encrypted credentials. - Gate unit files in CI with
systemd-analyze verifyand an offline security threshold. - Watch unit directories and timers with auditd or file integrity monitoring and alert on changes outside the pipeline.
- Restrict who can create units and run
systemctl; replace blanket sudo rules with per-unit verbs. - Keep an exception register for agents that cannot be sandboxed, with an owner and review date.
Standards and references
- systemd: systemd.exec, execution environment configuration
- systemd: systemd.resource-control, resource control unit settings
- systemd: systemd-analyze, analyse and debug the system manager
- systemd: System and Service Credentials
- NIST: SP 800-53 Rev. 5
- NIST: Cybersecurity Framework 2.0
- MITRE ATT&CK: Create or Modify System Process: Systemd Service
- MITRE ATT&CK: Scheduled Task/Job: Systemd Timers
Related NHI Mgmt Group resources: Linux Server Hardening Guide · Linux Capabilities Guide · Persistence Techniques Guide · Service Account Security Guide · Secrets Management Guide