Join our Newsletter — 33% off our NHI Course
Home› Guides› systemd Service Hardening Guide: Sandbox Every Service Unit…
Guide Endpoint Security

systemd Service Hardening Guide: Sandbox Every Service Unit Without Code Changes

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 8 November 2026 15 min read
On this page

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=yes and an empty or minimal CapabilityBoundingSet= remove most of the attack surface for typical daemons.
  • Measure before and after. systemd-analyze security gives each unit an exposure level from 0.0 to 10.0, and --offline with --threshold lets you gate unit files in CI.
  • Use credentials, not environment variables, for secrets. LoadCredential= and LoadCredentialEncrypted= 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.conf so vendor units stay untouched and a rollback is one file removal and systemctl 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 root unless User= is set. A service that only listens on a high port and reads a config file almost never needs root.
  • Static service users: User= and Group= select an account from the system user database. Names must be 1 to 31 characters. These accounts usually have a nologin shell and no password; see the Linux Service Accounts and Keytab Management Guide for how to inventory them.
  • Dynamic users: DynamicUser=yes allocates a UID and GID from the range 61184 to 65519 when the unit starts and releases it when it stops. It also implies NoNewPrivileges=, RestrictSUIDSGID=, RemoveIPC=, ProtectSystem=strict, ProtectHome=read-only and a disconnected PrivateTmp=. Persistent data goes in StateDirectory=, which systemd creates under /var/lib/private and chowns to the dynamic user.
  • Capabilities: root's power is split into capabilities such as CAP_NET_BIND_SERVICE, CAP_SYS_ADMIN and CAP_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* and Protect* 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.

CapabilityWhere it livesWho should hold itControl
Create or edit system units/etc/systemd/system/, /run/systemd/system/Configuration management service account, break-glass adminsRoot 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 onlyDo not edit; override with drop-ins so upgrades do not silently revert hardening
Start, stop, restart servicessystemctl via D-Bus and polkitService owners for their own unitsNarrow polkit rules or sudo entries per unit rather than blanket systemctl *
Per-user services and lingering~/.config/systemd/user/, loginctl enable-lingerUsually nobody on serversDisable lingering for interactive users; review /var/lib/systemd/linger/
Transient unitssystemd-runAdmins for troubleshootingLog 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.

DirectiveHardened valueEffectTypical breakage
NoNewPrivileges=yesProcess 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=strictWhole filesystem read-only except /dev, /proc, /sys and paths in ReadWritePaths= or StateDirectory=-family settingsWrites to undeclared log, cache or PID paths
ProtectHome=yes (or read-only, tmpfs)Hides /home, /root and /run/userServices that read user dotfiles or SSH keys
PrivateTmp=yesPrivate /tmp and /var/tmp, removing shared-temp attacks between servicesTwo services that exchange files via /tmp
PrivateDevices=yesMinimal /dev; removes CAP_MKNOD and CAP_SYS_RAWIO, blocks the @raw-io system calls, sets DevicePolicy=closedHardware agents, backup tools using raw disks
PrivateNetwork=yes for offline jobsNew network namespace with only loAnything 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 holdDaemons that bind low ports or change UID themselves
ProtectKernelTunables=, ProtectKernelModules=, ProtectKernelLogs=, ProtectControlGroups=yesRead-only /proc/sys and /sys, no module loading, no kernel log ring buffer, read-only cgroup treeMonitoring agents and container runtimes
ProtectClock=, ProtectHostname=yesBlocks changes to system clock and hostnameTime sync daemons
ProtectProc=, ProcSubset=invisible, pidHides other users' processes in /proc (needs User= or DynamicUser=); pid hides non-process filesProcSubset=pid is often too strict for general programs
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6Blocks netlink, packet and other socket familiesTools that use netlink for routing or audit
RestrictNamespaces=yesService cannot create new namespaces, closing a common route to kernel bugsBrowsers, container tools, sandboxes of their own
SystemCallFilter=, SystemCallArchitectures=@system-service plus ~@privileged @resources; nativeseccomp allow-list of system call groups; blocks non-native ABIsUnusual system calls; set SystemCallErrorNumber=EPERM while tuning
MemoryDenyWriteExecute=, LockPersonality=, RestrictRealtime=, RestrictSUIDSGID=yesNo writable and executable memory, fixed execution domain, no realtime scheduling, no creation of setuid filesJIT runtimes (Java, Node.js, .NET) fail with MemoryDenyWriteExecute=
UMask=0077 or 0027New 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=any with 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; lo must be listed explicitly.
  • TasksMax=, MemoryMax=, CPUQuota=: contain fork bombs and runaway memory. The manual recommends MemoryHigh= as the main control and MemoryMax= as the last resort.
  • DevicePolicy= and DeviceAllow=: closed allows only standard pseudo devices such as /dev/null and /dev/urandom; strict allows 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.

