Policy namespaces
separate policy sets for application developers for administrators for AppArmor developers for security researchers
Named sets of profiles each with its own unconfined profile. The :ns:profile syntax; loading with apparmor_parser -n; the tree under policy/namespaces; who can see and manage what; and how a container gets its own policy on top of a host profile.
On the map: attachment namespaces stacking
▶ Watch this deck — 12 scenes, ~10 min
Worth seeing first
- The profile name — the profile name that the namespace prefix goes in front of
- Named exec transitions — exec targets after an arrow, used to enter a namespace
- Profile stacking — the stacked labels a container task carries
Part of journeys
- Exec, transitions and labels, step 9 of 13 · previous: Profile stacking · next: Exec and domain transitions
01 The same profile name, twice
A policy namespace holds its own profiles and its own unconfined profile. Profile names are
unique within a namespace and are not shared between namespaces: foo and :c1:foo are
different profiles.
A container wants its own AppArmor policy: its own profile for /usr/bin/foo, loaded by its own tools. But profile names are unique, and the host already has a foo. A policy namespace solves this. It's a named set of profiles with its own unconfined profile. Inside c1, foo means c1's foo; from the host it's written :c1:foo. This deck shows the syntax, how to load into a namespace, what the tree looks like in the kernel's filesystem, who can see what, and how a container is set up. It has nothing to do with user or mount namespaces, although containers use those too.
Details and sources
Details
- Written form:
:c1:foois profilefooin policy namespacec1; a barefoois looked up in the namespace of the task that asks. - The kernel's own definition, the kernel: a namespace "defines the set profiles that are searched to determine which profile to attach to a task", profiles "can not be shared" between namespaces, names are unique within one, and "only namespaces and profiles below the current namespace are visible" (policy_ns.h:49-58).
- Every namespace gets its own
unconfinedprofile when it is allocated (policy_ns.c:122-126). - Namespace names cannot contain
:,/or NUL (policy_ns.h:58). - In the filesystem a namespace is the directory
/sys/kernel/security/apparmor/policy/namespaces/NAME/(apparmorfs.c:2229-2280). - The parser accepts the same profile name in the root namespace and in two others in one file: profile_ns_ok4.sd.
- Policy namespaces are not user, mount or PID namespaces.
features/namespaces/in apparmorfs and theusernsrule are about user namespaces; see the userns rule. - The names
c1,fooandhostare invented for the map.
Read more
- AppArmor wiki: AppArmorNamespaces: naming, visibility and views.
- AppArmor wiki: AppArmorPolicyView and AppArmorPolicyScope.
- Attachment and stacking, the two neighbours of this deck.
02 Writing a namespace in a profile name
:ns:name and :ns://name both name profile name in namespace
ns. Errors: Namespace not terminated: ..., Empty namespace: ...,
Empty named transition profile name: .... A duplicate in the same namespace gives
Multiple definitions for profile ... exist,bailing out.
The syntax is small. Start the profile name with a colon, write the namespace, close it with a second colon, then the usual name and attachment. One file can hold foo for the root namespace and foo for two others, and nothing clashes. You may put two slashes after the second colon; the parser accepts both spellings and they mean the same. With the namespace in front, the profile keyword is optional. Three things go wrong: a missing second colon, an empty namespace, and a namespace with no profile name. That last message talks about a named transition even though you wrote a profile head; the wording is a known discrepancy. And inside the profile, the profile name variable is plain foo.
Details and sources
Details
- Forms:
:ns:name { },profile :ns:name { },:ns:name /attach { }and:ns://name { }. The parser strips an optional//after the second colon, so both spellings give the same namespace and name (parser_misc.c:874-881). - Test profiles from the AppArmor tree: profile_ns_ok1.sd (
:foo:/does/not/exist), profile_ns_named_ok1.sd (:foo:exist /does/not/exist), profile_ns_ok4.sd (one name in three namespaces). - Error messages, verbatim (parser_misc.c:925-931): -
Namespace not terminated: %sforprofile :ns/t { }(profile_ns_bad8.sd); -Empty namespace: %sfor::/does/not/exist { }(profile_ns_bad4.sd); -Empty named transition profile name: %sfor:namespace: { }(profile_ns_bad5.sd). The wording mentions a transition although the input is a profile head. - A second definition of a name in the same namespace:
Multiple definitions for profile %s exist,bailing out.(parser_policy.c:64). @{profile_name}inside:ns:/hnameis/hname, without the namespace; the parser's equality test asserts both directions (equality.sh:909-915).- The parser does not check which characters the namespace contains. The limit (no
:,/or NUL) is stated by the kernel (policy_ns.h:58). apparmor_parser -Nprints the name as:ns://name(profile.h:463-470).
Read more
- apparmor.d(5): Profile Head.
- AppArmor wiki: AppArmorNamespaces.
- Profile names: the rest of the head.
for AppArmor developers for security researchers
In the code
- A token that starts with
:is a label for the lexer:LABELincludes{COLON}[^=](parser_lex.l:301-302, parser_lex.l:838-841). parse_label()splits namespace and name (parser_misc.c:914-968); the profile head calls it at parser_yacc.y:407.- With a namespace the
profilekeyword is optional: the check is$2->name[0] != '/' && !($1 || $2->ns)(parser_yacc.y:472-473). - Profiles sort by namespace first, then name (profile.h:434-446).
03 Loading into a namespace with -n
apparmor_parser -n NS file (long form --namespace NS) loads every profile of the
run into NS, creating it under the loader's current namespace. A namespace written in the file is
overridden with a warning. Known discrepancy: the policy cache is still read and written with -n;
-K skips it. The manual page prints the long option as --namespace-string, which the
parser rejects.
You don't have to edit profiles to put them in a namespace. Give the parser -n and a name, and everything in that run goes there. If the namespace doesn't exist, the kernel creates it as a child of the namespace you're in. -N lists the names it would load. If the file names a different namespace, the option wins and you get a warning. One known discrepancy: the source means to skip the policy cache with -n, but doesn't. Cache files are named after the profile file alone, so one file loaded into two namespaces can reuse the wrong cached binary. -K skips the cache.
Details and sources
Details
- Option:
apparmor_parser -n NS FILE, long form--namespace NS(parser_main.c:171; help text-n n, --namespace n Set Namespace for the profile, parser_main.c:242). - The manual page prints the long option as
--namespace-string(apparmor_parser.pod:217-219). The parser's option table has no such entry;unrecognized option '--namespace-string'is what the parser built from the AppArmor tree at 836052d21 answers. -N,--nameslists the names that would be loaded, as:NS://name(parser_main.c:163, profile.h:463-470).- A namespace written in the file loses against the option:
Warning from FILE (FILE line N): apparmor_parser: -n NS overriding policy specified namespace :OLD:. - Kernel side: the namespace named by the policy is found or created as a child of the loader's current namespace (or of the namespace whose
.loadfile was written) (policy.c:1229-1241, policy_ns.c:279-300). A failure is audited withinfo="failed to prepare namespace". - Interface: the write goes to
/sys/kernel/security/apparmor/.loador.replace; one write carries one namespace. - Known discrepancy, cache: the source sets
skip_cachefor-nonly after the cache has been set up, so the cache is still read and written (parser_main.c:1357-1371). The cache file name is built from the directory and the profile file's base name only (policy_cache.c:122-133). The hit was reproduced without a kernel; that the stale binary is then loaded follows from the code and was not run. -K,--skip-cacheskips the cache (parser_main.c:173).
Read more
for AppArmor developers for security researchers
In the code
-nis stored inprofile_ns(parser_main.c:750-752) and overwritesProfile::nsin the profile head action, with theWARN_OVERRIDEwarning (parser_yacc.y:414-429).cache_hit()tests onlymru_skip_cache, notskip_cache(policy_cache.c:209-218).
04 Namespaces are a tree you can see
Each namespace has profiles/, raw_data/, revision,
.load, .replace, .remove and namespaces/ under
policy/namespaces/<name>/. Create with a load or mkdir; remove with
rmdir or by writing :name: to .remove. The depth limit is 32, the same
test as for user namespaces. Removing a namespace does not kill its tasks: reading the kernel code, that part
of their label falls back to the parent's unconfined, and a host profile keeps applying.
Namespaces form a tree, and the kernel shows it to you as directories. Under policy there's a namespaces directory; each namespace in it has its own profiles, its own load and remove files, and a namespaces directory for its children. A namespace appears when the first profile is loaded into it, or when you make the directory yourself. Each has a level, root being zero, and a full name with double slashes that you'll meet in the audit log. Nesting is limited to about thirty-two levels, the same limit as user namespaces. Remove the directory, and the namespace goes, along with its profiles and children. Going by the kernel code, its tasks aren't killed: they keep running.
Details and sources
Details
All of this is read from the kernel source.
- Files of one namespace under
/sys/kernel/security/apparmor/policy/namespaces/NAME/:profiles/,raw_data/,revision(0444),.load,.replace,.remove(0640) andnamespaces/(apparmorfs.c:2229-2280). mkdir policy/namespaces/NAMEcreates a namespace andrmdirremoves it; both first pass the policy management check (apparmorfs.c:2085-2179).- A load creates a missing namespace as a child of the loader's namespace (policy_ns.c:279-300).
- Removal by name: write
:NAME:to.removefor the namespace,:NAME://profilefor one profile. Failures are audited asinfo="namespace does not exist","profile does not exist"or"no profile specified", all withENOENT(policy.c:1488-1556). The regression tests clean up withecho -n ":nnp:" > policy/.remove(nnp.sh:147). - Level and full name: a child's level is the parent's plus one (policy_ns.c:231); the full name joins the components with
//, as inroot//c1(lib.c:486-497). - Depth:
MAX_NS_DEPTHis 32, commented "Match max depth of user namespaces" (policy_ns.h:21-22). Creation fails withENOSPCwhen the parent's level is above 32 (policy_ns.c:226-227); user namespaces use the same test (user_namespace.c:96). - Removing a namespace releases its profiles and child namespaces and redirects its
unconfinedto the parent's (policy_ns.c:308-330). Nothing in that path signals tasks. This is stated from the code, not observed on a running kernel. - The tests detect the interface by the existence of
/sys/kernel/security/apparmor/policy/namespaces(prologue.inc:136-139).
Read more
- AppArmor wiki: AppArmorInterfaces:
.load,.replace,.remove, thepolicy/files, namespaces bymkdirandrmdir. - AppArmor wiki: AppArmorNamespaces.
- The apparmorfs tree.
05 Every namespace has its own unconfined
:c1:unconfined is the namespace's own unconfined profile. A namespace name with no profile
(:c1:, :c1://) resolves to it; ux inside the namespace leads to it; exec
from it attaches only profiles of c1. A stack containing it is unconfined only if every member
is.
Unconfined isn't one global thing. Each namespace has its own profile called unconfined, kept apart from the profiles you load. Name a namespace without a profile, :c1:, and you get that one. A task sitting in c1's unconfined behaves the way an unconfined task always does, with one difference that follows from the kernel code: when it execs, the kernel looks for an attaching profile among c1's profiles only. And when a profile inside c1 says ux, the program lands in c1's unconfined, not the host's. Finally, a label is unconfined only if every part of it is. Host stacked with c1's unconfined is still confined by host.
Details and sources
Details
Kernel behaviour is read from the kernel source.
- Each namespace allocates a profile named
unconfinedfor itself (policy_ns.c:83-96, policy_ns.c:122-126). It is not in the namespace's profile list; a lookup of the nameunconfinedreturns it as a special case (policy.c:655-657). - A name with a namespace and no profile resolves to that namespace's
unconfined(policy.c:679-683). The regression tests pass with all of:ns:,:ns://and:ns(stackonexec.sh:178-180). aa-exec -n NS -- cmdasks for:NS://: the name is built as:, namespace,://, and the profile only if-pwas given (aa_exec.c:162-186).- Exec from an unconfined profile searches the attachments of that profile's own namespace only (domain.c:697-699).
uxinside a namespace leads to theunconfinedof the same namespace (domain.c:630-631).- A label of several profiles has the unconfined flag only if every member has it (label.c:206-219), so
host//&:c1:unconfinedis confined byhost. - When the label is printed, no mode is shown for a namespace's
unconfined, and a stack that contains it does not reportmixedbecause of it (label.c:1563, label.c:1589-1594).
Read more
- aa-exec(1):
-nand the namespace example at the end of the page. - AppArmor wiki: Unconfined, the unconfined flag and default allow.
- Stacking: an unconfined member, attachment.
06 Moving a task into a namespace
Targets may carry a namespace: /usr/bin/foo px -> :c1:foo,,
change_profile -> :c1:foo,, aa_change_profile(":c1:foo"),
aa-exec -n c1 -p foo. Names resolve from the task's current namespace downward; a namespace that
is not visible gives ENOENT.
Loading a profile into c1 confines nobody. A task has to move there, and it moves by name. An exec rule can name the target after an arrow: px -> :c1:foo. A program can call aa_change_profile with the same string, if its profile has a matching change_profile rule. An administrator can use aa-exec with -n and -p. All three are lookups by name, relative to where the task is now: you can reach your own namespace and the ones below it. There's no spelling for the parent or for a sibling, and asking for something out of view fails as if it didn't exist. One tip: in a change_profile rule, write the single-colon form.
Details and sources
Details
- Exec rule:
/usr/bin/foo px -> :c1:foo,(also:c1://foo). Rule for the call:change_profile -> :c1:foo,; the parser's test isaudit change_profile -> :foo:/bin/foo,(a_ok_3.sd). - Call:
int aa_change_profile(const char *profile)writeschangeprofile :c1:footo the task'scurrentattribute (/proc/self/attr/apparmor/current, or thelsm_set_self_attrsystem call) (kernel.c:1067-1086).aa_change_onexec()writesexec NAMEto theexecattribute (kernel.c:1088-1099). - Its manual page:
ENOENT, "The specified profile does not exist, or is not visible from the current Namespace." (aa_change_profile.pod:93-96). - Tool:
aa-exec -n c1 -p foo -- cmdasks for:c1://fooat the next exec, and with-iimmediately (aa_exec.c:57, aa_exec.c:205-213). Errors:profile ':c1://foo' does not exist,insufficient permissions to change to the profile ':c1://foo'(aa_exec.c:215-222). - Lookup, the kernel: the name is split into namespace and profile; the namespace is looked up below the current namespace of the label that asks,
//descending one level per component (policy.c:671-685, policy_ns.c:174-214). There is no spelling for a parent or a sibling. A target that is not found is audited withinfo="label not found"(domain.c:1530-1539). - An unconfined caller needs no
change_profilerule (domain.c:295-299). - Known discrepancy: the kernel matches a change_profile request as
:, namespace,:, name (domain.c:106-111), and a rule writtenchange_profile -> :ns://name,compiles to a different pattern. Reading the code it does not grant the change; this was not run on a kernel. Write:ns:name. - The regression test for a namespaced target uses
nstest=":ns:changeprofile"andchange_profile -> ${nstest},(changeprofile.sh:33, changeprofile.sh:84-119).
Read more
for AppArmor developers for security researchers
In the code
- The target after
->isopt_named_transition(parser_yacc.y:1043-1047); the change_profile rule is at parser_yacc.y:808. - A target with a namespace is never treated as a child profile (block_rules.cc:474-479); the change_profile pattern is built from namespace and name at parser_regex.c:742-759.
- The kernel resolves exec targets from the transition table with
x_table_lookup()(domain.c:523-559).
07 One label, three readers
Labels are printed relative to the reader's namespace. A member in a visible child namespace prints as
:ns:name; members the reader cannot see are left out; if the task's namespace is not visible at
all the read fails with EACCES. Audit records use namespace="root//c1", the full
name.
Take one container task whose label has two parts: host, in the root namespace, and foo, in c1. Ask three readers what it's running under. By the kernel's rules, a shell on the host reads host//&:c1:foo. A shell inside the container reads plain foo: its own namespace needs no prefix, and host lives above it, so host is left out. A shell in a neighbouring namespace is refused. Visibility goes down the tree only. Two more forms to recognise. The audit log names the namespace in full, root//c1. And the kernel always prints the single-colon form; the form with two slashes is something you may type, not something you'll read back.
Details and sources
Details
Read from the kernel source; the three views on the slide are derived from these rules and were not observed on a running kernel.
- Where a label is read:
/proc/PID/attr/currentand/proc/PID/attr/apparmor/current,aa_getcon()andaa_gettaskcon()in libapparmor,ps -Z, andSO_PEERSECfor a socket peer. - If the task's namespace is not visible from the reader's, the read fails with
EACCES(procattr.c:37-40). "Visible" means the same namespace or one below it (policy_ns.c:40-52). - Spelling of a member: nothing in front for the reader's own namespace,
:ns:namefor a namespace below, with the part of the hierarchical name below the reader (policy_ns.c:64-81, label.c:1563-1576). The kernel prints the single-colon form only. - Members in namespaces the reader cannot see are left out of the printed label (label.c:1649-1699).
- The namespace prefix is printed once for consecutive members of one namespace:
:c1:A//&Bhas both inc1(label.c:1550-1561). - Audit records: a subject that is a single profile outside the root namespace gets
namespace="root//c1"andprofile="foo"; a subject of several profiles is printed aslabel=, viewed from the root (audit.c:117-135). - The aa-exec manual page shows both views:
ps -Zinside printsunconfinedfor the shell and-for a process it cannot see, and from the parentunconfined//&:ex1:unconfined(aa-exec.pod:167-182). - The inside view is asserted by a regression test: a task stacked with
:ns:stackprofilereads its own label asstackprofile, modeenforce(stackprofile.sh:117-139).
Read more
- AppArmor wiki: AppArmorPolicyView: which namespaces a task can see.
- aa_getcon(2) and aa-exec(1).
- Reading denials, labels in the kernel.
08 A container: its own namespace, under a host profile
Create the namespace, stack :c1:unconfined on the host profile, exec. The label becomes
host//&:c1:...: the host member keeps restricting, the c1 member decides
attachment inside. From inside, policy/ is c1's directory and
.ns_name, .ns_level, .ns_stacked read c1, 1,
yes. The sequence is read from the kernel code and the tree's tests, not from a container
manager's source.
Put the pieces together the way a container manager can. First it creates a namespace for the container. Then, before starting the container's first program, it adds the namespace's unconfined profile to its own label instead of replacing it, so the host profile stays. From then on the task's current namespace is c1: a program exec'd inside attaches from c1's profiles, the policy directory it sees is c1's, and the parser run inside loads into c1. In logs you'll meet lines like this one, with a namespace named after an LXD container. And through all of it, every access is still checked against host.
Details and sources
Details
The sequence is read from the kernel source and the tests in the AppArmor tree, not from a container manager's source.
- Create the namespace: a load into it (policy.c:1229-1241) or
mkdir /sys/kernel/security/apparmor/policy/namespaces/c1. - Stack instead of replace:
int aa_stack_profile(const char *profile)writesstack :c1:unconfinedto thecurrentattribute,int aa_stack_onexec(const char *profile)writes the same command to theexecattribute (kernel.c:1204-1236). The kernel merges the target into the current label (domain.c:1625). - The profile needs
change_profile -> &:c1:unconfined,. The regression test does exactly this with a namespacennp:change_profile-> &:nnp:unconfined,(nnp.sh:101-123). - After that the task's current namespace is the namespace of the last profile of its label, here
c1(label.h:53, label.h:162). - Exec inside: each member of the label makes its own transition and the results are joined (domain.c:1032-1035); the
c1member, being unconfined, searchesc1's attachments (domain.c:697-699). /sys/kernel/security/apparmor/policyis a link that resolves to the directory of the reader's current namespace (apparmorfs.c:2863-2881)..ns_name,.ns_level,.ns_stackedand.stackedin/sys/kernel/security/apparmor/report on the reading task (apparmorfs.c:1417-1474).- The log line is from the libapparmor test suite (change_onexec_lp1648143.in):
apparmor="DENIED" operation="change_onexec" info="no new privs" error=-1 namespace="root//lxd-tor_<var-lib-lxd>" profile="unconfined" name="system_tor" pid=18593 comm="(tor)" target="system_tor".
Read more
- AppArmor wiki: how to set up a policy namespace for containers (marked WIP by its authors).
- AppArmor wiki: CombiningStackingAndNamespaces (marked Draft WIP).
- aa_stack_profile(2).
- Stacking: the label with two members, and what
no_new_privsallows.
09 Who may load policy into a namespace
Policy management needs: policy not locked; uid 0 in the task's user namespace; the target namespace
visible; in a non-initial user namespace, kernel.unprivileged_userns_apparmor_policy non-zero and
equal user and policy namespace levels; and CAP_MAC_ADMIN allowed by every profile of the label.
Failures are audited with info="policy_locked", "not privileged for target profile"
or "not policy admin".
Can the container's root really load profiles? Sometimes. Every policy change goes through one gate. If policy has been locked, nobody passes. Otherwise the task must be root in its user namespace, and the namespace it targets must be its own or below. Inside a user namespace two more things must hold: the sysctl that allows unprivileged user namespaces to manage policy must be on, and the user namespace must sit at the same depth as the policy namespace. Last, it needs the capability mac_admin, and that's checked against every profile in its label. So if the host profile on the container doesn't allow mac_admin, loading fails with not policy admin, even for root.
Details and sources
Details
Read from the kernel source. Every load, replace, remove, mkdir and rmdir goes through aa_may_manage_policy() (policy.c:1001-1029).
- Locked policy:
info="policy_locked",EACCES. The switch is the module parameterlock_policy(/sys/module/apparmor/parameters/lock_policy) (lsm.c:1989-1990). - If the file was opened by another credential, the writer must not have more privilege than the opener:
info="not privileged for target profile"(policy.c:965-988). - The remaining tests share
info="not policy admin",EACCES: - uid 0 or group 0 in the task's user namespace, and the target namespace is the task's current one or below it (policy.c:907-925); - in a non-initial user namespace:kernel.unprivileged_userns_apparmor_policyis not 0 and the user namespace level equals the policy namespace level (policy.c:918-921); -CAP_MAC_ADMINin the user namespace and allowed by every confining profile of the label (policy.c:882-894, capability.c:188). In a profile that iscapability mac_admin,. - The sysctl
kernel.unprivileged_userns_apparmor_policydefaults to 1 (policy.c:91), has mode 0600, exists only withCONFIG_USER_NSand can be written only by a policy admin (lsm.c:2440-2459). - The check is called from the write handlers of
.load,.replaceand.removeand frommkdirandrmdir(apparmorfs.c:625, apparmorfs.c:736, apparmorfs.c:2095, apparmorfs.c:2146). - The parser's manual page: privileged commands "require the MAC_ADMIN capability within the affected AppArmor namespace" (apparmor_parser.pod:72-76).
- How user namespace levels line up with policy namespace levels in real container deployments was not determined from the trees.
10 How the namespace travels in the binary policy for AppArmor developers
parse_label() (parser/parser_misc.c:914) fills Profile::ns;
sd_serialize_top_profile() writes the namespace header string;
verify_header() and aa_prepare_ns() consume it. Exec targets are stored as
:ns\0name and restored by process_strs_entry(). The bytes shown are the output of
apparmor_parser 6.0.0~alpha2 (836052d21) for this rule.
Two things carry a namespace from profile text to the kernel. The first is the profile's own name. parse_label splits a leading colon, name, colon off the label; -n then overwrites it for every profile in the run. Serialisation writes it as a string called namespace between the version and the profile struct, and after the kernel's header check it reaches aa_prepare_ns, which finds or creates a child of the loader's namespace. One write carries one namespace. The second is an exec target. In the transition table the second colon becomes a NUL, so namespace and name are separate strings, and the kernel's unpacker puts the colon back before the label is parsed at exec time.
Details and sources
for AppArmor developers for security researchers
Details
- Lexer: a token that starts with
:(not:=) is a label (parser_lex.l:301-302, parser_lex.l:838-841). bool parse_label(bool *_stack, char **_ns, char **_name, const char *label, bool yyerr)splits:ns:nameand:ns://name(parser_misc.c:914-968; the split itself at parser_misc.c:862-880). The profile head calls it at parser_yacc.y:407.-nreplacesProfile::nsfor every profile of the run (parser_yacc.y:414-430).sd_serialize_top_profile()writesversion, then the stringnamespaceif the profile has one, then the profile struct (parser_interface.c:666-681).- Exec targets:
sd_serialize_xtable()overwrites the second colon of a target that starts with:with NUL, giving:ns\0name(parser_interface.c:413-456). Targets enter the table throughadd_entry_to_x_table()(block_rules.cc:458-472). - Kernel:
verify_header()reads thenamespacestring; an empty one isinvalid namespace name, a second different one in the same write isinvalid ns change(policy_unpack.c:1442-1485). aa_replace_profiles()passes the name toaa_prepare_ns(), which finds or creates a child of the loader's namespace (policy.c:1210-1241, policy_ns.c:279-300).process_strs_entry()puts the colon back in an exec target: an inner NUL of a string that starts with:becomes:(policy_unpack.c:488-514).- The bytes on the slide are the output of apparmor_parser 6.0.0~alpha2 (836052d21) for that rule.
Read more
11 aa_ns, the label's namespace and the view for AppArmor developers
labels_ns() (include/label.h:162) is the namespace of the last profile in the sorted vector.
aa_ns_visible() and aa_ns_name() (policy_ns.c:40-81) define view and spelling: with
subns false only the label's own namespace matches ("scope"), with it true its descendants do too
("view"). aa_label_snxprint() (label.c:1649) applies them per member;
aa_getprocattr() (procattr.c:31) returns -EACCES for an invisible label.
In the kernel a namespace is a struct aa_ns: a policy base with name and profile list, a parent pointer, a level, its own unconfined profile and a list of children. Nothing in a task points at a namespace directly. The task has a label, the label is a vector of profiles sorted by namespace level first, and labels_ns takes the namespace of the last one: the deepest. That's the current namespace, the view. aa_ns_visible answers whether one namespace can see another by walking parent pointers, and aa_ns_name returns the spelling: empty for the reader's own, the tail of the hierarchical name for a descendant, three dashes for anything hidden. The label printer applies both to each member.
Details and sources
for AppArmor developers for security researchers
Details
All from the kernel source.
struct aa_ns:base(name, hierarchical name, profile list),parent,level,unconfined,sub_ns,labels,dents[](policy_ns.h:60-77).MAX_NS_DEPTHis 32 (policy_ns.h:21-22).labels_ns(X)is the namespace of the last profile of the label's vector;labels_view(X)is the same macro (label.h:53, label.h:162-164). The vector is kept sorted by namespace level first (label.c:109-155).bool aa_ns_visible(struct aa_ns *curr, struct aa_ns *view, bool subns): true for the same namespace, and withsubnsfor any descendant, found by walkingparent(policy_ns.c:40-52).const char *aa_ns_name(struct aa_ns *curr, struct aa_ns *view, bool subns): empty for the reader's own namespace, the tail of the hierarchical name for a descendant,aa_hidden_ns_name(---) otherwise (policy_ns.c:30, policy_ns.c:64-81).- Creation and removal:
alloc_ns(),__aa_create_ns(),aa_prepare_ns(),destroy_ns(),__aa_remove_ns()(policy_ns.c:105-139, policy_ns.c:216-248, policy_ns.c:279-345); the root namespace is set up at policy_ns.c:367-386. aa_lookupn_ns()walks//-separated components down from a view (policy_ns.c:174-214).- Printing:
aa_label_snxprint()applies visibility and spelling per member (label.c:1649-1699, label.c:1550-1576);aa_getprocattr()returns-EACCESfor a label whose namespace is not visible and prints withFLAG_SHOW_MODE | FLAG_VIEW_SUBNS | FLAG_HIDDEN_UNCONFINED(procattr.c:31-69). - "Scope" and "view" are the words of the code:
@inview: whether to match labels in view or only in scope(domain.c:120). - The hierarchical name is built as
prefix//name(lib.c:486-497).
Read more
- AppArmor wiki: apparmor_kernel_development_guide: profiles, labels, proxies and namespaces.
- AppArmor wiki: AppArmorPolicyView and AppArmorPolicyScope.
- Labels in the kernel.
12 Where to go from here
Next: attachment for the search inside a namespace, stacking for labels like
host//&:c1:foo, adm-parser and adm-cache for the tools,
k-labels and re-blob for the internals.
That's a policy namespace: a named set of profiles with its own unconfined, written with colons, arranged in a tree where you can see downward and not up. Two neighbours finish the picture. Attachment explains the search that runs inside each namespace. Stacking explains the label with two parts that every container task in this deck carried, and why the host part can't be shaken off from inside. For the tools, the parser and cache topics cover the options around -n. For the code, follow labels into the kernel or the namespace string into the binary policy.
Details and sources
Details
- A policy namespace: a named set of profiles with its own
unconfined, written:ns:name, in a tree where a task sees its own namespace and the ones below it. - Interfaces met in this deck:
apparmor_parser -n NS,aa-exec -n NS -p NAME,aa_change_profile(),aa_stack_profile(),/sys/kernel/security/apparmor/policy/namespaces/,.ns_name,.ns_level,.ns_stacked, the sysctlkernel.unprivileged_userns_apparmor_policy. - Two known discrepancies to remember: the policy cache is not skipped with
-n(use-K), and the manual page's--namespace-stringis not accepted (use--namespace). - Commits read for this deck: AppArmor 836052d21 (6.0.0~alpha2), the kernel-rc2 (97d73c825). Kernel behaviour is stated from the source and was not observed on a running kernel.
Read more
Kernel behaviour here is read from the code of mainline Linux 7.4; parser output was checked with apparmor_parser. Items marked "known discrepancy" are what the code does today, not the intended design.
Names
A profile name that starts with : carries its policy namespace.
| Form | Meaning |
|---|---|
:ns:name { } | profile name in namespace ns; the profile keyword is optional |
profile :ns:name { } | the same |
:ns:name /attach { } | the same with an attachment |
:ns://name { } | the same; // after the second colon is accepted on input only |
:ns:/usr/bin/foo { } | a path-named profile in ns |
foo:/x { }has no leading colon and is not a namespace. The parser rejects it withProfile attachment must begin with a '/' or variable.@{profile_name}inside:ns:nameexpands toname, without the namespace.- The same name in two namespaces does not clash. A duplicate inside one namespace gives
Multiple definitions for profile ... exist,bailing out. apparmor_parser -Nprints the fully qualified name as:ns://name, andapparmor_parser -Rwrites that form to.remove.- The parser does not check the characters of the namespace. The kernel documents that namespace names cannot contain
:,/or NUL.
Targets
| Rule or call | Effect |
|---|---|
/bin/x px -> :ns:name, | exec moves to name in ns |
/bin/x px -> :ns://name, | the same |
/bin/x px -> :ns:, | exec moves to the unconfined profile of ns |
/bin/x px -> &:ns:name, | exec moves to the profile attached to /bin/x and adds :ns:name; with ix and nothing attached the current profile is kept (see stacking) |
change_profile -> :ns:name, | allows aa_change_profile(":ns:name") |
change_profile /exec -> :ns:name, | the same, only when the change happens at exec of /exec |
change_profile -> :*:name, | globs are allowed in either part |
change_profile -> &:ns:name, | allows stacking :ns:name; accepted when both the kernel and the profile's ABI have domain/stack |
aa-exec -n ns -p name -- cmd | asks for :ns://name at exec; with -i, immediately |
aa-exec -n ns -- cmd | asks for :ns://, the unconfined profile of ns |
- A profile file with no
abirule gets the parser's default ABI, which lacksdomain/stack:change_profile -> &:ns:name,then fails withThe current kernel does not support stacking of named transitions: &:ns:name. Putabi <abi/3.0>,or newer in the file. l /x -> :ns:foo,is rejected:link perms are not allowed on a named profile transition./bin/x cx -> :ns:b,is accepted by the parser, but a child transition is looked up among the children of the profile, so it cannot name another namespace.- aa-exec changes profile; it does not stack. A confined caller needs a matching
change_profilerule, an unconfined caller does not. Its errors are... profile ':ns://name' does not exist,... insufficient permissions to change to the profile ':ns://name'andMultiple -n/--namespace parameters given. aa_change_profile()fails withENOENTwhen "the specified profile does not exist, or is not visible from the current Namespace".
apparmor_parser
| Option | Effect |
|---|---|
-n NS, --namespace NS | load every profile, child profile and hat of the run into NS; the value is used as given |
-N, --names | list the names that would be loaded, as :NS://name |
-R | remove; for a namespaced profile it removes only that profile |
-K, --skip-cache | do not read the policy cache |
-nnames a child of the namespace the parser runs in. Run inside a container it creates the namespace below the container's namespace.- A namespace written in the file is replaced by the option, with
Warning from FILE (FILE line N): apparmor_parser: -n NS overriding policy specified namespace :OLD:. - The privileged commands "require the MAC_ADMIN capability within the affected AppArmor namespace"; see Managing policy below.
- See also adm-parser and adm-cache.
apparmorfs
Everything is under /sys/kernel/security/apparmor/.
policy/ the reader's own namespace (a per-reader link)
profiles/
raw_data/
revision
.load .replace .remove
namespaces/
c1/
profiles/
raw_data/
revision
.load .replace .remove
namespaces/
inner/
mkdir policy/namespaces/NAMEcreates a namespace andrmdirremoves it. Both are real operations that pass the policy management checks. An existing name givesEEXIST.policyleads each reader to the directory of its own current namespace, so inside a containerpolicy/profiles/lists the container's profiles.- The top-level
.load,.replaceand.removeact on the writer's current namespace. The copies inside a namespace directory act on that namespace. - Writing
:NAME:to.removeremoves the namespaceNAMEwith its profiles and child namespaces; writing:NAME://profileremoves one profile. - Removing a namespace does not kill its tasks. Reading the code, the namespace's
unconfinedis redirected to the parent'sunconfined, and the members of a label that live in surviving namespaces keep applying. The root namespace cannot be removed.
| File | What it reports about the reading task |
|---|---|
.stacked | yes when its label has more than one profile |
.ns_stacked | yes when the label has more than one profile and one is outside the label's namespace |
.ns_level | the level of its current namespace; the root is 0 |
.ns_name | the last component of its current namespace's name; root in the root namespace |
profileslists the profiles of the reader's namespace and of every namespace below it; a profile of a child prints as:c1:name (mode).features/domain/stacktells the parser that the kernel supports stacking.features/namespaces/belongs to theusernsrule, not to policy namespaces.
What each reader sees
Derived from the kernel's printing rules for a container whose namespace is c1; the inside view of a namespaced profile is also asserted by the regression test stackprofile.sh.
| Task label | Reader in root | Reader in c1 | Reader in sibling c2 |
|---|---|---|---|
host and foo in c1 | host//&:c1:foo (enforce) | foo (enforce) | EACCES |
host and unconfined in c1 | host//&:c1:unconfined (enforce) | unconfined | EACCES |
host only | host (enforce) | EACCES | EACCES |
host and p in inner below c1 | host//&:c1//inner:p (enforce) | :inner:p (enforce) | EACCES |
- The kernel prints
:ns:name, never:ns://name. - The namespace prefix is printed once for consecutive members of the same namespace:
:c1:A//&Bmeans bothAandBare inc1. - No mode is printed for a namespace's
unconfined, and a stack that contains it does not reportmixedbecause of it. ps -Zinside a namespace shows-for processes it cannot see.- Audit records: when the subject is a single profile outside the root namespace, the record has
namespace="root//c1"(the full name from the root) andprofile="foo". A subject with several profiles is printed aslabel=, viewed from the root. SO_PEERSECprints the peer's label from the caller's namespace, by the same rules as/proc/PID/attr/current.
Lookup rules
- A name is resolved relative to the current namespace of the label that asks. The namespace part is looked up among the namespaces below it;
//in the namespace part descends further (:c1//inner:name). - There is no spelling for the parent, for a sibling or for an absolute path from the root. An unknown or invisible name gives
ENOENT. :ns:,:ns://and:ns(no closing colon) name theunconfinedprofile ofns.- In a stacked name each
//&member is looked up in turn, and a member that names a namespace makes it the base for the members after it::ns:A//&Bfinds bothAandBinns. - Exec from a namespace's
unconfined, andpxwithout a target, search only the profiles of that profile's namespace.uxleads to theunconfinedof the same namespace.
Managing policy
Every load, replace, remove, mkdir and rmdir passes the same checks. The first two run in this order; the other four are one test with one failure text:
| Check | Failure |
|---|---|
policy is not locked (lock_policy, a one-way switch) | EACCES, info="policy_locked" |
| if the file was opened by another credential, the writer has no more privilege than the opener | info="not privileged for target profile" |
| uid 0 (or group 0) in the task's user namespace | info="not policy admin" |
| the target namespace is the task's current namespace or below it | info="not policy admin" |
in a non-initial user namespace: kernel.unprivileged_userns_apparmor_policy is not 0, and the user namespace level equals the policy namespace level | info="not policy admin" |
CAP_MAC_ADMIN in the task's user namespace, allowed by every profile of its label (capability mac_admin,) | info="not policy admin" |
kernel.unprivileged_userns_apparmor_policydefaults to 1, has mode 0600 and can be written only by a policy admin.- The audit record for a policy change carries
ns=when a namespace name is known. - There is no rule that limits which namespaces a profile may manage beyond these checks.
- How user namespace levels line up with policy namespace levels in real container deployments was not determined from the trees.
Limits
- Nesting depth:
MAX_NS_DEPTHis 32, commented "Match max depth of user namespaces"; creation beyond it fails withENOSPC. A namespace at level 32 can still create a child, as with user namespaces (kernel/user_namespace.c uses the same test). - No per-namespace quota is enforced: the size and count limits in the kernel's namespace accounting structure are not read anywhere.
- One write to
.loador.replacecarries one namespace: a second, different namespace in the same write fails withinvalid ns changeorpolicy load has mixed namespaces. - A load creates only a direct child of the loader's namespace, never a grandchild in one step.
Parser errors and warnings
| Message | When |
|---|---|
Namespace not terminated: %s | no second colon: :c1/foo { } |
Empty namespace: %s | ::/x { } |
Empty named transition profile name: %s | a namespace with no profile name in a profile head: :c1: { } |
Profile names must begin with a '/' or a namespace | a profile name that starts with & |
Multiple definitions for profile %s exist,bailing out. | the same name twice in one namespace |
-n %s overriding policy specified namespace :%s: | warning: -n and the file name different namespaces |
unrecognized option '--namespace-string' | the option name printed in the manual page |
The current kernel does not support stacking of named transitions: %s | a change_profile rule with an & target when the kernel or the profile's ABI lacks domain/stack; a profile file with no abi rule is in that case |
Kernel messages
These appear as info= in audit records.
| Message | When |
|---|---|
invalid namespace name | the binary policy carries an empty namespace string |
invalid ns change | a second, different namespace inside one write |
policy load has mixed namespaces | the same, found while replacing profiles |
failed to prepare namespace | the namespace could not be found or created |
namespace does not exist | .remove names an unknown namespace |
profile does not exist | .remove names an unknown profile |
no profile specified | .remove was given an empty name |
label not found | a change_profile target that does not exist or is not visible |
policy_locked | policy has been locked |
not privileged for target profile | the writer has more privilege than the opener of the file |
not policy admin | one of the policy management checks failed |
Known discrepancies
- **The cache is not skipped with
-n.** The parser's source means to disable the policy cache when-nis given, but the cache is still read and written. Cache files are named after the profile file only, so the same file loaded with two different-nvalues, or with and without-n, can reuse a binary compiled for another namespace. The cache hit was reproduced without a kernel; that the stale binary is then loaded follows from the code and was not run. Use-K. - **
change_profile -> :ns://name,** compiles to a different pattern thanchange_profile -> :ns:name,, and the kernel matches a change_profile request as:, namespace,:, name. Reading the code, a rule in the://form does not grant the change (not run on a kernel). Write:ns:name. Exec rule targets accept both spellings. - **
--namespace-string** is the long option in the manual page; the parser only knows--namespace. - Error wording.
Empty named transition profile nameis printed for a profile head with a namespace and no name, which is not a transition.
for AppArmor developers
Code map
Parser:
| Symbol | Where | Role |
|---|---|---|
parse_label() | parser/parser_misc.c:914 | splits :ns:name and :ns://name; source of the three label errors |
label_contains_ns() | parser/parser_misc.c:903 | tells add_named_transition() that a target is not a child profile |
profile_base action | parser/parser_yacc.y:407-430 | fills Profile::ns; applies -n (profile_ns) with the WARN_OVERRIDE warning |
Profile::fqname() | parser/profile.h:463 | builds :ns://hname for -N and -R |
sd_serialize_top_profile() | parser/parser_interface.c:666 | writes version, then the namespace string, then the profile struct |
sd_serialize_xtable() | parser/parser_interface.c:413 | stores a namespaced exec target as :ns\0name |
process_profile() | parser/parser_main.c:1337-1371 | sets skip_cache for -n after the cache has been set up |
Kernel (linux:security/apparmor/):
| Symbol | Where | Role |
|---|---|---|
struct aa_ns | include/policy_ns.h:60 | base, parent, level, unconfined, sub_ns, labels, dents[] |
alloc_ns(), __aa_create_ns() | policy_ns.c:105, 216 | allocation, level, apparmorfs directory, depth test |
aa_prepare_ns(), __aa_find_or_create_ns() | policy_ns.c:279, 250 | find or create on load; create on mkdir |
destroy_ns(), __aa_remove_ns() | policy_ns.c:308, 338 | release profiles and children, redirect unconfined to the parent |
aa_ns_visible(), aa_ns_name() | policy_ns.c:40-81 | view and spelling; aa_hidden_ns_name is --- |
aa_lookupn_ns() | policy_ns.c:174 | walks //-separated components down from a view |
labels_ns() | include/label.h:162 | namespace of the last profile of the sorted vector |
aa_splitn_fqname() | lib.c:183 | splits a text name into namespace and profile |
aa_fqlookupn_profile() | policy.c:663 | relative lookup; no profile name returns unconfined |
aa_label_strn_parse() | label.c:1892 | parses single and stacked names |
aa_label_snxprint() | label.c:1649 | prints a label for a reader's namespace |
aa_getprocattr() | procattr.c:31 | /proc/PID/attr/*; -EACCES when the label's namespace is not visible |
verify_header(), process_strs_entry() | policy_unpack.c:1442, 488 | read the namespace string; restore the colon in exec targets |
aa_replace_profiles(), aa_remove_profiles() | policy.c:1210, 1488 | load and remove with a namespace |
aa_may_manage_policy(), aa_policy_view_capable(), aa_policy_admin_capable() | policy.c:1001, 907, 927 | the policy management checks |
ns_mkdir_op(), ns_rmdir_op(), policy_get_link() | apparmorfs.c:2085, 2137, 2863 | mkdir, rmdir and the policy link |
"Scope" and "view" are the code's words (domain.c:120): with subns false only the label's own namespace matches, with subns true its descendants do too. aa_get_ns() and aa_put_ns() count references on ns->unconfined (FLAG_NS_COUNT). struct aa_ns_acct has max_size and max_count, which no code reads. A stacked exec target &:ns:name starts with & and is stored in the transition table unchanged.
Two more known discrepancies in serialisation, neither run on a kernel:
- Children and hats of a profile that names its namespace in the text (no
-n) are serialised without thenamespacefield, because nothing copies the parent'snsto the child. Seen in-Soutput forprofile :ns:a { profile b { } }. - A namespace prefix on a child profile or hat is accepted.
-Nlists the child under the parent's namespace, while the child's header carries the child's own prefix.
Roads from here
ATTACHMENT, NAMESPACES, STACKING
- Profile attachment — how the kernel picks a profile inside one namespace
- Profile stacking — keeping a host profile on a task that enters a namespace
RUNNING THE PARSER
- Running apparmor_parser (no slides yet) — the other apparmor_parser options
- The policy cache (no slides yet) — the policy cache that -n interacts with
IN THE KERNEL
- Labels in the kernel — labels and namespaces as kernel objects
THE DFA ENGINE · libapparmor_re
- The binary policy format — the binary policy that carries the namespace name