Begin with one foreground process and one contract
A .service unit tells the service manager how to create and supervise processes. It is not a shell script with a different filename. The manager interprets unit directives, constructs an execution environment, starts the configured program, tracks its control group, and decides when startup, failure, and shutdown have occurred. Monday's unit-graph introduction supplied the nouns and edges; Tuesday's systemctl article separated files, loaded configuration, runtime state, and installation policy. This installment concentrates on the service contract stored in the file.
Our disposable worker is /usr/bin/sleep with the operand infinity. Sleep remains in the foreground instead of forking into the background, which gives the manager a stable main process to supervise. It does no useful work, opens no network socket, and writes no state. That narrow behavior lets us inspect service semantics without installing or starting anything.
The file has two sections. [Unit] holds general metadata and relationships. Description is a human-readable label. Wants requests that network-online.target be included when this service is started, while After orders this service after that target. Inclusion and ordering are separate edges; neither line proves that a particular application endpoint is reachable. StartLimitIntervalSec=60s and StartLimitBurst=3 let the manager count three starts in a sixty-second rate-limit window anchored by the first counted attempt. Another start in that same window is refused; once the interval expires, the next counted attempt begins a new window. This is not a promise that every arbitrary sliding sixty-second span contains at most three starts.
In [Service], Type=exec means the start operation is not considered successfully dispatched until the manager has executed the configured program. ExecStart names the program and its argument. Restart=on-failure requests another start after an unsuccessful result, but not after a clean exit or an explicit systemctl stop. RestartSec=5s waits five seconds between attempts. TimeoutStopSec=20s bounds the stop operation; after the timeout, the manager applies its configured termination policy. These settings are systemd 255 syntax, tested with Ubuntu systemd 255.4-1ubuntu8.17 and Bash 5.2.21.
[Unit]
Description=CLI demo foreground worker
Wants=network-online.target
After=network-online.target
StartLimitIntervalSec=60s
StartLimitBurst=3
[Service]
Type=exec
ExecStart=/usr/bin/sleep infinity
Restart=on-failure
RestartSec=5s
TimeoutStopSec=20sThis is configuration text, not a terminal command. Nothing has been written or started yet. A real service may need an [Install] section for enablement, but enablement is deliberately outside this runtime contract. The earlier systemctl installment explains that distinction.
Create and verify the file without installing it
Run the fixture blocks in one Bash session and in order. The setup creates systemd-service-lab beneath the current directory and enters it. If that name already exists, choose another name and restart; do not let stale files supply expected-looking results. Each && operator runs the next command only after the previous one succeeds. Export sets the C locale for stable English diagnostics. Umask 022 prevents new files from being group- or other-writable.
Printf uses the fixed format %s\n: each %s consumes one following string and \n ends its line. Single quotes keep brackets, equals signs, and spaces literal for Bash. The shell's > redirection creates or replaces clitdj-demo.service with the resulting lines. The earlier printf deep dive explains why data is kept out of the format string.
Systemd-analyze verify loads the named file and referenced units, checks directives, dependencies, and executable paths, and prints diagnostics for detected problems. The --man=no option skips checking Documentation= references; it does not weaken the unit parser. The ./ prefix identifies the file in the current directory. Verify does not start ExecStart. Its successful silence is converted into a visible marker only because the final printf runs after &&. Read verify diagnostics even when its exit status is zero: on this build an unknown directive can produce a warning, be ignored, and still let the following marker print.
mkdir systemd-service-lab &&
cd systemd-service-lab &&
export LC_ALL=C &&
umask 022 &&
printf '%s\n' '[Unit]' 'Description=CLI demo foreground worker' 'Wants=network-online.target' 'After=network-online.target' 'StartLimitIntervalSec=60s' 'StartLimitBurst=3' '[Service]' 'Type=exec' 'ExecStart=/usr/bin/sleep infinity' 'Restart=on-failure' 'RestartSec=5s' 'TimeoutStopSec=20s' > clitdj-demo.service &&
systemd-analyze --man=no verify ./clitdj-demo.service &&
printf 'verification succeeded\n'verification succeededVerify was silent for this exact warning-free fixture; the marker came from printf and certifies only that verify returned zero. Review any preceding diagnostics. A passing parse does not prove that the process can serve requests, that its dependencies establish application readiness, that sandbox settings fit the program, or that the unit has been loaded by a manager. The container used for this article runs supervisord as PID 1, so no live service was installed or activated.
Read ExecStart as an argument vector, not a command line
ExecStart=/usr/bin/sleep infinity becomes an executable pathname followed by one argument. Systemd performs its documented quoting, specifier, and environment substitution, then calls the executable directly. It does not implicitly invoke a shell. A pipe character, output redirection, wildcard, semicolon, or && token therefore does not acquire its Bash meaning merely because it appears in ExecStart; it is normally passed as an argument to the program.
If a program genuinely requires shell grammar, name the shell explicitly, for example /bin/sh -c followed by one carefully quoted script argument. That choice expands the parsing and injection surface: now both unit-file expansion and shell expansion matter. Prefer a purpose-built executable or a small reviewed script with an absolute path when several shell operations are truly the service logic. Do not insert sh -c just to copy an interactive one-liner.
Type=exec is deliberate. With the older default Type=simple, the manager can consider startup dispatched before the execve system call succeeds, so a missing executable may be reported after the start job looked successful. Type=exec waits through that step. Neither type proves application readiness. A daemon that can signal readiness with sd_notify should use Type=notify; a program that forks and leaves a child generally needs Type=forking and a reliable way to identify its main process. Type=oneshot is for work whose command completion is the activation event. Choose the type to match actual process behavior, not the label that makes status look nicest.
The systemd.service 255 command-line and Type sections define these rules. Special executable prefixes can deliberately relax failure or privilege handling; they are omitted here because a punctuation shortcut should not silently weaken this contract.
Keep inclusion, order, and readiness separate
Wants=network-online.target asks the transaction to include the target. After=network-online.target orders this service after that target has finished its own activation. Wants alone would not add ordering, and After alone would not pull the target into the transaction. Requires is a stronger inclusion relationship, but still does not invent readiness or make another unit remain active forever. This is the same two-edge model introduced Monday, applied to an actual service.
Network-online.target is meaningful only when the system has an enabled wait-online implementation that defines what online means for that network stack. Even then, it is a boot-time synchronization point, not a continuous health monitor and not proof that a database, DNS answer, route, or remote API is usable. A robust application usually handles temporary unavailability itself rather than converting every remote endpoint into a boot dependency.
Verify resolves the target from the installed host while checking our local file. That proves the name can be loaded in this test environment; it does not execute an ordering experiment. On an authorized systemd host, systemctl list-dependencies and systemctl show with After, Wants, and Requires properties can inspect the manager graph. Those are read-only, host-dependent recipes, not captured output here.
Define failure before asking for restarts
For a long-running service, a clean zero exit normally means success and a nonzero exit, signal, timeout, or watchdog failure contributes a failed result. Restart=on-failure reacts to those failure classes. Restart=always also restarts after a clean exit, while Restart=no disables automatic restart. The exact restart table has exceptions for explicit stops and for exits classified by SuccessExitStatus, RestartPreventExitStatus, and RestartForceExitStatus. Those directives can refine a known program contract; they should not be used to repaint an unexplained failure as success.
The unit-level StartLimit settings bound repeated starts, including starts initiated by restart policy. With our values, the first counted start begins a sixty-second window; three starts are allowed in that window, and another is refused until the interval expires. The next counted start then begins a new window. Attempts near the end of one window and the beginning of the next can exceed three within an arbitrary sliding sixty-second span. RestartSec prevents a tight immediate loop but does not replace the burst limit. Systemctl reset-failed can clear failure state and the start-rate counter; Tuesday explained why evidence should be captured before doing that.
Systemd-analyze exit-status translates numeric values known to this build. The four operands below request only status 0, generic failure 1, BSD temporary failure 75, and systemd execution failure 203. These names help interpret manager properties and logs; they do not tell you which status a particular application promises.
systemd-analyze exit-status 0 1 75 203NAME STATUS CLASS
SUCCESS 0 libc
FAILURE 1 libc
TEMPFAIL 75 BSD
EXEC 203 systemdA service result and its main process status are related but not interchangeable. On a live host, systemctl show --property=Result,ExecMainCode,ExecMainStatus UNIT and the bounded journal query from Wednesday’s journalctl article preserve the layers needed for diagnosis.
Override one decision without copying the vendor file
An administrator normally changes a packaged service with a drop-in under /etc/systemd/system/UNIT.d rather than copying the whole vendor file. Drop-ins merge after the main file according to lookup and lexical-order rules. Copying the entire vendor file into /etc shadows the packaged main definition and can hide later vendor changes.
ExecStart is a list-valued setting. For services other than Type=oneshot, exactly one ExecStart command is normally permitted. A drop-in that replaces it must first assign the empty value ExecStart= to clear the inherited list, then supply the replacement. The fixture creates an alternate root beneath the lab, copies the main file there, and writes 20-local.conf with that two-line reset. Mkdir -p creates the parent directories. Cp copies the file. Double quotes keep the expanded $PWD pathname as one Bash word.
SYSTEMD_UNIT_PATH is set only for the verify process. Its value points first to our alternate unit directory; the trailing colon appends the compiled search path, allowing standard targets to resolve from the host. The assignment is an environment setting for one command, not a persistent export. Verify reads the merged main file and drop-in but still starts nothing.
mkdir -p clitdj-root/etc/systemd/system/clitdj-demo.service.d &&
cp clitdj-demo.service clitdj-root/etc/systemd/system/clitdj-demo.service &&
printf '%s\n' '[Service]' 'ExecStart=' 'ExecStart=/usr/bin/sleep 30' > clitdj-root/etc/systemd/system/clitdj-demo.service.d/20-local.conf &&
SYSTEMD_UNIT_PATH="$PWD/clitdj-root/etc/systemd/system:" systemd-analyze --man=no verify clitdj-demo.service &&
printf 'merged verification succeeded\n'merged verification succeededThe replacement would sleep for thirty seconds and then exit cleanly; it was never started. On a live host, systemctl edit UNIT creates a persistent drop-in and systemctl cat UNIT shows the disk files. Systemctl daemon-reload then asks the manager to reread definitions and rebuild dependencies. It does not restart the service; decide separately whether and when runtime state should change.
Keep configuration convenient and credentials out of it
Environment= is suitable for nonsecret configuration such as a log level. It is not a secret store: unit configuration and manager interfaces can expose environment settings, and child processes inherit them. EnvironmentFile= moves values to another file but does not turn them into protected credentials; access to that file and its containing directories still controls disclosure.
Systemd credentials give a service a read-only file in a per-unit credential directory. LoadCredential=api-token:/etc/clitdj-demo/api-token names the in-service credential api-token and the host source path. The %d specifier expands to the credential directory when used in an Exec command, so the application can accept a filename instead of a secret value in its argument vector or environment. The source file must already have appropriately restricted ownership and mode. LoadCredentialEncrypted can store authenticated encrypted material and decrypt it when the service starts; its key and Trusted Platform Module (TPM) behavior require their own deployment design.
The snippet is a design example, not part of the sleep fixture. The executable is hypothetical and the credential path does not exist here. SetCredential with a literal value is explicitly unsuitable for secrets because the literal can be exposed through IPC. Credentials reduce common exposure paths; root and sufficiently privileged host processes remain outside this boundary.
[Service]
LoadCredential=api-token:/etc/clitdj-demo/api-token
ExecStart=/usr/local/libexec/clitdj-demo --token-file=%d/api-tokenSystemd.exec 255 documents the credential directory, access model, size limits, and encryption options. The receiving application must read the file safely, avoid copying the value into logs or crash reports, and define rotation behavior.
Reduce privilege according to what the process actually needs
System services run as root unless the unit selects another identity. DynamicUser=yes allocates a transient UID and GID for the service lifetime. RuntimeDirectory and StateDirectory ask systemd to create managed writable locations; they are safer than granting a recycled dynamic UID arbitrary persistent paths. NoNewPrivileges prevents the service and descendants from gaining privilege through exec. PrivateTmp gives the service private temporary directories.
ProtectSystem=strict makes the filesystem hierarchy read-only to the service except API filesystems and explicit writable exceptions. ProtectHome=yes makes home directories inaccessible. ProtectKernelTunables, ProtectKernelModules, and ProtectControlGroups restrict kernel-facing configuration surfaces. RestrictSUIDSGID blocks creation of set-user-ID and set-group-ID files. An empty CapabilityBoundingSet removes Linux capabilities from the bounding set. RestrictAddressFamilies=AF_UNIX allows only local Unix-domain sockets; our sleep fixture needs no Internet sockets. SystemCallFilter=@system-service applies the upstream service-oriented syscall set, and SystemCallErrorNumber=EPERM makes a denied call return EPERM, conventionally displayed as Operation not permitted, rather than terminating the process with SIGSYS. UMask=0077 removes group and other permission bits from newly created files by default.
The next block copies the baseline and appends these [Service] settings. The >> operator is Bash append redirection: it adds printf output to the copied file, whereas the earlier > redirection created or replaced a file. Repeated section headers are valid. Verify checks the resulting file, but it cannot prove the application will still work. Apply hardening incrementally to a real program, exercise startup, normal work, reload, shutdown, failure, upgrade, and recovery paths, and preserve a rollback.
cp clitdj-demo.service clitdj-demo-hardened.service &&
printf '%s\n' '[Service]' 'DynamicUser=yes' 'RuntimeDirectory=clitdj-demo' 'StateDirectory=clitdj-demo' 'NoNewPrivileges=yes' 'PrivateTmp=yes' 'ProtectSystem=strict' 'ProtectHome=yes' 'ProtectKernelTunables=yes' 'ProtectKernelModules=yes' 'ProtectControlGroups=yes' 'RestrictSUIDSGID=yes' 'CapabilityBoundingSet=' 'RestrictAddressFamilies=AF_UNIX' 'SystemCallFilter=@system-service' 'SystemCallErrorNumber=EPERM' 'UMask=0077' >> clitdj-demo-hardened.service &&
systemd-analyze --man=no verify ./clitdj-demo-hardened.service &&
printf 'hardened verification succeeded\n'hardened verification succeededThese restrictions fit /usr/bin/sleep, not an arbitrary daemon. A network service would need AF_INET or AF_INET6; a program that writes persistent state needs an intentional writable directory. Some namespace and seccomp controls depend on kernel and container support and may be unavailable or relaxed. Do not paste a hardening list until you can state what each exception permits.
Use the exposure score as a question generator
Systemd-analyze security inspects service sandbox directives and computes an exposure estimate from 0.0 to 10.0. The --offline=yes option reads the supplied files without asking a running PID 1 manager. --no-pager prints directly. Tail -n 1 prints only the last line from each report; -n 1 means one line. The pipe connects the analyzer output to tail. Because Bash normally reports the last pipeline command status, these abbreviated commands are observations, not release gates; the separate verify commands above provide their own guarded success.
The baseline scores 9.4 because it declares little systemd sandboxing. The hardened copy scores 3.0 on this exact systemd 255.4 build. That comparison shows which unit-level controls the analyzer recognizes. It does not prove either service is vulnerable or safe. The analyzer does not understand application code, all IPC policy, data sensitivity, reachable attack surface, external confinement, or whether a listed restriction breaks required work. Scores and weights can also change between systemd versions.
systemd-analyze --offline=yes security ./clitdj-demo.service --no-pager | tail -n 1
systemd-analyze --offline=yes security ./clitdj-demo-hardened.service --no-pager | tail -n 1-> Overall exposure level for clitdj-demo.service: 9.4 UNSAFE :-{
-> Overall exposure level for clitdj-demo-hardened.service: 3.0 OK :-)Run the full report without tail to see each question and its weight. A lower score is useful evidence that more recognized restrictions are configured, not a certification. The systemd-analyze 255 manual explicitly warns that a high score does not establish vulnerability and a low score cannot cover application or IPC behavior.
Audit every path that can rewrite or escape the contract
For an authorized configuration review, begin with the effective main file and drop-ins, then follow every referenced executable, script, EnvironmentFile, credential source, writable directory, and socket. A root-owned unit is not a trustworthy boundary if an unintended account can replace a parent directory entry or the executable it launches. Conversely, a writable application data directory is not automatically a code-execution path; determine how the process interprets its contents.
Pay special attention to Exec prefixes such as + and !. In systemd.service, + deliberately runs that command with full privileges and does not apply User, Group, CapabilityBoundingSet, or filesystem namespacing restrictions such as PrivateDevices and PrivateTmp to that command line; control-group-wide restrictions still apply. The ! prefix is narrower: it suppresses only the User, Group, and SupplementaryGroups credential changes, leaving capability bounding and namespace restrictions in force, so an executable can perform its own credential change. Either prefix is a powerful documented capability, not a vulnerability by itself. It can also create an unexpected exception to otherwise strong-looking unit settings. Reviewers should explain why a prefix is needed and test the remaining boundary rather than judging the file by its hardening lines alone.
Also inspect drop-in precedence and list resets. A late empty CapabilityBoundingSet= assignment resets the bounding set to empty and removes all capabilities, as the hardened fixture does. By contrast, CapabilityBoundingSet=~ with no capability names resets it to the full available set, undoing an earlier bound and weakening that restriction. A late drop-in can also replace ExecStart after the required empty reset. Systemctl cat UNIT shows source files on disk; systemctl show UNIT exposes loaded properties; comparing both reveals a pending daemon-reload but not who made the change. Correlate package ownership, configuration management, file metadata, change records, and the bounded journal. An unexpected override is a finding to investigate, not proof of exploitation or a defect in systemd.
The lab deliberately leaves its files under systemd-service-lab for inspection. Remove only that exact directory after confirming its pathname; no recursive cleanup command is supplied for a privileged unit path.
Install only after the contract survives review
A real deployment crosses several distinct gates. First verify the candidate files in staging. Install the main file or reviewed drop-in with root ownership and non-writable group/other permissions. Ask the manager to reread definitions with systemctl daemon-reload. Inspect systemctl cat and selected systemctl show properties. Start or restart only in an approved change window, then inspect status, Result and ExecMainStatus, and a bounded journal query. Test graceful stop and failure recovery. Enable only if boot or another installation relationship is intended.
Those operations are intentionally not a pasteable block: installation paths, ownership, service account, state migration, health check, and rollback differ by application. Daemon-reload alone does not change an already running process. Restart changes runtime state and may interrupt service. Enable changes future activation policy and does not prove successful runtime startup. The week’s earlier installments keep those layers separate.
A good service unit is an executable claim about process behavior: which program stays in the foreground, when startup counts, what failure means, how often retry is acceptable, which files and interfaces are necessary, and where secrets enter. Verification, a clean exposure score, and a green status each answer only part of that claim. Treat the boundaries between them as the work, not as paperwork after the command.
systemctl --no-pager cat ACTUAL.service
systemctl show --all --property=LoadState,ActiveState,SubState,Result,ExecMainCode,ExecMainStatus,FragmentPath,DropInPaths,NeedDaemonReload ACTUAL.service
journalctl --no-pager -b -u ACTUAL.service -n 50Replace ACTUAL.service with a real authorized service. These three commands inspect disk configuration, loaded/runtime properties, and recent current-boot journal evidence. The --no-pager flag prints directly; --all retains empty properties; --property selects the named fields; -b selects the current boot; -u selects entries from or about the unit; and -n 50 limits the displayed recent matches to fifty. Their output is host-dependent. They do not install, reload, start, stop, restart, enable, or reset the unit.