Debian 13 Tutorial / Restrict Service Accounts and Writable Paths with systemd
Running services in Debian 13 under dedicated accounts and narrowing their scope to only the state directories actually needed makes management easier. NoNewPrivileges·ProtectSystem·StateDirectory have different roles, so they should be applied step by step, and you need to distinguish between the process being active and the actual functionality performing successfully.
Separate Account Ownership from Service Restrictions
This tutorial creates a loopback-only write-check service on Debian 13 with systemd 257 and Python 3.13. Dedicated accounts separate file ownership from other users, and systemd restrictions further limit the filesystem visibility and privilege acquisition scope for that service. These restrictions can complement the path-based policies in the AppArmor profile lab, but the mechanisms are different.
| Settings | Roles to verify in this exercise |
|---|---|
| User / Group | Running the process under dedicated UID and GID |
| NoNewPrivileges | Prevent gaining new privileges through later program execution; does not itself block file writes |
| ProtectSystem=strict | Applying broad read-only restrictions to the service's filesystem view |
| ProtectHome=true | Restricting access to home-related paths |
| PrivateTmp=true | Provide a separate temporary directory for the service; distinct from full filesystem isolation |
| StateDirectory | Prepare a service-owned persistent state path and provide environment variables |
Do not copy every restriction into every service. Executables stored in home directories, temporary files shared with other programs and additional writable paths may be affected. Check the Debian 13 systemd.exec manual together with the service’s actual behavior.
Check for Conflicts and Create a Service Account
The new account is lf-svc20, and the service is lf-service20.service. There should be no existing accounts, groups, units, or folders with the same names. Do not overwrite or remove existing items found in the queries below with this example.
getent passwd lf-svc20
getent group lf-svc20
systemctl show lf-service20.service -p LoadState
ls -ld /var/lib/lf-service20 /opt/lf-service20-scratch
ls -l /usr/local/libexec/lf-service20.py
sudo ss -lntp 'sport = :8080'
python3 --version
curl --version
Initial conditions: account/group queries return no match, units return not-found, files do not exist, and port 8080 has no listening lines. If Python or curl are missing, check the package change list and prepare with sudo apt install --no-install-recommends python3 curl. For paths and service settings, use systemd unit and drop-in application procedures .
sudo adduser --system --group --no-create-home --home /nonexistent --shell /usr/sbin/nologin lf-svc20
getent passwd lf-svc20
id lf-svc20
sudo passwd -S lf-svc20
sudo install -d -m 750 -o lf-svc20 -g lf-svc20 /opt/lf-service20-scratch
sudo install -d /usr/local/libexec
Create system accounts and groups with the same name, and do not use a normal login shell or create a home directory. Do not give the new account a sudo group or login password. UID and GID are automatically assigned, so do not fix example numbers. The nologin shell is a setting to distinguish it from interactive logins and does not prevent systemd from running programs with that UID. For account creation behavior, refer to the Debian adduser documentation.
/opt/lf-service20-scratch is a folder for comparison. Give the dedicated account ordinary write permission to this directory, and later verify whether the service’s read-only restriction prevents writing. Do not use actual application files.
Write the Complete HTTP Write-probe Program
Save the following entire content in sudo nano /usr/local/libexec/lf-service20.py. You can use editors other than nano. Keep the executable owned by the administrator and allow read-only access for the service account.
import json
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
def write_probe(path):
try:
path.write_text("write-probe-ok\n", encoding="utf-8")
return {"ok": True, "errno": None}
except OSError as error:
return {"ok": False, "errno": error.errno}
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path != "/health":
self.send_error(404)
return
required_dir = Path(os.environ.get("LF_WRITE_DIR", os.environ["STATE_DIRECTORY"]))
required = write_probe(required_dir / "required.txt")
outside = write_probe(Path("/opt/lf-service20-scratch/outside.txt"))
payload = json.dumps({"uid": os.getuid(), "required": required, "outside": outside}).encode()
self.send_response(200 if required["ok"] else 503)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
HTTPServer(("127.0.0.1", 8080), Handler).serve_forever()
This program performs two test writes for each /health request. 'required' is the essential state path of the service, and 'outside' is the result of the comparison path. If the required write fails, it is designed to return HTTP 503 instead of terminating the process. This behavior is for practice to observe errors and is not generally recommended to write files every time during operational status checks.
Since it uses STATE_DIRECTORY provided by systemd, it is run through the unit below. The path to run directly from the terminal without environment variables is not used as the start method in this example. Only the standard library is used, so pip installation is not required. It listens only on loopback and is not a production web server.
sudo chmod 644 /usr/local/libexec/lf-service20.py
ls -l /usr/local/libexec/lf-service20.py
Create the Base Service and Its State Directory
Save it in sudo nano /etc/systemd/system/lf-service20.service.
[Unit]
Description=Lesson 20 service write probe
[Service]
Type=exec
User=lf-svc20
Group=lf-svc20
ExecStart=/usr/bin/python3 /usr/local/libexec/lf-service20.py
StateDirectory=lf-service20
StateDirectoryMode=0750
UMask=0027
[Install]
WantedBy=multi-user.target
The StateDirectory=lf-service20 of the system service prepares /var/lib/lf-service20, and in this example, the specified user and group and 0750 mode are used. The path is passed to the program as the STATE_DIRECTORY environment variable. Code and configuration are owned by the administrator, while changeable state files are owned by a dedicated account to differentiate ownership.
sudo systemd-analyze verify /etc/systemd/system/lf-service20.service
sudo systemctl daemon-reload
sudo systemctl start lf-service20.service
curl --noproxy '*' --retry 5 --retry-connrefused --retry-delay 1 --max-time 10 -fsS http://127.0.0.1:8080/health
sudo stat -c '%U:%G %a %n' /var/lib/lf-service20
systemctl show lf-service20.service -p User -p Group -p MainPID
After normal startup, HTTP 200 and both required and outside are expected to be ok: true. The state folder is shown as lf-svc20:lf-svc20 with mode 750. Since there are no file system restrictions yet, it can also be written to the comparison folder. The short delay until the port is ready immediately after startup is handled with limited curl retries, and if it continues to fail, check the errors in the journal.
Apply Privilege and Filesystem Restrictions in Stages
First, create the folder with sudo install -d /etc/systemd/system/lf-service20.service.d, and save it in sudo nano /etc/systemd/system/lf-service20.service.d/20-privileges.conf.
[Service]
NoNewPrivileges=true
sudo systemctl daemon-reload
sudo systemctl restart lf-service20.service
curl --noproxy '*' --retry 5 --retry-connrefused --retry-delay 1 --max-time 10 -fsS http://127.0.0.1:8080/health
service_pid=$(systemctl show lf-service20.service -p MainPID --value)
sudo grep '^NoNewPrivs:' /proc/"$service_pid"/status
Verify that both writes continue to succeed and that NoNewPrivs is set to 1. This option prevents the process and its children from gaining new privileges when executing another program. For example, it targets gaining privileges via setuid settings that allow execution with the file owner's privileges. It should not be interpreted that all file access is restricted just because this option is enabled. Next, write sudo nano /etc/systemd/system/lf-service20.service.d/30-filesystem.conf.
[Service]
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
sudo systemd-analyze verify /etc/systemd/system/lf-service20.service
sudo systemctl daemon-reload
sudo systemctl restart lf-service20.service
curl --noproxy '*' --retry 5 --retry-connrefused --retry-delay 1 --max-time 10 -fsS http://127.0.0.1:8080/health
systemctl show lf-service20.service -p NoNewPrivileges -p ProtectSystem -p ProtectHome -p PrivateTmp -p StateDirectory
HTTP 200, required ok: true, and outside ok: false are expected. In the exercise, the errno for outside was 30, indicating a write error on a read-only file system. The path prepared as STATE_DIRECTORY remains writable as an exception, while the /opt path used for comparison becomes read-only from the service's perspective.
In this setting, not all paths written by the service are limited to a single state folder. /tmp and /var/tmp, separated with PrivateTmp, are also writable, and API filesystems and any other explicit exceptions must also be considered. This exercise compares limiting writes to unnecessary general paths while maintaining the required persistent state paths.
This does not make the entire host file system read-only. To compare writing outside the service with the same UID, you can create and then delete separate files as follows.
sudo -u lf-svc20 touch /opt/lf-service20-scratch/from-normal-context
sudo rm -- /opt/lf-service20-scratch/from-normal-context
Even if writing is possible under general permissions, the results differ in the isolated execution environment of the service. It is possible to review additional exceptions with ReadWritePaths, but that option does not grant ownership or mode of the file itself. Check the paths actually needed, and if the default state path is sufficient, do not expand the exceptions.
Observe an Active Service Returning HTTP 503
To create an example where features and restrictions conflict, only incorrectly specify a required write path. Save it in sudo nano /etc/systemd/system/lf-service20.service.d/90-wrong-path.conf.
[Service]
Environment=LF_WRITE_DIR=/opt/lf-service20-scratch
sudo systemctl daemon-reload
sudo systemctl restart lf-service20.service
systemctl is-active lf-service20.service
curl --noproxy '*' --retry 5 --retry-connrefused --retry-delay 1 --max-time 10 -sS -i http://127.0.0.1:8080/health
sudo journalctl -u lf-service20.service -b --no-pager -n 20
The service is active but returns HTTP 503, and required write becomes false. In this exercise, errno 30 for the required path and HTTP 503 were confirmed. The fact that the process can receive requests is different from the fact that the necessary storage functionality is normal. In this request, curl's --fail was not used to view the error body.
Instead of removing all security restrictions, restore the incorrectly specified path. Remove only the failure example file this time and restart.
sudo rm -- /etc/systemd/system/lf-service20.service.d/90-wrong-path.conf
sudo systemctl daemon-reload
sudo systemctl restart lf-service20.service
curl --noproxy '*' --retry 5 --retry-connrefused --retry-delay 1 --max-time 10 -fsS http://127.0.0.1:8080/health
systemctl show lf-service20.service -p ProtectSystem -p NoNewPrivileges
As required write and HTTP 200 are restored, check whether ProtectSystem=strict and NoNewPrivileges=yes are maintained. Do not delete other supplementary files. When diagnosing access failures in a real service, also consider UID and GID, general file permissions, service path restrictions, and AppArmor logs, modifying only the failed conditions.
Verify State Persistence and Clean Up the Lab
Files in the StateDirectory are not automatically deleted when the service is stopped. After checking the current state files, compare whether writing is possible if restarted.
sudo systemctl stop lf-service20.service
sudo cat /var/lib/lf-service20/required.txt
sudo systemctl start lf-service20.service
curl --noproxy '*' --retry 5 --retry-connrefused --retry-delay 1 --max-time 10 -fsS http://127.0.0.1:8080/health
The persistence of the state folder in this example was confirmed through stopping and starting. The service’s startup link configuration is separate, so this exercise kept it in a manually started state. When deleting operational data, it is important to distinguish that deleting units and deleting data are separate actions.
When finishing the exercise, stop the service first and remove only these files. The data deletion below assumes that there are only the newly created test files mentioned in this text.
sudo systemctl disable --now lf-service20.service
sudo rm -- /etc/systemd/system/lf-service20.service.d/20-privileges.conf /etc/systemd/system/lf-service20.service.d/30-filesystem.conf
sudo rmdir -- /etc/systemd/system/lf-service20.service.d
sudo rm -- /etc/systemd/system/lf-service20.service /usr/local/libexec/lf-service20.py
sudo systemctl daemon-reload
sudo rm -- /var/lib/lf-service20/required.txt /opt/lf-service20-scratch/outside.txt
sudo rmdir -- /var/lib/lf-service20 /opt/lf-service20-scratch
sudo userdel lf-svc20
getent passwd lf-svc20
getent group lf-svc20
sudo ss -lntp 'sport = :8080'
Confirm that the account has been removed and nothing is listening on the lab port. If a dedicated group with the same name remains and is not used by another account, remove only that group with sudo groupdel lf-svc20. If the folder is not empty, check for other files and do not handle it with recursive deletion. Account deletion does not include a function to find and delete all data of the UID, so maintain the order of first clearing the paths of the data you created.




