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
- Profile stacking — several profiles on one task and the stacked label text
- Policy namespaces — policy namespaces and who can see what
- The profile name — the name that becomes a label
Part of journeys
- Exec, transitions and labels, step 11 of 13 · previous: Exec and domain transitions · next: aa_change_profile and onexec (no slides yet)
01 A label is not a string
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 issizeof(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
pslisting shows threesleep 30tasks started withaa-exec -p demo,-p sandboxand-p 'demo//&sandbox';ps -eo labelreads/proc/PID/attr/current. - The profiles of the runs in this deck:
demo,sandboxandlearner(complain mode) in the root namespace;webanddbloaded into a namespace withapparmor_parser -n c1; three senders with onesignalrule each;svcfor 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
- Profile stacking, scene "Reading a stacked label". The profile name.
- label.c, label.h
- wiki: apparmor_kernel_development_guide: labels, proxies and namespaces as design notes; where it and the code differ, this deck follows the code.
02 struct aa_label: a sorted vector, kept once for AppArmor developers for security researchers
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 ofvec[]with, for a label inside a profile,profile[2]and the profile'srules[]. struct aa_profileends instruct aa_label labelpolicy.h:257-281;aa_alloc_profilesetslabel.vec[0] = profile, the profile flag andlabel.hnameto 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_cmpcompareslevel, then the namespace names;profile_cmptreats two profiles as equal when they are the same object or share the name pointer, else compares namespaces, thenstrcmpof the names.aa_vec_uniquesorts 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_labellabel.c:938-947:__vec_findlabel.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;
mediatesis the OR of the members' class masks. - Iteration:
label_for_each,label_for_each_confined(skips members in unconfined mode) and thefn_for_eachforms, 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
- Profile stacking, scene "From &baz to a sorted vector": the parser side and the calls.
- Policy namespaces, scene "aa_ns, the label's namespace and the view".
- wiki: AppArmorLabelsandTypes.
03 Two ways to make a label: merge and build for AppArmor developers for security researchers
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 == breturns the newesta; otherwise both are taken in their newest version and a label with room fora->size + b->sizeentries is allocated.label_merge_insertlabel.c:1081-1141 fills it withlabel_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 asa(orb), that label is returned. Otherwise the new label is inserted into the label set, where an equal one wins.- Users of merge:
stack NAMEdomain.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_scopelib.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
- Exec and domain transitions, scene "apparmor_bprm_creds_for_exec, step by step".
- Profile stacking.
- wiki: apparmor_kernel_development_guide: labels, proxies and namespaces as design notes; where it and the code differ, this deck follows the code.
04 The namespace of a label is its last member's
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)isvec_ns(&X->vec[0], X->size), the namespace ofvec[size - 1]label.h:52-54 label.h:162-164. The sort key starts with the namespace'slevellabel.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; withsubnsalso whencurris an ancestor ofview.aa_in_scopepasses false,aa_in_viewtrue lib.h:83-88.- In scope:
label_for_each_in_scopevisits 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_getprocattrreturns-EACCESwhen 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/currentprintedweb (enforce); the same task read from a root shell:demo//&:c1:web (enforce). A task in:c1:webreading/proc/1/attr/current, and the file of a task labelleddemo: "Permission denied". The same reader on a task labelleddemo//&: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
- Policy namespaces, scenes "One label, three readers" and "A container: its own namespace, under a host profile".
- Profile stacking, scene "A stack across namespaces".
- wiki: CombiningStackingAndNamespaces (draft).
05 Text out, text in
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; flagsFLAG_SHOW_MODE1,FLAG_VIEW_SUBNS2,FLAG_HIDDEN_UNCONFINED4 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//&webnames two profiles ofc1; 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_modenamegives the visible members' common mode, not counting unconfined members, ormixed. No visible member:unconfinedwhen the caller passedFLAG_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&, orforce_stack, puts the members ofbasefirst. Splitting:aa_label_strn_splitrunsaa_dfa_matchn_untilonstacksplitdfalabel.h:322-332.- Lookup of a piece label.c:1868-1878 label.c:1926-1945: a piece that begins with
:is resolved frombase, any other fromcurrbase, 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
createtrue the compound label is created if it does not exist yet label.c:1957-1968;aa_change_profileand exec targets pass true. If the creation fails, the tree returns-ENOMEM; the guest's 7.3.4 returned-ENOENTat 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//&demogavedemo//&sandbox (enforce);demo//&learnergavedemo//&learner (mixed);learnergavelearner (complain);demo//&unconfinedgavedemo//&unconfined (enforce);unconfinedgaveunconfined.:c1:web//&:c1:dband:c1:web//&dbboth readdb//&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
- Profile stacking, scene "Reading a stacked label". Reading confinement.
- Matching at run time, scene "Five walkers, one step": the walker that finds
//&. - aa_getcon(2), aa_splitcon(3).
06 Three files under /proc
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)andlsm_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'sprevious;exec: itsonexec;prevorexecwith nothing stored:-EINVAL. int aa_getprocattr(struct aa_label *label, char **string, bool newline)procattr.c:31-69:-EACCESif the label's namespace is not visible from the reader's; elseaa_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/currentreaddemo//admin (enforce)andattr/prevreaddemo (enforce); afterexec sandboxwas written,attr/execreadsandbox (enforce);attr/execwith nothing pending: "Invalid argument";attr/apparmor/currentreturned the same text asattr/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
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
readortrace, the tracee's forreadbyortracedby; the walk starts at the label class, steps over the byte of the ptrace class and continues withaa_label_matchlib.c:393-405. - Unix sockets af_unix.c:389-426: after type, protocol and address,
match_labelaf_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
sleeptasks labelleddemo,sandboxanddemo//&sandbox(their profiles havesignal (receive),) and the shell builtinkill -TERMrun 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 withpeer="demo//&sandbox"; for the sender with the stack rule,peer="demo"andpeer="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).
Read more
- Signal rules, Ptrace rules, Unix socket rules, Rule conditionals.
- Matching at run time, scene "Every other class starts with one byte".
- apparmor.d(5) Signal rules, apparmor.d(5) PTrace rules.
08 A profile is replaced under a running task
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_proxyholds 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 callsaa_label_replace(&old->label, &new->label)label.c:849-875: the proxy is pointed at the new label and the old one getsFLAG_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_removepoints 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)returnsl->proxy->labelwhenlis stale. Hooks begin with__begin_current_label_crit_sectioncred.h:149-161 cred.h:206-209;begin_current_label_crit_sectionalso queuesaa_replace_stale_label_tw_funcas 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_subtreesearches 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
svctried to read two files every three seconds while the profile was replaced four times and then removed. It followed every version: denied, then/etc/hostnamereadable, then both files, then neither, then, afterapparmor_parser -R, labelunconfinedand both readable. - Observed, stacked task
sandbox//&svcin the same run: it followed the first replacement (/etc/hostnamebecame 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 readsandbox//&svc (enforce). With fresh stacks, a removal as the first change gavesandbox//&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_replaceis called insideAA_BUG". In__label_insertthe call that puts the updated label into the tree is written inside an assertion,AA_BUG(!__label_replace(this, label))label.c:706, andAA_BUGdoes not evaluate its argument withoutCONFIG_SECURITY_APPARMOR_DEBUG_ASSERTSlib.h:57-72.__label_updatereaches 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 withoutCONFIG_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
- Loading policy into the kernel. The limits of name-based mediation, on access that outlives a rule.
- Profile stacking.
- wiki: apparmor_kernel_development_guide: labels, proxies and namespaces as design notes; where it and the code differ, this deck follows the code.
09 Where to go from here
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
- The deck in five lines: a label is a sorted, NULL-terminated vector of profiles, interned per namespace; its namespace is its last member's, and self-directed changes act on the members in it; the text form is produced by
aa_label_snxprintand consumed byaa_label_strn_parse; a peer label is fed to the policydb whole, then member by member; a stale label is followed through its proxy. - Exec and domain transitions, Profile stacking, Policy namespaces, Signal rules, Ptrace rules, Unix socket rules, io_uring rules, Hats, Matching at run time, Reading confinement, Reading a denial.
- Sources for this deck: Linux 97d73c825 for the code; two runs on a Debian guest for the observed results.
Read more
- label.c, label.h, procattr.c, ipc.c.
- wiki: apparmor_kernel_development_guide: labels, proxies and namespaces as design notes; where it and the code differ, this deck follows the code.
- wiki: AppArmorLabelsandTypes.
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_label | Meaning |
|---|---|
count | reference count |
node | position in the label set (a red-black tree) |
proxy | points at the newest version of this label |
hname | cached text, may be NULL; for a profile's label the profile's name |
flags | see below |
secid | the number other subsystems use for this label |
size | number of members |
mediates | one 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).
| Flag | Value | Meaning |
|---|---|---|
FLAG_HAT | 1 | the profile is a hat |
FLAG_UNCONFINED | 2 | on a compound label only if every member has it |
FLAG_NULL | 4 | a learning profile |
FLAG_IX_ON_NAME_ERROR | 8 | inherit when the executable's name cannot be built |
FLAG_IMMUTIBLE | 0x10 | no replacement |
FLAG_IN_TREE | 0x100 | the label is in a label set |
FLAG_PROFILE | 0x200 | the label is a profile's own |
FLAG_STALE | 0x800 | replaced 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
| Function | Input | Result |
|---|---|---|
aa_label_merge(a, b, gfp) label.c:1248-1287 | two labels | their union; a or b itself if nothing was added |
aa_vec_find_or_create_label(vec, len, gfp) label.c:938-947 | a sorted, unique vector | the label of the set with that vector, created if missing |
fn_label_build(L, P, GFP, FN) lib.h:289-344 | a label and a function per member | the label of all answers together |
aa_label_strn_parse(base, str, n, gfp, create, force_stack) label.c:1892-1978 | text | the label, or -ENOENT, -EINVAL, -ENOMEM |
aa_label_is_subset(set, sub) label.c:547-558 | two labels | whether every member of sub is in set |
aa_label_is_unconfined_subset(set, sub) label.c:574-593 | two labels | the same, not counting unconfined members of sub |
All code.
Printing
aa_label_snxprint(str, size, ns, label, flags) label.c:1649-1699 (code):
| Case | Text |
|---|---|
| a member in the reader's namespace | its 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 see | left out |
| between members | //& |
| no visible member | unconfined 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 -p | Read by the task itself | Read from the root namespace |
|---|---|---|
sandbox//&demo | demo//&sandbox (enforce) | the same |
demo//&sandbox//&demo | demo//&sandbox (enforce) | the same |
demo//&learner (learner is in complain mode) | demo//&learner (mixed) | the same |
learner | learner (complain) | the same |
demo//&unconfined | demo//&unconfined (enforce) | the same |
unconfined | unconfined | the same |
:c1:web | web (enforce) | :c1:web (enforce) |
demo//&:c1:web | web (enforce) | demo//&:c1:web (enforce) |
:c1:web//&:c1:db | db//&web (enforce) | :c1:db//&web (enforce) |
:c1:web//&db | db//&web (enforce) | :c1:db//&web (enforce) |
:c1:web//&demo | refused: info="label not found" error=-2 | |
sandbox//&:c1:web//&demo | refused: 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
| File | Read returns | Errors |
|---|---|---|
/proc/PID/attr/current, attr/apparmor/current | the newest label of the task's credentials, for the reader's namespace, with the mode and a newline | EACCES: the label's namespace is not visible to the reader |
attr/prev, attr/apparmor/prev | the label saved by change_hat | EINVAL: none saved |
attr/exec, attr/apparmor/exec | the label of a pending change_onexec or stack_onexec | EINVAL: 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
| Class | Who is asked | Input after the class's start state | Label match |
|---|---|---|---|
| signal | every sender profile for send, every target profile for receive | the mapped signal number | aa_label_match: compound, then components |
| ptrace | every tracer profile for read or trace, every tracee profile for readby or tracedby | from the label class: the byte of the ptrace class | aa_label_match |
| unix | the profile and each peer profile in scope | type, protocol, address | match_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 rule | demo | sandbox | demo//&sandbox |
|---|---|---|---|
signal (send) set=(term) peer=demo, | sent | denied, 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, | sent | sent | sent |
Replacement and removal
| Event | What the kernel does (code) |
|---|---|
| a profile is replaced | the 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 removed | its proxy points at the namespace's unconfined label label.c:785-798 |
| after a load | compound labels with a stale member are rebuilt label.c:2161-2175 |
| a hook runs for a task with a stale label | it uses the proxy's label cred.h:149-161 |
| the task returns to user space | its credentials are replaced by ones with the newest label task.c:93-117 |
| new credentials are prepared | they 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 moment | Task labelled svc | Task labelled sandbox//&svc |
|---|---|---|
| version 1: neither file | both denied | both denied |
version 2: /etc/hostname r, | hostname read | hostname read |
version 3: also /etc/shells r, | both read | shells denied |
| version 4: neither | both denied | hostname read |
| removed | unconfined, both read | sandbox//&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
| Object | Cached | Used |
|---|---|---|
| open file | the label, grown by merge, and the permissions granted file.h:42-46 | aa_file_perm skips the check when the subject's label is a subset and nothing more is asked file.c:626-678 |
| unix socket | its own label and the peer's af_unix.c:652-715 | the same test before a recheck file.c:598-613 |
| label | hname, its text in its own namespace label.c:1470-1496 | audit 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_replaceis called insideAA_BUG". On a kernel built withoutCONFIG_SECURITY_APPARMOR_DEBUG_ASSERTSa stacked label follows only the first replacement or removal of a member profile: the call that inserts the updated label is insideAA_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
mediatesmask and unconfined flag are not computed, becauseaccum_label_inforuns in the call that is skipped. labelset_of_mergepicks 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
- Profile stacking — stacked labels from the user's side
- Policy namespaces — the namespace tree and who may load policy
RULE CLASSES
- Signal rules — signal rules and their peer
- Ptrace rules — ptrace rules and their peer
- Unix socket rules — unix socket rules and their peer label
- Rule conditionals — where peer and label appear in a rule
PROFILE STRUCTURE
- Hats — the label a task carries in a hat
RUNNING THE PARSER
- Loading policy into the kernel (no slides yet) — replacing and removing profiles
- Reading a denial — the peer field in a log record
LIBAPPARMOR
- Reading confinement (no slides yet) — reading a label with aa_getcon
IN THE KERNEL
- Exec and domain transitions — how exec and requests build a new label
- Matching at run time — the walk that a peer label is fed to