26.2. Confining Applications
Patching reduces how often software is vulnerable; confinement reduces how much a vulnerable program can reach when it is. Debian 13 ships two complementary mechanisms: AppArmor, which confines programs by path-based profiles the kernel enforces on every file operation, and systemd's unit sandboxing, which restricts what a service can see at all. This section exercises both on a small program and a small service, including the failure mode that most confinement work actually produces - a legitimate operation denied - and its resolution.
26.2.1. Inspecting AppArmor Status and Profiles
Debian 13 enables AppArmor at boot: the apparmor.service unit loads every
profile under /etc/apparmor.d into the kernel. See what that amounts
to. On sec1, as john:
$ sudo aa-status
apparmor module is loaded.
111 profiles are loaded.
12 profiles are in enforce mode.
23 profiles are in complain mode.
0 profiles are in prompt mode.
0 profiles are in kill mode.
76 profiles are in unconfined mode.
3 processes have profiles defined.
3 processes are in enforce mode.
/usr/sbin/chronyd (633)
/usr/sbin/chronyd (636)
/usr/sbin/dhclient (1535) /{,usr/}sbin/dhclient
Selected output; the profile-name lists under each count and the trailing
zero-process lines are omitted. The enforce-mode count of 12 includes this
chapter's demonstration profile, built in the next two sections; the
others name system utilities such as man, dhclient, and chronyd
and their helper profiles.
Three facts fall out of the summary. First, profiles are loaded and being
enforced - the count under enforce is the one that means confinement,
not merely definitions. Second, a profile with a running process behind it
is worth knowing by name: dhclient and chronyd are confined system
daemons, and the parenthesized numbers are their process IDs. Third, the
complain-mode and dormant counts are definitions shipped by the
apparmor package for software that may be installed later; they confine
nothing until their target runs. The profiles themselves are plain files
under /etc/apparmor.d, named after the program path they confine, and
Debian's packaging convention keeps local customizations out of those
files entirely - the mechanism the next section uses.
26.2.2. Complain Mode, Enforce Mode, and Local Overrides
To watch confinement work, build a program with exactly one interesting
operation: it opens the file named on its command line and prints it. Save
this as apparmor-demo.c in the workspace:
#include <stdio.h>
int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr, "usage: %s FILE\n", argv[0]);
return 2;
}
FILE *f = fopen(argv[1], "r");
if (!f) {
perror("fopen");
return 1;
}
int c;
while ((c = fgetc(f)) != EOF)
putchar(c);
fclose(f);
return 0;
}
Compile it into place - /usr/local/bin is root-owned, so the compile
itself uses sudo:
$ sudo gcc -O2 -Wall -o /usr/local/bin/apparmor-demo apparmor-demo.c
A successful compile prints nothing. Give the program three files to read: one it may read, one it may not, and one the profile will grant through a local override:
$ sudo install -d -m 755 /srv/apparmor-demo
$ sudo sh -c 'printf "allowed content\n" > /srv/apparmor-demo/allowed.txt'
$ sudo sh -c 'printf "restricted content\n" > /srv/apparmor-demo/denied.txt'
$ sudo sh -c 'printf "local override content\n" > /srv/apparmor-demo/override.txt'
$ sudo chmod 644 /srv/apparmor-demo/*.txt
The sh -c wrapper exists because the redirection is performed by the
calling shell, which runs as root only inside the sudo invocation; all
five commands are silent. Now the profile. Under Debian's convention the
packaged profile lives in /etc/apparmor.d and includes a local/
file that starts empty, so an administrator can extend the profile without
ever editing the packaged part. The profile file, saved as
/etc/apparmor.d/usr.local.bin.apparmor-demo on sec1 (the path mirrors
the program path with slashes turned into dots):
#include <tunables/global>
/usr/local/bin/apparmor-demo {
#include <abstractions/base>
#include <local/usr.local.bin.apparmor-demo>
/usr/local/bin/apparmor-demo mr,
/srv/apparmor-demo/allowed.txt r,
}
The rules read directly: the program may map and read itself (mr), and
it may read exactly one file in /srv/apparmor-demo. The
abstractions/base include supplies the ordinary runtime needs of any
program - libraries, /proc basics, device access. The local include
file, saved as
/etc/apparmor.d/local/usr.local.bin.apparmor-demo, holds the
administrator's extension for this exercise:
/srv/apparmor-demo/override.txt r,
Load the profile into the kernel:
$ sudo apparmor_parser -r /etc/apparmor.d/usr.local.bin.apparmor-demo
Silent; -r replaces any previous version of the profile in the kernel.
The AppArmor command set used in this chapter:
| Command | Description |
|---|---|
apparmor_parser -r FILE |
(Re)load a profile from FILE into the kernel |
aa-complain PROGRAM |
Put PROGRAM's profile in complain mode: violations are logged, not blocked |
aa-enforce PROGRAM |
Put PROGRAM's profile back in enforce mode |
aa-status [PATTERN] |
Summarize loaded profiles and confined processes |
New profiles load in enforce mode, but the standard workflow for a program whose real needs you do not yet know is complain mode first: exercise the program, read what it tried to do, then decide. Switch the profile to complain and try the denied file, as john:
$ sudo aa-complain /usr/local/bin/apparmor-demo
Setting /usr/local/bin/apparmor-demo to complain mode.
$ /usr/local/bin/apparmor-demo /srv/apparmor-demo/denied.txt
restricted content
The read succeeded - complain mode permits everything - and the kernel logged the violation, which Section 26.2.3 reads. Enforce mode is where the profile means what it says:
$ sudo aa-enforce /usr/local/bin/apparmor-demo
Setting /usr/local/bin/apparmor-demo to enforce mode.
$ /usr/local/bin/apparmor-demo /srv/apparmor-demo/allowed.txt
allowed content
$ /usr/local/bin/apparmor-demo /srv/apparmor-demo/denied.txt
fopen: Permission denied
The program still runs, the permitted read still works, and the denied read fails exactly as a missing file would - except the file exists and john can read it directly; only the confined program is refused. The local override's value shows in the third case:
$ /usr/local/bin/apparmor-demo /srv/apparmor-demo/override.txt
local override content
Nothing about the packaged profile changed to grant this. The local/
include extended it, which is the pattern that survives package upgrades:
when the apparmor package updates its profile, your local file is left
alone and re-included. To revoke the extension, empty the local file and
reload, as root's shell must wrap the redirection again:
$ sudo sh -c ': > /etc/apparmor.d/local/usr.local.bin.apparmor-demo'
$ sudo apparmor_parser -r /etc/apparmor.d/usr.local.bin.apparmor-demo
Both silent. Restore the file's content with the editor - one line,
/srv/apparmor-demo/override.txt r, - and reload once more:
$ sudo apparmor_parser -r /etc/apparmor.d/usr.local.bin.apparmor-demo
Silent. With the override removed, the same read the local file had granted fails again:
$ /usr/local/bin/apparmor-demo /srv/apparmor-demo/override.txt
fopen: Permission denied
That is the whole lifecycle - extend locally, reload, revoke locally - and it is why AppArmor profiles on Debian compose with packaging instead of fighting it.
26.2.3. Investigating AppArmor Denials
Enforce-mode denials arrive as kernel audit events, and auditd (part of
the chapter's package list, configured in Section 26.6.2) writes them
to /var/log/audit/audit.log. On sec1, as john:
$ sudo grep 'apparmor="DENIED"' /var/log/audit/audit.log | tail -3
type=AVC msg=audit(1795451041.120:39012): apparmor="DENIED" operation="open" class="file" profile="/usr/local/bin/apparmor-demo" name="/srv/apparmor-demo/denied.txt" pid=90834 comm="apparmor-demo" requested_mask="r" denied_mask="r" fsuid=1001 ouid=0FSUID="john" OUID="root"
type=AVC msg=audit(1795451050.664:39097): apparmor="DENIED" operation="open" class="file" profile="/usr/local/bin/apparmor-demo" name="/srv/apparmor-demo/override.txt" pid=90946 comm="apparmor-demo" requested_mask="r" denied_mask="r" fsuid=1001 ouid=0FSUID="john" OUID="root"
type=AVC msg=audit(1795451757.370:42811): apparmor="DENIED" operation="open" class="file" profile="/usr/local/bin/apparmor-demo" name="/srv/apparmor-demo/denied.txt" pid=98058 comm="apparmor-demo" requested_mask="r" denied_mask="r" fsuid=1001 ouid=0FSUID="john" OUID="root"
Each entry is one denied operation with everything needed to act on
it: profile= names which confinement fired, name= the file the
program tried to open, requested_mask= the permission it wanted
(r here), pid= and comm= the offending process, and fsuid= the
identity the process ran as. The raw records also carry an
unprintable group-separator byte between the numeric and symbolic
identity fields (ouid=0 and FSUID="john"), which the listing
above omits for readability. An audit log accumulates across reboots
and earlier exercise rounds on the same host, so it holds more entries
than your own latest attempts - the log is append-only by design,
which is what makes it useful as evidence. The response to a denial
is exactly the
Section 26.2.2 workflow: confirm the operation is legitimate, extend the
profile through its local/ file (or fix the program), reload, and
re-test; a denial you did not expect and cannot explain is not a profile
problem but an incident-response trigger, which is what
Section 26.7 exists for.
A focused status check confirms the profile's current mode without the full listing:
$ sudo aa-status | grep apparmor-demo
/usr/local/bin/apparmor-demo
The entry appears under whichever count its mode puts it in the full listing; grepping for the profile name is the quick "is it loaded, and where" answer during profile work.
26.2.4. Systemd Sandboxing and Service Credentials
AppArmor confines one program's file operations; systemd's unit sandbox
directives confine a whole service before its first instruction runs, by
taking away filesystem visibility, kernel interfaces, and privileges the
service never needed. The demonstration service writes a state file under
its own directory and then proves, by failing, that it cannot write
anywhere else or read the administrator's home. Save this as
secure-demo.service in the workspace, for installation to
/etc/systemd/system/secure-demo.service on sec1:
[Unit]
Description=Sandboxed state writer demonstration
[Service]
Type=oneshot
DynamicUser=yes
StateDirectory=secure-demo
ExecStart=/usr/local/libexec/secure-demo.sh
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
NoNewPrivileges=yes
CapabilityBoundingSet=
RestrictAddressFamilies=AF_UNIX
LockPersonality=yes
MemoryDenyWriteExecute=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
UMask=0077
And the script it runs, saved as secure-demo.sh for installation to
/usr/local/libexec/secure-demo.sh:
#!/bin/sh
set -eu
printf 'state written at %s\n' "$(date -u +%FT%TZ)" > /var/lib/secure-demo/state
printf 'uid=%s gid=%s\n' "$(id -u)" "$(id -g)"
printf 'state: '; cat /var/lib/secure-demo/state
if printf 'forbidden\n' 2>/var/lib/secure-demo/forbidden.err >/etc/secure-demo-forbidden; then
echo 'UNEXPECTED: wrote to /etc'
exit 1
fi
printf 'write refused: '; cat /var/lib/secure-demo/forbidden.err
if cat /root/.bashrc 2>/var/lib/secure-demo/home.err >/dev/null; then
echo 'UNEXPECTED: read root home'
exit 1
fi
printf 'home refused: '; cat /var/lib/secure-demo/home.err
Install both, reload the unit definitions, and run the service. On sec1, as john:
$ sudo install -m 644 secure-demo.service /etc/systemd/system/secure-demo.service
$ sudo install -m 755 secure-demo.sh /usr/local/libexec/secure-demo.sh
$ sudo systemctl daemon-reload
$ sudo systemctl start secure-demo.service
$ systemctl show secure-demo.service -p Result --value
success
The four setup commands print nothing; the last one is the result check. A oneshot that succeeded after being denied two operations is the point, so read the journal:
$ sudo journalctl -u secure-demo.service -n 12 --no-pager
Nov 23 16:24:20 sec1 systemd[1]: secure-demo.service: Deactivated successfully.
Nov 23 16:24:20 sec1 systemd[1]: Finished secure-demo.service - Sandboxed state writer demonstration.
Nov 23 16:36:16 sec1 systemd[1]: Starting secure-demo.service - Sandboxed state writer demonstration...
Nov 23 16:36:16 sec1 secure-demo.sh[98307]: uid=62205 gid=62205
Nov 23 16:36:16 sec1 secure-demo.sh[98307]: state:
Nov 23 16:36:16 sec1 secure-demo.sh[98313]: state written at 2026-11-23T16:36:16Z
Nov 23 16:36:16 sec1 secure-demo.sh[98307]: write refused:
Nov 23 16:36:16 sec1 secure-demo.sh[98314]: /usr/local/libexec/secure-demo.sh: 6: cannot create /etc/secure-demo-forbidden: Read-only file system
Nov 23 16:36:16 sec1 secure-demo.sh[98307]: home refused:
Nov 23 16:36:16 sec1 secure-demo.sh[98316]: cat: /root/.bashrc: Permission denied
Nov 23 16:36:16 sec1 systemd[1]: secure-demo.service: Deactivated successfully.
Nov 23 16:36:16 sec1 systemd[1]: Finished secure-demo.service - Sandboxed state writer demonstration.
The uid=62205 line shows DynamicUser=yes at work: systemd allocated a
throwaway, high-numbered UID for this run, so the service owns nothing on
the host - not even an /etc/passwd entry - and the next run may get a
different one. StateDirectory=secure-demo is the one place it can
write persistently, /var/lib/secure-demo, created with the service's
own ownership. The two refusals are the sandbox directives: the attempt
to create a file in /etc died on ProtectSystem=strict, which mounts
the entire filesystem hierarchy read-only for the service, and the read
of /root/.bashrc died on ProtectHome=yes, which hides /home, /root, and
/run/user entirely. NoNewPrivileges=yes closes the
setuid escape route - a child process cannot gain privileges the unit
does not have; CapabilityBoundingSet= (empty) says the unit holds no
file capabilities at all; RestrictAddressFamilies=AF_UNIX takes away
internet sockets; the rest deny personality changes, writable-executable
memory, and kernel interface tampering. The directives and their exact
semantics are specified in systemd.exec(5); Section 8.3.2
covers writing services and choosing their users.
Confirm what the unit actually got, which is the honest check because it reads the merged effective configuration rather than the file:
$ sudo systemctl show secure-demo.service -p DynamicUser -p ProtectSystem -p ProtectHome -p NoNewPrivileges -p CapabilityBoundingSet -p StateDirectory
CapabilityBoundingSet=
DynamicUser=yes
ProtectHome=yes
ProtectSystem=strict
NoNewPrivileges=yes
StateDirectory=secure-demo
systemd's own auditor scores every unit against its full sandbox vocabulary:
$ systemd-analyze security secure-demo.service
✓ CapabilityBoundingSet=~CAP_SET(UID|GID|PCAP) Service cannot change UID/GID identities/capabilities
✓ LockPersonality= Service cannot change ABI personality
✓ ProtectKernelTunables= Service cannot alter kernel tunables (/proc/sys, …)
✓ RestrictAddressFamilies=~AF_PACKET Service cannot allocate packet sockets
✓ RestrictAddressFamilies=~AF_NETLINK Service cannot allocate netlink sockets
✓ RestrictAddressFamilies=~… Service cannot allocate exotic sockets
✓ RestrictAddressFamilies=~AF_(INET|INET6) Service cannot allocate Internet sockets
✓ CapabilityBoundingSet=~CAP_MAC_* Service cannot adjust SMACK MAC
✓ RestrictSUIDSGID= SUID/SGID file creation by service is restricted
✓ UMask= Files created by service are accessible only by service's own user by default
→ Overall exposure level for secure-demo.service: 4.0 OK 🙂
Selected output - the final checks and the verdict; the full listing scores every unit property and runs to dozens of lines.
The exposure level is a weighted score from 0.0 (best) to 10.0
(unconfined); 4.0 for a service that took every directive this exercise
set shows how far the ceiling goes - running systemd-analyze security
against the unit files of your real services and hardening the worst
first is the intended workflow. The same command explains what each
missing directive would cost, so the next hardening step is always
named.
Credentials are the one thing a sandboxed service still needs, and it
should get them the way this unit did not need to: through systemd's
credential mechanism rather than world-readable environment files. A
unit may declare LoadCredential=secret:/etc/myapp/secret or
SetCredential=secret:...; at runtime the service finds the content as
a file under the directory named in $CREDENTIALS_DIRECTORY, and with
systemd-creds encrypt --with-key=tpm2 the stored copy is sealed to the
host's TPM where firmware provides one. Both directives are documented
in systemd.exec(5); the properties that matter are that the credential
arrives as a read-only file at a location the kernel can keep out of
swap, that only the directory's name is exported to the environment -
the secret data itself never appears in /proc/PID/environ - and that
the file is readable only by the unit's own user
(User=/DynamicUser=) and the superuser, which is what keeps other
services from reading it. For services that only need an environment
file, the older pattern - a root-owned, mode-600
EnvironmentFile= - remains valid and is covered in
Section 8.3.2; whichever you choose, the file
permissions of Section 26.3.1 are what actually protect the secret.