From profile text to kernel

text to kernel tables for everyone

What one apparmor_parser run does. The profile text is read, compiled into matching tables and packed into a binary blob that is cached and written to the kernel in one write. libapparmor and the aa-* tools sit around that path.

On the map: start here

▶ Watch this deck — 9 scenes, ~7 min

Worth seeing first

  • Why AppArmor — what a profile is, before following it into the kernel

Part of journeys

  • From profile text to kernel tables, step 1 of 13 · next: The lexer

01 The kernel does not read your profile

FROM TEXT TO KERNEL /etc/apparmor.d/demo abi <abi/5.0>, include <tunables/global> profile demo /usr/bin/demo { include <abstractions/base> network inet stream, /etc/demo/** r, /etc/demo/*.conf r, owner /var/lib/demo/** rwk, /usr/bin/demo-helper Px -> demo-helper, } kernel demo (running) profile demo matching tables, no text saving the file changes nothing $ apparmor_parser -r /etc/apparmor.d/demo apparmor_parser -r: replace what is loaded this deck follows that one command
A profile file with one edited rule on the left, the kernel holding matching tables for the running demo program on the right, and apparmor_parser between them carrying the change across

The kernel holds compiled policy, not profile text. apparmor_parser -r FILE compiles a profile file and replaces the loaded profiles with the result.

You tighten one rule in demo's profile, save the file, and demo carries on exactly as before. Why? Because the kernel doesn't read profile files. It couldn't use them if it did: it has to answer in the middle of a system call, so it works from compact matching tables, not from text. Something has to turn your text into those tables and hand them over. That something is apparmor_parser, and -r tells it to replace the profile that's already loaded. This deck follows that one command, from the text file to a check in the kernel.

Details and sources

Details

  • The command: apparmor_parser -r FILE. -r is --replace (parser_main.c:156); the other two commands are -a (--add) and -R (--remove).
  • What the kernel holds can be read back: /sys/kernel/security/apparmor/profiles lists every loaded profile with its mode (apparmorfs.c:2709), and /sys/kernel/security/apparmor/policy/profiles/NAME.N/ has one directory per profile with the files name, mode and attach (apparmorfs.c:2038-2050) and a link raw_data to the binary policy it was loaded from (apparmorfs.c:1980).
  • There is no file there that holds the profile text. The kernel receives only the binary form.
  • /sys/kernel/security/apparmor/revision is a counter of policy changes (apparmorfs.c:2954).
  • To compile without loading: apparmor_parser -Q FILE (--skip-kernel-load, parser_main.c:169).

02 Four stops in one run

ONE RUN OF APPARMOR_PARSER 1 ask the kernel /sys/kernel/security/ apparmor/features which rule kinds it supports /etc/apparmor.d/demo 2 read the text includes, variables, aliases syntax errors name file and line 3 compile rules become matching tables 4 pack and write one blob kernel 1 ask the kernel a rule kind the kernel lacks is left out, and the profile still loads silently, unless you pass --warn=rule-not-enforced
Four boxes in a row for the four stops of one apparmor_parser run: ask the kernel, read the text, compile, pack and write, ending in the kernel

Features, text, tables, blob. A rule class the kernel does not support is dropped and the profile still loads; --warn=rule-not-enforced (or --warn=all) makes the parser say so.

One run of apparmor_parser makes four stops. First, it asks the kernel which kinds of rule it supports. Second, it reads your file and everything the file includes, fills in the variables, and if the syntax is wrong it stops and names the file and the line. Third, it compiles the rules into matching tables. Last, it packs those tables into one binary blob and writes it to the kernel. Keep the first stop in mind. A kind of rule your kernel doesn't support is left out of the tables, the profile still loads, and by default nothing tells you.

Details and sources

Details

  • Stop 1, features: the parser reads /sys/kernel/security/apparmor/features (features.c:53). --kernel-features FILE uses a file instead (parser_main.c:196).
  • Stop 2, text: includes are looked up in the base directory, default /etc/apparmor.d. -p (--preprocess) prints the text with includes resolved and stops; -N (--names) prints the profile names and stops (parser_main.c:163, parser_main.c:183).
  • A syntax error has the form AppArmor parser error for FILE in profile INCLUDED-FILE at line N: TEXT and the parser exits with a non-zero status.
  • Stop 3, compile, and stop 4, load: -Q (--skip-kernel-load) does everything except the load.
  • The dropped rule: a rule class is compiled only when the kernel feature set and the ABI declared by the profile both support it. The warning class is rule-not-enforced, described as "warn if a rule is not enforced" (parser_main.c:281); it is off by default.
  • Observed with the parser built from the AppArmor tree at 836052d21, --kernel-features /dev/null --warn=all, nothing loaded: Warning from profile demo (demo.sd): mqueue type=posix rules not enforced, and likewise "ptrace rules not enforced", "signal rules not enforced", "network rules not enforced", "userns rules not enforced". The exit status stayed 0.
  • A profile without an abi rule gets the warning FILE: File 'NAME' missing feature abi, falling back to default policy feature abi.

for AppArmor developers for security researchers

In the code

03 The same run, by function for AppArmor developers

PARSER STAGES process_profile() parser_main.c:1289 1 lex yylex parser_lex.l 2 parse yyparse() parser_main.c:1353 Profile objects 3 post-process post_process_policy parser_policy.c:179 implied rules, variables, aliases, merge 4 compile process_profile_rules parser_regex.c:1215 DFAs: xmatch, file, policydb 5 serialize sd_serialize_profile parser_interface.c:480 hats and children follow as siblings 6 load aa_kernel_interface_replace_policy kernel_interface.c:357 in libapparmor each profile file is compiled in a forked child unless -j0 (work_spawn, parser_main.c:1472)
Six parser stages under process_profile in two rows: lex, parse and post-process, then compile, serialize and load, each with the function that starts it and its source line

yyparse → post_process_policy → process_profile_rules → sd_serialize_profile → aa_kernel_interface_replace_policy, all called from process_profile() (parser/parser_main.c:1289). Up to three DFAs per profile: xmatch, file, policydb.

If you plan to read the code, here's the same run with one function per stage. Everything hangs off process_profile in parser_main.c. The flex scanner and the bison grammar, driven by yyparse, turn the text into Profile objects. Post-processing adds implied rules, expands variables, applies aliases and merges duplicates. Then process_profile_rules builds up to three DFAs per profile: one for attachment, one for file rules, and one for every other rule class. Serialization writes one tagged stream per profile, with hats and children following their parent as siblings. And the load is a call into libapparmor. Unless jobs is zero, each profile file gets its own forked child.

Details and sources

for AppArmor developers for security researchers

Details

Read at AppArmor 836052d21 (6.0.0~alpha2). The full stage table is in the reference under this deck.

04 The cache skips the compile, not the reading

THE POLICY CACHE /etc/apparmor.d/demo read the text always cached blob newer? than the profile and its includes yes: compile skipped /var/cache/apparmor/<features>.0/demo cached blob kernel no compile fresh blob -W saved only with --write-cache new kernel features: a new directory aa-load: loads cached blobs, no compiler
A flow chart: the profile text is always read, then a question whether the cached blob is newer; yes loads the cached blob and skips the compile, no compiles a fresh blob that is saved only with the write-cache option

Cached policy lives under /var/cache/apparmor/, in a directory named after the kernel feature set. A hit skips compilation only; the profile text is still read to check time stamps. The cache is written only with -W (--write-cache). aa-load loads cached policy without the compiler.

Compiling is the slow part, so the parser can keep its result. A common guess is that a cache hit skips everything. It doesn't. The text is always read, because the parser has to know every file the profile includes before it can tell whether the cache is stale. If the cached blob is newer than all of them, it's loaded as it is and the compile is skipped. If not, the parser compiles, and it saves the fresh blob only when you ran it with the --write-cache option. The cache directory is named after the kernel's feature set, so a kernel with different features starts a new cache instead of loading tables made for another kernel.

Details and sources

Details

  • Default location: /var/cache/apparmor (parser_main.c:1865); -L DIR (--cache-loc) names another.
  • Directory per feature set: /var/cache/apparmor/FEATURES-ID.0/, where the id is a hash of the kernel feature set (policy_cache.c:254-258). apparmor_parser --print-cache-dir prints it for the running kernel.
  • One cache file per profile file, named after its base name.
  • Staleness: a file that is newer than the cache file disables the hit; with debugging the parser says FILE: file 'NAME' is newer than cache file (policy_cache.c:115-117).
  • Writing: only with -W (--write-cache, parser_main.c:175) or write-cache in parser.conf; the variable is 0 by default (parser_main.c:76).
  • Other options: -K (--skip-cache) neither reads nor writes, -T (--skip-read-cache) does not read, --purge-cache clears it (parser_main.c:173-174, parser_main.c:187).
  • aa-load loads cached blobs without the compiler and does not check whether they are stale; the source says // Todo: Check cache validity (aa_load.c:105).
  • Without the kernel interface the parser prints Cache read/write disabled: interface file missing. (Kernel needs AppArmor 2.4 compatibility patch.) (parser_main.c:1731).

for AppArmor developers for security researchers

In the code

  • The text is parsed at parser_main.c:1353, before the test if (cache_hit(cachename)) at parser_main.c:1368; that order is why a hit does not skip reading.
  • The cache file is written to a temporary name and installed only when the run succeeded: if (retval == 0 && write_cache) (parser_main.c:1422-1429).

05 One write, and the profile is replaced

LOADING apparmor_parser write() /sys/kernel/security/apparmor/.replace -a .load -r .replace -R .remove kernel may you manage policy? no: write fails (EACCES) verify the blob bad blob: the write fails, nothing changes swap the profile all profiles of the file are replaced together demo (new rules) running processes get the new rules demo (pid 4242)
apparmor_parser writes the blob to the .replace file; inside the kernel three steps follow: a permission check, verification of the blob and the swap, after which the running demo process carries the new rules

-a, -r and -R write to .load, .replace and .remove under /sys/kernel/security/apparmor/. A rejected blob fails the write and leaves the loaded policy as it was. Replacing a profile updates the processes that carry it.

The hand-over is plainer than you might expect: one write of the whole blob to a file the kernel provides. .load adds a profile, .replace replaces it, .remove takes it out, and the parser picks the file from the option you gave. The kernel first checks that you're allowed to manage policy. Then it verifies the blob, and if anything is wrong, the write fails and the old profile stays as it was. Only then does it swap the new profile in. Processes already running under demo follow the swap, so here, unlike a first load, you don't restart anything.

Details and sources

Details

  • Files: /sys/kernel/security/apparmor/.load, .replace and .remove (apparmorfs.c:2936-2948). libapparmor names them at kernel_interface.c:138-140 and finds the real mount point of securityfs itself.
  • Options: -a (--add), -r (--replace), -R (--remove) (parser_main.c:151-162).
  • The files have mode 0666; permission is decided by the kernel when the write arrives, not by the file mode. In the kernel the write handler first calls aa_may_manage_policy (apparmorfs.c:625).
  • Locked policy: the write fails with EACCES and the audit record has info="policy_locked" (policy.c:1013-1016).
  • The kernel logs each change as a STATUS record, or ERROR on failure, with operation="profile_load", "profile_replace" or "profile_remove" (audit.h:103-105).
  • One write per file when the kernel has the feature policy/set_load (apparmorfs.c:2634, tested by libapparmor at kernel_interface.c:230-248); otherwise one write per profile.
  • Unprivileged policy loading inside a user namespace is governed by the sysctl kernel.unprivileged_userns_apparmor_policy (lsm.c:2454).
  • Not observed on a running kernel; the kernel side is stated from the kernel source.

for AppArmor developers for security researchers

In the code

  • aa_replace_profiles unpacks and verifies everything before it changes anything, then swaps with __replace_profile(ent->old, ent->new) (policy.c:1393) and refreshes the labels with __aa_labelset_update_subtree(ns) (policy.c:1414), which is how running tasks follow the replacement.

06 Unpacked once, walked at every check for AppArmor developers

IN THE KERNEL load: once per write check: at every open .replace policy_update apparmorfs.c:607 aa_may_manage_policy aa_replace_profiles policy.c:1184 aa_unpack policy_unpack.c:1745 verify_header unpack_profile unpack_dfa, verify_dfa __replace_profile policy.c:1393 labels updated demo: open() apparmor_file_open lsm.c:465 aa_path_perm file.c:287 aa_dfa_match match.c:518 walks the tables unpacked above aa_audit audit.c:200 aa_audit_file file.c:95, applies the mode a record only when refused or audited
Two rows of kernel functions. Load: the .replace file, policy_update, and aa_replace_profiles, which runs aa_unpack and then swaps the profile. Check: demo calling open, apparmor_file_open, aa_path_perm, aa_dfa_match walking the unpacked tables, aa_audit_file and aa_audit

Load: policy_update → aa_replace_profiles, which calls aa_unpack and then swaps. Check: apparmor_file_open → aa_path_perm → aa_dfa_match → aa_audit_file → aa_audit. The kernel does not see rule text or globs.

On the kernel side there are two paths, and they meet at the tables. The write lands in policy_update, which checks permission and copies the data in. It calls aa_replace_profiles. That first runs aa_unpack, which verifies the header, then unpacks each profile and its DFAs and verifies those too, and then swaps old for new and refreshes the labels that pointed at the old profile. Later, demo calls open. The file open hook calls aa_path_perm, which builds the path name and walks the file DFA with it. The state the walk ends in carries the permissions. aa_audit_file and aa_audit then apply the profile's mode, and write a record if the answer was no.

Details and sources

for AppArmor developers for security researchers

Details

Paths are under security/apparmor/ in the kernel. Read, not traced on a running kernel.

07 libapparmor: how programs talk to the kernel

LIBAPPARMOR libapparmor kernel apparmor_parser features, cache, load features/ .load .replace demo (your program) aa_getcon aa_change_hat aa_change_profile /proc/PID/attr/ the D-Bus daemon aa_query_label would this label be allowed? .access aa-enabled, aa-status aa_is_enabled, aa_find_mountpoint aa-logprof: the log-line parser profiles no compiler here
Four callers on the left, apparmor_parser, your program, the D-Bus daemon and the aa tools, each reaching a kernel interface on the right through libapparmor in the middle

libapparmor is the C library for talking to the kernel: features, cache and loading for the parser, aa_getcon, aa_change_hat and aa_change_profile for applications, aa_query_label for trusted helpers, and log parsing for the tools. It does not compile policy.

One more piece sits beside the path you just followed. The parser doesn't open those kernel files by hand. It calls libapparmor to read the feature list, manage the cache and do the write. Your own program can use the same library to read its label, or to switch into a hat or another profile. A trusted service such as the D-Bus daemon uses it to ask the kernel whether a label would be allowed something, which is how D-Bus rules get enforced. And the tools use it to find out whether AppArmor is on and to take log lines apart. What it doesn't contain is the compiler: libapparmor knows nothing about the profile language.

Details and sources

Details

Signatures are from apparmor.h at AppArmor 836052d21; link with -lapparmor.

  • Is AppArmor on: int aa_is_enabled(void); (apparmor.h:69-70). It returns 0 with errno set to ECANCELED (disabled at boot), ENOSYS (not present), ENOENT (enabled, interface not found) or EBUSY (only private interfaces) (kernel.c:310-312). The command is aa-enabled.
  • Read a label: int aa_getcon(char **label, char **mode);, int aa_gettaskcon(pid_t target, char **label, char **mode);, int aa_getpeercon(int fd, char **label, char **mode); (apparmor.h:110-113). They read /proc/PID/attr/apparmor/current or /proc/PID/attr/current (kernel.c:424-426).
  • Change confinement: int aa_change_hat(const char *subprofile, unsigned long magic_token);, int aa_change_profile(const char *profile);, int aa_change_onexec(const char *profile);, int aa_stack_profile(const char *profile); (apparmor.h:79-85).
  • Each of these sends one string to the kernel, with the lsm_set_self_attr system call when it is available and otherwise by a write to a file under /proc/PID/attr/ (kernel.c:997-1011): changehat %016lx^%s (kernel.c:1033), changeprofile %s (kernel.c:1078), exec %s (kernel.c:1099), stack %s (kernel.c:1215).
  • Ask for a decision: int aa_query_label(uint32_t mask, char *query, size_t size, int *allowed, int *audited); (apparmor.h:122). It writes the query to /sys/kernel/security/apparmor/.access and reads the answer back (apparmorfs.c:2704).
  • For the parser: int aa_features_new(aa_features **features, int dirfd, const char *path); (features.c:456) and aa_kernel_interface_new (kernel_interface.c:224-226).
  • Log lines: aa_log_record *parse_record(const char *str); (libaalogparse.c:41), used by the Python tools through the SWIG module LibAppArmor.
  • The DFA compiler is parser/libapparmor_re/, linked statically into apparmor_parser. It is not part of libapparmor.

08 The tools edit text and run the parser

THE TOOLS ON TOP demo a file it needs apparmor="DENIED" operation="open" profile="demo" ... the log aa-logprof reads the denials, asks you rewrites the text /etc/apparmor.d/demo + /var/lib/demo/cache/** rw, $ apparmor_parser ... -r /etc/apparmor.d/demo run by the tool the pipeline you just saw aa-complain, aa-enforce: edit flags=( ) and reload aa-status: reads the kernel's profile list
A loop: demo is denied a file and the kernel logs it, aa-logprof reads the log and adds a rule to the profile file, then runs apparmor_parser, which replaces the profile on demo

aa-logprof and aa-genprof turn logged events into rules in the profile file and reload it with apparmor_parser -r. aa-complain and aa-enforce edit the flags= of the file and reload. aa-status reads the kernel's list of profiles.

The tools you'll actually type sit on top of all this, and they take the same road. Say demo is refused a file it needs, and the kernel logs the denial. aa-logprof reads the log, shows you each event and asks what to do. Your answer becomes a line in the profile file. Then the tool runs apparmor_parser with -r itself, and the pipeline you've just seen does the rest. The mode tools work the same way. aa-complain doesn't flip a switch in the kernel: it edits the flags in the file and reloads. aa-status only reads.

Details and sources

Details

  • aa-logprof parses each log line with libapparmor's parse_record (logparser.py:288). aa-logprof -f FILE reads another log file; -d DIR names another profile directory.
  • After changing a profile file the Python tools run apparmor_parser -I<profile_dir> --base <profile_dir> -r <file> (aa.py:2430-2432).
  • aa-complain PROGRAM removes the flags enforce, kill, unconfined, prompt and default_allow from the profile file and adds complain (aa.py:266-273); the editing is done by change_profile_flags (aa.py:552). aa-enforce does the reverse.
  • aa-disable is different: it links the file into /etc/apparmor.d/disable/ and unloads the profile with apparmor_parser -R.
  • aa-status reads /sys/kernel/security/apparmor/profiles (aa_status.c:175-179) and the labels of the running processes; it changes nothing. aa-status --json prints the same as JSON.
  • The mode of a loaded profile can also be read from /sys/kernel/security/apparmor/policy/profiles/NAME.N/mode (apparmorfs.c:2044).

09 Pick a stage and go deeper

ROADS text tables blob kernel apparmor_parser options, exit status Features and ABI why a rule is dropped Policy cache /var/cache/apparmor Loading policy .load .replace .remove beside the path Is AppArmor enabled? libapparmor The utilities the aa-* tools The lexer developers: first stage Backend pipeline developers: rules to tables AppArmor in the kernel developers: the checks Unpacking policy developers: blob checks
The four stops text, tables, blob and kernel across the top, with the decks that continue from each stop underneath, and libapparmor and the utilities beside the path

Administrators: the parser, features, cache and loading decks. Application developers: libapparmor. AppArmor developers: the lexer, the backend pipeline and the kernel decks.

That's the whole road, from a text file to a check in the kernel, and each stop has its own part of the map. If you run systems, the decks on apparmor_parser, on features, on the cache and on loading are your next stops. If you write software, start with libapparmor and the tools built on it. And if you want to work on AppArmor itself, follow the lexer into the parser, the backend pipeline into the table compiler, or the kernel decks to where the checks are made.

Details and sources

Details

  • The road in one line: /sys/kernel/security/apparmor/features is read, the text under /etc/apparmor.d is parsed, the rules are compiled, the blob is written to /sys/kernel/security/apparmor/.replace, and the kernel walks the tables at each check.
  • One option per stop: --kernel-features FILE, -p and -N, -Q, -W for the cache, -a -r -R for the load.
  • Commits read for this deck: AppArmor 836052d21 (6.0.0~alpha2), the kernel-rc2 (97d73c825). Parser messages marked "observed" were printed by the parser built from that tree, compiling without loading; kernel behaviour is stated from the source.

Read more

Read at AppArmor 836052d21 (6.0.0~alpha2) and mainline Linux 7.4-rc2 (97d73c825). Messages marked "observed" were printed by the tree's parser (6.0.0~alpha2), run through tools/head-parser, compiling without loading; no kernel with AppArmor was used, so kernel behaviour here is what the code does, not a recorded session.

One run, stage by stage

StageWhat happensWhat you can observe
FeaturesThe parser reads the kernel's feature list from /sys/kernel/security/apparmor/features--kernel-features FILE uses a file instead of the running kernel
TextThe profile file and everything it includes are read; includes are looked up in the base directory, default /etc/apparmor.d-p prints the preprocessed text and stops; -N prints the profile names and stops
Cache testIf a cached blob is newer than the profile and every included file, it is loaded and the next two stages are skipped-K skips the cache, -T skips reading it
CompileRules become matching tables, packed into one binary blob per profile-Q (--skip-kernel-load) does everything except the load
Cache writeThe blob is saved for next time, only when asked-W (--write-cache), or write-cache in parser.conf
LoadOne write() hands the blob to the kernel-a add, -r replace, -R remove

-N on the example profile of syntax-map printed demo, demo//admin and demo//worker (observed).

A syntax error stops the run with a message of the form AppArmor parser error for FILE in profile INCLUDED-FILE at line N: TEXT (format string "AppArmor parser error for %s%s%s at line %d: %s"; the middle part names the file being read at that moment).

Without the kernel interface the parser prints Cache read/write disabled: interface file missing. (Kernel needs AppArmor 2.4 compatibility patch.) and carries on without the cache (observed with an installed apparmor_parser 5.0.2 on a kernel without AppArmor).

See adm-parser for every option and the exit status.

What is left out, and how to see it

A rule class is compiled only when both the kernel's feature list and the policy ABI of the profile (abi <abi/5.0>,) support it. Otherwise the rules of that class are dropped and the profile still loads, with exit status 0.

The warning class for this, rule-not-enforced, is off by default. --warn=rule-not-enforced or --warn=all turns it on.

Observed with the tree's parser (6.0.0~alpha2), an empty kernel feature set (--kernel-features /dev/null) and --warn=all, for the example profile:

  • Warning from profile demo (demo.sd): mqueue type=posix rules not enforced
  • "xattr attachment conditional ignored"
  • "ptrace rules not enforced"
  • "signal rules not enforced"
  • "extended network unix socket rules not enforced"
  • "network rules not enforced"
  • "dbus rules not enforced"
  • "userns rules not enforced"
  • "io_uring rules not enforced"
  • "mount rules not enforce" (the missing "d" is in the source, parser/mount.cc:782)
  • "mqueue rules not enforced", for the child profile worker, whose all, rule includes message queues

One more message of this class is in the source and was not printed: "mqueue type=sysv rules not enforced" (parser/mqueue.cc:199).

With --kernel-features pointing at the tree's abi/5.0 file, no warning was printed (observed).

A profile without an abi rule gets the warning "%s: File '%s' missing feature abi, falling back to default policy feature abi".

See adm-features and syn-abi.

The cache

ItemValue
Location/var/cache/apparmor/<features id>.0/, one file per profile file, named after its base name
Directory namederived from the kernel feature set; .1, .2 and so on when two feature sets collide on the same id
Fresh whenthe cached file is newer than the profile file and every file it includes
A hit skipscompilation only; the text is still read and parsed
Writtenonly with -W (--write-cache) or write-cache in parser.conf
Not used forprofiles read from standard input, profiles forced into complain mode
OptionEffect
-K, --skip-cachedo not read or write the cache
-T, --skip-read-cachedo not read the cache
-W, --write-cachesave the compiled blob
-L, --cache-loc DIRuse another cache location
--purge-cacheclear the cache
--print-cache-dirprint the cache directory for this kernel

aa-load loads cached blobs straight into the kernel. It does not run the compiler and does not check whether the cache is stale.

See adm-cache.

Loading

OptionFile written under /sys/kernel/security/apparmor/Effect
-a, --add.loadadd new profiles
-r, --replace.replacereplace loaded profiles, add new ones
-R, --remove.removeremove profiles
  • The path assumes securityfs at /sys/kernel/security; libapparmor finds the real mount point.
  • The load is one write() of the whole blob. When the kernel has the policy/set_load feature, all profiles of a file go in one write and are replaced together; otherwise libapparmor writes them one profile at a time.
  • The kernel first asks whether the writer may manage policy. It refuses with EACCES when policy is locked or the writer is not a policy administrator. The file modes do not decide this.
  • A blob that fails verification fails the write() with an error number and the loaded policy stays as it was. The kernel also emits a STATUS or ERROR audit record with operation "profile_load", "profile_replace" or "profile_remove".
  • Replacing a profile updates the processes that already carry it. A first load does not attach the profile to processes that are already running; see why-apparmor.

See adm-loading.

libapparmor's jobs

JobFunctionsUsed by
Is AppArmor enabled, where is its filesystemaa_is_enabled, aa_find_mountpointaa-enabled, aa-status
Read confinementaa_getcon, aa_gettaskcon, aa_getpeercon, aa_getprocattrapplications, aa-status
Change confinementaa_change_hat, aa_change_hatv, aa_change_profile, aa_change_onexec, aa_stack_profile, aa_stack_onexecapplications, aa-exec, mod_apparmor, pam_apparmor
Ask for a decisionaa_query_label, aa_query_file_path, aa_query_link_pathtrusted helpers such as the D-Bus daemon
Features, cache, loadaa_features_new, aa_policy_cache_new, aa_policy_cache_replace_all, aa_kernel_interface_load_policy, aa_kernel_interface_replace_policy, aa_kernel_interface_remove_policyapparmor_parser, aa-load, aa-features-abi
Parse log linesparse_recordthe Python tools, through the SWIG module LibAppArmor

Changing confinement writes one of these strings to the task's AppArmor attribute: libapparmor first tries the lsm_set_self_attr system call and falls back to a file under /proc/PID/attr/ (libraries/libapparmor/src/kernel.c:997-1011): "changehat %016lx^%s", "changeprofile %s", "exec %s", "stack %s".

aa_is_enabled returns 0 and sets errno to say why: ECANCELED (disabled at boot), ENOSYS (no sign of AppArmor), ENOENT (enabled, interface not found) or EBUSY (only private interfaces available).

libapparmor does not compile policy and does not know the profile language.

See lib-enabled, lib-labels, lib-change-hat, lib-change-profile, lib-query, lib-features and lib-cache-kernel.

The tools

C programs in binutils/, which call libapparmor:

  • aa-enabled, aa-exec, aa-features-abi, aa-load, aa-status

Programs in utils/, Python except aa-decode and aa-remove-unknown (shell). Those that change profiles (aa-audit, aa-autodep, aa-cleanprof, aa-complain, aa-enforce, aa-genprof, aa-logprof, aa-mergeprof) edit the text and reload it; aa-disable links the file into the disable directory and unloads the profile with -R:

  • aa-audit, aa-autodep, aa-cleanprof, aa-complain, aa-decode, aa-disable, aa-easyprof, aa-enforce, aa-genprof, aa-logprof, aa-mergeprof, aa-notify, aa-remove-unknown, aa-sandbox, aa-show-usage, aa-unconfined

After changing a profile file the Python tools reload it with:

apparmor_parser -I<profile_dir> --base <profile_dir> -r <file>

The parser path comes from the tool configuration, default /sbin/apparmor_parser. aa-complain and aa-enforce edit the flags= of the profile file and reload it; they do not change a kernel setting directly. aa-status reads the profiles file of the kernel's AppArmor filesystem.

See ut-overview and ut-modes.

for AppArmor developers

Parser stages with functions

Paths are under parser/ unless prefixed.

#StageFunctionsResult
0Start-upmain (parser_main.c:1806), get_kernel_features (parser_main.c:1726), aa_kernel_interface_new (parser_main.c:1853), aa_policy_cache_new (parser_main.c:1885)options, kernel features, cache handle
1Per fileprocess_profile (parser_main.c:1289), reset_parser (parser_main.c:1254); run in a forked child by work_spawn (parser_main.c:1472, used at 1693)one policy file
2Lexflex scanner parser_lex.l; include_filename (parser_lex.l:162); keyword_table (parser_misc.c:81-138)tokens
3Parseyyparse() (parser_main.c:1353); grammar parser_yacc.y, top rule at 345-371, profile_base at 391-458; add_to_list (parser_policy.c:60)Profile objects holding rule_t and cod_entry rules
4Cache testcache_hit (parser_main.c:1368) then process_binary (parser_main.c:1156)on a hit, stages 5 to 7 are skipped
5Post-processpost_process_policy (parser_policy.c:179) calls post_process_profile (parser_policy.c:127): add_implied_rules, process_profile_variables, replace_profile_aliases, profile_merge_rules, then process_profile_rules, then hats and childrenexpanded, merged rules
6Compileprocess_profile_rules (parser_regex.c:1215): process_profile_name_xmatch (xmatch), gen_policy_re (rule classes), process_profile_regex (file DFA, parser_regex.c:789), process_profile_policydb (parser_regex.c:1385); globs through convert_aaregex_to_pcre (parser_regex.c:118); blobs from aare_rules::create_dfablob (libapparmor_re/aare_rules.cc:352) and create_chfa (libapparmor_re/aare_rules.cc:194)up to three compressed DFA tables per profile
7Serializeload_policy (parser_policy.c:91), __sd_serialize_profile (parser_interface.c:683), sd_serialize_top_profile (parser_interface.c:666), sd_serialize_profile (parser_interface.c:480); load_flattened_hats (parser_interface.c:783-786)one tagged stream per profile, hats and children after it as siblings
8Write cachesetup_cache_tmp (parser_main.c:1414), install_cache (parser_main.c:1429); only when write_cache is setfile in the cache directory
9Loadaa_kernel_interface_load_policy, aa_kernel_interface_replace_policy, aa_kernel_interface_remove_policy (libraries/libapparmor/src/kernel_interface.c:314, 357, 400)one write() to .load, .replace or .remove
  • process_profile leaves early for -p (preprocess), -N (names), -D variables and the debug dump.
  • A cache hit does not skip lexing and parsing: yyparse() at parser_main.c:1353 comes before cache_hit at 1368.
  • -O and -D options only affect stage 6.
  • libapparmor_re (parser/libapparmor_re/) is the DFA engine, linked statically into the parser. It is not part of libapparmor.

See fe-lexer, fe-grammar, fe-post-process, re-pipeline and re-blob.

for AppArmor developers

Kernel side with functions

Paths are under linux:security/apparmor/.

  • Entry. profile_load (apparmorfs.c:687), profile_replace (705) and profile_remove (723) call policy_update (apparmorfs.c:607). It checks aa_may_manage_policy (apparmorfs.c:625; policy.c:1001), detects a zstd-compressed blob by its magic number (636-639) and copies the data with aa_simple_write_to_buffer (apparmorfs.c:459).
  • Unpack. aa_replace_profiles (policy.c:1184) calls aa_unpack (policy_unpack.c:1745), which runs verify_header (1442), unpack_profile (1121) and verify_profile (1574) for each profile. DFAs go through unpack_dfa (442) and aa_dfa_unpack (match.c:319) and are checked by verify_dfa (match.c:154); rule tables through unpack_pdb (policy_unpack.c:968).
  • Swap. Existing profiles are found with __lookup_replace (policy.c:1271) and replaced by __replace_profile (1393); new ones are added by __add_profile (1409); labels are refreshed by __aa_labelset_update_subtree (1414). Removal goes through aa_remove_profiles (policy.c:1488).
  • Check. apparmor_file_open (lsm.c:465), aa_path_perm (file.c:287), aa_path_name (path.c:202), __aa_path_perm (file.c:233), aa_str_perms (file.c:221), aa_dfa_match (match.c:518). The profile's mode is applied in aa_audit_file (file.c:95) and aa_audit (audit.c:200), which also write the audit record.

libapparmor's writes to /proc/PID/attr/ arrive at apparmor_setprocattr (lsm.c:943); queries on .access arrive at aa_write_access (apparmorfs.c:1204). The policy/set_load feature is declared at apparmorfs.c:2634.

See k-unpack, k-match, k-apparmorfs and k-audit.

Roads from here

RUNNING THE PARSER

TOOLS · utils/

LIBAPPARMOR

IN THE KERNEL

INSIDE THE PARSER

  • The lexer — the first stage inside the parser

THE DFA ENGINE · libapparmor_re