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
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.-ris--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/profileslists 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 filesname,modeandattach(apparmorfs.c:2038-2050) and a linkraw_datato 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/revisionis a counter of policy changes (apparmorfs.c:2954).- To compile without loading:
apparmor_parser -Q FILE(--skip-kernel-load, parser_main.c:169).
Read more
- apparmor_parser(8): -r, --replace.
- wiki: AppArmorInterfaces: the files of the AppArmor filesystem.
- Running the parser, loading policy, the AppArmor filesystem.
02 Four stops in one run
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 FILEuses 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: TEXTand 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
abirule gets the warningFILE: File 'NAME' missing feature abi, falling back to default policy feature abi.
Read more
for AppArmor developers for security researchers
In the code
- The error format string is "AppArmor parser error for %s%s%s at line %d: %s" (parser_yacc.y:1728).
- The supported-feature flags are set once in
set_supported_features(parser_main.c:1030); variables are expanded inpost_process_profile(parser_policy.c:127-133).
03 The same run, by function for AppArmor developers
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.
int process_profile(int option, aa_kernel_interface *kernel_interface, ...)runs one policy file (parser_main.c:1289).- Lex and parse:
retval = yyparse();(parser_main.c:1353); scanner parser_lex.l, grammar parser_yacc.y. - Post-processing:
post_process_policy(parser_policy.c:179) callspost_process_profile(parser_policy.c:127) for each profile. - Compile:
process_profile_rules(parser_regex.c:1215) callsprocess_profile_name_xmatch(attachment),process_profile_regex(file rules) andprocess_profile_policydb(the other classes) (parser_regex.c:1238-1268). - Serialize:
sd_serialize_profile(parser_interface.c:480); hats and children are written after their parent byload_flattened_hats(parser_interface.c:783-786). - Load:
aa_kernel_interface_replace_policy(kernel_interface.c:357). - Jobs:
-j N(--jobs, parser_main.c:184); the default is the number of processor cores (parser_main.c:99). Each file is processed in a forked child bywork_spawn(parser_main.c:1472). - To look at a stage:
-D(--dump) with a name fromapparmor_parser --help=dump,-O(--optimize) with a name from--help=optimize.
Read more
- apparmor_parser(8): -D, --dump and -O, --optimize.
- wiki: TechnicalDoc_HFA: the DFA compiler.
- The lexer, the grammar, post-processing, the backend pipeline, the binary blob.
04 The cache skips the compile, not the reading
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-dirprints 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) orwrite-cacheinparser.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-cacheclears it (parser_main.c:173-174, parser_main.c:187). aa-loadloads 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).
Read more
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
-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,.replaceand.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
EACCESand the audit record hasinfo="policy_locked"(policy.c:1013-1016). - The kernel logs each change as a
STATUSrecord, orERRORon failure, withoperation="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.
Read more
- apparmor_parser(8) COMMANDS.
- aa_kernel_interface(3).
- wiki: AppArmorInterfaces:
.load,.replace,.remove. - Loading policy, who may administer policy, unpacking in the kernel.
for AppArmor developers for security researchers
In the code
aa_replace_profilesunpacks 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
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.
- Entry:
profile_load,profile_replaceandprofile_remove(apparmorfs.c:687, apparmorfs.c:705, apparmorfs.c:723) callpolicy_update(apparmorfs.c:607). policy_updatechecksaa_may_manage_policy(apparmorfs.c:625) and recognises a zstd-compressed blob by its magic number (apparmorfs.c:636-639).ssize_t aa_replace_profiles(struct aa_ns *policy_ns, struct aa_label *label, ...)(policy.c:1184) callsaa_unpack(policy_unpack.c:1745), which runsverify_header,unpack_profileandverify_profilefor each profile in the blob (policy_unpack.c:1761-1772).- Swap:
__replace_profilefor an existing profile,__add_profilefor a new one, then__aa_labelset_update_subtree(policy.c:1393-1414). - Check: the hook
file_openisapparmor_file_open(lsm.c:465); it callsaa_path_perm(file.c:287). - The name is built by
aa_path_name(file.c:169) and matched byaa_str_perms, which callsaa_dfa_match(file_rules->dfa, start, name)(file.c:221-226; match.c:518). - Mode and record:
aa_audit_file(file.c:95) andaa_audit(audit.c:200). - libapparmor's writes to
/proc/PID/attr/arrive atapparmor_setprocattr(lsm.c:943); queries written to.accessarrive ataa_write_access(apparmorfs.c:1204).
Read more
- wiki: apparmor_kernel_development_guide.
- wiki: TechnicalDoc_HFA_Layout and TechnicalDoc_HFA_permissions: the table format and the permissions on accept states.
- Unpacking, matching, labels, the AppArmor filesystem, audit.
07 libapparmor: how programs talk to the kernel
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 witherrnoset toECANCELED(disabled at boot),ENOSYS(not present),ENOENT(enabled, interface not found) orEBUSY(only private interfaces) (kernel.c:310-312). The command isaa-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/currentor/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_attrsystem 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/.accessand 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) andaa_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 moduleLibAppArmor. - The DFA compiler is
parser/libapparmor_re/, linked statically intoapparmor_parser. It is not part of libapparmor.
Read more
- aa_getcon(2), aa_change_hat(2), aa_change_profile(2), aa_query_label(2).
- aa_find_mountpoint(2): the page for
aa_is_enabled. - kernel docs: Linux Security Modules (userspace API): the
/proc/self/attr/apparmor/files. - Is AppArmor enabled, labels, change_hat, change_profile, queries, D-Bus mediation.
08 The tools edit text and run the parser
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-logprofparses each log line with libapparmor'sparse_record(logparser.py:288).aa-logprof -f FILEreads another log file;-d DIRnames 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 PROGRAMremoves the flagsenforce,kill,unconfined,promptanddefault_allowfrom the profile file and addscomplain(aa.py:266-273); the editing is done bychange_profile_flags(aa.py:552).aa-enforcedoes the reverse.aa-disableis different: it links the file into/etc/apparmor.d/disable/and unloads the profile withapparmor_parser -R.aa-statusreads/sys/kernel/security/apparmor/profiles(aa_status.c:175-179) and the labels of the running processes; it changes nothing.aa-status --jsonprints 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).
Read more
- aa-logprof(8), aa-genprof(8), aa-complain(8), aa-status(8).
- Generate profiles with aa-genprof and the Quick Reference (Cheat Sheet) on apparmor.net.
- The tools, aa-logprof, the mode tools, aa-status.
09 Pick a stage and go deeper
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/featuresis read, the text under/etc/apparmor.dis 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,-pand-N,-Q,-Wfor the cache,-a-r-Rfor 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
- apparmor_parser(8), apparmor(7).
- Administrators: the parser, features, the cache, loading.
- Application developers: is AppArmor enabled, labels, the tools.
- AppArmor developers: the lexer, the backend pipeline, the kernel side.
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
| Stage | What happens | What you can observe |
|---|---|---|
| Features | The parser reads the kernel's feature list from /sys/kernel/security/apparmor/features | --kernel-features FILE uses a file instead of the running kernel |
| Text | The 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 test | If 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 |
| Compile | Rules become matching tables, packed into one binary blob per profile | -Q (--skip-kernel-load) does everything except the load |
| Cache write | The blob is saved for next time, only when asked | -W (--write-cache), or write-cache in parser.conf |
| Load | One 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, whoseall,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
| Item | Value |
|---|---|
| Location | /var/cache/apparmor/<features id>.0/, one file per profile file, named after its base name |
| Directory name | derived from the kernel feature set; .1, .2 and so on when two feature sets collide on the same id |
| Fresh when | the cached file is newer than the profile file and every file it includes |
| A hit skips | compilation only; the text is still read and parsed |
| Written | only with -W (--write-cache) or write-cache in parser.conf |
| Not used for | profiles read from standard input, profiles forced into complain mode |
| Option | Effect |
|---|---|
-K, --skip-cache | do not read or write the cache |
-T, --skip-read-cache | do not read the cache |
-W, --write-cache | save the compiled blob |
-L, --cache-loc DIR | use another cache location |
--purge-cache | clear the cache |
--print-cache-dir | print 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
| Option | File written under /sys/kernel/security/apparmor/ | Effect |
|---|---|---|
-a, --add | .load | add new profiles |
-r, --replace | .replace | replace loaded profiles, add new ones |
-R, --remove | .remove | remove 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 thepolicy/set_loadfeature, 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
EACCESwhen 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 aSTATUSorERRORaudit 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
| Job | Functions | Used by |
|---|---|---|
| Is AppArmor enabled, where is its filesystem | aa_is_enabled, aa_find_mountpoint | aa-enabled, aa-status |
| Read confinement | aa_getcon, aa_gettaskcon, aa_getpeercon, aa_getprocattr | applications, aa-status |
| Change confinement | aa_change_hat, aa_change_hatv, aa_change_profile, aa_change_onexec, aa_stack_profile, aa_stack_onexec | applications, aa-exec, mod_apparmor, pam_apparmor |
| Ask for a decision | aa_query_label, aa_query_file_path, aa_query_link_path | trusted helpers such as the D-Bus daemon |
| Features, cache, load | aa_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_policy | apparmor_parser, aa-load, aa-features-abi |
| Parse log lines | parse_record | the 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.
| # | Stage | Functions | Result |
|---|---|---|---|
| 0 | Start-up | main (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 |
| 1 | Per file | process_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 |
| 2 | Lex | flex scanner parser_lex.l; include_filename (parser_lex.l:162); keyword_table (parser_misc.c:81-138) | tokens |
| 3 | Parse | yyparse() (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 |
| 4 | Cache test | cache_hit (parser_main.c:1368) then process_binary (parser_main.c:1156) | on a hit, stages 5 to 7 are skipped |
| 5 | Post-process | post_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 children | expanded, merged rules |
| 6 | Compile | process_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 |
| 7 | Serialize | load_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 |
| 8 | Write cache | setup_cache_tmp (parser_main.c:1414), install_cache (parser_main.c:1429); only when write_cache is set | file in the cache directory |
| 9 | Load | aa_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_profileleaves early for-p(preprocess),-N(names),-D variablesand the debug dump.- A cache hit does not skip lexing and parsing:
yyparse()at parser_main.c:1353 comes beforecache_hitat 1368. -Oand-Doptions 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) andprofile_remove(723) callpolicy_update(apparmorfs.c:607). It checksaa_may_manage_policy(apparmorfs.c:625; policy.c:1001), detects a zstd-compressed blob by its magic number (636-639) and copies the data withaa_simple_write_to_buffer(apparmorfs.c:459). - Unpack.
aa_replace_profiles(policy.c:1184) callsaa_unpack(policy_unpack.c:1745), which runsverify_header(1442),unpack_profile(1121) andverify_profile(1574) for each profile. DFAs go throughunpack_dfa(442) andaa_dfa_unpack(match.c:319) and are checked byverify_dfa(match.c:154); rule tables throughunpack_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 throughaa_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 inaa_audit_file(file.c:95) andaa_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
- Running apparmor_parser (no slides yet) — the options of apparmor_parser and its exit status
- Kernel features and the policy ABI — why a rule can be dropped without a message
- The policy cache (no slides yet) — where the compiled policy is cached and when it is reused
- Loading policy into the kernel (no slides yet) — how policy is loaded and replaced and removed
TOOLS · utils/
- The AppArmor utilities (no slides yet) — the aa- tools that edit profiles and reload them
LIBAPPARMOR
- Is AppArmor enabled? (no slides yet) — the library every tool uses to talk to the kernel
IN THE KERNEL
- AppArmor in the kernel (no slides yet) — where the kernel makes its checks
- Unpacking and verifying policy (no slides yet) — how the kernel verifies what it was given
INSIDE THE PARSER
- The lexer — the first stage inside the parser
THE DFA ENGINE · libapparmor_re
- The backend pipeline — how rules become matching tables