MethodHow secrets are storedInherited by childrenUse for
Environment= in the unitPlain text in a world-readable unit fileYesNon-secret configuration only
EnvironmentFile=Plain text file, permissions set by youYesLegacy only; migrate away
LoadCredential=Copied at start from a file or AF_UNIX socket into $CREDENTIALS_DIRECTORYNoSecrets already protected on disk or supplied by an agent
LoadCredentialEncrypted= / SetCredentialEncrypted=AES256-GCM ciphertext, key from TPM2, /var/lib/systemd/credential.secret or bothNoSecrets at rest on the host, bound to that machine
  • How credentials behave: for system services the directory is /run/credentials/<unit>; reference it as %d or $CREDENTIALS_DIRECTORY rather 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.cred produces a file for LoadCredentialEncrypted=; -p prints a SetCredentialEncrypted= 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.

SignalSourceWhy it matters
New or changed files in /etc/systemd/system/, /run/systemd/system/, /usr/lib/systemd/system/, user unit directoriesauditd watch rules (-w /etc/systemd/system -p wa), file integrity monitoringT1543.002 persistence; drop-ins can silently remove hardening
.timer units created outside configuration managementSame watches plus systemctl list-timers --all baselinesT1053.006 scheduled execution
systemd-run and systemctl daemon-reload by interactive usersauditd execve rules, shell history, PAM session logsTransient 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 regressionsScheduled systemd-analyze security output shipped to your SIEMPackage upgrades and new drop-ins can raise exposure
Lingering enabled for a userFiles 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 security exposure across long-running services, tracked per release.
  • Root services: percentage of long-running services with no User= or DynamicUser=.
  • Capability coverage: percentage of units with an explicit CapabilityBoundingSet= and NoNewPrivileges=yes.
  • Secrets in environment: count of units using Environment= or EnvironmentFile= 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

  1. Inventory and score: run systemd-analyze security with no arguments on representative hosts. Rank services by exposure and by how reachable they are (network listeners first).
  2. 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 a StateDirectory=.
  3. Apply tier 1 in a test ring: NoNewPrivileges, ProtectSystem=strict with explicit ReadWritePaths=, ProtectHome, PrivateTmp, PrivateDevices, the kernel Protect* set. Run functional tests and watch the journal.
  4. Apply tier 2: capability bounding, address families, namespaces and the system call filter. Use SystemCallErrorNumber=EPERM so blocked calls fail rather than kill the process, read the audit log, then decide whether to allow the call or keep it blocked.
  5. Move secrets to credentials: replace environment secrets with LoadCredential= or encrypted credentials and adjust the application to read $CREDENTIALS_DIRECTORY.
  6. Gate in CI: run systemd-analyze verify and systemd-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.
  7. 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-reload and systemctl 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 with CAP_SYS_ADMIN can undo mount restrictions. The User= change is the foundation.
  • Broad ReadWritePaths: ReadWritePaths=/var or /etc cancels most of the value of ProtectSystem=strict. List exact directories, or use StateDirectory=, CacheDirectory= and LogsDirectory=.
  • 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 systemctl verb on any unit as root hands them a root shell.

Framework mapping

FrameworkReferenceHow systemd hardening supports it
NIST SP 800-53 Rev. 5AC-6 Least Privilege; CM-7 Least Functionality; SC-39 Process Isolation; CM-6 Configuration SettingsNon-root users, capability bounding, namespaces and system call filters; settings held as code
NIST SP 800-53 Rev. 5IA-5 Authenticator Management; SC-28 Protection of Information at RestEncrypted, host-bound credentials instead of plain-text secrets
NIST CSF 2.0PR.PS-01; PR.AA-05; DE.CM-09Configuration management, least-privilege access, monitoring of runtime environments
CIS Controls v8.1Control 4 Secure Configuration of Enterprise Assets and SoftwareHardened service configuration as part of the server baseline
ISO/IEC 27001:2022 Annex AA.8.2 Privileged access rights; A.8.9 Configuration managementWho may change units; baseline drop-ins under change control
MITRE ATT&CKT1543.002, T1053.006, T1068, T1003.007, T1552.001Detection of unit tampering; sandboxing limits privilege escalation and credential reads after compromise

Practitioner checklist

  • Run systemd-analyze security on 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 nologin shell or DynamicUser=yes.
  • Apply the baseline drop-in to network-facing services first, through configuration management, never by editing vendor units.
  • Set an explicit CapabilityBoundingSet= and NoNewPrivileges=yes on every unit that does not need to escalate.
  • Replace Environment= and EnvironmentFile= secrets with LoadCredential= or encrypted credentials.
  • Gate unit files in CI with systemd-analyze verify and 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

Related NHI Mgmt Group resources: Linux Server Hardening Guide · Linux Capabilities Guide · Persistence Techniques Guide · Service Account Security Guide · Secrets Management Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 8 November 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.