Profile stacking
two profiles at once for application developers for administrators for AppArmor developers for security researchers
Confining a task by several profiles at once so that it may do only what all of them allow. The //& label; aa_stack_profile and aa_stack_onexec; the change_profile permission for stacking; exec rules with -> &name; denials; no_new_privs; and stacks across namespaces.
On the map: attachment namespaces stacking
▶ Watch this deck — 12 scenes, ~10 min
Worth seeing first
- Profile attachment — how exec picks a profile, which each stack member repeats
- change_profile rules — the change_profile rule that permits stacking
- Named exec transitions — exec targets after an arrow, including the ampersand form
Part of journeys
- Exec, transitions and labels, step 8 of 13 · previous: change_profile rules · next: Policy namespaces
01 Two profiles on one task
A stack is a set of profiles that all confine one task. An access is allowed only when every confined member allows it, so the result is the intersection. Stacking adds a profile; it does not replace the current one.
Foo runs under its own profile, and it's about to handle untrusted input. You'd like to tighten it for that phase without writing a third profile that repeats the first. Or you run containers, and want a host profile to stay on every task whatever policy the container loads. Both are stacking: a second profile, baz, is added to the task, and the first one stays. From then on every request is put to both. Reading the config file is allowed by both, so it goes through. Writing the log is allowed by foo but not by baz, so it's denied. A stack can only take away. This deck is for anyone who reads stacked labels, writes the rules behind them, or works on the code.
Details and sources
Details
- A stack is one label with several profiles. Kernel side: the hooks run the check once per confining member and keep the last error, so one refusal fails the request. For a file path that is
fn_for_each_confined(label, profile, profile_path_perm(...))(file.c:302-304, label.h:225-236). - The aa-exec manual page says the same: "all profiles in the stack are checked as if they were the profile confining the application. The resulting mediation is the intersection of what is allowed by each profile in the stack." (aa-exec.pod:97-101).
- Ways to get a stack, each with its own slide:
aa_stack_profile(),aa_stack_onexec(), an exec rule with-> &NAME, andaa-exec -p "a//&b". - The kernel advertises support in
/sys/kernel/security/apparmor/features/domain/stack(apparmorfs.c:2606). - Regression test for the picture on the slide: with two stacked profiles, a file allowed by only one of them fails with
EACCESand a file allowed by both passes (stackprofile.sh:85-90). - The profiles
fooandbazand the files on the slide are invented for the map. Kernel behaviour is stated from the source, not observed on a running kernel.
Read more
- apparmor.net: Stacking.
- aa_stack_profile(2) and aa-exec(1).
- AppArmor wiki: AppArmorStacking (marked Draft WIP by its authors).
- Namespaces: the container case.
02 Reading a stacked label
name1//&name2 (mode). Members are sorted (namespace depth, then namespace name, then profile name) and unique. The mode is the members' common mode, or mixed. aa_getcon and aa_splitcon separate only the trailing mode; nothing in libapparmor splits on //&.
This is what a stacked task looks like from outside: the names of its profiles, joined by //&, and one mode in brackets. You read it from the task's attribute file, or with aa_getcon, which hands you the label and the mode as two strings. Three things to know when you read one. The order is the kernel's sort order, so foo that stacked baz reads baz first; it says nothing about which came first or which matters more. A member appears once: stack baz again and nothing changes. And there's one mode for the whole label: enforce if all members enforce, complain if all complain, and mixed when they differ.
Details and sources
Details
- Text form:
name1//&name2 (mode). Read it from/proc/PID/attr/currentor/proc/PID/attr/apparmor/current, withps -Z, or in code. - Library:
int aa_getcon(char **label, char **mode),int aa_gettaskcon(pid_t target, char **label, char **mode),char *aa_splitcon(char *con, char **mode)(kernel.c:1280-1283). They cut off the trailing(mode)only; nothing in libapparmor splits a label on//&(kernel.c:556-633). - Order, the kernel: members are sorted by namespace level, then namespace name, then profile name (label.c:109-155). The printed order is that sort order, not the order of stacking.
- A member appears once: merging a label with one it already contains returns the existing label (label.c:1130-1133, label.c:1256-1257).
- Mode: the members' common mode,
mixedwhen they differ; a namespace'sunconfinedis skipped (label.c:1579-1608). mixedis not a profile mode.aa-statushas it only in its list of process statuses (aa_status.c:134).- Regression tests assert the member set and the mode:
enforcefor two enforcing profiles,mixedandcomplainfor the other combinations (stackprofile.sh:90, stackprofile.sh:148, stackprofile.sh:170). The tests compare member sets; the printed order is derived from the kernel's sort. - From the aa-exec manual page:
aa-exec -p "unconfined//&firefox" -- bash, thenps -Zprintsfirefox//&unconfined (unconfined)(aa-exec.pod:108-118).
03 unconfined is a real member of a stack
From an unconfined task, stack baz yields baz//&unconfined (enforce). Access checks equal those of baz, but by the kernel's exec rules the unconfined member still takes part in exec and attaches profiles by executable path. This differs from aa_change_profile("baz"), whatever aa_stack_profile(3) says.
Here's one that catches people. Stack baz from an unconfined shell and read the label back: it isn't baz, it's baz, //&, unconfined. Unconfined is a member like any other. For file access that changes nothing, because unconfined allows everything and baz decides. The difference shows at the next exec. By the kernel's rules each member makes its own decision, and the unconfined member does what unconfined tasks do: it looks for a profile attached to the program. So starting foo from this shell gives baz stacked with foo, where a shell that had changed to baz would stay in baz. The library manual page says stacking from unconfined equals changing profile; the kernel code and its regression test say otherwise.
Details and sources
Details
- From an unconfined shell:
echo -n "stack baz" > /proc/self/attr/current, thencat /proc/self/attr/current. By the kernel's sort the label readsbaz//&unconfined (enforce). - The kernel: a stack request merges the target into the current label, whatever that label is (domain.c:1623-1628). Nothing removes
unconfinedfrom the result. - The regression test expects exactly this member set,
unconfined//&plus the stacked profile, with modeenforce, and fails a check for mode(null)(stackprofile.sh:68-76). - At exec the unconfined member runs the normal attachment search over its namespace's profiles (domain.c:697-720), so
baz//&unconfinedthat starts/usr/bin/foobecomesbaz//&foowhenbazhasixfor it. This result is derived from the code and was not run. - Known discrepancy: the manual page says "Calling aa_stack_profile("profile_a") while unconfined is equivalent to calling aa_change_profile("profile_a")" (aa_stack_profile.pod:52-54). Access is the same; the label and later exec transitions are not.
- The aa-exec manual page shows the same label shape:
firefox//&unconfined (unconfined), where thatfirefoxprofile hasflags=(unconfined)(aa-exec.pod:108-118).
Read more
- aa_stack_profile(2).
- AppArmor wiki: Unconfined, the unconfined flag and default allow.
- Attachment: the search the unconfined member runs at exec.
04 aa_stack_profile and aa_stack_onexec
aa_stack_profile(name) writes stack name to attr/current and takes effect at once. aa_stack_onexec(name) writes stack name to attr/exec and takes effect at the next execve, keeping the current profile. Errors: EACCES (no rule), ENOENT (not loaded), EINVAL (NULL).
There are two calls. aa_stack_profile adds the profile right now. It writes the word stack and the name to the task's current attribute, and when it returns, the task is confined by both. Files that are already open aren't rechecked, so open what you need first. aa_stack_onexec writes the same words to the exec attribute, and nothing changes until the next exec; then the current profile is kept, the new one is added, and the current profile's own exec rule for that program isn't consulted. Both fail with permission denied if the task's profile has no rule allowing the stack, and with no such file or directory if the profile isn't loaded. From a shell, an echo into the same file does it.
Details and sources
Details
- Signatures (apparmor.h:85-86): -
int aa_stack_profile(const char *profile);-int aa_stack_onexec(const char *profile); aa_stack_profilewritesstack NAMEto thecurrentattribute,aa_stack_onexecwritesstack NAMEto theexecattribute (kernel.c:1204-1244). The write goes through thelsm_set_self_attrsystem call when it is available, otherwise/proc/TID/attr/apparmor/currentor/proc/TID/attr/current(kernel.c:997-1012).- From a shell (aa_stack_profile.pod:112-117):
echo -n "stack profile_a" > /proc/self/attr/currentandecho -n "stack profile_a" > /proc/self/attr/exec. - The kernel accepts
changehat,permhat,changeprofile,permprofileandstackoncurrent, andexecandstackonexec(lsm.c:882-904). - Immediate: the target is merged into the current label and the task's label is replaced (domain.c:1623-1628). On exec: the request is stored in the task and applied at the next
execve; the members in the task's namespace keep their profile, get the target added, and their own exec rules are not used (domain.c:1629-1636, domain.c:953-961). - Open files: "Open file descriptors may not be remediated after a call to aa_stack_profile()" (aa_stack_profile.pod:63-65).
- Errors listed by the manual page:
EINVAL,ENOMEM,ENOENT(aa_stack_profile.pod:84-98).EACCESfor a missing rule is not listed there; the regression tests expect it, andENOENTfor a profile that is not loaded (stackprofile.sh:80, stackprofile.sh:97, stackonexec.sh:81-98). - A confined caller also needs write access to the attribute file:
/proc/*/attr/current w,or/proc/*/attr/exec w,.
Read more
05 Permission to stack is not permission to change
A stack request is matched as &name. change_profile -> baz, permits changing to baz; change_profile -> &baz, permits stacking it; change_profile, permits both; unconfined tasks need no rule. Without a matching rule the call fails with EACCES. The parser accepts the & rule when both the kernel and the profile's ABI have domain/stack; a profile file with no abi rule fails with The current kernel does not support stacking of named transitions: &baz.
Which rule lets foo stack baz? It's the change_profile rule, with an ampersand in front of the target. And the ampersand matters in both directions. When a task asks to stack, the kernel looks for the name with the ampersand in the profile's rules. A rule that names plain baz doesn't match, so stacking is refused, even though stacking can only remove access. A rule that names &baz allows stacking but not a plain change. The bare rule, change_profile with no target, covers both. An unconfined task needs no rule at all. And since the request is a write to the task's own attribute file, the profile has to allow that write too.
Details and sources
Details
- Rules:
change_profile -> baz,permits a change tobaz;change_profile -> &baz,permits stacking it;change_profile,permits both. With an exec condition:change_profile /bin/foo -> &bar,. - Parser tests: stacking_ok_1.sd (
change_profile -> &/bin/foo,), stacking_ok_2.sd (-> &bar), stacking_ok_3.sd (with an exec condition). - The kernel matches a stack request with
&in front of the name, and a namespaced target as:, namespace,:, name (domain.c:94-112). A target that is itself a stack is tried as a whole and then member by member (domain.c:256-271). - An unconfined profile gets the permission without a rule (domain.c:290-302). For a confined task, every member in the task's namespace is asked before the merge (domain.c:1569-1576).
- Without a rule the call fails with
EACCES: stackprofile.sh:94-97. The bare rule is what the regression test uses to stack a bare namespace:change_profile,thenstack :ns:(stackprofile.sh:174-181). Thatchange_profile -> baz,does not permit stackingbazfollows from the kernel's match and is not asserted by a test. - Parser message, verbatim:
The current kernel does not support stacking of named transitions: %s(parser_regex.c:742-755). It is printed when the kernel features or the profile's ABI lackdomain/stack(parser_main.c:1093-1095); the parser's built-in default ABI, used for a file with noabirule, has nostackentry indomain(default_features.c:169). Putabi <abi/3.0>,or newer in the file. - The request is a write to
/proc/PID/attr/current, so the profile needs a file rule for it; the regression test's profile has/proc/*/attr/current w,next tochange_profile-> &:nnp:unconfined,(nnp.sh:104-110).
Read more
for AppArmor developers for security researchers
In the code
- The change_profile production; a bare rule gets the target
**(parser_yacc.y:1648-1690). - With stacking support the target,
&included, is compiled as one string (parser_regex.c:760-762). change_profile_perms()is called per profile from the wrapper at domain.c:1458-1461.
06 px -> &baz stacks on what attaches, not on you
PATH ix -> &baz, gives the current profile plus baz when no profile attaches to PATH. PATH px -> &baz, gives the profile attached to PATH plus baz, and by the kernel code the exec fails with info="profile transition not found" when nothing attaches. The current profile stays only with ix or with aa_stack_onexec.
An exec rule can stack too: put an ampersand in front of the target. It's easy to read px -> &baz as: run bar under me, plus baz. That's not what the kernel code does. It first works out the ordinary transition for the rule, and then adds baz to that. With ix, and no profile attached to bar, the ordinary result is your own profile, so you get foo and baz. With px the ordinary result is whichever profile attaches to bar; you get that one and baz, and foo is gone. And if nothing attaches, px has nothing to build on and the exec is denied. So to keep foo, use ix, or stack on exec from the program itself.
Details and sources
Details
- Syntax:
/bin/bar px -> &baz,or/bin/bar ix -> &baz,. No space between&and the name. Parser test: stacking_ok_1.sd. - The kernel, read from the code: a table target that starts with
&is kept aside as the stack, and the kernel then runs the ordinary search for a profile attached to the program (domain.c:592-611). The lookup of the target skips the&(domain.c:540). - The result is the attached profile merged with the stack: the comment in the code is "base the stack on post domain transition" (domain.c:651-658).
- Fallbacks when nothing attaches:
ixkeeps the current profile,uxgives the namespace'sunconfined(domain.c:616-638). Withpxthere is no base and the exec fails withinfo="profile transition not found"(domain.c:740-751). Thepxcases are derived from the code and were not run. - The
ixcase is tested:ix -> &othertestgives the labeltest//&othertestin modeenforce(exec_stack.sh:83-90); a namespaced target,ix -> &:ns:name, is at exec_stack.sh:120. - Known discrepancy: the parser does not validate or gate exec targets that start with
&;/bin/bar px -> &,is accepted by the parser built from the AppArmor tree at 836052d21. - Known discrepancy:
cx -> &namein profiletis stored ast//&name, which the kernel reads as the stack oftand a top-level profilename, not a child (kernel side read, not run).
Read more
- apparmor.net: Stacking: exec transitions to a stack.
- apparmor.d(5): Directed profile transitions.
- Named exec transitions, exec modes, attachment.
for AppArmor developers for security researchers
In the code
- The target after
->and the two file rule productions (parser_yacc.y:1043-1047, parser_yacc.y:1072-1103). add_named_transition()stores the string with its&; forcxit prefixes the profile name and//(block_rules.cc:474-524).
07 At exec, every member decides for itself
By the kernel code, at execve each member computes its own transition; the resulting labels are merged, sorted and de-duplicated. One member's refusal fails the exec. A stack can shrink (two px to the same profile) or grow (px -> &name).
A stacked task starts another program. Who decides the new confinement? By the kernel's rules, everybody. Each member looks up the program in its own rules and gives its own answer: stay, move to another profile, go unconfined, or refuse. The answers are put together into the new label. So if baz says inherit and foo says px, the new label is bar stacked with baz. If both say px, both answers are bar, and the label is just bar: the stack got smaller. And if one member has no rule for the program, the exec fails, whatever the others say. A stack doesn't survive exec by itself; it survives because its members' rules keep it.
Details and sources
Details
All from the kernel source; the example labels are derived from the code and were not run.
- At
execvethe kernel builds the new label by running the transition for each member and merging the results (domain.c:1032-1035). The helper isfn_label_build(lib.h:289-343). - One member's transition is
profile_transition(): it matches the program's path against that member's rules and returns stay (ix), another profile (px,cx),unconfined(ux) or an error (domain.c:665-796). - An error from any member fails the exec.
- The merged label is sorted and de-duplicated, so two members that both move to
barleave the single profilebar. - A member that is
unconfinedsearches for an attached profile, as an unconfined task does. - The aa-exec manual page: "During an exec each profile gets to specify its transition and the results brought together to form a new canonicalized stack." (aa-exec.pod:103-106).
- Each member that asks for a safe exec sets
AT_SECUREfor the new program (domain.c:778-783, domain.c:1070-1078).
Read more
- aa-exec(1): the STACKING section.
- apparmor.net: Stacking.
- Exec modes, exec in the kernel, attachment.
08 A denial names one profile, not the stack
Each denying member writes its own record with profile="<that member>" (and namespace= if it is not in the root namespace). The //& text appears in target= and peer= fields. Stack requests are logged as operation="stack" or operation="stack_onexec". The record shown is built from the order in which the kernel prints fields; it was not captured from a running system.
The task is confined by baz and foo, and something is denied. You search the log for the stacked label and find nothing. That's because each member checks and logs for itself. Going by the kernel code, the record looks like this: it comes from the member that refused, and its profile field has that one name. The members that allowed the access stay silent. If two members refuse, you get two records. That's good news for fixing things: the record tells you exactly which profile to edit. The stacked form does turn up in other fields: the target of an exec or a stack request, and the peer of a signal or a socket.
Details and sources
Details
Read from the kernel source. The record on the slide is built from the order in which the kernel prints fields; it was not captured from a running system.
- Shape of the record for the task
baz//&foo:apparmor="DENIED" operation="open" class="file" profile="baz" name="/var/log/foo.log" ... requested_mask="w" denied_mask="w" fsuid=... ouid=.... - Each member audits for itself:
aa_audit()sets the subject of the record to that one profile (audit.c:207-224). profile=holds one name;namespace=is printed in front of it when the profile is not in the root namespace.label=is used only when the subject is a label of several profiles (audit.c:116-133).- Modes apply per member: a complain-mode member logs
ALLOWEDfor its own miss, an enforcing member logsDENIED(audit.c:211-214). target=carries the full label for exec, change_profile and stack records (file.c:69-72);peer=carries it for signals and sockets (ipc.c:73-75, net.c:162-164).- Stack requests are logged as
operation="stack"andoperation="stack_onexec"(audit.h:97-98). - What aa-logprof and the libapparmor log parser do with
//&in these fields was not determined; there is no stacked record among the log fixtures in the AppArmor tree.
09 Under no_new_privs, changing fails and stacking works
With no_new_privs: aa_change_profile, aa_change_onexec, px and ux to a label that drops a confining profile fail with EPERM (info="no new privs" on exec); aa_stack_profile, aa_stack_onexec and ix work. Transitions from unconfined are not restricted.
Sandboxed programs often run with no_new_privs set, and with it the kernel refuses any AppArmor transition that could loosen confinement. It can't compare two profiles rule by rule, so it uses a simple test: the new label must still contain every confining profile of the old one. Changing from foo to baz fails that test, however strict baz is, and so does a px exec to another profile; you get operation not permitted. Stacking passes by construction, because foo stays in the label. So if your program runs with no_new_privs and wants to tighten itself, stacking is the tool that works. An ix exec is unaffected, and the regression tests check each of these cases.
Details and sources
Details
no_new_privsis set withprctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0).- The kernel: at the first exec or change_profile after the flag was set, a confined task's current label is saved (domain.c:1010-1018). A later exec must produce a label that still contains every member of the saved label that is not
unconfined, otherwise it fails withEPERMandinfo="no new privs"(domain.c:1050-1056). - The test is
aa_label_is_unconfined_subset()(label.c:561-593). - For
aa_change_profilethe same test applies, withEPERMand no audit record ("not an apparmor denial per se, so don't log it"); a stack request skips it: "stacking is always a subset, so only check the nonstack case" (domain.c:1597, domain.c:1609-1618). - The kernel advertises the rule in
/sys/kernel/security/apparmor/features/domain/post_nnp_subset(apparmorfs.c:2608). - Regression tests, each run without and with the flag (nnp.sh:47-98):
ixpasses;ux,px, change on exec and change profile fail withEPERM; stack on exec and stack profile pass. Stacking theunconfinedprofile of a new namespace also passes (nnp.sh:101-123). - A record of this kind from the libapparmor test suite:
apparmor="DENIED" operation="change_onexec" info="no new privs" error=-1 ... target="system_tor"(change_onexec_lp1648143.in). - The saved label is the one at AppArmor's first transition attempt after the flag was set, not the one at the
prctlcall.
Read more
- aa_stack_profile(2) and aa_change_profile(2).
- AppArmor wiki: AppArmorStacking (marked Draft WIP by its authors).
- The calls that replace a profile, exec in the kernel.
10 A stack across namespaces
In host//&:c1:foo the task's namespace is c1. Changing profile, changing hat and on-exec requests ask and replace only the c1 members; host is carried over unchanged and still checked on every access. The host reads the full label; the task reads foo (enforce).
The members of a stack don't have to live in the same namespace. This is the container case: a host profile, and a profile from the container's own namespace, c1. Every access is still checked against both. What's special is who can change what. When the task, from inside, changes profile, the kernel code asks and replaces only the members in the task's own namespace. The host member is out of scope: it isn't consulted, and it's carried into the new label untouched. So nothing done inside the container removes it. The two sides also read different labels: the host sees the whole stack, and the task sees only its own part. Getting in took a rule as well: change_profile, with the ampersand and the namespaced name.
Details and sources
Details
Read from the kernel source, unless a test is named.
- Label:
host//&:c1:fooseen from the root namespace. The rule that letshostadd it:change_profile -> &:c1:foo,; the call:aa_stack_profile(":c1:foo"), which writesstack :c1:foo. - The namespace of a label is the namespace of its last member, the deepest one because of the sort (label.h:53, label.h:162).
- "In scope" is the set of members in that namespace (label.h:200-222, lib.h:90-94). Change profile, change hat and on-exec requests ask and replace only those; the other members are carried over (domain.c:1569-1573, domain.c:1598-1604, domain.c:1290, domain.c:953-961).
- Every member of every namespace is still checked on each access.
- A reader sees members in its own namespace or below (policy_ns.c:40-54); the task reads
foo (enforce), the host reads the whole label. - Regression test: a profile with
change_profile -> &:ns:stackprofile,stacks the namespaced profile; a file that only one of the two allows fails withEACCES, and the task reads its own label asstackprofilein modeenforce(stackprofile.sh:117-139). - The aa-exec manual page: after
aa-exec -p "unconfined//&:ex1:unconfined" -- bash,ps -Zinside showsunconfined, and from the parentunconfined//&:ex1:unconfined(aa-exec.pod:167-182).
Read more
- AppArmor wiki: CombiningStackingAndNamespaces (marked Draft WIP by its authors).
- AppArmor wiki: AppArmorPolicyScope and AppArmorPolicyView.
- Namespaces: syntax, the tree and who may load policy.
11 From &baz to a sorted vector for AppArmor developers
aa_label_merge (label.c:1248) unions two sorted vectors; order is profile_cmp (label.c:109-155). Hooks iterate with fn_for_each_confined (include/label.h:225-236); exec uses fn_label_build (include/lib.h:289-343). The parser stores &name as text (block_rules.cc:474-524, parser_regex.c:760-762).
On the parser side there's almost nothing. The ampersand is a legal first character of a name, so &baz goes into the transition table, or into the change_profile pattern, as text. At exec, the table lookup strips the ampersand, lets the normal attachment search pick the base, and merges the two. For a request, the stack command reaches aa_change_profile with the stack flag and merges with the current label. A label is a sorted vector of profile pointers. Merge is a union of two sorted vectors: equal entries once, and if nothing new was added the old label is returned. Labels are interned, so equal stacks are the same object.
Details and sources
for AppArmor developers for security researchers
Details
- Lexer:
&may start a label token (parser_lex.l:253, parser_lex.l:301-302). add_named_transition()puts the target,&included, into the exec table (block_rules.cc:474-524); a change_profile target is compiled as text (parser_regex.c:742-762).- The kernel, exec:
x_table_lookup()skips the leading&(domain.c:523-559);x_to_label()keeps the result asstack, falls through to the attachment search and merges (domain.c:574-663). - Request:
do_setattr()mapsstacktoaa_change_profile(args, AA_CHANGE_STACK), and on theexecattribute toAA_CHANGE_ONEXEC | AA_CHANGE_STACK(lsm.c:873-904);int aa_change_profile(const char *fqname, int flags)does the parse, the permission check per in-scope profile and the merge (domain.c:1484-1655). struct aa_labelhassizeandvec[], a vector of profile pointers (label.h:127-147).- Order:
ns_cmp()andprofile_cmp(), by namespace level, namespace name, profile name (label.c:109-155).aa_vec_unique()sorts and de-duplicates (label.c:274-318). - Merge:
aa_label_next_in_merge()zips two sorted vectors and returns equal heads once (label.c:994-1023);label_merge_insert()returns the existing label when nothing was added (label.c:1100-1141);aa_label_merge(a, b, gfp)returnsafora == b(label.c:1248-1275). - Iteration:
fn_for_each_confinedin the hooks (label.h:185-188, label.h:225-236);fn_label_buildat exec (lib.h:289-343). stringson the binary policy for/bin/bar px -> &baz,shows&baz(apparmor_parser 6.0.0~alpha2, 836052d21).
Read more
- AppArmor wiki: apparmor_kernel_development_guide: labels, proxies and domain transitions.
- AppArmor wiki: AppArmorLabelsandTypes.
- Labels in the kernel, exec in the kernel.
12 Where to go from here
Next: attachment and namespaces (the sister decks), syn-change-profile and lib-change-profile (the rule and the calls), lib-labels and adm-denials (reading labels and records), k-labels (the kernel side).
That's stacking. Several profiles on one task, every one of them asked, the label written with //&, and a request that can only add. To go on: attachment shows how exec chooses the profile that a stacked exec rule builds on, and namespaces explains the namespace part of a container's label. The change_profile topics cover the rule and the library calls that replace a profile rather than add one. If you read labels in a program, see the labels topic in the library district; if you read them in the audit log, see denials. And the kernel labels topic has the data structure.
Details and sources
Details
- A stack: several profiles on one task, every one asked for every access, the label written with
//&. - Interfaces met in this deck:
aa_stack_profile(),aa_stack_onexec(), thestackcommand on/proc/PID/attr/currentand/proc/PID/attr/exec, the ruleschange_profile -> &NAME,andPATH ix -> &NAME,,aa-exec -p "a//&b", andfeatures/domain/stackin apparmorfs. - A denial names the one member that refused;
//&shows up intarget=andpeer=. - Commits read for this deck: AppArmor 836052d21 (6.0.0~alpha2), the kernel-rc2 (97d73c825). Kernel behaviour is stated from the source; results marked as tested come from the regression tests in the AppArmor tree.
Read more
Label text
name1//&name2 (mode)
- A stacked label is its member names joined by
//&, followed by one mode for the whole label. A member may carry a namespace::ns:nameor:ns://name. - Order. The kernel keeps the members sorted: namespace depth first (the root namespace before its children), then namespace name, then the full profile name in byte order. The printed order is this sort order, not the order of stacking:
foothat stacksbazreadsbaz//&foo. The order carries no priority; every member is asked for every operation. - Uniqueness. A member appears once. Stacking a profile onto a label that already contains it changes nothing, so there is no "stack depth".
- Mode.
enforcewhen all visible members enforce,complainwhen all complain,mixedwhen they differ.mixedis not a profile mode;aa-statuslists it as a process status. A namespace'sunconfinedprofile is skipped when the mode is computed. - Namespace prefix. The prefix is printed only when the namespace differs from the reader's and from the previous member's: two members of
c1seen from the parent print as:c1:a//&b. On input, a member without a namespace is looked up in the namespace of the last member that named one. - Bare namespace.
:ns:,:ns://and:nsname that namespace'sunconfinedprofile. - **Leading
&.** On input to the kernel a leading&means "stack on top of the current label". - A profile whose name contains
//&cannot be told apart from a stack. Compare labels as whole strings.
Worked examples
All profiles are in enforce mode and in the root namespace unless stated. "test" means a regression test in the AppArmor tree asserts the member set and the mode; "derived" means the result follows from the kernel code and was not run. The order of members in a printed label is always derived from the kernel's sort.
| Start label | Action | Label read from the root namespace | Basis |
|---|---|---|---|
foo | aa_stack_profile("baz") with change_profile -> &baz, in foo | baz//&foo (enforce) | test: stackprofile.sh:90 |
baz//&foo | aa_stack_profile("baz") | baz//&foo (enforce), unchanged | derived |
unconfined | echo -n "stack baz" > /proc/self/attr/current | baz//&unconfined (enforce) | test: stackprofile.sh:74 |
unconfined | aa-exec -p "unconfined//&firefox" -- bash | firefox//&unconfined (unconfined); that firefox profile has flags=(unconfined) | aa-exec(1) |
foo (enforce) | stack baz (complain) | baz//&foo (mixed) | test: stackprofile.sh:148 |
foo (complain) | stack baz (complain) | baz//&foo (complain) | test: stackprofile.sh:170 |
a | stack b, then exec and stack c | a//&b//&c (enforce) | test: stackprofile.sh:108 |
foo | exec /bin/bar with /bin/bar ix -> &baz,; no profile attaches to /bin/bar | baz//&foo (enforce) | test (shape): exec_stack.sh:83-90 |
foo | exec /bin/bar with /bin/bar px -> &baz,; profile bar attaches | bar//&baz (enforce) | derived |
baz//&foo | exec; foo has px and bar attaches, baz has ix | bar//&baz (enforce) | derived |
baz//&unconfined | exec /usr/bin/foo; baz has ix, profile foo attaches | baz//&foo (enforce) | derived |
host | aa_stack_profile(":c1:foo") with change_profile -> &:c1:foo, | host//&:c1:foo (enforce); the task itself reads foo (enforce) | test (self view): stackprofile.sh:120-139 |
host//&:c1:foo | inside: aa_change_profile("baz") with change_profile -> baz, in :c1:foo | host//&:c1:baz (enforce); self view baz (enforce) | derived |
unconfined | aa-exec -p "unconfined//&:ex1:unconfined" -- bash | unconfined//&:ex1:unconfined; self view unconfined | aa-exec(1) |
baz//&foo, both with hat worker | aa_change_hat("worker", token) | baz//worker//&foo//worker (enforce) | derived |
foo, no_new_privs set | aa_change_profile("baz") with a matching rule | fails with EPERM; label stays foo | test: nnp.sh:69 |
foo, no_new_privs set | aa_stack_profile("baz") with change_profile -> &baz, | baz//&foo (enforce) | test: nnp.sh:83 |
Text written to the kernel in each case:
| Call | Text | File |
|---|---|---|
aa_stack_profile("baz") | stack baz | attr/current |
aa_stack_profile(":c1:foo") | stack :c1:foo | attr/current |
aa_stack_onexec("baz") | stack baz | attr/exec |
aa_change_profile("baz") | changeprofile baz | attr/current |
aa-exec -p "unconfined//&firefox" | exec unconfined//&firefox | attr/exec |
Rules
FILEGLOB ACCESS -> &TARGET, ACCESS FILEGLOB -> &TARGET, change_profile [safe] [EXEC] -> &TARGET, change_profile [unsafe] [EXEC] -> &TARGET,
- ACCESS on a file rule must contain an exec mode (
ix,px,uxand their variants). No space is allowed between&and TARGET. - TARGET may be
name,:ns:name,:ns://name, a quoted name, or several members joined with//&(&a//&b). Onchange_profilerules it may contain globs:change_profile /bin/x -> &:ns:**,. change_profile -> baz,permits a change tobazand not a stack;change_profile -> &baz,permits the stack and not the change; barechange_profile,permits both. An unconfined task needs no rule. When the requested target is itself a stack, the kernel accepts a rule for the whole string (&a//&b) or rules for each member.- A confined task also needs write access to the attribute file it writes the request to:
/proc/*/attr/current w,foraa_stack_profile,/proc/*/attr/exec w,foraa_stack_onexec. - The rule is covered in change_profile rules.
Accepted and rejected (seen with apparmor_parser 6.0.0~alpha2 (836052d21), -Q -K --skip-kernel-load, abi/5.0 kernel features; "with domain/stack" means abi <abi/5.0>, in the file):
| Rule | Result |
|---|---|
/bin/bar px -> &baz, | accepted |
/bin/bar ix -> &baz, and the pix and ux variants | accepted |
/bin/bar px -> &:ns:baz, and &:ns://baz | accepted |
/bin/bar px -> &a//&b, | accepted |
/bin/bar px -> "&b c", | accepted (quoted target) |
/bin/bar px -> & baz, | syntax error, unexpected TOK_ID, expecting TOK_END_OF_RULE |
/bin/bar x -> &baz, | Invalid perms, 'x' must be preceded by exec qualifier 'i', 'p', or 'u' |
change_profile -> &bar, | accepted when both the kernel and the profile's ABI have domain/stack; a profile with no abi rule fails with The current kernel does not support stacking of named transitions: &bar |
change_profile /bin/x -> &:ns:**, | accepted with domain/stack |
change_profile safe /bin/x -> &b, | accepted with domain/stack |
change_profile -> a//&b, | accepted: permission to change to the stack a//&b |
change-profile -> &x, | Lexer found unexpected character: '-' (0x2d) in state: INITIAL |
profile &foo { } | Profile names must begin with a '/' or a namespace |
Library
int aa_stack_profile(const char *profile); int aa_stack_onexec(const char *profile); int aa_getcon(char **label, char **mode); int aa_gettaskcon(pid_t target, char **label, char **mode); char *aa_splitcon(char *con, char **mode);
aa_stack_profileformatsstack NAMEand writes it to the task'scurrentattribute: throughlsm_set_self_attrwhen available, otherwise/proc/<tid>/attr/apparmor/current, otherwise/proc/<tid>/attr/current. It takes effect when the call returns. Files that are already open are not rechecked, and without anexecvethere is no memory barrier between the code before and after the call.aa_stack_onexecwrites the samestack NAMEto theexecattribute. Permission is checked at once; the label changes at the nextexecve. The pending request can be read back from/proc/PID/attr/exec.- The argument is parsed as a label, so
stack a//&badds several members at once.
| errno | When |
|---|---|
EINVAL | NULL argument (checked in the library before any write); a missing argument in the written text |
ENOMEM | out of memory |
ENOENT | the profile, or its namespace, is not loaded or not visible |
EACCES | no rule in the task's profile permits the stack (not listed in the manual page) |
EPERM | a tracer of the task may not trace the new label (not listed in the manual page) |
aa_getconandaa_gettaskconreturn the label of a stacked task as one string with//&inside, and one mode.aa_splitconsearches backwards for(and cuts there; nothing in libapparmor splits a label on//&. A task that is plainlyunconfinedhas no mode (*modeis NULL).- The label a task reads for itself can be shorter than the label read from the host; see Namespaces below. Reading labels from code is covered in lib-labels; the calls that replace a profile are in lib-change-profile.
Command words accepted by the attribute files:
| File | Commands |
|---|---|
/proc/PID/attr/current | changehat, permhat, changeprofile, permprofile, stack |
/proc/PID/attr/exec | exec, stack |
The first space ends the command. A name that itself starts with & turns any of the profile commands into a stack request, so changeprofile &baz stacks baz. A write is limited to one page.
Exec
- **
PATH ix -> &x,** The kernel first runs the ordinary lookup for a profile attached to PATH. When none attaches, the current profile is kept andxis added. When one does attach, that profile is the base. - **
PATH px -> &x,** The base is the profile attached to PATH; the current profile is not in the result. When nothing attaches the exec fails withEACCESandinfo="profile transition not found"(derived). - **
PATH ux -> &x,** Asix, but the fallback base is the namespace'sunconfined. - Every member decides. When a stacked task execs, each member applies its own exec rule to the program and returns a label; the labels are merged, sorted and de-duplicated. An error from any member fails the exec. The stack can shrink (two
pxto the same profile) or grow (px -> &x). aa-exec(1) puts it this way: each profile gets to specify its transition and the results are brought together to form a new stack. - **An
unconfinedmember** behaves as an unconfined task does: it looks for a profile attached to the program and otherwise staysunconfined. - A pending on-exec request replaces the exec rules of the members in the task's own namespace.
aa_stack_onexec: in-scope members are kept and the target is added.aa_change_onexec: in-scope members are replaced by the target. In both cases those members need the on-exec permission for the program (info="no change_onexec valid for executable"otherwise) and their exec rules are not used; members from outer namespaces run their normal exec transition. - **
AT_SECURE.** A stack-on-exec setsAT_SECUREfor the new program unless thechange_profilerule saysunsafe; so does any member whose exec rule asks for a safe exec. - How exec picks the attached profile is the subject of attachment.
no_new_privs
- The first time an exec, change_hat or change_profile runs with no_new_privs set on a confined task, the kernel saves the current label. Later transitions must produce a label that still contains every member of the saved label that is not
unconfined. - The saved label is the one at AppArmor's first transition attempt after the flag was set, not the one at the
prctlcall. A profile stacked after that point is not part of it, so policy may drop it again later while keeping the saved members. - The kernel advertises the rule as
domain/post_nnp_subsetin its features directory.
| Under no_new_privs | Result | Test (tests/regression/apparmor/nnp.sh) |
|---|---|---|
ix exec | allowed | :47-48 |
ux exec | EPERM | :54 |
px exec | EPERM, record with info="no new privs" and error=-1, one per member | :59 |
aa_change_onexec | EPERM | :64 |
aa_change_profile | EPERM, no audit record | :69 |
aa_stack_onexec | allowed | :78 |
aa_stack_profile | allowed | :83 |
x//&unconfined moving to x//&y | allowed: the unconfined member of the saved label is ignored | :92-98 |
stacking :nnp:unconfined, a new namespace | allowed | :121 |
Transitions from an unconfined task are not restricted.
Audit
- Each member checks and audits for itself. A denial is written by the member that refused, with
profile="<that member>", preceded bynamespace="..."when the member is not in the root namespace (for a childc1of the root the value isroot//c1). Members that allowed the access write nothing; two refusing members write two records. - Modes apply per member. A complain-mode member logs
ALLOWEDfor its own miss; an enforcing member logsDENIEDand the operation fails. A complain-mode member does not make the stack permissive. - Shape of a file denial for the task
baz//&foo, in the order the kernel prints the fields (not captured from a running system):
apparmor="DENIED" operation="open" class="file" profile="baz" name="/var/log/foo.log" ... requested_mask="w" denied_mask="w" fsuid=... ouid=...
| Field | When it carries //& |
|---|---|
target= | exec, change_profile and stack records: the new or requested label |
peer= | signal, ptrace and socket records: the other task's label |
label= | records whose subject is the whole label: a rejected attribute command (operation="setprocattr") and policy management |
profile= | not for a stack: one member per record |
| Record text | Meaning |
|---|---|
operation="stack" | an aa_stack_profile request |
operation="stack_onexec" | an aa_stack_onexec request |
info="label not found" | the target does not exist (ENOENT) |
info="failed to build target label" | the kernel could not build the new label |
info="no change_onexec valid for executable" | a pending on-exec request without permission for this program |
info="no new privs" | exec refused by the no_new_privs test |
info="profile transition not found" | px with nothing attached |
info="ix fallback", info="ux fallback" | a named or stacked target fell back to ix or ux |
info="change_profile unprivileged unconfined converted to stacking" | see Other effects below |
info="ptrace prevents transition" | a tracer may not trace the new label |
What aa-logprof and the libapparmor log parser do with //& in these fields was not determined; there is no stacked record among the log fixtures in the tree. Reading denials in general: adm-denials.
Namespaces
- Scope. The namespace of a label is the namespace of its last member, which is the deepest one because of the sort. "In scope" means the members of that namespace. Requests a task makes about itself (change_profile, change_hat, stack and on-exec requests) ask and replace only in-scope members; outer members are carried over unchanged.
- Mediation. Every member of every namespace is checked on each access, so a host profile keeps limiting a container whatever the container's own policy allows.
- View. A reader sees only members in its own namespace or below. The container's tasks read their label without the host member; the host reads the full stack. The mode shown inside reflects only the visible members.
- Lookup. A name without a namespace is resolved in the namespace of the task's label: inside
c1,aa_change_profile("baz")means:c1:baz. The target namespace must exist and be the task's namespace or below it, otherwiseENOENT. - Stack targets:
:NS:NAME,:NS://NAME, or bare:NS:for the namespace'sunconfined. Rule:change_profile -> &:NS:NAME,. - Documented example (aa-exec(1)):
aa-exec -p "unconfined//&:ex1:unconfined" -- bash. Inside,ps -Zshowsunconfinedfor the shell and-for processes outside the namespace; from the parent the shell isunconfined//&:ex1:unconfined. aa_stack_onexecof a bare:ns:leaves the task readingunconfinedwith no mode: it is in the namespace'sunconfined, stacked under its old profile (stackonexec.sh:178-180).- Namespace nesting is limited to 32 levels. Namespace syntax, creation and visibility: namespaces.
Other effects of a stack
- change_hat. A hat name is accepted only when every in-scope member has a hat of that name; each such member then moves to its own hat:
baz//worker//&foo//worker. When no supplied name fits, the error isENOENTwithinfo="hat not found"if any in-scope member has children, elseECHILDwithinfo="no hats defined". Stacking a second profile onto a program that uses hats breaks itsaa_change_hatcalls unless the second profile defines the same hats; a member from an outer namespace does not need them. (Derived from the kernel code.) - Unprivileged unconfined. With the kernel's unprivileged-unconfined restriction on, a plain change_profile or change-on-exec by an unconfined task without
CAP_MAC_OVERRIDEis turned into a stack:aa-exec -p baz -- cmdruns asbaz//&unconfined, with a record carryinginfo="change_profile unprivileged unconfined converted to stacking". Access is that ofbaz; theunconfinedmember keeps attaching profiles at exec. - Path names. Each member builds the path name of a file with its own flags, so
attach_disconnectedon one member does not apply to another. - Policy reload. A member that was replaced is swapped for its newest version and the label is sorted and de-duplicated again.
- Limits. There is no maximum number of members. The text form must fit the interface it passes through (one page for a write to
/proc).
Parser errors and warnings
| Message | When |
|---|---|
The current kernel does not support stacking of named transitions: %s | a change_profile rule with a & target, and the kernel or the profile's ABI lacks domain/stack; a profile file with no abi rule is in that case, whatever the kernel supports |
downgrading change_profile safe rule to unsafe due to lack of necessary kernel support | warning: change_profile safe without stacking support in the kernel |
Profile names must begin with a '/' or a namespace | profile &foo { }: & cannot start a profile name |
Invalid perms, 'x' must be preceded by exec qualifier 'i', 'p', or 'u' | /bin/bar x -> &baz, |
syntax error, unexpected TOK_ID, expecting TOK_END_OF_RULE | a space after &: /bin/bar px -> & baz, (seen with 6.0.0~alpha2) |
Lexer found unexpected character: '-' (0x2d) in state: INITIAL | the keyword spelled change-profile |
Known discrepancies
These are places where the code, the documentation or the expected meaning disagree. They are described as what the code does, not as intended design, and none is a technique to rely on.
- **
cx -> &namedoes not select a child.** The parser stores the target of acxrule in profiletast//&name, which the kernel reads as the stack oftand a top-level profilename(kernel side read, not run). - **
ix -> &nameorux -> &namewithnamenot loaded.** The exec proceeds with theixoruxfallback and without the stacked profile; withpx -> &namethe exec fails instead (read in the kernel code, not run). - **Exec targets with
&are not validated and not gated.** The parser checksdomain/stackand the target syntax only forchange_profilerules;/bin/bar px -> &,is accepted. - aa_stack_profile(3) says stacking from unconfined "is equivalent to calling aa_change_profile". The kernel produces
name//&unconfined, and the regression test expects that member set (stackprofile.sh:74). Access is the same; the label and later exec transitions are not. - aa_stack_profile(3) spells the rule keyword
change-profilein its example profile; the parser accepts onlychange_profile. - **
changeprofile &name** stacks, but is logged asoperation="change_profile"with the&kept inname=.
for AppArmor developers
Code map
Kernel paths are relative to linux:security/apparmor/; parser paths to the AppArmor tree.
| What | Where |
|---|---|
struct aa_label (size, vec[]), FLAG_PROFILE for the label embedded in one profile | include/label.h:127-157 |
ns_cmp, profile_cmp: namespace level, namespace name, profile name | label.c:109-155 |
vec_cmp: order of labels in a namespace's label set (rb-tree) | label.c:168-188 |
aa_vec_unique: sort and de-duplicate; insertion sort up to 8 entries | label.c:274-318 |
aa_label_next_in_merge: zip two sorted vectors, equal heads once | label.c:994-1023 |
label_merge_insert: fill the vector, refresh stale members, intern or reuse | label.c:1081-1141 |
aa_label_merge(a, b, gfp); a == b returns a | label.c:1248-1275 |
aa_label_snxprint, mode of a compound label, FLAG_HIDDEN_UNCONFINED | label.c:1538-1608, 1668-1696 |
aa_label_strn_parse and the stack-split DFA for //& | label.c:1861-1978, stacksplitdfa.in, include/label.h:322-343 |
__label_update: rebuild stale compound labels after a reload | label.c:2063-2125 |
aa_label_is_unconfined_subset: the no_new_privs test | label.c:574-592 |
fn_for_each, fn_for_each_confined, last_error | include/label.h:150-155, 185-188, 225-236 |
fn_for_each_in_ns, in-scope helpers | include/label.h:200-222, include/lib.h:90-94 |
fn_label_build, fn_label_build_in_scope | include/lib.h:289-361 |
matching a target label: & prefix and &:NS:NAME; label_match tries the whole stack, then each member | domain.c:94-112, 256-271 |
change_profile_perms; unconfined needs no rule | domain.c:290-302 |
x_table_lookup: skips the leading & | domain.c:523-559 |
x_to_label: stack = new, fall through to AA_X_NAME, "base the stack on post domain transition" | domain.c:574-663 |
profile_transition, the unconfined member's attachment | domain.c:665-796 |
profile_onexec, handle_onexec: pending on-exec requests | domain.c:798-975 |
exec: fn_label_build over the label, then no_new_privs, ptrace, AT_SECURE | domain.c:1010-1078 |
| change_hat on a compound label | domain.c:1169-1300 |
aa_change_profile(fqname, flags): operation name, leading &, parse, permission per in-scope profile, tracer, merge or store | domain.c:1484-1655 |
do_setattr: stack on current and on exec | lsm.c:853-921 |
aa_set_current_onexec: target and stack flag in the task context | task.c:125-133 |
audit_pre: profile=, namespace=, label= | audit.c:116-133 |
aa_getprocattr: view flags, -EACCES for an invisible namespace | procattr.c:31-70 |
domain/stack, domain/post_nnp_subset feature files | apparmorfs.c:2606-2608 |
lexer: & may start a label token; SUB_ID_WS after -> | parser/parser_lex.l:253, 301-302, 456-461, 822 |
exec rule target becomes nt_name | parser/parser_yacc.y:1043-1103, 1759-1768 |
add_named_transition: stores the string, & included; cx prefixes PROFILE// | parser/block_rules.cc:474-524 |
change_profile rule; safe downgrade warning; bare rule uses target ** | parser/parser_yacc.y:1648-1690 |
change_profile target compiled as one DFA string with stacking support; parse_label and the & refusal without it | parser/parser_regex.c:742-762 |
features_supports_stacking read from domain/stack | parser/parser_main.c:1093-1095 |
aa_stack_profile, aa_stack_onexec, setprocattr paths | libraries/libapparmor/src/kernel.c:997-1012, 1204-1244 |
splitcon, aa_getcon, aa_gettaskcon | libraries/libapparmor/src/kernel.c:556-633, 1261-1283 |
- A stack request is permission-checked for every in-scope profile before the merge; stacking currently needs the same kind of permission as a plain change (comment at domain.c:1561-1567).
- The result of a merge that adds nothing is the existing label (label.c:1130-1133). Two tasks with the same stack share one
struct aa_label. stringson the binary policy for/bin/bar px -> &baz,shows&baz(apparmor_parser 6.0.0~alpha2). Whether the parser emits a different xindex for-> &namewhen it writes the extended permission table itself was not determined.- The kernel structure is the subject of k-labels.
Roads from here
ATTACHMENT, NAMESPACES, STACKING
- Profile attachment — how exec picks the profile that a stack is built on
- Policy namespaces — the :ns: part of a stacked label and who can see it
RULE CLASSES
- change_profile rules — the rule that permits changing and stacking
RUNNING THE PARSER
- Reading a denial — reading the audit records a stack produces
LIBAPPARMOR
- aa_change_profile and onexec (no slides yet) — the library calls that change instead of stack
- Reading confinement (no slides yet) — reading a label and its mode with aa_getcon
IN THE KERNEL
- Labels in the kernel — labels as sorted vectors in the kernel