Your Linux Services Have Too Much Access. Lock Them Down with systemd Sandboxing
Running a Linux service as a dedicated user is not enough to protect your server. Learn how to use systemd sandboxing to restrict filesystem access, remove unnecessary capabilities, isolate devices, and reduce the impact of a compromised application.
A Linux service does not need unrestricted access to the server simply because it needs to run continuously.
Yet many production services operate with more permissions than they actually require. An application may run under a dedicated user but still have broad filesystem access, unnecessary Linux capabilities, visibility into sensitive directories, or access to devices and kernel interfaces it never uses.
That creates an avoidable security risk. If an application is compromised, the permissions available to its process can influence how far an attacker can go.
Fortunately, Linux administrators already have a useful set of security controls available through systemd service sandboxing. Without introducing another security platform or moving the application into a container, systemd can restrict what a service can access, modify, and do.
In this guide, we'll examine how systemd sandboxing works, which directives matter most, and how to apply them to a practical web application service without breaking its normal operation.
What you'll learn
- Why running a service as a dedicated user is not enough
- How to assess a service using
systemd-analyze security - How to restrict filesystem access and writable directories
- How to remove unnecessary Linux capabilities
- How to isolate devices and sensitive kernel interfaces
- How to build, validate, and troubleshoot a hardened service unit
Why a dedicated service user is not enough
Running an application as a non-root user is an important security practice. If the application is compromised, the attacker does not automatically inherit root privileges.
However, a dedicated service account does not automatically provide filesystem isolation.
For example, a service running as webapp might still be able to:
- Read configuration files that are accessible to other users.
- Access application data belonging to other services if permissions allow it.
- Modify files and directories writable by its account.
- Inspect parts of the host's filesystem.
- Interact with devices or kernel interfaces that the application does not need.
The exact access depends on traditional Linux permissions, ACLs, capabilities, and other security mechanisms.
This is where systemd sandboxing becomes useful. It adds restrictions around the service process, independently of the application's normal user and group permissions.
Think of it as giving a service a smaller operating environment: it can access the resources it needs, but unnecessary parts of the host are hidden, read-only, or restricted.
1. Assess your service before changing it
Before modifying a unit file, understand its current security posture.
systemd includes a built-in command for this:
systemd-analyze security
To inspect a particular service:
systemd-analyze security nginx.service
Or use your own application service:
systemd-analyze security webapp.service
The command evaluates several systemd security and sandboxing settings and produces an estimated exposure level. A lower score generally indicates that more of the available restrictions are enabled.
However, this score needs context.
It is not a vulnerability scan, penetration test, or guarantee that a service is secure. It evaluates systemd's service-level security settings, not every protection implemented by the application, kernel, firewall, or other security layers.
Use it as a starting point. Review the individual recommendations and decide which restrictions make sense for the workload.
2. Restrict filesystem access
One of the most useful systemd directives is ProtectSystem=.
Consider this setting:
ProtectSystem=strict
It makes the filesystem hierarchy read-only from the service's perspective, with exceptions for certain API filesystem areas such as /dev, /proc, and /sys.
This is particularly useful for applications that should read their code and configuration but should not modify operating system files.
For example, a web application usually needs to read its application files from /opt/webapp, but it should not need to modify /usr, /etc, or other system directories.
Give the service only the writable directories it needs
Making the filesystem read-only is useful, but applications often need somewhere to store uploads, generated files, sessions, or application state.
There are two practical approaches.
Option A: Use systemd-managed directories
For persistent application state, use:
StateDirectory=webapp
systemd creates and manages the service's state directory under:
/var/lib/webapp
It also makes that directory available for writing to the service, subject to the configured ownership and permissions.
You can set its permissions explicitly:
StateDirectoryMode=0750
This is generally preferable to making broad parts of the filesystem writable.
Other useful directory directives include:
| Directive | Default location | Typical purpose |
|---|---|---|
StateDirectory= |
/var/lib/ |
Persistent application data |
CacheDirectory= |
/var/cache/ |
Regenerable cache |
LogsDirectory= |
/var/log/ |
Application-managed log files |
RuntimeDirectory= |
/run/ |
Temporary runtime data |
Option B: Explicitly allow writable paths
If your application already uses a specific directory, you can allow it through ReadWritePaths=:
ReadWritePaths=/var/lib/webapp/uploads
This is useful when the directory structure is already established.
Remember that ReadWritePaths= changes the service's filesystem view. It does not override normal Unix ownership, permissions, ACLs, or a read-only filesystem mount.
Protect users' home directories
Another useful setting is:
ProtectHome=true
This makes /home, /root, and /run/user inaccessible to the service.
A network-facing application should not normally need access to administrators' home directories or other users' private files.
Do not enable this blindly if the application depends on files stored under those paths. Move required application data to an appropriate service directory or explicitly design the required access.

