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

Part of journeys

01 One exec, one new label

EXEC AND DOMAIN TRANSITIONS demo confined execve demo-tool demo-helper demo-worker apparmor_bprm_creds_for_exec reads the exec rules during execve a label for the new program a request for secure execution or an error: the exec fails without exec: change_profile · change_onexec · change_hat most slides show a real run; the profile is under this slide for profile authors, and for readers of the kernel code
demo calls execve for a tool, a helper or a worker. The kernel calls one AppArmor function, apparmor_bprm_creds_for_exec, which produces a label for the new program, a request for secure execution, or an error that fails the exec. Without exec a task can change its label through change_profile, change_onexec and change_hat

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_exec lsm.c:1862 and called from bprm_execve exec.c:1861, once per execve, before the kernel examines the format of the binary. Two more hooks run when the exec can no longer fail: bprm_committing_creds and bprm_committed_creds lsm.c:957-985.
  • The profile used for the runs in this deck: profile demo /usr/bin/demo with 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 rule change_profile -> sandbox,, a child profile worker attached to /usr/bin/demo-worker and a hat admin; the profiles demo-helper, demo-report and demo-env attach to their programs; sandbox and learner have no attachment. No profile attaches to demo-other, demo-lost or demo-plugin, and notloaded is 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/demo is a copy of a shell and the demo-* programs are copies of cat that 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

02 apparmor_bprm_creds_for_exec, step by step for AppArmor developers for security researchers

THE HOOK 1label = aa_get_newest_label(cred_label(bprm->cred))domain.c:1007 2no_new_privs, confined, first time: ctx->nnp = label1016 3ctx->onexec ? handle_onexec(...)1028 : fn_label_build(label, profile_transition(...))1032 one answer per profile, joined 4IS_ERR(new): the exec fails1037 5nnp subset test · tracer test · bprm->secureexec1050-1078 6set_cred_label(bprm->cred, new)1092 the task itself is not changed until the exec commits
The steps of apparmor_bprm_creds_for_exec: take the newest version of the label; if no_new_privs is set and the task is confined, remember the label once; if a request is pending call handle_onexec, otherwise fn_label_build calls profile_transition for every profile of the label; an error ends the exec; then the no_new_privs test, the tracer test and the secure exec flag; finally the new label is put into the credentials of the new program

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 from bprm->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. An ERR_PTR from one profile ends the build.
  • The tests on the result: no_new_privs domain.c:1050-1056; LSM_UNSAFE_SHARE is not mediated ("FIXME: currently don't mediate shared state", domain.c:1058-1061); a traced task: may_change_ptraced_domain asks whether the tracer may trace the new label, info = "ptrace prevents transition" domain.c:50-82 domain.c:1063-1068.
  • The local variable unsafe holds "a secure exec was requested": it is passed to profile_transition as secure_exec and, when true, sets bprm->secureexec = 1 domain.c:1070-1078.
  • A label with another proxy than the old one also sets bprm->per_clear |= PER_CLEAR_ON_SETID domain.c:1080-1089.
  • The exit through audit: domain.c:1100-1107 writes one exec record per profile of the old label, with the reason and the label that was refused as target.
  • Kernel statements are read from the kernel source and were not run, except where a bullet says "observed".

Read more

03 profile_transition: one profile's answer for AppArmor developers for security researchers

ONE PROFILE DECIDES name = aa_path_name(bprm->file, …) the executable's path, as for any file check unconfined find_attach(ns profiles, name) a match: its label none: stays unconfined each profile's xmatch DFA, by aa_dfa_leftmatch confined aa_str_perms(file DFA, name) an ordinary file lookup: a row no exec bit EACCES exec bit x_to_label(perms.xindex) the new label nothing found: "profile transition not found" complain mode: both failures return a new learning profile, demo//null-<name>
profile_transition, the decision of one profile. The name of the executable is built with aa_path_name. An unconfined profile runs find_attach over the profiles of the namespace, each with its xmatch DFA: a match is the new label, no match keeps it unconfined. A confined profile walks the name through its file DFA with aa_str_perms: without the exec bit the exec is refused; with it, x_to_label resolves the exec index of the row, and finding nothing is the error profile transition not found. In complain mode both failures get a learning profile

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 forced AUDIT record, and the task stays unconfined.
  • find_attach domain.c:394-507 walks a profile list. For each profile with an xmatch DFA: aa_dfa_leftmatch from attach->xmatch->start[AA_CLASS_XMATCH], and the final state's row must have MAY_EXEC domain.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 uses match_char (Matching at run time, scene "Five walkers, one step"). The labels observed for px and cx are 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); and if (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 -EACCES and is logged as ALLOWED; AA_X_UNSAFE is 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/demo is a copy of a shell and the demo-* programs are copies of cat that 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_attach keeps its candidate and conflict state across goto restart"; "find_attach stores max(count, xmatch_len) but compares the raw count (latent)".

Read more

04 The exec index, and what each mode did

THE EXEC INDEX xindex unconfined inherit child unsafe none · name · table index, 24 bits the lookup, always first inherit, unconfined: only if it found nothing programrulethe new program read from /proc/self/attr/currentdemo-toolixdemo (enforce)demo-helperpxdemo-helper (enforce)demo-workercxdemo//worker (enforce)demo-freeuxunconfineddemo-namedpx -> sandboxsandbox (enforce)demo-reportpx -> &sandboxdemo-report//&sandbox (enforce)demo-otherpixdemo (enforce)demo-lostpxPermission denied px with nothing to find: the exec fails, info="profile transition not found"
The exec index is one 32-bit word: flags for unconfined, inherit, child and unsafe, two bits for the kind of lookup (none, by name or by table) and a 24-bit table index. Observed labels of programs started by demo: ix keeps demo; px gives demo-helper; cx gives demo//worker; ux gives unconfined; px -> sandbox gives sandbox; px -> &sandbox gives demo-report//&sandbox; pix with no profile to find keeps demo; px with no profile to find fails with permission denied

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 0x0c000000 with AA_X_NONE 0, 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 the xindex field of the permission row; for policy without a permission table dfa_map_xindex builds it from the old accept word policy_compat.c:24-48.
  • x_to_label domain.c:574-663. AA_X_TABLE: x_table_lookup; AA_X_NAME: find_attach over the profile's children with AA_X_CHILD, else over the namespace. No label: with AA_X_INHERIT the newest version of the profile's own label and info = "ix fallback"; else with AA_X_UNCONFINED the namespace's unconfined label and info = "ux fallback" domain.c:616-638.
  • x_table_lookup domain.c:523-559: the index selects a string of the profile's table (rules->file->trans); a leading & is skipped for the lookup; with AA_X_CHILD the name is searched among the profile's children (aa_find_child), otherwise aa_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 with aa_label_merge. So px -> &sandbox gave demo-report//&sandbox: the profile attached to the program, plus sandbox.
  • Plain ix is type none plus inherit, so every such exec passes through the fallback. Observed with audit on 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 with target="notloaded". An allowed exec with a table target and audit: 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-plugin with pix -> &sandbox and no attaching profile ran as demo//&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/demo is a copy of a shell and the demo-* programs are copies of cat that print /proc/self/attr/current.
  • The search behind px and cx 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 uses match_char (Matching at run time, scene "Five walkers, one step"). The labels observed for px and cx are 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 -> &name and ux -> &name run without the stack when name is not loaded"; "the forced audit for "conflicting profile attachments - ux fallback" cannot trigger".

Read more

05 Secure exec, and what else a new label changes

SECURE EXEC AND THE REST Px row without AA_X_UNSAFE bprm->secureexec = 1 AT_SECURE = 1 AppArmor's hook the ELF loader, in the auxiliary vector the same program, started by demothrough px:AT_SECURE=0through Px:AT_SECURE=1 under Px the dynamic linker ignored LD_DEBUG when the label really changes: every open file is checked again a refused descriptor becomes the null device the parent-death signal is cleared resource limits follow the new profile with ix: none of this
A rule in the safe form leaves the unsafe flag out of the row; the hook then sets bprm->secureexec and the ELF loader writes AT_SECURE 1 into the auxiliary vector. Observed: the same program started through px read 0, through Px read 1. When the label changes, every open file is checked again under the new label and a refused descriptor is replaced by the null device, the parent-death signal is cleared and the resource limits of the new profile apply. None of this happens for ix

*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_transition domain.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 the ix case 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-px and /usr/bin/demo-env-Px are copies of od; each printed its own /proc/self/auxv, and entry 23 (AT_SECURE) was 0 and 1. With LD_DEBUG=statistics in the environment, the run through px printed the linker's statistics and the run through Px printed none. Which variables secure execution removes is the C library's decision: safe and unsafe exec.
  • apparmor_bprm_committing_creds lsm.c:957-973 returns early when the new label has the same proxy as the old one or is unconfined. Otherwise aa_inherit_files file.c:721-755 checks the controlling terminal and every open descriptor with aa_file_perm under the new label (the operation in a record is file_inherit) and replaces a refused descriptor with one for the null device; then current->pdeath_signal = 0; then __aa_transition_rlimits.
  • A changed label also clears the personality bits of PER_CLEAR_ON_SETID domain.c:1080-1089.
  • apparmor_bprm_committed_creds lsm.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/demo is a copy of a shell and the demo-* programs are copies of cat that print /proc/self/attr/current.
  • The descriptor replacement, the signal and the limits are read from the source and were not run.

Read more

06 no_new_privs: the old label must stay inside the new one

NO_NEW_PRIVS ctx->nnp = demo kept the first time the flag is seen on a confined task every confining profile of nnp must be in the new label else EPERM $ setpriv --no-new-privs /usr/bin/demo -c …demo-toolixdemo (enforce)demo-helperpxOperation not permitteddemo-workercxOperation not permitteddemo-freeuxOperation not permitteddemo-reportpx -> &sandboxOperation not permitteddemo-pluginpix -> &sandboxdemo//&sandbox (enforce) log: apparmor="DENIED" operation="exec" … info="no new privs" error=-1 … target="demo-helper" an unconfined task is not tested
With no_new_privs the kernel keeps a copy of the label of a confined task the first time it sees the flag, and every confining profile in that copy must still be in a new label. Observed under setpriv --no-new-privs: ix runs as demo; px, cx and ux fail with operation not permitted; px -> &sandbox fails too, because demo leaves the label; pix -> &sandbox with nothing attached runs as demo//&sandbox. The log says info no new privs

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 nnp of 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, in aa_change_hat domain.c:1341-1342 and in aa_change_profile domain.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 after prctl(PR_SET_NO_NEW_PRIVS), not the label at the prctl.
  • The test label.c:574-593: aa_label_is_unconfined_subset(set, sub) is true when every profile of sub that is missing from set is an unconfined profile. At exec domain.c:1050-1056: set is the new label, sub the snapshot; failure is -EPERM with info = "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 -EPERM without 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"; for cx target="demo//worker"; for ux target="unconfined"; for px -> &sandbox target="demo-report//&sandbox".
  • Also observed: under no_new_privs, changeprofile sandbox written to /proc/self/attr/current by demo failed, with no AppArmor record for the request.
  • Why px -> &sandbox fails: the stack is built on the profile that attaches to the program, demo-report, so demo is not in demo-report//&sandbox. With pix and no attaching profile the base is demo.
  • 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/demo is a copy of a shell and the demo-* programs are copies of cat that print /proc/self/attr/current.

Read more

07 Asking: attr/current now, attr/exec for the next exec

ASKING printf 'changeprofile sandbox' > …/attr/current printf 'exec sandbox' > …/attr/exec aa_change_profileparse the label · ask each profile changeprofile credentials get the new label now attr/current: sandbox (enforce) exec ctx->onexec = sandbox attr/exec: sandbox (enforce) attr/current: demo (enforce) next exec: used instead of the rules demo-helper (rule: px) ran as sandbox (enforce) then the request is cleared no rule: apparmor="DENIED" operation="change_onexec" … profile="demo" name="learner" the rule that permits asking: change_profile -> sandbox,
A task asks by writing to its own attr files. changeprofile sandbox written to attr/current reaches aa_change_profile, which parses the name, checks a change_profile rule in each profile and replaces the credentials at once: attr/current then reads sandbox. exec sandbox written to attr/exec parks the label in the task: attr/exec reads sandbox while attr/current still reads demo; at the next exec the hook uses the parked label instead of the exec rules, so demo-helper, whose rule says px, ran as sandbox

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_setattr lsm.c:853-927 accepts on current: changehat, permhat, changeprofile, permprofile, stack; on exec: exec, stack. The perm forms only test. Another word is refused with -EINVAL and 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 with aa_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) or AA_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 in ctx->onexec task.c:125-133; apparmor_getprocattr prints it for attr/exec lsm.c:839-840.
  • At the exec domain.c:928-975: handle_onexec first runs profile_onexec domain.c:798-869 for each in-scope profile: the executable's name is matched on the file DFA and the row needs AA_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 run profile_transition as usual.
  • Observed, the shell demo writing to its own files: after exec sandbox, attr/exec read sandbox (enforce) and attr/current read demo (enforce); the program executed next read sandbox (enforce), also when it was demo-helper, whose exec rule is px. Reading attr/exec with nothing pending failed with "Invalid argument". exec learner, which no rule allows: the write failed and apparmor="DENIED" operation="change_onexec" class="file" profile="demo" name="learner" comm="demo" target="learner" was logged. changeprofile learner: the same with operation="change_profile".
  • An unconfined task needs no rule: aa-exec -p sandbox -- cat /proc/self/attr/current printed sandbox (enforce).
  • The sysctl kernel.apparmor_restrict_unprivileged_unconfined turns a change requested by an unprivileged unconfined task into a stack with unconfined domain.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/demo is a copy of a shell and the demo-* programs are copies of cat that 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 with unconfined"; "changeprofile &name is audited as operation="change_profile"".

Read more

08 change_hat: a saved label and a token

CHANGE_HAT changehat 00000000000004d2^admin a token, a caret, a hat name a child of demo named admin, with the hat flag? no rule is consulted previous = demo token = 0x4d2 saved in the task attr/current: demo//admin (enforce) attr/prev: demo (enforce) changehat 00000000000004d2^ the token, no name: back to demo changehat 0000000000000001^ a wrong token: the task is killed apparmor="KILLED" operation="change_hat" … info="failed token match" error=-13 profile="demo//admin" … a child that is not a hat is refused · a forked child inherits previous and token known discrepancy: a change_onexec request made inside a hat overwrites the token (details below)
change_hat. The task writes changehat with a token and the name admin; the kernel finds a child of the profile with that name and the hat flag, saves the current label and the token in the task, and switches: attr/current reads demo//admin and attr/prev reads demo. Writing the token with no name returns to demo. A wrong token is fatal: the record says KILLED, failed token match, and the task is killed

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_name parses the token with simple_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. permhat tests only.
  • int aa_change_hat(const char *hats[], int count, u64 token, int flags) domain.c:1319-1445. change_hat domain.c:1169-1300: under the namespace lock, for each in-scope profile of the label, aa_find_child(root, name) where root is 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 in ctx->previous and 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, and aa_change_hat sets perms.kill, so the record is KILLED and 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 demo writing to its own file: after changehat 00000000000004d2^admin, attr/current read demo//admin (enforce) and attr/prev read demo (enforce); changehat 00000000000004d2^ returned to demo (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". ^nosuch and ^worker (a child profile, not a hat): the write failed, the label stayed demo (enforce), no record.
  • Observed: a child process forked while in the hat returned to demo (enforce) with the same token; the parent stayed demo//admin (enforce). The task context, with previous and token, 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/demo is a copy of a shell and the demo-* programs are copies of cat that 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_onexec stores the stack flag of the request in ctx->token task.c:125-133, the field that holds the hat token task.h:34-41; handle_onexec later reads that field as the flag domain.c:1028-1030. So an accepted exec NAME written to attr/exec leaves the token 0 and an accepted stack NAME leaves it 1. Observed, in a run of its own (findings/kernel/observed/run3-output.txt in the map's repository; the same guest; profile demo with the hats low and admin, where low has change_profile -> sandbox, and change_profile -> &sandbox,; the task entered low with the token 0x4d2): after exec sandbox, changehat 0000000000000000^admin entered the sibling hat and attr/current read demo//admin (enforce); after stack sandbox, changehat 0000000000000001^ returned the task to demo (enforce), and the real token got it killed. With nothing pending, each of the two writes got the task killed with info="failed token match". Limits: the rules of the hat must allow a change_onexec or stack_onexec request and the write to attr/exec; token 0 without a hat name is refused before the comparison ("NULL hat and NULL magic", procattr.c:115-118), so the exec form reaches sibling hats and the stack form 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

09 Where to go from here

ROADS Labels in the kernelthe object the hook builds Profile attachmentthe search and its score Exec modesthe rules as you write them Named exec transitionsthe arrow and the table safe and unsafe execwhat the C library removes change_profile rulespermission to ask Hatsthe profile side of change_hat Profile stackingexec with several profiles Matching at run timehow the exec row is found
Roads from this deck: Labels in the kernel for the object the hook builds, 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 stacked labels

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

Read more

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

StepCodeWhere
newest label of bprm->credaa_get_newest_label(cred_label(bprm->cred))domain.c:1007
no_new_privs snapshotctx->nnp = aa_get_label(label)domain.c:1016-1018
pending requesthandle_onexec(subj_cred, label, ctx->onexec, ctx->token, bprm, buffer, &cond, &unsafe)domain.c:1028-1030
exec rulesfn_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 taskmay_change_ptraced_domain(bprm->cred, new, &info): "ptrace prevents transition"domain.c:1063-1068
secure execbprm->secureexec = 1domain.c:1070-1078
personalityPER_CLEAR_ON_SETID is added to bprm->per_clear when the proxy differsdomain.c:1080-1089
the resultset_cred_label(bprm->cred, new)domain.c:1090-1092
committingaa_inherit_files, pdeath_signal = 0, __aa_transition_rlimitslsm.c:957-973
committedaa_clear_task_ctx_trans(task_ctx(current))lsm.c:979-985

All code.

The exec index

BitsNameMeaning
0x00ffffffAA_X_INDEX_MASKindex into the profile's string table
0x0c000000AA_X_TYPE_MASKAA_X_NONE 0, AA_X_NAME 0x04000000, AA_X_TABLE 0x08000000
0x10000000AA_X_UNSAFEdo not request a secure exec
0x20000000AA_X_CHILDsearch the profile's children
0x40000000AA_X_INHERITfallback: keep the profile
0x80000000AA_X_UNCONFINEDfallback: the namespace's unconfined label

file.h:48-64 (code).

The modes at run time

Rule in demoLookup (code)Label of the new program (observed)
ixnone; ix fallbackdemo (enforce)
pxfind_attach over the namespacedemo-helper (enforce)
cxfind_attach over the children of demodemo//worker (enforce)
uxnone; ux fallbackunconfined
pix, nothing attachessearch, then ix fallbackdemo (enforce)
px, nothing attachessearchPermission denied; info="profile transition not found", target="/usr/bin/demo-lost"
px -> sandboxtable stringsandbox (enforce)
px -> notloadedtable stringPermission denied; info="profile transition not found", target="notloaded"
px -> &sandboxtable string, then search, then mergedemo-report//&sandbox (enforce)
pix -> &sandbox, nothing attachestable string, search, fallback, mergedemo//&sandbox (enforce)
no exec rulePermission denied; requested_mask="x" denied_mask="x"
px / Px to the same programAT_SECURE 0 / 1

Reason strings of an exec record

info=WhenWhere
ix fallbacktype none or a failed lookup, with inheritdomain.c:626
ux fallbackthe same with unconfineddomain.c:636
conflicting profile attachmentstwo attachments tie in find_attachdomain.c:33-37 domain.c:495-499
conflicting profile attachments - ix fallback, - ux fallbacka tie followed by a fallbackdomain.c:622-623 domain.c:632-633
profile transition not foundexec permission but no labeldomain.c:746
could not create null profilecomplain mode, allocation faileddomain.c:762
no new privsthe subset test faileddomain.c:1054
ptrace prevents transitionthe tracer may not trace the new labeldomain.c:80
change_profile onexecdefault of a change_onexec checkdomain.c:807
no change_onexec valid for executablethe executable's row lacks the onexec permissiondomain.c:840
failed to build target labelbuilding the label faileddomain.c:972 domain.c:1641
change_profile unprivileged unconfined converted to stackingthe sysctl restriction applieddomain.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 demoResult (observed)
ixdemo (enforce)
pxOperation not permitted; info="no new privs" error=-1 ... target="demo-helper"
cxOperation not permitted; target="demo//worker"
uxOperation not permitted; target="unconfined"
px -> &sandboxOperation not permitted; target="demo-report//&sandbox"
pix -> &sandbox, nothing attachesdemo//&sandbox (enforce)
changeprofile sandboxthe 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

FileCommandKernel callOperation in the log
attr/currentchangeprofile NAMEaa_change_profile(NAME, AA_CHANGE_NOFLAGS)change_profile
attr/currentpermprofile NAMEaa_change_profile(NAME, AA_CHANGE_TEST)change_profile
attr/currentstack NAMEaa_change_profile(NAME, AA_CHANGE_STACK)stack
attr/currentchangehat TOKEN^NAMEaa_change_hat(names, count, token, AA_CHANGE_NOFLAGS)change_hat
attr/currentpermhat TOKEN^NAMEthe same with AA_CHANGE_TESTchange_hat
attr/execexec NAMEaa_change_profile(NAME, AA_CHANGE_ONEXEC)change_onexec
attr/execstack NAMEaa_change_profile with AA_CHANGE_ONEXEC and AA_CHANGE_STACKstack_onexec
eitheranything else-EINVALsetprocattr, 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):

FieldSet byCleared by
nnpthe first exec, change_hat or change_profile under no_new_privs while confinedthe end of the task
onexecaa_set_current_onexecexec committed; entering a hat; a change to unconfined or to another namespace
previousaa_set_current_hat, first entryaa_restore_previous_label; exec committed
tokenaa_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 demoResult (observed)
changehat 00000000000004d2^adminattr/current: demo//admin (enforce); attr/prev: demo (enforce)
changehat 00000000000004d2^demo (enforce)
changehat 0000000000000001^ while in the hatthe 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^nosuchthe 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 -> &name and ux -> &name run without the stack when name is not loaded.
  • find_attach keeps its candidate and conflict state across goto restart.
  • find_attach stores max(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 with unconfined.
  • changeprofile &name is audited as operation="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_SHARE is meant to stay unmediated.

Roads from here

ATTACHMENT, NAMESPACES, STACKING

FILE ACCESS

RULE CLASSES

PROFILE STRUCTURE

  • Hats — hats in a profile and the token

RUNNING THE PARSER

LIBAPPARMOR

IN THE KERNEL