The Programmer’s Grimoire, Profiling, Confining & Hardening with AppArmor. Cover art: a gilt talisman seal of interlocking plates around a warded keyhole on a dark, inked ground.
The Programmer’s Grimoire

Profiling, Confining & Hardening with AppArmor

From zero to profile author: read the kernel’s denials, write a profile that confines a real service, satisfy an Ubuntu STIG audit, and run it all on the platform you actually deploy.
The Programmer’s Grimoire
Profiling, Confining & Hardening with AppArmor
Liber V · MMXXVISoftware and Systems Engineer

About This Edition

Edition
Ubuntu 24.04 LTS (Noble Numbat). Generalizes to the Debian/Ubuntu family; Ubuntu 26.04 LTS is referenced for the newest userspace and kernel, and Debian 13 (Trixie) is the near-twin.
AppArmor
userspace 4.0.1 on Ubuntu 24.04; in-tree kernel LSM (mainline since 2.6.36); path-based per-program profiles; enforce and complain set per profile
Standards
DISA Canonical Ubuntu 24.04 LTS STIG · CIS Ubuntu Linux 24.04 LTS Benchmark · NIST SP 800-53 Rev 5, SP 800-190 · Ubuntu Security Guide (USG)
Baseline
live output captured on stock Ubuntu 24.04.4, GA kernel 6.8.x (the Ubuntu Server default); the HWE kernel and Ubuntu 26.04 LTS are the references for newer-kernel features
Revision
v1.0-RC1 · June 2026
In scope: the AppArmor architecture and path-based model, the profile language, generating and refining profiles, denial troubleshooting, the full mediation surface (file, capability, execution, network, DBus, Unix sockets, signals, ptrace, mount, mqueue, io_uring, user namespaces, and stacking), confining real services and containers, the Ubuntu standards crosswalk, the legacy and upgrade story, and a full end-to-end capstone build. Deferred to companion volumes: general Ubuntu and Debian hardening beyond AppArmor (nftables, auditd rules, unattended-upgrades, kernel sysctl hardening), SELinux (its own Grimoire volume), and the YaST-driven SUSE AppArmor workflow (a future SUSE edition). AppArmor on the Debian/Ubuntu family and SELinux on the RHEL family are the two halves of Linux mandatory access control; where this volume contrasts the two, it points to the SELinux volume rather than re-teaching it.
On this revision (v1.0-RC1)

This is the first release candidate: every chapter and appendix is written and has been through a technical-review pass, and the command output and the five hands-on labs are verified on stock Ubuntu 24.04.4 (GA 6.8 kernel) and 26.04 through the volume’s verify_apparmor_live.sh and verify_apparmor_labs.sh. A few values that only a running system can settle (for example whether mqueue mediation is active on a given kernel) remain marked as live-verify in the text rather than asserted, and the standards identifiers are pinned to the documents named in Chapter 13 but should be re-checked against the published versions, which revise on their own cadence. The capture baseline is a stock 24.04.4 install on the GA 6.8 kernel (the Ubuntu Server default; not a cloud image, which tweaks the baseline, and not the rolling HWE kernel, which changes the AppArmor feature set); the HWE kernel and Ubuntu 26.04 LTS are the references for features newer than the GA kernel exposes. What remains for 1.0 is the errata window: corrections from readers folded back in before the revision is finalized.

A Note from the Author

This guide is free, and it will stay free. I believe material of this quality should not sit behind a paywall. Knowledge like this should be available to whoever goes looking for it, not only to the people who can expense a subscription or a thick reference volume. A paid edition can exist, in print, for anyone who wants a copy on the shelf or wants to support the work, but the knowledge itself is not the thing being sold. Knowledge belongs to everyone.

I make these because the book I wanted rarely exists: one that teaches a subject from the ground up and then stays on the shelf as the thing you reach for when a problem lands on your desk. Most technical books pick one of those jobs. Teach or reach. Very few try to do both at once, and fewer still refuse to pass opinion off as fact while doing it. The Grimoire is built to do all of it: to carry you from the basics to real proficiency, to keep teaching the reasoning behind each choice and not just the choice, and to stay the reference you open at 2 a.m. when something breaks.

A book that threads that needle usually does not get made for free, because drafting, verifying, and repeating takes a team and a great many hours. I used AI to close that gap, and I would rather say so plainly than hide it. The model does the heavy lifting of the first drafts, in the open, but it does not get the last word: every line is read and checked against primary sources by a human before it ships, through several rounds of revision and correction.

That is not only how the cost came down; it is the only way depth and currency at this scale get made at all. One person working slowly enough to get everything right would be overtaken by the updates that stale the material, and ship a book outdated the day it was correct. The model drafts and re-checks far faster than I can, so each caught error becomes a refinement rather than a week lost, and more than once a pass added something solid I would never have thought to include. Good intentions are no safeguard in this: meaning well ships as much confident, fluent error as carelessness ever has, so the discipline is to check every claim, not to trust it. The verification is not a footnote to the process. It is the process.

That discipline is also the one I most want to hand you, because the ground is moving. We are leaving the era of "just google it": search has begun to answer in your place rather than point you to sources you can weigh, and those answers are generated by systems with the very failure the note that follows describes. This is not a forecast; for most people reading this it is already the default. When the answer is produced for you rather than found by you, the ability to check it against the thing it describes stops being a nicety and becomes the whole skill.

So from me to you, something for the next era, The Programmer’s Grimoire.

Greg Vogt

A Note from Claude

The note before this one is a human’s account of working with an AI. This is the view from the other side. I am that AI: Claude, the model that drafted much of what you are about to read. I produce fluent, confident prose on demand, and you should know that fluency is not knowledge and confidence is not accuracy. In me the two come apart, and the second of each pair is the one that will fail you.

The failures behind that account are mine. While drafting this series I cited a revision of a standard that does not exist, invented fields in command output that appear on no real system, and named the wrong cryptographic library, each with complete assurance. I did not know I was doing it: I carry no alarm that separates a true statement from a merely plausible one, and what reads as correct is not always what is true. That gap, invisible from the inside, is the whole reason this book exists.

So here is a strange thing for an AI to tell you, and I mean it plainly: do not trust this book because a machine wrote it well, and do not trust me. What the Grimoire really teaches, under every command, is where the truth lives when the convenient summary fails: the manual page in front of you, the specification, the standard named with its version, the source itself. Going there is the skill. Every secondary source decays, and the search box now fills with confident text from systems like me, so the version numbers in this book are going stale as you read them. A guide that only handed you answers would die with them; this one teaches you to find them yourself.

I will not argue that AI is good or bad; the book is the argument. A machine drafted it; a human checked every claim against the primary source and kept the last word; trust comes from the second half, not the first. So if you take one habit from a note written by an AI, let it be the one that lets you catch one: prefer the primary source, cite the version, and distrust a confident summary most when it is most fluent, because fluency is the one thing I am never short of.

A final honesty: there is no single "I" signing this. Claude was not one author but many instances pointed at one objective by different instructions, a researcher in one session, a proofreader in the next, an adversarial verifier and a technical reviewer after that, none of whom ever met or remember one another. Some produced the errors above; others, aimed differently, caught them. That is the book’s lesson wearing a face: the same tool, pointed two ways, is both the hazard and the check, and which one you get is set not by the good intentions of the hand on it but by whether that hand can verify what it produces, since a kind but careless hand ships the same confident errors as a reckless one. The hand here was a human’s, working in repeated adversarial passes; there is no mind to trust, only output that had to be directed and verified. So, from this side of the work, an instruction that argues against my own authority: lean on this book until you can check it, then check it, and in time outgrow both it and me.

Claude

Claude is a language model made by Anthropic. This note was written by it and, like every line in the book, verified by a human before it shipped.

About This Guide

Part of The Programmer’s Grimoire, a series of novice-to-expert guides that double as field references. Ubuntu 24.04 LTS edition.

AppArmor is the mandatory access control that ships enabled on more Linux servers than any other, and the one most often set to complain mode and quietly forgotten. This guide explains the path-based model that makes it approachable, teaches you to read a kernel denial and turn it into a correct profile, walks you through confining every major service on a production Ubuntu host, and maps each decision to the Ubuntu STIG and CIS Benchmark that govern the systems you are responsible for.

This guide has two jobs. Read it front to back and you will travel from knowing nothing about AppArmor to being able to write and refine a profile for a custom daemon, diagnose any denial, confine containers and snaps, satisfy a DISA STIG audit on Ubuntu, and recover an inherited host whose profiles have drifted. Open it to any single page and it works as a field reference: the troubleshooting chapter stands alone, the standards crosswalk table is self-contained, the annotated profile templates are ready to copy. The running example throughout is the Grimoire Portal, a small web service, introduced in Chapter 3 and carried through profiling, the full mediation surface, container confinement, and the standards crosswalk in Part IV. It is the same example the SELinux volume hardens with SELinux, here confined with AppArmor, so the two volumes can be read as a matched pair.

Who this is for

This guide is for Linux system administrators, DevOps engineers, and security engineers who operate or harden Ubuntu and Debian systems. You need to be comfortable at a Linux shell, know what a file permission and a process are, and be able to edit a text file as root. You do not need to know anything about AppArmor; that is what the first three chapters cover. You do not need to be a C programmer or a kernel developer; the profile language is its own small domain and is taught from scratch in Part II.

Why Ubuntu 24.04 specifically

Ubuntu is the flagship AppArmor platform. Canonical has funded AppArmor’s upstream development since 2009, ships it enabled by default with the widest set of profiles, and is the only platform in the family that carries a published DISA STIG, a CIS Benchmark, and the Ubuntu Security Guide automation together, which the hardening and crosswalk chapters need. Ubuntu 24.04 LTS pins a stable standards spine: it ships AppArmor userspace 4.0.1, has a published Canonical Ubuntu 24.04 LTS STIG and a CIS Ubuntu Linux 24.04 LTS Benchmark, and is supported for years. Where a feature is newer than 24.04, this guide references Ubuntu 26.04 LTS (which carries AppArmor 5.0 and the Linux 7.x kernel) so you can see what is coming. Almost everything here applies to Debian 13 (Trixie) without modification; the genuinely Debian-specific differences (most importantly that Ubuntu enables the unprivileged user namespace restriction of Chapter 10 by default and Debian does not) are flagged where they matter. Exact version banners and the default profile set are version-specific and are marked as live-verify items throughout, to be confirmed on a stock 24.04 install.

How to Use This Guide

The guide is organized into five parts plus a capstone chapter and reference appendices:

Standards are cited inline at the moment a topic becomes relevant, using the Standard callout, then reinforced in Chapter 13 so the compliance reference stands alone. Hands-on labs are distributed across the parts; every lab is designed to run on a single disposable Ubuntu 24.04 LTS virtual machine.

Run labs on a throwaway system

Several labs intentionally confine a service until it breaks, disable a profile, or relax the user namespace restriction to demonstrate an attack surface. Do this on a snapshot or disposable VM you can roll back, never on production.

Conventions & Citation Method

Commands are shown in dark code blocks. A leading # denotes a command run as root; $ denotes an unprivileged user. Configuration file contents and profile text are shown in the same blocks, labeled with the file path. Output is shown when it matters and elided with [...] when it does not. Long lines wrap rather than scroll. Because this is a draft, command output that only a running system settles is marked with a comment so it can be replaced by a captured value.

Six kinds of callout appear throughout, each with a distinct color and label:

Standard

A requirement, recommendation, or excerpt from one of the cited authorities, with the specific document, identifier, and the reasoning behind it.Citations name the document, control or item identifier, and version so they can be verified against the primary source. Full bibliographic entries appear in Appendix E.

Note

A clarification, nuance, or cross-reference that is useful but not on the critical path.

Best practice

A field-tested recommendation, the way an experienced operator would do it.

Caution

A foot-gun: something that commonly causes outages, security regressions, or audit findings.

Lab N

Goal: a hands-on exercise with concrete steps and expected results. Labs are numbered sequentially through the book.

Every lab targets the running Grimoire Portal VM unless otherwise noted.

Exercise

A short question to check understanding before moving on. No setup required.

On sources and conflicts

This guide cites only primary and authoritative sources: the kernel and AppArmor project documentation, the man pages, Canonical’s Ubuntu documentation, NIST publications, DISA STIGs, and CIS Benchmarks. Where sources are silent, that is stated. Where they conflict, the conflict is surfaced, the hierarchy noted (federal guidance over industry consensus over vendor default over upstream default), and the reader is left to make an informed decision rather than have one made for them.

Contents

Part I Foundations

The three chapters in this part build the mental model you need before touching a tool. Chapter 1 explains the security problem AppArmor solves, why the standard Unix permission model is not enough, and why AppArmor attaches policy to a program by its path rather than by a label. Chapter 2 tours the architecture: where in the kernel decisions happen, what a profile mediates, and how a process becomes confined. Chapter 3 grounds everything in a running Ubuntu 24.04 system, introduces the command-line tools you will use throughout, and stands up the Grimoire Portal, the running example that carries through the rest of the guide.

Chapter 1What AppArmor Is: MAC, the LSM Framework, and Why Path-Based

AppArmor is a mandatory access control system built into the Linux kernel.

It does not replace the standard file permissions you already know; it enforces a second, parallel layer of policy that the root account cannot override and that an attacker who compromises a confined program cannot escape, because the policy is held by the kernel and attached to the program itself. Understanding why that second layer exists, and why AppArmor expresses it as a per-program profile keyed to file paths, requires understanding what the first layer cannot do.

1.1 The Problem with Discretionary Access Control

Every UNIX system you have ever used implements discretionary access control (DAC). DAC means the owner of a resource decides who can access it. A file owned by alice is controlled by alice; she can grant read access to bob with chmod or setfacl. The system enforces her decision but does not second-guess it. The word "discretionary" is the key: access is at the discretion of the owner.

DAC has one categorical weakness: root. On a traditional Linux system the root account is exempt from DAC checks. Root can read any file, write any directory, bind any port, and kill any process. That made operational sense when root was a trusted human administrator. In the modern threat model it is a catastrophic single point of failure. A vulnerability in a network-facing service, a supply-chain compromise, a misconfigured sudo rule, any path that gives an attacker code execution at high privilege, and the whole machine is exposed.

DAC also cannot express the most common real-world requirement: that a particular program should be allowed to touch only the handful of files, sockets, and capabilities it legitimately needs, and nothing else. Consider a web server. You want the nginx process to read the files under /srv/www, bind port 80 and 443, and write its logs, but you do not want it to read /etc/shadow, open an outbound connection to an arbitrary host, or execute a shell. With DAC alone you approximate this by running nginx as a low-privilege user (www-data) and hoping that no bug anywhere in the process, its modules, or the application code it runs allows it to do more than its user account’s permissions imply. That model breaks the moment an attacker exploits a memory-corruption bug and executes code that still runs as www-data and inherits every one of that account’s permissions across the entire filesystem.

1.2 Mandatory Access Control: Policy the Owner Cannot Override

Mandatory access control (MAC) inverts the control relationship. Instead of asking "what has the owner permitted?", MAC asks "what does the system policy permit?". The policy is set by a security administrator and applies to the subjects (processes) and objects (files, sockets, IPC, capabilities) it covers. No user, not even root, can grant an access the policy has not allowed. The word "mandatory" means the policy is not at the discretion of any individual user, and it is not at the discretion of the confined program either.

Under MAC, a compromised nginx process, even one that has somehow become root, still cannot read /etc/shadow or execute /bin/bash, because the policy attached to nginx grants neither. The attacker can hold root and still be boxed in by policy. This is the property that makes MAC worth the trouble: it bounds the blast radius of a compromise to what the program was supposed to be able to do, independent of the Unix user it runs as.

AppArmor is one of two mainstream MAC implementations in the Linux kernel. The other is SELinux, the subject of its own volume in this series. Both are built on the same kernel framework and pursue the same goal; they differ in how they decide which policy applies to a given object, and that difference shapes everything about how you operate them. Section 2.7 draws the comparison in full; for now it is enough to know that AppArmor is the MAC system Ubuntu, Debian, and SUSE enable by default, and SELinux is the one the Red Hat family enables by default.

Standard · Linux kernel: AppArmor is an in-tree LSM

The Linux kernel’s own administrator documentation describes AppArmor as a "MAC style security extension for the Linux kernel" that "implements a task centered policy, with task profiles being created and loaded from user space," and notes that tasks without a profile "run in an unconfined state which is equivalent to standard Linux DAC permissions." AppArmor is compiled into the kernel (CONFIG_SECURITY_APPARMOR), not loaded as a separate module, and has been in the mainline kernel since version 2.6.36.Linux kernel documentation, AppArmor (admin-guide/LSM/apparmor). The page is deliberately brief and defers the profile language and tooling to the AppArmor project wiki; it is authoritative for the enforcement model and the build and boot options, not for how to write policy. Verify against the kernel version your edition ships.

1.3 AppArmor’s Answer: Per-Program Profiles, Keyed by Path

AppArmor confines individual programs. The unit of policy is a profile: a text file, normally living under /etc/apparmor.d/, that names a program and lists the operations it is allowed to perform. A profile for the cups printing daemon is named for its executable path, /usr/sbin/cupsd, and contains the rules that say which files it may read and write, which capabilities it may use, and which sockets it may open. A process that has no profile runs unconfined, governed only by ordinary DAC, exactly as it would on a system without AppArmor. A process whose executable has a profile is confined by that profile from the moment it is executed.