3. Remove unnecessary privileges and capabilities
Linux capabilities divide traditional root privileges into smaller units. Instead of granting a process unrestricted root-level authority, the kernel can grant specific capabilities for specific operations.
For example:
CAP_NET_BIND_SERVICEallows binding to privileged network ports below 1024.CAP_NET_ADMINpermits certain network administration operations.CAP_SYS_ADMINcovers a broad range of privileged operations and is particularly powerful.
A typical Node.js application listening on port 3000 does not need any of these capabilities.
You can clear the service's capability bounding set with:
CapabilityBoundingSet=
This removes the capabilities from the service's bounding set, preventing it from gaining those capabilities through normal privilege mechanisms.
If a service genuinely requires a capability, allow only that specific capability rather than granting a broad set.
For example, a service that must bind directly to port 443 might require CAP_NET_BIND_SERVICE, depending on the deployment design. Using a reverse proxy on ports 80 and 443 and keeping the application on an unprivileged port is often a cleaner alternative.
Also consider:
NoNewPrivileges=true
This prevents the service and its child processes from gaining additional privileges through mechanisms such as setuid/setgid executables or file capabilities.
Another useful restriction is:
RestrictSUIDSGID=true
It prevents the service from creating or modifying files with setuid or setgid permission bits.
These settings are useful, but they can break applications that rely on privilege transitions. Test the service's actual execution path before deploying them.
For more detail, see the Linux capabilities(7) documentation.
4. Isolate devices and kernel interfaces
A normal web application generally has no reason to access physical devices, modify kernel parameters, or load kernel modules.
systemd provides several directives to reduce this exposure.
PrivateDevices=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
Here's what they do:
PrivateDevices=truegives the service a restricted device view instead of exposing the host's full device tree.ProtectKernelTunables=truerestricts access to kernel tunable interfaces.ProtectKernelModules=trueprevents the service from loading or unloading kernel modules.ProtectControlGroups=truerestricts modification of the host's control group hierarchy.
These are sensible candidates for many ordinary application services.
However, they are not universal defaults for every workload. Monitoring agents, hardware management tools, container runtimes, and infrastructure services may legitimately need some of these interfaces.
The objective is not to disable everything. It is to identify what the application needs and restrict the rest.
5. Restrict network address families
systemd can also limit which socket address families a service may use.
For a typical web application:
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
This allows:
AF_UNIXfor local Unix domain sockets.AF_INETfor IPv4.AF_INET6for IPv6.
It prevents the service from creating sockets using other address families unless they are explicitly permitted.
This is a useful restriction, but it is important to understand what it does not do.
RestrictAddressFamilies= does not restrict the service to particular destination IP addresses, ports, or domains. It is not a replacement for firewall rules or network-level access controls.
Some applications may need additional address families, such as AF_NETLINK. Review the application's requirements before applying this setting.
6. Build a practical hardened systemd service
Let's apply these controls to a simple Node.js application.
Assume the application:
- Runs as a dedicated
webappuser. - Is installed under
/opt/webapp. - Listens on port 3000.
- Stores persistent application data under
/var/lib/webapp. - Does not need root privileges or direct hardware access.
Create a dedicated system account if one does not already exist:
sudo useradd \
--system \
--home-dir /var/lib/webapp \
--shell /usr/sbin/nologin \
webapp
Make sure the application files are owned by an appropriate administrative account and readable by the service account. The service should not need write access to its own executable code.
Create the unit file:
sudo nano /etc/systemd/system/webapp.service
Use the following as a starting configuration:
[Unit]
Description=Web Application
After=network.target
[Service]
Type=simple
User=webapp
Group=webapp
WorkingDirectory=/opt/webapp
ExecStart=/usr/bin/node /opt/webapp/server.js
Restart=on-failure
RestartSec=5
# Application state
StateDirectory=webapp
StateDirectoryMode=0750
# Filesystem restrictions
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
# Device and kernel restrictions
PrivateDevices=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
# Privilege restrictions
NoNewPrivileges=true
CapabilityBoundingSet=
RestrictSUIDSGID=true
# Network socket restrictions
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
# Additional hardening
LockPersonality=true
RestrictRealtime=true
[Install]
WantedBy=multi-user.target
This configuration is intentionally focused on a typical application service. It does not attempt to enable every available systemd security directive.
A few details matter:
StateDirectory=webappcreates/var/lib/webappand makes it available to the service for persistent state.ProtectSystem=strictprevents the service from modifying the rest of the filesystem through its service-specific view.PrivateTmp=truegives the service private temporary directories. These remain writable even withProtectSystem=strict.CapabilityBoundingSet=clears the service's capability bounding set. This application does not need special capabilities to listen on port 3000.ProtectHome=trueassumes the application does not depend on files under users' home directories.
If the application needs uploads, cache files, or other writable locations, configure those deliberately using systemd-managed directories or narrowly scoped writable paths.
Also, the example assumes the application can run without special device access or additional network address families. Adapt the settings if your application has different requirements.
7. Validate the configuration and test the application
A hardened service that cannot start or process requests is not a successful deployment.
After saving the unit file, reload systemd:
sudo systemctl daemon-reload
Validate the unit file:
sudo systemd-analyze verify /etc/systemd/system/webapp.service
Enable and start the service:
sudo systemctl enable --now webapp.service
Check its status:
sudo systemctl status webapp.service
Review the logs:
sudo journalctl -u webapp.service -n 100 --no-pager
Test the application's actual health endpoint. For example, if it exposes /health:
curl -i http://127.0.0.1:3000/health
Finally, review the sandboxing assessment:
sudo systemd-analyze security webapp.service
Compare the result with the original assessment. More importantly, review which restrictions are enabled and whether the application continues to function correctly.

