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

Part of journeys

01 The same profile name, twice

POLICY NAMESPACES host policy foo host unconfined container c1 profile foo /usr/bin/foo { } load two profiles named foo? :c1: foo unconfined foo :c1:foo different profiles, same name a policy namespace is not a user, mount or PID namespace
The host policy holds a profile foo; a container cannot load a second foo into it, so it gets its own policy namespace c1 with its own foo and its own unconfined.

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:foo is profile foo in policy namespace c1; a bare foo is 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 unconfined profile 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 the userns rule are about user namespaces; see the userns rule.
  • The names c1, foo and host are invented for the map.

Read more

02 Writing a namespace in a profile name

:NS:NAME profile : NS : // NAME ATTACHMENT { } the namespace optional, input only profile foo /usr/bin/foo { } profile :c1:foo /usr/bin/foo { } profile :c2:foo /usr/bin/foo { } one file, three profiles, no clash :c1://foo /usr/bin/foo { } same as :c1:foo; the profile keyword is optional you write the parser says :c1/foo { } ... Namespace not terminated: :c1/foo ::/x { } ... Empty namespace: ::/x :c1: { } ... Empty named transition profile name: :c1: known discrepancy in the wording @{profile_name} inside :c1:foo is foo, without the namespace
Syntax diagram of a profile head with a namespace, three profiles named foo in one file, the two-slash spelling, and the three parser errors.

: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: %s for profile :ns/t { } (profile_ns_bad8.sd); - Empty namespace: %s for ::/does/not/exist { } (profile_ns_bad4.sd); - Empty named transition profile name: %s for :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:/hname is /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 -N prints the name as :ns://name (profile.h:463-470).

for AppArmor developers for security researchers

In the code

03 Loading into a namespace with -n

apparmor_parser -n # foo.profile profile foo /usr/bin/foo { } $ apparmor_parser -r -n c1 foo.profile :c1: created by the load foo unconfined $ apparmor_parser -N -n c1 foo.profile :c1://foo -N lists the names it would load $ apparmor_parser -r -n c1 foo.profile Warning from foo.profile (foo.profile line 1): apparmor_parser: -n c1 overriding policy specified namespace :old: # the file now says: profile :old:foo the profile still lands in :c1: known discrepancy the cache is still used with -n cache files are named after the profile file only use -K when one file goes into two namespaces
apparmor_parser -n c1 loads a profile written without a namespace into c1, creating the namespace; -N lists names; a namespace in the file is overridden with a warning; the policy cache is still used 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, --names lists 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 .load file was written) (policy.c:1229-1241, policy_ns.c:279-300). A failure is audited with info="failed to prepare namespace".
  • Interface: the write goes to /sys/kernel/security/apparmor/.load or .replace; one write carries one namespace.
  • Known discrepancy, cache: the source sets skip_cache for -n only 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-cache skips the cache (parser_main.c:173).

for AppArmor developers for security researchers

In the code

04 Namespaces are a tree you can see

/sys/kernel/security/apparmor/policy policy/ profiles/ namespaces/ root level 0 c1/ profiles/ raw_data/ revision .load .replace .remove namespaces/ created by the first load with -n c1 c1 level 1 # mkdir policy/namespaces/c1/namespaces/inner inner/ inner level 2 root//c1 root//c1//inner full names, as the audit log prints them depth limit: 32, as for user namespaces # rmdir policy/namespaces/c1 # echo -n ":c1:" > .../apparmor/.remove profiles and child namespaces go with it task in c1 host keeps applying still running: its c1 part falls back to the parent's unconfined
The policy directory tree with namespaces c1 and inner beside the same tree as nested namespaces with levels 0, 1 and 2; removing c1 removes its profiles and children but its tasks keep running.

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) and namespaces/ (apparmorfs.c:2229-2280).
  • mkdir policy/namespaces/NAME creates a namespace and rmdir removes 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 .remove for the namespace, :NAME://profile for one profile. Failures are audited as info="namespace does not exist", "profile does not exist" or "no profile specified", all with ENOENT (policy.c:1488-1556). The regression tests clean up with echo -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 in root//c1 (lib.c:486-497).
  • Depth: MAX_NS_DEPTH is 32, commented "Match max depth of user namespaces" (policy_ns.h:21-22). Creation fails with ENOSPC when 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 unconfined to 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

