Exec and domain transitions
domain changes for AppArmor developers for security researchers for application developers
What the kernel does when a confined task starts a program or asks to change its own label. One hook computes the new label and every profile of the old label gives its own answer from its exec rule. The exec index and the fallbacks at run time. Secure exec and AT_SECURE. The no_new_privs test. The kernel side of change_onexec and change_profile and change_hat. With the labels and log records a running kernel produced.
On the map: in the kernel
▶ Watch this deck — 9 scenes, ~7 min
Worth seeing first
- Profile attachment — the search that px and an unconfined exec run
- Exec modes — the letters ix px cx ux and what they ask for
- Named exec transitions — exec rules that name their target
- safe and unsafe exec — what a safe exec means to the new program
Part of journeys
- Exec, transitions and labels, step 10 of 13 · previous: Policy namespaces · next: Labels in the kernel
01 One exec, one new label
apparmor_bprm_creds_for_exec (domain.c:985) runs once per execve. It sets the new program's label and bprm->secureexec, or returns an error. aa_change_profile and aa_change_hat change a label without exec.
Demo is a confined program, and it starts others: a tool, a helper, a worker. Each time, the kernel decides what the new program runs as. You know the rules a profile author writes for that: exec modes, arrows, safe and unsafe. This deck is the other side: the kernel function that reads those rules during execve, and the three things it can produce. A label for the new program. A request for secure execution. Or an error, and the exec fails. Then the ways a task changes its label without exec. Most slides show a real run. It's for profile authors, and for readers of the kernel code.
Details and sources
Details
- The hook is registered as
bprm_creds_for_execlsm.c:1862 and called frombprm_execveexec.c:1861, once perexecve, before the kernel examines the format of the binary. Two more hooks run when the exec can no longer fail:bprm_committing_credsandbprm_committed_credslsm.c:957-985. - The profile used for the runs in this deck:
profile demo /usr/bin/demowith one exec rule per program (/usr/bin/demo-tool ix,,/usr/bin/demo-helper px,,/usr/bin/demo-worker cx,,/usr/bin/demo-free ux,,/usr/bin/demo-other pix,,/usr/bin/demo-lost px,,/usr/bin/demo-named px -> sandbox,,/usr/bin/demo-gone px -> notloaded,,/usr/bin/demo-report px -> &sandbox,,/usr/bin/demo-plugin pix -> &sandbox,,/usr/bin/demo-env-px px,,/usr/bin/demo-env-Px Px,), the rulechange_profile -> sandbox,, a child profileworkerattached to/usr/bin/demo-workerand a hatadmin; the profilesdemo-helper,demo-reportanddemo-envattach to their programs;sandboxandlearnerhave no attachment. No profile attaches todemo-other,demo-lostordemo-plugin, andnotloadedis not loaded. - Observed: a Debian guest with kernel 7.3.4 in a disposable virtual machine, parser 5.0.2; domain.c, task.c, procattr.c and the headers they use are the same in that kernel and in the tree the map describes (findings/kernel/observed/README.md in the map's repository).
/usr/bin/demois a copy of a shell and thedemo-*programs are copies ofcatthat print/proc/self/attr/current. - Kernel statements are read from the kernel source and were not run, except where a bullet says "observed".
Read more
- Profile attachment, Exec modes, Named exec transitions, safe and unsafe exec.
- domain.c
- wiki: apparmor_kernel_development_guide: domain transitions, as design notes; where it and the code differ, this deck follows the code.
02 apparmor_bprm_creds_for_exec, step by step for AppArmor developers for security researchers
apparmor_bprm_creds_for_exec (domain.c:985-1108): newest label, the nnp snapshot, handle_onexec or fn_label_build(..., profile_transition(...)), the no_new_privs and ptrace tests, bprm->secureexec, set_cred_label(bprm->cred, new).
The hook runs once per execve, before the kernel looks at the binary. It takes the newest version of the task's label. If no_new_privs is set and the task is confined, it remembers that label, once. Then the main question. If the task left a request for this exec, handle_onexec answers. Otherwise fn_label_build calls profile_transition for every profile in the label and joins the answers. An error from any of them ends the exec. Then three tests on the result: the no_new_privs comparison, a tracer's right to trace the new label, and the secure exec flag. Last, the new label goes into the credentials the program will start with.
Details and sources
for AppArmor developers for security researchers
Details
int apparmor_bprm_creds_for_exec(struct linux_binprm *bprm)domain.c:985-1108. The label comes frombprm->cred, the credentials being prepared for the new program.- The snapshot domain.c:1016-1018:
if ((bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS) && !unconfined(label) && !ctx->nnp) ctx->nnp = aa_get_label(label);. The comment: "Ideally this would happen when nnp is set but there isn't a good way to do that yet." fn_label_build(L, P, GFP, FN)lib.h:289-344: for a label with one profile the function's result is the result; otherwise each profile's label is collected, the vectors are concatenated, sorted and made unique, and the label is found or created. AnERR_PTRfrom one profile ends the build.- The tests on the result: no_new_privs domain.c:1050-1056;
LSM_UNSAFE_SHAREis not mediated ("FIXME: currently don't mediate shared state", domain.c:1058-1061); a traced task:may_change_ptraced_domainasks whether the tracer may trace the new label,info = "ptrace prevents transition"domain.c:50-82 domain.c:1063-1068. - The local variable
unsafeholds "a secure exec was requested": it is passed toprofile_transitionassecure_execand, when true, setsbprm->secureexec = 1domain.c:1070-1078. - A label with another proxy than the old one also sets
bprm->per_clear |= PER_CLEAR_ON_SETIDdomain.c:1080-1089. - The exit through
audit:domain.c:1100-1107 writes oneexecrecord per profile of the old label, with the reason and the label that was refused astarget. - Kernel statements are read from the kernel source and were not run, except where a bullet says "observed".
Read more
- Profile stacking, scene "At exec, every member decides for itself".
- Labels in the kernel, scene on merge and build.
- wiki: apparmor_kernel_development_guide: domain transitions, as design notes; where it and the code differ, this deck follows the code.
03 profile_transition: one profile's answer for AppArmor developers for security researchers
profile_transition (domain.c:665-796): aa_path_name; unconfined: find_attach over the namespace; confined: aa_str_perms on the file DFA, MAY_EXEC, then x_to_label(perms.xindex). Complain mode substitutes a null- learning profile.
Here's one profile deciding. First the name: the executable's path, built the way every file check builds it. An unconfined profile then runs the attachment search, find_attach, over the namespace's profiles, each with its own small xmatch DFA; no match means stay unconfined. A confined profile does an ordinary file lookup instead. The name walks its file DFA, and the row must have the exec bit. No bit, no exec. With the bit, the same row carries an index that says where the new label comes from, and x_to_label resolves it. If that finds nothing: profile transition not found. In complain mode, both failures get a fresh learning profile instead.
Details and sources
for AppArmor developers for security researchers
Details
static struct aa_label *profile_transition(const struct cred *subj_cred, struct aa_profile *profile, const struct linux_binprm *bprm, char *buffer, struct path_cond *cond, bool *secure_exec)domain.c:665-796.- A name that cannot be built domain.c:684-695: an unconfined profile, or one with the flag for inheriting on a name error, keeps its label; otherwise the error is audited and the exec fails.
- Unconfined domain.c:697-722:
find_attach(&bprm->file->f_path, profile->ns, &profile->ns->base.profiles, name, &info). A conflict between two attachments sets an info string, which is logged with a forcedAUDITrecord, and the task stays unconfined. find_attachdomain.c:394-507 walks a profile list. For each profile with an xmatch DFA:aa_dfa_leftmatchfromattach->xmatch->start[AA_CLASS_XMATCH], and the final state's row must haveMAY_EXECdomain.c:431-436; then the count, the xattrs and the conflict rule. Profile attachment draws that loop; Matching at run time has the walker.- The search runs on
aa_dfa_leftmatch, and that function is not the same in the guest and in the tree: in 7.3.4 it steps without the retry of a diff-encoded state, in the tree it usesmatch_char(Matching at run time, scene "Five walkers, one step"). The labels observed forpxandcxare the ones the tree's code gives for these attachments, which are literal paths (derived); a diff-encoded attachment table was not examined on either kernel. - Confined domain.c:724-771:
state = aa_str_perms(rules->file, state, name, cond, &perms);andif (perms.allow & MAY_EXEC) new = x_to_label(...). A missing label:info = "profile transition not found", the exec bit is removed for the record,error = -EACCES. - Complain mode domain.c:749-767:
aa_new_learning_profile(profile, false, name, GFP_KERNEL)makes or finds the child<profile>//null-<name>in complain mode (it takes the namespace lock and calls__aa_new_learning_profile, policy.c:740-794); the record carries-EACCESand is logged asALLOWED;AA_X_UNSAFEis forced, so no secure exec. - The record domain.c:787-789:
aa_audit_file(subj_cred, profile, &perms, OP_EXEC, MAY_EXEC, name, target, new, cond->uid, info, error). Observed for a program with no exec rule:apparmor="DENIED" operation="exec" class="file" profile="demo" name="/usr/bin/demo-norule" comm="demo" requested_mask="x" denied_mask="x" fsuid=0 ouid=0. - Observed: a Debian guest with kernel 7.3.4 in a disposable virtual machine, parser 5.0.2; domain.c, task.c, procattr.c and the headers they use are the same in that kernel and in the tree the map describes (findings/kernel/observed/README.md in the map's repository).
/usr/bin/demois a copy of a shell and thedemo-*programs are copies ofcatthat print/proc/self/attr/current. - Kernel statements are read from the kernel source and were not run, except where a bullet says "observed".
- Known discrepancies in
find_attach, by their titles: "find_attachkeeps its candidate and conflict state acrossgoto restart"; "find_attachstoresmax(count, xmatch_len)but compares the raw count (latent)".
Read more
- Profile attachment, scenes "find_attach: one loop, four registers" and "When no profile matches".
- Matching at run time, scenes "Five walkers, one step" and "From a state to a row".
- wiki: apparmor_kernel_development_guide: domain transitions, as design notes; where it and the code differ, this deck follows the code.
04 The exec index, and what each mode did
AA_X_NONE, AA_X_NAME, AA_X_TABLE plus AA_X_CHILD, AA_X_INHERIT, AA_X_UNCONFINED, AA_X_UNSAFE (include/file.h:54-64). x_to_label (domain.c:574-663) looks up, then falls back. The labels were read by the started programs on a running kernel.
The index is one word. Two bits give the kind of lookup: none, by the program's name, or by a string in the profile's table. Flags add: among children, inherit, unconfined, unsafe. The lookup comes first; inherit and unconfined only apply when it found nothing. Here's demo on a real kernel. ix: no lookup, fallback, still demo. px: the search finds demo-helper. cx: the search runs among demo's children, and the label is demo//worker. ux: unconfined. A table entry names sandbox. With an ampersand, sandbox is stacked on whatever the search finds. pix with nothing to find stays demo. px with nothing to find fails the exec.
Details and sources
Details
- The word file.h:48-64:
AA_X_INDEX_MASK 0x00ffffff;AA_X_TYPE_MASK 0x0c000000withAA_X_NONE0,AA_X_NAME 0x04000000,AA_X_TABLE 0x08000000;AA_X_UNSAFE 0x10000000;AA_X_CHILD 0x20000000;AA_X_INHERIT 0x40000000;AA_X_UNCONFINED 0x80000000. It is thexindexfield of the permission row; for policy without a permission tabledfa_map_xindexbuilds it from the old accept word policy_compat.c:24-48. x_to_labeldomain.c:574-663.AA_X_TABLE:x_table_lookup;AA_X_NAME:find_attachover the profile's children withAA_X_CHILD, else over the namespace. No label: withAA_X_INHERITthe newest version of the profile's own label andinfo = "ix fallback"; else withAA_X_UNCONFINEDthe namespace's unconfined label andinfo = "ux fallback"domain.c:616-638.x_table_lookupdomain.c:523-559: the index selects a string of the profile's table (rules->file->trans); a leading&is skipped for the lookup; withAA_X_CHILDthe name is searched among the profile's children (aa_find_child), otherwiseaa_label_parse(&profile->label, lookup, GFP_KERNEL, true, false)resolves it, at every exec. The index was range checked at load policy_unpack.c:1543-1549.- A table string that began with
&domain.c:597-602 domain.c:651-658: the label found is kept as the stack, the code continues with the search by name, and the two are merged withaa_label_merge. Sopx -> &sandboxgavedemo-report//&sandbox: the profile attached to the program, plussandbox. - Plain
ixis type none plus inherit, so every such exec passes through the fallback. Observed withauditon the rule:apparmor="AUDIT" operation="exec" class="file" info="ix fallback" profile="demo" name="/usr/bin/demo-tool" comm="demo" requested_mask="x" fsuid=0 ouid=0 target="demo". - Observed failures:
demo-lost(px, nothing attaches):apparmor="DENIED" operation="exec" class="file" info="profile transition not found" error=-13 profile="demo" name="/usr/bin/demo-lost" comm="demo" requested_mask="x" denied_mask="x" fsuid=0 ouid=0 target="/usr/bin/demo-lost".demo-gone(px -> notloaded): the same withtarget="notloaded". An allowed exec with a table target andaudit:apparmor="AUDIT" operation="exec" class="file" profile="demo" name="/usr/bin/demo-named" comm="demo" requested_mask="x" fsuid=0 ouid=0 target="sandbox". - Also observed:
demo-pluginwithpix -> &sandboxand no attaching profile ran asdemo//&sandbox (enforce). - Observed: a Debian guest with kernel 7.3.4 in a disposable virtual machine, parser 5.0.2; domain.c, task.c, procattr.c and the headers they use are the same in that kernel and in the tree the map describes (findings/kernel/observed/README.md in the map's repository).
/usr/bin/demois a copy of a shell and thedemo-*programs are copies ofcatthat print/proc/self/attr/current. - The search behind
pxandcxruns onaa_dfa_leftmatch, and that function is not the same in the guest and in the tree: in 7.3.4 it steps without the retry of a diff-encoded state, in the tree it usesmatch_char(Matching at run time, scene "Five walkers, one step"). The labels observed forpxandcxare the ones the tree's code gives for these attachments, which are literal paths (derived); a diff-encoded attachment table was not examined on either kernel. - Known discrepancies, by their titles: "
ix -> &nameandux -> &namerun without the stack whennameis not loaded"; "the forced audit for "conflicting profile attachments - ux fallback" cannot trigger".
Read more
- Exec modes, scene "xindex and x_to_label": the parser's bits. Named exec transitions, scene "add_named_transition and x_table_lookup": the table.
- Profile stacking, scene "px -> &baz stacks on what attaches, not on you".
- apparmor.d(5) Access Modes Details.
05 Secure exec, and what else a new label changes
*secure_exec = true unless the row has AA_X_UNSAFE (domain.c:776-784); bprm->secureexec becomes AT_SECURE (fs/binfmt_elf.c:262). apparmor_bprm_committing_creds (lsm.c:957-973) revalidates open files, clears pdeath_signal and applies rlimits when the label changed.
A new label can also change how the program starts. If the rule was the safe form, the row lacks the unsafe flag, and the hook sets secureexec. The ELF loader copies that into the auxiliary vector as AT_SECURE. We ran one program twice from demo. Through lowercase px it saw zero. Through capital Px, one, and the dynamic linker ignored its debug variable. Three more things happen when the label changes. Every open file is checked again, and a descriptor the new profile may not use is replaced by the null device. The parent-death signal is cleared. Resource limits follow the new profile. With ix, none of this happens.
Details and sources
Details
- In
profile_transitiondomain.c:776-784:if (!(perms.xindex & AA_X_UNSAFE)) *secure_exec = true;. The test is skipped when the label returned is the profile's own and a reason is set, which is theixcase domain.c:730-739. In a stacked label one profile's request is enough. For a pending change_onexec the row of the change_profile rule decides domain.c:855-863. - In the hook domain.c:1070-1078:
bprm->secureexec = 1. The loader:NEW_AUX_ENT(AT_SECURE, bprm->secureexec)binfmt_elf.c:262; a secure exec also resets the stack limit exec.c:1240-1250. - Observed:
/usr/bin/demo-env-pxand/usr/bin/demo-env-Pxare copies ofod; each printed its own/proc/self/auxv, and entry 23 (AT_SECURE) was 0 and 1. WithLD_DEBUG=statisticsin the environment, the run throughpxprinted the linker's statistics and the run throughPxprinted none. Which variables secure execution removes is the C library's decision: safe and unsafe exec. apparmor_bprm_committing_credslsm.c:957-973 returns early when the new label has the same proxy as the old one or is unconfined. Otherwiseaa_inherit_filesfile.c:721-755 checks the controlling terminal and every open descriptor withaa_file_permunder the new label (the operation in a record isfile_inherit) and replaces a refused descriptor with one for the null device; thencurrent->pdeath_signal = 0; then__aa_transition_rlimits.- A changed label also clears the personality bits of
PER_CLEAR_ON_SETIDdomain.c:1080-1089. apparmor_bprm_committed_credslsm.c:979-985 clears the task's pending request, its saved hat label and the token.- Observed: a Debian guest with kernel 7.3.4 in a disposable virtual machine, parser 5.0.2; domain.c, task.c, procattr.c and the headers they use are the same in that kernel and in the tree the map describes (findings/kernel/observed/README.md in the map's repository).
/usr/bin/demois a copy of a shell and thedemo-*programs are copies ofcatthat print/proc/self/attr/current. - The descriptor replacement, the signal and the limits are read from the source and were not run.
Read more
- safe and unsafe exec: the keywords, the letter case and what the C library removes.
- rlimit rules. The limits of name-based mediation: descriptors inherited across exec.
- wiki: sanitized_helper.
06 no_new_privs: the old label must stay inside the new one
aa_label_is_unconfined_subset(new, ctx->nnp) (label.c:574-593) must hold, or the exec fails with EPERM and info="no new privs" (domain.c:1050-1056). The snapshot is taken at the first exec or change request after the flag is set (domain.c:1016, 1341, 1507). The six results were observed.
With no_new_privs set, a task promises not to gain privileges, and AppArmor can't compare two profiles. So it uses a rule it can check. The first time it sees the flag on a confined task, it keeps a copy of the label. From then on, every confining profile in that copy must still be in the new label. Watch demo under setpriv. ix: fine. px, cx, ux: operation not permitted, and the log says no new privs. px with a stack target fails too, because demo itself leaves the label. Only pix with a stack target works: demo stays, and sandbox is added. Unconfined tasks aren't tested.
Details and sources
Details
- The snapshot is the field
nnpof the task context task.h:34-41; it is copied to a child at fork task.h:68-75 and follows profile replacement task.c:66-71. It is taken in the exec hook domain.c:1016-1018, inaa_change_hatdomain.c:1341-1342 and inaa_change_profiledomain.c:1507-1508, each time only if the task has the flag, is not unconfined and has no snapshot yet. So it is the label at the first of these events afterprctl(PR_SET_NO_NEW_PRIVS), not the label at theprctl. - The test label.c:574-593:
aa_label_is_unconfined_subset(set, sub)is true when every profile ofsubthat is missing fromsetis an unconfined profile. At exec domain.c:1050-1056:setis the new label,subthe snapshot; failure is-EPERMwithinfo = "no new privs"and a record per profile of the old label. - Requests: change_hat domain.c:1383-1390 domain.c:1405-1412 and change_profile domain.c:1612-1619 return
-EPERMwithout a record ("not an apparmor denial per se, so don't log it"). A stack request skips the test ("stacking is always a subset", domain.c:1597-1598). - Observed records:
apparmor="DENIED" operation="exec" class="file" info="no new privs" error=-1 profile="demo" name="/usr/bin/demo-helper" comm="demo" requested_mask="x" denied_mask="x" fsuid=0 ouid=0 target="demo-helper"; forcxtarget="demo//worker"; foruxtarget="unconfined"; forpx -> &sandboxtarget="demo-report//&sandbox". - Also observed: under no_new_privs,
changeprofile sandboxwritten to/proc/self/attr/currentbydemofailed, with no AppArmor record for the request. - Why
px -> &sandboxfails: the stack is built on the profile that attaches to the program,demo-report, sodemois not indemo-report//&sandbox. Withpixand no attaching profile the base isdemo. - Observed: a Debian guest with kernel 7.3.4 in a disposable virtual machine, parser 5.0.2; domain.c, task.c, procattr.c and the headers they use are the same in that kernel and in the tree the map describes (findings/kernel/observed/README.md in the map's repository).
/usr/bin/demois a copy of a shell and thedemo-*programs are copies ofcatthat print/proc/self/attr/current.
Read more
- Profile stacking, scene "Under no_new_privs, changing fails and stacking works": the library calls.
- kernel docs: Linux Security Modules (userspace API).
- wiki: apparmor_kernel_development_guide: domain transitions, as design notes; where it and the code differ, this deck follows the code.
07 Asking: attr/current now, attr/exec for the next exec
do_setattr (lsm.c:853) maps changeprofile, stack and, on attr/exec, exec and stack to aa_change_profile (domain.c:1484). Now: aa_replace_current_label. At exec: aa_set_current_onexec, consumed by handle_onexec (domain.c:928). Observed on a running kernel.
A task can also ask. It writes a line to a file under /proc that only it can write. Both files reach one function, aa_change_profile. It parses the name and asks each profile whether a change_profile rule allows it. For the word changeprofile, the task's credentials get the new label at once. For the word exec, nothing changes yet: the label is parked in the task, and you can read it back. At the next exec, the hook finds it and uses it instead of the exec rules. We saw that: demo-helper has a px rule, but with sandbox parked, it ran as sandbox. Then the request is cleared.
Details and sources
Details
- Only the task itself can write its attr files base.c:2791.
do_setattrlsm.c:853-927 accepts oncurrent:changehat,permhat,changeprofile,permprofile,stack; onexec:exec,stack. Thepermforms only test. Another word is refused with-EINVALand logged; observed:apparmor="DENIED" operation="setprocattr" info="current" error=-22 profile="demo" comm="demo". int aa_change_profile(const char *fqname, int flags)domain.c:1484-1663. The name is parsed withaa_label_parse(label, fqname, GFP_KERNEL, true, false); a name that is not loaded:info = "label not found",-ENOENT.- Permission domain.c:1569-1573 domain.c:290-303: for every profile of the label in the task's namespace, the target's name is matched on the profile's file DFA from its start state and the row needs
AA_MAY_CHANGE_PROFILE(now) orAA_MAY_ONEXEC(at exec); a stack request matches&in front of the name. An unconfined profile is allowed. - Now domain.c:1622-1628:
aa_replace_current_label(new)prepares and commits new credentials task.c:48-91. At exec domain.c:1630-1635:aa_set_current_onexec(target, stack)stores the label inctx->onexectask.c:125-133;apparmor_getprocattrprints it forattr/execlsm.c:839-840. - At the exec domain.c:928-975:
handle_onexecfirst runsprofile_onexecdomain.c:798-869 for each in-scope profile: the executable's name is matched on the file DFA and the row needsAA_MAY_ONEXEC(info = "no change_onexec valid for executable"); then a NUL step and the match of the target label. Then in-scope profiles become the target (or are merged with it for a stack); profiles of other namespaces runprofile_transitionas usual. - Observed, the shell
demowriting to its own files: afterexec sandbox,attr/execreadsandbox (enforce)andattr/currentreaddemo (enforce); the program executed next readsandbox (enforce), also when it wasdemo-helper, whose exec rule ispx. Readingattr/execwith nothing pending failed with "Invalid argument".exec learner, which no rule allows: the write failed andapparmor="DENIED" operation="change_onexec" class="file" profile="demo" name="learner" comm="demo" target="learner"was logged.changeprofile learner: the same withoperation="change_profile". - An unconfined task needs no rule:
aa-exec -p sandbox -- cat /proc/self/attr/currentprintedsandbox (enforce). - The sysctl
kernel.apparmor_restrict_unprivileged_unconfinedturns a change requested by an unprivileged unconfined task into a stack withunconfineddomain.c:882-926. - Observed: a Debian guest with kernel 7.3.4 in a disposable virtual machine, parser 5.0.2; domain.c, task.c, procattr.c and the headers they use are the same in that kernel and in the tree the map describes (findings/kernel/observed/README.md in the map's repository).
/usr/bin/demois a copy of a shell and thedemo-*programs are copies ofcatthat print/proc/self/attr/current. - Known discrepancies, by their titles: "the unprivileged-unconfined restriction is decided at exec time for
change_onexec, so a task that drops CAP_MAC_OVERRIDE after asking is stacked withunconfined"; "changeprofile &nameis audited asoperation="change_profile"".
Read more
- change_profile rules, aa_change_profile and onexec, Profile stacking, scene "aa_stack_profile and aa_stack_onexec".
- aa_change_profile(2), aa-exec(1).
- wiki: AppArmorInterfaces: the attr commands.
08 change_hat: a saved label and a token
aa_change_hat (domain.c:1319-1445) builds the hat label with change_hat (domain.c:1169), stores previous and token with aa_set_current_hat (task.c:145) and returns with aa_restore_previous_label (task.c:185). A token mismatch is logged as KILLED. Observed on a running kernel. Known discrepancy, also observed: a change_onexec request made inside a hat overwrites the stored token (task.c:125-133).
A hat is the one change a task can undo. The write names a token and a hat. The kernel looks among the profile's children for one with that name and the hat flag. It doesn't consult any rule. Then it saves the current label in the task, with the token, and switches. The prev file now shows where it came from. To go back, the task writes the token with no name. A wrong token is fatal: the record says failed token match, and the task is killed. Two details from the run: a child that isn't a hat is refused, and a forked child inherits the token.
Details and sources
Details
- The write:
changehat <token as 16 hex digits>^<name>;split_token_from_nameparses the token withsimple_strtoull(args, &name, 16)and needs the^procattr.c:80-94. Up to 16 names separated by NUL bytes may follow; the first that works is used procattr.c:104-142.permhattests only. int aa_change_hat(const char *hats[], int count, u64 token, int flags)domain.c:1319-1445.change_hatdomain.c:1169-1300: under the namespace lock, for each in-scope profile of the label,aa_find_child(root, name)whererootis the profile, or its parent when the task is already in a hat; the child must have the hat flag ("target not hat",-EPERM). Not found: "hat not found" (-ENOENT) or, for a profile without children, "no hats defined" (-ECHILD); these are logged only when several names were given or in complain mode, where a learning hat is created.- Nothing in this path looks up a permission in the profile's tables; the rules the parser adds for a hat (Hats, scene "Three rules you did not write") are not read here.
aa_set_current_hat(label, token)task.c:145-174: the first entry stores the old label inctx->previousand the token; entering another hat later needs the same token; it also drops a pending change_onexec request.aa_restore_previous_label(token)task.c:185-209. A mismatch returns-EACCES, andaa_change_hatsetsperms.kill, so the record isKILLEDand the task is sent the profile's kill signal domain.c:1434-1442.- Under no_new_privs both directions pass the subset test first domain.c:1383-1390 domain.c:1405-1412; a tracer must be allowed to trace the hat domain.c:1375.
- Observed, the shell
demowriting to its own file: afterchangehat 00000000000004d2^admin,attr/currentreaddemo//admin (enforce)andattr/prevreaddemo (enforce);changehat 00000000000004d2^returned todemo (enforce). With token 1 the shell was killed (exit status 137):apparmor="KILLED" operation="change_hat" class="file" info="failed token match" error=-13 profile="demo//admin" comm="demo" target="demo".^nosuchand^worker(a child profile, not a hat): the write failed, the label stayeddemo (enforce), no record. - Observed: a child process forked while in the hat returned to
demo (enforce)with the same token; the parent stayeddemo//admin (enforce). The task context, withpreviousandtoken, is copied at fork task.h:68-75. - Observed: a Debian guest with kernel 7.3.4 in a disposable virtual machine, parser 5.0.2; domain.c, task.c, procattr.c and the headers they use are the same in that kernel and in the tree the map describes (findings/kernel/observed/README.md in the map's repository).
/usr/bin/demois a copy of a shell and thedemo-*programs are copies ofcatthat print/proc/self/attr/current. - Known discrepancy, not yet tracked in the bug list: "Kernel: a change_onexec request made inside a hat overwrites the hat token, so the hat can be left with token 0 or 1".
aa_set_current_onexecstores the stack flag of the request inctx->tokentask.c:125-133, the field that holds the hat token task.h:34-41;handle_onexeclater reads that field as the flag domain.c:1028-1030. So an acceptedexec NAMEwritten toattr/execleaves the token 0 and an acceptedstack NAMEleaves it 1. Observed, in a run of its own (findings/kernel/observed/run3-output.txt in the map's repository; the same guest; profiledemowith the hatslowandadmin, wherelowhaschange_profile -> sandbox,andchange_profile -> &sandbox,; the task enteredlowwith the token0x4d2): afterexec sandbox,changehat 0000000000000000^adminentered the sibling hat andattr/currentreaddemo//admin (enforce); afterstack sandbox,changehat 0000000000000001^returned the task todemo (enforce), and the real token got it killed. With nothing pending, each of the two writes got the task killed withinfo="failed token match". Limits: the rules of the hat must allow a change_onexec or stack_onexec request and the write toattr/exec; token 0 without a hat name is refused before the comparison ("NULL hat and NULL magic", procattr.c:115-118), so theexecform reaches sibling hats and thestackform reaches the parent. This is a defect and not how a hat is meant to be left: the token is the only lock on a hat (Hats, scene "The token is the only lock").
Read more
- Hats, scenes "Putting the hat on and taking it off" and "The token is the only lock". aa_change_hat.
- aa_change_hat(2).
- Labels in the kernel, scene "Three files under /proc".
09 Where to go from here
Next: labels in the kernel for the object, profile attachment for the search, exec modes and named exec transitions for the rules, safe and unsafe exec for the environment, change_profile rules and hats for asking, profile stacking for several profiles.
That's exec in the kernel: one hook, one answer per profile, an index that says where the label comes from, and three tests before the new program starts. And two ways to ask without exec. From here, labels in the kernel shows the object this hook builds and merges. Profile attachment has the search and its scoring. Exec modes and named transitions are the same rules from the author's side, and safe and unsafe exec tells you what the C library does with that flag. change_profile rules and hats cover the permission to ask. And profile stacking follows all of this for a task with several profiles.
Details and sources
Details
- The deck in five lines:
apparmor_bprm_creds_for_execcomputes the label of the new program; each profile answers throughprofile_transition, or throughhandle_onexecwhen a request is pending;x_to_labellooks up, then falls back; the result passes the no_new_privs test and the tracer test and may request a secure exec;aa_change_profileandaa_change_hatchange the label without exec. - Labels in the kernel, Profile attachment, Exec modes, Named exec transitions, safe and unsafe exec, change_profile rules, Hats, Profile stacking, Matching at run time, Reading a denial.
- Sources for this deck: Linux 97d73c825 for the code; three runs on a Debian guest for the observed results.
Read more
- domain.c, task.c, procattr.c.
- wiki: apparmor_kernel_development_guide: domain transitions, as design notes; where it and the code differ, this deck follows the code.
- apparmor.d(5) Access Modes Details.
Read more
Basis of the statements on this page: "code" means the kernel source of mainline Linux at commit 97d73c825 was read and not run; "observed" means seen on a Debian guest with kernel 7.3.4 in a disposable virtual machine, with the guest's apparmor_parser 5.0.2; domain.c, task.c, procattr.c and the headers they use are the same in that kernel and in the tree the map describes. One function they call is not: aa_dfa_leftmatch (match.c), the walker of the attachment search behind px and cx, steps without the retry of a diff-encoded state in 7.3.4 and with match_char in the tree. "derived" means reasoned from that code.
The profile of the runs
profile demo /usr/bin/demo {
include <abstractions/base>
/usr/bin/demo mr,
/usr/bin/{cat,sleep} mrix,
@{PROC}/@{pid}/attr/{current,exec,prev} rw,
signal (receive),
audit /usr/bin/demo-tool ix,
/usr/bin/demo-helper px,
/usr/bin/demo-worker cx,
/usr/bin/demo-free ux,
/usr/bin/demo-other pix,
/usr/bin/demo-lost px,
audit /usr/bin/demo-named px -> sandbox,
/usr/bin/demo-gone px -> notloaded,
/usr/bin/demo-report px -> &sandbox,
/usr/bin/demo-plugin pix -> &sandbox,
/usr/bin/demo-env-px px,
/usr/bin/demo-env-Px Px,
change_profile -> sandbox,
profile worker /usr/bin/demo-worker { ... }
^admin { ... }
}
/usr/bin/demo is a copy of dash; the demo-* programs are copies of cat, run as demo-X /proc/self/attr/current; demo-env-px and demo-env-Px are copies of od. Profiles demo-helper, demo-report and demo-env attach to their programs; sandbox and learner (complain mode) have no attachment.
The hook
| Step | Code | Where |
|---|---|---|
newest label of bprm->cred | aa_get_newest_label(cred_label(bprm->cred)) | domain.c:1007 |
| no_new_privs snapshot | ctx->nnp = aa_get_label(label) | domain.c:1016-1018 |
| pending request | handle_onexec(subj_cred, label, ctx->onexec, ctx->token, bprm, buffer, &cond, &unsafe) | domain.c:1028-1030 |
| exec rules | fn_label_build(label, profile, GFP_KERNEL, profile_transition(...)) | domain.c:1032-1035 |
| no_new_privs test | !aa_label_is_unconfined_subset(new, ctx->nnp): -EPERM, "no new privs" | domain.c:1050-1056 |
| traced task | may_change_ptraced_domain(bprm->cred, new, &info): "ptrace prevents transition" | domain.c:1063-1068 |
| secure exec | bprm->secureexec = 1 | domain.c:1070-1078 |
| personality | PER_CLEAR_ON_SETID is added to bprm->per_clear when the proxy differs | domain.c:1080-1089 |
| the result | set_cred_label(bprm->cred, new) | domain.c:1090-1092 |
| committing | aa_inherit_files, pdeath_signal = 0, __aa_transition_rlimits | lsm.c:957-973 |
| committed | aa_clear_task_ctx_trans(task_ctx(current)) | lsm.c:979-985 |
All code.
The exec index
| Bits | Name | Meaning |
|---|---|---|
0x00ffffff | AA_X_INDEX_MASK | index into the profile's string table |
0x0c000000 | AA_X_TYPE_MASK | AA_X_NONE 0, AA_X_NAME 0x04000000, AA_X_TABLE 0x08000000 |
0x10000000 | AA_X_UNSAFE | do not request a secure exec |
0x20000000 | AA_X_CHILD | search the profile's children |
0x40000000 | AA_X_INHERIT | fallback: keep the profile |
0x80000000 | AA_X_UNCONFINED | fallback: the namespace's unconfined label |
file.h:48-64 (code).
The modes at run time
Rule in demo | Lookup (code) | Label of the new program (observed) |
|---|---|---|
ix | none; ix fallback | demo (enforce) |
px | find_attach over the namespace | demo-helper (enforce) |
cx | find_attach over the children of demo | demo//worker (enforce) |
ux | none; ux fallback | unconfined |
pix, nothing attaches | search, then ix fallback | demo (enforce) |
px, nothing attaches | search | Permission denied; info="profile transition not found", target="/usr/bin/demo-lost" |
px -> sandbox | table string | sandbox (enforce) |
px -> notloaded | table string | Permission denied; info="profile transition not found", target="notloaded" |
px -> &sandbox | table string, then search, then merge | demo-report//&sandbox (enforce) |
pix -> &sandbox, nothing attaches | table string, search, fallback, merge | demo//&sandbox (enforce) |
| no exec rule | Permission denied; requested_mask="x" denied_mask="x" | |
px / Px to the same program | AT_SECURE 0 / 1 |
Reason strings of an exec record
info= | When | Where |
|---|---|---|
ix fallback | type none or a failed lookup, with inherit | domain.c:626 |
ux fallback | the same with unconfined | domain.c:636 |
conflicting profile attachments | two attachments tie in find_attach | domain.c:33-37 domain.c:495-499 |
conflicting profile attachments - ix fallback, - ux fallback | a tie followed by a fallback | domain.c:622-623 domain.c:632-633 |
profile transition not found | exec permission but no label | domain.c:746 |
could not create null profile | complain mode, allocation failed | domain.c:762 |
no new privs | the subset test failed | domain.c:1054 |
ptrace prevents transition | the tracer may not trace the new label | domain.c:80 |
change_profile onexec | default of a change_onexec check | domain.c:807 |
no change_onexec valid for executable | the executable's row lacks the onexec permission | domain.c:840 |
failed to build target label | building the label failed | domain.c:972 domain.c:1641 |
change_profile unprivileged unconfined converted to stacking | the sysctl restriction applied | domain.c:896 |
All code; ix fallback, profile transition not found and no new privs were also observed.
no_new_privs
Under setpriv --no-new-privs, from demo | Result (observed) |
|---|---|
ix | demo (enforce) |
px | Operation not permitted; info="no new privs" error=-1 ... target="demo-helper" |
cx | Operation not permitted; target="demo//worker" |
ux | Operation not permitted; target="unconfined" |
px -> &sandbox | Operation not permitted; target="demo-report//&sandbox" |
pix -> &sandbox, nothing attaches | demo//&sandbox (enforce) |
changeprofile sandbox | the write fails; no record for the request |
The test: every profile of the snapshot that is missing from the new label must be an unconfined profile label.c:574-593 (code). Stack requests are not tested domain.c:1597-1598 (code).
Commands written to the attr files
| File | Command | Kernel call | Operation in the log |
|---|---|---|---|
attr/current | changeprofile NAME | aa_change_profile(NAME, AA_CHANGE_NOFLAGS) | change_profile |
attr/current | permprofile NAME | aa_change_profile(NAME, AA_CHANGE_TEST) | change_profile |
attr/current | stack NAME | aa_change_profile(NAME, AA_CHANGE_STACK) | stack |
attr/current | changehat TOKEN^NAME | aa_change_hat(names, count, token, AA_CHANGE_NOFLAGS) | change_hat |
attr/current | permhat TOKEN^NAME | the same with AA_CHANGE_TEST | change_hat |
attr/exec | exec NAME | aa_change_profile(NAME, AA_CHANGE_ONEXEC) | change_onexec |
attr/exec | stack NAME | aa_change_profile with AA_CHANGE_ONEXEC and AA_CHANGE_STACK | stack_onexec |
| either | anything else | -EINVAL | setprocattr, info="current" or "exec" |
lsm.c:853-927, audit.h:92-100 (code).
The task context
struct aa_task_ctx task.h:34-41 (code):
| Field | Set by | Cleared by |
|---|---|---|
nnp | the first exec, change_hat or change_profile under no_new_privs while confined | the end of the task |
onexec | aa_set_current_onexec | exec committed; entering a hat; a change to unconfined or to another namespace |
previous | aa_set_current_hat, first entry | aa_restore_previous_label; exec committed |
token | aa_set_current_hat; also written by aa_set_current_onexec (the stack flag) | with previous |
All four are copied to a child at fork task.h:68-75 (code; the hat part observed).
Hats
Write by demo | Result (observed) |
|---|---|
changehat 00000000000004d2^admin | attr/current: demo//admin (enforce); attr/prev: demo (enforce) |
changehat 00000000000004d2^ | demo (enforce) |
changehat 0000000000000001^ while in the hat | the task is killed; apparmor="KILLED" operation="change_hat" class="file" info="failed token match" error=-13 profile="demo//admin" comm="demo" target="demo" |
changehat 00000000000004d2^nosuch | the write fails; no record |
changehat 00000000000004d2^worker (a child profile) | the write fails; no record |
in the hat, a forked child writes changehat 00000000000004d2^ | the child is demo (enforce), the parent stays in the hat |
Errors of aa_change_hat (code): "unconfined can not change_hat" -EPERM; "conflicting targets types" -EPERM; "target not hat" -EPERM; "hat not found" -ENOENT; "no hats defined" -ECHILD; "failed token match" -EACCES and a kill domain.c:1169-1300 domain.c:1319-1445.
Known discrepancies
By the titles under which they are tracked (Bugs found while building this map):
ix -> &nameandux -> &namerun without the stack whennameis not loaded.find_attachkeeps its candidate and conflict state acrossgoto restart.find_attachstoresmax(count, xmatch_len)but compares the raw count (latent).- The forced audit for "conflicting profile attachments - ux fallback" cannot trigger.
- The unprivileged-unconfined restriction is decided at exec time for
change_onexec, so a task that drops CAP_MAC_OVERRIDE after asking is stacked withunconfined. changeprofile &nameis audited asoperation="change_profile".
Not yet tracked there: "Kernel: a change_onexec request made inside a hat overwrites the hat token, so the hat can be left with token 0 or 1". aa_set_current_onexec writes the stack flag of the request into ctx->token task.c:125-133 (code). Observed in a run of its own (findings/kernel/observed/run3-output.txt in the map's repository; after exec sandbox written to attr/exec in a hat that allows it, changehat 0000000000000000^admin entered the sibling hat; after stack sandbox, changehat 0000000000000001^ returned to the parent profile).
Not determined
- What a tracer observes when the tracer test refuses an exec.
- change_hat with several names, and in a stacked label.
- Whether
LSM_UNSAFE_SHAREis meant to stay unmediated.
Roads from here
ATTACHMENT, NAMESPACES, STACKING
- Profile attachment — how the search scores and picks a profile
- Profile stacking — exec and requests with stacked labels
FILE ACCESS
- Exec modes — the modes as a profile author writes them
- Named exec transitions — the arrow and the exec table in the parser
- safe and unsafe exec — which variables secure execution removes
RULE CLASSES
- change_profile rules — the rule that permits asking
PROFILE STRUCTURE
- Hats — hats in a profile and the token
RUNNING THE PARSER
- Reading a denial — reading the exec records
LIBAPPARMOR
- aa_change_profile and onexec (no slides yet) — the library calls that write the request
- aa_change_hat (no slides yet) — the library call for hats
IN THE KERNEL
- Labels in the kernel — the label object that the hook builds
- Matching at run time — the lookup that returns the exec row