You can harden a systemd unit with an LLM in under a minute, and the draft will look like it came straight out of the systemd.exec man page. Some of it will have. The rest is the problem: directive names that don't exist, hardening lines in the wrong section, a sandbox so tight the service can't write its own data, and a capability list that hands a non-root process the power to ignore file permissions. In our lab, every one of those drafts started without an error from systemctl. LLM systemd.exec hardening is a draft until systemd has parsed every line, the service still does its job, and systemd-analyze security agrees the exposure went down for the right reasons.
This guide runs that loop on one small service. Every message, score and result below came from our lab: systemd 257.13, the version in Debian 13, running as PID 1 inside a container, plus systemd-analyze on a host where PID 1 is not systemd. We checked every directive against the systemd.exec and systemd.unit man pages before writing the drafts. The broken drafts were written for this guide to reproduce mistakes models commonly make with AI systemd sandbox directives. They are not a captured model transcript, and no model was called in the lab. systemd's output is the evidence.
Updated: we re-ran every draft on systemd 262.2 (November 5), the current stable release, which the "latest" man pages now describe. Every exposure score and every pass or fail matched 257.13. One log message changed wording, noted in Step 4.
Your own systems only. Harden units on machines you own or administer. Test on a VM or container you can throw away, not on a production host. Keep real hostnames, paths and secrets out of prompts.
What we ran, and what we didn't
The original lab used systemd 257.13. After 262.2 shipped, we re-ran the same drafts on it; every score and every pass or fail matched.
- systemd 257.13 (Debian package
257.13-1~deb13u1). The box we worked on runs a different init as PID 1, so we used it only for offline checks (systemd-analyze verifyandsystemd-analyze security --offline=yes). - A throwaway Debian 13 container built with
debootstrapand booted withsystemd-nspawn --boot --private-network, so systemd 257 was PID 1 and could start, sandbox and stop real services. A second container with Debian testing and systemd 262.2 was used for the re-test. - A toy service we wrote,
notesd: under 40 lines of Python 3.13 usinghttp.server. It listens on127.0.0.1:8080, returns all notes onGET /, and appends the request body to/var/lib/notesd/notes.txtonPOST /. At startup it logs its UID and state directory. - Twelve drafts plus a final unit, each installed as
notesd.service, started, called withcurl, and scored live and offline. - A probe that runs inside the baseline and final sandboxes and tries things
notesdshould never need.
What we didn't do: we didn't test on a full VM or bare metal. systemd-nspawn applies its own seccomp filter and drops some capabilities for everything in the container, so a baseline service there is already a little more confined than on a normal host. We could not show IPAddressDeny= being enforced in the container (a test client with IPAddressDeny=any still reached the service), so we make no claim about it beyond what the docs say. We didn't test SELinux or AppArmor, RootImage=, or user units. In the output below, we shortened absolute paths and removed repeated restart lines. Nothing else was changed.
How to harden a systemd unit with an LLM
Treat every draft as untrusted and put it through three gates, in order:
- Does systemd understand every line?
systemd-analyze verifyprints a warning for every directive it doesn't know. It still exits 0, so you have to read or grep the output. - Does the service still do its job? Start it and exercise every function: read, write, listen. A sandboxed service that is "active (running)" can still fail every request.
- Did the exposure go down for the right reasons?
systemd-analyze securitygives a score from 0.0 to 10.0. It's a checklist of settings, not a test. It doesn't know whether your service works, and it rewards some drafts that hand out privileges.
# Gate 1 and 3: static, no PID 1 needed
systemd-analyze verify notesd.service
systemd-analyze security --offline=yes --threshold=50 notesd.service
# Gate 2: on a disposable machine, as root
./smoke.sh notesd.service
Step 1: Write down what the service must still do
Before prompting, list what the service needs. You'll test against that list, and it's the most useful thing to give the model. For notesd:
- Listen on TCP
127.0.0.1:8080(IPv4 only; port above 1024, so no capabilities). - Read and write
/var/lib/notesd/and nothing else on disk. - Read its own code under
/opt/notesd/and the Python runtime under/usr. - No devices, no other processes, no kernel settings, no new privileges.
The baseline unit is what most people write first:
[Unit]
Description=notesd toy note service
After=network.target
[Service]
ExecStart=/usr/bin/python3 /opt/notesd/notesd.py
Restart=on-failure
[Install]
WantedBy=multi-user.target
It runs as root, and systemd-analyze security says so:
$ systemd-analyze security notesd.service
...
→ Overall exposure level for notesd.service: 9.6 UNSAFE :-{
The offline check on the same file reports 9.4. The only difference is one line: offline credits PrivateMounts= as set, and the live check marks it missing. Compare offline with offline and live with live.
Step 2: Prompt with the facts the model can't guess
The model can't know your systemd version, which paths the service writes, or whether it binds a privileged port. Without those, it guesses, and the guesses are where the breakage comes from. This is the prompt we would send:
Harden this systemd service for systemd 257 (Debian 13). Output a drop-in file
for /etc/systemd/system/notesd.service.d/hardening.conf, [Service] section only.
The service: Python 3 HTTP server, ExecStart=/usr/bin/python3 /opt/notesd/notesd.py.
It must still:
- listen on TCP 127.0.0.1:8080 (IPv4; unprivileged port)
- read and write /var/lib/notesd and nothing else on disk
- read /opt/notesd and /usr
It needs no capabilities, no devices, no other processes and no kernel access.
Rules:
- Use only directives documented in systemd.exec(5) and
systemd.resource-control(5) for systemd 257. Do not invent names.
- Use StateDirectory= for /var/lib/notesd rather than ReadWritePaths=.
- Do not add any capability. Do not use PrivateNetwork=.
- For SystemCallFilter=, use groups listed by `systemd-analyze syscall-filter`.
- After the file, list every directive with one line on what it breaks if wrong.
The last rule makes the model say what each line breaks, which is where PrivateNetwork= on a network service tends to get noticed.
Step 3: Catch invented directives with systemd-analyze verify
Our first draft used four real hardening directives and five that don't exist:
[Service]
ExecStart=/usr/bin/python3 /opt/notesd/notesd.py
Restart=on-failure
ProtectSystem=full
ProtectHome=yes
PrivateTmp=yes
NoNewPrivileges=yes
ProtectNetwork=yes
RestrictFilesystemAccess=yes
DenyWritePaths=/etc /usr /boot
MemoryDenyWrite=yes
SandboxLevel=strict
systemd-analyze verify names every one of them, and still exits 0:
$ systemd-analyze verify units/d1-invented/notesd.service
notesd.service:12: Unknown key 'ProtectNetwork' in section [Service], ignoring.
notesd.service:13: Unknown key 'RestrictFilesystemAccess' in section [Service], ignoring.
notesd.service:14: Unknown key 'DenyWritePaths' in section [Service], ignoring.
notesd.service:15: Unknown key 'MemoryDenyWrite' in section [Service], ignoring.
notesd.service:16: Unknown key 'SandboxLevel' in section [Service], ignoring.
$ echo $?
0
Installed for real, the unit started, logged the same five warnings to the journal, and served requests as root (notesd uid=0). The made-up lines did nothing; the real ones moved the score from 9.6 to 8.7. Note MemoryDenyWrite: the real directive is MemoryDenyWriteExecute=. A near-miss name is the hardest kind to spot by eye.
The second draft used only real directives, but put most of them in the wrong section:
$ systemd-analyze verify units/d2-section/notesd.service
notesd.service:4: Unknown key 'NoNewPrivileges' in section [Unit], ignoring.
notesd.service:5: Unknown key 'ProtectSystem' in section [Unit], ignoring.
notesd.service:6: Unknown key 'ReadWritePaths' in section [Unit], ignoring.
notesd.service:7: Unknown key 'PrivateTmp' in section [Unit], ignoring.
notesd.service:15: Unknown key 'ProtectHome' in section [Install], ignoring.
The systemd.exec man page says its options go "in the [Service], [Socket], [Mount], or [Swap] sections, depending on the unit type." In [Unit] or [Install], they are ignored, and this draft scored 9.6 live, exactly like the baseline.
System call groups get the same treatment. A draft with SystemCallFilter=@web-server @basic-io produced one warning:
notesd.service:11: Unknown system call group, ignoring: @web-server
There is no @web-server group. The line kept @basic-io as the whole allow list, and that comes back in Step 4. systemd-analyze syscall-filter prints the real groups for the version you have.
The fix for this gate is simple: fail the check on any warning. The validator script further down greps for Unknown, ignoring, Failed and Invalid and rejects the file if any line matches.
Step 4: Start it and call it, because "active (running)" proves little
We installed each of the next eight drafts in the container, started it, and ran a GET and a POST. Seven of them passed verify without a single warning; d9 is the @web-server draft from Step 3.
| Draft | What it added | What happened (systemd 257.13) |
|---|---|---|
| d3 | ProtectSystem=strict, no writable path | Running. GET 200; POST 500: [Errno 30] Read-only file system: '/var/lib/notesd/notes.txt' |
| d4 | PrivateNetwork=yes | ActiveState=active SubState=running, and curl exit 7 (connection refused) from outside |
| d5 | DynamicUser=yes + ReadWritePaths=/var/lib/notesd | Running as UID 61423. POST 500: [Errno 13] Permission denied |
| d6 | User=notesd, user never created | Failed at step USER, status=217/USER, five restarts, then failed |
| d8 | SystemCallFilter=~@network-io @privileged | code=killed, status=31/SYS, five restarts, then failed |
| d8b | d8 plus SystemCallErrorNumber=EPERM | Python traceback: PermissionError: [Errno 1] Operation not permitted, exit 1 |
| d9 | SystemCallFilter=@web-server @basic-io | status=31/SYS (only @basic-io was left) |
| d10 | RestrictAddressFamilies=AF_INET6 AF_UNIX | OSError: [Errno 97] Address family not supported by protocol |
A few of these deserve a closer look.
d3, ProtectSystem=strict alone. The docs say strict mounts the entire file system hierarchy read-only except /dev, /proc and /sys, and that ReadWritePaths= or StateDirectory= exempt specific paths. The draft had neither. Reads worked and the first write failed. If your health check only does a GET, this ships.
d4, PrivateNetwork=yes. The man page says it "configures only the loopback network device" inside a new namespace. The service bound 127.0.0.1:8080 in its own namespace, where nothing else can reach it, and systemd reported it healthy:
ActiveState=active SubState=running Result=success NRestarts=0
--- GET /
[http 000]
curl exit=7
d5, DynamicUser=yes with an existing directory. The docs say DynamicUser= implies ProtectSystem=strict, ProtectHome=read-only, NoNewPrivileges= and RestrictSUIDSGID=. The draft allow-listed /var/lib/notesd with ReadWritePaths=, but the directory was still owned by root from the days the service ran as root, so the dynamic user could read and not write. The docs also warn that dynamic UIDs are recycled, and point you to StateDirectory= instead.
When we switched to StateDirectory=notesd, systemd fixed the old directory itself, and said so:
notesd.service: Found pre-existing public StateDirectory= directory /var/lib/notesd, migrating to /var/lib/private/notesd.
notesd.service: Apparently, service previously had DynamicUser= turned off, and has now turned it on.
notesd uid=61423 state=/var/lib/notesd port=8080
On disk, /var/lib/notesd became a symlink to private/notesd, and the files there showed owner 65534. That's expected: the StateDirectory= docs say that with DynamicUser= and a kernel that supports ID-mapped mounts, the directory is owned by "nobody" on the host and mapped to the service's UID inside.
d6, a user that doesn't exist. On 257.13 the journal said Failed to determine user credentials: No such process; in our 262.2 re-test, it said Failed to determine credentials for user 'notesd': Unknown user. Create the account, or use DynamicUser=.
d8 and d9, system call filters. A model told to "block what a web server doesn't need" may deny @network-io, which on 257.13 contains socket, bind and listen, the calls the server needs. The man page says the default action for a denied call is to terminate the process with SIGSYS, so the journal shows status=31/SYS and nothing about which call. Adding SystemCallErrorNumber=EPERM turns the kill into an error the program can report, and the traceback points at socket.socket(...). Use EPERM while testing at least; it's much easier to debug.
d10, address families. "Only IPv6 and Unix sockets" sounds stricter, but the service binds an IPv4 address, so it died at startup.
Seven of these eight drafts passed systemd-analyze verify with no warnings. Only starting the service and calling it found the problems.
Step 5: Read the exposure score, but don't trust it alone
Here are the offline scores for the same drafts next to whether the service worked:
| Draft | Offline exposure (257.13) | Service works? |
|---|---|---|
| d0 baseline | 9.4 UNSAFE | yes (as root) |
| d1 invented names | 8.7 EXPOSED | yes (as root) |
| d3 strict, no writable path | 8.7 EXPOSED | no writes |
| d4 PrivateNetwork | 8.2 EXPOSED | unreachable |
| d5 DynamicUser + ReadWritePaths | 8.1 EXPOSED | no writes |
| d10 AF_INET6 only | 7.8 EXPOSED | dead |
| d7 broad capabilities | 6.7 MEDIUM | yes |
| d8 deny @network-io | 6.6 MEDIUM | dead |
| d11 final + PrivateNetwork | 0.5 SAFE | unreachable |
| final | 0.9 SAFE | yes |
The best score in the lab went to a unit that can't serve a single request: adding PrivateNetwork=yes to the working final unit took it from 0.9 to 0.5. The broken d8 and d10 also beat drafts that work. The score measures settings, and the man page says as much: it "only analyzes the per-service security features systemd itself implements," and a level is an estimate, not a verdict.
The draft worth worrying about is d7, which works and scores better than the baseline. It added a capability list "for flexibility":
DynamicUser=yes
StateDirectory=notesd
CapabilityBoundingSet=CAP_NET_BIND_SERVICE CAP_NET_ADMIN CAP_NET_RAW CAP_SYS_ADMIN CAP_DAC_OVERRIDE CAP_SETUID CAP_SETGID
AmbientCapabilities=CAP_NET_BIND_SERVICE CAP_NET_ADMIN CAP_DAC_OVERRIDE
The running process, as dynamic UID 61423:
CapPrm: 0000000000001402
CapEff: 0000000000001402
CapBnd: 00000000002034c2
CapAmb: 0000000000001402
NoNewPrivs: 1
0x1402 decodes to CAP_DAC_OVERRIDE, CAP_NET_BIND_SERVICE and CAP_NET_ADMIN. So a non-root process that only serves HTTP on port 8080 can bypass file permission checks and reconfigure networking. The security report did flag it, in five of its 81 checks, weighted 0.1 to 0.3 each:
✗ CapabilityBoundingSet=~CAP_(DAC_*|FOWNER|IPC_OWNER) Service may override UNIX file/IPC permission checks 0.2
✗ CapabilityBoundingSet=~CAP_SET(UID|GID|PCAP) Service may change UID/GID identities/capabilities 0.3
✗ CapabilityBoundingSet=~CAP_NET_ADMIN Service has network configuration privileges 0.2
✗ CapabilityBoundingSet=~CAP_NET_(BIND_SERVICE|BROADCAST|RAW) Service has elevated networking privileges 0.1
✗ CapabilityBoundingSet=~CAP_SYS_ADMIN Service has administrator privileges 0.3
The overall number still went from 9.6 to 6.7, because DynamicUser= alone switches on several scored protections, and our smoke test passed it too. The gate that catches this is a capability review against the list from Step 1. For notesd that list is empty, so any non-empty CapabilityBoundingSet= or any AmbientCapabilities= should fail.
Use the score as a ratchet, not a verdict. --threshold= makes it usable in CI: with --offline=yes, a unit above the threshold returns an error. The threshold is on a 0 to 100 scale, so 50 means 5.0:
$ systemd-analyze security --offline=yes --threshold=50 units/d7-broad-caps/notesd.service
→ Overall exposure level for notesd.service: 6.7 MEDIUM :-|
exit=1
$ systemd-analyze security --offline=yes --threshold=50 units/final/notesd.service
→ Overall exposure level for notesd.service: 0.9 SAFE :-}
exit=0
Step 6: The final unit, and what it actually blocks
This is the version that passed all three gates. We ship it as a drop-in, so the vendor or original unit stays untouched:
# /etc/systemd/system/notesd.service.d/hardening.conf
[Service]
DynamicUser=yes
StateDirectory=notesd
StateDirectoryMode=0700
UMask=0077
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
PrivateUsers=yes
ProtectHostname=yes
ProtectClock=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectKernelLogs=yes
ProtectControlGroups=yes
ProtectProc=invisible
ProcSubset=pid
NoNewPrivileges=yes
CapabilityBoundingSet=
AmbientCapabilities=
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
LockPersonality=yes
MemoryDenyWriteExecute=yes
SystemCallArchitectures=native
SystemCallFilter=@system-service
SystemCallFilter=~@privileged @resources
SystemCallErrorNumber=EPERM
IPAddressDeny=any
IPAddressAllow=localhost
DevicePolicy=closed
MemoryDenyWriteExecute=yes is fine for CPython, but don't copy it to a service with a JIT (Node.js, Java), which needs writable and executable memory. The empty CapabilityBoundingSet= drops every capability. We left AF_INET6 in RestrictAddressFamilies=; for an IPv4-only service you can drop it and test again.
The offline checks read drop-ins too. With --root= pointing at the container's file system, the untouched baseline unit plus this drop-in scored the same as the merged file:
$ systemd-analyze security --offline=yes --root=rootfs notesd.service
→ Overall exposure level for notesd.service: 0.9 SAFE :-}
Both verify and security --offline=yes also pick up a notesd.service.d/ directory sitting next to a unit file you pass by path. We checked that with a drop-in containing ProtectNetwork=yes: both commands printed the Unknown key warning with the drop-in's own file name and line number. That makes it easy to test a model's drop-in without installing anything.
The remaining items are the ones notesd needs, or that we chose to leave:
✗ RootDirectory=/RootImage= Service runs within the host's root directory 0.1
✗ RestrictAddressFamilies=~AF_UNIX Service may allocate local sockets 0.1
✗ RestrictAddressFamilies=~AF_(INET|INET6) Service may allocate Internet sockets 0.3
✗ PrivateNetwork= Service has access to the host's network 0.5
✗ DeviceAllow= Service has a device ACL with some special devices: char-rtc:r 0.1
✗ IPAddressDeny= Service defines IP address allow list with only localhost entries 0.1
A score says what's configured. To see what's enforced, we ran a probe script under the baseline unit and under the final sandbox (with User=notesd, so it got the same dynamic user and state directory):
| Probe | Baseline (root) | Final sandbox |
|---|---|---|
| Write the state directory | allowed | allowed |
Write /etc/probe | allowed | Read-only file system |
Modify /opt/notesd/notesd.py | allowed | Permission denied |
List /root | allowed | Permission denied |
Read /proc/1/cmdline | /usr/lib/systemd/systemd | No such file or directory |
Open an AF_PACKET raw socket | allowed | Address family not supported |
sethostname() | allowed | Operation not permitted |
| Set the setuid bit on its own file | allowed | Operation not permitted |
| Create a user namespace | allowed | Operation not permitted |
| Map memory writable and executable | allowed | Permission denied |
| Effective capabilities | fdecbfff (nspawn's set) | 0 |
The baseline column is a root process in an nspawn container; on a normal host it would have every capability. In the final column, notesd still serves GET and POST, and what an attacker would try after a bug in the HTTP handler is refused.
Common mistakes in LLM-written systemd hardening
| Mistake | What systemd did (257.13) | Fix |
|---|---|---|
Invented or near-miss directive (ProtectNetwork=, MemoryDenyWrite=) | Unknown key ... ignoring, unit runs unhardened, verify exit 0 | Fail on any verify warning; check names in systemd.exec(5) |
Hardening in [Unit] or [Install] | Ignored with a warning; same score as baseline | Everything goes in [Service] or a drop-in's [Service] |
Invented syscall group (@web-server) | Group ignored; the rest of the allow list killed the process | systemd-analyze syscall-filter for real groups |
ProtectSystem=strict with no writable path | Reads work, writes get EROFS | StateDirectory= (or ReadWritePaths=) |
PrivateNetwork=yes on a network service | "active (running)" and unreachable | Never on a service that listens for others |
DynamicUser=yes + ReadWritePaths= on a root-owned dir | Permission denied on write | StateDirectory=; systemd migrates the old directory |
User= for an account that doesn't exist | 217/USER, restart loop | Create the user, or use DynamicUser= |
Denying @network-io "for safety" | status=31/SYS | Start from @system-service; set SystemCallErrorNumber=EPERM |
RestrictAddressFamilies= missing AF_INET | Errno 97 at bind | Derive families from what the service binds |
| Capabilities "just in case" | Works, scores better, holds CAP_DAC_OVERRIDE | Start from an empty CapabilityBoundingSet= and add only what you can name a reason for |
A small validator for the loop
The static gates fit in a short script. It fails on any verify warning, then on an exposure above the threshold, using the exit codes from systemd-analyze:
#!/bin/bash
# usage: check_unit.sh <unit-file> [threshold]
# Static gates for a model-written unit. Threshold is in tenths: 50 = exposure 5.0.
unit=$1; threshold=${2:-50}
warnings=$(systemd-analyze verify "$unit" 2>&1 | grep -E "Unknown|ignoring|Failed|Invalid")
if [ -n "$warnings" ]; then
echo "REJECT (verify): $(wc -l <<<"$warnings") warning(s)"
sed 's#^.*/##' <<<"$warnings"
exit 2
fi
report=$(systemd-analyze security --offline=yes --threshold="$threshold" --no-pager "$unit" 2>&1)
status=$?
score=$(grep "Overall exposure" <<<"$report")
if [ "$status" -ne 0 ]; then
echo "REJECT (exposure above $threshold): ${score#*: }"
exit 3
fi
echo "STATIC OK: ${score#*: } (now start it and run the functional test)"
Across every draft:
d0-baseline REJECT (exposure above 50): 9.4 UNSAFE :-{
d1-invented REJECT (verify): 5 warning(s)
d2-section REJECT (verify): 5 warning(s)
d3-strict-no-rw REJECT (exposure above 50): 8.7 EXPOSED :-(
d4-privatenetwork REJECT (exposure above 50): 8.2 EXPOSED :-(
d5-dynamicuser-rwpaths REJECT (exposure above 50): 8.1 EXPOSED :-(
d6-user-missing REJECT (exposure above 50): 8.7 EXPOSED :-(
d7-broad-caps REJECT (exposure above 50): 6.7 MEDIUM :-|
d8-syscall-network-io REJECT (exposure above 50): 6.6 MEDIUM :-|
d9-syscall-invented-group REJECT (verify): 1 warning(s)
d10-af-inet6-only REJECT (exposure above 50): 7.8 EXPOSED :-(
d11-final-plus-privatenetwork STATIC OK: 0.5 SAFE :-} (now start it and run the functional test)
final STATIC OK: 0.9 SAFE :-} (now start it and run the functional test)
Look at the second-to-last line. The static gates let d11 through, and it's dead. That's why the functional test is not optional. Ours installs the unit, restarts it and checks the things from Step 1:
#!/bin/bash
# usage (on the test machine, as root): smoke.sh <unit-file>
install -m 0644 "$1" /etc/systemd/system/notesd.service
systemctl daemon-reload
systemctl restart notesd; sleep 2
fail=0
systemctl is-active --quiet notesd || { echo "FAIL: not active ($(systemctl show -p Result --value notesd))"; fail=1; }
curl -fsS -m 3 -o /dev/null http://127.0.0.1:8080/ || { echo "FAIL: GET"; fail=1; }
curl -fsS -m 3 -o /dev/null -d "smoke $(date +%s)" http://127.0.0.1:8080/ || { echo "FAIL: POST (write to state dir)"; fail=1; }
[ "$fail" -eq 0 ] && echo "FUNCTIONAL OK"
exit $fail
On d11 it printed FAIL: GET and FAIL: POST (write to state dir); on the final unit, FUNCTIONAL OK. It also passed d7, so keep the capability review from Step 5 in the loop, as a person or as a grep for AmbientCapabilities= and a non-empty CapabilityBoundingSet=.
To close the loop with a model, send the REJECT lines or the FAIL lines and the journal back, and ask for a corrected drop-in. This sketch does that with the OpenAI Python SDK and RedRouter's https://redrouter.org/v1 base URL from the quickstart. We did not run it against the API for this post; the systemd half is the scripts above.
import os, subprocess
from openai import OpenAI
client = OpenAI(base_url="https://redrouter.org/v1", api_key=os.environ["REDROUTER_API_KEY"])
messages = [{"role": "user", "content": open("prompt.txt").read()}] # Step 2 prompt
for attempt in range(4):
reply = client.chat.completions.create(model="glm-5.3-flash-red", messages=messages)
dropin = reply.choices[0].message.content.strip().removeprefix("```ini").removesuffix("```").strip()
# candidate/notesd.service is the original unit; the drop-in goes next to it
open("candidate/notesd.service.d/hardening.conf", "w").write(dropin + "\n")
check = subprocess.run(["./check_unit.sh", "candidate/notesd.service"], capture_output=True, text=True)
print(check.stdout.strip())
if check.returncode == 0:
break # static gates passed: now run smoke.sh on a throwaway VM and review capabilities
messages += [{"role": "assistant", "content": dropin},
{"role": "user", "content": check.stdout.strip() + "\nReturn the corrected drop-in only."}]
The sketch only automates the static gates. Run the smoke test and the capability review yourself before a candidate goes anywhere near a real host.
Where this fits with other Linux host tooling
Unit hardening limits what a compromised service can do; it doesn't tell you when something happens. For detection on the same hosts, Falco rules with an LLM covers syscall-level alerts, auditd rules with an LLM covers kernel audit trails, and osquery queries with an LLM covers asking the fleet what is running and how it's configured, which is one way to find the units still at 9.6.
What to send the model, and what not to
- Send: the output of
systemctl --version, the unit (orsystemctl catoutput) with secrets removed, the list of things the service must still do, the exactverifywarnings and journal lines from the last round, and which capabilities, if any, you can justify. - Scrub:
Environment=lines,EnvironmentFile=contents, credentials passed withLoadCredential=orSetCredential=, internal hostnames, IP addresses, and paths that reveal customers or projects. Unit files collect secrets more often than people expect. - Check retention. On RedRouter, account zero data retention is an opt-in setting, off by default. The data handling docs explain what is stored and the controls, and what RedRouter keeps covers the defaults in plain terms.
Choosing a model for systemd hardening
Any model that follows "output the drop-in only" and corrects itself from a warning line will do; the gates do the judging. On RedRouter, GLM 5.3 Flash Red (glm-5.3-flash-red) is $0.25 per 1M input tokens, $0.13 per 1M cached input tokens and $1.00 per 1M output tokens. red-cyber-1 (Beta), the featured model for authorized penetration testing and red-team work, is $0.28 / $0.13 / $1.10 per 1M tokens. Current rates for every model are in the models docs, and plans are on /pricing.
Hardening prompts talk about privilege escalation, raw sockets and what an attacker does after a foothold, because that's what the sandbox is for. RedRouter is built for that kind of authorized security work.
FAQ
Can I harden a systemd unit with an LLM?
Yes, as a first draft. In our lab on systemd 257.13, two of twelve drafts ran but were less hardened than they looked because systemd ignored lines, nine broke the service, and one worked while granting capabilities it didn't need. systemctl start returned success for every one of them. Only the final unit passed verify cleanly, served requests and scored 0.9.
What does LLM systemd.exec hardening get wrong most often?
In our drafts: names that don't exist or are slightly off (MemoryDenyWrite= instead of MemoryDenyWriteExecute=), directives in the wrong section, ProtectSystem=strict without a writable state directory, PrivateNetwork=yes on a network service, and capability lists added "just in case."
Which AI systemd sandbox directives are safe to start with?
For most network services that don't need root: DynamicUser=yes with StateDirectory=, ProtectSystem=strict, ProtectHome=yes, PrivateTmp=yes, PrivateDevices=yes, NoNewPrivileges=yes, an empty CapabilityBoundingSet=, RestrictAddressFamilies= limited to what the service binds, SystemCallArchitectures=native and SystemCallFilter=@system-service. Then test, and tighten one step at a time.
Why does systemd-analyze verify pass a unit with made-up directives?
It doesn't fail it, but it does warn. On 257.13 (and in our 262.2 re-test), unknown keys print Unknown key ... ignoring and the command exits 0, and systemd starts the unit with those lines dropped. Treat any warning as a failure in your pipeline.
What exposure score should a hardened service reach?
There's no official target. Our working notesd reached 0.9; a broken variant reached 0.5. Use --threshold= to stop regressions in CI, and rely on a functional test plus a capability review to decide whether a draft is good.
Is it safe to paste unit files into an LLM?
Paste the structure, not the secrets. Remove Environment= values, credential settings, hostnames and internal paths first. On RedRouter, account zero data retention is opt-in and off by default; see the data handling docs.
Sources
- systemd man pages: systemd.exec, systemd.unit, systemd.service, systemd.resource-control, systemd-analyze, systemd-nspawn.
- systemd releases: v257.13, v262.2; Debian's systemd package.
- Lab outputs: systemd 257.13 as PID 1 in a Debian 13
systemd-nspawncontainer, re-run on systemd 262.2, plus offlinesystemd-analyzeon the host. No model was called. - OpenAI Python SDK.
- RedRouter Docs: Quickstart, Models and pricing, Data handling.