05 Every namespace has its own unconfined

:c1:unconfined root unconfined not in the profile list foo /usr/bin/foo :c1: unconfined not in the profile list foo /usr/bin/foo two different profiles $ aa-exec -n c1 -- bash asks for :c1:// bash a namespace with no profile name means its unconfined exec foo by the kernel's rules: attaches from c1's profiles, not the host's /bin/sh ux, not here host//&:c1:unconfined a confined label: host still applies
The root namespace and c1 each have their own unconfined profile outside the profile list; a task in c1 unconfined attaches profiles of c1 only, and ux inside c1 leads back to c1 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 unconfined for itself (policy_ns.c:83-96, policy_ns.c:122-126). It is not in the namespace's profile list; a lookup of the name unconfined returns 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 -- cmd asks for :NS://: the name is built as :, namespace, ://, and the profile only if -p was 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).
  • ux inside a namespace leads to the unconfined of 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:unconfined is confined by host.
  • When the label is printed, no mode is shown for a namespace's unconfined, and a stack that contains it does not report mixed because of it (label.c:1563, label.c:1589-1594).

06 Moving a task into a namespace

GETTING IN root launcher :c1: foo /usr/bin/foo px -> :c1:foo, 1 exec rule change_profile -> :c1:foo, aa_change_profile(":c1:foo") writes changeprofile :c1:foo 2 change_profile $ aa-exec -n c1 -p foo -- /usr/bin/foo asks for :c1://foo at exec 3 aa-exec unconfined callers need no rule no way to name a parent or a sibling ENOENT: does not exist, or is not visible from the current namespace in change_profile rules write :c1:foo
A launcher task in the root namespace reaches profile foo in c1 three ways: an exec rule with a target, a change_profile rule with aa_change_profile, and aa-exec; there is no name for a parent or sibling 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 is audit change_profile -> :foo:/bin/foo, (a_ok_3.sd).
  • Call: int aa_change_profile(const char *profile) writes changeprofile :c1:foo to the task's current attribute (/proc/self/attr/apparmor/current, or the lsm_set_self_attr system call) (kernel.c:1067-1086). aa_change_onexec() writes exec NAME to the exec attribute (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 -- cmd asks for :c1://foo at the next exec, and with -i immediately (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 with info="label not found" (domain.c:1530-1539).
  • An unconfined caller needs no change_profile rule (domain.c:295-299).
  • Known discrepancy: the kernel matches a change_profile request as :, namespace, :, name (domain.c:106-111), and a rule written change_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" and change_profile -> ${nstest}, (changeprofile.sh:33, changeprofile.sh:84-119).

for AppArmor developers for security researchers

In the code

07 One label, three readers

WHO SEES WHAT foo (pid 4242) host (root) and foo (c1) one task, two profiles, two namespaces host shell (root namespace) $ cat /proc/4242/attr/current host//&:c1:foo (enforce) sees its own namespace and everything below a shell inside c1 $ cat /proc/4242/attr/current foo (enforce) host is above it: left out a shell in sibling c2 $ cat /proc/4242/attr/current cat: ...: Permission denied EACCES: nothing visible namespace="root//c1" profile="foo" a denial by the c1 part: audit uses the full name from the root the kernel prints :c1:foo; :c1://foo is accepted on input only
One task labelled host and foo in c1, read by three shells: the host sees host//&:c1:foo, a shell in c1 sees foo, and a shell in sibling c2 is refused.

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/current and /proc/PID/attr/apparmor/current, aa_getcon() and aa_gettaskcon() in libapparmor, ps -Z, and SO_PEERSEC for 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:name for 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//&B has both in c1 (label.c:1550-1561).
  • Audit records: a subject that is a single profile outside the root namespace gets namespace="root//c1" and profile="foo"; a subject of several profiles is printed as label=, viewed from the root (audit.c:117-135).
  • The aa-exec manual page shows both views: ps -Z inside prints unconfined for the shell and - for a process it cannot see, and from the parent unconfined//&:ex1:unconfined (aa-exec.pod:167-182).
  • The inside view is asserted by a regression test: a task stacked with :ns:stackprofile reads its own label as stackprofile, mode enforce (stackprofile.sh:117-139).

08 A container: its own namespace, under a host profile