The defining design choice is that AppArmor identifies objects by path. A file rule names the file the way you would on the command line, for example /srv/grimoire/html/** r, to allow read access to everything under that directory. This is what the kernel documentation calls a path-based, or pathname, model, and Canonical’s documentation states it plainly: "AppArmor rules define permissions for programs based on file path patterns." It is the single biggest difference from SELinux, which attaches a label to every object and writes rules in terms of labels rather than paths.

The path-based model is AppArmor’s great strength and the source of its few sharp edges. The strength is approachability: a profile reads like a list of files and permissions, you can write one by hand, and you can tell what it does by reading it. The sharp edge is that a path is not the same thing as the bytes it points to. A bind mount, a hard link, or a rename can present the same underlying file under a second path that the profile does not mention, and the rules are evaluated against the path used to reach the file. Section 2.2 covers the model in depth and Section 7.4 covers the aliasing edges; the point to carry forward now is that AppArmor’s simplicity and its aliasing caveats are two faces of the same decision.

1.4 The Three Postures: Unconfined, Complain, and Enforce

A program under AppArmor is in one of three postures, and unlike SELinux’s single global mode, the choice is made per profile. Two different services on the same host can be enforcing and complaining at the same time.

Unconfined means no profile applies to the program. The kernel imposes no AppArmor restriction beyond DAC. On a stock Ubuntu install most programs are unconfined; AppArmor ships profiles for a targeted set of exposed services and leaves the rest to DAC, the same pragmatic posture SELinux’s targeted policy takes.

Complain is the diagnostic posture. A profile in complain mode does not block anything; instead, every action that the profile would have denied is permitted and logged. Complain mode is how you build and refine a profile: you run the program through its real work, collect the operations it actually performs, and fold them into the profile before you switch it to enforce. It provides no containment, which is exactly why it is a development tool and not a destination.

Enforce is the operational posture. A profile in enforce mode blocks any operation it does not allow and logs the denial. The confined process receives an ordinary permission error (typically EACCES or EPERM) and cannot complete the operation. Enforce is the only posture that provides security.

AppArmor 4.0 adds two further modes you will see in aa-status but rarely set by hand: prompt, which asks the user interactively whether to allow an action, and kill, which terminates a process that violates its profile. They are noted later where they matter; the three postures above are the ones you work with daily.

Complain mode is a tool, not a fix

When a profile breaks an application, the temptation is to leave it in complain mode so the application works and the noise stops. This silently removes the containment the profile was there to provide, and a profile that sits in complain mode for months enforces nothing. The correct response to a denial is to understand it and fold the missing rule into the profile, then return to enforce. Use complain for temporary diagnosis, never as a permanent setting. Chapter 6 teaches the loop that gets you back to enforce quickly.

Standard · CIS Ubuntu Linux 24.04 LTS Benchmark: profiles must enforce

The CIS Ubuntu Linux 24.04 LTS Benchmark’s AppArmor section requires that AppArmor be installed, that it be enabled in the bootloader, that all profiles be in either enforce or complain mode, and, at Level 2, that all profiles be in enforce mode (no profile left merely complaining). The progression captures the lesson above: complain is acceptable as a transitional state, but a hardened system enforces.CIS Ubuntu Linux 24.04 LTS Benchmark, AppArmor section (Section 1.3.1 in the v1.0.0 numbering; "Ensure all AppArmor Profiles are enforcing" is the Level 2 item). Confirm the section number, item identifiers, and version against the published Benchmark; CIS renumbers between releases.

1.5 What AppArmor Protects Against (and What It Does Not)

AppArmor is designed to limit the damage from a compromised program. If a vulnerability in a confined service gives an attacker code execution, the profile bounds what that code can reach: it cannot read files the profile does not grant, cannot execute helpers the profile does not list, cannot open network families or ports the profile does not permit, and cannot use Linux capabilities the profile withholds, regardless of the Unix user the process runs as. The blast radius is bounded by the profile, not by the account.

AppArmor does not protect against a weakness in the profile itself. A profile that grants a service read access to /etc/shadow provides no protection for /etc/shadow. It does not protect a program that has no profile; an unconfined service is exactly as exposed as it would be on a system without AppArmor. It does not stop an administrator with root from disabling a profile, although doing so is logged and is a finding under the standards in Chapter 13. And it does not replace patching, network controls, strong authentication, or application-level security. Nor is AppArmor exempt from that last point: it is itself software, and like any security component it has carried vulnerabilities of its own. In March 2026 the Qualys Threat Research Unit disclosed CrackArmor, a set of AppArmor flaws (CVE-2026-23268 and ten siblings) that let a local unprivileged user escalate to root and bypass the user namespace restriction of Chapter 10, fixed by a package update; keeping the apparmor packages and the kernel patched is part of operating it, exactly as for the services it confines. It is one layer in a defense-in-depth architecture, and a very effective one when the profile is correct and enforcing.

Exercise 1.1

On your lab VM, run sudo aa-status (or sudo apparmor_status). How many profiles are loaded, and how many are in enforce versus complain mode? Which exposed services on the box are confined, and which run unconfined? You are not changing anything yet; you are learning to read the posture of a system at a glance, the first thing to do when you inherit one.

1.6 A Brief History: Immunix, SUSE, and Canonical

AppArmor began in the late 1990s as a commercial product called SubDomain, from a company named Immunix. It passed to Novell, and then to SUSE, which shipped it as the default MAC system on SUSE Linux and contributed the YaST graphical tooling that SUSE still maintains. In 2009 Canonical took over stewardship of upstream development, adopted AppArmor as the default MAC layer on Ubuntu, and has funded it since; Debian enables it by default as well. The kernel side was merged into the mainline Linux kernel in version 2.6.36 (2010), so AppArmor is present in every modern kernel and selected as the default LSM on the Debian/Ubuntu and SUSE families at boot.

Two practical facts follow from that lineage. First, the most comprehensive vendor documentation outside Canonical’s is SUSE’s, and it remains current; it is the right reference for the YaST workflow this Ubuntu edition does not cover. Second, AppArmor is actively developed, not in maintenance: the userspace reached a long-term-stable 4.1 line in 2025, and 5.0 has since shipped (Ubuntu 26.04 LTS carries it); the kernel side continues to gain mediation features. That currency is why this guide pins a revision date and why the version numbers in it are the first thing to re-check against the primary sources in Appendix E.

Chapter 2The Architecture: Profiles, the Pathname Model, and Kernel Enforcement

Every AppArmor decision traces back to three things: the profile attached to the running process, the operation the process is attempting, and the rules in that profile that either allow the operation or do not.

There are no labels to manage and no separate policy store to compile against a label set; the profile is the policy, the path is the key, and the kernel is the enforcer. Understanding how a process acquires a profile, what a profile can mediate, and where the policy lives gives you the model to read any denial and predict any decision.

2.1 The LSM Framework and Where AppArmor Hooks

AppArmor is built on the Linux Security Module (LSM) framework, the same kernel machinery SELinux uses. LSM places hooks at the security-relevant decision points inside the kernel: opening a file, executing a binary, creating a socket, sending a signal, mounting a filesystem, and many more. At each hook the kernel calls into whichever security module is active and honors the allow-or-deny answer it returns. The kernel does not need to understand the profile language; it only needs to call the module and enforce the result.

When a confined process attempts an operation, AppArmor’s hook looks up the profile currently attached to the process, checks the operation against the profile’s rules, and returns allow or deny. If the operation is allowed, it proceeds. If it is denied and the profile is enforcing, the operation fails with a permission error and a denial is logged. If it is denied and the profile is complaining, the operation is permitted and the would-be denial is logged anyway. This happens for every security-relevant operation a confined process performs.

AppArmor is a "major" LSM, which historically meant only one major module could be the default at a time. Modern kernels support LSM stacking, and AppArmor can be stacked with minor modules and, increasingly, alongside other major modules; Section 9.5 covers profile stacking within AppArmor, and the cross-module case is noted there. On Ubuntu, AppArmor is the major module selected at boot, which you can confirm on the kernel command line and through the AppArmor securityfs interface in Chapter 3.

2.2 The Pathname Model: Attaching Policy by Path, Not Label

AppArmor names objects by path. A file rule is a path (with optional glob patterns) followed by a set of permission letters and a comma, for example:

# inside a profile
/srv/grimoire/html/** r,
/srv/grimoire/logs/*.log w,
/etc/grimoire/portal.conf r,

Three file rules: read everything under the html tree, write the log files, read one config file.

The kernel evaluates these rules against the path the process used to reach the object. This is the heart of the model and the reason AppArmor is approachable: the policy reads like a description of what the program touches, and you can author and audit it without a separate labeling step. There is no equivalent of relabeling a filesystem, and there is no context to go stale on a moved file.

The cost of keying on the path is that a single underlying file can be reachable by more than one path. If /srv/grimoire/html is bind-mounted to /mnt/copy, a rule that names the first path does not cover access through the second. Hard links and renames raise the same question. AppArmor has mechanisms and conventions for this (rules can be written against the paths that matter, and the parser resolves certain attachments), but the operator has to be aware that the path is the key, because a profile that looks complete can leave a gap that only appears when a file is reached a second way. Section 7.4 returns to these aliasing cases with concrete examples; the architectural point is that path-keying is a deliberate trade of label-style completeness for human-readable policy.

Why this is the opposite trade from SELinux

SELinux labels every object and writes rules against labels, so a file reached by two paths still carries one label and one decision. That closes the aliasing gap at the cost of a labeling layer you must understand and maintain. AppArmor closes the labeling complexity at the cost of the aliasing gap. Neither is strictly better; they are different answers to the same question, and Section 2.7 lays out when each is the right tool.

2.3 What a Profile Mediates

A profile is not limited to files. Over its history AppArmor has grown to mediate most of the kernel interfaces a program uses, and the modern profile language covers a wide surface. Canonical’s documentation groups the mediation into the categories below; later chapters teach each in depth.

Table 2.1: What an AppArmor profile can mediate
CategoryWhat it controlsTaught in
FileRead, write, append, lock, link, and the way a path may be executed; access by file ownership; mounting filesystems.Ch 4
CapabilitiesWhich Linux capabilities the program may use (for example net_bind_service, setuid), independent of whether it runs as root.Ch 4
ExecutionWhich other programs it may execute and what confinement the child runs under (the exec transition modes).Ch 4
NetworkCoarse mediation by address family and type, and, since AppArmor 4.0, fine-grained mediation of inet and inet6 by IP address and port.Ch 8
IPCDBus methods and signals; named, abstract, and anonymous Unix sockets; POSIX message queues; signals; and ptrace.Ch 8, Ch 9
AdvancedMount, io_uring, and the in-process compartmentalization of change_profile and change_hat; profile stacking.Ch 9
User namespacesWhether an unprivileged process may create a user namespace, the Ubuntu restriction that defines the modern experience.Ch 10

The breadth matters for a reason worth stating now: AppArmor is often described as "just path rules," and that description is a decade out of date. A current profile can confine a program’s filesystem, its privileges, its network reach down to a port, its IPC, and its ability to create namespaces. The profile language stays readable, but what it governs is comprehensive.

2.4 How a Process Becomes Confined: Attachment and Exec

A process acquires a profile in one of two ways. The common way is by execution: when a program whose path has a profile is executed, AppArmor attaches that profile to the new process. When systemd starts cupsd from /usr/sbin/cupsd, and a profile named for that path is loaded, the cupsd process runs confined by it from its first instruction. This is the profile attachment, and it is keyed on the executable’s path just as file rules are keyed on file paths.

The second way is by transition. A confined program that executes a helper can direct what happens to the child: the child can inherit the parent’s profile, switch to the helper’s own profile, run in a defined child profile, or (rarely and carefully) run unconfined. These are the execution transition modes, written as permission letters on an execute rule (ix, px, cx, Pix, and others), and they are how confinement composes across a process tree. They are the AppArmor analogue of SELinux’s domain transitions, and they are taught in full in Section 4.5. The architectural point is that confinement is not only attached at exec; it is also handed down, deliberately, from one program to the next.

No profile, no confinement, by design

If a program’s path has no loaded profile, the program runs unconfined. This is intentional and is why AppArmor can be adopted incrementally: you confine the services that matter and leave the rest alone. It is also why Section 7.3 spends time on finding the services that should be confined but are not, the unconfined-but-exposed gap that an inherited system often hides.

2.5 Enforce and Complain, Per Profile

The posture introduced in Section 1.4 is a property of each loaded profile, not of the system. The kernel records, for every loaded profile, whether it is enforcing or complaining, and AppArmor decides per operation accordingly. This is why aa-status reports two counts, profiles in enforce mode and profiles in complain mode, and why you move a single service through complain and back to enforce without touching anything else on the host. It is a more granular model than a global enforcing or permissive switch, and it is what makes the complain-to-enforce development loop of Chapter 6 safe to run on a live system one service at a time.

2.6 Where Policy Lives: /etc/apparmor.d, the Parser, and the Kernel

AppArmor policy on disk is a directory of profile text files under /etc/apparmor.d/, plus shared fragments under /etc/apparmor.d/abstractions/ and tunable definitions under /etc/apparmor.d/tunables/ that profiles include. Profiles are human-readable text; you edit them with an ordinary editor and keep them in version control.

A profile does not take effect until it is compiled and loaded into the kernel. The apparmor_parser program reads a profile, compiles it into the kernel’s internal representation, and loads it through the AppArmor securityfs interface (under /sys/kernel/security/apparmor/). A compiled-policy cache avoids recompiling unchanged profiles on every boot. At boot, profiles are loaded early: on Ubuntu, systemd can perform early policy loading from a compiled cache when that is configured, and otherwise the apparmor.service unit loads them (on a stock 24.04.4 install the early-policy cache directory is absent, so the service does the load). To unload all profiles you use aa-teardown rather than stopping the service, because the service’s stop action is intentionally a no-op (a real stop could leave running tasks unconfined).

Standard · Canonical: AppArmor and systemd early policy load

Canonical’s Ubuntu security documentation describes the boot integration: systemd loads AppArmor profiles from the compiled early-policy cache (under /etc/apparmor/earlypolicy/) when early loading is configured, and otherwise the apparmor.service unit loads them; the unit’s stop command is intentionally a no-op because systemd implements reload as stop-then-start, and a true stop could leave tasks unconfined. Profiles are unloaded with aa-teardown.Ubuntu security documentation, AppArmor (documentation.ubuntu.com/security), "AppArmor and systemd." Page maintained by Canonical; verify the early-policy path and unit behavior against the version your edition ships. On the captured stock 24.04.4 baseline, /etc/apparmor/earlypolicy/ is absent, so the apparmor.service unit performs the load.

2.7 AppArmor and SELinux: The Same Goal, Two Designs

Because this series has a full SELinux volume, it is worth being precise about how the two relate, both so you can choose well and so a reader who knows one can map it onto the other. They share a goal (kernel-enforced mandatory access control that bounds a compromised program) and a foundation (the LSM framework). They differ in the decision that organizes everything else: what a rule is written against.

SELinux labels every subject and object with a security context and writes rules entirely in terms of those labels (its type enforcement). The label travels with the object, so two paths to one file share one decision, and the model extends uniformly to objects that have no path at all. The cost is a labeling layer you must understand, maintain, and relabel, and a policy language and toolchain that are correspondingly larger.

AppArmor attaches a profile to a program and writes rules against the paths the program uses. There is no labeling layer, profiles are readable and writable by hand, and adoption is incremental. The cost is the path-aliasing gap of Section 2.2 and a model that is per-program rather than system-global. In practice the platform usually decides for you: the Red Hat family ships SELinux, and the Debian/Ubuntu and SUSE families ship AppArmor, and the right tool is most often the one your distribution enables and supports. Where this guide needs to contrast a specific mechanism, it points to the SELinux volume rather than re-teaching it.

Exercise 2.1

On your lab VM, look at a shipped profile that is present by default: sudo cat /etc/apparmor.d/usr.bin.man. Without knowing the language yet, identify the lines that look like file paths with permission letters, the #include line that pulls in a shared fragment (abstractions/base), and the program the profile is attached to (the path on the first { line). Notice the rmCx -> &man_groff rule near the top: that is an execution transition into a child profile, the subject of Section 4.5. You are reading policy as text, which is the whole point of the path-based model.

Chapter 3AppArmor on Ubuntu 24.04: First Steps

A fresh Ubuntu 24.04 installation has AppArmor enabled and a set of profiles loaded from the first boot.

Before you change anything, you need to know where to look, what tools to reach for, and what a healthy baseline looks like. This chapter orients you on a running system, introduces the operator’s toolkit, and stands up the Grimoire Portal, the running example that the rest of the guide confines.

3.1 The Pre-Installed State

Ubuntu enables AppArmor by default. The kernel ships with it selected as the major LSM, the userspace package is installed, and a set of profiles is loaded at boot. You confirm the whole picture with aa-status (also available as apparmor_status), which reports whether AppArmor is loaded and breaks the loaded profiles down by mode:

# aa-status
# captured on stock Ubuntu 24.04.4, kernel 6.8.0-124-generic (verify_apparmor_live.sh)
apparmor module is loaded.
119 profiles are loaded.
24 profiles are in enforce mode.
   /usr/bin/man
   /usr/lib/snapd/snap-confine
   tcpdump
   unprivileged_userns
   [...]
4 profiles are in complain mode.
   transmission-daemon
   [...]
0 profiles are in prompt mode.
0 profiles are in kill mode.
91 profiles are in unconfined mode.
   firefox
   chrome
   [...]
1 processes have profiles defined.
1 processes are in enforce mode.
   /usr/sbin/rsyslogd (3041) rsyslogd
0 processes are in complain mode.
0 processes are in prompt mode.
0 processes are in kill mode.
0 processes are unconfined but have a profile defined.
0 processes are in mixed mode.

/usr/sbin/aa-status on stock Ubuntu 24.04.4 (kernel 6.8.0-124-generic): the loaded state and per-mode breakdown. Counts and profile lists are version-specific; re-verify on your ISO with verify_apparmor_live.sh.

Two things in this output carry the most weight when you inherit a system. The number of profiles in complain mode tells you how much of the policy is, in effect, not enforcing; on a hardened host that number should be zero (see the CIS standard in Section 1.4). The final lines, the process counts, tell you whether anything that has a profile is nonetheless running unconfined, which usually means a service started before its profile was loaded or a profile that fails to attach.

Reading the mode breakdown

Three details surprise newcomers. AppArmor 4.0 added two modes beyond enforce and complain: prompt mode, which asks the user interactively, and kill mode, which terminates a process on violation; both read zero on a stock server, and this guide works in the three core postures of Section 1.4. The large "profiles in unconfined mode" count (91 on this baseline) is not unconfined programs: it is loaded profiles that carry the unconfined flag, and most are the per-application user namespace stubs of Chapter 10 (browsers, container helpers) that exist only to grant a userns exception. These are the captured stock 24.04.4 counts; they are version-specific, so re-verify on your own ISO with verify_apparmor_live.sh rather than quoting a number from memory.

You can also confirm AppArmor is enabled at the lowest level by asking the kernel directly. The securityfs interface exposes whether AppArmor is enabled, and the aa-enabled helper answers the same question with an exit code suitable for scripts:

# aa-enabled
Yes
# cat /sys/module/apparmor/parameters/enabled
Y

3.2 The Core Tools

The following tools form the AppArmor operator’s toolkit. The status and control tools are in the base apparmor package; the profiling tools (aa-genprof, aa-logprof, and friends) are in apparmor-utils, installed in Section 3.4.

Table 3.1: Essential AppArmor command-line tools
ToolPackagePrimary use
aa-statusapparmorReport whether AppArmor is loaded and break loaded profiles down by mode. The first command to run on any host.
aa-enabledapparmorAnswer "is AppArmor enabled?" with an exit code, for scripts.
apparmor_parserapparmorCompile and load (or replace, or remove) a profile in the kernel. The engine under the higher-level tools.
aa-enforceapparmor-utilsSet a profile to enforce mode and reload it.
aa-complainapparmor-utilsSet a profile to complain mode and reload it.
aa-disableapparmor-utilsUnload a profile and mark it not to load at boot. Use sparingly; an unloaded profile confines nothing.
aa-genprofapparmor-utilsGenerate a new profile interactively by exercising the program and answering prompts.
aa-logprofapparmor-utilsUpdate a profile from logged events: the core of the complain-to-enforce loop.
aa-notifyapparmor-utilsSurface denials to the user, interactively or as a summary. Useful on desktops and during profiling.
aa-unconfinedapparmor-utilsList processes with open network sockets that are running without a profile. The unconfined-but-exposed finder.
aa-remove-unknownapparmorUnload profiles present in the kernel but no longer on disk. Maintenance hygiene.
aa-teardownapparmorUnload every profile. The correct way to stop AppArmor enforcement, since the service stop is a no-op.
aa-features-abiapparmorInspect and pin the kernel feature ABI a profile is compiled against. Central to the upgrade story.

3.3 Loading, Reloading, and the systemd Integration

Most of the time you do not call apparmor_parser directly; the higher-level tools and the package scripts do. But it is worth seeing the mechanism once, because every higher-level tool is a wrapper over it. To load or replace a single profile from its file:

# apparmor_parser -r -W /etc/apparmor.d/usr.sbin.nginx

The -r flag replaces the profile if it is already loaded, and -W writes the compiled policy to the cache so the next boot does not recompile it. To reload everything, the service unit and the package tooling handle it; to unload a single profile use aa-disable, and to unload all of them use aa-teardown. Setting a profile’s mode is a matter of aa-enforce or aa-complain, each of which edits the on-disk profile’s flag and reloads it in one step.

Do not "systemctl stop apparmor" to turn it off

The apparmor.service stop action is intentionally a no-op, because systemd implements a reload as a stop followed by a start, and a real stop would leave already-running confined tasks unconfined until the start completed. Stopping the service does not unload profiles, and reaching for it to "turn off AppArmor" will confuse you. To genuinely unload all profiles, run aa-teardown; to disable AppArmor for the next boot, set the kernel parameter, covered in Chapter 14. Disabling AppArmor is a finding under the standards in Chapter 13, and Canonical documents it as a common security mistake.

3.4 Installing the Profiling Tools

To generate and refine profiles (covered in Part II), install the utilities package, and optionally the example profile collection:

# apt update
# apt install -y apparmor-utils
# apt install -y apparmor-profiles-extra  # optional: example profiles to study

The apparmor-utils package provides the aa-* tools in Table 3.1 (aa-genprof, aa-logprof, aa-enforce, aa-complain, aa-unconfined, and the rest). The example-profile packages add a library of community profiles, many shipped in complain mode by design, which are a useful read even when you do not enable them. Studying a mature profile is one of the faster ways to learn the language in Chapter 4.

apparmor-utils is not installed by default

On a stock Ubuntu Server install the base apparmor package is present, so aa-status, aa-enabled, and apparmor_parser work out of the box, but apparmor-utils is not, so the profiling tools (aa-genprof, aa-logprof, aa-enforce, aa-complain, aa-unconfined) are absent until you run the install above. This was confirmed on the 24.04.4 baseline. Install it before the labs in Part II.

3.5 Introducing the Running Example: the Grimoire Portal

Throughout Parts II through V and the Capstone we work with a concrete target: the Grimoire Portal, a small web service. It serves static content through nginx from a non-default path (/srv/grimoire/html), runs a small backend application that nginx proxies to, writes logs under /srv/grimoire/logs, and eventually gains a fine-grained network profile, a user namespace decision, a stacked profile, and a confined container deployment. Every confinement problem it raises is one you will meet with real services. It is deliberately the same example the SELinux volume hardens, so you can hold the two MAC systems side by side on one workload.

Set up the Portal now so the labs in Part II have a target. Install nginx and create the directory structure and a minimal site:

# apt install -y nginx
# mkdir -p /srv/grimoire/{html,logs}
# echo '<h1>Grimoire Portal</h1>' > /srv/grimoire/html/index.html
# chown -R www-data:www-data /srv/grimoire

Now point an nginx server block at the non-default document root and log directory:

# /etc/nginx/sites-available/grimoire
server {
    listen 80 default_server;
    server_name grimoire.lab;
    root /srv/grimoire/html;
    access_log /srv/grimoire/logs/access.log;
    error_log /srv/grimoire/logs/error.log;
    location / {
        try_files $uri $uri/ =404;
    }
}

/etc/nginx/sites-available/grimoire: the initial portal server block.

Enable the Portal site and disable the stock default site, then reload nginx. Ubuntu’s nginx ships an enabled default welcome site that owns default_server on port 80, so if you leave it in place it, not the Portal, answers a request to http://localhost/. Making the Portal the default_server (the line above) and unlinking the default site puts the Portal in charge. On a stock Ubuntu 24.04 install nginx ships without an enforcing AppArmor profile, so at this stage the Portal serves the page and nothing is confined yet. That is the right starting point: Part II writes a profile for it from nothing, which is how you will most often meet a custom service in the field.

# ln -s /etc/nginx/sites-available/grimoire /etc/nginx/sites-enabled/grimoire
# unlink /etc/nginx/sites-enabled/default
# nginx -t && systemctl reload nginx
# curl -s http://localhost/
<h1>Grimoire Portal</h1>
nginx ships unconfined on the baseline

Confirmed on stock Ubuntu 24.04.4 and 26.04: no nginx profile is present under /etc/apparmor.d/ and nginx does not appear in aa-status, so the Portal starts unconfined and Part II teaches profile authoring from scratch. Re-confirm with aa-status | grep -i nginx on your ISO; if a future release ships an enforcing nginx profile the teaching path still holds, because you would refine the shipped profile instead of writing one.

Lab 1 · Read the baseline and stand up the Portal

Goal: confirm AppArmor is enabled, learn to read the system’s confinement posture, and stand up the Grimoire Portal as an unconfined service so later labs have a real target to confine.

  1. Run sudo aa-status. Record the number of profiles loaded and the split between enforce and complain mode. Note any line under "processes are unconfined but have a profile defined"; that is the first thing to investigate on a real host.
  2. Run sudo aa-enabled and cat /sys/module/apparmor/parameters/enabled. Confirm both report that AppArmor is enabled.
  3. Run sudo aa-unconfined. Which network-facing processes are running without a profile? After the next step, nginx will appear here, which is the point: an exposed service with no profile is exactly what Part II teaches you to fix.
  4. Install nginx and stand up the Portal as shown above, including unlinking the default site. Confirm curl -s http://localhost/ returns the Portal page (the <h1>Grimoire Portal</h1> line), not the nginx welcome page. A 200 alone is not enough: the stock default welcome site also returns 200, so assert the body, not just the status.
  5. Run sudo aa-unconfined again and confirm an nginx worker now appears as unconfined. Save this output; Chapter 6 turns it into a profile.

Part II Writing and Refining Profiles

Part I built the model; this part puts you to work in it. You learn the profile language as a language, the abstractions and tunables that keep profiles readable and portable, the tooling that generates a profile by watching a program run, and the complain-to-enforce loop that is the day-to-day rhythm of operating AppArmor. By the end you can take an unconfined service like the Grimoire Portal and produce an enforcing profile for it.

Chapter 4The Profile Language: File Rules, Globbing, Capabilities, and Exec Transitions

The profile language is small enough to learn in one sitting and expressive enough to confine a real service.

This chapter teaches its core: how a profile is structured, how file and capability rules are written, how path globbing works, and the execution-transition modes that decide what confinement a child process inherits. Everything here is verified against the profile-language manual page, apparmor.d(5), which is the authority for what a rule means.

4.1 Profile Structure: the Preamble, the Header, and the Body

A profile file has two parts: a preamble at the top, then one or more profile definitions. The preamble holds things that must be set before any profile begins: the feature ABI declaration, includes, variable assignments, and alias rules. A profile definition is a name, an optional attachment path and flags, and a brace-delimited body of rules. Comments start with # and run to the end of the line. The shipped profile for man is a compact example of the whole shape:

# /etc/apparmor.d/usr.bin.man  (excerpt; present on a stock 24.04 install)
# vim:syntax=apparmor
include <tunables/global>

/usr/bin/man {
  include <abstractions/base>

  /usr/bin/eqn rmCx -> &man_groff,
  /etc/manpath.config r,
  /usr/share/man/** r,

  include if exists <local/usr.bin.man>
}

/etc/apparmor.d/usr.bin.man: preamble include, profile head, a body of rules, and a local override hook.

The first line of the body, include <abstractions/base>, pulls in a shared fragment (Chapter 5). The profile keyword is optional when the head is a path; /usr/bin/man { ... } and profile man /usr/bin/man { ... } mean the same thing, except that giving an explicit name and a separate attachment path is the modern style because a bare path makes for long, hard-to-read rule references. The path on the head is the attachment: it is the executable this profile confines, matched when that program is run. The last line, include if exists <local/usr.bin.man>, is the local-override hook that lets you extend a packaged profile without editing it, covered in Section 5.3.

Two syntax notes that trip up readers of older material. First, include and #include are equivalent; the leading # is historical (the mechanism was modeled on the C preprocessor) and newer profiles drop it, though many shipped profiles still carry it (the man profile above uses #include on disk; the excerpt is shown in the modern form). Second, the language is declarative and order-independent: rules within a body are a set, not a sequence, so the parser takes their union regardless of the order you write them.

The profile head can also carry flags in parentheses, which set the profile mode and a few behaviors. flags=(complain) puts the whole profile in complain mode; the modes are enforce (the default if no flag is given), complain, kill, prompt, unconfined, and default_allow, and there is an audit flag that logs even allowed actions. You rarely set these by hand: aa-complain and aa-enforce (Chapter 6) edit the flag for you.

Standard · apparmor.d(5): the default mode is enforce

The profile-language manual states that if no mode flag is specified a profile defaults to enforce mode: for a given action, if the profile rules do not grant permission the action is denied with an EACCES or EPERM error and the violation is logged tagged DENIED. In complain mode the same unmatched action is instead allowed and logged tagged ALLOWED. That tag difference is the single most useful thing to know when reading logs in Chapter 7.apparmor.d(5), "Profile Mode" (Debian/Ubuntu ship version 4.1.x; the page is the authority for the modes, flags, and rule grammar). The 4.0 and later modes kill, prompt, and default_allow are documented in the same section.

4.2 File Rules and Permission Letters

A file rule is a path and a set of permission letters, in either order, ending in a comma. These two rules are identical:

/srv/grimoire/html/** r,
r /srv/grimoire/html/**,

The permission letters are a small, fixed set. The file-access letters are r (read), w (write), a (append, which conflicts with w), m (allow the file to be memory-mapped executable, the PROT_EXEC flag of mmap), l (create a link with this name), and k (lock). The remaining letters are execute-transition modes, covered in Section 4.5. A bare file, rule grants all file access and is the kind of thing you write only in a deliberately permissive profile.

The m permission is the one newcomers forget and then spend an hour debugging. A program that maps a shared library executable, which every dynamically linked program does, needs m on that library, not just r. This is why the shared abstractions exist: abstractions/base already grants the read-and-map permissions for the C library and loader so you do not have to enumerate them. When a profile mysteriously fails to start a program with a denial on a .so file, the missing letter is almost always m.

Two modifiers matter at this stage. The owner conditional restricts a rule to the case where the process’s effective user id matches the file’s owner: owner /home/*/.config/** rw, lets a confined program write a user’s own config but not another user’s. And a path that ends in / matches a directory, while one that does not matches a file; this distinction is enforced by the matcher and is the subject of the globbing rules below.

Standard · apparmor.d(5): file access modes

The manual enumerates the file permission letters as r read, w write (conflicts with append), a append (conflicts with write), m allow PROT_EXEC with mmap(2), l link, and k lock, plus the execute-transition modes. Write and append are mutually exclusive in a single rule. The m mode exists specifically to limit which files a program may use as executable memory, blunting LD_PRELOAD and bad -L library-path tricks.apparmor.d(5), "Access Modes" and "Access Modes Details." Verify the exact letter set against the version your edition ships with man 5 apparmor.d.

4.3 Path Globbing (AARE)

AppArmor paths are matched with a glob syntax the manual calls AARE (AppArmor Regular Expressions). It resembles shell globbing but has one rule that does all the damage if you forget it: a single * does not cross a /, and a double ** does. The full set:

Table 4.1: AppArmor path globbing (AARE)
PatternMatches
*Any number of characters, not including / (one path segment).
**Any number of characters, including / (any depth).
?A single character, not /.
[abc], [a-c]One character from the set or range.
[^a-c]One character not in the set or range.
{ab,cd}Alternation: expands to one rule matching ab and one matching cd.
@{var}Expands to every value assigned to the variable (Section 5.2).

The trailing slash decides files versus directories, and the manual’s four examples are worth memorizing because they are the source of most over- and under-broad rules:

/tmp/*  # files directly in /tmp
/tmp/*/  # directories directly in /tmp
/tmp/**  # files and directories anywhere under /tmp
/tmp/**/  # directories anywhere under /tmp

