Loading policy into the kernel
.load .replace .remove for administrators for AppArmor developers for security researchers
A saved profile changes nothing until its compiled form is written to the kernel. The parser has three actions and each writes to its own file in securityfs. Add refuses a name that is loaded. Replace adds or swaps. Remove takes a profile out. Every profile is one write and one STATUS record. Running programs follow a replaced profile at their next checked operation and become unconfined when it is removed. At boot one parser run with replace loads the whole profile directory.
On the map: running the parser
▶ Watch this deck — 9 scenes, ~7 min
Worth seeing first
- From profile text to kernel — one parser run from text to the write
01 A saved profile is not a loaded profile
The kernel enforces the compiled copy it was given, not the file on disk. apparmor_parser -r FILE compiles the file and writes the result to the kernel, which replaces the loaded profile.
Demo was refused a file, so you added one rule to its profile and saved. Run demo again: still refused. Why? Because the kernel doesn't look at profile files. It holds a compiled copy of the profile, loaded some time ago, and your edit hasn't reached it. One command takes it there: apparmor_parser -r. The parser compiles the text into a binary, writes that binary into a file the kernel provides, and the kernel swaps the profile. Now demo gets its file. This deck follows that last step: the three actions, the write itself, what the kernel checks and logs, what happens to programs that are already running, and how it's all done at boot.
Details and sources
Details
- The denial, the reload and the second
caton the slide were run in a Debian sid guest (kernel 7.3.4). The parser in the guest was the one built from the AppArmor tree, run asapparmor_parser --config-file=/dev/null -K -I DIR(-Kis--skip-cache); the slide writesapparmor_parser. - Before the reload:
aa-exec -p demo -- cat /etc/demo/secret.confprintedcat: /etc/demo/secret.conf: Permission deniedand the kernel logged theDENIEDrecord that Reading a denial takes apart. - The file with the new rule
/etc/demo/secret.conf r,was loaded withapparmor_parser -r(exit status 0); the samecatthen printedsecretand no record was logged. In the guest the changed file was a second file nameddemo-fixed.aapholding only the profiledemo; the slide calls itdemo.aap. - That a saved file changes nothing by itself is from the source, not run: nothing in the kernel reads profile text. The kernel is given compiled policy through three files and keeps what it was given.
-ris--replace. For each profile the parser builds the binary policy and libapparmor writes it to/sys/kernel/security/apparmor/.replace.- The steps before the write (reading the text, compiling the rules, building the binary) are From profile text to kernel; the bytes are The binary policy format.
for AppArmor developers for security researchers
In the code
- The action is chosen at parser_main.c:583-585; the write for replace is parser_interface.c:753-756, which calls
aa_kernel_interface_replace_policy()kernel_interface.c:357-363. - The kernel side of the file is
profile_replace()apparmorfs.c:705-714.
02 Three actions, three files
-a (the default) writes to .load and is refused when the name is loaded. -r writes to .replace and adds or replaces. -R writes to .remove and removes the profile with its children.
The parser has three actions, and each one writes to its own file in securityfs. Add is the default: it's what you get with no action option. It writes to .load, and the kernel takes the profile only if that name is free. Load demo twice with add and the second run fails: profile already exists. Replace, -r, writes to .replace, and it doesn't mind. A new name is added, a loaded one is swapped. That makes it the one to reach for on a running system. Remove writes to .remove and takes the profile out, with its children. And it's one action per run: ask for two, and the parser stops.
Details and sources
Details
-a,--add: the default when no action option is given (the help text saysAdd apparmor definitions [default]). Writes each profile's binary to.load. The kernel adds the profile, or fails the write when a profile of that name is loaded; the parser then printsPROGNAME: Unable to add "NAME". Profile already existsand stops loading the rest of that file's profiles.-r,--replace(--reloadis an undocumented second spelling): writes each profile's binary to.replace. A name that is not loaded is added; a loaded one is replaced.-R,--remove: the file is still parsed in full, but what is written to.removeis each profile's name. A name that is not loaded fails:PROGNAME: Unable to remove "NAME". Profile doesn't exist. The kernel removes a profile's children with it; the parser does not send hats and children one by one.- The two refusals on the slide are from the source, not run: no guest run adds a loaded name or removes a missing one.
PROGNAMEis the name the parser was started with. - With
-v, success printsAddition succeeded for "NAME".,Replacement succeeded for "NAME".orRemoval succeeded for "NAME".. Without it a successful run prints nothing. - One action per run.
-a,-r,-R,-S,-o,-Nand-peach count as an action; two of them givePROGNAME: Too many actions given on the command line.and exit status 1. - The three files are in the apparmor directory of securityfs, normally
/sys/kernel/security/apparmor. libapparmor finds the directory through the mount table;-f DIR,--subdomainfs DIRnames it. - A profile file whose name is also in
/etc/apparmor.d/disable/is skipped for add and replace withSkipping profile in DIR/disable: NAME; remove does not look there. -Rtogether with-B(binary input) is refused:Error: Invalid load option specified: 2.- Where the manual page and the code differ, the deck follows the code. The page says replace is "used to replace the definition already in the kernel with the definition given on standard input"; the code accepts files and directories and adds a name that is not loaded.
- Known discrepancy: Kernel: a refused add is logged as
profile_replacewithinfo="profile can not be replaced"; the specific reasons are never printed. From the source, not run. - Known discrepancy: Duplicate-definition and load messages name a profile without its namespace or parent.
for AppArmor developers for security researchers
In the code
- Options: parser_main.c:150-157, help parser_main.c:226-228; the default
OPTION_ADDparser_common.c:110 parser_main.c:948; the count of actions parser_main.c:957-961. - Messages: parser_interface.c:60-83 (the error texts), parser_interface.c:98-146 (per action). The loop that stops at the first failure: parser_policy.c:70-82.
- The file names: kernel_interface.c:138-140;
aa_kernel_interface_load_policy()kernel_interface.c:314-319,..._replace_policy()kernel_interface.c:357-363,..._remove_policy()kernel_interface.c:400-406. - Kernel handlers:
profile_load()apparmorfs.c:687-697 passesAA_MAY_LOAD_POLICY;profile_replace()apparmorfs.c:705-714 passesAA_MAY_LOAD_POLICY | AA_MAY_REPLACE_POLICY;profile_remove()apparmorfs.c:723-757.-EEXISTfor a loaded name without the replace bit: policy.c:824-836.-ENOENTfor a missing name on remove: policy.c:1527-1533. Children go with the parent: policy.c:200-243.
03 One write per profile
Each profile is one open, one write of the whole binary and one close. A cache file or a binary given with -B goes in one write with every profile in it, children and hats included. -R writes only the profile's name. -Q compiles without writing; -S and -o FILE give you the binary.
What does the write look like? Demo's file holds three profiles: demo and two small siblings. The parser compiles each one into its own binary, opens .replace, and hands over the whole binary in a single write. Then it closes the file and moves on. Three profiles, three writes, and in the log three records from one process. The kernel won't take a profile in pieces. Remove is lighter: the parser still parses your file, but all it writes is each profile's name. And if you only want to compile, -Q stops just short of the write, while two more options hand you the binary instead. Those runs write nothing to the kernel.
Details and sources
Details
demo.aapis the file of the guest runs: the profiledemoand the two profilesdemo-complain(flags=(complain)) anddemo-kill(flags=(kill)).- The three records are from
apparmor_parser -r demo.aap, run right after the same file had been added. Logged by a Debian sid guest (kernel 7.3.4, a distribution kernel without Ubuntu's AppArmor patches); the field names and their order were checked against the kernel source the map describes. On the slide the prefixaudit: type=1400 audit(SECONDS:SERIAL):is left out andinfo="same as current profile, skipping" profile="unconfined"is replaced by...andcomm="apparmor_parser"is left off. In full:apparmor="STATUS" operation="profile_replace" info="same as current profile, skipping" profile="unconfined" name="demo" pid=1299 comm="apparmor_parser", then the same fordemo-complainanddemo-kill, with audit serials 164, 165 and 166. - The parser in the guest was the one built from the AppArmor tree, run as
apparmor_parser --config-file=/dev/null -K -I DIR(-Kis--skip-cache); the slide writesapparmor_parser. - Per profile libapparmor opens the file (
openatwithO_WRONLY | O_CLOEXEC), writes the whole buffer with onewrite()and closes it. The directory itself is opened once per parser run. - The kernel accepts only a write that starts at offset 0; for any other offset the parser's text is
Bad write position. Each write is unpacked by itself, so it must hold complete policy: a profile cannot be sent in pieces. - The bytes are the binary policy, or a zstd-compressed one when the parser's compression is on; see The binary policy format.
- Remove writes the profile's full name with its terminating zero byte:
NAME,PARENT//CHILDfor a child,:NS://NAMEfor a profile in a namespace. - Compiling from text, the parser writes a profile's hats and child profiles separately, each in a write of its own and named
PARENT//CHILD, after the profile itself: parser_interface.c:783-785, parser_policy.c:84-88. .loadand.replacealso take a binary that holds several profiles, for example a profile with its children or its hats. When the compiled policy comes from the cache, or from a binary file given with-B, the whole file with every profile in it is one buffer and one write. The kernel treats that as one set that is loaded or refused together. See The policy cache.-Q,--skip-kernel-load: the action stays as given and everything else runs, the cache included; only the write is left out. It does not count as an action, so-Q -ris allowed.-S,--stdoutand-o FILE,--ofile FILEare actions: the binary goes to standard output or to FILE, which-Baccepts later. Both also skip reading the cache.-N(--names) and-p(--preprocess) do not write to the kernel either.- With any of these the parser does not open the directory of the three files, so the run needs no privilege to manage policy.
-Kis a different option:--skip-cache. - Known discrepancy: A child or hat that the kernel refuses is reported and then ignored: exit status 0.
- Known discrepancy: Cache hit on an uncompressed cache loads the profile twice and writes the cache without -W.
for AppArmor developers for security researchers
In the code
- One profile at a time:
load_policy_list()parser_policy.c:70-82 and__sd_serialize_profile()parser_interface.c:715-765; hats follow at parser_interface.c:783-790. write_policy_buffer_to_iface()kernel_interface.c:142-164; onewrite()when the kernel haspolicy/set_loadkernel_interface.c:82-92 kernel_interface.c:114-130, which the kernel declares at apparmorfs.c:2634.- Offset 0 only: apparmorfs.c:468-470 (
-ESPIPE). - The name written for remove:
fqname()profile.h:463-470; the kernel terminates it itself apparmorfs.c:736-750. - Cache and
-B: parser_main.c:1219-1222 parser_main.c:1367-1372; a set fails as a whole policy.c:1448-1462. kernel_load: default parser_common.c:68;-Qparser_main.c:817-818;-Sparser_main.c:616-620;-oparser_main.c:622-632; the directory is opened only when it is set parser_main.c:1852-1858.
04 What the kernel does with a write
Three checks: may the writer manage policy, does the binary verify, and is the name loaded. Identical bytes are skipped. Nothing changes until every check has passed.
The kernel doesn't trust what arrives. First question: may this process manage policy? If not, the write fails, and the parser tells you that you need policy admin privileges. Second, the binary is unpacked and verified. We once fed .load three hundred random bytes: the write failed, and the log said invalid profile format. Third, the name. Is a profile called demo loaded already? Through .load, that's an error. Through .replace, it decides between adding and replacing. There's one shortcut: if the bytes are exactly the ones already loaded, the kernel skips the work. Only after every check has passed does anything change. So a load that fails leaves the old profile in place.
Details and sources
Details
- The order on the slide is the order in the kernel: the permission check, the copy of the data, unpack and verify, the lookup of each name, and only then the change.
- Check 1. A writer that may not manage policy gets "permission denied" from the write. The parser's text for that refusal is
PROGNAME: Access denied. You need policy admin privileges to manage profiles.PROGNAME: Permission denied. You need policy admin privileges to manage profiles.is printed for a different error: the one the kernel returns when a profile marked immutable is replaced The kernel also logs aSTATUSrecord whoseinfo=ispolicy_locked,not privileged for target profileornot policy admin. From the source, not run. The mode of the files is not the check. Who passes it is Who can change policy. - The parser does not check for root itself; it leaves the decision to the kernel.
- Check 2. The record on the slide is real: 300 bytes from
/dev/urandomwere written to.loadwithcat.catprintedwrite error: Protocol not supportedand the kernel loggedapparmor="STATUS" info="invalid profile format" error=-93 profile="unconfined" pid=1317 comm="cat". Logged by a Debian sid guest (kernel 7.3.4, a distribution kernel without Ubuntu's AppArmor patches); the field names and their order were checked against the kernel source the map describes. The slide leaves out the prefix and the last three fields. What is verified is Unpacking and verifying policy. - Check 3. Each profile in the write is looked up by name. Without the replace permission of
.replace, a loaded name fails the whole write. A profile that is new gets its parent looked up as well. - The shortcut: the kernel keeps the bytes of every load when it is built and set to export binary policy (the default); without that every replace is carried out. A replace whose bytes equal the ones the loaded profile came from is logged with
info="same as current profile, skipping"and not carried out; the write still succeeds. The comparison is on bytes, not on rules: the same text compiled to different bytes is replaced for real (derived from the source). - "Only now": the kernel's own comment at that point is "Done with checks that may fail - do actual replacement". A write with several profiles (a cache file,
-B) is loaded or refused as one set; after a failure each other profile of the write gets a record withinfo="valid profile in failed atomic policy load"or"unchecked profile in failed atomic policy load". - A namespace named by the write, and placeholder parents of a child profile, are created before the last check and stay after a failure; no loaded profile changes.
- A profile marked immutable cannot be replaced.
- Known discrepancy: Kernel: a refused add is logged as
profile_replacewithinfo="profile can not be replaced"; the specific reasons are never printed. From the source, not run.
for AppArmor developers for security researchers
In the code
policy_update()apparmorfs.c:607-684:aa_may_manage_policy()at apparmorfs.c:625, compression and header detection apparmorfs.c:637-670, thenaa_replace_profiles()apparmorfs.c:673.aa_may_manage_policy()policy.c:1001-1029;aa_policy_admin_capable()policy.c:927-939. The parser's two texts: parser_interface.c:76-83; no root check: parser_main.c:985-999.aa_replace_profiles()policy.c:1184-1472:aa_unpack()policy.c:1200; one namespace per set policy.c:1210-1228; the lookup withnoreplacepolicy.c:1271-1275 and__lookup_replace()policy.c:1122-1136; the comment and the loop that changes things policy.c:1354-1414; the skip policy.c:1362-1372; the failure path policy.c:1447-1462.- The stored bytes are compared in policy_unpack.c:102-111 and policy.c:1245-1263.
05 One record per profile, and the list
A STATUS record names the operation, the writer's label in profile= and the changed profile in name=. /sys/kernel/security/apparmor/profiles lists what is loaded.
How do you know it worked? The parser says nothing on success, but the kernel writes one status record per profile. The first one's operation is profile_load, and two fields are easy to mix up. Profile is who did it: the parser, running unconfined. Name is the profile that changed. Replace the same file again and the operation becomes profile_replace, with a note: same as current profile, skipping. Nothing was swapped. Remove gives profile_remove. One surprise: the operation follows what the kernel did, not the option you typed, so -r on a new name logs profile_load. For the state right now, the profiles file in securityfs lists every loaded profile with its mode.
Details and sources
Details
- The three records are from three runs on the same file, in this order:
-a,-r,-R. Logged by a Debian sid guest (kernel 7.3.4, a distribution kernel without Ubuntu's AppArmor patches); the field names and their order were checked against the kernel source the map describes. On the slide the prefixaudit: type=1400 audit(SECONDS:SERIAL):is left out, the first record is broken over two lines and...stands forprofile="unconfined"in the second and forpid=1306 comm="apparmor_parser"in the third. The parser in the guest was the one built from the AppArmor tree, run asapparmor_parser --config-file=/dev/null -K -I DIR(-Kis--skip-cache); the slide writesapparmor_parser. - In full:
apparmor="STATUS" operation="profile_load" profile="unconfined" name="demo" pid=1292 comm="apparmor_parser";apparmor="STATUS" operation="profile_replace" info="same as current profile, skipping" profile="unconfined" name="demo" pid=1299 comm="apparmor_parser";apparmor="STATUS" operation="profile_remove" profile="unconfined" name="demo" pid=1306 comm="apparmor_parser". Each run logged three records, one per profile of the file. - The form:
apparmor="STATUS" operation="OP" [info="TEXT" [error=N]] [namespace="NS"] profile="WRITER" name="TARGET" pid=N comm="C" [ns="TARGETNS"]. profile=is the label of the process that wrote,unconfinedfor a root shell.name=is the profile loaded, replaced or removed.info=appears only when there is something to say, anderror=only with it and only when the write failed.- The operation is chosen for each profile by what the kernel found:
profile_loadwhen no profile of that name was loaded,profile_replacewhen one was, whichever file was written. So-rof a new name logsprofile_load. - A replace that changes a loaded profile logs the
profile_replaceline withoutinfo=. From the source: the guest run that changed demo's rules did not keep its record. - The record does not say which rules changed. With the audit daemon running the same record is in the audit log as
type=AVC msg=audit(...): apparmor="STATUS" .... Where records go is Reading a denial. - The
profilesfile: one lineNAME (MODE)per loaded profile; MODE isenforce,complain,kill,unconfinedoruser. A child is listed asPARENT//CHILD, a profile of a visible child namespace as:NS:NAME (MODE). The linedemo (enforce)on the slide is from the source, not run: no guest run printed the file. - Reading the file needs the right to view policy (in the first user namespace: effective user or group 0), although its mode is 0444.
aa-statusreads this file and reports the modeuserasprompt; see aa-status and aa-enabled. - Each loaded profile also has a directory under
policy/profiles/; see apparmorfs. - Known discrepancy: Kernel: the
profile_removerecord of a namespaced name logsns=with the rest of the written string. From the source, not run.
for AppArmor developers for security researchers
In the code
audit_policy()policy.c:840-876; the operation names audit.h:103-105; load or replace per profile policy.c:1360; the record of a real replace policy.c:1388-1389; of a remove policy.c:1541-1543.- Field order: audit.c:97-140;
pid=andcomm=come from the common LSM audit code. - The
profilesfile:seq_show_profile()apparmorfs.c:2539-2549; the mode names policy.c:94-100; the permission to open it apparmorfs.c:2558-2564 andaa_policy_view_capable()policy.c:907-925. aa-statusand the modeuser: aa_status.c:294-295.
06 Replace under a running program
A replaced profile needs no restart. The old version points at the new one, and each running process is judged by the new rules from its next checked operation.
Here's the case you'll meet most. Demo is running, a long-lived service, and you replace its profile. Do you have to restart it? No. And the kernel doesn't go looking for demo's processes either. It puts the new profile on the list under the same name, marks the old one stale, and leaves a forwarding note on it that points at the new one. Demo still holds the old profile. But the next time one of its operations is checked, a file open, a network call, a capability, the kernel follows the note and judges by the new rules. So the change lands at each process's next checked operation. In practice, that's at once.
Details and sources
Details
- From the source, not run for this deck. The same behaviour was observed on a running kernel for Labels in the kernel, scene "A profile is replaced under a running task": a shell that tried two files every three seconds followed three replacements of its profile without being restarted.
- What the guest runs of this deck show is the replace itself: after
apparmor_parser -rwith the new rule, a newly startedcatunder the profile could open the file. - "Forwarding note" is a comparison. The kernel keeps, for every profile, a small object that says which version is current. A replacement points it at the new version and marks the old one stale.
- No process is visited at the time of the write. Every checked operation starts by looking at the process's own label; when that label is stale, the current version is used for the check. The process's credentials are brought up to date when it next returns to user space.
- So the new rules apply from each process's next checked operation: a file open, a socket call, a capability check, a signal, an exec.
- A replace that is skipped as identical changes nothing for running processes.
- An exec transition that was already taken is not redone: a process that moved into another profile stays in that profile's current version, and changed exec rules count for later execs. See Exec and domain transitions.
- Children and hats that the new file no longer defines stay loaded; the kernel hands them to the new version of the parent (derived from the source, not run).
- Files that are already open: the permission remembered on an open file belongs to the label that opened it, and a use under the newer label is checked again against the current rules. This reading of the source is partial (sockets and inherited files take other paths) and nothing was run for it.
- Known discrepancy, described in Labels in the kernel: Kernel: a stacked label follows only the first replacement of a member profile, because
__label_replaceis called insideAA_BUG. It concerns tasks under a stack of profiles, not the plain case on this slide.
for AppArmor developers for security researchers
In the code
__replace_profile()callsaa_label_replace(&old->label, &new->label)policy.c:1066-1110; the caller shares the name first policy.c:1391-1393.aa_label_replace()label.c:849-875: the proxy is shared and redirected label.c:75-97, the old label getsFLAG_STALE.- Readers:
__begin_cred_crit_section()cred.h:149-161 andaa_get_newest_label()label.h:408-429. - The credentials are replaced by task work on return to user space: task.c:93-117 and
aa_replace_current_label()task.c:48-91. - Stacked labels are rebuilt after the load:
__aa_labelset_update_subtree()policy.c:1414 label.c:2135-2175. - Children kept: policy.c:1070-1092. Open files: file.c:655-669.
Read more
- Labels in the kernel, Exec and domain transitions.
- wiki: apparmor_kernel_development_guide: labels and proxies as design notes; where it and the code differ, this deck follows the code.
07 Remove leaves running programs unconfined
-R does not stop a program: it leaves it unconfined. Loading the profile again does not confine it again; a profile is entered at exec or on request. To change a profile use -r.
Remove looks like the opposite of add, and for the list it is. For a running program it's something else. Take demo's profile out while demo runs. Demo isn't stopped. The forwarding note on its old profile now points at unconfined, so from its next checked operation demo runs with no confinement from that profile. And here's the trap: load the profile again, and the running demo doesn't come back under it. A profile is entered when a program is executed, or when it asks to change profile. A load doesn't do that. So to change a profile, replace it. Keep remove for profiles you really want gone. And if you load one again, restart whatever was running under it.
Details and sources
Details
- From the source, not run for this deck. Observed for Labels in the kernel, scene "A profile is replaced under a running task": after
apparmor_parser -Rthe running shell's label readunconfinedand both test files were readable. - Remove takes the profile and its children off the list and points their "which version is current" object at the
unconfinedlabel of the namespace the profile was in. The kernel's own description: "mark them as replaced by unconfined". - The process follows that pointer at its next checked operation, exactly as for a replacement. It is not signalled and not stopped.
- Loading the profile again creates a new profile with that name. A process is put under a profile at exec, when the profile attaches to the program or an exec rule names it, or when the process asks with a change of profile (
aa-exec -pdoes that for the command it starts). A load does neither (derived from the source). See Exec and domain transitions. - The unit file of the AppArmor tree gives the same reason for its empty stop action: "removing AppArmor confinement from running processes (and not being able to re-apply it later)".
- The kernel's note on resource limits: "removing confinement does not restore rlimits to preconfinement values". A limit the profile had set with an rlimit rule stays on the process.
- For a process under a stack of profiles only the removed member becomes
unconfinedwhen the stacked label is rebuilt (derived; see the known discrepancy named under the previous scene). - The record is
operation="profile_remove"withname=the profile; it is written after the removal. - A name that is not loaded: the write fails and the record has
info="profile does not exist". An empty name:info="no profile specified". A name:NS:alone removes that namespace. From the source, not run.
for AppArmor developers for security researchers
In the code
aa_remove_profiles()policy.c:1488-1556; the comments quoted above policy.c:1481-1484.__remove_profile()policy.c:200-243 callsaa_label_remove()label.c:785-798, which is__label_remove(label, ns_unconfined(labels_ns(label)))label.c:604-625.- When the newest label is unconfined the task's pending transition state is cleared task.c:72-77.
- The unit file: apparmor.service:25-32.
08 Loading at boot
The shipped unit runs apparmor_parser --replace -- /etc/apparmor.d at boot and on reload. Its stop is /bin/true; aa-teardown unloads every profile.
Who runs the parser when the machine boots? In the AppArmor source it's a systemd unit, ordered early, before most services start. It runs a small script, and the script comes down to one parser run over all of /etc/apparmor.d, with replace. Replace, not add, so the same command works as a reload on a running system. The parser walks the directory itself and compiles files in parallel. Now look at stop: it does nothing, on purpose. Systemd restarts a unit by stopping and starting it, and unloading every profile would leave running programs unconfined. If that's what you want, aa-teardown does it, writing each loaded name to .remove. Your distribution may wrap all this differently.
Details and sources
Details
- This is what the AppArmor tree ships in its
init/directory, read and not run. Which unit, script andparser.confa distribution installs is not in the tree. apparmor.service:Type=oneshot,ExecStart=/lib/apparmor/apparmor.systemd reloadand the same line forExecReload. OrderedBefore=sysinit.targetandAfter=local-fs.target;ConditionSecurity=apparmor;AssertPathIsReadWrite=/sys/kernel/security/apparmor/.load;RequiresMountsFor=/var/cache/apparmor.apparmor.systemd reloadreads the function libraryrc.apparmor.functionsand ends in/sbin/apparmor_parser [--quiet] --replace -- /etc/apparmor.d.--quietis added on a quiet boot. One more directory can be named in the script; it is empty in the tree.- The parser is given the directory and walks it itself, loading each file, with several jobs in parallel.
- If the parser exits with a non-zero status the script prints
Error: At least one profile failed to loadand fails. - No cache option is on that command line. What the run takes from the cache is decided by
/etc/apparmor/parser.confand the parser's defaults; see The policy cache. start(the path without systemd) runs the parser with--add, and only when theprofilesfile is empty; otherwise it reports that profiles are already loaded.ExecStop=/bin/true. The comment in the unit: systemd maps restart to stop and start, "which means removing AppArmor confinement from running processes (and not being able to re-apply it later)".aa-teardownrunsapparmor.systemd stop: the script reads theprofilesfile, strips the mode, sorts, leaves out child names (a parent takes its children with it) and writes each name to.removewithprintf, without the parser.- In a container the script does nothing unless the container has its own policy namespace.
- One profile on demand:
profile-load NAMEruns/sbin/apparmor_parser -r -W /etc/apparmor.d/NAME.aa-loadloads cache files, always through.replace. - Known discrepancy:
aa-teardowncannot unload a profile whose mode the kernel prints asuser. From the source, not run.
for AppArmor developers for security researchers
In the code
- The unit: apparmor.service:1-36. The script: apparmor.systemd:79-114.
parse_profilesand the command line: rc.apparmor.functions:121-141, the action words rc.apparmor.functions:160-167;PARSERand the directories rc.apparmor.functions:34-52;remove_profilesrc.apparmor.functions:246-282; start only when nothing is loaded rc.apparmor.functions:217-244; containers rc.apparmor.functions:85-119.- The parser's directory walk and its jobs: parser_main.c:1939-1957 parser_main.c:1678-1695.
aa-teardown: aa-teardown:10;profile-load: profile-load:52;aa-load: aa_load.c:113 aa_load.c:247.
09 From the write to what it changes
-a, -r, -R; one write and one record per profile. Roads: the pipeline and the binary format, the cache, the kernel side, labels and exec, namespaces, aa-status and denials.
That's the last stretch of a profile's journey: one action, one write per profile, a few checks, one record, and running programs that follow along. Where next? Back up the road, the pipeline deck shows the whole parser run, and the binary format deck opens up what was written. The cache deck explains how a load can skip compiling. On the kernel side there's unpacking and verifying, the filesystem these three files live in, and who may change policy. Labels in the kernel shows the forwarding note for real, and the exec deck shows how a program enters a profile. Namespaces covers -n. And for looking at the result: aa-status, and reading a denial.
Details and sources
Details
-n NAME,--namespace NAMEputs every profile of the run into the policy namespace NAME. The namespace travels inside the binary; the file written is still.loador.replace, and for remove the namespace is part of the name,:NS://NAME. Policy namespaces has the rest.
Read more
- From profile text to kernel, The binary policy format, The policy cache, Running apparmor_parser.
- Unpacking and verifying policy, apparmorfs, Who can change policy.
- Labels in the kernel, Exec and domain transitions.
- Policy namespaces, aa-status and aa-enabled, Reading a denial, The policy cache and kernel interface API.
- apparmor_parser(8), --add, --replace, --remove, --namespace, aa-teardown(8), apparmor.net: Integrate and manage AppArmor in your environment.
Read more
Basis of the statements on this page: "guest" means the command was run in a disposable Debian sid virtual machine (kernel 7.3.4, a distribution kernel without Ubuntu's AppArmor patches) with the parser built from the AppArmor commit 836052d21, run as apparmor_parser --config-file=/dev/null -K -I DIR; the records are quoted without the prefix audit: type=1400 audit(SECONDS:SERIAL):. "source" means read in the AppArmor tree or in the kernel source the map describes, and not run. "derived" means reasoned from the source. Nothing on this page was run on the kernel the map describes; the field names and their order in the guest's records were checked against it.
The three actions
| Option | File written | What is written | Name not loaded | Name loaded | With -v |
|---|---|---|---|---|---|
-a, --add, or no action option | .load | the binary policy of one profile | added | refused: Unable to add "NAME". Profile already exists | Addition succeeded for "NAME". |
-r, --replace (--reload) | .replace | the binary policy of one profile | added | replaced, or skipped when the bytes are the loaded ones | Replacement succeeded for "NAME". |
-R, --remove | .remove | the profile's full name and a zero byte | refused: Unable to remove "NAME". Profile doesn't exist | removed with its children | Removal succeeded for "NAME". |
The two refusals are from the source. Guest: -a, -r and -R of demo.aap in this order each exited with status 0 and printed nothing.
- One action per run:
-a,-r,-R,-S,-o,-Nand-pcount; two givePROGNAME: Too many actions given on the command line.and exit status 1 (source). - After a refused add the parser stops loading the remaining profiles of that file (source).
- For remove the file is parsed in full and no binary is built. The name is
NAME,PARENT//CHILDor:NS://NAME.-Ralso skips the cache.-Rwith-Bis refused:Error: Invalid load option specified: 2(source). - A file whose name is in
/etc/apparmor.d/disable/is skipped for add and replace:Skipping profile in DIR/disable: NAME(source).
Compiling without loading
| Option | Counts as an action | What happens |
|---|---|---|
-Q, --skip-kernel-load | no | the given action runs, the cache included; the write to the kernel is left out |
-S, --stdout | yes | the binary goes to standard output; the cache is not read |
-o FILE, --ofile FILE | yes | the binary goes to FILE; the cache is not read |
-N, --names | yes | prints the profile names |
-p, --preprocess | yes | prints the text after includes |
With each of these the parser does not open the directory of the three files (source). A file written with -S or -o is what -B, --binary loads later. -K is --skip-cache and has nothing to do with the kernel write. Every option is in Running apparmor_parser.
Loading into a namespace
-n NAME, --namespace NAME sets the policy namespace of every profile of the run; a file that names another namespace gets the warning -n NAME overriding policy specified namespace :OTHER:. The namespace is inside the binary, the file written is still the root .load or .replace, and the kernel finds or creates the namespace. One write must not mix namespaces: info="policy load has mixed namespaces". For remove the namespace is in the name, :NS://NAME, and :NS: alone removes the namespace. All from the source. See Policy namespaces.
Known discrepancy: -n does not skip the policy cache, so a cached profile can be loaded into the wrong namespace.
The three files
/sys/kernel/security/apparmor/.load, .replace and .remove. libapparmor finds the directory through the mount table and falls back to that path; -f DIR, --subdomainfs DIR names it. The directory is opened once per run. Each namespace directory under policy/namespaces/ has its own three files.
- One call is one
openat, onewriteof the whole buffer and one close. - A write must start at offset 0; otherwise the kernel refuses it and the parser prints
Bad write position. - The parser calls once per profile, and once more for each hat. From the cache or with
-Bthe whole file is one write, and the kernel loads or refuses it as one set. - The buffer is the binary policy, plain or zstd-compressed, with or without the header the cache puts in front; the kernel recognises each. See The binary policy format.
- The mode of the files is not the access control; the handler checks the writer. See Who can change policy.
What the kernel does with a write, in order
1. The writer must be allowed to manage policy; otherwise the write fails and a STATUS record says why. 2. The data is copied in, unpacked and verified; a refused buffer changes nothing. Guest: 300 random bytes to .load gave write error: Protocol not supported and apparmor="STATUS" info="invalid profile format" error=-93 profile="unconfined" pid=1317 comm="cat". 3. All profiles of the write must be for one namespace, which is found or created. 4. Each name is looked up. A loaded name fails the write unless it came through .replace. A new profile needs its parent; a missing parent is filled in with an empty placeholder profile. 5. From here nothing can fail. Per profile: identical bytes are skipped, otherwise the record is written and the profile is added or replaced. 6. Stacked labels that contain a replaced profile are rebuilt.
A profile marked immutable cannot be replaced. Children of the old profile that the new one does not define are kept (derived).
The STATUS record
apparmor="STATUS" operation="OP" [info="TEXT" [error=N]] [namespace="NS"]
profile="WRITER" name="TARGET" pid=N comm="C" [ns="TARGETNS"]
| Field | Meaning |
|---|---|
operation | profile_load, profile_replace or profile_remove: what the kernel did to this profile. -r of a name that is not loaded logs profile_load |
info | present only when there is something to say |
error | present only with info and only when the write failed |
namespace, profile | the label of the process that wrote; unconfined for a root shell |
name | the profile loaded, replaced or removed |
pid, comm | the process that wrote |
ns | the target namespace, when the load named one |
Guest, one record per profile of the file (demo, demo-complain, demo-kill):
| Command | Record for demo |
|---|---|
-a demo.aap | apparmor="STATUS" operation="profile_load" profile="unconfined" name="demo" pid=1292 comm="apparmor_parser" |
-r demo.aap, unchanged | apparmor="STATUS" operation="profile_replace" info="same as current profile, skipping" profile="unconfined" name="demo" pid=1299 comm="apparmor_parser" |
-R demo.aap | apparmor="STATUS" operation="profile_remove" profile="unconfined" name="demo" pid=1306 comm="apparmor_parser" |
With the audit daemon the guest's audit log had type=AVC msg=audit(1794831843.372:434): apparmor="STATUS" operation="profile_replace" info="same as current profile, skipping" profile="unconfined" name="demo" pid=2056 comm="apparmor_parser". A replace with changed rules logs the profile_replace line without info= (source; the guest run that changed the rules did not keep its record).
Texts of info= on this path, all from the source and not run:
info= | When |
|---|---|
same as current profile, skipping | the bytes are the ones the loaded profile came from (guest) |
invalid profile format and the unpacker's other texts | the buffer does not verify (guest for this one); see Unpacking and verifying policy |
policy_locked, not privileged for target profile, not policy admin | the writer may not manage policy |
policy load has mixed namespaces, failed to prepare namespace | the namespace of the write |
profile can not be replaced | a loaded name through .load, or an immutable profile |
parent does not exist | a child whose parent cannot be found or made |
failed to create raw_data dir and files, failed to create | the entries under policy/ |
valid profile in failed atomic policy load, unchecked profile in failed atomic policy load | the other profiles of a write that failed |
no profile specified, namespace does not exist, profile does not exist | remove |
Messages of the parser
| Message | When |
|---|---|
Unable to add "NAME". Profile already exists | -a of a loaded name |
Unable to remove "NAME". Profile doesn't exist | -R of a name that is not loaded |
Access denied. You need policy admin privileges to manage profiles. | the kernel refused the writer |
Permission denied. You need policy admin privileges to manage profiles. | replacing a profile marked immutable |
Bad write position | a write that does not start at offset 0 |
Profile doesn't conform to protocol, Profile version not supported by Apparmor module, Profile does not match signature | the kernel refused the buffer |
Too many actions given on the command line. | two actions |
Cached reload succeeded for "FILE". | -v, the binary came from the cache |
All from the source. The exit status is not in the manual page (known discrepancy: apparmor_parser(8) does not document the exit status).
Running programs
| Replace | Remove | |
|---|---|---|
| The running process | keeps running | keeps running |
| Its confinement | the new version, from its next checked operation | unconfined of the profile's namespace, from its next checked operation |
| A restart | not needed | needed to confine it again, after the profile is loaded |
| Children and hats | those the new file lacks stay loaded (derived) | removed with the parent |
| Resource limits set by the profile | stay as they were |
From the source. Observed on a running kernel for Labels in the kernel: a shell followed three replacements and a removal of its profile without a restart. Not determined: whether every file that is already open is checked again under the new rules; what a kernel with Ubuntu's patches does differently.
The list of loaded profiles
/sys/kernel/security/apparmor/profiles: one line NAME (MODE) per profile of the reader's namespace and the namespaces below it; MODE is enforce, complain, kill, unconfined or user; children as PARENT//CHILD; profiles of a child namespace as :NS:NAME (MODE). The namespace's own unconfined is not listed. The file shows names and modes, not rules. Opening it needs the right to view policy. Source; no guest run printed the file. aa-status reads it; see aa-status and aa-enabled.
At boot, as shipped in the AppArmor tree
| File | What it does |
|---|---|
init/apparmor.service | ExecStart and ExecReload: /lib/apparmor/apparmor.systemd reload; ExecStop=/bin/true; before sysinit.target |
init/apparmor.systemd | reload: /sbin/apparmor_parser [--quiet] --replace -- /etc/apparmor.d; start: the same with --add, only when nothing is loaded; stop: unload everything |
init/rc.apparmor.functions | the functions behind them |
init/aa-teardown | apparmor.systemd stop: each name of the profiles file, without children, is written to .remove |
init/profile-load NAME | /sbin/apparmor_parser -r -W /etc/apparmor.d/NAME |
aa-load | loads cache files through .replace |
Source. What a distribution installs is not in the tree.
Known discrepancies
- Kernel: a refused add is logged as
profile_replacewithinfo="profile can not be replaced"; the specific reasons are never printed. - Kernel: the
profile_removerecord of a namespaced name logsns=with the rest of the written string. aa-teardowncannot unload a profile whose mode the kernel prints asuser.- next_profile_buffer reads past the end of the policy buffer on kernels without set_load.
- A child or hat that the kernel refuses is reported and then ignored: exit status 0.
- Cache hit on an uncompressed cache loads the profile twice and writes the cache without -W.
-ndoes not skip the policy cache, so a cached profile can be loaded into the wrong namespace.- Duplicate-definition and load messages name a profile without its namespace or parent.
The first three are from reading the source for this deck and were not run.
for AppArmor developers for security researchers
In the code
| Step | Where |
|---|---|
| the action and its count | parser_main.c:543-545 parser_main.c:583-590 parser_main.c:957-961 |
| one profile at a time | parser_policy.c:70-82 parser_interface.c:715-765 |
| the three library calls | kernel_interface.c:314-319 kernel_interface.c:357-363 kernel_interface.c:400-406 |
| open, write, close | kernel_interface.c:142-164 |
| the kernel's file handlers | apparmorfs.c:687-757 |
policy_update() | apparmorfs.c:607-684 |
aa_may_manage_policy() | policy.c:1001-1029 |
aa_replace_profiles() | policy.c:1184-1472 |
aa_remove_profiles(), __remove_profile() | policy.c:1488-1556 policy.c:200-243 |
audit_policy() | policy.c:840-876 |
aa_label_replace(), aa_label_remove() | label.c:849-875 label.c:785-798 |
| a stale label is followed | cred.h:149-161 label.h:408-429 |
| the credentials are updated | task.c:48-117 |
the profiles file | apparmorfs.c:2475-2564 |
| the files are created | apparmorfs.c:2936-2952 apparmorfs.c:2253-2269 |
Read more: apparmor_parser(8), --add, --replace, --remove, aa_kernel_interface(3), aa-teardown(8), wiki: AppArmorInterfaces.
Roads from here
START HERE
- From profile text to kernel — the whole parser run that ends in this write
ATTACHMENT, NAMESPACES, STACKING
- Policy namespaces — the namespace option and loading into a namespace
SECURITY · threat model and limits
- Who can change policy (no slides yet) — who may write to the three files
RUNNING THE PARSER
- Running apparmor_parser (no slides yet) — every option of the parser
- The policy cache (no slides yet) — loading a compiled profile without compiling
- Reading a denial — reading STATUS and DENIED records
TOOLS · utils/
- aa-status and aa-enabled (no slides yet) — the tool that reads the list of loaded profiles
LIBAPPARMOR
- The policy cache and kernel interface API (no slides yet) — the library calls behind the three writes
IN THE KERNEL
- Unpacking and verifying policy (no slides yet) — how the kernel verifies what arrives
- apparmorfs (no slides yet) — the filesystem the three files live in
- Labels in the kernel — how a running task follows a replaced profile
- Exec and domain transitions — how a program enters a profile
THE DFA ENGINE · libapparmor_re
- The binary policy format — the bytes that are written