A CONTAINER 1 create # apparmor_parser -n c1 profiles # or: mkdir policy/namespaces/c1 :c1: label of the first process host (enforce) 2 enter and keep host aa_stack_onexec(":c1:unconfined") change_profile -> &:c1:unconfined, added to the label, not replacing it host//&:c1:unconfined 3 exec /usr/bin/foo inside host: its own exec rule :c1:unconfined: attaches :c1:foo by the kernel's rules, the label is host//&:c1:foo (enforce) inside: foo (enforce) from inside c1 policy/profiles/ c1's profiles apparmor_parser -r new-profile loads into c1 .ns_name c1 .ns_level 1 .ns_stacked yes ... apparmor="DENIED" operation="change_onexec" info="no new privs" error=-1 namespace="root//lxd-tor_<var-lib-lxd>" profile="unconfined" name="system_tor" ... a namespace named after an LXD container every access is still checked against host
Three stages of starting a container: create namespace c1, stack c1 unconfined on the host profile, exec inside; then what a task inside sees and a real log line with a namespace named after an LXD container.

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) writes stack :c1:unconfined to the current attribute, int aa_stack_onexec(const char *profile) writes the same command to the exec attribute (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 namespace nnp: 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 c1 member, being unconfined, searches c1's attachments (domain.c:697-699).
  • /sys/kernel/security/apparmor/policy is a link that resolves to the directory of the reader's current namespace (apparmorfs.c:2863-2881).
  • .ns_name, .ns_level, .ns_stacked and .stacked in /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

09 Who may load policy into a namespace

THE GATE root in the container host//&:c1:foo apparmor_parser -r new-profile :c1: policy locked? info="policy_locked" uid 0 in its user namespace target namespace visible from here inside a user namespace, the sysctl kernel.unprivileged_userns_apparmor_policy is not 0, and user namespace level = policy namespace level CAP_MAC_ADMIN, and every profile in the label allows it in profile host: capability mac_admin, info="not policy admin" passes: the profile is loaded into c1 the same gate guards .load .replace .remove mkdir rmdir
A load request from root in the container passes a chain of checks before it reaches namespace c1: policy lock, uid 0 and visibility, the user namespace conditions, and CAP_MAC_ADMIN allowed by every profile of the label.

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 parameter lock_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_policy is not 0 and the user namespace level equals the policy namespace level (policy.c:918-921); - CAP_MAC_ADMIN in the user namespace and allowed by every confining profile of the label (policy.c:882-894, capability.c:188). In a profile that is capability mac_admin,.
  • The sysctl kernel.unprivileged_userns_apparmor_policy defaults to 1 (policy.c:91), has mode 0600, exists only with CONFIG_USER_NS and can be written only by a policy admin (lsm.c:2440-2459).
  • The check is called from the write handlers of .load, .replace and .remove and from mkdir and rmdir (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

PARSER TO KERNEL profile :c1:foo /usr/bin/foo { parse_label() parser_misc.c:914 Profile::ns = "c1" Profile::name = "foo" profile_base action parser_yacc.y:414-430 if (profile_ns) prof->ns = strdup(profile_ns); /* -n */ warns under WARN_OVERRIDE when the text named a different namespace sd_serialize_top_profile() parser_interface.c:666-681 version namespace "c1" profile { "foo" ... } name inside the struct: no namespace verify_header() reads namespace: "invalid namespace name", "invalid ns change" aa_replace_profiles() -> aa_prepare_ns(policy_ns ? policy_ns : labels_ns(label), ns_name) /bin/foo px -> :other:bar, sd_serialize_xtable() parser_interface.c:413-456 : o t h e r \0 b a r \0 process_strs_entry() writes : back over the NUL -> ":other:bar", parsed at exec by aa_label_parse()
Two tracks from profile text to the kernel: the namespace of a profile head becomes a namespace string in the blob header, and a namespaced exec target is stored with a NUL in place of the second colon.

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

11 aa_ns, the label's namespace and the view for AppArmor developers

KERNEL: policy_ns.c, label.c struct aa_ns base name, hname, profiles parent level unconfined sub_ns labels dents[] root (0) parent root//c1 (1) parent root//c1//inner (2) [0] host ns=root level 0 [1] foo ns=c1 level 1 sorted: ns level, ns hname, profile hname (label.c:109-155) labels_ns(L) = vec_last(L)->ns = c1 this is aa_get_current_ns() for the task aa_ns_visible(curr, view, subns) curr=root view=c1 true (ancestor walk) curr=c1 view=root false curr=c2 view=c1 false aa_ns_name(curr, view, subns) "" same namespace "c1" tail of hname after curr's "---" aa_hidden_ns_name aa_label_snxprint(buf, size, ns, label, FLAG_SHOW_MODE | FLAG_VIEW_SUBNS | FLAG_HIDDEN_UNCONFINED) each visible profile, //& between, :%s:%s when its ns differs from the reader's and the previous one's aa_getprocattr() returns -EACCES when labels_ns(label) is not visible
struct aa_ns and three chained instances, the sorted label vector whose last profile gives the label namespace, and the visibility, naming and printing functions.

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_DEPTH is 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 with subns for any descendant, found by walking parent (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 -EACCES for a label whose namespace is not visible and prints with FLAG_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).

12 Where to go from here

ROADS namespaces :ns:name, a tree, a view that goes down only attachment each namespace has its own list of candidates stacking host//&:c1:foo: how two profiles apply at once adm-parser adm-cache the other parser options; the cache that -n meets k-labels re-blob labels in the kernel; the binary policy format
Roads from namespaces to attachment, stacking, the parser and cache topics, kernel labels and the binary policy format.

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 sysctl kernel.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-string is 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.

FormMeaning
: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 with Profile attachment must begin with a '/' or variable.
  • @{profile_name} inside :ns:name expands to name, 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 -N prints the fully qualified name as :ns://name, and apparmor_parser -R writes 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 callEffect
/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 -- cmdasks for :ns://name at exec; with -i, immediately
aa-exec -n ns -- cmdasks for :ns://, the unconfined profile of ns
  • A profile file with no abi rule gets the parser's default ABI, which lacks domain/stack: change_profile -> &:ns:name, then fails with The current kernel does not support stacking of named transitions: &:ns:name. Put abi <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_profile rule, an unconfined caller does not. Its errors are ... profile ':ns://name' does not exist, ... insufficient permissions to change to the profile ':ns://name' and Multiple -n/--namespace parameters given.
  • aa_change_profile() fails with ENOENT when "the specified profile does not exist, or is not visible from the current Namespace".

apparmor_parser

OptionEffect
-n NS, --namespace NSload every profile, child profile and hat of the run into NS; the value is used as given
-N, --nameslist the names that would be loaded, as :NS://name
-Rremove; for a namespaced profile it removes only that profile
-K, --skip-cachedo not read the policy cache
  • -n names 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/NAME creates a namespace and rmdir removes it. Both are real operations that pass the policy management checks. An existing name gives EEXIST.
  • policy leads each reader to the directory of its own current namespace, so inside a container policy/profiles/ lists the container's profiles.
  • The top-level .load, .replace and .remove act on the writer's current namespace. The copies inside a namespace directory act on that namespace.
  • Writing :NAME: to .remove removes the namespace NAME with its profiles and child namespaces; writing :NAME://profile removes one profile.
  • Removing a namespace does not kill its tasks. Reading the code, the namespace's unconfined is redirected to the parent's unconfined, and the members of a label that live in surviving namespaces keep applying. The root namespace cannot be removed.
FileWhat it reports about the reading task
.stackedyes when its label has more than one profile
.ns_stackedyes when the label has more than one profile and one is outside the label's namespace
.ns_levelthe level of its current namespace; the root is 0
.ns_namethe last component of its current namespace's name; root in the root namespace
  • profiles lists 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/stack tells the parser that the kernel supports stacking. features/namespaces/ belongs to the userns rule, 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 labelReader in rootReader in c1Reader in sibling c2
host and foo in c1host//&:c1:foo (enforce)foo (enforce)EACCES
host and unconfined in c1host//&:c1:unconfined (enforce)unconfinedEACCES
host onlyhost (enforce)EACCESEACCES
host and p in inner below c1host//&: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//&B means both A and B are in c1.
  • No mode is printed for a namespace's unconfined, and a stack that contains it does not report mixed because of it.
  • ps -Z inside 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) and profile="foo". A subject with several profiles is printed as label=, viewed from the root.
  • SO_PEERSEC prints 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 the unconfined profile of ns.
  • 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//&B finds both A and B in ns.
  • Exec from a namespace's unconfined, and px without a target, search only the profiles of that profile's namespace. ux leads to the unconfined of 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:

CheckFailure
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 openerinfo="not privileged for target profile"
uid 0 (or group 0) in the task's user namespaceinfo="not policy admin"
the target namespace is the task's current namespace or below itinfo="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 levelinfo="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_policy defaults 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_DEPTH is 32, commented "Match max depth of user namespaces"; creation beyond it fails with ENOSPC. 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 .load or .replace carries one namespace: a second, different namespace in the same write fails with invalid ns change or policy 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

MessageWhen
Namespace not terminated: %sno second colon: :c1/foo { }
Empty namespace: %s::/x { }
Empty named transition profile name: %sa namespace with no profile name in a profile head: :c1: { }
Profile names must begin with a '/' or a namespacea 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: %sa 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.

MessageWhen
invalid namespace namethe binary policy carries an empty namespace string
invalid ns changea second, different namespace inside one write
policy load has mixed namespacesthe same, found while replacing profiles
failed to prepare namespacethe 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 founda change_profile target that does not exist or is not visible
policy_lockedpolicy has been locked
not privileged for target profilethe writer has more privilege than the opener of the file
not policy adminone 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 -n is 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 -n values, 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 than change_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 name is printed for a profile head with a namespace and no name, which is not a transition.

for AppArmor developers

Code map

Parser:

SymbolWhereRole
parse_label()parser/parser_misc.c:914splits :ns:name and :ns://name; source of the three label errors
label_contains_ns()parser/parser_misc.c:903tells add_named_transition() that a target is not a child profile
profile_base actionparser/parser_yacc.y:407-430fills Profile::ns; applies -n (profile_ns) with the WARN_OVERRIDE warning
Profile::fqname()parser/profile.h:463builds :ns://hname for -N and -R
sd_serialize_top_profile()parser/parser_interface.c:666writes version, then the namespace string, then the profile struct
sd_serialize_xtable()parser/parser_interface.c:413stores a namespaced exec target as :ns\0name
process_profile()parser/parser_main.c:1337-1371sets skip_cache for -n after the cache has been set up

Kernel (linux:security/apparmor/):

SymbolWhereRole
struct aa_nsinclude/policy_ns.h:60base, parent, level, unconfined, sub_ns, labels, dents[]
alloc_ns(), __aa_create_ns()policy_ns.c:105, 216allocation, level, apparmorfs directory, depth test
aa_prepare_ns(), __aa_find_or_create_ns()policy_ns.c:279, 250find or create on load; create on mkdir
destroy_ns(), __aa_remove_ns()policy_ns.c:308, 338release profiles and children, redirect unconfined to the parent
aa_ns_visible(), aa_ns_name()policy_ns.c:40-81view and spelling; aa_hidden_ns_name is ---
aa_lookupn_ns()policy_ns.c:174walks //-separated components down from a view
labels_ns()include/label.h:162namespace of the last profile of the sorted vector
aa_splitn_fqname()lib.c:183splits a text name into namespace and profile
aa_fqlookupn_profile()policy.c:663relative lookup; no profile name returns unconfined
aa_label_strn_parse()label.c:1892parses single and stacked names
aa_label_snxprint()label.c:1649prints 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, 488read the namespace string; restore the colon in exec targets
aa_replace_profiles(), aa_remove_profiles()policy.c:1210, 1488load and remove with a namespace
aa_may_manage_policy(), aa_policy_view_capable(), aa_policy_admin_capable()policy.c:1001, 907, 927the policy management checks
ns_mkdir_op(), ns_rmdir_op(), policy_get_link()apparmorfs.c:2085, 2137, 2863mkdir, 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 the namespace field, because nothing copies the parent's ns to the child. Seen in -S output for profile :ns:a { profile b { } }.
  • A namespace prefix on a child profile or hat is accepted. -N lists the child under the parent's namespace, while the child's header carries the child's own prefix.

See k-labels and re-blob.

Roads from here

ATTACHMENT, NAMESPACES, STACKING

RUNNING THE PARSER

IN THE KERNEL

THE DFA ENGINE · libapparmor_re