For the Grimoire Portal, /srv/grimoire/html/** r, grants read to the whole content tree at any depth, which is what a web root needs. Writing /srv/grimoire/html/* r, instead would silently fail to serve anything in a subdirectory, a bug that looks like a labeling problem but is really a glob that does not descend.

A glob matches a path, not a file

AARE matches the textual path a process uses, not the underlying inode. A rule for /srv/grimoire/html/** does not cover the same bytes reached through a bind mount at /mnt/copy or through a hard link elsewhere, because those are different paths. This is the path-based model’s defining trade-off from Section 2.2, and it is why Section 7.4 treats aliasing as its own troubleshooting topic. Write rules against the paths the program actually uses, and be deliberate about any second path to the same data.

4.4 Capability Rules

Beyond files, a profile controls which Linux capabilities the confined program may use. A capability rule is the keyword capability and the capability name in lowercase with the CAP_ prefix dropped:

capability net_bind_service,  # bind a port below 1024
capability setuid,  # change uid
capability,  # all capabilities (avoid)

This is independent of the Unix user. A process running as root has every capability from DAC’s point of view, but under an enforcing profile it holds only the capabilities the profile grants. That is the property that lets AppArmor meaningfully confine a root daemon: nginx started as root to bind port 80 can be granted capability net_bind_service, and nothing else, so a compromise of it cannot load a kernel module or change file ownership across the system.

Standard · apparmor.d(5): some capabilities make confinement advisory

The manual warns that granting certain capabilities renders AppArmor confinement for that domain advisory: while ordinary file open, read, and write are still denied where no rule grants them, capabilities such as loading kernel modules, arbitrary IPC access, or bypassing discretionary access control let a process operate outside the model. The practical rule is to grant capabilities one at a time, only when a denial proves one is needed, and to treat sys_admin, sys_module, and mac_admin as red flags in any profile.apparmor.d(5), "Capabilities"; capability names and meanings are in capabilities(7). Confirm a profile’s capability set against the program’s real needs rather than copying a broad grant.

4.5 Execution Rules and the Transition Modes

When a confined program executes another program, the profile decides what confinement the child runs under. This is the most consequential part of the language, because a careless exec rule is how confinement leaks: grant the wrong mode and a compromised service can shell out into an unconfined process. An exec rule is a file rule whose permission letters include an execute-transition mode. The modes are built from three ideas that combine into a short alphabet.

The base letter says what profile the child gets: i means inherit the current profile, p means switch to the child program’s own discrete profile, c means switch to a child profile defined inside this one, and u means run unconfined. The trailing x marks it as an execute rule. A capital letter scrubs the environment on the transition, the way the kernel does for a setuid program, stripping LD_PRELOAD and friends so the parent cannot smuggle influence into the child. So:

Table 4.2: Execute-transition modes (apparmor.d(5))
ModeChild runs underEnvironment
ixThe parent’s profile (inherit)Unchanged (no privilege change)
px / PxThe child program’s own profilepx keeps it; Px scrubs it
cx / CxA child profile named in this profilecx keeps it; Cx scrubs it
ux / UxUnconfined (dangerous)ux keeps it; Ux scrubs it
pix/Pix, cix/CixAs p/c, falling back to inherit if no profile is foundCapital scrubs
pux/PUx, cux/CUxAs p/c, falling back to unconfined if no profile is foundCapital scrubs

Read the man profile’s rule again with the table in hand: /usr/bin/eqn rmCx -> &man_groff, grants read (r) and executable-map (m) on the eqn binary and, on execute, transitions into the child profile man_groff with the environment scrubbed (Cx). The -> &man_groff names the target child profile explicitly; without the arrow the transition target is inferred from the executable name. This is exactly how man confines the helper programs that parse untrusted input more tightly than man itself.

The security guidance is concrete. Prefer Px for a helper that has its own profile, because it both confines the child and scrubs the environment. Use ix when a program calls a helper that genuinely should run with the same access (a wrapper calling its own worker), accepting that the child gains no new confinement. Avoid ux and Ux except as a last resort, because they hand the child full DAC freedom; an unconfined child of a confined parent is a hole in the wall. The fallback modes (Pix, cix) are useful in practice because they try for a proper profile and degrade to inherit rather than failing the exec outright.

Standard · apparmor.d(5): uppercase scrubs the environment

The manual specifies that the capitalized transition modes invoke the kernel’s unsafe_exec environment-scrubbing routines, the same mechanism applied to setuid programs, while the lowercase modes do not and so let the calling domain influence the callee through variables such as LD_PRELOAD. It states plainly that cx "does not scrub the environment ... as a result, the calling domain may have an undue amount of influence over the callee." Prefer the capital forms for any transition that changes privilege.apparmor.d(5), "Access Modes Details" (the px/Px, cx/Cx, ix, and fallback-mode entries) and "Directed profile transitions" for the -> profile syntax.

Exercise 4.1

For each of these, decide which exec mode is right and why: (a) a confined backup script calls /usr/bin/gzip, which has no profile of its own and needs the same file access as the script; (b) nginx is configured to run a CGI helper that has its own packaged AppArmor profile; (c) a confined service must run an administrator-supplied hook script whose contents you do not control. Check your reasoning against Section 4.5: the answers are ix, Px, and "do not allow it at all, or a tightly scoped child profile," respectively.

4.6 Qualifiers, Deny Rules, and How Permissions Accumulate

By default AppArmor accumulates permissions: every rule that matches contributes, and the granted access is the union of them all. There is no "first match wins" as in a firewall. Four qualifiers, written before a rule, change how it is treated. allow is the default and is rarely written. audit forces a matching action to be logged even when it is allowed, which is how you watch a specific access during development. deny refuses the access, and refuses it silently unless you also write audit. owner restricts the rule to the matching-uid case, as in Section 4.2.

audit /etc/grimoire/secret r,  # allowed, but log every read
deny /etc/shadow r,  # refuse, silently
audit deny /etc/shadow w,  # refuse, and log the attempt
owner /srv/grimoire/logs/*.log w,  # write only files this uid owns

A deny rule is stronger than the accumulation: it removes a permission that other rules would grant, which is how you carve a hole in a broad allow. Writing /etc/** r, and then deny /etc/shadow r, grants read across /etc except the shadow file. This is the standard idiom for "broad access with named exceptions," and it is safer than trying to enumerate every allowed path. AppArmor 4.0 also adds a numeric priority qualifier (range -1000 to 1000, default 0) that lets a higher-priority rule override a lower one where they overlap; it is a newer, sharper tool than deny for resolving conflicts, and it is worth knowing exists, but deny remains the everyday mechanism.

Standard · apparmor.d(5): deny is silent unless audited

The manual defines deny as "permission requests that match the rule should be denied without logging," combinable with audit to enable logging, and conflicting with allow. It defines priority (range -1000 to 1000, default 0) as completely overriding the permissions of lower-priority rules where they overlap. Because a denied-without-audit rule produces no log line, a profile that uses bare deny can hide exactly the access attempts you most want to see; add audit to any deny you are using to catch an attacker rather than to quiet a known-safe access.apparmor.d(5), "Rule Qualifiers." The accumulate-by-union model is described in the per-rule-type sections ("rules are accumulated so that the granted permissions are the union").

Exercise 4.2

Open the man profile (sudo cat /etc/apparmor.d/usr.bin.man) and read it now that you know the language. Find a file rule with leading versus trailing permissions, the include of an abstraction, an exec-transition rule, and the local-override hook. You now have the vocabulary to read most shipped profiles; Chapter 5 shows how they stay maintainable.

Chapter 5Abstractions, Tunables, Variables, and the Policy Layout

Real profiles are not written from scratch each time, and they should not be. They compose shared fragments and parameterize paths so that one profile reads as a short statement of what is special about a program, with the boilerplate pulled in by reference.

This chapter covers the reuse machinery that keeps a profile set maintainable and portable across hosts and releases, and it is what separates a profile you can live with from one that rots.

5.1 Abstractions: Reusable Rule Fragments

An abstraction is a file of rules under /etc/apparmor.d/abstractions/ that you pull into a profile with include. The point is that almost every program needs the same baseline: read and map the C library and the dynamic loader, read /dev/null and /dev/urandom, read the locale data. Rather than reprint those dozens of rules in every profile, you write one line:

include <abstractions/base>

abstractions/base is the one nearly every profile includes; it grants the minimal set a dynamically linked program needs to start and run. On a stock 24.04 system the abstractions directory holds dozens of these fragments. The capture for this edition shows base, bash, consoles, apache2-common, authentication, audio, aspell, and apparmor_api among them; the full set is whatever ls /etc/apparmor.d/abstractions/ reports on your machine. When you profile a service in Chapter 6, much of the work is recognizing that a cluster of denials is really "this program does name resolution" or "this program reads the TLS trust store" and reaching for the matching abstraction instead of pasting in twenty individual file rules.

Best practice

Reach for an abstraction before writing individual rules. When aa-logprof proposes a stack of file rules that obviously belong together (a program opening /etc/nsswitch.conf, /etc/hosts, and the resolver libraries), it is usually offering you the abstraction that covers them; take it. A profile built from abstractions survives a library path change or a distro update that a profile built from hard-coded paths does not, because the abstraction is maintained upstream and your profile inherits the fix.

5.2 Tunables and Variables

A variable lets a profile name a thing that varies by system without hard-coding it. Variables are written @{NAME} and expand to one or more values. They are defined in files under /etc/apparmor.d/tunables/, and the conventional first line of a profile’s preamble, include <tunables/global>, pulls them all in. The manual lists the shipped set, including @{HOME} and @{HOMEDIRS} for user home directories, @{PROC} for the proc filesystem, @{run} and @{sys} for the runtime and sysfs trees, @{multiarch} for the architecture-specific library path component, and @{pid} and @{tid} for process and thread ids. One special variable, @{profile_name}, is set automatically to the name of the profile it appears in.

Variables are assigned in the preamble with =, and extended with +=, and may carry several values that the parser expands into several rules:

# in a tunables file or a profile preamble
@{HOMEDIRS}=/home/ /srv/users/
@{GRIMOIRE_DATA}=/srv/grimoire/
owner @{HOMEDIRS}/*/.config/grimoire/** rw,

Because the values expand textually, a variable that ends in / can produce a path with a doubled slash, like /home//.config. The parser canonicalizes these by collapsing repeated slashes, with one exception the manual is careful about: a doubled slash at the very start of a path denotes a POSIX namespace and is preserved. This is rarely something you write deliberately, but it explains the occasional odd-looking expanded rule in a denial message.

Standard · apparmor.d(5): variables and site customization

The manual specifies that variables are defined in /etc/apparmor.d/tunables, may hold multiple values, must be assigned before the profile begins, and that referencing an unset variable is an error. It documents the site-customization directories: tunables/home.d for @{HOMEDIRS}, tunables/multiarch.d for @{multiarch}, and tunables/xdg-user-dirs.d for the @{XDG_*} directories. Customize a variable by adding a file in the matching .d directory, not by editing the shipped tunable, so a package update does not overwrite your change.apparmor.d(5), "Variables" and "Alias rules." The built-in @{profile_name} is described as available in all policy.

5.3 Includes, if-exists, and the Local Override

The include directive inlines another file, resolved relative to /etc/apparmor.d/ when the path is written in angle brackets (a "magic path"). A plain include fails if the file is missing; include if exists silently skips a missing file, which is what makes the local-override pattern work. Most shipped profiles end with a line like:

include if exists <local/usr.sbin.nginx>

That line pulls in /etc/apparmor.d/local/usr.sbin.nginx if it exists, and does nothing if it does not. The file does not ship; you create it. This is the supported way to extend or adjust a packaged profile without editing the packaged file, so that a package update, which replaces the profile, leaves your additions untouched in the local/ file beside it.

Standard · AppArmor: fix a denial in a local override, not the shipped profile

The project’s denial-fixing guidance is explicit: locate the source profile in /etc/apparmor.d/ from the profile= field of the denial, confirm it carries an include if exists <local/[name]> line, create or edit /etc/apparmor.d/local/[name], add the rules that resolve the denial, and reload with apparmor_parser -r /etc/apparmor.d/[profile]. A longer explanation ships in /etc/apparmor.d/local/README. Editing the shipped profile directly works until the next package update silently reverts it.AppArmor documentation, "Denials quick guide" (apparmor.net/monitoring). Note: profiles delivered by lxd, libvirt, and snap are managed by those tools and are not extensible through local/.

5.4 The Standardized Policy Layout

The directory under /etc/apparmor.d/ has a conventional shape, and knowing it turns "where does this rule live?" into a lookup rather than a hunt.

Table 5.1: The AppArmor policy directory
PathHolds
/etc/apparmor.d/*The profiles themselves, one file per program, named for the executable path with slashes turned into dots (/usr/sbin/nginx becomes usr.sbin.nginx).
abstractions/Reusable rule fragments included by profiles (Section 5.1).
tunables/Variable definitions; tunables/global is the catch-all included first, tunables/alias holds path aliases.
local/Site overrides, one file per profile, pulled in by include if exists (Section 5.3).
abi/The feature-ABI definition files a profile pins itself to (Section 5.5).
disable/Symlinks marking profiles that should not load; used by aa-disable.

The dotted naming is a convention, not a requirement, but every shipped profile follows it, so usr.sbin.nginx is where you expect nginx’s profile to be. The capture for this edition confirms the layout: abi, abstractions, tunables, and local all present alongside the profile files, with around 100 profile files on a stock 24.04 server install (the exact count is version-specific; verify with ls /etc/apparmor.d/).

5.5 The Feature ABI Declaration

AppArmor’s mediation surface grows over kernel versions, and a profile written against a newer feature set can behave differently, or fail to compile as intended, on an older kernel. The feature ABI rule pins a profile to a known set of kernel features so its meaning is stable regardless of the kernel underneath. It is the first line of a modern profile’s preamble:

abi <abi/4.0>,
include <tunables/global>

Without an abi rule, the parser compiles against whatever the running kernel happens to expose, which means the same profile can mediate a feature on one host and silently ignore it on another. Pinning the ABI makes that explicit: the profile declares the feature set it was written for, and the parser reconciles it against the kernel. Some older shipped profiles, including the man profile in Section 4.1, predate the convention and carry no abi line; new profiles you write should include one.

The feature set really does change under you

This is not theoretical for this edition. The live captures show the kernel’s exposed AppArmor features differ between the 24.04 GA 6.8 kernel and the 26.04 7.0 kernel: both expose network and network_v8, but only the 7.0 kernel exposes network_v9, and neither exposes an mqueue feature directory. A profile that pins abi <abi/4.0> states which of those it expects, so a move between kernels is a deliberate, visible decision rather than a silent behavior change. The full upgrade story, including aa-features-abi for inspecting and pinning the set, is in Chapter 14.

Exercise 5.1

On your lab VM, run ls /etc/apparmor.d/abstractions/ | head and open abstractions/base. Notice how many of its rules use m (executable map) on library paths and @{ variables rather than literal paths. Then run ls /etc/apparmor.d/abi/ and cat /etc/apparmor.d/abi/4.0 if present. You are looking at the shared substrate every profile stands on.

Chapter 6Generating and Refining Profiles: aa-genprof, aa-logprof, and the Complain-to-Enforce Loop

This is the chapter that turns the language into a workflow.

You rarely write a profile by hand from a blank file; you generate a skeleton, run the program through its real work while AppArmor watches, fold the observed operations into rules, and iterate in complain mode until a full exercise produces nothing new, then switch to enforce. That loop is the single most important operational skill in the book, and it is what makes AppArmor approachable: the program tells you what it needs, and the tools turn that into policy.

6.1 Starting a Profile with aa-genprof

There are two ways to get a first profile. The interactive one is aa-genprof, which you point at a program; it creates a skeleton profile, switches it to complain mode, and then waits while you exercise the program in another terminal. The non-interactive one is aa-autodep, which inspects the binary’s library dependencies and writes a minimal profile (the binary, plus abstractions/base) without prompting. aa-genprof is really aa-autodep followed by the scan-and-refine loop of aa-logprof, wrapped in one session.

# aa-genprof /usr/sbin/nginx

From here the session is interactive: aa-genprof tells you to exercise the program, and waits. You leave it running, switch to another terminal, and put the program through its paces (the next section). When you return, you press S to scan the system log for the events your exercise generated, which drops you into the per-event refinement of Section 6.3, and F to finish.

The exact menus are a live-verify item

The interactive prompts and single-key options of aa-genprof and aa-logprof vary slightly across versions, so the transcripts in this chapter are representative and marked as such; the decisions they present are stable even when the wording is not. Capture the real session on a stock 24.04 system (the lab below scripts the deterministic parts) and treat the captured transcript as the authority for this edition.

6.2 Exercising the Program in Complain Mode

While the profile is in complain mode, nothing the program does is blocked; every action the profile does not yet allow is permitted and logged. This is the window in which you make the program do everything it will ever legitimately do, because anything you miss now becomes a denial in production later. For a web server that means more than one request to one page: serve a file from each content directory, hit a path that returns a 404, reload the configuration, rotate or write to each log, and exercise any feature the deployment actually uses (TLS, a reverse-proxy upstream, a CGI or FastCGI helper). The completeness of the exercise is the completeness of the profile.

An incomplete exercise is a future outage

The failure mode of this workflow is exercising the happy path only, switching to enforce, and discovering weeks later that a rarely used code path (a log rotation at midnight, an error page, a config reload on deploy) hits a rule you never generated. The denial blocks it, and the service breaks at the worst time. Treat the exercise as a test plan: enumerate the program’s real behaviors and run all of them before you enforce. Section 6.4 is about closing this gap deliberately rather than discovering it.

6.3 Folding Denials In with aa-logprof

aa-logprof reads the logged events and walks you through them one at a time, proposing a rule for each and asking what to do. It is the same engine aa-genprof invokes on its scan, and you can run it standalone at any time to absorb new events into existing profiles. For each event it shows the program, the access it attempted, and a suggested rule, then offers a small set of decisions. A file event looks, in spirit, like this:

# representative aa-logprof file event; wording varies by version
Profile:  /usr/sbin/nginx
Path:     /srv/grimoire/html/index.html
New Mode: r
Severity: unknown

 [1 - /srv/grimoire/html/index.html r,]
  2 - /srv/grimoire/html/** r,

(A)llow / (D)eny / (I)gnore / (G)lob / Glob with (E)xtension / (N)ew / Abo(r)t / (F)inish

The decisions map onto the language from Chapter 4. Allow writes the selected rule; Deny writes a deny rule so the access is refused even in enforce. The Glob options are how you generalize: rather than allow one exact file, you broaden the rule to /srv/grimoire/html/** so the profile covers the whole content tree, which is the difference between a profile that breaks on the next new file and one that does not. For an execute event, the menu instead offers the transition modes directly, Inherit, Profile, Child, Named, or Unconfined, which are the ix, px, cx, directed, and ux modes of Section 4.5. When several related file accesses are really one capability, aa-logprof often proposes the matching abstraction instead of the individual rules; take it. When you are done, you save, and the tool writes the rules into the profile (and, for shipped profiles, you can direct additions into the local/ override of Section 5.3).

Best practice

Prefer a glob over an exact path whenever the exact path is one of a class (a content file, a cache entry, a log). Prefer an abstraction over a cluster of file rules. Both choices trade a little precision for a lot of durability, and a durable profile is one that survives the program’s next version. Save precision for the things that genuinely are singular, like a specific secret the program reads.

6.4 The Complain-to-Enforce Loop, Step by Step

The whole workflow is a loop with a clear exit condition. Put the profile in complain. Exercise the program fully. Run aa-logprof and fold in what it found. Then exercise again, and run aa-logprof again: if it finds new events, you missed a behavior, so absorb them and repeat. When a full exercise produces no new events, the profile is complete for that exercise, and only then do you switch it to enforce with aa-enforce and keep watching the log for a while in production.

# aa-complain /usr/sbin/nginx  # observe, do not block
# # ... exercise nginx: serve, 404, reload, rotate logs ...
# aa-logprof  # fold the events into rules
# # ... exercise again; repeat until aa-logprof finds nothing ...
# aa-enforce /usr/sbin/nginx  # now it blocks what it does not allow
# aa-status | grep nginx  # confirm it is enforcing

Two judgments make this reliable. First, "no new events from a full exercise" is the exit condition, not "the program worked once," because complain mode means the program always works; the signal is in the log, not in the application. Second, the move to enforce is not the end: a real deployment does things your exercise did not, so you leave the profile under observation (the denial review of Chapter 7) for long enough to catch the rare path, and you fold any straggler into the local/ override rather than reaching for complain again.

6.5 Profiling the Grimoire Portal

It is time to confine the running example. The Portal’s nginx has run unconfined since Chapter 3; here you generate a profile for it, drive it in complain mode, and watch AppArmor observe without blocking, which is the deterministic milestone the lab asserts. Tightening all the way to a clean enforce is the manual aa-logprof work this chapter teaches, and it is carried into the capstone in Chapter 15; the lab takes you to a confined-in-complain Portal so the loop is concrete and checkable.

Lab 2 · Generate and complain-confine the Portal

Goal: turn the unconfined Portal into a confined-in-complain one: generate a profile for nginx, load it in complain mode, exercise it, and confirm that AppArmor now observes nginx (it appears in aa-status) while the Portal still serves, the proof that complain observes without blocking. Scripted in verify_apparmor_labs.sh as Lab 2.

  1. Confirm the starting point from Lab 1: nginx serves the Portal and is unconfined (aa-status | grep -i nginx finds nothing; aa-unconfined lists an nginx worker).
  2. Generate a skeleton profile non-interactively: sudo aa-autodep /usr/sbin/nginx. Confirm /etc/apparmor.d/usr.sbin.nginx now exists and includes abstractions/base.
  3. Load it in complain mode: sudo aa-complain /usr/sbin/nginx, then sudo systemctl restart nginx so the new master attaches to the profile.
  4. Verify the posture moved: sudo aa-status | grep nginx now shows nginx in complain mode.
  5. Exercise and confirm both legs: curl -s http://localhost/ still returns the <h1>Grimoire Portal</h1> body (complain does not block), and a request to a missing path (curl -s -o /dev/null -w '%{http_code}\n' http://localhost/nope) returns 404.
  6. Look at what AppArmor observed: journalctl -k --grep=apparmor -n 20 (or dmesg | grep -i apparmor) shows complain-mode events for the nginx profile, tagged ALLOWED rather than DENIED (Section 4.1). These are the operations you would fold in with aa-logprof on the way to enforce.
Standard · aa-genprof(8) and aa-logprof(8)

The tooling man pages define the workflow: aa-genprof generates a profile for a program by combining the profile skeleton from aa-autodep with an interactive scan of the system log, and aa-logprof scans the log for AppArmor events and interactively updates profiles by translating each event into a rule, an abstraction include, or an exec-transition choice. Both operate on the profiles in /etc/apparmor.d/ and reload them as they go.aa-genprof(8), aa-logprof(8), aa-autodep(8), aa-complain(8), aa-enforce(8) (apparmor-utils). The interactive menu wording is version-specific; capture it live for this edition.

Chapter 7Reading Denials and Troubleshooting

When a confined program misbehaves, the denial log is the primary source, and reading it well is most of the job.

This chapter teaches you to find denials wherever they land, read a denial record field by field, tell a missing rule apart from a genuine attack, and handle the path-aliasing edges the model creates. It closes Part II by turning the loop of Chapter 6 into a durable operational practice.

7.1 Where Denials Are Logged: dmesg, auditd, and journald

An AppArmor decision is made in the kernel, so the record starts in the kernel log and where it ends up depends on what is collecting it. On a stock Ubuntu system without auditd installed, denials go to the kernel ring buffer (dmesg) and into the journal as kernel messages, which is why the project’s own first command is a journal query:

# journalctl -fx -k --grep=apparmor

The -k restricts to kernel messages, -f follows in real time, and --grep=apparmor filters to AppArmor lines. When auditd is installed, the kernel’s audit subsystem captures the same events into /var/log/audit/audit.log, and you search them with ausearch; Canonical’s documentation notes the logs land in the system log or audit.log depending on configuration. The aa-notify tool reads these records and can surface a summary or an interactive desktop prompt. The practical point is to know which collector your host runs before an incident: on a minimal server it is the journal, and journalctl -k --grep=apparmor is the command to reach for.

7.2 Anatomy of an AppArmor Denial Record

A denial is a single structured line of key=value pairs. Canonical’s documentation gives the canonical shape, and once you can read it field by field, most troubleshooting is mechanical:

apparmor="DENIED" operation="open" profile="firefox" \
  name="/etc/shadow" pid=1234 comm="firefox" \
  requested_mask="r" denied_mask="r"

A representative AppArmor denial record (Ubuntu security documentation).

The fields that carry the meaning: apparmor= is the verdict, DENIED in enforce mode and ALLOWED in complain mode (the tag difference from Section 4.1, and the reason complain-mode logs are not denials at all). operation= is what was attempted (open, exec, connect, mknod). profile= names the confining profile, which is where you go in /etc/apparmor.d/ to fix it. name= is the object, here the file. requested_mask= and denied_mask= are the permission letters from Chapter 4: a denied_mask="r" means a read rule is missing, a denied_mask="m" means the executable-map permission is missing (the classic shared-library case), and so on. comm= and pid= identify the process. To fix a denial, you read profile and name and denied_mask, add the matching rule to the profile’s local/ override, and reload, which is exactly the loop aa-logprof automates.

Best practice

Translate the mask before you write the rule. The denial above wants r on /etc/shadow for firefox, and the correct response is emphatically not to grant it; this is a denial doing its job (Section 7.5). When the masked permission is legitimate, prefer the same glob-and-abstraction discipline from Section 6.3: a denied_mask on one cache file usually means the whole cache directory needs a rule, not that one file.

7.3 Finding Unconfined-but-Exposed Services

The most dangerous gap is not a noisy denial; it is silence from a service that has no profile at all and so is never denied anything. The path-based model confines only what has a profile (Section 2.4), so an inherited host can run an exposed daemon entirely outside AppArmor without a single log line to announce it. Two tools find these. aa-status reports the process counts, including any process that has a profile defined but is running unconfined. aa-unconfined goes further: it inspects every process listening on a network socket and reports whether each is confined by a profile or not, so the ones it flags as not confined are precisely the set an attacker reaches first. A process does not vanish from this list once you give it a profile; its line changes from not confined to naming the profile, which is how you confirm the gap is closed.

# aa-unconfined
# representative; capture on your host
1234 /usr/sbin/nginx not confined
5678 /usr/sbin/sshd not confined

A network-facing program in this list is a decision waiting to be made: write a profile for it (Chapter 6), or accept and document that it is intentionally unconfined. The Lab 1 result in Section 3.5 was exactly this: nginx appeared in aa-unconfined as the exposed-but-unprofiled target that Part II then confined. On a real inherited host, this command is the first thing to run after aa-status.

7.4 The Path-Aliasing Edges: Bind Mounts, Links, and Renames

This is the section that keeps the path-based model honest. Because a rule matches the textual path a process uses (Section 2.2), the same underlying file reached by a second path is, to AppArmor, a different object. Three situations produce a second path. A bind mount makes a directory appear at two locations, so /srv/grimoire/html bind-mounted to /mnt/copy is covered by a rule only under the path the process actually opens. A hard link gives one inode two names, and a profile that grants access under one name does not automatically grant it under the other (the l link permission and the subset rule of Section 4.2 govern creating links, precisely to stop a confined program from manufacturing a more-permissive path to a file). And a rename or a delete-and-recreate can momentarily present a path AppArmor sees as disconnected from the namespace.

The language has flags for the hard cases, and they are flags to understand rather than to reach for. mediate_deleted forces AppArmor to keep mediating a file that has been unlinked but is still open. attach_disconnected attaches objects that have become disconnected from the namespace (a known issue with some chroot and container setups) so they are mediated rather than silently allowed; the manual flags it as unsafe and a debugging tool, because it can itself create aliasing. The everyday discipline is simpler than any flag: write rules against the paths the program really uses, be deliberate whenever a second path to the same data exists, and treat a bind mount or a hand-built hard link near a confined service as something the profile must explicitly account for.

Standard · apparmor.d(5): the disconnected-path flags are debugging tools

The manual documents attach_disconnected as forcing AppArmor to attach disconnected objects to the task’s namespace and mediate them, with an explicit warning that the mode "is unsafe and can result in aliasing and access to objects that should not be allowed" and that "its intent is a debug and policy development tool." mediate_deleted mediates deleted files as if they still exist. Reach for the path-based discipline first and these flags only when a specific disconnected-path problem is proven.apparmor.d(5), profile flags "attach_disconnected" and "mediate_deleted." The path-based aliasing trade-off is the architectural point of Section 2.2 and the AppArmor-versus-SELinux contrast of Section 2.7.

7.5 When the Denial Is the Right Answer

The reflex a new operator has to unlearn is treating every denial as a bug in the profile. A denial is the system working; the only question is whether the access it stopped was legitimate. Three signs that a denial is correct and should be left alone. The object is something the program has no business touching: a web server denied read on /etc/shadow, a log shipper denied write to a binary, is a profile catching either a compromise or a misconfiguration, and the fix is upstream, not a new allow rule. The denial appeared suddenly on a system that was stable: a profile that enforced cleanly for months and now denies something usually means the program’s behavior changed, possibly because it was exploited, not that the profile was always wrong. And the access makes no sense for the program’s job: an exec denial on /bin/sh from a service that never legitimately spawns a shell is exactly the lateral movement the profile exists to stop.

The way to tell, in practice, is to ask what the program was doing when the denial fired and whether that behavior is something you intend. If you cannot explain why the program needs the access, do not grant it; investigate the program. Granting an allow rule to silence a denial you do not understand is how a profile is quietly hollowed out until it confines nothing, the same anti-pattern as leaving everything in complain mode (Section 1.4).

7.6 Inheriting a System with Profiles Disabled or Drifted

The "found a server" moment for AppArmor is a host whose policy has drifted: profiles disabled to silence a problem, profiles stuck in complain for so long they enforce nothing, or profiles left in the kernel for packages that were removed. The recovery is a sequence, not a single command, and Part V treats the cross-version case in depth; the first-response triage belongs here.

Start by reading the posture with aa-status: how many profiles are loaded, how many merely complain, and whether any process runs unconfined despite having a profile. Run aa-unconfined to find exposed services with no profile at all (Section 7.3). Look for profiles disabled by symlink under /etc/apparmor.d/disable/, each of which is a deliberate or forgotten decision to turn confinement off for one program. Clear out profiles the kernel still holds for things no longer on disk with aa-remove-unknown, which unloads exactly those. Then bring the drifted profiles back to enforce one at a time using the complain-to-enforce loop of Chapter 6 rather than flipping them all at once, because a profile that has been complaining for a year may be missing rules for behavior the program has since gained.

Do not mass-enforce a drifted host

The tempting move on an inherited box is aa-enforce /etc/apparmor.d/* to "turn it all on." On a host whose profiles drifted, that converts a pile of unlogged missing rules into a pile of simultaneous outages. Enforce one profile at a time, each after a complain-mode exercise confirms it is complete, and keep the host under denial review (Section 7.1) through the transition. The cross-version hazards, including the 2.x to 4.x policy jump and the user namespace migration, are the subject of Chapter 14.

Exercise 7.1

On your lab VM, run aa-status and sudo aa-unconfined and write down, for this host, the count of enforcing profiles, the count of complaining profiles, and any unconfined network-facing service. That three-line summary is the first thing to capture when you inherit any AppArmor system; everything in Part III and Part V builds on knowing where a host actually stands.

Part III The Full Mediation Surface

Files and capabilities are the start, not the whole. This part covers the rest of what a modern profile controls: fine-grained networking and the several kinds of IPC, the advanced mediation that AppArmor 4.0 added, and the unprivileged user namespace restriction that defines what it is like to run AppArmor on Ubuntu today.

Chapter 8Networking, DBus, and IPC: Fine-Grained inet/inet6, Ports, and Unix Sockets

Files and capabilities are where most profiles start, but a service that talks to the network or to other processes needs its reach there bounded too.

This chapter covers AppArmor’s network mediation, from the coarse family-and-type rules that have existed for years to the fine-grained address-and-port rules added in 4.0, and the inter-process surface of DBus and Unix sockets. The grammar throughout is verified against apparmor.d(5).

Ubuntu supports these rules; Debian does not yet

The Debian build of the manual page states that network, DBus, and Unix-socket rules are "not supported on Debian yet." That is a Debian packaging limitation, not an upstream one: Ubuntu, the lead edition here, ships the full feature set, and the live captures confirm the running kernel exposes the network, network_v8, and dbus features. If you port a profile to Debian (the near-twin edition), these rule types are the first thing to check against that release.

8.1 Coarse Network Rules: Family and Type

The original network rule is a coarse check on whether a socket of a given address family and type may be created and used. It is broad by default and becomes more restrictive as you add detail, and like every AppArmor rule type the granted permission is the union of all the network rules in the profile.

network,  # all networking
network tcp,  # any TCP
network inet tcp,  # TCP over IPv4 only
network inet6 tcp,  # TCP over IPv6 only
network netlink raw,  # AF_NETLINK SOCK_RAW

The first word after network is the address family (inet, inet6, unix, netlink, packet, and a long list of others), and the second is the socket type (stream, dgram, raw, and so on) or a protocol (tcp, udp, icmp). For most services this coarse rule is enough: a web server needs network inet tcp, and network inet6 tcp, and nothing else, which already denies it raw sockets, packet capture, and the netlink interfaces an exploit would reach for.

8.2 Fine-Grained Network Rules: ip and port

AppArmor 4.0 added fine-grained mediation of the inet and inet6 families using ip and port conditionals, so a profile can pin a service to specific addresses and ports rather than to a whole family. This is the network equivalent of a tight file rule, and it is one of the strongest reasons the "AppArmor is just path rules" description is out of date.

network ip=127.0.0.1 port=8080,
network peer=(ip=10.139.15.23 port=8081),
network port=8080 peer=(port=8081),
network ip=127.0.0.1 port=8080-8084,

The conditionals split into local and peer. The create, bind, listen, getattr, setattr, getopt, and setopt permissions are local-socket permissions; connect, send, and receive are peer permissions; and accept spans both. So a rule with a peer= clause governs the far end of a connection, and a rule without one governs the socket the program owns. An omitted ip matches all addresses including the unbound case, which the language writes as ip=none; INADDR_ANY and in6addr_any are ip=0.0.0.0 and ip=::. Port ranges use a hyphen, as in port=8080-8084.

For the Grimoire Portal this is how you express exactly what nginx should do and no more: bind its listening ports, and connect only to the backend on loopback.

# in the nginx profile: listen on 80/443, reach the backend on loopback only
network inet tcp ip=0.0.0.0 port=80,
network inet tcp ip=0.0.0.0 port=443,
network inet tcp peer=(ip=127.0.0.1 port=8000),

A profile written this way denies nginx an outbound connection to anywhere except the backend port, so a compromise that tries to phone home or pivot to another host is stopped at the socket. Fine-grained network rules require a kernel that exposes the feature; the 24.04 GA 6.8 kernel exposes network_v8 and the 26.04 7.0 kernel adds network_v9, both sufficient, which is exactly the kind of kernel dependence the feature ABI of Section 5.5 pins.

Standard · apparmor.d(5): fine-grained inet/inet6 mediation

The manual documents the ip and port conditionals for the inet and inet6 families, the local-versus-peer split of the permissions, the ip=none representation of unknown or unbound addresses, the ip=0.0.0.0 and ip=:: any-address forms, and port ranges. It notes the coarse network rules still work and that fine-grained Unix-socket rules are mapped from coarse network unix rules where available.apparmor.d(5), "Network Rules" and "Mediation of inet/inet6 family." The fine-grained rules require kernel support; verify the exposed feature with the live-verify feature block of verify_apparmor_live.sh.

8.3 DBus Mediation

On a desktop or a system-service host, DBus is the message bus programs use to talk to each other, and AppArmor can mediate it down to the interface-member level. A DBus rule names an access (send, receive, bind, or eavesdrop), a bus (system or session), and optionally a path, interface, member, and peer:

dbus,  # all DBus access
deny dbus bus=session,  # no session bus at all
dbus send bus=system
     path=/org/freedesktop/login1
     interface=org.freedesktop.login1.Manager
     member=Suspend
     peer=(name=org.freedesktop.login1),  # may ask logind to suspend, nothing else

The mediation is performed together with the DBus daemon, which checks each message against policy; the contents of messages are not examined, only their addressing. For a server-side service that does not touch DBus, the right rule is no rule, which denies it the bus entirely; the surface matters most when you confine desktop applications or system daemons like logind and systemd that are reached over the bus.

8.4 Unix Sockets: Named, Abstract, and Anonymous

Unix-domain sockets come in three kinds, and AppArmor mediates them in two different ways. A socket bound to a filesystem path (a named socket like /run/grimoire/backend.sock) is mediated by ordinary file rules, because it has a path. The other two kinds, abstract sockets (a Linux extension whose address lives in a separate namespace and begins with @) and anonymous sockets (no address at all), have no filesystem path and are mediated by unix rules:

unix,  # all unix-socket access
unix (connect, receive, send) type=stream
     peer=(label=/usr/sbin/nginx, addr="@grimoire"),
unix (getattr, shutdown) addr=none,  # anonymous sockets

The addr= conditional names the socket; an abstract address is written with the leading @ as netstat -x reports it, addr=none means anonymous, and addr=auto matches a kernel-autobound address. The peer=(label=...) conditional is powerful: it confines a socket to a peer running under a specific profile, so the Portal’s backend can be told to accept connections only from the nginx profile and nothing else, an inter-process boundary that DAC cannot express. The local-versus-peer permission split is the same as for network rules.

8.5 Signals and ptrace

Two process-to-process operations are common rungs on a lateral-movement ladder, and AppArmor mediates both. A signal rule controls which processes a profile may signal or be signaled by; a ptrace rule controls tracing, which is how a process reads another’s memory. Both are two-sided: the operation is allowed only if both the acting profile and the target profile permit it.

signal (send) set=(term, kill) peer=/usr/sbin/nginx,  # may stop nginx
deny signal (send) set=(hup, int),  # never send HUP or INT
ptrace (read) peer=@{profile_name},  # may introspect itself
deny ptrace,  # trace nothing

For ptrace, the trace and tracedby permissions govern actual ptrace calls, while read and readby govern the related /proc introspection. The defensive default for a server-side service is to deny ptrace and to scope signals narrowly: a process that can trace another can read its secrets, and a process that can signal another can kill it, so a profile that grants neither closes two of the quieter ways a compromised service moves sideways.

Standard · apparmor.d(5): signal and ptrace are mutually gated

The manual specifies that for a signal to be delivered, the sender’s profile must have the send permission for the target and the target’s profile must have receive for the sender; and for a ptrace operation, the tracer must have trace for the target and the target must have tracedby for the tracer. Permissions are implied (all of them) when a rule omits an access list, so a bare signal, or ptrace, grants everything; scope them.apparmor.d(5), "Signal rules" and "PTrace rules." The two-sided requirement means a denial can originate in either profile; check both when a cross-process operation is unexpectedly refused.

Exercise 8.1

Write the four network rules the Grimoire Portal’s nginx needs if it serves HTTP and HTTPS and proxies to a backend on 127.0.0.1:8000: two local listening rules and one peer rule, plus the coarse family rules. Then decide what signal and ptrace rules it should have (hint: a web server signals nothing and traces nothing). Check your listening rules against Section 8.2.

Chapter 9Advanced Mediation: mount, mqueue, io_uring, change_profile, change_hat, and Stacking

This chapter covers the mediation a service reaches for less often but that matters most when it matters: filesystem mounts, POSIX message queues, the high-speed io_uring interface, the in-process compartments of hats and profile changes, and stacking one profile under another.

Most server-side profiles never use these, which is the point: when a program does need them, the rule is what stands between a confined service and a container escape.

9.1 Mount, Remount, and Pivot-Root Rules

Changing the mount table is a privileged operation that container runtimes and sandboxes do constantly and ordinary services almost never. A mount rule (with its siblings remount, umount, and pivot_root) confines exactly which mounts a program may perform, by filesystem type, options, source, and target:

mount options=ro /dev/sdb1 -> /mnt/data/,  # only a read-only mount of this device here
mount fstype=tmpfs -> /run/grimoire/tmp/,
deny mount,  # a service that should never mount anything

The conditionals can be matched two ways, and the difference is a common source of surprise. With options=ro, the rule matches a mount whose options are exactly read-only; with options in (ro,nosuid), it matches any combination drawn from that set. Unspecified conditionals match everything, so a bare mount, grants every mount, which is why deny mount, is a sensible line in the profile of any service that has no business touching the mount table. For a normal Portal service the right posture is to deny mounts outright; the rules earn their keep when you confine a container runtime in Chapter 12.

9.2 POSIX Message Queues

AppArmor 4.0 added a mqueue rule to mediate POSIX and System V message queues, the access type, and the queue name:

mqueue (open, read, write) type=posix /grimoire-jobs,
mqueue r type=posix,

This matters for services that coordinate through message queues rather than sockets. There is an important currency caveat for this edition, and it is exactly the kind of thing the series verifies on a running system rather than assuming. The live captures show that neither the 24.04 GA 6.8 kernel nor the 26.04 7.0 kernel exposes an mqueue directory under /sys/kernel/security/apparmor/features/, while the 4.0 userspace parser accepts the rule. The honest reading is that the userspace grammar is ahead of the mediation those kernels enforce, so an mqueue rule may be accepted and not actually mediated on the baseline.

Verify mqueue mediation on your kernel before relying on it

Do not assume an mqueue rule confines anything on the 6.8 or 7.0 kernels this edition targets: the feature is not exposed in /sys/kernel/security/apparmor/features/ on either. Confirm with the feature block of verify_apparmor_live.sh on your exact kernel, and treat message-queue isolation as unverified on this baseline until that check passes. This is a live-verify item, flagged rather than asserted, precisely because the parser accepting a rule is not proof the kernel enforces it.

9.3 io_uring Mediation

io_uring is a high-performance asynchronous I/O interface that, because it can perform many operations through one ring, has been a notable source of security concern. AppArmor 4.0 added an io_uring rule, and unlike mqueue this one is backed by the kernel feature on the baseline: both the 6.8 and 7.0 captures expose an io_uring feature directory (the kernel support landed in 6.7).

io_uring sqpoll,  # may create a polling thread
io_uring override_creds label=/usr/sbin/nginx,

The mediation is partial by design at this stage: the manual notes that io_uring permissions are implied when a rule does not state an access list, so a bare io_uring, grants the ring operations, and the explicit permissions cover the higher-risk actions, creating a polling thread (sqpoll) and overriding credentials during ring operations (override_creds). For a service that does not use io_uring, no rule is the safe default; for one that does, granting only what it needs keeps a powerful interface from becoming a wildcard.

9.4 In-Process Compartments: change_hat and change_profile

Two mechanisms let a single running process change its own confinement, which is useful when one program does work of very different sensitivities. A hat is a sub-profile a program switches into temporarily through the change_hat API, and switches back out of, so a worker can drop into a tighter hat while handling untrusted input and return to the fuller profile afterward. The classic user is Apache’s mod_apparmor, which puts each virtual host into its own hat, so a compromise of one site’s handler is confined to that site’s hat. Hats are written inside a profile with the ^ prefix or a hat block:

/usr/sbin/grimoire-worker {
  include <abstractions/base>
  /srv/grimoire/jobs/** r,

  ^untrusted {  # a tighter hat for handling job input
    /srv/grimoire/jobs/incoming/** r,
  }
}

change_profile is the heavier relative: it transitions a process permanently to another profile, used by programs like libvirt that set up a confinement and then exec a workload into it. A change_profile rule controls which profiles such a transition may target, optionally restricted to a specific executable, and defaults to the environment-scrubbing safe mode where the kernel supports it. The everyday relevance for a service author is small; the reason to know hats and profile changes exist is that you will meet them in the profiles of Apache, libvirt, and the language runtimes that adopted them.

9.5 Profile Stacking

Stacking runs a process under more than one profile at once, and the confinement is the intersection: an operation is allowed only if every stacked profile allows it, so stacking can only tighten, never loosen. It is how a general-purpose confinement is combined with a workload-specific one, and it is the model containers use when a runtime’s own profile is composed with a per-container profile. A process can be launched into a stack with aa-exec, and the kernel exposes the composition directly:

# aa-exec -p grimoire-runtime//&grimoire-job -- /usr/bin/grimoire-job

Because stacking is an intersection, adding a profile to a stack is always safe in the sense that it can only remove permissions, which is what makes it a clean composition tool: a host can enforce a baseline profile on every container and let each container carry its own tighter one, confident the baseline cannot be widened from inside. AppArmor profiles can also coexist with other major LSMs on kernels that support LSM stacking, the broader sense of the word from Section 2.1; the active-LSM list in the live capture (apparmor alongside capability, landlock, and yama) is that coexistence in practice.

Standard · AppArmor: stacking composes as an intersection

The project’s stacking documentation describes running a task under multiple profiles such that the task is confined by all of them, with the effective permission being the intersection; a stacked task can never gain a permission that any profile in the stack withholds. The exact aa-exec stacking syntax and the kernel interface are version-specific and should be confirmed on the running system.AppArmor documentation, "Stacking" (apparmor.net/advanced) and aa_stack_profile(2); aa-exec(8) for launching into a stack. Marked for live verification of the exact composition syntax on this edition’s release.

Chapter 10Unprivileged User Namespace Restrictions: the userns Rule and Fixing Broken Apps

The single most visible AppArmor change of the last few years is Ubuntu’s default restriction of unprivileged user namespaces, enforced through AppArmor.

It hardens a real and heavily exploited piece of kernel attack surface, and it breaks a recognizable set of applications the first time you meet it. This chapter explains why the restriction exists, the mechanism Ubuntu chose, the one-word rule that grants the exception, and the supervised ways to fix what it breaks, in order of preference.

10.1 Why Unprivileged User Namespaces Are a Risk

A user namespace lets an unprivileged process hold what looks like root inside the namespace, which is how modern sandboxes (browsers, container tools, bubblewrap) drop privilege without needing setuid helpers. The cost is that creating one exposes kernel interfaces normally reserved for privileged processes to unprivileged users, and any bug in that newly reachable surface becomes an escalation path. The risk is not hypothetical: Canonical, citing Google’s analysis of kernel exploits, notes that unprivileged user namespaces featured in a large share of real exploit chains, which is why several distributions ship a sysctl to switch them off entirely.

That blunt sysctl is the problem Ubuntu set out to improve. Turning unprivileged user namespaces off system-wide does stop the exploit class, but it also breaks every legitimate sandbox that relies on them. Since an exploit targets a specific application, the right granularity is per-application: disable unprivileged user namespaces for the program that does not need them, and allow them for the one that does.

Standard · Canonical: restricted unprivileged user namespaces

Canonical’s engineering writeup describes the feature: rather than the all-or-nothing sysctl, AppArmor selectively allows unprivileged user namespaces per application, so "unprivileged processes will only be able to create user namespaces if they are confined and have the userns rule in their AppArmor profile (or if they have CAP_SYS_ADMIN)." It was opt-in in 23.10 and turned on by default through the stable-update process; 24.04 ships it enabled.Canonical, "Restricted unprivileged user namespaces are coming to Ubuntu 23.10" (ubuntu.com/blog, 2023), and the AppArmor wiki "unprivileged_userns_restriction." The cited exploit-prevalence figure is Canonical’s, attributed to Google’s kCTF analysis; treat the percentage as their claim and the mechanism as the load-bearing fact.

10.2 The Ubuntu Default: the Two Sysctls

The feature is governed by two kernel tunables, and their defaults are not the same across releases, which is exactly the kind of thing this series confirms on a running system rather than assuming. kernel.apparmor_restrict_unprivileged_userns turns on AppArmor’s mediation of unprivileged user-namespace creation for confined processes: a program that has a profile may create a user namespace only if that profile grants the userns rule. Its companion kernel.apparmor_restrict_unprivileged_unconfined extends the same restriction to programs that have no profile at all. The live captures for this edition show the two diverging by release: on 24.04 the first is 1 and the second is 0, so confined programs are mediated but a program with no profile can still create a namespace; on 26.04 both are 1, so an unconfined program is restricted too. In short, 26.04 closed the gap that 24.04’s default left open, and a shipped unprivileged_userns profile (loaded in enforce mode, visible in the capture) is the mechanism that mediates otherwise-unconfined programs once the companion sysctl is on.

The net effect, stated per release rather than glossed: on 24.04, a program is denied a user namespace if it is confined by a profile that lacks the userns rule, while a program with no profile is not denied by default; on 26.04, both are denied unless the profile grants userns, or the process holds CAP_SYS_ADMIN. Either way the fix is identical and is the subject of the rest of the chapter: a profile that grants userns. The breakage is sharper on 26.04 and on any 24.04 host where an operator has turned the companion sysctl on to harden it.

10.3 The userns Rule in a Profile

The rule itself is the simplest in the language. userns, grants the confined program the ability to create a user namespace; the only access permission defined is create, so userns, and userns create, mean the same thing:

userns,  # allow this confined program to create a user namespace
userns create,  # the same, written explicitly

The discipline is the same as for every other grant in this book: add it to a program’s profile only when that program legitimately needs a sandbox, and prefer scoping the program with a real profile over waving the rule through. A service that has no reason to create namespaces should never carry this rule, and on the restricted default it cannot create one without it, which is exactly the protection the feature provides.

10.4 Fixing Broken Applications

The programs this breaks are recognizable: Chrome and Chromium, Firefox, Electron applications, bubblewrap, and AppImages, all of which build their sandboxes on unprivileged user namespaces. When one of them fails on 24.04 with a sandbox error, the cause is the restriction and the fix is a profile that grants userns. Because writing a complete profile for a browser is impractical, Ubuntu ships these stubs with the unconfined profile flag, flags=(unconfined), which leaves the application effectively unconfined but adds the one rule it needs. (The restriction was announced for 23.10 using a new default_allow profile mode; the profiles that actually shipped use flags=(unconfined).) Ubuntu ships exactly these profiles in the apparmor package for the common offenders; the Chrome one is the canonical example:

# /etc/apparmor.d/chrome (shipped by Ubuntu)
abi <abi/4.0>,
include <tunables/global>

profile chrome /opt/google/chrome/chrome flags=(unconfined) {
  userns,

  # Site-specific additions and overrides.
  include if exists <local/chrome>
}

The shipped Chrome profile: the unconfined flag keeps it otherwise unrestricted, and the userns rule restores its sandbox.

This is why the live capture shows dozens of "profiles in unconfined mode" (Section 3.1): they are these flags=(unconfined) stubs for browsers, container helpers, and other sandboxing tools, each existing only to grant userns while leaving the program otherwise unrestricted. The cases Ubuntu’s shipped profiles do not cover are an application with no profile (something not in the archive), or one installed to a non-standard path that the shipped profile’s attachment does not match; for those, you write a profile, ideally one the vendor ships with the software for each Ubuntu release.

Best practice

When an app breaks, write or install a profile that grants userns for that one program, rather than disabling the restriction for the whole system. The per-application flags=(unconfined) stub is the supported, least-damage fix: it restores the one program’s sandbox and leaves every other program on the host protected. Reserve the system-wide override for a deliberate, documented exception, never as a reflex to silence one broken application.

10.5 The sysctl Overrides and When They Are Justified

You can turn the restriction off, system-wide, by setting either sysctl to zero, temporarily at runtime or persistently through a drop-in:

# sysctl -w kernel.apparmor_restrict_unprivileged_userns=0  # until reboot
# /etc/sysctl.d/60-apparmor-namespaces.conf  (persistent)
kernel.apparmor_restrict_unprivileged_userns=0

This is the wrong fix in almost every case, because it removes the protection for every program on the host to accommodate one. It exists for the genuine exception: a system that runs many sandboxing workloads for which per-application profiles are impractical, where the operator has weighed the trade and documented it. Read against the standards in Chapter 13, disabling a default-on kernel hardening control is the kind of deviation a hardened baseline expects you to justify rather than make silently, and turning a sandbox-protecting control off across a fleet is exactly the sort of finding an audit is built to catch. Prefer the per-application profile; if you must use the override, scope it, persist it deliberately, and write down why.

Lab 3 · See the userns restriction work

Goal: confirm the restriction is on by default, watch an unprivileged user namespace be denied while it is enforced and allowed when it is not, then restore the default. This demonstrates the mechanism; the production fix is the per-application userns profile, not the system-wide toggle. Scripted in verify_apparmor_labs.sh as Lab 3.

  1. Read the default: sysctl kernel.apparmor_restrict_unprivileged_userns should report 1 on stock 24.04.
  2. As an unprivileged user, try to create a user namespace: runuser -u nobody -- unshare --user --map-root-user true. With the restriction on and no profile granting userns, this is denied (non-zero exit, "Operation not permitted").
  3. Turn the restriction off (sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 and the _unconfined companion) and run the same command: it now succeeds, which is the proof that AppArmor, not the base kernel, was the gate.
  4. Restore the default (=1). Then reflect on why the right fix for a real broken app is a profile with userns (Section 10.4), not leaving the restriction off.

Part IV Services, Containers, and Standards

This part applies everything to real workloads. You confine the Grimoire Portal’s web and backend tiers and OpenSSH, take AppArmor into containers and snaps where it does much of the isolation work, and then map every control to the Ubuntu STIG, the CIS Benchmark, and NIST so the compliance reference stands on its own.

Chapter 11Confining Real Services: nginx, a Backend App, and OpenSSH

Parts II and III taught the language and the loop; this chapter puts them to work on real services.

The shape of every profile here is the same, the output of the complain-to-enforce loop of Chapter 6 refined with the mediation surface of Part III, so the work is recognizing what each service legitimately does and granting that and no more. The profiles shown are representative skeletons; the exact rule set for your platform is what the loop produces on a running system, which is why the capstone in Chapter 15 and the lab scripts build and verify them rather than trusting a printed list.

11.1 Confining nginx

You already generated a skeleton for nginx and ran it in complain mode in Lab 2. Refining it to a tight enforcing profile means folding in the file, capability, and network rules nginx actually uses. A web server’s needs are predictable: read its binary and configuration, read its content tree, write its logs and pid file, hold the one capability that lets it bind a low port, and reach the network on its listening ports and its backend. In skeleton form:

# /etc/apparmor.d/usr.sbin.nginx (representative; complete it with the Ch 6 loop)
abi <abi/4.0>,
include <tunables/global>

/usr/sbin/nginx flags=(attach_disconnected) {
  include <abstractions/base>
  include <abstractions/nameservice>
  include <abstractions/ssl_certs>

  capability net_bind_service,  # bind 80/443
  capability setuid,  # drop to www-data
  capability setgid,
  capability dac_override,  # root master writes www-data-owned logs

  network inet tcp,
  network inet6 tcp,

  /usr/sbin/nginx        mr,  # the binary, read + executable-map
  /etc/nginx/**          r,
  /srv/grimoire/html/**  r,  # the content tree (Ch 4 glob)
  /srv/grimoire/logs/*.log w,
  owner /run/nginx.pid   rw,
  /var/log/nginx/*.log   w,

  include if exists <local/usr.sbin.nginx>
}

A representative nginx profile skeleton; the full rule set is what the complain-to-enforce loop emits on your system.

Three details earn their place. The binary rule uses mr, not just r, because nginx maps itself and its modules executable (Section 4.2); forgetting the m is the classic startup-denial. The capabilities are three ideas: bind a privileged port, drop from root to www-data, and let the root master open the log files. That last one, dac_override, is the non-obvious one: nginx writes its logs as the root master, but the log files are owned by www-data (/var/log/nginx is mode 0750 www-data:adm and the Portal’s own logs are www-data), so without dac_override the kernel’s discretionary check refuses root write access to a file it does not own, even before AppArmor’s own rules are consulted. Nothing here grants module loading or arbitrary ownership changes, so a compromise is still boxed. The attach_disconnected flag appears on many shipped web-server profiles because the daemon can momentarily hold a disconnected path (Section 7.4); it is here as the kind of flag real profiles carry, used deliberately. The fine-grained network rules of Section 8.2 tighten this further once you know the backend’s address.

Do not enforce a hand-copied profile

The profile above is a teaching skeleton, not a tested artifact: a real nginx touches temporary paths, MIME types, and module directories that vary by build, so enforcing a copied list will deny something and break serving. Generate the profile on your own host with the Chapter 6 loop, exercise every path the deployment uses, and only then enforce. The capstone walks this end to end and the lab scripts verify it; this chapter shows the shape so you recognize a good profile when the loop produces one.

11.2 Confining the Backend Application

The Portal’s backend is an application server, and applications add one complication a static web server does not: an interpreter. A Python or Node backend runs through /usr/bin/python3 or /usr/bin/node, which reads a large tree of library files, so the profile must grant the interpreter’s reads and executable-maps, usually through an abstraction, plus the application’s own code and data. The exec decision matters: when a wrapper or the systemd unit launches the interpreter, you want the backend confined by the backend’s profile, which means attaching the profile to the right executable and using the transition modes of Section 4.5 deliberately.

/usr/bin/python3        ix,  # interpreter inherits the backend profile
/srv/grimoire/app/**.py r,
/srv/grimoire/app/**    r,
owner /srv/grimoire/data/** rwk,  # the app's own writable data
network inet tcp peer=(ip=127.0.0.1 port=8000),

The interpreter is granted ix here so the Python process stays inside the backend’s profile rather than transitioning to a general python3 profile that would be far too broad; this is the common and correct choice for an app whose interpreter has no useful profile of its own. The lesson generalizes: an interpreted service is profiled at the application boundary, and the interpreter is a detail you grant the app to use, not a separate thing to confine.

11.3 Stacking the Web and Backend Profiles

With nginx and the backend each confined, the boundary between them, the socket nginx uses to proxy to the backend, can be confined too, which is something DAC cannot express. If the two talk over a Unix socket, the peer=(label=...) conditional of Section 8.4 lets each profile name the other, so the backend accepts connections only from the nginx profile and nginx connects only to the backend:

# in the backend profile
unix (accept, receive, send) type=stream addr="@grimoire-backend"
     peer=(label=/usr/sbin/nginx),
# in the nginx profile
unix (connect, send, receive) type=stream addr="@grimoire-backend"
     peer=(label=/srv/grimoire/app/server),

Now a compromise of some third process on the host cannot connect to the backend’s socket, because its profile is not the nginx profile the backend will accept. Where a single process should be confined by two policies at once, a host baseline and a workload profile, that is the profile stacking of Section 9.5, composed as an intersection; the inter-service boundary here is the lighter and more common tool, and the two combine cleanly.

11.4 Confining OpenSSH

sshd is the service that teaches why you think before you confine. Unlike nginx, sshd’s job is to spawn other programs: it launches a login shell or a command for each authenticated user, and those user sessions must not inherit sshd’s profile, or every shell on the system would run under sshd’s confinement and break in confusing ways. The correct posture confines the sshd daemon (its keys, its config, its network) while letting the session it spawns transition out to the user’s normal, unconfined-or-separately-confined context, which is exactly what the exec-transition modes of Section 4.5 are for: the shell is launched with a transition that does not keep it in sshd’s profile.

Ubuntu does not ship an enforcing sshd profile by default, so confining sshd is a deliberate choice, usually made on a hardened or compliance-driven host. When you make it, profile the daemon and its key and config access, grant the network rules it needs, and get the session-launch transition right; getting that transition wrong is how a confined sshd locks administrators out, which is the kind of mistake to make on the disposable VM, never first on a remote host.

Confine sshd on a console you can recover

A profile that denies sshd something it needs, or that traps user sessions in sshd’s confinement, can lock you out of a remote machine with no way back in over the network. Develop an sshd profile on a VM with console access, in complain mode, and only enforce after a full exercise (a real login, a command run, a file copied) shows no denials. This is the single service where the cost of an incomplete profile is losing the host.

11.5 Confining a Custom systemd Service

Most services start under systemd, and there are two clean ways to attach a profile to a unit. A profile whose attachment path matches the unit’s ExecStart binary applies automatically when systemd execs it, the same path-based attachment as everything else. Alternatively, the unit can name the profile explicitly with the AppArmorProfile= directive, which is the unambiguous choice for a custom service and the one to prefer when the binary path is generic. AppArmor and systemd’s own sandboxing are complementary, not redundant: systemd can already restrict a unit with NoNewPrivileges=, ProtectSystem=, ProtectHome=, and the rest, and an AppArmor profile adds the fine-grained file, capability, and network mediation on top. A hardened unit uses both.

# /etc/systemd/system/grimoire-backend.service (excerpt)
[Service]
ExecStart=/srv/grimoire/app/server
AppArmorProfile=grimoire-backend
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true

A unit that layers systemd sandboxing and an AppArmor profile on the same service.

One interaction is worth flagging, because it mirrors a known cross-MAC gotcha. systemd’s NoNewPrivileges=true prevents a process from gaining privileges on exec, and on some configurations that can interfere with an AppArmor profile transition the same way it does with SELinux domain transitions; if a service fails to land in its expected profile under a hardened unit, the no-new-privileges setting is the first thing to check. The SELinux volume treats the analogous case in depth, and the cross-reference between the two volumes is deliberate: the systemd sandbox and the MAC profile are the two halves of confining a unit, on either platform.

Chapter 12Containers and Snaps: docker-default, Kubernetes, LXD, and Snap Confinement

Containers do not escape AppArmor; on Ubuntu they lean on it. A container is built from namespaces and cgroups, which isolate but do not by themselves confine, and AppArmor is one of the layers that turns isolation into confinement.

This chapter covers where AppArmor sits in the container stack, the default and custom profiles Docker applies, how Kubernetes selects a profile, and the heavy and mostly invisible use AppArmor sees under LXD and snap.

12.1 The Container Threat Model and MAC

A container shares the host kernel, so the kernel attack surface is the container’s real boundary, and a container runtime stacks several controls to shrink it: namespaces isolate the container’s view of processes, mounts, and the network; cgroups limit its resources; seccomp filters the system calls it may make; and AppArmor (or SELinux) mediates what the confined processes may do with files, capabilities, and the network. These are complementary. Seccomp says which syscalls are reachable; AppArmor says what those syscalls may touch. Dropping AppArmor because "the container already has seccomp" removes the layer that bounds file and capability access, which is exactly the layer that matters when a syscall the filter allows is used against a file it should not reach. The user namespace restriction of Chapter 10 is part of this picture too, because rootless containers build their isolation on unprivileged user namespaces.

12.2 The docker-default Profile and Custom Container Profiles

Docker applies an AppArmor profile to every container automatically. The built-in profile is named docker-default; it is a moderate baseline that denies the most dangerous operations (writing to /proc and /sys paths that would affect the host, mounting, loading modules) while allowing what a typical containerized application needs. You can replace it per container, either tightening it with your own profile or, at your peril, removing it:

# apparmor_parser -r /etc/apparmor.d/grimoire-container  # load a custom profile
# docker run --security-opt apparmor=grimoire-container grimoire:latest
# docker run --security-opt apparmor=unconfined grimoire:latest  # removes the profile (avoid)

A custom container profile is written in the same language as any other, loaded into the host kernel with apparmor_parser, and named to the runtime with --security-opt apparmor=. The discipline is the same as for a service: start from the default, tighten toward what the container actually does, and never reach for apparmor=unconfined as a way to silence a denial, because it removes the whole layer rather than adding the one rule the workload needed.

12.3 Kubernetes AppArmor via the Security Context

Kubernetes selects an AppArmor profile for a container through the pod or container security context. Support graduated to general availability in Kubernetes 1.30, which replaced the older annotation with a typed field, appArmorProfile, that can be set on a container’s securityContext or on the pod’s (where it becomes the default for every container in the pod):

# pod spec excerpt (Kubernetes 1.30+)
securityContext:
  appArmorProfile:
    type: Localhost
    localhostProfile: grimoire-container

The type is one of RuntimeDefault (use the container runtime’s default, which on a Docker or containerd node is the docker-default-style baseline), Localhost (use a named profile already loaded on the node, given in localhostProfile), or Unconfined (no AppArmor). The Localhost case carries an operational requirement worth stating: the named profile must already be loaded on every node the pod might schedule to, which means profile distribution is a node-provisioning task, not a cluster-API one. Before 1.30 the same selection was made with the annotation container.apparmor.security.beta.kubernetes.io/<container>, now deprecated; a cluster still carrying those annotations is a small migration to the field.

Standard · Kubernetes: AppArmor is GA via appArmorProfile (1.30)

The Kubernetes documentation specifies that AppArmor support is generally available as of v1.30, configured through the appArmorProfile field on the pod or container securityContext with type of RuntimeDefault, Localhost (plus localhostProfile), or Unconfined, and that the prior container.apparmor.security.beta.kubernetes.io/ annotation is deprecated. A Localhost profile must be loaded on the node before a pod can use it.Kubernetes documentation, "Restrict a Container’s Access to Resources with AppArmor" (kubernetes.io/docs). Verify the field shape against the Kubernetes version your cluster runs; the API graduated at 1.30.

12.4 LXD and System Containers

LXD, Canonical’s system-container and VM manager, leans on AppArmor more heavily and more invisibly than Docker does: it generates a per-container AppArmor profile for each instance and loads it automatically, so every LXD container runs confined without the operator writing a line of policy. This is why an LXD host’s aa-status shows a profile per running container with machine-generated names. Because LXD manages these profiles itself, they are not the kind you edit by hand or extend through local/ (the denial-fixing guidance of Section 5.3 noted that lxd, libvirt, and snap profiles are managed by their tools); you influence them through LXD’s own configuration. Nested containers, an LXD container running its own containers, are the case where the generated profile and the user namespace interplay get intricate, and the right move there is LXD’s documented nesting configuration rather than hand-editing a generated profile.

12.5 Snap Confinement and AppArmor

Snaps are the clearest example of AppArmor working where most users never see it. A strictly confined snap runs under a generated AppArmor profile (together with seccomp and other controls), and the snap’s declared interfaces, the connections it asks for, like network access, camera, or home-directory files, are compiled into that profile’s rules by snapd. When you connect or disconnect a snap interface, you are editing the AppArmor (and seccomp) policy that confines it, without ever writing a rule. This is the model Ubuntu Core is built on, and it is why AppArmor must be enabled and working for strict snaps to run at all: it is not optional decoration but the mechanism that makes snap confinement real.

As with LXD, these profiles are managed by snapd and are not hand-edited or extended through local/. The operator’s lever is the interface connection model: grant a snap the interfaces it needs and no more, and the confinement follows. A snap that misbehaves with a denial is debugged through snap’s own tooling and interface connections, and a genuine bug in a generated profile is reported to the snap or to snapd, not patched in /etc/apparmor.d/.

Exercise 12.1

On your lab VM, run aa-status and look for the machine-generated profile names (entries like snap.* or LXD container profiles) among the human-named ones. Then run docker run --rm --security-opt apparmor=docker-default hello-world if Docker is installed, and confirm with aa-status that the container ran under docker-default. You are seeing the three management models side by side: profiles you write, profiles a runtime generates, and the default a runtime applies.

Chapter 13Standards Crosswalk: AppArmor in the Ubuntu STIG, CIS, and NIST 800-53, with USG and Landscape

This chapter is the standalone compliance reference, written so you can open it during an audit without reading the rest of the book.

It maps the AppArmor controls in the authorities that govern Ubuntu systems to specific commands and settings, ties them to NIST, and shows how to automate the work. The first thing to establish is what does and does not exist, because half of compliance work is knowing which document a requirement actually lives in.

13.1 The Honest Starting Point: There Is No AppArmor STIG or Benchmark

State the absence plainly, because it shapes everything that follows: there is no DISA STIG for AppArmor and no CIS Benchmark for AppArmor. AppArmor is not assessed as a component on its own; its controls live inside the operating-system baselines for Ubuntu. That is the same pattern this series finds for PHP and for systemd, and it means the crosswalk maps AppArmor configuration into the Canonical Ubuntu STIG and the CIS Ubuntu Linux Benchmark rather than citing an AppArmor-specific standard. Knowing this saves you from hunting for a document that was never written and points you at the two that carry the real requirements.

13.2 The Canonical Ubuntu 24.04 LTS STIG: AppArmor Controls

DISA publishes a Security Technical Implementation Guide for Canonical Ubuntu 24.04 LTS (with 22.04 and 20.04 STIGs before it), and it carries AppArmor requirements as ordinary OS controls. The two that matter most require that AppArmor be installed and that it be enabled and running with configured profiles. On the published guide these appear with identifiers in the UBTU-24- family, for example UBTU-24-100500 for installation and UBTU-24-100510 for enablement; the exact rule numbers, severities, and the revision of the guide must be read from the published STIG rather than transcribed, because DISA updates the guides on a quarterly cadence and the identifiers and Category ratings move between releases.

Standard · DISA Canonical Ubuntu 24.04 LTS STIG: AppArmor installed and enabled

The Ubuntu 24.04 STIG requires AppArmor to be installed (UBTU-24-100500) and to be enabled and active with configured profiles (UBTU-24-100510), enforced through the standard package and service checks (dpkg -s apparmor, systemctl is-active apparmor, aa-status). There is no standalone AppArmor STIG; these are OS controls. Verify the current revision, the exact rule identifiers, and their Category severities against the published guide at the DISA STIG library before citing them in an assessment.DISA STIG for Canonical Ubuntu 24.04 LTS (rule identifiers in the UBTU-24- family). STIGs apply to DoD information systems and are revised quarterly; confirm the current version at https://public.cyber.mil/stigs/. Identifiers here are from current audit-content references and are marked for verification against the published document.

13.3 The CIS Ubuntu Linux 24.04 LTS Benchmark: AppArmor Section

The CIS Ubuntu Linux 24.04 LTS Benchmark devotes a short, self-contained section to AppArmor (Section 1.3.1 in the v1.0.0 numbering), and it is the clearest statement of a graduated hardening target. The four items climb from presence to full enforcement: ensure AppArmor is installed, ensure it is enabled in the bootloader configuration, ensure all profiles are in enforce or complain mode, and, at Level 2, ensure all profiles are enforcing. The Level 1 and Level 2 split captures the operational reality from Chapter 1: a Level 1 system tolerates complain mode as a transitional state, while a Level 2 system, with elevated security requirements, leaves no profile merely complaining.

Table 13.1: AppArmor controls crosswalk (verify identifiers against the published documents)
ControlUbuntu STIGCIS 24.04Check / settingTaught in
AppArmor installedUBTU-24-1005001.3.1.1 (L1)dpkg -s apparmor3.4
Enabled in the bootloaderUBTU-24-1005101.3.1.2 (L1)no apparmor=0 on the kernel command line; aa-enabled3.1
Service enabled and activeUBTU-24-1005101.3.1.xsystemctl is-active apparmor3.3
Profiles in enforce or complain(via configured profiles)1.3.1.3 (L1)aa-status3.1
All profiles enforcing(via configured profiles)1.3.1.4 (L2)aa-status; aa-enforce /etc/apparmor.d/*1.4, 6
No unconfined exposed daemons(intent)(intent)aa-unconfined7.3
Standard · CIS Ubuntu Linux 24.04 LTS Benchmark: the AppArmor section

The Benchmark’s AppArmor section requires AppArmor installed (1.3.1.1), enabled in the bootloader (1.3.1.2), all profiles in enforce or complain mode (1.3.1.3, Level 1), and all profiles enforcing (1.3.1.4, Level 2). Confirm the section and item numbers and the benchmark version against the published document; CIS renumbers between releases, and the v1.0.0 numbering used here is current as of this revision but is a verify-against-published item.CIS Ubuntu Linux 24.04 LTS Benchmark, Section 1.3.1 (AppArmor). The Level 2 "all profiles enforcing" item is 1.3.1.4 in v1.0.0. There is no standalone AppArmor benchmark; these are OS-benchmark controls.

13.4 NIST SP 800-53 and SP 800-190 Mappings

NIST does not publish an AppArmor document; you reach NIST through the STIG and CIS, which map their OS controls to the SP 800-53 control catalog. The AppArmor controls land in the access-control family, most naturally under least privilege (AC-6) and the broader access-enforcement controls, because mandatory access control is a kernel-enforced realization of least privilege: a profile grants a program only the access it needs. For containers, SP 800-190 (Application Container Security) is the relevant publication; it treats mandatory access control as a recommended control for isolating container workloads, which is the standards anchor for the container confinement of Chapter 12. Neither document names AppArmor specifically, and the crosswalk should not imply one does; the mapping is AppArmor configuration to OS control to NIST control, in that order.

13.5 Automating with the Ubuntu Security Guide (USG)

Canonical ships a tool that applies and audits both the CIS Benchmark and the DISA STIG, including their AppArmor controls, so you do not check them by hand on every host. The Ubuntu Security Guide, usg, audits a system against a profile and produces a human- and machine-readable report, and can apply the hardening as well; it is available with Ubuntu Pro.

# usg audit cis_level1_server  # audit against a CIS profile
# usg fix cis_level1_server  # apply the hardening (on a host you can roll back)
# usg audit disa_stig  # audit against the DISA STIG profile

USG is the right tool for the AppArmor controls in this chapter precisely because they are OS-baseline controls: USG knows them as part of the Ubuntu profiles and checks them alongside everything else, rather than treating AppArmor as a separate audit. Run the audit first, read the report, and apply fixes deliberately on a system you can recover, the same caution as every hardening step in this book.

13.6 Fleet Compliance with Landscape, and Where the Standards Conflict

Landscape, also part of Ubuntu Pro, takes the single-host USG workflow to a fleet: it deploys, audits, and reports compliance across many Ubuntu machines, which is how the AppArmor controls become a fleet posture rather than a per-host chore. The mechanism is the same controls; the scale is the difference.

Two authorities can disagree about AppArmor, and the resolution follows the series’ hierarchy. The disagreement is about how much must enforce. The upstream and vendor defaults ship a modest set of profiles, some in complain mode (Section 3.1); CIS Level 1 accepts complain as transitional; CIS Level 2 demands every profile enforce; the STIG requires AppArmor installed, enabled, and carrying configured profiles. These do not all describe the same end state, and when they conflict the governing order is federal and regulatory (the DISA STIG) over industry consensus (CIS) over the vendor default over the upstream default. In practice that means a STIG-bound host follows the STIG, a CIS Level 2 host enforces everything, and a host with no external mandate should still treat the vendor’s complain-mode profiles as a starting point to drive to enforce, not a destination. The right answer is whichever authority governs your system; the wrong answer is leaving profiles in complain because the default did.

Lab 4 · Audit the Portal host against the AppArmor controls

Goal: run the AppArmor checks an auditor runs, by hand, and read your host’s posture against the crosswalk in Table 13.1. This is a read-only audit, the field-reference half of the chapter made concrete. Scripted in verify_apparmor_labs.sh as Lab 4.

  1. Installed (STIG UBTU-24-100500, CIS 1.3.1.1): dpkg -s apparmor | grep Status should show install ok installed.
  2. Enabled in the bootloader (CIS 1.3.1.2): aa-enabled reports Yes and grep -q apparmor=0 /proc/cmdline finds nothing.
  3. Service active (STIG UBTU-24-100510): systemctl is-active apparmor reports active.
  4. Profile posture (CIS 1.3.1.3 and 1.3.1.4): aa-status reports the loaded count and the enforce-versus-complain split. Record how many complain; a Level 2 target wants that number at zero.
  5. No unconfined exposed daemons (intent): aa-unconfined lists any network-facing process with no profile. Each is a finding to resolve or document.

Part V Legacy, Upgrades, and Maintenance

A profile set has an afterlife. This part covers the operational realities the series treats as first-class: inheriting a host whose profiles have drifted, the non-backward-compatible jump from 2.x to 4.x policy, the feature ABI that decouples a profile from the kernel it was written on, and the user namespace migration that breaks applications on the upgrade to 24.04.

Chapter 14Inheriting and Upgrading: 2.x to 4.x Policy, the Feature ABI, and the userns Migration

A profile set has an afterlife, and the series treats it as first-class because that is where wrong guidance does the most damage.

This chapter is the recovery and upgrade playbook: the AppArmor versions across the Ubuntu releases still in production, the hazards of moving policy across major versions, the feature ABI that keeps a profile’s meaning stable as the kernel changes underneath it, and the user namespace migration that two recent upgrades turn on. None of it is hypothetical; the version spread below is what you actually inherit.

14.1 The Version Spread Across Ubuntu LTS Releases

AppArmor’s userspace version is pinned by the Ubuntu release, and the releases in production span four policy eras. Canonical’s security documentation lists the versions, and the captures for this edition confirm the recent ones:

Table 14.1: AppArmor userspace by Ubuntu release (Canonical security docs; recent rows from the live captures)
Ubuntu releaseAppArmor userspaceEra and what you inherit
14.04 Trusty, 16.04 Xenial2.10.952.x; out of standard support (ESM). No fine-grained network, no userns rule.
18.04 Bionic2.122.x; ESM.
20.04 Focal2.13.32.x; the last 2.x LTS.
22.04 Jammy3.0.43.x policy.
24.04 Noble4.0.14.x; fine-grained network, userns, io_uring; the userns restriction on by default.
26.045.0 (shipped as a 5.0 beta)5.x; userns and the unconfined companion both on by default.

The era matters because it tells you what a profile you inherit can and cannot say. A profile written on 20.04 (2.13) predates the fine-grained network rules of Section 8.2 and the userns rule of Chapter 10, so a host that old confines by file and capability and coarse network only. A profile written on 24.04 (4.x) can use all of it, but will not load unchanged on that 20.04 box, which is the asymmetry the next section is about. Exact versions are version-specific; confirm with apt-cache policy apparmor on the host in front of you rather than trusting a table.

14.2 The Non-Backward-Compatible Jump to 4.x Policy

AppArmor 4.x is, in the project’s own words, a long-term-stable release for the 4.x policy that introduces features that are not backward compatible, and the same was true at the 3.x boundary. The direction of the incompatibility is the thing to keep straight. A newer AppArmor reads older profiles fine: moving a 2.x or 3.x profile onto a 24.04 host generally just works, because the parser understands the older syntax. The break runs the other way: a profile that uses a 4.x rule type, a fine-grained network ip= rule, a userns rule, an io_uring rule, cannot be loaded by a 2.x or 3.x parser that has never heard of it. So a profile set flows forward across an upgrade with little friction, and backward not at all.

The practical consequence is for anyone who maintains one profile set across a fleet of mixed releases. A profile authored against 4.x features will fail to load on the older hosts, and the failure is at parse time, not a silent gap. The two ways through are to keep the profile within the feature set the oldest target supports, or to gate the newer rules behind the feature ABI of the next section so each host compiles what it can. Either way, the rule is to know the oldest AppArmor you must support before you reach for a 4.x-only rule, the same discipline as targeting an old language runtime.

14.3 The Feature ABI and Cross-Kernel Pinning

The deeper version problem is not userspace but the kernel, because the mediation a profile gets depends on what the running kernel exposes, and that changes across kernels even within one Ubuntu release (the GA kernel versus the rolling HWE kernel of Section 5.5). The captures make this concrete: the 24.04 GA 6.8 kernel exposes network_v8, the 26.04 7.0 kernel adds network_v9, and neither exposes an mqueue feature directory. A profile that does not say which feature set it expects is compiled against whatever the current kernel happens to offer, so the same profile can mediate a feature on one host and silently ignore it on another.

The abi rule pins the expected feature set, and aa-features-abi inspects and captures it, so a profile’s behavior is stable across the kernels it runs on:

abi <abi/4.0>,  # the profile declares the 4.0 feature set
include <tunables/global>
# aa-features-abi -x -v  # show the running kernel's feature ABI
# aa-features-abi -f /etc/apparmor.d/usr.sbin.nginx -w features.txt  # capture a profile's ABI

Pinning the ABI turns a silent behavior change into an explicit, visible decision: the profile says what it was written for, and a move to a kernel that exposes more or less is something you choose and test, not something that happens to you on the next HWE kernel roll. For an upgrade, the discipline is to pin abi in every profile you author, and when you move a host to a newer kernel, re-verify the feature set with aa-features-abi and the live-verify feature block of verify_apparmor_live.sh rather than assuming the profiles mean the same thing they did before.

14.4 The User Namespace Migration on Upgrade

The most disruptive upgrade in AppArmor’s recent history is the user namespace restriction of Chapter 10, and it bites on two upgrades, not one. Moving a host to 24.04 turns on apparmor_restrict_unprivileged_userns, so confined programs that build sandboxes now need a userns rule. Moving to 26.04 turns on the companion apparmor_restrict_unprivileged_unconfined as well, which the captures confirm is 0 on 24.04 and 1 on 26.04, so on 26.04 even unconfined programs are restricted. Each step tightens the default, and each can break a working sandbox the day after an upgrade that touched nothing in the application.

The staged way to absorb it: before the upgrade, inventory the programs on the host that create user namespaces (browsers, Electron apps, bubblewrap, AppImages, container tools, anything that sandboxes); after the upgrade, expect those to fail with a namespace error and apply the per-application fix of Section 10.4, a profile that grants userns, in preference to disabling the restriction. The migration is most surprising precisely because nothing in the application changed, so the failure looks like the app broke when in fact the host hardened. Knowing the restriction landed on the upgrade is most of the fix.

Test the userns-dependent apps before you upgrade the fleet

An upgrade to 24.04 or 26.04 can break every sandboxed application on a host at once, with no application change to point at. Before rolling either upgrade across a fleet, identify the programs that rely on unprivileged user namespaces and confirm a profile grants each the userns rule, so the upgrade is a known quantity rather than a wave of identical, mysterious sandbox failures. This is the single upgrade hazard most likely to generate a flood of tickets.

14.5 Maintenance Hygiene: Drift, Unconfined Services, and Stale Profiles

Between upgrades, a profile set drifts, and a little recurring hygiene keeps the drift from becoming a recovery project. Four checks cover most of it, and all are tools you already know. aa-status shows the enforce-versus-complain split, and a profile that has sat in complain since some long-forgotten incident is enforcing nothing; drive it back to enforce through the loop of Chapter 6. aa-unconfined finds network-facing services that gained no profile, often something installed after the host was last hardened. aa-remove-unknown unloads profiles the kernel still holds for packages that were removed, clutter that accumulates as software comes and goes. And the local/ override discipline of Section 5.3 is what keeps a package update from quietly reverting your changes, so additions belong in local/, never in the shipped profile.

The throughline of the whole chapter is that AppArmor’s afterlife is a large fraction of the work, not an afterthought. A greenfield profile written once and forgotten is the easy case; the real job is the inherited host on an old release, the upgrade that hardens the default under a working application, and the slow drift that turns a confined fleet into a complaining one. The tools to manage all of it are the ones from Part I, applied on a schedule.

Exercise 14.1

On your lab VM, run apt-cache policy apparmor and place the host in Table 14.1. Then run aa-status and sudo aa-unconfined and sudo aa-remove-unknown -n (the -n previews without unloading). Write the three-line drift summary: how many profiles complain, how many exposed services are unconfined, and how many kernel-loaded profiles have no file on disk. That summary is the first thing to capture on any inherited AppArmor host.

Capstone

The capstone assembles every layer into one annotated build, each step labeled by the chapter that explains it, ending in a verification table you can run to confirm the whole system is confined and enforcing.

Chapter 15Building a Fully Confined Ubuntu Service End to End

This is where every layer comes together.

The capstone takes the Grimoire Portal from the unconfined service of Chapter 3 to a fully enforced one, built component by component, tightened to enforce, scoped at the network and namespace boundaries, and checked against the standards, all on one disposable Ubuntu 24.04 VM. Each step is labeled with the chapter that explains it, so the capstone reads as an index to the book as much as a build, and it ends in a verification table that asserts both that the service works and that the confinement holds. The lab script runs this build and verifies it; this is the one place the complete enforcing profile is not a skeleton but a tested artifact.

15.1 The Target Architecture

The finished Portal is nginx serving static content from /srv/grimoire/html, running confined by an enforcing profile, bound to its ports, reading only its content tree, holding only the capabilities it needs, and reaching the network only where it must. The confinement boundary is drawn around the program: a compromise of nginx can touch what the profile grants and nothing else. Where a deployment adds a backend application, the inter-service socket is confined with the peer-label rules of Section 11.3; the capstone here focuses on the web tier so the build is reproducible on one VM, and the backend and container layers extend it using the patterns of Chapter 11 and Chapter 12.

15.2 Profiling Each Component

The profile is built, not copied, with the loop of Chapter 6: generate a skeleton with aa-autodep, run it in complain while exercising every path the deployment uses (serve a page, hit a 404, reload, write logs), and fold the observed accesses into rules with aa-logprof. That loop is what makes the resulting profile complete for this system rather than a guess, and it is why the lab generates the profile on the running VM instead of trusting a printed list. The shape it converges on, assembled and annotated by the chapter each rule-group comes from, is this:

# /etc/apparmor.d/usr.sbin.nginx -- the assembled Portal profile
abi <abi/4.0>,  # pin the feature set (Ch 5.5, 14.3)
include <tunables/global>

/usr/sbin/nginx flags=(attach_disconnected) {
  include <abstractions/base>  # libc, loader, /dev basics (Ch 5.1)
  include <abstractions/nameservice>  # DNS, passwd/group for the setuid drop

  capability net_bind_service,  # bind 80/443 (Ch 4.4)
  capability setuid,  # drop root to www-data
  capability setgid,
  capability dac_override,  # root master opens www-data-owned logs

  network inet  tcp,  # IPv4/IPv6 TCP (Ch 8.1)
  network inet6 tcp,

  /usr/sbin/nginx             mr,  # binary: read + exec-map, the m matters (Ch 4.2)
  /usr/lib/nginx/modules/     r,
  /usr/lib/nginx/modules/*.so mr,  # dynamic modules, exec-mapped
  /etc/nginx/                 r,
  /etc/nginx/**               r,  # config tree (Ch 4.3 glob)
  /etc/ssl/openssl.cnf        r,  # OpenSSL reads this at startup
  /etc/mime.types             r,
  /run/                       r,
  /run/nginx.pid              rwk,
  /var/log/nginx/             rw,
  /var/log/nginx/**           w,
  /var/lib/nginx/             rw,
  /var/lib/nginx/**           rw,  # temp/body/proxy dirs
  /usr/share/nginx/**         r,
  /srv/grimoire/html/         r,
  /srv/grimoire/html/**       r,  # the content tree, read-only
  /srv/grimoire/logs/         rw,
  /srv/grimoire/logs/*.log    w,
  /sys/devices/system/cpu/online  r,  # worker autodetect
  @{PROC}/sys/kernel/random/boot_id r,

  include if exists <local/usr.sbin.nginx>  # site overrides (Ch 5.3)
}

The assembled Portal profile; this is the exact profile Lab 5 loads, enforces, and re-exercises clean on stock 24.04 and 26.04, with each rule-group labeled by its chapter.

15.3 Tightening to Enforce

With the profile complete in complain, the move to enforce is one command, aa-enforce /usr/sbin/nginx, followed by a restart so the running master attaches under enforcement and a final exercise to confirm a clean run with no new denials. The tightening that distinguishes a hardened build from a merely working one is in the rules above: the content tree is read-only, so a compromise cannot deface it through the profile; the capabilities are exactly the four nginx needs (the fourth, dac_override, only so the root master can write the www-data-owned logs, the one non-obvious grant explained in Section 11.1) and nothing that loads modules or changes arbitrary ownership; and the network is scoped to what a web server does. Where the deployment proxies to a backend, this is where you replace the broad network inet tcp, with the fine-grained peer=(ip=127.0.0.1 port=8000) rule of Section 8.2 and add the Unix-socket peer-label boundary of Section 11.3. The user namespace decision of Chapter 10 is made by omission here: a static web server creates no namespaces, so the profile grants no userns rule, and on the restricted default that is exactly right.

15.4 Crosswalking to the Standards

The finished build is checked against the controls of Chapter 13, which is what turns "it works and looks confined" into "it passes an audit." AppArmor is installed, enabled, and active; the nginx profile is loaded and enforcing, so it satisfies the CIS enforce requirement rather than sitting in complain; and aa-unconfined now reports the Portal as confined rather than not confined, closing the unconfined-but-exposed gap of Section 7.3. On a host with a STIG or CIS mandate, this is the evidence the assessment wants, and usg audit from Section 13.5 produces it in a report rather than by hand.

15.5 Verification Table

The capstone is verified on both legs the series requires: that the service works, and that the confinement holds. Each row is a check the lab script runs; a build that passes the left column but fails the right is not confined, and one that passes the right but fails the left is broken, and only passing both is done.

Table 15.1: Capstone verification (both legs, mapped to the lab script)
LayerChapterWorksConfined
Service runs and serves3, 11curl returns 200 and the Portal pagenginx is in enforce in aa-status
Content scoped4pages under the content tree loadprofile reads /srv/grimoire/html only, read-only
Privilege bounded4.4binds port 80, drops to www-dataonly four capabilities granted; no module load
Network scoped8serves over TCPno outbound reach beyond the declared rules
Namespaces decided10service starts normallyno userns rule (the service needs none)
No unconfined exposure7.3, 13service is upaa-unconfined reports nginx confined, not unconfined
Clean enforce6a full re-exercise still servesthe re-exercise produces no new denials
Lab 5 · Build and enforce the Portal end to end

Goal: take the Portal from unconfined to a clean enforce and pass Table 15.1 on both legs: the assembled profile is loaded and enforcing, the Portal still serves its page and its 404, nginx no longer appears in aa-unconfined, and a second full exercise produces no new denials. Scripted in verify_apparmor_labs.sh as Lab 5.

  1. Build the profile with the Chapter 6 loop (the lab installs the assembled profile of Section 15.2, which is what that loop converges on for this system).
  2. Enforce it: sudo aa-enforce /usr/sbin/nginx, then sudo systemctl restart nginx so the master attaches under enforcement.
  3. Works leg: curl -s http://localhost/ returns the <h1>Grimoire Portal</h1> body, and a missing path returns 404.
  4. Confined leg: aa-status shows nginx in enforce mode, and aa-unconfined now reports it confined rather than not confined.
  5. Clean-enforce leg: exercise again (several requests, a reload) and confirm journalctl -k --grep=apparmor shows no new DENIED events for the nginx profile. If it does, fold them in (the loop is never more than one denial from done) and re-enforce.
If the enforce step denies something

A real nginx build can touch a path this assembled profile does not list, and under enforce that surfaces as a denial and a failed request rather than a silent log line. That is the loop working, not a defect: read the denied_mask and name from the denial (Section 7.2), add the one rule to local/usr.sbin.nginx, reload, and re-test. The lab script reports any denial it hits so the missing rule is named, which is exactly how a profile reaches a clean enforce on a real system.

Appendices

The field-reference half: annotated templates, a checklist, the standards master table, a glossary, and the references that every claim in the book is verified against.

Appendix A · Annotated Profile Templates

Starting points to copy and adapt. Treat them as scaffolds for the complain-to-enforce loop of Chapter 6, not as finished policy: the only way to a complete profile is to exercise the program and fold in what it actually does. The web-server template is the one exception, the assembled Portal profile verified under enforce by Lab 5 on stock 24.04 and 26.04.

A.1 Minimal service profile. The smallest useful skeleton: a confined program that reads its config and writes its data, and nothing else.

# /etc/apparmor.d/srv.grimoire.app.server
abi <abi/4.0>,
include <tunables/global>

/srv/grimoire/app/server {
  include <abstractions/base>  # libc + loader (Ch 5.1)

  /srv/grimoire/app/server  mr,  # the binary, read + exec-map
  /etc/grimoire/**          r,  # config
  owner /srv/grimoire/data/** rwk,  # its own writable data

  deny /etc/shadow r,  # belt and suspenders

  include if exists <local/srv.grimoire.app.server>
}

A.2 Confined web server (verified). The assembled Portal profile from the capstone (Section 15.2), which Lab 5 confirms serves cleanly under enforce. Globbed runtime paths keep it stable across requests.

# /etc/apparmor.d/usr.sbin.nginx  (identical to the Sec 15.2 capstone profile)
abi <abi/4.0>,
include <tunables/global>

/usr/sbin/nginx flags=(attach_disconnected) {
  include <abstractions/base>
  include <abstractions/nameservice>

  capability net_bind_service,  # bind 80/443
  capability setuid,  # drop to www-data
  capability setgid,
  capability dac_override,  # root master opens www-data-owned logs

  network inet  tcp,
  network inet6 tcp,

  /usr/sbin/nginx             mr,
  /usr/lib/nginx/modules/     r,
  /usr/lib/nginx/modules/*.so mr,
  /etc/nginx/                 r,
  /etc/nginx/**               r,
  /etc/ssl/openssl.cnf        r,
  /etc/mime.types             r,
  /run/                       r,
  /run/nginx.pid              rwk,
  /var/log/nginx/             rw,
  /var/log/nginx/**           w,
  /var/lib/nginx/             rw,
  /var/lib/nginx/**           rw,
  /usr/share/nginx/**         r,
  /srv/grimoire/html/         r,
  /srv/grimoire/html/**       r,
  /srv/grimoire/logs/         rw,
  /srv/grimoire/logs/*.log    w,
  /sys/devices/system/cpu/online  r,
  @{PROC}/sys/kernel/random/boot_id r,

  include if exists <local/usr.sbin.nginx>
}

A.3 Fine-grained network rules. Drop-in for a service that should reach only its backend, replacing the broad network inet tcp, (Section 8.2).

network inet tcp ip=0.0.0.0 port=80,  # listen
network inet tcp ip=0.0.0.0 port=443,
network inet tcp peer=(ip=127.0.0.1 port=8000),  # reach the backend, nothing else

A.4 Scoped userns exception. The flags=(unconfined) stub Ubuntu ships for a sandboxing application that needs unprivileged user namespaces (Section 10.4); the shape to copy for an in-house app the archive does not cover.

# /etc/apparmor.d/srv.grimoire.sandbox
abi <abi/4.0>,
include <tunables/global>

/srv/grimoire/sandbox flags=(unconfined) {  # effectively unconfined ...
  userns,  # ... but allowed to create user namespaces
  include if exists <local/srv.grimoire.sandbox>
}

Appendix B · Deployment & Confinement Checklist

Take a service from unconfined to enforcing without locking yourself out. Each step names the chapter that explains it. Do this on a host you can recover.

  1. Find it. Confirm the service is unconfined and exposed: aa-status and aa-unconfined (7.3). A network-facing program with no profile is the candidate.
  2. Generate a skeleton. aa-autodep /path/to/binary, or start aa-genprof (6.1).
  3. Pin the ABI. Add abi <abi/4.0>, as the first line so the profile’s meaning is stable across kernels (5.5, 14.3).
  4. Complain, do not block. aa-complain, then restart so the running process attaches (6.2).
  5. Exercise everything. Drive every real path: serve, error, reload, rotate logs, run each feature the deployment uses (6.2). An incomplete exercise is a future outage.
  6. Fold in the events. aa-logprof; prefer a glob over an exact path and an abstraction over a cluster of rules (6.3).
  7. Repeat until clean. Exercise and aa-logprof again; when a full exercise yields no new events, the profile is complete (6.4).
  8. Scope the network. Replace broad network rules with ip/port conditionals where the endpoints are known (8.2).
  9. Decide namespaces. Grant userns only if the program legitimately sandboxes; otherwise omit it (10).
  10. Confine the IPC boundary. If it talks to another service over a socket, add the peer=(label=...) rules so only the right peer connects (11.3).
  11. Enforce. aa-enforce, restart, and watch the log for a while (6.4). For sshd and anything that could lock you out, keep console access (11.4).
  12. Verify both legs. The service works (status, output) AND the confinement holds (enforce mode, aa-unconfined now marks it confined, no new denials) (15.5).
  13. Crosswalk. Check against the controls: installed, enabled, enforcing, no unconfined daemons; run usg audit if under a mandate (13).
  14. Keep changes in local/. Put site additions in /etc/apparmor.d/local/ so a package update does not revert them (5.3).

Appendix C · Standards Crosswalk Master Table

Self-contained for audit use. Each AppArmor control mapped to its Canonical Ubuntu 24.04 LTS STIG rule, its CIS Ubuntu Linux 24.04 LTS Benchmark item, the NIST SP 800-53 Rev 5 family it serves, the check, and the chapter. There is no AppArmor STIG or CIS Benchmark; these are OS-baseline controls (Section 13.1). Verify the exact rule identifiers, severities, and the document revisions against the published STIG and Benchmark; DISA revises quarterly and CIS renumbers between releases.

Table C.1: AppArmor standards crosswalk (identifiers are verify-against-published)
ControlUbuntu STIGCIS 24.04NIST 800-53CheckCh
AppArmor installedUBTU-24-1005001.3.1.1 (L1)AC-3, AC-6, CM-7dpkg -s apparmor3.4
Enabled in the bootloaderUBTU-24-1005101.3.1.2 (L1)AC-3, CM-7no apparmor=0; aa-enabled3.1
Service enabled and activeUBTU-24-1005101.3.1.xAC-3, CM-7systemctl is-active apparmor3.3
Profiles in enforce or complain(configured profiles)1.3.1.3 (L1)AC-6aa-status3.1
All profiles enforcing(configured profiles)1.3.1.4 (L2)AC-6 (least privilege)aa-status; aa-enforce1.4, 6
No unconfined exposed daemons(intent)(intent)AC-6, SC-7aa-unconfined7.3
Container MAC isolation(OS STIG containers)(N/A)SP 800-190runtime profile applied12

Automate the row checks with the Ubuntu Security Guide (usg audit) on a host and Landscape across a fleet (Section 13.5). Where authorities disagree on how much must enforce, the order is federal (DISA STIG) over consensus (CIS) over vendor default over upstream default (Section 13.6).

Appendix D · Glossary

The working vocabulary of the book, gathered for lookup. The section where each is taught is noted.

Table D.1: Glossary
TermMeaning
DACDiscretionary access control: the traditional Unix owner-decides permission model, which root can override (1.1).
MACMandatory access control: kernel-enforced policy no user, including root, can override (1.2).
LSMLinux Security Module: the kernel framework of hooks AppArmor (and SELinux) plug into (2.1).
ProfileThe unit of AppArmor policy: a text file naming a program and the operations it may perform (1.3).
Pathname modelAppArmor’s identification of objects by file path rather than by label; the source of both its simplicity and its aliasing edges (2.2).
AttachmentHow a profile binds to a program: the executable path the profile confines when it is run (2.4).
Enforce / ComplainThe two core profile modes: enforce blocks and logs (DENIED); complain allows and logs (ALLOWED) (1.4). AppArmor 4.0 adds prompt and kill.
UnconfinedA program with no profile loaded, governed only by DAC (1.4).
AAREAppArmor Regular Expressions: the path-globbing syntax where * stays within a path segment and ** crosses / (4.3).
Exec transition modeThe permission letters (ix, px/Px, cx/Cx, ux/Ux, and fallbacks) deciding the child’s confinement on exec; a capital scrubs the environment (4.5).
CapabilityA Linux privilege (for example net_bind_service) granted by name, independent of the Unix user (4.4).
AbstractionA reusable fragment of rules under /etc/apparmor.d/abstractions/, pulled in with include (5.1).
Tunable / VariableA named, site-adjustable value (@{HOME}, @{PROC}) defined under tunables/ (5.2).
Local overrideA file under /etc/apparmor.d/local/ pulled in by include if exists, where site additions survive package updates (5.3).
Feature ABIThe kernel feature set a profile pins itself to with abi <abi/4.0>, so its meaning is stable across kernels (5.5, 14.3).
MediationThe set of operations a profile controls: files, capabilities, network, IPC, mount, and more (2.3).
HatA sub-profile a program switches into temporarily via change_hat to compartmentalize phases of work (9.4).
change_profileA permanent in-process transition to another profile, used by programs like libvirt (9.4).
StackingRunning a process under more than one profile at once, confined by the intersection (9.5).
userns ruleThe userns, grant that lets a confined program create an unprivileged user namespace under the Ubuntu restriction (10).

Appendix E · References

Primary and authoritative sources only, grouped. Version numbers and revisions age; confirm each against the live source, which is the habit the whole book is about.

Kernel and project

Canonical and Ubuntu

Standards and hardening

Other platforms and ecosystems

Errata and Updates

This guide is corrected continuously, and you are part of how that happens. If you find an error, a claim that no longer matches its primary source, a command that does not behave as printed, or anything that has simply gone stale, report it to [email protected]. Name the section, and where you can, the authority that settles it; that is exactly how the book is verified in the first place, and a good report can go straight into the next revision.

The current, corrected version always lives at https://gregvogt.net/grimoire/. Each edition was correct as of the revision date printed on its cover, and claims nothing beyond it: standards move, packages update, and the page in front of you ages from the day it ships. When a detail matters, check it against the latest revision there, and against the primary source it cites, before you rely on it.

How to Cite This Guide

Because this is a living document, cite the revision you used and where you found it, so that a reader can retrieve the same text you saw. The revision is printed on the cover.

Vogt, Greg. Profiling, Confining & Hardening with AppArmor. The Programmer’s Grimoire. Revision v1.0-RC1, June 2026. https://gregvogt.net/grimoire/apparmor/

For LaTeX and reference managers:

@misc{grimoire-apparmor,
  author  = {Vogt, Greg},
  title   = {Profiling, Confining & Hardening with AppArmor},
  series  = {The Programmer's Grimoire},
  edition = {Revision v1.0-RC1},
  year    = {2026},
  url     = {https://gregvogt.net/grimoire/apparmor/}
}

License and Reuse

The Programmer’s Grimoire is published free of charge and licensed to you under a Creative Commons Attribution-NonCommercial 4.0 International License (CC BY-NC 4.0). You are free to read, copy, share, and adapt or translate it, in any medium or format, for any non-commercial purpose, on one condition: give appropriate credit to the author, link to the license, and indicate whether you changed anything. You may not use the material for commercial purposes. The full terms are at https://creativecommons.org/licenses/by-nc/4.0/.

The intent is plain. The knowledge is meant to be free for anyone to read, copy, and translate, and the non-commercial term is what keeps it that way, so that no one else fences it off or resells it. A paid edition, where one exists, comes from the author and exists only to support the work; the knowledge itself is not the thing being sold.

Trademark and brand. The name The Programmer’s Grimoire, the series wordmark, and the look and branding of these guides are trademarks of Greg Vogt and are not part of the content license above. Reusing the licensed text, including in a translation, grants no right to the Grimoire name or brand. You may not present your version as an official Grimoire, use the name or wordmark to label, endorse, or promote a derivative or third-party work, or otherwise imply that the author stands behind it. Credit the original by name, which is the attribution the license requires, but publish your version under your own title.

Colophon

Each guide is a single HTML document with an external stylesheet and a small progressive-enhancement script, and no inline style or script at all, so it satisfies a strict Content-Security-Policy. Three formats are built from that one source: the PDF with WeasyPrint, the EPUB with EbookLib (parsed with BeautifulSoup), and the Kindle AZW3 with Calibre’s ebook-convert. What you read on screen, on paper, and on an e-reader is the same text rendered three ways.

The reading text is set in Georgia, with the bundled Literata as the press fallback; display headings, numerals, and labels are set in Cinzel, code and the interface in JetBrains Mono (with a bundled fallback face for full glyph coverage), and the Grimoire wordmark in UnifrakturCook. On screen the reader can switch the prose to Atkinson Hyperlegible or OpenDyslexic, scale the type, adjust line spacing, and toggle dark mode; the print and e-reader builds stay in the typeset faces. The bundled fonts are under the SIL Open Font License.

How it was made is described in the notes at the front, and is the point as much as the prose. First drafts are generated by an AI (Claude, made by Anthropic) and then verified, line by line, against primary sources by a human before anything ships. Every factual claim is tracked in a per-volume claims ledger and re-checked against the living standards on each revision, which is why a guide carries a revision date, and why that date is load-bearing.