Linux and servers · Advanced · 16 min
Sandbox a systemd service with ProtectSystem, PrivateTmp and other security options
By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · systemd 259
You will take a working systemd service from an exposure score of 8.3 to below 1.0 with systemd-analyze security, adding sandbox options in four drop-in files and checking the app still serves its page.
On this page
A service account stops your app from running as root, but the process can still read most of the file system, see every other process, open raw sockets if it gains a capability, and call any of several hundred kernel system calls. If someone finds a bug in the app, all of that is theirs to use. systemd can take most of it away with lines in the unit file. Nothing changes in the app itself.
You will start from the myapp service built in Run your app as a systemd service. systemd-analyze security gives it an exposure score from 0 (locked down) to 10 (nothing restricted). You will add options in four groups, each in its own drop-in file, re-score after every group, and finish below 1.0 with the app still answering on port 8080. Ubuntu 26.04 ships systemd 259; the scores in this tutorial come from that version, and other versions weigh the checks slightly differently.
Step 1 · Score the service as it is
Look at the unit you are starting from:
cat /etc/systemd/system/myapp.serviceIt already has four protections: NoNewPrivileges, ProtectSystem=strict, ProtectHome and PrivateTmp. Now score it. --offline=true reads the unit files from disk instead of asking the running systemd, so you can score a change before you apply it:
systemd-analyze security --offline=true --threshold=83 myapp.service | tail -n 1--threshold takes a number from 0 to 100, ten times the score, and makes the command exit with an error when the unit scores worse than that. Here --threshold=83 means "fail if the score is above 8.3", so the command doubles as a check on the figure below; every re-score in this tutorial uses it the same way. The last line reads:
→ Overall exposure level for myapp.service: 8.3 EXPOSED :-(Without those four lines the same unit scores 9.0 UNSAFE, which is where most hand-written units begin. Now look at the full report, which has about 80 rows:
systemd-analyze security --offline=true myapp.service | head -n 12Each row is one check. ✓ means the unit sets that restriction; ✗ means it does not, and the EXPOSURE column says how much that gap adds to the score. The NAME column is the option to set, so ✗ PrivateDevices= points at the line to add. A name starting with ~, such as CapabilityBoundingSet=~CAP_SYS_ADMIN, means "remove this from the allowed set".
On a running server, systemd-analyze security with no unit name lists every loaded service and its score. It is a quick way to see which packaged services on the machine are the least confined:
systemd-analyze securityCheck it worked
Your score line says 8.3 EXPOSED, and the report shows ✓ NoNewPrivileges= and ✓ ProtectSystem=. If it says 9.0 or more, your unit is missing the four lines above; add them to /etc/systemd/system/myapp.service before you go on.
Step 2 · Lock down files, devices and /proc
Keep the new options out of the main unit file. A drop-in is a .conf file in /etc/systemd/system/myapp.service.d/; systemd merges every file there into the unit, in name order. One file per group means you can back out a group by deleting one file.
sudo mkdir -p /etc/systemd/system/myapp.service.d
sudo tee /etc/systemd/system/myapp.service.d/10-files.conf > /dev/null <<'CONF'
[Service]
StateDirectory=myapp
PrivateDevices=true
ProtectProc=invisible
ProcSubset=pid
UMask=0077
CONFWhat each line changes for the process:
StateDirectory=myappcreates/var/lib/myapp, owned by the service user, and makes it writable throughProtectSystem=strict. This is where an app should keep data it writes. For a folder that already exists elsewhere, such as/srv/myapp/uploads, useReadWritePaths=/srv/myapp/uploadsinstead. UnderProtectSystem=stricteverything not listed is read-only.PrivateDevices=truegives the service its own minimal/devwithnull,zero,randomand a few others, and no disks or hardware.ProtectProc=invisiblehides other users' processes in/proc, andProcSubset=pidhides the rest of/procthat is not about processes, such as kernel settings.UMask=0077makes new files readable by the service user only.
Before you score anything, make sure systemd can read what you wrote. systemd-analyze verify exits 0 even when it ignores a bad line, so check its output rather than its exit code:
if systemd-analyze verify myapp.service 2>&1 | grep .; then echo "Fix the lines above"; false; else echo "No problems found"; fiThen score it again:
systemd-analyze security --offline=true --threshold=75 myapp.service | tail -n 1Check it worked
The check prints No problems found and the score drops to 7.5. If you see a line such as Failed to parse ProtectSystem=sometimes, ignoring: Invalid argument, systemd is skipping that option; correct the spelling and run the check again.
Step 3 · Keep the service away from the kernel
The next group stops the process changing kernel state, even if it later gains a capability. None of these options affect an ordinary web app, which never needs to load kernel modules or set the clock.
One line needs a decision first. PrivateUsers=true runs the service in its own user namespace where only root and the service user exist, so files owned by any other account look as if they belong to nobody. If your app needs to read files owned by another account, leave that line out of the block below.
sudo tee /etc/systemd/system/myapp.service.d/20-kernel.conf > /dev/null <<'CONF'
[Service]
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectKernelLogs=true
ProtectControlGroups=true
ProtectClock=true
ProtectHostname=true
RestrictNamespaces=true
LockPersonality=true
RestrictRealtime=true
RestrictSUIDSGID=true
RemoveIPC=true
PrivateUsers=true
CONFIn plain terms:
ProtectKernelTunables,ProtectKernelModules,ProtectKernelLogsandProtectControlGroupsmake/proc/sys,/sysand the cgroup tree read-only, block module loading, and deny the kernel log.ProtectClockandProtectHostnamestop the service changing the system clock or the hostname.RestrictNamespacesblocks creating new namespaces, a common first move in local privilege escalation exploits.LockPersonality,RestrictRealtimeandRestrictSUIDSGIDstop odd execution modes, real-time scheduling (which can starve the machine) and creating set-user-ID files.RemoveIPCdeletes shared memory and semaphores the user leaves behind when the service stops.PrivateUsers=truegives the service its own user namespace, as described above.
if systemd-analyze verify myapp.service 2>&1 | grep .; then echo "Fix the lines above"; false; else echo "No problems found"; fi
systemd-analyze security --offline=true --threshold=50 myapp.service | tail -n 1Check it worked
You see No problems found and the score is now 5.0 MEDIUM. In the full report, the ProtectKernel... rows and RestrictNamespaces= rows have turned to ✓.
Step 4 · Drop capabilities and limit the network
A process running as an ordinary user has no capabilities, but a bug or a set-user-ID helper could hand it some. An empty CapabilityBoundingSet= means none can ever be gained. This app only listens on 127.0.0.1:8080, so it needs IPv4 and IPv6 sockets, plus Unix sockets for local name lookups, and nothing else.
Check one thing before you copy the block. IPAddressDeny=any with IPAddressAllow=localhost drops every packet to or from an address other than 127.0.0.0/8 and ::1. That suits an app behind Nginx on the same server. If the app must reach a database on another host, or be reached directly from the internet, add those addresses to IPAddressAllow= or leave both lines out.
sudo tee /etc/systemd/system/myapp.service.d/30-caps-network.conf > /dev/null <<'CONF'
[Service]
CapabilityBoundingSet=
AmbientCapabilities=
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
IPAddressAllow=localhost
IPAddressDeny=any
CONFAn app that binds a port below 1024 itself, such as 80 or 443, needs CAP_NET_BIND_SERVICE. In that case write CapabilityBoundingSet=CAP_NET_BIND_SERVICE and AmbientCapabilities=CAP_NET_BIND_SERVICE instead of the empty lines.
if systemd-analyze verify myapp.service 2>&1 | grep .; then echo "Fix the lines above"; false; else echo "No problems found"; fi
systemd-analyze security --offline=true --threshold=27 myapp.service | tail -n 1Check it worked
The score is 2.7 OK. Every CapabilityBoundingSet=~CAP_... row in the report is now ✓.
Step 5 · Filter system calls
The last group uses seccomp to limit which kernel system calls the process can make. systemd ships named groups of calls; @system-service is the set a typical service needs. List what is in it:
systemd-analyze syscall-filter @system-service | head -n 20Allow that group, then take the privileged and resource-control calls back out of it. If your service runs on a runtime that compiles code to machine code as it runs, drop the MemoryDenyWriteExecute=true line from the block first: that includes Node.js, whose V8 engine is a JIT compiler, the Java virtual machine, .NET, LuaJIT and PHP with its JIT turned on. Such a service typically crashes at start-up with this option. Keep the rest of the group.
sudo tee /etc/systemd/system/myapp.service.d/40-syscalls.conf > /dev/null <<'CONF'
[Service]
SystemCallArchitectures=native
SystemCallFilter=@system-service
SystemCallFilter=~@privileged @resources
SystemCallErrorNumber=EPERM
MemoryDenyWriteExecute=true
CONFSystemCallArchitectures=nativeblocks calls made through another architecture's interface, such as 32-bit calls on a 64-bit kernel, which can get around a filter.SystemCallErrorNumber=EPERMmakes a blocked call fail with "Operation not permitted" instead of killing the process. The app logs a readable error and you can find the cause.MemoryDenyWriteExecute=truestops the process creating memory that is both writable and executable, a step many exploits rely on.
if systemd-analyze verify myapp.service 2>&1 | grep .; then echo "Fix the lines above"; false; else echo "No problems found"; fi
systemd-analyze security --offline=true --threshold=9 myapp.service | tail -n 1The score is now 0.9 SAFE. To keep it below 1.0, add a check like this to a deploy script or CI job. It fails, and stops the script, whenever a change pushes the score above 1.0:
if systemd-analyze security --offline=true --threshold=10 myapp.service > /dev/null; then echo "myapp scores 1.0 or lower"; else echo "Score is above 1.0"; false; fiIf several teams edit the unit and you only want CI to catch large regressions, a looser --threshold=30 (3.0) works the same way.
Check it worked
The score line ends 0.9 SAFE :-} and the threshold check prints myapp scores 1.0 or lower. List what is still open:
systemd-analyze security --offline=true myapp.service | grep '✗'About six rows remain, such as PrivateNetwork= and RestrictAddressFamilies=~AF_(INET|INET6). They stay open on purpose: a web server needs the network and Internet sockets.
Step 6 · Apply the sandbox and check the app still works
A lower score only matters if the app still runs. Load the drop-ins and restart the service:
sudo systemctl daemon-reload
sudo systemctl restart myapp
systemctl status myapp --no-pager
curl http://127.0.0.1:8080/The status shows Active: active (running) and lists the four files under Drop-In: /etc/systemd/system/myapp.service.d. curl prints <h1>It runs</h1>. Then score the running service, which should match the offline score:
systemd-analyze security myapp | tail -n 1Check the kernel is enforcing the sandbox on the live process:
grep -E '^(NoNewPrivs|Seccomp|CapBnd):' /proc/$(systemctl show -p MainPID --value myapp)/statusYou should see NoNewPrivs: 1, Seccomp: 2 (a filter is active) and CapBnd: 0000000000000000 (no capabilities left).
When the service fails
If the status shows failed or the service restarts in a loop, read the last start attempt:
journalctl -u myapp -b -n 30 --no-pagerLook for the status= value on the line that says the main process exited, and translate it:
systemd-analyze exit-status 226 228 238226/NAMESPACE: systemd could not build the file system view, most often because a path inReadWritePaths=does not exist. Create it, or prefix the path with-to make it optional.228/SECCOMP: the system call filter could not be installed.238/STATE_DIRECTORY:/var/lib/myappcould not be created or given to the service user.Read-only file systemorPermission deniedfrom the app itself: it writes somewhere outsideStateDirectoryorReadWritePaths. Add that path.Operation not permittedfrom the app: a blocked system call, thanks toSystemCallErrorNumber=EPERM. To find which call, addSystemCallLog=~@system-serviceto40-syscalls.conf, restart, and search the kernel log for seccomp audit records withjournalctl -k -b -g 'type=1326'. Each one is a line something likeaudit: type=1326 ... comm="python3" ... syscall=165 ... code=0x7ffc0000. The call appears as a number, not a name;ausyscall 165(from theauditdpackage) turns it into a name such asmount. Ifauditdis running, the records go to its log instead, andsudo ausearch -m SECCOMP -ishows them with names. Remove the log line once you have fixed the filter.
To find the group at fault quickly, move one drop-in file out of the folder, run sudo systemctl daemon-reload and restart. When the app works again, the last file you moved holds the option that broke it; put the file back and remove options from it one at a time.
Check it worked
curl returns <h1>It runs</h1>, systemctl status myapp shows the four drop-ins, and systemd-analyze security myapp scores below 1.0.
Next steps
- Give each of your services its own user, state and log folders managed by systemd: /tutorials/give-a-service-its-own-system-user-and-directories.
- Use the same drop-in method on services installed by packages: /tutorials/change-a-packaged-service-with-systemd-drop-ins.
- Cap how much memory and CPU the service can take: /tutorials/limit-a-service-cpu-and-memory-with-systemd.
Related tutorials
- Write safer Bash scripts with strict mode and trapsYou will build a small Bash release script that stops on the first error, says which line failed, survives file names with spaces and always removes its temporary files.
- Write least-privilege sudo rules with visudoYou will replace blanket sudo access with checked rule files in /etc/sudoers.d that let two operators restart one service and edit one file, give an automation account a password-free command list, and audit what every account can run.
- Upgrade a server from Ubuntu 24.04 LTS to 26.04 LTSYou will take a backed-up Ubuntu 24.04 server through do-release-upgrade to 26.04 LTS over SSH with a fallback login, then confirm services, repositories and language runtimes work on the new release.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials