Labels in the kernel

stacks and namespaces for AppArmor developers for security researchers for application developers

What a label is inside the kernel. A sorted vector of profiles that is kept once per namespace. How two labels are merged and how a stack is written with the two slashes and an ampersand. What a namespace does to a label and to its readers. How a label is printed and parsed. The three attr files under /proc. How a peer rule for signal or ptrace or unix is matched against a stacked label. And how a running task follows a profile that is replaced or removed.

On the map: in the kernel

▶ Watch this deck — 9 scenes, ~7 min

Worth seeing first

Part of journeys

01 A label is not a string

LABELS IN THE KERNEL $ ps -eo label,argsdemo (enforce)sleep 30sandbox (enforce)sleep 30demo//&sandbox (enforce)sleep 30 rules name such text too: peer=demo//&sandbox task credentials one pointer struct aa_label vec[0] → demo vec[1] → sandbox a short sorted list of profiles text is made when somebody reads, and taken apart when somebody writes in this deck: the object · namespaces · print and parse · the attr files · peers · replacement for anyone who reads labels or writes peer rules
ps shows three tasks with the labels demo, sandbox and demo//&sandbox. In the kernel a task does not hold that text: its credentials hold one pointer to a label, and the label is a sorted vector of pointers to profiles. The text is made when someone reads and taken apart when someone writes

A task's credentials hold a pointer to a struct aa_label (include/cred.h:22); the label is a sorted vector of struct aa_profile * (include/label.h:127-148). The ps output was recorded on a running kernel.

Ask ps what three sleeping tasks are confined by, and you get text: demo, sandbox, and demo//&sandbox. Rules name such text too, as a peer. You might think the kernel keeps a string per task. It doesn't. A task's credentials hold one pointer, to a label, and a label is a short sorted list of profiles. The text is made when somebody reads, and taken apart when somebody writes. This deck is about that object: how it's built, how namespaces, printing and peer rules treat it, and what happens when a profile is replaced. It's for anyone who reads labels or writes peer rules.

Details and sources

Details

  • The pointer: cred_label(cred) reads AppArmor's part of the credentials' security blob, whose size is sizeof(struct aa_label *) cred.h:22-28 lsm.c:1774. Credentials that are copied take a reference on the newest version of the label lsm.c:97-110.
  • The ps listing shows three sleep 30 tasks started with aa-exec -p demo, -p sandbox and -p 'demo//&sandbox'; ps -eo label reads /proc/PID/attr/current.
  • The profiles of the runs in this deck: demo, sandbox and learner (complain mode) in the root namespace; web and db loaded into a namespace with apparmor_parser -n c1; three senders with one signal rule each; svc for replacement.
  • Observed: a Debian guest with kernel 7.3.4 in a disposable virtual machine, parser 5.0.2; label.c differs from the tree the map describes only in an error code of the parser of label strings, and the other files this slide rests on are the same (findings/kernel/observed/README.md in the map's repository).
  • Kernel statements are read from the kernel source and were not run, except where a bullet says "observed".

Read more

02 struct aa_label: a sorted vector, kept once for AppArmor developers for security researchers

THE VECTOR struct aa_label {struct aa_proxy *proxy;long flags;int size;u64 mediates;struct aa_profile *vec[];}; [0] demo [1] sandbox NULL sorted: namespace level, namespace name, profile name struct aa_profile demo… its own label: size 1, vec[0] = demo one profile and a stack are the same kind of thing the label set: a tree per namespace one aa_label per vector, found by comparing vectors aa-exec -p 'sandbox//&demo'demo//&sandbox (enforce)aa-exec -p 'demo//&sandbox//&demo'demo//&sandbox (enforce) equal labels are the same object: comparing two is a pointer comparison
struct aa_label has a proxy pointer, flags, a mask of mediated classes, a size and a vector of profile pointers that ends in NULL. The vector is sorted by namespace level, namespace name and profile name. Every profile contains a label of size one whose only entry is the profile itself. Compound labels are kept in a tree per namespace, so asking for the same set twice gives the same object. Observed: sandbox//&demo and demo//&sandbox//&demo both print as demo//&sandbox

struct aa_label (include/label.h:127-148); order by profile_cmp (label.c:137-155); a profile's own label is set up in aa_alloc_profile (policy.c:375-420); compound labels are found or created in the namespace's label set (label.c:938-947).

It's small: a size and a vector of profile pointers ending in null. It's sorted: by how deep the namespace is, then the namespace's name, then the profile's name. Every profile contains a label of its own with one entry, itself. So a single profile and a stack are the same kind of thing, and code just loops over the vector. Stacks live in a tree, one per namespace, ordered by that same comparison. Ask for sandbox stacked with demo, or demo with sandbox twice, and you get the same object back; we saw both print as demo//&sandbox. So comparing two labels is a pointer comparison.

Details and sources

for AppArmor developers for security researchers

Details

  • The whole structure label.h:127-148: count, node (the tree), rcu, proxy, hname (a cached text, may be NULL), flags, secid, size, mediates, and a union of vec[] with, for a label inside a profile, profile[2] and the profile's rules[].
  • struct aa_profile ends in struct aa_label label policy.h:257-281; aa_alloc_profile sets label.vec[0] = profile, the profile flag and label.hname to the profile's name policy.c:375-420. labels_profile(label) is the last entry label.h:166-169.
  • Order label.c:109-155: ns_cmp compares level, then the namespace names; profile_cmp treats two profiles as equal when they are the same object or share the name pointer, else compares namespaces, then strcmp of the names. aa_vec_unique sorts and removes duplicates: insertion sort up to 8 entries, sort() above label.c:274-320.
  • The label set label.h:66-76: a red-black tree and a lock in each namespace; it holds no reference, and a label leaves it when its last reference is dropped. A compound label belongs to the set of its last member's namespace label.h:162-163.
  • aa_vec_find_or_create_label label.c:938-947: __vec_find label.c:735-758, else allocate and __label_insert, which returns an equal label already in the tree label.c:677-721. A vector of length 1 is the profile's own label label.c:915-916.
  • Flags of a compound label label.c:204-223: unconfined only if every member is; stale if any member is; mediates is the OR of the members' class masks.
  • Iteration: label_for_each, label_for_each_confined (skips members in unconfined mode) and the fn_for_each forms, which call a function per member and keep the last error label.h:175-236.
  • Observed: a Debian guest with kernel 7.3.4 in a disposable virtual machine, parser 5.0.2; label.c differs from the tree the map describes only in an error code of the parser of label strings, and the other files this slide rests on are the same (findings/kernel/observed/README.md in the map's repository).
  • Kernel statements are read from the kernel source and were not run, except where a bullet says "observed".

Read more

03 Two ways to make a label: merge and build for AppArmor developers for security researchers

MERGE AND BUILD aa_label_merge(a, b) demo + sandbox demo sandbox two sorted vectors, zipped demo sandbox + demo nothing new: the first label, unchanged stack requests · an exec rule with & · the label cached on an open file fn_label_build(label, fn) demo sandbox one answer per member sandbox sandbox one vector · sort · unique sandbox in both: an equal label that already exists wins over a new one
Two ways to make a label. aa_label_merge walks two sorted vectors like a zip and keeps equal entries once; if nothing new turned up it returns the label it was given. It is used by a stack request, by an exec rule with an ampersand and by the label cached on an open file. fn_label_build asks one function per member for a label, puts all answers into one vector, sorts it, removes duplicates and looks the result up in the tree; two members that both answer sandbox give plain sandbox

aa_label_merge (label.c:1248-1287) with label_merge_insert (label.c:1081-1141); fn_label_build (include/lib.h:289-344) with aa_vec_unique and aa_vec_find_or_create_label.

New labels come from two places. aa_label_merge takes two labels and walks both vectors like a zip, keeping equal entries once. If nothing new turned up, it hands back the label you had. That's the stack request, the ampersand in an exec rule, and the cache on an open file, which collects the labels that have used it. fn_label_build is for exec and change requests. It asks a function for a label per member, pours the answers into one vector, sorts it, drops duplicates, and looks the result up in the tree. So two members that both answer sandbox give plain sandbox. Either way, an existing equal label wins.

Details and sources

for AppArmor developers for security researchers

Details

  • struct aa_label *aa_label_merge(struct aa_label *a, struct aa_label *b, gfp_t gfp) label.c:1248-1287: a == b returns the newest a; otherwise both are taken in their newest version and a label with room for a->size + b->size entries is allocated.
  • label_merge_insert label.c:1081-1141 fills it with label_for_each_in_merge, which steps through both vectors in order and returns equal heads once label.c:994-1023. If no member was stale and the result is as long as a (or b), that label is returned. Otherwise the new label is inserted into the label set, where an equal one wins.
  • Users of merge: stack NAME domain.c:1625; an exec rule whose target begins with & domain.c:651-658; change_onexec with stack domain.c:872-880; the label cached on an open file, which grows to the union of the labels that passed a check on it file.c:469-488; the two labels cached on a unix socket af_unix.c:652-715.
  • fn_label_build(L, P, GFP, FN) lib.h:289-344; fn_label_build_in_scope lib.h:347-361 uses one function for the members in the label's namespace and another for the rest.
  • What "two members answer sandbox" looks like at exec: Profile stacking, scene "At exec, every member decides for itself".
  • The file cache file.c:626-678: a later use of an open file skips the check when no more permissions are requested than were granted and the subject's label is a subset of the cached label (aa_label_is_subset, label.c:547-558).
  • Kernel statements are read from the kernel source and were not run, except where a bullet says "observed".

Read more

04 The namespace of a label is its last member's

NAMESPACES IN A LABEL demoroot, level 0 webc1, level 1 sorted: the deepest namespace is last labels_ns(label) = c1: the label's namespace change_profile · change_onexec · change_hat touch only the members in c1 demo rides along untouched: the host profile stays who reads the label of this taskwhat the read returnsa reader in the root namespacedemo//&:c1:web (enforce)the task itselfweb (enforce)a :c1:web task reading a plain demo taskPermission denied visibility goes down the tree only
A label with demo from the root namespace and web from the namespace c1: the vector is sorted with the deepest namespace last, and the namespace of that last member is the namespace of the label. Requests the task makes about itself (change_profile, change_onexec, change_hat) touch only the members in that namespace; the others are carried along. Observed readers: the root namespace reads demo//&:c1:web, the task itself reads web, and a c1 task reading a root task gets permission denied

labels_ns() (include/label.h:162) is the namespace of the last member. "In scope" means the same namespace, "in view" also its descendants (include/lib.h:83-94, policy_ns.c:40-54). The three reads were observed.

A label can hold profiles from different namespaces, and the sort puts the deepest last. The namespace of that last member is the label's namespace, and it decides two things. First, what the task can change about itself: change_profile, change_onexec and change_hat touch only the members in that namespace, and the rest ride along. That's how a container keeps its host profile. Second, what readers see. Here's a task with demo from the root and web from namespace c1. A reader on the host sees both, with a prefix on web. The task itself sees web only. A task in c1 that looks at a host task gets permission denied.

Details and sources

Details

  • labels_ns(X) is vec_ns(&X->vec[0], X->size), the namespace of vec[size - 1] label.h:52-54 label.h:162-164. The sort key starts with the namespace's level label.c:109-126, and the root has level 0.
  • aa_ns_visible(curr, view, subns) policy_ns.c:40-54: true for the same namespace; with subns also when curr is an ancestor of view. aa_in_scope passes false, aa_in_view true lib.h:83-88.
  • In scope: label_for_each_in_scope visits the members whose namespace is the label's lib.h:90-94 label.h:200-222. change_profile checks permission in those members and replaces only those domain.c:1569-1573 domain.c:1599-1604; change_onexec domain.c:947-961 and change_hat domain.c:1290-1293 do the same. An exec without a pending request asks every member.
  • Reading: aa_getprocattr returns -EACCES when the label's namespace is not visible from the reader's, and prints with the reader's namespace as the point of view procattr.c:31-69.
  • Observed: aa-exec -p 'demo//&:c1:web' -- cat /proc/self/attr/current printed web (enforce); the same task read from a root shell: demo//&:c1:web (enforce). A task in :c1:web reading /proc/1/attr/current, and the file of a task labelled demo: "Permission denied". The same reader on a task labelled demo//&:c1:web: web (enforce).
  • Observed: a Debian guest with kernel 7.3.4 in a disposable virtual machine, parser 5.0.2; label.c differs from the tree the map describes only in an error code of the parser of label strings, and the other files this slide rests on are the same (findings/kernel/observed/README.md in the map's repository).
  • Kernel statements are read from the kernel source and were not run, except where a bullet says "observed".

Read more

05 Text out, text in

TEXT OUT, TEXT IN aa_label_snxprint demo//&sandbox (enforce)demo//&learner (mixed)demo//&unconfined (enforce)unconfined:c1:db//&web (enforce) visible members, joined with //& one mode: the common one, or mixed unconfined alone: no mode one prefix for two profiles of c1 aa_label_strn_parse demo//&:c1:web demo :c1:web split at //& by a DFA built into the kernel :c1:web//&demo :c1:web demo, looked up in c1 a prefix sticks apparmor="DENIED" operation="change_onexec" … info="label not found" error=-2 … name=":c1:web//&demo" then: sort, remove duplicates, find or create
Printing: visible members are joined with //&, a namespace prefix is written only when the namespace changes from the member before, and one mode is appended for the whole label. Observed: demo//&sandbox (enforce), demo//&learner (mixed), demo//&unconfined (enforce), unconfined, and :c1:db//&web (enforce) for two profiles of c1. Parsing: a small built-in DFA finds the separators, each piece is looked up, and a namespace prefix applies to every piece after it: demo//&:c1:web is accepted, :c1:web//&demo is refused as label not found

aa_label_snxprint (label.c:1649-1699) and aa_profile_snxprint (label.c:1538-1577) print; aa_label_strn_parse (label.c:1892-1978) parses, splitting with aa_label_strn_split on stacksplitdfa (include/label.h:322). The printed labels and the refusal were observed.

Printing walks the vector as one reader sees it. Hidden members are skipped. Visible ones are joined with //&. A namespace prefix is written only when the namespace changes from the member before, so two profiles of c1 print with one prefix. Then one mode for the whole label: the common mode, or mixed. Parsing goes the other way. A small DFA built into the kernel finds the separators. Each piece is looked up, and a prefix sticks: every later piece is looked up in that namespace. So the namespaced member must come last when you write a label. The other order was refused as label not found.

Details and sources

Details

  • int aa_label_snxprint(char *str, size_t size, struct aa_ns *ns, struct aa_label *label, int flags) label.c:1649-1699; flags FLAG_SHOW_MODE 1, FLAG_VIEW_SUBNS 2, FLAG_HIDDEN_UNCONFINED 4 label.h:297-301.
  • The prefix label.c:1550-1555: :<name>: is written when the member's namespace differs from the reader's and from the namespace of the member printed before it. So :c1:db//&web names two profiles of c1; this is the form the kernel prints and also one it accepts.
  • The mode label.c:1579-1630 label.c:1692-1696: appended once, as (mode), if any visible member is not its namespace's unconfined profile; label_modename gives the visible members' common mode, not counting unconfined members, or mixed. No visible member: unconfined when the caller passed FLAG_HIDDEN_UNCONFINED, else --- label.c:1683-1687.
  • struct aa_label *aa_label_strn_parse(struct aa_label *base, const char *str, size_t n, gfp_t gfp, bool create, bool force_stack) label.c:1892-1978. A leading &, or force_stack, puts the members of base first. Splitting: aa_label_strn_split runs aa_dfa_matchn_until on stacksplitdfa label.h:322-332.
  • Lookup of a piece label.c:1868-1878 label.c:1926-1945: a piece that begins with : is resolved from base, any other from currbase, which moves to a member as soon as that member is in another namespace. A piece may be :ns:name, :ns://name, or :ns: alone for that namespace's unconfined profile policy.c:663-690. A piece that is not found: -ENOENT.
  • With create true the compound label is created if it does not exist yet label.c:1957-1968; aa_change_profile and exec targets pass true. If the creation fails, the tree returns -ENOMEM; the guest's 7.3.4 returned -ENOENT at this place, and that is the one difference in label.c between the two. The refusal shown on the slide does not come from here: it is the lookup of a piece, the same code in both.
  • Observed with aa-exec -p LABEL -- cat /proc/self/attr/current: sandbox//&demo gave demo//&sandbox (enforce); demo//&learner gave demo//&learner (mixed); learner gave learner (complain); demo//&unconfined gave demo//&unconfined (enforce); unconfined gave unconfined. :c1:web//&:c1:db and :c1:web//&db both read db//&web (enforce) from inside and :c1:db//&web (enforce) from the root namespace. :c1:web//&demo: apparmor="DENIED" operation="change_onexec" class="file" info="label not found" error=-2 profile="unconfined" name=":c1:web//&demo" comm="aa-exec".
  • Observed: a Debian guest with kernel 7.3.4 in a disposable virtual machine, parser 5.0.2; label.c differs from the tree the map describes only in an error code of the parser of label strings, and the other files this slide rests on are the same (findings/kernel/observed/README.md in the map's repository).

Read more

06 Three files under /proc

THREE FILES UNDER /PROC filewhat is printedobservedattr/currentthe task's labeldemo//admin (enforce)attr/prevthe label a hat returns todemo (enforce)attr/execa label parked for the next execsandbox (enforce) printed for the reader's namespace, newest version out of sight: Permission denied nothing stored: Invalid argument writes: only by the task itself current changeprofile permprofile changehat permhat stack exec exec stack any other word: apparmor="DENIED" operation="setprocattr" info="current" error=-22 … the read is a file access too: the reader's profile must allow /proc/PID/attr/current
Three files in /proc/PID/attr. current prints the label in the credentials of the task, prev the label a hat returns to, exec a label parked for the next exec. A read prints the newest version of the label as seen from the namespace of the reader; a label out of sight gives permission denied, and exec or prev with nothing stored gives invalid argument. Only the task itself may write, with a few command words; any other word is refused and logged

apparmor_getprocattr (lsm.c:828-851) picks the label; aa_getprocattr (procattr.c:31-69) prints it for the reader's namespace or returns -EACCES. do_setattr (lsm.c:853-927) accepts the commands. The outputs and errors were observed.

User space meets labels in three files in a task's attr directory. current is the label in the task's credentials. exec is a label waiting for the next exec. prev is the label a hat will return to. A read prints the newest version, as seen from the reader's namespace. If that label is out of the reader's sight, the read fails with permission denied. With nothing parked, exec and prev fail with invalid argument. Only the task itself may write, and only a few command words are accepted; anything else is refused and logged. And the read is a file access too: the reader's profile must allow it.

Details and sources

Details

  • The files base.c:2875-2896: current (mode 0666), prev (0444), exec (0666) in /proc/PID/attr/, and the same three in /proc/PID/attr/apparmor/. The plain names go to the first security module that answers them security.c:3946-3957; the directory always means AppArmor. lsm_get_self_attr(2) and lsm_set_self_attr(2) reach the same code lsm.c:788-826 lsm.c:929-941.
  • Read lsm.c:828-851: current: aa_get_newest_cred_label(__task_cred(task)); prev: the task context's previous; exec: its onexec; prev or exec with nothing stored: -EINVAL.
  • int aa_getprocattr(struct aa_label *label, char **string, bool newline) procattr.c:31-69: -EACCES if the label's namespace is not visible from the reader's; else aa_label_snxprint(..., FLAG_SHOW_MODE | FLAG_VIEW_SUBNS | FLAG_HIDDEN_UNCONFINED) and a newline.
  • Write: refused by the proc layer for any task but the owner base.c:2791. The commands and what they do are in Exec and domain transitions, scenes "Asking" and "change_hat".
  • Observed: in the hat admin, attr/current read demo//admin (enforce) and attr/prev read demo (enforce); after exec sandbox was written, attr/exec read sandbox (enforce); attr/exec with nothing pending: "Invalid argument"; attr/apparmor/current returned the same text as attr/current (seen in the first run, with other profile names: ka//&:kns:kp (enforce) from both). A word that is no command: apparmor="DENIED" operation="setprocattr" info="current" error=-22 profile="demo" comm="demo".
  • Observed: a task whose profile had no rule for the file could not read its own label: apparmor="DENIED" operation="open" class="file" profile="svcc" name="/proc/3379/attr/current" comm="cat" requested_mask="r" denied_mask="r" fsuid=0 ouid=0.
  • Observed: a Debian guest with kernel 7.3.4 in a disposable virtual machine, parser 5.0.2; label.c differs from the tree the map describes only in an error code of the parser of label strings, and the other files this slide rests on are the same (findings/kernel/observed/README.md in the map's repository).

07 A peer rule meets a stacked label

A PEER RULE MEETS A STACK start[signal] byte: term the peer's label, as text a row 1 demo//&sandbox the whole label, members joined by //& 2 demo sandbox else each member alone: all must be allowed the sender's ruleto demoto sandboxto demo//&sandboxsignal (send) set=(term) peer=demo,sentdenieddeniedsignal (send) set=(term) peer=demo//&sandbox,denieddeniedsentpeer=demo, and peer=sandbox, (two rules)sentsentsent unix sockets: only step 2, each peer profile by name log: … operation="signal" … requested_mask="send" denied_mask="send" signal=term peer="demo//&sandbox"
A peer label is matched as text through the policydb. For a signal: the start state of the signal class, one byte for the signal number, then the label of the peer. First the whole label with its members joined by //&; if that does not grant the request, each member alone, and all of them must be allowed. Observed: a sender with peer=demo reaches a demo task but not the stack demo//&sandbox; a sender with a rule for the stack reaches only the stack; a sender with one rule per member reaches all three

aa_label_match (label.c:1443-1456): label_compound_match feeds the whole label, then label_components_match each member with aa_perms_accum. Callers: profile_signal_perm (ipc.c:78) and profile_ptrace_perm (task.c:254). Unix: match_label (af_unix.c:173). The nine results were observed.

Rules for signals and ptrace name a peer. The kernel compares it as text, through the policydb. For a signal: the class's start state, one byte for the signal, then the peer's label. First the whole label is fed, members joined by //&. If that doesn't grant the request, each member is fed alone, and all must be allowed. A sender allowed peer=demo reaches a demo task, but not the stack of demo and sandbox. A sender with a rule for the exact stack reaches only the stack. One with a rule per member reaches all three. Unix sockets only match member by member.

Details and sources

Details

  • Both sides are asked ipc.c:102-116: xcheck_labels(sender, target, profile, profile_signal_perm(..., target, MAY_WRITE, ...), profile_signal_perm(..., sender, MAY_READ, ...)): every profile of the sender for send with the target label as peer, every profile of the target for receive with the sender label as peer perms.h:156-197. An unconfined profile, and one whose policydb does not mediate signals, allows ipc.c:87-95.
  • int aa_label_match(const struct aa_profile *profile, struct aa_ruleset *rules, struct aa_label *label, aa_state_t state, bool inview, u32 request, struct aa_perms *perms) label.c:1443-1456.
  • The compound form label.c:1328-1366: the first visible member, then for each further one the string //& and the member. A member is its name (hname); a member of another namespace is :, the namespace name, :, the name (match_component, label.c:1294-1310). The members come in the vector's order, so a rule must spell the stack in sorted order.
  • The component form label.c:1384-1429: every visible member alone from the same start state; the rows are combined with aa_perms_accum, which ANDs allow and ORs deny perms.h:134-154. A member that leads to state 0 gives no permissions.
  • Ptrace task.c:254-329: the tracer's profiles are asked for read or trace, the tracee's for readby or tracedby; the walk starts at the label class, steps over the byte of the ptrace class and continues with aa_label_match lib.c:393-405.
  • Unix sockets af_unix.c:389-426: after type, protocol and address, match_label af_unix.c:173-193 is called for each profile of the peer label that is in scope, with the peer profile's name only.
  • Observed, with three sleep tasks labelled demo, sandbox and demo//&sandbox (their profiles have signal (receive),) and the shell builtin kill -TERM run under three sender profiles. The table on the slide is the result. Records: apparmor="DENIED" operation="signal" class="signal" profile="sender1" comm="demo" requested_mask="send" denied_mask="send" signal=term peer="sandbox" and the same with peer="demo//&sandbox"; for the sender with the stack rule, peer="demo" and peer="sandbox".
  • The receive side, ptrace and unix sockets were read from the source and not run.
  • Observed: a Debian guest with kernel 7.3.4 in a disposable virtual machine, parser 5.0.2; label.c differs from the tree the map describes only in an error code of the parser of label strings, and the other files this slide rests on are the same (findings/kernel/observed/README.md in the map's repository).

08 A profile is replaced under a running task

REPLACED UNDER A RUNNING TASK profile svc, oldlabel: stale profile svc, newa new object, a new label proxy newest task still holds the old pointer each hook follows the proxy; credentials are swapped on return to user space one task labelled svc ("plain"), never restartedplain t1: hostname DENIED, shells DENIED$ apparmor_parser -K -r svc2.sdplain t2: hostname ok, shells DENIED…$ apparmor_parser -K -R svc4.sdlabels: plain: unconfined a stack is rebuilt from its members' newest versions known discrepancy: in the run, a stacked task followed only the first change (details below) stack: sandbox//&svc (enforce)
A profile is replaced while a task runs under it. The loader builds a new profile with a new label; the old label is marked stale and the proxy both share is pointed at the new one. The task still holds the old pointer: every hook follows the proxy, and the credentials are swapped when the task returns to user space. Observed: a task that was refused a file read it after a reload, without a restart; after removal its label read unconfined. A stack is rebuilt from the newest versions of its members; in the run that happened for the first change only

aa_label_replace (label.c:849-875) redirects the shared aa_proxy and sets FLAG_STALE; aa_get_newest_label (include/label.h:408) follows it; aa_schedule_stale_label_replacement (task.c:108) swaps the credentials. Compound labels: __aa_labelset_update_subtree (label.c:2161). Observed on a running kernel.

What happens to a running task when its profile is reloaded? The loader builds a new profile object, with a new label. The old label is marked stale, and the proxy they share now points at the new one. The task keeps the old pointer. Every hook follows the proxy, and on the way back to user space the task's credentials are swapped. So new rules apply at once: our task was refused a file, and after a reload it opened it. Remove the profile, and the proxy points at unconfined. Stacks are meant to be rebuilt the same way. In our run that worked for the first change only.

Details and sources

Details

  • struct aa_proxy holds a counted pointer to a label label.h:104-107; every label has one, and a replacement takes over the proxy of the label it replaces (__proxy_share, label.c:90-97).
  • Replacing a profile policy.c:1391-1414: share_name(old, new), then __replace_profile(old, new) policy.c:1066-1110, which calls aa_label_replace(&old->label, &new->label) label.c:849-875: the proxy is pointed at the new label and the old one gets FLAG_STALE (__aa_proxy_redirect, label.c:75-88), and the new label takes the old one's place in the tree. A load that is byte for byte the loaded profile is skipped ("same as current profile, skipping").
  • Removing a profile: aa_label_remove points the proxy at the namespace's unconfined label label.c:785-798 policy.c:200-243.
  • Readers label.h:408-429: aa_get_newest_label(l) returns l->proxy->label when l is stale. Hooks begin with __begin_current_label_crit_section cred.h:149-161 cred.h:206-209; begin_current_label_crit_section also queues aa_replace_stale_label_tw_func as task work for the return to user space, which commits credentials with the newest label cred.h:222-231 task.c:93-117 task.c:48-91.
  • Compound labels policy.c:1414 label.c:2025-2175: after a load, __aa_labelset_update_subtree searches the label set of the namespace and of its children for labels with a stale member and replaces each by a label built from the members' newest versions (__label_update).
  • Observed, plain task: a shell labelled svc tried to read two files every three seconds while the profile was replaced four times and then removed. It followed every version: denied, then /etc/hostname readable, then both files, then neither, then, after apparmor_parser -R, label unconfined and both readable.
  • Observed, stacked task sandbox//&svc in the same run: it followed the first replacement (/etc/hostname became readable) and none after it: the rule added by the third version did not apply, the rule removed by the fourth stayed, and after the removal its label still read sandbox//&svc (enforce). With fresh stacks, a removal as the first change gave sandbox//&unconfined (enforce), and a change to complain mode as the first change gave (mixed); the change back did not show.
  • Known discrepancy, not yet tracked in the bug list: "Kernel: a stacked label follows only the first replacement of a member profile, because __label_replace is called inside AA_BUG". In __label_insert the call that puts the updated label into the tree is written inside an assertion, AA_BUG(!__label_replace(this, label)) label.c:706, and AA_BUG does not evaluate its argument without CONFIG_SECURITY_APPARMOR_DEBUG_ASSERTS lib.h:57-72. __label_update reaches that line with the old compound label still in the tree, then takes the old label out label.c:2063-2120. After the first update no version of the stack is in a label set, and the search for stale labels walks the set label.c:2025-2049, so later replacements and removals of a member do not find it. Observed (the bullet above): a tightened profile was not enforced on the stacked task and a removed profile kept confining it. That is a defect, not the intended behaviour: the code is written to rebuild every stale stack after each load. The guest's kernel is built without CONFIG_SECURITY_APPARMOR_DEBUG, which the assertions depend on; the lines are the same in the tree the map describes.
  • An open file keeps the label and permissions it was checked with; a later use is rechecked when the subject's label is not covered by it file.c:626-678. What a replacement does not revoke: The limits of name-based mediation.
  • Observed: a Debian guest with kernel 7.3.4 in a disposable virtual machine, parser 5.0.2; label.c differs from the tree the map describes only in an error code of the parser of label strings, and the other files this slide rests on are the same (findings/kernel/observed/README.md in the map's repository).

Read more

09 Where to go from here

ROADS Exec and domain transitionshow a new label is chosen Profile stackingstacks from the outside Policy namespacesthe tree and its views Signal rulespeer=, both ends asked Ptrace rulestracer and tracee Unix socket rulesthe peer label of a socket Matching at run timethe walk a label is fed to Reading confinementaa_getcon and the mode Reading a denialthe peer field in the log
Roads from this deck: Exec and domain transitions for how a new label is chosen, Profile stacking and Policy namespaces for the user side, Signal, Ptrace and Unix socket rules for the peer, Matching at run time for the walk, and Reading confinement for aa_getcon

Next: exec and domain transitions for how labels are chosen, profile stacking and policy namespaces for the outside view, signal, ptrace and unix rules for peers, matching at run time for the walk, the library's label calls for reading.

That's a label: a sorted vector of profiles, kept once; a namespace taken from its last member; text only at the edges; and a proxy that lets a running task follow its profile. From here, exec and domain transitions shows how the kernel chooses the profiles that go into a new label. Profile stacking and policy namespaces are the same objects seen from outside. The signal, ptrace and unix decks have the rules whose peer you now know how to read. Matching at run time is the walk that the label text is fed to. And the labels topic in the library district reads all this back with aa_getcon.

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. Of the files this page rests on, label.c differs between that kernel and the tree only in the error code returned when a compound label cannot be created; task.c, procattr.c, ipc.c, policy.c, af_unix.c and the headers are the same. "derived" means reasoned from that code.

The structure

Field of struct aa_labelMeaning
countreference count
nodeposition in the label set (a red-black tree)
proxypoints at the newest version of this label
hnamecached text, may be NULL; for a profile's label the profile's name
flagssee below
secidthe number other subsystems use for this label
sizenumber of members
mediatesone bit per rule class any member mediates
vec[]the members, sorted, NULL after the last; inside a profile: profile[2] and rules[]

label.h:127-148 (code).

FlagValueMeaning
FLAG_HAT1the profile is a hat
FLAG_UNCONFINED2on a compound label only if every member has it
FLAG_NULL4a learning profile
FLAG_IX_ON_NAME_ERROR8inherit when the executable's name cannot be built
FLAG_IMMUTIBLE0x10no replacement
FLAG_IN_TREE0x100the label is in a label set
FLAG_PROFILE0x200the label is a profile's own
FLAG_STALE0x800replaced or removed

label.h:81-101 (code; the list there is longer).

Order

1. Namespace level, lower first (the root is 0). 2. Namespace name, strcmp. 3. Profile name (hname, with the parents of a child: demo//worker), strcmp.

label.c:109-155 (code). Observed: sandbox//&demo is stored and printed as demo//&sandbox; :c1:web//&:c1:db as :c1:db//&web; demo (root) comes before :c1:web.

Making labels

FunctionInputResult
aa_label_merge(a, b, gfp) label.c:1248-1287two labelstheir union; a or b itself if nothing was added
aa_vec_find_or_create_label(vec, len, gfp) label.c:938-947a sorted, unique vectorthe label of the set with that vector, created if missing
fn_label_build(L, P, GFP, FN) lib.h:289-344a label and a function per memberthe label of all answers together
aa_label_strn_parse(base, str, n, gfp, create, force_stack) label.c:1892-1978textthe label, or -ENOENT, -EINVAL, -ENOMEM
aa_label_is_subset(set, sub) label.c:547-558two labelswhether every member of sub is in set
aa_label_is_unconfined_subset(set, sub) label.c:574-593two labelsthe same, not counting unconfined members of sub

All code.

Printing

aa_label_snxprint(str, size, ns, label, flags) label.c:1649-1699 (code):

CaseText
a member in the reader's namespaceits name
a member in a visible child namespace:<namespace, relative to the reader>:<name>, the prefix only if the previous printed member was in another namespace
a member the reader cannot seeleft out
between members//&
no visible memberunconfined with FLAG_HIDDEN_UNCONFINED, else ---
with FLAG_SHOW_MODE, some visible member is not an unconfined profile (enforce), (complain), (kill), (user) or (mixed)

Observed through /proc/PID/attr/current:

Label asked for with aa-exec -pRead by the task itselfRead from the root namespace
sandbox//&demodemo//&sandbox (enforce)the same
demo//&sandbox//&demodemo//&sandbox (enforce)the same
demo//&learner (learner is in complain mode)demo//&learner (mixed)the same
learnerlearner (complain)the same
demo//&unconfineddemo//&unconfined (enforce)the same
unconfinedunconfinedthe same
:c1:webweb (enforce):c1:web (enforce)
demo//&:c1:webweb (enforce)demo//&:c1:web (enforce)
:c1:web//&:c1:dbdb//&web (enforce):c1:db//&web (enforce)
:c1:web//&dbdb//&web (enforce):c1:db//&web (enforce)
:c1:web//&demorefused: info="label not found" error=-2
sandbox//&:c1:web//&demorefused: info="label not found" error=-2

A shell that wrote stack demo to its own attr/current while unconfined read demo//&unconfined (enforce).

The attr files

FileRead returnsErrors
/proc/PID/attr/current, attr/apparmor/currentthe newest label of the task's credentials, for the reader's namespace, with the mode and a newlineEACCES: the label's namespace is not visible to the reader
attr/prev, attr/apparmor/prevthe label saved by change_hatEINVAL: none saved
attr/exec, attr/apparmor/execthe label of a pending change_onexec or stack_onexecEINVAL: none pending

lsm.c:828-851, procattr.c:31-69 (code; the three contents and both errors observed). Writing: Exec and domain transitions.

Peer matching

ClassWho is askedInput after the class's start stateLabel match
signalevery sender profile for send, every target profile for receivethe mapped signal numberaa_label_match: compound, then components
ptraceevery tracer profile for read or trace, every tracee profile for readby or tracedbyfrom the label class: the byte of the ptrace classaa_label_match
unixthe profile and each peer profile in scopetype, protocol, addressmatch_label: the peer profile's name

ipc.c:78-116, task.c:254-329, af_unix.c:173-193, af_unix.c:389-426, label.c:1294-1456 (code).

Text fed for a member (code): its name, or : namespace : name for a member of another namespace; members of a compound are separated by //& and come in the label's order.

Observed (targets demo, sandbox, demo//&sandbox; kill -TERM from a shell under the sender profile):

Sender's ruledemosandboxdemo//&sandbox
signal (send) set=(term) peer=demo,sentdenied, peer="sandbox"denied, peer="demo//&sandbox"
signal (send) set=(term) peer=demo//&sandbox,denied, peer="demo"denied, peer="sandbox"sent
peer=demo, and peer=sandbox,sentsentsent

Replacement and removal

EventWhat the kernel does (code)
a profile is replacedthe new profile shares the old name and proxy; the proxy points at the new label; the old label is stale policy.c:1138-1145 label.c:849-875
a profile is removedits proxy points at the namespace's unconfined label label.c:785-798
after a loadcompound labels with a stale member are rebuilt label.c:2161-2175
a hook runs for a task with a stale labelit uses the proxy's label cred.h:149-161
the task returns to user spaceits credentials are replaced by ones with the newest label task.c:93-117
new credentials are preparedthey get the newest label lsm.c:97-110

Observed, one run; svc was replaced three times and removed while two shells read /etc/hostname and /etc/shells every three seconds:

svc at that momentTask labelled svcTask labelled sandbox//&svc
version 1: neither fileboth deniedboth denied
version 2: /etc/hostname r,hostname readhostname read
version 3: also /etc/shells r,both readshells denied
version 4: neitherboth deniedhostname read
removedunconfined, both readsandbox//&svc (enforce), hostname read, shells denied

With fresh stacks (observed): removal as the first change: sandbox//&svcb (enforce) became sandbox//&unconfined (enforce). Complain mode as the first change: sandbox//&svcc (mixed); back to enforce: still (mixed), while a task labelled svcc read svcc (enforce).

Caches

ObjectCachedUsed
open filethe label, grown by merge, and the permissions granted file.h:42-46aa_file_perm skips the check when the subject's label is a subset and nothing more is asked file.c:626-678
unix socketits own label and the peer's af_unix.c:652-715the same test before a recheck file.c:598-613
labelhname, its text in its own namespace label.c:1470-1496audit records

All code.

Known discrepancies

  • Not yet tracked in the bug list: "Kernel: a stacked label follows only the first replacement of a member profile, because __label_replace is called inside AA_BUG". On a kernel built without CONFIG_SECURITY_APPARMOR_DEBUG_ASSERTS a stacked label follows only the first replacement or removal of a member profile: the call that inserts the updated label is inside AA_BUG() label.c:706 lib.h:57-72. Observed (the tables above). The bug list is Bugs found while building this map.
  • Derived from the same lines and not observed: the updated label's mediates mask and unconfined flag are not computed, because accum_label_info runs in the call that is skipped.
  • labelset_of_merge picks the label set of the namespace that sorts first, while a merged label belongs to the set of its last member label.c:1150-1159; its only caller is in a commented-out block (code; latent).

Not determined

  • Whether a label string can name the root namespace again after a deeper one.
  • The printed form of a label with members in three namespaces.
  • The receive side of a signal, ptrace and unix peers on a running kernel.

Roads from here

ATTACHMENT, NAMESPACES, STACKING

RULE CLASSES

PROFILE STRUCTURE

  • Hats — the label a task carries in a hat

RUNNING THE PARSER

LIBAPPARMOR

IN THE KERNEL