8. Troubleshoot problems caused by sandboxing
The most common mistake is enabling several restrictions at once and assuming that any resulting failure is an application bug.
When a service stops working after hardening, investigate the specific resource it can no longer access.
Start with its logs:
sudo journalctl -u webapp.service -b --no-pager
Check the service's state:
sudo systemctl status webapp.service
Common problems include:
| Symptom | Possible cause | What to check |
|---|---|---|
| Application cannot upload files | Writable directory is missing | StateDirectory= or ReadWritePaths= |
| Application cannot read a file | Directory is inaccessible | ProtectHome= and filesystem restrictions |
| Service cannot bind to a port | Privileged port or missing capability | Port number and capability requirements |
| Application cannot access a device | Restricted device namespace | PrivateDevices= |
| Network functionality breaks | Required address family is blocked | RestrictAddressFamilies= |
| Application cannot create temporary files | Temporary directory assumptions | PrivateTmp= and application configuration |
Avoid solving these problems by removing every security restriction.
Instead, identify the exact dependency and allow only the access required to support it. For example, if an application needs to write to /var/lib/webapp/uploads, make that directory writable rather than making /var/lib or the entire filesystem writable.
This approach keeps the security boundary narrow and makes future maintenance easier.
9. A practical systemd hardening checklist
Before considering a service hardened, review the following:
- [ ] The service runs under a dedicated non-root account.
- [ ] Application code and configuration are not writable by the service unnecessarily.
- [ ]
ProtectSystem=strictis enabled where compatible. - [ ] Persistent writable paths are explicitly defined.
- [ ]
ProtectHome=trueis enabled where compatible. - [ ]
PrivateTmp=trueis enabled where appropriate. - [ ] Unnecessary Linux capabilities are removed.
- [ ]
NoNewPrivileges=trueis enabled where compatible. - [ ] Device and kernel access is restricted where appropriate.
- [ ] Network address families match application requirements.
- [ ] Unit syntax and service startup have been validated.
- [ ] Application functionality has been tested after hardening.
- [ ] Logs and monitoring are working as expected.
Treat this as a review checklist, not a universal configuration template. Different services have different operational requirements.
Final thoughts: Make least privilege part of service deployment
Linux service security should not stop at creating a dedicated user and setting file permissions.
A compromised application should have as little access to the host as reasonably possible. systemd provides practical controls for reducing that access without requiring a complete change to the deployment architecture.
Start with the service's actual requirements. Restrict filesystem access, remove unnecessary capabilities, isolate devices, and limit access to sensitive kernel interfaces. Then validate the configuration and test the application under real operating conditions.
Remember that systemd sandboxing is one layer of defense, not a complete security boundary. It does not replace application security, patch management, firewall rules, secrets protection, monitoring, or container and virtual machine isolation where those are appropriate.
The strongest result comes from combining these controls into a repeatable deployment process rather than treating hardening as a one-time task.
If you're building or maintaining production infrastructure and need help with secure server configurations, deployment automation, or operational hardening, explore ShellSecrets DevOps Solutions. The goal is to make security and reliability part of how applications are deployed and operated—not something added after an incident.