Every topic is a short narrated deck about AppArmor: the profile language, the policy compiler, libapparmor, the tools and the kernel. Pick any place, follow the roads at the end of each deck, and switch perspective at the top to see only what applies to you.
Source: gitlab.com/zygoon/apparmor-map · report a problem or suggest a change
Click a place to enter it. Inside a topic you see only its exits, like rooms in an adventure game; m brings the whole map back. space plays, ← → step. This map describes AppArmor at commit 836052d21 (6.0.0~alpha2) and mainline Linux at commit 97d73c825 (7.4-rc2). Where it says "the kernel", it means that Linux tree.
A refused access is one record: the profile that refused, the operation, the object and the permission. This deck reads it field by field, for administrators and application developers.
demo was compiled by the parser of the AppArmor tree the map describes and entered with aa-exec -p demo; it allows reading /etc/demo/demo.conf and has no rule for /etc/demo/secret.conf.audit: type=1400 audit(1794831779.488:174): apparmor="DENIED" operation="open" class="file" profile="demo" name="/etc/demo/secret.conf" pid=1323 comm="cat" requested_mask="r" denied_mask="r" fsuid=0 ouid=0. On the slide the prefix audit: type=1400 audit(SECONDS:SERIAL): is left out and the record is broken over lines.comm="cat" and not "demo": the record names the command that ran under the profile. The profile is in profile=.EACCES ("Permission denied") from AppArmor exactly as from file modes; the record is the only thing that tells the two apart.audit_pre() (audit.c:93-141); pid= and comm= by the LSM audit helper (lsm_audit.c:423); the file fields by file_audit_cb() (file.c:45-77).With the audit daemon running, records are in /var/log/audit/audit.log as type=AVC. Without it they are in the kernel log (dmesg, journalctl -k) as audit: type=1400. The text after the prefix is the same.
dmesg and in journalctl -k: Nov 16 12:23:31 aamap kernel: audit: type=1400 audit(1794831811.744:217): apparmor="DENIED" ....apt-get install auditd on the same guest: auditctl -s printed enabled 1, rate_limit 0, backlog_limit 8192, lost 0; new records were in /var/log/audit/audit.log (type=AVC msg=audit(1794831843.332:433): apparmor="ALLOWED" operation="open" class="file" profile="demo-complain" ...) and the number of apparmor= lines in dmesg stayed 0.fsuid=0 ouid=0FSUID="root" OUID="root": auditd appends the names it looked up after a separator character that a terminal does not show./var/log/syslog and /var/log/kern.log hold the kernel log too on systems that run a syslog daemon. On the Debian sid image neither exists; on the Ubuntu guests both exist and had the records./var/log/audit/audit.log, /var/log/syslog, /var/log/messages (logprof.conf:15).USER_AVC) and carry the AppArmor text inside msg='...': see D-Bus mediation and the reference below.aa_audit_msg() calls common_lsm_audit() (audit.c:160-165), which starts a record of type AUDIT_AVC (lsm_audit.c:437-460; the number 1400: audit.h:127).pr_notice("type=%d %s\n") under printk_ratelimit() (audit.c:582-590).apparmor= is DENIED (refused), ALLOWED (complain mode: would be refused), AUDIT (allowed by an audit rule), KILLED (refused and signalled) or STATUS (policy changed).
....DENIED: apparmor="DENIED" operation="open" class="file" profile="demo" name="/etc/demo/secret.conf" pid=1323 comm="cat" requested_mask="r" denied_mask="r" fsuid=0 ouid=0; cat printed Permission denied.ALLOWED: the profile demo-complain has flags=(complain) and no rule for the file: apparmor="ALLOWED" operation="open" class="file" profile="demo-complain" name="/etc/demo/secret.conf" pid=1468 comm="cat" requested_mask="r" denied_mask="r" fsuid=0 ouid=0; cat printed the file. The record still has denied_mask: it says what would have been denied.AUDIT: the rule is audit /etc/demo/audited.conf r,: apparmor="AUDIT" operation="open" class="file" profile="demo" name="/etc/demo/audited.conf" pid=1474 comm="cat" requested_mask="r" fsuid=0 ouid=0. There is no denied_mask. A second AUDIT record with operation="getattr" followed.KILLED: the profile demo-kill has flags=(kill): apparmor="KILLED" operation="open" class="file" profile="demo-kill" name="/etc/demo/secret.conf" pid=1494 comm="cat" requested_mask="r" denied_mask="r" fsuid=0 ouid=0; the shell reported Killed and exit status 137.STATUS: apparmor="STATUS" operation="profile_load" profile="unconfined" name="demo" pid=1292 comm="apparmor_parser". Here profile= is the label of the process that changed policy and name= is the profile that was changed. Loading the same profile again logged operation="profile_replace" info="same as current profile, skipping"; removing it operation="profile_remove".STATUS record with info= and error=: 300 random bytes written to .load logged apparmor="STATUS" info="invalid profile format" error=-93 profile="unconfined" pid=1317 comm="cat".HINT, ERROR and AUTO. None was produced in the run; AUTO is replaced before a record is written.audit deny file rule in a complain-mode profile is allowed and logged ALLOWED.aa_audit() (audit.c:200-237) and aa_select_audit_type() (audit.c:143-152). After a KILLED record the profile's signal is sent (audit.c:228-231).audit_header is Y, its default (audit.c:97-100).profile is the profile to edit; comm is only the command name. operation and class say what was checked and by which kind of rule; name is the object. info and error give a reason when the kernel has one.
audit: type=1400 audit(SECONDS:SERIAL): is left out and the record is broken over lines.apparmor, operation, class, info and error (only when there is a reason), namespace (only when the profile is not in the root policy namespace), profile (or label when the subject is a stack of profiles), name, then pid and comm, then the fields of the class.operation values seen in the run: open, mknod (creating a file), exec, link, chown, getattr, connect, create (a socket), capable, signal, ptrace, mount, umount, userns_create, change_onexec, profile_load, profile_replace, profile_remove. The complete list is in the reference below.class values seen: file, cap, net, signal, ptrace, mount, namespace. change_onexec is logged with class="file".comm is the task's command name, at most 15 characters. In the run a refused exec had comm="sh" (the caller) and name="/opt/demo/helper" (the program that was to run); Python scripts had comm="python3".name is quoted. When it contains a space, a quote or a control character the kernel writes it as hexadecimal digits without quotes; libapparmor and the utilities decode it.name is not always a full path. The mount command's look at a mount that is not attached yet logged operation="getattr" class="file" ... name="", and opening the POSIX message queue /demo logged operation="open" class="file" ... name="demo", both with info="Failed name lookup - disconnected path" error=-13: the object had no path from the task's root, so name is not a path a file rule can be written from. See The other profile flags for attach_disconnected.mqueue (create, open, read, write, delete) type=posix /demo-ok, got the same refusal for /demo-ok: apparmor="DENIED" operation="open" class="file" info="Failed name lookup - disconnected path" error=-13 profile="demo-mq" name="demo-ok" pid=1455 comm="python3" requested_mask="wrc" denied_mask="wrc" fsuid=0 ouid=0. The same was logged on Debian 13. What kernels with message queue mediation log instead is in Upstream and Ubuntu kernels.info values seen: failed af match (no rule for the address family), failed mntpnt match, Failed name lookup - disconnected path, same as current profile, skipping, invalid profile format. error is a negative errno: -13 EACCES, -93 EPROTONOSUPPORT.STATUS record profile= is the label of the process that changed policy and name= the profile that changed.io_uring at index 18.audit_pre(): audit.c:93-141. The operation strings: audit.h:47-110. The class names: audit.c:40-74. pid= and comm=: lsm_audit.c:423.label=, Policy namespaces for namespace=.denied_mask is the refused part in rule letters; c and d are written w in a rule. fsuid is who asked and ouid who owns the file: when they differ, an owner rule does not apply.
audit: type=1400 audit(SECONDS:SERIAL): is left out and the record is broken over lines.owner /srv/demo/** r,; /srv/demo/root-owned.txt belongs to root with mode 644; it was read by the user tester (uid 1000) with runuser -u tester -- aa-exec -p demo -- cat /srv/demo/root-owned.txt. File modes would allow the read; the profile does not, because the rule applies only when the task's fsuid is the file's owner.r read, w write, a append, x execute, m map executable, k lock, l link, and in records also c create and d delete. A check of file attributes (getattr) is logged as r; chmod, chown and setattr are logged as w.requested_mask to the permissions that were not allowed before it writes the record, so the two masks are normally the same. An AUDIT record has requested_mask only.apparmor="DENIED" operation="mknod" class="file" profile="demo" name="/var/lib/demo/new" pid=1342 comm="touch" requested_mask="c" denied_mask="c" fsuid=0 ouid=0.apparmor="DENIED" operation="link" class="file" profile="demo" name="/var/lib/demo/link" pid=1355 comm="ln" requested_mask="l" denied_mask="l" fsuid=0 ouid=0 target="/etc/demo/demo.conf". name is the new link, target the existing file; the rule is link /var/lib/demo/link -> /etc/demo/demo.conf, or l on the new name: see Link rules.chown on a file is refused as a file operation before any capability is asked: apparmor="DENIED" operation="chown" class="file" profile="demo" name="/etc/demo/demo.conf" pid=1361 comm="chown" requested_mask="w" denied_mask="w" fsuid=0 ouid=0. The rule it maps to is a w file rule.operation="connect" class="file" profile="demo" name="/run/demo.sock" ... requested_mask="wr" denied_mask="wr".fsuid and ouid are numbers as seen from the initial user namespace. In audit.log the audit daemon appends FSUID="root" OUID="root" with the names.target is also the profile of a transition: apparmor="DENIED" operation="change_onexec" class="file" profile="demo" name="demo-complain" pid=1439 comm="aa-exec" target="demo-complain".file_audit_cb(): file.c:45-77. The letter table aa_file_perm_chrs: lib.c:253. getattr shown as r, setattr/chmod/chown as w: file.c:28-38. Only the denied permissions are reported: file.c:132-133.Other classes carry their own fields: capname; family and sock_type; signal and peer; fstype, srcname and name. Each value is a word of the rule.
.... The four rules were compiled by the tree's parser without a message.apparmor="DENIED" operation="capable" class="cap" profile="demo" pid=1367 comm="chroot" capability=18 capname="sys_chroot" (from chroot / true, which failed with Operation not permitted). The two spaces before capname are in the record.apparmor="DENIED" operation="create" class="net" info="failed af match" error=-13 profile="demo" pid=1379 comm="python3" family="inet" sock_type="stream" protocol=0 requested="create" denied="create". Network records use requested and denied with words (create, connect, send, receive, bind, listen, accept, getattr, setattr, getopt, setopt, shutdown), not the _mask fields.addr, peer_addr and peer: apparmor="DENIED" operation="connect" class="net" profile="demo" pid=1387 comm="python3" family="unix" sock_type="stream" protocol=0 requested="send receive connect" denied="send connect" addr=none peer_addr="@demo" peer="unconfined". The rule: unix (connect, send) type=stream peer=(addr=@demo label=unconfined),. See Unix socket rules.apparmor="DENIED" operation="signal" class="signal" profile="demo" pid=1394 comm="sh" requested_mask="send" denied_mask="send" signal=hup peer="unconfined". The receiving side is checked against its own profile and logs its own record with receive./proc/1/environ logged apparmor="DENIED" operation="ptrace" class="ptrace" profile="demo" pid=1401 comm="cat" requested_mask="read" denied_mask="read" peer="unconfined"; the rule is ptrace (read) peer=unconfined,.apparmor="DENIED" operation="mount" class="mount" info="failed mntpnt match" error=-13 profile="demo" name="/mnt/demo/" pid=1407 comm="mount" fstype="tmpfs" srcname="none". This record is from LIBMOUNT_FORCE_MOUNT2=always mount -t tmpfs none /mnt/demo, which makes the mount command use the mount(2) system call. With the command's default system calls the record was operation="mount" class="mount" info="failed mntpnt match" error=-13 profile="demo" name="/mnt/demo/" pid=1413 comm="mount" flags="rw, move", without fstype and srcname.apparmor="DENIED" operation="umount" class="mount" profile="demo" name="/mnt/demo/" pid=1420 comm="umount"; the rule is umount /mnt/demo/,.apparmor="DENIED" operation="userns_create" class="namespace" profile="demo" pid=1427 comm="unshare" requested="userns_create" denied="userns_create" execpath="/usr/bin/unshare"; the rule is userns,.setrlimit, io_uring, pivotroot) are in the decks of their rules.capability= itself: lsm_audit.c:194), network net.c:118-166, signal ipc.c:52-76, ptrace task.c:233-250, mount mount.c:92-118, user namespace task.c:353-372.Complain mode logs ALLOWED and lets the access through. No line is written for a plain deny, for a capability refused again within a second, or for records beyond the kernel log's rate limit: 11 lines for 201 denials in the test.
demo-complain has flags=(complain); cat /etc/demo/secret.conf under it printed the file and logged apparmor="ALLOWED" operation="open" class="file" profile="demo-complain" name="/etc/demo/secret.conf" pid=1468 comm="cat" requested_mask="r" denied_mask="r" fsuid=0 ouid=0. A plain deny rule still refuses in complain mode: see Profile mode flags.audit deny file rule in a complain-mode profile is allowed and logged ALLOWED.deny /etc/demo/quiet.conf r, in the profile, cat printed Permission denied and the kernel log got no line. audit deny keeps the record: see The audit qualifier.echo -n noquiet > /sys/module/apparmor/parameters/audit the same read logged apparmor="DENIED" operation="open" class="file" profile="demo" name="/etc/demo/quiet.conf" pid=1487 comm="cat" requested_mask="r" denied_mask="r" fsuid=0 ouid=0. The values are normal (the default), quiet_denied, quiet.allowed, quiet, noquiet and all; quiet_denied and quiet remove denials, and quiet.allowed removes the ALLOWED records of complain mode (only noquiet was tried; the rest is from the source). A value other than normal overrides every profile's own audit flag.chroot("/") 20 times; all 20 failed and one record was logged (capname="sys_chroot"). The duplicate filter is per capability and lasts one second. File operations have no such filter (from the source; the recorded run refused one chown and logged one record).kernel.printk_ratelimit = 5 and kernel.printk_ratelimit_burst = 10 are the guest's defaults. A shell loop ran 200 refused reads, and one more 7 seconds later. dmesg then had 11 DENIED lines and the line kauditd_printk_skb: 339 callbacks suppressed. Why the counter says 339 for 190 missing lines was not determined.auditctl -s: rate_limit 0, backlog_limit 8192), the same loop of 200 added 200 lines to /var/log/audit/audit.log, and lost stayed 0.sysctl -w kernel.printk_ratelimit=0 switches the kernel log's limit off; the run did that for every other test.auditctl -r for a rate limit, the backlog limit); they were at their defaults here.profile names the profile to edit; name and denied_mask are the rule. Reload with apparmor_parser -r, run again, and expect the next denial.
/etc/demo/secret.conf r, after the rule for demo.conf. apparmor_parser -r exited with status 0; aa-exec -p demo -- cat /etc/demo/secret.conf printed secret; the kernel log got no new line./etc/apparmor.d/demo, where a profile normally lives; the STATUS line on the slide is shortened with .... The run did not keep the kernel log of this reload. The reloads it did keep replaced a profile with an identical one and logged apparmor="STATUS" operation="profile_replace" info="same as current profile, skipping" profile="unconfined" name="demo" pid=1299 comm="apparmor_parser"; for a profile that changed, the kernel writes the same record without info (from the source, not run).profile is the profile to edit (aa-status lists what is loaded; the file is usually under /etc/apparmor.d/). class and operation say which kind of rule. name and denied_mask, or the class's own fields, are the rule's words. fsuid and ouid say whether owner fits.c and d as w. Generalise the path with care: /etc/demo/*.conf r, covers the directory's configuration files; /etc/demo/** rw, would give away much more than the record asked for.-r replaces a loaded profile. Running processes keep the profile and get the new rules at once.include if exists <local/NAME>), put a local addition there instead of editing the shipped file: see include if exists and the Denials quick guide.info="Failed name lookup - disconnected path" is the exception to "name and denied_mask are the rule": its name is empty or has no leading slash, so it is not a path that a file rule can name. The scene "Who was stopped, doing what, to what" has two such records. Whether attach_disconnected and a file rule make such an access work was not tried.deny rule for such a path also silences its record.First word, then who, what and to what, then the permission. Roads: the tools that read the log, the qualifiers and flags that decide whether a line is written, and the kernel side.
Basis of the statements on this page: "logged" means the line was written by a running kernel, a Debian sid guest with kernel 7.3.4 (a distribution kernel without Ubuntu's AppArmor patches), under profiles compiled by the parser of the AppArmor commit 836052d21. "source" means the kernel source the map describes was read and the record was not produced. Records are quoted without the prefix audit: type=1400 audit(SECONDS:SERIAL):. What other kernels add to these records is in Upstream and Ubuntu kernels.
| Situation | Where | Line starts | Commands |
|---|---|---|---|
| the audit daemon (auditd) is running | /var/log/audit/audit.log | type=AVC msg=audit(1794831843.332:433): | grep apparmor= /var/log/audit/audit.log |
| no audit daemon | the kernel log | audit: type=1400 audit(1794831779.488:174): | dmesg, journalctl -k |
| a syslog daemon is installed | also /var/log/syslog, /var/log/kern.log | the kernel log's line with a time stamp | grep apparmor= /var/log/kern.log |
| D-Bus mediation | the same two places | type=1107 in the kernel log (USER_AVC), the AppArmor text inside msg='...' |
Logged: both forms, on one guest before and after installing auditd; after it, dmesg received no AppArmor line. The utilities read the first existing file of /var/log/audit/audit.log, /var/log/syslog, /var/log/messages (logprof.conf:15).
apparmor= | Meaning | Call result | Basis |
|---|---|---|---|
DENIED | the profile refused the access | fails, usually EACCES | logged |
ALLOWED | complain mode: the access would be refused | succeeds | logged |
AUDIT | a rule with audit (or the audit mode all) allowed the access | succeeds | logged |
KILLED | kill mode or a kill rule: refused | fails, and the profile's signal is sent (the test process was killed, exit status 137) | logged |
STATUS | a profile was loaded, replaced or removed, or a load failed | logged | |
HINT, ERROR | in the kernel's table | source | |
AUTO | internal; replaced before a record is written | source |
In the order the kernel writes them.
| Field | Value | Says | Becomes |
|---|---|---|---|
apparmor | one of the words above | the kind of record | |
operation | a word | what was checked | with class, the kind of rule |
class | file, cap, net, rlimits, domain, mount, ptrace, signal, namespace, io_uring, dbus, ... | the rule class consulted | the rule's keyword |
info | text | a reason | |
error | negative errno, only with info | ||
namespace | name, only outside the root policy namespace | where the profile lives | |
profile | name | the profile that decided; in STATUS the label of the process changing policy | the profile to edit |
label | label, instead of profile for a stack | ||
name | quoted, or hexadecimal without quotes when it has a space, a quote or a control character | the object: a path, a mount point, a target profile; in STATUS the profile changed | the path of the rule |
pid | number | the process | |
comm | at most 15 characters | the command name |
Operations in the source: open, exec, mknod, mkdir, rmdir, unlink, truncate, link, symlink, rename_src, rename_dest, chmod, chown, getattr, file_receive, file_perm, file_lock, file_mmap, file_mprotect, file_inherit; mount, umount, pivotroot; create, post_create, bind, connect, listen, accept, sendmsg, recvmsg, getsockname, getpeername, getsockopt, setsockopt, socket_shutdown; ptrace, signal; capable, sysctl; change_hat, change_profile, change_onexec, stack, stack_onexec; setprocattr, setrlimit; userns_create; uring_override, uring_sqpoll; profile_load, profile_replace, profile_remove.
| Class | Fields | Rule | Logged example |
|---|---|---|---|
| file | requested_mask, denied_mask, fsuid, ouid, target | NAME LETTERS, (c, d as w); owner when the uids match; link NAME -> TARGET, | operation="open" class="file" profile="demo" name="/srv/demo/root-owned.txt" pid=1336 comm="cat" requested_mask="r" denied_mask="r" fsuid=1000 ouid=0 |
| cap | capability, capname | capability CAPNAME, | operation="capable" class="cap" profile="demo" pid=1367 comm="chroot" capability=18 capname="sys_chroot" |
| net | family, sock_type, protocol, requested, denied | network FAMILY SOCK_TYPE, | operation="create" class="net" info="failed af match" error=-13 profile="demo" pid=1379 comm="python3" family="inet" sock_type="stream" protocol=0 requested="create" denied="create" |
| net, unix sockets | also addr, peer_addr, peer | unix (DENIED) type=SOCK_TYPE peer=(addr=PEER_ADDR label=PEER), | operation="connect" class="net" profile="demo" pid=1387 comm="python3" family="unix" sock_type="stream" protocol=0 requested="send receive connect" denied="send connect" addr=none peer_addr="@demo" peer="unconfined" |
| signal | requested_mask, denied_mask, signal, peer | signal (DENIED) set=(SIGNAL) peer=PEER, | operation="signal" class="signal" profile="demo" pid=1394 comm="sh" requested_mask="send" denied_mask="send" signal=hup peer="unconfined" |
| ptrace | requested_mask, denied_mask, peer | ptrace (DENIED) peer=PEER, | operation="ptrace" class="ptrace" profile="demo" pid=1401 comm="cat" requested_mask="read" denied_mask="read" peer="unconfined" |
| mount | fstype, srcname, trans, flags, options | mount fstype=FSTYPE options=(FLAGS) SRCNAME -> NAME,; umount NAME, | operation="mount" class="mount" info="failed mntpnt match" error=-13 profile="demo" name="/mnt/demo/" pid=1407 comm="mount" fstype="tmpfs" srcname="none" |
| namespace | requested, denied, execpath | userns, | operation="userns_create" class="namespace" profile="demo" pid=1427 comm="unshare" requested="userns_create" denied="userns_create" execpath="/usr/bin/unshare" |
| rlimits | rlimit, value, peer | set rlimit RLIMIT <= VALUE, | source |
| io_uring | requested, denied, tcontext | io_uring (...) label=TCONTEXT, | source |
| transitions | target | change_profile -> TARGET,, an exec rule | operation="change_onexec" class="file" profile="demo" name="demo-complain" pid=1439 comm="aa-exec" target="demo-complain" |
| policy load errors | ns, name, offset | apparmor="STATUS" info="invalid profile format" error=-93 profile="unconfined" pid=1317 comm="cat" | |
| D-Bus (bus daemon) | bus, path, interface, member, mask, name, label, peer_label | dbus (MASK) bus=BUS path=PATH interface=INTERFACE member=MEMBER peer=(label=PEER_LABEL), | type=1107 ... msg='apparmor="DENIED" operation="dbus_method_call" bus="system" path="/" interface="org.freedesktop.DBus" member="ListNames" mask="send" name="org.freedesktop.DBus" pid=1505 label="demo-dbus" peer_label="unconfined" |
The mount row is the record of the mount(2) system call. The mount command's default system calls logged flags="rw, move" without fstype and srcname. Known discrepancies: Kernel: mount_setattr(2), fsconfig reconfigure and fsopen/fsmount are not checked as remounts or new mounts; Kernel: mount audit records have no word for lazytime, and MS_REC shows only with bind or a propagation flag; Kernel: signal=unknown(%d) is logged without a leading space; Kernel: changeprofile &name is audited as operation="change_profile".
| Letter | Permission | In a rule |
|---|---|---|
r | read; also getattr | r |
w | write; also chmod, chown, setattr | w |
a | append | a |
c | create | w |
d | delete | w |
x | execute | an exec mode such as ix or Px |
m | map executable | m |
k | lock | k |
l | link | l |
Logged: failed af match, failed mntpnt match, Failed name lookup - disconnected path, same as current profile, skipping, invalid profile format. From the source, among others: failed type match, failed protocol match, profile transition not found, label not found, no new privs, ix fallback, ux fallback, target restricted, link not subset of target, hat not found, conflicting profile attachments.
A record with info="Failed name lookup - disconnected path" has a name that is empty or relative, and a file rule cannot be written from it. Logged: name="" for the mount command's look at a detached mount, and name="demo", requested_mask="wrc" for opening the POSIX message queue /demo, also under a profile that has an mqueue rule for the queue. Known discrepancy: a POSIX message queue on a kernel without mqueue mediation is refused as a file with a disconnected path.
| Cause | Effect | Basis |
|---|---|---|
a plain deny rule | refused, no record; audit deny logs | logged |
/sys/module/apparmor/parameters/audit | normal (default), quiet_denied and quiet remove denials, quiet.allowed removes the ALLOWED records of complain mode, noquiet logs quieted denials, all logs every access; a value other than normal overrides the profiles' own flag | noquiet logged; the rest source |
| the capability filter | the same capability for the same credentials: one record per second | logged: 20 calls, 1 record |
| the kernel log's rate limit (no audit daemon) | kernel.printk_ratelimit 5 seconds, burst 10 | logged: 201 denials, 11 lines |
| the audit daemon's own limits | auditctl -s shows rate_limit, backlog_limit, lost | logged with defaults: 200 of 200 |
1. Decide whether the access is wanted. 2. profile: the profile to edit. 3. class and operation: the kind of rule. 4. name and denied_mask, or the fields of the class: the words of the rule. 5. fsuid and ouid: whether owner fits. 6. apparmor_parser -r FILE; a STATUS record with operation="profile_replace" follows. 7. Run the program again and read the next record.
audit_pre(), audit.c:93-141. Type selection: audit.c:143-152, audit.c:200-237. Complain mode clears EPERM and EACCES: audit.h:206-211.pid, comm: lsm_audit.c:423, lsm_audit.c:437-460. Printing to the kernel log: audit.c:582-590.laddr, faddr, lport, fport, saddr, daddr, src, dest, peer_profile, peer_pid, name2, parent, magic_token and others come from older kernels, other kernels and user-space daemons. Its test suite has 679 files of real lines (test_multi).A rule the kernel cannot enforce is left out with exit status 0 and no message unless you ask. This deck shows where the kernel publishes its feature set, how to print it, how to choose the two sets and how to see what was left out.
network_v8/sctp, which no rule on these slides needs) with the parser built from the AppArmor tree, --config-file=/dev/null -K, the kernel features read from the running kernel.demo-all: a file rule, capability net_bind_service,, network inet stream,, network inet tcp ip=127.0.0.1 port=8080,, unix (connect) type=stream peer=(addr=@demo),, dbus send bus=session path=/org/demo,, signal send set=hup,, ptrace read,, mount fstype=tmpfs -> /mnt/demo/,, mqueue (create) type=posix /demo,, userns,, io_uring sqpoll,. The slide shows four of them.apparmor_parser -Q -K demo-all.sd printed nothing and exited with status 0. With --warn=all it printed Warning from profile demo-all (demo-all.sd): mqueue type=posix rules not enforced and exited with status 0. -Q compiles without loading; -K skips the cache, without which a cached profile is not compiled again and prints no warning. The slide shortens the file name.apparmor_parser -a of a profile with mqueue (create, open, read, write, delete) type=posix /demo-ok, exited with status 0 in the same guest.deny rule are left out alike.mq_open("/demo-ok", O_CREAT|O_RDWR) under that profile failed with "Permission denied", and so did every other queue name, with and without an mqueue rule. The kernel logged a file record: apparmor="DENIED" operation="open" class="file" info="Failed name lookup - disconnected path" error=-13 profile="demo-mq" name="demo-ok" pid=1455 comm="python3" requested_mask="wrc" denied_mask="wrc" fsuid=0 ouid=0. The queue is opened as a file on a mount that is attached nowhere, and file mediation refuses a path it cannot resolve. Debian 13 logged the same. See Reading a denial; what kernels with message queue mediation do is in Upstream and Ubuntu kernels.set_supported_features(): parser_main.c:1030-1125. The two warning classes are not in the default set: parser.h:77-78, parser_main.c:281-282./sys/kernel/security/apparmor/features holds one file per fact: 49 files on the test kernel. A missing entry, such as ipc, means rules of that kind are left out. Left out is not open: this kernel still refuses the message queue, as a file with a disconnected path.
network_v8/sctp (net.c:24-36), which makes 50. The ls output on the slide is that list's top level, wrapped over two lines.capability 0xffffff; caps/extended yes; caps/mask (the capability names); dbus/mask acquire send receive; domain/attach_conditions/xattr, domain/change_hat, domain/change_hatv, domain/change_onexec, domain/change_profile, domain/computed_longest_left, domain/disconnected.path, domain/fix_binfmt_elf_mmap, domain/kill.signal, domain/post_nnp_subset, domain/stack, domain/unconfined_allowed_children yes; domain/version 1.2; file/mask create read write exec append mmap_exec link lock; io_uring/mask sqpoll override_creds; mount/mask mount umount pivot_root; mount/move_mount detached; namespaces/mask userns_create; namespaces/pivot_root no; namespaces/profile yes; network_v8/af_mask and network_v9/af_mask (the address family names); network_v8/tcp-fast-open, network_v9/tcp-fast-open, network_v9/af_unix yes; policy/compressed_load, policy/diff-encode, policy/extended_policy_header, policy/set_load yes; policy/outofband 0x000001; policy/permstable32 (13 words); policy/permstable32_version 0x000003; policy/state32 0x000001; policy/unconfined_restrictions/change_profile yes; policy/versions/v5 to v9 yes; ptrace/mask read trace; query/label/data, query/label/multi_transaction yes; query/label/perms allow deny audit quiet; rlimit/mask (the limit names); signal/mask (the signal names).ipc/posix_mqueue (mqueue rules), network_v8/af_inet (ip= and port=), network and network/af_unix (the older network and unix mediation), network_v9_skb (interface=), domain/interruptible, domain/disconnected.ipc.ipc entry means mqueue rules are left out of every profile compiled for this kernel. It does not mean message queues are open to confined programs: in the same guest, opening a POSIX message queue under a profile was refused, with and without an mqueue rule, and the record on the slide was logged in full as apparmor="DENIED" operation="open" class="file" info="Failed name lookup - disconnected path" error=-13 profile="demo-mq" name="demo-ok" pid=1455 comm="python3" requested_mask="wrc" denied_mask="wrc" fsuid=0 ouid=0.dbus/mask is published by the kernel, although D-Bus rules are enforced by the bus daemon: see D-Bus mediation.CONFIG_SECURITY_APPARMOR_COMPRESSED_POLICY: apparmorfs.c:2642-2645.aa-features-abi -x prints the kernel's feature set as text; -w FILE saves it. An abi file has the same form, so the two can be compared with diff.
aa-features-abi -x -w FILE exited with status 0 and wrote 116 lines (2482 bytes); the first nine are the ones on the slide, with the capability list shortened. The distribution's own aa-features-abi -x printed the same bytes.aa-features-abi [OPTIONS] <SOURCE> [OUTPUT OPTIONS]. Source: -x, --extract (the running kernel) or -f F, --file=F (a file). Output: --stdout (the default) or -w F, --write=F. Options: -d, --debug; -v, --verbose; -h, --help. -x together with -f is refused: options --extract and --file are mutually exclusive.-f reads a feature file and writes it out again, which checks that the file can be parsed.name { followed by its entries and a } line; a file becomes name { followed by its content, with } on the next line.diff on the slide was made between the saved text of the guest's kernel and the abi/5.0 file of the AppArmor tree; the two lines shown are two of its lines. Only in abi/5.0: disconnected.ipc, interruptible, the ipc block, userns_create {pciu&, the network block, af_inet, metadata_tagging_version, the notify blocks, and io_uring and userns under unconfined_restrictions. Only in the kernel: tcp-fast-open, compressed_load, diff-encode, extended_policy_header.--kernel-features FILE replaces the running kernel's feature set with a file, to compile policy for another kernel. It changes what the parser assumes, not what a kernel can do.
-Q -K --skip-kernel-load), with the feature text saved from the Debian sid guest as the file. It printed Warning from profile demo-all (/work/demo-all.sd): mqueue type=posix rules not enforced, and -S wrote 1037 bytes. In the guest itself, with the features read from the running kernel, the warning and the 1037 bytes were the same. The slide shortens the file names and the warning prefix.abi/3.0 file of the AppArmor tree as the kernel set (the slide writes the installed path). Output, in full: Warning from profile demo-all (demo-all.sd): mqueue type=posix rules not enforced, ... userns rules not enforced, ... io_uring rules not enforced, exit status 0. The same three lines came out on every kernel tried, because the file replaced the kernel's set./sys/kernel/security/apparmor/features.Failed to load kernel features from 'FILE': ..., exit status 1 (from the source, not run).-M FILE (--features-file) and -m STRING (--match-string) set the kernel's set and pin the policy's set to the same value in one step./etc/apparmor.d/cache/.features as the default of -M; the parser reads the running kernel when no option is given.-m and -M: parser_main.c:669-696.For profiles without an abi rule, --policy-features names the policy set: a file or <kernel>. --override-policy-abi also replaces the set of profiles that have an abi rule.
network_v8/sctp, which no rule on these slides needs) with the parser built from the AppArmor tree, --config-file=/dev/null -K, the kernel features read from the running kernel. The profile is the twelve-rule profile with its first line removed; all runs had -Q --warn=all and exit status 0. The slide writes the installed path of the abi file; the runs used the copy from the AppArmor tree.Warning from demo-all-noabi.sd (demo-all-noabi.sd line 1): .../apparmor_parser: File 'demo-all-noabi.sd' missing feature abi, falling back to default policy feature abi, then network rules not enforced (three times), extended network unix socket rules not enforced, mqueue type=posix rules not enforced, userns rules not enforced, io_uring rules not enforced, and a line profile demo-all network rules not enforced.--warn=all the same file prints nothing: the "missing feature abi" warning belongs to the warning class abi, which is off by default (run with the tree's parser outside a guest).--policy-features FILE with abi/3.0: downgrading extended network unix socket rule to generic network rule, mqueue type=posix rules not enforced, userns rules not enforced, io_uring rules not enforced.--policy-features "<kernel>": mqueue type=posix rules not enforced only. The word must reach the parser with its angle brackets, so quote it in a shell. It always means the running kernel, also when --kernel-features names a file: on a machine without an AppArmor kernel the tree's parser stopped with Failed to load kernel features into the policy-features abi: No such file or directory, exit status 1 (run with the tree's parser outside a guest).--override-policy-abi FILE with abi/3.0, on the profile that has abi <abi/5.0>,: the same four lines as --policy-features with abi/3.0 on the profile without the rule. It also accepts <kernel>.--compile-features is the older name of --policy-features.--policy-features "does not override feature ABI rules"; --override-policy-abi does.Failed to load policy-features from 'FILE': ..., exit status 1 (from the source, not run).policy-features=FILE in /etc/apparmor/parser.conf pins every profile without an abi rule. Debian ships such a line, Ubuntu none. A profile's own abi rule wins over the pin.
--config-file FILE names another file; --print-config-file prints which one is used.#policy-features=/etc/apparmor.d/abi/kernel-5.4-vanilla and #policy-features=/etc/apparmor.d/abi/kernel-5.4-outoftree-network, and says that only one should be used at a time. It also has #warn=no-abi, to switch the abi warnings off without a pin.abi/5.0 file, --warn=all): with a config file holding policy-features=.../abi/3.0, the twelve-rule profile without an abi rule printed mqueue type=posix rules not enforced, userns rules not enforced and io_uring rules not enforced, and no "missing feature abi" line. The same profile with abi <abi/5.0>, printed nothing: the abi rule won over the pin. With policy-features=.../abi/5.0 and warn=all both in the config file, the profile without an abi rule printed nothing./etc/apparmor/parser.conf on Debian 13 and Debian sid has one line that is not a comment, policy-features=/usr/share/apparmor-features/features. On Ubuntu 24.04, 26.04 and 26.10 every line is a comment. The content of Debian's features file was not examined.policy-features= line replaces an earlier one.-Q -K --warn=all lists what was left out or downgraded (without -K a cached profile is not compiled again and prints nothing); -D rule-exprs shows what was compiled; --Werror with the warning enabled fails the compile. ip= and port= conditions are dropped with no message.
network_v8/sctp, which no rule on these slides needs) with the parser built from the AppArmor tree, --config-file=/dev/null -K, the kernel features read from the running kernel. The slide shortens file names and writes ... for apparmor_parser.apparmor_parser -Q -K demo-all.sd: no output, exit status 0. With --warn=all: Warning from profile demo-all (demo-all.sd): mqueue type=posix rules not enforced, exit status 0.-K: the warnings are printed while a profile is compiled. Reading the cache is on by default and -Q does not turn it off, so for a profile that has a fresh cache entry, which is the normal state of the files in /etc/apparmor.d, the parser takes the compiled profile from the cache and prints no warning. -K (--skip-cache) or -T (--skip-read-cache) makes it compile. -D and -S skip reading the cache by themselves. See The policy cache.rule-not-enforced ("warn if a rule is not enforced") and rule-downgraded ("warn if a rule is downgraded to a lesser but still enforcing rule"). Neither is in the default set. --help=warn lists all classes; --warn=all switches every class on, so it prints other warnings too. A line warn=rule-not-enforced in parser.conf makes it permanent.-D rule-exprs prints one rule: line per compiled rule. For the twelve-rule profile with abi <abi/5.0>,: 24 lines in the Debian sid guest. "Another kernel" is the Ubuntu 26.04 guest (kernel 7.0), where the same command gave 67 and --warn=all printed nothing; Ubuntu 24.04 gave 66 and Debian 13 gave 19. See Upstream and Ubuntu kernels.--Werror run was made with the tree's parser outside a guest, with the feature text saved from the Debian sid guest as the kernel set. With --warn=rule-not-enforced --Werror=rule-not-enforced it printed Warning converted to Error from profile demo-all (/work/demo-all.sd): mqueue type=posix rules not enforced and exited with status 1.--Werror=rule-not-enforced without --warn=rule-not-enforced exits with status 1 and prints nothing. Seen in the same run without the --warn option, and with a bare --Werror.--warn=all, recorded in the research notes with the tree's parser: ip= and port= on a network rule when the kernel has no network_v8/af_inet (the rule is kept as a family and type rule), interface= without network_v9_skb/iface, and the flag attach_disconnected.ipc.af_inet, so deny rules get wider. Seen on the running Debian sid kernel: with network inet stream, and deny network (connect) inet stream peer=(ip=127.0.0.1 port=25), a connect to port 22 was refused as well as one to port 25.attach_disconnected.ipc is dropped without a warning and its bit is written anyway.info="Failed name lookup - disconnected path". See the scene "What the kernel publishes" and Reading a denial.--Werror: parser_common.c:169-186.The cache directory is named after a hash of the kernel's feature text. A kernel with a different feature set gets a new directory and every profile is compiled again. --print-cache-dir prints the one in use.
apparmor_parser --print-cache-dir was run with the distribution's parser in five guests. Debian 13 (kernel 6.12.116): /var/cache/apparmor/979b3ac6.0. Ubuntu 24.04 (6.8.0-147): b8ec2925.0. Ubuntu 26.04 (7.0.0-43): f6da0254.0. Debian sid (7.3.4): 48da56f3.0. Ubuntu 26.10 (7.3.0-10): 0bd21c56.0. "Another 7.3" on the slide is the Ubuntu 26.10 kernel: the same kernel version as Debian sid's with a different feature set. Each guest's /var/cache/apparmor/ held exactly that one directory.--kernel-features naming the feature text saved from the Debian sid guest, printed /var/cache/apparmor/48da56f3.0 as well: the name depends on the feature text and on nothing else of the machine.--kernel-features. The policy set does not enter the name.The feature directory, aa-features-abi, --kernel-features, --policy-features, parser.conf and --warn=all. Roads: the abi rule, the parser and its config, the cache, other kernels.
Basis of the statements on this page: "guest" means the command was run in a disposable virtual machine with the parser and aa-features-abi built from the AppArmor commit 836052d21 (--config-file=/dev/null -K, kernel features read from the running kernel unless an option says otherwise). The main guest is Debian sid with kernel 7.3.4, whose 49 feature files are the entries of the feature tables of the kernel source the map describes less one (network_v8/sctp). "tree" means the tree's parser was run without a kernel (-Q -K --skip-kernel-load), with the kernel set named. "source" means read and not run. The abi rule, the shipped abi files and the table of which entry switches on which kind of rule are in The abi rule and the abi files and are not repeated here.
/sys/kernel/security/apparmor/features, readable by every user. Top level on the kernel: capability (a file) and the directories caps, dbus, domain, file, io_uring, mount, namespaces, network_v8, network_v9, policy, ptrace, query, rlimit, signal.
| Entry | Value (guest) | What it switches on |
|---|---|---|
file/mask | create read write exec append mmap_exec link lock | file rules (always compiled) |
network_v8, network_v9 | directories | network rules |
network_v9/af_unix | yes | fine-grained unix rules |
mount/mask | mount umount pivot_root | mount, umount and pivot_root rules |
mount/move_mount | detached | read from the kernel set only |
signal/mask, ptrace/mask | the signal names; read trace | signal and ptrace rules |
dbus/mask | acquire send receive | dbus rules are compiled (the bus daemon enforces them) |
namespaces/mask | userns_create | userns rules |
io_uring/mask | sqpoll override_creds | io_uring rules |
domain/stack | yes | stacking (& targets) |
domain/attach_conditions/xattr | yes | xattrs= on a profile |
domain/kill.signal | yes | flags=(kill.signal=...) |
caps/mask | the capability names | which capability names are known |
policy/versions/v5 to v9, policy/permstable32, policy/permstable32_version, policy/state32, policy/outofband, policy/set_load, policy/diff-encode, policy/compressed_load, policy/extended_policy_header | yes or a number | the format of the compiled profile |
policy/unconfined_restrictions/change_profile | yes | |
query/label/* | the query interface | |
not present: ipc/posix_mqueue, network_v8/af_inet, network, network/af_unix, network_v9_skb, domain/interruptible, domain/disconnected.ipc | mqueue rules; ip= and port=; the older network and unix mediation; interface=; two profile flags |
aa-features-abi [OPTIONS] <SOURCE> [OUTPUT OPTIONS]
SOURCE: -x, --extract the running kernel
-f F, --file=F a feature file
OUTPUT: --stdout the default
-w F, --write=F a file
OPTIONS: -d, --debug -v, --verbose -h, --help
Guest: -x -w FILE wrote 116 lines. -x with -f: options --extract and --file are mutually exclusive (source). The text form: name {content and } for a file, name { ... } for a directory.
| Option | Sets | Value | Beats an abi rule |
|---|---|---|---|
| (none) | kernel set: the running kernel. Policy set: the file's abi rule, else the built-in default | ||
--kernel-features FILE | the kernel set | a feature file | not applicable |
--policy-features FILE (older name --compile-features) | the policy set of files without an abi rule | a file or <kernel> | no |
--override-policy-abi FILE | the policy set of every file | a file or <kernel> | yes |
-M FILE, --features-file FILE | both: the kernel set, and the policy set as with --policy-features | a file | no |
-m STRING, --match-string STRING | both, from a string | feature text | no |
policy-features=FILE in parser.conf | as --policy-features, on every run | no |
Guest, the twelve-rule profile, -Q -K --warn=all:
| Profile and option | Output (prefix left out) |
|---|---|
with abi <abi/5.0>, | mqueue type=posix rules not enforced |
with it, --kernel-features abi/3.0 | mqueue, userns and io_uring rules not enforced |
with it, --override-policy-abi abi/3.0 | downgrading extended network unix socket rule to generic network rule; mqueue, userns, io_uring not enforced |
| without an abi rule | File '...' missing feature abi, falling back to default policy feature abi; network (three lines), extended network unix socket rules not enforced, mqueue, userns, io_uring not enforced |
without, --policy-features "<kernel>" | mqueue type=posix rules not enforced |
without, --policy-features abi/3.0 | the unix rule downgraded; mqueue, userns, io_uring not enforced |
Every run exits with status 0. Without --warn=all none prints anything (tree).
/etc/apparmor/parser.conf: every long option as name=value or name, one per line, read before the command line. --config-file FILE names another file.
| System (guest) | Active lines |
|---|---|
| the shipped file of the tree | none; two commented policy-features= examples |
| Debian 13, Debian sid | policy-features=/usr/share/apparmor-features/features |
| Ubuntu 24.04, 26.04, 26.10 | none |
Tree: a pin to abi/3.0 removes the "missing feature abi" warning of a profile without an abi rule and leaves mqueue, userns and io_uring rules out; a profile with abi <abi/5.0>, is compiled against abi/5.0 whatever the pin says.
| Command | Shows |
|---|---|
apparmor_parser -Q -K --warn=all FILE | one line per kind of rule left out or downgraded, per profile; also every other warning. Without -K (or -T) a profile with a fresh cache entry is not compiled again and prints nothing |
--warn=rule-not-enforced, --warn=rule-downgraded | only these two classes |
apparmor_parser -Q -D rule-exprs FILE | the compiled rules, one rule: line each |
-K --warn=rule-not-enforced --Werror=rule-not-enforced | exit status 1 and Warning converted to Error ... |
apparmor_parser --help=warn | the warning classes |
Known discrepancies: --Werror=rule-not-enforced without --warn=rule-not-enforced exits with status 1 and prints nothing; inet conditionals are dropped silently when the kernel has no af_inet, so deny rules get wider; attach_disconnected.ipc is dropped without a warning and its bit is written anyway; Two "not enforced" warnings are printed for rules that are compiled; Only the first "Ignoring" warning of a profile is printed.
The twelve-rule profile with abi <abi/5.0>,, compiled in each guest by the tree's parser with -Q -K --warn=all. Which kernel has which entry, and why, is Upstream and Ubuntu kernels.
| Guest kernel | Feature files | Warnings | rule: lines | Cache directory |
|---|---|---|---|---|
| Debian 13, 6.12.116 | 38 | unix rule downgraded; dbus and mqueue rules not enforced | 19 | 979b3ac6.0 |
| Ubuntu 24.04, 6.8.0-147 | 51 | none | 66 | b8ec2925.0 |
| Ubuntu 26.04, 7.0.0-43 | 67 | none | 67 | f6da0254.0 |
| Debian sid, 7.3.4 | 49 | mqueue rules not enforced | 24 | 48da56f3.0 |
| Ubuntu 26.10, 7.3.0-10 | 68 | none | 67 | 0bd21c56.0 |
<cache location>/<hash>.<n>: the hash is eight hexadecimal digits computed from the kernel set's text; n is 0 unless two texts collide. apparmor_parser --print-cache-dir prints it. Tree: with --kernel-features naming the text saved from the Debian sid guest, the name is the guest's, 48da56f3.0.
parser.conf (policy-features=), and the options given by whatever loads policy at boot.deny rule is left out like any other rule of its kind.Attachment happens at exec. The kernel compares the executable's path with the attachment of every candidate profile and keeps the best one. A profile loaded later does not attach to programs that are already running.
Kernel behaviour in this deck is read from the kernel source; it was not run on a kernel, except where a regression test of the AppArmor tree is named.
bprm_creds_for_exec (lsm.c:1862), which is apparmor_bprm_creds_for_exec (domain.c:985).cat /proc/PID/attr/current, ps -Z, aa-status.profile foo /usr/bin/foo { } is named foo and attaches to /usr/bin/foo. A path-named profile uses its name as its attachment. profile foo { } has no attachment and is only reached by name. The order after the name is fixed: attachment, xattrs=, flags=.
[profile] NAME [ATTACHMENT] [xattrs=(...)] [flags=(...)] {. The order after the name is fixed.The use of file paths as profile names is deprecated. See man apparmor.d for more information. Its class is deprecated; it prints only with apparmor_parser --warn=deprecated or --warn=all.Profile names must begin with a '/', namespace or keyword 'profile' or 'hat'. and Profile attachment must begin with a '/' or variable.profile exist /does/not/exist { (profile_basic_named_ok1.sd:8).Px -> NAME in another profile, aa-exec -p NAME -- COMMAND, or aa_change_profile("NAME").profile_base: TOK_ID opt_id_or_var opt_cond_list identities flags TOK_OPEN (parser_yacc.y:391); the attachment check is at parser_yacc.y:431-433 and the deprecation warning at parser_yacc.y:469-470.The score is the number of leading characters of the path consumed before the match first returns to a state it was just in. For /usr/bin/foo: /usr/bin/foo scores 12, /usr/bin/* 10, /usr/** 6, /** 2. Worked out from the code; not measured on a kernel.
The scores are worked out from the kernel source; they were not measured on a kernel.
count returned by aa_state_t aa_dfa_leftmatch(const struct aa_dfa *dfa, aa_state_t start, const char *str, unsigned int *count) (match.c:816-824).#define WB_HISTORY_SIZE 32 (match.h:154-159); the test is is_loop (match.c:720-739)./usr/bin/foo: /usr/bin/foo 12, /usr/bin/fo? 12, /usr/bin/fo* 11, /usr/bin/f* 10, /usr/bin/* 10, /usr/** 6, /** 2. The full table is in the reference under this deck./usr/*/foo scores 6 for /usr/bin/foo and 10 for /usr/b/foo.*, ** and ? match.convert_aaregex_to_pcre (parser_regex.c:118); the kernel sees only the DFA built from it, which is why the count is over DFA states and not over characters of the pattern.A candidate is replaced only by a profile with a strictly higher score. foo (12) beats bin (10) beats usr (6) for /usr/bin/foo, in any load order. Worked out from the code; not measured on a kernel.
Worked out from the kernel source; not measured on a kernel.
if (count < candidate_len) continue; (domain.c:439-440)./usr/bin/foo the profiles /usr/bin/foo, /usr/bin/* and /usr/** score 12, 10 and 6. For /usr/lib/x/foo only /usr/** matches.Equal score and equal matched xattrs is a conflict: the search returns no profile and sets conflicting profile attachments. /usr/bin/* and /usr/bin/f* tie at 10 for /usr/bin/foo; /usr/bin/fo* scores 11. Worked out from the code and recorded as a known discrepancy with what people expect; not measured on a kernel.
Worked out from the kernel source and recorded as a known discrepancy with what profile authors expect; not measured on a kernel.
conflicting profile attachments (domain.c:495-499)./usr/bin/* and /usr/bin/f* tie for /usr/bin/foo: the first character a * takes is counted, and counting stops when the walk stays in the same state (match.c:769-774). Nine literals plus one is 10; ten literals plus nothing is 10./usr/bin/fo* scores 11 and wins over both.operation="exec" and info="conflicting profile attachments" (type AUDIT by the code, since the exec itself is allowed), and the program running unconfined. No sample of this record exists in the trees; only the operation, info and name fields are certain.xattrs= condition, or drop the overlap.TODO: allow for more flexible best match (domain.c:463-468).max(count, attach->xmatch_len) (domain.c:481), while later profiles are compared by their raw count.On a tie: an unconfined task stays unconfined and an operation="exec" record with info="conflicting profile attachments" is forced; px/cx deny with info="profile transition not found"; pix keeps the current profile with info="conflicting profile attachments - ix fallback"; pux runs unconfined. Known limitation: under px the audit record cannot tell a tie from a missing profile; the kernel log can.
Read from the kernel source; not run on a kernel.
conflicting profile attachments, conflicting profile attachments - ix fallback, conflicting profile attachments - ux fallback (domain.c:33-37).operation="exec", info="conflicting profile attachments", name= the path.px or cx: no label is found, so info becomes profile transition not found and the error is -EACCES (domain.c:741-754).pix or cix: the task keeps its profile, info="conflicting profile attachments - ix fallback" (domain.c:617-628).pux or cux: the namespace's unconfined profile, info="conflicting profile attachments - ux fallback" (domain.c:629-636).px the conflict text goes only to the kernel log, rate-limited: AppArmor: profile_transition (from profile launcher) audit info "conflicting profile attachments" dropped on missing transition (domain.c:742-746). Look for it with dmesg or journalctl -k.px and cx without a fallback.new->proxy == profile->label.proxy (domain.c:730-737), a comparison that a ux fallback does not appear to satisfy; not confirmed by a run.xattrs=(name=value ...) adds required extended attributes to the attachment. With equal path scores the profile with more matched xattrs wins; a higher path score wins regardless. The parser drops the condition when the kernel or the profile's ABI lacks xattr attachment, and a file with no abi rule is in that case: the profile is then broader than written. The warning xattr attachment conditional ignored appears only with --warn=rule-not-enforced or --warn=all.
profile tagged /usr/bin/foo xattrs=(user.foo=hello) {. Values are globs; a bare name means any value. Man page example: profile trusted /usr/bin/* xattrs=(security.apparmor="trusted") { (apparmor_xattrs.pod:39).setfattr -n user.foo -v hello /usr/bin/foo, getfattr -d /usr/bin/foo.domain/attach_conditions/xattr in both the kernel and the ABI of the profile (parser_main.c:1096-1098), and policy/outofband in the kernel (parser_main.c:1758-1759). Check with ls /sys/kernel/security/apparmor/features/domain/attach_conditions/.xattr attachment conditional ignored (parser_regex.c:472-476) and prints only with --warn=rule-not-enforced or --warn=all (parser_common.c:169-171).abi <abi/3.0>, or newer for the condition to be kept; without an abi rule the parser's default ABI is used, which has no xattr attachment.xattrs=: hat profiles can't use xattrs matches.aa_xattrs_match (domain.c:313-314), outside the RCU read lock; the search restarts if the namespace revision changed meanwhile (domain.c:443-455).Unconfined tasks and px search the top-level profiles of the namespace; cx searches the current profile's children; px -> name and cx -> name look the target up by name; ix and ux do not search. An on-exec request (aa-exec -p, aa_change_onexec) is tested first.
Read from the kernel source; not run on a kernel.
aa-exec -p NAME -- COMMAND, which calls aa_change_onexec(name) (aa_exec.c:210-211), or from C with int aa_change_onexec(const char *profile);. libapparmor sends the string exec NAME with the lsm_set_self_attr system call when it is available, and otherwise writes it to the task's exec attribute under /proc/PID/attr/ (kernel.c:997-1011).px: the same search over the namespace's top-level profiles. cx: the search over the children of the current profile (domain.c:603-611).px -> name, cx -> name: a lookup by name in the profile's transition table; the target's attachment is not consulted (domain.c:592-597).ix keeps the current profile; ux goes to the namespace's unconfined profile (domain.c:617-636).aa-exec -i -p NAME changes the profile at once with aa_change_profile instead of at exec (aa_exec.c:205-207).aa_change_onexec).AA_X_NAME 0x04000000, AA_X_TABLE 0x08000000, AA_X_CHILD, AA_X_INHERIT and AA_X_UNCONFINED (file.h:56-64); x_to_label dispatches on them (domain.c:574-578) and x_table_lookup resolves a named target (domain.c:523-524).No match: unconfined stays unconfined with no record; px/cx fail with EACCES and info="profile transition not found"; pix keeps the current profile (info="ix fallback"); pux goes to the namespace's unconfined profile (info="ux fallback"); complain mode creates <profile>//null-<path>. The two fallback texts are logged only if the rule audits. With no exec rule for the path at all, the exec is denied, or learned in complain mode.
Read from the kernel source; not run on a kernel. The two log lines quoted are from the libapparmor test corpus.
px or cx: info="profile transition not found", error -EACCES (domain.c:747-754). The info= and error= fields are written together (audit.c:111-115).pix, cix: the current profile, info="ix fallback". pux, cux: the namespace's unconfined profile, info="ux fallback" (domain.c:617-636). A record is written for these only if the rule audits.PARENT//null-PATH (policy.c:756-757). A real record: apparmor="ALLOWED" operation="exec" profile="/home/cb/bin/hello.sh" name="/usr/bin/rm" ... target="/home/cb/bin/hello.sh//null-/usr/bin/rm" (exec01.in:1).-EACCES (domain.c:768-770). A real record: apparmor="DENIED" operation="exec" profile="/usr/bin/wireshark" name="/usr/lib64/wireshark/extcap/androiddump" ... requested_mask="x" denied_mask="x" (exec02.in:1).aa-status (is it loaded), cat /proc/PID/attr/current (what the process carries), then the attachment in the profile head against the real path of the binary (readlink -f).aa_new_learning_profile(profile, false, name, GFP_KERNEL) (domain.c:756-759) and is added to the parent's children (policy.c:789).attach_disconnected and attach_disconnected.path=/prefix belong to the profile confining the task that calls execve; the flag attaches the path to a root, it does not attach a profile. Without it a confined exec of a disconnected file fails with info="Failed name lookup - disconnected path"; an unconfined task keeps its label and nothing attaches.
Read from the kernel source; not run on a kernel, except the regression test named below.
flags=(attach_disconnected) or flags=(attach_disconnected.path=/prefix) (profile.h:231-242). A relative prefix is the error attach_disconnected path must begin with a / (parser_variable.c:49-50)./ and the lookup fails with -EACCES (path.c:53-61). With it the / is put back and the prefix, if any, in front (path.c:62-68).info= texts: Failed name lookup - disconnected path, Failed name lookup - deleted entry, Failed name lookup - name too long, Failed name lookup (path.c:208-216).execve (domain.c:684-685).no_attach_disconnected, chroot_attach, chroot_no_attach, mediate_deleted, delegate_deleted.attach_disconnected, attach_disconnected.path.int aa_path_name(const struct path *path, int flags, char *buffer, const char **name, const char **info, const char *disconnected) (path.c:202-203) calls d_namespace_path, which marks a path as not connected when it is outside the task's mount namespace (path.c:125-127).FLAG_IX_ON_NAME_ERROR (policy_ns.c:91-92).For unconfined tasks and px, candidates are the top-level profiles of the deciding profile's own namespace. Children and hats are searched only by cx from their parent. The same attachment in two namespaces is not a conflict; px -> :ns:name reaches another namespace by name.
Read from the kernel source; not run on a kernel, except the regression test named below.
profile->ns->base.profiles: the top-level profiles of the namespace of the task's own profile (domain.c:698-699).px it is ns->base.profiles with ns = profile->ns; for cx it is profile->base.profiles, the children of the current profile (domain.c:603-611).Px -> :ns:name (domain.c:551-552).apparmor_parser -n NAME -r FILE (parser_main.c:171). The namespaces are listed under /sys/kernel/security/apparmor/policy/namespaces/ (apparmorfs.c:2275).:ns:name (mode) (label.c:1566-1568).alias /usr/ -> /opt/x/, gives profile foo /usr/bin/foo a second attachment /opt/x/bin/foo. @{exec_path} and @{attach_path} both hold the attachment pattern, globs included, and an alias rewrites the resulting rule like any other file rule; in a profile without an attachment they are undefined (Failed to find declaration for: @{attach_path}).
alias /usr/ -> /opt/x/, in the preamble. If the alias source is a prefix of the attachment text, the profile gets an alternate attachment with the prefix replaced (parser_alias.c:176-190). It is a test on the pattern text: /us*/bin/foo is not aliased by /usr/.profile_name, attach_path, exec_path (parser.h:334-337).@{attach_path} and @{exec_path} are both set to the attachment text (parser_variable.c:159-175). The source notes update to use kernel vars if available, so @{exec_path} is not the path that was executed.profile bin /usr/bin/* { @{exec_path} r, } grants read on everything /usr/bin/* matches.@{profile_name} is escaped so that its characters are not read as globs; the other two are not (parser_variable.c:151-155).Failed to find declaration for: @{attach_path}.apparmor_parser -Q -K -D variables FILE.process_profile_name_xmatch (parser/parser_regex.c:478) builds the xmatch DFA for every profile with an attachment; xmatch_len is min_match_len() of the expression tree. The kernel unpacks them into struct aa_attachment. The parser does not write the optional attach string. The lengths shown were read from the output of apparmor_parser 6.0.0~alpha2 (836052d21).
Read at AppArmor 836052d21 (6.0.0~alpha2) and the kernel.
bool process_profile_name_xmatch(Profile *prof) (parser_regex.c:478), called from process_profile_rules (parser_regex.c:1238).profile_base (parser_yacc.y:391).xmatch_len is the smallest min_match_len() over the expression trees (aare_rules.cc:173-176).sd_write_uint32(buf, profile->xmatch_len) (parser_interface.c:496-501).unpack_pdb(e, &profile->attach.xmatch, ...) and then the u32 into profile->attach.xmatch_len; a DFA without the length fails with missing xmatch len (policy_unpack.c:1174-1187).attach is read by the kernel (policy_unpack.c:1171-1172) and not written by the parser.struct aa_attachment { const char *xmatch_str; struct aa_policydb *xmatch; unsigned int xmatch_len; int xattr_count; char **xattrs; }; (policy.h:213-219).apparmor_parser -Q -K -D dfa-states FILE (names from --help=dump).find_attach (linux:security/apparmor/domain.c:394-506) returns the best match or NULL on no match or conflict. aa_dfa_leftmatch (match.c:816) supplies count; aa_xattrs_match (domain.c:313) supplies the tie-breaker and runs outside the RCU read lock, restarting the walk if the namespace revision changed. The counts are worked out from the code, not measured.
Read from the kernel; the counts in the narration are worked out from the code, not measured.
static struct aa_label *find_attach(const struct path *path, struct aa_ns *ns, struct list_head *head, const char *name, const char **info) (domain.c:394-396).candidate, candidate_len, candidate_xattrs, conflict (domain.c:398-400).aa_dfa_leftmatch(attach->xmatch->dfa, attach->xmatch->start[AA_CLASS_XMATCH], name, &count), then perms->allow & MAY_EXEC (domain.c:431-436).if (count < candidate_len) continue; (domain.c:439-440). Tie: count == candidate_len && ret <= candidate_xattrs (domain.c:469-475). Replace: candidate_len = max(count, attach->xmatch_len) (domain.c:480-483).ns->revision changed (domain.c:443-455).strcmp(profile->base.name, name) and then wins at once (domain.c:485-491).if (!candidate || conflict) returns NULL, with *info = CONFLICTING_ATTACH_STR for a conflict (domain.c:495-499).list_add_rcu, so the newest is visited first (policy.c:164).aa_dfa_leftmatch (match.c:816-824), is_loop (match.c:720-739), WB_HISTORY_SIZE 32 (match.h:154)./proc/PID/attr/current holds label (mode) or unconfined. policy/profiles/<name>/attach shows <unknown> for profiles with an attachment. Known limitation: aa-status's "unconfined but have a profile defined" finds only path-named profiles without globs. A profile loaded after a process started does not attach to it.
cat /proc/PID/attr/current or /proc/PID/attr/apparmor/current. The kernel answers current, prev (the label saved by change_hat) and exec (a pending on-exec target) (lsm.c:835-840).foo (enforce), or unconfined (procattr.c:52-54).ps -Z prints the same label per process; the aa-exec man page shows firefox//&unconfined (unconfined) in its LABEL column (aa-exec.pod:114-118).aa-status reads current for every process with aa_getprocattr(pid, "current", &profile, &mode) (aa_status.c:427).N processes are unconfined but have a profile defined. (aa_status.c:763) compares profile names with the path of the executable, strcmp(profiles[i].name, real_exe) (aa_status.c:468-474). It misses named profiles and glob attachments./sys/kernel/security/apparmor/policy/profiles/NAME.N/attach (apparmorfs.c:2050-2051) prints <unknown> for a profile with an attachment (apparmorfs.c:1364-1367), because the parser does not send the attachment text.info="conflicting profile attachments"; under px only the kernel log has it (dmesg, journalctl -k).int aa_gettaskcon(pid_t target, char **label, char **mode);./proc/PID/attr/ and the policy directory.Next: the profile head (syn-profile-name, syn-xattrs), exec rules (syn-exec-modes, syn-named-transitions), the kernel's exec hook (k-exec), then namespaces and stacking.
px and cx deny, pix and pux fall back.Kernel behaviour on this page was worked out by reading the code at the commits above. It was not run on a kernel, except where a row says "tested", which means a regression test in the AppArmor tree asserts it.
[profile] NAME [ATTACHMENT] [xattrs=(...)] [flags=(...)] { rules }
NAME identifies the profile in rules, in /proc/PID/attr/current and in logs. ATTACHMENT is the pattern compared with the path of the executable at exec. The order attachment, xattrs=, flags= is fixed.profile is required unless the name starts with /.| Spelling | Name | Attachment |
|---|---|---|
profile foo /usr/bin/foo { } | foo | /usr/bin/foo |
/usr/bin/foo { } or profile /usr/bin/foo { } | /usr/bin/foo | copied from the name (deprecated spelling) |
profile foo { } | foo | none: not picked by the search at exec |
profile foo "/usr/bin/my app" { }.//).profile foo* { }, has no attachment variable, yet a pattern is still built from the name. Such a pattern matches no absolute path unless it starts with a wildcard: profile ** { } matches every path.Worked out from the kernel code; not measured on a kernel. The score is the number of leading characters of the executed path that the pattern consumes before the match first returns to a state it was recently in.
| Attachment | Score | Why |
|---|---|---|
/usr/bin/foo | 12 | every character is literal |
/usr/bin/fo? | 12 | ? takes one character and does not repeat |
/usr/bin/fo* | 11 | eleven literals; the * starts repeating at once |
/usr/bin/f* | 10 | ten literals |
/usr/bin/* | 10 | nine literals plus the first character the * takes |
/usr/** | 6 | five literals plus the first character the ** takes |
/usr/*/foo | 6 | as above; the same pattern scores 10 for /usr/b/foo because a glob that takes exactly one character does not repeat |
/** | 2 | one literal plus one |
An unconfined task executes /usr/bin/foo.
| Profiles loaded | Scores | Result | Basis |
|---|---|---|---|
/usr/bin/foo and /usr/bin/* | 12, 10 | the exact one, in either load order | derived |
/usr/bin/* and /usr/** | 10, 6 | /usr/bin/*; for /usr/lib/x/foo only /usr/** matches | derived |
/usr/bin/* and /usr/bin/f* | 10, 10 | conflict: no profile, the task stays unconfined | derived |
two names with the attachment /usr/bin/foo | 12, 12 | conflict; the parser rejects duplicate names, not duplicate attachments | derived |
/usr/bin/foo and /usr/bin/foo xattrs=(user.foo=hello) | 12, 12 | without the xattr on the file the plain one; with it the one that lists it | tested: xattrs_profile.sh "xattrs break path length ties" |
DIR/* xattrs=(user.foo=hello) and DIR/file | lower, higher | the exact path, with or without the xattr | tested: xattrs_profile.sh "longer paths have higher priority than xattrs" |
/usr/bin/*, /usr/bin/f* and /usr/bin/foo | 10, 10, 12 | the exact one; a higher score clears the tie in any order | derived |
The glob tie in row three is what the counting gives. It is recorded as a known discrepancy with what profile authors expect, not as a statement of the intended design.
| Task's profile | Exec rule | No attachment matches | Two attachments tie |
|---|---|---|---|
unconfined, or a profile with flags=(unconfined) | none needed | keeps its label; no record | keeps its label; an audit record is forced with info="conflicting profile attachments" |
| confined | px / cx | EACCES, info="profile transition not found" | the same record; the conflict text goes only to the kernel log |
| confined, complain mode | px / cx | learning profile <profile>//null-<path> | the same |
| confined | pix / cix | keeps the current profile, info="ix fallback" | keeps the current profile; forced record with info="conflicting profile attachments - ix fallback" |
| confined | pux / cux | the namespace's unconfined profile, info="ux fallback" | unconfined; info="conflicting profile attachments - ux fallback" is set; record not forced, written only if the rule audits |
| confined | px -> name and the name is not loaded | as the confined rows above, by fallback | not applicable |
| confined | no rule for the path | EACCES, or a learning profile in complain mode | not applicable |
ix fallback and ux fallback strings are the info value the kernel sets. Whether a record is written for them depends on the rule's auditing.aa-exec -p NAME, aa_change_onexec()) is tested before any exec rule and overrides it.Known discrepancies:
px and cx without a fallback.px the audit record cannot tell a tie from a missing profile. The kernel log can, in a rate-limited line: AppArmor: profile_transition (from profile launcher) audit info "conflicting profile attachments" dropped on missing transition. The code comments acknowledge the limitation.xattrs=(name=value ...); a bare name means any value. Values are globs.security.ima cannot be matched reliably.xattrs=.domain/attach_conditions/xattr in both the kernel and the profile's ABI, and policy/outofband in the kernel. The profile file needs abi <abi/3.0>, or newer: a file without an abi rule gets the parser's default ABI, which has no xattr attachment. If a feature is missing the parser drops the condition (warning only with --warn=rule-not-enforced) and loads the profile, which then attaches by path alone and is broader than written.profile foo xattrs=(user.a=b) { } is accepted; with no attachment, its pattern is the string foo, which no absolute path matches.When the kernel cannot build an absolute path for the executable, the exec of a confined task fails and the record carries one of:
| info | When |
|---|---|
Failed name lookup - disconnected path | the file is on a mount outside the task's mount namespace, or on an internal mount |
Failed name lookup - deleted entry | the file was deleted and the profile does not mediate deleted files |
Failed name lookup - name too long | the path does not fit the buffer |
Failed name lookup | any other naming error |
flags=(attach_disconnected) makes a disconnected name absolute; flags=(attach_disconnected.path=/prefix) also puts the prefix in front. The prefix must begin with /.execve, because that profile's settings build the name. It is not a property of the profile that might attach. Its name refers to attaching the path to a root.attach_disconnected.path=/dis, a disconnected usr/bin/foo is looked up as /dis/usr/bin/foo in the current profile's exec rules and, for px, in the search (regression test: attach_disconnected.sh).alias /usr/ -> /opt/x/, adds /opt/x/bin/foo as a second attachment of profile foo /usr/bin/foo. The original still matches./us*/bin/foo is not aliased by /usr/. See syn-alias.@{exec_path} and @{attach_path} both expand to the attachment pattern, globs included, not to the path that was executed. profile bin /usr/bin/* { @{exec_path} r, } grants read on everything /usr/bin/* matches.alias /usr/ -> /opt/x/,, @{exec_path} r, in profile foo /usr/bin/foo is compiled as /usr/bin/foo r, and /opt/x/bin/foo r,. Unlike @{profile_name} their value is not escaped.profile foo { @{attach_path} r, } fails with Failed to find declaration for: @{attach_path} (the message names the variable that was used). A child profile without an attachment does not inherit the parent's value. They cannot be used in the attachment itself.@{exec_path} as possibly a kernel variable; at this commit the parser substitutes the attachment text. See syn-builtin-variables.| Where | What it shows |
|---|---|
/proc/PID/attr/current, /proc/PID/attr/apparmor/current | label (mode), for example foo (enforce), or unconfined |
/proc/PID/attr/exec | a pending on-exec target |
/proc/PID/attr/prev | the label saved by change_hat |
ps -Z | the label per process |
aa-status | processes per profile and mode, read from current |
/sys/kernel/security/apparmor/profiles | every loaded profile with its mode |
/sys/kernel/security/apparmor/policy/profiles/<name>/attach | <unknown> for a profile with an attachment, the profile name otherwise; the parser does not send the attachment text |
operation="exec", info= and name= fields are certain.| Message | When |
|---|---|
Profile names must begin with a '/', namespace or keyword 'profile' or 'hat'. | a name without the profile keyword that is not a path |
Profile attachment must begin with a '/' or variable. | the attachment is neither a path nor a variable |
syntax error, unexpected TOK_CONDLISTID, expecting TOK_OPEN | flags= written before xattrs= |
profile id: invalid conditional group peer=() | peer=(...) after the attachment; any other name gives syntax error, unexpected TOK_CONDID, expecting TOK_OPEN |
hat profiles can't use xattrs matches | xattrs= on a hat |
The use of file paths as profile names is deprecated. See man apparmor.d for more information | a path as the profile name; warning class deprecated, shown only with --warn=deprecated |
xattr attachment conditional ignored | warning, shown only with --warn=rule-not-enforced or --warn=all: the kernel or the profile's ABI lacks xattr attachment (a file with no abi rule is in that case); the profile loads without the condition |
attach_disconnected path must begin with a / | attach_disconnected.path= with a relative path |
Failed to find declaration for: @{attach_path} | @{attach_path} in a profile without an attachment (@{exec_path} in the message when that variable was used) |
Invalid profile name 'NAME' - bad regular expression | the attachment or name is not a valid pattern |
| Text | Where | Meaning |
|---|---|---|
conflicting profile attachments | audit info= | two best matches tied; unconfined exec |
conflicting profile attachments - ix fallback | audit info= | tie under pix / cix; the task kept its profile |
conflicting profile attachments - ux fallback | audit info= | tie under pux / cux; record not forced, written only if the rule audits |
profile transition not found | audit info= | px / cx found no profile, or found a tie |
ix fallback, ux fallback | audit info= | no match; the fallback was used |
no new privs | audit info=, error EPERM | the new label is not a subset under no-new-privs |
AppArmor: profile_transition (from profile P) audit info "..." dropped on missing transition | kernel log, rate-limited | the info text replaced by profile transition not found |
AppArmor: find_attach (from profile P) audit info "..." dropped | kernel log, rate-limited | an earlier info text overwritten during a fallback |
Parser, in call order:
| Function | Where | Role |
|---|---|---|
profile_base | parser/parser_yacc.y:391-459 | $1 name, $2 attachment, condition list, flags |
process_profile_variables | parser/parser_variable.c:137-178 | expands variables; copies a path name into prof->attachment (:58-78); defines @{attach_path} and @{exec_path} |
replace_profile_aliases | parser/parser_alias.c:200-208 | process_name (:159-191) pushes alternates on prof->altnames |
process_profile_name_xmatch | parser/parser_regex.c:478-623 | one AA_MAY_EXEC rule per name, xattr tail (:548-607), create_dfablob; no DFA only for a Basic pattern with no altname, attachment or xattrs (:511) |
min_match_len | parser/libapparmor_re/expr-tree.h:343, aare_rules.cc:162-177 | the value written as xmatch_len |
sd_serialize_profile | parser/parser_interface.c:495-501 | writes the aadfa blob and the u32 xmatch_len after the name; "xattrs" at :458-478 |
Kernel:
| Function | Where | Role |
|---|---|---|
apparmor_bprm_creds_for_exec | linux:security/apparmor/domain.c:985-1105 | the exec hook; on-exec first, else one profile_transition per profile of the label |
profile_transition | domain.c:665-796 | names the path with the current profile's path flags; find_attach if unconfined, else the exec rule and x_to_label |
find_attach | domain.c:394-506 | the search: candidate, candidate_len, candidate_xattrs, conflict |
aa_dfa_leftmatch, is_loop | linux:security/apparmor/match.c:816-824, 719-739 | the count, with a history of WB_HISTORY_SIZE (32) states |
aa_xattrs_match | domain.c:313-375 | number of matched xattrs or a negative error; runs outside the RCU read lock |
x_to_label, x_table_lookup | domain.c:574-663, 523-559 | AA_X_NAME searches (children with AA_X_CHILD), AA_X_TABLE looks up by name, then the ix / ux fallbacks |
aa_path_name | linux:security/apparmor/path.c:201-221 | builds the name and sets the Failed name lookup strings |
unpack_pdb into struct aa_attachment | linux:security/apparmor/policy_unpack.c:1174-1196, include/policy.h:213-219 | xmatch, xmatch_len, xattrs[] |
find_attach: profile_transition with profile->ns->base.profiles (domain.c:698-699) and x_to_label with profile->base.profiles or ns->base.profiles (:603-611). Profiles are added at the list head (policy.c:164), so the newest is visited first.strcmp(profile->base.name, name) and then wins at once (domain.c:485-492). With the current parser every profile that has an attachment has a DFA, so this branch is for blobs from older parsers."attach" string (policy_unpack.c:1172), which is why apparmorfs prints <unknown> (apparmorfs.c:1358-1368).These are on the AppArmor bug sweep list; none is presented as intended design.
xmatch_len stops at the first *, **, ? or [^x]. Observed with apparmor_parser 6.0.0~alpha2 (836052d21): /usr/bin/?oo 10, /usr/bin/[^a]oo 10, /usr/bin/[ab]oo 12, /usr/bin/*foo 9. The cause is NotCharSetNode::contains_oob() (parser/libapparmor_re/expr-tree.h:746-754), which reads as inverted next to its comment.find_attach stores candidate_len = max(count, attach->xmatch_len) (domain.c:481) but compares later profiles by their raw count (:439-440, :469). With the lengths the parser emits today xmatch_len does not exceed the count of a matching path, so the result does not change; the asymmetry is latent.find_attach (domain.c:385-388) says exact matches are preferred and then the greatest xmatch_len. The code prefers the greatest left-match count.conflicting profile attachments - ux fallback sits behind a proxy comparison (domain.c:730-737) that a ux fallback does not appear to satisfy; not confirmed by a run.find_attach still calls it the search "for unconfined processes" (domain.c:378); px and cx use it too.dbus rules are compiled into the profile, but the kernel has no D-Bus hook. The bus daemon asks the kernel what the profile allows and enforces the answer itself. This deck is for application developers, administrators and security researchers.
demo of the runs. The others allow Hello, GetId, RequestName, ReleaseName, AddMatch and RemoveMatch on the bus daemon itself, owning org.demo.client, and receiving the signal Changed. Without a send rule for Hello a program cannot use the bus at all.aa-exec -p demo -- busctl --system call org.freedesktop.login1 /org/freedesktop/login1 org.freedesktop.login1.Manager ListSessions; it printed Call failed: Access denied and exited 1. org.freedesktop.login1 is systemd-logind, which is unconfined on the guest.dbus-send shows the daemon's full error: Error org.freedesktop.DBus.Error.AccessDenied: An AppArmor policy prevents this sender from sending this message to this recipient; type="method_call", sender=":1.61" (uid=0 pid=1701 comm="dbus-send --system --print-reply --dest=org.freede" label="demo (enforce)") interface="org.freedesktop.login1.Manager" member="ListSessions" error name="(unset)" requested_reply="0" destination="org.freedesktop.login1" (uid=0 pid=764 comm="/usr/lib/systemd/systemd-logind" label="unconfined")./sys/kernel/security/apparmor/.access (apparmorfs.c:859-898), the feature file features/dbus/mask (apparmorfs.c:2662-2664) and a class name for records. No hook looks at D-Bus messages./run/dbus/system_bus_socket rw, and a unix rule. See Unix socket rules.bus/apparmor.c, named by function) and from the runs; they have no pinned link.The daemon reads the peer's label from the socket when a program connects. For each check it writes a query to /sys/kernel/security/apparmor/.access and reads back allow, deny, audit and quiet. libapparmor wraps this as aa_query_label().
.access by a test script as root.aa_getpeercon() on the connection's socket once, when the connection is set up (bus_apparmor_init_connection_confinement). int aa_getpeercon(int fd, char **label, char **mode); reads the socket option SO_PEERSEC and splits demo (enforce) into the label and the mode (kernel.c:1300-1320, kernel.c:1363-1400).int aa_query_label(uint32_t mask, char *query, size_t size, int *allowed, int *audited); (kernel.c:1425-1510). The caller leaves room at the start of query; the function puts label and a zero byte there, opens .access, writes the query once and reads 67 bytes.allow 0x%08x, deny 0x%08x, audit 0x%08x, quiet 0x%08x (apparmorfs.c:1068-1070). Permission bits: send 0x2, receive 0x4, eavesdrop 0x20, bind 0x40 (apparmor.h:60-65). For demo's own rule the reply was allow 0x00008002; bit 0x8000 is added by the kernel to every permission set of an older-format table and is not a dbus permission.allow and not in deny; to be logged when the query is refused and the bit is not in quiet, or allowed and the bit is in audit (kernel.c:1498-1501)..access has mode 0666 (apparmorfs.c:2704). The kernel finds the label in the namespace of the writing task, starts from "everything allowed" and lets each profile of the label narrow the answer (apparmorfs.c:1022-1071). A label the kernel does not know makes the write fail with ENOENT; the daemon then refuses the message and logs info=.features/query/label/perms contains allow deny audit quiet.bus/apparmor.c, named by function) and from the runs; they have no pinned link.send is asked of the sender's profile and receive of the recipient's, each with the other side's label as the peer. An unconfined side is not asked, and neither is anyone for a reply that was requested.
org.demo was owned by dbus-test-tool echo --system --name=org.demo (package dbus-tests) running under the profile demo-service; it answers every method call with an empty reply.aa-exec -p demo -- busctl --system call org.demo /org/demo org.demo.Api Status returned with exit status 0 and no record. The same call with Reset printed Call failed: Access denied. The record on the slide is that denial, without its prefix audit: type=1107 audit(1794836373.212:170): pid=755 uid=993 auid=4294967295 ses=4294967295 subj=unconfined msg=' and broken over three lines.name= is the sender's unique name (:1.14); in a send record it is the destination.busctl calling Status on org.demo was refused as well, by the service's rule, which names peer=(label=demo); the record has mask="receive" label="demo-service" peer_label="unconfined". The unconfined sender was not asked about; the confined recipient was.demo has no receive rule for it and demo-service no send rule, and the Status call still returned. dbus-daemon allows a requested reply, one that the recipient had asked for, without a query (bus_apparmor_allows_send, the requested_reply branch); an unrequested reply is queried like any message, and method returns and errors are not logged.dbus-monitor under demo received the signal Changed and not Other; the record was operation="dbus_signal" ... mask="receive" ... label="demo" peer_pid=1551 peer_label="unconfined".org.freedesktop.DBus), the peer label is the daemon's own label, unconfined on the guest. When a message would start a service, only the sender is asked.ALLOWED: see the reference below.bus/apparmor.c, named by function) and from the runs; they have no pinned link.A bind query carries the bus and the name; an eavesdrop query only the bus. In a message query the name is the destination as the caller wrote it, so peer=(name=org.demo) does not match a call addressed to :1.11.
... stands: each of the first three was aa-exec -p demo -- busctl --system call org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus ... with RequestName su NAME 0 or AddMatch s "eavesdrop=true,type='signal',interface='org.demo.Api'". The aa-exec -p demo -- in front matters: the same busctl call to org.demo from an unconfined shell was refused, by the service's profile (the scene "One message, two questions"). Records are shown without their prefix and without apparmor="DENIED".u 1 is the bus daemon's answer "you are now the primary owner". The guest's bus policy allowed root to own names starting with org.demo; dbus-daemon asks AppArmor before it looks at that policy (bus/services.c, before bus_client_policy_check_can_own).dbus bind bus=system name=org.demo.client,. The feature file calls this permission acquire; the rule and the record say bind.operation="dbus_eavesdrop" bus="system" mask="eavesdrop" pid=1540 label="demo". dbus-daemon asks this for a match rule with eavesdrop=true and for BecomeMonitor. dbus-monitor tries BecomeMonitor first, then an eavesdropping match, then a plain match; under demo that left one send denial (interface org.freedesktop.DBus.Monitoring) and one eavesdrop denial before it received anything.org.freedesktop.DBus when the message has none. Seen: the call addressed to :1.11 was refused with the record on the slide, although :1.11 was the connection that owned org.demo.deny rule with peer=(name=org.demo) does not cover a call addressed to the unique name. This was derived from the source, not run. peer=(label=...) does not depend on how the caller addressed the message.bus/apparmor.c, named by function) and from the runs; they have no pinned link.A D-Bus record has type=1107 and the bus daemon's pid; the AppArmor fields are inside msg='...'. mask is the permission asked, label the profile asked, peer_label the other side. A session bus writes the same text to the system log.
peer_label; in the kernel log it is two lines, because dbus-daemon ends its text with a newline and the audit library appends exe="/usr/bin/dbus-daemon" sauid=993 hostname=? addr=? terminal=?' after it. journalctl -k | grep apparmor= shows only the first line. There are two spaces after operation="dbus_method_call"; the slide breaks the line there.type=1107 is USER_AVC, a record sent by a user-space program. The kernel's own AppArmor records are type=1400: see Reading a denial. With the audit daemon running, both kinds go to /var/log/audit/audit.log; without it, to the kernel log (dmesg, journalctl -k). No audit daemon ran on the guests, so the audit.log form of this record was not seen.msg=: pid=755 uid=993 subj=unconfined describe the bus daemon (user messagebus, its own label). Inside msg=: pid=1671 is the process of the profile that was asked and peer_pid=764 the other side; peer_pid is missing when the peer is the bus daemon itself.operation is dbus_ and the message type (dbus_method_call, dbus_signal), or dbus_bind, or dbus_eavesdrop. mask is one of send, receive, bind, eavesdrop.name: in a send record the destination as the caller wrote it, in a receive record the sender's unique name, in a bind record the name asked for.peer=(label=unconfined) from peer_label; peer=(name=org.freedesktop.login1) from name is the other choice. Neither is a recommendation to add it.apparmor="ALLOWED" appears for a profile in complain mode. Seen under demo-complain: the login call, the name and the eavesdropping match all succeeded, each with an ALLOWED record.tester with dbus-run-session logged Nov 16 13:40:24 aamap dbus-daemon[1687]: apparmor="DENIED" operation="dbus_method_call" bus="session" path="/org/freedesktop/DBus" interface="org.freedesktop.DBus" member="Hello" mask="send" name="org.freedesktop.DBus" pid=1688 label="demo" peer_label="unconfined" in the journal and no type 1107 record. The system bus daemon keeps the capability to write audit records (CapEff: 0000000020000000); a user's daemon does not have it and uses syslog.apparmor="DENIED" operation="dbus_method_call" bus="system" path="/" interface="org.freedesktop.DBus" member="ListNames" mask="send" name="org.freedesktop.DBus" label="demo-dbus" peer_label="unconfined" exe="/usr/bin/dbus-broker" sauid=0 hostname=? addr=? terminal=?': one line, one space after operation, no pid=.bus/apparmor.c, named by function) and from the runs; they have no pinned link.dbus-daemon mediates only when AppArmor is enabled and features/dbus/mask exists, which mainline has from 6.17. Otherwise everything is delivered and nothing is logged. Its Features property lists AppArmor when it mediates; <apparmor mode="required"/> makes it refuse to start without.
bus_apparmor_pre_init, bus_apparmor_full_init): it mediates if it was built with AppArmor, aa_is_enabled() is true and it can open features/dbus/mask under apparmorfs. It does not look at the file's content. Debian and Ubuntu build it with AppArmor and the audit library on Linux.dbus feature entry from 6.17 (apparmorfs.c:2662-2664, apparmorfs.c:2697); Ubuntu kernels have had it since at least 6.8. See Upstream and Ubuntu kernels.features/dbus/mask; Features printed the three entries on the slide; under the profile demo every attempt of this deck succeeded with no record: the call to the login service, a Reset call to the confined service, owning org.demo.other, the eavesdropping match and both signals.Warning from profile demo (demo.sd): dbus rules not enforced with --warn=all or --warn=rule-not-enforced (dbus.cc:203, dbus.cc:220-223). See Kernel features and the policy ABI.Features printed as 4 "ActivatableServicesChanged" "AppArmor" "HeaderFiltering" "SystemdActivation", and the journal had [system] AppArmor D-Bus mediation is enabled.<apparmor mode="enabled"/> (the default: mediate if possible), "disabled" or "required". With required and no mediation dbus-daemon fails to start with AppArmor mediation required but not present. The configuration files shipped on the guests have no such element. The required case was read in the source, not run./sys/module/apparmor/parameters/enabled and requires the words acquire, send and receive in features/dbus/mask; without them it prints Kernel is missing AppArmor DBus support. and continues without mediation.bus/apparmor.c, named by function) and from the runs; they have no pinned link.On mainline 6.17 and later the kernel leaves a profile out of dbus queries unless it mediates the v9 network class, which profiles compiled under abi/3.0 or abi/4.0 do not. Their dbus rules load and are not consulted. Ubuntu kernels consult them.
network_v9 unix support are not consulted, so profiles that pin abi/3.0 or abi/4.0 get no dbus mediation. It is on the map's bug list under that title; this deck's runs are the first to reproduce it.network_v9/af_unix (parser_regex.c:1424-1432); the dbus marker and the dbus rules are added whenever both have dbus (parser_regex.c:1406-1408). The tree's abi/3.0 and abi/4.0 list dbus and no network_v9.demo and demo-abi4 differ only in the abi line.| Profile | Compiled by | Reply to "send ListSessions to login1" | The call |
|---|---|---|---|
demo, abi <abi/5.0>, | the tree's parser | allow 0x00000000 | Access denied, record |
demo-abi4, abi <abi/4.0>, | the tree's parser | allow 0xffffffff ... quiet 0xffffffff | answered, no record |
demo-abi3, abi <abi/3.0>, | the tree's parser | allow 0xffffffff | answered, no record |
abi <abi/4.0>, | Debian's parser 5.0.2 | allow 0xffffffff | answered, no record |
| no abi rule | the tree's parser, no parser.conf | allow 0xffffffff | answered, no record |
| no abi rule | Debian's parser with its parser.conf | allow 0x00000000 | Access denied, record |
org.demo.other, registered an eavesdropping match and received both signals, with no record.policy-features; that default has dbus and no network_v9 (default_features.c:127-136). Debian's parser.conf points to a file that has both.demo-abi4 on Debian sid: nothing by default. With --warn=all: a note that an included abstraction declares another abi, and three times downgrading extended network unix socket rule to generic network rule. Nothing about dbus.abi <abi/5.0>,. Profiles written for the 3.x and 4.x releases pin abi/3.0 and abi/4.0: the Debian 13 guest ships 97 profiles with abi <abi/4.0>,, four of them with dbus rules or dbus abstractions; the Ubuntu 26.04 guest ships three with abi <abi/3.0>,.allow 0xffffffff to a dbus question about a confined label means the profile was skipped. A script that does it is in the research notes of this deck.The enforcement point is the bus daemon. It takes the label at connect time, skips peers labelled unconfined, applies complain mode itself and believes the kernel's reply. .access has mode 0666. A name is a claim; peer=(label=...) names the confinement.
aa_getpeercon() when the connection is set up and uses it for every later check (bus_apparmor_init_connection_confinement; kernel.c:1363-1400). Derived, not run: a program that changes profile after connecting is still asked about under the label of the connection.unconfined, or when there is no mode and the label is the string unconfined (is_unconfined). The kernel does the same on its side: an unconfined profile leaves the answer at "everything allowed" (apparmorfs.c:867-868).allow 0xffffffff deny 0x00000000 audit 0x00000000 quiet 0xffffffff for every dbus question about a profile compiled under abi/3.0 or abi/4.0, the same reply as for unconfined.allow 0x00000000 for the login call under demo-complain); the daemon turns the refusal into ALLOWED because the mode string that came with the label is complain..access) is a refusal with info= in the record, by the source; not run..access is -rw-rw-rw- 1 root root on the guests (apparmorfs.c:2704). The kernel code has no check of the caller before it answers a permission query (apparmorfs.c:1204-1240); a confined task needs a file rule for the path. The answer reveals what a label may do, for any class the query names.demo//&demo-abi4, got ENOENT (seen). For a live stack the kernel intersects the profiles' answers (apparmorfs.c:1056-1065); not run.peer=(name=...) is as strong as the bind rules of every other profile on the bus, and unconfined programs are not bound by them. With dbus-daemon the name is also the destination as the caller wrote it (the scene "Owning a name, and listening in").bus/apparmor.c, named by function) and from the runs; they have no pinned link.Check that the bus's Features property lists AppArmor, that features/dbus/mask exists, and, on a mainline kernel, that the profile is compiled under abi/5.0. Roads: the rule syntax, reading records, upstream and Ubuntu kernels, the abi rule, kernel features, the query interface and unix socket rules.
Features property lists AppArmor), the kernel has the dbus feature entry, and the kernel consults the profile, which on mainline 6.17 and later needs a profile compiled with the v9 network class (abi <abi/5.0>,). A profile with no abi rule is compiled with that class only if policy-features in parser.conf names a feature file that has network_v9; see the scene "Old ABI, new kernel: every answer is yes".busctl --system get-property org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus Features (seen: as 4 "ActivatableServicesChanged" "AppArmor" "HeaderFiltering" "SystemdActivation" when the daemon mediates); cat /sys/kernel/security/apparmor/features/dbus/mask (seen: acquire send receive); the abi line of the profile, and uname -r to know which kernel answers. For a session bus use busctl --user.Basis of the statements on this page: "seen" means it happened on a running guest: Debian sid (kernel 7.3.4, a distribution kernel without Ubuntu's AppArmor patches, dbus-daemon 1.16.4), Ubuntu 26.04 (kernel 7.0.0-43, dbus-daemon 1.16.2) or Debian 13 (kernel 6.12.116, dbus-daemon 1.16.2), under profiles compiled by the parser of the AppArmor commit 836052d21 unless another parser is named. "source" means the code was read and not run: the kernel tree the map describes, the AppArmor tree, the Ubuntu kernel tags 6.8 to 7.3, and the source packages dbus 1.16.4-1 and dbus-broker 37-5 and 37-5ubuntu5. The bus daemons are in neither tree the map describes, so statements about them carry no pinned link. Records are quoted without the prefix audit: type=1107 audit(SECONDS:SERIAL): pid=755 uid=993 auid=4294967295 ses=4294967295 subj=unconfined msg='. The rule syntax is in D-Bus rules.
All three must hold.
| Condition | How to check | If not |
|---|---|---|
| the bus daemon mediates | busctl --system get-property org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus Features lists AppArmor; the journal has AppArmor D-Bus mediation is enabled | every message is delivered, nothing is logged |
| the kernel has the dbus feature entry | /sys/kernel/security/apparmor/features/dbus/mask exists (acquire send receive) | the daemon does not mediate; the parser leaves dbus rules out (dbus rules not enforced, only with --warn=rule-not-enforced or --warn=all) |
| the kernel consults the profile | a dbus question about the label is not answered allow 0xffffffff | every question about that profile is answered "allowed", nothing is logged |
| Kernel | dbus feature entry | Profiles consulted in a dbus query |
|---|---|---|
| mainline before 6.17 (seen: Debian 13, 6.12) | no | none: no mediation |
| mainline 6.17 and later (seen: Debian sid, 7.3) | yes | only profiles that mediate the v9 network class |
| Ubuntu 6.8 to 7.3 (seen: Ubuntu 26.04, 7.0) | yes | every profile with the dbus class |
| dbus-daemon | Mediates |
|---|---|
| built without AppArmor | no |
AppArmor disabled in the kernel, or features/dbus/mask cannot be opened | no |
<apparmor mode="disabled"/> in the bus configuration | no |
<apparmor mode="enabled"/> or no such element (the default) | if the two conditions above allow |
<apparmor mode="required"/> | yes, or it fails to start: AppArmor mediation required but not present |
Source. The decision is made once, at startup. dbus-broker's launcher makes the same decision from /sys/module/apparmor/parameters/enabled and the words acquire, send and receive in features/dbus/mask, and prints Kernel is missing AppArmor DBus support. or AppArmor required, but not supported. Exiting.
| Event | Permission | Label asked | Fields in the question | Not asked when |
|---|---|---|---|---|
| a message is to be delivered | send | the sender's | bus, destination name, recipient's label, path, interface, member | the sender is unconfined; the message is a requested reply |
| the same message | receive | the recipient's | bus, sender's unique name, sender's label, path, interface, member | the recipient is unconfined; requested reply; the message would start a service |
RequestName | bind | the caller's | bus, name | the caller is unconfined |
AddMatch with eavesdrop=true, BecomeMonitor | eavesdrop | the caller's | bus | the caller is unconfined |
aa_getpeercon), with its mode.org.freedesktop.DBus when there is none. When the recipient is the bus daemon, the recipient's label is the daemon's own.ALLOWED..access is missing) refuses the message; the record has info=. Source.Debian sid; Ubuntu 26.04 gave the same results.
| Attempt | Result | Record |
|---|---|---|
demo calls org.demo Status | empty reply | none |
demo calls org.demo Reset | Call failed: Access denied | operation="dbus_method_call" mask="receive" label="demo-service" peer_label="demo" |
unconfined caller, org.demo Status | denied | mask="receive" label="demo-service" peer_label="unconfined" |
demo calls :1.11, the owner of org.demo, Status | denied | mask="send" name=":1.11" label="demo" peer_label="demo-service" |
demo calls login1 ListSessions | denied | mask="send" name="org.freedesktop.login1" label="demo" peer_label="unconfined" |
demo RequestName org.demo.client | u 1 | none |
demo RequestName org.demo.other | denied | operation="dbus_bind" name="org.demo.other" mask="bind" label="demo" |
demo AddMatch "eavesdrop=true,..." | denied | operation="dbus_eavesdrop" mask="eavesdrop" label="demo" |
signal Changed to a dbus-monitor under demo | received | none |
signal Other to the same | not received | operation="dbus_signal" mask="receive" label="demo" peer_label="unconfined" |
demo-complain: login1, org.demo.other, eavesdrop | all succeed | the same records with apparmor="ALLOWED" |
The rules behind them:
# profile demo
dbus send bus=system path=/org/freedesktop/DBus interface=org.freedesktop.DBus
member={Hello,GetId,RequestName,ReleaseName,AddMatch,RemoveMatch}
peer=(name=org.freedesktop.DBus),
dbus send bus=system path=/org/demo interface=org.demo.Api peer=(name=org.demo),
dbus bind bus=system name=org.demo.client,
dbus receive bus=system path=/org/demo interface=org.demo.Api member=Changed,
# profile demo-service
dbus send bus=system path=/org/freedesktop/DBus interface=org.freedesktop.DBus
peer=(name=org.freedesktop.DBus),
dbus bind bus=system name=org.demo,
dbus receive bus=system path=/org/demo interface=org.demo.Api member=Status peer=(label=demo),| Refusal | D-Bus error org.freedesktop.DBus.Error.AccessDenied with the text |
|---|---|
| a message | An AppArmor policy prevents this sender from sending this message to this recipient; type="method_call", sender=":1.61" (uid=0 pid=1701 comm="..." label="demo (enforce)") interface="..." member="..." error name="(unset)" requested_reply="0" destination="org.freedesktop.login1" (uid=0 pid=764 comm="..." label="unconfined") (seen; the same text when the recipient's profile refuses) |
| a name | Connection "..." is not allowed to own the service "..." due to AppArmor policy (source) |
| eavesdropping | Connection "..." is not allowed to eavesdrop due to AppArmor policy (source) |
busctl prints only Call failed: Access denied.
| Field | Meaning | Rule part |
|---|---|---|
type=1107 | USER_AVC: sent by a user-space program | |
pid=, uid=, subj= before msg= | the bus daemon's pid, user and own label | |
apparmor= | DENIED; ALLOWED for complain mode or an audited allowed access | |
operation= | dbus_method_call, dbus_signal, dbus_bind, dbus_eavesdrop | the kind of rule |
bus= | system or session | bus= |
path=, interface=, member= | the message's header fields; absent when the message has none | path=, interface=, member= |
mask= | send, receive, bind or eavesdrop | the permission |
name= | send: the destination as written; receive: the sender's unique name; bind: the name asked for | peer=(name=...); name= in a bind rule |
pid= inside msg= | the process of the label that was asked | |
label= | the label that was asked | the profile to edit |
peer_pid=, peer_label= | the other side; peer_pid is absent when it is the bus daemon | peer=(label=...) |
info=, peer_info= | the error text when the question itself failed | |
exe=, sauid=, hostname=, addr=, terminal= | added by the audit library |
exe="/usr/bin/dbus-daemon" sauid=993 hostname=? addr=? terminal=?'. The first line has no closing quote.dbus-daemon[PID]: apparmor="DENIED" ... to the system log and no type 1107 record.audit; method returns and errors; anything when the daemon does not mediate or the kernel skips the profile.quiet mask has the bit (a deny rule); an allowed access is logged when the audit mask has it. Not run.Seen on Debian sid (kernel 7.3.4). The six profiles have the same dbus rules.
| Profile | abi rule | Compiled by | Reply to a dbus question | login1 call, org.demo.other, eavesdrop, signal Other |
|---|---|---|---|---|
demo | abi <abi/5.0>, | tree parser | by the rules | refused, logged |
demo-abi4 | abi <abi/4.0>, | tree parser | allow 0xffffffff deny 0x00000000 audit 0x00000000 quiet 0xffffffff | all succeed, no record |
demo-abi3 | abi <abi/3.0>, | tree parser | the same | all succeed, no record |
demo-distro4 | abi <abi/4.0>, | Debian's parser 5.0.2 | the same | all succeed, no record |
demo-noabi | none | tree parser, no parser.conf | the same | all succeed, no record |
demo-distro-noabi | none | Debian's parser, parser.conf with policy-features= | by the rules | refused, logged |
network_v9 unix support are not consulted, so profiles that pin abi/3.0 or abi/4.0 get no dbus mediation.dbus and without network_v9 in the AppArmor tree: abi/3.0, abi/4.0, abi/4.0-ip, abi/kernel-5.4-outoftree-network, and the parser's built-in default for profiles without an abi rule (default_features.c:127-136). With it: abi/5.0, abi/5.0-interface.network_v9/af_unix (parser_regex.c:1424-1432). It printed nothing about dbus for demo-abi4, with or without --warn=all.abi <abi/4.0>,.write: "label" 00 LABEL 00 20 BUS 00 NAME 00 PEERLABEL 00 PATH 00 INTERFACE 00 MEMBER send, receive
"label" 00 LABEL 00 20 BUS 00 NAME bind
"label" 00 LABEL 00 20 BUS eavesdrop
read: allow 0x%08x\ndeny 0x%08x\naudit 0x%08x\nquiet 0x%08x\n
/sys/kernel/security/apparmor/.access, mode 0666, one write and one read per open (apparmorfs.c:1204-1240, apparmorfs.c:1022-1071). 20 is the dbus class, 32.int aa_query_label(uint32_t mask, char *query, size_t size, int *allowed, int *audited); (kernel.c:1425-1510). The first AA_QUERY_CMD_LABEL_SIZE bytes of query are overwritten with label and a zero byte.0x2, receive 0x4, eavesdrop 0x20, bind 0x40. Bit 0x8000 in a reply is added by the kernel and is not a dbus permission.allowed: every asked bit is in allow and none in deny. audited: refused and not in quiet, or allowed and in audit (kernel.c:1498-1501).ENOENT the kernel does not know the label; EPROTONOSUPPORT no .access or an unexpected reply; EPROTO a short write or read.demo, send Status to org.demo: allow 0x00008002; send ListSessions to login1: allow 0x00000000; bind org.demo.client: allow 0x00008040; demo-service, receive Status from label demo: allow 0x00008004, from unconfined: allow 0x00000000; label unconfined: allow 0xffffffff ... quiet 0xffffffff; an unknown label and the unused stack demo//&demo-abi4: ENOENT.Source only (37-5 as packaged by Debian and Ubuntu 26.04, 37-5ubuntu5 of Ubuntu 26.10); not run for this deck.
aa_query_label.method= where dbus-daemon has member= and no name=; 37-5ubuntu5 writes member=, name=, label= and peer_label=. A record of 37-5ubuntu5 seen on an Ubuntu 26.10 guest: apparmor="DENIED" operation="dbus_method_call" bus="system" path="/" interface="org.freedesktop.DBus" member="ListNames" mask="send" name="org.freedesktop.DBus" label="demo-dbus" peer_label="unconfined" exe="/usr/bin/dbus-broker" sauid=0 hostname=? addr=? terminal=?'./var/log/audit/audit.log; no guest ran the audit daemon.convert_aaregex_to_pcre() (parser/parser_regex.c:118) rewrites one AppArmor glob as a regular expression string. It runs last in the front end, once per pattern.
pattern_t convert_aaregex_to_pcre(const char *aare, int anchor, int glob, std::string& pcre, int *first_re_pos) (parser_regex.c:118-119). "AARE" is the AppArmor regular expression syntax of profiles: the globs *, **, ?, [ ] and { }. The name says PCRE; the output is the smaller regular expression syntax that the backend's own parser reads.post_process_profile adds implied rules, expands variables, applies aliases, merges rules and then calls process_profile_rules (parser_policy.c:127-165), which converts the attachment and every rule and hands the strings to the backend (parser_regex.c:1215-1283).process_dfa_entry (parser_regex.c:648-688).demo3.sd):abi <abi/5.0>,
include <tunables/global>
profile demo /usr/bin/demo {
/etc/demo/** r,
audit deny @{HOME}/.ssh/** rw,
/usr/bin/[a-z]* ix,
}
-Q -K -D rule-exprs (nothing loaded into a kernel, no cache) and the tree's abi/5.0 feature set. Each aare: line is printed by the conversion itself.Before the conversion: processunquoted (scanner), process_variables (post-processing) and filter_slashes (parser/parser_regex.c:61-96). A leading // survives.
processunquoted decodes escapes and keeps a backslash before a decoded * ? [ ] { } ^ , \ (parser_misc.c:468-509); see The lexer.block_rules::process_variables expands the name and the link name of every entry and calls expand_variables of every rule object (block_rules.cc:393-416). A variable with several values becomes {a,b}. The -d dump shows the entry at that point: ({/home//*,/root}/.ssh/**); tunables/home defines @{HOME} as @{HOMEDIRS}/*/ /root/ and @{HOMEDIRS} as /home/.filter_slashes (parser_regex.c:61-96) rewrites the string in place: a / that follows a / is dropped; when the string starts with exactly two slashes they are both kept ("special case for linux // namespace", lines 70-74). A single trailing slash is kept, although the comment above the function says trailing slashes are filtered.filter_slashes(entry->name) unless the entry is a change_profile rule, then the conversion (parser_regex.c:658-660); the same for the link target (parser_regex.c:699-701).filter_slashes is also applied to the attachment (parser_variable.c:76), mount points and devices (mount.cc:649-653), D-Bus paths (dbus.cc:190) and unix socket addresses (af_unix.cc:174-178).-D rule-exprs prints after aare:; //etc/x and /etc//demo///conf are from a profile written for this deck.-Q -K -D rule-exprs (nothing loaded into a kernel, no cache) and the tree's abi/5.0 feature set. Each aare: line is printed by the conversion itself./, so the rule starts with // and never matches".bEscape, ingrouping and incharclass (parser/parser_regex.c:132-134) are all the state there is. {/home/*,/root}/.ssh/** becomes (/home/[^/\x00]*|/root)/\.ssh/[^/\x00][^\x00]*.
bool bEscape, int ingrouping, int incharclass and int grouping_count[MAX_ALT_DEPTH] (parser_regex.c:132-135). The loop is while (error == error_type::no_error && *sptr) with one switch (*sptr) (parser_regex.c:149-405); bEscape is cleared at the end of every pass except the one that reads the backslash.\ (parser_regex.c:152-168), * (parser_regex.c:169-229), ? (parser_regex.c:231-254), [ and ] (parser_regex.c:256-280), { and } (parser_regex.c:282-330), , (parser_regex.c:332-355), ^ and $ (parser_regex.c:358-366), ., +, |, (, ) and every other character (parser_regex.c:374-402)./ and the run of stars is followed by / or the end of the pattern, [^/\x00] is written first (parser_regex.c:178-205). The test looks only for / or the end. A star that is followed by , or } inside a group does not get it, so {/home/*,/root}/.ssh/** also describes /home//.ssh/...; a path with an empty component does not reach the matcher from the kernel, so nothing more is matched in practice (derived).aare: {/home/*,/root}/.ssh/** -> (/home/[^/\x00]*|/root)/\.ssh/[^/\x00][^\x00]*.-Q -K -D rule-exprs (nothing loaded into a kernel, no cache) and the tree's abi/5.0 feature set. Each aare: line is printed by the conversion itself.. + | ( ) are always escaped, ^ $ outside a class. \* \[ \] \{ \} stay escaped; \? and \, become ? and ,.
., +, |, (, ) (parser_regex.c:374-380). Escaped outside a character class and copied inside one: ^ and $ (parser_regex.c:358-366).\* (parser_regex.c:170-177), \[ and \] (parser_regex.c:257-260, parser_regex.c:269-272), \{ and \} (parser_regex.c:283-286, parser_regex.c:307-310). \\ is written as \\ (parser_regex.c:152-168).\? is written as ? (parser_regex.c:232-238); \, as , outside a class and as \, inside one (parser_regex.c:333-345).str_escseq accepts what follows as an escape sequence (\x00, \000, \d000 and the letter escapes), the sequence is copied with its backslash for the backend to decode; otherwise the backslash is dropped and, with warnings of class format enabled, the parser prints Character q was quotedunnecessarily, dropped preceding quote ('\') character.* ? [ ] { } ^ , \ (see The lexer).-Q -K -D rule-exprs (nothing loaded into a kernel, no cache) and the tree's abi/5.0 feature set. Each aare: line is printed by the conversion itself.\^ loses its escape, and * or ? inside [...] are expanded".{a,b} becomes (a|b), nested fewer than 50 deep, with at least one comma per group. [...] is copied; a negated class written in a profile can match /.
{: ingrouping++; at 50 (MAX_ALT_DEPTH, parser_regex.c:122) the error Regex grouping error: Exceeded maximum nesting of {}; otherwise the comma count of the new level is cleared and ( is written. So 49 levels are the most that convert: a pattern nested 49 deep compiles and one nested 50 deep is refused (both run with the tree's parser) (parser_regex.c:282-304)., inside a group and outside a class: the count of the current level goes up and | is written; elsewhere the comma is copied (parser_regex.c:346-353).}: a count of zero is the error Regex grouping error: Invalid number of items between {}; then ingrouping-- and ) (parser_regex.c:306-330). So {conf} is refused and {c,} gives (c|).Regex grouping error: Unclosed grouping or character class, expecting close } (parser_regex.c:411-416).[: incharclass = 1 and the character is copied; ] clears it (parser_regex.c:256-280). Inside a class {, } and , are copied (parser_regex.c:288-290, parser_regex.c:312-314). The class is parsed later by the regular expression grammar of the backend (parse.y:109-150).*, ** and ? are written as classes that exclude / (and NUL); a class written by the author has no such exclusion, so [^a] matches / as well.-Q -K -D rule-exprs (nothing loaded into a kernel, no cache) and the tree's abi/5.0 feature set. Each aare: line is printed by the conversion itself.\^ loses its escape, and * or ? inside [...] are expanded". With the tree's parser /etc/demo/[a*]z is converted to /etc/demo/[a[^/\x00]*]z.} without an opening { prints two messages, "Invalid number of items between {}" and then "Invalid close }, no matching open { detected", because the comma count is tested before the depth (parser_regex.c:316-324). Run with the tree's parser.@{u16} has an unbalanced bracket and also matches [ and 65536 to 69999".pattern_t is Basic, TailGlob, Regex or Invalid; *first_re_pos is the offset of the first glob. process_profile_name_xmatch uses both.
enum class pattern_t { Basic, TailGlob, Regex, Invalid } (immunix.h:139-144). The function starts with Basic; a ** that ends the pattern while the type is still Basic makes it TailGlob; every other glob, class or group makes it Regex (parser_regex.c:206-221); an error makes it Invalid (parser_regex.c:437-438).*first_re_pos is set once, to the offset of the first glob in the input, and stays 0 when there is none (update_re_pos, parser_regex.c:121).process_profile_name_xmatch (parser_regex.c:478-518): the attachment, or the profile name when there is none, is converted with &prof->xmatch_len as the position; for a Basic pattern the length is strlen(name). A Basic pattern in a profile without alias names, separate attachment or xattrs gets prof->xmatch = NULL; anything else goes to the backend as a small DFA.entry->pattern_type (parser_regex.c:664); no other code in parser/ reads it, and nothing outside the unit tests distinguishes TailGlob from Regex.convert_entry appends the conversion of a value, or the default "match anything" pattern when the value is absent (parser_regex.c:1316-1336); build_list_val_expr joins a list of values with | (parser_regex.c:1286-1314). Direct calls: dbus.cc:229-281, signal.cc:330, ptrace.cc:141, af_unix.cc:275-299, network.cc:434, mount.cc:769.glob argument: glob_default writes [^/\x00]*, [^\x00]* and [^/\x00]; glob_null writes [^/]*, .* and [^/], which also match a NUL byte (parser_regex.c:98-114). glob_null is used for xattr values (parser_regex.c:582-584) and abstract unix socket addresses (af_unix.cc:275).NotCharSetNode::contains_oob() is inverted, so xmatch_len stops at the first wildcard".Regex grouping error: ... says what is wrong; Unable to parse input line 'PATTERN' quotes the pattern with variables expanded. Neither has a file name or a line number.
demo with the rule /etc/demo/{conf} r,. The path at the start of three of the lines is where the parser program was when it ran:/src/apparmor/parser/apparmor_parser: Regex grouping error: Invalid number of items between {}
/src/apparmor/parser/apparmor_parser: Unable to parse input line '/etc/demo/{conf}'
ERROR processing regexs for profile demo, failed to load
ERROR generating policy re for profile demo, failed to load
/src/apparmor/parser/apparmor_parser: Errors found in file. Aborting.
| Pattern | First line |
|---|---|
/etc/demo/{conf} | Regex grouping error: Invalid number of items between {} |
/etc/demo/{a,b | Regex grouping error: Unclosed grouping or character class, expecting close } |
/etc/demo/[ab | the same text, also with "expecting close }" |
/etc/demo/a] | Regex grouping error: Invalid close ], no matching open [ detected |
/etc/demo/a} | Regex grouping error: Invalid number of items between {} and then Regex grouping error: Invalid close }, no matching open { detected |
Invalid profile name 'PATTERN' - bad regular expression and ERROR processing xmatch for profile NAME, failed to load.@{CONF}/x is quoted with the value of the variable in place of @{CONF}: the value itself for one value, {a,b} for several.--warn=all the conversion can also print a warning, Character C was quotedunnecessarily, dropped preceding quote ('\') character. It does carry a file and a line, but the line is the last line of the file.-Q -K (nothing loaded into a kernel, no cache) and the tree's abi/5.0 feature set.Unable to parse input line '%s' at parser_regex.c:430. They use PERROR with progname, not yyerror.block::gen_policy_re (block.cc:90), line 4 by process_profile_rules (parser_regex.c:1252), line 5 by process_profile (parser_main.c:1393).Regex error: trailing '\' escape character (parser_regex.c:421) was not reached from a profile: a pattern that ends in a backslash is stopped earlier, by the scanner (known discrepancy, by title: "A path ending in an escaped backslash cannot be written: quoted it runs to the next quote, unquoted it swallows the blank").Next: the backend pipeline, then the expression tree. Related: globbing, quoting and escaping, profile attachment, the grammar.
dfarules->add_rule(tbuf.c_str(), entry->priority, entry->rule_mode, entry->perms, audit, parseopts) (parser_regex.c:685-688); aare_rules::add_rule is at aare_rules.cc:46. -D rule-exprs prints both sides, the aare: line of the front end and the rule: line of the backend:aare: /etc/demo/** -> /etc/demo/[^/\x00][^\x00]* rule: /etc/demo/[^/\x00][^\x00]* -> /etc/demo/[^\x0/]([^\x0])* priority=0 (0x10004/0)< 0x10004>
Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run (-Q -K -D rule-exprs, with the tree's abi/5.0 feature set), with nothing loaded into a kernel. "code" means the parser source was read and not run; "derived" means the result was reasoned from that code.
| Read | Written | Notes | Basis |
|---|---|---|---|
* | [^/\x00]* | after / and before / or the end, [^/\x00] first | tree |
** | [^\x00]* | the same mandatory character | tree |
? | [^/\x00] | tree | |
[ ... ] | copied | {, }, ,, ^, $ are copied inside | tree |
{ , } | (, a bar, ) | at least one comma; at most 49 levels | tree |
. + ( ) and the bar | with a backslash | always | tree |
^ $ | \^ \$ | outside a class | tree |
\* \[ \] \{ \} \\ | unchanged | tree (\*, \{, \}), code | |
\? \, | ? , | \, stays inside a class | tree |
\x00 \000 \d000 and letter escapes | unchanged | decoded by the backend | code |
\ + any other character | the character | warning of class format | tree |
| anything else | copied | tree |
With glob_null (xattr values, abstract unix socket addresses) the three globs are [^/]*, .* and [^/] (code).
| Step | Where | Effect |
|---|---|---|
| quotes and escapes | scanner, processid | quotes removed; escapes decoded; a decoded * ? [ ] { } ^ , \ keeps a backslash |
| variables | post-processing, process_variables | @{VAR} replaced by its value, or by {a,b} for several values |
| aliases | post-processing | an entry whose name starts with an alias source is duplicated with the target |
| slashes | filter_slashes, just before the conversion | runs of / collapsed; exactly two leading slashes kept |
pattern_t | Meaning | Example |
|---|---|---|
Basic | no glob | /usr/bin/demo |
TailGlob | plain text and one final ** | /etc/demo/** |
Regex | any other glob, class or group | /usr/bin/[a-z]* |
Invalid | an error was printed | /etc/demo/{conf} |
*first_re_pos: offset of the first glob in the input; 0 without one (code).
| Message | Cause | Basis |
|---|---|---|
Regex grouping error: Invalid number of items between {} | a group without a comma | tree |
Regex grouping error: Unclosed grouping or character class, expecting close } | { or [ not closed | tree |
Regex grouping error: Invalid close ], no matching open [ detected | ] without [ | tree |
Regex grouping error: Invalid close }, no matching open { detected | } without { | tree |
Regex grouping error: Exceeded maximum nesting of {} | 50 or more levels | tree |
Regex error: trailing '\' escape character | pattern ends in a backslash | code |
Unable to parse input line 'PATTERN' | follows each of the above | tree |
Invalid profile name 'PATTERN' - bad regular expression | the pattern is an attachment or profile name | tree |
Character C was quotedunnecessarily, dropped preceding quote ('\') character | warning, class format | tree |
| Function | Where | What |
|---|---|---|
convert_aaregex_to_pcre | parser_regex.c:118-445 | the conversion |
filter_slashes | parser_regex.c:61-96 | collapse repeated slashes in place |
process_profile_name_xmatch | parser_regex.c:478-628 | attachment, alias names, xattr values |
process_dfa_entry | parser_regex.c:648-787 | file, link and change_profile entries |
convert_entry, clear_and_convert_entry, build_list_val_expr | parser_regex.c:1286-1336 | helpers for the other rule classes |
aare_rules::add_rule | aare_rules.cc:46 | where the string enters the backend |
yyparse(), generated from parser/parser_yacc.y, consumes the scanner's tokens and builds Profile objects directly in its actions. The first error calls exit(1).
yyparse() from it. process_profile() calls it once per policy file (parser_main.c:1353).$$) is the value of the rule's symbol: a struct cod_entry *, a block *, a Profile * and so on (the %union, parser_yacc.y:213-254).yyerror, which prints one message and calls exit(1) (parser_yacc.y:1748-1757). The grammar has no error recovery.demo3.sd):abi <abi/5.0>,
include <tunables/global>
profile demo /usr/bin/demo {
/etc/demo/** r,
audit deny @{HOME}/.ssh/** rw,
/usr/bin/[a-z]* ix,
}
-Q -K (nothing loaded into a kernel, no cache) and the tree's abi/5.0 feature set.list: preamble profilelist (parser/parser_yacc.y:345). The policy feature set is chosen in the action between the two. profile_base (391) is shared by profiles, hats and child profiles.
list: preamble { ... } profilelist (parser_yacc.y:345-371). preamble is any sequence of alias, varassign and abi_rule (parser_yacc.y:506-509); profilelist is any number of profile (parser_yacc.y:373-379).abi rule already seen, else the pinned features, else the built-in default with the warning File 'NAME' missing feature abi, falling back to default policy feature abi (parser_yacc.y:346-370).syntax error, unexpected TOK_SET_VAR, expecting end of file. An assignment inside a profile: syntax error, unexpected TOK_EQUALS, expecting TOK_MODE (both run with the tree's parser).profile: opt_profile_flag profile_base (parser_yacc.y:460-478); the flag is empty, TOK_PROFILE or hat_start (parser_yacc.y:381-383).profile_base: TOK_ID opt_id_or_var opt_cond_list identities flags TOK_OPEN rules TOK_CLOSE (parser_yacc.y:391-458).hat: hat_start profile_base (parser_yacc.y:490-504) and local_profile: TOK_PROFILE profile_base (parser_yacc.y:480-488) appear as alternatives of rules.varassign covers the four operators =, +=, ?= and := through assign_op, once for set variables and once for boolean variables (parser_yacc.y:519-570).abi rule is also accepted inside a profile body (parser_yacc.y:722).rules (parser/parser_yacc.y:713-859) is left-recursive. File, link and change_profile rules become cod_entry list items; other classes become rule_t objects; capabilities are a bit mask.
rules and what each action does:| Alternative | Lines | Action |
|---|---|---|
| empty | parser_yacc.y:713-720 | new block() |
rules abi_rule | parser_yacc.y:722 | nothing more |
rules opt_prefix rule | parser_yacc.y:724-736 | entry_add_prefix, add_entry; rule is file_rule or link_rule |
rules opt_prefix block | parser_yacc.y:743-759 | subblock->add_prefix, add_subblock |
rules opt_prefix network_rule | parser_yacc.y:761-783 | add_prefix, a unix_rule for each AF_UNIX entry, add_rule, add_compat_net |
rules opt_prefix prefix_rule | parser_yacc.y:795-802 | add_prefix, add_rule; the classes are listed at parser_yacc.y:785-793 |
rules opt_prefix change_profile | parser_yacc.y:804-819 | owner refused, generic_add_prefix, add_entry |
rules opt_prefix capability | parser_yacc.y:821-825 | add_capabilities |
rules hat | parser_yacc.y:827-834 | add_hat |
rules local_profile | parser_yacc.y:836-843 | add_hat |
rules cond_rule | parser_yacc.y:845-850 | add_cond_set |
rules TOK_SET TOK_RLIMIT TOK_ID TOK_LE TOK_VALUE opt_id TOK_END_OF_RULE | parser_yacc.y:852-859 | add_rlimit |
block_rules::add_entry puts the entry at the head of a singly linked list; add_rule appends to a vector (block_rules.cc:23-36). The other methods are in block.cc:112-175.block in braces inside a profile is TOK_OPEN rules TOK_CLOSE, the same rules symbol again (parser_yacc.y:738-741); cond_rule is if, else if and else around such blocks (parser_yacc.y:862-900).if is evaluated in the grammar action, while parsing (parser_yacc.y:872-886); both branches stay attached to the block.add_rule. Qualifier blocks, Conditional blocks.opt_prefix: opt_priority opt_audit_flag opt_rule_mode opt_owner_flag (parser/parser_yacc.y:705). Order mistakes are syntax errors; conflicts are found by add_prefix.
opt_prefix: opt_priority opt_audit_flag opt_rule_mode opt_owner_flag fills a struct prefixes with priority, audit, rule_mode and owner (parser_yacc.y:705-711). Each part may be empty (parser_yacc.y:677-703).rules begin with opt_prefix: rule, block, network_rule, prefix_rule, change_profile and capability. An abi rule, a hat, a child profile, a conditional and set rlimit take no prefix: audit set rlimit nofile <= 10, is syntax error, unexpected TOK_SET, expecting TOK_ID or TOK_MODE or TOK_SET_VAR (run with the tree's parser).opt_priority converts the number and checks the range -1000 to 1000 (parser_yacc.y:677-691).entry_add_prefix (parser_misc.c:1147-1160) calls generic_add_prefix (parser_misc.c:1109), keeps the owner or the other half of the permissions, and checks the exec qualifiers; - rule objects: prefix_rule_t::add_prefix (rule.h:381-440); - blocks: block::add_prefix applies the prefix to every entry and rule in the block and its sub-blocks (block.cc:273-283, block_rules.cc:612).add_prefix: priority levels not supported, conflicting audit prefix, conflicting mode prefix, conflicting owner prefix (rule.h:392-422).deny without audit sets the audit field to "implied", which is how a deny rule is quiet; audit deny resets it (rule.h:428-440).owner in its grammar action: owner conditional not allowed on change_profile rules (parser_yacc.y:812-813).AppArmor parser error for FILE in profile FILE at line N:. The conflict is reported at the line of the block's closing brace, where the action runs.-Q -K (nothing loaded into a kernel, no cache) and the tree's abi/5.0 feature set.priority= on a rule inside a block is refused for every rule class except file rules"; "A deny block around an audit deny rule drops the audit".frule: id_or_var file_perms opt_named_transition TOK_END_OF_RULE calls do_file_rule and new_entry; the entry's name is the unconverted pattern.
file_perms: TOK_MODE calls parse_perms (parser_yacc.y:1640-1646), which parses the letters once and shifts the result into the owner half and the other half (parser_misc.c:736-745). r is 0x4 in each half: 0x10004.frule: id_or_var file_perms opt_named_transition TOK_END_OF_RULE (parser_yacc.y:1072-1083); the permissions-first spelling is the second frule (parser_yacc.y:1085-1101). file_rule_tail applies safe and unsafe (parser_yacc.y:1117-1130); bare file, becomes the path /{**,} with all permissions (parser_yacc.y:1103-1114).do_file_rule (parser_yacc.y:1759-1769) calls new_entry (parser_misc.c:970-992): a zeroed struct cod_entry with name, perms and link_name, audit and rule_mode unspecified, priority 0 and pattern_type set to pattern_t::Invalid until the pattern is converted.rules action: entry_add_prefix($3, $2, error) and $1->add_entry($3) (parser_yacc.y:724-736).new_entry(name, AA_LINK_BITS, target) (parser_yacc.y:1141-1152); a change_profile rule is a cod_entry too, with the target as the name and ** when no target is written (parser_yacc.y:1648-1692).signal_rule: TOK_SIGNAL opt_signal_perm opt_conds TOK_END_OF_RULE { signal_rule *ent = new signal_rule($2, $3); $$ = ent; } (parser_yacc.y:1466-1470). The constructor reads the conditions; that is where a rule class reports an unknown condition.-d prints the entries after post-processing: Perms: r:r priority=0 Name: (/etc/demo/**).-d lists deny and audit file rules as plain allow rules".name later. Rule objects.The final action of profile_base (parser/parser_yacc.y:399-458) creates the Profile; add_to_list (parser/parser_policy.c:60) inserts it into a set and exits on a duplicate.
profile_base has two actions. The first runs right after TOK_OPEN and swaps in an empty include cache (parser_yacc.y:392-398). The second runs after TOK_CLOSE (parser_yacc.y:399-458): - new Profile() and parse_label(&self_stack, &prof->ns, &prof->name, $1, true); a name that begins with & is refused (parser_yacc.y:401-411); - the namespace from -n replaces the one in the profile, with a warning (parser_yacc.y:414-429); - Profile attachment must begin with a '/' or variable. (parser_yacc.y:431-433); the scanner lets few such attachments through, one is profile demo &x {, reported at the line of the closing brace (run with the tree's parser); - the conditional group must be xattrs: profile id: invalid conditional group %s=() (parser_yacc.y:434-440); - identities, flags, prof->add_block($8) and prof->post_parse_profile() (parser_yacc.y:441-450, profile.cc:91); - the include cache of the surrounding level is restored (parser_yacc.y:453-455).profile then warns about a path used as a name and refuses a name without /, namespace or keyword: Profile names must begin with a '/', namespace or keyword 'profile' or 'hat'. (parser_yacc.y:468-472). For a four-line profile demo { ... } the parser reports this at line 4, the closing brace (run with the tree's parser).profilelist: profilelist profile calls add_to_list($2) (parser_yacc.y:375-379), an insert into policy_list, a std::set of profile pointers with its own ordering (profilelist.h:22-37). When the insert finds an equal profile: Multiple definitions for profile %s exist,bailing out. and exit(1) (parser_policy.c:60-68). This message does not go through yyerror, so it has no file and no line.add_hat instead (parser_yacc.y:827-843).-Q -K (nothing loaded into a kernel, no cache) and the tree's abi/5.0 feature set.yyparse() returns.A syntax error names the token found and the tokens that could follow. The line is that of the token being read, often one after the mistake. TOK_END_OF_RULE is the comma.
AppArmor parser error for FILE in profile FILE at line N: syntax error, unexpected X, expecting Y or Z. The second and third examples on the slide show only the part after the colon.| Token | In the profile |
|---|---|
TOK_ID | a name, a path or a pattern |
TOK_MODE | permission letters such as r, rw, ix |
TOK_END_OF_RULE | the comma that ends a rule |
TOK_OPEN, TOK_CLOSE | { and } |
TOK_SET_VAR, TOK_BOOL_VAR | @{name} and ${name} |
TOK_EQUALS | = |
TOK_ARROW | -> |
TOK_VALUE | a value after =, or an item of a list in parentheses |
TOK_CONDID | a word in front of =, such as peer or set |
TOK_OPENPAREN, TOK_CLOSEPAREN | ( and ) |
| a keyword token | the keyword in capitals: TOK_AUDIT, TOK_DENY, TOK_CAPABILITY, ... |
end of file | the end of the policy file |
| Mistake | Message |
|---|---|
capability chown with no comma, then } | syntax error, unexpected TOK_CLOSE, expecting TOK_ID or TOK_END_OF_RULE |
owner audit /etc/demo/** r, | syntax error, unexpected TOK_AUDIT, expecting TOK_ID or TOK_MODE or TOK_SET_VAR |
@{CONF}=/etc/demo inside a profile | syntax error, unexpected TOK_EQUALS, expecting TOK_MODE |
one } too many | syntax error, unexpected TOK_CLOSE, expecting end of file |
/etc/demo/** rq, | syntax error, unexpected TOK_ID, expecting TOK_MODE |
Invalid capability nosuch. or invalid priority 2000 > 1000.-Q -K (nothing loaded into a kernel, no cache) and the tree's abi/5.0 feature set. The paths start with /work/ because that is where the files were when the parser ran.%token declarations (parser_yacc.y:78-193). The long form of the message comes from bison's parse.error=verbose, which the build passes when bison is version 3 or later (Makefile:38-45).file_rule_tail: opt_exec_mode id_or_var file_perms id_or_var exists only to give the missing-comma message (parser_yacc.y:1132-1139).vprintyyerror builds the header from profilename, current_filename and current_lineno; yyerror then calls exit(1) (parser_yacc.y:1721-1757).TOK_CLOSE at the end of a file is such a case. The parser generated by bison 3.8.2 collects the list from the tables of the state on top of its stack and names at most four tokens; when five or more are possible it prints none, and the message ends after the unexpected token (yypcontext_expected_tokens and YYARGS_MAX = 5 in the generated parser_yacc.c, a build product that is not in the repository; no such message was produced in the runs for this deck).Next: from AARE to regular expressions. Related: the lexer, the preamble, qualifier blocks, file rules, running apparmor_parser.
rules and adds to a block; qualifiers are four slots in a fixed order; objects are built in the actions and the first error ends the run.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run (-Q -K, with the tree's abi/5.0 feature set), with nothing loaded into a kernel. "code" means the parser source was read and not run; "derived" means the result was reasoned from that code.
list: preamble profilelist
preamble: (alias | varassign | abi_rule)*
profilelist: profile*
profile: opt_profile_flag profile_base
profile_base: TOK_ID opt_id_or_var opt_cond_list identities flags TOK_OPEN rules TOK_CLOSE
rules: (abi_rule | opt_prefix rule | opt_prefix block | opt_prefix network_rule
| opt_prefix prefix_rule | opt_prefix change_profile | opt_prefix capability
| hat | local_profile | cond_rule | set-rlimit)*
opt_prefix: opt_priority opt_audit_flag opt_rule_mode opt_owner_flag
block: TOK_OPEN rules TOK_CLOSE
rule: file_rule | link_rule
prefix_rule: mnt_rule | dbus_rule | signal_rule | ptrace_rule | unix_rule | userns_rule
| mqueue_rule | io_uring_rule | all_rule
The notation is shortened: * stands for the left-recursive lists of the source (code).
| Line | Object | Stored by |
|---|---|---|
| file rule, link rule, change_profile rule | struct cod_entry | block::add_entry |
| mount, remount, umount, pivot_root, dbus, signal, ptrace, unix, userns, mqueue, io_uring, all, network | a class derived from rule_t | block::add_rule |
| capability | bits in a 64-bit mask | block::add_capabilities |
set rlimit | an entry in the limits table | block::add_rlimit |
{ ... } with qualifiers | block | block::add_subblock |
| hat, child profile | Profile | block::add_hat |
if / else | cond_expr_set | block::add_cond_set |
| alias (preamble) | alias table | new_alias |
| variable assignment (preamble) | symbol table | global_symtab.add_var, add_set_value |
abi | policy feature set | abi_features |
| Message | Cause | Basis |
|---|---|---|
syntax error, unexpected X, expecting Y | the tokens match no rule | tree |
missing an end of line character? (entry: NAME) | no comma after a file rule | tree |
Profile names must begin with a '/', namespace or keyword 'profile' or 'hat'. | a bare name without profile | tree |
Profile attachment must begin with a '/' or variable. | an attachment such as &x | tree |
hat profiles can't use xattrs matches | code | |
variable NAME was previously declared | = on an existing variable | code |
variable NAME was not previously declared, but is being assigned additional values | += on a new variable | code |
invalid priority N > 1000 | priority out of range | tree |
conflicting mode prefix, conflicting audit prefix, conflicting owner prefix | qualifiers of a block and of a rule inside it disagree | tree (mode), code |
owner conditional not allowed on change_profile rules | owner change_profile -> x, | tree |
Invalid capability NAME. | unknown capability | tree |
subset can only be used with link rules. | code | |
link and exec perms conflict on a file rule using -> | code | |
unsafe rule missing exec permissions | safe or unsafe without an exec permission | code |
Exec condition must begin with '/'. | change_profile | code |
Multiple definitions for profile NAME exist,bailing out. | two profiles with one name (printed without file and line) | tree |
| Function | Where | What |
|---|---|---|
yyerror, vprintyyerror | parser_yacc.y:1721-1757 | header, message, exit(1) |
do_file_rule | parser_yacc.y:1759-1769 | new_entry plus the transition name |
new_entry | parser_misc.c:970-992 | allocate a cod_entry |
parse_perms | parser_misc.c:736-745 | permission letters to bits for owner and other |
entry_add_prefix, generic_add_prefix | parser_misc.c:1109-1160 | qualifiers on a cod_entry |
prefix_rule_t::add_prefix | rule.h:381-440 | qualifiers on a rule object |
block::add_prefix, block::add_subblock | block.cc:161-283 | qualifiers on a block |
add_to_list | parser_policy.c:60-68 | insert a profile, exit on a duplicate |
abi_features | parser_yacc.y:1884-1906 | read the feature file of an abi rule |
The scanner (parser/parser_lex.l, flex) turns profile text into tokens; the grammar (parser/parser_yacc.y, bison) asks for them one at a time.
demo3.sd):abi <abi/5.0>,
include <tunables/global>
profile demo /usr/bin/demo {
/etc/demo/** r,
audit deny @{HOME}/.ssh/** rw,
/usr/bin/[a-z]* ix,
}
yyparse() is called once per policy file (parser_main.c:1353) and calls the scanner for each token.TOK_ID, TOK_MODE, ...; the list is parser_yacc.y:78-193) and, for some tokens, a value: the text of a name or of a permission string.-Q -K (nothing loaded into a kernel, no cache) and the tree's abi/5.0 feature set.@{HOME}/.ssh/** is one TOK_ID because {LABEL} matches more text than {SET_VARIABLE}; rw is a TOK_MODE only when a blank or a comma follows.
audit and deny match {VARIABLE_NAME} and are found in the keyword table (parser_lex.l:856-909).@{HOME}/.ssh/** matches {SET_VARIABLE} (seven characters, TOK_SET_VAR, parser_lex.l:714-717) and {LABEL}, which is a /, a variable, a : or an & followed by name characters (parser_lex.l:301, parser_lex.l:838-841). {LABEL} is longer, so the result is one TOK_ID. A variable followed directly by a blank is a TOK_SET_VAR; the grammar accepts either through id_or_var (parser_yacc.y:1037-1038).MODE_CHARS is ([RrWwaLlMmkXx])|(([Pp]|[Cc])[Xx])|(([Pp]|[Cc])?([IiUu])[Xx]) (parser_lex.l:257); the rule is ({MODES})/([[:space:],]), with the blank or comma as trailing context (parser_lex.l:843-846). The trailing character counts for the match length, which is how rw, wins over the one-word pattern.TOK_END_OF_RULE in the initial state and in the rule-class states (parser_lex.l:911-917).DEBUG (parser_lex.l:55-61); the cut shown here is derived from the patterns.{VARIABLE_NAME} matches the word, get_keyword_token() looks it up in keyword_table (55 entries, parser/parser_misc.c:81); no entry means TOK_ID.
VARIABLE_NAME is [[:alpha:]][[:alnum:]_]* (parser_lex.l:296).get_keyword_token(yytext) (parser_misc.c:187-191), a lookup in keyword_table (parser_misc.c:81-139).-1: the word is returned as TOK_ID through processunquoted (parser_lex.l:862-866).TOK_RLIMIT, TOK_NETWORK, TOK_CHANGE_PROFILE, TOK_MOUNT, TOK_REMOUNT, TOK_UMOUNT, TOK_DBUS, TOK_SIGNAL, TOK_PTRACE, TOK_UNIX, TOK_ABI, TOK_USERNS, TOK_MQUEUE and TOK_IF (parser_lex.l:867-907). Every other keyword pushes the initial state again (parser_lex.l:908).user and owner are both TOK_OWNER, rewrite and alias both TOK_ALIAS, unmount and umount both TOK_UMOUNT (parser_misc.c:95-112).listen, accept, connect, getopt, setopt and shutdown (parser_lex.l:627-634), create (parser_lex.l:636-638), getattr and setattr (parser_lex.l:645-648). Anywhere else they are names.send, receive, bind, read, write, eavesdrop, trace, readby, tracedby (parser_lex.l:650-679), safe and unsafe (parser_lex.l:593-596), open and delete. In the initial state they are keywords: /etc/demo/** send, gives syntax error, unexpected TOK_SEND, expecting TOK_MODE, where /etc/demo/** listen, gives unexpected TOK_ID (both run with the tree's parser).priority, flags, peer, xattrs and identities in front of = (parser_lex.l:408-436), all (parser_lex.l:811-813), profile and hat (parser_lex.l:848-850), include (parser_lex.l:781-809).IOURING_MODE can never be entered" (the table has io_uring, the action has no case for it).29 exclusive start conditions (%x, parser/parser_lex.l:331-359) and %option stack; a condition name is recognised by the = behind it, inside the scanner.
%option stack (parser_lex.l:27) and 29 %x declarations (parser_lex.l:331-359). The macros PUSH, POP, PUSH_AND_RETURN, POP_AND_RETURN and BEGIN_AND_RETURN wrap yy_push_state, yy_pop_state and BEGIN (parser_lex.l:79-116).| Purpose | States |
|---|---|
| a name follows | SUB_ID (after profile, hat, ^), SUB_ID_WS (after ->), SUB_VALUE |
| a rule class | NETWORK_MODE, RLIMIT_MODE, MOUNT_MODE, DBUS_MODE, SIGNAL_MODE, PTRACE_MODE, UNIX_MODE, CHANGE_PROFILE_MODE, USERNS_MODE, MQUEUE_MODE, IOURING_MODE, ABI_MODE |
| conditions and lists | EXTCOND_MODE, EXTCONDLIST_MODE, LIST_VAL_MODE, LIST_COND_MODE, LIST_COND_VAL, LIST_COND_PAREN_VAL, IDENTITY_VALUE, INTEGER_MODE |
assignments and if | ASSIGN_MODE, ASSIGN_EXPR_START, ASSIGN_EXPR_MODE, EXPR_MODE |
| includes | INCLUDE, INCLUDE_EXISTS |
{VARIABLE_NAME}/{WS}*= returns TOK_CONDID and pushes EXTCOND_MODE in one action. The comment there: "we match to the = in the lexer so that we can switch scanner state. By the time the parser see the = it may be too late as bison may have requested the next token from the scanner" (parser_lex.l:437-444).( moves from EXTCOND_MODE to LIST_VAL_MODE with BEGIN, not a push, so ) pops straight back to the signal state (parser_lex.l:479-503); = followed by a value moves to SUB_VALUE, and the value pops (parser_lex.l:464-470, parser_lex.l:491). The sequence on the slide is derived from these rules.TOK_ID (parser_lex.l:690-695): signal audit, gives syntax error, unexpected TOK_ID, expecting TOK_CONDID or TOK_END_OF_RULE (run with the tree's parser).profile, hat or ^ the scanner is in SUB_ID, where only a name or a quoted name matches (parser_lex.l:456-462, parser_lex.l:820, parser_lex.l:848-850). That is why a profile may be named like a keyword or like permission letters.priority= and after +" (two states are missing from the last rule of the file).name=value forms seen here. The profile name.processid() strips quotes and decodes escapes; a decoded * ? [ ] { } ^ , \ keeps a backslash (parser/parser_misc.c:488) for convert_aaregex_to_pcre.
{IDS}: any characters except blank, tab, carriage return, new line, ", ! and a , that is not followed by a name character; a backslash in front of a blank, a tab, ", ! or , lets that character in (parser_lex.l:262-267), or {QUOTED_ID}: text between double quotes, with \" allowed inside (parser_lex.l:287-288). In the initial state a path is matched by {LABEL}, which begins with /, a variable, : or & and continues with the same characters (parser_lex.l:301).processid (parser_misc.c:527-535) calls processquoted for a string that starts with " (parser_misc.c:511-525), which removes the two quotes and calls processunquoted (parser_misc.c:468-509).processunquoted decodes an escape with strn_escseq (lib.c:158): up to three octal digits, \d and up to three decimal digits, \x and up to two hex digits, \\, \", and the letters a e f n r t.*?[]{}^,\ is written with a backslash in front (parser_misc.c:488-490); any other decoded character is written as it is; a sequence that is not a valid escape is copied unchanged, backslash included (parser_misc.c:495-502).-D rule-exprs prints after aare: for these rules; the dump is made later, so for other names it also shows expanded variables.-Q -K (nothing loaded into a kernel, no cache) and the tree's abi/5.0 feature set.ID_FIRST_CHARS is defined and never used, so a name may start with #".include_filename() pushes a flex buffer (parser/parser_lex.l:207); <<EOF>> pops it (400-406). An include cache per profile body skips a file already included there.
include/{WS} and include{WS}+if{WS}+exists/{WS} push the states INCLUDE and INCLUDE_EXISTS (parser_lex.l:789-794, parser_lex.l:804-809); the two #include forms do the same after the warning deprecated use of '#include' (parser_lex.l:781-787, parser_lex.l:796-802).<name>, <"name">, "name" or a bare name and calls include_filename(filename, lt, exists) (parser_lex.l:376-398).include_filename (parser_lex.l:162-225): a name in angle brackets is searched in the -I directories and then the base directory by search_path (parser_include.c:154-185); any other name is opened as written. A regular file is pushed with push_include_stack(fullpath) and yypush_buffer_state(yy_create_buffer(yyin, YY_BUF_SIZE)) (parser_lex.l:203-207). A directory is read with include_dir_cb, which pushes every regular file in it whose name is not blacklisted (parser_lex.l:128-160, parser_lex.l:208-217).fclose(yyin); pop_include_stack(); yypop_buffer_state(); and yyterminate() when no buffer is left (parser_lex.l:400-406).current_filename and current_lineno of each including file and restarts the count at 1 (parser_include.c:187-246). The line number on the slide for tunables/global (15) is where that file includes tunables/home./etc/demo/** and the line r, after the include, the parser compiles the rule /etc/demo/** r, (run with the tree's parser).Could not open 'NAME' (parser_lex.l:192-196); with if exists the scanner returns without a message.Could not open 'abi/5.0': Too many open files. The include inside the body is not found in the include cache, because every profile head starts an empty cache, and MAX_NEST_LEVEL (parser_include.c:58) is not checked anywhere. Run with the tree's parser.#include on the last line needs a final new line".apparmor_parser -p FILE prints the flattened profile: ##included, ##failed include and ##skipped duplicate include mark what the scanner did with each include.
-p, --preprocess: the parser prints the profile with its includes flattened and stops after parsing; nothing is compiled, cached or loaded (parser_main.c:1378-1379).DUMP_PREPROCESS, parser_lex.l:64). The include lines are not echoed; in their place the scanner prints a mark (parser_lex.l:170-184, parser_lex.l:223):| Mark | Meaning |
|---|---|
##included <NAME> | the file was found on the search path and its text follows |
##included "NAME" | the same for a name written in quotes or bare |
##failed include <NAME> | the file was not found; printed for include if exists (a plain include of a missing file ends the run with an error) |
##skipped duplicate include <NAME> | the file was already included in this profile body, or in the preamble |
demo3.sd the output has 516 lines: 14 ##included marks and 8 ##failed include marks, all from tunables/global and the files it includes. The slide shows lines 1 to 5, two of the marks and the first lines of the profile. The last panel is from a second profile whose body has include <abstractions/base> twice.## lines, which are comments.-Q -K (nothing loaded into a kernel, no cache) and the tree's abi/5.0 feature set.-D variables stops one step later and prints the symbol table (parser_main.c:1386-1389); -d runs post-processing and prints the built profiles.Lexer found unexpected character names the character and the scanner state. In the header, "for FILE" is the policy file and "in profile FILE" is the file being read, which may be an include.
Lexer found unexpected character: 'C' (0xNN) in state: STATE: the last rule of the scanner matches any character that no other rule of the current state accepts. In a path the characters that need quotes are a blank, a tab, ", ! and a comma at the end; write the path in double quotes.r w a l m k x with the exec forms (ix, px, cx, ux, pix and so on, either case) and then a blank or a comma. rq does not qualify, is taken as a word, is not a keyword, and reaches the grammar as a name: syntax error, unexpected TOK_ID, expecting TOK_MODE.AppArmor parser error for FILE in profile CURRENT at line N: MESSAGE. FILE is the policy file named on the command line. CURRENT is the file the scanner is reading; inside an include it is the included file, and N is a line of that file. Despite the words, it is not a profile name./work/lex5.sd includes /work/inc1, whose second line is /etc/demo/extra, r, (a comma inside the path ends the rule early).Could not open 'NAME' for an include that is missing; Variable declarations do not accept trailing commas for @{CONF}=/etc/demo,; the warning deprecated use of '#include' (shown with --warn=all or --warn=pound-include; --warn=include is refused as Invalid --warn option include; run with the tree's parser).-Q -K (nothing loaded into a kernel, no cache) and the tree's abi/5.0 feature set. The paths start with /work/ because that is where the files were when the parser ran.priority= and after +": priority=x /etc/demo/** r, prints only flex scanner jammed and exits with status 2 (run with the tree's parser).state_names (parser_lex.l:938-968).yyerror prints the header and calls exit(1) (parser_yacc.y:1721-1757); the second name is current_filename, set by the include stack (parser_include.c:197-222).Could not open '%s': parser_lex.l:195-196. Variable declarations do not accept trailing commas: parser_lex.l:573, parser_lex.l:732.Next: the grammar. Related: from AARE to regular expressions, quoting and escaping, include, comments and line structure, running apparmor_parser.
Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run (-Q -K, or -p, with the tree's abi/5.0 feature set), with nothing loaded into a kernel. "code" means the parser source was read and not run; "derived" means the result was reasoned from that code.
| Text | Token | Notes |
|---|---|---|
a path, :ns:name, &name, @{VAR}tail | TOK_ID | {LABEL}; quotes stripped, escapes decoded (code) |
@{VAR} alone | TOK_SET_VAR | |
${VAR} | TOK_BOOL_VAR | |
permission letters before a blank or , | TOK_MODE | |
| a word in the keyword table | its token | may select a state |
| any other word | TOK_ID | |
, | TOK_END_OF_RULE | in the initial and rule-class states |
{ } | TOK_OPEN TOK_CLOSE | |
( ) | TOK_OPENPAREN TOK_CLOSEPAREN | ( opens a list state |
-> | TOK_ARROW | a name follows |
= += ?= := | TOK_EQUALS TOK_ADD_ASSIGN TOK_COND_ASSIGN TOK_OVERRIDE_ASSIGN | an assignment follows |
^ | TOK_CARET | a hat name follows |
name before = | TOK_CONDID | priority, flags, peer, xattrs, identities have tokens of their own |
# to the end of the line | none | comment |
include NAME | none | the file becomes the input |
network unix capability if else not defined change_profile unsafe safe link owner user other subset audit deny allow prompt set rlimit alias rewrite ptrace file mount remount umount unmount pivot_root in dbus signal send receive bind read write eavesdrop peer trace tracedby readby abi userns mqueue delete open io_uring override_creds sqpoll all priority and or: 55 words (parser_misc.c:81-139) (code).
| Message | Cause | Basis |
|---|---|---|
Lexer found unexpected character: 'C' (0xNN) in state: STATE | a character no rule of the current state accepts | tree |
Could not open 'NAME' | an include whose file is missing | tree |
Could not open 'PATH' in 'NAME' | a file in an included directory cannot be opened | code |
Could not process include directory 'PATH' in 'NAME' | reading an included directory failed | code |
Variable declarations do not accept trailing commas | a comma at the end of an assignment | tree |
deprecated use of '#include' (warning, class pound-include) | #include instead of include | tree |
flex scanner jammed | see the known discrepancy in the details of the scenes on start conditions and on the scanner's messages | tree |
| Function | Where | What |
|---|---|---|
get_keyword_token | parser_misc.c:187-191 | word to token, or -1 |
processid, processquoted, processunquoted | parser_misc.c:468-535 | the value of a name token |
include_filename | parser_lex.l:162-225 | open an include and push a buffer |
include_dir_cb | parser_lex.l:128-160 | one file of an included directory |
search_path | parser_include.c:154-185 | look a name up in the -I directories and the base directory |
push_include_stack, pop_include_stack, reset_include_stack | parser_include.c:205-246 | file name and line for messages |
yyerror | parser_yacc.y:1748-1757 | print the header and the message, exit(1) |
The kernel holds no profile text. apparmor_parser compiles the file rules into one state machine when the profile is loaded, and each check is a walk over it.
abi <abi/5.0>,
profile demo /usr/bin/demo {
audit /etc/demo.conf r,
/etc/demo/* r,
deny /etc/demo/secret r,
owner /run/demo/** rw,
}
-S. The steps and the full state table are in the reference under the deck.file_open hook, apparmor_file_open (lsm.c:465), and ends in __aa_path_perm (file.c:233-251), which walks the machine and compares the result with the request.if (!unconfined(label)) first (lsm.c:488).process_profile_regex; the file machine is created at parser_regex.c:797./usr/bin/demo and a 5-state machine for the rule classes. This deck draws only the file machine.All file rules of a profile become one machine: 34 states here. Rules with a common beginning share states. A check costs one step per character of the path, whatever the number of rules.
-D dfa-stats: Created dfa: states 34 and Dfa minimization no states removed: partitions 34./etc/demo and are shared by three rules. States 4 to 18 (even numbers) spell /run/demo.-D rule-exprs prints them: /etc/demo/* becomes /etc/demo/[^/\x00][^/\x00]* (parser_regex.c:204, parser_regex.c:225) and /run/demo/** becomes /run/demo/[^/\x00][^\x00]* (parser_regex.c:220).A state stands for what has been read so far; an edge says where to go for one character. The walk starts in state 1. A character without an edge leads to state 0, and state 0 has no way out.
DFA_START and DFA_NOMATCH (match.h:17-18)./. State 2 has two, e to state 3 and r to state 4. Every other byte in states 1 and 2 leads to state 0.The kernel reads the path one byte at a time and follows one edge per byte. /etc/demo.conf takes 14 steps and ends in state 30. A path no rule covers ends in state 0.
/etc/demo.conf: 1, 2, 3, 5, 7, 9, 11, 13, 15, 17, 19, 22, 26, 28, 30./home/user/.ssh/id_rsa: 1, 2, then 0 for each of the remaining 20 characters. The kernel does not stop early; it reads the whole path (match.c:541-546).open() (path.c:202)./etc/demo is matched as /etc/demo/ (path.c:167-177).aa_str_perms calls aa_dfa_match(file_rules->dfa, start, name) (file.c:221-231). The loop is while (*str): the terminating NUL ends the walk.rules->file->start[AA_CLASS_FILE] (file.c:244), which is 1 unless the policy carries a dfa_start field (policy_unpack.c:1029-1031).aa_dfa_match_len and aa_dfa_leftmatch.* compiles to a state that loops on every character except /; ** to one that loops on every character. Both need at least one character first, so /etc/demo/ itself matches neither.
/etc/demo/motd: the walk reaches state 20 after /etc/demo/, state 23 with m, and stays in 23 for o, t, d./etc/demo/sub/x: s leads to state 24 (the first state of the side track for secret), u to 23, b stays, and the second / has no edge: state 0./etc/demo/ alone stops in state 20, which carries no permissions: * and ** at the end of a rule both need at least one character after the slash./run/demo/cache/db: state 21 after /run/demo/, state 25 with c, and every further character, slashes included, stays in 25.?, [...], {a,b} and the slash rules. apparmor.d(5), Globbing.* is emitted as [^/\x00] followed by [^/\x00]* (parser_regex.c:204, parser_regex.c:225), and ** as [^/\x00] followed by [^\x00]* (parser_regex.c:220). The NUL byte is kept out of every class because it separates the parts of multi-part matches.Permissions are attached to states. Only the state the path ends in counts: 30 carries read (with audit), 23 read, 25 read and write for the owner, and most states nothing.
/etc/demo.conf), 23 and the five states 24, 27, 29, 31, 32 (names under /etc/demo/), 25 (anything under /run/demo/), and 33 (/etc/demo/secret, where the deny rule applies).r gives more than the read bit: the compiled entry also allows opening the file and reading its attributes. rw adds write, append, create, delete, and changing attributes, mode and owner.aa_lookup_condperms, file.c:194-209). The table for this machine has 12 entries; the reference under the deck lists them.allow 0x244: AA_MAY_GETATTR, AA_MAY_OPEN, MAY_READ.Each state has an owner set and an other set; the kernel picks by comparing the process's fsuid with the file's owner. A deny rule compiles to states of its own in which the permission is absent.
fsuid in the log) with the uid that owns the file (ouid). Equal: the owner set. Different: the other set.owner puts the same permissions in both sets./etc/demo/s, se, sec, secr and secre are 24, 27, 29, 31 and 32. All of them carry read, from the * rule. State 33, reached by /etc/demo/secret, does not./etc/demo/secrets leaves state 33 for state 23 with its last character: read is allowed again.aa_lookup_condperms returns perms[index] when uid_eq(subj_uid, cond->uid) and perms[index + 1] otherwise, for states whose accept2 entry has ACCEPT_FLAG_OWNER (file.c:202-206). The subject uid is current_fsuid() (file.c:227); cond->uid is the inode's owner (lsm.c:492-496).allow 0x200 (AA_MAY_GETATTR only), quiet 0x244, deny 0.Requested permissions outside the allowed set fail with EACCES and are logged as DENIED. An allowed access is logged as AUDIT only if the rule said audit. A deny rule refuses without a log line.
pid and comm are invented, and a real record starts with audit: type=1400 audit(time:serial):):apparmor="AUDIT" operation="open" class="file" profile="demo" name="/etc/demo.conf" pid=4242 comm="demo" requested_mask="r" fsuid=1000 ouid=0 apparmor="DENIED" operation="open" class="file" profile="demo" name="/etc/demo.conf" pid=4242 comm="demo" requested_mask="w" denied_mask="w" fsuid=1000 ouid=0
/etc/demo/secret returns EACCES and writes nothing. Writing audit deny in the rule would bring the line back.ALLOWED.requested_mask holds only the refused part of what was asked.__aa_path_perm: if (request & ~perms->allow) e = -EACCES; then aa_audit_file (file.c:246-250).aa_audit_file: an allowed request is masked with perms->audit and logged as AUDIT_APPARMOR_AUDIT if anything remains (file.c:119-130); a refused one is reduced to the bits outside allow, loses its quiet bits, and is logged if anything remains (file.c:131-150).audit_pre (audit.c:93-141) and file_audit_cb (file.c:45-67).match_char: pos = base[state] + c; if check[pos] == state the next state is next[pos], otherwise default[state]. accept[state] then indexes the permission table.
match_char is at match.c:443-455. base_idx keeps the low 24 bits of a base entry (match.c:23); the high bits are flags (match.h:196-202).MATCH_FLAG_DIFF_ENCODE, a miss repeats the lookup from the default state with the same byte instead of ending the step. The tables of this machine do not use it: their header flags are 0.next and check: each state's row is placed at an offset (base) where its entries do not collide with others, and check records the owner of each slot. For this machine 34 states with 256 possible bytes each fit in 275 slots./ and for the NUL byte that lead to state 0.accept[state] is the index of the state's permission entry; with ACCEPT_FLAG_OWNER in accept2[state] (policy.h:61-63) the next entry is the one for non-owners (file.c:197-206).aa_perms record unpacked from 14 u32 fields (policy_unpack.c:901-923).Next: the pipeline for where the machine comes from, globbing and file rules for the language, the DFA engine decks for the compiler, matching at run time for the kernel code, reading a denial for the log.
abi <abi/5.0>,
profile demo /usr/bin/demo {
audit /etc/demo.conf r,
/etc/demo/* r,
deny /etc/demo/secret r,
owner /run/demo/** rw,
}
The four file rules compile to one machine with 34 states. Everything below was read back from the binary policy that apparmor_parser writes for this profile.
"Reached by" is the shortest input that leads to the state. A byte that is not listed leads to state 0. "Accept" is the state's index into the permission table; for the other half add 1.
| State | Reached by | Edges | Accept | Carries |
|---|---|---|---|---|
| 0 | (no match) | none: every byte stays in 0 | 0 | |
| 1 | (start) | / → 2 | 0 | |
| 2 | / | e → 3, r → 4 | 0 | |
| 3 | /e | t → 5 | 0 | |
| 4 | /r | u → 6 | 0 | |
| 5 | /et | c → 7 | 0 | |
| 6 | /ru | n → 8 | 0 | |
| 7 | /etc | / → 9 | 0 | |
| 8 | /run | / → 10 | 0 | |
| 9 | /etc/ | d → 11 | 0 | |
| 10 | /run/ | d → 12 | 0 | |
| 11 | /etc/d | e → 13 | 0 | |
| 12 | /run/d | e → 14 | 0 | |
| 13 | /etc/de | m → 15 | 0 | |
| 14 | /run/de | m → 16 | 0 | |
| 15 | /etc/dem | o → 17 | 0 | |
| 16 | /run/dem | o → 18 | 0 | |
| 17 | /etc/demo | . → 19, / → 20 | 0 | |
| 18 | /run/demo | / → 21 | 0 | |
| 19 | /etc/demo. | c → 22 | 0 | |
| 20 | /etc/demo/ | [^\x00/s] → 23, s → 24 | 0 | |
| 21 | /run/demo/ | [^\x00/] → 25 | 0 | |
| 22 | /etc/demo.c | o → 26 | 0 | |
| 23 | /etc/demo/a | [^\x00/] → 23 | 8 | r |
| 24 | /etc/demo/s | [^\x00/e] → 23, e → 27 | 8 | r |
| 25 | /run/demo/a | [^\x00] → 25 | 6 | owner rw |
| 26 | /etc/demo.co | n → 28 | 0 | |
| 27 | /etc/demo/se | [^\x00/c] → 23, c → 29 | 8 | r |
| 28 | /etc/demo.con | f → 30 | 0 | |
| 29 | /etc/demo/sec | [^\x00/r] → 23, r → 31 | 8 | r |
| 30 | /etc/demo.conf | none | 10 | r audit |
| 31 | /etc/demo/secr | [^\x00/e] → 23, e → 32 | 8 | r |
| 32 | /etc/demo/secre | [^\x00/t] → 23, t → 33 | 8 | r |
| 33 | /etc/demo/secret | [^\x00/] → 23 | 2 | deny r |
Entries come in pairs: the even one is used when the file's owner is the user the process runs as, the odd one otherwise. getattr is present in every entry.
| Entry | allow | audit | quiet | Used by |
|---|---|---|---|---|
| 0 | getattr | states without permissions (25 of them), owner | ||
| 1 | getattr | states without permissions (23 of them), other | ||
| 2 | getattr | read, open, getattr | states 33, owner | |
| 3 | getattr | read, open, getattr | states 33, other | |
| 4 | getattr | read, open, getattr | no state | |
| 5 | getattr | read, open, getattr | no state | |
| 6 | write, read, append, create, delete, open, setattr, getattr, chmod, chown | states 25, owner | ||
| 7 | getattr | states 25, other | ||
| 8 | read, open, getattr | states 23, 24, 27, 29, 31, 32, owner | ||
| 9 | read, open, getattr | states 23, 24, 27, 29, 31, 32, other | ||
| 10 | read, open, getattr | read, open, getattr | states 30, owner | |
| 11 | read, open, getattr | read, open, getattr | states 30, other |
demo runs as user 1000. "owner" means the file belongs to user 1000, "other" that it belongs to user 0. Each row was computed from the compiled tables with the kernel's rules; the widget shows the same results.
| Request | File is | Final state | Entry | Outcome | Log record |
|---|---|---|---|---|---|
read /etc/demo.conf | other | 30 | 11 | allowed and logged | apparmor="AUDIT" |
write /etc/demo.conf | other | 30 | 11 | denied | apparmor="DENIED" |
read /etc/demo/motd | other | 23 | 9 | allowed | none |
read /etc/demo/sub/x | other | 0 | 0 | denied | apparmor="DENIED" |
read /etc/demo/secret | other | 33 | 3 | denied quietly | none |
read /etc/demo/secrets | other | 23 | 9 | allowed | none |
read /etc/demo/ | other | 20 | 1 | denied | apparmor="DENIED" |
write /run/demo/cache/db | owner | 25 | 6 | allowed | none |
write /run/demo/cache/db | other | 25 | 7 | denied | apparmor="DENIED" |
read /home/user/.ssh/id_rsa | owner | 0 | 0 | denied | apparmor="DENIED" |
exec /usr/bin/demo-helper | other | 0 | 0 | denied | apparmor="DENIED" |
file_open hook maps the open flags to a request: read, write, append, create.allow, the open fails with EACCES.AUDIT) only for bits that are in audit.DENIED) unless every refused bit is in quiet.tools/head-parser -Q -K --skip-kernel-load -D rule-exprs -D dfa-stats -D dfa-states -D compressed-dfa demo.sd tools/head-parser -S -K demo.sd > demo.bin tools/matching-demo.py demo.sd demo.bin > site/matching-demo.json
-D dfa-states prints the states and their edges, -D compressed-dfa the packed tables, -S the binary policy. The feature set is abi/5.0.tools/matching-demo.py unpacks the file machine from the binary policy and walks it with a port of match_char.| Table | Values |
|---|---|
| base | 7:1, 8:2, 10:2, 11:2, 12:3, 14:2, 15:1, 16:2, 17:4, 18:5, 19:6, 20:6, 21:7, 22:4, 23:8, 24:17, 25:1, 26:9, 27:9, 28:4, 29:10, 31:19, 32:11, 33:12; 0 for the rest |
| default | 20:23, 21:25, 23:23, 24:23, 25:25, 27:23, 29:23, 31:23, 32:23, 33:23; 0 for the rest |
| accept | 23:8, 24:8, 25:6, 27:8, 29:8, 30:10, 31:8, 32:8, 33:2; 0 for the rest |
| accept2 | 0 for states 0 and 1, 1 for all others |
Entries of next and check that belong to a state (position: check → next):
1: 25 → 0 6: 20 → 0 7: 21 → 0 8: 23 → 0 9: 27 → 0 10: 29 → 0 11: 32 → 0 12: 33 → 0 17: 24 → 0 19: 31 → 0 47: 1 → 2 48: 7 → 9 49: 8 → 10 50: 17 → 19 51: 17 → 20 52: 18 → 21 53: 20 → 0 54: 21 → 0 55: 23 → 0 56: 27 → 0 57: 29 → 0 58: 32 → 0 59: 33 → 0 64: 24 → 0 66: 31 → 0 99: 5 → 7 100: 9 → 11 101: 2 → 3 102: 10 → 12 103: 11 → 13 104: 12 → 14 105: 19 → 22 106: 28 → 30 108: 27 → 29 109: 13 → 15 110: 6 → 8 111: 14 → 16 112: 15 → 17 113: 16 → 18 114: 2 → 4 115: 22 → 26 116: 3 → 5 117: 4 → 6 118: 24 → 27 119: 26 → 28 120: 31 → 32 121: 20 → 24 124: 29 → 31 127: 32 → 33
apparmor_bprm_creds_for_exec (domain.c:985) runs once per execve. It sets the new program's label and bprm->secureexec, or returns an error. aa_change_profile and aa_change_hat change a label without exec.
bprm_creds_for_exec lsm.c:1862 and called from bprm_execve exec.c:1861, once per execve, before the kernel examines the format of the binary. Two more hooks run when the exec can no longer fail: bprm_committing_creds and bprm_committed_creds lsm.c:957-985.profile demo /usr/bin/demo with one exec rule per program (/usr/bin/demo-tool ix,, /usr/bin/demo-helper px,, /usr/bin/demo-worker cx,, /usr/bin/demo-free ux,, /usr/bin/demo-other pix,, /usr/bin/demo-lost px,, /usr/bin/demo-named px -> sandbox,, /usr/bin/demo-gone px -> notloaded,, /usr/bin/demo-report px -> &sandbox,, /usr/bin/demo-plugin pix -> &sandbox,, /usr/bin/demo-env-px px,, /usr/bin/demo-env-Px Px,), the rule change_profile -> sandbox,, a child profile worker attached to /usr/bin/demo-worker and a hat admin; the profiles demo-helper, demo-report and demo-env attach to their programs; sandbox and learner have no attachment. No profile attaches to demo-other, demo-lost or demo-plugin, and notloaded is not loaded./usr/bin/demo is a copy of a shell and the demo-* programs are copies of cat that print /proc/self/attr/current.apparmor_bprm_creds_for_exec (domain.c:985-1108): newest label, the nnp snapshot, handle_onexec or fn_label_build(..., profile_transition(...)), the no_new_privs and ptrace tests, bprm->secureexec, set_cred_label(bprm->cred, new).
int apparmor_bprm_creds_for_exec(struct linux_binprm *bprm) domain.c:985-1108. The label comes from bprm->cred, the credentials being prepared for the new program.if ((bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS) && !unconfined(label) && !ctx->nnp) ctx->nnp = aa_get_label(label);. The comment: "Ideally this would happen when nnp is set but there isn't a good way to do that yet."fn_label_build(L, P, GFP, FN) lib.h:289-344: for a label with one profile the function's result is the result; otherwise each profile's label is collected, the vectors are concatenated, sorted and made unique, and the label is found or created. An ERR_PTR from one profile ends the build.LSM_UNSAFE_SHARE is not mediated ("FIXME: currently don't mediate shared state", domain.c:1058-1061); a traced task: may_change_ptraced_domain asks whether the tracer may trace the new label, info = "ptrace prevents transition" domain.c:50-82 domain.c:1063-1068.unsafe holds "a secure exec was requested": it is passed to profile_transition as secure_exec and, when true, sets bprm->secureexec = 1 domain.c:1070-1078.bprm->per_clear |= PER_CLEAR_ON_SETID domain.c:1080-1089.audit: domain.c:1100-1107 writes one exec record per profile of the old label, with the reason and the label that was refused as target.profile_transition (domain.c:665-796): aa_path_name; unconfined: find_attach over the namespace; confined: aa_str_perms on the file DFA, MAY_EXEC, then x_to_label(perms.xindex). Complain mode substitutes a null- learning profile.
static struct aa_label *profile_transition(const struct cred *subj_cred, struct aa_profile *profile, const struct linux_binprm *bprm, char *buffer, struct path_cond *cond, bool *secure_exec) domain.c:665-796.find_attach(&bprm->file->f_path, profile->ns, &profile->ns->base.profiles, name, &info). A conflict between two attachments sets an info string, which is logged with a forced AUDIT record, and the task stays unconfined.find_attach domain.c:394-507 walks a profile list. For each profile with an xmatch DFA: aa_dfa_leftmatch from attach->xmatch->start[AA_CLASS_XMATCH], and the final state's row must have MAY_EXEC domain.c:431-436; then the count, the xattrs and the conflict rule. Profile attachment draws that loop; Matching at run time has the walker.aa_dfa_leftmatch, and that function is not the same in the guest and in the tree: in 7.3.4 it steps without the retry of a diff-encoded state, in the tree it uses match_char (Matching at run time, scene "Five walkers, one step"). The labels observed for px and cx are the ones the tree's code gives for these attachments, which are literal paths (derived); a diff-encoded attachment table was not examined on either kernel.state = aa_str_perms(rules->file, state, name, cond, &perms); and if (perms.allow & MAY_EXEC) new = x_to_label(...). A missing label: info = "profile transition not found", the exec bit is removed for the record, error = -EACCES.aa_new_learning_profile(profile, false, name, GFP_KERNEL) makes or finds the child <profile>//null-<name> in complain mode (it takes the namespace lock and calls __aa_new_learning_profile, policy.c:740-794); the record carries -EACCES and is logged as ALLOWED; AA_X_UNSAFE is forced, so no secure exec.aa_audit_file(subj_cred, profile, &perms, OP_EXEC, MAY_EXEC, name, target, new, cond->uid, info, error). Observed for a program with no exec rule: apparmor="DENIED" operation="exec" class="file" profile="demo" name="/usr/bin/demo-norule" comm="demo" requested_mask="x" denied_mask="x" fsuid=0 ouid=0./usr/bin/demo is a copy of a shell and the demo-* programs are copies of cat that print /proc/self/attr/current.find_attach, by their titles: "find_attach keeps its candidate and conflict state across goto restart"; "find_attach stores max(count, xmatch_len) but compares the raw count (latent)".AA_X_NONE, AA_X_NAME, AA_X_TABLE plus AA_X_CHILD, AA_X_INHERIT, AA_X_UNCONFINED, AA_X_UNSAFE (include/file.h:54-64). x_to_label (domain.c:574-663) looks up, then falls back. The labels were read by the started programs on a running kernel.
AA_X_INDEX_MASK 0x00ffffff; AA_X_TYPE_MASK 0x0c000000 with AA_X_NONE 0, AA_X_NAME 0x04000000, AA_X_TABLE 0x08000000; AA_X_UNSAFE 0x10000000; AA_X_CHILD 0x20000000; AA_X_INHERIT 0x40000000; AA_X_UNCONFINED 0x80000000. It is the xindex field of the permission row; for policy without a permission table dfa_map_xindex builds it from the old accept word policy_compat.c:24-48.x_to_label domain.c:574-663. AA_X_TABLE: x_table_lookup; AA_X_NAME: find_attach over the profile's children with AA_X_CHILD, else over the namespace. No label: with AA_X_INHERIT the newest version of the profile's own label and info = "ix fallback"; else with AA_X_UNCONFINED the namespace's unconfined label and info = "ux fallback" domain.c:616-638.x_table_lookup domain.c:523-559: the index selects a string of the profile's table (rules->file->trans); a leading & is skipped for the lookup; with AA_X_CHILD the name is searched among the profile's children (aa_find_child), otherwise aa_label_parse(&profile->label, lookup, GFP_KERNEL, true, false) resolves it, at every exec. The index was range checked at load policy_unpack.c:1543-1549.& domain.c:597-602 domain.c:651-658: the label found is kept as the stack, the code continues with the search by name, and the two are merged with aa_label_merge. So px -> &sandbox gave demo-report//&sandbox: the profile attached to the program, plus sandbox.ix is type none plus inherit, so every such exec passes through the fallback. Observed with audit on the rule: apparmor="AUDIT" operation="exec" class="file" info="ix fallback" profile="demo" name="/usr/bin/demo-tool" comm="demo" requested_mask="x" fsuid=0 ouid=0 target="demo".demo-lost (px, nothing attaches): apparmor="DENIED" operation="exec" class="file" info="profile transition not found" error=-13 profile="demo" name="/usr/bin/demo-lost" comm="demo" requested_mask="x" denied_mask="x" fsuid=0 ouid=0 target="/usr/bin/demo-lost". demo-gone (px -> notloaded): the same with target="notloaded". An allowed exec with a table target and audit: apparmor="AUDIT" operation="exec" class="file" profile="demo" name="/usr/bin/demo-named" comm="demo" requested_mask="x" fsuid=0 ouid=0 target="sandbox".demo-plugin with pix -> &sandbox and no attaching profile ran as demo//&sandbox (enforce)./usr/bin/demo is a copy of a shell and the demo-* programs are copies of cat that print /proc/self/attr/current.px and cx runs on aa_dfa_leftmatch, and that function is not the same in the guest and in the tree: in 7.3.4 it steps without the retry of a diff-encoded state, in the tree it uses match_char (Matching at run time, scene "Five walkers, one step"). The labels observed for px and cx are the ones the tree's code gives for these attachments, which are literal paths (derived); a diff-encoded attachment table was not examined on either kernel.ix -> &name and ux -> &name run without the stack when name is not loaded"; "the forced audit for "conflicting profile attachments - ux fallback" cannot trigger".*secure_exec = true unless the row has AA_X_UNSAFE (domain.c:776-784); bprm->secureexec becomes AT_SECURE (fs/binfmt_elf.c:262). apparmor_bprm_committing_creds (lsm.c:957-973) revalidates open files, clears pdeath_signal and applies rlimits when the label changed.
profile_transition domain.c:776-784: if (!(perms.xindex & AA_X_UNSAFE)) *secure_exec = true;. The test is skipped when the label returned is the profile's own and a reason is set, which is the ix case domain.c:730-739. In a stacked label one profile's request is enough. For a pending change_onexec the row of the change_profile rule decides domain.c:855-863.bprm->secureexec = 1. The loader: NEW_AUX_ENT(AT_SECURE, bprm->secureexec) binfmt_elf.c:262; a secure exec also resets the stack limit exec.c:1240-1250./usr/bin/demo-env-px and /usr/bin/demo-env-Px are copies of od; each printed its own /proc/self/auxv, and entry 23 (AT_SECURE) was 0 and 1. With LD_DEBUG=statistics in the environment, the run through px printed the linker's statistics and the run through Px printed none. Which variables secure execution removes is the C library's decision: safe and unsafe exec.apparmor_bprm_committing_creds lsm.c:957-973 returns early when the new label has the same proxy as the old one or is unconfined. Otherwise aa_inherit_files file.c:721-755 checks the controlling terminal and every open descriptor with aa_file_perm under the new label (the operation in a record is file_inherit) and replaces a refused descriptor with one for the null device; then current->pdeath_signal = 0; then __aa_transition_rlimits.PER_CLEAR_ON_SETID domain.c:1080-1089.apparmor_bprm_committed_creds lsm.c:979-985 clears the task's pending request, its saved hat label and the token./usr/bin/demo is a copy of a shell and the demo-* programs are copies of cat that print /proc/self/attr/current.aa_label_is_unconfined_subset(new, ctx->nnp) (label.c:574-593) must hold, or the exec fails with EPERM and info="no new privs" (domain.c:1050-1056). The snapshot is taken at the first exec or change request after the flag is set (domain.c:1016, 1341, 1507). The six results were observed.
nnp of the task context task.h:34-41; it is copied to a child at fork task.h:68-75 and follows profile replacement task.c:66-71. It is taken in the exec hook domain.c:1016-1018, in aa_change_hat domain.c:1341-1342 and in aa_change_profile domain.c:1507-1508, each time only if the task has the flag, is not unconfined and has no snapshot yet. So it is the label at the first of these events after prctl(PR_SET_NO_NEW_PRIVS), not the label at the prctl.aa_label_is_unconfined_subset(set, sub) is true when every profile of sub that is missing from set is an unconfined profile. At exec domain.c:1050-1056: set is the new label, sub the snapshot; failure is -EPERM with info = "no new privs" and a record per profile of the old label.-EPERM without a record ("not an apparmor denial per se, so don't log it"). A stack request skips the test ("stacking is always a subset", domain.c:1597-1598).apparmor="DENIED" operation="exec" class="file" info="no new privs" error=-1 profile="demo" name="/usr/bin/demo-helper" comm="demo" requested_mask="x" denied_mask="x" fsuid=0 ouid=0 target="demo-helper"; for cx target="demo//worker"; for ux target="unconfined"; for px -> &sandbox target="demo-report//&sandbox".changeprofile sandbox written to /proc/self/attr/current by demo failed, with no AppArmor record for the request.px -> &sandbox fails: the stack is built on the profile that attaches to the program, demo-report, so demo is not in demo-report//&sandbox. With pix and no attaching profile the base is demo./usr/bin/demo is a copy of a shell and the demo-* programs are copies of cat that print /proc/self/attr/current.do_setattr (lsm.c:853) maps changeprofile, stack and, on attr/exec, exec and stack to aa_change_profile (domain.c:1484). Now: aa_replace_current_label. At exec: aa_set_current_onexec, consumed by handle_onexec (domain.c:928). Observed on a running kernel.
do_setattr lsm.c:853-927 accepts on current: changehat, permhat, changeprofile, permprofile, stack; on exec: exec, stack. The perm forms only test. Another word is refused with -EINVAL and logged; observed: apparmor="DENIED" operation="setprocattr" info="current" error=-22 profile="demo" comm="demo".int aa_change_profile(const char *fqname, int flags) domain.c:1484-1663. The name is parsed with aa_label_parse(label, fqname, GFP_KERNEL, true, false); a name that is not loaded: info = "label not found", -ENOENT.AA_MAY_CHANGE_PROFILE (now) or AA_MAY_ONEXEC (at exec); a stack request matches & in front of the name. An unconfined profile is allowed.aa_replace_current_label(new) prepares and commits new credentials task.c:48-91. At exec domain.c:1630-1635: aa_set_current_onexec(target, stack) stores the label in ctx->onexec task.c:125-133; apparmor_getprocattr prints it for attr/exec lsm.c:839-840.handle_onexec first runs profile_onexec domain.c:798-869 for each in-scope profile: the executable's name is matched on the file DFA and the row needs AA_MAY_ONEXEC (info = "no change_onexec valid for executable"); then a NUL step and the match of the target label. Then in-scope profiles become the target (or are merged with it for a stack); profiles of other namespaces run profile_transition as usual.demo writing to its own files: after exec sandbox, attr/exec read sandbox (enforce) and attr/current read demo (enforce); the program executed next read sandbox (enforce), also when it was demo-helper, whose exec rule is px. Reading attr/exec with nothing pending failed with "Invalid argument". exec learner, which no rule allows: the write failed and apparmor="DENIED" operation="change_onexec" class="file" profile="demo" name="learner" comm="demo" target="learner" was logged. changeprofile learner: the same with operation="change_profile".aa-exec -p sandbox -- cat /proc/self/attr/current printed sandbox (enforce).kernel.apparmor_restrict_unprivileged_unconfined turns a change requested by an unprivileged unconfined task into a stack with unconfined domain.c:882-926./usr/bin/demo is a copy of a shell and the demo-* programs are copies of cat that print /proc/self/attr/current.change_onexec, so a task that drops CAP_MAC_OVERRIDE after asking is stacked with unconfined"; "changeprofile &name is audited as operation="change_profile"".aa_change_hat (domain.c:1319-1445) builds the hat label with change_hat (domain.c:1169), stores previous and token with aa_set_current_hat (task.c:145) and returns with aa_restore_previous_label (task.c:185). A token mismatch is logged as KILLED. Observed on a running kernel. Known discrepancy, also observed: a change_onexec request made inside a hat overwrites the stored token (task.c:125-133).
changehat <token as 16 hex digits>^<name>; split_token_from_name parses the token with simple_strtoull(args, &name, 16) and needs the ^ procattr.c:80-94. Up to 16 names separated by NUL bytes may follow; the first that works is used procattr.c:104-142. permhat tests only.int aa_change_hat(const char *hats[], int count, u64 token, int flags) domain.c:1319-1445. change_hat domain.c:1169-1300: under the namespace lock, for each in-scope profile of the label, aa_find_child(root, name) where root is the profile, or its parent when the task is already in a hat; the child must have the hat flag ("target not hat", -EPERM). Not found: "hat not found" (-ENOENT) or, for a profile without children, "no hats defined" (-ECHILD); these are logged only when several names were given or in complain mode, where a learning hat is created.aa_set_current_hat(label, token) task.c:145-174: the first entry stores the old label in ctx->previous and the token; entering another hat later needs the same token; it also drops a pending change_onexec request. aa_restore_previous_label(token) task.c:185-209. A mismatch returns -EACCES, and aa_change_hat sets perms.kill, so the record is KILLED and the task is sent the profile's kill signal domain.c:1434-1442.demo writing to its own file: after changehat 00000000000004d2^admin, attr/current read demo//admin (enforce) and attr/prev read demo (enforce); changehat 00000000000004d2^ returned to demo (enforce). With token 1 the shell was killed (exit status 137): apparmor="KILLED" operation="change_hat" class="file" info="failed token match" error=-13 profile="demo//admin" comm="demo" target="demo". ^nosuch and ^worker (a child profile, not a hat): the write failed, the label stayed demo (enforce), no record.demo (enforce) with the same token; the parent stayed demo//admin (enforce). The task context, with previous and token, is copied at fork task.h:68-75./usr/bin/demo is a copy of a shell and the demo-* programs are copies of cat that print /proc/self/attr/current.aa_set_current_onexec stores the stack flag of the request in ctx->token task.c:125-133, the field that holds the hat token task.h:34-41; handle_onexec later reads that field as the flag domain.c:1028-1030. So an accepted exec NAME written to attr/exec leaves the token 0 and an accepted stack NAME leaves it 1. Observed, in a run of its own (findings/kernel/observed/run3-output.txt in the map's repository; the same guest; profile demo with the hats low and admin, where low has change_profile -> sandbox, and change_profile -> &sandbox,; the task entered low with the token 0x4d2): after exec sandbox, changehat 0000000000000000^admin entered the sibling hat and attr/current read demo//admin (enforce); after stack sandbox, changehat 0000000000000001^ returned the task to demo (enforce), and the real token got it killed. With nothing pending, each of the two writes got the task killed with info="failed token match". Limits: the rules of the hat must allow a change_onexec or stack_onexec request and the write to attr/exec; token 0 without a hat name is refused before the comparison ("NULL hat and NULL magic", procattr.c:115-118), so the exec form reaches sibling hats and the stack form reaches the parent. This is a defect and not how a hat is meant to be left: the token is the only lock on a hat (Hats, scene "The token is the only lock").Next: labels in the kernel for the object, profile attachment for the search, exec modes and named exec transitions for the rules, safe and unsafe exec for the environment, change_profile rules and hats for asking, profile stacking for several profiles.
apparmor_bprm_creds_for_exec computes the label of the new program; each profile answers through profile_transition, or through handle_onexec when a request is pending; x_to_label looks up, then falls back; the result passes the no_new_privs test and the tracer test and may request a secure exec; aa_change_profile and aa_change_hat change the label without exec.Basis of the statements on this page: "code" means the kernel source of mainline Linux at commit 97d73c825 was read and not run; "observed" means seen on a Debian guest with kernel 7.3.4 in a disposable virtual machine, with the guest's apparmor_parser 5.0.2; domain.c, task.c, procattr.c and the headers they use are the same in that kernel and in the tree the map describes. One function they call is not: aa_dfa_leftmatch (match.c), the walker of the attachment search behind px and cx, steps without the retry of a diff-encoded state in 7.3.4 and with match_char in the tree. "derived" means reasoned from that code.
profile demo /usr/bin/demo {
include <abstractions/base>
/usr/bin/demo mr,
/usr/bin/{cat,sleep} mrix,
@{PROC}/@{pid}/attr/{current,exec,prev} rw,
signal (receive),
audit /usr/bin/demo-tool ix,
/usr/bin/demo-helper px,
/usr/bin/demo-worker cx,
/usr/bin/demo-free ux,
/usr/bin/demo-other pix,
/usr/bin/demo-lost px,
audit /usr/bin/demo-named px -> sandbox,
/usr/bin/demo-gone px -> notloaded,
/usr/bin/demo-report px -> &sandbox,
/usr/bin/demo-plugin pix -> &sandbox,
/usr/bin/demo-env-px px,
/usr/bin/demo-env-Px Px,
change_profile -> sandbox,
profile worker /usr/bin/demo-worker { ... }
^admin { ... }
}
/usr/bin/demo is a copy of dash; the demo-* programs are copies of cat, run as demo-X /proc/self/attr/current; demo-env-px and demo-env-Px are copies of od. Profiles demo-helper, demo-report and demo-env attach to their programs; sandbox and learner (complain mode) have no attachment.
| Step | Code | Where |
|---|---|---|
newest label of bprm->cred | aa_get_newest_label(cred_label(bprm->cred)) | domain.c:1007 |
| no_new_privs snapshot | ctx->nnp = aa_get_label(label) | domain.c:1016-1018 |
| pending request | handle_onexec(subj_cred, label, ctx->onexec, ctx->token, bprm, buffer, &cond, &unsafe) | domain.c:1028-1030 |
| exec rules | fn_label_build(label, profile, GFP_KERNEL, profile_transition(...)) | domain.c:1032-1035 |
| no_new_privs test | !aa_label_is_unconfined_subset(new, ctx->nnp): -EPERM, "no new privs" | domain.c:1050-1056 |
| traced task | may_change_ptraced_domain(bprm->cred, new, &info): "ptrace prevents transition" | domain.c:1063-1068 |
| secure exec | bprm->secureexec = 1 | domain.c:1070-1078 |
| personality | PER_CLEAR_ON_SETID is added to bprm->per_clear when the proxy differs | domain.c:1080-1089 |
| the result | set_cred_label(bprm->cred, new) | domain.c:1090-1092 |
| committing | aa_inherit_files, pdeath_signal = 0, __aa_transition_rlimits | lsm.c:957-973 |
| committed | aa_clear_task_ctx_trans(task_ctx(current)) | lsm.c:979-985 |
All code.
| Bits | Name | Meaning |
|---|---|---|
0x00ffffff | AA_X_INDEX_MASK | index into the profile's string table |
0x0c000000 | AA_X_TYPE_MASK | AA_X_NONE 0, AA_X_NAME 0x04000000, AA_X_TABLE 0x08000000 |
0x10000000 | AA_X_UNSAFE | do not request a secure exec |
0x20000000 | AA_X_CHILD | search the profile's children |
0x40000000 | AA_X_INHERIT | fallback: keep the profile |
0x80000000 | AA_X_UNCONFINED | fallback: the namespace's unconfined label |
file.h:48-64 (code).
Rule in demo | Lookup (code) | Label of the new program (observed) |
|---|---|---|
ix | none; ix fallback | demo (enforce) |
px | find_attach over the namespace | demo-helper (enforce) |
cx | find_attach over the children of demo | demo//worker (enforce) |
ux | none; ux fallback | unconfined |
pix, nothing attaches | search, then ix fallback | demo (enforce) |
px, nothing attaches | search | Permission denied; info="profile transition not found", target="/usr/bin/demo-lost" |
px -> sandbox | table string | sandbox (enforce) |
px -> notloaded | table string | Permission denied; info="profile transition not found", target="notloaded" |
px -> &sandbox | table string, then search, then merge | demo-report//&sandbox (enforce) |
pix -> &sandbox, nothing attaches | table string, search, fallback, merge | demo//&sandbox (enforce) |
| no exec rule | Permission denied; requested_mask="x" denied_mask="x" | |
px / Px to the same program | AT_SECURE 0 / 1 |
info= | When | Where |
|---|---|---|
ix fallback | type none or a failed lookup, with inherit | domain.c:626 |
ux fallback | the same with unconfined | domain.c:636 |
conflicting profile attachments | two attachments tie in find_attach | domain.c:33-37 domain.c:495-499 |
conflicting profile attachments - ix fallback, - ux fallback | a tie followed by a fallback | domain.c:622-623 domain.c:632-633 |
profile transition not found | exec permission but no label | domain.c:746 |
could not create null profile | complain mode, allocation failed | domain.c:762 |
no new privs | the subset test failed | domain.c:1054 |
ptrace prevents transition | the tracer may not trace the new label | domain.c:80 |
change_profile onexec | default of a change_onexec check | domain.c:807 |
no change_onexec valid for executable | the executable's row lacks the onexec permission | domain.c:840 |
failed to build target label | building the label failed | domain.c:972 domain.c:1641 |
change_profile unprivileged unconfined converted to stacking | the sysctl restriction applied | domain.c:896 |
All code; ix fallback, profile transition not found and no new privs were also observed.
Under setpriv --no-new-privs, from demo | Result (observed) |
|---|---|
ix | demo (enforce) |
px | Operation not permitted; info="no new privs" error=-1 ... target="demo-helper" |
cx | Operation not permitted; target="demo//worker" |
ux | Operation not permitted; target="unconfined" |
px -> &sandbox | Operation not permitted; target="demo-report//&sandbox" |
pix -> &sandbox, nothing attaches | demo//&sandbox (enforce) |
changeprofile sandbox | the write fails; no record for the request |
The test: every profile of the snapshot that is missing from the new label must be an unconfined profile label.c:574-593 (code). Stack requests are not tested domain.c:1597-1598 (code).
| File | Command | Kernel call | Operation in the log |
|---|---|---|---|
attr/current | changeprofile NAME | aa_change_profile(NAME, AA_CHANGE_NOFLAGS) | change_profile |
attr/current | permprofile NAME | aa_change_profile(NAME, AA_CHANGE_TEST) | change_profile |
attr/current | stack NAME | aa_change_profile(NAME, AA_CHANGE_STACK) | stack |
attr/current | changehat TOKEN^NAME | aa_change_hat(names, count, token, AA_CHANGE_NOFLAGS) | change_hat |
attr/current | permhat TOKEN^NAME | the same with AA_CHANGE_TEST | change_hat |
attr/exec | exec NAME | aa_change_profile(NAME, AA_CHANGE_ONEXEC) | change_onexec |
attr/exec | stack NAME | aa_change_profile with AA_CHANGE_ONEXEC and AA_CHANGE_STACK | stack_onexec |
| either | anything else | -EINVAL | setprocattr, info="current" or "exec" |
lsm.c:853-927, audit.h:92-100 (code).
struct aa_task_ctx task.h:34-41 (code):
| Field | Set by | Cleared by |
|---|---|---|
nnp | the first exec, change_hat or change_profile under no_new_privs while confined | the end of the task |
onexec | aa_set_current_onexec | exec committed; entering a hat; a change to unconfined or to another namespace |
previous | aa_set_current_hat, first entry | aa_restore_previous_label; exec committed |
token | aa_set_current_hat; also written by aa_set_current_onexec (the stack flag) | with previous |
All four are copied to a child at fork task.h:68-75 (code; the hat part observed).
Write by demo | Result (observed) |
|---|---|
changehat 00000000000004d2^admin | attr/current: demo//admin (enforce); attr/prev: demo (enforce) |
changehat 00000000000004d2^ | demo (enforce) |
changehat 0000000000000001^ while in the hat | the task is killed; apparmor="KILLED" operation="change_hat" class="file" info="failed token match" error=-13 profile="demo//admin" comm="demo" target="demo" |
changehat 00000000000004d2^nosuch | the write fails; no record |
changehat 00000000000004d2^worker (a child profile) | the write fails; no record |
in the hat, a forked child writes changehat 00000000000004d2^ | the child is demo (enforce), the parent stays in the hat |
Errors of aa_change_hat (code): "unconfined can not change_hat" -EPERM; "conflicting targets types" -EPERM; "target not hat" -EPERM; "hat not found" -ENOENT; "no hats defined" -ECHILD; "failed token match" -EACCES and a kill domain.c:1169-1300 domain.c:1319-1445.
By the titles under which they are tracked (Bugs found while building this map):
ix -> &name and ux -> &name run without the stack when name is not loaded.find_attach keeps its candidate and conflict state across goto restart.find_attach stores max(count, xmatch_len) but compares the raw count (latent).change_onexec, so a task that drops CAP_MAC_OVERRIDE after asking is stacked with unconfined.changeprofile &name is audited as operation="change_profile".Not yet tracked there: "Kernel: a change_onexec request made inside a hat overwrites the hat token, so the hat can be left with token 0 or 1". aa_set_current_onexec writes the stack flag of the request into ctx->token task.c:125-133 (code). Observed in a run of its own (findings/kernel/observed/run3-output.txt in the map's repository; after exec sandbox written to attr/exec in a hat that allows it, changehat 0000000000000000^admin entered the sibling hat; after stack sandbox, changehat 0000000000000001^ returned to the parent profile).
LSM_UNSAFE_SHARE is meant to stay unmediated.A task's credentials hold a pointer to a struct aa_label (include/cred.h:22); the label is a sorted vector of struct aa_profile * (include/label.h:127-148). The ps output was recorded on a running kernel.
cred_label(cred) reads AppArmor's part of the credentials' security blob, whose size is sizeof(struct aa_label *) cred.h:22-28 lsm.c:1774. Credentials that are copied take a reference on the newest version of the label lsm.c:97-110.ps listing shows three sleep 30 tasks started with aa-exec -p demo, -p sandbox and -p 'demo//&sandbox'; ps -eo label reads /proc/PID/attr/current.demo, sandbox and learner (complain mode) in the root namespace; web and db loaded into a namespace with apparmor_parser -n c1; three senders with one signal rule each; svc for replacement.struct aa_label (include/label.h:127-148); order by profile_cmp (label.c:137-155); a profile's own label is set up in aa_alloc_profile (policy.c:375-420); compound labels are found or created in the namespace's label set (label.c:938-947).
count, node (the tree), rcu, proxy, hname (a cached text, may be NULL), flags, secid, size, mediates, and a union of vec[] with, for a label inside a profile, profile[2] and the profile's rules[].struct aa_profile ends in struct aa_label label policy.h:257-281; aa_alloc_profile sets label.vec[0] = profile, the profile flag and label.hname to the profile's name policy.c:375-420. labels_profile(label) is the last entry label.h:166-169.ns_cmp compares level, then the namespace names; profile_cmp treats two profiles as equal when they are the same object or share the name pointer, else compares namespaces, then strcmp of the names. aa_vec_unique sorts and removes duplicates: insertion sort up to 8 entries, sort() above label.c:274-320.aa_vec_find_or_create_label label.c:938-947: __vec_find label.c:735-758, else allocate and __label_insert, which returns an equal label already in the tree label.c:677-721. A vector of length 1 is the profile's own label label.c:915-916.mediates is the OR of the members' class masks.label_for_each, label_for_each_confined (skips members in unconfined mode) and the fn_for_each forms, which call a function per member and keep the last error label.h:175-236.aa_label_merge (label.c:1248-1287) with label_merge_insert (label.c:1081-1141); fn_label_build (include/lib.h:289-344) with aa_vec_unique and aa_vec_find_or_create_label.
struct aa_label *aa_label_merge(struct aa_label *a, struct aa_label *b, gfp_t gfp) label.c:1248-1287: a == b returns the newest a; otherwise both are taken in their newest version and a label with room for a->size + b->size entries is allocated.label_merge_insert label.c:1081-1141 fills it with label_for_each_in_merge, which steps through both vectors in order and returns equal heads once label.c:994-1023. If no member was stale and the result is as long as a (or b), that label is returned. Otherwise the new label is inserted into the label set, where an equal one wins.stack NAME domain.c:1625; an exec rule whose target begins with & domain.c:651-658; change_onexec with stack domain.c:872-880; the label cached on an open file, which grows to the union of the labels that passed a check on it file.c:469-488; the two labels cached on a unix socket af_unix.c:652-715.fn_label_build(L, P, GFP, FN) lib.h:289-344; fn_label_build_in_scope lib.h:347-361 uses one function for the members in the label's namespace and another for the rest.aa_label_is_subset, label.c:547-558).labels_ns() (include/label.h:162) is the namespace of the last member. "In scope" means the same namespace, "in view" also its descendants (include/lib.h:83-94, policy_ns.c:40-54). The three reads were observed.
labels_ns(X) is vec_ns(&X->vec[0], X->size), the namespace of vec[size - 1] label.h:52-54 label.h:162-164. The sort key starts with the namespace's level label.c:109-126, and the root has level 0.aa_ns_visible(curr, view, subns) policy_ns.c:40-54: true for the same namespace; with subns also when curr is an ancestor of view. aa_in_scope passes false, aa_in_view true lib.h:83-88.label_for_each_in_scope visits the members whose namespace is the label's lib.h:90-94 label.h:200-222. change_profile checks permission in those members and replaces only those domain.c:1569-1573 domain.c:1599-1604; change_onexec domain.c:947-961 and change_hat domain.c:1290-1293 do the same. An exec without a pending request asks every member.aa_getprocattr returns -EACCES when the label's namespace is not visible from the reader's, and prints with the reader's namespace as the point of view procattr.c:31-69.aa-exec -p 'demo//&:c1:web' -- cat /proc/self/attr/current printed web (enforce); the same task read from a root shell: demo//&:c1:web (enforce). A task in :c1:web reading /proc/1/attr/current, and the file of a task labelled demo: "Permission denied". The same reader on a task labelled demo//&:c1:web: web (enforce).aa_label_snxprint (label.c:1649-1699) and aa_profile_snxprint (label.c:1538-1577) print; aa_label_strn_parse (label.c:1892-1978) parses, splitting with aa_label_strn_split on stacksplitdfa (include/label.h:322). The printed labels and the refusal were observed.
int aa_label_snxprint(char *str, size_t size, struct aa_ns *ns, struct aa_label *label, int flags) label.c:1649-1699; flags FLAG_SHOW_MODE 1, FLAG_VIEW_SUBNS 2, FLAG_HIDDEN_UNCONFINED 4 label.h:297-301.:<name>: is written when the member's namespace differs from the reader's and from the namespace of the member printed before it. So :c1:db//&web names two profiles of c1; this is the form the kernel prints and also one it accepts. (mode), if any visible member is not its namespace's unconfined profile; label_modename gives the visible members' common mode, not counting unconfined members, or mixed. No visible member: unconfined when the caller passed FLAG_HIDDEN_UNCONFINED, else --- label.c:1683-1687.struct aa_label *aa_label_strn_parse(struct aa_label *base, const char *str, size_t n, gfp_t gfp, bool create, bool force_stack) label.c:1892-1978. A leading &, or force_stack, puts the members of base first. Splitting: aa_label_strn_split runs aa_dfa_matchn_until on stacksplitdfa label.h:322-332.: is resolved from base, any other from currbase, which moves to a member as soon as that member is in another namespace. A piece may be :ns:name, :ns://name, or :ns: alone for that namespace's unconfined profile policy.c:663-690. A piece that is not found: -ENOENT.create true the compound label is created if it does not exist yet label.c:1957-1968; aa_change_profile and exec targets pass true. If the creation fails, the tree returns -ENOMEM; the guest's 7.3.4 returned -ENOENT at this place, and that is the one difference in label.c between the two. The refusal shown on the slide does not come from here: it is the lookup of a piece, the same code in both.aa-exec -p LABEL -- cat /proc/self/attr/current: sandbox//&demo gave demo//&sandbox (enforce); demo//&learner gave demo//&learner (mixed); learner gave learner (complain); demo//&unconfined gave demo//&unconfined (enforce); unconfined gave unconfined. :c1:web//&:c1:db and :c1:web//&db both read db//&web (enforce) from inside and :c1:db//&web (enforce) from the root namespace. :c1:web//&demo: apparmor="DENIED" operation="change_onexec" class="file" info="label not found" error=-2 profile="unconfined" name=":c1:web//&demo" comm="aa-exec".//&.apparmor_getprocattr (lsm.c:828-851) picks the label; aa_getprocattr (procattr.c:31-69) prints it for the reader's namespace or returns -EACCES. do_setattr (lsm.c:853-927) accepts the commands. The outputs and errors were observed.
current (mode 0666), prev (0444), exec (0666) in /proc/PID/attr/, and the same three in /proc/PID/attr/apparmor/. The plain names go to the first security module that answers them security.c:3946-3957; the directory always means AppArmor. lsm_get_self_attr(2) and lsm_set_self_attr(2) reach the same code lsm.c:788-826 lsm.c:929-941.current: aa_get_newest_cred_label(__task_cred(task)); prev: the task context's previous; exec: its onexec; prev or exec with nothing stored: -EINVAL.int aa_getprocattr(struct aa_label *label, char **string, bool newline) procattr.c:31-69: -EACCES if the label's namespace is not visible from the reader's; else aa_label_snxprint(..., FLAG_SHOW_MODE | FLAG_VIEW_SUBNS | FLAG_HIDDEN_UNCONFINED) and a newline.admin, attr/current read demo//admin (enforce) and attr/prev read demo (enforce); after exec sandbox was written, attr/exec read sandbox (enforce); attr/exec with nothing pending: "Invalid argument"; attr/apparmor/current returned the same text as attr/current (seen in the first run, with other profile names: ka//&:kns:kp (enforce) from both). A word that is no command: apparmor="DENIED" operation="setprocattr" info="current" error=-22 profile="demo" comm="demo".apparmor="DENIED" operation="open" class="file" profile="svcc" name="/proc/3379/attr/current" comm="cat" requested_mask="r" denied_mask="r" fsuid=0 ouid=0.aa_label_match (label.c:1443-1456): label_compound_match feeds the whole label, then label_components_match each member with aa_perms_accum. Callers: profile_signal_perm (ipc.c:78) and profile_ptrace_perm (task.c:254). Unix: match_label (af_unix.c:173). The nine results were observed.
xcheck_labels(sender, target, profile, profile_signal_perm(..., target, MAY_WRITE, ...), profile_signal_perm(..., sender, MAY_READ, ...)): every profile of the sender for send with the target label as peer, every profile of the target for receive with the sender label as peer perms.h:156-197. An unconfined profile, and one whose policydb does not mediate signals, allows ipc.c:87-95.int aa_label_match(const struct aa_profile *profile, struct aa_ruleset *rules, struct aa_label *label, aa_state_t state, bool inview, u32 request, struct aa_perms *perms) label.c:1443-1456.//& and the member. A member is its name (hname); a member of another namespace is :, the namespace name, :, the name (match_component, label.c:1294-1310). The members come in the vector's order, so a rule must spell the stack in sorted order.aa_perms_accum, which ANDs allow and ORs deny perms.h:134-154. A member that leads to state 0 gives no permissions.read or trace, the tracee's for readby or tracedby; the walk starts at the label class, steps over the byte of the ptrace class and continues with aa_label_match lib.c:393-405.match_label af_unix.c:173-193 is called for each profile of the peer label that is in scope, with the peer profile's name only.sleep tasks labelled demo, sandbox and demo//&sandbox (their profiles have signal (receive),) and the shell builtin kill -TERM run under three sender profiles. The table on the slide is the result. Records: apparmor="DENIED" operation="signal" class="signal" profile="sender1" comm="demo" requested_mask="send" denied_mask="send" signal=term peer="sandbox" and the same with peer="demo//&sandbox"; for the sender with the stack rule, peer="demo" and peer="sandbox".aa_label_replace (label.c:849-875) redirects the shared aa_proxy and sets FLAG_STALE; aa_get_newest_label (include/label.h:408) follows it; aa_schedule_stale_label_replacement (task.c:108) swaps the credentials. Compound labels: __aa_labelset_update_subtree (label.c:2161). Observed on a running kernel.
struct aa_proxy holds a counted pointer to a label label.h:104-107; every label has one, and a replacement takes over the proxy of the label it replaces (__proxy_share, label.c:90-97).share_name(old, new), then __replace_profile(old, new) policy.c:1066-1110, which calls aa_label_replace(&old->label, &new->label) label.c:849-875: the proxy is pointed at the new label and the old one gets FLAG_STALE (__aa_proxy_redirect, label.c:75-88), and the new label takes the old one's place in the tree. A load that is byte for byte the loaded profile is skipped ("same as current profile, skipping").aa_label_remove points the proxy at the namespace's unconfined label label.c:785-798 policy.c:200-243.aa_get_newest_label(l) returns l->proxy->label when l is stale. Hooks begin with __begin_current_label_crit_section cred.h:149-161 cred.h:206-209; begin_current_label_crit_section also queues aa_replace_stale_label_tw_func as task work for the return to user space, which commits credentials with the newest label cred.h:222-231 task.c:93-117 task.c:48-91.__aa_labelset_update_subtree searches the label set of the namespace and of its children for labels with a stale member and replaces each by a label built from the members' newest versions (__label_update).svc tried to read two files every three seconds while the profile was replaced four times and then removed. It followed every version: denied, then /etc/hostname readable, then both files, then neither, then, after apparmor_parser -R, label unconfined and both readable.sandbox//&svc in the same run: it followed the first replacement (/etc/hostname became readable) and none after it: the rule added by the third version did not apply, the rule removed by the fourth stayed, and after the removal its label still read sandbox//&svc (enforce). With fresh stacks, a removal as the first change gave sandbox//&unconfined (enforce), and a change to complain mode as the first change gave (mixed); the change back did not show.__label_replace is called inside AA_BUG". In __label_insert the call that puts the updated label into the tree is written inside an assertion, AA_BUG(!__label_replace(this, label)) label.c:706, and AA_BUG does not evaluate its argument without CONFIG_SECURITY_APPARMOR_DEBUG_ASSERTS lib.h:57-72. __label_update reaches that line with the old compound label still in the tree, then takes the old label out label.c:2063-2120. After the first update no version of the stack is in a label set, and the search for stale labels walks the set label.c:2025-2049, so later replacements and removals of a member do not find it. Observed (the bullet above): a tightened profile was not enforced on the stacked task and a removed profile kept confining it. That is a defect, not the intended behaviour: the code is written to rebuild every stale stack after each load. The guest's kernel is built without CONFIG_SECURITY_APPARMOR_DEBUG, which the assertions depend on; the lines are the same in the tree the map describes.Next: exec and domain transitions for how labels are chosen, profile stacking and policy namespaces for the outside view, signal, ptrace and unix rules for peers, matching at run time for the walk, the library's label calls for reading.
aa_label_snxprint and consumed by aa_label_strn_parse; a peer label is fed to the policydb whole, then member by member; a stale label is followed through its proxy.Basis of the statements on this page: "code" means the kernel source of mainline Linux at commit 97d73c825 was read and not run; "observed" means seen on a Debian guest with kernel 7.3.4 in a disposable virtual machine, with the guest's apparmor_parser 5.0.2. Of the files this page rests on, label.c differs between that kernel and the tree only in the error code returned when a compound label cannot be created; task.c, procattr.c, ipc.c, policy.c, af_unix.c and the headers are the same. "derived" means reasoned from that code.
Field of struct aa_label | Meaning |
|---|---|
count | reference count |
node | position in the label set (a red-black tree) |
proxy | points at the newest version of this label |
hname | cached text, may be NULL; for a profile's label the profile's name |
flags | see below |
secid | the number other subsystems use for this label |
size | number of members |
mediates | one bit per rule class any member mediates |
vec[] | the members, sorted, NULL after the last; inside a profile: profile[2] and rules[] |
label.h:127-148 (code).
| Flag | Value | Meaning |
|---|---|---|
FLAG_HAT | 1 | the profile is a hat |
FLAG_UNCONFINED | 2 | on a compound label only if every member has it |
FLAG_NULL | 4 | a learning profile |
FLAG_IX_ON_NAME_ERROR | 8 | inherit when the executable's name cannot be built |
FLAG_IMMUTIBLE | 0x10 | no replacement |
FLAG_IN_TREE | 0x100 | the label is in a label set |
FLAG_PROFILE | 0x200 | the label is a profile's own |
FLAG_STALE | 0x800 | replaced or removed |
label.h:81-101 (code; the list there is longer).
1. Namespace level, lower first (the root is 0). 2. Namespace name, strcmp. 3. Profile name (hname, with the parents of a child: demo//worker), strcmp.
label.c:109-155 (code). Observed: sandbox//&demo is stored and printed as demo//&sandbox; :c1:web//&:c1:db as :c1:db//&web; demo (root) comes before :c1:web.
| Function | Input | Result |
|---|---|---|
aa_label_merge(a, b, gfp) label.c:1248-1287 | two labels | their union; a or b itself if nothing was added |
aa_vec_find_or_create_label(vec, len, gfp) label.c:938-947 | a sorted, unique vector | the label of the set with that vector, created if missing |
fn_label_build(L, P, GFP, FN) lib.h:289-344 | a label and a function per member | the label of all answers together |
aa_label_strn_parse(base, str, n, gfp, create, force_stack) label.c:1892-1978 | text | the label, or -ENOENT, -EINVAL, -ENOMEM |
aa_label_is_subset(set, sub) label.c:547-558 | two labels | whether every member of sub is in set |
aa_label_is_unconfined_subset(set, sub) label.c:574-593 | two labels | the same, not counting unconfined members of sub |
All code.
aa_label_snxprint(str, size, ns, label, flags) label.c:1649-1699 (code):
| Case | Text |
|---|---|
| a member in the reader's namespace | its name |
| a member in a visible child namespace | :<namespace, relative to the reader>:<name>, the prefix only if the previous printed member was in another namespace |
| a member the reader cannot see | left out |
| between members | //& |
| no visible member | unconfined with FLAG_HIDDEN_UNCONFINED, else --- |
with FLAG_SHOW_MODE, some visible member is not an unconfined profile | (enforce), (complain), (kill), (user) or (mixed) |
Observed through /proc/PID/attr/current:
Label asked for with aa-exec -p | Read by the task itself | Read from the root namespace |
|---|---|---|
sandbox//&demo | demo//&sandbox (enforce) | the same |
demo//&sandbox//&demo | demo//&sandbox (enforce) | the same |
demo//&learner (learner is in complain mode) | demo//&learner (mixed) | the same |
learner | learner (complain) | the same |
demo//&unconfined | demo//&unconfined (enforce) | the same |
unconfined | unconfined | the same |
:c1:web | web (enforce) | :c1:web (enforce) |
demo//&:c1:web | web (enforce) | demo//&:c1:web (enforce) |
:c1:web//&:c1:db | db//&web (enforce) | :c1:db//&web (enforce) |
:c1:web//&db | db//&web (enforce) | :c1:db//&web (enforce) |
:c1:web//&demo | refused: info="label not found" error=-2 | |
sandbox//&:c1:web//&demo | refused: info="label not found" error=-2 |
A shell that wrote stack demo to its own attr/current while unconfined read demo//&unconfined (enforce).
| File | Read returns | Errors |
|---|---|---|
/proc/PID/attr/current, attr/apparmor/current | the newest label of the task's credentials, for the reader's namespace, with the mode and a newline | EACCES: the label's namespace is not visible to the reader |
attr/prev, attr/apparmor/prev | the label saved by change_hat | EINVAL: none saved |
attr/exec, attr/apparmor/exec | the label of a pending change_onexec or stack_onexec | EINVAL: none pending |
lsm.c:828-851, procattr.c:31-69 (code; the three contents and both errors observed). Writing: Exec and domain transitions.
| Class | Who is asked | Input after the class's start state | Label match |
|---|---|---|---|
| signal | every sender profile for send, every target profile for receive | the mapped signal number | aa_label_match: compound, then components |
| ptrace | every tracer profile for read or trace, every tracee profile for readby or tracedby | from the label class: the byte of the ptrace class | aa_label_match |
| unix | the profile and each peer profile in scope | type, protocol, address | match_label: the peer profile's name |
ipc.c:78-116, task.c:254-329, af_unix.c:173-193, af_unix.c:389-426, label.c:1294-1456 (code).
Text fed for a member (code): its name, or : namespace : name for a member of another namespace; members of a compound are separated by //& and come in the label's order.
Observed (targets demo, sandbox, demo//&sandbox; kill -TERM from a shell under the sender profile):
| Sender's rule | demo | sandbox | demo//&sandbox |
|---|---|---|---|
signal (send) set=(term) peer=demo, | sent | denied, peer="sandbox" | denied, peer="demo//&sandbox" |
signal (send) set=(term) peer=demo//&sandbox, | denied, peer="demo" | denied, peer="sandbox" | sent |
peer=demo, and peer=sandbox, | sent | sent | sent |
| Event | What the kernel does (code) |
|---|---|
| a profile is replaced | the new profile shares the old name and proxy; the proxy points at the new label; the old label is stale policy.c:1138-1145 label.c:849-875 |
| a profile is removed | its proxy points at the namespace's unconfined label label.c:785-798 |
| after a load | compound labels with a stale member are rebuilt label.c:2161-2175 |
| a hook runs for a task with a stale label | it uses the proxy's label cred.h:149-161 |
| the task returns to user space | its credentials are replaced by ones with the newest label task.c:93-117 |
| new credentials are prepared | they get the newest label lsm.c:97-110 |
Observed, one run; svc was replaced three times and removed while two shells read /etc/hostname and /etc/shells every three seconds:
svc at that moment | Task labelled svc | Task labelled sandbox//&svc |
|---|---|---|
| version 1: neither file | both denied | both denied |
version 2: /etc/hostname r, | hostname read | hostname read |
version 3: also /etc/shells r, | both read | shells denied |
| version 4: neither | both denied | hostname read |
| removed | unconfined, both read | sandbox//&svc (enforce), hostname read, shells denied |
With fresh stacks (observed): removal as the first change: sandbox//&svcb (enforce) became sandbox//&unconfined (enforce). Complain mode as the first change: sandbox//&svcc (mixed); back to enforce: still (mixed), while a task labelled svcc read svcc (enforce).
| Object | Cached | Used |
|---|---|---|
| open file | the label, grown by merge, and the permissions granted file.h:42-46 | aa_file_perm skips the check when the subject's label is a subset and nothing more is asked file.c:626-678 |
| unix socket | its own label and the peer's af_unix.c:652-715 | the same test before a recheck file.c:598-613 |
| label | hname, its text in its own namespace label.c:1470-1496 | audit records |
All code.
__label_replace is called inside AA_BUG". On a kernel built without CONFIG_SECURITY_APPARMOR_DEBUG_ASSERTS a stacked label follows only the first replacement or removal of a member profile: the call that inserts the updated label is inside AA_BUG() label.c:706 lib.h:57-72. Observed (the tables above). The bug list is Bugs found while building this map.mediates mask and unconfined flag are not computed, because accum_label_info runs in the call that is skipped.labelset_of_merge picks the label set of the namespace that sorts first, while a merged label belongs to the set of its last member label.c:1150-1159; its only caller is in a commented-out block (code; latent).aa_str_perms (file.c:221) is aa_dfa_match plus aa_lookup_condperms; __aa_path_perm (file.c:233) compares and calls aa_audit_file. The example is the three-rule profile demo3.sd of the DFA engine decks.
demo3.sd: /etc/demo/** r,, audit deny @{HOME}/.ssh/** rw,, /usr/bin/[a-z]* ix, in profile demo /usr/bin/demo. Its file DFA has 22 states in 277 slots and a permission table of 8 rows; the numbers are those of Table compression and How the tables are packed.apparmor_file_open lsm.c:465-507 maps the open flags to a request (aa_map_file_to_perms, file.h:112-131) and calls aa_path_perm file.c:287-307, which asks every confined profile of the task's label (fn_for_each_confined). An exec does not come this way: its check is in the exec hook (Exec and domain transitions).aa_state_t aa_str_perms(struct aa_policydb *file_rules, aa_state_t start, const char *name, struct path_cond *cond, struct aa_perms *perms) file.c:221-231.__aa_path_perm file.c:233-251: if (request & ~perms->allow) e = -EACCES; then aa_audit_file(...).aa_path_name path.c:202; how a name can differ from what the program asked for is in The limits of name-based mediation.match_char (match.c:443-455) on the example: state 17, /: slot 51, check 17, next 19. State 19, m: slot 114, check 6, default 21. aa_dfa_match (match.c:518) runs it for every byte up to the NUL.
u32 b = (base)[(state)]; unsigned int pos = base_idx(b) + (C); if ((check)[pos] != (state)) { (state) = (def)[(state)]; if (b & MATCH_FLAG_DIFF_ENCODE) continue; break; } (state) = (next)[pos]; break; inside do { } while (1). base_idx(X) is X & 0xffffff match.c:23. The continue is the next slide.aa_state_t aa_dfa_match(const struct aa_dfa *dfa, aa_state_t start, const char *str) match.c:518-550 fetches the four table pointers once, returns 0 at once when started in state 0, and maps each byte through the equivalence class table first if the DFA has one.u32 in the kernel whatever the stream held: aa_dfa_unpack widens 16-bit default, next and check tables at load match.c:277-305 match.c:411-421.rules->file->start[AA_CLASS_FILE] file.c:244, which is DFA_START, 1, unless the stream says otherwise policy_unpack.c:1029-1032.default[i] < state_count; no unknown flag bits in a base entry; base_idx(base[i]) + 255 < the length of next and check; every next and check entry below state_count. The loader runs it when asked to verify states; Unpacking and verifying policy has the conditions.MATCH_FLAG_DIFF_ENCODE (0x80000000) in base[state]: a miss sets state = default[state] and repeats the lookup with the same input (match.c:447-451). verify_dfa rejects chains that loop (match.c:201-231).
MATCH_FLAG_DIFF_ENCODE 0x80000000, MATCH_FLAG_OOB_TRANSITION 0x20000000. MARK_DIFF_ENCODE 0x40000000 and MARK_DIFF_ENCODE_VERIFIED 0x10000000 are written by the loader while it checks the chains and the second stays set afterwards. In the stream only the two flags may be set: MATCH_FLAGS_INVALID is every other bit of the top byte, the two marks included (0x5f000000), and a base entry with one of them fails the load: "AppArmor DFA state with invalid match flags" match.c:168-171.YYTH_FLAG_DIFF_ENCODE in the table set header match.c:172-177.0x80000000 (the flag, offset 0) and the defaults 6 to 9. State 6 has the entries NUL to 0 and x to 7. The walk shown is derived from those tables.policy/diff-encode; see Table compression.aa_dfa_match, aa_dfa_match_len, aa_dfa_next, aa_dfa_leftmatch, aa_dfa_match_until and aa_dfa_matchn_until (match.c:473-824) all step with match_char.
aa_state_t aa_dfa_match_len(const struct aa_dfa *dfa, aa_state_t start, const char *str, int len) match.c:473-504: "will happily match again the 0 byte and only finishes when @len input is consumed". Callers: an xattr value domain.c:347-348, the : around a namespace name in a peer label label.c:1306-1308, a class number above the table policy.h:337-338.aa_state_t aa_dfa_next(const struct aa_dfa *dfa, aa_state_t state, const char c) match.c:562-579. aa_dfa_null_transition is aa_dfa_next(dfa, start, 0) lib.h:139-144.aa_state_t aa_dfa_leftmatch(const struct aa_dfa *dfa, aa_state_t start, const char *str, unsigned int *count) match.c:816-824 calls leftmatch_fb match.c:741-801: each state entered is stored in a ring of WB_HISTORY_SIZE (32) entries match.h:154-159; when the new state is in the ring (is_loop, match.c:720-739) the rest of the string is walked with aa_dfa_match and the count stops. A final state 0 sets the count to 0. Its only caller is find_attach domain.c:431-433; Profile attachment explains the count.aa_dfa_match_until and aa_dfa_matchn_until match.c:612-708 return at the first state with a non-zero accept entry and report the position. aa_label_strn_split uses them on stacksplitdfa to find //& label.h:322-344; that table and nulldfa are compiled in and unpacked at boot lsm.c:2522-2565.aa_dfa_match_until, aa_dfa_matchn_until and leftmatch_fb have the step written out without the continue: a miss in a diff-encoded state ends in its default state and the byte is not tried there. aa_dfa_match, aa_dfa_match_len, aa_dfa_next and the out-of-band step use match_char in both. Nothing in this deck was observed through the three that differ, and aa_dfa_leftmatch on a diff-encoded attachment table was not run on either kernel (findings/kernel/observed/README.md in the map's repository).aa_dfa_null_transition (include/lib.h:139) steps with byte 0. aa_dfa_outofband_transition (match.c:581-597) needs MATCH_FLAG_OOB_TRANSITION in the base word and looks at slot base - 1. The kernel supports one out-of-band input.
aa_state_t aa_dfa_outofband_transition(const struct aa_dfa *dfa, aa_state_t state) match.c:581-597: if (!(b & MATCH_FLAG_OOB_TRANSITION)) return DFA_NOMATCH; then match_char(state, def, base, next, check, -1); with the comment "No Equivalence class remapping for outofband transitions".base_idx(base) < dfa->max_oob fails ("AppArmor DFA out of bad transition out of range"), as does a flagged state when the header lacks YYTH_FLAG_OOB_TRANS. max_oob is fixed at 1; the code that would read a larger number from the header is commented out match.c:348-360. MAX_OOB_SUPPORTED is 1 match.h:44.aa_xattrs_match domain.c:313-375 steps out of band after the executable's name and after each attribute; for an attribute that is present it steps over a NUL and then feeds the value with aa_dfa_match_len. A missing attribute that the profile requires leaves state 0.aa_lookup_condperms (file.c:194-209): perms[accept[state]], or the next row when accept2[state] has ACCEPT_FLAG_OWNER and the fsuid is not the file's owner. aa_lookup_perms (include/policy.h:156) has no owner test. Example: state 21, rows 4 and 5, allow 0x244.
struct aa_perms *aa_lookup_condperms(kuid_t subj_uid, struct aa_policydb *rules, aa_state_t state, struct path_cond *cond) file.c:194-209; the uid passed is current_fsuid() file.c:227. ACCEPT_FLAG_OWNER is 1 policy.h:61-63. A policydb without a table gives &default_perms, all zero file.c:182.static inline struct aa_perms *aa_lookup_perms(struct aa_policydb *policy, aa_state_t state) policy.h:156-165.struct aa_perms perms.h:69-88: allow, deny, subtree, cond, kill, complain, prompt, audit, quiet, hide, xindex, tag, label.0x200 (no match), 2 and 3 0x200 (left by the deny rule), 4 and 5 0x244 (the r rule), 6 and 7 0x10201 with the inherit bit in xindex (the ix rule). State 21 has accept 4, state 20 accept 6, every other state 0; accept2 is 1 on every state except 0 and 1.compute_fperms makes two rows per state and remap_dfa_accept(dfa, 2) sets accept[state] = state * 2 and the owner flag; the policydb gets one row per state. map_old_perms widens the old bits: read gives getattr and open; write gives setattr, create, delete, chmod, chown and open policy_compat.c:78-98.0x200) is in every row, also the row of state 0; that is why stat is allowed on every name (What is not mediated).start[class] is filled at load (policy_unpack.c:1043-1046); RULE_MEDIATES (include/policy.h:331) returns it. Capability: byte cap >> 5, bit 1 << (cap & 0x1f) (capability.c:128-146). Signal: the signal number, then the peer label (ipc.c:93-99).
struct aa_policydb policy.h:110-120: the DFA, the permission table and its size, the string table trans, tags, and aa_state_t start[AA_CLASS_LAST + 1]. A profile has three: rules->policy, rules->file and attach.xmatch policy.h:190-219.AA_CLASS_LAST).start[0] from the stream or 1; for (i = AA_CLASS_FILE + 1; i <= AA_CLASS_LAST; i++) pdb->start[i] = aa_dfa_next(pdb->dfa, pdb->start[0], i);.RULE_MEDIATES(rules, class) policy.h:331-339. A label carries a bit per mediated class, the OR over its profiles, so that a hook can skip a label without a walk: label_mediates label.h:253-256.aa_dfa_next(dfa, state, cap >> 5), request = 1 << (cap & 0x1f), aa_lookup_perms, the profile's modes, aa_check_perms; with state 0 the capability sets stored in the profile are used.aa_dfa_next(dfa, state, ad->signal) and aa_label_match for the peer (Labels in the kernel). Ptrace starts from start[AA_CLASS_LABEL] and steps over the byte for the ptrace class lib.c:393-405.apparmor="DENIED" operation="capable" class="cap" profile="demo" comm="demo" capability=1 capname="dac_override". Observed: a Debian guest with kernel 7.3.4 in a disposable virtual machine, parser 5.0.2; capability.c, lib.c, audit.c and include/policy.h are the same in that kernel and in the tree the map describes, and match.c and policy_unpack.c differ only outside aa_dfa_next and the loop that fills start[] (findings/kernel/observed/README.md in the map's repository).__aa_path_perm (file.c:246) tests request & ~allow; aa_audit_file (file.c:95-154) applies audit, quiet, kill and complain mode. Other classes go through aa_check_perms (lib.c:425-464), which also reads deny and hide. The five results were observed on a running kernel.
aa_audit_file file.c:95-154. No error: request &= perms->audit (or 0xffff when the profile audits everything); nothing left, no record; otherwise an AUDIT record. An error: only the bits not in allow are reported; a bit in kill makes it KILL; request &= ~quiet unless the profile's audit mode is noquiet or all; nothing left, the error is returned silently.aa_audit audit.c:200-237: in complain mode the type becomes ALLOWED and complain_error turns -EACCES into 0 audit.h:206-211; in kill mode DENIED becomes KILL and the task is sent the profile's signal.deny sets the same bits in quiet, audit deny does not (Permissions in the DFA, scene "What becomes of a deny rule"). In the example the rows left by the audit deny rule equal the row of state 0.denied = request & (~perms->allow | perms->deny); an allowed request is logged for bits in audit; a denial returns -EACCES, or -ENOENT if all denied bits are in hide; quiet bits are dropped; aa_select_audit_type audit.c:143-152 gives KILL for a bit in kill, ALLOWED if every denied bit is in complain, else DENIED. aa_apply_modes_to_perms lib.c:364-391 sets those masks from the profile's mode and audit mode first.apparmor="DENIED" operation="mknod" class="file" profile="demo" name="/etc/demo/new" comm="demo" requested_mask="c" denied_mask="c" fsuid=0 ouid=0; apparmor="DENIED" operation="open" class="file" profile="demo" name="/root/.ssh/id_test" comm="demo" requested_mask="r" denied_mask="r" fsuid=0 ouid=0; apparmor="ALLOWED" operation="open" class="file" profile="democ" name="/etc/hostname" comm="democ" requested_mask="r" denied_mask="r" fsuid=0 ouid=0. The plain deny run used the same three rules with deny in place of audit deny (profile demoq); the complain run the same rules without the deny rule and flags=(complain) (profile democ), and the file it read, /etc/hostname, has no rule. A plain deny in a complain-mode profile stays refused and silent: the denied bits are quiet, so aa_audit_file returns the error before the complain-mode branch (file.c:139-149); read from the code, not run.aa_dfa_match, the walker a file check uses (findings/kernel/observed/README.md in the map's repository).audit deny file rule in a complain-mode profile is allowed and logged ALLOWED (the denial is not quiet, so it reaches the complain-mode branch of aa_audit). Read from the code here; not part of this run.Next: the packing lab and table compression for the arrays, permissions in the DFA for the rows, exec and domain transitions and labels in the kernel for what continues from a row, reading a denial for the record.
match_char steps through base, check, next and default; accept[state] indexes the permission table, with an owner and an other row for file rules; start[class] begins every other class; a file request needs request & ~allow == 0, and audit and quiet decide the record.Basis of the statements on this page: "code" means the kernel source of mainline Linux at commit 97d73c825 was read and not run; "tree" means a number comes from the parser built from the AppArmor commit 836052d21, as recorded in Table compression, Permissions in the DFA and How the tables are packed; "derived" means reasoned from those tables or that code; "observed" means seen on a Debian guest with kernel 7.3.4 in a disposable virtual machine, where the files concerned (file.c, lib.c, audit.c) are the same as in the tree the map describes. match.c is not the same: in 7.3.4 aa_dfa_match_until, aa_dfa_matchn_until and leftmatch_fb have the step written out without the retry of a diff-encoded state, where the tree uses match_char. Nothing on this page was observed through those three.
| Name | Where | What |
|---|---|---|
match_char(state, def, base, next, check, C) | match.c:443-455 | pos = base_idx(base[state]) + C; check[pos] == state: state = next[pos]; else state = def[state], and again with the same C if the base entry has MATCH_FLAG_DIFF_ENCODE |
base_idx(X) | match.c:23 | X & 0xffffff |
DFA_NOMATCH, DFA_START | match.h:17-18 | 0 and 1 |
aa_state_t | match.h:135 | unsigned int |
DEFAULT_TABLE, BASE_TABLE, NEXT_TABLE, CHECK_TABLE, ACCEPT_TABLE, ACCEPT_TABLE2 | match.h:93-99 | u32 * views of the tables; EQUIV_TABLE is u8 * |
All code.
| Bit | Name | Meaning |
|---|---|---|
0x80000000 | MATCH_FLAG_DIFF_ENCODE | a miss continues in the default state with the same input |
0x40000000 | MARK_DIFF_ENCODE | set and cleared by verify_dfa while it follows a chain |
0x20000000 | MATCH_FLAG_OOB_TRANSITION | the state has an out-of-band transition at slot base - 1 |
0x10000000 | MARK_DIFF_ENCODE_VERIFIED | left set by verify_dfa on a checked diff-encoded state |
0x5f000000 | MATCH_FLAGS_INVALID | every bit of the top byte except the two flags, the two marks included: set in the stream, the load fails |
0x00ffffff | the offset |
match.h:196-202 (code). Header flags of a table set: YYTH_FLAG_DIFF_ENCODE 1, YYTH_FLAG_OOB_TRANS 2 match.h:40-42.
| Function | Input ends | Returns | Callers |
|---|---|---|---|
aa_dfa_match(dfa, start, str) match.c:518-550 | at NUL | the state | file names, profile names in a peer label, mount strings |
aa_dfa_match_len(dfa, start, str, len) match.c:473-504 | after len bytes | the state | xattr values, : in a peer label, a class byte above AA_CLASS_LAST |
aa_dfa_next(dfa, state, c) match.c:562-579 | one byte | the state | class start states, capability and signal bytes, the null transition |
aa_dfa_outofband_transition(dfa, state) match.c:581-597 | one input, -1 | the state, or 0 without the flag | aa_xattrs_match |
aa_dfa_match_until(dfa, start, str, &pos) match.c:612-650 | at NUL or the first accepting state | the state and the position | aa_label_str_split |
aa_dfa_matchn_until(dfa, start, str, n, &pos) match.c:669-708 | after n bytes or the first accepting state | the state and the position | aa_label_strn_split |
aa_dfa_leftmatch(dfa, start, str, &count) match.c:816-824 | at NUL | the state and a count | find_attach |
All code. Every one returns 0 at once for a start state of 0 except aa_dfa_next and the out-of-band step. With an equivalence class table the byte is mapped first; the out-of-band input is not.
| Check at load | Where |
|---|---|
| default, base, next and check exist; base and default have the same length, next and check too; an equivalence class table has 256 entries | match.c:104-143 |
at least 2 states; default[i] < states; no invalid flag bits; base_idx(base[i]) + 255 < slots; next[i] and check[i] below states | match.c:154-199 |
a diff-encoded or out-of-band state needs the header flag; an out-of-band state needs base_idx >= 1 | match.c:172-187 |
| diff-encode chains end | match.c:201-231 |
| the start states are below states | policy_unpack.c:1034-1040 |
| accept entries, plus one for an owner pair, are inside the permission table | policy_unpack.c:1492-1509 |
| a row has no bit in both allow and deny, and so on; an exec index of type table is inside the string table | policy_unpack.c:1511-1560 |
Code. When these run and what else is checked is the subject of Unpacking and verifying policy.
struct aa_perms perms.h:69-88 (code):
| Field | When it is set (the source's comments, reworded) |
|---|---|
allow | |
deny | explicit deny, or conflict if allow also set |
subtree | allow perm on full subtree only when allow is set |
cond | only for bits neither allowed nor denied |
kill | only for bits that are not allowed, or denied |
complain | accumulates; used only for bits neither allowed nor denied |
prompt | accumulates; used only for bits neither allowed nor denied |
audit | set only when allow is set |
quiet | only for bits that are not allowed, or denied |
hide | only for bits that are not allowed, or denied |
xindex | the exec index, see Exec and domain transitions |
tag, label | string table indexes, if present |
File permission bits perms.h:16-47 (code): exec 0x1, write 0x2, read 0x4, append 0x8, create 0x10, delete 0x20, open 0x40, rename 0x80, setattr 0x100, getattr 0x200, chmod 0x1000, chown 0x2000, lock 0x8000, exec mmap 0x10000, link 0x40000, stack 0x10000000, onexec 0x20000000, change_profile 0x40000000, change_hat 0x80000000.
The example's table (tree): rows 0 to 3 0x200; rows 4 and 5 0x244; rows 6 and 7 0x10201 with AA_X_INHERIT. States: 21 accept 4, 20 accept 6, all others 0.
| Class | Number | A hook's first step after start[class] |
|---|---|---|
| file | 2 | a DFA of its own (rules->file); the name |
| capability | 3 | byte cap >> 5; request 1 << (cap & 0x1f) |
| mount | 7 | the mount point, then NUL-separated fields |
| ptrace | 9 | reached from start[16] (label) plus the byte 9; the peer label |
| signal | 10 | the signal number; the peer label |
| net, net v9 | 14, 15 | family, type, protocol; for unix the address and peer label |
| io_uring | 22 | the label of the credentials to take over, when there is one |
apparmor.h:19-44, policy_unpack.c:1026-1047, capability.c:121-150, ipc.c:78-100, lib.c:393-405 (code). RULE_MEDIATES(rules, class) returns start[class]; 0 means not mediated by this profile policy.h:331-339.
For a file request, __aa_path_perm and aa_audit_file file.c:95-154 file.c:233-251 (code):
| Case | Result | Record |
|---|---|---|
| every requested bit in allow, none in audit | 0 | none |
| every requested bit in allow, some in audit (or the profile audits all) | 0 | AUDIT |
| a bit missing from allow, all missing bits in quiet | -EACCES | none (unless the audit mode is noquiet or all) |
| a bit missing from allow, some not quiet | -EACCES | DENIED |
| the same in a complain-mode profile | 0 | ALLOWED |
| a missing bit in kill, or a kill-mode profile | -EACCES and a signal | KILLED in the log |
For the other classes, aa_apply_modes_to_perms and aa_check_perms lib.c:364-391 lib.c:425-464 (code): denied = request & (~allow | deny); -ENOENT instead of -EACCES when every denied bit is in hide; aa_select_audit_type audit.c:143-152.
Observed for the example profile on /usr/bin/demo (a static program):
| Run | Result | Record |
|---|---|---|
demo cat /etc/demo/motd | prints the file | none |
demo sh -c "echo x > /etc/demo/new" | Permission denied | apparmor="DENIED" operation="mknod" class="file" profile="demo" name="/etc/demo/new" comm="demo" requested_mask="c" denied_mask="c" fsuid=0 ouid=0 |
demo cat /root/.ssh/id_test | Permission denied | apparmor="DENIED" operation="open" class="file" profile="demo" name="/root/.ssh/id_test" comm="demo" requested_mask="r" denied_mask="r" fsuid=0 ouid=0 |
the same with a plain deny rule (profile demoq) | Permission denied | none |
demo cat /etc/hostname | Permission denied | apparmor="DENIED" operation="open" ... name="/etc/hostname" ... requested_mask="r" denied_mask="r" |
the same in complain mode (profile democ) | prints the file | apparmor="ALLOWED" operation="open" class="file" profile="democ" name="/etc/hostname" comm="democ" requested_mask="r" denied_mask="r" fsuid=0 ouid=0 |
demo executes a program with no rule | Permission denied | apparmor="DENIED" operation="exec" class="file" profile="demo" name="/usr/local/bin/nothing" comm="demo" requested_mask="x" denied_mask="x" fsuid=0 ouid=0 |
audit deny file rule in a complain-mode profile is allowed and logged ALLOWED (code; see Bugs found while building this map).aa_dfa_next, the _until pair and aa_dfa_leftmatch describe aa_dfa_match (code; documentation only).aa_dfa_leftmatch on a diff-encoded attachment table on a running kernel.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.
:c1:foo is profile foo in policy namespace c1; a bare foo is looked up in the namespace of the task that asks.unconfined profile when it is allocated (policy_ns.c:122-126).:, / or NUL (policy_ns.h:58)./sys/kernel/security/apparmor/policy/namespaces/NAME/ (apparmorfs.c:2229-2280).features/namespaces/ in apparmorfs and the userns rule are about user namespaces; see the userns rule.c1, foo and host are invented for the map.: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.
: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).:foo:/does/not/exist), profile_ns_named_ok1.sd (:foo:exist /does/not/exist), profile_ns_ok4.sd (one name in three namespaces).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.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).:, / or NUL) is stated by the kernel (policy_ns.h:58).apparmor_parser -N prints the name as :ns://name (profile.h:463-470).: is a label for the lexer: LABEL includes {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.profile keyword is optional: the check is $2->name[0] != '/' && !($1 || $2->ns) (parser_yacc.y:472-473).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.
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).--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).Warning from FILE (FILE line N): apparmor_parser: -n NS overriding policy specified namespace :OLD:..load file was written) (policy.c:1229-1241, policy_ns.c:279-300). A failure is audited with info="failed to prepare namespace"./sys/kernel/security/apparmor/.load or .replace; one write carries one namespace.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).-n is stored in profile_ns (parser_main.c:750-752) and overwrites Profile::ns in the profile head action, with the WARN_OVERRIDE warning (parser_yacc.y:414-429).cache_hit() tests only mru_skip_cache, not skip_cache (policy_cache.c:209-218).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.
All of this is read from the kernel source.
/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).: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).//, as in root//c1 (lib.c:486-497).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).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./sys/kernel/security/apparmor/policy/namespaces (prologue.inc:136-139)..load, .replace, .remove, the policy/ files, namespaces by mkdir and rmdir.: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.
Kernel behaviour is read from the kernel source.
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).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).ux inside a namespace leads to the unconfined of the same namespace (domain.c:630-631).host//&:c1:unconfined is confined by host.unconfined, and a stack that contains it does not report mixed because of it (label.c:1563, label.c:1589-1594).-n and the namespace example at the end of the page.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.
/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).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).ENOENT, "The specified profile does not exist, or is not visible from the current Namespace." (aa_change_profile.pod:93-96).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).// 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).change_profile rule (domain.c:295-299).:, 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.nstest=":ns:changeprofile" and change_profile -> ${nstest}, (changeprofile.sh:33, changeprofile.sh:84-119).-> is opt_named_transition (parser_yacc.y:1043-1047); the change_profile rule is at parser_yacc.y:808.x_table_lookup() (domain.c:523-559).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.
Read from the kernel source; the three views on the slide are derived from these rules and were not observed on a running kernel.
/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.EACCES (procattr.c:37-40). "Visible" means the same namespace or one below it (policy_ns.c:40-52).: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.:c1:A//&B has both in c1 (label.c:1550-1561).namespace="root//c1" and profile="foo"; a subject of several profiles is printed as label=, viewed from the root (audit.c:117-135).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).:ns:stackprofile reads its own label as stackprofile, mode enforce (stackprofile.sh:117-139).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.
The sequence is read from the kernel source and the tests in the AppArmor tree, not from a container manager's source.
mkdir /sys/kernel/security/apparmor/policy/namespaces/c1.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).change_profile -> &:c1:unconfined,. The regression test does exactly this with a namespace nnp: change_profile-> &:nnp:unconfined, (nnp.sh:101-123).c1 (label.h:53, label.h:162).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).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".no_new_privs allows.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".
Read from the kernel source. Every load, replace, remove, mkdir and rmdir goes through aa_may_manage_policy() (policy.c:1001-1029).
info="policy_locked", EACCES. The switch is the module parameter lock_policy (/sys/module/apparmor/parameters/lock_policy) (lsm.c:1989-1990).info="not privileged for target profile" (policy.c:965-988).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,.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)..load, .replace and .remove and from mkdir and rmdir (apparmorfs.c:625, apparmorfs.c:736, apparmorfs.c:2095, apparmorfs.c:2146).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.
: (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:name and :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.-n replaces Profile::ns for every profile of the run (parser_yacc.y:414-430).sd_serialize_top_profile() writes version, then the string namespace if the profile has one, then the profile struct (parser_interface.c:666-681).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 through add_entry_to_x_table() (block_rules.cc:458-472).verify_header() reads the namespace string; an empty one is invalid namespace name, a second different one in the same write is invalid ns change (policy_unpack.c:1442-1485).aa_replace_profiles() passes the name to aa_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).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.
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).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).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).@inview: whether to match labels in view or only in scope (domain.c:120).prefix//name (lib.c:486-497).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.
unconfined, written :ns:name, in a tree where a task sees its own namespace and the ones below it.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.-n (use -K), and the manual page's --namespace-string is not accepted (use --namespace).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.
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 with Profile attachment must begin with a '/' or variable.@{profile_name} inside :ns:name expands to name, without the namespace.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.:, / or NUL.| 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 |
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.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".| 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 |
-n names a child of the namespace the parser runs in. Run inside a container it creates the namespace below the container's namespace.Warning from FILE (FILE line N): apparmor_parser: -n NS overriding policy specified namespace :OLD:.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..load, .replace and .remove act on the writer's current namespace. The copies inside a namespace directory act on that namespace.:NAME: to .remove removes the namespace NAME with its profiles and child namespaces; writing :NAME://profile removes one profile.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.| 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 |
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.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 |
:ns:name, never :ns://name.:c1:A//&B means both A and B are in c1.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.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.// in the namespace part descends further (:c1//inner:name).ENOENT.:ns:, :ns:// and :ns (no closing colon) name the unconfined profile of ns.//& 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.unconfined, and px without a target, search only the profiles of that profile's namespace. ux leads to the unconfined of the same namespace.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_policy defaults to 1, has mode 0600 and can be written only by a policy admin.ns= when a namespace name is known.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)..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.| 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 |
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 |
-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.Empty named transition profile name is printed for a profile head with a namespace and no name, which is not a transition.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:
-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 { } }.-N lists the child under the parent's namespace, while the child's header carries the child's own prefix.The kernel holds compiled policy, not profile text. apparmor_parser -r FILE compiles a profile file and replaces the loaded profiles with the result.
apparmor_parser -r FILE. -r is --replace (parser_main.c:156); the other two commands are -a (--add) and -R (--remove)./sys/kernel/security/apparmor/profiles lists every loaded profile with its mode (apparmorfs.c:2709), and /sys/kernel/security/apparmor/policy/profiles/NAME.N/ has one directory per profile with the files name, mode and attach (apparmorfs.c:2038-2050) and a link raw_data to the binary policy it was loaded from (apparmorfs.c:1980)./sys/kernel/security/apparmor/revision is a counter of policy changes (apparmorfs.c:2954).apparmor_parser -Q FILE (--skip-kernel-load, parser_main.c:169).Features, text, tables, blob. A rule class the kernel does not support is dropped and the profile still loads; --warn=rule-not-enforced (or --warn=all) makes the parser say so.
/sys/kernel/security/apparmor/features (features.c:53). --kernel-features FILE uses a file instead (parser_main.c:196)./etc/apparmor.d. -p (--preprocess) prints the text with includes resolved and stops; -N (--names) prints the profile names and stops (parser_main.c:163, parser_main.c:183).AppArmor parser error for FILE in profile INCLUDED-FILE at line N: TEXT and the parser exits with a non-zero status.-Q (--skip-kernel-load) does everything except the load.rule-not-enforced, described as "warn if a rule is not enforced" (parser_main.c:281); it is off by default.--kernel-features /dev/null --warn=all, nothing loaded: Warning from profile demo (demo.sd): mqueue type=posix rules not enforced, and likewise "ptrace rules not enforced", "signal rules not enforced", "network rules not enforced", "userns rules not enforced". The exit status stayed 0.abi rule gets the warning FILE: File 'NAME' missing feature abi, falling back to default policy feature abi.set_supported_features (parser_main.c:1030); variables are expanded in post_process_profile (parser_policy.c:127-133).yyparse → post_process_policy → process_profile_rules → sd_serialize_profile → aa_kernel_interface_replace_policy, all called from process_profile() (parser/parser_main.c:1289). Up to three DFAs per profile: xmatch, file, policydb.
Read at AppArmor 836052d21 (6.0.0~alpha2). The full stage table is in the reference under this deck.
int process_profile(int option, aa_kernel_interface *kernel_interface, ...) runs one policy file (parser_main.c:1289).retval = yyparse(); (parser_main.c:1353); scanner parser_lex.l, grammar parser_yacc.y.post_process_policy (parser_policy.c:179) calls post_process_profile (parser_policy.c:127) for each profile.process_profile_rules (parser_regex.c:1215) calls process_profile_name_xmatch (attachment), process_profile_regex (file rules) and process_profile_policydb (the other classes) (parser_regex.c:1238-1268).sd_serialize_profile (parser_interface.c:480); hats and children are written after their parent by load_flattened_hats (parser_interface.c:783-786).aa_kernel_interface_replace_policy (kernel_interface.c:357).-j N (--jobs, parser_main.c:184); the default is the number of processor cores (parser_main.c:99). Each file is processed in a forked child by work_spawn (parser_main.c:1472).-D (--dump) with a name from apparmor_parser --help=dump, -O (--optimize) with a name from --help=optimize.Cached policy lives under /var/cache/apparmor/, in a directory named after the kernel feature set. A hit skips compilation only; the profile text is still read to check time stamps. The cache is written only with -W (--write-cache). aa-load loads cached policy without the compiler.
/var/cache/apparmor (parser_main.c:1865); -L DIR (--cache-loc) names another./var/cache/apparmor/FEATURES-ID.0/, where the id is a hash of the kernel feature set (policy_cache.c:254-258). apparmor_parser --print-cache-dir prints it for the running kernel.FILE: file 'NAME' is newer than cache file (policy_cache.c:115-117).-W (--write-cache, parser_main.c:175) or write-cache in parser.conf; the variable is 0 by default (parser_main.c:76).-K (--skip-cache) neither reads nor writes, -T (--skip-read-cache) does not read, --purge-cache clears it (parser_main.c:173-174, parser_main.c:187).aa-load loads cached blobs without the compiler and does not check whether they are stale; the source says // Todo: Check cache validity (aa_load.c:105).Cache read/write disabled: interface file missing. (Kernel needs AppArmor 2.4 compatibility patch.) (parser_main.c:1731).if (cache_hit(cachename)) at parser_main.c:1368; that order is why a hit does not skip reading.if (retval == 0 && write_cache) (parser_main.c:1422-1429).-a, -r and -R write to .load, .replace and .remove under /sys/kernel/security/apparmor/. A rejected blob fails the write and leaves the loaded policy as it was. Replacing a profile updates the processes that carry it.
/sys/kernel/security/apparmor/.load, .replace and .remove (apparmorfs.c:2936-2948). libapparmor names them at kernel_interface.c:138-140 and finds the real mount point of securityfs itself.-a (--add), -r (--replace), -R (--remove) (parser_main.c:151-162).aa_may_manage_policy (apparmorfs.c:625).EACCES and the audit record has info="policy_locked" (policy.c:1013-1016).STATUS record, or ERROR on failure, with operation="profile_load", "profile_replace" or "profile_remove" (audit.h:103-105).policy/set_load (apparmorfs.c:2634, tested by libapparmor at kernel_interface.c:230-248); otherwise one write per profile.kernel.unprivileged_userns_apparmor_policy (lsm.c:2454)..load, .replace, .remove.aa_replace_profiles unpacks and verifies everything before it changes anything, then swaps with __replace_profile(ent->old, ent->new) (policy.c:1393) and refreshes the labels with __aa_labelset_update_subtree(ns) (policy.c:1414), which is how running tasks follow the replacement.Load: policy_update → aa_replace_profiles, which calls aa_unpack and then swaps. Check: apparmor_file_open → aa_path_perm → aa_dfa_match → aa_audit_file → aa_audit. The kernel does not see rule text or globs.
Paths are under security/apparmor/ in the kernel. Read, not traced on a running kernel.
profile_load, profile_replace and profile_remove (apparmorfs.c:687, apparmorfs.c:705, apparmorfs.c:723) call policy_update (apparmorfs.c:607).policy_update checks aa_may_manage_policy (apparmorfs.c:625) and recognises a zstd-compressed blob by its magic number (apparmorfs.c:636-639).ssize_t aa_replace_profiles(struct aa_ns *policy_ns, struct aa_label *label, ...) (policy.c:1184) calls aa_unpack (policy_unpack.c:1745), which runs verify_header, unpack_profile and verify_profile for each profile in the blob (policy_unpack.c:1761-1772).__replace_profile for an existing profile, __add_profile for a new one, then __aa_labelset_update_subtree (policy.c:1393-1414).file_open is apparmor_file_open (lsm.c:465); it calls aa_path_perm (file.c:287).aa_path_name (file.c:169) and matched by aa_str_perms, which calls aa_dfa_match(file_rules->dfa, start, name) (file.c:221-226; match.c:518).aa_audit_file (file.c:95) and aa_audit (audit.c:200)./proc/PID/attr/ arrive at apparmor_setprocattr (lsm.c:943); queries written to .access arrive at aa_write_access (apparmorfs.c:1204).libapparmor is the C library for talking to the kernel: features, cache and loading for the parser, aa_getcon, aa_change_hat and aa_change_profile for applications, aa_query_label for trusted helpers, and log parsing for the tools. It does not compile policy.
Signatures are from apparmor.h at AppArmor 836052d21; link with -lapparmor.
int aa_is_enabled(void); (apparmor.h:69-70). It returns 0 with errno set to ECANCELED (disabled at boot), ENOSYS (not present), ENOENT (enabled, interface not found) or EBUSY (only private interfaces) (kernel.c:310-312). The command is aa-enabled.int aa_getcon(char **label, char **mode);, int aa_gettaskcon(pid_t target, char **label, char **mode);, int aa_getpeercon(int fd, char **label, char **mode); (apparmor.h:110-113). They read /proc/PID/attr/apparmor/current or /proc/PID/attr/current (kernel.c:424-426).int aa_change_hat(const char *subprofile, unsigned long magic_token);, int aa_change_profile(const char *profile);, int aa_change_onexec(const char *profile);, int aa_stack_profile(const char *profile); (apparmor.h:79-85).lsm_set_self_attr system call when it is available and otherwise by a write to a file under /proc/PID/attr/ (kernel.c:997-1011): changehat %016lx^%s (kernel.c:1033), changeprofile %s (kernel.c:1078), exec %s (kernel.c:1099), stack %s (kernel.c:1215).int aa_query_label(uint32_t mask, char *query, size_t size, int *allowed, int *audited); (apparmor.h:122). It writes the query to /sys/kernel/security/apparmor/.access and reads the answer back (apparmorfs.c:2704).int aa_features_new(aa_features **features, int dirfd, const char *path); (features.c:456) and aa_kernel_interface_new (kernel_interface.c:224-226).aa_log_record *parse_record(const char *str); (libaalogparse.c:41), used by the Python tools through the SWIG module LibAppArmor.parser/libapparmor_re/, linked statically into apparmor_parser. It is not part of libapparmor.aa_is_enabled./proc/self/attr/apparmor/ files.aa-logprof and aa-genprof turn logged events into rules in the profile file and reload it with apparmor_parser -r. aa-complain and aa-enforce edit the flags= of the file and reload. aa-status reads the kernel's list of profiles.
aa-logprof parses each log line with libapparmor's parse_record (logparser.py:288). aa-logprof -f FILE reads another log file; -d DIR names another profile directory.apparmor_parser -I<profile_dir> --base <profile_dir> -r <file> (aa.py:2430-2432).aa-complain PROGRAM removes the flags enforce, kill, unconfined, prompt and default_allow from the profile file and adds complain (aa.py:266-273); the editing is done by change_profile_flags (aa.py:552). aa-enforce does the reverse.aa-disable is different: it links the file into /etc/apparmor.d/disable/ and unloads the profile with apparmor_parser -R.aa-status reads /sys/kernel/security/apparmor/profiles (aa_status.c:175-179) and the labels of the running processes; it changes nothing. aa-status --json prints the same as JSON./sys/kernel/security/apparmor/policy/profiles/NAME.N/mode (apparmorfs.c:2044).Administrators: the parser, features, cache and loading decks. Application developers: libapparmor. AppArmor developers: the lexer, the backend pipeline and the kernel decks.
/sys/kernel/security/apparmor/features is read, the text under /etc/apparmor.d is parsed, the rules are compiled, the blob is written to /sys/kernel/security/apparmor/.replace, and the kernel walks the tables at each check.--kernel-features FILE, -p and -N, -Q, -W for the cache, -a -r -R for the load.Read at AppArmor 836052d21 (6.0.0~alpha2) and mainline Linux 7.4-rc2 (97d73c825). Messages marked "observed" were printed by the tree's parser (6.0.0~alpha2), run through tools/head-parser, compiling without loading; no kernel with AppArmor was used, so kernel behaviour here is what the code does, not a recorded session.
| Stage | What happens | What you can observe |
|---|---|---|
| Features | The parser reads the kernel's feature list from /sys/kernel/security/apparmor/features | --kernel-features FILE uses a file instead of the running kernel |
| Text | The profile file and everything it includes are read; includes are looked up in the base directory, default /etc/apparmor.d | -p prints the preprocessed text and stops; -N prints the profile names and stops |
| Cache test | If a cached blob is newer than the profile and every included file, it is loaded and the next two stages are skipped | -K skips the cache, -T skips reading it |
| Compile | Rules become matching tables, packed into one binary blob per profile | -Q (--skip-kernel-load) does everything except the load |
| Cache write | The blob is saved for next time, only when asked | -W (--write-cache), or write-cache in parser.conf |
| Load | One write() hands the blob to the kernel | -a add, -r replace, -R remove |
-N on the example profile of syntax-map printed demo, demo//admin and demo//worker (observed).
A syntax error stops the run with a message of the form AppArmor parser error for FILE in profile INCLUDED-FILE at line N: TEXT (format string "AppArmor parser error for %s%s%s at line %d: %s"; the middle part names the file being read at that moment).
Without the kernel interface the parser prints Cache read/write disabled: interface file missing. (Kernel needs AppArmor 2.4 compatibility patch.) and carries on without the cache (observed with an installed apparmor_parser 5.0.2 on a kernel without AppArmor).
See adm-parser for every option and the exit status.
A rule class is compiled only when both the kernel's feature list and the policy ABI of the profile (abi <abi/5.0>,) support it. Otherwise the rules of that class are dropped and the profile still loads, with exit status 0.
The warning class for this, rule-not-enforced, is off by default. --warn=rule-not-enforced or --warn=all turns it on.
Observed with the tree's parser (6.0.0~alpha2), an empty kernel feature set (--kernel-features /dev/null) and --warn=all, for the example profile:
Warning from profile demo (demo.sd): mqueue type=posix rules not enforcedworker, whose all, rule includes message queuesOne more message of this class is in the source and was not printed: "mqueue type=sysv rules not enforced" (parser/mqueue.cc:199).
With --kernel-features pointing at the tree's abi/5.0 file, no warning was printed (observed).
A profile without an abi rule gets the warning "%s: File '%s' missing feature abi, falling back to default policy feature abi".
See adm-features and syn-abi.
| Item | Value |
|---|---|
| Location | /var/cache/apparmor/<features id>.0/, one file per profile file, named after its base name |
| Directory name | derived from the kernel feature set; .1, .2 and so on when two feature sets collide on the same id |
| Fresh when | the cached file is newer than the profile file and every file it includes |
| A hit skips | compilation only; the text is still read and parsed |
| Written | only with -W (--write-cache) or write-cache in parser.conf |
| Not used for | profiles read from standard input, profiles forced into complain mode |
| Option | Effect |
|---|---|
-K, --skip-cache | do not read or write the cache |
-T, --skip-read-cache | do not read the cache |
-W, --write-cache | save the compiled blob |
-L, --cache-loc DIR | use another cache location |
--purge-cache | clear the cache |
--print-cache-dir | print the cache directory for this kernel |
aa-load loads cached blobs straight into the kernel. It does not run the compiler and does not check whether the cache is stale.
See adm-cache.
| Option | File written under /sys/kernel/security/apparmor/ | Effect |
|---|---|---|
-a, --add | .load | add new profiles |
-r, --replace | .replace | replace loaded profiles, add new ones |
-R, --remove | .remove | remove profiles |
/sys/kernel/security; libapparmor finds the real mount point.write() of the whole blob. When the kernel has the policy/set_load feature, all profiles of a file go in one write and are replaced together; otherwise libapparmor writes them one profile at a time.EACCES when policy is locked or the writer is not a policy administrator. The file modes do not decide this.write() with an error number and the loaded policy stays as it was. The kernel also emits a STATUS or ERROR audit record with operation "profile_load", "profile_replace" or "profile_remove".See adm-loading.
| Job | Functions | Used by |
|---|---|---|
| Is AppArmor enabled, where is its filesystem | aa_is_enabled, aa_find_mountpoint | aa-enabled, aa-status |
| Read confinement | aa_getcon, aa_gettaskcon, aa_getpeercon, aa_getprocattr | applications, aa-status |
| Change confinement | aa_change_hat, aa_change_hatv, aa_change_profile, aa_change_onexec, aa_stack_profile, aa_stack_onexec | applications, aa-exec, mod_apparmor, pam_apparmor |
| Ask for a decision | aa_query_label, aa_query_file_path, aa_query_link_path | trusted helpers such as the D-Bus daemon |
| Features, cache, load | aa_features_new, aa_policy_cache_new, aa_policy_cache_replace_all, aa_kernel_interface_load_policy, aa_kernel_interface_replace_policy, aa_kernel_interface_remove_policy | apparmor_parser, aa-load, aa-features-abi |
| Parse log lines | parse_record | the Python tools, through the SWIG module LibAppArmor |
Changing confinement writes one of these strings to the task's AppArmor attribute: libapparmor first tries the lsm_set_self_attr system call and falls back to a file under /proc/PID/attr/ (libraries/libapparmor/src/kernel.c:997-1011): "changehat %016lx^%s", "changeprofile %s", "exec %s", "stack %s".
aa_is_enabled returns 0 and sets errno to say why: ECANCELED (disabled at boot), ENOSYS (no sign of AppArmor), ENOENT (enabled, interface not found) or EBUSY (only private interfaces available).
libapparmor does not compile policy and does not know the profile language.
See lib-enabled, lib-labels, lib-change-hat, lib-change-profile, lib-query, lib-features and lib-cache-kernel.
C programs in binutils/, which call libapparmor:
aa-enabled, aa-exec, aa-features-abi, aa-load, aa-statusPrograms in utils/, Python except aa-decode and aa-remove-unknown (shell). Those that change profiles (aa-audit, aa-autodep, aa-cleanprof, aa-complain, aa-enforce, aa-genprof, aa-logprof, aa-mergeprof) edit the text and reload it; aa-disable links the file into the disable directory and unloads the profile with -R:
aa-audit, aa-autodep, aa-cleanprof, aa-complain, aa-decode, aa-disable, aa-easyprof, aa-enforce, aa-genprof, aa-logprof, aa-mergeprof, aa-notify, aa-remove-unknown, aa-sandbox, aa-show-usage, aa-unconfinedAfter changing a profile file the Python tools reload it with:
apparmor_parser -I<profile_dir> --base <profile_dir> -r <file>
The parser path comes from the tool configuration, default /sbin/apparmor_parser. aa-complain and aa-enforce edit the flags= of the profile file and reload it; they do not change a kernel setting directly. aa-status reads the profiles file of the kernel's AppArmor filesystem.
See ut-overview and ut-modes.
Paths are under parser/ unless prefixed.
| # | Stage | Functions | Result |
|---|---|---|---|
| 0 | Start-up | main (parser_main.c:1806), get_kernel_features (parser_main.c:1726), aa_kernel_interface_new (parser_main.c:1853), aa_policy_cache_new (parser_main.c:1885) | options, kernel features, cache handle |
| 1 | Per file | process_profile (parser_main.c:1289), reset_parser (parser_main.c:1254); run in a forked child by work_spawn (parser_main.c:1472, used at 1693) | one policy file |
| 2 | Lex | flex scanner parser_lex.l; include_filename (parser_lex.l:162); keyword_table (parser_misc.c:81-138) | tokens |
| 3 | Parse | yyparse() (parser_main.c:1353); grammar parser_yacc.y, top rule at 345-371, profile_base at 391-458; add_to_list (parser_policy.c:60) | Profile objects holding rule_t and cod_entry rules |
| 4 | Cache test | cache_hit (parser_main.c:1368) then process_binary (parser_main.c:1156) | on a hit, stages 5 to 7 are skipped |
| 5 | Post-process | post_process_policy (parser_policy.c:179) calls post_process_profile (parser_policy.c:127): add_implied_rules, process_profile_variables, replace_profile_aliases, profile_merge_rules, then process_profile_rules, then hats and children | expanded, merged rules |
| 6 | Compile | process_profile_rules (parser_regex.c:1215): process_profile_name_xmatch (xmatch), gen_policy_re (rule classes), process_profile_regex (file DFA, parser_regex.c:789), process_profile_policydb (parser_regex.c:1385); globs through convert_aaregex_to_pcre (parser_regex.c:118); blobs from aare_rules::create_dfablob (libapparmor_re/aare_rules.cc:352) and create_chfa (libapparmor_re/aare_rules.cc:194) | up to three compressed DFA tables per profile |
| 7 | Serialize | load_policy (parser_policy.c:91), __sd_serialize_profile (parser_interface.c:683), sd_serialize_top_profile (parser_interface.c:666), sd_serialize_profile (parser_interface.c:480); load_flattened_hats (parser_interface.c:783-786) | one tagged stream per profile, hats and children after it as siblings |
| 8 | Write cache | setup_cache_tmp (parser_main.c:1414), install_cache (parser_main.c:1429); only when write_cache is set | file in the cache directory |
| 9 | Load | aa_kernel_interface_load_policy, aa_kernel_interface_replace_policy, aa_kernel_interface_remove_policy (libraries/libapparmor/src/kernel_interface.c:314, 357, 400) | one write() to .load, .replace or .remove |
process_profile leaves early for -p (preprocess), -N (names), -D variables and the debug dump.yyparse() at parser_main.c:1353 comes before cache_hit at 1368.-O and -D options only affect stage 6.libapparmor_re (parser/libapparmor_re/) is the DFA engine, linked statically into the parser. It is not part of libapparmor.See fe-lexer, fe-grammar, fe-post-process, re-pipeline and re-blob.
Paths are under linux:security/apparmor/.
profile_load (apparmorfs.c:687), profile_replace (705) and profile_remove (723) call policy_update (apparmorfs.c:607). It checks aa_may_manage_policy (apparmorfs.c:625; policy.c:1001), detects a zstd-compressed blob by its magic number (636-639) and copies the data with aa_simple_write_to_buffer (apparmorfs.c:459).aa_replace_profiles (policy.c:1184) calls aa_unpack (policy_unpack.c:1745), which runs verify_header (1442), unpack_profile (1121) and verify_profile (1574) for each profile. DFAs go through unpack_dfa (442) and aa_dfa_unpack (match.c:319) and are checked by verify_dfa (match.c:154); rule tables through unpack_pdb (policy_unpack.c:968).__lookup_replace (policy.c:1271) and replaced by __replace_profile (1393); new ones are added by __add_profile (1409); labels are refreshed by __aa_labelset_update_subtree (1414). Removal goes through aa_remove_profiles (policy.c:1488).apparmor_file_open (lsm.c:465), aa_path_perm (file.c:287), aa_path_name (path.c:202), __aa_path_perm (file.c:233), aa_str_perms (file.c:221), aa_dfa_match (match.c:518). The profile's mode is applied in aa_audit_file (file.c:95) and aa_audit (audit.c:200), which also write the audit record.libapparmor's writes to /proc/PID/attr/ arrive at apparmor_setprocattr (lsm.c:943); queries on .access arrive at aa_write_access (apparmorfs.c:1204). The policy/set_load feature is declared at apparmorfs.c:2634.
See k-unpack, k-match, k-apparmorfs and k-audit.
profiles/apparmor.d/abstractions/ holds 130 abstractions. base appears in 122 include lines of the shipped profiles, nameservice in 49, consoles in 27, nameservice-strict in 14.
apparmor_api/ and 11 under ubuntu-browsers.d/. On an installed system they are under /etc/apparmor.d/abstractions/.base, consoles and nameservice-strict (lsblk:16-18).include <abstractions/NAME> lines over profiles/apparmor.d/ outside abstractions/, at AppArmor 836052d21: 198 profile files at the top level plus apache2.d/phpsysinfo. base 122 lines, nameservice 49, consoles 27, nameservice-strict 14, ssl_certs 10, user-tmp 9, private-files-strict 9.base at least once, and 96 do not mention it.Includes are pasted as text, once per profile. Variables come from the including profile's include <tunables/global>. apparmor_parser -p prints the expanded profile with ##included <...> markers.
include <abstractions/NAME> looks the file up in the parser's include path; #include <...> is the older spelling of the same rule.base includes crypto (base:15), which includes openssl and upki.include if exists. Run with the parser built from the AppArmor tree at 836052d21, include <abstractions/nonexistent> on line 4 of a file gives: AppArmor parser error for /work/a1.sd in profile /work/a1.sd at line 4: Could not open 'abstractions/nonexistent'.include of it in the same profile is skipped, and -p prints ##skipped duplicate include <...> there. A child profile keeps its own list, so it can include base again and gets the rules.@{HOME}, @{PROC}, @{run}, @{etc_ro}, @{multiarch}) must be defined by the including profile, normally with include <tunables/global>.abi <abi/5.0>,. The first abi declaration the parser reads, the one in your profile, stays in force. When an included file declares a different one, the compile still succeeds; the parser prints ... features abi 'abi/5.0' differs from policy declared feature abi, using the features abi declared in policy, and only when run with --warn=abi or --warn=all (run with the tree's parser on a profile that declared abi <abi/4.0>,).apparmor_parser -p (--preprocess) prints the profile with every include expanded and a ##included <...> line before each file's text. The two marker lines on the slide show the format and the nesting of base and crypto; they are not a capture of a run on lsblk.##included marker (parser_lex.l:170-181), Could not open and the if exists exit (parser_lex.l:192-197), the buffer push that makes it a text paste (parser_lex.l:207), directories read file by file (parser_lex.l:208-216, callback at parser_lex.l:128), the ##skipped duplicate include marker (parser_lex.l:223).abi inside a profile body is grammatical (parser_yacc.y:722); the first declaration wins and a different later one only warns (parser_yacc.y:1892-1903). The abi warning class is not among the default warnings (parser.h:77-78).base grants the loader and libraries, logging sockets, locale data, a few /proc and /sys files, and ptrace, signal and unix rules. It includes crypto. It grants no executable path, no /etc/passwd, no network, no /tmp and no terminal devices.
abstractions/base by group, at AppArmor 836052d21:
| Group | Rules | Lines |
|---|---|---|
| Nested include | include <abstractions/crypto>, which includes openssl and upki | base:15 |
| Logging | /dev/log w, and the journal sockets @{run}/systemd/journal/{dev-log,socket} w,, stdout rw, | base:25, base:43-49 |
| Random devices | /dev/random r, /dev/urandom r, | base:26-27 |
| Locale, time zones, gconv | read access to the locale, zoneinfo and gconv trees | base:32-55 |
| Loader | @{etc_ro}/ld.so.cache mr, ld.so.conf, ld.so.preload, the ld-*.so loaders with mr | base:62-71 |
| Libraries | /{usr/,}lib{,32,64}/** r, and **.so* mr,; the same under lib/@{multiarch}/ | base:74-77 |
| Null devices | /dev/null rw, /dev/zero rw, /dev/full rw, | base:87-92 |
| procfs and sysfs | @{PROC}/meminfo, stat, cpuinfo, filesystems, five files under @{PROC}/sys/, @{PROC}/@{pid}/{maps,auxv,status}, CPU and hugepage files under @{sys}; all r | base:95-128 |
| ptrace | ptrace (readby), ptrace (tracedby), ptrace (read) peer=@{profile_name}, | base:134-142 |
| signal | signal (receive) peer=unconfined, signal peer=@{profile_name}, signal (receive, send) set=("exists"), | base:145-151 |
| unix | unix peer=(label=@{profile_name}), unix (receive) peer=(label=unconfined), unix (create), unix (getattr, getopt, setopt, shutdown), | base:154-163 |
| eCryptfs | owner @{HOME}/.Private/** mrixwlk, owner @{HOMEDIRS}/.ecryptfs/*/.Private/** mrixwlk, | base:176-180 |
| Site additions | include if exists <abstractions/base.d> | base:184 |
include <abstractions/base> adds 94 non-comment lines to the expanded text (-p run with the parser built from the tree; the profile's own two lines are not counted, the repeated abi lines are).base has no capability rule, no network rule and no rule with x except the ix in the two eCryptfs rules.@{exec_path} mr,), /etc/passwd (a name lookup abstraction), any network rule, /tmp (user-tmp), terminal devices (consoles)./proc/PID/... for @{PROC}/@{pid}/....base. ptrace (readby), and ptrace (tracedby), have no peer condition: whether another task may read or trace this one is then decided by that task's own policy. ptrace (read) peer=@{profile_name}, lets the program read tasks of its own profile through /proc.signal (receive) peer=unconfined, and unix (receive) peer=(label=unconfined), open the profile to unconfined peers.@{PROC}/@{pid}/{maps,auxv,status} r, has no owner. For another task's maps and auxv the ptrace check still applies; status is world-readable in the kernel unless procfs is mounted with hidepid (linux:fs/proc/base.c:728). Read from the code, not run.ix together with w on files the user owns under ~/.Private/: a place where a confined program that can write can also execute, under the same profile.nameservice-strict: lookup files and resolver configuration (30 expanded lines). nameservice: that plus NIS, LDAP, winbind, Kerberos and mDNS back ends, network inet/inet6 stream/dgram, network netlink raw, capability net_bind_service and read access to /etc/krb5.keytab and /etc/ldap.secret (142 lines).
nameservice-strict (nameservice-strict:11-38): r on @{etc_ro}/default/nss, gai.conf, group, host.conf, hosts, nsswitch.conf, passwd, protocols, resolv.conf, services; the extrausers and nscd copies of passwd and group; @{run}/nscd/db* r,; and it includes nss-systemd, which gives rw on the sockets @{run}/systemd/userdb/io.systemd.*. It has no network rule and no rule that maps a library./etc/resolv.conf is often a symlink into @{run}, so the strict file also lists @{run}/{NetworkManager,connman,netconfig,resolvconf}/resolv.conf and the two systemd-resolved files (nameservice-strict:34-38). See Symlinks: rules see through them.nameservice includes nameservice-strict (nameservice:15) and adds:| Comes with | Rule | Line |
|---|---|---|
nameservice | network inet stream, network inet6 stream, network inet dgram, network inet6 dgram, | nameservice:92-95 |
nameservice | network netlink raw, ("Netlink raw needed for nscd") | nameservice:99 |
nameservice | /var/lib/sss/pipes/nss rw, (sssd) | nameservice:25 |
nameservice | nscd sockets rw, @{run}/nscd/db* mix, | nameservice:35-40 |
nameservice | libnss_*.so* mr, | nameservice:48-49 |
nameservice | @{run}/avahi-daemon/socket rw, | nameservice:52 |
nameservice | a dbus send to systemd for dynamic users | nameservice:84-89 |
nameservice | @{PROC}/@{pid}/net/route r, | nameservice:103 |
nis | capability net_bind_service, | nis:16 |
kerberosclient | /etc/{,krb5/}krb5.keytab rk, and /tmp/krb5cc* r, | kerberosclient:30, kerberosclient:45 |
ldapclient | /etc/ldap.secret r,; it also includes ssl_certs | ldapclient:15, ldapclient:26 |
winbind | rw on the winbindd pipes | winbind:15-17 |
mdns | @{run}/mdnsd w, | mdns:16 |
authd | @{run}/authd.sock rw, | authd:5 |
nis, ldapclient, winbind, likewise, mdns, kerberosclient, authd.-p output of the parser built from the tree, for a profile with only that include; the profile's own two lines are not counted, repeated abi lines are.nameservice-strict in 14 include lines, among them lsblk:18, hostname:21 and iotop-c:8; nameservice in 49, among them curl:17, bin.ping:18 and usr.sbin.dnsmasq:20.CLI: base, consoles, nameservice-strict. Daemon: base, a name lookup abstraction, the family abstraction, ssl_certs (and ssl_keys for servers). GUI: toolkit, display, fonts, dbus-session-strict, or gnome / kde, which include most of them (357 and 279 expanded lines).
dovecot-lmtp (usr.lib.dovecot.lmtp:18-22) and transmission-gtk (transmission:58-65). The slide leaves out include <abstractions/ and >.dovecot-common is included by 22 profile files: the 21 usr.lib.dovecot.* files and usr.sbin.dovecot (grep). It carries capability setgid, (dovecot-common:14). Other dovecot workers take fewer lines; usr.lib.dovecot.imap-login has only base and dovecot-common.gnome includes base, fonts, gtk, X, freedesktop.org, xdg-desktop, user-tmp, wayland, opengl and vulkan (gnome:15-24) and expands to 359 non-comment lines; kde includes base, fonts, X, freedesktop.org, xdg-desktop, user-tmp and qt5 (kde:14-20) and expands to 281 (-p runs with the parser built from the tree).gnome: owner /tmp/** rwkl, from user-tmp (user-tmp:21); /dev/dri/** rw, through opengl, vulkan, mesa and dri-common; the X11 sockets from X and owner @{run}/user/*/wayland-[0-9]* rw, from wayland; rw on the XDG base directories themselves from xdg-desktop.profiles/apparmor.d, only transmission includes gnome and none includes kde; X is in 3 include lines, fonts in 5, vulkan in 3 (grep). The larger desktop profiles are under profiles/apparmor/profiles/extras/.Inventory by kit (the complete tables are in the reference below):
| Kit | Abstractions |
|---|---|
| Command line | consoles, terminfo, user-tmp, user-manpages, gnupg, apparmor_api/* |
| Daemon | authentication, wutmp, libpam-systemd, hosts_access, mysql, cups-client, web-data; family abstractions apache2-common, dovecot-common, postfix-common, frr, samba |
| TLS | ssl_certs for clients (10 include lines), ssl_keys for servers that read private keys (3); openssl is redundant where base is included, because base includes crypto, which includes openssl |
| Desktop | X, wayland, gtk, qt5, qt6, gnome, kde, fonts, freedesktop.org, xdg-desktop, dconf, dri-common, mesa, nvidia, opengl, vulkan, video, audio |
| D-Bus | dbus-strict and dbus-session-strict (socket and handshake), dbus and dbus-session (the whole bus) |
| Interpreters | bash, perl, python, ruby, php |
postfix-common has capability setuid, setgid, sys_chroot (postfix-common:17-19), frr has six capabilities and a bare network, (frr:18-24).authentication: /etc/shadow r. ssl_keys: /etc/ssl/** r. dbus, dbus-session: the whole bus. user-tmp: l on /tmp/**. ubuntu-helpers: a sanitized_helper profile with /** rwkl,.
The rows of the slide, and the rest of the list:
| Abstraction | Rule | Line |
|---|---|---|
authentication | @{etc_ro}/shadow r, and @{etc_ro}/gshadow r,; also unix_chkpwd Px, and six nested includes | authentication:23-24, authentication:36 |
ssl_keys | /etc/ssl/** r, ("Just include the whole /etc/ssl directory if we should have access to private keys too"), plus ACME, dehydrated and certbot private keys | ssl_keys:19 |
dbus | dbus bus=system, | dbus:18 |
dbus-session | dbus bus=session, and /usr/bin/dbus-launch ix, | dbus-session:18-19 |
dbus-accessibility | dbus bus=accessibility, | dbus-accessibility:18 |
user-tmp | owner /tmp/** rwkl, owner /var/tmp/** rwkl, owner @{HOME}/tmp/** rwkl, | user-tmp:15-22 |
bash | @{HOME}/.bash_history rw, without owner; ls and dircolors with mix | bash:18, bash:45-46 |
audio | rw on the legacy device names, /dev/snd/* rw, /dev/sound/* rw, @{PROC}/asound/** rw, | audio:16-39 |
nameservice | network rules, capability net_bind_service, through nis, the Kerberos keytab, the LDAP secret | see the nameservice scene |
apache2-common | /**/.htaccess r, | apache2-common:32 |
user-write, user-download | owner @{HOME}/[^.]* rwl,: every non-hidden entry at the top of the home directory | user-write:20, user-download:20 |
web-data | @{HOME}/public_html/** r, without owner | web-data:20-21 |
base | owner @{HOME}/.Private/** mrixwlk, (eCryptfs, with ix) | base:177 |
Abstractions that carry capabilities:
| Abstraction | Capabilities | Line |
|---|---|---|
nis | net_bind_service | nis:16 |
nvidia | ipc_lock | nvidia:7 |
ubuntu-konsole | sys_ptrace | ubuntu-konsole:10 |
dovecot-common | setgid | dovecot-common:14 |
postfix-common | setuid, setgid, sys_chroot | postfix-common:17-19 |
frr | net_bind_service, chown, setgid, setuid, dac_override, dac_read_search, and a bare network, | frr:18-24 |
ubuntu-helpers defines a profile instead of adding rules (ubuntu-helpers:36):
profile sanitized_helper has network inet, network inet6, network unix, (ubuntu-helpers:42-44), dbus,, Pixr on everything in the bin and lib directories, PUxr on browser sandboxes, /usr/bin/snap ux, and / r, /** rwkl, (ubuntu-helpers:93).audit deny owner /**/* m, and audit deny owner /**/*.py* r, (ubuntu-helpers:97-98).ubuntu-browsers, ubuntu-email, ubuntu-media-players and similar abstractions send helpers there with Cx -> sanitized_helper,. No profile directly under profiles/apparmor.d uses them at this commit (grep).ruby names only Ruby 1.8 and 1.9 directories (ruby:14-23). Not checked against an installed Ruby.audio has no PipeWire rule (grep). Not checked on a system.l in /tmp. D-Bus mediation. Exec modes. AppArmor's threat model.base, 49 for nameservice, 9 for user-tmp.apparmor_parser -p: - capability net_bind_service, (from nis, through nameservice); - /etc/{,krb5/}krb5.keytab rk, and /etc/ldap.secret r, (through nameservice): AppArmor stops objecting, the files' own modes still apply; - l on owner /tmp/** rwkl, (user-tmp): the program may create hard links in /tmp to files it owns; - dbus bus=system, or dbus bus=session, without conditions: every service on that bus is reachable, and what a service then does for the caller happens outside this profile; - ix together with w under ~/.Private/ (base); - @{HOME}/.bash_history rw, and @{HOME}/public_html/** r, without owner: other users' files match when the ordinary permission check lets them through; - Cx -> sanitized_helper,: the child profile is close to unconfined for a non-root user, with /** rwkl,, three network families and Pixr on the bin directories. Its two deny rules use owner, which is why the header says it does not work for root.Cx -> sanitized_helper, and no sanitized_helper child was not determined; such a profile compiles with the tree's parser.private-files-strict adds audit deny ... mrwkl on ~/.ssh, ~/.gnupg, ~/.aws, browser profiles and keyrings; it includes private-files. A deny cannot be overridden by an allow of the same priority.
private-files-strict includes private-files (private-files-strict:7) and adds audit deny ... mrwkl on @{HOME}/.aws/, .gnupg/, .ssh/, .gnome2_private/, .gnome2/keyrings/, @{run}/user/[0-9]*/keyring**, .mozilla/, .config/chromium/, .config/evolution/, .evolution/, Thunderbird, KMail and KWallet data, each as DIR/{,**}, and audit deny ... w on a few parent directories (private-files-strict:10-27).private-files has three groups: - history and editor backup files, denied without audit: deny @{HOME}/.*history mrwkl, and seven more. The comment gives the reason: "don't audit files under $HOME otherwise get a lot of false positives when reading contents of directories" (private-files:7-16); - places from which files get executed: audit deny ... wl on @{HOME}/bin/, .config/autostart/, .config/upstart/, .init/, the KDE Autostart/ and env/ directories, .local/share/thumbnailers/ and .pki/nssdb/ (private-files:19-30); - shell start-up files: deny @{HOME}/.*rc mrk, with audit deny @{HOME}/.*rc wl,, and the same pair for .bash*, .inputrc, .{,z}profile*, .{,z}log{in,out} and .zshenv (private-files:33-49).audit deny writes a log record for each refused access; plain deny refuses silently.mrwkl includes l, so the profile also may not create a link in those directories.private-files-strict is in 9 include lines of the shipped profiles, among them curl (curl:18).local/README says so and gives the remedy: "To override them, you have to specify an allow rule with a higher priority" (local/README:25-28). A browser profile therefore cannot include private-files-strict and read ~/.mozilla with an ordinary rule.priority=1 rules (curl:27-28) are for @{HOME}/.curlrc and @{HOME}/.config/curlrc. Read as text, the name .curlrc matches the pattern of deny @{HOME}/.*rc mrk,, and .config/curlrc matches no deny rule in either file. The profile's comment only says "allow reading configuration files from $HOME", and the commit that added the rules has no message body, so which deny, if any, the author had in mind is not recorded. The compiled result for .curlrc was not queried.deny rule still blocks, silently, in a complain-mode profile (read from the code, not run).audit deny rules in a complain-mode profile the kernel code reads as allowing the access; the question is open. Test deny rules in enforce mode.audit deny @{HOME}/.config/ w, is a rule for the directory itself, not for what is below it.deny rules for history and start-up files leave no log record, so probing for them is silent.abstractions/NAME.d/ extends an abstraction for all profiles that include it. local/PROFILE extends one profile. Both are read through include if exists; reload with apparmor_parser -r.
base ends with include if exists <abstractions/base.d> (base:184). base.d is a directory: every file in it is read. The same line, with the abstraction's own name, ends every top-level abstraction except two.ubuntu-browsers has no include line at all, and ubuntu-helpers has include if exists <local/ubuntu-helpers> inside the profile it defines (ubuntu-helpers:39). The files under apparmor_api/ and ubuntu-browsers.d/ have no extension line either; ubuntu-browsers.d/ is a directory of separate abstractions, not the extension directory of ubuntu-browsers.NAME.d directory. Whether a distribution ships files there was not determined.local/PROFILE: all 198 profile files directly under profiles/apparmor.d contain an include if exists <local/...> line (grep), for example lsblk:58. The tree's local/README:1 describes the convention./opt/site/lib/ and /srv/images/ and the file name site are illustrations.NAME.d is pasted into every including profile like the abstraction itself. A deny rule placed there cannot be undone by an ordinary allow rule of any profile that includes the abstraction.apparmor_parser -r replaces the loaded profile with the newly compiled one. How a changed include file is noticed, and what the policy cache does with it, is the subject of Loading policy into the kernel and The policy cache./etc/apparmor.d/abstractions/base.d/ is a single place that widens every profile with base: 122 include lines in the shipped profiles. A file there is not part of any package's profile, so a review of the shipped profile text does not show it.NAME.d and for local/PROFILE. The policy of a machine is the apparmor_parser -p output on that machine./etc/apparmor.d, and who may load the result, is the question of Who can change policy.aa-logprof proposes an abstraction when one of its rules covers the logged event. # LOGPROF-SUGGEST: no in an abstraction stops that. --no-abstraction turns proposals off. New profiles start with abstractions/base, plus the interpreter's abstraction for scripts.
libraries/libapparmor/testsuite/test_multi/syslog_datetime_01.in, the values (profile demo, the path, the ids) are illustrative. The menu is rendered from the tool's code, not captured from a session.local/; it is a file under abstractions/ of the profile directory, or it is listed in custom_includes in logprof.conf; and one of its rules of that rule type covers the event.include <abstractions/NAME>, sorted by name; the path and its globbed forms follow. The first option is preselected./etc/ssl/certs/ca-certificates.crt the rules that cover it are /etc/{,libre}ssl/certs/{,**} r, in ssl_certs (ssl_certs:17) and /etc/ssl/** r, in ssl_keys (ssl_keys:19). Checked by running the rule classes of the tree's Python module over every top-level abstraction; a full aa-logprof session was not run.base does not appear on the menu, and why a read of /etc/ssl/openssl.cnf raises no question in a profile with base: base includes crypto, which includes openssl.# LOGPROF-SUGGEST: is a comment line in an abstraction. Absent or empty: always eligible. no: never proposed. Anything else is a space-separated list of regular expressions matched against the profile name. Shipped uses, all no: frr:2, frr-snmp:2, transmission-common:2. On the slide frr stands for these; it has no rule for the certificate bundle either.--no-abstraction exists on aa-genprof and aa-logprof ("Do not use any abstractions in profiles"). It removes the proposals from the menu; a new profile still gets base.include <abstractions/base> if that file exists; otherwise the tool prints WARNING: Can't find abstractions/base, therefore not adding it to the new profile. For a script, the interpreter on the #! line decides one more abstraction: bash, dash, sh give abstractions/bash; perl gives perl; python, python2, python3, python3.N give python; ruby and rubyN.N give ruby. Other interpreters (node, lua, php) get only base.@{etc_ro}/passwd r, does not cover a logged read of /etc/passwd. Abstractions written with @{etc_ro}, @{PROC}, @{HOME} or @{run} may therefore neither be proposed nor be recognised as already granting an access, so the tool can ask about a path the policy already allows. Checked at the level of the rule classes; a full aa-logprof session was not run.match_includes (aa.py:1419-1459): the loop over loaded include files, the already-included and local/ skips, the is_covered test and the logprof_suggest handling. valid_include (aa.py:1463-1475).is_known_rule (aa.py:2341-2351) checks the profile and its includes recursively before any question.loadincludes reads every file under tunables and abstractions (aa.py:2519-2534).get_interpreter_and_abstraction (aa.py:372-381), create_new_profile (aa.py:391-404).LOGPROF-SUGGEST: the regex (regex.py:93), where it is read (aa.py:2034-2038), the empty default (profile_storage.py:83).--no-abstraction: aa-logprof:32, aa-genprof:72, disable_abstractions (aa.py:284-286).# self.variables = variables # XXX), aare.py:83, the brace rewriting at common.py:238-243; test-aare.py:239 is a test case with a @{PROC}/ pattern; it expects no match against /foobar.One abstraction is shared by many profiles, and abstractions/NAME.d/ on the installed system adds to it. Review the output of apparmor_parser -p on the machine, and search it for capability, krb5.keytab, rwkl, dbus bus=, ix and sanitized_helper.
base, consoles, nameservice, private-files-strict, ssl_certs, user-tmp.profiles/apparmor.d/ outside abstractions/ at AppArmor 836052d21: base 122, nameservice 49, consoles 27, nameservice-strict 14, ssl_certs 10, user-tmp 9, private-files-strict 9. Abstractions include each other as well: gnome pulls in ten, nameservice eight.include if exists <abstractions/base.d> is the last line of base (base:184); all top-level abstractions except ubuntu-browsers and ubuntu-helpers have the same line for their own name. The tree ships no such directory, so anything found there on a machine was added by the distribution or the administrator.NAME.d takes effect for a profile when that profile is compiled and loaded again; see Loading policy into the kernel and The policy cache for when that happens.| Rule | Abstraction | Line |
|---|---|---|
capability net_bind_service, | nis, included by nameservice | nis:16 |
/etc/{,krb5/}krb5.keytab rk, | kerberosclient, included by nameservice and authentication | kerberosclient:30 |
/etc/ldap.secret r, | ldapclient, included by nameservice | ldapclient:15 |
owner /tmp/** rwkl, | user-tmp, also through gnome and kde | user-tmp:21 |
dbus bus=session, dbus bus=system, | dbus-session, dbus | dbus-session:19, dbus:18 |
owner @{HOME}/.Private/** mrixwlk, | base | base:177 |
/usr/bin/NAME Cx -> sanitized_helper, | ubuntu-browsers, ubuntu-email and the other ubuntu-* lists | ubuntu-browsers:11-25 |
apparmor_parser -p prints the profile with every include expanded and does not load anything.NAME.d and local/ on the machine..d directory, is write access to the policy of every profile that includes it. For base that is nearly every confined program.deny rule in an abstraction is inherited the same way and cannot be undone by an ordinary allow rule in the profile, so the fan-in works for tightening as well.sanitized_helper is defined inside an abstraction (ubuntu-helpers). A profile that includes it and has Cx -> sanitized_helper, rules gives a taken-over program a child profile with /** rwkl, and three network families. What happens at exec time when the child is missing was not determined.Next: prac-general-purpose, prac-privileged, syn-include, syn-abstractions-tunables, dbus-mediation, ut-logprof, prac-sys-proc.
nameservice-strict and explicit paths.if exists, quoted and angle-bracket paths.abi line every abstraction starts with.dbus* abstractions actually control, and who enforces it.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run with -p or -Q on a profile, with nothing loaded into a kernel; "code" means the source of the parser, the tools or mainline Linux 7.4 was read, not run; "grep" is a count over profiles/apparmor.d/ at that commit. File names without a directory are under profiles/apparmor.d/abstractions/. Nothing here was observed on a running kernel.
.d means the file ends with include if exists <abstractions/NAME.d>. "Users" are include lines in the shipped profiles outside abstractions/ (grep).
| Name | Purpose | Notable grants | Includes | .d | Users |
|---|---|---|---|---|---|
base | what a dynamically linked program needs to start, log and be signalled | loader and libraries mr, /dev/log w, journal sockets, locale data, /dev/null rw, procfs and sysfs files, ptrace, signal and unix rules, eCryptfs mrixwlk | crypto | yes | 122 |
crypto | gcrypt, gnutls and crypto-policies configuration | @{PROC}/sys/crypto/* r, | openssl, upki | yes | through base |
openssl | OpenSSL configuration | /etc/ssl/openssl.cnf r, and engine directories | yes | 3, redundant with base | |
upki | upki configuration and cache | /etc/upki/config.toml r, /var/cache/upki/** r, | yes | through base |
| Name | Purpose | Notable grants | Includes | .d | Users |
|---|---|---|---|---|---|
nameservice-strict | users, groups and hosts from files; resolver configuration | ten files under @{etc_ro}, extrausers and nscd copies, resolver files under @{run} | nss-systemd | yes | 14 |
nss-systemd | systemd user database | rw on @{run}/systemd/userdb/io.systemd.* | yes | through the above | |
nameservice | every lookup back end | network inet/inet6 stream/dgram, network netlink raw, sssd pipe, nscd and avahi sockets, libnss_*.so* mr | nameservice-strict, nis, ldapclient, winbind, likewise, mdns, kerberosclient, authd | yes | 49 |
nis | NIS | capability net_bind_service, | yes | through nameservice | |
ldapclient | LDAP | /etc/ldap.secret r, | ssl_certs | yes | through nameservice |
kerberosclient | Kerberos | /etc/{,krb5/}krb5.keytab rk, /tmp/krb5cc* r, | yes | through nameservice | |
winbind, likewise, mdns, authd | winbind pipes, likewise, mdnsd, authd socket | rw on the daemon's pipes or socket | yes | through nameservice |
| Name | Purpose | Notable grants | .d |
|---|---|---|---|
consoles | terminal devices | /dev/console rw, /dev/tty rw, /dev/pts/[0-9]* rw, /dev/pts/ r, | yes |
terminfo | terminfo databases | r | yes |
user-tmp | temporary files | owner /tmp/** rwkl, /tmp/ rw, and the same for /var/tmp and @{HOME}/tmp | yes |
user-manpages | man pages and groff temp files | r, temp files | yes |
groff | groff tools | mrix on the groff binaries | yes |
gnupg | GnuPG files | named files under @{HOME}/.gnupg/, including secring.gpg r | yes |
aspell, enchant | spelling dictionaries | enchant includes aspell | yes |
libnuma, golang, psi-read, psi-read-poll | small procfs and sysfs sets | see the /proc and /sys table | yes |
alts | libalternatives | includes base | yes |
apparmor_api/introspect, examine, change_profile, find_mountpoint, is_enabled | files a program using libapparmor needs | change_profile includes introspect; is_enabled includes find_mountpoint | no |
| Name | Purpose | Notable grants | .d |
|---|---|---|---|
authentication | PAM | @{etc_ro}/shadow r, gshadow r, pam_*.so mr, unix_chkpwd Px,; includes kerberosclient, nis, winbind, likewise, smbpass, p11-kit | yes |
wutmp | login records | rwk on wtmp, btmp, lastlog, @{run}/utmp | yes |
libpam-systemd | logind sessions | dbus send for CreateSession, ReleaseSession; includes dbus-strict | yes |
hosts_access | tcp wrappers | /etc/hosts.allow, /etc/hosts.deny | yes |
mysql | MySQL client | socket and charsets | yes |
cups-client | CUPS client | @{run}/cups/cups.sock rw, | yes |
web-data | document roots | read-only, including @{HOME}/public_html/** r, without owner | yes |
apache2-common | Apache family | includes nameservice; /**/.htaccess r,; @{PROC}/@{pid}/attr/{apparmor/,}current rw, for change_hat | yes |
dovecot-common | Dovecot family (22 profile files) | capability setgid, | yes |
postfix-common | Postfix family | capability setuid, setgid, sys_chroot | yes |
frr, frr-snmp | FRR family (18 profiles) | network, and six capabilities; # LOGPROF-SUGGEST: no | yes |
samba, samba-rpcd, smbpass | Samba family | /var/lib/samba/** rwk, | yes |
transmission-common | Transmission family | 162 rule lines; # LOGPROF-SUGGEST: no | yes |
php, php5, php-worker | PHP | configuration, modules, session files rwlk | yes |
| Name | Purpose | Notable grants | Users |
|---|---|---|---|
ssl_certs | CA bundles and public certificates | read-only | 10 |
ssl_keys | private keys | /etc/ssl/** r, and ACME, dehydrated, letsencrypt and certbot private keys | 3 |
p11-kit | PKCS#11 modules | module configuration, *.so mr, the keyring's pkcs11 socket rw |
A TLS client needs ssl_certs. ssl_keys is for servers that read their private key.
| Name | Notable grants |
|---|---|
bash | @{HOME}/.bashrc, .profile, .bash_profile r; @{HOME}/.bash_history rw, (no owner); /{usr/,}bin/ls mix, /usr/bin/dircolors mix,; @{HOMEDIRS} r, |
perl | /usr/bin/perl rmix,, module trees r, **.so* mr |
python | interpreter binaries r (no execute), standard library and site-packages, owner @{HOME}/.cache/Python/** rw, |
ruby | /usr/lib{,32,64}/ruby/1.[89]{.[0-9],}/... only |
php | see daemons |
golang | cgroup CPU quota files |
| Name | Notable grants | Includes |
|---|---|---|
X | Xauthority files owner ... r, /tmp/.X11-unix/* rw, and the abstract X sockets, deny /var/cache/libx11/compose/* wlk, | dri-common |
wayland | owner @{run}/user/*/wayland-[0-9]* rw, | |
gtk | themes and settings, owner @{HOME}/.Xauthority r, owner @{HOME}/.xsession-errors w, | |
qt5, qt6 | plugin and QML trees mr; write variants qt5-settings-write, qt6-settings-write, qt5-compose-cache-write, qt6-compose-cache-write | |
gnome | GTK module trees mr, @{PROC}/@{pid}/mounts r, | base, fonts, gtk, X, freedesktop.org, xdg-desktop, user-tmp, wayland, opengl, vulkan |
kde | KDE configuration; opt-in write sets kde-globals-write, kde-icon-cache-write, kde-language-write, recent-documents-write, trash | base, fonts, X, freedesktop.org, xdg-desktop, user-tmp, qt5 |
fonts | system fonts r, owner @{HOME}/.{,cache/}fontconfig/** mrwkl, | |
freedesktop.org | applications, icons, mime databases r; recently-used.xbel* rw | |
xdg-desktop | rw on the XDG base directories themselves, not their contents | |
dconf | owner @{run}/user/*/dconf/user rw,, database r | |
dri-common, dri-enumerate, mesa | /dev/dri/** rw,, shader cache rw | mesa includes both dri files |
nvidia | capability ipc_lock, /dev/nvidia* rw | |
opengl, vulkan | mesa, nvidia | |
video | /dev/video[0-9]* rw, | |
audio | rw on OSS and ALSA devices, @{PROC}/asound/** rw,, PulseAudio cookie, socket and shm | |
ibus, fcitx, fcitx-strict, mozc | input methods |
| Name | Grants |
|---|---|
dbus-strict | @{run}/dbus/system_bus_socket rw, and the six handshake calls to org.freedesktop.DBus |
dbus | dbus-strict plus dbus bus=system, |
dbus-session-strict | the session socket owner @{run}/user/[0-9]*/bus rw,, abstract @/tmp/dbus-*, machine-id |
dbus-session | adds /usr/bin/dbus-launch ix, and dbus bus=session, |
dbus-accessibility-strict, dbus-accessibility | the accessibility bus; the non-strict one has dbus bus=accessibility, |
dbus-network-manager-strict | named NetworkManager read calls |
Users: dbus-session-strict 6 profile files, dbus-strict 2, dbus 2. What these rules control, and who enforces them, is in D-Bus mediation.
| Name | What it is |
|---|---|
xdg-open, gio-open, gvfs-open, exo-open, kde-open5 | meant for a child profile. The header shows the pattern /usr/bin/xdg-open rPx -> foo//xdg-open, with profile foo//xdg-open { include <abstractions/xdg-open> }. xdg-open expands to 776 lines (tree). |
ubuntu-browsers, ubuntu-console-browsers, ubuntu-email, ubuntu-console-email, ubuntu-media-players, ubuntu-bittorrent-clients, ubuntu-feed-readers | lists of /usr/bin/NAME Cx -> sanitized_helper,; the including profile must also include ubuntu-helpers |
ubuntu-helpers | defines profile sanitized_helper |
ubuntu-gnome-terminal, ubuntu-xterm, ubuntu-konsole | ix on the terminal emulator; ubuntu-konsole has capability sys_ptrace, |
ubuntu-browsers.d/* | building blocks for browser profiles; user-files includes private-files, java includes private-files-strict |
snap_browsers | defines profile snap_browsers with child profiles |
| Name | Rules | Users |
|---|---|---|
private-files | deny on history and backup files; audit deny ... wl on ~/bin, autostart and plugin directories; deny ... mrk and audit deny ... wl on shell start-up files, including @{HOME}/.*rc | through the strict one and ubuntu-browsers.d/user-files |
private-files-strict | includes private-files; audit deny ... mrwkl on .aws, .gnupg, .ssh, keyrings, .mozilla, Chromium, Evolution, Thunderbird, KMail, KWallet | 9 |
Non-comment lines that the include adds to the -p output of a profile that contains only this include (tree). The profile's own two lines (profile t { and }) are not counted; repeated abi lines are.
| Abstraction | Lines |
|---|---|
nameservice-strict | 30 |
base | 94 |
nameservice | 142 |
kde | 279 |
gnome | 357 |
xdg-open | 776 |
| Abstraction | Rule | File and line |
|---|---|---|
authentication | @{etc_ro}/shadow r, @{etc_ro}/gshadow r, | authentication:23-24 |
ssl_keys | /etc/ssl/** r, | ssl_keys:19 |
dbus | dbus bus=system, | dbus:18 |
dbus-session | dbus bus=session, /usr/bin/dbus-launch ix, | dbus-session:18-19 |
dbus-accessibility | dbus bus=accessibility, | dbus-accessibility:18 |
user-tmp | owner /tmp/** rwkl, (with l) | user-tmp:21 |
bash | @{HOME}/.bash_history rw, without owner | bash:18 |
audio | /dev/snd/* rw, @{PROC}/asound/** rw, | audio:36-39 |
nameservice | network inet stream, and three more; network netlink raw, | nameservice:92-99 |
nis (through nameservice) | capability net_bind_service, | nis:16 |
kerberosclient (through nameservice) | /etc/{,krb5/}krb5.keytab rk, /tmp/krb5cc* r, | kerberosclient:30,45 |
ldapclient (through nameservice) | /etc/ldap.secret r, | ldapclient:15 |
apache2-common | /**/.htaccess r, | apache2-common:32 |
user-write, user-download | owner @{HOME}/[^.]* rwl, | user-write:20, user-download:20 |
web-data | @{HOME}/public_html/** r, without owner | web-data:20-21 |
base | owner @{HOME}/.Private/** mrixwlk, | base:177 |
nvidia | capability ipc_lock, | nvidia:7 |
ubuntu-konsole | capability sys_ptrace, | ubuntu-konsole:10 |
dovecot-common | capability setgid, | dovecot-common:14 |
postfix-common | capability setuid, setgid, sys_chroot, | postfix-common:17-19 |
frr | six capabilities and network, | frr:18-24 |
ubuntu-helpers | profile sanitized_helper with /** rwkl,, network inet, inet6, unix,, dbus,, Pixr on bin and lib directories, PUxr on browser sandboxes, /usr/bin/snap ux,; then audit deny owner /**/* m, and audit deny owner /**/*.py* r, | ubuntu-helpers:36-98 |
The header of ubuntu-helpers says the profile "does not work for root owned processes, because of the way we use owner matching" and ends "Use at your own risk."
All r unless noted.
| Abstraction | Rules | Lines |
|---|---|---|
base | @{PROC}/sys/kernel/version, ngroups_max, cap_last_cap; @{PROC}/sys/crypto/fips_enabled; @{PROC}/sys/vm/overcommit_memory; @{PROC}/meminfo, stat, cpuinfo, filesystems; @{PROC}/@{pid}/{maps,auxv,status}; @{sys}/devices/system/cpu/, online, possible; transparent hugepage enabled, hpage_pmd_size | base:95-128 |
crypto | @{PROC}/sys/crypto/fips_enabled, @{PROC}/sys/crypto/* | crypto:24,27 |
nameservice | @{PROC}/@{pid}/net/psched, ipv6_route, route | nameservice:55,102-103 |
nss-systemd | @{PROC}/sys/kernel/random/boot_id | nss-systemd:30 |
bash | @{PROC}/@{pid}/mounts, @{PROC}/filesystems | bash:37-38 |
gnome | @{PROC}/@{pid}/mounts | gnome:82 |
golang | owner @{PROC}/@{pid}/mountinfo, owner @{PROC}/@{pid}/cgroup, cgroup CPU quota files | golang:5-8 |
audio | @{PROC}/asound/** rw, | audio:39 |
nvidia | @{PROC}/interrupts, @{PROC}/modules, @{PROC}/driver/nvidia/params | nvidia:20-23 |
mesa | @{sys}/devices/@{pci_bus}/**/{revision,config} | mesa:17 |
apparmor_api/find_mountpoint | @{PROC}/@{pids}/mounts | find_mountpoint:16 |
psi-read, psi-read-poll | @{PROC}/pressure/{cpu,memory,io}, r and rw | line 6 of each |
base's @{PROC}/@{pid}/{maps,auxv,status} r, has no owner. For another task's maps and auxv the ptrace check still applies; status is world-readable unless procfs is mounted with hidepid (code). More in Writing rules for /sys and /proc.
| Place | Reaches | Read through |
|---|---|---|
/etc/apparmor.d/abstractions/NAME.d/* | every profile that includes NAME | include if exists <abstractions/NAME.d> at the end of NAME |
/etc/apparmor.d/local/PROFILE | one profile | include if exists <local/PROFILE> at the end of the profile |
.d line: ubuntu-browsers (no include line), ubuntu-helpers (include if exists <local/ubuntu-helpers> inside its profile), and the files under apparmor_api/ and ubuntu-browsers.d/.NAME.d directory. All 198 profile files directly under profiles/apparmor.d have a local/ include (grep).NAME.d cannot be undone by an ordinary allow rule of an including profile.| Text | Meaning |
|---|---|
include <abstractions/NAME> | search the include path; #include <...> is the older spelling |
include if exists <...> | no error when the file or directory is missing |
include <DIR> | every file in the directory is read |
AppArmor parser error for FILE in profile FILE at line N: Could not open 'abstractions/nonexistent' | a missing include without if exists (tree) |
... features abi 'abi/5.0' differs from policy declared feature abi, using the features abi declared in policy | an included file declares another abi than the profile; printed only with --warn=abi or --warn=all; the compile succeeds (tree) |
##included <abstractions/NAME> | marker in -p output before an included file's text |
##skipped duplicate include <...> | marker in -p output where a file was already included in this profile |
##failed include <...> | marker in -p output for a file that could not be opened (code) |
include <tunables/global>.aa-genprof, aa-autodep): include <abstractions/base>; if the file is missing, WARNING: Can't find abstractions/base, therefore not adding it to the new profile.#! line adds one abstraction, r on the script and ix on the interpreter.| Interpreter | Abstraction |
|---|---|
bash, dash, sh | abstractions/bash |
perl | abstractions/perl |
python, python2, python3, python3.N | abstractions/python |
ruby, rubyN.N | abstractions/ruby |
| anything else (node, lua, php) | none |
local/, is under abstractions/ or listed in custom_includes of logprof.conf, and has a rule covering the event. Proposals come first in the menu, sorted by name, without ranking by breadth.# LOGPROF-SUGGEST: in an abstraction: absent or empty, always eligible; no, never proposed; otherwise regular expressions matched against the profile name. Shipped: frr, frr-snmp, transmission-common, all no.--no-abstraction (aa-genprof, aa-logprof) removes the proposals; new profiles still get base.None of these is intended behaviour to rely on.
@{etc_ro}/passwd r, does not cover a logged /etc/passwd. Abstractions written with @{etc_ro}, @{PROC}, @{HOME}, @{run} may neither be proposed nor recognised as already granting the access. Checked with the rule classes of the tree's Python module; a full aa-logprof session was not run.ubuntu-helpers header: says a second include causes parser errors about multiple definitions. With the tree's parser the duplicate is skipped and the compile succeeds. Documentation only.opengl header: line 2 reads # Vulkan access requirements. Documentation only.ruby: covers only ruby/1.[89] directories, so the abstraction that aa-genprof adds for a Ruby script may grant nothing useful. Not verified against an installed Ruby.audio reads PipeWire's client configuration (audio:89-91) but has no rule for a PipeWire socket. Not verified on a system.audit deny in a complain-mode profile: the kernel code reads as allowing the access; open question. The private-files pair uses audit deny for most of its rules.Cx -> sanitized_helper, when the profile has no sanitized_helper child (such a profile compiles with -Q); whether distributions ship files in abstractions/*.d/.| What | Where |
|---|---|
include path search, ##included marker | parser/parser_lex.l:170-181 |
Could not open, if exists | parser/parser_lex.l:192-197 |
| text inclusion (buffer push), directory includes | parser/parser_lex.l:207-216, :128 |
##skipped duplicate include | parser/parser_lex.l:223 |
| duplicate check | parser/parser_include.c:165 |
| per-profile include cache | parser/parser_yacc.y:396-397, :454-455 |
abi in a profile body; first declaration wins | parser/parser_yacc.y:722, :1892-1903 |
| default warning classes | parser/parser.h:77-78 |
match_includes, valid_include | utils/apparmor/aa.py:1419-1459, :1463-1475 |
| menu order | utils/apparmor/aa.py:1152-1156 |
is_known_rule | utils/apparmor/aa.py:2341-2351 |
loadincludes | utils/apparmor/aa.py:2519-2534 |
| interpreter mapping, new profile | utils/apparmor/aa.py:372-381, :391-404 |
LOGPROF-SUGGEST | utils/apparmor/regex.py:93, utils/apparmor/aa.py:2034-2038, utils/apparmor/profile_storage.py:83 |
--no-abstraction | utils/aa-logprof:32, utils/aa-genprof:72, utils/apparmor/aa.py:284-286 |
| variable gap in the matcher | utils/apparmor/aare.py:49, :83, utils/apparmor/common.py:238-243 |
The shipped curl profile grants owner file rw @{HOME}/**, because the files are chosen on the command line. Broad rules keep the program working; what the profile leaves out is the protection.
# allow reading other configuration files/certs from $HOME
# (see --config, --cacert options)
# allow writing output to $HOME, /tmp (see -o option)
owner file rw @{HOME}/**,
include <abstractions/...> lines, no capability rule of its own.include <abstractions/...> lines; owner rules under @{HOME} with **; network rules by family and type, without addresses; no capability rule.owner bounds the breadth: the rule gives nothing on files of other users. See the scene "Your files"./etc/passwd and sys_admin on the slide are examples of what has no rule. The scene "What the broad profile still blocks" goes through the list.curl: 6 abstractions, no capability rules of its own, owner file rw @{HOME}/**,. ping: capability net_raw, capability setuid, two raw socket rules and two exact file paths.
capability lines, lines containing **, owner lines. curl's three owner lines are 27, 28 and 33.@{exec_path} mixr, and @{PROC}/sys/net/ipv6/conf/all/disable_ipv6 r, (bin.ping:25-27).abstractions/base and abstractions/nameservice, so both get the rules shown in the scene "What the includes brought along".profiles/apparmor.d/, by style (grep counts):| Group | Files |
|---|---|
flags=(unconfined): a name only, nothing confined | 76 |
allow all, (sbuild and 13 sbuild-*) and plasmashell | 15 |
| all others | 107, of which 68 have a capability NAME, rule |
flags=(unconfined) profile is not a broad profile. Its file says so: "This profile allows everything and only exists to give the application a name instead of having the label "unconfined"" (firefox:1-2, profile line at firefox:7).Each include <abstractions/NAME> pulls in a shared block of rules. apparmor_parser -p prints the profile with every include expanded: curl's 23 lines become 397.
base names shared libraries by pattern, for example /{usr/,}lib/@{multiarch}/**.so* mr, (base:74-77), so a new library version or file name is still covered. A profile that listed exact library files would need an edit after such an upgrade.apparmor_parser -p (--preprocess) prints the profile with every include pasted in. Each pasted file is announced by a ##included <...> line (parser_lex.l:176); a repeated include is replaced by ##skipped duplicate include <...> (parser_lex.l:223).-I profiles/apparmor.d -p on profiles/apparmor.d/curl. The pipeline on the slide is a reading aid for an installed system; that exact command line was not run.@{HOME}, @{PROC}, @{run}) come from include <tunables/global> in the profile's preamble (curl:12).aa-genprof or aa-autodep always starts with abstractions/base (aa.py:391-392).network rules and 11 owner rules (mbsync:17-40); znc has base, nameservice, ssl_certs, perl, python (znc:6-37).After expansion curl has capability net_bind_service, (from abstractions/nis), network netlink raw, (from nameservice) and ptrace, signal and unix rules (from base). Check with apparmor_parser -p.
-p on profiles/apparmor.d/curl.capability net_bind_service,: nameservice includes nis (nameservice:62), and nis has the rule with the comment "portmapper may ask root processes to do nis/ldap at low ports" (nis:15-16).network inet stream, network inet6 stream, network inet dgram, network inet6 dgram, and network netlink raw, ("Netlink raw needed for nscd"): nameservice:92-99.base (base:134-163): ptrace (readby), ptrace (tracedby), ptrace (read) peer=@{profile_name}, signal (receive) peer=unconfined, signal peer=@{profile_name}, signal (receive, send) set=("exists"), unix peer=(label=@{profile_name}), unix (receive) peer=(label=unconfined), unix (create), unix (getattr, getopt, setopt, shutdown),.ix: owner @{HOME}/.Private/** mrixwlk, and owner @{HOMEDIRS}/.ecryptfs/*/.Private/** mrixwlk, (base:176-180).ping includes nameservice (bin.ping:18) and its expanded text contains the same rules.nameservice-strict: 30 non-comment lines after expansion against 142 for nameservice.apparmor_parser -p, not the profile file. The six include lines of curl stand for about 370 lines the author of the profile did not write.base and matter for lateral movement: ptrace (readby), and ptrace (tracedby), carry no peer condition, so any task whose own policy lets it read or trace may do so to this one; signal (receive) peer=unconfined, and unix (receive) peer=(label=unconfined), open the profile to unconfined peers.owner @{HOME}/.Private/** mrixwlk, gives ix on files the user owns under ~/.Private/: a place where a confined program that can write may also execute, inheriting the same profile.nameservice reaches further than name lookup: through kerberosclient and ldapclient it grants read access to /etc/krb5.keytab and /etc/ldap.secret (kerberosclient:30, ldapclient:15). The files' own permissions still apply.abstractions/NAME.d/ (for example include if exists <abstractions/base.d>), so the expanded text of a machine can differ from the tree.owner limits a rule to files whose owner is the process's fsuid. abstractions/user-tmp grants owner /tmp/** rwkl, and owner /var/tmp/** rwkl,.
owner file rw @{HOME}/**, (curl:33); owner @{HOME}/[^.]**.@{qpdf_ext} rw, with @{qpdf_ext} = [qQpP][dD][fF] [jJ][sS][oO][nN] (qpdf:6, qpdf:17); owner @{HOME}/.znc/moddata/** rw, (znc:32).@{HOME} is defined by tunables/global through tunables/home: @{HOME}=@{HOMEDIRS}/*/ /root/ with @{HOMEDIRS}=/home/ (home:15-21). /home/ann on the slide is an illustration.owner rule is used when the uid the task accesses files with (its fsuid) equals the file's owner; otherwise the rules without owner decide. The log fields fsuid= and ouid= are the two values compared.abstractions/user-tmp in full (user-tmp:15-22):owner @{HOME}/tmp/** rwkl,
owner @{HOME}/tmp/ rw,
owner /var/tmp/** rwkl,
/var/tmp/ rw,
owner /tmp/** rwkl,
/tmp/ rw,
owner /tmp/tr_session_id_* rwk, (transmission:31).m on files the user can write, which allows mapping them executable: owner file mrw @{HOME}/orcexec.*, (rygel:62-64, generated code) and owner @{HOME}/.znc/modules/* mrw, (znc:30, loadable modules). They are deliberate.uid_eq(subj_uid, cond->uid) the first permission set is used, else the next one (file.c:202-205).The expanded curl profile has no write rule for system directories (its write rules outside owner paths name devices, service sockets, the snapd socket and the temp directories themselves), no raw socket rule, no exec rule of its own, one capability, and audit deny @{HOME}/.ssh/{,**} mrwkl, from private-files-strict. A missing rule is a denial. The outcomes are read from the kernel code, not run.
-p). The outcomes are what the kernel code does; none was run on a kernel./etc/cron.d/x: the write rules are owner file rw @{HOME}/**, (curl:33), abstractions/user-tmp and file rw @{run}/snapd.socket, (curl:45). Nothing covers /etc, /usr, /var/lib or /boot. The open fails with EACCES.network rules are unix stream, unix dgram, inet stream, inet dgram, inet6 stream, inet6 dgram (curl:36-41) plus netlink raw from nameservice. There is no network inet raw, and no network packet,.@{exec_path} mr, (curl:24), without x. The expanded profile has exec permission in three places only: @{run}/nscd/db* mix, (from nameservice) and the two eCryptfs rules of base. Any other exec fails with EACCES.capability net_bind_service,. Every other capability is refused with EPERM, also for a process started by root.audit deny @{HOME}/.ssh/{,**} mrwkl, (private-files-strict:12). A deny rule wins over an allow rule of the same priority, and audit puts the refusal in the log.priority=1 owner file r @{HOME}/.curlrc, and priority=1 owner file r @{HOME}/.config/curlrc, (curl:27-28). private-files has deny @{HOME}/.*rc mrk,, which matches the name .curlrc; which deny each of the two lines was written against was not traced.testcase_dmesg_capability.in (operation="capable" ... capability=23 capname="sys_nice", two spaces before capname) with illustrative values (testcase_dmesg_capability.in). dac_override is capability 1 (capability.h:121).mount, umount, pivot_root, userns, change_profile, and ptrace or signals towards other profiles.abi <abi/5.0>,) and on the kernel: mqueue has no hook in the kernel, so no profile restricts it there.apparmor_capable calls aa_capable for a confined task (lsm.c:199-211); profile_capable returns -EPERM unless the capability is in the allow set (capability.c:128-154).aa_profile_af_perm matches family, type and protocol against the profile's rules (net.c:254-270).error = -EACCES (domain.c:740-770).unconfined and default_allow profiles (parser_regex.c:1385-1450).owner on root's files under /root/ (@{HOME} includes /root/).file rw @{run}/snapd.socket, (curl:43-45) lets the profile talk to the snapd socket; the comment says it is kept "until we can revisit it with delegation or profile refactoring". What snapd grants to that peer is outside both trees.Broad fits when the program has no capabilities, writes only owner paths and keeps its children confined. tar (capability dac_override, with file rwl /**,) shows what happens otherwise.
capability line in their files.owner rules only: under @{HOME}, /tmp, /var/tmp, @{run}/user/*, or for the daemon variant under its own state directory: owner /var/lib/transmission{-daemon,}/downloads/** rw, (transmission:39).ix of an interpreter (/{usr/,}bin/python{3,3.[0-9],3.[1-9][0-9]} rix,, znc:41) or a child profile (file Cx /usr/bin/dash,, tnftp:34; file Cx /usr/libexec/rygel/mx-extract -> mx-extract,, rygel:37). None uses ux, Ux or pux.priority=1 file Cx @{tnftp_rx}/* -> cmds, (tnftp:66); the cmds child has deny network, (tnftp:77) and audit deny file w @{tnftp_rx}/*, (tnftp:80).capability chown, capability fowner, capability dac_override, capability dac_read_search, and file rwl /**, (tar:18-25). usr.sbin.apache2 has the same combination.Uxr for three helpers and says "Ideally these would use a child profile. They are all ELF executables so running with 'Ux', while not ideal, is ok because we will at least benefit from glibc's secure execute" (firefox:480-485).flags=(unconfined) is not a broad profile: it gives the program a profile name and confines nothing. 76 of the 198 files in profiles/apparmor.d carry the flag (grep).aa-enforce and aa-complain skip a profile with flags=(unconfined) unless --force is given (tools.py:198-206). aa-enforce --force on one of the 76 stubs would leave a profile whose only rules are userns, and @{exec_path} mr, (firefox:7-11).aa-genprof PROGRAM creates the profile with flags=(complain) and abstractions/base, then loops: run the program, (S)can, answer. (F)inish sets enforce mode. Missing permissions in complain mode are logged as apparmor="ALLOWED" (read from the kernel code).
aa-genprof [-d DIR] [-f LOGFILE] [-j] [--no-abstraction] [-o OUTDIR] program (aa-genprof:67-74). Related: aa-autodep [--force] [-d DIR] [--no-reload] program..., aa-logprof [-d DIR] [-f LOGFILE] [-m MARK] [-j] [-a] [--no-abstraction] [-o OUTDIR], aa-complain, aa-enforce./proc/sys/kernel/printk_ratelimit to 0 so that records are not dropped, restoring it at exit; print "Please start the application to be profiled in another window and exercise its functionality now."; offer (S)can system log for AppArmor events and (F)inish. On Finish every profile it put into complain mode is set to enforce and reloaded: "Reloaded AppArmor profiles in enforce mode."aa-genprof uses that file and puts it in complain mode.flags=(complain), include <abstractions/base>, and for a binary PATH mr, (aa.py:386-410); a script with a #! line gets r on the script, ix on the interpreter and the interpreter's abstraction. The file also gets abi <abi/5.0>, and include <tunables/global> when those files exist (aa.py:516-519); they are left off the slide./usr/bin/curl flags=(complain) { (read from the tool's code, not from a run).-f, or the first existing of /var/log/audit/audit.log /var/log/syslog /var/log/messages (logprof.conf:15).apparmor="ALLOWED". An exec with no matching rule runs under a learning profile named in target= with //null- in its name.deny rules still refuse, and silently. A complain-mode profile that includes private-files-strict still blocks ~/.ssh.[qualifiers] in logprof.conf (shells, core utilities) are refused a profile of their own (aa.py:2501-2510).aa-complain, restart the service, use it, aa-logprof, answer, aa-enforce (README:11-34).create_new_profile (aa.py:386-428), autodep (aa.py:484-520), the profile head in get_header (profile_storage.py:136-176), do_logprof_pass (aa.py:1501-1516), set_logfile (aa.py:1478-1490).perms->complain |= ~(perms->allow | perms->deny) (lib.c:369-370); the error is cleared for an ALLOWED record (lib.c:460-461, complain_error at audit.h:206-211); the learning profile on exec (domain.c:749-767).aa-logprof offers include <abstractions/...> lines whose rules cover the event, then the exact path and globs. Keys: (A)llow, (D)eny, (I)gnore, (G)lob, Glob with (E)xtension, (N)ew, Audi(t). Glob widens one step per press, ending at /**. The menu is rendered from the tool's code, not captured from a session.
operation="open" record in syslog_datetime_01.in (syslog_datetime_01.in), with illustrative values; pid= and comm= are behind the .... The profile name is the one aa-genprof gave the new profile in the previous scene.(D)eny follows the sessions recorded for aa-logprof. Headers Profile, Path, New Mode, Severity (aa.py:1167-1173, file.py:353-399); options are printed as N - text with the selected one in brackets (ui.py:500-507). The severity number comes from utils/severity.db, is left out on the slide and blocks nothing.include <abstractions/NAME> for every abstraction with a rule that covers the event, sorted by name (aa.py:1152-1156); then, for a file, paths of existing rules that match, globs from the [globs] table of logprof.conf, and the exact path last (aa.py:2378-2408). The first option is the preselected one.ssl_certs has /etc/{,libre}ssl/certs/{,**} r, (ssl_certs:17) and ssl_keys has /etc/ssl/** r, under the comment "Just include the whole /etc/ssl directory if we should have access to private keys too" (ssl_keys:16-19). Nothing ranks proposals by breadth. That these are the only two for this path is read from the abstraction files, not from a run.base already covers /etc/ssl/openssl.cnf through crypto and openssl.(O)wner permissions off appears only when the record's fsuid equals its ouid and the proposed rule therefore starts with owner.(D)eny, as the slide shows, also for a record logged in complain mode (ALLOWED): Return writes a deny rule, so press A to allow. Known discrepancy, "the default answer of every rule question is Deny": the code means Allow to be the default for complain-mode records and Deny for enforce-mode records, but the test that should select Allow never matches (aa.py:1177-1182). Observed in the recorded sessions of aa-logprof: every rule question under Complain-mode changes: showed (A)llow / [(D)eny].*; when the path already ends in /* or /** it removes one more directory and ends in /** (aare.py:97-123).--no-abstraction on either tool suppresses the include offers (aa-genprof:72, aa-logprof:32); base is still added to a new profile.aa-logprof -a accepts every rule and answers exec questions with px when a profile for the target exists, otherwise ix (ui.py:518-526).@{etc_ro} or @{HOME} may not be recognised as covering a logged path, and the question is asked again. A full session was not run. See Choosing abstractions.aa-logprof -a it is accepted without a question.ssl_keys on a client is the example on the slide.owner file rw @{HOME}/**, minus the deny rules of private-files-strict is what a compromised curl can read and write; network inet stream, has no address condition. This is derived from the profile text and the kernel code; it was not run.
owner file rw @{HOME}/**, (curl:33) covers every file the user owns under the home directory, less the deny rules below.private-files (private-files:9-49) denies shell history and editor backup files, reading and writing ~/.*rc, ~/.bash*, ~/.profile* and login files, and writing under ~/bin/, ~/.config/autostart/, ~/.config/upstart/, ~/.init/, the KDE autostart and env directories and ~/.local/share/thumbnailers/. private-files-strict (private-files-strict:10-27) adds ~/.aws, ~/.gnupg, ~/.ssh, GNOME keyrings, ~/.mozilla, Chromium, Evolution, Thunderbird, KMail and KWallet data.~/.git-credentials, ~/.kube/config, documents and source trees. These names are examples chosen for the slide; the claim is only that no deny rule in the two files matches them.audit deny @{HOME}/.config/ w, is a rule for the directory itself. It does not match ~/.config/systemd/user/x.service, and no other deny does. Whether a file there is ever run depends on the system: on a system where the user's systemd instance reads that directory, the unit runs as a new process that the curl profile does not confine, unless a profile attaches to it.network inet stream, network inet dgram, and the inet6 pair (curl:36-41) have no address or port condition.file rw @{run}/snapd.socket, (curl:43-45) is the one grant in the profile that is neither the user's own files nor a network family: the profile may open the snapd socket for reading and writing. The comment above the rule says it stays "until we can revisit it with delegation or profile refactoring". What snapd lets that peer do is outside both trees.Next: prac-abstractions, prac-privileged, syn-owner, syn-globbing, ut-genprof, ut-logprof, adm-denials.
owner compares and where it can be written.*, ** and [^.] match.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run with -p on a shipped profile, with nothing loaded into a kernel; "code" means the source of the tools or of mainline Linux 7.4 was read, not run; "derived" means the result was reasoned from that code and from the profile text. Counts are grep counts over the tree. Nothing here was observed on a running kernel.
profiles/apparmor.d/curl, 23 non-comment lines.
| Line | Text | Remark |
|---|---|---|
| 10 | abi <abi/5.0>, | the feature set the profile is compiled for |
| 12 | include <tunables/global> | defines @{HOME}, @{PROC}, @{run} |
| 14 | profile curl /usr/bin/curl { | name and attachment |
| 15 | include <abstractions/base> | libc, locale, loader, logging; also ptrace, signal and unix rules |
| 16 | include <abstractions/consoles> | /dev/tty, /dev/pts/*, /dev/console |
| 17 | include <abstractions/nameservice> | users, hosts, DNS; also sockets and one capability |
| 18 | include <abstractions/private-files-strict> | deny rules for key stores and start-up files |
| 19 | include <abstractions/ssl_certs> | CA certificates, read-only |
| 22 | include <abstractions/user-tmp> | owner rules for /tmp, /var/tmp, ~/tmp |
| 24 | @{exec_path} mr, | map and read the binary; no x |
| 27-28 | priority=1 owner file r @{HOME}/.curlrc, and .config/curlrc | curl's own configuration, above the deny rules |
| 33 | owner file rw @{HOME}/**, | the broad rule: --config, --cacert, -o |
| 36-41 | network unix stream, unix dgram, inet stream, inet dgram, inet6 stream, inet6 dgram, | by family and type, no addresses |
| 45 | file rw @{run}/snapd.socket, | the snap socket |
| 48 | /etc/rpmdevtools/curlrc r, | rpmdev-spectool's curlrc |
| 51 | include if exists <local/curl> | site additions |
Rules of other classes after expansion (tree):
| Rule | Comes from | File and line |
|---|---|---|
capability net_bind_service, | nameservice includes nis | abstractions/nis:16 (include at abstractions/nameservice:62) |
network netlink raw, | nameservice | abstractions/nameservice:99 |
network inet stream, and three more | nameservice (and curl itself) | abstractions/nameservice:92-95 |
ptrace (readby), ptrace (tracedby), ptrace (read) peer=@{profile_name}, | base | abstractions/base:134-142 |
signal (receive) peer=unconfined, signal peer=@{profile_name}, signal (receive, send) set=("exists"), | base | abstractions/base:145-151 |
unix peer=(label=@{profile_name}), unix (receive) peer=(label=unconfined), unix (create), unix (getattr, getopt, setopt, shutdown), | base | abstractions/base:154-163 |
owner @{HOME}/.Private/** mrixwlk, owner @{HOMEDIRS}/.ecryptfs/*/.Private/** mrixwlk, | base | abstractions/base:177,180 |
@{run}/nscd/db* mix, | nameservice | abstractions/nameservice:40 |
nameservice alone expands to 142 non-comment lines, nameservice-strict to 30 (tree).The 198 regular files directly in profiles/apparmor.d/ (not abstractions/, tunables/, abi/, local/, apache2.d/).
| Group | Files | Evidence |
|---|---|---|
| Name only, nothing confined | 76 with flags=(unconfined) (1password, brave, chrome, chromium, code, firefox, flatpak, steam, thunderbird, ...) | body is userns, and @{exec_path} mr, |
| Everything allowed by rule | sbuild and 13 sbuild-*; plasmashell | allow all,; bare capability, network, mount, ... |
| Broad, abstraction-based, no capability rules of their own | curl, tnftp, mbsync, qpdf, znc, john, gs, rygel, transmission, lsb_release | 3 to 11 abstractions per profile, owner @{HOME}/... rules, recursive globs |
| Precise, privileged | bin.ping, usr.sbin.traceroute, sbin.klogd, unix-chkpwd, who, iotop-c, nvidia_modprobe, usr.sbin.ntpd, usr.sbin.dnsmasq, the dovecot files, ... | 1 to 12 named capabilities, exact paths, Px/Cx, peer conditions |
| Privileged and broad | tar, usr.sbin.apache2, zgrep's helper child | capabilities next to a whole-filesystem glob |
Numbers per file (non-comment lines; include <abstractions/ lines; capability lines; lines with **; owner lines):
| File | Lines | Abstractions | Capabilities | ** | owner |
|---|---|---|---|---|---|
| curl | 23 | 6 | 0 | 1 | 3 |
| mbsync | 27 | 4 | 0 | 9 | 11 |
| qpdf | 25 | 1 | 0 | 16 | 12 |
| znc | 27 | 5 | 0 | 4 | 13 |
| tnftp (4 profiles) | 49 | 16 | 0 | 2 | 5 |
| transmission (4 profiles) | 70 | 23 | 0 | 6 | 9 |
| bin.ping | 15 | 3 | 2 | 0 | 0 |
| usr.sbin.dnsmasq | 88 | 4 | 7 | 1 | 5 |
profiles/apparmor/profiles/extras/ holds 111 more profile files. Its README says they "are not turned on by default because they are not as mature as the profiles in /etc/apparmor.d/".The expanded curl profile (tree) and the result in the kernel (code, derived).
| Rule class | In the expanded curl profile | Request without a rule |
|---|---|---|
| capability | net_bind_service only | refused with EPERM |
| file write | owner rules under @{HOME}, /tmp, /var/tmp; @{run}/snapd.socket | refused with EACCES |
| network | unix and inet/inet6 stream and dgram; netlink raw | socket creation refused |
| exec | @{run}/nscd/db* mix, and the two eCryptfs ix rules | refused with EACCES |
| ptrace | be read or traced by others; read itself | refused |
| signal | receive from unconfined; itself; the exists check | refused |
| mount, umount, pivot_root, userns, change_profile | none | refused |
| named secrets | audit deny on ~/.ssh, ~/.gnupg, ~/.aws and others | refused and logged |
mqueue has no hook in the mainline kernel.| Width | Shipped example | File |
|---|---|---|
| The whole home directory | owner file rw @{HOME}/**, | curl:33 |
| One file type, outside dot directories | owner @{HOME}/[^.]**.@{qpdf_ext} rw, | qpdf:17 |
| The program's own directory | owner @{HOME}/.znc/moddata/** rw, | znc:32 |
| A directory tree kept in a tunable | owner file r @{rygel_media_dirs}/{,**}, | rygel:56 |
abstractions/user-tmp:
owner @{HOME}/tmp/** rwkl,
owner @{HOME}/tmp/ rw,
owner /var/tmp/** rwkl,
/var/tmp/ rw,
owner /tmp/** rwkl,
/tmp/ rw,
owner in the kernel (code): the rule is used when the task's fsuid equals the file's owner.owner /tmp/tr_session_id_* rwk, (transmission:31).aa-autodep [--force] [-d DIR] [--no-reload] program... aa-genprof [-d DIR] [-f LOGFILE] [-j] [--no-abstraction] [-o OUTDIR] program aa-logprof [-d DIR] [-f LOGFILE] [-m MARK] [-j] [-a] [--no-abstraction] [-o OUTDIR] aa-complain [-d DIR] [--no-reload] [--force] program... aa-enforce [-d DIR] [--no-reload] [--force] program...
A new profile contains (code):
| Program | Contents |
|---|---|
| any | flags=(complain), include <abstractions/base>; in the file also abi <abi/5.0>, and include <tunables/global> when present |
| a binary | PATH mr, |
a #! script | SCRIPT r,, INTERPRETER ix, and abstractions/bash, perl, python or ruby when the interpreter is one of those |
Question keys for a file record:
| Key | Effect |
|---|---|
| (A)llow | add the selected option to the profile |
| (D)eny | add a deny rule |
| (I)gnore | skip this record |
| (G)lob | widen the path one step and add it to the options |
| Glob with (E)xtension | widen the path and keep the file extension |
| (N)ew | edit the path by hand |
| Audi(t) | toggle audit on the proposed rule |
| (O)wner permissions on / off | toggle owner; offered when the record's fsuid equals its ouid |
| Abo(r)t, (F)inish | abandon the session (after a confirmation), or stop asking |
[globs] entries of logprof.conf, the exact path. The first is preselected./usr/share/foo/a.txt, /usr/share/foo/*, /usr/share/**, /usr/**, /**.ALLOWED records, Deny for DENIED records.aa-logprof -a: every rule accepted, exec questions answered with px if a profile for the target exists, else ix.-f is not given: /var/log/audit/audit.log, /var/log/syslog, /var/log/messages, first existing.| Message | When |
|---|---|
It seems AppArmor was not started. Please enable AppArmor and try again. | aa-genprof when AppArmor is not available |
... is currently marked as a program that should not have its own profile. ... | the program is listed under [qualifiers] in logprof.conf (shells, core utilities) |
Profile ... is in unconfined mode. Use --force to switch it to enforce mode. | aa-enforce on a flags=(unconfined) profile |
WARNING: Can't find abstractions/base, therefore not adding it to the new profile. | the abstraction file is missing |
apparmor="ALLOWED": any permission that no rule allows and no rule denies (code).deny rule covers. It is refused without a record (code).libraries/libapparmor/testsuite/test_multi/exec01.in, shortened) names it in target=:apparmor="ALLOWED" operation="exec" profile="/home/cb/bin/hello.sh" name="/usr/bin/rm" ... requested_mask="x" denied_mask="x" fsuid=1000 ouid=0 target="/home/cb/bin/hello.sh//null-/usr/bin/rm"
testcase_dmesg_capability.in (shortened):apparmor="DENIED" operation="capable" ... pid=7292 comm="syscall_setprio" capability=23 capname="sys_nice"
aa-logprof turns that record into capability sys_nice,.| What | Where |
|---|---|
new profile: complain flag, base, mr on the binary | utils/apparmor/aa.py:386-428 |
| interpreter to abstraction mapping | utils/apparmor/aa.py:347-383 |
abi and tunables/global added to the file | utils/apparmor/aa.py:516-519 |
| genprof loop, printk ratelimit, Scan and Finish | utils/aa-genprof:122-192 |
| one pass over the log | utils/apparmor/aa.py:1501-1516 |
include proposals (match_includes) | utils/apparmor/aa.py:1419-1459 |
known-rule check (is_known_rule) | utils/apparmor/aa.py:2341-2351 |
file options (propose_file_rules), option order (order_globs) | utils/apparmor/aa.py:2378-2408, utils/apparmor/aa.py:1022-1034 |
keys (available_buttons), default key | utils/apparmor/aa.py:1331-1361, utils/apparmor/aa.py:1177-1182 |
Glob (glob_path) | utils/apparmor/aare.py:97-123 |
-a answers | utils/apparmor/ui.py:518-526 |
| exec menu and its defaults | utils/apparmor/aa.py:622-661, utils/apparmor/aa.py:785-789 |
[qualifiers] refusal | utils/apparmor/aa.py:2501-2510 |
--force guard for unconfined profiles | utils/apparmor/tools.py:198-206 |
| owner test | linux:security/apparmor/file.c:202-205 |
| capability check | linux:security/apparmor/lsm.c:199-211, linux:security/apparmor/capability.c:128-154 |
| socket check | linux:security/apparmor/net.c:254-270 |
| exec without a rule; learning profile in complain mode | linux:security/apparmor/domain.c:749-770 |
| complain set and cleared error | linux:security/apparmor/lib.c:369-370, linux:security/apparmor/lib.c:460-461, linux:security/apparmor/include/audit.h:206-211 |
| "mediates" entry per class | parser/parser_regex.c:1385-1450 |
Two hard links are two names for one file, and AppArmor matches the name that was used. A file denied under one name can be allowed under another; the ordinary owner and mode checks still apply. This is read from the kernel code; it was not run on a kernel.
This scene is derived from the kernel code. It was not run on a kernel. The inode number is decoration.
/var/tmp/s and /etc/shadow are the same file. Systems that label the file itself give the same answer under every name; a name-based system does not./var/tmp/** rw, and no rule for /etc/shadow: open("/etc/shadow") is matched as /etc/shadow and denied; open("/var/tmp/s", O_RDWR) is matched as /var/tmp/s and allowed by AppArmor./etc/shadow because of its mode cannot open the link either.d_namespace_path (path.c:88-128); d_absolute_path is called on the path that was looked up at path.c:124-127.A symlink is resolved to the target's name; a hard link is itself a name of the file. Unlike a copy, a link keeps the inode: owner, mode (including setuid and setgid) and future content, and can be made to a file the program cannot read.
fs.protected_hardlinks setting may: next scene).link() does not follow a symlink given as the existing name. linkat() follows it only with AT_SYMLINK_FOLLOW. Without that flag the hard link is made to the symlink itself, and target= in an AppArmor record is the symlink's own path (read from the kernel code).EXDEV before any other check.AT_SYMLINK_FOLLOW becomes LOOKUP_FOLLOW at namei.c:5988-5989; the EXDEV test is at namei.c:6001-6003.Order in the kernel: same mount (EXDEV), fs.protected_hardlinks (EPERM, an AUDIT_ANOM_LINK audit record), AppArmor's link check for confined tasks (EACCES), then the file system. Unconfined programs are not checked by AppArmor.
The order of checks and their results are read from the kernel code. Nothing here was run. ann and the three callers are illustrations.
linkat system call: look up both names; EXDEV if they are on different mounts; the fs.protected_hardlinks check; the security module hook, which is where AppArmor is asked; then the file system's own checks (write and search permission on the directory among them).fs.protected_hardlinks is the file /proc/sys/fs/protected_hardlinks, value 0 or 1. With 1, a link is refused with EPERM unless the caller's fsuid owns the file or the caller has CAP_FOWNER, or the file is a "safe source": a regular file, not setuid, not setgid with group execute, and both readable and writable by the caller.AUDIT_ANOM_LINK with the text linkat. The code read for this deck shows only the record type and that word, so no full log line is shown. It is not an apparmor="DENIED" record, and no profile rule changes it.EACCES.CAP_FOWNER. A confined task holds that capability only with a capability fowner, rule, so the setting can refuse a confined root too (namei.c:1381-1382).filename_linkat: namei.c:5996-6010, with security_path_link at namei.c:6008.may_linkat: namei.c:1366-1387; safe_hardlink_source: namei.c:1323-1342; the audit call at namei.c:1385.apparmor_path_link calls aa_path_link only for a label that is not unconfined: lsm.c:367-384. error = -EACCES; at the start of the per-profile check: file.c:358.Link check for confined tasks: l on the new name; the existing file must match the rule's target (info="target restricted"); with the subset test, permissions on the new name must be covered by those on the existing name. Records carry operation="link", name= and target=. The outcomes are read from the kernel code.
The three steps and their outcomes are derived from the kernel code; no kernel was run. The record on the slide is real: it is the record in the libapparmor test suite file testcase_dmesg_link_01.in, shortened with ..., fields in the kernel's order.
The check, per profile, in the order the code makes it:
l). Without it the request is denied: requested_mask="l" denied_mask="l".info="target restricted".info="link not subset of target".l is needed on the new name only. The existing name needs no l.name= is the new name, target= the existing file, ouid= the owner of the existing file.apparmor="DENIED" operation="link" parent=19088 profile="/home/ubuntu/bzr/apparmor/tests/regression/apparmor/link" name="/tmp/sdtest.19088-12382-HWH57d/linkfile" pid=19142 comm="link" requested_mask="l" denied_mask="l" fsuid=0 ouid=0 target="/tmp/sdtest.19088-12382-HWH57d/target".info when no exec permission is involved. A real record of that kind (file_xm.in): apparmor="DENIED" operation="link" profile="cargo" name="/var/tmp/portage/dev-lang/rust-1.67.1/work/rustc-1.67.1-src/build/bootstrap/debug/libbootstrap.rlib" pid=12412 comm="cargo" requested_mask="xm" denied_mask="xm" fsuid=250 ouid=250 target="/var/tmp/portage/dev-lang/rust-1.67.1/work/rustc-1.67.1-src/build/bootstrap/debug/deps/libbootstrap-4542dd99e796257e.rlib".rw case of the slide. That is why step 3 shows no masks.linkat(fd, "", AT_FDCWD, path, AT_EMPTY_PATH) on an O_TMPFILE descriptor goes through the same check. The existing name is then a deleted entry, which the regression test describes as "Denial log entry for tmpfile is /path/#[6digits]" (linkat_tmpfile.sh:31-49).attach_disconnected) is packed without the mediate-deleted bit, and the link check then fails for a deleted existing file with info="Failed name lookup - deleted entry". This was not run, and it may be intended.aa_path_link: file.c:437-467; profile_path_link: file.c:331-416; the link permission test at file.c:360-365, the target test at file.c:368-382, the early return without the subset bit at file.c:385-386, the subset comparison at file.c:391-400, xindex_is_subset at file.c:322-329 and its use at file.c:401-407.target= is written at file.c:73-76; ouid is set at file.c:413-415.PATH rwl,: any target, subset test on. link NEW -> OLD,: target restricted, no subset test. link subset NEW -> OLD,: both. rw on a directory plus link DIR/* -> /**, lets the program give itself rw on any file it can link. This is read from the kernel code; it was not run on a kernel.
The four rows and their outcomes are derived from the kernel code; they were not run on a kernel. The request is assumed to pass the kernel's own checks first (same mount, fs.protected_hardlinks, directory permissions), and the file's owner and mode still apply to the later open. That is what "as far as AppArmor is concerned" stands for.
/var/tmp/** rwl,: the letter allows any file as the target, with the subset test. The manual states the equivalence: /foo l, maps to link subset /foo -> /**, (apparmor.d.pod:1165-1171), and "the new link MUST have a subset of permissions as the original file (with the exception that the destination does not have to have link access)" (apparmor.d.pod:1105-1110).link /var/tmp/* -> /srv/data/**,: the target must match /srv/data/**, and nothing is compared. /etc/shadow is refused with info="target restricted".link subset /var/tmp/* -> /srv/data/**,: both the target restriction and the subset test./var/tmp/** rw, with link /var/tmp/* -> /**,: the link is allowed, and the rw rule then applies to the new name. This is the combination to avoid./var/tmp/** rwl, with /etc/shadow r,. The subset test fails for write only: the new name would add w.rename() moves a name without a subset test. It needs rw on the old name and w on the new one. A file renamed into a directory whose rule adds x or m gains those permissions under the new name.rename asks for: lsm.c:433-442.An l-only rule passes the subset test for any target, because the compared set is empty. A deny on a directory blocks links created in it, not links made from it. Links by unconfined programs are not checked by AppArmor (read from the kernel code).
Everything here is derived from the kernel code: it states what the check, as defined, permits. Nothing was run. The profile publisher, the key name and /srv/export/ are illustrations. This is how the check is defined, not a bug in it.
audit deny @{HOME}/.ssh/{,**} mrwkl, (private-files-strict:12).fs.protected_hardlinks lets it through, and it can write /srv/export/.l leaves nothing to compare, so the test passes for any target.deny ... l denies. A deny with l is carried by the link pair keyed on the new name: it stops creating a link whose new name is under ~/.ssh/. Linking a file from ~/.ssh/ to another directory is stopped only by the subset test of the rule for that directory, because the deny removes read and write from the existing name, and only if that rule grants more than l.fs.protected_hardlinks and the file permissions are the only limits.rename() has no subset test. It asks for read, write and delete on the old name and write and create on the new one (lsm.c:433-442); a file moved into a directory whose rule adds x or m gains those permissions.l in shared or broad locations: owner /tmp/** rwkl, (user-tmp:21); /tmp/ntp* rwl, and /var/tmp/ntp* rwl, in a root daemon's profile, without owner (usr.sbin.ntpd:43, usr.sbin.ntpd:68); /** mrwlkix, (usr.sbin.apache2:86); /** rwkl, (ubuntu-helpers:93); file rwl /**, (tar:25); owner @{HOME}/[^.]* rwl, (user-write:20, user-download:20).profile_path_link: file.c:360-407. The hooks for link and rename: lsm.c:367-384, lsm.c:433-442.owner on a link or file rule is tested against the existing file's owner. owner /var/tmp/** rwl, lets a program link only files it owns, and grants nothing on a planted link to someone else's file. This is read from the kernel code; it was not run on a kernel.
Derived from the kernel code; not run on a kernel. ann, the uid 1000 and the file names are illustrations.
owner rules count only when the task's fsuid equals that owner. So owner /var/tmp/** rwl, gives l only for files the task owns; for any other file the new name has no l and the link is denied.owner rule on the new name grants access only if the opener owns the file. The owner is a property of the file and is the same under every name.ouid= in a link record is the owner of the existing file.owner rule always matches.owner does nothing for a program that runs as root and links root-owned files. ntpd's /tmp/ntp* rwl, has no owner (usr.sbin.ntpd:43), and adding one would not narrow it for root's own files.owner /var/tmp/** rwkl, and owner /tmp/** rwkl,, next to /var/tmp/ rw, and /tmp/ rw, for the directories themselves (user-tmp:15-22).owner in front of a link rule is accepted by the parser: owner /tmp/foo l -> /tmp/bar1, (ok_link_4.sd).aa_path_link fills cond from the existing inode: file.c:443-448.aa_lookup_condperms): file.c:202-206, used at file.c:227-228.ouid in the record: file.c:413-415.Give l only where the program calls link(). Prefer the letter (subset test on). Keep link name and target in one tree. Put owner on rules for /tmp and /var/tmp. Keep fs.protected_hardlinks at 1.
The four rules are quoted from the shipped profiles. The right-hand column applies the previous scenes to them: it says what each rule allows in the kernel, read from the code. It is not a finding of a defect in any profile.
@{DOVECOT_MAILSTORE}/** rwkl, (usr.lib.dovecot.dovecot-lda:25); @{run}/klogd.pid krwl, (sbin.klogd:31); owner /tmp/** rwkl, (user-tmp:21); /tmp/ntp* rwl, (usr.sbin.ntpd:43).The guidance:
name= in the denial.l only where the program calls link or linkat. Prefer the bare l letter, which has the subset test, over link A -> B, without subset.link rule is needed, keep the target pattern narrow and inside the same tree as the new name, as the mail store rule does.owner on write rules for directories shared with other users (/tmp, /var/tmp), so that a name planted there for someone else's file gets no permission.deny for one path to protect a file that may have other names; a deny matches names, not files.fs.protected_hardlinks and fs.protected_symlinks at 1; they cover programs that are not confined.l rules: /var/log/boot.msg rwl, (sbin.klogd:30); /var/lib/ntp/drift rwl, (usr.sbin.ntpd:48); /etc/shadow rwl, and its siblings in the extras profile for passwd (usr.bin.passwd:23-37); and a link rule with a narrow target, owner @{HOME}/.config/QtProject.conf rwl -> @{HOME}/.config/#[0-9]*[0-9], (qt5-settings-write:9).O_TMPFILE and then linkat need l on the final name and w on the directory entries (linkat_tmpfile.sh:31-49).attach_disconnected; not run, and it may be intended. See the scene "The link check in three steps".Next: syn-link-rules, prac-symlinks, prac-privileged, syn-owner, adm-denials, sec-path-limits, k-match.
fs.protected_hardlinks for ordinary users, the profile's link check for confined programs, and the file system's own permissions. owner limits what a planted link can expose.What each deck answers:
link, the l letter and subset.l shows up in root daemons.user-tmp and its l in /tmp.owner on write and link rules.target= field.Basis of the statements on this page: the kernel behaviour is read from the source of mainline Linux 7.4 (7.4-rc2, 97d73c825) and the shipped policy from the AppArmor tree at 836052d21 (6.0.0~alpha2). Nothing here was observed on a running kernel. "Derived" means reasoned from that code. The grammar of link rules, the l letter and subset is in syn-link-rules.
For link(old, new) and linkat(...), in this order:
| Step | What is checked | On failure | Log record |
|---|---|---|---|
| 1 | both names are looked up; they must be on the same mount | EXDEV | none |
| 2 | fs.protected_hardlinks, when it is 1 | EPERM | an audit record of type AUDIT_ANOM_LINK with the text linkat; not an AppArmor record |
| 3 | the security module hook: AppArmor's link check, for confined tasks only | EACCES | apparmor="DENIED" operation="link" with name= and target= |
| 4 | the file system's own checks, such as write and search permission on the directory | the file system's error | none from AppArmor |
link() does not follow a symlink given as the existing name. linkat() follows it only with AT_SYMLINK_FOLLOW; without it the link is made to the symlink itself and target= is the symlink's own path.
Per profile, for a confined task:
l); otherwise the request is denied.info="target restricted".info="link not subset of target".l is needed on the new name only.
| Rule spelling | Target | Subset test |
|---|---|---|
/var/tmp/** rwl, | any file | on |
link /var/tmp/* -> /srv/data/**, | must match /srv/data/** | off |
link subset /var/tmp/* -> /srv/data/**, | must match /srv/data/** | on |
Worked examples for link("/etc/shadow", "/var/tmp/s") by a task that passes the kernel's own checks (derived, not run):
| Profile fragment | Outcome |
|---|---|
/var/tmp/** rw, | denied at step 2: no l; requested_mask="l" denied_mask="l" |
/var/tmp/** rwl, and nothing for /etc/shadow | denied at step 5: /etc/shadow has neither read nor write |
/var/tmp/** rwl, and /etc/shadow r, | denied at step 5, for write only |
/var/tmp/** rw, and link /var/tmp/* -> /srv/data/**, | denied at step 3 with info="target restricted" |
/var/tmp/** rw, and link /var/tmp/* -> /**, | allowed, no subset test; the task can then open /var/tmp/s read-write under the first rule. The combination to avoid |
What the subset test protects against: a profile that may write in one directory and may only read, or not access, files elsewhere cannot give itself more permissions on those files by linking them into the writable directory.
A denial at step 2, from the libapparmor test suite (testcase_dmesg_link_01.in):
[ 2010.738449] audit: type=1400 audit(1284062308.965:276251): apparmor="DENIED" operation="link" parent=19088 profile="/home/ubuntu/bzr/apparmor/tests/regression/apparmor/link" name="/tmp/sdtest.19088-12382-HWH57d/linkfile" pid=19142 comm="link" requested_mask="l" denied_mask="l" fsuid=0 ouid=0 target="/tmp/sdtest.19088-12382-HWH57d/target"
A failed subset test (file_xm.in):
type=AVC msg=audit(1676978994.840:1493): apparmor="DENIED" operation="link" profile="cargo" name="/var/tmp/portage/dev-lang/rust-1.67.1/work/rustc-1.67.1-src/build/bootstrap/debug/libbootstrap.rlib" pid=12412 comm="cargo" requested_mask="xm" denied_mask="xm" fsuid=250 ouid=250 target="/var/tmp/portage/dev-lang/rust-1.67.1/work/rustc-1.67.1-src/build/bootstrap/debug/deps/libbootstrap-4542dd99e796257e.rlib"FSUID="portage" OUID="portage"
| Field | Meaning in a link record |
|---|---|
name= | the new name |
target= | the existing file |
ouid= | the owner of the existing file |
requested_mask=, denied_mask= | l when the new name has no link permission; for a failed subset test, the permissions the existing name lacks |
info="target restricted" | the existing file does not match the rule's target |
info="link not subset of target" | set only when exec transitions of the two names disagree |
Not determined: the exact mask letters of a failed subset test for a pair of rw rules. The code reports the permissions of the new name that the existing name lacks, and file_xm.in shows xm; no kernel was available to produce a record for rw.
owner rules count only when the task's fsuid equals that owner.owner /var/tmp/** rwl,: the task can link only files it owns into /var/tmp/; for any other file the new name has no l.owner rule on the new name grants access only if the opener owns the file.owner always matches.owner /tmp/foo l -> /tmp/bar1, (ok_link_4.sd), audit deny owner link subset /alpha/beta -> /tmp/**, (ok_link_audit_deny_owner_subset.sd).sysctl fs.protected_hardlinks, file /proc/sys/fs/protected_hardlinks, value 0 or 1. With 1, a link is refused with EPERM unless one of these holds:
CAP_FOWNER;The variable has no initializer in the kernel source, so the kernel's own default is 0. The value on an installed system is set outside both source trees. Documentation: kernel docs: protected_hardlinks.
| Caller | Sysctl | link("/etc/shadow", "/var/tmp/s") |
|---|---|---|
| ordinary user, unconfined | 1 | refused by the sysctl: EPERM |
| root, unconfined | 1 | created: root owns the file and AppArmor is not asked |
| root, confined | 1 | the sysctl lets it through; the profile's link check decides |
| ordinary user, unconfined | 0 | created if the user can write the directory; the file's owner and mode still limit what can be done with it |
A refusal by the sysctl produces no AppArmor record, and no profile rule changes it.
| Way | What AppArmor checks | Subset test |
|---|---|---|
rename(old, new) | read, write and delete on the old name (rw), write and create on the new name (w) | none: a file renamed into a directory whose rule adds x or m gains those permissions |
| bind mount | mount rules, not link rules | none |
O_TMPFILE then linkat(fd, "", AT_FDCWD, path, AT_EMPTY_PATH) | the same link check; the existing name is a deleted entry, logged as /path/#NNNNNN. The regression test passes with l on the final name plus w on dir/ and dir/* (linkat_tmpfile.sh:31-49) | as for any link |
| Rule | Source | Shared directory | owner |
|---|---|---|---|
@{DOVECOT_MAILSTORE}/** rwkl, | usr.lib.dovecot.dovecot-lda:25 | no | no |
@{run}/klogd.pid krwl, | sbin.klogd:31 | no | no |
/var/log/boot.msg rwl, | sbin.klogd:30 | no | no |
owner /tmp/** rwkl,, owner /var/tmp/** rwkl, | user-tmp:15-22 | yes | yes |
/tmp/ntp* rwl,, /var/tmp/ntp* rwl, | usr.sbin.ntpd:43, usr.sbin.ntpd:68 | yes | no (a root daemon) |
/var/lib/ntp/drift rwl, | usr.sbin.ntpd:48 | no | no |
/etc/shadow rwl, and siblings | usr.bin.passwd:23-37 | no | no |
owner @{HOME}/[^.]* rwl, | user-write:20, user-download:20 | no | yes |
owner @{HOME}/.config/QtProject.conf rwl -> @{HOME}/.config/#[0-9]*[0-9], | qt5-settings-write:9 | no | yes |
/** mrwlkix, | usr.sbin.apache2:86 | everything | no |
/** rwkl, | ubuntu-helpers:93 | everything | no |
file rwl /**, | tar:25 | everything | no |
name= in the denial; where a path is a symlink on some systems and a real file on others, list both.l only where the program calls link or linkat. Prefer the bare l letter, which has the subset test, over link A -> B, without subset.link rule is needed, keep the target pattern narrow and inside the same tree as the new name.owner on write rules for directories shared with other users (/tmp, /var/tmp).deny for one path to protect a file that may have other names. A deny matches names, not files.fs.protected_hardlinks and fs.protected_symlinks at 1. They cover programs that are not confined.All of this is what the kernel code permits; none of it was run.
l-only new name passes the subset test for any target: the compared set is empty. With /srv/export/* l, a task can link a file it cannot read into /srv/export/; a second program whose rules allow /srv/export/* r, then reads it under the new name.deny with l, as in audit deny @{HOME}/.ssh/{,**} mrwkl, (private-files-strict:12), denies creating a link whose new name is under ~/.ssh/. Linking a file out of ~/.ssh/ is stopped only by the subset test of the destination's rule, and only if that rule grants more than l.fs.protected_hardlinks and the file permissions are the only limits for them.rename has no subset test and can add x or m in the destination.l in shared or broad locations are listed in the table above.attach_disconnected is set, and the kernel then does not apply its default. linkat on an O_TMPFILE descriptor would fail with ENOENT and info="Failed name lookup - deleted entry" under flags=(attach_disconnected) and pass without flags. Not run; it may be intended.linkat_tmpfile.sh marks the case "tmpdir and tmpfile (w), link" as xpass, the harness's marker for a known problem. What that records about current kernels was not determined.| What | Where |
|---|---|
aa_path_link | file.c:437-467 |
profile_path_link: names, link permission, target, subset | file.c:331-416, file.c:345-356, file.c:360-365, file.c:368-382, file.c:385-386, file.c:391-400 |
xindex_is_subset and its use | file.c:322-329, file.c:401-407 |
target= in the record; ouid | file.c:73-76, file.c:413-415 |
| owner condition: filled, tested | file.c:443-448, file.c:202-206, file.c:227-228 |
apparmor_path_link, apparmor_path_rename | lsm.c:367-384, lsm.c:433-442 |
| name construction | path.c:88-128; deleted entries path.c:160-164 |
| path flags default at unpack | policy_unpack.c:1246-1252 |
| parser writing path flags | parser_interface.c:530-545 |
filename_linkat | namei.c:5996-6010; AT_SYMLINK_FOLLOW namei.c:5988-5989 |
may_linkat, safe_hardlink_source | namei.c:1366-1387, namei.c:1323-1342 |
| the sysctl variable and table | namei.c:1211, namei.c:1226-1234 |
inode_owner_or_capable | inode.c:2770-2785 |
manual: l and its link-rule equivalent | apparmor.d.pod:1105-1110, apparmor.d.pod:1165-1171 |
unix-chkpwd: capability audit_write, and capability dac_read_search, each with a reason, and /etc/shadow r,. A precise profile lists individual capabilities, exact paths and named exec targets.
unix-chkpwd, attached to /{,usr/}{,s}bin/unix_chkpwd (unix-chkpwd:14). Its two capabilities each sit under a comment that gives the reason: capability audit_write, "To write records to the kernel auditing log." and capability dac_read_search, "To read shadow with 000 permissions." (unix-chkpwd:18-21)./etc/shadow r, (unix-chkpwd:27). The only network rule of its own is network netlink raw, (unix-chkpwd:23).abstractions/base and abstractions/nameservice (unix-chkpwd:15-16), which add their own rules; the next scene shows what nameservice brings.owner /dev/pts/[0-9]* rw, and owner /dev/tty[0-9]* rw, stand under the comment "file_inherit" (unix-chkpwd:37-39): terminals the helper inherits already open.flags=(attach_disconnected.path=/att/unix-chkpwd/), and five rules name paths below that prefix, for example /att/unix-chkpwd/run/systemd/journal/dev-log w, (unix-chkpwd:41-46). See The other profile flags.**, 2 owner rules.ping: capability net_raw, capability setuid, network inet raw, network inet6 raw, and two exact paths. Through abstractions/nameservice it also gets capability net_bind_service, inet stream and dgram sockets and network netlink raw.
owner file rw @{HOME}/**, (curl:33), six network rules (curl:36-41) and file rw @{run}/snapd.socket, (curl:45).abstractions/nameservice adds to every profile that includes it: network inet stream, network inet6 stream, network inet dgram, network inet6 dgram, and network netlink raw, (nameservice:92-99), and through abstractions/nis capability net_bind_service, (nis:16). The parser built from the AppArmor tree, run on bin.ping, lists them next to ping's own two capabilities.abstractions/nameservice-strict instead: iotop-c:8, hostname:21, nslookup:20, mbsync:18./etc/modules.conf, the /proc path) and curl has four (.curlrc, .config/curlrc, /etc/rpmdevtools/curlrc, @{run}/snapd.socket), so the number does not separate the styles.**, owner lines):| File | Lines | Abstractions | Capabilities | ** | owner | Flags |
|---|---|---|---|---|---|---|
| bin.ping | 15 | 3 | 2 | 0 | 0 | none |
| sbin.klogd | 18 | 1 | 2 | 0 | 0 | none |
| unix-chkpwd | 22 | 2 | 2 | 0 | 2 | attach_disconnected.path=/att/unix-chkpwd/ |
| usr.sbin.ntpd | 58 | 4 | 9 | 0 | 0 | attach_disconnected |
| usr.sbin.dnsmasq | 88 | 4 | 7 | 1 | 5 | attach_disconnected |
| usr.sbin.dovecot | 66 | 7 | 9 | 4 | 1 | attach_disconnected |
| usr.sbin.smbd | 65 | 8 | 12 | 10 | 0 | attach_disconnected.path=/att/smbd/ |
| curl, for contrast | 23 | 6 | 0 | 1 | 3 | none |
** (usr.sbin.ntpd:22-69).passwd profile has one rule per file the program rewrites: /etc/shadow rwl, /etc/shadow.old rwl, /etc/shadow.tmp?????? rwl, /etc/shadow.lock rwl, /etc/shadow- rw, /etc/shadow+ rw, (extras/usr.bin.passwd:23-37).deny capability sys_admin, plus capability sys_nice, (iotop-c) forces the weaker capability and silences the probe. In the kernel a capability without a rule fails with EPERM; with deny it fails without a log record. Read from the kernel code.
capability <name> [<name>...], and deny capability <name>,.ioprio_set checks sys_admin or sys_nice, "with sys_admin checked first, with OR shortcut logic", when it sets a real-time class.if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_NICE)) return -EPERM; for the real-time class (ioprio.c:47).deny capability X, and no rule for X both refuse X. The deny form adds two things: no log record, and no later rule or include can grant it. In the kernel a capability without a rule fails with EPERM (capability.c:150-154); one in the quiet set, which is where deny puts it, returns the error without a record (capability.c:87-92).operation="capable" ... capability=23 capname="sys_nice"); profile, pid and comm are illustrative, and ... stands for the fixture's parent= field. sys_admin is capability 21 and sys_nice is 23 (capability.h:281, capability.h:296).capability net_admin, # for DHCP server and capability net_raw, # for DHCP server ping checks (usr.sbin.dnsmasq:22-28).# capability dac_override, and # capability setuid, commented out under "Flatpak seems to work fine without these capabilities, so don't grant them unless actual functionality breakage is caused elsewhere" (fusermount3:11-15).nvidia_modprobe holds chown, mknod, setuid and sys_admin; capability sys_module, exists only in its kmod child (nvidia_modprobe:12-15, nvidia_modprobe:44).deny capability net_admin, # noisy setsockopt() calls (usr.sbin.traceroute:20), deny capability block_suspend, (usr.sbin.nscd:22), deny capability sys_admin, with "libudev seems to work fine without the BPF filter in place, so we can silence the denial" (lsusb:43-45).capability, grants every capability (plasmashell:8).CAP_SYS_ADMIN 10, CAP_SYS_MODULE 10, CAP_DAC_OVERRIDE 9, CAP_SETUID 9, CAP_NET_RAW 8). The number informs the author; the tool refuses nothing by severity.info="optional: no audit" (capability.c:139-144, capability.c:156-163).profile_capable: capability.c:121-166; the quiet test in audit_caps: capability.c:87-92; the hook apparmor_capable: lsm.c:199-211.profile_capable a profile compiled with abi <abi/5.0> takes (policy DFA or the older bit sets) was not determined; both refuse a capability that has no rule.capability, rule is that of __ALL__: capability.py:127-129.dnsmasq: /etc/dnsmasq.d/ r, /etc/dnsmasq.d/* r, /var/lib/misc/dnsmasq.leases rw, @{run}/*dnsmasq*.pid w, and one read-only **: @{TFTP_DIR}/** r,. Site additions go in local/usr.sbin.dnsmasq.
* matches within one path component, ** crosses /. A rule for a directory itself ends in /: /etc/dnsmasq.d/ r, lists the directory, /etc/dnsmasq.d/* r, reads its direct entries (usr.sbin.dnsmasq:42-43)./var/lib/misc/dnsmasq.leases rw, # Required only for DHCP server usage (usr.sbin.dnsmasq:66), @{run}/*dnsmasq*.pid w, (usr.sbin.dnsmasq:61), the profile line with /usr/{bin,sbin}/dnsmasq (usr.sbin.dnsmasq:17), and @{TFTP_DIR}/** r, under "for the read-only TFTP server" (usr.sbin.dnsmasq:74-76).@{TFTP_DIR}=/var/tftp /srv/tftp /srv/tftpboot is declared in the profile file itself (usr.sbin.dnsmasq:14)./var/lib/misc/dnsmasq.*.leases rw,.include if exists <local/usr.sbin.dnsmasq> (usr.sbin.dnsmasq:142), so the reviewed file stays unchanged./dev/nvidia-modeset w, /dev/nvidia-uvm w, /dev/nvidia-uvm-tools w, (nvidia_modprobe:27-29); @{run}/mount/utab.lock rwk, (fusermount3:55); /var/log/wtmp.@{d} r, for rotated logs (who:11); /usr/lib{,64}/libvirt/libvirt_leaseshelper (usr.sbin.dnsmasq:87).(N)ew key lets you type the exact pattern; the (G)lob key works against this style (aa.py:1248-1287)./var/lib/ntp/@{PROC}/@{pid}/net/if_inet6 r, and /var/lib/ntp@{run}/ntp/ntpd.pid w, (usr.sbin.ntpd:57, usr.sbin.ntpd:72-73), because the name the kernel reports depends on where the task's root is.Cx -> child moves a helper into a child profile: capability sys_module, exists only in nvidia_modprobe's kmod child. ix keeps the parent's profile, capabilities included: /{,usr/}bin/{ba,da,}sh ix, in dnsmasq.
<path> Px, (the target's own profile), <path> Px -> name, (a named profile), <path> Cx -> child, (a child profile in the same file), <path> ix, (stay in the current profile). An upper-case P or C asks for secure execution, which scrubs the environment; see safe and unsafe exec.capability lines, summarised on the slide (nvidia_modprobe:12-15); /usr/bin/kmod Cx -> kmod, (nvidia_modprobe:23); the child with capability sys_module, (nvidia_modprobe:39-62). A child profile is named parent//child in the kernel, hence nvidia_modprobe//kmod./usr/libexec/libvirt_leaseshelper Cx -> libvirt_leaseshelper, (usr.sbin.dnsmasq:87-88); the child has one abstraction, no capability and nine file rules (usr.sbin.dnsmasq:121-139)./{,usr/}bin/{ba,da,}sh ix, # Required to execute --dhcp-script argument (usr.sbin.dnsmasq:68). With ix the shell and the script keep the profile dnsmasq, including usr.sbin.dnsmasq:22-28. This follows from the rule; it was not run.Px, each with its own profile file, and two with rix (usr.sbin.dovecot:50-70).helper, sed to sed, and runs cat, expr, mktemp, rm and the shell with ix (zgrep:23-37, zgrep:46-73).Px across files: /usr/lib*/samba/{,samba/}samba-dcerpcd Px -> samba-dcerpcd, (usr.sbin.smbd:43).change_profile -> php-fpm//*, and write access to @{PROC}/@{pid}/attr/{apparmor/,}current (php-fpm:29, php-fpm:50-57); apache2 uses hats (usr.sbin.apache2:90-103).ux-family rule in profiles/apparmor.d/ is /** pux, in plasmashell (plasmashell:24), one of the allow-everything profiles.audit deny /var/** w, after include <abstractions/wutmp> (who) removes a grant. signal (receive) peer=libvirtd, (dnsmasq) names the sender. audit on an allow rule (wpa_supplicant) logs each use.
[audit] [deny] [owner] <rule>.include <abstractions/wutmp> (who:9), then "Deny the writes allowed by abstractions/wutmp" with audit deny /var/** w, and audit deny @{run}/utmp w, (who:39-41).signal (receive) peer=libvirtd, and ptrace (readby) peer=libvirtd,, each also written with the path-named peer /usr/{bin,sbin}/libvirtd (usr.sbin.dnsmasq:32-35). The peer is a profile name. The rule covers any signal; the slide shows one.audit dbus (send) rule spans five lines in the file and is shortened with ... on the slide (wpa_supplicant:84-89). It is a D-Bus rule: the bus daemon enforces and logs it, not the kernel. See D-Bus mediation.audit appears in four files of profiles/apparmor.d/ (tnftp, unprivileged_userns, wpa_supplicant, who); three of them use it only as audit deny.deny writes no record; audit deny does. See The audit qualifier.peer=<profile> and peer=(label=<profile>) are accepted on signal, ptrace, unix and dbus rules. More shipped examples: unix (receive, send) type=stream peer=(label=dovecot-anvil), (usr.sbin.dovecot:39-40); signal (send) peer=@{profile_name}//*, (usr.sbin.apache2:76); a unix rule tied to an address, addr="@/tmp/.X11-unix/X[0-9]*" (Xorg:65).audit deny capability, and audit deny change_profile, (unprivileged_userns:8-9); deny network, in tnftp's command child (tnftp:77).deny /usr/bin/apt-cache x, and deny /tmp/gtalkplugin.log w, (lsb_release:43, lsb_release:52); deny / rw, (php-fpm:47).owner inside privileged profiles: unix-chkpwd:37-39; for rootless podman, next to the unqualified root-owned form, usr.sbin.dnsmasq:111-116.local/ included.audit deny file rule in a complain-mode profile appears to be allowed, going by the kernel code (verdict unclear, not run). who relies on audit deny to cancel the writes from wutmp. Test deny rules in enforce mode./etc/passwd r, and deny /etc/passwd r, (zgrep:22, zgrep:42). The deny decides and the allow is dead. Read from the file, not run.Complain-mode records and aa-audit show what reached AppArmor during your runs. Shipped comments (who, iotop-c, lsusb) cite system calls, kernel code and library source: knowledge from tracing and reading code, which the log does not contain. That an O_PATH open is not mediated is read from the kernel code.
apparmor="ALLOWED" operation="open" parent=... profile=... name=... pid=... comm=... requested_mask="r" denied_mask="r" fsuid=... ouid=...), with illustrative values. It is the record that /dev/pts/ r, in the who profile answers (who:27).operation=, profile=, name=, requested_mask=, denied_mask=, fsuid=, ouid=; capability records carry capability= and capname=. Reading them is in Reading a denial./dev/ r, rule.O_PATH open returns before the file-open security hook is called (open.c:951-956, open.c:977). Read from the code, not run. See What is not mediated.aa-audit adds the audit flag to the profile and reloads it ("Setting %s to audit mode.", tools.py:228-243). aa-audit --remove takes it away again ("Removing audit mode from %s."). In the kernel every allowed permission of such a profile is logged as an AUDIT record, and denials that deny rules keep quiet are logged too. aa-logprof drops AUDIT records, so they are read by a person. No shipped profile carries the flag.aa-unconfined "Lists unconfined processes having tcp or udp ports" (aa-unconfined:31): a way to find network-facing programs that have no profile yet.audit rule is set); denials quieted by deny rules; a capability check repeated for the same credentials within one second; optional capability probes in enforce mode; records lost to rate limiting (aa-genprof sets /proc/sys/kernel/printk_ratelimit to 0 and warns "Can't set printk_ratelimit, some events might be lost" when it cannot, aa-genprof:133-143; aa-logprof alone does not); code paths the runs did not reach; operations that are not mediated; and the reason for any of it.AUDIT_ALL: policy_unpack.c:1241. With it, every permission is audited and nothing is quiet: lib.c:374-380; for files file.c:122-123 and file.c:142-149; for capabilities capability.c:80-92.AUDIT_CACHE_TIMEOUT_NS: capability.c:70, capability.c:94-106.do_dentry_open returns for O_PATH at open.c:951-956; security_file_open is called at open.c:977.AUDIT, STATUS and ERROR events: logparser.py:303-304.Shipped examples of privilege next to breadth: tar (dac_override, file rwl /**,), sbin.syslogd (dac_override, /var/log/** rw,), usr.sbin.apache2 (/** mrwlkix,), usr.sbin.dnsmasq (sh ix with seven capabilities), extras usr.sbin.sshd (Uxr for shells). What each allows is derived from the rules, not demonstrated.
Each consequence below is derived from the rule text. None was demonstrated on a running system.
capability dac_override, and capability dac_read_search, under the comment "used to compress user files as root", then file rwl /**, (tar:18-25). The file rule covers every path, link permission included, and the capability removes the permission-bit check. The same profile runs any program in the bin directories with ix (tar:27-30), which keeps those capabilities. What remains as a control: the profile's lack of other capabilities and of network rules.capability dac_override, (sbin.syslogd:22) next to /var/log/** rw, (sbin.syslogd:42): any file under /var/log, whoever owns it.dac_override among them, with / rw, and /** mrwlkix, (usr.sbin.apache2:78-86); the hats DEFAULT_URI and HANDLING_UNTRUSTED_INPUT have the same file rule (usr.sbin.apache2:95, usr.sbin.apache2:102). The profile gives the process a name and a capability list; file access is left to the permission bits./{,usr/}bin/{ba,da,}sh ix, # Required to execute --dhcp-script argument (usr.sbin.dnsmasq:68) next to seven capabilities (usr.sbin.dnsmasq:22-28), net_admin, dac_override and setuid among them. A script run this way has the whole profile.Uxr rules for shells and for nologin and false (extras/usr.sbin.sshd:92-105), /usr/lib/openssh/sftp-server PUx, (extras/usr.sbin.sshd:160), fifteen capabilities (extras/usr.sbin.sshd:29-43) and /** r, with owner /** rwl, (extras/usr.sbin.sshd:153-155). For a login service the session is meant to leave the daemon's profile. The extras directory holds profiles that are not enabled by default.abstractions/nameservice, which adds inet stream and dgram sockets, network netlink raw, and capability net_bind_service, (nameservice:92-99, nis:16).l permission in world-writable directories, in a root daemon: /tmp/ntp* rwl, and /var/tmp/ntp* rwl, (usr.sbin.ntpd:43, usr.sbin.ntpd:68). See Hard links and name-based rules.profiles/apparmor.d/, 76 are flags=(unconfined) and 14 are allow all,.aa-logprof -a accepts every logged event and is a source of weak generated profiles.aa-logprof -a the secure-execution question is answered "no", so an exec to a profiled target is written as lower-case px, although the interactive default is Px (ui.py:159-160, ui.py:518-526, aa.py:884-887). Read from the code, not run.apparmor_parser -p FILE (--preprocess) prints the profile with its includes expanded, which is what the grep on the slide needs. The pattern is an illustration of where to look; no output of it was recorded for the map.aa-status lists the loaded profiles and their modes; see aa-status and aa-enabled.aa-genprof --no-abstraction, (N)ew for exact paths, px/cx with secure execution, hand-written comments, deny and peer= rules, aa-enforce, then aa-audit for a watch period. Site changes go into local/<profile>.
aa-genprof [-d DIR] [-f LOGFILE] [-j] [--no-abstraction] [-o DIR] program. --no-abstraction: "Do not use any abstractions in profiles" (aa-genprof:68-73). The new profile starts in complain mode; Finish switches it to enforce (aa-genprof:187-190).aa-logprof [-d DIR] [-f LOGFILE] [-m MARK] [-j] [-a] [--no-abstraction] [-o DIR]. -a, --allow-all: "Accept silently all rules" (aa-logprof:27-33).aa-enforce, aa-complain and aa-audit take program names, or --profile, --profile-file, --executable-file, plus -d DIR and --no-reload. aa-enforce and aa-complain skip a flags=(unconfined) profile without --force ("Profile %s is in unconfined mode. Use --force to switch it to enforce mode."). aa-audit -r (--remove) removes the audit flag again (tools.py:196-243). aa-enforce clears the complain flag and leaves an audit flag in place (aa.py:276-281).(N)ew asks for the path and warns when it does not match the log entry: "The specified path does not match this log entry" (aa.py:1260-1287).px or cx the tool asks "Should AppArmor enable secure-execution mode when switching profiles?" with yes as the default; yes gives Px or Cx. After ux it warns "Launching processes in an unconfined state is a very dangerous operation and can cause serious security holes." (aa.py:863-900).audit deny rules. Those are edits by hand.attach_disconnected (ntpd, dnsmasq, dovecot) or attach_disconnected.path= (smbd, unix-chkpwd), and the second form needs rules for the prefixed paths (unix-chkpwd:41-46). See The other profile flags.complain on cx child profiles created during the session. Check the flags of child profiles in the written file.audit deny file rule in a complain-mode profile appears to be allowed, going by the kernel code (verdict unclear, not run).aa-logprof -a an exec to a profiled target is written as lower-case px although the interactive default is Px (ui.py:159-160, ui.py:518-526). Read from the code, not run.Review a precise profile for symlinks (prac-symlinks), hard links (prac-hardlinks) and /proc and /sys paths (prac-sys-proc). Then: prac-abstractions, syn-capability, syn-child-profiles, syn-audit, sec-unmediated, adm-denials.
/bin is a symlink to usr/bin: /{usr/,}bin/{,iputils-}ping (bin.ping:15), /{,usr/}{,s}bin/unix_chkpwd (unix-chkpwd:14).l permission appears on pid, lock and state files, @{run}/klogd.pid krwl, and /var/log/boot.msg rwl, (sbin.klogd:30-31), /etc/shadow rwl, (extras/usr.bin.passwd:31), /var/lib/ntp/drift rwl, (usr.sbin.ntpd:48); and in world-writable directories, /tmp/ntp* rwl, and /var/tmp/ntp* rwl, (usr.sbin.ntpd:43, usr.sbin.ntpd:68), owner /tmp/** rwkl, (user-tmp:21).@{sys}/bus/pci/devices/ r, and then reads through the resolved device path, @{sys}/devices/@{pci_bus}/**/config r, (nvidia_modprobe:30-31). Three spellings of a /proc path exist in the tree: @{PROC}/kmsg (sbin.klogd:25), the literal /proc/kmsg (sbin.syslogd:34) and the literal /proc/*/cmdline (iotop-c:24)./var/lib/ntp (usr.sbin.ntpd:57, usr.sbin.ntpd:72-73).Basis of the statements on this page: profile text is quoted from the AppArmor tree at 836052d21 (6.0.0~alpha2); "code" means the source of mainline Linux 7.4 (97d73c825) or of the AppArmor utilities was read, not run; "derived" means the result was reasoned from that code or from rule text. Nothing here was observed on a running kernel.
Counts per file in profiles/apparmor.d/: rule lines, include <abstractions/...> lines, capability lines, lines containing **, owner lines.
| File | Lines | Abstractions | Capabilities | ** | owner | Flags |
|---|---|---|---|---|---|---|
| bin.ping | 15 | 3 | 2 | 0 | 0 | none |
| sbin.klogd | 18 | 1 | 2 | 0 | 0 | none |
| unix-chkpwd | 22 | 2 | 2 | 0 | 2 | attach_disconnected.path=/att/unix-chkpwd/ |
| usr.sbin.ntpd | 58 | 4 | 9 | 0 | 0 | attach_disconnected |
| usr.sbin.dnsmasq | 88 | 4 | 7 | 1 | 5 | attach_disconnected |
| usr.sbin.dovecot | 66 | 7 | 9 | 4 | 1 | attach_disconnected |
| usr.sbin.smbd | 65 | 8 | 12 | 10 | 0 | attach_disconnected.path=/att/smbd/ |
Privileged and broad: capabilities next to a whole-tree rule.
| Profile | Rules | Where |
|---|---|---|
| tar | capability dac_override, and file rwl /**, | tar:18-25 |
| sbin.syslogd | capability dac_override, and /var/log/** rw, | sbin.syslogd:22, sbin.syslogd:42 |
| usr.sbin.apache2 and its two hats | six capabilities and /** mrwlkix, | usr.sbin.apache2:78-86 |
zgrep, child helper | capability dac_override, capability dac_read_search, and /{,**} r, | zgrep:50-51, zgrep:62 |
| extras usr.sbin.sshd | fifteen capabilities, /** r,, owner /** rwl,, Uxr for shells | extras/usr.sbin.sshd:29-43, extras/usr.sbin.sshd:92-105, extras/usr.sbin.sshd:153-155 |
Of the 198 profile files directly in profiles/apparmor.d/, 76 are flags=(unconfined) and 14 are allow all,.
| Technique | Shipped example | Where |
|---|---|---|
| Grant with a reason | capability net_admin, # for DHCP server | usr.sbin.dnsmasq:22-28 |
| Decline | # capability dac_override, kept commented out | fusermount3:11-15 |
| Choose the weaker | deny capability sys_admin, with capability sys_nice, | iotop-c:10-20 |
| Silence | deny capability net_admin, # noisy setsockopt() calls | usr.sbin.traceroute:20 |
| Isolate in a child | capability sys_module, only in nvidia_modprobe//kmod | nvidia_modprobe:44 |
Kernel results (code):
EPERM.deny fails with EPERM and no record, unless the profile has the audit flag.info="optional: no audit".capability, grants every capability.| Technique | Example from dnsmasq | Line |
|---|---|---|
| Directory, then its entries | /etc/dnsmasq.d/ r, and /etc/dnsmasq.d/* r, | usr.sbin.dnsmasq:42-43 |
| A single state file | /var/lib/misc/dnsmasq.leases rw, | usr.sbin.dnsmasq:66 |
| One-star pattern in one directory | @{run}/*dnsmasq*.pid w, | usr.sbin.dnsmasq:61 |
| Alternation for two layouts | /usr/{bin,sbin}/dnsmasq | usr.sbin.dnsmasq:17 |
Read-only ** | @{TFTP_DIR}/** r, | usr.sbin.dnsmasq:74-76 |
| Variable declared in the profile | @{TFTP_DIR}=/var/tftp /srv/tftp /srv/tftpboot | usr.sbin.dnsmasq:14 |
| Site additions | include if exists <local/usr.sbin.dnsmasq> | usr.sbin.dnsmasq:142 |
/var/lib/ntp/@{PROC}/@{pid}/net/if_inet6 r, and /var/lib/ntp@{run}/ntp/ntpd.pid w, (usr.sbin.ntpd:57, usr.sbin.ntpd:72-73).| Mode | Meaning | Shipped example | What the started program has |
|---|---|---|---|
Px | the target's own profile, secure execution | dovecot's 19 helpers (usr.sbin.dovecot:50-70) | only its own profile |
Px -> name | a named profile, secure execution | samba-dcerpcd Px -> samba-dcerpcd, (usr.sbin.smbd:43) | the named profile |
Cx -> child | a child profile in the same file | /usr/bin/kmod Cx -> kmod, (nvidia_modprobe:23) | the child's rules only |
ix | stay in the current profile | /{,usr/}bin/{ba,da,}sh ix, (usr.sbin.dnsmasq:68) | everything the parent has, capabilities included |
Ux, PUx | leave confinement, secure execution | shells in the extras sshd profile (extras/usr.sbin.sshd:92-105) | no profile |
| Use | Example | Where |
|---|---|---|
audit deny to subtract from an include | audit deny /var/** w, after include <abstractions/wutmp> | who:39-41 |
deny for what must not happen | audit deny capability, and audit deny change_profile, | unprivileged_userns:8-9 |
deny to silence a probe | deny /usr/bin/apt-cache x, | lsb_release:43 |
audit on an allow rule | audit dbus (send) bus=system path=/fi/w1/wpa_supplicant1/** ... | wpa_supplicant:84-89 |
owner | owner /dev/pts/[0-9]* rw, | unix-chkpwd:37-39 |
| Peer by profile name | signal (receive) peer=libvirtd, | usr.sbin.dnsmasq:32-35 |
| Peer by label | unix (receive, send) type=stream peer=(label=dovecot-anvil), | usr.sbin.dovecot:39-40 |
deny is silent; audit deny logs the attempt.local/ included.Shows:
audit on a rule, or after aa-audit on the profile, each use of an allowed permission as an AUDIT record (code).Does not show:
deny rules;printk_ratelimit to 0, aa-logprof alone does not;O_PATH open (code);| Step | Command or key | Tool message or note |
|---|---|---|
| 1 | aa-genprof --no-abstraction /usr/sbin/dnsmasq | "Do not use any abstractions in profiles"; the profile starts in complain mode |
| 2 | exercise the program, then (S)can | include reload, shutdown and error paths |
| 3 | (N)ew for each path; profile or child for each exec | "Should AppArmor enable secure-execution mode when switching profiles?": yes |
| 4 | edit by hand | reasons as comments, deny, audit deny, peer= |
| 5 | aa-enforce dnsmasq, then aa-audit dnsmasq | "Setting %s to enforce mode.", "Setting %s to audit mode."; aa-audit --remove ends the watch: "Removing audit mode from %s." |
| 6 | local/usr.sbin.dnsmasq | read through include if exists <local/usr.sbin.dnsmasq> |
aa-logprof -a ("Accept silently all rules") is the opposite of this procedure.
| Check | Shipped line | Deck |
|---|---|---|
| Symlinks: does the rule name the resolved path? | /{usr/,}bin/{,iputils-}ping (bin.ping:15) | Symlinks: rules see through them |
Hard links: l where others can write | /tmp/ntp* rwl, (usr.sbin.ntpd:43) | Hard links and name-based rules |
| /proc and /sys: self, pids, device paths | @{sys}/devices/@{pci_bus}/**/config r, (nvidia_modprobe:30-31) | Writing rules for /sys and /proc |
| Chroots: paths as seen from the task's root | /var/lib/ntp@{run}/ntp/ntpd.pid w, (usr.sbin.ntpd:57) | Symlinks: rules see through them |
| Write globs next to DAC-bypass capabilities | /var/log/** rw, with capability dac_override, (sbin.syslogd:42) | The limits of name-based mediation |
aa-logprof -a and px: in allow-all mode the secure-execution question is answered "no", so an exec to a profiled target is written as lower-case px although the interactive default is Px (ui.py:159-160, ui.py:518-526, aa.py:884-887). Read from the code, not run./etc/passwd r, and deny /etc/passwd r, (zgrep:22, zgrep:42). The deny decides; the allow is dead. Read from the file, not run.audit deny file rule in a complain-mode profile appears to be allowed by the kernel (verdict unclear). who relies on audit deny to cancel writes from abstractions/wutmp. Test deny rules in enforce mode. Read from the code, not run.profile_capable capability.c:121-166; quiet handling and the one-second cache in audit_caps capability.c:70-106; hook apparmor_capable lsm.c:199-211.ioprio_set asks for CAP_SYS_ADMIN before CAP_SYS_NICE: ioprio.c:47.AUDIT_ALL policy_unpack.c:1241; applied to permissions lib.c:374-380; file records file.c:122-123, file.c:142-149.O_PATH: do_dentry_open returns at open.c:951-956, before security_file_open at open.c:977.(G)lob and (N)ew aa.py:1248-1287; allow-all answers ui.py:159-160, ui.py:518-526; dropped AUDIT events logparser.py:303-304; --no-abstraction aa-genprof:72.AppArmor matches the resolved path. Where /etc/resolv.conf is a symlink, opening it is checked as its target, and name= in the denial shows the target.
name= in the denial. It is the name AppArmor rebuilt for the object that was opened, and it can differ in every component from what the program passed.requested_mask="r" is what the program asked for and denied_mask="r" the part that was refused. profile= is the profile that refused it.operation="open" record in the libapparmor test suite (syslog_datetime_01.in), with the profile, name and masks of this example. The values are illustrative./etc/resolv.conf is a symlink depends on the system; neither source tree proves it. The tree's evidence is the comment in the shipped abstraction: "On systems where /etc/resolv.conf is managed programmatically, it is a symlink to @{run}/(whatever program is managing it)/resolv.conf." (nameservice-strict:34-35), followed by rules for the targets, next to @{etc_ro}/resolv.conf r, for the case of a regular file (nameservice-strict:21)./run/ and not /var/run/, because /var/run is resolved as well where it is a symlink.d_namespace_path (path.c:88-128); the open hook passes &file->f_path (lsm.c:498-500).In the kernel symlinks are followed in the VFS before AppArmor's file hook. Only the final object's path is matched; directories and links on the way are not checked by AppArmor.
All of this is read from the kernel source. That /bin is a symlink to usr/bin and /usr/bin/sh a symlink to dash describes a common layout, not a fact from either tree.
O_NOFOLLOW, lstat and AT_SYMLINK_NOFOLLOW stop at the link itself./ restarts the walk at the task's root.nosymfollow, and openat2 with RESOLVE_NO_SYMLINKS, fail with ELOOP in the VFS, before any AppArmor check.readlink, and none for the permission check on each directory passed through. Search permission on directories (x in the file mode) is left to the ordinary Unix permission checks.pick_link reads the link text and continues the walk (namei.c:2013-2091); it calls security_inode_follow_link at namei.c:2059-2062.step_into_slowpath decides whether an entry is a symlink that must be followed (namei.c:2104-2116).inode_follow_link, inode_readlink or inode_permission entry (lsm.c:1796-1816).apparmor_file_open checks &file->f_path, the object the walk ended at (lsm.c:498-500).ELOOP for nosymfollow and RESOLVE_NO_SYMLINKS: namei.c:2046-2048.The matched name is rebuilt from the object: absolute, without ., .. or symlinks, from the mount namespace root (so a chroot's files keep their outside path), with a trailing / for directories. No path to the root means info="Failed name lookup - disconnected path".
Read from the kernel source; not observed on a running kernel.
., no .. and no symlink./var/lib/ntp, for example /var/lib/ntp/@{PROC}/@{pid}/net/if_inet6 r, (usr.sbin.ntpd:57, usr.sbin.ntpd:72-73). The profile flag chroot_relative makes the name relative to the task's root instead./, so a rule for the directory itself is written /etc/demo/ r,.info= texts: Failed name lookup - deleted entry, Failed name lookup - disconnected path, Failed name lookup - name too long, Failed name lookup. The record shows whatever partial name was built.flags=(attach_disconnected) puts the leading / back on a disconnected name. flags=(attach_disconnected.path=/att/unix-chkpwd/) puts a prefix in front, and the shipped profile then has rules with that prefix, such as /att/unix-chkpwd/run/systemd/journal/dev-log w, (unix-chkpwd:14, unix-chkpwd:41-46).aa_path_name (path.c:202-222) calls d_namespace_path (path.c:88-128): d_absolute_path at path.c:124-127, __d_path for chroot_relative at path.c:119-123, the trailing slash at path.c:170-177, the disconnected case at path.c:48-72 and path.c:151-152.info strings: path.c:209-216.aa_path_perm runs the check for every confined profile of the label (file.c:287-309); a failed lookup is audited and denied at file.c:169-177.struct path each hook passes: truncate, chmod, chown, getattr (lsm.c:246-259, lsm.c:350-353, lsm.c:450-463); create, mkdir, mknod, symlink, unlink, rmdir (lsm.c:271-278); rename (lsm.c:403-406); open (lsm.c:498-500); exec (domain.c:684-699).SB_NOUSER file systems are skipped: lib.h:146-149.Name the target, and both spellings where layouts differ: /{usr/,}bin/, @{run}=/run/ /var/run/, @{run}/systemd/resolve/stub-resolv.conf r,. Find it with readlink -f PATH or the denial's name=.
profile ping /{usr/,}bin/{,iputils-}ping { (bin.ping:15). A second example of both spellings is /{usr/,}bin/ls mix, (bash:45). - @{run}=/run/ /var/run/ (run:1). - @{etc_ro}/resolv.conf r, (nameservice-strict:21) and @{run}/systemd/resolve/stub-resolv.conf r, with its neighbours (nameservice-strict:36-38). - @{etc_ro}/localtime r, (base:34-35) and /usr/share/zoneinfo{,-icu}/** r, (base:41-42).readlink -f PATH and realpath PATH resolve every component and print the final path. namei -l PATH shows each step of the walk. The output on the slide is an example for a system where systemd-resolved manages the file; it was not taken from a machine.alias rules rewrite rule paths when the policy is compiled. They are a separate mechanism, shown commented out in alias:13-19.x rules and profile attachment use the resolved path of the executable. Where /usr/bin/editor is a chain of symlinks to /usr/bin/vim.basic, both the rule and the profile must name /usr/bin/vim.basic.
Read from the kernel source; not observed on a running kernel. The chain /usr/bin/editor to /etc/alternatives/editor to /usr/bin/vim.basic describes a system that uses the alternatives mechanism; the profile names editor and vim are invented for the slide.
x rules of the profile confining the caller, and it is the name the attachment search uses when the kernel has to pick a profile.aa-status, ps -Z, or cat /proc/PID/attr/current. To see where a path really leads: readlink -f /usr/bin/editor.profile notepadqq /{{usr/bin,etc/alternatives}/notepadqq,usr/lib/notepadqq/notepadqq.sh} flags=(unconfined) { (notepadqq:7). The etc/alternatives alternative can match only on a system where that entry is a real file and not a symlink.aa_path_name(&bprm->file->f_path, ...), the fallback name = bprm->filename on error, and find_attach with the same name for an unconfined task: domain.c:684-699.With /srv/www/** r,, opening a symlink /srv/www/x that points to /etc/shadow is matched as /etc/shadow and denied. Symlinks cannot extend what a profile allows. This is read from the kernel code; it was not run on a kernel.
This scene is derived from the kernel code. It was not run on a kernel, and the record is built for the map on the layout of an operation="open" record in the libapparmor test suite (syslog_datetime_01.in); its values are illustrative.
/srv/www/x does not appear in it.apparmor_file_open passes &file->f_path (lsm.c:498-500); d_absolute_path builds the name from it (path.c:124-127).symlink() needs w on the new name (operation="symlink", requested_mask="c"); the link text is not examined. unlink needs w on the link's path; rename needs rw on the old name and w on the new. readlink is not mediated by AppArmor in the kernel.
Read from the kernel source, except the record and the regression test named below.
| Operation | What AppArmor is asked | On which path |
|---|---|---|
symlink(text, new) | create; w grants it | the new name; the text is not examined |
readlink(path) | nothing | not mediated |
lstat(path) | getattr | the link's own path |
unlink(path) | delete; w grants it | the link's own path, with the link's own owner |
rename(old, new) | read, write and delete on the old name (rw grants them); write and create on the new name (w) | the link's own names |
lchown, fchownat and fchmodat with AT_SYMLINK_NOFOLLOW | chown or chmod | the link's own path |
link(old, new) where old is a symlink, without AT_SYMLINK_FOLLOW | a hard link check | the symlink itself is linked |
open with O_PATH and O_NOFOLLOW | nothing | not checked |
open with O_NOFOLLOW, without O_PATH | nothing: the VFS fails with ELOOP |
aa-logprof derives from it is owner /home/b.c w, (symlink.profile).c (create) and d (delete) are letters of the log only. No profile letter exists for them; w is what a rule grants.ouid= is the caller's own fsuid, so an owner rule always matches a creation.w on the new name and fails with rlixm (symlink.sh:22-39).lstat: by reading, the getattr permission is granted on every path for policy in the older format, so lstat is not denied. For policy that carries a permission table this was not fully determined.apparmor_path_symlink requests AA_MAY_CREATE and does not use old_name (lsm.c:360-365); common_perm_create takes the caller's fsuid as owner (lsm.c:319). The VFS calls the hook at namei.c:5835.w maps to AA_MAY_CREATE among others (policy_compat.c:84-86); the getattr mapping is at policy_compat.c:103.readlink: the lookup does not follow the last component and security_inode_readlink is called, for which AppArmor has no hook (stat.c:568-584).AT_SYMLINK_NOFOLLOW in chmod and chown: open.c:726, open.c:846. O_PATH returns before the open hook: open.c:951-956. ELOOP for opening a symlink itself: namei.c:4248-4249.symlink() is checked only as creation of the new name. A confined program can plant links to paths it cannot access; programs that follow them are judged by their own confinement. fs.protected_symlinks covers sticky world-writable directories and the final component only. All of this is what the kernel code permits; none of it was run.
Everything here is derived from the kernel code: it states what the code permits. No exploit was run. /var/lib/demo/report.txt and the backup job are illustrations.
symlink() is checked as creation of the new name; the link text is not passed to the policy check.fs.protected_symlinks: with the value 1, following a symlink is permitted when the follower's fsuid owns the link, or the directory is not both sticky and world-writable, or the directory's owner owns the link. Otherwise the walk fails with EACCES and the kernel logs an AUDIT_ANOM_LINK record with follow_link. That is not an AppArmor record, and no profile rule changes it.CAP_DAC_OVERRIDE does not bypass it.owner /tmp/** rwkl, from abstractions/user-tmp (user-tmp:21).readlink is not mediated. Link texts under a path are readable subject to the ordinary Unix permission checks only.O_PATH opens return before the LSM open hook, and so does fstatat on such a descriptor. The shipped who profile records this in a comment: "O_PATH fds bypass mediation" (who:19-24).apparmor_path_symlink: lsm.c:360-365.may_follow_link: namei.c:1280-1307, with the comment on CAP_DAC_OVERRIDE at namei.c:1269-1271; called only with WALK_TRAILING at namei.c:2040-2044.do_dentry_open returns for O_PATH at open.c:951-956, before security_file_open at open.c:977. security_inode_readlink: stat.c:584./proc/self/status is matched as /proc/1234/status: write @{PROC}/@{pid}/status r,. /proc/self/exe and /proc/self/fd/N jump to the object and are matched under that object's own path.
Read from the kernel source; not observed on a running kernel. The pid 1234 is an example.
/proc/self is an ordinary symlink whose text is the caller's process (thread group) id. /proc/thread-self resolves to <tgid>/task/<tid>.@{PROC}/@{pid}/{maps,auxv,status} r, (base:116). @{PROC} is /proc/ (proc:12) and @{pid} a pattern for a number (kernelvars:16)./etc/mtab is a symlink to ../proc/self/mounts, opening it is matched as /proc/1234/mounts.exe, cwd, root and fd/N are not text links. The walk switches to the object itself, and the open is matched under that object's own path with the permissions the new open asks for.lstat of /proc/self/fd/3 is a getattr on /proc/1234/fd/3. readlink of it is not mediated by AppArmor; procfs applies its own ptrace-mode check before such a link is used.fd/N has been deleted or cannot be reached from the root, the rules for deleted and disconnected names apply (see the scene "The name comes from the file, not from you").proc_self_get_link returns the thread group id as text (self.c:11-28).proc_pid_get_link obtains a struct path and calls nd_jump_link (base.c:1800-1813), which replaces the walk's position (namei.c:1174-1195).Next: prac-hardlinks, prac-sys-proc, attachment, syn-flags-other, adm-denials, sec-path-limits, k-match.
name= in a denial shows it.w on the link's own path. l and link rules concern hard links.attach_disconnected. - Reading denials: the name= field and the rest of the record. - The limits of deciding by name, how the kernel matches a name. - File rules, access modes.Basis of the statements on this page: the kernel behaviour is read from the source of mainline Linux 7.4 (7.4-rc2, 97d73c825) and the shipped policy from the AppArmor tree at 836052d21 (6.0.0~alpha2). Nothing here was observed on a running kernel. "Derived" means reasoned from that code.
AppArmor does not see the string a program passes. Each file check receives the object the kernel resolved, and the name is rebuilt from it.
| Operation | Object whose path is used |
|---|---|
| open | the opened file, after every symlink was followed |
| exec | the opened binary; the same name is used to search for a profile to attach |
| create, mkdir, mknod, symlink, unlink, rmdir | the entry itself in its parent directory |
| truncate, chmod, chown, getattr | the looked-up object (the link itself only with a no-follow call) |
| rename | both names |
| link | both names: see prac-hardlinks |
Properties of the name:
., .. or symlink: the chain of real directory entries above the object./srv/chroot that opens /etc/passwd is matched as /srv/chroot/etc/passwd. The profile flag chroot_relative makes it relative to the task's root./.EACCES unless the profile has attach_disconnected (see syn-flags-other).name= in a denial is this rebuilt name. It is the string to put in a rule.| Operation | What AppArmor is asked | On which path |
|---|---|---|
symlink(text, new) | create; w grants it | the new name; the text is not examined |
readlink(path) | nothing | not mediated |
lstat(path) | getattr | the link's own path |
unlink(path) | delete; w grants it | the link's own path, with the link's own owner |
rename(old, new) | read, write and delete on the old name (rw grants them); write and create on the new name (w) | the link's own names |
lchown, fchownat and fchmodat with AT_SYMLINK_NOFOLLOW | chown or chmod | the link's own path |
link(old, new) where old is a symlink, without AT_SYMLINK_FOLLOW | a hard link check | the symlink itself is linked |
open with O_PATH and O_NOFOLLOW | nothing | not checked |
open with O_NOFOLLOW, without O_PATH | nothing: the VFS fails with ELOOP |
ouid= is the caller's fsuid, so an owner rule always matches.l and link rules are about hard links only.Which paths are symlinks on an installed system is not a fact from either source tree. The left column describes common layouts; the trees show only that shipped policy is written to cope with them. The two /proc rows at the end are the exception: those links are created by the kernel.
| Path, where it is a symlink | Shipped rule or variable | Source |
|---|---|---|
/bin to usr/bin | profile ping /{usr/,}bin/{,iputils-}ping {, /{usr/,}bin/ls mix, | bin.ping:15, bash:45 |
/sbin to usr/sbin | profile unix-chkpwd /{,usr/}{,s}bin/unix_chkpwd ... | unix-chkpwd:14 |
/lib, /lib64 to usr/lib... | /{usr/,}lib{,32,64}/** r, | base:74 |
/var/run to /run | @{run}=/run/ /var/run/ | run:1 |
/etc/resolv.conf to a file under /run | @{etc_ro}/resolv.conf r, and @{run}/systemd/resolve/stub-resolv.conf r, with its neighbours | nameservice-strict:21, nameservice-strict:34-38 |
/etc/localtime to a file under /usr/share/zoneinfo | @{etc_ro}/localtime r, and /usr/share/zoneinfo{,-icu}/** r, | base:34-35, base:41-42 |
/etc/alternatives/NAME to the real binary | name the real binary; notepadqq lists etc/alternatives/notepadqq, which can match only where that entry is a real file | notepadqq:7 |
/etc/mtab to ../proc/self/mounts | /etc/mtab r, and @{PROC}/@{pid}/mounts r, | bash:36-37 |
/proc/self to the pid | @{PROC}/@{pid}/{maps,auxv,status} r, | base:116 |
/proc/mounts to self/mounts (kernel) | @{PROC}/@{pid}/mounts r, | bash:37, root.c:383 |
/proc/net to self/net (kernel) | @{PROC}/@{pid}/net/if_inet6 r, | usr.sbin.ntpd:57, proc_net.c:423 |
More on the /proc rows: prac-sys-proc.
info= texts: Failed name lookup - deleted entry, Failed name lookup - disconnected path, Failed name lookup - name too long, Failed name lookup.operation="symlink" with requested_mask="c" and denied_mask="c". The fix is a w rule on the new name. A record from the libapparmor test suite:apparmor="DENIED" operation="symlink" profile="/home/test.sh" name="/home/b.c" pid=8016 comm="ln" requested_mask="c" denied_mask="c" fsuid=0 ouid=0
ELOOP comes from the VFS and not from AppArmor: opening a symlink itself with O_NOFOLLOW (without O_PATH), any symlink on a mount with nosymfollow, and openat2 with RESOLVE_NO_SYMLINKS.EACCES with an AUDIT_ANOM_LINK record (follow_link) comes from fs.protected_symlinks, below.EACCES and an AUDIT_ANOM_LINK record. No AppArmor record is written and no profile rule changes the result.CAP_DAC_OVERRIDE does not bypass it.readlink -f PATH or realpath PATH: every component resolved, the final path printed.namei -l PATH: each step of the walk, with owners and modes.name= in the denial: already the resolved name.aa-status, ps -Z (see attachment).Derived from the code; nothing here was run as an exploit.
w on a directory can create symlinks there to any path, including paths it is denied. That does not help the confined program, whose own opens are matched on the target. Another program that follows the link is judged by its own profile, or by none. owner /tmp/** rwkl, in abstractions/user-tmp is such a rule (user-tmp:21).readlink is not mediated: link texts are readable subject to the ordinary Unix permission checks only.O_PATH opens return before the LSM open hook, and fstatat on such a descriptor is not mediated either; the shipped who profile says so in a comment (who:19-24).fs.protected_symlinks covers sticky world-writable directories and the final component only, and is 0 unless something sets it.| What | Where |
|---|---|
aa_path_name, the info strings | path.c:202-222 |
d_namespace_path: d_absolute_path, chroot_relative, trailing slash, disconnected and deleted | path.c:88-128, path.c:48-72, path.c:151-177 |
aa_path_perm; a failed lookup audited and denied | file.c:287-309, file.c:169-177 |
AppArmor's hook list (no inode_follow_link, inode_readlink, inode_permission) | lsm.c:1796-1816 |
| create and symlink hooks | lsm.c:271-278, lsm.c:319, lsm.c:360-365 |
| unlink, rename, getattr, open hooks | lsm.c:327-330, lsm.c:403-442, lsm.c:460-463, lsm.c:498-500 |
| exec: name and attachment | domain.c:684-699 |
w to AA_MAY_CREATE; getattr on every state | policy_compat.c:84-86, policy_compat.c:103 |
pick_link, security_inode_follow_link, ELOOP | namei.c:2013-2091 |
may_follow_link, the sysctl | namei.c:1280-1307, namei.c:1210, namei.c:1217-1225 |
nd_jump_link | namei.c:1174-1195 |
security_path_symlink call | namei.c:5835 |
readlink | stat.c:568-584 |
O_PATH in do_dentry_open | open.c:951-956 |
/proc/self, magic links | self.c:11-28, base.c:1800-1813 |
| parser: path flags written to the kernel | parser_interface.c:536-537 |
lstat of a path matched by no rule can be denied under policy that carries a permission table. For policy in the older format the getattr permission is added to every state.fs.protected_symlinks: neither tree contains this.fs.protected_symlinks was applied to non-final components in earlier kernels; only mainline Linux 7.4 was read./proc/self/status r, and /sys/class/net/eth0/address r, are accepted by the parser and never match: AppArmor checks /proc/<pid>/status and a path under /sys/devices/. The kernel side is read from the kernel code.
The kernel behaviour here is read from the kernel code; nothing was observed on a running kernel. Both records are built for the map on the field layout of an operation="open" record in the libapparmor test suite (syslog_datetime_01.in); their values are illustrative.
/proc/self is a symlink whose text is the caller's process (thread-group) id in decimal. The kernel follows it before AppArmor is asked, so the name that is matched is /proc/1234/status./sys/class/net/eth0 is a symlink into /sys/devices/. The attribute file address lives in the device directory, and that is the name that is matched.pci0000:00/0000:00:1f.6, is an illustration of the shape the shipped rule @{sys}/devices/@{pci_bus}/*/net/*/address r, matches (opencl-pocl:22). It differs from machine to machine./proc/self/maps r,: exit status 0 and no warning. That run used -Q -K --skip-kernel-load, which compiles without loading; the apparmor_parser -r line on the slide stands for "compiles without a diagnostic".name= in a denial is the resolved name, and it is the string to start a rule from. requested_mask is what the program asked for, denied_mask the part that was refused./proc/self/status would in fact be granted by abstractions/base, which has @{PROC}/@{pid}/{maps,auxv,status} r, (base:116). The demo profile on the slide includes nothing.proc_self_get_link returns the thread-group id as text: self.c:11-28. The class symlink is created by the driver core at core.c:3521-3522./proc/self/X is matched as /proc/<pid>/X; /proc/mounts and /proc/net/X as /proc/<pid>/mounts and /proc/<pid>/net/X. Write @{PROC}/@{pid}/X. Both variables come from include <tunables/global>.
Read from the kernel code; not observed on a running kernel. The pid 1234 and the thread id 1240 are illustrations.
/proc/self is a symlink whose text is the caller's thread-group id; /proc/thread-self has the text <tgid>/task/<tid>. The number is the one in the pid namespace of that procfs mount./proc/mounts is a symlink to self/mounts and /proc/net a symlink to self/net. That is why abstractions grant @{PROC}/@{pid}/mounts r, (bash:37) and @{PROC}/@{pid}/net/route r, (nameservice:103) and not /proc/mounts or /proc/net/route.@{PROC}=/proc/ (proc:12) and @{pid} (kernelvars:16). A profile that uses them must include tunables/global (or tunables/proc and tunables/kernelvars) in its preamble.@{PROC} ends in a slash and rules write @{PROC}/name; the parser collapses the doubled slash. The tree's parser prints aare: /proc/meminfo for @{PROC}/meminfo.tunables/proc.d (proc:15).abstractions/base: @{PROC}/@{pid}/{maps,auxv,status} r, (base:116).exe, cwd, root and fd/N under a process directory are not text links: the kernel jumps to the target, and the open is matched under the target's own name. See symlinks, the scene "/proc/self and the links that jump".@{PROC}/@{tid}/attr/{apparmor/,}{current,exec} w, (change_profile:13) and owner @{PROC}/@{pid}/task/@{tid}/comm rw, (dig:46).proc_self_get_link: self.c:11-28; proc_thread_self_get_link: thread_self.c:11-25; the mounts link: root.c:383; the net link: proc_net.c:423.apparmor_file_open: lsm.c:465-500; d_namespace_path: path.c:89-128./sys/ gets /proc prepended, with a TODO about the hard-coded /proc (path.c:105-110). Which kernel code path reaches it was not determined.filter_slashes: parser_regex.c:61, called at parser_regex.c:659.@{pid}, @{pids} and @{tid} all expand to a number from 1 to 4999999; none means "this process". For maps, environ, fdinfo, mem and the magic links, procfs also makes a ptrace access check, which needs a ptrace (read) rule for other processes (read from the kernel code).
Read from the kernel code and from the shipped tunables; not run on a kernel. The pids and the programs behind them are illustrations.
@{pid}={[1-9],[1-9][0-9],...,[1-4][0-9][0-9][0-9][0-9][0-9][0-9]} (kernelvars:16); @{tid}=@{pid} and @{pids}=@{pid} (kernelvars:19, kernelvars:22). The pattern matches 1 to 4999999. The kernel's limit on pids is 4·1024·1024 on 64-bit, so it covers every valid pid.operation="ptrace" profile= pid= comm= requested_mask= denied_mask= peer=); its values are illustrative. requested_mask="read" follows from AppArmor treating a read-mode ptrace check as read.maps, smaps and the other memory-map files, mem (which asks for attach, not read), fdinfo, the ns/* links, environ, and the magic links exe, cwd, root, fd/N. status has none: it is readable subject to the file permissions unless procfs is mounted with hidepid.abstractions/base grants: ptrace (readby),, ptrace (tracedby), and ptrace (read) peer=@{profile_name}, (base:134-142). A profile with base can read these files of processes under the same profile.lsof pairs its /proc/@{pids}/... rules with ptrace read, and capability sys_ptrace, (lsof:25-28).[0-9]* in owner @{PROC}/@{pid}/task/[0-9]*/comm rw, is one digit followed by anything but a slash (sbin.dhclient:53); a plain * also matches names that are not numbers: @{PROC}/*/mounts r, (usr.lib.dovecot.lmtp:35), /proc/*/cmdline r, (iotop-c:24-25).apparmor_ptrace_access_check: lsm.c:128-141, with the read or trace mapping at lsm.c:139-141.__ptrace_may_access: the own-thread-group return at ptrace.c:325-327, the security hook at ptrace.c:371.proc_mem_open base.c:818-826, mem base.c:855, environ base.c:984, magic links base.c:1787, fdinfo fd.c:94, ns/* namespaces.c:63.PID_MAX_LIMIT: threads.h:34-35.-D rule-exprs on owner @{PROC}/@{pid}/fd/ r, prints the seven-way alternation.owner @{PROC}/@{pid}/... applies when the reader's fsuid equals the target process's effective uid. Files of a non-dumpable process are owned by root, so owner fails for a program that dropped privileges (read from the kernel code).
Read from the kernel code; not run on a kernel. The pids 1300, 987 and 2000, ann and the helper are illustrations.
owner compares the reader's fsuid with the owner of the file. For the files in /proc/<pid>/ procfs sets that owner to the target process's effective uid and gid.owner rule denies it access to its own /proc files.owner @{PROC}/@{pid}/mountinfo r, (golang:5, lsblk:56); owner @{PROC}/@{pid}/fd/ r, (gio-open:56); owner @{PROC}/@{pid}/{cgroup,cpuset,status} r, (opencl-pocl:41).profiles/apparmor.d: the fd/ directory rule appears 7 times without owner (six with @{pid}, one with @{pids}) and 7 times with it (one of them as owner @{att}@{PROC}/@{pid}/fd/ r,).owner on /proc/sys or /sys attributes is meaningful only for programs that run as root. A real record for a directory under /sys/class/ shows ouid=0 (syslog_datetime_01.in), and wpa_supplicant, a root daemon, has owner @{PROC}/sys/net/ipv{4,6}/conf/** rw, (wpa_supplicant:123).task_dump_owner: base.c:1872-1897, called at base.c:1953.apparmor_file_open fills the owner condition from the inode: lsm.c:491-496./sys/class/<class>/, /sys/bus/<bus>/devices/, /sys/block/ and /sys/dev/{char,block}/ hold symlinks into /sys/devices/. Rule for the listing: @{sys}/class/net/ r,. Rule for an attribute: @{sys}/devices/.../address r,.
The kernel side is read from the kernel code. The tree contents on the slide are illustrations. The record is real: it is in the libapparmor test suite (complex_profile_name.in), with the long profile name shortened with ....
subsystem link back and a device link to the parent. Buses do the same in /sys/bus/<bus>/devices/. /sys/block/ is a directory of links, and so are /sys/dev/char/<maj>:<min> and /sys/dev/block/<maj>:<min>.../ components. The kernel walks them, and the name AppArmor matches is the location under /sys/devices/./sys/devices/virtual/<class>/.@{sys}/class/net/ r, (opencl-pocl:18) and @{sys}/devices/@{pci_bus}/*/net/*/address r, (opencl-pocl:22).@{sys}/bus/usb/devices/ r, with @{sys}/devices/**/usb[0-9]**/uevent r, (lsusb:58, lsusb:64); @{sys}/block/ r,, @{sys}/class/block/ r,, @{sys}/dev/block/ r, with @{sys}/devices/@{pci_bus}/** r, (lsblk:22-26).wpa_supplicant profile records the pairing in a comment: @{sys}/devices/@{pci_bus}/**/ieee80211/phy[0-9]*/name r, followed by "Might also need @{sys}/class/ieee80211/ r," (wpa_supplicant:139-140).@{sys}/class/video4linux/** r, (video:8) covers only names that stay under /sys/class/. An attribute opened through a class entry is matched by the /sys/devices/... rule a few lines below it (video:12)./sys/devices/system/cpu/..., /sys/kernel/..., /sys/module/..., and /sys/fs/cgroup/..., which is a separate file system mounted there.stat on the class symlink itself can be denied.subsystem and device links: core.c:3510-3522; /sys/dev/{char,block} links: core.c:3580-3589; bus device links: bus.c:583; /sys/block: genhd.c:507, genhd.c:1011; virtual devices: core.c:3327-3332.apparmor_file_open: lsm.c:465./sys/devices/... paths depend on bus topology. Use @{pci_bus} (pci@{hex4}:@{hex2}) and @{int}, enumerate bus roots as lsblk does, or glob the location and keep the attribute literal as lsusb does: @{sys}/devices/**/usb[0-9]**/speed r,.
The four paths at the top are illustrations shaped after the rules in the lsblk profile and their comments. They are not taken from a log.
@{sys}/devices/@{pci_bus}/** r,, @{sys}/devices/virtual/** r,, @{sys}/devices/platform/** r, (lsblk:26-28); "Needed for Xen PVH guests" with @{sys}/devices/vbd-@{int}/block/** r, (lsblk:36-37); "Needed for disks over network e.g. Hyper-V VMs (including Azure), IBM Power, ..." with @{sys}/devices/**/host@{int}/** r, (lsblk:39-40); "Needed for channel subsystem for IBM Z" with @{sys}/devices/css@{int}/** r, (lsblk:42-43); "Needed for Azure ACPI/NVMe" with two rules that spell out ACPI device names (lsblk:45-47).lsusb lists one attribute per line under @{sys}/devices/**/usb[0-9]**/: uevent, busnum, descriptors, devnum, speed and more (lsusb:64-68).@{sys}/devices/@{pci_bus}/**/config r, matches /sys/devices/pci0000:00/0000:00:02.0/config and devices behind deeper bridges, but not platform devices, virtual devices or USB controllers on a platform bus.@{run} has two values, /run/ and /var/run/, so a rule written with it becomes two rules. udev data read next to sysfs is written @{run}/udev/data/*usb:* r, (lsusb:54).tunables/sys is an empty, deprecated file; @{sys} is defined in tunables/kernelvars. @{securityfs} and @{apparmorfs} are not part of tunables/global and must be included separately.@{u16} in tunables/system has an unbalanced bracket, [1-9][@{d}@{d} (system:38), and mis-matches three-digit values. The tree's parser, run with -D rule-exprs, prints the malformed alternation and exits 0. No shipped profile uses the variable. @{u8} is a four-value variable, which is probably intended.The variables:
| Variable | Definition | Source |
|---|---|---|
@{sys} | /sys/ | kernelvars:33 |
@{PROC} | /proc/ | proc:12 |
@{pid}, @{pids}, @{tid} | a number from 1 to 4999999 | kernelvars:16-22 |
@{d} | [0-9] | system:12 |
@{h} | [0-9a-fA-F] | system:24 |
@{int} | 1 to 10 digits | system:27 |
@{hex2}, @{hex4} | two and four hex digits | system:60-61 |
@{pci_bus} | pci@{hex4}:@{hex2} | system:99-100 |
@{run} | /run/ /var/run/ | run:1 |
Read access ranges from one file (ping) through one attribute at any location (lsusb) and a bus subtree (lsblk) to @{sys}/devices/** r, (Xorg) and @{PROC}/** r, (phpsysinfo). Write rules name one leaf.
All rules on the slide are quoted from shipped profiles. What each covers is read from the rules and from the kernel code.
@{PROC}/sys/net/ipv6/conf/all/disable_ipv6 r, (bin.ping:27).@{sys}/devices/**/usb[0-9]**/descriptors r, (lsusb:66), one of a list of attribute rules (lsusb:64-96).@{sys}/devices/@{pci_bus}/** r, (lsblk:26).@{sys}/**/ r,, @{sys}/devices/** r,, @{sys}/module/** r, (Xorg:97-99); @{PROC}/** r, and @{sys}/devices/** r, in the phpsysinfo hat (phpsysinfo:24, phpsysinfo:31). @{PROC}/** r, includes every process's environ, cmdline and maps as far as the file rule is concerned; the file permissions and the ptrace check remain.@{sys}/devices/@{pci_bus}/**/backlight/*/brightness rw, (Xorg:101); /proc/sys/kernel/task_delayacct rw, (iotop-c:28).@{PROC}/mtrr rw, (Xorg:95): again one named file.@{PROC}/asound/** rw, (audio:39).severity.db, the table the tools use to rank what a profile grants: /proc/** 6 for read and 9 for write, /proc/kallsyms 7 for read, /sys/** 4 and 8, /sys/firmware/** 10 for write (severity.db:71-77).file r @{sys}/devices/{,**}, and file rw @{sys}/devices/**/statistics/rx_*, (tshark:57-58); lsof names each per-process file (lsof:38-52).@{PROC}/kmsg, /proc/kmsg and /proc/*/cmdline.The guidance in four lines:
name= in the denial, or from readlink -f.@{pid} (own) or @{pids} (others), and add owner where the target runs as the same user./proc/sys and /sys should name one file./proc/self/... rules are accepted without a diagnostic and never match. @{pid} rules cover all processes; for maps, environ, mem and fd links the effective limits are the ptrace check and DAC (read from the kernel code). abstractions/base grants @{PROC}/@{pid}/{maps,auxv,status} r, without owner.
Everything here is read from the shipped policy and from the kernel code; nothing was run on a kernel. The two "dead" rules are examples written for the map: no shipped profile has a rule containing /proc/self (there is only a comment, systemd-detect-virt:22).
@{PROC}/@{pid}/{maps,auxv,status} r, (base:116); /proc/*/cmdline r, (iotop-c:24); @{PROC}/** r, (phpsysinfo:24); @{PROC}/asound/** rw, (audio:39)./proc/self, which can never match. Checked with the tree's parser on a scratch profile: exit status 0, no diagnostic. This is a missing diagnostic rather than wrong behaviour.@{u16} variable has an unbalanced bracket; see the scene "Device paths differ from machine to machine".self under /proc, and any rule that names an attribute through /sys/class/, /sys/bus/.../devices/, /sys/block/ or /sys/dev/. As an illustration of how to look for them: grep -n '/proc/self\|/sys/class/.*[^/] ' PROFILE.@{pid}. It is every process. Which per-process files have a ptrace check in procfs: maps, smaps, mem, environ, fdinfo, ns/* and the magic links. Which do not: status, cmdline and stat are readable subject to the file permissions and the hidepid mount option.ptrace (readby),, ptrace (tracedby),, ptrace (read) peer=@{profile_name}, (base:134-142). "Same profile" covers every process running under that profile, whatever user or session it belongs to.owner is the available narrowing. Its exception is the non-dumpable process, whose files are owned by root./proc/<pid>/fd/N, exe, cwd and root are matched under the target's own name, after procfs has made its own ptrace-mode check. What counts is a file rule for the target plus access to the link. open("/proc/PID/fd/N") is a new open of the target. readlink on them is not mediated by AppArmor./proc/sys and /sys in shipped policy: @{PROC}/asound/** rw,; w on @{sys}/devices/**/usb@{int}/{,**} (devices-usb:18); owner @{PROC}/sys/net/ipv{4,6}/conf/** rw, (wpa_supplicant:123).severity.db rates /proc/** 6 to read and 9 to write, /sys/** 4 and 8 (severity.db:71-77).@{PROC}/@{pid}/attr/{apparmor/,}current write rules are the interface for changing confinement: see aa_change_profile and aa_change_hat.hidepid: base.c:728-742. The ptrace callers in procfs: base.c:818-826, base.c:984, base.c:1787; the jump of a magic link: base.c:1800-1813.__ptrace_may_access: ptrace.c:325-327, ptrace.c:371. apparmor_ptrace_access_check: lsm.c:128-141.Resolved name: name= in the denial, or readlink -f PATH. Check includes with apparmor_parser -p. Replace the pid with @{pid} and add owner when ouid equals fsuid. aa-logprof proposes /proc/*/..., not @{PROC}/@{pid}/....
The record on the slide is built for the map on the field layout of an operation="open" record in the libapparmor test suite (syslog_datetime_01.in); its values are illustrative. The readlink -f output is an illustration consistent with the first scene. The two options in the aa-logprof panel are what the tool's code proposes for such a path; a full aa-logprof session was not run.
name= in the denial, readlink -f PATH, or realpath PATH. For a device node, udevadm info -q path -n DEVICE prints the sysfs device path.apparmor_parser -p FILE prints the profile with its includes flattened, so grep shows whether an abstraction already has the rule. Variables are not expanded in that output: search for the file name, not for /proc/.owner @{PROC}/@{pid}/mountinfo r, is shipped in abstractions/golang (golang:5) and in the lsblk profile (lsblk:56).ouid= equal to fsuid= in the record means the program owns the file, so an owner rule would match.abstractions/base already grants in these trees, all r (base:95-128): @{PROC}/sys/kernel/version, @{PROC}/sys/kernel/ngroups_max, @{PROC}/sys/crypto/fips_enabled, @{PROC}/meminfo, @{PROC}/stat, @{PROC}/cpuinfo, @{sys}/devices/system/cpu/ with online and possible, the transparent hugepage files enabled and hpage_pmd_size, @{PROC}/@{pid}/{maps,auxv,status}, @{PROC}/filesystems, @{PROC}/sys/vm/overcommit_memory, @{PROC}/sys/kernel/cap_last_cap.crypto (@{PROC}/sys/crypto/*), nameservice (@{PROC}/@{pid}/net/route, ipv6_route, psched), bash and gnome (@{PROC}/@{pid}/mounts), nss-systemd (boot_id), golang (mountinfo, cgroup, cgroup cpu quota files), psi-read, and the apparmor_api/* abstractions. The full table is in the reference below.[globs] section of logprof.conf. The procfs entry there is ^/proc/\d+/ = /proc/*/, "strip pid numbers from /proc accesses" (logprof.conf:148-149). There is no entry for /sys.AARE('@{PROC}/meminfo', True).match('/proc/meminfo') is False, so a rule written with @{PROC} or @{pid} may not be recognised as covering a later log event, and the tool may ask again. A full aa-logprof session was not run. A # XXX marker in the code and an existing test expectation suggest this is known.glob_common: aa.py:2547-2552; propose_file_rules: aa.py:2378-2408; convert_regexp: common.py:230-259.AARE: aare.py:49, aare.py:83; the test expectation: test-aare.py:239.Next: prac-symlinks, prac-privileged, prac-abstractions, syn-variables, syn-ptrace, syn-owner, adm-denials, ut-logprof.
/proc/self becomes /proc/<pid>, so rules are written @{PROC}/@{pid}/.... @{pid} means any process; owner narrows a rule to processes of the same user, and a ptrace check stands behind the sensitive per-process files./sys, a class or bus directory needs its own rule with a trailing slash, and attributes are matched under /sys/devices/. Keep the attribute name literal; glob or enumerate the device location.What each deck answers:
/proc and /sys rules matter most./proc and /sys rules base already grants.@{PROC} and @{pid} expand.name= field. aa-logprof: what the tool proposes.Nothing in this deck was run on a live kernel; the kernel behaviour is read from the kernel code.
Basis of the statements on this page: the kernel behaviour is read from the kernel source and the shipped policy from the AppArmor tree. Nothing here was observed on a running kernel. Parser statements marked "parser run" were made with the tree's own apparmor_parser (6.0.0~alpha2), compiling without loading (-Q -K --skip-kernel-load).
| The program opens | AppArmor matches |
|---|---|
/proc/self/X | /proc/<tgid>/X |
/proc/thread-self/X | /proc/<tgid>/task/<tid>/X |
/proc/mounts | /proc/<tgid>/mounts |
/proc/net/X | /proc/<tgid>/net/X |
/proc/<pid>/exe, cwd, root, fd/N | the target's own path: a new open of the target |
/sys/class/C/D/attr | /sys/devices/.../attr |
/sys/bus/B/devices/D/attr | /sys/devices/.../attr |
/sys/block/D/attr | /sys/devices/.../block/D/attr |
/sys/dev/char/M:m/attr, /sys/dev/block/M:m/attr | /sys/devices/.../attr |
the directory /sys/class/C/ itself | /sys/class/C/ |
Not symlinks, and named directly: /sys/devices/system/cpu/..., /sys/kernel/..., /sys/module/..., /sys/fs/cgroup/... (a separate cgroup file system mounted there). Examples: @{sys}/devices/system/cpu/online r, (base:108), @{sys}/module/apparmor/parameters/enabled r, (is_enabled:17), @{sys}/fs/cgroup/**/cpu.max r, (golang:8).
A rule with the literal word self under /proc never matches. The pid is the number in the pid namespace of that procfs mount.
| Variable | Definition | Source | Included by tunables/global |
|---|---|---|---|
@{PROC} | /proc/; sites extend it in tunables/proc.d | proc:12 | yes |
@{sys} | /sys/ | kernelvars:33 | yes |
@{pid} | a number from 1 to 4999999, as seven alternatives | kernelvars:16 | yes |
@{tid}, @{pids} | @{pid} | kernelvars:19, kernelvars:22 | yes |
@{d} | [0-9] | system:12 | yes |
@{h} | [0-9a-fA-F] | system:24 | yes |
@{int} | 1 to 10 digits | system:27 | yes |
@{hex2}, @{hex4} | two and four hex digits | system:60-61 | yes |
@{pci_bus} | pci@{hex4}:@{hex2} | system:99-100 | yes |
@{run} | /run/ /var/run/: two values, so one rule becomes two | run:1 | yes |
@{securityfs} | @{sys}/kernel/security/ | securityfs:10 | no: include it separately |
@{apparmorfs} | @{securityfs}/apparmor/ | apparmorfs:11 | no: include it separately |
@{PROC} and @{sys} end in a slash; rules write @{PROC}/name and the parser collapses the doubled slash (parser run: aare: /proc/meminfo).tunables/sys is an empty, deprecated file.@{pid}, @{pids} and @{tid} compile to the same pattern. By convention @{pid} is written where a program looks at itself, @{pids} where it looks at other processes, @{tid} for thread ids. None of them means "this process".procfs itself asks whether the reader may inspect the target process. For a process outside the reader's own thread group that question reaches AppArmor as a ptrace request.
File under /proc/<pid>/ | procfs asks for | AppArmor rule needed for another process | Own process |
|---|---|---|---|
maps, smaps and the other memory-map files | ptrace read | ptrace (read) peer=..., | not asked |
environ | ptrace read | ptrace (read) peer=..., | not asked |
fdinfo/N | ptrace read | ptrace (read) peer=..., | not asked |
ns/* | ptrace read | ptrace (read) peer=..., | not asked |
exe, cwd, root, fd/N (magic links) | ptrace read, then the target is opened under its own name | ptrace (read) peer=..., and a file rule for the target | not asked; the file rule for the target is still needed |
mem | ptrace attach | ptrace (trace) peer=..., | not asked |
status, cmdline, stat | nothing on open; file permissions and the hidepid mount option | none |
readby or tracedby permission; abstractions/base grants ptrace (readby), and ptrace (tracedby), to every profile that includes it, plus ptrace (read) peer=@{profile_name}, (base:134-142).operation="ptrace", not as a file denial.lsof pairs its /proc/@{pids}/... rules with ptrace read, and capability sys_ptrace, (lsof:25-28).owner compares the reader's fsuid with the owner of the file./proc/<pid>/ are owned by the target process's effective uid and gid.owner rule then denies that program its own files.owner on /proc/sys or /sys attributes is meaningful only for programs that run as root: a real record for /sys/class/power_supply/ shows ouid=0.owner @{PROC}/@{pid}/mountinfo r, (golang:5, lsblk:56), owner @{PROC}/@{pid}/fd/ r, (gio-open:56, samba-rpcd:26), owner @{PROC}/@{pid}/{cgroup,cpuset,status} r, (opencl-pocl:41), owner @{PROC}/@{pid}/task/@{tid}/comm rw, (dig:46). Over profiles/apparmor.d the fd/ directory rule appears 7 times without owner and 6 times with it.| Abstraction | Rules in /proc and /sys | Source |
|---|---|---|
| base | @{PROC}/sys/kernel/version, ngroups_max, @{PROC}/sys/crypto/fips_enabled, @{PROC}/meminfo, stat, cpuinfo, @{sys}/devices/system/cpu/ with online and possible, transparent hugepage enabled and hpage_pmd_size, @{PROC}/@{pid}/{maps,auxv,status}, @{PROC}/filesystems, @{PROC}/sys/vm/overcommit_memory, @{PROC}/sys/kernel/cap_last_cap; all r | base:95-128 |
| crypto (included by base) | @{PROC}/sys/crypto/fips_enabled r,, @{PROC}/sys/crypto/* r, | crypto:24-27 |
| nameservice | @{PROC}/@{pid}/net/psched r,, ipv6_route r,, route r, | nameservice:55, nameservice:102-103 |
| bash | @{PROC}/@{pid}/mounts r,, @{PROC}/filesystems r, | bash:37-38 |
| gnome | @{PROC}/@{pid}/mounts r, | gnome:82 |
| nss-systemd | @{PROC}/sys/kernel/random/boot_id r, | nss-systemd:30 |
| golang | owner @{PROC}/@{pid}/mountinfo r,, owner @{PROC}/@{pid}/cgroup r,, cgroup cpu quota files | golang:5-8 |
| audio | @{PROC}/asound/** rw,: read and write on the whole ALSA procfs tree | audio:39 |
| mesa | @{sys}/devices/@{pci_bus}/**/{revision,config} r, | mesa:17 |
| nvidia | @{PROC}/interrupts, @{PROC}/modules, @{PROC}/driver/nvidia/params | nvidia:20-23 |
| video | @{sys}/class/video4linux/** r, and device paths | video:7-17 |
| devices-usb-read, devices-usb | @{sys}/devices/**/usb@{int}/{,**} r,; devices-usb adds w | devices-usb-read:19-26, devices-usb:18 |
| apparmor_api/examine, introspect, change_profile, find_mountpoint, is_enabled | the attr files, @{PROC}/@{pids}/mounts r,, the apparmor module parameter | examine:14, change_profile:13, find_mountpoint:16, is_enabled:17-18 |
| psi-read, psi-read-poll | @{PROC}/pressure/{cpu,memory,io}, r and rw | psi-read:6 |
base's @{PROC}/@{pid}/{maps,auxv,status} r, has no owner. For another process's maps and auxv the ptrace check still applies; for status it does not.
| Level | Rule | Source |
|---|---|---|
| one file | @{PROC}/sys/net/ipv6/conf/all/disable_ipv6 r, | bin.ping:27 |
| one file, write | /proc/sys/kernel/task_delayacct rw, | iotop-c:28 |
| one attribute, any location | @{sys}/devices/**/usb[0-9]**/descriptors r, and its neighbours | lsusb:64-96 |
| per-process files, each named | @{PROC}/@{pids}/stat r,, @{PROC}/@{pids}/task/@{tid}/fd/ r, and more | lsof:38-52 |
| a bus subtree | @{sys}/devices/@{pci_bus}/** r,, virtual/**, platform/**, then Xen, network disks, IBM Z, Azure | lsblk:26-28, lsblk:36-47 |
| everything under devices, write on one leaf | @{sys}/**/ r,, @{sys}/devices/** r,, @{sys}/module/** r,; @{sys}/devices/@{pci_bus}/**/backlight/*/brightness rw, | Xorg:97-101 |
| devices, with a write glob | file r @{sys}/devices/{,**},, file rw @{sys}/devices/**/statistics/rx_*, | tshark:57-58 |
| everything | @{PROC}/** r,, @{sys}/devices/** r, | phpsysinfo:24, phpsysinfo:31 |
| loose pid patterns | @{PROC}/*/mounts r,; /proc/*/cmdline r,, /proc/*/task/ r,: * is any single name, not only a number | usr.lib.dovecot.lmtp:35, iotop-c:24-25 |
utils/severity.db rates /proc/** 6 for read and 9 for write, /proc/kallsyms 7 for read, /sys/** 4 and 8, /sys/firmware/** 10 for write (severity.db:71-77).
name= in the denial; readlink -f PATH or realpath PATH; udevadm info -q path -n DEVICE for the sysfs path of a device node.apparmor_parser -p FILE | grep NAME prints the profile with its includes flattened.@{pid} (own) or @{pids} (others), and add owner where the target runs as the same user (ouid= equals fsuid= in the record).@{pci_bus}/** or ** or enumerate bus roots, and add the class or bus directory rule with a trailing slash./proc/sys and /sys should name one file.[globs] section of logprof.conf.^/proc/\d+/ = /proc/*/, "strip pid numbers from /proc accesses" (logprof.conf:148-149). There is no entry for /sys.@{PROC} or @{pid}.self under /proc, and any rule that names an attribute through /sys/class/, /sys/bus/.../devices/, /sys/block/ or /sys/dev/. They compile and never match. No shipped profile has a /proc/self rule.@{pid} is every process. For maps, environ, mem, fdinfo, ns/* and the magic links the effective limits are the ptrace check and the file permissions; status, cmdline and stat have no ptrace check.ptrace (read) peer=@{profile_name}, with readby and tracedby: processes under one profile can inspect each other.owner narrows a rule to the reader's own uid; a non-dumpable process is the exception.readlink on them is not mediated by AppArmor.@{PROC}/asound/** rw,, w on @{sys}/devices/**/usb@{int}/{,**}, owner @{PROC}/sys/net/ipv{4,6}/conf/** rw,.severity.db ratings, above.@{PROC}/@{pid}/attr/{apparmor/,}current write rules are the interface for changing confinement: lib-change-profile, lib-change-hat./proc/self rules. Checked with a parser run on a scratch profile containing /proc/self/maps r,: exit status 0, no warning. A missing diagnostic rather than wrong behaviour.AARE('@{PROC}/meminfo', True).match('/proc/meminfo') is False and AARE('/proc/meminfo', True).match('/proc/meminfo') is True. A full aa-logprof session was not run; a # XXX marker and an existing test expectation suggest it is known.@{u16} in tunables/system has an unbalanced bracket, [1-9][@{d}@{d} (system:38). Checked with a parser run using -D rule-exprs: the malformed alternation is printed and the exit status is 0. Three-digit values are mis-matched; no shipped profile uses the variable. @{u8} is a four-value variable, probably intended./proc/sys special case for internal mounts in AppArmor's name building.stat on a class symlink itself can be denied.| What | Where |
|---|---|
/proc/self, /proc/thread-self | self.c:11-28, thread_self.c:11-25 |
/proc/mounts, /proc/net | root.c:383, proc_net.c:423 |
| magic links: check and jump | base.c:1787, base.c:1800-1813 |
| procfs ptrace callers | base.c:818-826, base.c:855, base.c:984, fd.c:94, namespaces.c:63 |
hidepid | base.c:728-742 |
| owner of procfs inodes | base.c:1872-1897, base.c:1953 |
__ptrace_may_access | ptrace.c:325-327, ptrace.c:371 |
PID_MAX_LIMIT | threads.h:34-35 |
| class, subsystem, device and dev links | core.c:3510-3522, core.c:3580-3589, core.c:3327-3332 |
| bus and block links | bus.c:583, genhd.c:507, genhd.c:1011 |
| kernfs link text | symlink.c:67, symlink.c:87 |
apparmor_ptrace_access_check | lsm.c:128-141 |
apparmor_file_open, owner condition | lsm.c:465-500, lsm.c:491-496 |
d_namespace_path, the /proc/sys special case | path.c:89-128, path.c:105-110 |
parser: filter_slashes | parser_regex.c:61, parser_regex.c:659 |
| tools: globs, proposals, matching | aa.py:2547-2552, aa.py:2378-2408, aare.py:49, common.py:230-259, test-aare.py:239 |
apparmor_parser -S writes the binary policy to stdout: 5009 bytes for the three-rule example, starting with the element version.
apparmor_parser -Q -S -K demo3.sd, run with the parser built from the AppArmor tree and a feature set that has the policy entries the kernel exports; nothing was loaded into a kernel. -S writes the binary policy to standard output and loads nothing; -K skips the cache.demo3.sd):abi <abi/5.0>,
include <tunables/global>
profile demo /usr/bin/demo {
/etc/demo/** r,
audit deny @{HOME}/.ssh/** rw,
/usr/bin/[a-z]* ix,
}
abi/5.0 feature set is 4529 bytes.Element codes (parser/parser_interface.c:162-177): 0 U8, 1 U16, 2 U32, 3 U64, 4 NAME, 5 STRING, 6 BLOB, 7 STRUCT, 8 STRUCTEND, 11 ARRAY, 12 ARRAYEND. Stream integers are little-endian. The first element is version.
enum class sd_code (parser_interface.c:162-177). The forms (parser_interface.c:197-331): a name is 04, a 16-bit length that includes the NUL, and the bytes (parser_interface.c:252-261); a string is 05 with the same layout (parser_interface.c:286-297); a blob is 06, a 32-bit length and the bytes (parser_interface.c:263-269); an array is 0b, a 16-bit count, the elements and 0c (parser_interface.c:310-320); a struct is 07, the elements and 08 (parser_interface.c:299-308).enum aa_code has the same values up to ARRAYEND and no OFFSET (policy_unpack.h:63).ENCODE_VERSION (parser.h:315-332, parser_common.c:61-63): bits 0-9 are the kernel ABI; when that is above 5, bit 11 is force complain, bits 12-19 the parser ABI (2) and bits 20-27 the policy version (2). kernel_abi_version is 7 or 6 when the features have policy/versions/v7 or v6, and 5 otherwise (parser_main.c:1763-1766).aa_unpack_nameX, aa_unpack_u32, aa_unpack_array, aa_unpack_blob, aa_unpack_str (policy_unpack.c:242, policy_unpack.c:291); every bounds check goes through aa_inbounds (policy_unpack.c:180).verify_header (policy_unpack.c:1442) refuses a kernel ABI below 5 or above 9 with "unsupported interface version" (-EPROTONOSUPPORT). The force complain bit is FORCE_COMPLAIN_FLAG, 0x800 (policy_unpack.c:1224, policy_compat.h:17).aa_features_supports(features, "policy/versions/v7") is false for a feature set that has policy/notify_versions, because the lookup matches versions against the end of notify_versions (features.c:361-444). The tree's abi/5.0 file has that entry, so with it the parser writes version 5, without policy version, parser ABI or force complain bit, and leaves the file class marker out of policydb. This was confirmed by running the tree's parser; the kernel's own feature directory has no notify_versions.sd_serialize_profile (parser/parser_interface.c:480-604) writes name, xmatch, flags, capabilities, optional structs, policydb, then the file permission table and DFA. unpack_profile (linux:security/apparmor/policy_unpack.c:1121-1432) reads them in the same order.
void sd_serialize_profile(std::ostringstream &buf, Profile *profile, int flattened) (parser_interface.c:480-604); the reader is unpack_profile (policy_unpack.c:1121). All fields, in order (writer lines in parser_interface.c, reader lines in policy_unpack.c):| # | Field | Written when | Writer | Reader |
|---|---|---|---|---|
| 1 | string: name (parent//child when flattened) | always | 488-493 | 1140-1158 |
| 2 | xmatch: blob aadfa, then u32 xmatch_len | xmatch exists | 496-501 | 1175-1196 |
| 3 | string disconnected | flag attach_disconnected.path= | 504-507 | 1199 |
| 4 | string disconnected_ipc | set, and feature domain/disconnected.ipc | 509-512 | not read |
| 5 | u32 kill | set, and feature domain/kill.signal | 514-517 | 1203-1207 |
| 6 | u32 error | set, and feature policy/profile/error | 519-522 | not read |
| 7 | struct flags: flag bits, mode, audit | always | 524-529 | 1209-1244 |
| 8 | u32 path_flags | any path flag | 530-545 | 1247-1252 |
| 9 | four u32: capability allow, audit, quiet, 0 | always | 549-553 | 1255-1262 |
| 10 | struct caps64: the high halves | always | 555-560 | 1265-1277 |
| 11 | array identity | feature domain/identity | 562-563, 333-344 | not read |
| 12 | struct xattrs: array of names | xattrs= | 565, 458-478 | 1290, 591-620 |
| 13 | struct rlimits: mask, array of 16 u64 | any rlimit | 567, 398-411 | 1295, 667-701 |
| 14 | array net_allowed_af | old network encoding only | 570-584 | not read |
| 15 | struct policydb: perms, blob aadfa, xtable | policydb DFA exists | 586-595 | 1305-1331 |
| 16 | perms, permsv, blob aadfa (file DFA) | file DFA exists | 597-598 | 1333-1352 |
| 17 | struct xtable | file DFA exists and a named exec target | 599-602 | 1075 (in unpack_pdb) |
| 18 | struct end | always | 603 | 1407 |
rename, attach (policy_unpack.c:1169), capsx (policy_unpack.c:1280), secmark (policy_unpack.c:1300), tags, start and dfa_start (policy_unpack.c:1026), and a data struct (policy_unpack.c:1354).PACKED_FLAG_HAT); mode 0 enforce, 1 complain, 2 kill, 3 unconfined, 4 user (policy_unpack.h:32).deny & quiet, and audit is limited to allowed capabilities (parser_interface.c:549-558).info field of the audit record: "bad xmatch", "missing xmatch len", "profile missing flags", "failed to unpack profile flags", "failed to unpack profile capabilities", "failed to unpack policydb", "failed to unpack end of profile" (policy_unpack.c:1126).aa_unpack_nameX, which steps back when the name differs (policy_unpack.c:242).attach_disconnected.ipc is dropped without a warning and its bit is written anyway"; "mediate_deleted is packed with the bit the kernel calls PATH_DELEGATE_DELETED".Of 5009 bytes, 4040 are the table sets of the three DFAs (1344, 1168, 1528). In the file DFA's 1528 bytes, next and check take 1136.
-S output made with a feature set that has the kernel's policy entries):| Offset | Element | Value |
|---|---|---|
| 0000 | name version, u32 | 0x202007 |
| 0010 | name profile, struct | |
| 001c | string | demo |
| 0024 | name aadfa, blob | size 1350 = 6 pad + table set of 1344 at 0038 (xmatch, 15 states) |
| 0578 | u32 | xmatch_len 13 |
| 057d | name flags, struct of 3 u32 | 0, 0 (enforce), 0 |
| 0597 | 4 u32 | capability allow, audit, quiet, 0: all 0 |
| 05ab | name caps64, struct of 4 u32 | all 0 |
| 05cb | name policydb, struct | |
| 05d8 | name perms, struct: version 1, array of 2 rows | allow 0x8000, 0x8004 |
| 0683 | name aadfa, blob | size 1175 = 7 pad + table set of 1168 at 0698 (5 states) |
| 0b28 | struct end (policydb) | |
| 0b29 | name perms, struct: version 1, array of 8 rows | allow 0x200 four times, 0x244 twice, 0x10201 twice |
| 0d78 | name permsv, u32 | 3 |
| 0d87 | name aadfa, blob | size 1531 = 3 pad + table set of 1528 at 0d98 (22 states) |
| 1390 | struct end (profile) | total 0x1391 = 5009 |
abi/5.0 feature set): the one-rule profile of 4529 bytes has DFAs of 15, 5 and 13 states and 3840 bytes of table sets; a profile with three abstractions is 46041 bytes for 1695 states in the file DFA.sd_write_aligned_blob (parser/parser_interface.c:274-284) pads so the table set starts at a multiple of 8 within the unit; the blob length includes the pad. unpack_dfa skips size & 7 bytes (linux:security/apparmor/policy_unpack.c:442-468).
sd_write_aligned_blob (parser_interface.c:274-284) writes the pad and the data as one blob; sd_serialize_dfa (parser_interface.c:383-396) writes the optional permission table and then the blob.unpack_dfa is sz = blob - start - ((pos - start) & 7); pad = ALIGN(sz, 8) - sz, with pos already past the blob; that equals size & 7 (policy_unpack.c:442).aa_dfa_unpack copies each table into its own allocation with unaligned reads (match.c:34), so the alignment of the data in the buffer does not matter to it.perms: version 1 and an array of rows of 14 u32 (parser/parser_interface.c:346-374). permsv 3 follows the file table. xtable: names for exec slots 4 to 15, written inside policydb and after the file DFA (413-456, 590-602).
kernel_supports_permstable32_version >= 2 and it is not empty (parser_interface.c:387-390); permsv is written at parser_interface.c:376-380.unpack_perms_table (policy_unpack.c:925); unpack_perm refuses a version other than 1 (policy_unpack.c:905); unpack_pdb (policy_unpack.c:968): with a table the accept table is an index and accept2 is expected only when permsv is above 2 (policy_unpack.c:996); without a table both accept tables are required (policy_unpack.c:1002).apparmor_parser -Q -K -S and a feature set that has the kernel's policy entries (15416 bytes; the tree's abi/5.0 feature set gives the same size and the same table):abi <abi/5.0>,
profile :ns1:demo /usr/bin/demo flags=(complain) {
capability net_bind_service,
set rlimit nofile <= 1024,
/usr/bin/demo-helper Px -> demo-helper,
/usr/bin/other Px -> :ns2:other,
/usr/lib/demo/worker Cx -> worker,
profile worker { /tmp/w r, }
^admin { /etc/demo/admin.conf rw, }
}
demo//worker (the Cx rule, written last) comes first and demo-helper (written first) comes last. The array is at 0x0bd8 inside policydb and again after the file DFA.sd_serialize_xtable (parser_interface.c:413-456) writes nothing when slot 4 is empty (parser_interface.c:417-418); a target in another namespace is written as :ns, NUL, name, NUL (parser_interface.c:433-449). The index in a row is the slot minus 4 (policy_compat.cc:59-62). The table is written inside policydb and after the file DFA (parser_interface.c:590-602). The xmatch DFA has no table.unpack_strs_table(e, "xtable", false, &pdb->trans) (policy_unpack.c:1075, policy_unpack.c:528); process_strs_entry refuses an entry that starts with NUL or white space and turns the NUL after a namespace back into : (policy_unpack.c:470); verify_perms checks each table index and trims unused tail entries (policy_unpack.c:1534).sd_serialize_xtable skips empty slots, which would shift later indexes if the table ever had a gap (parser_interface.c:417-430); not determined whether it can.-> on a rule without exec or link permission is accepted and takes an exec table slot".__sd_serialize_profile writes a profile and then each child and hat as its own unit named parent//child (parser/parser_interface.c:683-791). aa_unpack loops over the units (linux:security/apparmor/policy_unpack.c:1745-1838).
sd_serialize_top_profile (parser_interface.c:666-681) writes version, then namespace when the profile has one, then the profile struct; the name is flattened to parent//child when the profile has a parent (parser_interface.c:488-490). __sd_serialize_profile (parser_interface.c:683-791) then calls load_flattened_hats (parser_interface.c:783-786, parser_policy.c:70-89).apparmor_parser -Q -K -S and a feature set that has the kernel's policy entries (the tree's abi/5.0 feature set gives the same size and offsets):abi <abi/5.0>,
profile :ns1:demo /usr/bin/demo flags=(complain) {
capability net_bind_service,
set rlimit nofile <= 1024,
/usr/bin/demo-helper Px -> demo-helper,
/usr/bin/other Px -> :ns2:other,
/usr/lib/demo/worker Cx -> worker,
profile worker { /tmp/w r, }
^admin { /etc/demo/admin.conf rw, }
}
demo, with namespace ns1), 0x1c96 (demo//admin, flags 1, 0, 0) and 0x3027 (demo//worker). The first unit also has mode 1 (complain), capability allow 0x400 and rlimits with mask 0x80 and 16 values. The slide draws the bodies of the child and the hat as { ... }; with empty bodies the output is 13361 bytes and the units start at 0x0000, 0x1c96 and 0x2e5f.aa_unpack (policy_unpack.c:1745) loops over the units; the version element is required only for the first unit (policy_unpack.c:1761). verify_header reports a namespace that differs from an earlier unit's as "invalid ns change" (policy_unpack.c:1442).\x04\x08\x00version\0\x02 as a marker. The kernel does not search for them: aa_unpack parses unit after unit in order (policy_unpack.c:1759). libapparmor splits a buffer at \x04\x08\x00version\0 (11 bytes) and writes the units one by one, for kernels without set_load (kernel_interface.c:68-124). The kernel uses its 12-byte aa_hdr_magic once, to recognise an uncompressed stream behind an 8-byte user header (apparmorfs.c:604, apparmorfs.c:649). The parser uses the same 12 bytes, followed by the version word, to accept a cache file that is not compressed (policy_cache.c:36-69).With policy/compressed_load and policy/set_load the stream is zstd-compressed (level 3 unless -c, -O compress-default or -O compress-small): the 5009 bytes become 565 in all, an 8-byte header and a 557-byte frame. A cache file that is not compressed is accepted by its version marker and version word (parser/policy_cache.c:36-69); a compressed one by its header.
set_compression_level (parser_main.c:480-506, constants at parser.h:98-100): an explicit -c level is kept; otherwise there is no compression unless the kernel has both policy/set_load and policy/compressed_load; then the level is 10 with -O compress-default, 20 with -O compress-small, else 3.compress_policy_zstd compresses one unit (parser_interface.c:646-664). For -S and -o the output is struct compr_user_header (version 1, level, six bytes of padding) followed by the frame (lib.c:46-69, apparmor_private.h:41-47).-S and a feature set that has the kernel's policy entries plus compressed_load: 565 bytes in all, an 8-byte header and a 557-byte frame. The header is written for -S, -o and cache files (parser_interface.c:757-763, policy_cache.c:336); a direct load writes the bare frame (parser_interface.c:747-756). The one-rule profile of 4529 bytes compresses to 497.install_compressed_cache reads it back, compresses all units of the file into one zstd frame and installs the 8-byte header plus that frame (parser_main.c:1428-1435, policy_cache.c:311-343).is_valid_precompressed_profile looks at the header version, the zstd magic and the level (policy_cache.c:80-96, policy_cache.c:136-146, private.c:37-55); the version word is inside the frame and is not tested. A file that is not compressed: valid_cached_file_version compares the first 16 bytes, the 12-byte version marker and the version word the parser would write now (policy_cache.c:36-69, called at policy_cache.c:170-176). So a changed version word makes the uncompressed cache files stale; for compressed ones this check does not run.policy_update looks for the zstd magic at offset 0 or after an 8-byte struct aa_user_hdr, or for the 12-byte version marker after such a header, and decompresses before unpacking (apparmorfs.c:598). The two feature entries exist only with CONFIG_SECURITY_APPARMOR_COMPRESSED_POLICY (apparmorfs.c:2642).Compression error: out of memory, Compression error: %s (parser_interface.c:651, parser_interface.c:660). Warning, class WARN_DEBUG_CACHE: WARNING: Kernel does not support compressed policies. Defaulting to uncompressed (parser_main.c:501-503).--help prints "default: 10" and apparmor_parser(8) says "a default value of 10 is used" (parser_main.c:490-498 against parser_main.c:267-277; apparmor_parser.pod:376).-n does not skip the policy cache, so a cached profile can be loaded into the wrong namespace".Load path: policy_update (decompress), aa_unpack (units), verify_header, unpack_profile, unpack_pdb, unpack_dfa, aa_dfa_unpack, then verify_dfa, verify_dfa_accept_index and verify_perms.
policy_update detects compression and decompresses (apparmorfs.c:598); aa_unpack loops over the units (policy_unpack.c:1745); verify_header checks the version word and the namespace (policy_unpack.c:1442); unpack_profile takes the fields in order (policy_unpack.c:1121); unpack_pdb takes the permission table, the DFA blob and the name table (policy_unpack.c:968); unpack_dfa skips the pad (policy_unpack.c:442); aa_dfa_unpack checks the magic and copies the tables out (match.c:333).verify_dfa (match.c:154) runs when aa_g_paranoid_load is set (policy_unpack.c:458, lsm.c:2006).verify_dfa_accept_index checks, for the file and policydb DFAs, that the accept value, and the accept value plus 1 with the owner flag, are inside the table; verify_perms checks all three tables (policy_unpack.c:1492); verify_perm rejects a row with a bit in both allow and deny (policy_unpack.c:1511).aa_dfa_unpack does not use the version string or th_ssize of the table set header.verify_profile calls verify_dfa_accept_index for rules->file and rules->policy only. For attach.xmatch with its own perms struct, aa_lookup_perms would index without a bound (policy.h:156, domain.c:349). Reaching it needs a hand-built stream and the right to administer policy; not reproduced.Next: unpacking and verifying policy, matching at run time. Operations: the policy cache, loading policy into the kernel. Security: who can change policy. Back: table compression, the backend pipeline.
Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run with -Q -K -S, and the output was decoded with a short script written for the purpose (not code from the tree); nothing was loaded into a kernel. The three-rule example was compiled with a feature set that has the policy entries the kernel exports (version word 0x202007); the other examples with the tree's abi/5.0 file (version word 5). "code" means the parser source, or the kernel source, was read and not run; "derived" means the result was reasoned from that code. Nothing here was observed on a running kernel.
| Code | Name | Form |
|---|---|---|
| 0, 1, 2, 3 | U8, U16, U32, U64 | the code byte, then the integer, little-endian |
| 4 | NAME | 04, 16-bit length including the NUL, bytes; precedes the value it names |
| 5 | STRING | 05, 16-bit length including the NUL, bytes |
| 6 | BLOB | 06, 32-bit length, bytes |
| 7, 8 | STRUCT, STRUCTEND | 07, elements, 08 |
| 11, 12 | ARRAY, ARRAYEND | 0b, 16-bit count, elements, 0c |
| 9, 10, 13 | LIST, LISTEND, OFFSET | defined, not written |
Code: parser_interface.c:162-331; kernel readers at policy_unpack.c:242 and policy_unpack.c:291.
| Bits | Meaning |
|---|---|
| 0-9 | kernel ABI: 7 or 6 with policy/versions/v7 or v6, else 5 |
| 11 | force complain (only when the kernel ABI is above 5) |
| 12-19 | parser ABI, 2 (only above 5) |
| 20-27 | policy version, 2 (only above 5) |
policy entries; 5 with the tree's abi/5.0 (tree).| # | Field | Written when |
|---|---|---|
| 1 | string: name (parent//child when flattened) | always |
| 2 | blob aadfa (xmatch), u32 xmatch_len | xmatch exists |
| 3 | string disconnected | attach_disconnected.path= |
| 4 | string disconnected_ipc | set, and feature domain/disconnected.ipc |
| 5 | u32 kill | set, and feature domain/kill.signal |
| 6 | u32 error | set, and feature policy/profile/error |
| 7 | struct flags: flag bits, mode, audit | always |
| 8 | u32 path_flags | any path flag |
| 9 | four u32: capability allow, audit, quiet, 0 | always |
| 10 | struct caps64 | always |
| 11 | array identity | feature domain/identity |
| 12 | struct xattrs | xattrs= |
| 13 | struct rlimits: mask, 16 u64 | any rlimit |
| 14 | array net_allowed_af | old network encoding only |
| 15 | struct policydb: perms, blob aadfa, xtable | policydb DFA exists |
| 16 | perms, permsv, blob aadfa (file DFA) | file DFA exists |
| 17 | struct xtable | a named exec target |
| 18 | struct end | always |
rename, attach, capsx, secmark, tags, start, dfa_start, a data struct (code).| Offset | Element | Value |
|---|---|---|
| 0000 | name version, u32 | 04 08 00 "version\0" 02 07 20 20 00 = 0x202007 |
| 0010 | name profile, struct | |
| 001c | string | demo |
| 0024 | name aadfa, blob | size 1350 = 6 pad + table set of 1344 at 0038 (xmatch: 15 states, accept[14] = 1) |
| 0578 | u32 | xmatch_len 13 |
| 057d | name flags, struct of 3 u32 | 0, 0 (enforce), 0 |
| 0597 | 4 u32 | capability allow, audit, quiet, 0: all 0 |
| 05ab | name caps64, struct of 4 u32 | all 0 |
| 05cb | name policydb, struct | |
| 05d8 | name perms, struct: version 1, array of 2 rows | allow 0x8000, 0x8004 |
| 0683 | name aadfa, blob | size 1175 = 7 pad + table set of 1168 at 0698 (5 states) |
| 0b28 | struct end (policydb) | |
| 0b29 | name perms, struct: version 1, array of 8 rows | allow 0x200 four times, 0x244 twice, 0x10201 twice |
| 0d78 | name permsv, u32 | 3 |
| 0d87 | name aadfa, blob | size 1531 = 3 pad + table set of 1528 at 0d98 (22 states) |
| 1390 | struct end (profile) | total 0x1391 = 5009 |
Tree. Table sets: 1344 + 1168 + 1528 = 4040 bytes; permission tables 140 + 560 bytes; everything else 269 bytes.
size & 7 bytes (policy_unpack.c:442) (code).perms { version 1, array N [ row ... ] }; a row is 14 u32: reserved, allow, deny, subtree, cond, kill, complain, prompt, audit, quiet, hide, xindex, tag, label (parser_interface.c:346-374) (code).permsv 3 follows the file table; above 2 the kernel expects an accept2 table with the owner flag (code).xtable: an array of strings for exec slots 4 to 15; a row's xindex is the slot minus 4 (code).:ns, NUL, name, NUL; the kernel turns the NUL back into : (code).policydb and after the file DFA when permission tables are used (tree).version, an optional namespace, and the profile struct (code).parent//child; a hat has flag bit 1 (code, tree).04 08 00 "version\0" 02 mark the start of a unit (code).| Option | zstd level |
|---|---|
none, kernel has policy/set_load and policy/compressed_load | 3 |
-O compress-default | 10 |
-O compress-small | 20 |
-c N | N |
kernel lacks either entry, no -c | not compressed |
-S (the 8-byte header and a 557-byte frame; a direct load writes the bare frame), starting 01 03 00 00 00 00 00 00 28 b5 2f fd (tree).version marker and the version word the parser would write now (policy_cache.c:36-69) (code).policy/compressed_load and policy/set_load) a cache file is the 8-byte header and one zstd frame over all units of the file. The parser accepts it by the header version, the zstd magic and the level; the version word is not tested (policy_cache.c:80-96, policy_cache.c:148-181) (code).| Check | Function | When |
|---|---|---|
| every access inside the buffer | aa_inbounds | always |
| kernel ABI field of the version word 5 to 9; no namespace change between units | verify_header | always |
| magic number and header flags of a table set | aa_dfa_unpack | always |
| table sizes agree | aa_dfa_unpack | always |
| base + 255 inside next/check; state numbers in range; diff chains end | verify_dfa | paranoid load |
| accept index, and index + 1 with the owner flag, inside the table | verify_dfa_accept_index | file and policydb DFAs |
| xindex in range; no bit in both allow and deny | verify_perms, verify_perm | always |
All rows: code.
"unsupported interface version", "invalid ns change", "bad xmatch", "missing xmatch len", "profile missing flags", "failed to unpack profile flags", "failed to unpack profile capabilities", "failed to unpack policydb", "failed to unpack end of profile". They appear in the info field of the audit record (code).
abi/5.0 file as kernel features the parser writes version word 5: the lookup of policy/versions/v7 matches the end of notify_versions (features.c:361-444) (tree).sd_serialize_xtable skips empty slots (code; not determined whether a gap can occur).attach_disconnected.ipc is dropped without a warning and its bit is written anyway"; "mediate_deleted is packed with the bit the kernel calls PATH_DELEGATE_DELETED"; "-> on a rule without exec or link permission is accepted and takes an exec table slot"; "Children and hats of a profile that names its namespace are serialised without the namespace"; "A child or hat that the kernel refuses is reported and then ignored: exit status 0"; "next_profile_buffer reads past the end of the policy buffer on kernels without set_load"; "Cache hit on an uncompressed cache loads the profile twice and writes the cache without -W"; "-n does not skip the policy cache, so a cached profile can be loaded into the wrong namespace".policy/notify_versions treat a version 5 stream differently.The parser builds the states of the machine from the rules: 38 for the three-rule example. apparmor_parser -D dfa-stats prints the count.
apparmor_parser -Q -K -D dfa-stats demo3.sd, run with the parser built from the AppArmor tree; nothing was loaded into a kernel. The command prints one Created dfa line per state machine of the profile; the second line is the one for the file rules. The count is the same with the tree's abi/5.0 feature set and with one that has the kernel's policy entries.demo3.sd):abi <abi/5.0>,
include <tunables/global>
profile demo /usr/bin/demo {
/etc/demo/** r,
audit deny @{HOME}/.ssh/** rw,
/usr/bin/[a-z]* ix,
}
DFA::DFA computes followpos for every leaf, makes state 0 from the empty set and state 1 from the root's firstpos (hfa.cc:489-497). A state is a set of tree positions.
DFA(Node *root, optflags const &flags, bool filedfa) (hfa.h:441); the constructor is at hfa.cc:470-543.root->compute_pos(firstpos, lastpos) computes nullable, firstpos, lastpos and followpos (hfa.cc:489-494); the rules are in the comment at expr-tree.h:305-334, after the Dragon Book, section 3.9.2.add_new_state (hfa.cc:329-371) splits the node set into accept and non-accept nodes, interns both in anodes_cache and nnodes_cache, and maps the pair to a state through node_map (hfa.h:246-273, hfa.h:373-406).DFA_NOMATCH 0 and DFA_START 1 (match.h:17).longest=4 in the -D dfa-stats line agrees with the four-position set.-D dfa-node-map prints addresses, not node labels (hfa.cc:60-69, hfa.cc:438), so it cannot be related to the tree dump.update_state_transitions calls follow() on each position of a state and creates a state for each new target set (hfa.cc:373-427, 441-465). -D dfa-states-initial prints the result.
update_state_transitions (hfa.cc:373-427) collects, per input character, the union of the followpos sets of the positions that accept it.follow per node kind (expr-tree.h:571-581, expr-tree.h:620-632, expr-tree.h:689-709, expr-tree.h:763-773): a CharNode or CharSetNode adds its followpos to the entries of its characters, seeding a new entry from the current otherwise set; a NotCharSetNode or AnyCharNode adds to otherwise and to every existing entry it matches.DFA::dump, hfa.cc:1174-1241): first the start state and every accepting state, then per state the explicit transitions that do not lead to state 0. A state with nothing but transitions to state 0 is not listed.abi/5.0 feature set and with one that has the kernel's policy entries. The complete dump is in the reference under the deck.cleanup() (hfa.cc:339-348).-D dfa-progress prints a status line (hfa.cc:446-454); -D dfa-graph writes Graphviz (hfa.cc:1246-1294).State has trans (explicit transitions) and otherwise (hfa.h:362-363). [^\x0/] -> {35} in a dump is otherwise = {35} plus explicit transitions on NUL and / to state 0.
StateTrans is std::map<transchar, State *> (hfa.h:43); a State has trans and otherwise (hfa.h:362-363), and State::next looks in trans first (hfa.h:319-334).update_state_transitions, cases.otherwise becomes the state's otherwise, and each entry of cases becomes an explicit transition unless its target equals otherwise (hfa.cc:394-399, hfa.cc:418-425).[^\x0]: its / transition leads to {21} and is listed on its own line.[\x01-.0-\xff] (254 explicit transitions, default state 0) and [^/\x00] (default the target, two explicit transitions) behave the same and are stored differently. A comment in the minimizer states that it "will fail to fully minimize" in that case; see Minimisation.(0x 10004/0//0/0/0), with a blank after 0x and a doubled slash; the fields are allow/deny/prompt/audit/quiet. Known discrepancy, by title: "Debug dumps with malformed output".Accepting states of the example: {34} allow 0x904241, {35} allow 0x10004, {37} deny 0x3800e. -D dfa-uniq-perms lists the distinct sets; a State computes its permissions in its constructor (hfa.h:305-309).
-D dfa-states-initial dump lists the start state and the accepting states:{1} <== (allow/deny/prompt/audit/quiet)
{34}(0x 904241/0//0/0/0)
{35}(0x 10004/0//0/0/0)
{37}(0x 0/3800e//0/0/0)
-D dfa-uniq-perms (hfa.cc:571-580) prints, for the file DFA:Unique Permission sets: dfa (4) ---------------------- allow:0 deny:0 audit:0 quiet:0 prompt:0 allow:0 deny:3800e audit:0 quiet:0 prompt:0 allow:10004 deny:0 audit:0 quiet:0 prompt:0 allow:904241 deny:0 audit:0 quiet:0 prompt:0
policy entries; the slide shortens the four lines to one.0x904241 is 0x804201 (exec and inherit, for owner and for other) plus the implied mmap bit 0x40 in both halves.State computes its permissions in its constructor (hfa.h:305-309), and add_new_state builds the state for every transition target before it checks for a duplicate (hfa.cc:340, hfa.cc:349-351). On the profile /etc/demo/** rw, deny /etc/demo/*.conf w, priority=10 allow /etc/demo/override.conf w, the -D dfa-perms-build dump has 97 "Building Perms" blocks, 76 of them for the same accept node (run with the abi/5.0 feature set).Out of band character -1: created only for xattr attachment conditions, never matched by a negated set or ., taken in the kernel by aa_dfa_outofband_transition (linux:security/apparmor/match.c:581-597).
profile xa /usr/bin/x* xattrs=(user.a=one user.b=tw*), not the three-rule example. From its -D dfa-states dump, attachment machine (parser of the AppArmor tree, abi/5.0 feature set):{10} perms: none
x 0x78 -> {11} (0x 1/0//0/0/0)
{11} perms: (0x 1/0//0/0/0)
-0x1 -> {12}
[^\x0/] -> {11} (0x 1/0//0/0/0)
{12} perms: none
0x0 -> {13}
transchar with a negative value is out of band; only -1 is used (expr-tree.h:89-91). The header comment gives the reason: a NUL separator cannot separate data that may contain NUL (expr-tree.h:61-87).cat_with_oob_separator and for the tail separator (aare_rules.cc:69-72, aare_rules.cc:215-216); the only user is the xattr part of xmatch (parser_regex.c:597-601, parser_regex.c:615-619).oob_range records the largest out of band number seen (hfa.cc:423-424); max_range becomes 257 and ord_range 9 (hfa.cc:473-476, hfa.cc:511-514). ord_range is used only as a shift in the compress-small sort key (chfa.cc:105).. never match it (expr-tree.h:704-707, expr-tree.h:770-772).aa_dfa_outofband_transition returns DFA_NOMATCH unless the state's base entry has MATCH_FLAG_OOB_TRANSITION, then looks up offset -1 (match.c:581); it is called from aa_xattrs_match (domain.c:330, domain.c:356).xattr attachment conditional ignored and drops the condition without policy/outofband or the xattr attachment feature (parser_regex.c:472-476, parser_regex.c:549-553).-O equiv the out of band transitions are dropped (hfa.cc:1395-1402); the option is off by default.-D compressed-dfa prints an out of band entry as \xff.States created: 100 literal rules 14; /srv/**x plus 2, 4, 6, 8, 10, 14, 15 ?: 14, 38, 134, 518, 2054, 32774, 65542. Above 65534 states the parser exits with Too many states (N) for type state_t.
apparmor_parser -Q -K -D dfa-stats FILE prints three Created dfa: states N lines per profile, in the order attachment, file rules, other rule classes. The numbers here are for the file rules of profiles without an attachment, one profile per row, measured with the parser built from the AppArmor tree (the tree's abi/5.0 feature set, nothing loaded into a kernel).| Rules | States created | After merging |
|---|---|---|
/srv/a r, | 8 | 8 |
10 rules /srv/file0 to /srv/file9 | 12 | 12 |
100 rules /srv/file100 to /srv/file199 | 14 | 14 |
/srv/** r, | 8 | 8 |
/srv/**/data r, | 13 | 13 |
5 rules /srv/**/{data,cache,state,logs,tmp} r,, written separately | 25 | 25 |
the same 5 with w, plus /srv/**/*.conf r, | 31 | 31 |
/srv/** r, /srv/**.log r, /srv/**.sock r, /srv/**/lock r, | 23 | 16 |
the same four paths with r, w, rw, k | 30 | 29 |
/**/a/**/b/**/c r, | 20 | 14 |
/srv/{a,b,c}/{d,e,f}/{g,h,i} r, | 12 | 12 |
/srv/**x?? r, | 14 | 14 |
/srv/**x???? r, | 38 | 38 |
/srv/**x?????? r, | 134 | 134 |
/srv/**x???????? r, | 518 | 518 |
/srv/**x?????????? r, | 2054 | 2054 |
/srv/**x and 14 ? | 32774 | 32774 |
/srv/**x and 15 ? | 65542 | 65542, then the error |
x??? family grows as about 2^(k+1) for k question marks, and merging removes none of it.base, nameservice and user-tmp abstractions and has one rule of its own: 2387 states created, 1695 after merging.Too many states (65542) for type state_t, the exit status is 1, and the message names no profile.-O state32 lifts the limit to 16777214 states when the kernel's features list policy/state32./, or drop the fixed-length tail.A position that stays live (**) combined with a fixed-length tail makes every combination of tail positions a distinct state: about 2^(k+1). In -D dfa-stats, size is distinct node sets, dups is repeated lookups and longest is the largest set.
-D dfa-stats line (hfa.cc:525-535, counters at hfa.cc:44-58): Created dfa: states N proto { cache: size= dups= longest= avg= }, nnodes { ... }, anodes { ... }. proto counts the pairs of sets that identify a state, nnodes the sets of non-accept nodes and anodes the sets of accept nodes. size is the number of distinct entries, dups the number of insertions that found an existing entry, longest and avg the size of the sets. Many dups with a small size means the rules share structure./srv/**x?? r, alone in a profile: Created dfa: states 14 proto { cache: size=14 dups=24 longest=5 avg=2 }, nnodes { ... }, anodes { ... }. longest=5 is the set {*, x, ?1, ?2, accept}, reached after three x in a row. The 38-state member of the family, /srv/**x????, prints size=38 dups=96 longest=7 avg=3./srv/**x?????? has 134 states before and after.Created dfa: states 15 proto { cache: size=15 dups=1 longest=1 avg=0 }, nnodes { cache: size=14 dups=2 longest=1 avg=0 }, anodes { cache: size=1 dups=0 longest=1 avg=1 }
Created dfa: states 38 proto { cache: size=38 dups=40 longest=4 avg=1 }, nnodes { cache: size=38 dups=40 longest=4 avg=1 }, anodes { cache: size=3 dups=28 longest=1 avg=1 }
Created dfa: states 6 proto { cache: size=6 dups=16 longest=3 avg=1 }, nnodes { cache: size=4 dups=18 longest=3 avg=1 }, anodes { cache: size=2 dups=17 longest=1 avg=1 }
Created dfa: states 65542 ... and then Dfa minimization no states removed: partitions 65542 init 3 (accept 1) (abi/5.0 feature set).** adds a few states. Different permissions on overlapping globs keep states apart: 30 against 23 created, 29 against 16 kept.** and of x are in every state once the star has started, and ?1, ?2 and the accept node join when an x was seen one, two or three bytes back.Next: permissions in the DFA, minimisation, table compression. For profile authors: globbing, choosing abstractions. The walk: how the kernel checks an access.
Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run (-Q -K with the -D options shown), with nothing loaded into a kernel. The measured state counts were made with the tree's abi/5.0 file as the kernel feature set; the dumps of the three-rule profile are the same with that file and with a feature set that has the kernel's policy entries. "code" means the parser source, or the kernel source, was read and not run; "derived" means the result was reasoned from that code. Nothing here was observed on a running kernel.
apparmor_parser -Q -K -D dfa-stats FILE prints Created dfa: states N for each state machine of a profile: attachment, file rules, other rule classes. One profile per row, no attachment, the file-rule machine (tree).
| Rules | States created | After merging |
|---|---|---|
/srv/a r, | 8 | 8 |
10 rules /srv/file0 to /srv/file9 | 12 | 12 |
100 rules /srv/file100 to /srv/file199 | 14 | 14 |
/srv/** r, | 8 | 8 |
/srv/**/data r, | 13 | 13 |
5 rules /srv/**/{data,cache,state,logs,tmp} r,, written separately | 25 | 25 |
the same 5 with w, plus /srv/**/*.conf r, | 31 | 31 |
/srv/** r, /srv/**.log r, /srv/**.sock r, /srv/**/lock r, | 23 | 16 |
the same four paths with r, w, rw, k | 30 | 29 |
/**/a/**/b/**/c r, | 20 | 14 |
/srv/{a,b,c}/{d,e,f}/{g,h,i} r, | 12 | 12 |
/srv/**x?? r, | 14 | 14 |
/srv/**x???? r, | 38 | 38 |
/srv/**x?????? r, | 134 | 134 |
/srv/**x???????? r, | 518 | 518 |
/srv/**x?????????? r, | 2054 | 2054 |
/srv/**x and 14 ? | 32774 | 32774 |
/srv/**x and 15 ? | 65542 | 65542, then the error |
base, nameservice, user-tmp abstractions and one rule | 2387 | 1695 |
Too many states (N) for type state_t and exits with status 1 (tree). The message names no profile.-O state32 lifts the limit when the kernel's features list policy/state32 (code).| Step | Where |
|---|---|
| clear position data of shared accept nodes | hfa.cc:481-487 |
compute_pos: nullable, firstpos, lastpos, followpos | hfa.cc:489-494, rules at expr-tree.h:305-334 |
| state 0 from the empty set, state 1 from the root's firstpos | hfa.cc:489-497 |
work queue: update_state_transitions per state | hfa.cc:441-465, hfa.cc:373-427 |
add_new_state: intern the node sets, find or create the state | hfa.cc:329-371 |
| statistics | hfa.cc:522-535 |
follow per node kind (code): a CharNode or CharSetNode adds its followpos to the entries of its characters; a NotCharSetNode or AnyCharNode adds to otherwise and to every existing entry it matches.
| Field | Meaning |
|---|---|
label | the number printed as {n} in dumps |
trans | explicit transitions, a map from input character to state |
otherwise | the default target for every character not in trans |
perms | allow, deny, prompt, audit, quiet masks; computed in the constructor |
State::next(c) looks in trans and falls back to otherwise (hfa.h:319-334) (code).DFA_NOMATCH and DFA_START (match.h:17) (code).transchar with a negative value; only -1 is used (expr-tree.h:89-91) (code).max_range 257 when one is present (hfa.cc:511-514) (code).aa_dfa_outofband_transition (match.c:581), which needs MATCH_FLAG_OOB_TRANSITION on the state's base entry (code).xattr attachment conditional ignored when the kernel lacks policy/outofband or the xattr attachment feature (code).Created dfa: states N proto { cache: size= dups= longest= avg= }, nnodes { ... }, anodes { ... }
| Field | Meaning |
|---|---|
states | states created, including state 0 |
proto | pairs (non-accept set, accept set) that identify a state |
nnodes | sets of non-accept nodes |
anodes | sets of accept nodes |
size | distinct entries |
dups | insertions that found an existing entry |
longest, avg | size of the sets |
-D dfa-states-initial: the start state and each accepting state with its permission tuple (allow/deny/prompt/audit/quiet), then each state with its transitions that do not lead to state 0.-D dfa-uniq-perms: the distinct permission sets.-D dfa-node-map: the state for each pair of node sets (addresses).-D dfa-graph: Graphviz. -D dfa-progress: a status line while states are built.The complete -D dfa-states-initial dump of the file DFA of the three-rule example (tree):
{1} <== (allow/deny/prompt/audit/quiet)
{34}(0x 904241/0//0/0/0)
{35}(0x 10004/0//0/0/0)
{37}(0x 0/3800e//0/0/0)
{1} perms: none
/ 0x2f -> {2}
{2} perms: none
e 0x65 -> {3}
h 0x68 -> {4}
r 0x72 -> {5}
u 0x75 -> {6}
{3} perms: none
t 0x74 -> {7}
{4} perms: none
o 0x6f -> {8}
{5} perms: none
o 0x6f -> {9}
{6} perms: none
s 0x73 -> {10}
{7} perms: none
c 0x63 -> {11}
{8} perms: none
m 0x6d -> {12}
{9} perms: none
o 0x6f -> {13}
{10} perms: none
r 0x72 -> {14}
{11} perms: none
/ 0x2f -> {15}
{12} perms: none
e 0x65 -> {16}
{13} perms: none
t 0x74 -> {17}
{14} perms: none
/ 0x2f -> {18}
{15} perms: none
d 0x64 -> {19}
{16} perms: none
/ 0x2f -> {20}
{17} perms: none
/ 0x2f -> {21}
{18} perms: none
b 0x62 -> {22}
{19} perms: none
e 0x65 -> {23}
{20} perms: none
/ 0x2f -> {21}
[^\x0] -> {20}
{21} perms: none
\. 0x2e -> {24}
{22} perms: none
i 0x69 -> {25}
{23} perms: none
m 0x6d -> {26}
{24} perms: none
s 0x73 -> {27}
{25} perms: none
n 0x6e -> {28}
{26} perms: none
o 0x6f -> {29}
{27} perms: none
s 0x73 -> {30}
{28} perms: none
/ 0x2f -> {31}
{29} perms: none
/ 0x2f -> {32}
{30} perms: none
h 0x68 -> {33}
{31} perms: none
a 0x61 -> {34} (0x 904241/0//0/0/0)
b 0x62 -> {34} (0x 904241/0//0/0/0)
c 0x63 -> {34} (0x 904241/0//0/0/0)
d 0x64 -> {34} (0x 904241/0//0/0/0)
e 0x65 -> {34} (0x 904241/0//0/0/0)
f 0x66 -> {34} (0x 904241/0//0/0/0)
g 0x67 -> {34} (0x 904241/0//0/0/0)
h 0x68 -> {34} (0x 904241/0//0/0/0)
i 0x69 -> {34} (0x 904241/0//0/0/0)
j 0x6a -> {34} (0x 904241/0//0/0/0)
k 0x6b -> {34} (0x 904241/0//0/0/0)
l 0x6c -> {34} (0x 904241/0//0/0/0)
m 0x6d -> {34} (0x 904241/0//0/0/0)
n 0x6e -> {34} (0x 904241/0//0/0/0)
o 0x6f -> {34} (0x 904241/0//0/0/0)
p 0x70 -> {34} (0x 904241/0//0/0/0)
q 0x71 -> {34} (0x 904241/0//0/0/0)
r 0x72 -> {34} (0x 904241/0//0/0/0)
s 0x73 -> {34} (0x 904241/0//0/0/0)
t 0x74 -> {34} (0x 904241/0//0/0/0)
u 0x75 -> {34} (0x 904241/0//0/0/0)
v 0x76 -> {34} (0x 904241/0//0/0/0)
w 0x77 -> {34} (0x 904241/0//0/0/0)
x 0x78 -> {34} (0x 904241/0//0/0/0)
y 0x79 -> {34} (0x 904241/0//0/0/0)
z 0x7a -> {34} (0x 904241/0//0/0/0)
{32} perms: none
[^\x0/] -> {35} (0x 10004/0//0/0/0)
{33} perms: none
/ 0x2f -> {36}
{34} perms: (0x 904241/0//0/0/0)
[^\x0/] -> {34} (0x 904241/0//0/0/0)
{35} perms: (0x 10004/0//0/0/0)
[^\x0] -> {35} (0x 10004/0//0/0/0)
{36} perms: none
[^\x0/] -> {37} (0x 0/3800e//0/0/0)
{37} perms: (0x 0/3800e//0/0/0)
[^\x0] -> {37} (0x 0/3800e//0/0/0)-D dfa-node-map prints addresses, not node labels (hfa.cc:60-69, hfa.cc:438) (tree).(0x 904241/0//0/0/0); by title: "Debug dumps with malformed output" (tree).-O equiv out of band transitions are dropped (hfa.cc:1395-1402) (tree; the option is off by default).perms_t::operator< compares audit twice (hfa.h:151-154); no effect on the ordering (code).Filter deny, then minimize (on by default): 38 states become 22. remove-unreachable and equiv exist and are off by default.
-D stats prints Minimized dfa: final partitions N (accept A) init I (accept B) (hfa.cc:896-900): N states are left, A of them accepting; refinement started from I partitions, B of them with permissions.create_chfa: filter deny, minimize, remove unreachable, equivalence classes (aare_rules.cc:273-308).filter-deny and minimize are on; remove-unreachable and equiv are off.demo3.sd, from the parser built from the AppArmor tree with nothing loaded into a kernel. They are the same with the tree's abi/5.0 feature set and with one that has the kernel's policy entries.DFA::apply_and_clear_deny runs before minimize when filter-deny is set or the DFA has no extended permissions (aare_rules.cc:273-278). Without it the example keeps all 38 states.
int DFA::apply_and_clear_deny(void) (hfa.cc:685-693) calls the per-state function (hfa.h:349-356), which works on the permission set (hfa.h:106-130): allow &= ~deny; prompt &= ~deny; deny = 0.audit and quiet are left as computed. A plain deny has quiet bits, so its state stays accepting and does not merge into state 0; an audit deny, as in the example, has none.permstable32_version < 2 or filter-deny is set (aare_rules.cc:273-278); the flag is on by default, with a TODO to remove it (parser_common.c:125-129).-D dfa-states-initial and -D dfa-states-post-filter, parser of the AppArmor tree, feature set with the kernel's policy entries. The line for -O no-filter-deny was recorded with the tree's abi/5.0 feature set.filter-deny; with -O no-filter-deny the 16 extra states are kept and the table rows still carry no deny bit.Starting partitions: the start state alone, every other state by the content of its perms_t (hfa.cc:742-768). Example: 4 partitions, init 4 (accept 2).
void DFA::minimize(optflags const &flags) (hfa.cc:732-936). The starting partitions are made with a PermMap keyed through deref_less_than_perms (hfa.cc:729, hfa.cc:742-768): the start state alone, every other state by the content of its permission set. The non-matching state shares a partition with every other state without permissions.policy entries. The addresses change from run to run. The complete dump is in the reference under the deck.-D dfa-minimize-uniq-perms prints the permission sets seen by the minimizer (aare_rules.cc:281-282).-D dfa-minimize-partitions prints the address of the permission set (hfa.cc:720): a perms_t * is passed where the printer takes a reference.perms_t::operator< compares audit twice (hfa.h:151-154); no effect on the ordering.Refinement (hfa.cc:791-827): members that differ from the representative under same_mappings move out into a new partition, which is refined in turn; repeat until a pass makes no split. Example: 4 partitions become 22; 16 states join state 0.
same_mappings(s1, s2) (hfa.cc:643-683) returns false at once when the otherwise targets are in different partitions. Otherwise it walks the two sorted transition maps and compares the partition of each target, using the other state's otherwise where one of them has no explicit entry.Dfa minimization no states removed: partitions N ... (hfa.cc:829-836).Remap (hfa.cc:849-927): transitions go to representatives, a transition equal to otherwise is erased, non-representatives are deleted. Survivors of the example: {0} {1} {2} {3} {6} {7} {10} {11} {14} {15} {18} {19} {22} {23} {25} {26} {28} {29} {31} {32} {34} {35}.
otherwise is erased.nonmatching and start are re-pointed (hfa.cc:904-914). The stats line is printed at hfa.cc:896-900.e and u only.Minimization different permissions in same partion, a std::runtime_error (hfa.cc:881-883); the comment says it cannot happen at present.std::runtime_error is not caught by the catch (int) of create_chfa.-D dfa-states-post-minimize prints the states after this step. parser/tst/minimize.sh checks state counts for small profiles.Not merged: states with different permission sets (30 created, 29 kept), and equivalent states whose otherwise targets are in different partitions (hfa.cc:645-651; 7 states where 6 would do). States that really differ, like those of the x??? family, stay as well.
abi/5.0 feature set, one profile each (-D dfa-stats and -D stats): states created and states kept, file DFA.same_mappings returns false at once when the otherwise targets of the two states are in different partitions (hfa.cc:650-651); the comment at hfa.cc:645-649 says the function "will fail to fully minimize" in that case.[\x01-.0-\xff] is 254 explicit transitions with otherwise leading to state 0; [^/\x00], which is what ? becomes, is otherwise leading to the target with two explicit transitions to state 0. Both accept the same bytes.otherwise targets differ, so the result is not always minimal.otherwise and on which rules make a profile big.DFA::remove_unreachable (hfa.cc:590-640), only with -O remove-unreachable. On the example it changes nothing: 38 states with -O remove-unreachable -O no-minimize.
void DFA::remove_unreachable(optflags const &flags) (hfa.cc:590-640): a work queue from start over otherwise and explicit transitions; nonmatching is always kept; unreached states are erased and deleted.-O remove-unreachable (aare_rules.cc:287-291), which is off by default (parser_common.c:123-129).DFA: states N removed C unreachable states (hfa.cc:636-638). -D dfa-unreachable and -D dfa-states-post-unreachable show the result.-O remove-unreachable -O no-minimize (parser of the AppArmor tree, abi/5.0 feature set).<== start marker in the dfa-unreachable dump cannot print, since the start state is always reachable (hfa.cc:623-624).DFA::equivalence_classes and apply_equivalence_classes (hfa.cc:1300-1361, 1389-1404), only with -O equiv. The class table is a 256-byte YYTD_ID_EC table; the kernel maps each byte through it (linux:security/apparmor/match.c:486-494).
map<transchar, transchar> DFA::equivalence_classes(optflags const &flags) (hfa.cc:1300-1361) and void DFA::apply_equivalence_classes(map<transchar, transchar> &eq) (hfa.cc:1389-1404).Equiv class reduces to N classes (hfa.cc:1357-1359).YYTD_ID_EC table (chfa.cc:450-456, chfa.cc:505-507) and applied by the kernel per byte (match.c:486).profile xa /usr/bin/x* xattrs=(user.a=one user.b=tw*) with -O equiv -D equiv, parser of the AppArmor tree, abi/5.0 feature set.base, nameservice and user-tmp abstractions (1695 states, kernel features abi/5.0 plus diff-encode): 2495 next/check slots with -O equiv against 2476 without, and 44009 bytes of -S output against 42905. One profile was measured.apply_equivalence_classes re-inserts only transitions with a non-negative character (hfa.cc:1395-1402), so out of band transitions are lost. For the xa profile the default compile has 2: (12, 11) {11} -> {12} and base 536870915 for state 11; with -O equiv state 11 has base 10 and no entry to state 12. The kernel returns DFA_NOMATCH for a state without the flag (match.c:590). The option is off by default.Next: table compression. Back: permissions in the DFA, building the DFA, the backend pipeline. Tests: testing AppArmor.
minimize.sh. Matching at run time: where the kernel applies an equivalence class table.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run (-Q -K with the -D and -O options shown), with nothing loaded into a kernel. The dumps of the three-rule profile were made with a feature set that has the policy entries the kernel exports, and its state counts are the same with the tree's abi/5.0 file; the other measurements were made with abi/5.0. "code" means the parser source, or the kernel source, was read and not run; "derived" means the result was reasoned from that code. Nothing here was observed on a running kernel.
| Stage | Call in create_chfa | Runs when |
|---|---|---|
| filter deny | dfa.apply_and_clear_deny() (aare_rules.cc:273-278) | permstable32_version < 2, or filter-deny (default on) |
| minimize | dfa.minimize(opts) (aare_rules.cc:279-285) | minimize (default on) |
| remove unreachable | dfa.remove_unreachable(opts) (aare_rules.cc:287-291) | remove-unreachable (default off) |
| equivalence classes | dfa.equivalence_classes, apply_equivalence_classes (aare_rules.cc:298-308) | equiv (default off) |
All rows: code.
allow &= ~deny; prompt &= ~deny; deny = 0; audit and quiet are kept (hfa.h:106-130) (code).-O no-filter-deny 38 (Dfa minimization no states removed: partitions 38 init 5 (accept 3)) (tree).same_mappings(s1, s2): false when the otherwise targets are in different partitions; otherwise the partitions of the targets of all explicit transitions are compared (hfa.cc:643-683) (code).otherwise, delete the rest (hfa.cc:849-927) (code).| Stats line | Fields |
|---|---|
Minimized dfa: final partitions N (accept A) init I (accept B) | N states left, A accepting; I starting partitions, B with permissions |
Dfa minimization no states removed: partitions N init I (accept B) | nothing merged |
-D dfa-minimize-partitions, file DFA of the three rules (tree; the addresses change from run to run; blank lines removed):
Dumping Minimization partition mapping: Initial
[0] 0x6488b88ea3d0: {0} : {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, {13}, {14}, {15}, {16}, {17}, {18}, {19}, {20}, {21}, {22}, {23}, {24}, {25}, {26}, {27}, {28}, {29}, {30}, {31}, {32}, {33}, {36}, {37},
[1] 0x6488b88ea3d0: {1} :
[2] 0x6488b89064c0: {34} :
[3] 0x6488b8906660: {35} :
Dumping Minimization partition mapping: Pre-remap
[0] 0x6488b88ea3d0: {0} : {4}, {5}, {8}, {9}, {12}, {13}, {16}, {17}, {20}, {21}, {24}, {27}, {30}, {33}, {36}, {37},
[1] 0x6488b88ea3d0: {2} :
[2] 0x6488b88ea3d0: {3} :
[3] 0x6488b88ea3d0: {6} :
[4] 0x6488b88ea3d0: {7} :
[5] 0x6488b88ea3d0: {10} :
[6] 0x6488b88ea3d0: {11} :
[7] 0x6488b88ea3d0: {14} :
[8] 0x6488b88ea3d0: {15} :
[9] 0x6488b88ea3d0: {18} :
[10] 0x6488b88ea3d0: {19} :
[11] 0x6488b88ea3d0: {22} :
[12] 0x6488b88ea3d0: {23} :
[13] 0x6488b88ea3d0: {25} :
[14] 0x6488b88ea3d0: {26} :
[15] 0x6488b88ea3d0: {28} :
[16] 0x6488b88ea3d0: {29} :
[17] 0x6488b88ea3d0: {31} :
[18] 0x6488b88ea3d0: {32} :
[19] 0x6488b88ea3d0: {1} :
[20] 0x6488b89064c0: {34} :
[21] 0x6488b8906660: {35} :
Partitions after minimization
{0} : {4}, {5}, {8}, {9}, {12}, {13}, {16}, {17}, {20}, {21}, {24}, {27}, {30}, {33}, {36}, {37},
{2} :
{3} :
{6} :
{7} :
{10} :
{11} :
{14} :
{15} :
{18} :
{19} :
{22} :
{23} :
{25} :
{26} :
{28} :
{29} :
{31} :
{32} :
{1} :
{34} :
{35} :
{1} <== (allow/deny/prompt/audit/quiet)
{2}(0x 4/0//0/0/0)
{3}(0x 4/0//0/0/0)
{4}(0x 4/0//0/0/0)
{1} perms: none
0x2 -> {2} (0x 4/0//0/0/0)
\a 0x7 -> {2} (0x 4/0//0/0/0)
\t 0x9 -> {2} (0x 4/0//0/0/0)
\n 0xa -> {2} (0x 4/0//0/0/0)
0xe -> {2} (0x 4/0//0/0/0)
0xf -> {3} (0x 4/0//0/0/0)
0x11 -> {2} (0x 4/0//0/0/0)
0x15 -> {4} (0x 4/0//0/0/0)
0x16 -> {4} (0x 4/0//0/0/0)
\ 0x20 -> {2} (0x 4/0//0/0/0)
{3} perms: (0x 4/0//0/0/0)
0x0 -> {5}
{5} perms: none
1 0x31 -> {2} (0x 4/0//0/0/0)
Dumping Minimization partition mapping: Initial
[0] 0x6488b88fec40: {0} : {5},
[1] 0x6488b88fec40: {1} :
[2] 0x6488b88fde50: {2} : {3}, {4},
Dumping Minimization partition mapping: Pre-remap
[0] 0x6488b88fec40: {0} :
[1] 0x6488b88fec40: {5} :
[2] 0x6488b88fec40: {1} :
[3] 0x6488b88fde50: {2} : {4},
[4] 0x6488b88fde50: {3} :
| Label | Row in the packed tables | Path so far |
|---|---|---|
| {0} | 0 | no match; also the 16 states of the deny rule |
| {1} | 1 | start |
| {2} | 2 | / |
| {3} {7} {11} {15} {19} {23} {26} {29} | 3 5 7 9 11 13 15 17 | /e to /etc/demo |
| {32} | 19 | /etc/demo/ |
| {35} | 21 | /etc/demo/ plus one or more characters |
| {6} {10} {14} {18} {22} {25} {28} | 4 6 8 10 12 14 16 | /u to /usr/bin |
| {31} | 18 | /usr/bin/ |
| {34} | 20 | /usr/bin/ plus a lower-case letter and any non-slash characters |
| Rules | Created | Kept |
|---|---|---|
/srv/** r, /srv/**.log r, /srv/**.sock r, /srv/**/lock r, | 23 | 16 |
the same four paths with r, w, rw, k | 30 | 29 |
/**/a/**/b/**/c r, | 20 | 14 |
base, nameservice, user-tmp abstractions and one rule | 2387 | 1695 |
/srv/**x?????? r, | 134 | 134 |
100 rules /srv/file100 to /srv/file199 | 14 | 14 |
/a[\x01-.0-\xff]z r, and /b?z r, | 7 | |
/a?z r, and /b?z r, | 6 |
Tree, abi/5.0.
otherwise and explicit transitions; state 0 is always kept; the rest is erased (hfa.cc:590-640) (code).-O remove-unreachable; stats DFA: states N removed C unreachable states (code). On the example it removes nothing (tree).YYTD_ID_EC table; the kernel maps every input byte through it (match.c:486) (code).-O equiv -D equiv, for profile xa /usr/bin/x* xattrs=(user.a=one user.b=tw*) (tree):DFA equivalence class (eq): 1: / 2: u ... 9: \x0
-S against 42905 (tree, abi/5.0 plus diff-encode).| Option | Shows |
|---|---|
dfa-states-post-filter | the states after filter deny |
dfa-states-post-minimize | the states after the remap |
dfa-states-post-unreachable | the states after remove_unreachable |
dfa-minimize-partitions | Initial, Pre-remap, Partitions after minimization |
dfa-minimize-uniq-perms | the permission sets seen by the minimizer |
dfa-unreachable | the states that were removed |
equiv, equiv-stats | the class table and the number of classes |
Minimization different permissions in same partion: a std::runtime_error (hfa.cc:881-883); the source comment says it cannot happen at present (code).otherwise targets differ are not merged (hfa.cc:645-651) (tree).-O equiv out of band transitions are dropped (hfa.cc:1395-1402) (tree).-D dfa-minimize-partitions prints addresses of permission sets (hfa.cc:720) (tree).perms_t::operator< compares audit twice (hfa.h:151-154) (code).-D dfa-minimize is accepted and has no effect (code).dfa-unreachable dump cannot print (hfa.cc:623-624) (code).-O equiv reduces the table of any profile. Measured on two profiles, and the arrays grew on both: the three-rule example from 277 to 288 next/check slots, and the 1695-state profile from 2476 to 2495. In the example the 256-slot tail past the highest base stays, and with every entry in columns 1 to 15 the combs collide more, so the highest base rises from 21 to 32; see How the tables are packed.22 states × 256 byte values would be 5632 cells; the packed next and check arrays of the example have 277 slots. Each lab under a slide works on tables unpacked from the compiled policy.
demo3.sd): 38 states after subset construction, 22 after minimization, 277 next/check slots. The statistics line of the parser: Compressed trans table: states 22, next/check 277, optimal next/check 50 avg/state 12.59, compression 1240/11264 = 88.99 % (chfa.cc:201-208).-S, with a feature set that has the policy entries the kernel exports; nothing was loaded into a kernel.tools/packing-demo.py in the map's repository. It unpacks the tables as the kernel does, compares them with the parser's -D compressed-dfa dump, and replays the packer: a port of insert_state gives the same base for every state and the same two arrays.The full table of the example, drawn from the real data: 5632 cells, 4825 of them leading to state 0. Only 49 cells differ from the rest of their row.
match_char (match.c:443-455): pos = base[state] + byte; next[pos] if check[pos] == state, else default[state]./etc/demo/ matched) has default 21; state 21 (the ** loop) has default 21; state 20 (the [a-z]* loop of /usr/bin/) has default 20. Every other state has default 0./usr/bin/ matched): a to z lead to state 20.-S, with a feature set that has the policy entries the kernel exports; nothing was loaded into a kernel. Kernel statements are read from the kernel source and were not run.Each state keeps a default state and only the entries that differ from it. For the example that is 49 entries instead of 5632 cells: most states have one, state 19 two, state 18 twenty-six.
otherwise state, "the default state for transitions not in trans" (hfa.h:296); the table's default is that otherwise, or the non-matching state when there is none (chfa.cc:241-250).e, u); state 18 twenty-six (a to z); states 19 and 20 two each (the NUL byte and /, both to state 0); state 21 one (the NUL byte, to state 0). State 0 has none./etc/demo/. Its first ** byte may be anything except / and NUL, which is why those two are its exceptions.-S, with a feature set that has the policy entries the kernel exports; nothing was loaded into a kernel.** and [a-z] match.CHFA::insert_state places each state's entries at the first offset, the base, where all of them land on free slots. next holds the target of a slot and check its owner.
insert_state (chfa.cc:238-317) walks the free slots from the first one that is at least the row's first byte, and fits_in (chfa.cc:214-233) tests whether every entry of the row lands on a free slot there; a slot past the end counts as free, because the arrays grow.-O compress-small sorts them by number of transitions instead; the lab uses the default order.-S, with a feature set that has the policy entries the kernel exports; nothing was loaded into a kernel.The arrays are always the highest base plus 256 slots long, because the kernel requires base + 255 to be inside for every state: 21 + 256 = 277. In the example 50 slots are in use.
base + 255 stays inside (chfa.cc:268-287); the kernel rejects a table where it does not, with AppArmor DFA next/check upper bounds error (match.c:188-191), a check made when paranoid load is on.optimal next/check 50 is computed differently, as 2 plus the entries of every state except the start state (chfa.cc:91-98): 2 + 48. The two numbers agree whenever the start state has exactly one entry, as it has here (its /).-S, with a feature set that has the policy entries the kernel exports; nothing was loaded into a kernel. Kernel statements are read from the kernel source and were not run.pos = base[s] + c; if check[pos] == s the next state is next[pos], otherwise default[s]. State 17 reading / owns slot 51; state 19 reading m lands on slot 114, owned by state 6, and takes its default.
match_char is at match.c:443-455; the offset is the low 24 bits of the base entry (match.c:23)./etc/demo/motd on this machine: states 1, 2, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 21, 21, 21. The first ten bytes each hit a slot their state owns. m in state 19 lands on slot 114, which state 6 (/us) owns for r. In state 21, whose base is 1, o lands on the empty slot 112, t on slot 117, which state 2 owns for u, and d on slot 101, which state 2 owns for e. Each is a miss, and the default, 21, applies./ at slot 51; there next gives state 20.-S, with a feature set that has the policy entries the kernel exports; nothing was loaded into a kernel. Kernel statements are read from the kernel source and were not run.-O equiv maps the 256 byte values of the example to 16 classes, so a full table would have 352 cells. Packed, the arrays grow from 277 to 288 slots, and a 256-byte class table is added. The option is off by default.
DFA::equivalence_classes (hfa.cc:1300-1361) numbers the classes from 1; bytes that no transition names stay in class 0. For the example: Equiv class reduces to 15 classes, and 228 bytes in class 0./; 2 e; 3 u; 4 t; 5 s; 6 c; 7 r; 8 d; 9 b; 10 i; 11 m; 12 n; 13 o; 14 the other fourteen lower-case letters; 15 the NUL byte.Compressed trans table: states 22, next/check 288, optimal next/check 37, against 277 and 50 without the option. State 18 stores 13 entries instead of 26, but the highest base rises from 21 to 32, and the bound of 256 slots past the base does not change with the option (hfa.cc:473-474). The -S output grows from 5009 to 5905 bytes: each of the three DFAs of the profile gets a class table.-O equiv out of band transitions are dropped, so xattrs= conditions cannot match; see Minimisation.-O equiv -D equiv, feature set with the kernel's policy entries. Kernel statements are read from the kernel source and were not run.DFA::diff_encode stores a state as its differences from a shallower state. For /srv/**x?? r, states 10 to 13 keep no entries and name 6 to 9 as their default: 264 slots become 260. The three-rule example has no state that gains from it.
DFA::diff_encode (hfa.cc:1014-1113) picks for each state the candidate with the highest positive diff_weight (hfa.cc:128-219); make_relative (hfa.cc:228-268) then erases the entries the two share and sets the flag.Diff encode states: 4 of 14 reached @ depth 9. 11 trans removed; {6} <- {10}, {7} <- {11}, {8} <- {12}, {9} <- {13}. Base of states 10 to 13: 2147483648, which is 0x80000000, the flag with offset 0. Without the option (-O no-diff-encode): 264 slots, 28 in use; with it: 260 slots, 17 in use.MATCH_FLAG_DIFF_ENCODE continues in default[state] with the same byte (match.c:443-455). The parser's comment gives the bound: at most 2m lookups for m bytes (hfa.cc:985-1012).Diff encode states: 0 of 22 (derived from the code, not printed): candidates are the shallower states that lead to the same targets (hfa.cc:1049-1067). The states along /etc/demo and /usr/bin, up to states 18 and 19, each lead to a state nothing else leads to, so they have no candidate. State 20 has the candidate 18, but their defaults differ (20 and 0), so each of the 228 bytes neither state names would need a masking entry: the weight is -226. State 21 has the candidate 19: they share the entry for NUL (+1), and 21 would need an entry to mask 19's entry for / (-1). The weight is 0, and only a positive weight is taken (hfa.cc:959-975).policy/diff-encode; see Table compression.policy entries. Kernel statements are read from the kernel source and were not run.First fit leaves almost no holes in a large table, so the arrays are about one slot per stored entry plus 256. What varies between profiles is the number of entries per state: 2 for **, 26 for [a-z], none for a diff-encoded twin.
policy entries:| Profile | States | Full table | Entries | Slots | In use | Diff encoded |
|---|---|---|---|---|---|---|
| the three-rule example | 22 | 5632 | 49 | 277 | 50 | 0 |
/srv/**x?? r, with -O no-diff-encode | 14 | 3584 | 27 | 264 | 28 | - |
/srv/**x?? r, | 14 | 3584 | 16 | 260 | 17 | 4 |
/srv/**x?????? r, with -O no-diff-encode | 134 | 34304 | 387 | 625 | 388 | - |
/srv/**x?????? r, | 134 | 34304 | 196 | 440 | 197 | 64 |
base, nameservice, user-tmp and one rule, -O no-diff-encode | 1695 | 433920 | 2982 | 3198 | 2983 | - |
| the same with diff encoding | 1695 | 433920 | 2256 | 2476 | 2257 | 395 |
/ and a.? rule without diff encoding and 1.46 with it; 1.76 and 1.33 for the three abstractions.-O compress-small, which changes the order in which rows are placed.x followed by ? doubles the states. Globbing.Next: table compression for the reference, how the kernel checks an access for the walk, minimisation for the states, the binary policy format for the stream, matching at run time for the kernel code.
tools/packing-demo.py.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run with -S -K -D compressed-dfa -D stats and the options shown, with a feature set that has the policy entries the kernel exports and nothing loaded into a kernel; the tables were then unpacked from the -S output. "code" means the parser source, or the kernel source, was read and not run; "derived" means the result was computed from those tables or reasoned from that code. Nothing here was observed on a running kernel. Table compression is the reference for the table formats; this page holds the numbers the lab works with.
abi <abi/5.0>,
include <tunables/global>
profile demo /usr/bin/demo {
/etc/demo/** r,
audit deny @{HOME}/.ssh/** rw,
/usr/bin/[a-z]* ix,
}
| What | Value | Basis |
|---|---|---|
| states of the file DFA | 22 | tree |
| cells of a full table, 22 × 256 | 5632 | derived |
| cells that lead to state 0 | 4825 | derived |
| cells equal to their row's default | 5583 | derived |
| stored entries | 49 | derived |
| slots in next and in check | 277 | tree |
| slots in use | 50: the 49 entries and slot 0 | derived |
| highest base | 21 | tree |
Compressed trans table: states 22, next/check 277, optimal next/check 50 avg/state 12.59, compression 1240/11264 = 88.99 % (tree). optimal is 2 plus the entries of every state except the start state (chfa.cc:91-98): 2 + 48 (code).
| State | Read so far | Default | Base | Entries |
|---|---|---|---|---|
| 0 | no match | 0 | 0 | none; slot 0 is placed by hand |
| 1 | start | 0 | 0 | / to 2 |
| 2 | / | 0 | 0 | e to 3, u to 4 |
| 3 | /e | 0 | 0 | t to 5 |
| 4 | /u | 0 | 0 | s to 6 |
| 5 | /et | 0 | 0 | c to 7 |
| 6 | /us | 0 | 0 | r to 8 |
| 7 | /etc | 0 | 1 | / to 9 |
| 8 | /usr | 0 | 2 | / to 10 |
| 9 | /etc/ | 0 | 0 | d to 11 |
| 10 | /usr/ | 0 | 0 | b to 12 |
| 11 | /etc/d | 0 | 1 | e to 13 |
| 12 | /usr/b | 0 | 0 | i to 14 |
| 13 | /etc/de | 0 | 0 | m to 15 |
| 14 | /usr/bi | 0 | 0 | n to 16 |
| 15 | /etc/dem | 0 | 0 | o to 17 |
| 16 | /usr/bin | 0 | 3 | / to 18 |
| 17 | /etc/demo | 0 | 4 | / to 19 |
| 18 | /usr/bin/ | 0 | 21 | a to z, all to 20 |
| 19 | /etc/demo/ | 21 | 5 | NUL to 0, / to 0 |
| 20 | /usr/bin/ and a lower-case letter | 20 | 6 | NUL to 0, / to 0 |
| 21 | /etc/demo/ and one more byte | 21 | 1 | NUL to 0 |
Tree; the "read so far" column is derived (the shortest input that reaches the state).
base + 255 is inside for every state (chfa.cc:138, chfa.cc:268-287) (code). In all eight tables measured the length is exactly 256 plus the highest base (tree).tools/packing-demo.py in the map's repository).pos = base[s] + c; if check[pos] == s the next state is next[pos], otherwise default[s]; with a diff-encoded state a miss continues in default[s] with the same byte (match.c:443) (code).
/etc/demo/motd, byte by byte (derived):
| State | Byte | Slot | check | Result |
|---|---|---|---|---|
| 1 | / | 47 | 1 | next: 2 |
| 2 | e | 101 | 2 | next: 3 |
| 3 | t | 116 | 3 | next: 5 |
| 5 | c | 99 | 5 | next: 7 |
| 7 | / | 48 | 7 | next: 9 |
| 9 | d | 100 | 9 | next: 11 |
| 11 | e | 102 | 11 | next: 13 |
| 13 | m | 109 | 13 | next: 15 |
| 15 | o | 111 | 15 | next: 17 |
| 17 | / | 51 | 17 | next: 19 |
| 19 | m | 114 | 6 | default: 21 |
| 21 | o | 112 | 0 | default: 21 |
| 21 | t | 117 | 2 | default: 21 |
| 21 | d | 101 | 2 | default: 21 |
| by byte | with -O equiv | |
|---|---|---|
| columns of a full table | 256 | 16 (classes 0 to 15) |
| cells of a full table | 5632 | 352 |
| stored entries | 49 | 36 |
| highest base | 21 | 32 |
| slots | 277 | 288 |
-S output of the profile | 5009 bytes | 5905 bytes |
Tree: Equiv class reduces to 15 classes; Compressed trans table: states 22, next/check 288, optimal next/check 37 .... Classes: 1 /; 2 e; 3 u; 4 t; 5 s; 6 c; 7 r; 8 d; 9 b; 10 i; 11 m; 12 n; 13 o; 14 a f g h j k l p q v w x y z; 15 NUL; 0 the other 228 bytes. The bound of 256 slots past the base is not changed by the option (hfa.cc:473-474) (code).
/srv/**x?? r,| State | Read so far | accept | Without: default, entries | With: default, entries |
|---|---|---|---|---|
| 6 | /srv/ | 0 | 6; NUL to 0, x to 7 | the same |
| 7 | /srv/x | 0 | 8; NUL to 0, / to 6, x to 9 | the same |
| 8 | /srv/x and one byte | 0 | 10; NUL to 0, / to 6, x to 11 | the same |
| 9 | /srv/xx | 0 | 12; NUL to 0, / to 6, x to 13 | the same |
| 10 | /srv/x and two bytes | 2 | 6; NUL to 0, x to 7 | 6, flag; none |
| 11 | /srv/x, a byte, x | 2 | 8; NUL to 0, / to 6, x to 9 | 7, flag; none |
| 12 | /srv/xx and a byte | 2 | 10; NUL to 0, / to 6, x to 11 | 8, flag; none |
| 13 | /srv/xxx | 2 | 12; NUL to 0, / to 6, x to 13 | 9, flag; none |
Tree: Diff encode states: 4 of 14 reached @ depth 9. 11 trans removed; 264 slots and 28 in use without (-O no-diff-encode), 260 and 17 with. The three-rule example: Diff encode states: 0 of 22 reached @ depth 12. 0 trans removed (tree); the reason is in the details of the scene "Like that state, except" (derived).
| Profile | States | Full table | Entries | Per state | Slots | Full to the last used slot | Diff encoded |
|---|---|---|---|---|---|---|---|
| the three-rule example | 22 | 5632 | 49 | 2.23 | 277 | 35 % | 0 |
/srv/**x?? r,, -O no-diff-encode | 14 | 3584 | 27 | 1.93 | 264 | 22 % | - |
/srv/**x?? r, | 14 | 3584 | 16 | 1.14 | 260 | 14 % | 4 |
/srv/**x?????? r,, -O no-diff-encode | 134 | 34304 | 387 | 2.89 | 625 | 79 % | - |
/srv/**x?????? r, | 134 | 34304 | 196 | 1.46 | 440 | 65 % | 64 |
base, nameservice, user-tmp and one rule, -O no-diff-encode | 1695 | 433920 | 2982 | 1.76 | 3198 | 98 % | - |
| the same | 1695 | 433920 | 2256 | 1.33 | 2476 | 97 % | 395 |
States, slots and diff encoded states: tree. The other columns: derived from the tables.
-O compress-small on these tables.-O equiv reduces the arrays of any profile; two were measured (this example, and the 1695-state profile in Minimisation), and both grew.Accept nodes become five masks per state, and the masks become rows of a permission table. Rule priority and the deny mask are resolved in the parser and are not in the compiled policy.
demo3.sd):abi <abi/5.0>,
include <tunables/global>
profile demo /usr/bin/demo {
/etc/demo/** r,
audit deny @{HOME}/.ssh/** rw,
/usr/bin/[a-z]* ix,
}
-D rule-exprs (parser of the AppArmor tree; the same with the tree's abi/5.0 feature set and with one that has the kernel's policy entries):rule: /etc/demo/[^/\x00][^\x00]* -> ... priority=0 (0x10004/0)< 0x10004> rule: /usr/bin/[a-z][^/\x00]* -> ... priority=0 (0x804201/0)< 0x804201> rule: (/home/[^/\x00]*|/root)/\.ssh/[^/\x00][^\x00]* -> ... priority=0 deny (0x3800e/0)< 0x3800e>
UniquePermsCache::insert picks DenyMatchFlag, PromptMatchFlag, ExactMatchFlag or MatchFlag (aare_rules.h:78-101). For a deny node the second mask is quiet: deny /b w, is (0x2800a/2800a), audit deny /c w, is (0x2800a/0).
Node *insert(int priority, rule_mode_t mode, perm32_t perms, perm32_t audit, bool exact_match) on UniquePermsCache (aare_rules.h:78-101); the key is UniquePerm (aare_rules.h:39-59).DenyMatchFlag is the quiet mask (expr-tree.h:1193).ImportantNode with an empty follow set (expr-tree.h:1118-1121, expr-tree.h:1144-1148).perms without the link and change_profile bits, and the same mask as the second argument unless the rule says audit; an allow or prompt rule passes perms as the second argument when the rule says audit. The inversion for deny is in the front end (rule.h:430-433).< 0x3800e> prints the permission mask only (expr-tree.h:1157).0x2800a is write with its implied append in both halves.Score per bit: priority << 2 plus 3 (deny), 2 (exact node on an exec bit), 1 (allow), 0 (prompt) (hfa.cc:1536-1554). Lower is skipped, higher clears and replaces, equal accumulates. This is the last use of priority.
perms_t::perms_t (hfa.cc:1661-1708, declared at hfa.h:54) and pri_update_perm (hfa.cc:1529-1654). The steps:MIN_INTERNAL_PRIORITY*4, which is -4004 (hfa.cc:1665);perms | audit are visited; for the file DFA the exec type bits are not scored as bits of their own (hfa.cc:1683-1685);priority << 2 plus 3 for a deny node, 2 for an exact node on an exec bit, 1 for any other allow, 0 for a prompt node (hfa.cc:1537-1554);deny and quiet and clears allow, audit and prompt; exact replaces the exec type bits and sets allow and audit; allow sets allow and audit; prompt sets prompt and audit.perm32_t mask = 1 << i with i up to 31 shifts a signed int into the sign bit (hfa.cc:1533); no wrong result is known./etc/demo/override.conf: glob allow 1, priority=10 allow 41, deny 3: the deny is skipped for the write bit. Other *.conf files: (0x 10004/2800a//0/0/2800a), write denied and quiet.
/etc/demo/** rw,, deny /etc/demo/*.conf w,, priority=10 allow /etc/demo/override.conf w,. The trace is from -D dfa-perms-build, parser of the AppArmor tree, abi/5.0 feature set. The slide leaves out the pointer that begins each line as printed:0x62eb090db8e0[1]=1 vs. 41 mask: 2 xmask: 0 amask: 2 0x62eb090db8e0[1]=1 < 41 clearing mask: 2 from 3800e/0 -> 3800c/0 0x62eb090db8e0[1]=41 <= 41 exact 2/0 0x62eb090dcbb0[1]=41 vs. 3 mask: 2 xmask: 0 amask: 2 0x62eb090dcbb0[1]=41 > 3 SKIPPING 2800a/2800a
-D expr-tree dump. Two later runs (one with a feature set that has the kernel's policy entries, one with abi/5.0) took the deny first: [1]=-4004 vs. 3, then [1]=3 vs. 41 with clearing mask: 2 from 0/0 -> 0/0, then [1]=41 > 1 SKIPPING 3800e/0 for the glob allow. -4004 is the start value of a register. The computed set is (0x 3800e/0//0/0/0) in every order.[1] is the bit number: bit 1 is write. The lines are printed at hfa.cc:1558-1651 and hfa.cc:1670-1702.*.conf file the dump has clearing mask: 2 from 3800e/0 -> 3800c/0, then deny 2/2, and the state is (0x 10004/2800a//0/0/2800a). The tuple is allow/deny/prompt/audit/quiet, printed with a blank after 0x and a doubled slash. 0x2800a is write with its implied append in both halves.dfa-perms-build lines for the implied mmap bit have no line end (hfa.cc:1505, hfa.cc:1509, hfa.cc:1517, hfa.cc:1521).An ExactMatchFlag scores priority*4 + 2 on exec bits and replaces the glob's exec type (hfa.cc:1549-1551, 1606-1625). Rows: glob 0x10201 ... i0, demo-helper 0x201 ... p0.
/usr/bin/[a-z]* ix, and /usr/bin/demo-helper Px -> demo-helper,. The table is from -D compressed-dfa, parser of the AppArmor tree, abi/5.0 feature set; the dump has six rows (owner and other for each of three sets), and the slide shows one row of each pair.ExactMatchFlag on an exec bit scores one more than a plain allow (hfa.cc:1549-1551); it clears what the glob rule set for the exec bit and its type bits and installs its own (hfa.cc:1606-1625).add_rule_vec (aare_rules.cc:98-105): a character class is not a wildcard for this test, ? is.0x10201 is AA_MAY_EXEC, AA_MAY_GETATTR and AA_EXEC_MMAP (0x10000). The xindex i0 is AA_X_INHERIT with index 0; p0 is a table transition to entry 0 (policy_compat.cc:48-49, policy_compat.cc:143-144, perms.h:130-148).ix is added unless a higher score already decided that bit (hfa.cc:1497-1524, hfa.cc:1697-1699).parser/tst/simple_tests/xtrans/minimize-x-conflict.sd (/b px,, /* Pixr,, /a Cx -> foo,, #=EXRESULT PASS) passes because the exact rules dominate the glob.Overlapping patterns: profile has merged rule with conflicting x modifiers from perms_t::perms_t (hfa.cc:1703-1707), exit status 255. Identical paths: profile t: has merged rule /usr/bin/demo with conflicting x modifiers from the front end (parser/block_rules.cc:325), exit status 1.
is_merged_x_consistent compares the exec type bits (hfa.cc:1610-1615, hfa.cc:1632-1637, hfa.cc:1643-1648; the function is at immunix.h:171-186). A difference makes the constructor print the message and throw (hfa.cc:1703-1707); the caller then prints ERROR processing regexs for profile t, failed to load (parser_regex.c:1277).abi/5.0 feature set), in a profile named t. The complete messages:profile has merged rule with conflicting x modifiers ERROR processing regexs for profile t, failed to load
profile t: has merged rule /usr/bin/demo with conflicting x modifiers ERROR merging rules for profile t, failed to load
apply_and_clear_deny: allow &= ~deny; prompt &= ~deny; deny = 0 (hfa.h:106-130). The table writer never sets a deny bit (policy_compat.cc:160-244): deny reaches the kernel as "absent from allow" plus, for a plain deny, a quiet bit.
perm32_t allow, deny, prompt, audit, quiet (hfa.h:176).apply_and_clear_deny (hfa.h:106-130): allow &= ~deny; prompt &= ~deny; allow |= deny & AA_COMPAT_CONT_MATCH; deny = 0. Audit and quiet are not changed. It returns true when the state is no longer accepting.permstable32_version < 2); otherwise when filter-deny is set, which is the default, with a TODO to remove it (aare_rules.cc:273-278, parser_common.c:125-129).-D dfa-uniq-perms (parser of the AppArmor tree, abi/5.0 feature set; the path notes are added here):allow:0 deny:0 audit:0 quiet:0 prompt:10004 /d prompt /d r, allow:0 deny:2800a audit:0 quiet:0 prompt:0 /c audit deny /c w, allow:0 deny:2800a audit:0 quiet:2800a prompt:0 /b deny /b w, allow:10004 deny:0 audit:10004 quiet:0 prompt:0 /a audit /a r, allow:10004 deny:2800a audit:0 quiet:2800a prompt:0 /e /e rw, and deny /e w,
-O no-filter-deny gives 12 rows and 8 states. The deny column is 0 in both. For the three-rule example it is 22 states against 38./e rw, and deny /e w,, run with a feature set that has the kernel's policy entries: state {3}(0x 10004/2800a//0/0/2800a), Perms Table size: 6, the state's row (0x244/0x0/0x0//0x0/0x317a//0) at accept index 2, and rows 2 to 5 all equal. Quiet 0x317a is the write bit after the same expansion that turns read into 0x244.aa_perms::deny (policy_compat.cc:160-190, policy_compat.cc:199-244); map_perms_to_accept does not pass the deny mask on (hfa.h:132-138).unpack_perm reads a deny field (policy_unpack.c:911) and verify_perm rejects a row with a bit in both allow and deny (policy_unpack.c:1511).filter-deny.-O filter-deny leaves unused duplicate permission table entries"; "Kernel: an audit deny file rule in a complain-mode profile is allowed and logged ALLOWED"; "A deny block around an audit deny rule drops the audit".filter-deny is still the default; whether the kernel treats quiet without deny as the compiler assumes in every hook.map_perms_to_accept: accept1 = allow, accept2 = PACK_AUDIT_CTL(audit, quiet), accept3 = prompt (hfa.h:132-138). File layout of accept1: bits 0-6 and 14-20 permissions, 7-13 and 21-27 exec type and index, 30 onexec, 31 change_profile.
map_perms_to_accept (hfa.h:132-138): accept1 = allow, accept2 = PACK_AUDIT_CTL(audit, quiet), accept3 = prompt.PACK_AUDIT_CTL keeps bits 0-6 and 14-20 of each mask and puts quiet 7 bits higher (immunix.h:123-127).permstable32_version < 2: the accept table holds accept1 and the accept2 table holds accept2 (chfa.cc:129-137, chfa.cc:160-164)./usr/bin/demo (decoded from the -S output made with a feature set that has the kernel's policy entries).perms struct both tables are expected (policy_unpack.c:1002); the kernel builds its permission table with aa_compat_map_xmatch, aa_compat_map_policy or aa_compat_map_file (policy_compat.c:302) and rewrites the accept table to state numbers (remap_dfa_accept, policy_compat.c:288).policy/perms_compatprompt, parser_main.c:1768).compute_perms_table (hfa.cc:1423-1458): one aa_perms row per unique permission set, two for the file DFA. Example: 8 rows; state {35} has accept 4 (0x244), state {34} accept 6 (0x10201, i0). Each row is computed through the three accept words of the older format (hfa.cc:1412-1420).
compute_perms_table (hfa.cc:1423-1458) and compute_perms_table_ent (hfa.cc:1412-1420). The table has uniq_perms.size() rows, times 2 for the file DFA (hfa.cc:1427-1432). Row 0 (and 1) is the set of the non-matching state; the others follow the order of uniq_perms (hfa.cc:1437-1442). The start and non-matching states get index 0 (hfa.cc:1433-1435, hfa.cc:1445-1457).-D compressed-dfa, parser of the AppArmor tree; it is the same with the tree's abi/5.0 feature set and with one that has the kernel's policy entries. As printed, every row continues with accept1: 0x, accept2: 0x; the row numbers are added on the slide.map_old_perms (policy_compat.cc:41-65, policy_compat.cc:127-190): read adds getattr and open; write adds setattr, create, delete, chmod, chown and open; 0x10 is link; 0x20 is lock and link subset; 0x40 is exec mmap; AA_MAY_GETATTR is always set; bit 31 is AA_MAY_CHANGE_PROFILE and bit 30 AA_MAY_ONEXEC; xindex comes from the exec type bits.map_other, AA_MAY_LOCK is always added, AA_COMPAT_CONT_MATCH becomes AA_CONT_MATCH. The two policydb rows of the example are 0x8000 and 0x8004.permstable32_version >= 2; version 1 is treated as absent (aare_rules.cc:200, aare_rules.cc:318-320, parser_main.c:1779-1784). With version 3 the file DFA also writes accept2 = 1 on every state except 0 and 1 (chfa.cc:118-122, chfa.cc:158-159).prompt &= ~(allow | deny) is applied per file row and not for policydb rows (policy_compat.cc:172, policy_compat.cc:188). The fields subtree, cond, kill, complain, hide, tag and label are always 0 from this compiler.unpack_perms_table (policy_unpack.c:901), aa_lookup_perms (policy.h:156), aa_lookup_condperms, which adds 1 for a non-owner when accept2 has ACCEPT_FLAG_OWNER (file.c:194), and verify_perm (policy_unpack.c:1511).permission not in permission table map and permission not in idx table map, thrown as std::runtime_error (hfa.cc:1452-1454).-O filter-deny leaves unused duplicate permission table entries".std::runtime_errors are not caught by create_chfa.Next: minimisation, table compression, the binary policy format. The language side: rule priority, allow and deny, the audit qualifier, exec modes. The kernel side: matching at run time.
priority*4 + kind; an exact rule wins an exec bit over a glob of the same priority; equal scores with different exec modes are an error; deny is folded into allow before the answer is written as a table row or as the old accept words.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run (-Q -K with the -D and -O options shown), with nothing loaded into a kernel. The dumps were made with the tree's abi/5.0 file as the kernel feature set unless a row says "kernel policy entries", which means a feature set with the policy entries the kernel exports; the permission table of the three-rule example is the same under both. "code" means the parser source, or the kernel source, was read and not run; "derived" means the result was reasoned from that code. Nothing here was observed on a running kernel.
Key: (priority, mode, exact, perms, audit) (aare_rules.h:39-59) (code).
| Class | Chosen when (tested in this order) | Kind in the score |
|---|---|---|
DenyMatchFlag | the rule is a deny rule | 3 |
PromptMatchFlag | the rule is a prompt rule | 0 |
ExactMatchFlag | an allow rule whose tree has no star, plus, any-char or negated set | 2 on exec bits, 1 otherwise |
MatchFlag | any other allow rule | 1 |
| Rule | perms argument | second argument |
|---|---|---|
| allow | the permissions | the permissions when the rule says audit, else 0 (audit) |
| prompt | the permissions | the permissions when the rule says audit, else 0 (audit) |
deny | the permissions, without the link and change_profile bits | the same mask (quiet) |
audit deny | the same | 0 (not quiet) |
Code: aare_rules.h:78-101, parser_regex.c:675-690. Tree: deny /b w, prints deny (0x2800a/2800a), audit deny /c w, prints deny (0x2800a/0).
score = priority*4 + kind, per permission bit (hfa.cc:1537-1554) (code).| Kind | Sets | Clears |
|---|---|---|
| deny | deny, quiet (from the node's second mask) | allow, audit, prompt |
| exact, on an exec bit | allow, audit, and the exec type bits | the exec type bits of the loser |
| allow | allow, audit | |
| prompt | prompt, audit |
ix adds the mmap bit unless a higher score already decided that bit (hfa.cc:1497-1524) (code).| Mask | Meaning |
|---|---|
| allow | permitted |
| deny | refused by a deny rule |
| prompt | ask user space |
| audit | log when used |
| quiet | do not log the denial |
Dumps print the tuple as (0x 10004/2800a//0/0/2800a): allow/deny/prompt/audit/quiet, with a blank after 0x and a doubled slash (hfa.h:58-68). Six rules in one profile, -D dfa-uniq-perms (tree; path notes added):
allow:0 deny:0 audit:0 quiet:0 prompt:10004 /d prompt /d r, allow:0 deny:2800a audit:0 quiet:0 prompt:0 /c audit deny /c w, allow:0 deny:2800a audit:0 quiet:2800a prompt:0 /b deny /b w, allow:10004 deny:0 audit:10004 quiet:0 prompt:0 /a audit /a r, allow:10004 deny:2800a audit:0 quiet:2800a prompt:0 /e /e rw, and deny /e w,
? is not (aare_rules.cc:98-105) (code).is_merged_x_consistent (immunix.h:171-186) compares the exec type bits before an exec bit that is already allowed is set again (code).parser/tst/simple_tests/xtrans/minimize-x-conflict.sd.allow &= ~deny; prompt &= ~deny; allow |= deny & AA_COMPAT_CONT_MATCH; deny = 0 (hfa.h:106-130) (code).permstable32_version < 2, so always for xmatch; otherwise on by default (aare_rules.cc:273-278) (code).| Profile | Default | -O no-filter-deny |
|---|---|---|
| the six rules above | 16 table rows, 7 states | 12 table rows, 8 states |
| the three-rule example | 22 states | 38 states |
Tree. The deny column of the table is 0 in every case.
| Bits of accept1 (file DFA) | Meaning |
|---|---|
| 0-6 | owner permissions |
| 7-13 | owner exec type and table index |
| 14-20 | other permissions |
| 21-27 | other exec type and table index |
| 30 | onexec |
| 31 | change_profile |
accept2 = PACK_AUDIT_CTL(audit, quiet): bits 0-6 and 14-20 of audit in place, the same bits of quiet 7 higher (immunix.h:123-127) (code). accept3 = prompt is computed and not written (code).perms_t through accept1, accept2 and accept3 and then through compute_fperms_user and compute_fperms_other to an aa_perms row (compute_perms_table_ent, hfa.cc:1412-1420), so a row can say only what the old words could (code).| Old bit | New bits in the row |
|---|---|
| read 0x4 | read, getattr, open |
| write 0x2 | write, setattr, create, delete, chmod, chown, open |
| 0x10 | link |
| 0x20 | lock, link subset |
| 0x40 | exec mmap |
| exec 0x1 | exec, with xindex from the exec type bits |
| always | getattr |
permstable32 use the table; with version 3 the file DFA also writes accept2 = 1 on every state except 0 and 1 (code).Perms Table size: 8 (allow/deny/prompt//audit/quiet//xindex) [0] (0x200/0x0/0x0//0x0/0x0//0) no match, owner [1] (0x200/0x0/0x0//0x0/0x0//0) no match, other [2] (0x200/0x0/0x0//0x0/0x0//0) the deny set after filtering, owner [3] (0x200/0x0/0x0//0x0/0x0//0) the deny set after filtering, other [4] (0x244/0x0/0x0//0x0/0x0//0) r, owner [5] (0x244/0x0/0x0//0x0/0x0//0) r, other [6] (0x10201/0x0/0x0//0x0/0x0//i0) ix, owner [7] (0x10201/0x0/0x0//0x0/0x0//i0) ix, other
0x8000 and 0x8004 (tree, kernel policy entries).perms[accept[state]], plus 1 for a non-owner when accept2[state] has the owner flag (file.c:194) (code).| Message | From | Exit status |
|---|---|---|
profile has merged rule with conflicting x modifiers | hfa.cc:1703-1707 | followed by the next line |
ERROR processing regexs for profile %s, failed to load | parser_regex.c:1277 | 255 |
profile %s: has merged rule %s with conflicting x modifiers | block_rules.cc:325 | followed by the next line |
ERROR merging rules for profile %s, failed to load | the front end | 1 |
permission not in permission table map, permission not in idx table map | hfa.cc:1452-1454 | std::runtime_error, not reproduced |
Messages and statuses of the first four rows: tree.
filter-deny (tree).-O filter-deny leaves unused duplicate permission table entries" (tree).dfa-perms-build lines for the implied mmap bit have no line end (tree).1 << i with i up to 31 on a signed int (hfa.cc:1533) (code).audit deny file rule in a complain-mode profile is allowed and logged ALLOWED"; "A deny block around an audit deny rule drops the audit".prompt rule reaches a kernel without the permission table.filter-deny is still the default.The backend turns the rules of one profile into up to three state machines and packs them into tables. For the three-rule demo profile: 15, 22 and 5 states, 5009 bytes.
demo3.sd):abi <abi/5.0>,
include <tunables/global>
profile demo /usr/bin/demo {
/etc/demo/** r,
audit deny @{HOME}/.ssh/** rw,
/usr/bin/[a-z]* ix,
}
apparmor_parser -Q -K -D stats demo3.sd, and the size from apparmor_parser -Q -K -S demo3.sd | wc -c. Both were run with the parser built from the AppArmor tree, and nothing was loaded into a kernel. The kernel feature set given to the parser was one with the policy entries the kernel exports; the tree's own abi/5.0 file gives the same counts and the same size.-Q skips the kernel load, -K skips the cache, -S writes the binary policy to standard output.parser/libapparmor_re/ plus parser/parser_regex.c (rules in, tables out) and parser/parser_interface.c (the bytes).process_profile_rules builds xmatch, then the file DFA, then policydb. Dump lines for the three come in that order and are not labelled.
process_profile_rules calls the three builders in the order xmatch (parser_regex.c:1238), file (parser_regex.c:1258), policydb (parser_regex.c:1268).process_profile_name_xmatch (parser_regex.c:478-627):AA_MAY_EXEC with priority 0 (parser_regex.c:526-527);filedfa=false and permstable32_version=-1 (parser_regex.c:615-619), so it always uses the old accept tables and always has deny filtered (aare_rules.cc:273).process_dfa_entry from path rules, link pairs and change_profile (parser_regex.c:648-787); it is built only when rule_count > 0 (parser_regex.c:794), with filedfa=true (parser_regex.c:797).process_profile_policydb adds one marker rule \d<class> with AA_MAY_READ for each mediated class (parser_regex.c:1338-1357, parser_regex.c:1392-1453). Its priority is 1001, or -1001 for the classes that keep permissions on the class state (parser_regex.c:1372, parser_regex.c:1383). The DFA is built at parser_regex.c:1457-1461.-D rule-exprs: \d21 \d2 \d7 \d32 \d10 \d9 \d14 \d15 \d15\0001 \d22. The dumps on this slide come from the parser of the AppArmor tree, run with a feature set that has the policy entries the kernel exports; that kernel has no ipc entry, so the example has no message queue marker \d17.abi/5.0 file as kernel features the parser computes kernel ABI 5 and leaves out the file class marker \d2 (parser_regex.c:1400-1402): the feature lookup of policy/versions/v7 matches the end of notify_versions.aare_rules::create_chfa (parser/libapparmor_re/aare_rules.cc:194-345): tree, DFA, filter deny, minimize, remove unreachable, equivalence classes, diff encode, perms table, CHFA.
CHFA *aare_rules::create_chfa(int *min_match_len, vector <aa_perms> &perms_table, optflags const &opts, bool filedfa, int permstable32_version, aare_rules *tail = NULL, bool tail_oob = true) (aare_rules.h:147-151).| Stage | Call | Lines | Runs when |
|---|---|---|---|
| tail | build the tail's tree, put a separator in front | aare_rules.cc:203-221 | a tail rule set is given (xattrs) |
| tree | build_tree | aare_rules.cc:162-187, called at aare_rules.cc:223 | always |
| (numbering) | label_nodes(root) | aare_rules.cc:235 | always; for dumps |
| DFA | DFA dfa(root, opts, filedfa) | aare_rules.cc:260 | always |
| filter deny | dfa.apply_and_clear_deny() | aare_rules.cc:273-278 | permstable32_version < 2, or filter-deny |
| minimize | dfa.minimize(opts) | aare_rules.cc:279-285 | minimize |
| unreachable | dfa.remove_unreachable(opts) | aare_rules.cc:287-291 | remove-unreachable |
| equiv | dfa.equivalence_classes, apply_equivalence_classes | aare_rules.cc:298-308 | equiv |
| diff encode | dfa.diff_encode(opts) | aare_rules.cc:310-315 | diff-encode |
| perms table | dfa.compute_perms_table(perms_table) | aare_rules.cc:318-333 | permstable32_version >= 2 |
| CHFA | new CHFA(dfa, eq, opts, permstable32_version) | aare_rules.cc:334 | always |
try block throws an int (aare_rules.cc:340-342).perms_t::perms_t prints profile has merged rule with conflicting x modifiers and throws (hfa.cc:1703-1707); the caller prints ERROR processing regexs for profile t, failed to load (parser_regex.c:1277) and the parser exits with status 255. Seen in a run of the tree's parser with the abi/5.0 feature set.create_dfablob calls create_chfa, has flex_table write the table set into a stream and copies it into a malloc buffer (aare_rules.cc:352-388).build_tree (aare_rules.cc:170-171).std::runtime_error thrown by minimize and compute_perms_table (hfa.cc:883, hfa.cc:1452-1454) is not caught by the catch (int), which is the only handler; build_tree runs before the try block. No other handler in the parser catches it. Not reproduced.create_dfablob returns NULL with *size still set when malloc fails (aare_rules.cc:380-384). Not reproduced.File DFA of the example: 38 states created, 22 after filter deny and minimize, packed into 277 next/check slots, 1528 bytes. -D stats prints the counts.
apparmor_parser -Q -K -D stats demo3.sd, run with the parser of the AppArmor tree and a feature set that has the policy entries the kernel exports. The lines for the three DFAs, in the order xmatch, file, policydb (escape codes removed; the tree's abi/5.0 gives the same lines except Diff encode, which it does not print):Created dfa: states 15 proto { cache: size=15 dups=1 longest=1 avg=0 }, nnodes { cache: size=14 dups=2 longest=1 avg=0 }, anodes { cache: size=1 dups=0 longest=1 avg=1 }
Dfa minimization no states removed: partitions 15 init 3 (accept 1)
Diff encode states: 0 of 15 reached @ depth 14. 0 trans removed
Compressed trans table: states 15, next/check 258, optimal next/check 14 avg/state 17.20, compression 1122/7680 = 85.39 %
Created dfa: states 38 proto { cache: size=38 dups=40 longest=4 avg=1 }, nnodes { cache: size=38 dups=40 longest=4 avg=1 }, anodes { cache: size=3 dups=28 longest=1 avg=1 }
Minimized dfa: final partitions 22 (accept 2) init 4 (accept 2)
Diff encode states: 0 of 22 reached @ depth 12. 0 trans removed
Compressed trans table: states 22, next/check 277, optimal next/check 50 avg/state 12.59, compression 1240/11264 = 88.99 %
Created dfa: states 6 proto { cache: size=6 dups=16 longest=3 avg=1 }, nnodes { cache: size=4 dups=18 longest=3 avg=1 }, anodes { cache: size=2 dups=17 longest=1 avg=1 }
Minimized dfa: final partitions 5 (accept 2) init 3 (accept 1)
Diff encode states: 0 of 5 reached @ depth 3. 0 trans removed
Compressed trans table: states 5, next/check 257, optimal next/check 4 avg/state 51.40, compression 1058/2560 = 58.67 %
Created dfa is printed by subset construction: the number of states, and the sizes of the caches for node sets. See Building the DFA.Minimized dfa: final partitions 22 (accept 2) init 4 (accept 2): 22 states are left, 2 of them accepting; the refinement started from 4 partitions. Dfa minimization no states removed is printed when nothing merged. See Minimisation.Compressed trans table: the packed size against a full table, 4*N + 6*S bytes over 512*S for N next/check slots and S states. See Table compression.audit deny rule lose their deny and quiet bits in filter deny and are then equal to the state with no permissions. See Permissions in the DFA.-O no-filter-deny the second line becomes Dfa minimization no states removed: partitions 38 init 5 (accept 3) (run with the abi/5.0 feature set).stats is a group of dump flags (common_optarg.c:37-42). The parser prints some of the lines with terminal escape codes; strip them with sed 's/\x1b\[[0-9;]*[A-Za-z]//g'.Dump options by stage: rule-exprs, expr-tree, dfa-states-initial, dfa-states-post-filter, dfa-minimize-partitions, diff-encode, compressed-dfa. All print to stderr; stats is a group.
| Stage | Option | Printed at |
|---|---|---|
| AARE to regular expression, rule to tree | rule-exprs | parser_regex.c:142-143, parser_regex.c:441-442, aare_rules.cc:112-135 |
| Tree statistics | expr-stats | expr-tree.cc:972-976, expr-tree.cc:1021-1042 |
| Tree | expr-tree, expr-simplified | aare_rules.cc:236-240, aare_rules.cc:251-255 |
| Permission of each state | dfa-perms-build | hfa.cc:1558-1651, hfa.cc:1670-1702 |
| Subset construction | dfa-stats, dfa-progress, dfa-node-map | hfa.cc:446-454, hfa.cc:522-535 |
| Permission sets | dfa-uniq-perms, dfa-minimize-uniq-perms | aare_rules.cc:261-262, aare_rules.cc:281-282 |
| States | dfa-states-initial, dfa-states-post-filter, dfa-states-post-minimize, dfa-states-post-unreachable, dfa-states | aare_rules.cc:264-293 |
| Minimization | dfa-minimize-partitions | hfa.cc:770-771, hfa.cc:838-839, hfa.cc:847-894 |
| Unreachable states | dfa-unreachable | hfa.cc:621-628 |
| Graphviz | dfa-graph | aare_rules.cc:295-296 |
| Equivalence classes | equiv, equiv-stats | aare_rules.cc:303-308, hfa.cc:1357-1359 |
| Diff encoding | diff-encode, diff-stats, diff-progress | aare_rules.cc:313-314, hfa.cc:1069-1072, hfa.cc:1096-1099 |
| Perms table and packed tables | compressed-dfa | aare_rules.cc:322-336 |
| Packing statistics | compress-stats, compress-progress | chfa.cc:201-208 |
| States with packed numbers | dfa-compressed-states | aare_rules.cc:337-338 |
| Table width | state32 | chfa.cc:524-525, chfa.cc:532-533 |
stats and progress are groups (common_optarg.c:37-42).dfa-states is printed before diff encoding and dfa-compressed-states after it (aare_rules.cc:292-293, aare_rules.cc:310, aare_rules.cc:337-338); only the second shows the transitions that diff encoding left.-D dfa-minimize is accepted and no code tests the flag (common_optarg.c:54).-D expr-tree and -D expr-simplified print the same tree (aare_rules.cc:236-255).flags_table with an underscore as a dump option and flags-table with a dash as an optimisation (common_optarg.c:82, common_optarg.c:120).parser/tst/minimize.sh reads -D dfa-states.Default -O set: expr-normalize expr-simplify expr-vector minimize diff-encode rule-merge filter-deny. Kernel features clear diff-encode, state32 and flags-table without a message.
-O <name> switches a flag on, -O no-<name> off. The table is dfaoptflag_table (common_optarg.c:87-127). -O show prints the current set while options are parsed, before the kernel features are read (parser_main.c:655-656).expr-normalize, expr-simplify, expr-vector, minimize, diff-encode, rule-merge, filter-deny.equiv, remove-unreachable, expr-left-simplify, compress-small, compress-default, state32, flags-table, zstd-recompress.get_kernel_features (parser_main.c:1791-1801; the features are looked up at parser_main.c:1750-1757): diff-encode is cleared without policy/diff_encode or policy/diff-encode; state32 without policy/state32; flags-table without policy/flags_table or without state32. No message is printed. The two spellings of diff-encode are explained in the comment at parser_main.c:1746-1749.abi/5.0 file has no diff-encode entry; the kernel advertises policy/diff-encode (apparmorfs.c:2635).filter-deny is forced for any DFA built with permstable32_version < 2 (aare_rules.cc:273).Conflicting --Optimize options: compress-default, compress-small (parser_main.c:663-667); Invalid --Optimize option %s (parser_main.c:659-660).compress-small and compress-fast are one bit with opposite sense, as are expr-left-simplify and expr-right-simplify (common_optarg.c:99-102, common_optarg.c:110-114). compress-small also selects zstd level 20 for the policy stream when no level is given (parser_main.c:494-495).-O 0 clears expr-normalize, expr-simplify, minimize, remove-unreachable, diff-encode, state32 and flags-table, and leaves expr-vector, filter-deny, rule-merge and equiv as they were (common_optarg.c:88-93); the help text says "no optimizations".apparmor_parser -Q -K -D dfa-stats FILE prints the state count that decides compile time. A cache hit skips the compile; the profile text is still read. Too many states (N) for type state_t means one profile needs more than 65534 states.
-D dfa-stats prints one Created dfa line per state machine, in the order attachment, file rules, other rule classes.policy entries, so diff encoding is on as it is on a running system; nothing was loaded into a kernel. Each run had just under 2 seconds of start-up in it (the three-rule profile takes 1.9 s in all), which is taken off here:| Profile | States created | After merging | Table slots | Bytes of -S | Time |
|---|---|---|---|---|---|
the three-rule demo profile | 38 | 22 | 277 | 5009 | none to speak of |
base, nameservice, user-tmp abstractions and one rule | 2387 | 1695 | 2476 | 41913 | well under a second |
one rule /srv/**x?????????????? (14 question marks) | 32774 | 32774 | 58559 | not measured | well under a second |
one rule /srv/**x??????????????? (15 question marks) | 65542 | 65542 | 116981 | error | about 1.5 s |
Too many states (65542) for type state_t names no profile and does not mention -O state32, which lifts the limit when the kernel's features list policy/state32. The exit status is 1. There is no warning before the limit./var/cache/apparmor (parser_main.c:1864-1866).--debug-cache prints file '%s' is newer than cache file.version marker and the version word this parser would write now (policy_cache.c:36-69, policy_cache.c:170-176). When the kernel takes compressed policy, the cache file is an 8-byte header and one zstd frame, and the parser checks the header version, the zstd magic and the compression level instead; the version word is inside the frame and is not looked at (policy_cache.c:80-96, policy_cache.c:136-146, policy_cache.c:148-181). See The binary policy format.-j runs profiles in parallel worker processes; the number of jobs is derived from free memory (parser_main.c:1629-1660).-O state32 and the kernel feature are handled at chfa.cc:514-535.--dfa-cache-loc, compiled in only with USE_DFA_CACHE (Makefile:72-73). Known discrepancies, by title: "DFA cache key leaves out the permstable32 version that its comment says it covers", "The DFA cache stores entries that its lookup always rejects", "The DFA cache renames a short file into place when the final write fails in fclose()", "The DFA cache writes through a symlink at a predictable temp name and leaks temp files", "A corrupted DFA cache entry is accepted as a hit".Cost centres: add_new_state (hfa.cc:329-358), permissions per target before de-duplication (hfa.cc:340), partition refinement (hfa.cc:791-827). Three abstractions: 2387 states created, 1695 kept; 3160 with -O 0.
policy entries, so diff encoding is on by default (-D stats, and the size of the -S output). The profile is profile big /usr/bin/big { include <abstractions/base> include <abstractions/nameservice> include <abstractions/user-tmp> /etc/demo/** r, } after abi <abi/5.0>, and include <tunables/global>. The rows are its file DFA; the bytes are the whole profile.-O no-minimize, none with -O 0. Without diff encoding (-O no-diff-encode, or a feature set with no policy/diff-encode entry such as the tree's abi/5.0) the default table has 3198 slots and the -O no-minimize table 6170.add_new_state creates a State for a set of nodes and looks it up among the existing ones (hfa.cc:329-358). The State constructor computes the permissions (hfa.h:305-309), so the work at hfa.cc:340 is done before the duplicate is found and deleted (hfa.cc:349-351).-D dfa-progress prints a status line every 1000 states (hfa.cc:446-454).Next: the expression tree, building the DFA, permissions in the DFA, minimisation, table compression, the binary policy format. Around the backend: how the kernel checks an access, the pipeline, the policy cache, kernel features.
Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run (-Q -K with the -D and -O options shown, or -S), with nothing loaded into a kernel. The kernel feature set given to the parser is named where it matters: the tree's abi/5.0 file, or a file with the policy entries the kernel exports. "code" means the parser source, or the kernel source, was read and not run; "derived" means the result was reasoned from that code. Nothing here was observed on a running kernel.
Compile time follows the number of states the rules turn into, not the number of rules. apparmor_parser -Q -K -D dfa-stats FILE prints one Created dfa: states N line per state machine (tree).
| Profile | States created | After merging | Table slots | Bytes of -S | Time |
|---|---|---|---|---|---|
the three-rule demo profile | 38 | 22 | 277 | 5009 | none to speak of |
base, nameservice, user-tmp abstractions and one rule | 2387 | 1695 | 2476 | 41913 | well under a second |
the same with -O no-minimize | 2387 | 2387 | 3302 | 55081 | well under a second |
the same with -O 0 | 3160 | 3160 | 7799 | 84289 | well under a second |
one rule /srv/**x?????????????? (14 question marks) | 32774 | 32774 | 58559 | not measured | well under a second |
one rule /srv/**x??????????????? (15 question marks) | 65542 | 65542 | 116981 | error | about 1.5 s |
Measured with a feature set that has the kernel's policy entries, so diff encoding is on except with -O 0 (tree). Start-up of just under 2 seconds was taken off the times. Without diff encoding the slots are 3198 (default), 6170 (-O no-minimize), 117145 and 234039 (the two one-rule profiles).
| Message | Meaning | Exit status |
|---|---|---|
Too many states (N) for type state_t | one state machine needs more than 65534 states | 1 |
Too many transitions (N) for type state_t | the packed table has more slots than a 16-bit number can address | 1 |
-O state32 lifts the limit when the kernel's features list policy/state32 (code).version marker and the version word this parser would write; for a compressed file, the 8-byte header (header version, zstd magic and level), with no test of the version word (code).-K skips the cache, -W writes it, -j N compiles N profiles at once.| Stage | Call | Lines | Runs when |
|---|---|---|---|
| tree | build_tree | aare_rules.cc:162-187, aare_rules.cc:223 | always |
| DFA | DFA dfa(root, opts, filedfa) | aare_rules.cc:260 | always |
| filter deny | dfa.apply_and_clear_deny() | aare_rules.cc:273-278 | permstable32_version < 2, or filter-deny |
| minimize | dfa.minimize(opts) | aare_rules.cc:279-285 | minimize |
| unreachable | dfa.remove_unreachable(opts) | aare_rules.cc:287-291 | remove-unreachable (off by default) |
| equiv | dfa.equivalence_classes, apply_equivalence_classes | aare_rules.cc:298-308 | equiv (off by default) |
| diff encode | dfa.diff_encode(opts) | aare_rules.cc:310-315 | diff-encode |
| perms table | dfa.compute_perms_table(perms_table) | aare_rules.cc:318-333 | permstable32_version >= 2 |
| CHFA | new CHFA(dfa, eq, opts, permstable32_version) | aare_rules.cc:334 | always |
All rows: code.
| DFA | Built by | Input | filedfa | permstable32_version | States in the example |
|---|---|---|---|---|---|
| xmatch | process_profile_name_xmatch (parser_regex.c:478-627) | attachment or local name, alias names, xattrs as a tail | false | -1 | 15 created, 15 kept |
| file | process_profile_regex (parser_regex.c:789-808) | path rules, link pairs, change_profile | true | what the kernel supports | 38 created, 22 kept |
| policydb | process_profile_policydb (parser_regex.c:1338-1461) | every other rule class, plus one marker rule per mediated class | false | what the kernel supports | 6 created, 5 kept |
Builders and arguments: code. State counts: tree, the same with both feature sets.
| Name | Default | Effect | Cleared when the kernel lacks |
|---|---|---|---|
expr-normalize | on | normalise the tree before simplification | |
expr-simplify | on | simplify and factor the tree | |
expr-vector | on | flatten alternations into vectors before factoring | |
expr-left-simplify | off | factor from the left first (expr-right-simplify is the same bit, inverted) | |
minimize | on | merge equal states | |
filter-deny | on | fold deny into allow before minimizing; forced when permstable32_version < 2 | |
remove-unreachable | off | drop states no path reaches | |
equiv | off | equivalence classes of input bytes | |
diff-encode | on | store a state as a difference from another | policy/diff-encode (or diff_encode) |
state32 | off | 32-bit state numbers | policy/state32 |
flags-table | off | write a per-state flags table | policy/flags_table, or state32 |
compress-small | off | slower, tighter packing (compress-fast is the same bit, inverted); zstd level 20 when none is given | |
compress-default | off | pack using default states | |
rule-merge | on | merge rules in the front end | |
zstd-recompress | off | recompress the policy stream |
Table and defaults: code (common_optarg.c:87-127, parser_common.c:123-129, parser_main.c:1791-1801). The effect column is a summary of the help text and of the stage each flag guards.
| Stage | Option |
|---|---|
| AARE to regular expression, rule to tree | rule-exprs |
| Tree | expr-tree, expr-simplified, expr-stats |
| Subset construction | dfa-stats, dfa-progress, dfa-node-map, dfa-perms-build |
| Permission sets | dfa-uniq-perms, dfa-minimize-uniq-perms |
| States | dfa-states-initial, dfa-states-post-filter, dfa-states-post-minimize, dfa-states-post-unreachable, dfa-states, dfa-compressed-states |
| Minimization | dfa-minimize-partitions |
| Unreachable states | dfa-unreachable |
| Equivalence classes | equiv, equiv-stats |
| Diff encoding | diff-encode, diff-stats, diff-progress |
| Packed tables | compressed-dfa, compress-stats, compress-progress, state32 |
| Graphviz | dfa-graph |
| Groups | stats, progress |
Code (common_optarg.c:30-85); the lines where each is printed are in the details of the scene "A dump for every stage".
| Message | Where | Exit status |
|---|---|---|
profile has merged rule with conflicting x modifiers | hfa.cc:1703-1707 | followed by the next line |
ERROR processing regexs for profile %s, failed to load | parser_regex.c:1277 | 255 (tree, abi/5.0) |
Conflicting --Optimize options: compress-default, compress-small | parser_main.c:663-667 | |
Invalid --Optimize option %s | parser_main.c:659-660 | |
Too many states (N) for type state_t | chfa.cc:435-439 | 1 (tree, abi/5.0) |
-O 0 leaves expr-vector, filter-deny, rule-merge and equiv as they were and clears state32; its help text says "no optimizations" (common_optarg.c:88-93) (code).-D dfa-minimize is accepted and has no effect (common_optarg.c:54) (code).std::runtime_error from minimize and compute_perms_table is not caught by the catch (int) in create_chfa (hfa.cc:883, hfa.cc:1452-1454, aare_rules.cc:340-342) (code; not reproduced).create_dfablob returns NULL with *size still set when malloc fails (aare_rules.cc:380-384) (code; not reproduced).abi/5.0 file as kernel features the parser compiles for kernel ABI 5: version word 5 and no file class marker in policydb (tree).-D rule-merge prints.diff-encode entry in the tree's abi/5.0 file is intended.22 states: about 50 explicit transitions, packed into 277 next/check slots plus a base and a default entry per state. -D compress-stats prints Compressed trans table: states 22, next/check 277, optimal next/check 50 ....
-D compress-stats prints the line on the slide (chfa.cc:201-208). optimal next/check is 2 plus the explicit transitions of every state except the start state and the non-matching state (chfa.cc:91-98): 2 + 48 = 50 for the file DFA, which stores 49. compression X/Y compares X = 4*N + 6*S bytes (1240 for N = 277 slots and S = 22 states) with Y = 512*S (11264), the size of a full row of 256 16-bit numbers per state.Compressed trans table: states 15, next/check 258, optimal next/check 14 avg/state 17.20, compression 1122/7680 = 85.39 % Compressed trans table: states 22, next/check 277, optimal next/check 50 avg/state 12.59, compression 1240/11264 = 88.99 % Compressed trans table: states 5, next/check 257, optimal next/check 4 avg/state 51.40, compression 1058/2560 = 58.67 %
abi/5.0 feature set and with one that has the kernel's policy entries.CHFA::insert_state (chfa.cc:238-317) places each state's explicit transitions at the first base where all of them land on free slots. In the example five / transitions sit in slots 47 to 51, from bases 0 to 4.
CHFA::CHFA (chfa.cc:62-209, declared at chfa.h:46-47) builds the tables; insert_state (chfa.cc:238-317) places one state, using fits_in (chfa.cc:214-233).-O compress-small they are sorted by number of transitions, most first, then by span (chfa.cc:99-108, chfa.cc:150-199).next_check starts with max(2 + number of transitions, max_range) slots and a doubly linked free list (chfa.cc:43-53, chfa.cc:138-142). A state without transitions gets base 0 and no slots (chfa.cc:251-252).-D compressed-dfa: slot: (next, check) {owner label} -> {target label}: byte. The numbers in parentheses are packed state numbers, the numbers in braces are the labels from subset construction: packed 1 is {1}, 7 is {11} (/etc), 8 is {14} (/usr), 16 is {28} (/usr/bin), 17 is {29} (/etc/demo), 18 is {31} (/usr/bin/).abi/5.0 feature set and with one that has the kernel's policy entries. The complete dump is in the reference under the deck.-O compress-small on a profile with three abstractions: 2465 slots against 2476, and 42873 bytes of -S against 42905 (kernel features abi/5.0 plus diff-encode).compress-small ever gives more than that 0.4 %.Lookup for state s and byte c: pos = base[s] + c; if check[pos] == s take next[pos], else default[s]. State 19: / hits its own slot 52; x lands on slot 125, owned by state 18, and falls to default 21.
-D compressed-dfa dump used on the slide: 52: (0, 19) {32} -> {0}: /, 5: (0, 19) {32} -> {0}: \x0, 125: (20, 18) {31} -> {34}: h. There is no entry for slot 14.19: (0, 121, 5) {32} -> {35} is accept 0, accept2 1, default 21, base 5: the dump prints accept2 and the default state without a separator. Known discrepancy, by title: "Debug dumps with malformed output".21 + 104, the h of state 18, and slot 14 is empty: both are derived from the dump and agree with the check table decoded from the -S output (check[125] = 18, check[14] = 0).match_char (match.c:443).Base entry: low 24 bits offset, 0x80000000 diff encoded, 0x20000000 out of band transition (chfa.h:35-38). The next/check arrays are at least the highest base plus 256 long: 277 = 21 + 256.
MATCH_FLAG_DIFF_ENCODE and MATCH_FLAG_OOB_TRANSITION (match.h:196); the parser's are in chfa.h:35-38. The kernel masks the offset with 0xffffff (match.c:23).base - 1, and the kernel requires the offset of such a state to be at least max_oob (match.c:178).base + 255 stays inside it (chfa.cc:255-287) and sets the flags at chfa.cc:303-315; the kernel's test is at match.c:188.YYTH_FLAG_DIFF_ENCODE and YYTH_FLAG_OOB_TRANS (chfa.cc:71-75).-D compressed-dfa dump (the same with both feature sets): highest base 21 for the file DFA (state 18), 2 for xmatch, 1 for policydb.-D compressed-dfa prints the base with its flag bits in decimal (536870915, 2147483648) and an out of band entry as \xff.verify_dfa leaves MARK_DIFF_ENCODE_VERIFIED set in the base table; no effect was found.DFA::diff_encode (hfa.cc:1014-1113): a state keeps only transitions that differ from a shallower state and points its default at it. Three abstractions: 395 of 1695 states encoded, 3198 to 2476 slots. Matching takes at most 2m lookups for m bytes.
/srv/**x?? r, (14 states), not from the three-rule example, and were made with the tree's abi/5.0 feature set plus a diff-encode entry (-D diff-stats -D diff-encode -D compressed-dfa):Diff encode states: 4 of 14 reached @ depth 9. 11 trans removed
{6} <- {10}
{7} <- {11}
{8} <- {12}
{9} <- {13}
...
6: (0, 16, 1) {6} -> {6}
7: (0, 18, 2) {7} -> {8}
...
10: (2, 16, 2147483648) {10} -> {6}
11: (2, 17, 2147483648) {11} -> {7}
Diff encode states: 0 of 22 reached @ depth 12. 0 trans removed (feature set with the kernel's policy entries). For a profile with three abstractions: Diff encode states: 395 of 1695 reached @ depth 49. 726 trans removed.DFA::diff_encode (hfa.cc:1014-1113), in five steps:otherwise target and of each transition target (hfa.cc:1054-1067);diff_weight (hfa.cc:128-219) adds 1 for each identical transition and subtracts for each transition that would have to be masked; a candidate must be shallower, or relative to a shallower state (hfa.cc:136-144);make_relative erases identical transitions, adds masking transitions, sets the flag and makes otherwise the chosen state (hfa.cc:228-268, hfa.cc:1088-1094).Diff encode states: D of T reached @ depth N. X trans removed (hfa.cc:1096-1099). The self-check messages Diff encode error: actual savings A != expected B and Diff encode error: actual count ... go to stderr without failing the compile (hfa.cc:1101-1107).-D dfa-compressed-states shows a diff encoded state as its remaining transitions and [] -> {rel}.match_char loops while the base entry has MATCH_FLAG_DIFF_ENCODE (match.c:443); verify_dfa requires the header flag when any state has the bit and rejects a chain that loops (match.c:172, match.c:201).xattrs=, both kernel features, and a state with an explicit 0xff transition.profile de1 /x{*,*y/z} xattrs=(user.a=1) { } while the tables are correct.diff_weight and make_relative read begin() of a possibly empty map.flatten_relative and undiff_encode are dead code.-D diff-encode prints chains: 0 and average chain size: inf or -nan.CHFA::flex_table (chfa.cc:514-535): 16-bit entries up to 65534 states; with -O state32 and more than 65535 states, 32-bit entries up to 16777214. Otherwise Too many states (N) for type state_t, exit status 1.
CHFA::flex_table chooses the width (chfa.cc:514-535): 16-bit entries, or 32-bit entries when state32 is set and the DFA has more than 65535 states. -D state32 prints which one was used (chfa.cc:524-525, chfa.cc:532-533).size >= 65535. Errors: Too many states (N) for type state_t (chfa.cc:435-439) and Too many transitions (N) for type trans_t (chfa.cc:440-444); both end the parser with exit(1).abi/5.0 feature set.-O flags-table and 16-bit states the parser prints Flags table specified when using 16 bit state and exits (chfa.cc:528-531).state32 is off by default (parser_common.c:123-129) and cleared without policy/state32; flags-table is cleared without policy/flags_table or without state32 (parser_main.c:1795-1801).state32 (apparmorfs.c:2640) and no flags_table entry; it keeps all state tables as 32 bit in memory (match.c:411).-O state32 a DFA of exactly 65535 states is refused, because the 32-bit branch needs size > 65535. Not reproduced.policy/flags_table.accept: a permission table index, or the accept1 word in the old encoding. accept2: 1 on file DFA states with table version 3, the accept2 word in the old encoding, absent otherwise (chfa.cc:118-137, 155-164).
| Table | Id | Entry | One per | Content |
|---|---|---|---|---|
| accept | 1 | 32 bit | state | permission table index, or the accept1 word |
| accept2 | 7 | 32 bit | state | 1 on file DFA states with permission table version 3; the accept2 word in the old encoding; absent otherwise |
| equivalence classes | 5 | 8 bit | 256 inputs | class per byte, only with -O equiv |
| base | 2 | 32 bit | state | offset into next/check plus flag bits |
| default | 4 | 16 or 32 bit | state | state used when check fails |
| next | 8 | 16 or 32 bit | slot | target state |
| check | 3 | 16 or 32 bit | slot | owner state |
-S output of the three-rule example, made with a feature set that has the kernel's policy entries: file DFA accept is 6 for state 20 and 4 for state 21, accept2 is 1 on states 2 to 21; xmatch accept is 1 for state 14 and accept2 is all 0; policydb accept is 1 for states 2 and 3 and there is no accept2 table.permstable32_version -1 (parser_regex.c:618), so it always uses the old encoding.Table set: header (magic 0x1B5E783D, th_hsize 24, th_ssize, th_flags, notflex), then accept, accept2, [equivalence classes], base, default, next, check; each table td_id, td_flags (entry size), td_hilen, td_lolen, entries, padding to 8. Big-endian.
struct table_set_header and the per-table header are in flex-tables.h:6-23 and flex-tables.h:42-49; the writer is flex_table_serialize and its callers (chfa.cc:393-512); the order of the tables is at chfa.cc:500-511.-S output of the example (feature set with the kernel's policy entries):| Offset | What | Bytes |
|---|---|---|
| 0x0d98 | header: 1b5e783d 00000018 000005f8 0000 6e6f74666c657800 0000 | 24 |
| 0x0db0 | accept: 0001 0004 00000000 00000016, 22 entries of 4 bytes, padding | 104 |
| 0x0e18 | accept2 | 104 |
| 0x0e80 | base | 104 |
| 0x0ee8 | default: 22 entries of 2 bytes, padding | 56 |
| 0x0f20 | next: 277 entries of 2 bytes, padding | 568 |
| 0x1158 | check | 568 |
| 0x1390 | end |
1b5e783d 00000018 00000540 0000 6e6f74666c657800 0000.aa_dfa_unpack (match.c:333) checks the magic, rejects unknown header flags and then takes tables until the blob ends (match.c:365).get_kernel_features (parser/parser_main.c:1726-1804): policy/diff-encode, policy/state32, policy/outofband, policy/permstable32_version gate the table forms. The kernel's checks of the tables at load (verify_dfa) are in the binary policy deck.
get_kernel_features (parser_main.c:1726-1804):| Feature entry | Parser variable | Effect when absent |
|---|---|---|
policy/diff_encode or policy/diff-encode | kernel_supports_diff_encode | diff-encode cleared (parser_main.c:1750-1753, parser_main.c:1791-1793) |
policy/state32 | kernel_supports_state32 | state32 cleared (parser_main.c:1754-1755, parser_main.c:1795-1796) |
policy/flags_table | kernel_supports_flags_table | flags-table cleared (parser_main.c:1756-1757, parser_main.c:1797-1801) |
policy/outofband | kernel_supports_oob | xattr attachment conditions dropped with a warning (parser_main.c:1758-1759, parser_regex.c:549-553) |
policy/permstable32 and policy/permstable32_version/0x000002 or 0x000003 | kernel_supports_permstable32_version | the old accept encoding; version 1 or no version counts as absent (parser_main.c:1769-1785) |
policy/set_load and policy/compressed_load belong to The binary policy format.aa_sfs_entry_policy (apparmorfs.c:2632).verify_dfa (match.c:154) runs when aa_g_paranoid_load is set (policy_unpack.c:458, lsm.c:2006). Its checks: default state below the state count (match.c:164); no invalid flags (match.c:168); the header flag for diff encoding (match.c:172); the out of band offset and header flag (match.c:178); the base bound (match.c:188); next and check entries below the state count (match.c:194); diff chains (match.c:201).verify_dfa_accept_index does that for the file and policydb DFAs, see The binary policy format.abi/5.0 (and abi/5.0-interface) as kernel features the parser also computes kernel ABI 5: the feature lookup of policy/versions/v7 matches the end of notify_versions. See The binary policy format.diff-encode entry in abi/5.0 is intended.Next: the binary policy format. The walk: how the kernel checks an access, matching at run time. Back: permissions in the DFA, minimisation, the backend pipeline.
Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run (-Q -K with the -D and -O options shown, or -S), with nothing loaded into a kernel. The packed dump of the three-rule example is the same with the tree's abi/5.0 file as kernel features and with a feature set that has the policy entries the kernel exports; the byte offsets of its table set are from the second; the diff encoding dumps were made with abi/5.0 plus a diff-encode entry; the state32 run with abi/5.0. "code" means the parser source, or the kernel source, was read and not run; "derived" means the result was reasoned from that code. Nothing here was observed on a running kernel.
pos = base[s] + c; if check[pos] == s the next state is next[pos], otherwise default[s] (code: match.c:443).default[s] with the same byte (code).| Table | Id | Entry | One per | Content |
|---|---|---|---|---|
| accept | 1 | 32 bit | state | permission table index, or the accept1 word |
| accept2 | 7 | 32 bit | state | 1 on file DFA states with permission table version 3; the accept2 word in the old encoding; absent otherwise |
| equivalence classes | 5 | 8 bit | 256 inputs | class per byte, only with -O equiv |
| base | 2 | 32 bit | state | offset into next/check plus flag bits |
| default | 4 | 16 or 32 bit | state | state used when check fails |
| next | 8 | 16 or 32 bit | slot | target state |
| check | 3 | 16 or 32 bit | slot | owner state |
Code: chfa.cc:118-137, chfa.cc:450-470, flex-tables.h:25-34.
| Bits | Meaning |
|---|---|
| 0-23 | offset into next and check |
29 (0x20000000) | the state has an out of band transition, stored at base - 1 |
31 (0x80000000) | the state is diff encoded |
The table set header carries YYTH_FLAG_DIFF_ENCODE and YYTH_FLAG_OOB_TRANS when any state has the bit (chfa.cc:71-75) (code).
-O compress-small most transitions first (chfa.cc:99-108) (code).Compressed trans table: states S, next/check N, optimal next/check O avg/state A, compression X/Y = P %, with O = 2 plus the explicit transitions of every state except the start and non-matching states (chfa.cc:91-98), X = 4*N + 6*S, Y = 512*S (code).Diff encode states: D of T reached @ depth N. X trans removed. Self-check: Diff encode error: actual savings A != expected B, Diff encode error: actual count ...; printed without failing the compile (code)./srv/**x?? r, 4 of 14 states, 264 to 260 slots; three abstractions 395 of 1695 states, 3198 to 2476 slots; the three-rule example 0 of 22.| Case | Result |
|---|---|
| fewer than 65535 states | 16-bit default, next, check |
more than 65535 states with -O state32 and policy/state32 | 32-bit entries, up to 16777214 states |
| 65535 states or more otherwise | Too many states (N) for type state_t, exit status 1 |
Code: chfa.cc:514-535, chfa.cc:435-444. The error was seen with 65542 states (tree).
header (24 bytes, big-endian) u32 th_magic 0x1B5E783D u32 th_hsize 24 u32 th_ssize size of the whole table set u16 th_flags char th_version[] "notflex", NUL, padding table (repeated) u16 td_id u16 td_flags entry size in bytes: 1, 2 or 4 u32 td_hilen 0 u32 td_lolen number of entries entries, then padding to a multiple of 8
Order: accept, accept2, equivalence classes, base, default, next, check (chfa.cc:500-511) (code). The file DFA of the example (tree):
Offset in the -S output | Table | Bytes |
|---|---|---|
| 0x0d98 | header | 24 |
| 0x0db0 | accept | 104 |
| 0x0e18 | accept2 | 104 |
| 0x0e80 | base | 104 |
| 0x0ee8 | default | 56 |
| 0x0f20 | next | 568 |
| 0x1158 | check | 568 |
-D compressed-dfa, file DFA (tree). The first number of a state line is the packed state number, the label in braces is the one from subset construction. A state line is (accept, accept2 and default run together, base).
Perms Table size: 8
(allow/deny/prompt//audit/quiet//xindex)
(0x200/0x0/0x0//0x0/0x0//0)accept1: 0x, accept2: 0x
(0x200/0x0/0x0//0x0/0x0//0)accept1: 0x, accept2: 0x
(0x200/0x0/0x0//0x0/0x0//0)accept1: 0x, accept2: 0x
(0x200/0x0/0x0//0x0/0x0//0)accept1: 0x, accept2: 0x
(0x244/0x0/0x0//0x0/0x0//0)accept1: 0x, accept2: 0x
(0x244/0x0/0x0//0x0/0x0//0)accept1: 0x, accept2: 0x
(0x10201/0x0/0x0//0x0/0x0//i0)accept1: 0x, accept2: 0x
(0x10201/0x0/0x0//0x0/0x0//i0)accept1: 0x, accept2: 0x
size=22 (accept, accept2, default, base): {state} -> {default state}
0: (0, 00, 0) {0} -> {0}
1: (0, 00, 0) {1} -> {0}
2: (0, 10, 0) {2} -> {0}
3: (0, 10, 0) {3} -> {0}
4: (0, 10, 0) {6} -> {0}
5: (0, 10, 0) {7} -> {0}
6: (0, 10, 0) {10} -> {0}
7: (0, 10, 1) {11} -> {0}
8: (0, 10, 2) {14} -> {0}
9: (0, 10, 0) {15} -> {0}
10: (0, 10, 0) {18} -> {0}
11: (0, 10, 1) {19} -> {0}
12: (0, 10, 0) {22} -> {0}
13: (0, 10, 0) {23} -> {0}
14: (0, 10, 0) {25} -> {0}
15: (0, 10, 0) {26} -> {0}
16: (0, 10, 3) {28} -> {0}
17: (0, 10, 4) {29} -> {0}
18: (0, 10, 21) {31} -> {0}
19: (0, 121, 5) {32} -> {35}
20: (6, 120, 6) {34} -> {34}
21: (4, 121, 1) {35} -> {35}
size=277 (next, check): {check state} -> {next state} : offset from base
0: (0, 0) {0} -> {0}: \x0
1: (0, 21) {35} -> {0}: \x0
5: (0, 19) {32} -> {0}: \x0
6: (0, 20) {34} -> {0}: \x0
47: (2, 1) {1} -> {2}: /
48: (9, 7) {11} -> {15}: /
49: (10, 8) {14} -> {18}: /
50: (18, 16) {28} -> {31}: /
51: (19, 17) {29} -> {32}: /
52: (0, 19) {32} -> {0}: /
53: (0, 20) {34} -> {0}: /
98: (12, 10) {18} -> {22}: b
99: (7, 5) {7} -> {11}: c
100: (11, 9) {15} -> {19}: d
101: (3, 2) {2} -> {3}: e
102: (13, 11) {19} -> {23}: e
105: (14, 12) {22} -> {25}: i
109: (15, 13) {23} -> {26}: m
110: (16, 14) {25} -> {28}: n
111: (17, 15) {26} -> {29}: o
114: (8, 6) {10} -> {14}: r
115: (6, 4) {6} -> {10}: s
116: (5, 3) {3} -> {7}: t
117: (4, 2) {2} -> {6}: u
118: (20, 18) {31} -> {34}: a
119: (20, 18) {31} -> {34}: b
120: (20, 18) {31} -> {34}: c
121: (20, 18) {31} -> {34}: d
122: (20, 18) {31} -> {34}: e
123: (20, 18) {31} -> {34}: f
124: (20, 18) {31} -> {34}: g
125: (20, 18) {31} -> {34}: h
126: (20, 18) {31} -> {34}: i
127: (20, 18) {31} -> {34}: j
128: (20, 18) {31} -> {34}: k
129: (20, 18) {31} -> {34}: l
130: (20, 18) {31} -> {34}: m
131: (20, 18) {31} -> {34}: n
132: (20, 18) {31} -> {34}: o
133: (20, 18) {31} -> {34}: p
134: (20, 18) {31} -> {34}: q
135: (20, 18) {31} -> {34}: r
136: (20, 18) {31} -> {34}: s
137: (20, 18) {31} -> {34}: t
138: (20, 18) {31} -> {34}: u
139: (20, 18) {31} -> {34}: v
140: (20, 18) {31} -> {34}: w
141: (20, 18) {31} -> {34}: x
142: (20, 18) {31} -> {34}: y
143: (20, 18) {31} -> {34}: z| Feature entry | Effect when absent |
|---|---|
policy/diff_encode or policy/diff-encode | no diff encoding |
policy/state32 | -O state32 cleared |
policy/flags_table | -O flags-table cleared |
policy/outofband | xattr attachment conditions dropped with a warning |
policy/permstable32_version 2 or 3 | the old accept encoding |
Code: parser_main.c:1726-1804.
| Option | Shows |
|---|---|
compressed-dfa | the permission table, the state lines and the next/check entries |
dfa-compressed-states | the state dump with packed numbers, after diff encoding |
diff-encode | one line per chain, {base} <- {relative}, and a summary |
diff-stats, compress-stats, state32 | the statistics lines quoted above |
| Message | Effect |
|---|---|
Too many states (N) for type state_t | exit status 1 |
Too many transitions (N) for type trans_t | exit status 1 |
Flags table specified when using 16 bit state | the parser exits |
Diff encode error: actual savings A != expected B | printed, compile continues |
Diff encode error: actual count ... | printed, compile continues |
xattrs=, both kernel features and an explicit 0xff transition).diff_weight and make_relative read begin() of a possibly empty map (code; no failure reproduced).flatten_relative and undiff_encode are dead code (code).-D diff-encode prints chains: 0 and average chain size: inf or -nan (tree).-D compressed-dfa prints an out of band entry as \xff and the base with its flag bits in decimal (tree).-O state32 a DFA of exactly 65535 states is refused (code; not reproduced).verify_dfa leaves MARK_DIFF_ENCODE_VERIFIED set in the base table (code; no effect found).policy/flags_table.compress-small ever gives more than the 0.4 % seen here.Patterns become regular expression strings, strings become node trees, trees are grouped by permission, simplified, and joined into the one tree that subset construction starts from.
build_tree).-D rule-exprs, -D expr-tree, -D expr-stats.demo3.sd):abi <abi/5.0>,
include <tunables/global>
profile demo /usr/bin/demo {
/etc/demo/** r,
audit deny @{HOME}/.ssh/** rw,
/usr/bin/[a-z]* ix,
}
abi/5.0 feature set and with a feature set that has the kernel's policy entries; the dumps of the two other profiles used in this deck were made with abi/5.0.* is [^/\x00]*, ** is [^\x00]*, ? is [^/\x00]. A * or ** that is a whole path component gets [^/\x00] in front. -D rule-exprs prints each rewrite.
pattern_t convert_aaregex_to_pcre(const char *aare, int anchor, int glob, std::string& pcre, int *first_re_pos) (parser_regex.c:118-119); the translation is at parser_regex.c:149-405.* gives [^/\x00]*, ** gives [^\x00]*, ? gives [^/\x00]. A run of * that follows / and is followed by / or the end of the pattern gets [^/\x00] inserted first (parser_regex.c:178-205)./etc/demo/* does not match /etc/demo/, while /etc/demo* does match /etc/demo.{a,b} gives (a|b), nested up to 50 levels (MAX_ALT_DEPTH, parser_regex.c:122, parser_regex.c:293). [...] is copied; {, } and , are literal inside it. A negated class such as [^a] in a profile is copied as written and can match /.., +, |, (, ) are always escaped; ^ and $ are escaped outside a class (parser_regex.c:358-380).pattern_t::Basic (no glob), TailGlob (only a final **), Regex, or Invalid; *first_re_pos is the offset of the first glob (parser_regex.c:121, parser_regex.c:213).anchor adds ^ and $ (parser_regex.c:145-147, parser_regex.c:425-427); every caller in parser_regex.c passes 0.glob_null): * is [^/]*, ** is .*, ? is [^/], so a value may contain NUL (parser_regex.c:204, parser_regex.c:220, parser_regex.c:225, parser_regex.c:582-584).@{HOME} is @{HOMEDIRS}/*/ /root/ in profiles/apparmor.d/tunables/home, line 21; the front end expands it before the backend sees the pattern.Regex grouping error: Invalid close ], no matching open [ detected (parser_regex.c:275), Regex grouping error: Exceeded maximum nesting of {} (parser_regex.c:295), Regex grouping error: Invalid number of items between {} (parser_regex.c:317), Regex grouping error: Invalid close }, no matching open { detected (parser_regex.c:323), Regex grouping error: Unclosed grouping or character class, expecting close } (parser_regex.c:414), Regex error: trailing '\' escape character (parser_regex.c:421), Unable to parse input line '%s' (parser_regex.c:430).Character %c was quotedunnecessarily, dropped preceding quote ('\') character (parser_regex.c:396-399).\^ loses its escape, and * or ? inside [...] are expanded".regex_parse (parser/libapparmor_re/parse.y:85-161) builds CharNode, CharSetNode, NotCharSetNode, AnyCharNode, StarNode, PlusNode, CatNode and AltNode. The rule: line of -D rule-exprs shows the tree printed back.
regex: /* empty */ | expr
expr: terms | expr '|' terms0 | '|' terms0
terms: qterm | terms qterm
qterm: term | term '*' | term '+'
term: '.' | regex_char | '[' charset ']' | '[' '^' charset ']'
| '[' '^' '^' cset_chars ']' | '(' regex ')'
* + . | ^ - [ ] ( ) as themselves and everything else as CHAR. A backslash is decoded by str_escseq with the extra set *+.|^$-[](){}.strn_escseq (lib.c:155-213): up to three octal digits; \d plus up to three decimal digits; \x plus up to two hex digits; \a \e \f \n \r \t; \\; \". Example: the class marker \d21 parses to the single byte 0x15 (rule: \d21 -> \x15).CharNode (parse.y:109-114). An empty alternative is the shared epsnode (parse.y:85-94).regex_error prints nothing (parse.y:197-202) and add_rule_vec returns false (aare_rules.cc:81-82).[--], [---] and [^^-x] as not parsed (parse.y:81-83).\x plus unpadded hex (expr-tree.cc:78-79), so [^\x0/] is "not NUL and not slash", and NUL followed by 1 prints as \x01.node_type_t):| Class | Matches | expr-tree.h lines |
|---|---|---|
EpsNode | the empty string; one static instance epsnode | 512-537 |
CharNode | one transchar | 568-611 |
CharSetNode | any of a set | 614-680 |
NotCharSetNode | any byte not in the set; never an out of band character | 683-757 |
AnyCharNode | any byte (.) | 760-775 |
StarNode, PlusNode, OptionalNode | repetition of one child | 778-861 |
CatNode, AltNode | sequence and alternation with a vector of children | 963-1103 |
SharedTreeNode | a subtree referenced from several places | 880-960 |
MatchFlag, ExactMatchFlag, DenyMatchFlag, PromptMatchFlag | nothing; mark an accepting position | 1150-1205 |
transchar holds a short: 0 to 255 are bytes, negative values are out of band characters, and only -1 is used (expr-tree.h:89-91, expr-tree.h:105-112).OptionalNode exists and the grammar never creates one (parse.y:102-105).min_match_len() gives the shortest match and stops at an out of band character (expr-tree.h:596-606, expr-tree.h:1039-1055); xmatch uses it. AnyCharNode does not override it and counts as 0 (expr-tree.h:760-775); globs never produce that node for an attachment, and no effect was found.follow does on each node kind.add_rule_vec files each rule under the accept node for its (priority, mode, exact, perms, audit) (aare_rules.h:39-59, aare_rules.cc:53-62). Simplification later runs inside one group only.
bool add_rule(const char *rule, int priority, rule_mode_t mode, perm32_t perms, perm32_t audit, optflags const &opts) and bool add_rule_vec(int priority, rule_mode_t mode, perm32_t perms, perm32_t audit, int count, const char **rulev, optflags const &opts, bool oob).UniquePerm: priority, mode, exact, perms, audit (aare_rules.h:39-59). unique_perms.insert returns the one accept node for a key; its class is chosen by testing in the order DenyMatchFlag, PromptMatchFlag, ExactMatchFlag, MatchFlag (aare_rules.h:78-101). So a deny rule is never exact.exact_match is 1 unless the tree contains a star, a plus, an any-char or a negated set (aare_rules.cc:98-105): /usr/bin/[a-z] is exact, /usr/bin/? is not (? is a negated set).add_to_rules stores expr_map[accept] = AltNode(old, tree) (aare_rules.cc:53-62).CharNode(0), or with the out of band character when oob is true (aare_rules.cc:64-72, aare_rules.cc:83-91). A link pair is link \x00 target (parser_regex.c:692-716); change_profile builds up to three vectors (parser_regex.c:765-784); mount rules use NUL-separated fields (mount.cc:836). Only the xattr tail uses oob = true (parser_regex.c:597-601).0x10004 is read for owner (0x4) and for other (0x4 shifted left by 14); 0x804201 is exec (0x1) and inherit (0x200) for owner and the same two bits shifted by 14 for other; 0x3800e is write, read and append (0xe) for both halves.-S output was identical in four runs.reverse is applied twice (aare_rules.cc:107-108, aare_rules.cc:55-56); no caller sets it.simplify_tree flattens, merges single characters, removes duplicate alternatives and factors suffixes, then prefixes: ab|ac to a(b|c). Five rules: 46 character nodes to 26; 37 created states to 32.
/etc/demo/a.conf r,, /etc/demo/b.conf r,, /etc/demo/sub/a.conf r,, /etc/other r, and /etc/demo/a.conf w,. The front end's rule-merge joins the two rules for /etc/demo/a.conf into one rw rule (< 0x3800e>) before the backend sees them. That is why the read group on the slide has three paths and the dump has a second group.abi/5.0 feature set, -D expr-tree -D expr-stats:-O no-expr-simplify: (((/etc/demo/sub/a\.conf|/etc/demo/b\.conf)|/etc/other)< 0x10004>|/etc/demo/a\.conf< 0x3800e>) Created dfa: states 37 Minimized dfa: final partitions 32 (accept 2) init 4 (accept 2) default: expr tree: c 46, [] 0, [^] 0, | 2, + 0, * 0, . 0, cat 43 expr-vector: flattened 42, eps 0, chars 0, dups 0, collapsed 3, factored 3 simplified expr tree: c 26, [] 0, [^] 0, | 2, + 0, * 0, . 0, cat 4 (/etc/(demo/(b|sub/a)\.conf|other)< 0x10004>|/etc/demo/a\.conf< 0x3800e>) Created dfa: states 32 Dfa minimization no states removed: partitions 32 init 4 (accept 2)
-O no-rule-merge the tree is (/etc/demo/a\.conf< 0x2800a>|/etc/(demo(/b|([]|/sub)/a)\.conf|other)< 0x10004>); [] is the empty alternative.simplify_tree (expr-tree.cc:1019-1044, vector code at expr-tree.cc:572-978):flatten_node: a Cat inside a Cat, or an Alt inside an Alt, is spliced into its parent (expr-tree.cc:606-626);simplify_vec_cat: removes epsnode children and collapses a one-child Cat (expr-tree.cc:676-699);merge_alt_chars: a|b|[cd] becomes [abcd] (expr-tree.cc:705-734);simplify_vec_alt: sorts the alternatives, drops adjacent equals, then factors (expr-tree.cc:909-935);factor_alt and factor_run (expr-tree.cc:818-906); the header comment gives ab | ac -> a(b | c), ba | ca -> (b | c)a and a | ab -> a(E | b).-O expr-left-simplify swaps the order (expr-tree.cc:967-970).expr-vector: line counts flattened, eps, chars, dups, collapsed, factored (expr-tree.cc:973-976). -D expr-stats prints one block per group, because simplification runs per group. The three blocks of the three-rule example:expr tree: c 17, [] 0, [^] 3, | 1, + 0, * 2, . 0, cat 18 expr-vector: flattened 16, eps 0, chars 0, dups 0, collapsed 1, factored 1 simplified expr tree: c 16, [] 0, [^] 3, | 1, + 0, * 2, . 0, cat 3 expr tree: c 9, [] 1, [^] 1, | 0, + 0, * 1, . 0, cat 10 expr-vector: flattened 9, eps 0, chars 0, dups 0, collapsed 0, factored 0 simplified expr tree: c 9, [] 1, [^] 1, | 0, + 0, * 1, . 0, cat 1 expr tree: c 10, [] 0, [^] 2, | 0, + 0, * 1, . 0, cat 11 expr-vector: flattened 10, eps 0, chars 0, dups 0, collapsed 0, factored 0 simplified expr tree: c 10, [] 0, [^] 2, | 0, + 0, * 1, . 0, cat 1
expr-vector (default) and the older rotate-and-factor simplifier (-O no-expr-vector). Both factor suffixes first; the comment at expr-tree.cc:991-996 gives about 7 thousand against about 1.25 million states for one test.
simplify_tree_old runs normalize(dir) (when expr-normalize is set) and simplify_tree_base until nothing changes, for direction 1 and then 0 (expr-tree.cc:984-1017). MAX_PASSES is 1 (expr-tree.cc:983).merge_charset (expr-tree.cc:313), basic_alt_factor (expr-tree.cc:337) and basic_simplify (expr-tree.cc:391). The simplifier is selected at expr-tree.cc:1030-1033.abi/5.0 feature set. All three variants create 32 states; the third is (((/etc/demo/sub/a|/etc/demo/b)\.conf|/etc/other)< 0x10004>|/etc/demo/a\.conf< 0x3800e>) in full.-O no-expr-normalize is accepted with the default simplifier and does nothing; the vector simplifier never calls normalize (expr-tree.cc:1004-1005, common_optarg.c:95-96).build_tree (aare_rules.cc:162-187): per group Cat(simplified group, accept node), joined left to right by binary AltNode. -D expr-tree prints the result; group order varies between runs.
Node *build_tree(optflags const &opts, SharedTreeNode *tail, int *min_match_len) (aare_rules.h:120-121). For each group it simplifies, computes min_match_len, builds Cat(group, accept) and joins the groups left to right with binary AltNode (aare_rules.cc:162-187).-D expr-tree already shows the simplified tree unless -O no-expr-simplify is given (comment at aare_rules.cc:230-234). label_nodes numbers the nodes for dumps (aare_rules.cc:235).policy entries (the tree's abi/5.0 gives the same line):DFA: Expression Tree ((/(home/([^\x0/])*|root)/\.ssh/[^\x0/]([^\x0])*< 0x3800e>|/usr/bin/[abcdefghijklmnopqrstuvwxyz]([^\x0/])*< 0x804201>)|/etc/demo/[^\x0/]([^\x0])*< 0x10004>)
-D rule-exprs prints aare: <pattern> -> <regex> (parser_regex.c:142-143, parser_regex.c:441-442) and rule: <regex> -> <tree> priority=N [deny|prompt] (0x<perms>/<audit>)<accept> (aare_rules.cc:112-135); -D expr-stats prints node counts before and after (expr-tree.cc:1024-1028, expr-tree.cc:1037-1041) and the vector counters (expr-tree.cc:973-976); -D expr-tree prints DFA: Expression Tree (aare_rules.cc:236-240).-S output was identical in four runs.-D expr-simplified prints the same tree a second time (aare_rules.cc:242-255).With a tail, each group ends in Alt(accept, tail); the tail is one SharedTreeNode prefixed by the out of band character -1 (aare_rules.cc:203-221, 179-180). Only xattr attachment conditions use it.
profile xa /usr/bin/x* xattrs=(user.a=one user.b=tw*), not the three-rule example. Run with the parser of the AppArmor tree, abi/5.0 feature set, -D rule-exprs -D expr-tree:aare: tw* -> \x00tw[^/]* aare: one -> \x00one rule: \x00tw[^/]*\-x01\x00one -> \x0tw([^/])*\d-1\x0one priority=0 (0x1/0)< 0x1> DFA: Expression Tree /usr/bin/x([^\x0/])*(< 0x1>|\d-1\x0tw([^/])*([]|\d-1\x0one)< 0x1>)
SharedTreeNode (aare_rules.cc:203-221); each group ends in Alt(accept, tail) (aare_rules.cc:179-180). [] is the empty alternative.create_chfa returns NULL when the two rule sets use different accept node caches or either is reversed (aare_rules.cc:207-209); flip_tree must not be used on a tree with a shared tail (expr-tree.h:877-878).xattr attachment conditional ignored when the kernel lacks domain/attach_conditions/xattr or policy/outofband (parser_regex.c:549-553).NotCharSetNode::contains_oob() is inverted, so xmatch_len stops at the first wildcard"; "Without an abi rule, xattrs= is dropped silently and change_profile -> &x is refused "by the kernel"".Next: building the DFA (states from positions), permissions in the DFA (accept nodes). Back: globbing, from AARE to regular expressions, the backend pipeline.
@{HOME} was expanded. Extended attribute conditions, Exec modes.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run (-Q -K with the -D and -O options shown), with nothing loaded into a kernel. The dumps of the three-rule profile are the same with the tree's abi/5.0 feature set and with a feature set that has the kernel's policy entries; the other dumps were made with abi/5.0. "code" means the parser source, or the kernel source, was read and not run; "derived" means the result was reasoned from that code. Nothing here was observed on a running kernel.
| Glob | In a path | In an xattr value (glob_null) | |
|---|---|---|---|
* | [^/\x00]* | [^/]* | |
** | [^\x00]* | .* | |
? | [^/\x00] | [^/] | |
{a,b} | `(a | b)`, up to 50 levels | the same |
[...] | copied | copied |
* that follows / and is followed by / or the end gets [^/\x00] (or [^/]) in front: /etc/demo/* does not match /etc/demo/ (code, tree).., +, |, (, ) are always escaped; ^ and $ outside a class (code).convert_aaregex_to_pcre returns pattern_t::Basic (no glob), TailGlob (only a final **), Regex or Invalid (parser_regex.c:118-121) (code).regex: /* empty */ | expr
expr: terms | expr '|' terms0 | '|' terms0
terms: qterm | terms qterm
qterm: term | term '*' | term '+'
term: '.' | regex_char | '[' charset ']' | '[' '^' charset ']'
| '[' '^' '^' cset_chars ']' | '(' regex ')'
\d plus up to three decimal digits, \x plus up to two hex digits, \a \e \f \n \r \t, \\, \" (code).? operator and anchors. + exists (code).| Class | Matches | expr-tree.h lines |
|---|---|---|
EpsNode | the empty string | 512-537 |
CharNode | one transchar | 568-611 |
CharSetNode | any of a set | 614-680 |
NotCharSetNode | any byte not in the set; never an out of band character | 683-757 |
AnyCharNode | any byte | 760-775 |
StarNode, PlusNode, OptionalNode | repetition of one child | 778-861 |
CatNode, AltNode | sequence, alternation | 963-1103 |
SharedTreeNode | a subtree referenced from several places | 880-960 |
MatchFlag, ExactMatchFlag, DenyMatchFlag, PromptMatchFlag | nothing; mark an accepting position | 1150-1205 |
transchar holds a short; 0 to 255 are bytes, negative values are out of band, only -1 is used (expr-tree.h:89-112) (code).
DenyMatchFlag, prompt gives PromptMatchFlag, exact gives ExactMatchFlag, otherwise MatchFlag (aare_rules.h:78-101) (code).| Pass | What it does | expr-tree.cc lines | ||||
|---|---|---|---|---|---|---|
flatten_node | splices a Cat in a Cat, an Alt in an Alt | 606-626 | ||||
simplify_vec_cat | removes empty children, collapses a one-child Cat | 676-699 | ||||
merge_alt_chars | `a | b | [cd] to [abcd]` | 705-734 | ||
simplify_vec_alt | sorts alternatives, drops duplicates, factors | 909-935 | ||||
factor_alt, factor_run | `ab | ac to a(b | c), ba | ca to (b | c)a` | 818-906 |
Right (suffix) pass first, then left; -O expr-left-simplify swaps them. The expr-vector: line counts flattened, eps, chars, dups, collapsed, factored (code).
-O no-expr-vector selects simplify_tree_old (expr-tree.cc:980-1017): normalize(dir) when expr-normalize is set, then simplify_tree_base, for direction 1 and then 0 (code).merge_charset, basic_alt_factor, basic_simplify (expr-tree.cc:204-520) (code).| Option | Line format | |
|---|---|---|
-D rule-exprs | aare: <pattern> -> <regex> and `rule: <regex> -> <tree> priority=N [deny | prompt] (0x<perms>/<audit>)<accept>` |
-D expr-stats | `expr tree: c .., [] .., [^] .., | .., + .., * .., . .., cat .., the expr-vector: counters, simplified expr tree: ...` |
-D expr-tree | DFA: Expression Tree and the tree on one line |
The three-rule example, file DFA (tree):
aare: /etc/demo/** -> /etc/demo/[^/\x00][^\x00]*
rule: /etc/demo/[^/\x00][^\x00]* -> /etc/demo/[^\x0/]([^\x0])* priority=0 (0x10004/0)< 0x10004>
aare: /usr/bin/[a-z]* -> /usr/bin/[a-z][^/\x00]*
rule: /usr/bin/[a-z][^/\x00]* -> /usr/bin/[abcdefghijklmnopqrstuvwxyz]([^\x0/])* priority=0 (0x804201/0)< 0x804201>
aare: {/home/*,/root}/.ssh/** -> (/home/[^/\x00]*|/root)/\.ssh/[^/\x00][^\x00]*
rule: (/home/[^/\x00]*|/root)/\.ssh/[^/\x00][^\x00]* -> (/home/([^\x0/])*|/root)/\.ssh/[^\x0/]([^\x0])* priority=0 deny (0x3800e/0)< 0x3800e>
DFA: Expression Tree
((/(home/([^\x0/])*|root)/\.ssh/[^\x0/]([^\x0])*< 0x3800e>|/usr/bin/[abcdefghijklmnopqrstuvwxyz]([^\x0/])*< 0x804201>)|/etc/demo/[^\x0/]([^\x0])*< 0x10004>)
The five-rule profile under each option set (tree, abi/5.0):
| Options | Tree | States created | |||
|---|---|---|---|---|---|
-O no-expr-simplify | `(((/etc/demo/sub/a\.conf | /etc/demo/b\.conf) | /etc/other)< 0x10004> | /etc/demo/a\.conf< 0x3800e>)` | 37 |
| default | `(/etc/(demo/(b | sub/a)\.conf | other)< 0x10004> | /etc/demo/a\.conf< 0x3800e>)` | 32 |
-O no-expr-vector | `(/etc/(demo/(sub/a | b)\.conf | other)< 0x10004> | /etc/demo/a\.conf< 0x3800e>)` | 32 |
-O no-expr-vector -O no-expr-normalize | `(((/etc/demo/sub/a | /etc/demo/b)\.conf | /etc/other)< 0x10004> | /etc/demo/a\.conf< 0x3800e>)` | 32 |
| Message | parser_regex.c line |
|---|---|
Regex grouping error: Invalid close ], no matching open [ detected | 275 |
Regex grouping error: Exceeded maximum nesting of {} | 295 |
Regex grouping error: Invalid number of items between {} | 317 |
Regex grouping error: Invalid close }, no matching open { detected | 323 |
Regex grouping error: Unclosed grouping or character class, expecting close } | 414 |
Regex error: trailing '\' escape character | 421 |
Unable to parse input line '%s' | 430 |
warning: Character %c was quotedunnecessarily, dropped preceding quote ('\') character | 396-399 |
All rows: code.
-D expr-tree and -D expr-simplified print the same tree (aare_rules.cc:236-255) (tree).reverse is applied twice; no caller sets it (aare_rules.cc:107-108, aare_rules.cc:55-56) (code).-O no-expr-normalize does nothing with the default simplifier (code).\^ loses its escape, and * or ? inside [...] are expanded"; "NotCharSetNode::contains_oob() is inverted, so xmatch_len stops at the first wildcard"; "Without an abi rule, xattrs= is dropped silently and change_profile -> &x is refused "by the kernel"".A file rule is matched against a path that the kernel builds from the mount and directory entry at the moment of the check. The file carries no AppArmor label for file rules, so anything that changes the path changes the answer.
/etc/demo/public r,) is matched against a string. For every file hook the kernel builds that string from the pair of mount and directory entry it was handed, then walks the profile's file table with it.info="Failed name lookup - name too long"./etc/demo/public (rule: r) and /etc/demo/secret (no rule), both owned by root, and a task running as root, so ordinary owner and mode checks never stand in the way.7.3.4+deb14-cloud-amd64, apparmor_parser 5.0.2), as root. The run used the profile demo-t and the test program t from findings/security/observed/; the slide writes demo for both. The kernel code cited is mainline at the commit the map describes; the guest kernel is one release older and behaved as that code reads.aa_path_name and d_namespace_path build the name: path.c:88-176, path.c:202-222.SB_NOUSER are skipped before any name is built: path_mediated_fs, lib.h:146-149.A bind mount gives a file a second path, and a file rule for that path applies to it. Observed: with /etc/demo/secret bind-mounted on /etc/demo/public, the confined program reads the secret through the rule for the public file.
/etc/demo/public then covers whatever is mounted there.unshare -m sh -c 'mount --bind /etc/demo/secret /etc/demo/public && aa-exec -p demo-t -- ./t open /etc/demo/public' printed open O_RDONLY: ok (3) and read: ok, read 12 bytes: "secret data". The audit log had no record for it.mount system call needs CAP_SYS_ADMIN over the mount namespace. A confined task also needs capability sys_admin, and a mount rule in its profile. An unconfined task is not asked by AppArmor. Container runtimes and service managers arrange mounts before the confined program starts.deny rule names a path as well. A file under a denied path is reachable under any other name it has.7.3.4+deb14-cloud-amd64, apparmor_parser 5.0.2), as root. The run used the profile demo-t and the test program t from findings/security/observed/; the slide writes demo for both. The kernel code cited is mainline at the commit the map describes; the guest kernel is one release older and behaved as that code reads.d_absolute_path on the path that was handed to the hook: path.c:117-128.mount(2) for a confined task: apparmor_sb_mount lsm.c:707-742, bind mounts in aa_bind_mount mount.c:355-394.By default the matched name starts at the root of the task's mount namespace, so a chroot does not shorten it. With flags=(chroot_relative) it starts at the task's root. Observed both ways with the same rule and the same open.
namespace_relative): the name is the path from the root of the current mount namespace. After chroot("/srv/jail"), open("/etc/demo/public") is matched as /srv/jail/etc/demo/public.flags=(chroot_relative): the name is the path from the task's root directory. The same open is matched as /etc/demo/public./etc/demo/public r, and capability sys_chroot,: without the flag open inside the chroot: FAILED errno=13 (Permission denied) and the audit record apparmor="DENIED" operation="open" class="file" profile="demo-t" name="/srv/jail/etc/demo/public" comm="t" requested_mask="r" denied_mask="r" fsuid=0 ouid=0. With the flag: open inside the chroot: ok (3), read: ok, read 10 bytes: "jail copy"./srv/jail, holding its own /etc/demo/public with the text "jail copy") was made beforehand by the unconfined setup script (findings/security/observed/run.sh); the profile gives demo no write access there. A program that can also write a directory tree and holds sys_chroot can build such a jail itself.etc/demo/public there. With chroot_relative that file carries the name of the system's file.chroot needs CAP_SYS_CHROOT, which a confined task has only with capability sys_chroot,. AppArmor has no separate rule for the chroot call itself.pivot_root moves that root and has its own rule class.:ns:) is a different thing: it separates sets of profiles, not file trees. See Policy namespaces.7.3.4+deb14-cloud-amd64, apparmor_parser 5.0.2), as root. The run used the profile demo-t and the test program t from findings/security/observed/; the slide writes demo for both. The kernel code cited is mainline at the commit the map describes; the guest kernel is one release older and behaved as that code reads.PATH_CHROOT_REL selects __d_path against current->fs root, otherwise d_absolute_path: path.c:117-128. Flag bits: path.h:17-26.apparmor_sb_pivotroot: lsm.c:774-786.A rename is checked on the old and the new name of the thing renamed: rw on the old, w on the new. Renaming a directory changes the name of every file below it without a check on any of them. Observed.
rw in profile letters) and write and create on the new name (w). RENAME_EXCHANGE asks both ways round./srv/demo/a/. A rule such as /srv/** rw, covers every directory name below /srv and therefore allows moving any of them./srv/demo/a/ rw,, /srv/demo/c/ rw,, /srv/demo/c/** r,. open /srv/demo/a/secret-notes: FAILED errno=13. rename /srv/demo/a /srv/demo/c: ok. open /srv/demo/c/secret-notes: ok, read 6 bytes: "notes". The audit log holds only the first denial.apparmor="DENIED" operation="rename_dest" class="file" profile="demo-t" name="/srv/demo/b2/" comm="t" requested_mask="wc" denied_mask="wc" (first run).rw on the old name and w on the new moves it from under one rule to under another.w on directory names that sit above data other rules protect by name.7.3.4+deb14-cloud-amd64, apparmor_parser 5.0.2), as root. The run used the profile demo-t and the test program t from findings/security/observed/; the slide writes demo for both. The kernel code cited is mainline at the commit the map describes; the guest kernel is one release older and behaved as that code reads.apparmor_path_rename: lsm.c:386-448; the masks at lsm.c:433-444.aa_path_link file.c:437-477.The name is matched at open. Later reads and writes on the descriptor are not matched again when the open already covered them. Observed: an open descriptor keeps working after the file is renamed to a denied path, and after the profile is replaced without the rule.
read, write, mmap, locking and receiving a descriptor ask again, but the question is answered from that memory when nothing more is requested and the task's label is the one remembered. Only otherwise is a name built, at that later moment, and matched./srv/demo/b/moving (allowed by /srv/demo/b/** r,); mv /srv/demo/b/moving /srv/demo/hidden by another process; then read from the same fd after the wait: ok, read 7 bytes: "moving", fd 3 is /srv/demo/hidden, open the new path: FAILED errno=13./etc/demo/public; apparmor_parser -r loaded the same profile without that rule; then read from the same fd after the wait: ok, read 12 bytes: "public data", open the same path again: FAILED errno=13, with apparmor="DENIED" operation="open" ... name="/etc/demo/public"./proc/self/fd/3 shows /srv/demo/b/gone (deleted).7.3.4+deb14-cloud-amd64, apparmor_parser 5.0.2), as root. The run used the profile demo-t and the test program t from findings/security/observed/; the slide writes demo for both. The kernel code cited is mainline at the commit the map describes; the guest kernel is one release older and behaved as that code reads.apparmor_file_open records the request in the file's context: lsm.c:465-507; the opener's label is stored by apparmor_file_alloc_security lsm.c:509-519.aa_file_perm: the fast path at file.c:655-661, the slow path __file_path_perm at file.c:490-544 with the comment "No revocation at this time" at file.c:504-507.At an exec that changes the profile, inherited descriptors are checked against the new profile; a denied one is replaced by a null file or closed (closed in the run). A descriptor opened by an unconfined task is exempt: the confined program can use it whatever its rules say. Both observed.
file_inherit. A descriptor that fails is replaced by the null device or closed.file_receive) and on each later use.unconfined, the check ends with success before any name is built. The kernel comment calls it "file delegation from unconfined tasks".opener has /etc/demo/secret r, and an exec rule Px -> demo-t. The program opened the secret, then executed itself into demo-t: readlink /proc/self/fd/N: FAILED errno=2, read from the inherited fd: FAILED errno=9 (Bad file descriptor), and apparmor="DENIED" operation="file_inherit" class="file" profile="demo-t" name="/etc/demo/secret" comm="t" requested_mask="r" denied_mask="r".sh -c 'exec 3</etc/demo/secret; exec aa-exec -p demo-t -- ./t fdread 3' printed fd 3 is /etc/demo/secret and read from the inherited fd: ok, read 12 bytes: "secret data". No audit record.O_CLOEXEC, and start confined services from a launcher that holds nothing they should not get.ix) checks nothing: the label did not change.7.3.4+deb14-cloud-amd64, apparmor_parser 5.0.2), as root. The run used the profile demo-t and the test program t from findings/security/observed/; the slide writes demo for both. The kernel code cited is mainline at the commit the map describes; the guest kernel is one release older and behaved as that code reads.apparmor_bprm_committing_creds calls aa_inherit_files unless the label is unchanged or the new one is unconfined: lsm.c:957-973; aa_inherit_files file.c:721-754.__file_is_delegated is unconfined(obj_label): file.c:577-580; used in the fast path of aa_file_perm file.c:655-661.A path that does not reach the namespace root is denied with info="Failed name lookup - disconnected path". attach_disconnected prefixes a slash, so rules for the real root also match the disconnected file. Both observed.
info="Failed name lookup - disconnected path" and a name= without a leading slash./mnt/d (a tmpfs), umount -l /mnt/d followed, then openat(dirfd, "f"): FAILED errno=13, and apparmor="DENIED" operation="open" class="file" info="Failed name lookup - disconnected path" error=-13 profile="demo-t" name="f" comm="t" requested_mask="r" denied_mask="r".flags=(attach_disconnected) and the rule /f r,: openat(dirfd, file) after the wait: ok (4), read: ok, read 24 bytes: "from the detached mount", fd 4 is /f. A different file, /f with the text "the real /f", exists in the namespace.mq_open("/demo-queue") was denied as operation="open" class="file" info="Failed name lookup - disconnected path" ... name="demo-queue".info="Failed name lookup - deleted entry" unless mediate_deleted or delegate_deleted is in effect; one of them normally is. A descriptor that is already open keeps working (previous scene).attach_disconnected.path=/outside puts disconnected files under their own prefix, so rules can name them separately. See The other profile flags.7.3.4+deb14-cloud-amd64, apparmor_parser 5.0.2), as root. The run used the profile demo-t and the test program t from findings/security/observed/; the slide writes demo for both. The kernel code cited is mainline at the commit the map describes; the guest kernel is one release older and behaved as that code reads.disconnect(): path.c:48-72; where connected is cleared path.c:138-147; deleted entries path.c:158-164; the info strings path.c:209-216.open(..., O_PATH) reaches no AppArmor check. fstat on the handle succeeds; re-opening it through /proc/self/fd/N is checked like any open and denied. Observed for a file with no rule and for a file with a deny rule.
O_PATH open gives a descriptor that names a location. It cannot be read or written. The kernel finishes such an open before it calls the security hook for opening files.fstat (allowed under every profile, see What is not mediated); openat(fd, "name", ...) and a re-open through /proc/self/fd/N, which are ordinary opens and are checked under the object's current name; fchdir, which has no AppArmor check; linkat and execveat with AT_EMPTY_PATH, which reach the link and exec checks./etc/demo/secret (no rule): open O_PATH: ok (3), fstat on the O_PATH fd: ok (0), size=12 uid=0 mode=600, fd 3 is /etc/demo/secret, re-open through /proc/self/fd/N O_RDONLY: FAILED errno=13 (Permission denied). The same lines for /etc/demo/denied, which has deny /etc/demo/denied rwkl,.who profile records the same thing from a system-call trace: an openat with O_PATH and a newfstatat, and the note that these calls are not mediated, so the profile has no rule for them.O_PATH open that the log never mentions, nothing is missing from the profile.7.3.4+deb14-cloud-amd64, apparmor_parser 5.0.2), as root. The run used the profile demo-t and the test program t from findings/security/observed/; the slide writes demo for both. The kernel code cited is mainline at the commit the map describes; the guest kernel is one release older and behaved as that code reads.do_dentry_open returns for O_PATH at open.c:951-956, before security_file_open at open.c:977.vfs_getattr calls security_inode_getattr: stat.c:258-267.who profile: who:14-24.Next: sec-unmediated, prac-symlinks, prac-hardlinks, syn-flags-other, syn-mount, adm-denials, k-match.
O_PATH.mount rule and no capability sys_admin unless the program mounts, and no w on directory names above data protected by name; treat attach_disconnected and chroot_relative as widening flags; restart the program after removing a rule.What each deck answers:
attach_disconnected, chroot_relative, mediate_deleted.name= and info= fields.Basis of the statements on this page: "observed" means run on 2026-11-16 in a disposable Debian forky/sid guest (kernel 7.3.4+deb14-cloud-amd64, apparmor_parser 5.0.2), as root, with the profiles and the test program kept in findings/security/observed/. "Code" means read from the kernel source at the commit the map describes and not run. The guest kernel is a distribution kernel one release older than that source; every observation agrees with the code cited in the scenes.
| Input | Effect on the name | Basis |
|---|---|---|
| the directory entry used | each hard link is its own name | code; see Hard links |
| symlinks on the way | resolved before the check; the target's name is matched | code; see Symlinks |
| the mount the file was reached through | a bind mount's path is the name | observed |
| the task's mount namespace | the name starts at that namespace's root | observed (chroot case), code |
flags=(chroot_relative) | the name starts at the task's root directory | observed |
| a directory | the name ends in / | observed (name="/etc/demo/private/") |
| the moment of the check | a rename before the check changes the name | observed |
All with a profile that has /etc/demo/public r, and no rule for /etc/demo/secret, unless a row says otherwise.
| Case | What was done | Result |
|---|---|---|
| bind mount | mount --bind /etc/demo/secret /etc/demo/public by an unconfined shell, then the confined open of /etc/demo/public | reads "secret data"; no audit record |
| chroot | chroot("/srv/jail"), open /etc/demo/public | denied, name="/srv/jail/etc/demo/public" |
chroot with chroot_relative | the same | allowed; reads the jail's copy |
| directory rename | rules /srv/demo/a/ rw, /srv/demo/c/ rw, /srv/demo/c/** r,; rename a to c | a/secret-notes denied before, c/secret-notes read after |
| rename to a name with no rule | rename a to b2 | denied, operation="rename_dest" name="/srv/demo/b2/" requested_mask="wc" |
| open file renamed | another process moves the open file to a path with no rule | the descriptor keeps reading; a new open is denied |
| profile replaced | apparmor_parser -r with the rule removed, file open | the descriptor keeps reading; a new open is denied |
| file deleted while open | rm by another process | the descriptor keeps reading |
| descriptor from an unconfined parent | exec 3</etc/demo/secret then aa-exec | the confined program reads the secret; no audit record |
| descriptor across a profile-changing exec | opened under profile opener, exec into demo-t | descriptor closed; operation="file_inherit" denied |
| disconnected path | directory descriptor, umount -l, openat | denied, info="Failed name lookup - disconnected path" name="f" |
disconnected with attach_disconnected | the same, rule /f r, | allowed as /f |
O_PATH | open and fstat of the secret | both succeed; re-open through /proc/self/fd/N denied |
info= | Meaning |
|---|---|
Failed name lookup - disconnected path | the path does not reach the root of the mount namespace and the profile has no attach_disconnected |
Failed name lookup - deleted entry | the file is unlinked and neither mediate_deleted nor delegate_deleted is in effect |
Failed name lookup - name too long | the path does not fit the buffer |
operation="file_inherit" is the check of a descriptor carried across an exec; operation="rename_src" and operation="rename_dest" are the two halves of a rename.
mount rule and no capability sys_admin unless the program mounts. A confined program without them cannot create a second name by mounting.w on directory names above data that other rules protect by name: /srv/** rw, allows moving /srv/private/.attach_disconnected and chroot_relative widen a profile. Prefer attach_disconnected.path=.deny rule protects a path, not a file.O_CLOEXEC and a launcher that holds nothing sensitive.| What | Where |
|---|---|
| building the name | d_namespace_path, aa_path_name in linux:security/apparmor/path.c:88-222 |
| disconnected paths | disconnect in linux:security/apparmor/path.c:48-72 |
| the path hooks | linux:security/apparmor/lsm.c:222-463 |
| open and the per-file context | apparmor_file_open, apparmor_file_alloc_security in linux:security/apparmor/lsm.c:465-519 |
| revalidation | aa_file_perm, __file_path_perm in linux:security/apparmor/file.c:490-675 |
| inherited descriptors | aa_inherit_files in linux:security/apparmor/file.c:721-754 |
O_PATH | do_dentry_open in linux:fs/open.c:951-977 |
Under a profile with no rule for a file, opening, listing, chmod and truncate are denied and logged, while stat, readlink, chdir, extended attributes, timestamps and ioctl are not checked at all. Observed in one run.
/etc/demo/secret, no rule): open O_RDONLY, opening the directory /etc/demo/private, chmod, truncate. For example apparmor="DENIED" operation="chmod" class="file" profile="demo-t" name="/etc/demo/secret" comm="t" requested_mask="w" denied_mask="w".stat, access(R_OK), readlink, chdir, open(O_PATH) and fstat, getxattr, listxattr, setxattr, utimensat, and ioctl(FS_IOC_SETFLAGS) on a descriptor opened read-only.7.3.4+deb14-cloud-amd64, apparmor_parser 5.0.2), as root. The run used the profiles demo-t and demo-mnt and the test program t from findings/security/observed/; the slide writes demo. The kernel code cited is mainline at the commit the map describes; the guest kernel is one release older and behaved as that code reads.apparmor_hooks[] registers 81 of the kernel's security hooks. File mediation uses the path_* and file_* hooks plus inode_getattr; the other inode_* hooks, file_ioctl, sb_remount and the IPC and key hooks are not registered. Read from the kernel source.
apparmor_hooks[] with 81 LSM_HOOK_INIT entries: lsm.c:1785-1891. Every hook the kernel has is declared in lsm_hook_defs.h (about 280).capable and capget, mounts (sb_mount, sb_umount, sb_pivotroot, move_mount), ten path_* hooks, inode_getattr, the file hooks, the process attribute interfaces, about twenty socket hooks, credential and exec hooks, task_setrlimit, task_kill, userns_create, two io_uring hooks, and audit and label conversion helpers.inode_permission, inode_readlink, inode_follow_link, inode_setattr, the xattr and ACL hooks, file_ioctl, file_ioctl_compat, file_fcntl, path_chroot, path_notify, sb_remount, sb_kern_mount, the fs_context_* hooks, all System V IPC hooks, key_*, bpf*, perf_event_*, netlink_send, task_setnice, task_setscheduler, task_prlimit, uring_cmd.settime, syslog, module loading, raising priority), and the capability rule is the mediation.stat is always allowed: the get-attribute permission is set for every state of the file table. access, readlink and chdir have no AppArmor check. Opening the file is checked. Observed, also on a file with an explicit deny rule.
stat, lstat, statx, fstat: the kernel calls the get-attribute hook, AppArmor matches the name and asks for the get-attribute permission. That bit is set in every entry of a profile's file permission table, including the entry for "no rule matched", so the request cannot fail.access and faccessat use the inode permission hook, which AppArmor does not register. The result is the owner-and-mode answer: in the run access R_OK: ok on the secret, although opening it for reading is denied.readlink uses the inode readlink hook (not registered). Run: readlink: ok (6), -> secret.chdir and fchdir have no path hook. Run: chdir: ok, cwd=/etc/demo/private; then open relative "inside": FAILED errno=13 with name="/etc/demo/private/inside" in the log.name="/etc/demo/private/" requested_mask="r".deny /etc/demo/denied rwkl, in the profile: open denied, stat: ok, size=12 uid=0 mode=644.7.3.4+deb14-cloud-amd64, apparmor_parser 5.0.2), as root. The run used the profiles demo-t and demo-mnt and the test program t from findings/security/observed/; the slide writes demo. The kernel code cited is mainline at the commit the map describes; the guest kernel is one release older and behaved as that code reads.apparmor_inode_getattr asks for AA_MAY_GETATTR: lsm.c:460-463.compute_fperms_allow sets AA_MAY_GETATTR unconditionally, and compute_fperms runs it for every state from 0: policy_compat.c:100-103, policy_compat.c:166-169. The parser does the same when it writes the permission table itself (see Permissions in the DFA).vfs_getattr stat.c:258-267, security_inode_readlink stat.c:584, chdir and fchdir open.c:550-590, security_inode_permission namei.c:661.chmod, chown and truncate need w and are checked. Extended attributes, ACLs and timestamps are not: setxattr and utimensat succeed on a file with no rule and on a file with a deny rule. Observed. Ownership and capabilities still apply.
w: chmod (operation="chmod"), chown, truncate (operation="truncate"). Run on the secret: both FAILED errno=13, logged with requested_mask="w" denied_mask="w".setxattr, getxattr, listxattr, removexattr, POSIX ACLs (set through the same family of hooks), and timestamp changes with utimensat or futimens.getxattr user.note: ok (8), value=original; setxattr user.note=changed: ok (0); utimensat (set atime and mtime to 1970): ok (0). Afterwards, unconfined: user.note="changed" and 1970-01-01 00:00:01.000000000 +0000./etc/demo/denied under deny /etc/demo/denied rwkl,: setxattr ok, utimensat ok, no audit record.CAP_FOWNER; user.* attributes need write permission by the file's mode; trusted.* needs CAP_SYS_ADMIN; security.* attributes have their own checks. A confined task has a capability only when its profile has the capability rule.xattrs= attachment condition reads attributes that the owner of an executable can set.7.3.4+deb14-cloud-amd64, apparmor_parser 5.0.2), as root. The run used the profiles demo-t and demo-mnt and the test program t from findings/security/observed/; the slide writes demo. The kernel code cited is mainline at the commit the map describes; the guest kernel is one release older and behaved as that code reads.security_inode_setxattr and siblings: xattr.c:309, xattr.c:461, xattr.c:511, xattr.c:571; security_inode_setattr in notify_change: attr.c:540. None has an AppArmor function.apparmor_path_truncate lsm.c:350-358, apparmor_path_chmod and apparmor_path_chown lsm.c:450-458.File rules decide who gets a descriptor and whether it may be read, written, mapped or locked. ioctl and fcntl are not checked. Observed: FS_IOC_SETFLAGS succeeds on a file opened with only r allowed.
read and write (file_permission), mmap and mprotect (the m permission for executable mappings), flock and POSIX locks (k), ftruncate, and receiving a descriptor from another process.ioctl (the file_ioctl hook is not registered), fcntl (file_fcntl: F_SETFL, F_SETOWN, leases, seals), and O_PATH opens (see The limits of name-based mediation).open O_RDONLY: ok (3) on /etc/demo/public (rule: r), ioctl FS_IOC_GETFLAGS: ok (0), flags=0x80000, ioctl FS_IOC_SETFLAGS (add noatime) on the read-only fd: ok (0), flags=0x80080; afterwards lsattr prints -------A------e-------. No audit record. Setting that flag needs ownership of the file, which the task had./dev/kvm, graphics and input devices. A rule such as /dev/dri/card0 rw, hands over all of it.7.3.4+deb14-cloud-amd64, apparmor_parser 5.0.2), as root. The run used the profiles demo-t and demo-mnt and the test program t from findings/security/observed/; the slide writes demo. The kernel code cited is mainline at the commit the map describes; the guest kernel is one release older and behaved as that code reads.security_file_ioctl: ioctl.c:592 (compat ioctl.c:648); security_file_fcntl: fcntl.c:603. Neither is in apparmor_hooks[].apparmor_file_permission and apparmor_file_lock lsm.c:547-560, common_mmap lsm.c:562-582.AppArmor checks mount(2), umount, pivot_root and move_mount. mount_setattr, an fsconfig reconfigure and a mount built with fsopen and fsmount passed a profile that denies the same thing through mount(2). Observed; all need CAP_SYS_ADMIN.
sb_mount (the mount system call: new mounts, remounts, binds, moves, propagation changes), sb_umount, sb_pivotroot, move_mount.mount_setattr(2) changes per-mount attributes (read-only, nosuid, nodev, noexec, propagation) and calls no security hook.fspick plus fsconfig(FSCONFIG_CMD_RECONFIGURE) changes superblock options and reaches only the sb_remount hook, which AppArmor does not register.fsopen, fsconfig(FSCONFIG_CMD_CREATE) and fsmount create a mount that is attached with move_mount. AppArmor checks that last step as a move with no source, so a rule about a file system type or about flags is not consulted.open_tree(OPEN_TREE_CLONE) plus move_mount makes a bind mount the same way.capability sys_admin, mount, umount, deny remount, deny mount fstype=tmpfs,: mount(MS_REMOUNT|MS_BIND|MS_RDONLY): FAILED errno=13; mount_setattr(MOUNT_ATTR_RDONLY): ok, and /proc/self/mountinfo shows /mnt/x ro,relatime; fspick: ok, fsconfig(FSCONFIG_SET_FLAG, ro): ok, fsconfig(FSCONFIG_CMD_RECONFIGURE): ok, and mountinfo shows the superblock ro; mount("none", DIR, "tmpfs"): FAILED errno=13; fsopen(tmpfs): ok, fsconfig(FSCONFIG_CMD_CREATE): ok, fsmount: ok, move_mount onto DIR: ok, and mountinfo shows a tmpfs on /mnt/y. No audit record for the successful calls.mount, with deny mount options in (rbind,bind) /mnt/src/ -> **,: mount(SRC, DST, MS_BIND): FAILED errno=13; open_tree(SRC, OPEN_TREE_CLONE): ok, move_mount onto DST: ok.open_tree and move_mount is checked as a move without a source, so deny mount options in (bind) does not stop mount --bind". Whether they are defects or limits of the hook set is for the maintainers; the behaviour is observed.CAP_SYS_ADMIN over the mount namespace. A profile with no capability sys_admin, rule is not affected. A profile with no mount rule at all still refuses move_mount, so nothing new can be attached, but mount_setattr and a reconfigure go through.7.3.4+deb14-cloud-amd64, apparmor_parser 5.0.2), as root. The run used the profiles demo-t and demo-mnt and the test program t from findings/security/observed/; the slide writes demo. The kernel code cited is mainline at the commit the map describes; the guest kernel is one release older and behaved as that code reads.do_mount_setattr (no hook): namespace.c:5102; security_sb_remount in reconfigure_super: super.c:1049; security_sb_kern_mount: fsopen.c:241; open_tree: namespace.c:3376.aa_move_mount drops a detached source and checks a move: mount.c:424-456.System V IPC and kernel keys have no AppArmor hook: they work under any profile, subject to their own owner and mode. A POSIX message queue is refused as a disconnected file, not by an mqueue rule. Sockets, signals, ptrace and capabilities are mediated. Observed.
shmget, shmat, msgget, semget and the calls on them): the kernel's hooks ipc_permission, shm_*, msg_queue_* and sem_* have no AppArmor function. A shared memory segment is also a file, but on a kernel-internal mount that AppArmor skips. Run: shmget: ok, shmat: ok, msgget: ok.key_permission is not registered. Run: add_key(user, demo): ok.mqueue rule class, and this kernel has no hook for it (see mqueue rules and Upstream and Ubuntu). The queue is a file on the internal mqueue mount, so mq_open reaches the file-open check with a path that does not connect to the root. Run: mq_open /demo-queue: FAILED errno=13 and apparmor="DENIED" operation="open" class="file" info="Failed name lookup - disconnected path" error=-13 profile="demo-t" name="demo-queue" comm="t" requested_mask="wrc" denied_mask="wrc".flags=(attach_disconnected) and the file rule /demo-queue rw, the same mq_open succeeds (second run): the queue is then governed by a file rule for a path at the root.socket(AF_INET, SOCK_STREAM): FAILED errno=13, apparmor="DENIED" operation="create" class="net" info="failed af match" ... family="inet" sock_type="stream".CAP_BPF, CAP_PERFMON, CAP_SYS_ADMIN and two sysctls), changing another process's priority or scheduler (same user or CAP_SYS_NICE), netlink messages after the socket exists.7.3.4+deb14-cloud-amd64, apparmor_parser 5.0.2), as root. The run used the profiles demo-t and demo-mnt and the test program t from findings/security/observed/; the slide writes demo. The kernel code cited is mainline at the commit the map describes; the guest kernel is one release older and behaved as that code reads.mqueue rule and for one without; see Kernel features and the policy ABI.security_ipc_permission: util.c:571; security_key_permission: permission.c:90. Neither is in apparmor_hooks[].SB_NOUSER shmem.c:5234-5236, and path_mediated_fs skips such file systems lib.h:146-149.apparmor_socket_create: lsm.c:1258-1304.File rules cover opening, creating, deleting, linking, renaming, and changing mode, owner and length. They do not cover metadata, extended attributes, timestamps or ioctl. Ownership, capability rules and other kernel mechanisms cover those. Unmediated operations are never logged.
capable is in the hook table), and a confined task has a capability only when its profile says so. Changing another user's file, mounting, chroot, raw sockets, loading modules, setting the clock, tracing another user's processes: all need one.aa-logprof cannot propose a rule for it and none is needed. The shipped who profile documents such a pair of calls in a comment.apparmor_capable: lsm.c:199-215, registered at lsm.c:1789.who profile's comment about unmediated calls: who:14-24.Next: sec-path-limits, syn-access-modes, syn-capability, syn-mount, prac-privileged, upstream-and-ubuntu, k-overview.
access, readlink, chdir; extended attributes, ACLs and timestamps; ioctl and fcntl; O_PATH opens; mount_setattr, fsconfig reconfigure and mounts built with fsopen and fsmount; System V IPC and kernel keys.What each deck answers:
Basis of the statements on this page: "observed" means run on 2026-11-16 in a disposable Debian forky/sid guest (kernel 7.3.4+deb14-cloud-amd64, apparmor_parser 5.0.2), as root, with the profiles and the test program kept in findings/security/observed/. "Code" means read from the kernel source at the commit the map describes and not run. The guest kernel is a distribution kernel one release older than that source; every observation agrees with the code cited in the scenes. Distribution kernels with extra AppArmor patches can differ: see Upstream and Ubuntu.
| Operation | AppArmor | Why | Basis | What still applies |
|---|---|---|---|---|
open for read, write, append | checked | file_open | observed | |
| listing a directory | checked (an open) | file_open | observed | |
chmod, chown, truncate | checked, need w | path_chmod, path_chown, path_truncate | observed | |
create, delete, mkdir, rmdir, mknod, symlink | checked | path_* hooks | code | |
| hard link, rename | checked | path_link, path_rename | observed (rename) | |
mmap with PROT_EXEC, mprotect | checked, need m | mmap_file, file_mprotect | code | |
flock, POSIX locks | checked, need k | file_lock | code | |
stat, fstat, statx | always allowed | get-attribute bit set in every table entry | observed | search permission on the directories |
access, faccessat | not checked | inode_permission not registered | observed | owner and mode |
readlink | not checked | inode_readlink not registered | observed | |
chdir, fchdir | not checked | no path hook | observed | search permission |
| walking through directories | not checked | inode_permission not registered | code | search permission |
open(O_PATH) | not checked | the kernel returns before the hook | observed | |
getxattr, listxattr | not checked | xattr hooks not registered | observed | mode; attribute namespace rules |
setxattr, removexattr, ACLs | not checked | xattr and ACL hooks not registered | observed (setxattr) | owner, mode, CAP_FOWNER, CAP_SYS_ADMIN for trusted.* |
utimensat, futimens | not checked | inode_setattr not registered | observed | owner or CAP_FOWNER |
ioctl | not checked | file_ioctl not registered | observed | the driver's own checks; capabilities |
fcntl | not checked | file_fcntl not registered | code | |
mount(2), umount, pivot_root, move_mount | checked | sb_mount, sb_umount, sb_pivotroot, move_mount | observed (mount) | CAP_SYS_ADMIN |
mount_setattr | not checked | no hook in the kernel | observed | CAP_SYS_ADMIN |
fsconfig reconfigure | not checked | sb_remount not registered | observed | CAP_SYS_ADMIN |
fsopen + fsmount | checked only as a move at move_mount | sb_kern_mount, fs_context_* not registered | observed | CAP_SYS_ADMIN |
open_tree(OPEN_TREE_CLONE) | checked only as a move at move_mount | no hook | observed | CAP_SYS_ADMIN |
| System V shm, msg, sem | not checked | IPC hooks not registered | observed (shm, msg) | object owner and mode; IPC namespace |
| kernel keys | not checked | key_permission not registered | observed | key permissions |
| POSIX message queue | refused as a disconnected file | no mqueue hook; the queue is a file on an internal mount | observed | |
| sockets, signals, ptrace, capabilities, rlimits, exec, user namespace creation | checked | their own hooks and rule classes | observed (inet socket), code |
mqueue rule, is in Kernel features and the policy ABI.| Letter | Covers | Does not cover |
|---|---|---|
r | open for reading, reading a directory | stat, readlink, getxattr (never checked) |
w | open for writing, create, delete, rename, chmod, chown, truncate | setxattr, ACLs, timestamps, ioctl |
a | open for appending | |
l | creating a hard link at this name | |
k | file locks | |
m | executable mappings | |
x with a mode | execution |
An operation in the "not checked" rows never appears in the audit log, in enforce or in complain mode. When strace shows such a call and aa-logprof proposes nothing for it, the profile is complete as far as AppArmor is concerned.
| What | Where |
|---|---|
| the hook table | apparmor_hooks[], linux:security/apparmor/lsm.c:1785-1891 |
| every hook the kernel defines | linux:include/linux/lsm_hook_defs.h |
| get-attribute always allowed | compute_fperms_allow, linux:security/apparmor/policy_compat.c:100-103 |
| file systems skipped | path_mediated_fs, linux:security/apparmor/include/lib.h:146-149 |
O_PATH | linux:fs/open.c:951-956 |
| xattr hooks | linux:fs/xattr.c:309, 461, 511, 571 |
| setattr hook | linux:fs/attr.c:540 |
| ioctl and fcntl hooks | linux:fs/ioctl.c:592, linux:fs/fcntl.c:603 |
mount_setattr | linux:fs/namespace.c:5102 |
| remount hook | linux:fs/super.c:1049 |
| move_mount as checked by AppArmor | linux:security/apparmor/mount.c:424-456 |
A stack is a set of profiles that all confine one task. An access is allowed only when every confined member allows it, so the result is the intersection. Stacking adds a profile; it does not replace the current one.
fn_for_each_confined(label, profile, profile_path_perm(...)) (file.c:302-304, label.h:225-236).aa_stack_profile(), aa_stack_onexec(), an exec rule with -> &NAME, and aa-exec -p "a//&b"./sys/kernel/security/apparmor/features/domain/stack (apparmorfs.c:2606).EACCES and a file allowed by both passes (stackprofile.sh:85-90).foo and baz and the files on the slide are invented for the map. Kernel behaviour is stated from the source, not observed on a running kernel.name1//&name2 (mode). Members are sorted (namespace depth, then namespace name, then profile name) and unique. The mode is the members' common mode, or mixed. aa_getcon and aa_splitcon separate only the trailing mode; nothing in libapparmor splits on //&.
name1//&name2 (mode). Read it from /proc/PID/attr/current or /proc/PID/attr/apparmor/current, with ps -Z, or in code.int aa_getcon(char **label, char **mode), int aa_gettaskcon(pid_t target, char **label, char **mode), char *aa_splitcon(char *con, char **mode) (kernel.c:1280-1283). They cut off the trailing (mode) only; nothing in libapparmor splits a label on //& (kernel.c:556-633).mixed when they differ; a namespace's unconfined is skipped (label.c:1579-1608).mixed is not a profile mode. aa-status has it only in its list of process statuses (aa_status.c:134).enforce for two enforcing profiles, mixed and complain for the other combinations (stackprofile.sh:90, stackprofile.sh:148, stackprofile.sh:170). The tests compare member sets; the printed order is derived from the kernel's sort.aa-exec -p "unconfined//&firefox" -- bash, then ps -Z prints firefox//&unconfined (unconfined) (aa-exec.pod:108-118).From an unconfined task, stack baz yields baz//&unconfined (enforce). Access checks equal those of baz, but by the kernel's exec rules the unconfined member still takes part in exec and attaches profiles by executable path. This differs from aa_change_profile("baz"), whatever aa_stack_profile(3) says.
echo -n "stack baz" > /proc/self/attr/current, then cat /proc/self/attr/current. By the kernel's sort the label reads baz//&unconfined (enforce).unconfined from the result.unconfined//& plus the stacked profile, with mode enforce, and fails a check for mode (null) (stackprofile.sh:68-76).baz//&unconfined that starts /usr/bin/foo becomes baz//&foo when baz has ix for it. This result is derived from the code and was not run.firefox//&unconfined (unconfined), where that firefox profile has flags=(unconfined) (aa-exec.pod:108-118).aa_stack_profile(name) writes stack name to attr/current and takes effect at once. aa_stack_onexec(name) writes stack name to attr/exec and takes effect at the next execve, keeping the current profile. Errors: EACCES (no rule), ENOENT (not loaded), EINVAL (NULL).
int aa_stack_profile(const char *profile); - int aa_stack_onexec(const char *profile);aa_stack_profile writes stack NAME to the current attribute, aa_stack_onexec writes stack NAME to the exec attribute (kernel.c:1204-1244). The write goes through the lsm_set_self_attr system call when it is available, otherwise /proc/TID/attr/apparmor/current or /proc/TID/attr/current (kernel.c:997-1012).echo -n "stack profile_a" > /proc/self/attr/current and echo -n "stack profile_a" > /proc/self/attr/exec.changehat, permhat, changeprofile, permprofile and stack on current, and exec and stack on exec (lsm.c:882-904).execve; the members in the task's namespace keep their profile, get the target added, and their own exec rules are not used (domain.c:1629-1636, domain.c:953-961).EINVAL, ENOMEM, ENOENT (aa_stack_profile.pod:84-98). EACCES for a missing rule is not listed there; the regression tests expect it, and ENOENT for a profile that is not loaded (stackprofile.sh:80, stackprofile.sh:97, stackonexec.sh:81-98)./proc/*/attr/current w, or /proc/*/attr/exec w,.A stack request is matched as &name. change_profile -> baz, permits changing to baz; change_profile -> &baz, permits stacking it; change_profile, permits both; unconfined tasks need no rule. Without a matching rule the call fails with EACCES. The parser accepts the & rule when both the kernel and the profile's ABI have domain/stack; a profile file with no abi rule fails with The current kernel does not support stacking of named transitions: &baz.
change_profile -> baz, permits a change to baz; change_profile -> &baz, permits stacking it; change_profile, permits both. With an exec condition: change_profile /bin/foo -> &bar,.change_profile -> &/bin/foo,), stacking_ok_2.sd (-> &bar), stacking_ok_3.sd (with an exec condition).& in front of the name, and a namespaced target as :, namespace, :, name (domain.c:94-112). A target that is itself a stack is tried as a whole and then member by member (domain.c:256-271).EACCES: stackprofile.sh:94-97. The bare rule is what the regression test uses to stack a bare namespace: change_profile, then stack :ns: (stackprofile.sh:174-181). That change_profile -> baz, does not permit stacking baz follows from the kernel's match and is not asserted by a test.The current kernel does not support stacking of named transitions: %s (parser_regex.c:742-755). It is printed when the kernel features or the profile's ABI lack domain/stack (parser_main.c:1093-1095); the parser's built-in default ABI, used for a file with no abi rule, has no stack entry in domain (default_features.c:169). Put abi <abi/3.0>, or newer in the file./proc/PID/attr/current, so the profile needs a file rule for it; the regression test's profile has /proc/*/attr/current w, next to change_profile-> &:nnp:unconfined, (nnp.sh:104-110).** (parser_yacc.y:1648-1690).& included, is compiled as one string (parser_regex.c:760-762).change_profile_perms() is called per profile from the wrapper at domain.c:1458-1461.PATH ix -> &baz, gives the current profile plus baz when no profile attaches to PATH. PATH px -> &baz, gives the profile attached to PATH plus baz, and by the kernel code the exec fails with info="profile transition not found" when nothing attaches. The current profile stays only with ix or with aa_stack_onexec.
/bin/bar px -> &baz, or /bin/bar ix -> &baz,. No space between & and the name. Parser test: stacking_ok_1.sd.& is kept aside as the stack, and the kernel then runs the ordinary search for a profile attached to the program (domain.c:592-611). The lookup of the target skips the & (domain.c:540).ix keeps the current profile, ux gives the namespace's unconfined (domain.c:616-638). With px there is no base and the exec fails with info="profile transition not found" (domain.c:740-751). The px cases are derived from the code and were not run.ix case is tested: ix -> &othertest gives the label test//&othertest in mode enforce (exec_stack.sh:83-90); a namespaced target, ix -> &:ns:name, is at exec_stack.sh:120.&; /bin/bar px -> &, is accepted by the parser built from the AppArmor tree at 836052d21.cx -> &name in profile t is stored as t//&name, which the kernel reads as the stack of t and a top-level profile name, not a child (kernel side read, not run).-> and the two file rule productions (parser_yacc.y:1043-1047, parser_yacc.y:1072-1103).add_named_transition() stores the string with its &; for cx it prefixes the profile name and // (block_rules.cc:474-524).By the kernel code, at execve each member computes its own transition; the resulting labels are merged, sorted and de-duplicated. One member's refusal fails the exec. A stack can shrink (two px to the same profile) or grow (px -> &name).
All from the kernel source; the example labels are derived from the code and were not run.
execve the kernel builds the new label by running the transition for each member and merging the results (domain.c:1032-1035). The helper is fn_label_build (lib.h:289-343).profile_transition(): it matches the program's path against that member's rules and returns stay (ix), another profile (px, cx), unconfined (ux) or an error (domain.c:665-796).bar leave the single profile bar.unconfined searches for an attached profile, as an unconfined task does.AT_SECURE for the new program (domain.c:778-783, domain.c:1070-1078).Each denying member writes its own record with profile="<that member>" (and namespace= if it is not in the root namespace). The //& text appears in target= and peer= fields. Stack requests are logged as operation="stack" or operation="stack_onexec". The record shown is built from the order in which the kernel prints fields; it was not captured from a running system.
Read from the kernel source. The record on the slide is built from the order in which the kernel prints fields; it was not captured from a running system.
baz//&foo: apparmor="DENIED" operation="open" class="file" profile="baz" name="/var/log/foo.log" ... requested_mask="w" denied_mask="w" fsuid=... ouid=....aa_audit() sets the subject of the record to that one profile (audit.c:207-224).profile= holds one name; namespace= is printed in front of it when the profile is not in the root namespace. label= is used only when the subject is a label of several profiles (audit.c:116-133).ALLOWED for its own miss, an enforcing member logs DENIED (audit.c:211-214).target= carries the full label for exec, change_profile and stack records (file.c:69-72); peer= carries it for signals and sockets (ipc.c:73-75, net.c:162-164).operation="stack" and operation="stack_onexec" (audit.h:97-98).//& in these fields was not determined; there is no stacked record among the log fixtures in the AppArmor tree.With no_new_privs: aa_change_profile, aa_change_onexec, px and ux to a label that drops a confining profile fail with EPERM (info="no new privs" on exec); aa_stack_profile, aa_stack_onexec and ix work. Transitions from unconfined are not restricted.
no_new_privs is set with prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0).unconfined, otherwise it fails with EPERM and info="no new privs" (domain.c:1050-1056).aa_label_is_unconfined_subset() (label.c:561-593).aa_change_profile the same test applies, with EPERM and no audit record ("not an apparmor denial per se, so don't log it"); a stack request skips it: "stacking is always a subset, so only check the nonstack case" (domain.c:1597, domain.c:1609-1618)./sys/kernel/security/apparmor/features/domain/post_nnp_subset (apparmorfs.c:2608).ix passes; ux, px, change on exec and change profile fail with EPERM; stack on exec and stack profile pass. Stacking the unconfined profile of a new namespace also passes (nnp.sh:101-123).apparmor="DENIED" operation="change_onexec" info="no new privs" error=-1 ... target="system_tor" (change_onexec_lp1648143.in).prctl call.In host//&:c1:foo the task's namespace is c1. Changing profile, changing hat and on-exec requests ask and replace only the c1 members; host is carried over unchanged and still checked on every access. The host reads the full label; the task reads foo (enforce).
Read from the kernel source, unless a test is named.
host//&:c1:foo seen from the root namespace. The rule that lets host add it: change_profile -> &:c1:foo,; the call: aa_stack_profile(":c1:foo"), which writes stack :c1:foo.foo (enforce), the host reads the whole label.change_profile -> &:ns:stackprofile, stacks the namespaced profile; a file that only one of the two allows fails with EACCES, and the task reads its own label as stackprofile in mode enforce (stackprofile.sh:117-139).aa-exec -p "unconfined//&:ex1:unconfined" -- bash, ps -Z inside shows unconfined, and from the parent unconfined//&:ex1:unconfined (aa-exec.pod:167-182).aa_label_merge (label.c:1248) unions two sorted vectors; order is profile_cmp (label.c:109-155). Hooks iterate with fn_for_each_confined (include/label.h:225-236); exec uses fn_label_build (include/lib.h:289-343). The parser stores &name as text (block_rules.cc:474-524, parser_regex.c:760-762).
& may start a label token (parser_lex.l:253, parser_lex.l:301-302).add_named_transition() puts the target, & included, into the exec table (block_rules.cc:474-524); a change_profile target is compiled as text (parser_regex.c:742-762).x_table_lookup() skips the leading & (domain.c:523-559); x_to_label() keeps the result as stack, falls through to the attachment search and merges (domain.c:574-663).do_setattr() maps stack to aa_change_profile(args, AA_CHANGE_STACK), and on the exec attribute to AA_CHANGE_ONEXEC | AA_CHANGE_STACK (lsm.c:873-904); int aa_change_profile(const char *fqname, int flags) does the parse, the permission check per in-scope profile and the merge (domain.c:1484-1655).struct aa_label has size and vec[], a vector of profile pointers (label.h:127-147).ns_cmp() and profile_cmp(), by namespace level, namespace name, profile name (label.c:109-155). aa_vec_unique() sorts and de-duplicates (label.c:274-318).aa_label_next_in_merge() zips two sorted vectors and returns equal heads once (label.c:994-1023); label_merge_insert() returns the existing label when nothing was added (label.c:1100-1141); aa_label_merge(a, b, gfp) returns a for a == b (label.c:1248-1275).fn_for_each_confined in the hooks (label.h:185-188, label.h:225-236); fn_label_build at exec (lib.h:289-343).strings on the binary policy for /bin/bar px -> &baz, shows &baz (apparmor_parser 6.0.0~alpha2, 836052d21).Next: attachment and namespaces (the sister decks), syn-change-profile and lib-change-profile (the rule and the calls), lib-labels and adm-denials (reading labels and records), k-labels (the kernel side).
//&.aa_stack_profile(), aa_stack_onexec(), the stack command on /proc/PID/attr/current and /proc/PID/attr/exec, the rules change_profile -> &NAME, and PATH ix -> &NAME,, aa-exec -p "a//&b", and features/domain/stack in apparmorfs.//& shows up in target= and peer=.name1//&name2 (mode)
//&, followed by one mode for the whole label. A member may carry a namespace: :ns:name or :ns://name.foo that stacks baz reads baz//&foo. The order carries no priority; every member is asked for every operation.enforce when all visible members enforce, complain when all complain, mixed when they differ. mixed is not a profile mode; aa-status lists it as a process status. A namespace's unconfined profile is skipped when the mode is computed.c1 seen from the parent print as :c1:a//&b. On input, a member without a namespace is looked up in the namespace of the last member that named one.:ns:, :ns:// and :ns name that namespace's unconfined profile.&.** On input to the kernel a leading & means "stack on top of the current label".//& cannot be told apart from a stack. Compare labels as whole strings.All profiles are in enforce mode and in the root namespace unless stated. "test" means a regression test in the AppArmor tree asserts the member set and the mode; "derived" means the result follows from the kernel code and was not run. The order of members in a printed label is always derived from the kernel's sort.
| Start label | Action | Label read from the root namespace | Basis |
|---|---|---|---|
foo | aa_stack_profile("baz") with change_profile -> &baz, in foo | baz//&foo (enforce) | test: stackprofile.sh:90 |
baz//&foo | aa_stack_profile("baz") | baz//&foo (enforce), unchanged | derived |
unconfined | echo -n "stack baz" > /proc/self/attr/current | baz//&unconfined (enforce) | test: stackprofile.sh:74 |
unconfined | aa-exec -p "unconfined//&firefox" -- bash | firefox//&unconfined (unconfined); that firefox profile has flags=(unconfined) | aa-exec(1) |
foo (enforce) | stack baz (complain) | baz//&foo (mixed) | test: stackprofile.sh:148 |
foo (complain) | stack baz (complain) | baz//&foo (complain) | test: stackprofile.sh:170 |
a | stack b, then exec and stack c | a//&b//&c (enforce) | test: stackprofile.sh:108 |
foo | exec /bin/bar with /bin/bar ix -> &baz,; no profile attaches to /bin/bar | baz//&foo (enforce) | test (shape): exec_stack.sh:83-90 |
foo | exec /bin/bar with /bin/bar px -> &baz,; profile bar attaches | bar//&baz (enforce) | derived |
baz//&foo | exec; foo has px and bar attaches, baz has ix | bar//&baz (enforce) | derived |
baz//&unconfined | exec /usr/bin/foo; baz has ix, profile foo attaches | baz//&foo (enforce) | derived |
host | aa_stack_profile(":c1:foo") with change_profile -> &:c1:foo, | host//&:c1:foo (enforce); the task itself reads foo (enforce) | test (self view): stackprofile.sh:120-139 |
host//&:c1:foo | inside: aa_change_profile("baz") with change_profile -> baz, in :c1:foo | host//&:c1:baz (enforce); self view baz (enforce) | derived |
unconfined | aa-exec -p "unconfined//&:ex1:unconfined" -- bash | unconfined//&:ex1:unconfined; self view unconfined | aa-exec(1) |
baz//&foo, both with hat worker | aa_change_hat("worker", token) | baz//worker//&foo//worker (enforce) | derived |
foo, no_new_privs set | aa_change_profile("baz") with a matching rule | fails with EPERM; label stays foo | test: nnp.sh:69 |
foo, no_new_privs set | aa_stack_profile("baz") with change_profile -> &baz, | baz//&foo (enforce) | test: nnp.sh:83 |
Text written to the kernel in each case:
| Call | Text | File |
|---|---|---|
aa_stack_profile("baz") | stack baz | attr/current |
aa_stack_profile(":c1:foo") | stack :c1:foo | attr/current |
aa_stack_onexec("baz") | stack baz | attr/exec |
aa_change_profile("baz") | changeprofile baz | attr/current |
aa-exec -p "unconfined//&firefox" | exec unconfined//&firefox | attr/exec |
FILEGLOB ACCESS -> &TARGET, ACCESS FILEGLOB -> &TARGET, change_profile [safe] [EXEC] -> &TARGET, change_profile [unsafe] [EXEC] -> &TARGET,
ix, px, ux and their variants). No space is allowed between & and TARGET.name, :ns:name, :ns://name, a quoted name, or several members joined with //& (&a//&b). On change_profile rules it may contain globs: change_profile /bin/x -> &:ns:**,.change_profile -> baz, permits a change to baz and not a stack; change_profile -> &baz, permits the stack and not the change; bare change_profile, permits both. An unconfined task needs no rule. When the requested target is itself a stack, the kernel accepts a rule for the whole string (&a//&b) or rules for each member./proc/*/attr/current w, for aa_stack_profile, /proc/*/attr/exec w, for aa_stack_onexec.Accepted and rejected (seen with apparmor_parser 6.0.0~alpha2 (836052d21), -Q -K --skip-kernel-load, abi/5.0 kernel features; "with domain/stack" means abi <abi/5.0>, in the file):
| Rule | Result |
|---|---|
/bin/bar px -> &baz, | accepted |
/bin/bar ix -> &baz, and the pix and ux variants | accepted |
/bin/bar px -> &:ns:baz, and &:ns://baz | accepted |
/bin/bar px -> &a//&b, | accepted |
/bin/bar px -> "&b c", | accepted (quoted target) |
/bin/bar px -> & baz, | syntax error, unexpected TOK_ID, expecting TOK_END_OF_RULE |
/bin/bar x -> &baz, | Invalid perms, 'x' must be preceded by exec qualifier 'i', 'p', or 'u' |
change_profile -> &bar, | accepted when both the kernel and the profile's ABI have domain/stack; a profile with no abi rule fails with The current kernel does not support stacking of named transitions: &bar |
change_profile /bin/x -> &:ns:**, | accepted with domain/stack |
change_profile safe /bin/x -> &b, | accepted with domain/stack |
change_profile -> a//&b, | accepted: permission to change to the stack a//&b |
change-profile -> &x, | Lexer found unexpected character: '-' (0x2d) in state: INITIAL |
profile &foo { } | Profile names must begin with a '/' or a namespace |
int aa_stack_profile(const char *profile); int aa_stack_onexec(const char *profile); int aa_getcon(char **label, char **mode); int aa_gettaskcon(pid_t target, char **label, char **mode); char *aa_splitcon(char *con, char **mode);
aa_stack_profile formats stack NAME and writes it to the task's current attribute: through lsm_set_self_attr when available, otherwise /proc/<tid>/attr/apparmor/current, otherwise /proc/<tid>/attr/current. It takes effect when the call returns. Files that are already open are not rechecked, and without an execve there is no memory barrier between the code before and after the call.aa_stack_onexec writes the same stack NAME to the exec attribute. Permission is checked at once; the label changes at the next execve. The pending request can be read back from /proc/PID/attr/exec.stack a//&b adds several members at once.| errno | When |
|---|---|
EINVAL | NULL argument (checked in the library before any write); a missing argument in the written text |
ENOMEM | out of memory |
ENOENT | the profile, or its namespace, is not loaded or not visible |
EACCES | no rule in the task's profile permits the stack (not listed in the manual page) |
EPERM | a tracer of the task may not trace the new label (not listed in the manual page) |
aa_getcon and aa_gettaskcon return the label of a stacked task as one string with //& inside, and one mode. aa_splitcon searches backwards for ( and cuts there; nothing in libapparmor splits a label on //&. A task that is plainly unconfined has no mode (*mode is NULL).Command words accepted by the attribute files:
| File | Commands |
|---|---|
/proc/PID/attr/current | changehat, permhat, changeprofile, permprofile, stack |
/proc/PID/attr/exec | exec, stack |
The first space ends the command. A name that itself starts with & turns any of the profile commands into a stack request, so changeprofile &baz stacks baz. A write is limited to one page.
PATH ix -> &x,** The kernel first runs the ordinary lookup for a profile attached to PATH. When none attaches, the current profile is kept and x is added. When one does attach, that profile is the base.PATH px -> &x,** The base is the profile attached to PATH; the current profile is not in the result. When nothing attaches the exec fails with EACCES and info="profile transition not found" (derived).PATH ux -> &x,** As ix, but the fallback base is the namespace's unconfined.px to the same profile) or grow (px -> &x). aa-exec(1) puts it this way: each profile gets to specify its transition and the results are brought together to form a new stack.unconfined member** behaves as an unconfined task does: it looks for a profile attached to the program and otherwise stays unconfined.aa_stack_onexec: in-scope members are kept and the target is added. aa_change_onexec: in-scope members are replaced by the target. In both cases those members need the on-exec permission for the program (info="no change_onexec valid for executable" otherwise) and their exec rules are not used; members from outer namespaces run their normal exec transition.AT_SECURE.** A stack-on-exec sets AT_SECURE for the new program unless the change_profile rule says unsafe; so does any member whose exec rule asks for a safe exec.unconfined.prctl call. A profile stacked after that point is not part of it, so policy may drop it again later while keeping the saved members.domain/post_nnp_subset in its features directory.| Under no_new_privs | Result | Test (tests/regression/apparmor/nnp.sh) |
|---|---|---|
ix exec | allowed | :47-48 |
ux exec | EPERM | :54 |
px exec | EPERM, record with info="no new privs" and error=-1, one per member | :59 |
aa_change_onexec | EPERM | :64 |
aa_change_profile | EPERM, no audit record | :69 |
aa_stack_onexec | allowed | :78 |
aa_stack_profile | allowed | :83 |
x//&unconfined moving to x//&y | allowed: the unconfined member of the saved label is ignored | :92-98 |
stacking :nnp:unconfined, a new namespace | allowed | :121 |
Transitions from an unconfined task are not restricted.
profile="<that member>", preceded by namespace="..." when the member is not in the root namespace (for a child c1 of the root the value is root//c1). Members that allowed the access write nothing; two refusing members write two records.ALLOWED for its own miss; an enforcing member logs DENIED and the operation fails. A complain-mode member does not make the stack permissive.baz//&foo, in the order the kernel prints the fields (not captured from a running system):apparmor="DENIED" operation="open" class="file" profile="baz" name="/var/log/foo.log" ... requested_mask="w" denied_mask="w" fsuid=... ouid=...
| Field | When it carries //& |
|---|---|
target= | exec, change_profile and stack records: the new or requested label |
peer= | signal, ptrace and socket records: the other task's label |
label= | records whose subject is the whole label: a rejected attribute command (operation="setprocattr") and policy management |
profile= | not for a stack: one member per record |
| Record text | Meaning |
|---|---|
operation="stack" | an aa_stack_profile request |
operation="stack_onexec" | an aa_stack_onexec request |
info="label not found" | the target does not exist (ENOENT) |
info="failed to build target label" | the kernel could not build the new label |
info="no change_onexec valid for executable" | a pending on-exec request without permission for this program |
info="no new privs" | exec refused by the no_new_privs test |
info="profile transition not found" | px with nothing attached |
info="ix fallback", info="ux fallback" | a named or stacked target fell back to ix or ux |
info="change_profile unprivileged unconfined converted to stacking" | see Other effects below |
info="ptrace prevents transition" | a tracer may not trace the new label |
What aa-logprof and the libapparmor log parser do with //& in these fields was not determined; there is no stacked record among the log fixtures in the tree. Reading denials in general: adm-denials.
c1, aa_change_profile("baz") means :c1:baz. The target namespace must exist and be the task's namespace or below it, otherwise ENOENT.:NS:NAME, :NS://NAME, or bare :NS: for the namespace's unconfined. Rule: change_profile -> &:NS:NAME,.aa-exec -p "unconfined//&:ex1:unconfined" -- bash. Inside, ps -Z shows unconfined for the shell and - for processes outside the namespace; from the parent the shell is unconfined//&:ex1:unconfined.aa_stack_onexec of a bare :ns: leaves the task reading unconfined with no mode: it is in the namespace's unconfined, stacked under its old profile (stackonexec.sh:178-180).baz//worker//&foo//worker. When no supplied name fits, the error is ENOENT with info="hat not found" if any in-scope member has children, else ECHILD with info="no hats defined". Stacking a second profile onto a program that uses hats breaks its aa_change_hat calls unless the second profile defines the same hats; a member from an outer namespace does not need them. (Derived from the kernel code.)CAP_MAC_OVERRIDE is turned into a stack: aa-exec -p baz -- cmd runs as baz//&unconfined, with a record carrying info="change_profile unprivileged unconfined converted to stacking". Access is that of baz; the unconfined member keeps attaching profiles at exec.attach_disconnected on one member does not apply to another./proc).| Message | When |
|---|---|
The current kernel does not support stacking of named transitions: %s | a change_profile rule with a & target, and the kernel or the profile's ABI lacks domain/stack; a profile file with no abi rule is in that case, whatever the kernel supports |
downgrading change_profile safe rule to unsafe due to lack of necessary kernel support | warning: change_profile safe without stacking support in the kernel |
Profile names must begin with a '/' or a namespace | profile &foo { }: & cannot start a profile name |
Invalid perms, 'x' must be preceded by exec qualifier 'i', 'p', or 'u' | /bin/bar x -> &baz, |
syntax error, unexpected TOK_ID, expecting TOK_END_OF_RULE | a space after &: /bin/bar px -> & baz, (seen with 6.0.0~alpha2) |
Lexer found unexpected character: '-' (0x2d) in state: INITIAL | the keyword spelled change-profile |
These are places where the code, the documentation or the expected meaning disagree. They are described as what the code does, not as intended design, and none is a technique to rely on.
cx -> &name does not select a child.** The parser stores the target of a cx rule in profile t as t//&name, which the kernel reads as the stack of t and a top-level profile name (kernel side read, not run).ix -> &name or ux -> &name with name not loaded.** The exec proceeds with the ix or ux fallback and without the stacked profile; with px -> &name the exec fails instead (read in the kernel code, not run).& are not validated and not gated.** The parser checks domain/stack and the target syntax only for change_profile rules; /bin/bar px -> &, is accepted.name//&unconfined, and the regression test expects that member set (stackprofile.sh:74). Access is the same; the label and later exec transitions are not.change-profile in its example profile; the parser accepts only change_profile.changeprofile &name** stacks, but is logged as operation="change_profile" with the & kept in name=.Kernel paths are relative to linux:security/apparmor/; parser paths to the AppArmor tree.
| What | Where |
|---|---|
struct aa_label (size, vec[]), FLAG_PROFILE for the label embedded in one profile | include/label.h:127-157 |
ns_cmp, profile_cmp: namespace level, namespace name, profile name | label.c:109-155 |
vec_cmp: order of labels in a namespace's label set (rb-tree) | label.c:168-188 |
aa_vec_unique: sort and de-duplicate; insertion sort up to 8 entries | label.c:274-318 |
aa_label_next_in_merge: zip two sorted vectors, equal heads once | label.c:994-1023 |
label_merge_insert: fill the vector, refresh stale members, intern or reuse | label.c:1081-1141 |
aa_label_merge(a, b, gfp); a == b returns a | label.c:1248-1275 |
aa_label_snxprint, mode of a compound label, FLAG_HIDDEN_UNCONFINED | label.c:1538-1608, 1668-1696 |
aa_label_strn_parse and the stack-split DFA for //& | label.c:1861-1978, stacksplitdfa.in, include/label.h:322-343 |
__label_update: rebuild stale compound labels after a reload | label.c:2063-2125 |
aa_label_is_unconfined_subset: the no_new_privs test | label.c:574-592 |
fn_for_each, fn_for_each_confined, last_error | include/label.h:150-155, 185-188, 225-236 |
fn_for_each_in_ns, in-scope helpers | include/label.h:200-222, include/lib.h:90-94 |
fn_label_build, fn_label_build_in_scope | include/lib.h:289-361 |
matching a target label: & prefix and &:NS:NAME; label_match tries the whole stack, then each member | domain.c:94-112, 256-271 |
change_profile_perms; unconfined needs no rule | domain.c:290-302 |
x_table_lookup: skips the leading & | domain.c:523-559 |
x_to_label: stack = new, fall through to AA_X_NAME, "base the stack on post domain transition" | domain.c:574-663 |
profile_transition, the unconfined member's attachment | domain.c:665-796 |
profile_onexec, handle_onexec: pending on-exec requests | domain.c:798-975 |
exec: fn_label_build over the label, then no_new_privs, ptrace, AT_SECURE | domain.c:1010-1078 |
| change_hat on a compound label | domain.c:1169-1300 |
aa_change_profile(fqname, flags): operation name, leading &, parse, permission per in-scope profile, tracer, merge or store | domain.c:1484-1655 |
do_setattr: stack on current and on exec | lsm.c:853-921 |
aa_set_current_onexec: target and stack flag in the task context | task.c:125-133 |
audit_pre: profile=, namespace=, label= | audit.c:116-133 |
aa_getprocattr: view flags, -EACCES for an invisible namespace | procattr.c:31-70 |
domain/stack, domain/post_nnp_subset feature files | apparmorfs.c:2606-2608 |
lexer: & may start a label token; SUB_ID_WS after -> | parser/parser_lex.l:253, 301-302, 456-461, 822 |
exec rule target becomes nt_name | parser/parser_yacc.y:1043-1103, 1759-1768 |
add_named_transition: stores the string, & included; cx prefixes PROFILE// | parser/block_rules.cc:474-524 |
change_profile rule; safe downgrade warning; bare rule uses target ** | parser/parser_yacc.y:1648-1690 |
change_profile target compiled as one DFA string with stacking support; parse_label and the & refusal without it | parser/parser_regex.c:742-762 |
features_supports_stacking read from domain/stack | parser/parser_main.c:1093-1095 |
aa_stack_profile, aa_stack_onexec, setprocattr paths | libraries/libapparmor/src/kernel.c:997-1012, 1204-1244 |
splitcon, aa_getcon, aa_gettaskcon | libraries/libapparmor/src/kernel.c:556-633, 1261-1283 |
struct aa_label.strings on the binary policy for /bin/bar px -> &baz, shows &baz (apparmor_parser 6.0.0~alpha2). Whether the parser emits a different xindex for -> &name when it writes the extended permission table itself was not determined.The abi line freezes what a profile's text means. What its abi file cannot express is not checked for the profile, so it stays allowed; under a newer file the same text denies whatever it does not allow.
abi/6.0 file in the tree, and nothing here says what a later AppArmor will mediate. abi/5.0 and abi/6.0 stand for "the file the profile was written for" and "a later file that has an entry for the new class".apparmor_parser -Q -K --skip-kernel-load -D rule-exprs, kernel feature set written from the kernel source, nothing loaded into a kernel). The profile is profile demo /usr/bin/demo { /etc/demo/** r, } with one abi line in front. With abi <abi/3.0>, its marker lines are \d2, \d7, \d32, \d10, \d9 and \d14. With abi <abi/5.0>, there are four more: \d21 (user namespaces), \d22 (io_uring), \d15 and \d15\0001 (unix sockets). Both runs print nothing and exit with status 0.sqpoll and override_creds at lsm.c:638. Without the marker both hooks let the access through. The markers were printed by the parser; "allowed" and "denied" on the slide are taken from the kernel source and were not observed on a running kernel.\d15), is not on the slide: with abi/5.0 the profile's unix sockets are matched by unix rules. See the scene "Some rules stay, but say less".RULE_MEDIATES: policy.h:331.abi <abi/5.0>, or abi "path",. <kernel> and <default> are special names. The comma is required.
ABI = ( 'abi' ) ( ABS PATH | MAGIC PATH | '<kernel>' | '<default>' ) ',' (apparmor.d.pod:120).3.0, 4.0, 4.0-ip, 5.0, 5.0-interface, kernel-5.4-outoftree-network, kernel-5.4-vanilla.-I directories, then the base directory. See include.abi simple_tests/includes/abi/4.19 , (abi/ok_16.sd, a test the parser is expected to accept). The quoted form is that of the neighbouring tests in that directory, for example abi "simple_tests/includes/abi/4.19", (abi/ok_1.sd). The quoted line on the slide, abi "/etc/apparmor.d/abi/5.0",, was run with the tree's parser for this deck with the path of the feature file in the test image (/src/apparmor/profiles/apparmor.d/abi/5.0) in place of /etc/apparmor.d/abi/5.0: with a userns, rule and --warn=all it prints nothing and exits with status 0.<kernel>: "should never be used in shipped policy as it can cause system breakage when a new kernel is installed". "The special abi default is equivalent to not specifying an ABI" (apparmor.d.pod:2840-2844).abi "kernel", opens a file called kernel (derived).--warn=all and a profile holding userns,: abi <kernel>, prints nothing; abi <default>, prints userns rules not enforced.abi/5.0 file, given to the parser as an option; no running kernel was consulted. The scenes on the files, from "Seven files, and you name one" on, use a kernel feature set written from the kernel source.-b and -I in terms that do not match the code.abi_rule: TOK_ABI TOK_ID TOK_END_OF_RULE | TOK_ABI TOK_VALUE TOK_END_OF_RULE (parser_yacc.y:1052-1063).ABI_MODE (parser_lex.l:893-895, parser_lex.l:911-916).A rule class is compiled only if the policy ABI and the kernel ABI both have it. With abi/3.0, userns, is left out.
--warn=all: the profile on the slide with abi <abi/3.0>, prints Warning from profile demo (/work/ab1.sd): userns rules not enforced, and -S writes 4401 bytes. With abi <abi/4.0>, there is no output and -S writes 4481 bytes. Both were run again for this deck with the same result for the warning. /work/ab1.sd is the scratch name of the file; the slide shows (...).--warn=all the first run prints nothing and exits with status 0. The warning classes for left-out rules are off by default: see Running apparmor_parser.abi/5.0 file, given with --kernel-features, not a running kernel. That set has user namespace mediation./sys/kernel/security/apparmor/features: see Kernel features and the policy ABI.abi/5.0, with which nothing is left out.set_supported_features() computes each features_supports_* switch as the intersection of the two sets (parser_main.c:1030-1125; features_intersect at parser_main.c:1000-1003).Override option, then the file's first abi rule, then the pinned set, then the built-in default. Warnings of class abi are off by default.
userns, of the scene before, with --warn=all.abi <abi/3.0>, with --override-policy-abi /src/apparmor/profiles/apparmor.d/abi/4.0: no userns warning.abi <abi/3.0>, with --policy-features .../abi/4.0: userns rules not enforced.--policy-features .../abi/4.0: no warning at all.Warning ... File '/work/ab3.sd' missing feature abi, falling back to default policy feature abi, then Warning from profile demo (/work/ab3.sd): userns rules not enforced.abi <abi/3.0>, then abi <abi/4.0>,: Warning from /work/ab4.sd (/work/ab4.sd line 2): ... /work/ab4.sd features abi 'abi/4.0' differs from policy declared feature abi, using the features abi declared in policy, then userns rules not enforced. In the other order the same warning names abi/3.0 and userns is compiled. The same rule twice draws no warning..... The file names under /work/ are scratch names.--policy-features is also spelled --compile-features; -M and -m set it together with the kernel features. The options accept '<kernel>' as a value.abi are off by default; --warn=abi or --warn=all turns them on.--warn=all): the missing-abi warning for line 1, then the "differs" warning for the body's line, then userns rules not enforced.abi rule, xattrs= is dropped silently and change_profile -> &x is refused "by the kernel".abi_features: parser_yacc.y:1884-1906.default_features_abi: default_features.c:127.The abi rule names one of seven feature files in /etc/apparmor.d/abi/. Which one you name decides which rule classes of the profile are compiled.
/etc/apparmor.d/abi/: 3.0, 4.0, 4.0-ip, 5.0, 5.0-interface, kernel-5.4-outoftree-network, kernel-5.4-vanilla. There is no 6.0 file./sys/kernel/security/apparmor/features: a directory becomes name {...} and a file becomes name {content} (features.c:53). The format is in Kernel features and the policy ABI.abi <abi/5.0>,
profile demo /usr/bin/demo {
/etc/demo/** r,
capability net_bind_service,
network inet stream,
network inet tcp ip=127.0.0.1 port=8080,
unix (connect) type=stream peer=(addr=@demo),
dbus send bus=session path=/org/demo,
signal send set=hup,
ptrace read,
mount fstype=tmpfs -> /mnt/demo/,
mqueue (create) type=posix /demo,
userns,
io_uring sqpoll,
}
abi <abi/5.0>, and the kernel's feature set, one rule of this profile is left out, the mqueue rule. The run is in the scene "The same profile under 3.0, 4.0 and 5.0".abi/5.0 is named by shipped policy: under profiles/apparmor.d 345 lines are abi <abi/5.0>, (210 in column 0, 135 indented: 134 in abstractions and one in apache2.d/phpsysinfo) and 111 under profiles/apparmor/profiles/extras. No other file is named.abi <abi/5.0>, into a new profile (aa.py:516-517), and the tree's build fails for a shipped abstraction (profiles/Makefile:171-176) or profile (profiles/Makefile:190-195) without it.<kernel> and <default> are in the scene "abi, a feature file, a comma"; which source decides is in "Who decides the policy ABI".3.0, 4.0 and 5.0 each add rule classes. 4.0-ip and 5.0-interface add one feature to a numbered file. The two kernel-5.4 files are for parser.conf.
kernel-5.4-vanilla to kernel-5.4-outoftree-network: adds dbus, network (the old table of address families) and network/af_unix (unix rules in the old encoding).kernel-5.4-outoftree-network to 3.0: adds network_v8 (network rules) and perfmon and bpf in caps/mask.3.0 to 4.0: adds ipc/posix_mqueue (mqueue rules for POSIX queues) and namespaces/mask with userns_create (userns rules); also mctp in the address family masks and checkpoint_restore in caps/mask.4.0 to 4.0-ip: one entry, network_v8/af_inet (ip= and port= on network inet and inet6 rules).4.0-ip to 5.0: adds network_v9 with af_unix (unix rules in the current encoding), io_uring, and domain/interruptible, domain/kill.signal and domain/disconnected.ipc. These are the "three flags" of the slide: interruptible, kill.signal= and attach_disconnected.ipc=.5.0 to 5.0-interface: adds network_v9_skb with iface (interface= on network rules).kernel-5.4 files, 398bb20df, release 3.0.0; 3.0, 730db1760, release 3.0.0; 4.0, f1b4da2f6, release 4.0.0; 4.0-ip and 5.0, d688f93a4 and aecf78014, release 5.0.0; 5.0-interface, dc761781e, first in 6.0.0~alpha1 (6.0.0 is not released at the commit the map describes). So 4.0-ip is newer than 4.0 in one entry only, and it arrived with release 5.0.0.kernel-5.4 files are offered by the parser's configuration file as commented lines: #policy-features=/etc/apparmor.d/abi/kernel-5.4-vanilla and #policy-features=/etc/apparmor.d/abi/kernel-5.4-outoftree-network (parser.conf:77-81). They pin profiles that have no abi rule.file, domain and policy entries are not found. Each file has one closing brace more than opening ones: in kernel-5.4-vanilla it follows the mount entry (kernel-5.4-vanilla:31; the file has no network block), in kernel-5.4-outoftree-network it follows the network block (kernel-5.4-outoftree-network:39). The file, domain and policy entries after it are in the text and are not found by the lookup. Among them are domain/attach_conditions/xattr (the xattrs= attachment condition) and domain/stack (& targets): both files have the two entries in their text, and the lookup finds them from 3.0 on, which has the same entries in the same order and no extra brace. The slide does not list them as something 3.0 adds.An older abi file leaves userns, mqueue and io_uring rules out. -K --warn=all says so; the default output does not, and without -K a cached profile is not compiled again.
apparmor_parser -Q -K --skip-kernel-load --warn=all on the profile of the scene "Seven files, and you name one", with nothing loaded into a kernel. The slide leaves out --skip-kernel-load and the kernel feature set. The kernel feature set of the runs is a file written from the feature tables of the kernel source (apparmorfs.c:2684, net.c:24), given with --kernel-features; it is not a running kernel.abi <abi/3.0>,, exit status 0. Every line begins Warning from profile demo (FILE): :downgrading extended network unix socket rule to generic network rule mqueue type=posix rules not enforced userns rules not enforced io_uring rules not enforced
abi <abi/4.0>,, exit status 0:downgrading extended network unix socket rule to generic network rule mqueue type=posix rules not enforced io_uring rules not enforced
abi <abi/5.0>,, exit status 0: mqueue type=posix rules not enforced. The slide orders the lines by rule class so that a class keeps its row, and shortens two of them with an ellipsis.--warn=all: no output and exit status 0 (run for all three abi lines).-K: reading the cache is on by default and -Q does not turn it off. When the cache has an entry for the profile that is newer than the file, the parser takes the compiled profile from it and skips the compile, which is where these warnings are printed. Run for this deck with a cache directory that survives between runs: -Q -W --cache-loc DIR --warn=all on the abi <abi/3.0>, profile prints the four warnings and writes the cache; then -Q --cache-loc DIR --warn=all --show-cache prints Cache hit: DIR/fd0f5cfe.0/demo-3.0.sd and no warning, exit status 0; with -K (or -T, --skip-read-cache) it prints Cache miss and the four warnings again. A profile that is installed and loaded is normally in the cache, so without -K the check says nothing exactly there.-S): 5961 bytes with abi/3.0, 6049 with abi/4.0, 6337 with abi/5.0.rule-not-enforced and rule-downgraded. Both are off by default (parser_main.c:281-282); --warn=rule-not-enforced --warn=rule-downgraded turns on just these two.capability and rlimit rules. signal, ptrace and mount are in all seven files. dbus is in every file but kernel-5.4-vanilla; who enforces dbus rules is in D-Bus mediation.mqueue rule of this profile: the rule is left out in all three columns, and the queue is still refused, by the file check and not by the mqueue class. Observed on Debian 13 and Debian sid, with and without an mqueue rule: mq_open fails with error 13 and the log has apparmor="DENIED" operation="open" class="file" info="Failed name lookup - disconnected path". The record is in Kernel features and the policy ABI.network_v9 unix support are not consulted, so profiles that pin abi/3.0 or abi/4.0 get no dbus mediation. This one was found by reading the code and has not been run on a kernel.-Q only turns off the load into the kernel (parser_main.c:817-819); -K and -T are described in apparmor_parser.pod:234-240.--warn.Under abi/4.0 a unix rule becomes a network unix rule. ip= and port= are compiled only where the abi file and the kernel both have af_inet; otherwise the rule covers the whole family.
-D rule-exprs and the kernel feature set written from the kernel source, and run again for this deck: - abi/5.0, the unix rule: rule: \x0f\x00\x01\x00\x01...*\x00[^\000]*\x00\x01\x00demo\x00[^\000]* with permission (0x40/0). The peer address demo is in the rule. Also present under abi/5.0: rule: \x0f\x00\x01\x00\x01 with (0x40/0), the generic unix stream connect rule, which the parser always adds beside the full one; the kernel does not use it for a unix socket when class 15 is mediated (af_unix.c:406, policy.h:360). - abi/4.0 (also abi/3.0 and abi/4.0-ip), the unix rule: only rule: \x0e\x00\x01\x00\x01 with (0x40/0): family unix, type stream, the connect permission, no address. - the inet rule with ip= and port=, every abi file: rule: \x0f\x00\x02\x00\x01 (\x0e before abi/5.0) with (0x1fc076/0), the same line as the rule network inet stream, above it in the profile.abi/5.0-interface file as a stand-in kernel feature set and abi/4.0-ip or abi/5.0 in the profile: the dump then has a line containing \x01\x00\x1f\x90\x01\x7f\x00\x00\x01\x00 (port 0x1f90 is 8080, the address is 127.0.0.1). It was not observed on a running kernel. Which kernels have the entry is in Upstream and Ubuntu kernels.abi/3.0 and abi/4.0 downgrade the unix rule on it: they name network/af_unix, the kernel names network_v9/af_unix, and a feature must be in both sets.rule-downgraded, which is off by default.deny unix (connect) type=stream peer=(addr=@demo), under abi <abi/4.0>, prints deny unix socket rule not enforced, can't be downgraded to generic network rule with --warn=all, and the dump has no network rule; exit status 0.ip= and port= need network_v8/af_inet or network_v9/af_inet in both sets. abi/4.0-ip, abi/5.0 and abi/5.0-interface have the first; no shipped file has the second; the kernel's tables have neither (net.c:24).interface= needs network_v9_skb/iface, which only abi/5.0-interface has. Recorded with the stand-in kernel set that has it: with abi/5.0, network send interface=eth0, compiles without eth0, exit status 0, and --warn=all prints nothing.change_profile safe rules: downgrading change_profile safe rule to unsafe due to lack of necessary kernel support (from the code).af_inet, so deny rules get wider.deny unix rules are dropped when the kernel lacks fine-grained unix mediation, even where the downgrade would be exact.A rule class is compiled when the abi file and the kernel both have its entry. On this kernel 4.0-ip compiles to the same bytes as 4.0, and 5.0-interface to the same bytes as 5.0.
network_v9/af_unix (fine-grained unix rules), io_uring, namespaces/mask/userns_create, ipc/posix_mqueue, network_v8/af_inet, domain/interruptible.network and no ipc; domain (apparmorfs.c:2600) has no interruptible and no disconnected.ipc; network_v8 and network_v9 (net.c:24) have no af_inet. The runs used a feature file written from these tables, not a running kernel.abi/5.0 and the kernel's tables do not have: network, network/af_unix, network_v8/af_inet, ipc/posix_mqueue, domain/interruptible, domain/disconnected.ipc.interface= needs network_v9_skb/iface. abi/5.0 does not offer it; only abi/5.0-interface does, and the kernel's tables have no network_v9_skb. So that side file changes nothing on this kernel.abi <abi/4.0-ip>, gives the same -D rule-exprs dump and the same 6049 bytes as with abi <abi/4.0>,; with abi <abi/5.0-interface>, the same dump and the same 6337 bytes as with abi <abi/5.0>,.flags=(interruptible) with abi <abi/5.0>, prints flag interruptible not supported. Ignoring under --warn=all.abi <abi/5.0>, needs no change: the classes that kernel lacks are left out. Recorded with the tree's abi/4.0 file as a stand-in for an older kernel: io_uring rules not enforced. With the tree's abi/3.0 as the stand-in: mqueue type=posix rules not enforced, userns rules not enforced, io_uring rules not enforced.abi/5.0 file, and the parser then stops with Could not open 'abi/5.0' (derived from the releases in which the files arrived; not run on an older package).ipc/posix_mqueue entry means the mqueue rule is left out; it does not mean the queue is open to the profile. Observed on Debian 13 and Debian sid, with and without an mqueue rule: mq_open fails with error 13 and the log has apparmor="DENIED" operation="open" class="file" info="Failed name lookup - disconnected path". See Kernel features and the policy ABI.abi/5.0-interface file as a stand-in kernel feature set: the profile of the scene "Seven files, and you name one", which has no interface=, has 67 rule: lines with abi <abi/5.0>, and 149 with abi <abi/5.0-interface>,. What a kernel with that entry does with the extra rules is not determined.attach_disconnected.ipc is dropped without a warning and its bit is written anyway.A rule class missing from the policy ABI is left out silently: exit status 0, no message unless --warn=all.
--warn=all, prints nothing and exits with status 0. With --warn=all it prints userns rules not enforced. Recorded sizes of the compiled profile: 4401 bytes against 4481 with abi <abi/4.0>,.abi <abi/3.0>, with deny userns, and /x r, exits with status 0 and no output; with --warn=all it prints Warning from profile demo (...): userns rules not enforced, and the -D rule-exprs dump has the attachment and /x only.--policy-features, --compile-features, -M and -m; --override-policy-abi; and the abi file itself, which is found on the include search path, so a -I directory shadows /etc/apparmor.d/abi/.abi <tunables/global>, with network inet stream, and signal send, exits with status 0 and no output; with --warn=all it prints network rules not enforced and signal rules not enforced; -S writes 3025 bytes against 4681 with abi <abi/4.0>,.abi rule, xattrs= is dropped silently and change_profile -> &x is refused "by the kernel".parser_yacc.y:1884-1906 loads the file and 345-369 settles the policy ABI; parser_main.c:1030-1125 sets the switches; parser_regex.c:1392-1452 adds one marker per class, which the kernel's RULE_MEDIATES tests.
abi_features(): parser_yacc.y:1884-1906; the special names: parser_yacc.y:1846-1857; the lookup with search_path: parser_yacc.y:1858-1863.preamble that settles the policy ABI: parser_yacc.y:345-369.features_intersect(a, b, str) is aa_features_supports(a, str) && aa_features_supports(b, str) (parser_main.c:1000-1003). set_supported_features() calls it for 24 paths (parser_main.c:1030-1125). The 24 paths, their switches and the files that have them are in the table "Feature by file" below the deck.mount/move_mount/detached (parser_main.c:1086-1087).walk_one, features.c:361-444).warn_once() prints io_uring rules not enforced in the warning class rule-not-enforced.process_profile_policydb(), parser_regex.c:1392-1452. One is added for every class whose switch is on, whether or not the profile has a rule of that class; profiles in unconfined or default-allow mode get only the user namespace marker.-D rule-exprs, abi <abi/5.0>, and the kernel feature set written from the kernel source, is the line rule: \d22 -> \x16 priority=-1001 (0x4/0)< 0x4>. The other markers of that run: \d21 (user namespaces, priority -1001), and with priority 1001 \d2, \d7 (mount), \d32 (dbus), \d10 (signal), \d9 (ptrace), \d14, \d15 and \d15\0001 (network and unix). Class numbers: policydb.h:24-56.RULE_MEDIATES returns the start state of the class in the profile's policy (policy.h:331). For io_uring the check is skipped and the hook returns 0 when that state is 0 (lsm.c:638). The same test: net.c:265, mount.c:254, ipc.c:93, task.c:388. Taken from the source; not observed on a running kernel. One class does not simply let the access through without its marker: for a tracer the kernel falls back to a CAP_SYS_PTRACE check (task.c:290). ptrace is in all seven files, so no abi line removes that marker.caps/mask of an abi file only adds names to the parser's capability table (parser_yacc.y:365, parser_misc.c:407-435); it does not gate capability rules. Recorded: capability perfmon, under abi <abi/kernel-5.4-vanilla>,, whose caps/mask has no perfmon, compiles as itself.policy block of an abi file (versions, permstable32, set_load, state32, outofband) and the file entry are looked up in the kernel feature set only (parser_main.c:1743-1776).Could not open '%s': %m, fstat failed for '%s': %m, failed to find features abi '%s': %m, failed features abi not set but include cache skipped (parser_yacc.y:1870-1900; no input was found that prints the last one), Failed to setup default policy feature abi (parser_yacc.y:360).rules: rules abi_rule (parser_yacc.y:722; the tests abi/ok_20.sd and abi/ok_21.sd).mqueue rule: mq_open fails with error 13 and the log has apparmor="DENIED" operation="open" class="file" info="Failed name lookup - disconnected path". See Kernel features and the policy ABI.abi <DIRECTORY>, reports "failed to find features abi 'abi': Success".file, domain and policy entries are not found. Recorded: xattrs= on the profile head under abi <abi/kernel-5.4-vanilla>, prints xattr attachment conditional ignored with --warn=all, and the compiled profile is identical to the one without xattrs=; with the extra closing brace removed from a copy of the file there is no warning. The lookup returns false at a closing brace at depth 0 (features.c:401-406).aa_features_supports(features, "policy/versions/v7") is false for a feature set that has policy/notify_versions. It applies where abi/5.0 or abi/5.0-interface is the kernel feature set, not where it is the policy ABI.chown.abi/3.0, demo may create user namespaces and use io_uring whatever its rules say (from the parser's output and the marker mechanism; not run on a kernel).ip=, port= and interface= are removed without a message in any warning class where the abi file or the kernel lacks the entry.apparmor_parser -Q -K --warn=all, and -D rule-exprs to see which \dN marker lines the profile carries. Without -K (or -T) a profile that is in the cache is not compiled again and no warning is printed.A missing file, a missing comma and a misplaced abi rule are errors. The other mistakes print nothing by default. Start a new profile with abi <abi/5.0>, and compile once with -K --warn=all.
abi/5.0 file as the kernel feature set; rows 6 to 8 are about the files and were run with a kernel feature set written from the kernel source. Nothing was loaded into a kernel.AppArmor parser error for /work/ab9.sd in profile /work/ab9.sd at line 1: Could not open 'abi/nope': No such file or directory.abi/5.0 arrived with AppArmor 5.0.0 (commit aecf78014). A system with an older AppArmor has no such file, and the abi rule then fails as it does for any file that is not installed. That line of the slide is derived from that and from this run, which names a file the tree does not have: abi <abi/6.0>, gives AppArmor parser error for /work/demo-6.0.sd in profile /work/demo-6.0.sd at line 1: Could not open 'abi/6.0': No such file or directory, exit status 1 (/work/ is where the run kept the file). It was not run on an older package. An older kernel is a different matter and needs no change: see the scene "The file offers, the kernel decides".syntax error, unexpected TOK_VALUE, expecting TOK_END_OF_RULE.abi abi/4.0, without angle brackets gives Could not open 'abi/4.0': No such file or directory. A bare name is opened as written and not searched for, so abi/4.0 is looked for in the working directory (recorded in the research notes and run again).--warn=all: Warning ... File '/work/ab3.sd' missing feature abi, falling back to default policy feature abi. Without that option nothing is printed.abi <abi/3.0>, then abi <abi/4.0>, in one preamble, recorded in the research notes and run again for the review of this deck: nothing is printed by default, exit status 0. With --warn=abi: Warning from /work/ab4.sd (/work/ab4.sd line 2): ... /work/ab4.sd features abi 'abi/4.0' differs from policy declared feature abi, using the features abi declared in policy. The first rule counts: a userns, rule in that file is left out. In the other order the same warning names abi/3.0 and userns is compiled. The same rule twice draws no warning.unix rule: under abi <abi/4.0>, the rule unix (connect) type=stream peer=(addr=@demo), prints nothing, and with --warn=all prints downgrading extended network unix socket rule to generic network rule (the scene "Some rules stay, but say less"). The slide shows one rule of that profile per row. The kernel feature set is the file written from the kernel source, as in the earlier scenes; exit status 0 in all of them.-D rule-exprs, kernel feature set as above. The profile is profile demo /usr/bin/demo { /etc/demo/** r, } with one abi line in front. With abi <abi/3.0>, its marker lines are \d2, \d7, \d32, \d10, \d9 and \d14. With abi <abi/5.0>, there are four more: \d21 (user namespaces), \d22 (io_uring), \d15 and \d15\0001 (unix sockets). Both runs print nothing and exit with status 0. A marker makes the kernel check the class, and a class that is checked and has no rule is denied: for user namespaces at task.c:388, for io_uring sqpoll and override_creds at lsm.c:638. So the program could create user namespaces and use io_uring under the old line, and cannot under the new one. The markers were printed by the parser; the denial is taken from the kernel source and was not observed on a running kernel. With \d15 the profile's unix sockets are also matched by unix rules.userns, and io_uring rules if the program needs them, and run the profile in complain mode first, where the new denials are logged and not enforced.-K makes the parser compile the profile and not take it from the cache; without it a profile that is in the cache prints none of these warnings. The run is in the notes of the scene "The same profile under 3.0, 4.0 and 5.0". The result of --warn=all also depends on the kernel feature set of the machine where you run it, so run it on the oldest and the newest system you target.kernel-5.4 files in an abi rule. They are meant for policy-features= in the parser's configuration file (parser.conf:77-81).rule-not-enforced and rule-downgraded, both off by default (parser_main.c:281-282). --warn=all turns on every class.abi/4.0: io_uring rules; the flags interruptible, kill.signal= and attach_disconnected.ipc=; ip= and port=; and on this kernel fine-grained unix rules, which become network unix rules without an address or a peer. - abi/3.0: also userns and mqueue rules. - no abi rule: also network rules on this kernel, xattrs= and & targets.abi/3.0 to abi/5.0.abi/4.0-ip and abi/5.0-interface matter only on a kernel that has their extra entry. abi/5.0 already has the entry for ip= and port=.abi <includes/abi/4.19, (abi/bad_6.sd) and abi <>, (abi/bad_20.sd)./work/ are scratch names of the runs.abi <DIRECTORY>, reports "failed to find features abi 'abi': Success".abi <abi/5.0>, of the shipped abstractions does not stand in for an abi rule in your own preamble.file, domain and policy entries are not found. Recorded in the research notes for a profile with /etc/demo/** r, and change_profile -> &other,: under abi <abi/kernel-5.4-vanilla>, the compile fails with The current kernel does not support stacking of named transitions: &other, exit status 255; under abi <abi/3.0>, it compiles.af_inet, so deny rules get wider.abi rule, xattrs= is dropped silently and change_profile -> &x is refused "by the kernel".--Werror=rule-not-enforced (parser_common.c:171-175; from the code, not run).The abi rule names the policy ABI; an abi file offers rule classes and the kernel accepts what it has. New profiles name abi/5.0.
Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run on the profile (-Q -K --skip-kernel-load, with --warn=all where a warning is quoted and -D rule-exprs where a compiled rule is described), with nothing loaded into a kernel. The kernel feature set of the runs in the sections on the files ("Why an abi line", and "The files" to "Choosing a line") was a file written from the feature tables of the kernel source (apparmorfs.c:2684, net.c:24, capability.c:28), given with --kernel-features; it is not a running kernel. Rows marked "kernel with every entry" used the tree's abi/5.0-interface file as the kernel feature set instead, standing in for a kernel that has every entry the shipped files name. The runs in the sections on the rule ("Grammar" to "The abi line and a userns rule") used the tree's abi/5.0 file as the kernel feature set, also given with --kernel-features; that set has user namespace mediation. "code" means the parser source, or the kernel source, was read and not run; "derived" means the result was reasoned from that code. Nothing here was observed on a running kernel.
The abi line freezes what the text of a profile means. A profile lists what is allowed, and whatever it does not list in a checked class is denied. A class that the profile's abi file has no entry for could not be written about when the profile was written, so the parser compiles the profile so that the class is not checked for it: the access stays allowed (the manual: "policy will be built so that the kernel does NOT enforce that feature", apparmor.d.pod:2833-2834). A newer abi file has the entry, and on a kernel that has it too the class is checked: the same text under the newer line denies what it does not allow. As an example of a future release: if AppArmor 6 mediated something new, a profile that names abi/5.0 would go on allowing it, and the same text under an abi/6.0 would deny it until a rule is added. There is no abi/6.0 file at this commit. The case that exists: a profile with one file rule has no marker for user namespaces, io_uring or unix sockets under abi <abi/3.0>, and has all three under abi <abi/5.0>, (tree); that a checked class without a rule is denied is from the kernel source (code). See "Choosing a line".
ABI RULE: 'abi' ( <magic/path> | "path" | path | '<kernel>' | '<default>' ) ','
<magic/path> is searched for like an include: the -I directories, then the base directory (code). "path" and a bare path are opened as written (tree for the bare path that does not exist; the test abi/ok_16.sd).<kernel> is the kernel's feature set; <default> is the parser's built-in default and is equivalent to writing no abi rule (code; tree for the userns, results below). Only the angle-bracket forms are special (derived).The policy ABI is the feature set the abi rule names; the kernel ABI is the feature set of the kernel. A rule class is compiled only if both sets have its feature (code). apparmor.d(5): "If the kernel supports a feature not supported by the policy then policy will be built so that the kernel does NOT enforce that feature". A rule class the policy ABI lacks is left out; that is not an error and by default not a message (tree).
| Order | Source | Recorded run (profile with userns,) |
|---|---|---|
| 1 | --override-policy-abi FILE | abi <abi/3.0>, in the file, override to abi/4.0: userns compiled |
| 2 | the first abi rule of the file | abi <abi/3.0>, in the file, --policy-features .../abi/4.0: userns rules not enforced |
| 3 | --policy-features FILE (also --compile-features, -M, -m) | no abi rule, --policy-features .../abi/4.0: userns compiled, no warning |
| 4 | the built-in default | no abi rule, no option: the missing-abi warning and userns rules not enforced |
All four are tree runs recorded in the research notes. Two different abi rules in one preamble: the first counts, and the second draws the "differs" warning (tree).
| First line | With --warn=all | Without | Size of -S |
|---|---|---|---|
abi <abi/3.0>, | userns rules not enforced | nothing, exit status 0 | 4401 bytes |
abi <abi/4.0>, | nothing | nothing | 4481 bytes |
| none | File '...' missing feature abi, falling back to default policy feature abi, then userns rules not enforced | nothing | 4401 bytes |
abi <kernel>, | nothing: userns compiled | not recorded | not recorded |
abi <default>, | userns rules not enforced | not recorded | not recorded |
Tree runs recorded in the research notes.
All seven are in /etc/apparmor.d/abi/ (profiles/apparmor.d/abi/ in the tree).
| File | Arrived with | Commit | What it is | Meant for |
|---|---|---|---|---|
kernel-5.4-vanilla | release 3.0.0 | 398bb20df | the features of a 5.4 kernel without extra patches | policy-features= in parser.conf, to pin profiles that have no abi rule |
kernel-5.4-outoftree-network | release 3.0.0 | 398bb20df | the same plus dbus and the old network and unix mediation | policy-features= in parser.conf |
3.0 | release 3.0.0 | 730db1760 | adds network_v8 | an abi rule |
4.0 | release 4.0.0 | f1b4da2f6 | adds POSIX message queues and user namespaces | an abi rule |
4.0-ip | release 5.0.0 | d688f93a4 | 4.0 plus one entry, network_v8/af_inet | an abi rule, on a kernel that has the entry |
5.0 | release 5.0.0 | aecf78014 | adds network_v9 with af_unix, io_uring and three profile flags | an abi rule; the one that shipped policy names |
5.0-interface | 6.0.0~alpha1 | dc761781e | 5.0 plus network_v9_skb | an abi rule, on a kernel that has the entry |
6.0 file at this commit.abi/5.0: 345 lines under profiles/apparmor.d (210 in column 0, 135 indented: 134 in abstractions and one in apache2.d/phpsysinfo) and 111 under profiles/apparmor/profiles/extras. aa-genprof and aa-autodep write abi <abi/5.0>, into new profiles (code)./sys/kernel/security/apparmor/features; see Kernel features and the policy ABI.The rows are the 24 paths the parser looks up in the policy ABI and in the kernel feature set, then the two differences in caps/mask. A rule class is compiled only where the abi file named by the profile and the kernel both have the path. y present; - absent; (y) present in the text but not found by the lookup (see "In the code" for apparmor-developers and security-researchers). Column k-van is kernel-5.4-vanilla, k-oot is kernel-5.4-outoftree-network, 5.0-if is 5.0-interface, default is the parser's built-in default used when there is no abi rule, and kernel is the kernel source the map describes.
| Feature path | Switches on | k-van | k-oot | 3.0 | 4.0 | 4.0-ip | 5.0 | 5.0-if | default | kernel |
|---|---|---|---|---|---|---|---|---|---|---|
mount | mount, umount, remount, pivot_root rules | y | y | y | y | y | y | y | y | y |
signal | signal rules | y | y | y | y | y | y | y | y | y |
ptrace | ptrace rules | y | y | y | y | y | y | y | y | y |
dbus | dbus rules | - | y | y | y | y | y | y | y | y |
network | the old table of address families | - | y | y | y | y | y | y | y | - |
network/af_unix | unix rules, old encoding | - | y | y | y | y | y | y | y | - |
network_v8 | network rules | - | - | y | y | y | y | y | - | y |
network_v8/af_inet | ip= and port= | - | - | - | - | y | y | y | - | - |
network_v9 | network rules, current encoding | - | - | - | - | - | y | y | - | y |
network_v9/af_unix | unix rules, current encoding | - | - | - | - | - | y | y | - | y |
network_v9/af_inet | ip= and port=, current encoding | - | - | - | - | - | - | - | - | - |
network_v9_skb | packet rules | - | - | - | - | - | - | y | - | - |
network_v9_skb/iface | interface= | - | - | - | - | - | - | y | - | - |
domain/attach_conditions/xattr | xattrs= on the profile head | (y) | (y) | y | y | y | y | y | - | y |
domain/stack | & targets; change_profile safe | (y) | (y) | y | y | y | y | y | (y) | y |
namespaces/mask/userns_create | userns rules | - | - | - | y | y | y | y | - | y |
ipc/posix_mqueue | mqueue rules, POSIX queues | - | - | - | y | y | y | y | - | - |
ipc/sysv_mqueue | mqueue rules, System V queues | - | - | - | - | - | - | - | - | - |
io_uring | io_uring rules | - | - | - | - | - | y | y | - | y |
domain/interruptible | flags=(interruptible) | - | - | - | - | - | y | y | - | - |
domain/kill.signal | flags=(kill.signal=...) | - | - | - | - | - | y | y | - | y |
domain/disconnected.ipc | flags=(attach_disconnected.ipc=...) | - | - | - | - | - | y | y | - | - |
policy/profile/error | flags=(error=...) | - | - | - | - | - | - | - | - | - |
domain/identity | names of identities | - | - | - | - | - | - | - | - | - |
caps/mask has perfmon bpf | names only; does not gate capability rules | - | - | y | y | y | y | y | y | y |
caps/mask has checkpoint_restore | names only | - | - | - | y | y | y | y | - | y |
kernel column from the kernel's tables (code); the default column is from the research notes.capability and rlimit rules, change_profile without & and hats depend on no path: they are compiled under every file (tree for file rules and capability).mount/move_mount/detached is looked up in the kernel set only. 5.0 and 5.0-interface have it and so does the kernel.Entries that are in the files and are not looked up in a policy ABI (code): file/mask, rlimit/mask, query/..., capability, namespaces/profile, namespaces/pivot_root, namespaces/userns_create, caps/extended, domain/version, domain/change_*, domain/computed_longest_left, domain/post_nnp_subset, domain/fix_binfmt_elf_mmap, domain/unconfined_allowed_children, domain/disconnected.path, every af_mask, and the whole policy block. The policy block and file are looked up in the kernel feature set only.
| From, to | Entries added | Rule classes or syntax this switches on |
|---|---|---|
kernel-5.4-vanilla to kernel-5.4-outoftree-network | dbus/mask; network/af_mask, network/af_unix | dbus rules; the old table of address families; unix rules in the old encoding |
kernel-5.4-outoftree-network to 3.0 | network_v8/af_mask; perfmon bpf in caps/mask; the domain entries are found | network rules; xattrs= on the profile head; & targets |
3.0 to 4.0 | ipc/posix_mqueue; namespaces/mask = userns_create; mctp in the af_masks; checkpoint_restore in caps/mask | mqueue rules for POSIX queues; userns rules |
4.0 to 4.0-ip | network_v8/af_inet | ip= and port= on network inet and inet6 rules |
4.0-ip to 5.0 | network_v9/af_mask, network_v9/af_unix; io_uring/mask; domain/interruptible, domain/kill.signal, domain/disconnected.ipc; mount/move_mount | unix and network rules in the current encoding; io_uring rules; the flags interruptible, kill.signal=, attach_disconnected.ipc= |
5.0 to 5.0-interface | network_v9_skb with af_mask, iface, localout, postroute, rcv_skb, relabel | interface= on network rules; packet rules |
Each step also adds entries that are not looked up in a policy ABI (in the policy block and elsewhere); they are left out of this table.
The profile of the scene "Seven files, and you name one", one rule per row (tree). Every run exits with status 0. Messages appear only with --warn=all; the class is rule-not-enforced unless stated.
| Rule | abi/3.0 | abi/4.0 | abi/5.0 |
|---|---|---|---|
/etc/demo/** r, | compiled | compiled | compiled |
capability net_bind_service, | compiled | compiled | compiled |
network inet stream, | compiled | compiled | compiled |
network inet tcp ip=127.0.0.1 port=8080, | kept without ip= and port=; no message | the same | the same |
unix (connect) type=stream peer=(addr=@demo), | downgraded to a network unix stream rule; downgrading extended network unix socket rule to generic network rule (class rule-downgraded) | the same | compiled |
dbus send bus=session path=/org/demo, | compiled | compiled | compiled |
signal send set=hup, | compiled | compiled | compiled |
ptrace read, | compiled | compiled | compiled |
mount fstype=tmpfs -> /mnt/demo/, | compiled | compiled | compiled |
mqueue (create) type=posix /demo, | left out; mqueue type=posix rules not enforced | the same | the same |
userns, | left out; userns rules not enforced | compiled | compiled |
io_uring sqpoll, | left out; io_uring rules not enforced | left out; io_uring rules not enforced | compiled |
size of -S | 5961 bytes | 6049 bytes | 6337 bytes |
abi/4.0-ip gives the same output and the same 6049 bytes as abi/4.0; abi/5.0-interface the same output and the same 6337 bytes as abi/5.0 (tree).--warn=all nothing is printed (tree, for abi/3.0).xattrs=(user.demo=1) on the profile head is compiled under abi/3.0 (4585 bytes against 4513 without it); change_profile -> &other, compiles under abi/3.0; flags=(interruptible) under abi/5.0 prints flag interruptible not supported. Ignoring.ip=127.0.0.1 port=8080 is compiled into the rule with abi/4.0-ip and abi/5.0, and is not with abi/4.0. network send interface=eth0, is compiled with the interface under abi/5.0-interface; under abi/5.0 it is compiled without it, exit status 0, no message.The two kernel-5.4 files and a profile with no abi rule, same profile, same kernel feature set (tree):
| First line | Left out or changed | Size of -S |
|---|---|---|
abi <abi/kernel-5.4-vanilla>, | both network rules, the unix rule, the dbus, mqueue, userns and io_uring rules | 5409 bytes |
abi <abi/kernel-5.4-outoftree-network>, | the same without the dbus rule | 5721 bytes |
| no abi rule | the same as the line above, after File 'FILE' missing feature abi, falling back to default policy feature abi | 5721 bytes |
The messages of these runs: network rules not enforced (three times), extended network unix socket rules not enforced, dbus rules not enforced (vanilla only), mqueue type=posix rules not enforced, userns rules not enforced, io_uring rules not enforced, and profile demo network rules not enforced.
The switch is the intersection, so the result is the same whether the abi file or the kernel lacks the path. apparmor.d(5): "the compile may downgrade the rule with the feature to something the kernel supports, drop the rule completely, or fail the compile".
| Rule class or syntax | Entry | Result when absent on either side | Message and class | Basis |
|---|---|---|---|---|
network | network_v8 or network_v9 | left out | network rules not enforced (rule-not-enforced) | tree |
network ... ip= port= | network_v8/af_inet or network_v9/af_inet | kept as a family and type rule | none | tree |
network ... interface= | network_v9_skb/iface | kept without the interface | none | tree |
unix | network_v9/af_unix or network/af_unix | allow rules become network unix rules | downgrading extended network unix socket rule to generic network rule (rule-downgraded); with no network entry at all extended network unix socket rules not enforced | tree |
deny unix | the same | left out | deny unix socket rule not enforced, can't be downgraded to generic network rule (rule-not-enforced) | tree |
dbus | dbus | left out | dbus rules not enforced | tree |
signal, ptrace | signal, ptrace | left out | signal rules not enforced, ptrace rules not enforced | code |
mount | mount | left out | not recorded | code |
mqueue | ipc/posix_mqueue, ipc/sysv_mqueue | left out | mqueue type=posix rules not enforced, mqueue type=sysv rules not enforced | tree |
userns | namespaces/mask/userns_create | left out | userns rules not enforced | tree |
io_uring | io_uring | left out | io_uring rules not enforced | tree |
xattrs= on the head | domain/attach_conditions/xattr | condition removed; the profile attaches by path alone | xattr attachment conditional ignored (rule-not-enforced) | tree |
change_profile -> &x, & targets | domain/stack | the compile fails, exit status 255 | The current kernel does not support stacking of named transitions: &x | tree |
change_profile safe ... | domain/stack | compiled as unsafe | downgrading change_profile safe rule to unsafe due to lack of necessary kernel support (rule-downgraded) | code |
flags=(interruptible) | domain/interruptible | flag cleared | flag interruptible not supported. Ignoring | tree |
flags=(kill.signal=...) | domain/kill.signal | not written | kill.signal not supported. Ignoring | tree |
flags=(attach_disconnected.ipc=...) | domain/disconnected.ipc | see the known discrepancy below | none | code |
The profile of the scene "Seven files, and you name one" with abi <abi/5.0>, against three kernel feature sets (tree, --warn=all):
| Kernel feature set | Warnings |
|---|---|
| written from the kernel source | mqueue type=posix rules not enforced |
the tree's abi/4.0 file, standing in for an older kernel | io_uring rules not enforced |
the tree's abi/3.0 file, standing in for an older kernel | mqueue type=posix rules not enforced, userns rules not enforced, io_uring rules not enforced |
Kernels that have the entries this one lacks: Upstream and Ubuntu kernels.
abi <abi/5.0>, as the first line of a new profile file. It is what every shipped profile has and what aa-genprof writes.apparmor_parser -Q -K --warn=all FILE (or --warn=rule-not-enforced --warn=rule-downgraded) on the oldest and the newest system you target. Without the warning option a rule that is left out prints nothing and the exit status is 0. Without -K a profile that is already in the cache is not compiled again and no warning is printed (tree: after a run with -W, -Q --warn=all --show-cache prints Cache hit and no warning; with -K or -T the warnings are back).abi/4.0: io_uring rules; the flags interruptible, kill.signal= and attach_disconnected.ipc=; ip= and port=; and on this kernel fine-grained unix rules, which become network unix rules without an address or a peer. abi/3.0: also userns and mqueue rules. No abi rule: also network rules on this kernel, xattrs= and & targets. A class that is left out is not denied: it is not checked for the profile (POSIX message queues are the exception; see the known discrepancies below).abi/3.0 to abi/5.0 without new rules no longer lets the program create user namespaces or use io_uring sqpoll and override_creds, and its unix sockets are matched by unix rules. Basis: a profile with one file rule has no \d21, \d22 or \d15 marker line under abi/3.0 and has all three under abi/5.0 (tree); that a checked class without a rule is denied is from the kernel source (code), not from a running kernel. Raise the line, add the rules the program needs, then test in complain mode.abi/4.0-ip and abi/5.0-interface are for kernels that have network_v8/af_inet or network_v9_skb. On this kernel they compile to the same bytes as 4.0 and 5.0. abi/5.0 already has af_inet. An ip=, port= or interface= in a profile that may run where the entry is missing gives a rule for the whole family and type, with no message.abi/5.0 the classes that kernel lacks are left out. The file must be installed: without it the parser stops with Could not open 'abi/5.0' (derived: a package older than release 5.0 does not ship the file).kernel-5.4 files in an abi rule. They are meant for policy-features= in parser.conf.kernel-5.4 files in parser.conf, or name one in an abi rule, the xattrs= attachment condition is removed and the profile attaches by path alone; --warn=all prints xattr attachment conditional ignored (tree). A profile with a & target fails to compile.| Message | Class, default | Cause | Basis |
|---|---|---|---|
Could not open 'NAME': No such file or directory | error, exit status 1 | the file named by the abi rule was not found or is not installed; abi/5.0 on a system older than AppArmor 5.0 is the same case (derived) | tree |
syntax error, unexpected TOK_VALUE, expecting TOK_END_OF_RULE | error | no comma | tree |
syntax error, unexpected TOK_ABI, expecting end of file | error | an abi rule after a profile | tree |
File 'FILE' missing feature abi, falling back to default policy feature abi | warning abi, off | no abi rule and no option | tree |
features abi 'NAME' differs from policy declared feature abi, using the features abi declared in policy | warning abi, off | a later abi rule that differs from the first | tree |
userns rules not enforced, io_uring rules not enforced, mqueue type=posix rules not enforced, dbus rules not enforced, network rules not enforced | warning rule-not-enforced, off | the abi file or the kernel lacks the entry of the class | tree |
extended network unix socket rules not enforced | warning rule-not-enforced, off | no unix entry and no network entry | tree |
downgrading extended network unix socket rule to generic network rule | warning rule-downgraded, off | no unix entry in both sets; a network entry in both | tree |
xattr attachment conditional ignored | warning rule-not-enforced, off | domain/attach_conditions/xattr not found | tree |
flag interruptible not supported. Ignoring | warning, off | domain/interruptible missing on either side | tree |
The current kernel does not support stacking of named transitions: NAME | error, exit status 255 | domain/stack not found | tree |
| none | ip=, port= or interface= without its entry | tree | |
fstat failed for '%s': %m, failed to find features abi '%s': %m, Failed to setup default policy feature abi | error | not produced in the runs | code |
--policy-features and its other spellings, by --override-policy-abi, and by which file the name in the abi rule resolves to on the include search path.userns, and deny userns,).abi/3.0, the program may create user namespaces and use io_uring whatever its rules say (derived from the parser's output and the marker rules; not run on a kernel).ip=, port= and interface= are removed without a message in any warning class where the abi file or the kernel lacks the entry. A deny rule with such a condition then covers the whole family and type.kernel-5.4 files, named in an abi rule or pinned in parser.conf, remove the xattrs= attachment condition: the profile attaches by path alone.apparmor_parser -Q -K --warn=all (without -K or -T a cached profile is not compiled again and prints no warning), and -D rule-exprs to see which \dN marker lines a profile carries.abi_features(): parser_yacc.y:1884-1906; the order of sources: parser_yacc.y:346-369; the built-in default: default_features.c:127.set_supported_features(): parser_main.c:1030-1125. features_intersect(): parser_main.c:1000-1003. The lookup used from the kernel set only: parser_main.c:1086-1087 and parser_main.c:1743-1776.walk_one): features.c:361-444.-D rule-exprs dump they are the \dN lines with priority=1001 (-1001 for user namespaces and io_uring).domain), net.c:24 (network_v8, network_v9). The kernel tests a class with RULE_MEDIATES (policy.h:331), for example net.c:265, mount.c:254, ipc.c:93, lsm.c:638.caps/mask of an abi file adds names to the capability table only (parser_yacc.y:365, parser_misc.c:407-435).mqueue rule: mq_open fails with error 13 and the log has apparmor="DENIED" operation="open" class="file" info="Failed name lookup - disconnected path". See Kernel features and the policy ABI.-b and -I in terms that do not match the code.abi <tunables/global>, with network inet stream, and signal send,: exit status 0, no output; with --warn=all, network rules not enforced and signal rules not enforced; -S writes 3025 bytes against 4681 with abi <abi/4.0>,.abi <DIRECTORY>, reports "failed to find features abi 'abi': Success". Recorded for abi <abi>,.abi <abi/4.0>, in the body, the missing-abi warning, the "differs" warning and userns rules not enforced.file, domain and policy entries are not found. kernel-5.4-vanilla line 31 (after the mount entry; the file has no network block) and kernel-5.4-outoftree-network line 39 (after the network block) are a closing brace without an opening one; the file, domain and policy entries follow it, and the lookup returns false at a closing brace at depth 0 (features.c:401-406). These are the (y) cells of the table. Recorded: xattrs=(user.demo=1) under abi <abi/kernel-5.4-vanilla>, prints xattr attachment conditional ignored and the compiled profile is identical to the one without xattrs=; with --policy-features naming a copy of the file without line 31 there is no warning; change_profile -> &other, under the same abi line fails with the stacking message, exit status 255, and compiles under abi <abi/3.0>,.abi/5.0-interface file as the kernel feature set: the profile of the scene "Seven files, and you name one", which has no interface=, has 67 rule: lines with abi <abi/5.0>, and 149 with abi <abi/5.0-interface>,; 81 of them are packet rules for the two inet rules and the unix rule. What a kernel with that entry does with them is not determined.aa_features_supports(features, "policy/versions/v7") is false for a feature set that has policy/notify_versions. It applies where abi/5.0 or abi/5.0-interface is the kernel feature set, not where it is the policy ABI.af_inet, so deny rules get wider.deny unix rules are dropped when the kernel lacks fine-grained unix mediation, even where the downgrade would be exact.network_v9 unix support are not consulted, so profiles that pin abi/3.0 or abi/4.0 get no dbus mediation. Found by reading the code; not run on a kernel.chown.attach_disconnected.ipc is dropped without a warning and its bit is written anyway.abi rule, xattrs= is dropped silently and change_profile -> &x is refused "by the kernel".tunables/ files hold definitions for the preamble. abstractions/ files hold rules for a profile body.
include <tunables/NAME> and include <abstractions/NAME>./etc/apparmor.d, where the tree's profiles/apparmor.d is installed.Tunables: assignments, aliases, includes. Abstractions: rules and includes. Both end with include if exists <.../NAME.d>.
abstractions/base as the example: a comment header, an indented abi <abi/5.0>, and nested includes such as include <abstractions/crypto> (base:13-15), rules, and the last line include if exists <abstractions/base.d> (base:184).profiles/apparmor.d are the indented abi <abi/5.0>,.abstractions/ubuntu-browsers.d/ is not an extension directory: it holds separate abstractions that are included by name.tunables/global includes home, multiarch, proc, alias, kernelvars, system, xdg-user-dirs, share, etc, run.
-p markers of the example file, in order: ##included <tunables/global>, <tunables/home>, <tunables/home.d>, <tunables/multiarch>, <tunables/multiarch.d>, <tunables/proc>, ##failed include <tunables/proc.d>, ##included <tunables/alias>, ##failed include <tunables/alias.d>, ##included <tunables/kernelvars>, ##failed include <tunables/kernelvars.d>, ##included <tunables/system>, ##failed include <tunables/system.d>, ##included <tunables/xdg-user-dirs>, ##included <tunables/xdg-user-dirs.d>, ##included <tunables/share>, ##failed include <tunables/share.d>, ##included <tunables/etc>, ##failed include <tunables/etc.d>, ##included <tunables/run>, ##failed include <tunables/run.d>, ##failed include <tunables/global.d>.home: @{HOMEDIRS}=/home/, @{HOME}=@{HOMEDIRS}/*/ /root/; multiarch: @{multiarch}=*-linux-gnu*; proc: @{PROC}=/proc/; kernelvars: @{pid}, @{tid}, @{pids}, @{uid}, @{uids}, @{sys}=/sys/; run: @{run}=/run/ /var/run/; etc: @{etc_ro}=/etc/ /usr/etc/, @{etc_rw}=/etc/; share: @{flatpak_exports_root}, @{system_share_dirs}, @{user_share_dirs}; xdg-user-dirs: @{XDG_DESKTOP_DIR}="Desktop" and seven more; system (102 lines): character classes and counted patterns; alias: comments, then include if exists <tunables/alias.d>.global: apparmorfs, securityfs, sys, dovecot, gs, ntpd, print-devices, rygel.=.-D variables on the example file prints 85 lines; $DEMO_DEBUG and @APP_DATA are demo's. The three built-in variables are not in this dump.@{u16} has an unbalanced bracket and also matches [ and 65536 to 69999.An abstraction's rules become rules of the profile that includes it. Its variables come from tunables/global.
-p markers inside demo's profile, in order: ##included <abstractions/base>, ##included <abstractions/crypto>, ##included <abstractions/openssl>, ##failed include <abstractions/openssl.d>, ##included <abstractions/upki>, ##failed include <abstractions/upki.d>, ##failed include <abstractions/crypto.d>, ##failed include <abstractions/base.d>.{/home/*,/root}/.Private/** is an aare: line of the same file's -D rule-exprs dump; it comes from line 177 of base.include <tunables/global>, a profile that includes base fails with Failed to find declaration for: @{HOMEDIRS} (run with the tree's parser for this deck). The manual describes the case with @{HOME} (apparmor.d.pod:2812-2820).--warn=all, for a file whose preamble has no abi rule: Warning from /work/a1.sd (/src/apparmor/profiles/apparmor.d/abstractions/base line 13): ... features abi 'abi/5.0' differs from policy declared feature abi, using the features abi declared in policy.Site definitions go in tunables/NAME.d/, site rules in abstractions/NAME.d/. Reload the profiles afterwards.
@{HOMEDIRS} += /srv/nfs/home/ added, demo's rule audit deny @{HOME}/.ssh/** rw, is compiled as {/home/*,/root,/srv/nfs/home/*}/.ssh/**. In the run the line stood in a file site.local in a directory given with -I and was included with include if exists <site.local> after include <tunables/global>; it stands in for tunables/home.d/site.local, which could not be changed in the tree used for the runs.abstractions/base.d/. The file name site and the rule /srv/shared/certs/** r, are invented, and the slide shows no dump for it.apparmor_parser -r is the reload command of Running apparmor_parser; no output is shown..d directories: tunables/home.d, tunables/multiarch.d, tunables/xdg-user-dirs.d, each with a site.local of comments, for example #@{HOMEDIRS}+=/srv/nfs/home/ /mnt/home/ (home.d/site.local).= on a variable that a tunables file declared is an error, so a site file uses +=: see Variable assignment..d directory are skipped: see include if exists.NAME.d file stops every profile that includes NAME from compiling.preamble (parser_yacc.y:506-509) takes tunables; rules takes abstractions. Errors name the included file.
preamble: parser_yacc.y:506-509. The rules alternatives on the slide: parser_yacc.y:722, parser_yacc.y:724, parser_yacc.y:845-850.AppArmor parser error for /work/t1.sd in profile /src/apparmor/profiles/apparmor.d/tunables/home at line 15: syntax error, unexpected TOK_EQUALS, expecting TOK_MODE, and AppArmor parser error for /work/t2.sd in profile /src/apparmor/profiles/apparmor.d/abstractions/consoles at line 16: syntax error, unexpected TOK_MODE, expecting TOK_OPEN. In the second, the first rule of the abstraction is taken for a profile name.tunables/global twice in its preamble.Tunables above the profile, abstractions inside, and tunables/global whenever you use an abstraction.
AppArmor parser error for /work/p06e.sd in profile /src/apparmor/profiles/apparmor.d/tunables/home at line 15: syntax error, unexpected TOK_EQUALS, expecting TOK_MODE. The slide shortens the directory to ....AppArmor parser error for /work/at06b.sd in profile /src/apparmor/profiles/apparmor.d/abstractions/consoles at line 16: syntax error, unexpected TOK_MODE, expecting TOK_OPEN.Failed to find declaration for: @{HOMEDIRS} and ERROR expanding variables for profile demo, failed to load. @{HOMEDIRS} is the first undefined name met; the manual describes the case with @{HOME}.include <tunables/global>, as a stand-in for a site file. Output: '@{HOMEDIRS}' is already defined and AppArmor parser error for /work/at06d.sd in profile /work/at06d.sd at line 3: variable @{HOMEDIRS} was previously declared./work/ are scratch names of the runs.Mechanism here; choosing abstractions is its own deck.
Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run on the fragment (-Q -K --skip-kernel-load, with the tree's abi/5.0 file as kernel feature set and the tree's profiles/apparmor.d on the search path), with nothing loaded into a kernel; "code" means the parser source or a shipped policy file was read and not run; "derived" means the result was reasoned from that code. Nothing here was observed on a running kernel.
| Tunables | Abstractions | |
|---|---|---|
| Directory | tunables/ | abstractions/ |
| Included from | the preamble | a profile body, also of a child profile or a hat |
| May contain | variable assignments, alias rules, includes of other tunables files | rules, includes of other abstractions, an indented abi line |
| Last line | include if exists <tunables/NAME.d> | include if exists <abstractions/NAME.d> |
| Site changes | assignments in tunables/NAME.d/, usually with += | rules in abstractions/NAME.d/ |
| In the wrong place | a syntax error in the tunables file (tree) | a syntax error in the abstraction (tree) |
Neither has syntax of its own. Both are files found on the include search path (code).
| File | Included by global | Defines | Shipped .d directory |
|---|---|---|---|
home | 1 | @{HOMEDIRS}=/home/, @{HOME}=@{HOMEDIRS}/*/ /root/ | home.d with site.local |
multiarch | 2 | @{multiarch}=*-linux-gnu* | multiarch.d with site.local |
proc | 3 | @{PROC}=/proc/ | none |
alias | 4 | nothing: comments with two example alias rules | none |
kernelvars | 5 | @{pid}, @{tid}, @{pids}, @{uid}, @{uids}, @{sys}=/sys/ | none |
system | 6 | character classes and counted patterns such as @{int}, @{hex}, @{u16} (102 lines) | none |
xdg-user-dirs | 7 | @{XDG_DESKTOP_DIR}="Desktop" and seven more | xdg-user-dirs.d with site.local |
share | 8 | @{flatpak_exports_root}, @{system_share_dirs}, @{user_share_dirs} | none |
etc | 9 | @{etc_ro}=/etc/ /usr/etc/, @{etc_rw}=/etc/ | none |
run | 10 | @{run}=/run/ /var/run/ | none |
apparmorfs, securityfs, sys, dovecot, gs, ntpd, print-devices, rygel | no | not examined here | none |
The order is that of the -p markers of the running example (tree). tunables/global also tries tunables/global.d (tree: ##failed include). The shipped tunables use only = (code).
abstractions/base as the example (code):
| Line | Text |
|---|---|
| 13 | abi <abi/5.0>, (indented) |
| 15 | include <abstractions/crypto> |
| 62 | @{etc_ro}/ld.so.cache mr, |
| 177 | owner @{HOME}/.Private/** mrixwlk, |
| 184 | include if exists <abstractions/base.d> |
##included <abstractions/base>, <abstractions/crypto>, <abstractions/openssl>, <abstractions/upki> (tree).include <tunables/global> the profile fails with Failed to find declaration for: @{HOMEDIRS} (tree).NAME.d directory of the shipped file. Which names are skipped there is in syn-include-if-exists.+=. A plain = on a declared variable gives variable @{HOMEDIRS} was previously declared (tree, with the assignment in the profile file's own preamble).apparmor_parser -r. The change takes effect when a profile is compiled (derived).@{HOMEDIRS} with its dump is in the scene "Change the dot d directory, not the shipped file".| Message | Cause | Basis |
|---|---|---|
in profile .../tunables/home at line 15: syntax error, unexpected TOK_EQUALS, expecting TOK_MODE | include <tunables/global> inside a profile | tree |
in profile .../abstractions/consoles at line 16: syntax error, unexpected TOK_MODE, expecting TOK_OPEN | include <abstractions/consoles> above the profile | tree |
Failed to find declaration for: @{HOMEDIRS}, then ERROR expanding variables for profile demo, failed to load | include <abstractions/base> without include <tunables/global> | tree |
variable @{HOMEDIRS} was previously declared | @{HOMEDIRS} = ... after the tunables declared it | tree |
in profile FILE at line N: ... for a file of a NAME.d directory | a syntax error in a site file; every profile that includes NAME fails | tree, with a stand-in file |
Which abstractions exist and what each grants is prac-abstractions.
preamble productions (parser_yacc.y:506-509); an abstraction by rules (parser_yacc.y:722-724, parser_yacc.y:845-850).@{u16} has an unbalanced bracket and also matches [ and 65536 to 69999.The file letters are r w a l k m and x with a transition type. They may appear in any order.
r w a l k m and x with a transition type. The scanner's set is [RrWwaLlMmkXx] plus the exec forms (parser_lex.l:257-258).requested_mask and denied_mask come from its own string, x w r a c d k m l, in the kernel (lib.c:253). c (create) and d (delete) exist only there; both are granted by w.c from the log fixtures in the AppArmor tree: apparmor="ALLOWED" operation="mkdir" profile="/usr/sbin/sshd" name="/run/user/1000/kakoune/" ... requested_mask="c" denied_mask="c" (testcase_socklogd_mkdir.in:1).MODE = ( r | w | a | l | k | m | EXEC MODE )+. w with a is an error. Bare x is valid only after deny.
MODE = ( 'r' | 'w' | 'a' | 'l' | 'k' | 'm' | EXEC MODE )+. One word; letters in any order, repeats allowed; white space or a comma ends it.MODE_CHARS ([RrWwaLlMmkXx])|(([Pp]|[Cc])[Xx])|(([Pp]|[Cc])?([IiUu])[Xx]) and MODES {MODE_CHARS}+ (parser_lex.l:257-258).w with a in one word: Conflict 'a' and 'w' perms are mutually exclusive. (parser_misc.c:595, parser_misc.c:602; test bad_append_1.sd).x in a rule that is not a deny rule: Invalid perms, 'x' must be preceded by exec qualifier 'i', 'p', or 'u'. An exec mode in a deny rule: Invalid perms, in deny rules 'x' must not be preceded by exec qualifier 'i', 'p', or 'u' (parser_misc.c:1090-1104).R W L M X I are lowered with a warning (parser_misc.c:704-718). Uppercase P, C and U are exec modes: see exec modes and safe and unsafe. A and K are not accepted.AppArmor parser error for FILE in profile FILE at line N: MESSAGE.r allows open for reading, read, directory listing and PROT_READ mappings. A rename needs r and w on the source name.
All kernel facts are from the kernel source, read and not run.
open: the LSM hook apparmor_file_open asks for the permissions computed from the open flags by aa_map_file_to_perms; FMODE_READ gives MAY_READ (lsm.c:498-500, file.h:119-120). A directory opened for listing is an open of the directory's own name.read: hook apparmor_file_permission passes the mask from the VFS (lsm.c:547-550).apparmor_file_receive, with the permissions of the open mode (lsm.c:542-545).mmap or mprotect with PROT_READ asks for MAY_READ (lsm.c:570-571).apparmor_path_rename asks on the old name for MAY_READ | AA_MAY_GETATTR | MAY_WRITE | AA_MAY_SETATTR | AA_MAY_DELETE (lsm.c:433-437).r; the kernel records MAY_EXEC | MAY_READ | AA_EXEC_MMAP for it (lsm.c:482-485).r in a profile also grants reading attributes and open: the old read bit maps to AA_MAY_GETATTR | AA_MAY_OPEN (policy_compat.c:82-83).w allows write, create, delete, rename, truncate, chmod and chown. Logs show create as c and delete as d; both are granted by w.
All kernel facts are from the kernel source, read and not run.
w grants: the old write bit maps to AA_MAY_SETATTR | AA_MAY_CREATE | AA_MAY_DELETE | AA_MAY_CHMOD | AA_MAY_CHOWN | AA_MAY_OPEN, next to MAY_WRITE and MAY_APPEND themselves (policy_compat.c:80, policy_compat.c:84-86).apparmor_path_unlink, apparmor_path_rmdir: AA_MAY_DELETE.apparmor_path_mkdir, apparmor_path_mknod, apparmor_path_symlink: AA_MAY_CREATE.apparmor_path_truncate, apparmor_file_truncate: MAY_WRITE | AA_MAY_SETATTR.apparmor_path_rename asks for MAY_WRITE | AA_MAY_SETATTR | AA_MAY_CREATE on the new name (lsm.c:439-443); apparmor_path_chmod and apparmor_path_chown ask for AA_MAY_CHMOD and AA_MAY_CHOWN (lsm.c:450-458).FMODE_WRITE gives MAY_WRITE, O_TRUNC adds MAY_WRITE, O_CREAT adds AA_MAY_CREATE (file.h:117-128).aa_file_perm_chrs is "xwracd km l " (lib.c:253); setattr, chmod and chown are printed as w, getattr as r (file.c:28-38).operation="mkdir" ... requested_mask="c" denied_mask="c" (testcase_socklogd_mkdir.in:1).w is wider than "write": by the old-format mapping it also grants create, delete, setattr, chmod and chown on every name the rule matches (policy_compat.c:78-98; read from the kernel source, not observed on a running kernel). The only narrower letter is a.r: compute_fperms_allow adds AA_MAY_GETATTR unconditionally (policy_compat.c:100-103). By that code a profile cannot hide the existence, size or owner of a file it names for another purpose.a narrows the open, not necessarily the descriptor: whether a later write(2) on a descriptor opened with O_APPEND under an a-only rule is refused was not determined (see "Not determined" in the reference below).c and d cannot be written in a profile, so a policy cannot allow create without delete, or the reverse.requested_mask and denied_mask.a grants the append permission only: an open with O_APPEND of an existing file. O_TRUNC, O_CREAT, delete and chmod need w.
a sets AA_MAY_APPEND; w sets AA_MAY_WRITE | AA_MAY_APPEND; the two letters in one word are an error (parser_misc.c:599-604). Tests: ok_append_1.sd, bad_append_1.sd./a a, and /a w,, are merged without error (observed with the released parser 5.0.2).aa_map_file_to_perms turns the open flags into the request (file.h:117-128):O_WRONLY | O_APPEND: MAY_APPEND replaces MAY_WRITE.O_TRUNC adds MAY_WRITE; O_CREAT adds AA_MAY_CREATE, whether or not the file exists.O_RDWR | O_APPEND: MAY_READ and MAY_APPEND, so the rule needs r as well.write(2) on a descriptor opened under an a-only rule is allowed by a running kernel. The open records the granted request (lsm.c:502) and each write arrives as MAY_WRITE (lsm.c:547-550, file.c:655-669). The AppArmor regression tests have no append test.k allows flock and fcntl locks (a write lock also needs w). m allows mmap or mprotect with PROT_EXEC; libraries need mr.
Kernel facts are from the kernel source, read and not run.
apparmor_file_lock asks for AA_MAY_LOCK, plus MAY_WRITE when the command is F_WRLCK (lsm.c:552-560). The log operation is file_lock (audit.h:66).operation="file_lock" requested_mask="k" denied_mask="k" name="/var/run/samba/unexpected.tdb" ... profile="/usr/sbin/nmbd" (testcase14.in:1).common_mmap, called from the hooks apparmor_mmap_file and apparmor_file_mprotect, asks for MAY_READ for PROT_READ, MAY_WRITE for a PROT_WRITE mapping that is not MAP_PRIVATE, and AA_EXEC_MMAP for PROT_EXEC (lsm.c:562-595).MAY_EXEC | MAY_READ | AA_EXEC_MMAP without a rule lookup at open (lsm.c:482-485). Shared libraries and the ELF loader are opened and mapped later, under the profile the program runs in.apparmor_parser -X (--readimpliesX, "Map profile read permissions to mr") makes r imply m (parser_main.c:243).ix.ix implies m: add_implied_ix_mmap adds the mapping bit for the owner and the other half when the priority of the mapping bit is not higher than that of the exec bit (hfa.cc:1497-1524).parse_sub_perms (parser/parser_misc.c:560) sets bits from parser/immunix.h:35-48; map_old_perms (linux:security/apparmor/policy_compat.c:78-98) expands them.
AA_MAY_EXEC 0x1, AA_MAY_WRITE 0x2, AA_MAY_READ 0x4, AA_MAY_APPEND 0x8, AA_OLD_MAY_LINK 0x10, AA_OLD_MAY_LOCK 0x20, AA_OLD_EXEC_MMAP 0x40, AA_EXEC_PUX 0x80, AA_EXEC_UNSAFE 0x100, AA_EXEC_INHERIT 0x200, transition type 0x3c00.parse_sub_perms walks the letters (parser_misc.c:560-734); perm32_t parse_perms(const char *str_perms) stores the field at AA_USER_SHIFT 0 and AA_OTHER_SHIFT 14 (parser_misc.c:736-745, immunix.h:24-25).AA_ONEXEC and AA_CHANGE_HAT, bit 31 is AA_CHANGE_PROFILE (immunix.h:63-65)./a r, is 0x10004, /a rw, is 0x3800e; owner leaves only the low half.map_old_perms keeps the low four bits and adds AA_MAY_GETATTR | AA_MAY_OPEN for read, AA_MAY_SETATTR | AA_MAY_CREATE | AA_MAY_DELETE | AA_MAY_CHMOD | AA_MAY_CHOWN | AA_MAY_OPEN for write, AA_MAY_LINK for 0x10, AA_MAY_LOCK | AA_LINK_SUBSET for 0x20 and AA_EXEC_MMAP for 0x40 (policy_compat.c:78-98). The owner and other halves are read with dfa_user_allow and dfa_other_allow (policy_compat.c:53-70); the exec bits of a half become an index through dfa_map_xindex (policy_compat.c:24-48).compute_fperms_allow adds AA_MAY_GETATTR to every allow set (policy_compat.c:100-103).map_old_perms at policy_compat.cc:127-147, dfa_map_xindex at policy_compat.cc:41-65)."Conflict 'a' and 'w' perms are mutually exclusive." "Invalid perms, 'x' must be preceded by exec qualifier 'i', 'p', or 'u'". Uppercase R W L M X I are deprecated spellings of lowercase.
Messages of the parser built from the AppArmor tree at 836052d21. The full form is AppArmor parser error for FILE in profile FILE at line N: MESSAGE.
/a wa,: Conflict 'a' and 'w' perms are mutually exclusive. (parser_misc.c:595, parser_misc.c:602; bad_append_1.sd)./bin/ls rx,: Invalid perms, 'x' must be preceded by exec qualifier 'i', 'p', or 'u' (parser_misc.c:1097-1100; simple_bad_no_bare_x.sd). The message omits c, although cx is an exec mode./bin/ls K,: syntax error, unexpected TOK_ID, expecting TOK_MODE (bad_lock_1.sd). K is not in the scanner's letter set (parser_lex.l:257-258).mark r,: syntax error, unexpected TOK_MODE, expecting TOK_ID or TOK_SET_VAR (observed with the released parser 5.0.2).R W L M X I: warning Uppercase qualifiers "RWLIMX" are deprecated, please convert to lowercase, then See the apparmor.d(5) manpage for details. (parser_misc.c:549-558, parser_misc.c:704-718). Printed once per run.deprecated (parser_main.c:284), off by default. apparmor_parser --warn=deprecated or --warn=all turns it on.--warn.x.Next: syn-exec-modes for x, syn-link-rules for l, adm-denials for the letters in log records.
r: open for reading, read, directory listing, PROT_READ mappings, the old name of a rename.w: write, create, delete, rename, truncate, chmod, chown; the log shows create as c and delete as d.a: an open with O_APPEND of an existing file, nothing else. k: flock and fcntl locks. m: PROT_EXEC mappings.x needs a transition type and l needs a link target; each has its own deck.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the fragment, with nothing loaded into a kernel; "code" means the kernel source of mainline Linux 7.4 (7.4-rc2, 97d73c825) or the parser source was read, not run. Nothing on this page was run against a kernel: every statement about what the kernel asks for or grants is "code".
MODE = ( 'r' | 'w' | 'a' | 'l' | 'k' | 'm' | EXEC MODE )+
[RrWwaLlMmkXx] plus the exec forms (ix, px, Px, cx, Cx, ux, Ux and the fallback forms such as pix); exec modes are in syn-exec-modes.wr is rw.| Letter | Allows | Requests that ask for it | Also needs |
|---|---|---|---|
r | read | open for reading; read; listing a directory; mmap or mprotect with PROT_READ; receiving a descriptor from another process; the source name of a rename | a rename source also needs w |
w | write, create, delete, attribute changes | open for writing; O_TRUNC; write; create through O_CREAT, mkdir, mknod, symlink; unlink; rmdir; truncate; chmod; chown; both names of a rename; a shared writable mapping; a write lock | a rename source also needs r; a write lock also needs k |
a | append | open for writing with O_APPEND | nothing else is granted: see the next section |
l | a hard link with this name | link on the new name | a link rule or a matching target: syn-link-rules |
k | file locks | flock; fcntl locks | a write lock (F_WRLCK) also needs w |
m | mapping the file as executable | mmap or mprotect with PROT_EXEC | libraries are normally given mr |
x | execute | execve | a transition type in allow rules: syn-exec-modes |
/var/lib/demo/x a rule must give w on /var/lib/demo/x; w on /var/lib/demo/ is not what is asked (code).w on the new name. It is not a link request and does not need l (code).w; a shared one does (code).What an open asks for, from the kernel's translation of the open flags (code):
| Open flags | The open asks for | Under a rule with only a |
|---|---|---|
O_WRONLY, O_APPEND | append | granted |
O_WRONLY | write | not granted |
O_WRONLY, O_APPEND, O_TRUNC | append and write | not granted |
O_WRONLY, O_APPEND, O_CREAT | append and create | not granted |
O_RDWR, O_APPEND | read and append | needs r as well |
a grants the append permission and nothing else: no create, delete, truncate, chmod or chown.w sets both the write and the append bit, so every request that a satisfies is also satisfied by w.w and a in one mode word are an error. Two separate rules, /a a, and /a w,, are merged without error (tree).The kernel prints requested_mask and denied_mask with its own letter string, x w r a c d k m l (code).
| Letter in the log | Meaning | Profile letter that grants it |
|---|---|---|
c | create | w |
d | delete | w |
w | write; also chmod, chown and other attribute changes | w |
r | read; also reading attributes | r |
a | append | a or w |
k | lock | k |
m | executable mapping | m |
l | link | l |
x | execute | an exec mode |
Sample records, shortened, from the log fixtures in the AppArmor tree:
apparmor="ALLOWED" operation="mkdir" profile="/usr/sbin/sshd" name="/run/user/1000/kakoune/" ... requested_mask="c" denied_mask="c" ... operation="file_lock" requested_mask="k" denied_mask="k" name="/var/run/samba/unexpected.tdb" ... profile="/usr/sbin/nmbd"
Reading denial records: adm-denials.
w includes a.ix adds m on the same path, unless a rule of higher priority decided that bit (code).r (code).r; the kernel records read and executable mapping for it under the label that ran the exec. Derived from the code of mainline Linux 7.4 and not run on a kernel: a profile reached through px or cx is asked again and needs mr on its own executable, because the recorded permissions count only while the task's label is the one that opened the file (linux:security/apparmor/lsm.c:482-485, linux:security/apparmor/file.c:506-520, 655-669). With ix the label stays, and the parser adds m to an ix rule (parser/libapparmor_re/hfa.cc:1497-1524). Shared libraries and the ELF loader are mapped by the new program and need mr in the profile it runs under (code).apparmor_parser -X makes r imply m: the dumped permission of /a r, changes from 0x10004 to 0x110044 (tree). A parser built with FORCE_READ_IMPLIES_EXEC does the same (code).The parser prints an error as AppArmor parser error for FILE in profile FILE at line N: MESSAGE (tree). The table gives MESSAGE.
| Message | Cause |
|---|---|
Conflict 'a' and 'w' perms are mutually exclusive. | wa or aw in one mode word (tree) |
Invalid perms, 'x' must be preceded by exec qualifier 'i', 'p', or 'u' | an allow rule with a bare x, such as rx (tree); also /a x -> b, (tree) |
Invalid perms, in deny rules 'x' must not be preceded by exec qualifier 'i', 'p', or 'u' | deny /a px, (tree); deny /a x, is accepted |
syntax error, unexpected TOK_ID, expecting TOK_MODE | a word that is not a mode where one is expected, such as K (tree) |
syntax error, unexpected TOK_MODE, expecting TOK_ID or TOK_SET_VAR | a word of mode letters where a path is expected, such as mark r, (tree) |
Uppercase qualifiers "RWLIMX" are deprecated, please convert to lowercase followed by See the apparmor.d(5) manpage for details. | a warning, for uppercase R W L M X I (tree, with --warn=all). Its class is deprecated, which is off by default; --warn=deprecated turns it on. Printed once per run |
Internal: unexpected perms character 'C' in input | internal; needs a mismatch between the scanner and the mode parser (code) |
Internal error generated invalid perm 0xN | internal (code) |
P, C and U are not deprecated spellings: they are exec modes. A and K are not accepted at all.'i', 'p', or 'u' and omit c, although cx is an exec mode.RWLIMX, and the code that lowers the letter also names append, but the scanner does not accept an uppercase A.x is valid for named transitions; the parser rejects /a x -> b, (tree).Bits of one half, set by parse_sub_perms (parser/parser_misc.c:560-734) from parser/immunix.h:35-48:
| Bit | Name | Letter |
|---|---|---|
0x1 | AA_MAY_EXEC | x |
0x2 | AA_MAY_WRITE | w (with 0x8) |
0x4 | AA_MAY_READ | r |
0x8 | AA_MAY_APPEND | a, w |
0x10 | AA_OLD_MAY_LINK | l |
0x20 | AA_OLD_MAY_LOCK | k |
0x40 | AA_OLD_EXEC_MMAP | m |
0x80 | AA_EXEC_PUX | exec fallback |
0x100 | AA_EXEC_UNSAFE | exec |
0x200 | AA_EXEC_INHERIT | exec |
0x3c00 | transition type | exec |
parse_perms (parser/parser_misc.c:736-745) stores the field twice: AA_USER_SHIFT 0 and AA_OTHER_SHIFT 14 (parser/immunix.h:24-25). /a r, dumps as 0x10004, /a rw, as 0x3800e (tree); owner leaves only the low half.AA_ONEXEC and AA_CHANGE_HAT; bit 31 is AA_CHANGE_PROFILE (parser/immunix.h:63-65).(allow/deny//prompt/audit/quiet) in this layout.map_old_perms (linux:security/apparmor/policy_compat.c:78-98; the parser's copy is parser/libapparmor_re/policy_compat.cc:127-147):
| Old bit | Kernel permissions |
|---|---|
0x1 0x2 0x4 0x8 | kept: MAY_EXEC, MAY_WRITE, MAY_READ, MAY_APPEND |
| read | adds AA_MAY_GETATTR, AA_MAY_OPEN |
| write | adds AA_MAY_SETATTR, AA_MAY_CREATE, AA_MAY_DELETE, AA_MAY_CHMOD, AA_MAY_CHOWN, AA_MAY_OPEN |
0x10 | AA_MAY_LINK |
0x20 | AA_MAY_LOCK, AA_LINK_SUBSET (the same value, linux:security/apparmor/include/perms.h:34,49) |
0x40 | AA_EXEC_MMAP |
AA_MAY_GETATTR is also added to the allow set by compute_fperms_allow (linux:security/apparmor/policy_compat.c:103).aa_map_file_to_perms (linux:security/apparmor/include/file.h:112-131) turns open flags into the request: FMODE_WRITE to MAY_WRITE, FMODE_READ to MAY_READ, O_APPEND replaces MAY_WRITE by MAY_APPEND, O_TRUNC adds MAY_WRITE, O_CREAT adds AA_MAY_CREATE.aa_file_perm_chrs (linux:security/apparmor/lib.c:253); the folding of chmod, chown and setattr into w and getattr into r is in linux:security/apparmor/file.c:28-38.ix implies m step: parser/libapparmor_re/hfa.cc:1497-1524.Hooks in linux:security/apparmor/lsm.c:
| Operation | Hook | Request |
|---|---|---|
| unlink, rmdir | apparmor_path_unlink, apparmor_path_rmdir (327-330, 339-342) | AA_MAY_DELETE |
| mkdir, mknod, symlink | apparmor_path_mkdir, apparmor_path_mknod, apparmor_path_symlink (332-348, 360-365) | AA_MAY_CREATE |
| truncate | apparmor_path_truncate, apparmor_file_truncate (350-358) | MAY_WRITE, AA_MAY_SETATTR |
| link | apparmor_path_link (367-384) | see syn-link-rules |
| rename | apparmor_path_rename (386-448) | source: MAY_READ, AA_MAY_GETATTR, MAY_WRITE, AA_MAY_SETATTR, AA_MAY_DELETE; destination: MAY_WRITE, AA_MAY_SETATTR, AA_MAY_CREATE |
| chmod, chown | apparmor_path_chmod, apparmor_path_chown (450-458) | AA_MAY_CHMOD, AA_MAY_CHOWN |
| open | apparmor_file_open (465-507) | from aa_map_file_to_perms; an exec open is preset to MAY_EXEC, MAY_READ, AA_EXEC_MMAP (482-485) |
| receive a descriptor | apparmor_file_receive (542-545) | from the open mode |
| read, write | apparmor_file_permission (547-550) | the mask from the VFS |
| lock | apparmor_file_lock (552-560) | AA_MAY_LOCK, plus MAY_WRITE for F_WRLCK |
| mmap, mprotect | common_mmap (562-595) | MAY_READ for PROT_READ; MAY_WRITE for a shared PROT_WRITE mapping; AA_EXEC_MMAP for PROT_EXEC |
How the bits become tables: re-perms. Where the kernel looks them up: k-match.
write(2) on a descriptor opened with O_APPEND under an a-only rule is allowed by a running kernel. The open records MAY_APPEND in the file context (linux:security/apparmor/lsm.c:502) and each write arrives as MAY_WRITE (linux:security/apparmor/lsm.c:547-550; linux:security/apparmor/file.c:655-669). No kernel was available and tests/regression/apparmor has no append test.open with O_APPEND|O_CREAT on a file that already exists is refused under an a-only rule. O_CREAT adds AA_MAY_CREATE to the request whether or not the file exists (linux:security/apparmor/include/file.h:127-128), so by reading it is refused. Not run.AA_MAY_GETATTR in every policy format, that is, whether stat of a path that no rule matches is ever refused.alias /usr/ -> /opt/demo/usr/, makes rules written for /usr/ apply under /opt/demo/usr/ as well.
/opt/demo/usr/ (run with the tree's parser for this deck; see the scene "A rule gains a twin, and so does the attachment").# alias /usr/ -> /mnt/usr/, and # alias /var/lib/mysql/ -> /home/mysql/,. No shipped file under profiles/ has an alias rule outside a comment.demo are invented for the map.alias FROM -> TO, in the preamble. Site aliases belong in tunables/alias.
ALIAS RULE = 'alias' ABS PATH '->' REWRITTEN ABS PATH ',' (apparmor.d.pod:116)./usr/ are from rewrite/alias_dupe_1.sd, a test the parser is expected to accept.tunables/alias reaches a profile only through include <tunables/global> in that file's preamble; the -p output of the example file has ##included <tunables/alias> (run with the tree's parser for this deck).include if exists <tunables/alias.d>.alias: TOK_ALIAS TOK_ID TOK_ARROW TOK_ID TOK_END_OF_RULE (parser_yacc.y:511-517), in preamble only (parser_yacc.y:506-509).alias is a keyword (parser_misc.c:105).Each matching rule is duplicated with the new prefix; the original stays. The attachment gains an alternate name.
aare: /usr/lib/demo/worker -> /usr/lib/demo/worker and aare: /opt/demo/usr/lib/demo/worker -> /opt/demo/usr/lib/demo/worker, each followed by a rule: line with priority=0 (0x804201/0): the same permissions./usr/bin/demo and /opt/demo/usr/bin/demo.aare: lines in all; 17 begin with /opt/demo/usr/: the attachment's twin and 16 rule twins, one for the worker rule and fifteen for rules of abstractions/base, such as /usr/share/locale/**.aare: line, the rule text after expansion.Twins for file rules, link rules and the attachment. No twins for mount, unix, dbus and change_profile paths or exec targets.
include <tunables/global>, alias /home/ -> /mnt/users/, and alias /usr -> /opt/usr,: /home/*/.config/demo r, gains /mnt/users/*/.config/demo; deny /home/secret r, gains /mnt/users/secret; link /home/a -> /home/b, gains /mnt/users/a, /mnt/users/b. The mount, change_profile and unix rules on the slide are not aliased.alias /a/ -> /b/,: a rule in an if true { } block, in an audit { } block, in a hat and in a child profile is aliased, and the child profile /a/kid gets the attachment /b/kid. /{a,x}/alt r, is not aliased. The exec target of /a/exe px -> /a/target, stays /a/target. /a r, is not aliased and /a/ r, is."/with space/y" r, is aliased by alias "/with space/" -> "/other space/", and /with\ space/x r, is not: the two spellings are different text.@{exec_path} mr, is aliased afterwards like any file rule, while the variable itself holds the attachment as written.deny /usr/share/secret r,, the dump has /usr/share/secret and /opt/demo/usr/share/secret, both as deny rules (run with the tree's parser for this deck).alias /home/ -> /mnt/users/, the rule @{HOME}/.demo r, compiles only as {/home/*,/root}/.demo. Recorded with the same alias: owner @{HOMEDIRS}/*/x w, is compiled as /home/*/x and /mnt/users/*/x while @{HOMEDIRS} has the one value /home/. With a second value (@{HOMEDIRS} += /srv/nfs/home/, the line of a site file) the rule is compiled as {/home,/srv/nfs/home}/*/x and has no twin (run with the tree's parser for the review of this deck). The slide therefore shows no rule that begins with a variable: compare the alias with the text that -D rule-exprs prints.alias /usr -> /opt/usr, copies /usrlocal/y to /opt/usrlocal/y.After an alias a profile matches a superset of paths and attaches to a superset of programs. Aliases do not chain.
/usr/lib/demo/worker ix, and deny /usr/share/secret r, gives aare: lines for /usr/share/secret and /opt/demo/usr/share/secret, both followed by a rule: line marked deny. The path /usr/share/secret is invented./a/x r, compiles as /a/x, /b/x and /c/x, and the attachments of that profile are /a/bin/demo, /c/bin/demo, /b/bin/demo. /b/x is not aliased again to /d/x.'/a/' is already defined on standard error and is dropped, with exit status 0 (recorded).tunables/alias and tunables/alias.d/ apply to every profile whose preamble includes tunables/global.@{exec_path} and @{attach_path} do not include the alternates.ix or Px, the attachment) apply to files that user controls. This is reasoned from the mechanism and was not run.-D rule-exprs after any change under tunables/alias*.parser_alias.c:111-157 copies entries by strncmp prefix; 159-191 adds alternate attachment names; both run after variable expansion.
new_alias() (parser_alias.c:37-94) returns 1 on every path, so Failed to create alias %s -> %s cannot be reached (parser_yacc.y:513-514).replace_profile_aliases() (parser_alias.c:201-209) is called after a profile's variables are expanded (parser_policy.c:133-144).process_name (parser_alias.c:159-191); the attachment matcher is built from the attachment and every alternate (parser_regex.c:531-533).block::apply_aliases (block.cc:295-303); process_entries (parser_alias.c:111-157); do_alias (parser_alias.c:96-107).AA_SHARED_PERMS bits are skipped (parser_alias.c:123; immunix.h:66).free_aliases() is called from reset_parser() (parser_main.c:1260).SUB_ID_WS state takes the right side of the arrow (parser_lex.l:822).An alias is per file and covers file rules, link rules and attachments only. Verify with -D rule-exprs.
AppArmor parser error for /work/p06b.sd in profile /work/p06b.sd at line 2: syntax error, unexpected TOK_ALIAS, expecting TOK_ID or TOK_MODE or TOK_SET_VAR. The parser's test rewrite/bad_alias_inside_profile.sd expects a failure for it.TOK_PROFILE: ... at line 2: syntax error, unexpected TOK_PROFILE, expecting TOK_END_OF_RULE.... at line 1: syntax error, unexpected TOK_ID, expecting TOK_ARROW.'/usr/' is already defined on standard error, exit status 0, and the dump has each twin once./work/ are scratch names of the runs.alias foo -> bar, and alias /x -> y, exit with status 0, and /x/1 r, gains the rule y/1.An alias adds twins for file rules, link rules and the attachment.
Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run on the fragment (-Q -K --skip-kernel-load -D rule-exprs, with the tree's abi/5.0 file as kernel feature set), with nothing loaded into a kernel; "code" means the parser source was read and not run; "derived" means the result was reasoned from that code. Nothing here was observed on a running kernel.
ALIAS RULE: 'alias' FROM '->' TO ','
alias "/with space/" -> "/other space/", (tree).rewrite/alias_dupe_1.sd).'FROM' is already defined on standard error and is dropped; exit status 0 (tree).Recorded results with alias /home/ -> /mnt/users/, unless the row names another alias (tree).
| Rule | Result |
|---|---|
/home/*/.config/demo r, | twin /mnt/users/*/.config/demo |
deny /home/secret r, | twin /mnt/users/secret, a deny rule |
link /home/a -> /home/b, | twin /mnt/users/a, /mnt/users/b |
owner @{HOMEDIRS}/*/x w, (a variable with one value) | /home/*/x and twin /mnt/users/*/x; with a second value in @{HOMEDIRS} the rule is {/home,/srv/nfs/home}/*/x and has no twin (see the known discrepancy below) |
the attachment /usr/bin/demo with alias /usr/ -> /opt/demo/usr/, | alternate /opt/demo/usr/bin/demo |
/usr/lib/demo/worker ix, with the same alias | twin /opt/demo/usr/lib/demo/worker, same permissions |
a rule in a hat, a child profile, an if true { } block, an audit { } block, with alias /a/ -> /b/, | twin |
the child profile /a/kid with alias /a/ -> /b/, | attachment /b/kid added |
"/with space/y" r, with alias "/with space/" -> "/other space/", | twin |
/with\ space/x r, with the same alias | no twin: a different spelling is different text |
mount /home/src -> /home/mnt/, | no twin |
change_profile /home/bin/x -> other, | no twin |
unix (bind) addr=@/home/sock, | no twin |
/a/exe px -> /a/target, with alias /a/ -> /b/, | the rule gets a twin; the target stays /a/target |
/{a,x}/alt r, with alias /a/ -> /b/, | no twin: the text does not begin with /a/ |
/a r, with alias /a/ -> /b/, | no twin; /a/ r, gets one |
/a/x r, with alias /a/ -> /b/,, alias /a/ -> /c/,, alias /b/ -> /d/, | /a/x, /b/x, /c/x: no chaining |
The running example: 17 of 106 compiled lines are twins (tree).
tunables/alias is the shipped place for site aliases. It holds two commented examples and ends with include if exists <tunables/alias.d>. tunables/global includes it.tunables/global does not see those aliases (derived).apparmor.d(5) describes alias rules as "remapping paths" and "an alternative form of path rewriting". The parser adds a copy and keeps the original rule and the original attachment (tree). This page follows the parser.
| Message | Cause | Exit status | Basis |
|---|---|---|---|
syntax error, unexpected TOK_ALIAS, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | an alias inside a profile | 1 | tree |
syntax error, unexpected TOK_PROFILE, expecting TOK_END_OF_RULE | no comma, and a profile on the next line | 1 | tree |
syntax error, unexpected TOK_ID, expecting TOK_ARROW | no arrow | 1 | tree |
'/usr/' is already defined | the same alias twice | 0 | tree |
| none | an alias that matches nothing | 0 | tree |
tunables/alias or tunables/alias.d/, and then applies to every profile file that includes tunables/global.-D rule-exprs after any change to an alias.preamble (parser_yacc.y:506-509).new_alias() (parser_alias.c:37-94), process_entries (parser_alias.c:111-157), process_name (parser_alias.c:159-191), replace_profile_aliases() (parser_alias.c:201-209).alias /home/ -> /mnt/users/, the rule @{HOME}/.demo r, compiles only as {/home/*,/root}/.demo.alias foo -> bar, and alias /x -> y, exit with status 0; alias /a/* -> /b/, and alias @{V}/ -> /w/, are accepted and match nothing.alias /usr -> /opt/usr, copies /usrlocal/y to /opt/usrlocal/y.all, allows everything the rule classes can express. Add deny rules to subtract.
all has no kernel object: the parser replaces it with ordinary rules before compiling, and the kernel sees those.profile worker { all, } is line 36 of demo's profile. The profile on the slide, with the two deny rules, compiles with no warning (run with the tree's parser). The program demo and its profiles are invented for the map.[audit] [allow|deny|prompt] all,. No priority=, no owner, nothing after the word.
all,, allow all,, audit all,, audit deny all, and prompt all, are accepted (run with the tree's parser). What prompt does in the kernel is in prompt.priority=1 all, gives priority prefix not allowed on all rules; owner all, gives owner prefix not allowed on all rules; all /srv/** r, gives syntax error, unexpected TOK_ID, expecting TOK_END_OF_RULE (run with the tree's parser).allow and names beginning with all are unaffected.capability all, gives syntax error, unexpected TOK_ALL, expecting TOK_ID or TOK_END_OF_RULE; see capability rules.audit { all, } is audit all, and deny { all, } is deny all,; owner { all, } is refused with the owner message. Inside a true if block it works as outside (run with the tree's parser). The expansion is always added to the profile's main block.all, = a bare rule of every class + /{**,} with all file permissions + /{**,} ix + all capabilities, each with the qualifiers of the all rule.
ix (inherit): a program the task starts runs under the same profile.all rule: audit all, audits every one of them, deny all, denies them, with one exception: its file entry covers only files the task owns.deny all, denies only the owner half of the file permissions": for a file the task does not own, deny all, denies nothing and an allow rule elsewhere in the profile still applies. See Known bugs.--warn=rule-not-enforced, as for hand-written rules.all_rule::add_implied_rules (all_rule.cc:33-148), called from parser_policy.c:131, before variable expansion. By source line: unix 38-40, dbus 42-44, io_uring 46-48, mqueue 50-52, ptrace 54-56, signal 58-60, userns 62-64, mount, remount, umount and pivot_root 66-80, network 82-85, the file entry 89-110, the exec entry 111-141, capabilities 142-145.AA_BASE_PERMS & ~(AA_EXEC_TYPE | AA_MAY_EXEC) (all_rule.cc:97); compiled, all, gives /([^\x00]*|) with 0x1f807e at priority 0 and the exec entry 0x804201 at priority -1 (run with the tree's parser).Not included: change_profile, set rlimit, exec transitions other than ix, hats and child profiles.
set rlimit rule AppArmor sets no limit, and whether the call succeeds is the kernel's ordinary rule; see rlimit rules.all, next to change_profile -> other, compiles (run with the tree's parser).deny all, the exec entry has no ix.all,, for example /usr/bin/sudo Px,, is an ordinary rule at priority 0 against the implied exec entry at priority -1, so it wins. That is why all refuses a priority= of its own.priority - 1 at all_rule.cc:124, no ix under deny at all_rule.cc:129-130. The comment // TODO: rlimit: all_rule.cc:147.all, gives a confined profile with broad rules. flags=(unconfined) is a mode tested before any rule.
all, is not in that mode, so its rules are evaluated.default_allow: "similar and for many profiles will be equivalent to specifying an allow all, rule", without the same options (apparmor.d.pod:742-745).unconfined and default_allow are taught in profile modes; this slide states only what distinguishes them from the rule.all, is broader than most hand-written profiles (every capability, every mount, every file) and narrower than unconfined in two ways only: exec stays in the profile, and change_profile is absent.all, plus a short deny list confines exactly as much as that list. Anything the list forgot, and anything a rule class cannot express (see what is not mediated), is allowed.unconfined and default_allow profiles, except the one for user namespaces (parser_regex.c:1392-1397).all, plus deny rules is a deny-list profile. audit all, logs everything and refuses nothing.
audit all, (run with the tree's parser). The results "allowed" and "denied" are derived from the rule that a deny wins over an allow of the same priority (see allow and deny); they were not run on a kernel.all, sit at priority 0, the exec entry at -1. A deny at the default priority therefore wins, and an allow rule with a higher priority than a deny would win over that deny; see priority. all itself cannot be given a priority.audit access all,; the form the grammar accepts is audit all,. The manual's deny-list example itself does not compile: deny file, is refused with Invalid perms, in deny rules 'x' must not be preceded by exec qualifier 'i', 'p', or 'u' (run with the tree's parser). Write the denies per path or per class, as on the slide.deny all, gives /{**,} deny 0x6e: the owner half only (all_rule.cc:97-101). all, gives both halves. Checked with the tree's parser and on a kernel.
-D rule-exprs): all, gives /([^\x00]*|) with 0x1f807e; deny all, gives /([^\x00]*|) deny 0x6e and the exec entry deny 0x4001; /etc/hostname r, with deny all, compiles, with the rule for /etc/hostname beside the deny. deny /** rwlk, gives 0xb802e and deny owner /** rw, gives 0xe.if (rule_mode != rule_mode_t::DENY) { perms |= perms << AA_OTHER_SHIFT; } with the comment duplicate to other permission set (all_rule.cc:97-101). The exec entry is duplicated to the other half in both modes (all_rule.cc:131-132).deny all, denies only the owner half of the file permissions". Confirmed on a kernel: under /** r, deny all, a file owned by root is read and a file the task owns is refused (see Known bugs).deny all, equals deny owner /{**,} with the non-exec permissions.all_rule::add_implied_rules (all_rule.cc:33-148), called from parser_policy.c:131; all_rule.h:77 compiles to nothing.
all_rule::add_implied_rules: all_rule.cc:33-148, called from parser_policy.c:131. The refused seats: all_rule.h:46-56. gen_policy_re returns without output (all_rule.h:77).all, from the tree's parser (-D rule-exprs), summarised: the file entry 0x1f807e at priority 0, the link pair 0x40030, the exec entry 0x804201 at priority -1, \x16 0x18, \x15 0x8, the ptrace rule (\x10|)\x09[^\000]+ 0x1e, the signal rule (\x10\xa|\x0a.)[^\000]+ 0x6, three dbus rules, mqueue rules for classes 17 and 18, the mount-class rules with 0x7 and the remount rule with 0x2.prompt all, marks each implied rule as prompt (run with the tree's parser).move_conditionals that is declared and not defined (all_rule.h:33-40).all, expands to rules. Deny subtracts; flags are something else.
[audit] [allow|deny|prompt] all, is replaced by the parser with a bare rule of every class, two file rules for every path and every capability.change_profile, set rlimit, exec transitions other than ix, hats and child profiles.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the line (-Q -K --skip-kernel-load --warn=all, -D rule-exprs for compiled forms), with nothing loaded into a kernel; "code" means the parser source or the kernel source was read, not run. Nothing here was observed on a running kernel.
ALL RULE: [audit] [allow|deny|prompt] all ,
all is a keyword only when followed by a blank or a character that cannot be part of a word; allow is unaffected (code).| Seat | On an all rule |
|---|---|
priority= | refused: priority prefix not allowed on all rules (tree) |
audit | taken: copied onto every implied rule |
allow, deny, prompt | taken: copied onto every implied rule; prompt is in syn-prompt |
owner, other | refused: owner prefix not allowed on all rules (tree) |
| Implied rule, as a profile line | Deck | Under deny all, |
|---|---|---|
unix, | syn-unix | denied |
dbus, | syn-dbus | denied |
io_uring, | syn-io-uring | denied |
mqueue, | syn-mqueue | denied |
ptrace, | syn-ptrace | denied |
signal, | syn-signal | denied |
userns, | syn-userns | denied |
mount, remount, umount, pivot_root, | syn-mount | denied |
network, | syn-network | denied |
/{**,} with every file permission except exec | syn-file-rules | the owner half only (known discrepancy) |
/{**,} ix, at the rule's priority minus one | syn-exec-modes | exec denied, without ix |
capability, (every capability) | syn-capability | denied |
The classes the feature set lacks are dropped from the expansion, silently by default (code). Read from the parser source and confirmed with a dump of all, and of deny all, (tree).
| Missing | Effect | Deck |
|---|---|---|
change_profile | a task under all, cannot ask to change profile | syn-change-profile |
set rlimit | no limit is set | syn-rlimit |
exec transitions other than ix | every program runs under the same profile | syn-exec-modes |
| hats and child profiles | they must be declared | syn-hats, syn-child-profiles |
all, | flags=(unconfined) | flags=(default_allow) | |
|---|---|---|---|
| What it is | a rule, expanded by the parser | a profile mode | a profile mode |
| Rules evaluated by the kernel | yes, on every operation | no: the mode is tested first | see syn-flags-modes |
| Deny rules beside it | enforced | nothing to subtract from | see syn-flags-modes |
| Exec | stays in the profile (ix) | as for an unconfined task | see syn-flags-modes |
| apparmor.d(5) | "a generic rule for all supported rule types" | "similar and for many profiles will be equivalent to specifying an allow all, rule" |
| Rule | Message |
|---|---|
priority=1 all, | priority prefix not allowed on all rules |
owner all, | owner prefix not allowed on all rules |
all /srv/** r, | syntax error, unexpected TOK_ID, expecting TOK_END_OF_RULE |
capability all, | syntax error, unexpected TOK_ALL, expecting TOK_ID or TOK_END_OF_RULE |
All rows are from the tree's parser.
all_rule is a prefix_rule_t whose gen_policy_re returns without output (parser/all_rule.h:77).add_implied_rules (parser/all_rule.cc:33-148) runs first in post-processing (parser/parser_policy.c:131), before variable expansion. It adds one object of each rule class with no conditionals and the prefixes of the all rule, two file entries, and calls add_capabilities with every bit set.all rule, which is always 0; the exec entry has that priority minus one (parser/all_rule.cc:124).mnt_rule with the permissions 0x7; the remount rule stays apart with 0x2 (tree).all, (tree): the file entry /([^\x00]*|) 0x1f807e, the link pair 0x40030, the exec entry 0x804201 at priority -1, \x16 0x18, \x15 0x8, and the rules of the other classes.None of these is taught as intended behaviour. All are on the bug list as confirmed; see Known bugs.
deny all, carries the owner half of the permissions only: deny all, compiles to /([^\x00]*|) deny 0x6e, where all, has 0x1f807e; reproduce with -D rule-exprs (tree). Confirmed on a kernel.parser/all_rule.h: copies of the io_uring permission macros and a declared, undefined move_conditionals (code).Inside a qualifier block the block's qualifiers apply: audit { all, } is audit all, and deny { all, } is deny all,; owner { all, } is refused with the owner message. Inside a true if block it works as outside (run with the tree's parser).
deny removes permissions that other rules grant. Rule order in the file has no effect.
deny in front of a rule, as in deny /etc/demo/secret.key r,./usr/bin/** r, with deny /usr/bin/foo r, (ok_deny_3.sd).open(2) of the key fails with EACCES. In the kernel a file request is refused when it asks for a permission that is not in the allow set of the matched name (file.c:246-247).demo, its files and its profile are invented for the map. Nothing on this slide was observed on a running kernel; the kernel behaviour is stated from the kernel source.-D dfa-states-initial, the state for the key is (0x 0/10004//0/0/10004) in the format (allow/deny//prompt/audit/quiet): nothing allowed, read denied and quiet for both the owner and the other half.deny is one of the alternatives of opt_rule_mode (parser_yacc.y:700-703).[priority=N] [audit] [allow|deny|prompt] [owner|other] RULE,. No access type means allow.
[priority=N] [audit] [allow|deny|prompt] [owner|other] RULE,. The order is fixed.file and before the keyword of any other rule class: deny file /a w,, deny capability chown,.-Q -K --skip-kernel-load --warn=all, nothing loaded into a kernel): deny audit /etc/demo/** w, is rejected: syntax error, unexpected TOK_AUDIT, expecting TOK_ID or TOK_MODE or TOK_SET_VAR; deny allow /foo r, is rejected: syntax error, unexpected TOK_ALLOW, expecting TOK_ID or TOK_MODE or TOK_SET_VAR.AppArmor parser error for FILE in profile FILE at line N: MESSAGE.set rlimit rules take no qualifier at all, also not through a block; the message is prefix not allowed on rlimit rules (parser.h:171-178, bad_rlimit_block_deny.sd). This is from the parser source and its test file.ACCESS TYPE = ( 'allow' | 'deny' ), omits prompt (apparmor.d.pod:198); the parser accepts three words.opt_prefix production, opt_priority opt_audit_flag opt_rule_mode opt_owner_flag (parser_yacc.y:705-711); the third seat is opt_rule_mode: empty, TOK_ALLOW, TOK_DENY or TOK_PROMPT (parser_yacc.y:700-703).deny, allow, prompt (parser_misc.c:100-102).prefixes.rule_mode (rule.h:244).allow RULE, equals RULE,. Permissions of allow rules matching the same name are combined.
allow RULE, grants exactly what RULE, grants. The manual page: "This is the default value for rules and does not need to be specified" (apparmor.d.pod:2550-2554).-Q -K --skip-kernel-load --warn=all, nothing loaded into a kernel), /var/lib/demo/state rw, together with allow /var/lib/demo/state k, gives one name with read, write, append and lock.request & (~perms->allow | perms->deny) (lib.c:430). Read from the source, not run.deny { allow /etc/demo/** r, } is rejected with conflicting mode prefix; deny { /etc/demo/** r, } is accepted and the rule becomes a deny rule.deny { capability chown, audit capability kill, } (ok_block1.sd).allow and a rule with no access type both become a MatchFlag node, or an ExactMatchFlag for a pattern without globs (aare_rules.h:85-92).perms.allow |= match->perms & amask; perms.audit |= match->audit & amask; (hfa.cc:1638-1639).conflicting mode prefix; an unspecified one takes the block's (rule.h:409-416 for rule classes, parser_misc.c:1111-1118 for file rules).-D dfa-states-initial: (0x b802e/0//0/0/0).At equal priority a deny overrides an allow for the permissions the deny names; other permissions of the allow remain. The refusal is what the file check of the kernel does with a missing allow bit.
/a rw, and deny /a w,, read stays allowed; write and append are refused. w includes append, so a denied w also removes a.priority=1 /a rw, and deny /a w,, read and write are allowed. With priority=1 on both, the deny wins again./a* rw, and priority=-1 deny /** w,, names matching /a* keep read and write.pri_update_perm scores each matching node per bit: priority << 2, plus 3 for a deny node, 2 for an exact match on an exec bit, 1 for an allow node, 0 for prompt (hfa.cc:1529-1554). The highest score keeps the bit.perms.deny |= match->perms & amask; perms.quiet |= match->audit & amask; and the bit is cleared from allow, audit and prompt (hfa.cc:1585-1594).-D dfa-states-initial, r for both halves is 0x10004, w with append 0x2800a): /a rw, with deny /a w, gives (0x 10004/2800a//0/0/2800a); priority=1 /a rw, with deny /a w, gives (0x 3800e/0//0/0/0).deny refuses without a log record. Reading the kernel code of the kernel, this holds in complain mode as well; it was not tested on a running kernel. audit deny logs the refusal.
apparmor="DENIED"; in complain mode the request is allowed and the record says apparmor="ALLOWED" (audit.c:200-236).deny rule: EACCES and no record, in enforce and in complain mode. The denied permissions are marked quiet; the kernel removes quiet bits from the request before logging and returns the error when nothing is left (file.c:142-149 for files, lib.c:440-447 for the other rule classes, capability.c:87-92 for capabilities).audit deny does not mark the permissions quiet, so the refusal is logged.echo -n noquiet > /sys/module/apparmor/parameters/audit, or apparmor.audit=noquiet on the kernel command line (apparmor.pod:222-235). The modes are normal, quiet_denied, quiet.allowed, quiet, noquiet and all (audit.c:20-27); noquiet and all ignore the quiet marks (file.c:143-146).deny in force in complain mode is the quiet mark.deny hides probing. The refused request returns EACCES and leaves no record, so a confined program that probes a denied path is not visible in the log (file.c:143-149; read from the kernel source, not observed on a running kernel). Shipped profiles use plain deny to silence noise; the absence of DENIED records is not evidence that nothing was attempted. audit deny, or the kernel audit mode noquiet, brings the records back.deny still refuses, silently, because the quiet bits are removed from the request before the complain decision; an audit deny in complain mode is permitted and logged as ALLOWED (derived from the same code, not run; see audit).-O filter-deny the deny field written for the kernel is 0, and a denial is a bit missing from allow plus a bit in quiet (run with the parser built from the AppArmor tree at 836052d21, nothing loaded into a kernel, -D compressed-dfa; hfa.h:132-138). The kernel's test of perms->deny for the other rule classes (lib.c:430) therefore has nothing to match in policy built by this parser.priority= on an allow rule overrides a deny written without one: priority.audit deny.deny gets audit_t::IMPLIED, audit deny gets UNSPECIFIED (rule.h:426-440); IMPLIED compares equal to FORCE (rule.h:207-211), so the emitters pass the permissions as the fourth argument, which on a deny node is the quiet mask.complain |= ~(perms->allow | perms->deny) (file.c:117-118); aa_audit turns an AUDIT_APPARMOR_ALLOWED record into success with complain_error, but a fully quieted request has already returned.audit (lsm.c:1974-1976).Scores: priority*4 + 3 deny, +1 allow (parser/libapparmor_re/hfa.cc:1536-1554). apply_and_clear_deny and map_perms_to_accept leave allow and quiet; the packed deny field is 0.
DenyMatchFlag(priority, perms, quiet) node (expr-tree.h:1191-1197), created by the node cache next to PromptMatchFlag, ExactMatchFlag and MatchFlag (aare_rules.h:85-92).pri_update_perm (hfa.cc:1529-1554): score priority << 2, +3 deny, +2 exact match on an exec bit, +1 allow, +0 prompt. The comment notes that this is the last use of priority; it is not passed to the back end.perms.deny and perms.quiet and clears allow, audit and prompt (hfa.cc:1585-1594).DFA::apply_and_clear_deny (hfa.cc:685-693) calls the per-state function: allow &= ~deny; prompt &= ~deny; deny = 0;, with audit and quiet left as computed (hfa.h:106-130).-O filter-deny is set (aare_rules.cc:273-278). The option is on by default: { 1, "filter-deny", "filter out deny information from final dfa", CONTROL_DFA_FILTER_DENY } (common_optarg.c:104-105), default flags at parser_common.c:123-129.map_perms_to_accept emits accept1 = allow, accept2 = PACK_AUDIT_CTL(audit, quiet), accept3 = prompt (hfa.h:132-138); compute_perms_table_ent builds the permission table entries from those three words (hfa.cc:1406-1421, builders at policy_compat.cc:160-244). None of them sets deny.deny field, written by sd_serialize_perm (parser_interface.c:346-350); with this parser its value is 0.u32 deny; /* explicit deny, or conflict if allow also set */ (perms.h:69-71), denied = request & (~perms->allow | perms->deny) (lib.c:430), and complain mode excludes it (lib.c:369-370).-D dfa-states-initial for /a rw, with deny /a w, prints (0x 10004/2800a//0/0/2800a); -D dfa-states-post-filter prints (0x 10004/0//0/0/2800a). The header line of the dump reads (allow/deny/prompt/audit/quiet).caps.allow & ~caps.deny, quiet is caps.deny & caps.quiet (parser_interface.c:549-558).audit deny, not deny audit. In deny rules write a bare x. A higher-priority allow overrides a deny.
-Q -K --skip-kernel-load --warn=all, nothing loaded into a kernel). The full form is AppArmor parser error for FILE in profile FILE at line N: MESSAGE.deny audit /etc/demo/** w,: syntax error, unexpected TOK_AUDIT, expecting TOK_ID or TOK_MODE or TOK_SET_VAR. Write audit deny.deny /usr/bin/demo-helper Px,: Invalid perms, in deny rules 'x' must not be preceded by exec qualifier 'i', 'p', or 'u'. Write deny /usr/bin/demo-helper x,.deny { allow /etc/demo/** r, }: conflicting mode prefix.priority=10 allow /etc/demo/override.conf r, with deny /etc/demo/** r,: override.conf is readable, the other names are refused and quiet.echo -n noquiet > /sys/module/apparmor/parameters/audit makes the kernel log refusals that deny rules keep quiet (apparmor.pod:222-235). Deny rules also arrive through include lines, for example from abstractions.priority= has no effect on capability rules, so a deny capability rule cannot be overridden that way.opt_prefix production (parser_yacc.y:705-711), which is why deny audit fails in the grammar.check_x_qualifier holds the exec message (parser_misc.c:1090-1102).conflicting mode prefix: rule.h:409-416 and parser_misc.c:1111-1118.override.conf, -D dfa-states-initial: (0x 10004/0//0/0/0); the priority 10 allow scores 41 against 3 for the deny (hfa.cc:1536-1554).AA_LINK_BITS and AA_CHANGE_PROFILE (parser_regex.c:674-683).Next: syn-audit (log a denial), syn-priority (override a deny), syn-qualifier-blocks (deny a group of rules).
allow is the default access type; allow rules that match the same name add up.deny removes the permissions it names from allow rules of the same or lower priority, and the refusal is not logged.audit deny logs the refusal; a higher priority= on an allow rule overrides a deny.deny also refuses silently in complain mode.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the fragment (-Q -K --skip-kernel-load --warn=all), with nothing loaded into a kernel; "code" means the parser or kernel source was read, not run. Nothing here was observed on a running kernel. Kernel statements are for mainline Linux 7.4.
QUALIFIERS: [priority=N] [audit] [allow|deny|prompt] [owner|other] RULE LINE: [QUALIFIERS] RULE ,
allow, deny, prompt. With nothing written the rule is an allow rule (code).file and before the keyword of any other rule class: deny file /a w,, deny capability chown,.audit deny is the only way to combine the two words; deny audit is rejected (tree).| Keyword | Meaning |
|---|---|
allow | The default access type, spelled out. allow RULE, grants what RULE, grants. The explicit word conflicts with a surrounding deny { } or prompt { } block; a rule with no access type takes the block's. |
deny | Removes the named permissions from what allow rules of the same or lower priority grant. Grants nothing. Without audit it also marks the permissions quiet, so the refusal is not logged. audit deny logs it: syn-audit. |
prompt | The third access type: syn-prompt. |
Allow rules of the same priority that match the same name add up their permissions (code).
The decision is made for one permission of one name at a time, not rule against rule. The order of the rules in the file has no effect. Scoring: syn-priority.
| Rules | Result | Basis |
|---|---|---|
/a rw, and deny /a w, | read allowed; write and append refused and quiet | tree |
/etc/demo/** r, and deny /etc/demo/secret.key r, | the key is refused and quiet; other names readable | tree |
priority=1 /a rw, and deny /a w, | read and write allowed; nothing quiet | tree |
priority=10 allow /etc/demo/override.conf r, and deny /etc/demo/** r, | override.conf readable; other names refused and quiet | tree |
priority=1 /a rw, and priority=1 deny /a w, | as the first row: at equal priority the deny wins | tree |
/a* rw, and priority=-1 deny /** w, | names matching /a* keep read and write; elsewhere write is refused and quiet | tree |
Kernel side, from the source of mainline Linux 7.4 (code); none of it was run.
| Cause | Enforce mode | Complain mode |
|---|---|---|
| no rule allows the request | EACCES and a DENIED record | allowed, with an ALLOWED record |
deny rule | EACCES, no record | EACCES, no record |
audit deny rule | see syn-audit | see syn-audit |
deny follows from the quiet bit: the kernel removes quieted bits from the request before logging, and returns the error when nothing is left (linux:security/apparmor/file.c:143-149 for files, lib.c:440-447 for other classes, capability.c:87-92 for capabilities).noquiet and all ignore the quiet masks, so quieted denials are logged (/sys/module/apparmor/parameters/audit; linux:security/apparmor/file.c:144-145). Reading the records: adm-denials.deny is accepted on every rule class except rlimit rules, which take no qualifier (code).allow & ~deny, quiet is deny & quiet (code). priority= has no effect on capability rules.x; there is no transition to choose (tree).| Option | Default | Effect |
|---|---|---|
-O filter-deny | on | removes the denied bits from allow and prompt and clears the deny word of each state before minimization, so states that differ only in deny can merge |
-O no-filter-deny | keeps the deny word during minimization |
With either setting the deny field written to the kernel is 0 (tree: -D compressed-dfa prints every table entry with deny 0x0; code: parser/libapparmor_re/hfa.h:132-138). A deny rule reaches the kernel as a bit missing from allow and a bit set in quiet.
A parse error is printed as AppArmor parser error for FILE in profile FILE at line N: MESSAGE (tree).
| Message | Cause |
|---|---|
syntax error, unexpected TOK_AUDIT, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | deny audit /etc/demo/** w,: write audit deny (tree) |
syntax error, unexpected TOK_ALLOW, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | deny allow /foo r,: one access type per rule (tree) |
Invalid perms, in deny rules 'x' must not be preceded by exec qualifier 'i', 'p', or 'u' | deny /usr/bin/demo-helper Px,: write a bare x (tree) |
conflicting mode prefix | a rule's explicit access type against its block's, as in deny { allow /etc/demo/** r, } (tree) |
prefix not allowed on rlimit rules | an rlimit rule inside a deny { } block (tree; parser/tst/simple_tests/rlimits/bad_rlimit_block_deny.sd) |
Known discrepancies between apparmor.d(5) at the commit above and the code:
ACCESS TYPE = ( 'allow' | 'deny' ) (parser/apparmor.d.pod:198) omits prompt; the parser accepts three words.-O filter-deny. By the code read here the parser does not emit that information with or without the option; what keeps a plain deny in force in complain mode is the quiet mask.| Step | Where |
|---|---|
grammar: opt_rule_mode is empty, TOK_ALLOW, TOK_DENY or TOK_PROMPT | parser/parser_yacc.y:700-703; seat order 705-711 |
| keywords | parser/parser_misc.c:100-101 |
field prefixes.rule_mode | parser/rule.h:244 |
prefix_rule_t::add_prefix (rule classes): conflict check, IMPLIED for deny, UNSPECIFIED for audit deny | parser/rule.h:409-440 |
generic_add_prefix (file and change_profile entries) | parser/parser_misc.c:1111-1142 |
audit_t::IMPLIED compares equal to FORCE | parser/rule.h:207-211 |
MatchFlag, ExactMatchFlag, DenyMatchFlag | parser/libapparmor_re/aare_rules.h:85-92, expr-tree.h:1191-1197 |
pri_update_perm: score priority*4 + 3 deny, 2 exact exec, 1 allow, 0 prompt | parser/libapparmor_re/hfa.cc:1529-1653 |
apply_and_clear_deny | parser/libapparmor_re/hfa.cc:685-693, hfa.h:106-127; called from aare_rules.cc:273-278 |
map_perms_to_accept | parser/libapparmor_re/hfa.h:132-138 |
permission table builders, which do not set deny | parser/libapparmor_re/policy_compat.cc:160-246 |
packed deny field | parser/parser_interface.c:350 |
aa_check_perms (Linux 7.4) | linux:security/apparmor/lib.c:430-447 |
aa_audit_file (Linux 7.4) | linux:security/apparmor/file.c:143-153 |
Dump format (-D dfa-states-initial): (allow/deny//prompt/audit/quiet) in hex. The doubled / is a known defect of the dump. Bits per half: x 0x1, w 0x2, r 0x4, a 0x8; the other half is shifted left by 14, so r for both halves is 0x10004, w (which implies a) is 0x2800a and rw is 0x3800e.
| Rules | State | Basis |
|---|---|---|
/a rw, deny /a w, | (0x 10004/2800a//0/0/2800a), after filter-deny (0x 10004/0//0/0/2800a) | tree |
/etc/demo/** r, deny /etc/demo/secret.key r,, state for the key | (0x 0/10004//0/0/10004) | tree |
priority=1 /a rw, deny /a w, | (0x 3800e/0//0/0/0) | tree |
priority=10 allow /etc/demo/override.conf r, deny /etc/demo/** r,, state for override.conf | (0x 10004/0//0/0/0) | tree |
audit RULE, logs each access the rule permits, as an apparmor="AUDIT" record. It does not change the decision. (The kernel, read from the source.)
audit in front of a rule, as in audit /etc/demo/tls/key.pem r,.audit, an allowed access produces no record: the kernel keeps only the requested permissions that are in the profile's audit set, and returns without logging when none are left (file.c:119-130 for files, lib.c:432-438 for the other rule classes).AUDIT, written as apparmor="AUDIT" (audit.c:29-30, audit.c:143-146).apparmor="AUDIT" operation="getattr" class="file" profile="/usr/sbin/mosquitto" name="/etc/mosquitto/pwfile" pid=8119 comm="mosquitto" requested_mask="r" fsuid=122 ouid=122. An AUDIT record has requested_mask and no denied_mask.demo, its key file and its profile are invented for the map. Nothing on this slide was observed on a running kernel; the kernel behaviour is stated from the kernel source.audit (parser_yacc.y:693-694); the keyword table maps the word at parser_misc.c:99.[priority=N] audit [allow|deny|prompt] [owner|other] RULE,. audit works on file, capability, signal, network and most other rules, and on blocks. The order of the qualifiers is fixed.
[priority=N] [audit] [allow|deny|prompt] [owner|other] RULE,. The order is fixed.audit { RULES } applies the qualifier to every rule inside. Example from the parser's tests: entry_mods_audit_ok1.sd.-Q -K --skip-kernel-load --warn=all, nothing loaded into a kernel):deny audit /foo r, is rejected: syntax error, unexpected TOK_AUDIT, expecting TOK_ID or TOK_MODE or TOK_SET_VAR.audit priority=1 /foo r, is rejected: syntax error, unexpected TOK_PRIORITY, expecting TOK_ID or TOK_MODE or TOK_SET_VAR.AppArmor parser error for FILE in profile FILE at line N: MESSAGE.set rlimit rules take no qualifier at all, also not through a block; the message is prefix not allowed on rlimit rules (parser.h:171-178, bad_rlimit_block_audit.sd). This is from the parser source and its test file.@{HOME} is defined in tunables/home, which tunables/global includes.opt_prefix production (parser_yacc.y:705-711); the audit seat is opt_audit_flag (parser_yacc.y:693-694).An audit allow rule logs uses of the permissions it names, in enforce and in complain mode. Permissions granted by other rules are not logged. This is read from the kernel source of the kernel, not observed on a running kernel.
audit rule are logged. The parser built from the AppArmor tree at 836052d21 compiles audit /a r, to a state with allow 0x10004 and audit 0x10004; a rule without audit leaves the audit set empty.read() or write().requested_mask holds the audited permissions only. Opening the file read-write with the rules on the slide gives requested_mask="w".r and w cover.audit: entry->audit == audit_t::FORCE ? entry->perms : 0 (parser_regex.c:685-688).allowed_caps & caps.audit (block_rules.cc:143-152, parser_interface.c:551).deny RULE, refuses silently. audit deny RULE, refuses and logs apparmor="DENIED". The program sees EACCES in both cases. (The kernel, read from the source.)
deny /c r, compiles to a state whose quiet set equals the denied permissions; audit deny /b r, compiles to the same denial with an empty quiet set.EACCES with or without audit.requested_mask and denied_mask, then fsuid= and ouid=.audit deny @{HOME}/.ssh/** rw,. The example profile carries flags=(complain, ...). In complain mode this rule is logged as ALLOWED and not refused (next scene); the slide shows it as it behaves in an enforce-mode profile.noquiet (/sys/module/apparmor/parameters/audit); the quiet sets are then ignored (file.c:143-146, lib.c:374-380).deny leaves no record: a confined program that probes a denied path is not visible in the log unless the rule is audit deny or the kernel's audit mode is noquiet or all. Shipped profiles use plain deny to silence noise, so the absence of DENIED records is not evidence that nothing was attempted.quiet suppresses all records, including those asked for by audit rules (audit.c:216-219).In complain mode: audit allow logs AUDIT; plain deny still refuses without a record; audit deny is logged as ALLOWED and permitted. The last two are derived from the kernel source of the kernel and were not tested on a running kernel.
All statements here are read from the kernel source of the kernel. Rows 3 and 4 of the slide are derived from that code and were not tested on a running kernel.
audit allow (row 2): the request is allowed, so the audited permissions are logged as AUDIT; the profile mode plays no part (file.c:119-130).deny (row 3): the denied permissions are in the quiet set. The kernel removes them from the request, nothing is left, and it returns the error before the complain-mode conversion is reached (file.c:143-149). Result: EACCES, no record.audit deny (row 4): the denied permissions are not allowed and not quieted. The request is handled like row 1: logged as ALLOWED and permitted.audit deny rules gives a log that says ALLOWED for the accesses its author meant to forbid. Treat audit deny in a complain-mode profile as detection only.aa_audit_file (file.c:95-154), aa_audit (audit.c:200-236), complain_error (audit.h:206-211).aa_check_perms the same order applies: quiet bits are removed first and the function returns when none are left (lib.c:440-447); otherwise aa_select_audit_type picks ALLOWED when all denied bits are in complain (audit.c:143-151).audit → audit mask; plain deny → quiet mask; audit deny → neither (parser/rule.h:426-440). aa_audit_file (linux:security/apparmor/file.c:95-154, the kernel) applies them.
audit_t has the values UNSPECIFIED, FORCE and IMPLIED; internal_audit_t::operator== makes IMPLIED compare equal to FORCE (rule.h:195-232).add_rule is the quiet mask, for the others the audit mask (parser_regex.c:675-688).-D rule-exprs -D dfa-states-initial). Format (allow/deny//prompt/audit/quiet); r for the owner and other halves together is 0x10004.pri_update_perm: a deny node sets deny and quiet and clears allow and audit for its bits (hfa.cc:1589-1593); allow and prompt nodes add their audit bits (hfa.cc:1639, hfa.cc:1650).PACK_AUDIT_CTL(audit, quiet) (immunix.h:126-127); in a permission table entry the audit and quiet words are written at parser_interface.c:356-357.aa_audit_file (file.c:95-154); aa_check_perms for the other classes (lib.c:425-464); aa_select_audit_type (audit.c:143-151); aa_audit (audit.c:200-236).all sets audit to every permission, noquiet clears quiet (lib.c:374-380).audit deny and priority=N audit are the valid orders. A higher-priority rule without audit removes the audit of lower rules for the permissions it grants. The rule qualifier, the profile flag audit and the kernel's audit mode are three separate switches.
deny audit /foo r,: syntax error, unexpected TOK_AUDIT, expecting TOK_ID or TOK_MODE or TOK_SET_VAR.audit priority=1 /foo r,: syntax error, unexpected TOK_PRIORITY, expecting TOK_ID or TOK_MODE or TOK_SET_VAR.priority=1 /a r, audit /a rw, compiles to a state where read and write are allowed and only write and append are audited. Audit is decided per permission together with allow, and the priority 1 rule wins the read permission.audit (this deck);flags=(audit) (profile.h:221-222), covered in other profile flags;/sys/module/apparmor/parameters/audit, with the values normal, quiet_denied, quiet, noquiet, all and one more for quieting allowed accesses (audit.c:20-27, the kernel). When it is not normal it replaces the profile's own setting (policy.h:459-465).conflicting audit prefix is a message in the parser source. audit { audit /a r, } and audit { audit deny /a r, } are accepted by the tree's parser, and no input that produces the message was found.deny { } block around an audit deny rule loses the audit. Observed with the parser built from the tree for file, signal and ptrace rules; see the reference below.Next: syn-allow-deny, syn-priority, syn-qualifier-blocks, adm-denials (reading the records), k-audit (how they are produced), syn-flags-modes (complain mode).
audit on an allow rule: an AUDIT record for each use of the permissions the rule names.audit deny: the refusal of a deny rule with its DENIED record restored.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the fragment (-Q -K --skip-kernel-load --warn=all), with nothing loaded into a kernel; "code" means the parser source or the kernel source of mainline Linux 7.4 was read, not run; "derived" means the result was reasoned from that code. Nothing here was observed on a running kernel.
RULE: [priority=N] audit [allow|deny|prompt] [owner|other] RULE ,
BLOCK: audit [allow|deny|prompt] [owner|other] { RULES }
audit is the second qualifier: after priority=N, before the access type (code).set rlimit rules take no qualifier: prefix not allowed on rlimit rules (code).audit deny is the only way to combine the two words; deny audit is a syntax error (tree).audit /foo rw,, audit rw /bar,, audit { /one rw, } (parser/tst/simple_tests/profile/entry_mods_audit_ok1.sd), audit other /tmp/** rw, (parser/tst/simple_tests/file/ok_other_3.sd).| Rule for the request | Enforce mode | Complain mode |
|---|---|---|
audit allow rule | allowed, apparmor="AUDIT" | allowed, apparmor="AUDIT" |
allow rule without audit | allowed, no record | allowed, no record |
| no rule | refused, apparmor="DENIED" | allowed, apparmor="ALLOWED" |
deny rule | refused, no record | refused, no record (derived) |
audit deny rule | refused, apparmor="DENIED" | allowed, apparmor="ALLOWED" (derived) |
audit rule are logged. Permissions that other rules grant on the same path are not.An AUDIT record (from libraries/libapparmor/testsuite/test_multi/testcase36.in):
apparmor="AUDIT" operation="getattr" class="file" profile="/usr/sbin/mosquitto" name="/etc/mosquitto/pwfile" pid=8119 comm="mosquitto" requested_mask="r" fsuid=122 ouid=122
A DENIED record, as produced for an audit deny rule (shape of the kernel's file records, values invented):
apparmor="DENIED" operation="open" class="file" profile="demo" name="/home/user/.ssh/id_rsa" pid=4242 comm="demo" requested_mask="r" denied_mask="r" fsuid=1000 ouid=1000
requested_mask and no denied_mask. requested_mask holds the audited permissions only.fsuid= is the task's filesystem uid, ouid= the owner of the object.priority=1 /a r, audit /a rw, allows read and write and audits only write and append (tree). See syn-priority.audit on a change_profile rule is accepted and has no effect at this commit: the rule is compiled without an audit mask (code: parser/parser_regex.c:765-773). With --warn=rule-downgraded or --warn=all the parser prints Warning kernel does not support audit modifier for change_profile rule.; by default it prints nothing (tree).flags=(audit) is a switch for a whole profile: syn-flags-other./sys/module/apparmor/parameters/audit applies to every profile and, when it is not normal, replaces the profile's own setting. all audits every access, noquiet shows the denials that deny rules quiet, quiet suppresses all records (code, mainline Linux 7.4). Changing it needs policy administration rights.audit rule reports only the accesses that rule covers. Everything else that is allowed stays unlogged.deny leaves no record in either mode. A missing DENIED record does not show that nothing was attempted.audit deny rule does not refuse (derived).quiet, rules with audit produce no records (code).The full form of a parser error is AppArmor parser error for FILE in profile FILE at line N: MESSAGE (tree). The table gives MESSAGE.
| Message | Example | When |
|---|---|---|
| syntax error, unexpected TOK_AUDIT, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | deny audit /foo r, | audit after the access type (tree) |
| syntax error, unexpected TOK_PRIORITY, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | audit priority=1 /foo r, | priority=N after audit (tree) |
| prefix not allowed on rlimit rules | audit { set rlimit nofile <= 1024, } | any qualifier on an rlimit rule (tree, and the parser's test rlimits/bad_rlimit_block_audit.sd) |
| conflicting audit prefix | none found | present in the parser source; audit { audit /a r, } and audit { audit deny /a r, } are accepted (tree) and no input producing the message was found |
| Warning kernel does not support audit modifier for change_profile rule. | audit change_profile -> x, | a warning of the class rule-downgraded, printed whatever the kernel supports; off by default (tree) |
These are differences between the documentation and the behaviour, listed as such. They are not taught as intended behaviour.
deny { audit deny RULE, } and deny { deny { audit RULE, } } compile as a quiet deny: the audit is lost. Observed with the tree's parser for file, signal and ptrace rules. The manual page says a deny applied to a rule that carries audit results in an audited denial. Capability rules keep the audited denial (tree).parser/apparmor.d.pod, lines 608-616) does not match the kernel code read for the table above: by that code a plain deny is kept in force by its quiet marking, and an audit deny is not kept in force.| What | Where |
|---|---|
opt_audit_flag, opt_prefix | parser_yacc.y:693-694, parser_yacc.y:705-711 |
keyword audit | parser_misc.c:99 |
internal_audit_t, audit_t values (IMPLIED equals FORCE) | rule.h:195-232 |
prefix_rule_t::add_prefix (rule objects) | rule.h:397-440 |
generic_add_prefix (file rules) | parser_misc.c:1121-1142 |
| file rule emitter, audit or quiet as fourth argument | parser_regex.c:675-688 |
audit change_profile warning | parser_regex.c:725-730 |
| capability sets | block_rules.cc:143-152, parser_interface.c:549-552 |
pri_update_perm | hfa.cc:1589-1593, hfa.cc:1639, hfa.cc:1650 |
PACK_AUDIT_CTL | immunix.h:126-127 |
| audit and quiet words of a permission entry | parser_interface.c:356-357 |
aa_audit_file | file.c:95-154 |
aa_file_perm (cached checks on open files) | file.c:626-660 |
aa_check_perms | lib.c:425-464 |
| audit mode applied to the masks | lib.c:374-390 |
aa_select_audit_type, aa_audit | audit.c:143-151, audit.c:200-236 |
complain_error | audit.h:206-211 |
audit mode names, AUDIT_MODE() | audit.c:20-27, policy.h:459-465 |
| capability audit cache | capability.c:67-110 |
State dumps (-D rule-exprs -D dfa-states-initial), format (allow/deny//prompt/audit/quiet). Per half x 0x1, w 0x2, r 0x4, a 0x8; the other half is shifted left by 14, so r for both halves is 0x10004, w with its implied append is 0x2800a and rw is 0x3800e.
| Rules | State | Basis |
|---|---|---|
audit /a r, | (0x 10004/0//0/10004/0) | tree |
audit deny /b r, | (0x 0/10004//0/0/0) | tree |
deny /c r, | (0x 0/10004//0/0/10004) | tree |
priority=1 /a r, audit /a rw, | (0x 3800e/0//0/2800a/0) | tree |
priority=-1 /a r, deny /a r, priority=5 audit /a r, | (0x 10004/0//0/10004/0) | tree |
if EXPR { rules } compiles the rules in only when the expression is true at compile time.
if ${DEMO_DEBUG} { /tmp/demo-debug.log w, }. The panel shows a shortened profile; the counts are those of the whole example file.-D rule-exprs that begin aare:: 106 with ${DEMO_DEBUG} = false, 107 with true. They are compiled lines, not rules of the file: two are the attachment and its alias twin, three are peer labels (aare: demo) from abstractions/base, 17 are alias twins, and the rest are the rules of the file and of the included abstraction. The extra line is aare: /tmp/demo-debug.log. Both were run with the tree's parser for this deck.if (grep of profiles/). The parser's tests have 67 files in parser/tst/simple_tests/conditional/.demo and its profile are invented for the map. Nothing on this slide was observed on a running kernel.if EXPR { } else if EXPR { } else { }. The first true branch is compiled; the others are left out.
IF_BLOCK = 'if' EXPR BLOCK [ ( 'else' 'if' EXPR BLOCK )* ] [ 'else' BLOCK ] (apparmor.d.pod:188).profile demo /usr/bin/demo { }. Of the chain only /ver9 is compiled. The profile changed: this is not the district's example file.if true { /first r, } else if true { /second r, } else { /third r, } compiles only /first.^hat { if true { /inhat r, } } compiles /inhat); inside and around a qualifier block (deny { if true { /x r, } } gives a deny rule; if true { audit { /y r, } }); nested (if true { if false { /n r, } else { /z r, } } gives /z only).cond_rule: TOK_IF expr block | TOK_IF expr block TOK_ELSE block | TOK_IF expr block TOK_ELSE cond_rule (parser_yacc.y:862-899).rules: rules cond_rule (parser_yacc.y:845-850).if and else are keywords (parser_misc.c:87-88).Factors: ${VAR}, true, false, defined @{VAR}, a comparison, ( ). Operators: not, then and, then or.
-D rule-exprs. In the fourth, @{SET} is assigned in the preamble and @{NOPE} is not.defined @{HOME} and @{VER} >= 9 on the chips are forms, not runs.not binds tightest, then and, then or. or and and are left associative.true or false, in any case: if TRUE { /upper r, } is compiled (recorded in the research notes).defined tests existence, not truth. A variable assigned "" is defined (defined_1.sd, expected to pass); if not not defined @FOO { } (defined_2.sd, expected to pass).if $FOO and (($BAR and $THREE)) { } (ok_16.sd) and if (($FOO and $BAR) or $THREE) { } (ok_20.sd), both expected to pass.in first and not, and, or last (apparmor.d.pod:2909-2964). The deck follows the grammar.defined ${bool} is false for a defined boolean, and and/or and nested if do not short-circuit.expr: expr TOK_OR term | term; term: term TOK_AND notfactor | notfactor; notfactor: TOK_NOT notfactor | factor (parser_yacc.y:902-964).defined: parser_yacc.y:945-959, cond_expr.cc:49-56.==, !=, in: sets of text. <, <=, >, >=: numbers if both sides are single integers, text if neither is.
@{SET} = /a /b, @{ONE} = /a and @{VER} = 10 in the preamble. "true" means the rule of the block appears in -D rule-exprs. The profile changed: this is not the district's example file.@{ONE} in @{SET} true; /a in /a/b false (no substring match); "a b" == "a b" true; @{SET} == @{SET} true.AppArmor parser error for /work/c3.sd in profile /work/c3.sd at line 3: Can only compare numbers with numbers, exit status 1.@{SET} = 1 2 and if @{SET} > 0 (recorded in the research notes).Error retrieving variable @{NOPE} (recorded in the research notes).Value out of valid range.@{TEST_VERSION} >= @{BAZ} (apparmor.d.pod:2981-2998).if read numbers in base 0 while == and != compare text. Recorded in the research notes: 0x10 >= 16 and 010 <= 8 are true, 0x10 == 16 is false, and 08 < 9 is Can only compare numbers with numbers.factor: id_or_var OP id_or_var (parser_yacc.y:966-1038).get_set, str_set_to_long with strtol(text, &end, 0), and std::includes for in (cond_expr.cc:70-161).A branch that is not taken is parsed and its includes are followed. Its rules, hats, child profiles and variables are not used.
profile demo /usr/bin/demo next to the rule /etc/demo/** r,: -D rule-exprs prints the attachment and /etc/demo/** only, -N prints only demo, exit status 0, no message. /srv/x is an invented path.-N prints only demo, the compiled profile contains none of the names, and the only file rule is the one outside the block.if false { /x/@{UNDEFINED} r, } compiles, exit status 0.bogus_keyword foo, in it prints syntax error, unexpected TOK_ID, expecting TOK_MODE, exit status 1; if false { include <does/not/exist> } prints Could not open 'does/not/exist', exit status 1.Multiple definitions for profile dupehat exist,bailing out. (recorded in the research notes; bad_dup_hats_1.sd, expected to fail).if defined @{VAR} { include <x> } does not make the include optional. include if exists does: see include if exists.if or qualifier block makes the same include in the rest of the profile a no-op..d directories.-D rule-exprs does.block::add_cond_set registers hats and merges capability, rlimit and network data for the taken block only (block.cc:175-184).parser_yacc.y:862-1038 builds the chain; cond_expr.h:63-95 keeps the taken block; block.cc walks only it.
if puts the scanner into EXPR_MODE (parser_lex.l:902-904) until { (parser_lex.l:725-769).else the parser builds a condition with the negated result (parser_yacc.y:876-879).cond_expr holds its result and its block; a cond_expr_set is one whole chain and remembers the block of the first true condition (set_block, cond_expr.h:63-95).block::add_cond_set adds the chain to the enclosing block (block.cc:175-184).set_block: variable expansion, rule post-processing, implied rules and code generation (block.cc:227-257, block.cc:285-293, block.cc:312-329, block.cc:85-109).and and or and in branches that are not taken.defined ${bool} is false for a defined boolean, and and/or and nested if do not short-circuit.if only inside a profile, always with braces. A condition is a boolean, a comparison or defined.
${DEMO_DEBUG} = false on line 1 and if ${DEMO_DEBUG} { /tmp/demo-debug.log w, } on line 2, above the profile, print ... at line 2: syntax error, unexpected TOK_IF, expecting end of file.AppArmor parser error for /work/c6.sd in profile /work/c6.sd at line 2: Unset boolean variable ${NOPE} used in if-expression. Row 3 has @{V} = 9 in the preamble.else followed by } is syntax error, unexpected TOK_CLOSE, expecting TOK_OPEN or TOK_IF.if (bad_1.sd), if truish { } (bad_id.sd), else ^FOO { } (else_if_8.sd), all expected to fail.defined ... and does not avoid the "Error retrieving variable" error: both sides of and are evaluated. See the entry named in the scene "Evaluated while parsing, chosen once, skipped later".if blocks are decided at compile time. Rule conditionals such as peer= are checked by the kernel.
if EXPR { rules }, with any number of else if EXPR { } branches and at most one else { }. The first true branch is compiled.true, false, defined, comparisons and parentheses, combined with not, and, or.deny { }) have no condition. Rule conditionals (peer=, fstype=) are part of one rule and belong to the compiled profile; conditional blocks do not.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run on the fragment (-Q -K --skip-kernel-load -D rule-exprs unless another option is named, with the tree's abi/5.0 as kernel feature set), with nothing loaded into a kernel; "code" means the parser source was read and not run; "derived" means the result was reasoned from that code. Nothing here was observed on a running kernel.
IF_BLOCK = 'if' EXPR BLOCK [ ( 'else' 'if' EXPR BLOCK )* ] [ 'else' BLOCK ]
BLOCK is rules in braces. There is no comma after the closing brace.| Where | Allowed | Basis |
|---|---|---|
| in a profile body | yes | tree |
in a hat: ^hat { if true { /inhat r, } } | yes | tree |
| in a child profile | yes | code |
inside a qualifier block: deny { if true { /x r, } } | yes; the rule is a deny rule | tree |
around a qualifier block: if true { audit { /y r, } } | yes | tree |
nested: if true { if false { /n r, } else { /z r, } } | yes; /z only | tree |
| in the preamble | no: syntax error, unexpected TOK_IF, expecting end of file | tree |
| around a part of a rule | no | the parser's tests bad_2.sd, bad_3.sd |
expr: expr or term | term
term: term and notfactor | notfactor
notfactor: not notfactor | factor
factor: ${NAME} | true | false | defined VARIABLE | OPERAND OP OPERAND | ( expr )
OPERAND: a word | "a quoted string" | @{NAME}
OP: == != in > >= < <=
not binds tightest, then and, then or; and and or are left associative (code).if true or false and false is true; if not true or true is true; if not (true or true) is false (tree).true or false, in any case: if TRUE { } is taken (tree).| Operator | Operands | Rule | Recorded example | Basis |
|---|---|---|---|---|
== | sets of text | the two sets are equal | @{SET} == /a false with @{SET} = /a /b; "a b" == "a b" true; @{SET} == @{SET} true | tree |
!= | sets of text | the two sets differ | @{SET} != /a true | tree |
in | sets of text | every value on the left is among those on the right; whole values | /a in @{SET} true; @{ONE} in @{SET} true; @{SET} in @{ONE} false; /a in /a/b false | tree |
< <= > >= | two single whole numbers | compared as numbers | 9 < 10 true; 10 > 9 true | tree |
< <= > >= | neither is a number | compared as text | abc < abd true; b10 > b9 false | tree |
< <= > >= | one number, one not | Can only compare numbers with numbers | @{VER} > abc with @{VER} = 10; @{SET} > 0 with @{SET} = 1 2 | tree |
Error retrieving variable @{NOPE} (tree).defined @{NAME} is true when a set variable of that name exists (tree: if defined @{SET} and not defined @{NOPE} is taken)."" is defined (the parser's test defined_1.sd).${D} = defined @{NOPE} gives $D = false (tree, -D variables).defined ${NAME} see the known discrepancies.| What | Result | Run |
|---|---|---|
| file rules, exec rules, network rules, change_profile rules | left out | if false { } around them: the only file rule compiled is the one outside (tree) |
| capabilities and rlimits | left out | the same run |
| hats and child profiles | left out | the same run: -N prints only demo |
| variables | not expanded | if false { /x/@{UNDEFINED} r, }: exit status 0 (tree) |
| the syntax check | still happens | bogus_keyword foo, in the block: syntax error, unexpected TOK_ID, expecting TOK_MODE, exit status 1 (tree) |
| includes | still followed | if false { include <does/not/exist> }: Could not open 'does/not/exist', exit status 1 (tree) |
| alias rules | applied to every branch, without effect on the result | code |
| Message | Cause | Basis |
|---|---|---|
syntax error, unexpected TOK_IF, expecting end of file | an if in the preamble | tree |
Unset boolean variable ${NOPE} used in if-expression | a boolean that was never assigned | tree |
Invalid boolean : '@{V}' is not true or false | a set variable, or a word other than true and false, as a factor | tree |
Error retrieving variable @{NOPE} | an undefined set variable in a comparison | tree |
Can only compare numbers with numbers | an ordering comparison of a number and something else | tree |
syntax error, unexpected TOK_ID, expecting TOK_OPEN or TOK_OR | no braces: if true /a r, | tree |
syntax error, unexpected TOK_ELSE, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | an else without an if | tree |
syntax error, unexpected TOK_CLOSE, expecting TOK_OPEN or TOK_IF | else followed by } | tree |
Multiple definitions for profile dupehat exist,bailing out. | a hat in a taken block that repeats a hat outside it | tree |
Value out of valid range | a number too large for the comparison | code |
in first and not, and, or last (apparmor.d.pod:2909-2964). In the grammar the comparisons are factors, and not binds before and before or. This page follows the grammar..d directories: see include if exists.-D rule-exprs prints the rules that were.EXPR_MODE (parser_lex.l:725-769, parser_lex.l:902-904); the words and, or, not, defined, in are tokens only there and in ASSIGN_EXPR_MODE (parser_lex.l:750-763).cond_rule (parser_yacc.y:862-899), expr, term, notfactor, factor (parser_yacc.y:902-1038).cond_expr and cond_expr_set (cond_expr.h:63-95); evaluation (cond_expr.cc:29-161).if or qualifier block makes the same include in the rest of the profile a no-op.if read numbers in base 0 while == and != compare text. Runs: if 0x10 >= 16 { /hexge r, } and if 010 <= 8 { /octle r, } are taken, if 0x10 == 16 { /hexeq r, } is not; if 08 < 9 { /x r, } is Can only compare numbers with numbers, exit status 1.defined ${bool} is false for a defined boolean, and and/or and nested if do not short-circuit. A defined ... and guard therefore does not avoid Error retrieving variable.${DEMO_DEBUG} = false in the preamble; if ${DEMO_DEBUG} { ... } in the profile. The value decides what is compiled.
-D rule-exprs that begin aare:: 106 with ${DEMO_DEBUG} = false, 107 with true. They are compiled lines, not rules of the file: two are the attachment and its alias twin, three are peer labels (aare: demo) from abstractions/base, 17 are alias twins, and the rest are the rules of the file and of the included abstraction. The extra line is aare: /tmp/demo-debug.log. Both were run with the tree's parser for this deck.-D variables prints the switch as $DEMO_DEBUG = false.profiles/apparmor.d).${NAME} = true or false, any case, in the preamble. $NAME without braces is the same variable.
${NAME} or $NAME. The name follows the rule for set variables: a letter, then letters, digits and underscores.true or false, in any mix of case, or from an expression. The line ends the assignment.-D variables prints $VAR = true, $BOOLEAN = false, $HO_HUM = true, exit status 0.BOOL_VAR = '${' ALPHA [ ( ALPHANUMERIC | '_' ) ... ] '}' and one line of prose (apparmor.d.pod:110-114, apparmor.d.pod:2445-2451).=, ?= and :=: see variable assignment. += is refused.BOOL_VARIABLE $(\{VARIABLE_NAME\}|VARIABLE_NAME) (parser_lex.l:299).varassign: TOK_BOOL_VAR assign_op expr (parser_yacc.y:550-570).str_to_boolean compares without regard to case (parser_misc.c:538-547).A boolean variable is used only in the expression of an if. In a path, $NAME is literal text.
${DEMO_DEBUG} = false, if not ${DEMO_DEBUG} { /etc/demo/** r, } and if ${DEMO_DEBUG} { /tmp/demo-debug.log w, }, the dump of -D rule-exprs has /etc/demo/** and not the log file; exit status 0./y/$B r, compiles as the literal /y/$B (recorded in the research notes)./tmp/${DEMO_DEBUG} r, was run with the tree's parser for this deck. It prints three lines: Regex grouping error: Invalid number of items between {}, Unable to parse input line '/tmp/${DEMO_DEBUG}', ERROR processing regexs for profile demo, failed to load. The exit status is 255: the failure is in the compile stage, not in the syntax stage.${FOO} is text too (vars_assignment_reference_1.sd, expected to pass).@{V} = 9 and if @{V} { } is Invalid boolean : '@{V}' is not true or false (recorded in the research notes).TOK_BOOL_VAR in factor (parser_yacc.y:937-943, parser_yacc.y:953-959).get_boolean_var (cond_expr.cc:43-48).${B} = ${A} and not false, ${C} = 3 > 2, ${D} = defined @{NOPE}: evaluated at once, stored as true or false.
-D variables prints $B = true, $D = false, $C = true, $A = true, in the dump's own order; the slide orders the rows by line.if: boolean variables, true, false, not, and, or, parentheses, comparisons and defined. The operators are explained in conditional blocks.${EARLY} = ${LATER} on line 1 and ${LATER} = true on line 2 print AppArmor parser error for /work/b-order.sd in profile /work/b-order.sd at line 1: Unset boolean variable ${LATER} used in if-expression, exit status 1. The message says "if-expression" although the line is an assignment.defined ${bool} is false for a defined boolean, and and/or and nested if do not short-circuit.ASSIGN_EXPR_START and ASSIGN_EXPR_MODE (parser_lex.l:706-711, parser_lex.l:728-749, parser_lex.l:771-779).add_var(name, boolean) (parser_yacc.y:555-563).A boolean is set in the preamble or in a file it includes. There is no command-line switch; a change needs a recompile.
tunables/demo.d is an invented directory and no shipped profile works this way. It was run with the tree's parser for this deck: ${DEMO_DEBUG} = false, then include if exists <tunables/demo.d>, with the directory found through -I and holding one file site.local with the line ${DEMO_DEBUG} := true. -D variables prints $DEMO_DEBUG = true, -D rule-exprs has aare: /tmp/demo-debug.log, nothing is printed even with --warn=all, exit status 0. With ?= in place of = in the profile the result is the same (also run).${DEMO_DEBUG} = true included first and ${DEMO_DEBUG} ?= false after it, also ends with $DEMO_DEBUG = true, but prints '${DEMO_DEBUG}' is already defined on standard error (run with the tree's parser for this deck). Known discrepancy: ?= on a declared variable prints '@{NAME}' is already defined.?= keeps an existing value, := replaces, = is an error for an existing name: see variable assignment.parser/parser_main.c touches the table of variables before parsing. It was not run.${A} = true then @{A} = /a is variable @{A} was previously declared (recorded in the research notes)..d directory: see include if exists.:= in a file that is included later overrides the profile's own value.-D rule-exprs for the values that are possible.parser_lex.l:706-779 switches to expression mode; parser_yacc.y:550-570 evaluates and stores into the shared symbol table.
INITIAL, a boolean variable followed by an assignment operator pushes ASSIGN_EXPR_START (parser_lex.l:706-711); the operator switches to ASSIGN_EXPR_MODE (parser_lex.l:771-779), which ends at the end of the line (parser_lex.l:728-749).and, or, not, defined and in are tokens only in EXPR_MODE and ASSIGN_EXPR_MODE (parser_lex.l:750-763).varassign: TOK_BOOL_VAR assign_op expr (parser_yacc.y:550-570) evaluates the expression and stores the result.add_var for a boolean: symtab.cc:42-45. The lookup that refuses a set: Variable %s is not a boolean variable (symtab.cc:160-164).true and false go through str_to_boolean (cond_expr.cc:36-48).Only true or false (any case) or an expression. A misspelt name in an if is Unset boolean variable.
$VAR = beeblebrox (boolean_bad_1.sd) and $FOO=1 (boolean_bad_8.sd), both expected to fail.... at line 3: Invalid assignment += not allowed with boolean variables, for an assignment on line 2.${DEMO_DEBUG} = false in the preamble and the misspelt name in the block: ... at line 3: Unset boolean variable ${DEMO_DEBGU} used in if-expression.Regex grouping error: Invalid number of items between {}, Unable to parse input line '/tmp/${DEMO_DEBUG}', ERROR processing regexs for profile demo, failed to load.... at line 2: syntax error, unexpected TOK_BOOL_VAR, expecting TOK_ID or TOK_MODE or TOK_SET_VAR. The parser's own test is boolean_bad_5.sd (expected to fail).@{A}/x with ${A} = true) prints Variable A is not a set variable (recorded in the research notes).+= on a boolean reports that the variable was not declared. This is the set-variable form @{A} += /a on a boolean A, not the form in row 3.Onward: syn-boolean-conditionals, the blocks that test booleans.
${NAME} holds true or false. It is assigned in the preamble with =, ?= or :=, from true, false or an expression.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run on the fragment (-Q -K --skip-kernel-load, with the tree's abi/5.0 as kernel feature set and the dump option named), with nothing loaded into a kernel; "code" means the parser source was read and not run; "derived" means the result was reasoned from that code. Nothing here was observed on a running kernel.
boolean: ${NAME} | $NAME
NAME: a letter, then letters, digits and _
assignment: BOOLEAN ( = | ?= | := ) EXPRESSION up to the end of the line
EXPRESSION: true | false | a conditional expression
true and false are accepted in any mix of case: $VAR = True, ${BOOLEAN} = fALsE, $HO_HUM=TRUE (tree).= is an error if the name exists, ?= keeps an existing value, := replaces, += is refused: see variable assignment.| Place | Result | Basis |
|---|---|---|
if ${NAME} { } and any expression of an if | tested | tree |
| the right-hand side of another boolean assignment | tested | tree |
a path, without braces: /y/$B r, | the literal text /y/$B | tree |
a path, with braces: /tmp/${DEMO_DEBUG} r, | Regex grouping error: Invalid number of items between {}, exit status 255 | tree |
| the value of a set variable | text | the parser's test vars_assignment_reference_1.sd |
| Line | -D variables | Basis |
|---|---|---|
${A} = true | $A = true | tree |
${B} = ${A} and not false | $B = true | tree |
${C} = 3 > 2 | $C = true | tree |
${D} = defined @{NOPE} | $D = false | tree |
$VAR = True | $VAR = true | tree |
${BOOLEAN} = fALsE | $BOOLEAN = false | tree |
${DEMO_DEBUG} = false then ${DEMO_DEBUG} := true | $DEMO_DEBUG = true | tree |
${DEMO_DEBUG} = true then ${DEMO_DEBUG} ?= false | $DEMO_DEBUG = true | tree |
${EARLY} = ${LATER} before ${LATER} = true is Unset boolean variable ${LATER} used in if-expression (tree).${A} = true then @{A} = /a is variable @{A} was previously declared (tree).Variable A is not a set variable (tree). A set used as a boolean: Variable %s is not a boolean variable (code).parser/parser_main.c touches the table before parsing).profiles/apparmor.d).| Message | Cause | Exit | Basis |
|---|---|---|---|
Invalid boolean : 'maybe' is not true or false | a word that is not true or false | 1 | tree |
Invalid boolean : '1' is not true or false | a number | 1 | tree |
Invalid assignment += not allowed with boolean variables | += | 1 | tree |
Unset boolean variable ${NAME} used in if-expression | a name that was never assigned, in an if or in an assignment | 1 | tree |
Regex grouping error: Invalid number of items between {} | ${NAME} in a path | 255 | tree |
syntax error, unexpected TOK_BOOL_VAR, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | an assignment inside a profile | 1 | tree |
variable %s was previously declared | = on a name that exists | 1 | code |
.d directory: see include if exists.:= in a file that is included later overrides the profile's own value.-D rule-exprs prints the rules that were compiled; the profile text does not say which branch was taken.BOOL_VARIABLE (parser_lex.l:299); ASSIGN_EXPR_START and ASSIGN_EXPR_MODE (parser_lex.l:706-711, parser_lex.l:728-749, parser_lex.l:771-779).varassign: TOK_BOOL_VAR assign_op expr (parser_yacc.y:550-570).add_var for a boolean (symtab.cc:42-45); get_boolean_var and its error (symtab.cc:160-164, cond_expr.cc:43-48); str_to_boolean (parser_misc.c:538-547).defined ${bool} is false for a defined boolean, and and/or and nested if do not short-circuit.+= on a boolean reports that the variable was not declared. Run: ${A} = true then @{A} += /a prints Variable A is not a set variable and then variable @{A} was not previously declared, but is being assigned additional values.@{exec_path} mr, allows the profile's own program. The parser defines the variable from the profile head.
@{exec_path} mr, lets the confined program map (m) and read (r) the file it was started from.profile demo /usr/bin/demo { @{exec_path} mr, ... }, -D rule-exprs): the rule prints aare: /usr/bin/demo. The same text is printed once more for the attachment itself.@{exec_path} in 176 files under profiles/apparmor.d, @{profile_name} in 4 and @{attach_path} in none (counted with grep in the AppArmor tree at 836052d21)./usr/bin/demo; the kernel has no variables.PROFILE_NAME_VARIABLE, PROFILE_ATTACH_VAR, PROFILE_EXEC_VAR (parser.h:335-337).@{profile_name}, @{attach_path}, @{exec_path}: defined by the parser, separately for each profile.
@{profile_name} holds the name of the profile the rule stands in. @{attach_path} and @{exec_path} hold its attachment and have the same value.@{exec_path}: "If the kernel supports it as a kernel variable, it will be set to the specific path that matches the executable at run time" (apparmor.d.pod:2367-2371). No code implements this and the kernel tree has no such variable (searched under security/apparmor/, not run). The deck follows the code: both variables have the same value.@{profile_name}, @{attach_path} or @{exec_path} keeps the value of the first profile that uses it. Recorded in the research notes: the preamble line @{DIR} = /var/lib/@{profile_name} used in the profiles one and two compiles /var/lib/one/** in both.PROFILE_NAME_VARIABLE "profile_name", PROFILE_ATTACH_VAR "attach_path", PROFILE_EXEC_VAR "exec_path" (parser.h:335-337).@{profile_name} is demo, demo//worker and demo//admin. In a path, // becomes /.
-D rule-exprs): aare: /run/demo/**, aare: /run/demo/worker/**, aare: /run/demo/admin/**, exit status 0.demo, demo//worker, demo//admin. In a file path the // collapses to /.// stays: signal peer=@{profile_name}, in the child profile worker prints aare: demo//worker, and in demo it prints aare: demo (run with the tree's parser for this deck)./var/run/@{profile_name} rwk, (vars_auto_profile_name_01.sd, expected to pass); signal peer=@{profile_name}, and ptrace (read) peer=@{profile_name}, in base.escape_re(prof->get_name(false)) (parser_variable.c:105-135, parser_variable.c:154-157); get_name(false) leaves the namespace out (profile.h:472-477).@{exec_path} is the attachment pattern, unescaped. @{profile_name} is the name, with {}[]*? escaped.
-D rule-exprs): in the child profile profile kid /usr/bin/k*, @{exec_path} mr, prints aare: /usr/bin/k*; in /usr/bin/path[12] { }, @{exec_path} mr, prints aare: /usr/bin/path[12] and /p@{profile_name} r, prints aare: /p/usr/bin/path\[12\]./usr/bin/kate is an invented program, drawn to show the order of events. Nothing on this slide was observed on a running kernel./. Variables in the attachment are expanded first.@{attach_path} has the same value as @{exec_path}. Recorded in the research notes: in profile one /usr/bin/one, /a@{attach_path} r, prints aare: /a/usr/bin/one.profile helpers /usr/lib/demo/* { @{exec_path} mr, } prints aare: /usr/lib/demo/*.@{exec_path} mr, in a profile with a wide attachment grants map and read on every path the attachment matches, not on the binary that was executed.m this is every file a broad pattern such as /usr/bin/* covers.-D rule-exprs), not the variable.escape_re puts a backslash before each of {}[]*? (parser_variable.c:87-103); it is applied to the name only.@{exec_path} and @{attach_path} need an attachment. In a profile without one, and in a hat, they are undefined.
@{exec_path} mr, in profile demo /usr/bin/demo prints aare: /usr/bin/demo (run with the tree's parser for this deck).profile noattach { @{exec_path} mr, } prints Failed to find declaration for: @{exec_path} and ERROR expanding variables for profile noattach, failed to load, exit status 1. The parser's own test is vars_auto_attach_path_bad_1.sd (expected to fail).@{exec_path} mr, in ^admin inside profile demo /usr/bin/demo prints Failed to find declaration for: @{exec_path} and ERROR expanding variables for profile admin, failed to load, exit status 1.@{profile_name} in a hat: /run/@{profile_name}/** rw, in ^admin compiles as /run/demo/admin/** (run with the tree's parser for this deck). In a named profile without attachment it is the name, by the same code path (derived; not run for this deck)./ uses the name as its attachment: /usr/bin/demo { @{profile_name} mr, } prints aare: /usr/bin/demo (run with the tree's parser for this deck).@{profile_name} = hijack and @{exec_path} = /hijack in the preamble, the rules of profile one /usr/bin/one get one and /usr/bin/one. The scene "Set before a profile, removed after it" of this deck shows the mechanism.exec_path from the preamble is used. With @{exec_path} = /hijack in the preamble, @{exec_path} mr, in profile noattach compiles as /hijack.if (prof->attachment) (parser_variable.c:159-175).parser_variable.c:137-179 swaps the three names in and out of the symbol table around each profile.
@{profile_name} = hijack and @{exec_path} = /hijack, the profile is profile one /usr/bin/one. Its rules get the built-in values (/p/@{profile_name} r, prints aare: /p/one), and -D expanded-variables afterwards prints @profile_name = "hijack" and @exec_path = "/hijack".expanded, variable.cc:353-355).@{profile_name}, @{attach_path} or @{exec_path} keeps the value of the first profile that uses it. Recorded in the research notes: @{DIR} = /var/lib/@{profile_name} used in the profiles one and two compiles /var/lib/one/** in both..d directory, may assign them.exec_path is used (recorded in the research notes; intent not determined).@{exec_path}: the head's pattern. @{profile_name}: the name. They are the same text only for a profile named by its path.
aare: /usr/lib/demo/*, exit status 0.Failed to find declaration for: @{exec_path}, then ERROR expanding variables for profile demo-admin, failed to load, exit status 1.profile demo /usr/bin/demo: Failed to find declaration for: @{attach_path}, then ERROR expanding variables for profile admin, failed to load, exit status 1.aare: demo -> demo, exit status 0 and no message. That the rule matches no file is derived: the kernel compares absolute paths, and demo is not one.aare: /usr/bin/demo, exit status 0. With --warn=all the parser adds The use of file paths as profile names is deprecated. See man apparmor.d for more information.@{profile_name} repeats the name; @{exec_path} and @{attach_path} repeat the attachment.
@{profile_name}: the hierarchical name of the profile, with {}[]*? escaped.@{attach_path} and @{exec_path}: the attachment pattern as written, the same value in both; defined only in a profile that has an attachment.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run on the fragment (-Q -K --skip-kernel-load, with the tree's abi/5.0 as kernel feature set and the dump option named), with nothing loaded into a kernel; "code" means the parser source was read and not run; "derived" means the result was reasoned from that code. Nothing here was observed on a running kernel.
| Variable | Value | Escaping | Defined |
|---|---|---|---|
@{profile_name} | the hierarchical name of the profile, without the namespace | a backslash before each of {}[]*? | in every profile |
@{attach_path} | the attachment as written, after variable expansion; the profile name when that begins with / | none | only in a profile with an attachment |
@{exec_path} | the same value as @{attach_path} | none | only in a profile with an attachment |
| Profile | @{profile_name} | @{attach_path} and @{exec_path} | Basis |
|---|---|---|---|
profile demo /usr/bin/demo | demo | /usr/bin/demo | tree |
/usr/bin/demo { } (named by its path) | /usr/bin/demo | /usr/bin/demo | tree for the name; code for the attachment |
/usr/bin/path[12] { } | /usr/bin/path\[12\] | /usr/bin/path[12] | tree |
profile noattach { } | noattach (derived) | undefined: Failed to find declaration for: @{exec_path} | tree |
child profile worker /usr/lib/demo/worker in demo | demo//worker | /usr/lib/demo/worker | tree |
child profile kid /usr/bin/k* | one//kid in profile one | /usr/bin/k* | tree |
hat ^admin in demo | demo//admin | undefined: Failed to find declaration for: @{exec_path} | tree |
| Use | In demo | In the child worker | Basis |
|---|---|---|---|
/run/@{profile_name}/** rw, | /run/demo/** | /run/demo/worker/** | tree |
signal peer=@{profile_name}, | demo | demo//worker | tree |
// of a hierarchical name collapses to /. In a label it stays.@{exec_path} appears in 176 files under profiles/apparmor.d, @{profile_name} in 4, @{attach_path} in none (counted with grep in the tree).abstractions/base has signal peer=@{profile_name}, and ptrace (read) peer=@{profile_name},./var/run/@{profile_name} rwk, (vars_auto_profile_name_01.sd), /run/@{exec_path}/tmp rwk, (vars_auto_exec_path_03.sd), both expected to pass.@{exec_path}: "If the kernel supports it as a kernel variable, it will be set to the specific path that matches the executable at run time" (apparmor.d.pod:2367-2371).exec_path or attach_path under security/apparmor/ (code). This page follows the code.| Message | Cause | Exit | Basis |
|---|---|---|---|
Failed to find declaration for: @{exec_path} then ERROR expanding variables for profile P, failed to load | @{exec_path} in a profile without attachment or in a hat | 1 | tree |
Failed to find declaration for: @{attach_path} then the same second line | @{attach_path} in the same places | 1 | tree |
none; the rule compiles as the text demo | @{profile_name} mr, in profile demo /usr/bin/demo | 0 | tree |
@{exec_path} mr, in a profile with a wide attachment grants map and read on every path the attachment matches, not on the binary that was executed. Run: profile helpers /usr/lib/demo/* { @{exec_path} mr, } compiles the rule as /usr/lib/demo/*..d file may assign them. Inside a profile that has the built-in, the user's value is not used.exec_path is used: with @{exec_path} = /hijack in the preamble, @{exec_path} mr, in profile noattach compiles as /hijack (tree; intent not determined).process_profile_variables (parser_variable.c:137-179); the name variable (parser_variable.c:105-135, parser_variable.c:154-157); the attachment variables (parser_variable.c:159-175); escape_re (parser_variable.c:87-103).get_name(false): profile.h:472-477.@{profile_name}, @{attach_path} or @{exec_path} keeps the value of the first profile that uses it. Run: the preamble line @{DIR} = /var/lib/@{profile_name} and the rule @{DIR}/** rw, in the profiles one and two print aare: /var/lib/one/** for both; -D expanded-variables prints @DIR = "/var/lib/one"; exit status 0.@{exec_path} above).exec_path taking effect in a profile without attachment is intended.A confined task may use a capability only if it holds it and its profile lists it. capability net_bind_service, lists one.
capable; AppArmor registers apparmor_capable for it (lsm.c:199-211, registered at lsm.c:1789).EPERM (capability.c:150-154) and the kernel's capability test fails. The system call then returns what it returns for a missing capability: EACCES for bind to a low port (af_inet.c:516-520).network rule; see Network rules./sys/kernel/security/apparmor/features/caps/mask lists the capability names the kernel knows (capability.c:28-32, apparmorfs.c:2694).capability net_bind_service, is line 10 of demo's profile. The program demo and its profile are invented for the map.[QUALIFIERS] capability [NAME ...],. Names are lower case without CAP_, separated by blanks. capability, means all.
capability, with no name allows every capability. The rule all, includes every capability too (all_rule.cc:144).chown, dac_override, dac_read_search, fowner, fsetid, kill, setgid, setuid, setpcap, linux_immutable, net_bind_service, net_broadcast, net_admin, net_raw, ipc_lock, ipc_owner, sys_module, sys_rawio, sys_chroot, sys_ptrace, sys_pacct, sys_admin, sys_boot, sys_nice, sys_resource, sys_time, sys_tty_config, mknod, lease, audit_write, audit_control, setfcap, mac_override, mac_admin, syslog, wake_alarm, block_suspend, audit_read, perfmon, bpf, checkpoint_restore (base_cap_names.h:1-81).checkpoint_restore, number 40 (capability.h:421-423).capability: TOK_CAPABILITY caps TOK_END_OF_RULE returns a 64-bit mask (parser_yacc.y:1694-1716); with no name every bit is set (parser_yacc.y:1696-1698).A capability rule lets a task use a capability it already holds. It grants none, and it does not replace the network or file rule for the same operation.
network rule refuses every socket; the caller sees EACCES. See Network rules.capget(2) is filtered too: the effective and permitted sets a confined task reads are intersected with what its profiles allow (hook capget, lsm.c:167-197; capability.c:194-223). A profile in complain mode reports the full set.capability dac_override, is all-or-nothing for every file.deny capability X, always wins and is not logged; audit deny logs it. audit capability X, logs uses. priority= has no effect; owner is an error.
priority= (accepted, no effect), audit, and allow / deny / prompt. The seat of owner and other is refused: owner conditional not allowed on capability rules.deny. What it sends is "allowed and not denied", "allowed and audited" and "denied and quiet" (parser_interface.c:549-559). No priority can therefore let an allow beat a deny here (block_rules.cc:135-138).prompt capability chown, is accepted and stored as allow (block_rules.cc:148-152); see prompt.owner { capability chown, } gives owner prefix not allowed on capability rules (block_rules.h:69). Block example: capability/ok_block1.sd.deny audit capability ... is a syntax error: audit sits before deny.A refused capability fails the call as a missing capability would (EACCES for setpriority and bind, EPERM for most calls) and is logged as operation="capable" capability=N capname="name", one record per second per capability. Plain deny rules log nothing.
apparmor="DENIED" operation="capable" parent=... profile=... pid=7292 comm=... capability=23 capname="sys_nice", with two blanks before capname). The profile and command names are demo's; the values are illustrative. capability=N comes from the common LSM audit code (lsm_audit.c:194); capname= is added by AppArmor (capability.c:47-53); the operation name is capable (audit.h:48).EPERM: setpriority returns EACCES when the nice test fails (sys.c:243-245).deny rule, unless the profile's audit mode is noquiet or all (capability.c:84-92); and checks the kernel makes without auditing, in enforce mode.ALLOWED. A profile in kill mode logs the type KILL.block_rules.cc:133-154 builds caps.allow/audit/deny/quiet; parser_interface.c:547-559 writes them; capability.c:149-165 tests the bit.
caps.allow, caps.audit, caps.quiet and a discarded one; then the optional caps64 with the upper halves; then the optional capsx into caps.extended (policy_unpack.c:1254-1288). struct aa_caps: capability.h:29-36.failed to unpack profile capabilities, failed to unpack upper profile capabilities, failed to unpack extended profile capabilities.caps/extended and the tree's abi/5.0 lists it (abi/5.0:3); no parser code reads it.AA_CLASS_CAP, class 3): one byte cap >> 5, then bit cap & 0x1f (capability.c:128-147). It is not reachable with this parser. The bit test: capability.c:149-165.capability chown, and capability audit_control, differ in bytes 61 and 64.aa_profile_capget loops over CAP_LAST_CAP >> 5 chunks, which is one, and shifts by i * 5 (capability.c:204-214). With policy that mediates the class in the policydb, capget(2) would not report capabilities 32 to 40. Found by reading; not run.With a kernel feature set that lacks them, perfmon, bpf and checkpoint_restore compile as sys_admin (parser_yacc.y:1710-1714). No warning is printed.
perfmon, bpf and checkpoint_restore, all to sys_admin (base_cap_names.h:9, base_cap_names.h:11, base_cap_names.h:47).--kernel-features names, or the running kernel's /sys/kernel/security/apparmor/features/caps/mask. The policy ABI of an abi rule is not consulted for this.capability, and all, set every bit regardless.sys_admin is capability 21 (capability.h:281), perfmon 38 (capability.h:383).linux/capability.h (Makefile:404-415), plus names from caps/mask of the kernel feature set and of the policy ABI at run time, numbered by position (parser_misc.c:407-436).sys_admin, and a deny is wider too. A reviewer has to know the caps/mask of the target kernel.audit_control then compiles to a bit that differs between runs, with exit status 0 (parser_misc.c:234-257, parser_misc.c:339-356). Reproduced with the tree's parser.chown: new rows get back-map 0 (parser_misc.c:347) where "no back-map" is 0xff (capability.h:25). Reproduced with the tree's parser.capability_backmap and capability_in_kernel: parser_misc.c:298-314. The comment /* TODO: special backmap warning */ is at parser_yacc.y:1712.add_cap_feature_mask (parser_misc.c:407-436) is called at parser_main.c:1841 and parser_yacc.y:365-367.Lower-case names without CAP_; blanks between names; no parentheses, quotes or variables.
AppArmor parser error for FILE in profile FILE at line N: MESSAGE; the slide shows MESSAGE, produced by the tree's parser. The message of the last row continues with the tokens the parser expected.capability cap_chown, gives Invalid capability cap_chown.; capability "chown", gives Lexer found unexpected character: '"' (0x22) in state: INITIAL; capability all, gives syntax error, unexpected TOK_ALL; capability set=hup, gives syntax error, unexpected TOK_CONDID.} gives syntax error, unexpected TOK_CLOSE, expecting TOK_ID or TOK_END_OF_RULE.capability ptrace trace, fails: ptrace is not a capability name (ptrace/bad_05.sd). Another failing example: capability/bad_1.sd.feature capability 'NAME:N' does not equal expected M. Ignoring ..., when a feature set lists a known name at another position (parser_misc.c:331).Capabilities filter privilege. Sockets, files and other objects have their own rules.
[QUALIFIERS] capability [NAME ...],: the task may use the named capabilities if it holds them. capability, names all of them.operation="capable", at most once a second per capability; plain deny is not logged.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the line (-Q -K --skip-kernel-load --warn=all), with nothing loaded into a kernel; "code" means the parser source or the kernel source was read, not run. Nothing here was observed on a running kernel.
CAPABILITY RULE: [QUALIFIERS] capability [NAME ...] , QUALIFIERS: [priority=N] [audit] [allow|deny|prompt]
capability, with no name means every capability (code).all as a name (tree).all, includes every capability; see syn-all.The name is the kernel's constant in lower case without CAP_. "Back-map" is the capability the parser uses instead when the kernel feature set does not list the name (code; confirmed by a run of the tree's parser).
| Number | Name | Kernel constant | Back-map |
|---|---|---|---|
| 0 | chown | CAP_CHOWN | |
| 1 | dac_override | CAP_DAC_OVERRIDE | |
| 2 | dac_read_search | CAP_DAC_READ_SEARCH | |
| 3 | fowner | CAP_FOWNER | |
| 4 | fsetid | CAP_FSETID | |
| 5 | kill | CAP_KILL | |
| 6 | setgid | CAP_SETGID | |
| 7 | setuid | CAP_SETUID | |
| 8 | setpcap | CAP_SETPCAP | |
| 9 | linux_immutable | CAP_LINUX_IMMUTABLE | |
| 10 | net_bind_service | CAP_NET_BIND_SERVICE | |
| 11 | net_broadcast | CAP_NET_BROADCAST | |
| 12 | net_admin | CAP_NET_ADMIN | |
| 13 | net_raw | CAP_NET_RAW | |
| 14 | ipc_lock | CAP_IPC_LOCK | |
| 15 | ipc_owner | CAP_IPC_OWNER | |
| 16 | sys_module | CAP_SYS_MODULE | |
| 17 | sys_rawio | CAP_SYS_RAWIO | |
| 18 | sys_chroot | CAP_SYS_CHROOT | |
| 19 | sys_ptrace | CAP_SYS_PTRACE | |
| 20 | sys_pacct | CAP_SYS_PACCT | |
| 21 | sys_admin | CAP_SYS_ADMIN | |
| 22 | sys_boot | CAP_SYS_BOOT | |
| 23 | sys_nice | CAP_SYS_NICE | |
| 24 | sys_resource | CAP_SYS_RESOURCE | |
| 25 | sys_time | CAP_SYS_TIME | |
| 26 | sys_tty_config | CAP_SYS_TTY_CONFIG | |
| 27 | mknod | CAP_MKNOD | |
| 28 | lease | CAP_LEASE | |
| 29 | audit_write | CAP_AUDIT_WRITE | |
| 30 | audit_control | CAP_AUDIT_CONTROL | |
| 31 | setfcap | CAP_SETFCAP | |
| 32 | mac_override | CAP_MAC_OVERRIDE | |
| 33 | mac_admin | CAP_MAC_ADMIN | |
| 34 | syslog | CAP_SYSLOG | |
| 35 | wake_alarm | CAP_WAKE_ALARM | |
| 36 | block_suspend | CAP_BLOCK_SUSPEND | |
| 37 | audit_read | CAP_AUDIT_READ | |
| 38 | perfmon | CAP_PERFMON | sys_admin |
| 39 | bpf | CAP_BPF | sys_admin |
| 40 | checkpoint_restore | CAP_CHECKPOINT_RESTORE | sys_admin |
| Seat | On a capability rule |
|---|---|
priority= | taken, without effect: deny is subtracted by the parser whatever the priorities (code) |
audit | taken: each use of an allowed capability is logged; with deny, the refusal is logged |
allow, deny, prompt | taken: allow is the default; deny removes the capability whatever else allows it and its refusals are not logged; prompt is stored as allow (code), see syn-prompt |
owner, other | refused: owner conditional not allowed on capability rules (tree) |
audit { capability chown, } works; owner { capability chown, } gives owner prefix not allowed on capability rules (tree).All statements in this section are from the kernel source (linux:security/apparmor/capability.c, linux:security/apparmor/lsm.c:167-211), not from a run.
1. The kernel's own capability check comes first. A task that does not hold the capability is refused there. 2. For a task whose label is not unconfined, AppArmor then tests the capability against each confined profile of the label. All of them must list it. 3. A capability that is not listed is refused: the hook returns EPERM and the system call returns its usual error for a missing capability. In complain mode it is allowed and logged.
capget(2) is filtered: the effective and permitted sets a confined task reads are intersected with what its profiles allow.network, file or other rule for the same operation.apparmor="DENIED" operation="capable" ... profile="demo" pid=7292 comm="demo" capability=23 capname="sys_nice"
libraries/libapparmor/testsuite/test_multi/testcase_dmesg_capability.in; the profile and command names are illustrative.deny rule is not logged, unless the profile's audit mode is noquiet or all (code).| Rule | Message |
|---|---|
capability CAP_NET_BIND_SERVICE, | Invalid capability CAP_NET_BIND_SERVICE. |
capability cap_chown, | Invalid capability cap_chown. |
capability net_bind_service, net_admin, | syntax error, unexpected TOK_END_OF_RULE, expecting TOK_MODE |
capability (chown), | syntax error, unexpected TOK_OPENPAREN, expecting TOK_ID or TOK_END_OF_RULE |
capability @{caps}, | syntax error, unexpected TOK_SET_VAR, expecting TOK_ID or TOK_END_OF_RULE |
capability "chown", | Lexer found unexpected character: '"' (0x22) in state: INITIAL |
capability all, | syntax error, unexpected TOK_ALL, expecting TOK_ID or TOK_END_OF_RULE |
capability set=hup, | syntax error, unexpected TOK_CONDID, expecting TOK_ID or TOK_END_OF_RULE |
capability chown before } | syntax error, unexpected TOK_CLOSE, expecting TOK_ID or TOK_END_OF_RULE |
deny audit capability net_admin, | syntax error, unexpected TOK_AUDIT, expecting TOK_ID or TOK_MODE or TOK_SET_VAR |
owner capability chown, | owner conditional not allowed on capability rules |
owner { capability chown, } | owner prefix not allowed on capability rules |
| a feature set lists a known name at another position | warning feature capability 'NAME:N' does not equal expected M. Ignoring ... (code) |
All rows are from the tree's parser unless marked.
block_rules::add_capabilities ORs it into caps.allow, caps.audit, caps.deny or caps.quiet (parser/block_rules.cc:133-154).parser/parser_interface.c:547-559): allow & ~deny, allowed & audit, deny & quiet, and a zero word; the upper halves follow in caps64.caps.allow, caps.audit, caps.quiet, with optional caps64 and capsx (linux:security/apparmor/policy_unpack.c:1254-1288); profile_capable tests one bit (linux:security/apparmor/capability.c:149-165). The policydb branch for AA_CLASS_CAP (capability.c:128-147) is not reachable with this parser.parser/base_cap_names.h), checked at build time against the build host's linux/capability.h (parser/Makefile:404-415); names from caps/mask of the kernel feature set and of the policy ABI are added at run time (parser/parser_misc.c:407-436).parser/parser_yacc.y:1710-1714, parser/parser_misc.c:298-314.None of these is taught as intended behaviour; the verdicts come from the review (sec-bugs).
capability audit_control, then compiles to a bit that differs between runs, with exit status 0 (tree).chown (tree).aa_profile_capget covers only capabilities 0 to 31; it is not reachable with this parser (code, not run).change_profile -> TARGET, lets a task under this profile ask to continue under TARGET.
int aa_change_profile(const char *profile) and int aa_change_onexec(const char *profile) (apparmor.h:80-81). They write changeprofile NAME to /proc/self/attr/apparmor/current (or /proc/self/attr/current) and exec NAME to the exec file next to it.aa_change_profile (domain.c:1484-1660). aa-exec -p PROFILE -- CMD uses the same interface./sys/kernel/security/apparmor/features/domain/change_profile, change_onexec and stack (apparmorfs.c:2604-2606).change_profile -> demo//worker, is line 23 of demo's profile; it compiles with no warning (run with the tree's parser). The program demo and its profile are invented for the map.[QUALIFIERS] change_profile [[safe|unsafe] EXEC] [-> TARGET],. No target means any profile.
/ or @{. safe and unsafe are allowed only with EXEC.-> {new_profile1,new_profile2},). A rule without a target means any profile. A target literally named safe or unsafe is read as a name after the arrow: change_profile -> safe, is accepted.change_profile -> b, and change_profile -> &b, are different permissions: the & stays in the compiled target. What a stack target means is in stacking; a target in another namespace is in namespaces.allow, deny, prompt and priority= are accepted, and audit is accepted by the grammar (run with the tree's parser). owner and other are refused: owner change_profile -> demo//worker, gives owner conditional not allowed on change_profile rules.audit change_profile is never audited, and the warning blames the kernel": audit change_profile ... is accepted and the audit flag is not compiled; see the details of "What demo and the log see".owner { change_profile -> x, } is accepted although owner change_profile is an error".change_profile -> :ns://name, compiles to a pattern the kernel never walks".abi rule, xattrs= is dropped silently and change_profile -> &x is refused "by the kernel"": in a profile with no abi rule, change_profile -> &x, is refused with The current kernel does not support stacking of named transitions: &x, whatever the kernel supports (run with the tree's parser).&name) are validated and feature-gated only for change_profile, and only without stacking support". See Known bugs./ or @{ (parser_yacc.y:1674-1675); safe and unsafe need EXEC (parser_yacc.y:1672-1673); an absent TARGET is ** (parser_yacc.y:1681).CHANGE_PROFILE_MODE; -> pushes SUB_ID_WS (parser_lex.l:593-608, parser_lex.l:873-874).aa_change_profile() changes now; aa_change_onexec() changes at the next exec. Every change_profile rule grants both.
current attribute file: changeprofile NAME (change now), permprofile NAME (test only) and stack NAME. On the exec attribute file: exec NAME and stack NAME (lsm.c:882-904).AA_MAY_CHANGE_PROFILE and AA_MAY_ONEXEC. A change now replaces the label (domain.c:1622-1628); a change at exec stores the target for the next exec (domain.c:1629-1636). At exec the stored target is checked again against the executable (domain.c:837-862).change_profile rule grants both requests.change_onexec, so a task that drops CAP_MAC_OVERRIDE after asking is stacked with unconfined". It applies where kernel.apparmor_restrict_unprivileged_unconfined is on; see Known bugs.change_profile EXEC -> TARGET, permits the change at exec only for executables matching EXEC.
info is no change_onexec valid for executable (domain.c:840).aa_change_profile() to the target.change_profile /usr/lib/demo/worker, compiles with any profile as the target (run with the tree's parser).change_profile -> T, lets the task enter T with any executable. change_profile, lets it enter any profile visible to it, less restrictive ones included, subject to the kernel's other checks: the target must exist, a tracer must be allowed to trace the new label (domain.c:1581-1585), and under no_new_privs the change must not reduce confinement (domain.c:1612-1619).-> demo//*) grows with every profile loaded later that matches.demo//worker, /usr/lib/demo/worker and /usr/lib/demo/worker\x00demo//worker (run with the tree's parser).With an exec condition the exec sets AT_SECURE unless the rule says unsafe. safe and unsafe need an exec condition.
AT_SECURE for the new program; what the loader then ignores is in safe and unsafe exec.unsafe; a rule without an exec condition carries no exec bits at all.profile demo: has merged rule demo//worker with conflicting x modifiers, followed by ERROR merging rules for profile demo, failed to load (run with the tree's parser). Examples in the tree: the onx_conflict_unsafe_*.sd files in parser/tst/simple_tests/change_profile.domain/stack (a profile with no abi rule), a safe rule prints the warning downgrading change_profile safe rule to unsafe due to lack of necessary kernel support (class rule-downgraded, off by default) and is compiled exactly like a rule with no mode, without the unsafe bits.Missing rule: EACCES, operation="change_profile" / "change_onexec" with target=. Missing profile: ENOENT, info="label not found".
apparmor="DENIED" operation="change_profile" profile="php-fpm" name="php-fpm//webapp" pid=825 comm="php-fpm" target="php-fpm//webapp") with class="file" after operation as in the newer testcase_changeprofile_03.in. The second follows change_onexec_gl636.in (operation="change_onexec" class="file" info="label not found" error=-2 profile=... name="snap.firefox.firefox" pid=6209 comm="snap-confine").change_profile, change_onexec, stack and stack_onexec. error=-2 is ENOENT.EPERM, next to the comment not an apparmor denial per se, so don't log it (domain.c:1612-1619). A change that is refused for the same reason at exec time is logged with info="no new privs" (domain.c:1050-1056); an older record of that kind is change_onexec_lp1648143.in.audit change_profile is never audited, and the warning blames the kernel": audit change_profile ... is accepted and the audit flag is not compiled; the only notice is Warning kernel does not support audit modifier for change_profile rule., shown with --warn=rule-downgraded or --warn=all (run with the tree's parser; a deny change_profile rule prints the same warning).changeprofile &name is audited as operation="change_profile"": a changeprofile &name request is logged as operation="change_profile". See Known bugs.parser_regex.c:764-784 adds target, exec and exec NUL target to the file DFA; block_rules.cc:602-608 adds the /proc/*/attr/ rules; domain.c:837-862, 1448-1469 match them.
-D rule-exprs): demo's line 23 gives demo//worker 0xc0000000, /[^/\x00][^\x00]* 0x40000000 and /[^/\x00][^\x00]*\x00demo//worker 0x40000000; with the exec condition of the slide, demo//worker 0xc0000000, /usr/lib/demo/worker 0x40000000 and /usr/lib/demo/worker\x00demo//worker 0x40004001; with unsafe the last entry is 0x40404101; change_profile, gives [^\x00]*, /[^/\x00][^\x00]* and /[^/\x00][^\x00]*\x00[^\x00]*. A target &demo//worker keeps the & in the string./proc/*/attr/apparmor/ and /sys/module/apparmor/parameters/enabled with read, and /proc/*/attr/{apparmor/,}{current,exec} with write (run with the tree's parser).domain/stack is consulted for feature gating (parser_main.c:1093-1095); without it the target is split into namespace and name (parser_regex.c:742-759)./proc/*/attr/{apparmor/,}{current,exec} for any pid in the path pattern. What a write there can do is decided by the kernel's own checks on the attribute interface; see who can change policy.audit change_profile is never audited, and the warning blames the kernel"; see "What demo and the log see"), so allowed profile changes cannot be audited per rule.The target goes after ->. safe/unsafe need an exec condition. Target names are not checked at compile time.
AppArmor parser error for FILE in profile FILE at line N: MESSAGE; the slide shows MESSAGE. Rows 1 to 4 were run with the tree's parser. The conflict of row 4 is printed without a line number and is followed by ERROR merging rules for profile demo, failed to load.change_profile -> demo//wrker,, is accepted (run with the tree's parser). That it fails at run time with label not found is derived from the kernel source.abi rule a & target gives The current kernel does not support stacking of named transitions: &x. Known discrepancy, on the bug list as "Without an abi rule, xattrs= is dropped silently and change_profile -> &x is refused "by the kernel""; the check itself is on the bug list as "Stack targets (&name) are validated and feature-gated only for change_profile, and only without stacking support".rule-downgraded, which is off by default: the warning that says a safe rule was downgraded (see "safe is the default"), and Warning kernel does not support audit modifier for change_profile rule.change_profile permits; libapparmor asks. & targets: Stacking. :ns: targets: Namespaces.
[QUALIFIERS] change_profile [[safe|unsafe] EXEC] [-> TARGET],: no target means any profile; no exec condition means any program.aa_change_profile() or aa_change_onexec().Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the line (-Q -K --skip-kernel-load --warn=all, -D rule-exprs for compiled forms), with nothing loaded into a kernel; "code" means the parser source or the kernel source was read, not run. Nothing here was observed on a running kernel.
CHANGE_PROFILE RULE: [QUALIFIERS] change_profile [ [safe|unsafe] EXEC ] [ -> TARGET ] , QUALIFIERS: [priority=N] [audit] [allow|deny|prompt]
/ or @{ (tree).safe and unsafe need EXEC; with EXEC and neither word the rule is safe (tree).change_profile /usr/lib/demo/worker, (tree).| Seat | On a change_profile rule |
|---|---|
priority= | taken |
audit | taken by the grammar: the audit flag is not compiled (known discrepancy) |
allow, deny, prompt | taken; prompt is in syn-prompt |
owner, other | refused: owner conditional not allowed on change_profile rules (tree) |
| Rule | Change now | Change at exec | Secure execution at that exec |
|---|---|---|---|
change_profile, | to any profile | to any profile, with any executable | the rule carries no exec bits |
change_profile -> T, | to T | to T, with any executable | the rule carries no exec bits |
change_profile EXEC -> T, | to T | to T, only when executing EXEC | yes (safe is the default) |
change_profile EXEC, | to any profile | to any profile, only when executing EXEC | yes |
change_profile unsafe EXEC -> T, | to T | to T, only when executing EXEC | no |
The first three columns follow from the compiled entries (tree) and the kernel's checks (linux:security/apparmor/domain.c:837-862, 1448-1469, code); nothing was run on a kernel. The kernel sets secure execution when the matched permissions lack the unsafe bit (linux:security/apparmor/domain.c:855-862). By that test a change at exec under the first two rows would also get secure execution, because an entry without EXEC cannot carry the unsafe bit; this is derived from the code and was not run.
| Form | Example | Meaning |
|---|---|---|
| name | -> demo//worker | that profile |
| glob or alternation | -> demo//*, -> {a,b} | every profile whose name matches, also ones loaded later |
| variable | -> @{profile_name}//worker | expanded by the parser |
&name | -> &demo//worker | a stack: see stacking |
:ns:name | -> :ns:demo | a profile in another namespace: see namespaces |
| libapparmor call | Attribute file and command | Kernel request | Operation in the log |
|---|---|---|---|
aa_change_profile(name) | /proc/self/attr/apparmor/current: changeprofile NAME | AA_MAY_CHANGE_PROFILE | change_profile |
aa_change_onexec(name) | /proc/self/attr/apparmor/exec: exec NAME | AA_MAY_ONEXEC | change_onexec |
aa_stack_profile(name) | current: stack NAME | stack | |
aa_stack_onexec(name) | exec: stack NAME | stack_onexec |
The commands are read at linux:security/apparmor/lsm.c:882-904 (code). The calls are in lib-change-profile.
| The caller gets | When | The record |
|---|---|---|
EACCES | no rule permits the change | operation="change_profile" or "change_onexec", name= and target= the target |
ENOENT | the target profile is not loaded | info="label not found" error=-2, name= the target |
EPERM | under no_new_privs, a request that would reduce confinement | none |
A tracer that may not trace the new label also refuses the change, with info="ptrace prevents transition" (linux:security/apparmor/domain.c:50-82, 1581-1585, code); see stacking.
Records from the tree (libraries/libapparmor/testsuite/test_multi/testcase_changeprofile_02.in and change_onexec_gl636.in):
apparmor="DENIED" operation="change_profile" profile="php-fpm" name="php-fpm//webapp" pid=825 comm="php-fpm" target="php-fpm//webapp" apparmor="DENIED" operation="change_onexec" class="file" info="label not found" error=-2 profile="/usr/lib/snapd/snap-confine" name="snap.firefox.firefox" pid=6209 comm="snap-confine"
| Rule | Message |
|---|---|
change_profile demo//worker, | Exec condition must begin with '/'. |
change_profile safe -> demo//worker, | Exec condition is required when unsafe or safe keywords are present |
owner change_profile -> demo//worker, | owner conditional not allowed on change_profile rules |
| a safe and an unsafe rule for the same EXEC and TARGET | profile demo: has merged rule demo//worker with conflicting x modifiers, then ERROR merging rules for profile demo, failed to load |
change_profile -> demo//wrker, | none; the target is not checked |
audit change_profile -> demo//worker, with --warn=rule-downgraded | Warning kernel does not support audit modifier for change_profile rule. |
a safe rule in a profile with no abi rule, --warn=rule-downgraded | warning downgrading change_profile safe rule to unsafe due to lack of necessary kernel support |
change_profile -> &x, in a profile with no abi rule | The current kernel does not support stacking of named transitions: &x |
All rows are from the tree's parser.
parser/parser_yacc.y:1650-1691).parser/parser_regex.c:764-784): TARGET with change-now and on-exec (0xc0000000); EXEC, or /[^/\x00][^\x00]* when absent, with on-exec (0x40000000); EXEC NUL TARGET with on-exec and the exec bits (0x40004001 safe, 0x40404101 unsafe, 0x40000000 without EXEC) (tree)./proc/*/attr/apparmor/, /proc/*/attr/{apparmor/,}{current,exec} and /sys/module/apparmor/parameters/enabled (parser/block_rules.cc:602-608).aa_change_profile (linux:security/apparmor/domain.c:1484-1660); a change now replaces the label, a change at exec stores the target; at exec the kernel matches the exec name, requires AA_MAY_ONEXEC, steps over a NUL and matches the target (linux:security/apparmor/domain.c:837-862).None of these is taught as intended behaviour. All are on the bug list as confirmed; see Known bugs.
audit change_profile ... is accepted and the audit flag is not compiled; the only notice is a warning that is off by default (tree).abi rule, change_profile -> &x is refused with a message that names the kernel (code).change_profile -> :ns://name, compiles to a pattern the kernel never walks (code).&name) are validated and feature-gated only for change_profile, and only without stacking support (code).owner { change_profile -> x, } is accepted although owner change_profile is an error (tree).changeprofile &name request is audited as operation="change_profile" (code).change_onexec, so a task that drops CAP_MAC_OVERRIDE after asking is stacked with unconfined (kernel; on the bug list).A child profile is a profile declared inside another profile. It is used when the parent starts a program through an exec rule with a c mode such as Cx.
profile NAME { RULES } written inside the body of another profile, and an exec rule in the parent with a c mode, as in /usr/lib/demo/worker Cx -> worker,./usr/bin/baz Cx -> baz, (apparmor.d.pod:2880) and profile baz { ... } (apparmor.d.pod:2889-2896).cx, Cx, cix, Cix, cux and CUx (apparmor.d.pod:865-905).demo//worker, next to its parent, not as a top-level profile of its own.bprm_creds_for_exec, implemented by apparmor_bprm_creds_for_exec (lsm.c:1862, domain.c:985). For a c mode the search is over the current profile's own children; for a p mode over the namespace's top-level profiles (domain.c:603-611).demo, its worker and the profile are invented for the map. Nothing on this slide was observed on a running kernel.local_profile: TOK_PROFILE profile_base (parser_yacc.y:480-488).c and C set AA_EXEC_LOCAL | AA_MAY_EXEC (parser_misc.c:649-687; the constant is at immunix.h:82).profile NAME [ATTACHMENT] [xattrs=( )] [+ identities=( )] [flags=( )] { rules } inside a profile body. The keyword is required. A child does not inherit its parent's rules.
profile NAME [ATTACHMENT] [xattrs=( )] [+ identities=( )] [flags=( )] { RULES }, inside a profile body. There is no comma after the closing brace.profile is required inside a body. Without it, /usr/lib/demo/worker { is read as the start of a file rule and the parser built from the AppArmor tree at 836052d21 answers syntax error, unexpected TOK_OPEN, expecting TOK_MODE (-Q -K --skip-kernel-load --warn=all, nothing loaded into a kernel).Lexer found unexpected character: '\n' (0xa) in state: SUB_ID (same parser, same options)./ or a variable: Profile attachment must begin with a '/' or variable.xattrs; a hat may not (hat profiles can't use xattrs matches).profile /bin/grep { }; local_named_profile_ok1.sd has profile true /bin/true { }, a name plus an attachment, next to a hat.profile_base: TOK_ID opt_id_or_var opt_cond_list identities flags TOK_OPEN rules TOK_CLOSE is shared by top-level profiles, children and hats (parser_yacc.y:391-399); local_profile is at parser_yacc.y:480-488 and is added to a body by rules: rules local_profile (parser_yacc.y:836-843).TOK_PROFILE for the keyword and enters the SUB_ID state for the name (parser_lex.l:850, parser_lex.l:456-461). A bare path at the start of a rule is TOK_ID (parser_lex.l:838-841), which is why the keyword cannot be left out.A child named worker in profile demo is demo//worker in listings, labels and logs. apparmor_parser -N prints the full names alphabetically. Inside the child, @{profile_name} expands to the full name.
apparmor_parser -N (--names, "Dump names of profiles in input.") prints the full names without compiling or loading anything (parser_main.c:231, apparmor_parser.pod:102).profile worker { } in profile demo /usr/bin/demo { } is listed as demo//worker; profile /usr/lib/demo/helper { } as demo///usr/lib/demo/helper.ns the fully qualified name is :ns://demo//worker (profile.h:462-470, read from the source).@{profile_name} is the full name without the namespace (parser_variable.c:154-155; asserted by the tests at equality.sh:919-923).prefix//name in aa_policy_init (lib.c:478-497).profile= field of log records; /proc/<pid>/attr/apparmor/current (and the older /proc/<pid>/attr/current); and int aa_getcon(char **label, char **mode) or int aa_gettaskcon(pid_t target, char **label, char **mode) from libapparmor (apparmor.h:110-111).Profile::hname() returns parent->hname() + "//" + name; fqname() adds :ns:// (profile.h:454-470).get_name(false) (parser_interface.c:488-490)./usr/lib/demo/worker Cx -> worker, runs the helper in demo//worker. The child is found by name, so it needs no attachment. A missing child is found out only at exec: "profile transition not found" (read from the kernel source, for a profile in enforce mode).
/usr/lib/demo/worker Cx -> worker,. The target is the child's short name; the man page example is /usr/bin/baz Cx -> baz, (apparmor.d.pod:2880).demo//worker in the parent's exec table. Checked with the parser built from the AppArmor tree at 836052d21: the string is in the binary profile.Cx -> missing, compiles without a message (same parser, -Q -K --skip-kernel-load --warn=all).Profile NAME has too many specified profile transitions. (immunix.h:70, read from the source).x_table_lookup walks the table entry and, for a child transition, calls aa_find_child(profile, name) (domain.c:523-559).info="profile transition not found" (domain.c:740-751). In complain mode a learning profile is created instead and the exec goes on (the same lines).cix continues in the parent (info="ix fallback"), cux unconfined (info="ux fallback") (domain.c:616-637).add_named_transition builds the entry with sprintf(name, "%s//%s", prof->name, entry->nt_name) when the mode is a c mode and the target has no namespace (block_rules.cc:474-520); add_entry_to_x_table starts at index (AA_EXEC_LOCAL >> 10) + 1 and reuses an equal string (block_rules.cc:458-472).post_parse_profile_file calls it for every entry with a target and prints the table-full error (block_rules.cc:576-611).prof->name is the local name of the profile holding the rule, so a named cx -> inside a child stores child//target, not the full name; see "Known discrepancies" in the reference below.A bare Cx searches the parent's children by attachment (or by a name equal to the path). A child's attachment is used only for such execs from its parent. Started from elsewhere, the program is matched against top-level profiles only, and runs unconfined if none of those attaches to it.
/usr/lib/demo/* Cx, with no arrow. Each child that should be found needs an attachment (profile logger /usr/lib/demo/logger { }) or a name that is the path (profile /usr/lib/demo/helper { }).c mode x_to_label calls find_attach over the current profile's children, profile->base.profiles; for a p mode over the namespace's top-level profiles, ns->base.profiles (domain.c:603-611).find_attach compares the program's path with each candidate's attachment and keeps the best match; a profile whose name equals the path also matches (domain.c:394-520, the name comparison at domain.c:485). Two equally good matches give info="conflicting profile attachments" (domain.c:33).ns->base.profiles only (domain.c:697-699). A child is not on that list, so its attachment is never consulted there.cx refuses the exec, cix continues in the parent, cux runs unconfined (see the previous slide).profile true /bin/true { }.xmatch DFA by process_profile_name_xmatch (parser_regex.c:478-520); an invalid pattern gives Invalid profile name 'NAME' - bad regular expression.profile_base (parser_yacc.y:388-391); its check is at parser_yacc.y:431-433.AA_X_NAME | AA_X_CHILD (policy_compat.c:40-41); the flags are defined at file.h:58-62.Child profile: entered at exec through a cx rule, for a program you start. Hat: entered and left with aa_change_hat(), for part of your own program's work. change_hat on a child fails with "target not hat".
^NAME { } or hat NAME { }; a child profile NAME { }. Both are loaded as parent//NAME, and the two share one set of names within a profile.int aa_change_hat(const char *subprofile, unsigned long magic_token) and int aa_change_hatv(const char *subprofiles[], unsigned long token) (apparmor.h:79-83). aa_change_hat(NULL, token) returns to the parent.changehat TOKEN^NAME to the task's /proc/<tid>/attr/apparmor/current (or /proc/<tid>/attr/current) (kernel.c:1033, path formats at kernel.c:424-426).apparmor_setprocattr (lsm.c:943); change_hat looks the name up among the profile's children and, when the profile found is not a hat, fails with info="target not hat" and EPERM (domain.c:1232-1243).bprm_creds_for_exec hook and a c mode in the parent (domain.c:603-611). There is no way back: the started program keeps the child's label and its own execs follow the child's rules.change_hat needs: /proc/*/attr/apparmor/ r,, /sys/module/apparmor/parameters/enabled r, and /proc/[0-9]*/attr/{apparmor/,}current w, (profile.cc:78-89, block_rules.h:27; rule dump made with the released parser 5.0.2).cx -> NAME can enter a hat was not determined.hat: hat_start profile_base and sets profile_flag_t::HAT; local_profile is the same without the flag (parser_yacc.y:480-504).local_profile: TOK_PROFILE profile_base; storage in defined_hats; add_named_transition() stores name//target in the exec table; kernel x_to_label() uses find_attach() over the profile's children or x_table_lookup().
local_profile: TOK_PROFILE profile_base (parser_yacc.y:480-488); rules: rules local_profile calls add_hat, with the message Assert: 'local_profile rule' returned NULL. (parser_yacc.y:836-843).block::add_hat sets hat->parent and calls add_to_known_hats, which inserts into defined_hats and exits with Multiple definitions for profile NAME exist,bailing out. on a duplicate (block.cc:137-155).add_entry_to_x_table and add_named_transition (block_rules.cc:458-520), driven by post_parse_profile_file (block_rules.cc:576-611). AA_EXEC_COUNT is 16 (immunix.h:70); AA_EXEC_LOCAL is AA_EXEC_MOD_0 | AA_EXEC_MOD_1, index 3 (immunix.h:82), and the loop starts at index 4.cx -> rule equals the rule's own path the rule is turned back into the unnamed form (block_rules.cc:492-496).load_flattened_hats loads defined_hats as a policy list after the parent (parser_policy.c:84-89, called from parser_interface.c:783-785); each child's blob carries its full name (parser_interface.c:488-490).AA_X_NAME | AA_X_CHILD (policy_compat.c:40-41).x_to_label (domain.c:574-650): AA_X_TABLE goes to x_table_lookup, which uses aa_find_child when AA_X_CHILD is set and aa_label_parse otherwise (domain.c:523-559); AA_X_NAME goes to find_attach over profile->base.profiles or ns->base.profiles.& is a stack: the entry is looked up and then the AA_X_NAME search runs as well (domain.c:597-600).Inside a profile the keyword profile is required. Children and hats of one profile share one set of names. The parser does not verify Cx -> targets; a wrong name shows up at exec as "profile transition not found".
-Q -K --skip-kernel-load --warn=all, nothing loaded into a kernel). The full form is AppArmor parser error for FILE in profile FILE at line N: MESSAGE.syntax error, unexpected TOK_OPEN, expecting TOK_MODE.profile worker bin { }: Profile attachment must begin with a '/' or variable.Multiple definitions for profile NAME exist,bailing out. (block.cc:137-146). The released parser 5.0.2 words it Multiple definitions for hat NAME in profile (null) exist,bailing out.Cx -> missing, compiles without a message; the parser does not verify that the target exists.info="profile transition not found" when the parent is in enforce mode (domain.c:740-751). The record's profile= is the parent and name= the program's path.apparmor_parser -r after deleting a child from the file leaves the old child loaded (read from the kernel source, policy.c:1066-1091: __replace_profile moves children that the new version does not replace over to it).The mode letters: syn-exec-modes. The arrow: syn-named-transitions. The sibling: syn-hats. The kernel's side: k-exec.
profile NAME { } inside a profile, loaded as parent//NAME.cx, Cx, cix, Cix, cux or CUx: by name with -> NAME, by attachment without the arrow.info="profile transition not found" (the kernel, domain.c:746).Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the fragment (-Q -K --skip-kernel-load --warn=all, nothing loaded into a kernel); "5.0.2" means the released parser 5.0.2 was run; "code" means the kernel or parser source was read, not run. Everything said here about what happens at exec is "code".
CHILD: 'profile' NAME [ATTACHMENT] [xattrs=( ... )] { '+' identities=( ... ) } [flags=( ... )] '{' rules '}'
profile is required. At the top level a path may stand alone as a profile head; inside a body a path at the start of a line begins a file rule.ATTACHMENT must begin with / or a variable.rules is an ordinary profile body, so children may contain children and hats, to any depth.| Token | Meaning |
|---|---|
profile | inside a body: starts a child profile |
// | the separator in loaded names: parent//child. Not written in the child's head |
cx Cx cix Cix cux CUx | the exec modes that send the started program into a child of the current profile: syn-exec-modes |
-> | names the child in an exec rule: syn-named-transitions |
For children of profile demo /usr/bin/demo { }:
| In the file | Loaded name | Basis |
|---|---|---|
profile worker { } | demo//worker | tree |
profile logger /usr/lib/demo/logger { } | demo//logger | tree |
profile /usr/lib/demo/helper { } | demo///usr/lib/demo/helper | tree |
profile inner { } inside worker | demo//worker//inner | tree |
any of these when demo is in namespace ns | :ns://demo//worker | code |
apparmor_parser -N prints the full names. Children and hats of one profile are listed and loaded in alphabetical order, not file order (tree).profile= field of its log lines (code).@{profile_name} expands to the full name without the namespace (asserted by parser/tst/equality.sh).| Rule in the parent | How the child is found | The child needs |
|---|---|---|
/usr/lib/demo/worker Cx -> worker, | by name: the parser stores demo//worker in the profile's exec table (tree: the string is in the binary profile) and the kernel looks that name up at exec (code) | nothing more |
/usr/lib/demo/* Cx, | by search: the kernel matches the program's path against the attachments of the parent's children (code) | an attachment, or a name that is the path |
px, or by an unconfined task, searches the namespace's top-level profiles (code).Cx -> exists: Cx -> missing, compiles without a message (tree).| Mode | Result |
|---|---|
cx, Cx | the exec is refused; the log line carries info="profile transition not found" |
cix, Cix | the program runs in the parent profile |
cux, CUx | the program runs unconfined |
cx, Cx with the parent in complain mode | a learning profile is created and the exec goes on |
The modes and their fallbacks: syn-exec-modes.
| Child profile | Hat | |
|---|---|---|
| Written as | profile NAME { } | ^NAME { } or hat NAME { } |
| Loaded as | parent//NAME | parent//NAME |
| Entered | at exec, by a cx rule of the parent | at any time, by the program calling aa_change_hat() |
| Left | not at all: the started program keeps the child's label; its own execs follow the child's rules | aa_change_hat(NULL, token) |
| May have an attachment | yes | yes (what it is for was not determined) |
May have xattrs=( ) | yes | no |
change_hat to a child declared with profile fails with info="target not hat" (code).cx -> NAME can enter a hat was not determined.A profile that declares a child or a hat receives three implied file rules (tree, rule dump):
/proc/*/attr/apparmor/ r,
/sys/module/apparmor/parameters/enabled r,
/proc/[0-9]*/attr/{apparmor/,}current w,
They exist for change_hat. A parent that has only child profiles gets them too, although change_hat cannot enter such a child. A child without hats or children of its own does not get them. Details: syn-hats.
As for hats, see syn-hats:
-r after deleting a child from the file leaves the old child loaded (code).apparmor_parser -R removes the parent, and the kernel removes its children with it (code).| Message | Cause |
|---|---|
syntax error, unexpected TOK_OPEN, expecting TOK_MODE | a path and a brace inside a profile, without the keyword profile (tree) |
Profile attachment must begin with a '/' or variable. | profile worker bin { } (tree) |
Multiple definitions for profile NAME exist,bailing out. | two children, or a child and a hat, with one name in the same profile (tree). 5.0.2 words it Multiple definitions for hat NAME in profile (null) exist,bailing out. |
Lexer found unexpected character: '\n' (0xa) in state: SUB_ID | a new line between profile and the name; the character is printed raw (tree) |
Profile NAME has too many specified profile transitions. | more named exec targets than the exec table holds: 16 slots of which 4 are reserved (code) |
FILE: Invalid profile name 'NAME' - bad regular expression | the attachment, or a path-like name, is not a valid pattern (code) |
Assert: 'local_profile rule' returned NULL. | internal check in the grammar (code) |
kernel: info="profile transition not found" | plain cx or Cx and no child found at exec, enforce mode (code) |
kernel: info="target not hat" | change_hat to a child that is not a hat (code) |
cx -> inside a child. The prefix the parser puts before the target is the local name of the profile that holds the rule, not its full name. For profile a { profile b { /z cx -> c, profile c { } } } the exec table of a//b holds b//c, while the grandchild is loaded as a//b//c (tree, strings of the binary profile). By the code of mainline Linux 7.4 the entry is resolved from the namespace root, where b//c does not exist unless a top-level profile b has a child c, so the rule does not reach the grandchild. Not run on a kernel. One level of nesting, as in this deck, is not affected.a//b and a child b nested in a get the same loaded name. The parser keeps them in different lists and its duplicate check does not see the clash (code). What a running kernel does with the two was not determined.Cx -> other//name, can be rewritten by the parser into a transition to a child of the current profile when name equals the rule's path (code; listed in the project's bug notes as a suspected parser bug).| Step | Where | |
|---|---|---|
local_profile: TOK_PROFILE profile_base; rules: rules local_profile | parser/parser_yacc.y:480-488, 836-843 | |
profile_base: name, attachment, xattrs, identities, flags, body | parser/parser_yacc.y:391-399 | |
| attachment check | parser/parser_yacc.y:431-433 | |
hat rule: the same profile_base plus the HAT flag | parser/parser_yacc.y:490-504 | |
profile keyword pushes SUB_ID; the name token | parser/parser_lex.l:278, 456-461, 850 | |
a bare path inside a body is TOK_ID | parser/parser_lex.l:838-841 | |
block::add_to_known_hats, block::add_hat: defined_hats, duplicate check | parser/block.cc:137-155 | |
| ordered set of children and hats | parser/profilelist.h:28 | |
hname(), fqname() | parser/profile.h:454-470 | |
c modes set AA_EXEC_LOCAL | parser/parser_misc.c:649-687; parser/immunix.h:82 | |
add_entry_to_x_table, add_named_transition: sprintf("%s//%s", prof->name, nt_name) | parser/block_rules.cc:458-520 | |
post_parse_profile_file: every entry with a target; the table-full error | parser/block_rules.cc:576-611 | |
AA_EXEC_COUNT 16 | parser/immunix.h:70 | |
| attachment or path-like name compiled to the child's xmatch | parser/parser_regex.c:478-520 | |
@{profile_name} | parser/parser_variable.c:154-155 | |
implied rules for a profile with defined_hats | parser/profile.cc:78-89 | |
serialization: name written is hname(); load_flattened_hats | parser/parser_interface.c:488-490, 783-785; parser/parser_policy.c:84-89 | |
| kernel: packed exec index 3 becomes `AA_X_NAME \ | AA_X_CHILD` | linux:security/apparmor/policy_compat.c:40-41 |
kernel: x_table_lookup(), aa_label_parse() | linux:security/apparmor/domain.c:523-559 | |
kernel: x_to_label(); find_attach() over profile->base.profiles for cx, ns->base.profiles for px | linux:security/apparmor/domain.c:574-650, 603-611 | |
kernel: find_attach(); a name equal to the path matches | linux:security/apparmor/domain.c:394-520, 485 | |
| kernel: "profile transition not found"; learning profile in complain mode | linux:security/apparmor/domain.c:740-751 | |
| kernel: "target not hat" | linux:security/apparmor/domain.c:1232-1243 | |
kernel: hname built as prefix//name | linux:security/apparmor/lib.c:478-497 | |
| kernel: parent lookup on load; children kept on replacement | linux:security/apparmor/policy.c:523-544, 1071-1091, 1293-1323 |
post_parse_profile runs when the inner profile_base is reduced (parser/parser_yacc.y:450), before add_hat sets parent (parser/parser_yacc.y:836-843), so hname() is not yet usable in add_named_transition: the origin of the first known discrepancy above.cx -> rule equals the rule's own path, the rule is turned back into the unnamed form (parser/block_rules.cc:492-496).parser/tst/simple_tests/profile/local/local_profiles_ok1.sd, local_named_profile_ok1.sd; parser/tst/simple_tests/xtrans/x-conflict.sd. Man page example: parser/apparmor.d.pod:2880, 2889-2896.Rules end with ,. Bodies are in { }. # starts a comment to the end of the line. include lines and comments take no comma.
, ends a rule, { and } hold a body, # starts a comment that runs to the end of the line.include <file> and the older #include <file> take no comma.demo is invented for the map. Statements about the parser were checked with the parser built from the AppArmor tree at 836052d21 (-Q -K --skip-kernel-load --warn=all, nothing loaded into a kernel).END_OF_RULE is [,] (parser_lex.l:254) and returns TOK_END_OF_RULE (parser_lex.l:911-917); the braces return TOK_OPEN and TOK_CLOSE (parser_lex.l:834-836); the comment rule is #.*\r?\n (parser_lex.l:815-818).Comma: every rule, abi, alias. Closing brace: profile, hat, child, qualifier block, if block. End of line: comments, include, variable assignments.
network, capability, mount, signal, change_profile and the others), and in the preamble abi <...>, and alias A -> B,.} and no comma: a profile, a hat, a child profile, a qualifier block (deny { }, audit { }) and an if block.include and #include; a variable assignment @{X} = ... and a boolean assignment ${X} = .... A backslash directly before the new line continues an assignment.Variable declarations do not accept trailing commas.include if exists <x>, gives syntax error, unexpected TOK_END_OF_RULE (run with the released parser 5.0.2).\r\n is accepted wherever \n is: dos_line_endings.sd.{ } block with no qualifier is accepted, and blocks nest: audit { deny { /x w, } } (5.0.2).TOK_END_OF_RULE in the grammar: alias (parser_yacc.y:511), abi_rule (parser_yacc.y:1052), change_profile (parser_yacc.y:1648), and so on for every rule class.block: TOK_OPEN rules TOK_CLOSE and its use with qualifiers (parser_yacc.y:738-759).ASSIGN_MODE has the trailing comma error, a comment rule, the backslash continuation and a new line rule that leaves the state (parser_lex.l:570-588); the boolean form repeats them (parser_lex.l:735-747).New lines are white space inside and between rules. /etc/demo/a,b r, names the path /etc/demo/a,b: a comma followed directly by a word character is part of the word.
-Q -K --skip-kernel-load --warn=all)./foo,bar r, is one rule for the path /foo,bar: ok_comma_1.sd, expected result PASS./foobar, r, fails: bad_comma_1.sd, expected result FAIL. The message is syntax error, unexpected TOK_END_OF_RULE, expecting TOK_MODE."/foobar," r,: ok_comma_2.sd./etc/demo/** r,,, gives syntax error, unexpected TOK_END_OF_RULE, expecting TOK_ID or TOK_MODE or TOK_SET_VAR.{a,b}.ID_CHARS, [^ \t\r\n"!,]; ID is one such character, or a comma followed by one, or an escape (parser_lex.l:264-266).({MODES})/([[:space:],]) (parser_lex.l:843).# begins a comment at the start of a line, after a rule's comma and between the words of file and capability rules. It is not a comment inside a word (/a#b), inside ( ) lists, or inside rules such as signal, network, mount, dbus before their comma.
Run with the parser built from the AppArmor tree at 836052d21 (-Q -K --skip-kernel-load --warn=all, nothing loaded into a kernel):
/etc/demo/** r, # configuration); between the words of a file rule or a capability rule./etc/demo/a#b r, names the path /etc/demo/a#b.( ) list. flags=(complain # for now gives Invalid profile flag: #.signal send # why gives syntax error, unexpected TOK_ID, expecting TOK_CONDID or TOK_END_OF_RULE. The rules affected are network, signal, ptrace, dbus, unix, mount, change_profile, rlimit, mqueue, userns and abi.profile, hat, ^ or ->. profile #demo { } defines a profile named #demo.# is a comment and also ends the assignment: @{X} = /a /b # tail (run with the released parser 5.0.2).Lexer found unexpected character: '#' (0x23) in state: INITIAL.apparmor_parser -p (--preprocess, "Dump preprocessed profile") echoes comments to its output (parser_main.c:262, read from the source).#.*\r?\n exists in the scanner's INITIAL state (parser_lex.l:815-818) and in the two assignment states (parser_lex.l:576-580, parser_lex.l:735-739). The list state, SUB_ID (parser_lex.l:456-461) and the rule states have none.# is an ordinary word character: ID_CHARS does not exclude it (parser_lex.l:264). ID_FIRST_CHARS at parser_lex.l:262 does, but no other definition uses it.Invalid profile flag: %s. is at profile.h:261.#include <file> is an include (deprecated spelling; warning class pound-include, off by default). # include <file> and ##include <file> are comments.
#include <file>, with no blank after the hash, is an include. # include <file> and ##include <file> are comments (parser built from the AppArmor tree at 836052d21).Warning from FILE (FILE line N): deprecated use of '#include'.pound-include, "warn when #include is used" (parser_main.c:295). Turn it on with --warn=pound-include or --warn=all; it is not in the default set (parser.h:77-78). apparmor_parser --help=warn lists the classes./a r, #include <x> performs the include after the rule (run with the released parser 5.0.2).#include: a comment that begins #included by hand is read as an include of the file d and fails with Could not open 'd' (tree parser).#include if exists, include if exists, #include, include; the two with a hash call pwarn(WARN_INCLUDE, ...) (parser_lex.l:781-809). They precede the comment rule (parser_lex.l:815-818) and match the same length, so flex takes the earlier rule.INCLUDE and INCLUDE_EXISTS states (parser_lex.l:376-397).A { or } that stands alone delimits a body; bodies nest and take no trailing comma. Inside a word, {a,b} is a pattern. profile demo{ fails because the brace is read as part of the name.
{ or } that stands alone opens or closes a body. Bodies nest. No comma follows the closing brace.{a,b} is a pattern of alternatives, and its commas do not end the rule: /var/lib/demo/{cache,state}/** rw,.profile demo{ fails with syntax error, unexpected TOK_MODE, expecting TOK_OPEN: without a blank the brace is read as part of the name (parser built from the AppArmor tree at 836052d21, -Q -K --skip-kernel-load --warn=all).^HAT2 on one line and { /var/log/HAT2 rwl, } on the next.} gives syntax error, unexpected end of file, expecting TOK_ID or TOK_MODE or TOK_SET_VAR; one too many gives syntax error, unexpected TOK_CLOSE, expecting end of file.audit, deny and owner but not a priority: priority=1 { /a r, } gives priority is not allowed on rule blocks (block.h:46-52).open is accepted in place of {, as in profile demo /usr/bin/demo open (tree parser). There is no closing counterpart and no diagnostic.OPEN_BRACE and CLOSE_BRACE (parser_lex.l:249-250) return TOK_OPEN and TOK_CLOSE in the INITIAL state (parser_lex.l:834-836) and after if (parser_lex.l:725-727). Braces are not excluded from ID_CHARS (parser_lex.l:264), so inside a word they stay in the word.profile_base: ... TOK_OPEN rules TOK_CLOSE (parser_yacc.y:391-399); block: TOK_OPEN rules TOK_CLOSE (parser_yacc.y:738-759).convert_aaregex_to_pcre (parser_regex.c:282-330).Comment rule #.*\r?\n in INITIAL, ASSIGN_MODE, ASSIGN_EXPR_MODE only. #include rules precede it. {END_OF_RULE} pops rule-specific states. Known discrepancy: open yields TOK_OPEN, the token of {.
OPEN_BRACE, CLOSE_BRACE, END_OF_RULE (parser_lex.l:249-254); ID_FIRST_CHARS, ID_CHARS, ID, IDS (parser_lex.l:262-267).#.*\r?\n appears three times: INITIAL (parser_lex.l:815-818), ASSIGN_MODE (parser_lex.l:576-580) and ASSIGN_EXPR_MODE (parser_lex.l:735-739). In the assignment states it also calls POP().#include ones use trailing context /.*\r?\n, so their match is as long as the comment's and the earlier rule wins.get_keyword_token(yytext), then PUSH_AND_RETURN(state, token) with a rule-specific state (parser_lex.l:856-909). {END_OF_RULE} returns TOK_END_OF_RULE and pops when the state is not INITIAL (parser_lex.l:911-917).SUB_ID is absent from the white space rule's condition list (parser_lex.l:372-373); its only rule takes {IDS} or a quoted string and pops (parser_lex.l:456-461). A new line there reaches the catch-all Lexer found unexpected character: '%s' (0x%x) in state: %s (parser_lex.l:930).keyword_table (parser_misc.c:81-138) has {"open", TOK_OPEN} at parser_misc.c:131. TOK_OPEN is declared once (parser_yacc.y:82) and is also the open permission of mqueue rules (parser_yacc.y:1566).state_names[YY_START]; apparmor_parser -p prints what DUMP_PREPROCESS echoes.-p, --preprocess."missing an end of line character? (entry: PATH)" is a missing comma after the rule for PATH, reported at the next rule. In syntax errors TOK_END_OF_RULE is the comma, TOK_OPEN and TOK_CLOSE are braces.
Messages from the parser built from the AppArmor tree at 836052d21 (-Q -K --skip-kernel-load --warn=all). The full form is AppArmor parser error for FILE in profile FILE at line N: MESSAGE.
missing an end of line character? (entry: PATH). PATH is the rule that lacks the comma; the line is that of the next rule. File rules only: other rule classes give a generic syntax error.syntax error, unexpected TOK_CLOSE, expecting TOK_END_OF_RULE.@{X} = /a,: Variable declarations do not accept trailing commas.}: syntax error, unexpected end of file, expecting TOK_ID or TOK_MODE or TOK_SET_VAR. Fixture: simple_bad_no_close_brace1.sd.} too many: syntax error, unexpected TOK_CLOSE, expecting end of file.{: fixture simple_bad_no_opening_brace1.sd, expected result FAIL.TOK_END_OF_RULE is the comma, TOK_OPEN is {, TOK_CLOSE is }.Multiple definitions for profile NAME exist,bailing out. (parser_policy.c:60-66).file_rule_tail: opt_exec_mode id_or_var file_perms id_or_var calls yyerror(_("missing an end of line character? (entry: %s)"), $2) (parser_yacc.y:1132-1139).Inside words: syn-globbing, syn-quoting. Blocks: syn-qualifier-blocks, syn-hats. Includes: syn-include. Assignments: syn-variables. The scanner: fe-lexer.
, ends a rule, { } hold a body, # starts a comment to the end of the line.#include with no blank after the hash is an include, not a comment.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the fragment (-Q -K --skip-kernel-load --warn=all, nothing loaded into a kernel); "5.0.2" means the released parser 5.0.2 was run; "code" means the parser source was read, not run. Comments and line structure exist only in the parser: nothing of them reaches the kernel.
FILE: { PREAMBLE-LINE | PROFILE | COMMENT }
PROFILE: HEAD '{' BODY '}'
BODY: { RULE ',' | BLOCK | PROFILE | HAT | INCLUDE | COMMENT }
BLOCK: [ QUALIFIERS ] '{' BODY '}'
COMMENT: '#' text to the end of the line
| Construct | Ends with |
|---|---|
every rule (file, network, capability, mount, signal, change_profile and the others) | , |
abi <...>, and alias A -> B, in the preamble | , |
| a profile, a hat, a child profile | } with no comma after it |
a qualifier block (deny { }, audit { }) and an if block | } with no comma after it |
| a comment | the end of the line |
include and #include | the end of the line; no comma |
a variable assignment @{X} = ... and a boolean assignment ${X} = ... | the end of the line; a backslash directly before the new line continues it |
{ } block with no qualifier is accepted, and blocks nest: audit { deny { /x w, } } (tree).parser/tst/simple_tests/change_hat/new_style3.sd).| Character | Where it is structure | Where it is part of a word |
|---|---|---|
, | ends a rule when a blank, a new line or another , follows | when a word character follows directly: /etc/demo/a,b r, is one rule for the path /etc/demo/a,b (tree); inside {a,b} it separates alternatives; inside a quoted string ("/foobar," r,) |
{ } | standing alone: open and close a body | inside a word: a pattern of alternatives, see syn-globbing; profile demo{ reads the brace as part of the name |
# | starts a comment in ordinary rule text and in assignments | inside a word (/etc/demo/a#b); directly after profile, hat, ^ or ->; inside ( ) lists; inside the keyword rules listed under Comments |
| new line | ends a comment, an include line and an assignment | white space everywhere else; not accepted directly after profile, hat or ^ |
\r\n is accepted wherever \n is (parser/tst/simple_tests/file/dos_line_endings.sd). A carriage return that is not followed by a line feed is a lexer error (5.0.2).A # is a comment where the parser could start a new word:
| Place | Example | Result | Basis |
|---|---|---|---|
| the start of a line | # demo: a small network service | comment | tree |
| after a rule's comma | /etc/demo/** r, # configuration | comment | tree |
between the words of a file rule or a capability rule | capability # why then chown, on the next line | comment | tree |
| after a variable assignment | @{X} = /a /b # tail | comment; it also ends the assignment | tree |
| inside a word | /etc/demo/a#b r, | the path /etc/demo/a#b | tree |
inside a ( ) list | flags=(complain # for now | Invalid profile flag: #. | tree |
| inside a keyword rule, before its comma | signal send # why | syntax error | tree |
directly after profile, hat, ^, -> | profile #demo { } | a profile named #demo; known discrepancy, see below | tree |
network, signal, ptrace, dbus, unix, mount, change_profile, rlimit, mqueue, userns, abi. A comment after the comma of such a rule is fine.apparmor_parser -p (preprocess) echoes comments to its output (code).# Last Modified:, #=DESCRIPTION, #=EXRESULT) is a plain comment to it.The scanner tries these four patterns, in this order, before the comment pattern:
| Pattern | Meaning |
|---|---|
#include if exists FILE | include, old spelling |
include if exists FILE | include |
#include FILE | include, old spelling |
include FILE | include |
#include with no blank after the hash is an include, not a comment. Putting one hash in front of an include line does not switch it off.# include <file> and ##include <file> are comments (tree).Warning from FILE (FILE line N): deprecated use of '#include'. Its class is pound-include: turn it on with --warn=pound-include or --warn=all. It is not in the default set, and warnings are not printed with -N or -q./a r, #include <x> performs the include after the rule (tree).parser/tst/simple_tests/include_tests/ok_27.sd).include if exists <x>, is a syntax error (tree).if exists: syn-include. The warning options: adm-parser.Errors are printed as AppArmor parser error for FILE in profile FILE at line N: MESSAGE (tree). The line is where the parser noticed the problem, often one line after the mistake.
| Message | Cause |
|---|---|
missing an end of line character? (entry: PATH) | a missing comma between two file rules; PATH is the rule that lacks it; reported at the line of the next rule. File rules only: other rule classes give a generic syntax error |
syntax error, unexpected TOK_CLOSE, expecting TOK_END_OF_RULE | a missing comma on the last rule of a body |
syntax error, unexpected TOK_END_OF_RULE, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | a doubled comma: /etc/demo/** r,, |
syntax error, unexpected TOK_END_OF_RULE, expecting TOK_MODE | a comma right after a path: /etc/demo/c, r, (parser/tst/simple_tests/file/bad_comma_1.sd) |
syntax error, unexpected TOK_END_OF_RULE | a comma after an include line (5.0.2) |
Variable declarations do not accept trailing commas | @{X} = /a, |
syntax error, unexpected end of file, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | a missing } |
syntax error, unexpected TOK_CLOSE, expecting end of file | one } too many |
syntax error, unexpected TOK_MODE, expecting TOK_OPEN | no blank before {: profile demo{ |
Invalid profile flag: #. | a comment inside a flags=( ) list |
syntax error, unexpected TOK_ID, expecting TOK_CONDID or TOK_END_OF_RULE | a comment inside a signal rule |
Lexer found unexpected character: 'C' (0xNN) in state: STATE | a # on a last line that has no final new line; a new line directly after profile; a carriage return without a line feed |
priority is not allowed on rule blocks | priority=1 { /a r, } |
Multiple definitions for profile NAME exist,bailing out. | a second top-level profile of the same name; a body cannot be closed and continued later |
Could not open 'FILE' | an include, also one written as #include, names a file that is not found |
warning: deprecated use of '#include' | the old spelling, with --warn=pound-include |
In syntax errors TOK_END_OF_RULE is the comma, TOK_OPEN is { and TOK_CLOSE is }.
These are things the parser does that do not look like intended design. They are described as behaviour, not as features to rely on.
open is accepted in place of {: profile demo /usr/bin/demo open, a rule and } is accepted (tree). There is no closing counterpart, and no diagnostic. No valid profile changes meaning.#include has no word boundary: a comment that begins #included by hand is read as an include of the file d and fails with Could not open 'd' (tree).Lexer found unexpected character: '#' (0x23) in state: INITIAL (tree). By the pattern the same holds for a #include line (code).# after profile, hat, ^ and ->: profile #demo { } defines a profile named #demo (tree).| What | Where |
|---|---|
OPEN_BRACE, CLOSE_BRACE, END_OF_RULE definitions | parser/parser_lex.l:249-254 |
ID_CHARS, ID, IDS: a word excludes blank, tab, CR, LF, ", ! and ,; , followed by a word character is part of the word | parser/parser_lex.l:262-267 |
white space skipped, per start condition (SUB_ID is not in the list) | parser/parser_lex.l:372-373 |
INCLUDE, INCLUDE_EXISTS: the file name | parser/parser_lex.l:376-397 |
SUB_ID, SUB_ID_WS: the name after profile, hat, ^, -> | parser/parser_lex.l:456-461 |
ASSIGN_MODE: trailing comma error, comment with POP(), backslash continuation, new line with POP() | parser/parser_lex.l:570-588 |
EXPR_MODE: { after if | parser/parser_lex.l:725-727 |
ASSIGN_EXPR_MODE: comment, continuation, new line | parser/parser_lex.l:735-747 |
the four include patterns, with pwarn(WARN_INCLUDE, ...) | parser/parser_lex.l:781-809 |
the comment rule #.*\r?\n in INITIAL | parser/parser_lex.l:815-818 |
{ and } return TOK_OPEN and TOK_CLOSE | parser/parser_lex.l:834-836 |
| keyword lookup; rule keywords push their own start condition | parser/parser_lex.l:856-909 |
{END_OF_RULE} returns TOK_END_OF_RULE and pops a rule state | parser/parser_lex.l:911-917 |
| new lines counted | parser/parser_lex.l:919-924 |
Lexer found unexpected character | parser/parser_lex.l:930 |
keyword_table, with "open" mapped to TOK_OPEN | parser/parser_misc.c:81-138 (131) |
profile_base: TOK_OPEN rules TOK_CLOSE; the include cache is saved at { and restored at } | parser/parser_yacc.y:391-399, 453-455 |
block: TOK_OPEN rules TOK_CLOSE and its use with qualifiers | parser/parser_yacc.y:738-759 |
file_rule_tail: the "missing an end of line character?" production | parser/parser_yacc.y:1132-1139 |
Invalid profile flag | parser/profile.h:261 |
priority is not allowed on rule blocks | parser/block.h:46-52 |
Multiple definitions for profile | parser/parser_policy.c:60-66 |
warning class pound-include; the default warning set | parser/parser_main.c:295; parser/parser.h:77-78 |
#include patterns and the comment pattern both run to the end of the line, so the earlier #include rules win.INITIAL, ASSIGN_MODE and ASSIGN_EXPR_MODE only. LIST_VAL_MODE, SUB_ID and the rule states (NETWORK_MODE, SIGNAL_MODE and the others) have none.ID_FIRST_CHARS (parser/parser_lex.l:262) excludes # but no other definition uses it; ID_FIRST is built from ID_CHARS. This is why a name may begin with #.TOK_OPEN is also the open permission of mqueue rules (parser/parser_yacc.y:1566); in MQUEUE_MODE the scanner has its own rule for the word, so the keyword_table entry only has an effect in INITIAL.A dbus rule describes D-Bus messages: bus, object path, interface, member and peer. Socket rules only reach the bus daemon.
/sys/kernel/security/apparmor/.access (apparmorfs.c:879-897)./sys/kernel/security/apparmor/features/dbus/mask contains acquire send receive (apparmorfs.c:2662-2665).org.freedesktop.secrets and org.freedesktop.login1 stand for other services on a bus. org.demo, its interface and the member Status are invented for the map.[QUALIFIERS] dbus [send|receive|bind|eavesdrop] [bus= path= interface= member= name=] [peer=(name= label=)],.
audit, allow, deny, prompt and priority= are taken (audit deny dbus send bus=session,, prompt dbus send, and priority=5 dbus send, are accepted by the parser built from the tree). owner is refused: owner prefix not allowed on dbus rules (dbus.h:54-58).path are collapsed (dbus.cc:176-199).dbus (), is accepted and means all permissions. A second permission word outside parentheses, or a permission after a conditional, is a syntax error. Upper-case RW is not accepted.0x2, receive 0x4, eavesdrop 0x20, bind 0x40 (apparmor.h:60-65).DBUS_MODE (parser_lex.l:650-695, parser_lex.l:881-882).dbus_rule constructor and its validation: dbus.cc:39-121.Message rules (path, interface, member, peer=( )) take send and receive. Service rules (name=) take bind. Eavesdrop rules take only bus=.
dbus rule contains message conditionals and service conditionals (dbus.cc:94), dbus "bind" access cannot be used with message rule conditionals (dbus.cc:102), dbus "send" and/or "receive" accesses cannot be used with service rule conditionals (dbus.cc:104), dbus "eavesdrop" access can only contain a bus conditional (dbus.cc:108).bus= alone belongs to no kind: dbus (bind send) bus=session, is accepted and becomes a bind part and a send part.dbus name=(SomeService), is an implicit bind (ok_bind_1.sd). Other test files: ok_eavesdrop_1.sd, bad_bind_2.sd.bus, path, interface, member and peer=(name= label=) each match one property of the message. A conditional left out matches anything.
name= means the peer's name inside the group and the name the profile may own outside it. A rule cannot have both: dbus conditional "name" can only be specified once.label is only valid inside the group: dbus "label" conditional can only be used inside of the "peer=()" grouping.dbus send bus=session path=/org/a interface=org.a member=Foo peer=(name=org.b label=unconfined),.bind); it is not a finding about a bus daemon. What a daemon puts into its query is in neither source tree: the card on the slide is the message, not the query. It was since run for D-Bus mediation: dbus-daemon 1.16 puts the destination into the query as the caller wrote it, so peer=(name=org.demo) matched a call addressed to org.demo and did not match the same call addressed to the owner's unique name (:1.11). peer=(label=...) does not depend on how the caller addressed the message.bus, path, interface and member are also accepted inside peer=( ) and are stored as if written outside (dbus send bus=session peer=(path=/x),); apparmor.d(5) documents only name and label there (dbus.cc:77-84, apparmor.d.pod:342).dbus bind bus=B name=N, allows owning the name N. dbus eavesdrop bus=B, allows receiving other programs' messages. The feature file's acquire is written bind.
dbus acquire bus=session name=org.demo, gives syntax error, unexpected TOK_ID, expecting TOK_END_OF_RULE. The word acquire is the kernel's, in the feature file features/dbus/mask (apparmorfs.c:2662-2665).dbus bind eavesdrop, is a syntax error: two permission words need parentheses.RequestName is the D-Bus call by which a program asks for a name. Neither source tree contains a bus daemon: the slide shows what the rule allows, not how a daemon decides.dbus bind bus=system name=org.a, gives \x20system\x00org\.a with 0x40; dbus eavesdrop bus=session, gives \x20session with 0x20.dbus.cc:206-315 emits up to three rules under class 32 (\x20); apparmorfs.c:879-897 answers queries on .access. Enforcement is in the bus daemon.
-D rule-exprs: \x20session\x00org\.demo\x00[^\000]*\x00/org/demo\x00org\.demo\.Api\x00[^\000]* with 0x2.\d32 is added at priority 1001 for every confined profile when dbus is supported (parser_regex.c:1406-1408). Rules are merged by their six strings (dbus.h:67-89).dbus in the feature set the rule is dropped, with the warning dbus rules not enforced, which is off by default (dbus.cc:203, dbus.cc:220-223).aa_write_access takes the commands label\0, profile\0 and labelall\0 (apparmorfs.c:1174-1231). The reply carries the allow, deny, audit and quiet masks (apparmorfs.c:1022-1071). profile_query_cb: apparmorfs.c:879-897.aa_query_label (kernel.c:1425-1510).network_v9 (the tree's abi/3.0 and abi/4.0). A profile pinned to one of those and loaded on a mainline kernel from 6.17 has dbus rules that are not applied to queries. This was run for D-Bus mediation: on Debian sid (kernel 7.3.4, dbus-daemon 1.16.4) profiles with abi <abi/3.0>, and abi <abi/4.0>, got the reply allow 0xffffffff deny 0x00000000 audit 0x00000000 quiet 0xffffffff to every dbus question, their calls were delivered and nothing was logged; the same profile with abi <abi/5.0>, was refused and logged. On Ubuntu 26.04 (kernel 7.0.0-43), which does not have the kernel test, all three were enforced. A profile with no abi rule behaves like abi/4.0 here unless parser.conf sets policy-features to a feature file with network_v9.peer=(name=...) is as strong as the bind rules of every other profile on that bus, and unconfined programs are not bound by them. peer=(label=...) names the confinement instead.peer=( ) (dbus.cc:77-84).bind, not acquire; label inside peer=( ); one name per rule; one value per conditional.
-Q -K --skip-kernel-load --warn=all, nothing loaded into a kernel). The full form is AppArmor parser error for FILE in profile FILE at line N: MESSAGE.only "=" allowed in conditions of dbus rules (dbus.cc:46), invalid dbus conditional "%s" (dbus.cc:64), perms contains unknown dbus access (dbus.cc:100), dbus rule: invalid conditional group %s=(), owner prefix not allowed on dbus rules (dbus.h:54-58).dbus rules not enforced is printed when the feature set has no dbus; it needs --warn=rule-not-enforced.dbus rule: invalid conditional group %s=(): parser_yacc.y:1346.Grammar here; enforcement and denials in the D-Bus mediation deck.
send and receive; service rules (name=) take bind; eavesdrop rules take only bus=.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the line (-Q -K --skip-kernel-load --warn=all, feature set abi/5.0), with nothing loaded into a kernel; "code" means the source was read, not run. This page covers the grammar and the compiled form. Enforcement by the bus daemon, with runs on three guests, is in D-Bus mediation.
DBUS RULE: [QUALIFIERS] dbus [PERMISSIONS] [CONDITIONAL ...] [peer=( [name=PATTERN] [label=PATTERN] )] ,
PERMISSIONS: PERMISSION | ( PERMISSION [,] ... )
PERMISSION: send | receive | bind | eavesdrop
write and w are send; read and r are receive; rw and wr are both
CONDITIONAL: bus=PATTERN | path=PATTERN | interface=PATTERN | member=PATTERN | name=PATTERN
dbus (), means all permissions (tree).| Conditional | Where | Meaning | Makes the rule a |
|---|---|---|---|
bus | outside the group | the bus: session, system or another name | no kind by itself |
path | outside | the object path | message rule |
interface | outside | the interface | message rule |
member | outside | the method or signal name | message rule |
name | outside | the name the profile may own | service rule |
name | inside peer=( ) | the peer's bus name | message rule |
label | inside peer=( ) only | the peer's AppArmor label | message rule |
Every conditional takes one value and only =. Values are patterns. A conditional that is left out matches anything.
| Kind | Conditionals | Permissions | Without a written permission | Wrong mix |
|---|---|---|---|---|
| message | bus, path, interface, member, peer=(name label) | send, receive | send receive | dbus "bind" access cannot be used with message rule conditionals |
| service | bus, name | bind | bind | dbus "send" and/or "receive" accesses cannot be used with service rule conditionals |
| eavesdrop | bus | eavesdrop | - | dbus "eavesdrop" access can only contain a bus conditional |
none of these (dbus, or bus= only) | bus | any | all four | - |
A rule with message conditionals and a name outside the group: dbus rule contains message conditionals and service conditionals.
| Seat | On a dbus rule |
|---|---|
priority= | taken |
audit | taken |
allow, deny, prompt | taken |
owner, other | refused: owner prefix not allowed on dbus rules |
dbus (the kernel file features/dbus/mask contains acquire send receive). Otherwise the rule is dropped and, with --warn=rule-not-enforced, the parser prints dbus rules not enforced.network_v9/af_unix. Run for D-Bus mediation: on Debian sid (kernel 7.3.4) the dbus rules of profiles compiled under abi/3.0 and abi/4.0 were not consulted (every question answered allow 0xffffffff, nothing logged); under abi/5.0 they were. Ubuntu kernels do not have the test: on Ubuntu 26.04 (kernel 7.0.0-43) all three were enforced.| Line | Message |
|---|---|
dbus acquire bus=session name=org.demo, | syntax error, unexpected TOK_ID, expecting TOK_END_OF_RULE |
dbus send bus=session label=demo-helper, | dbus "label" conditional can only be used inside of the "peer=()" grouping |
dbus send bus=session name=org.demo peer=(name=org.x), | dbus conditional "name" can only be specified once |
dbus send bus=(session system), | dbus conditional "bus" only supports a single value |
dbus bind eavesdrop, | syntax error, unexpected TOK_EAVESDROP, expecting TOK_END_OF_RULE |
dbus bind bus=session interface=org.demo.Api, | dbus "bind" access cannot be used with message rule conditionals |
owner dbus send, | owner prefix not allowed on dbus rules |
an operator other than = | only "=" allowed in conditions of dbus rules |
| an unknown conditional | invalid dbus conditional "NAME" |
a group other than peer | dbus rule: invalid conditional group NAME=() |
feature set without dbus (warning, off by default) | dbus rules not enforced |
\x20 and bus, name, peer label, path, interface, member. A missing field is [^\000]* (dbus.cc:206-315).0x2, receive 0x4, eavesdrop 0x20, bind 0x40 (apparmor.h:60-65).\d32 at priority 1001 (parser_regex.c:1406-1408).aa_write_access (apparmorfs.c:1174-1231), profile_query_cb (apparmorfs.c:879-897), the reply (apparmorfs.c:1022-1071). libapparmor: aa_query_label (kernel.c:1425-1510).bus, path, interface and member are accepted inside peer=( ) and stored as if written outside (tree; dbus.cc:77-84). The verdict is in known bugs.eavesdrop and bind queries are formed, which label it queries). Only the parser's encoding and the kernel's reply are covered.An exec rule is a file rule whose mode ends in x. The letters before the x choose the profile of the new program.
Kernel facts are from the kernel source, read and not run.
bprm_creds_for_exec, implemented by apparmor_bprm_creds_for_exec (domain.c:985, registered at lsm.c:1862). It runs during execve, once per profile of the task's label.MAY_EXEC (domain.c:725-729). Without it the exec fails with EACCES.ix), a profile found by the executable's path (px), a child (cx), or unconfined (ux).exec (audit.h:92); a record carries requested_mask="x" and, when a profile was chosen, target=. Example fixture: exec01.in:1.EXEC MODE = [p|P|c|C] [i|u|U] x. Basic: ix px cx ux. With fallback: pix cix pux cux. An uppercase first letter is the safe form.
EXEC MODE = [ 'p' | 'P' | 'c' | 'C' ] [ 'i' | 'u' | 'U' ] 'x'. The scanner's pattern: (([Pp]|[Cc])[Xx])|(([Pp]|[Cc])?([IiUu])[Xx]) (parser_lex.l:257).ix, ux Ux, px Px, cx Cx, pix Pix, cix Cix, pux PUx, cux CUx.pIx, PIx and Pux are accepted (parser tests and the released parser 5.0.2).ix has no safe form. Ix is read as ix with the deprecation warning for uppercase letters (parser_misc.c:616-626). There is no uix: it is a syntax error (5.0.2)./usr/bin/sort rix,.x alone is written only in deny rules: deny /usr/bin/demo-helper x, (parser_misc.c:1090-1104).parser/tst/simple_tests/xtrans/, for example simple_ok_pix_1.sd.-> name after the mode.ix runs the program under the current profile and implies m. ux runs it unconfined; lowercase ux draws a warning with --warn=dangerous.
Kernel facts are from the kernel source, read and not run.
ix and ux have no lookup step (domain.c:588-591). The fallback step then applies: inherit takes the newest version of the current profile's label with info="ix fallback"; unconfined takes the unconfined label of the namespace of the profile that holds the rule with info="ux fallback" (domain.c:617-637).ix never requests secure execution: there is no safe form of ix. See safe and unsafe.ux prints a parser warning: Unconfined exec qualifier (ux) allows some dangerous environment variables to be passed to the unconfined process; 'man 5 apparmor.d' for details. (parser_misc.c:628-632).dangerous (parser_main.c:289), off by default: apparmor_parser --warn=dangerous or --warn=all. Lowercase pux and cux do not print it.ux rule becomes unconfined: stacking.ux and Ux remove confinement for the new program and everything it starts. pux, cux and their uppercase forms do the same whenever no profile attaches: the fallback is taken without an error, and the reason string ux fallback is passed to the audit call of the exec, which for an allowed exec writes a record only when the permission is audited (domain.c:616-638, domain.c:787-790; read from the kernel source, not observed on a running kernel).ux only, and only with --warn=dangerous or --warn=all. Lowercase pux and cux, which also pass the environment to a possibly unconfined program, print nothing (run with the parser built from the AppArmor tree at 836052d21, nothing loaded into a kernel; parser_misc.c:628-632).ix keeps the profile, so every program reachable through an ix rule runs with the caller's permissions. An ix rule on a shell or an interpreter gives every script the task can supply the whole profile.*, ? or [^...] overrides patterns that match the same name, and priority= overrides both (aare_rules.cc:98-105). Braces and plain sets count as exact; see the reference below.px and cx is by the path of the executable at exec time; a target that is missing fails the exec in enforce mode but creates a learning profile in complain mode (domain.c:740-767).ix implies m on the same path: add_implied_ix_mmap (hfa.cc:1497-1524).ix result profile_transition jumps to the audit step and skips the AA_X_UNSAFE test (domain.c:730-739).px switches to the profile that attaches to the executable's path and fails with "profile transition not found" when none does.
Kernel facts are from the kernel source, read and not run.
px runs the attachment search find_attach over the top-level profiles of the namespace of the profile that holds the rule, with the path of the executable (domain.c:603-612; find_attach is domain.c:394-507)./usr/bin/* Px, resolves each program separately.info="profile transition not found", the exec permission is removed from the result and the exec fails with EACCES (domain.c:740-754).PARENT//null-PATH is created and the exec continues under it (domain.c:749-766). Fixture record with target="/home/cb/bin/hello.sh//null-/usr/bin/rm": exec01.in:1.conflicting profile attachments, the record says profile transition not found (domain.c:33-37).px rule.AA_X_NAME in dfa_map_xindex (policy_compat.c:38-39).cx searches only the children of the current profile. A child named after the executable matches; a child with a plain name needs cx -> name.
Kernel facts are from the kernel source, read and not run.
cx runs the same attachment search as px, over the children of the profile that holds the rule instead of the namespace's profiles (domain.c:604-607).worker, attaches to nothing and needs cx -> worker: named transitions.px, info="profile transition not found" and EACCES, or a learning profile in complain mode./bin/foo Cx, with no such child and is expected to pass. The same file names its children after paths: profile /bin/cat { ... }.AA_X_NAME | AA_X_CHILD in dfa_map_xindex (policy_compat.c:40-41).pix/cix: use the attaching profile or child, else inherit. pux/cux: else run unconfined. Without a fallback letter a failed search refuses the exec.
Kernel facts are from the kernel source, read and not run.
info="ix fallback", unconfined gives the namespace's unconfined label with info="ux fallback" (domain.c:616-638). Inherit is tested first.conflicting profile attachments - ix fallback and conflicting profile attachments - ux fallback (domain.c:33-37), and a record is forced (domain.c:730-739).profile transition not found, EACCES.Pix and Cix. For pux and cux the case of the first letter decides: safe and unsafe.pix, cix, pux, cux in the list of modes.dfa_map_xindex (linux:security/apparmor/policy_compat.c:24-48) maps the parser's bits; x_to_label (linux:security/apparmor/domain.c:574-663) does lookup then fallback.
AA_MAY_EXEC 0x1, AA_EXEC_PUX 0x80, AA_EXEC_UNSAFE 0x100, AA_EXEC_INHERIT 0x200, type in bits 10 to 13. Types: AA_EXEC_UNCONFINED 1, AA_EXEC_PROFILE 2, AA_EXEC_LOCAL 3 (immunix.h:80-82); values 4 to 15 are table slots, AA_EXEC_COUNT is 16 (immunix.h:70).parse_sub_perms sets them: ix at parser_misc.c:616-626, ux and Ux at parser_misc.c:628-647, px, cx and the fallback forms at parser_misc.c:649-688.dfa_map_xindex maps 0x100 to AA_X_UNSAFE, 0x200 to AA_X_INHERIT, 0x80 and type 1 to AA_X_UNCONFINED, type 2 to AA_X_NAME, type 3 to AA_X_NAME | AA_X_CHILD, a higher type to AA_X_TABLE | (type - 4) (policy_compat.c:24-48). The values of the AA_X_ constants: file.h:54-64.apparmor_bprm_creds_for_exec calls profile_transition for each profile of the label, then applies the no_new_privs and ptrace tests and sets bprm->secureexec (domain.c:985-1108).profile_transition: aa_path_name, aa_str_perms, the MAY_EXEC test, x_to_label, "profile transition not found", the learning profile, the AA_X_UNSAFE test (domain.c:665-796).x_to_label: a switch on the type (AA_X_NONE, AA_X_TABLE, AA_X_NAME), then the fallback, AA_X_INHERIT before AA_X_UNCONFINED (domain.c:574-663).ix and plain ux have type AA_X_NONE: no lookup, then the fallback branch."has merged rule ... with conflicting x modifiers" means two rules give one path two exec modes. A path with no *, ? or [^...] overrides one that has them. In deny rules write a bare x.
Messages of the parser built from the AppArmor tree at 836052d21, nothing loaded into a kernel.
/usr/bin/demo-helper pxix,: Exec qualifier 'i' invalid, conflicting qualifier already specified (parser_misc.c:619). For the other letters the message names the letter or the pair./usr/bin/demo-helper Px, and /usr/bin/demo-helper px,: profile demo: has merged rule /usr/bin/demo-helper with conflicting x modifiers (block_rules.cc:322-327)./usr/bin/demo-* Px, and /usr/bin/* ix,: profile has merged rule with conflicting x modifiers, then ERROR processing regexs for profile demo, failed to load. No path and no line number.px against Px on one path is a conflict (immunix.h:171-186). The owner half and the other half are compared separately.*, **, ? or [^...] overrides patterns that match the same path. Braces and plain sets still count as exact: /usr/bin/{demo-helper,x} Px, with /usr/bin/* ix, is accepted, /usr/bin/demo-? Px, conflicts (run with the parser built from the tree at 836052d21). Tests: minimize-x-conflict.sd passes, x-conflict.sd fails.priority=: priority.deny /a px, gives Invalid perms, in deny rules 'x' must not be preceded by exec qualifier 'i', 'p', or 'u'; deny /a x, is accepted (parser_misc.c:1090-1104).px and Px differ.IS_DIFF_QUAL, which compares AA_EXEC_TYPE (parser_misc.c:563).Next: syn-safe-unsafe (letter case), syn-named-transitions (-> name), attachment (the search behind px), k-exec (the kernel hook).
ix: keep the current profile. ux: unconfined. px: the profile that attaches to the executable's path. cx: the same search over the children of the current profile.pix, cix, pux, cux: search, then fall back to inherit or unconfined. Without a fallback letter an empty search fails the exec with profile transition not found.no_new_privs set gets EPERM and info="no new privs" unless the new label is a subset of the label held when the flag was set (domain.c:1050-1056).Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the fragment, with the tree's abi/5.0 file as the kernel features and nothing loaded into a kernel; "code" means the kernel source of mainline Linux 7.4 (7.4-rc2, 97d73c825) or the parser source was read, not run; "fixture" means a parser test in parser/tst/simple_tests/ asserts it. Nothing here was run against a kernel: every statement about what happens at exec is from the kernel source.
EXEC MODE: [ 'p' | 'P' | 'c' | 'C' ] [ 'i' | 'u' | 'U' ] 'x' lexer: (([Pp]|[Cc])[Xx])|(([Pp]|[Cc])?([IiUu])[Xx])
ix, ux Ux, px Px, cx Cx, pix Pix, cix Cix, pux PUx, cux CUx.pIx, PIx and Pux are accepted (fixture, tree).ix has no safe form. Ix is accepted as ix with the deprecation warning for uppercase letters (code).uix: it is a syntax error (tree)./usr/bin/sort rix,. See syn-access-modes.x alone is written only in deny rules: deny /usr/bin/demo-helper x,. See syn-allow-deny.-> name after the mode names the target profile: syn-named-transitions.| Mode | Search | When nothing is found | Environment |
|---|---|---|---|
ix | none | not applicable: the current profile is kept | not scrubbed |
ux / Ux | none | not applicable: the unconfined label of the profile's namespace | lowercase passes it on; uppercase scrubs |
px / Px | top-level profiles of the current namespace, by the path of the executable | the exec fails | by letter case |
cx / Cx | children of the profile that holds the rule, by the path of the executable | the exec fails | by letter case |
pix / Pix | as px | inherit, as ix | not scrubbed after the fallback |
cix / Cix | as cx | inherit, as ix | not scrubbed after the fallback |
pux / PUx | as px | unconfined, as ux | by the case of the first letter |
cux / CUx | as cx | unconfined, as ux | by the case of the first letter |
/usr/bin/* Px, resolves each program separately.px does not consider child profiles or hats. cx considers only the children of the profile holding the rule; a child matches when its name is the executable's path or its attachment matches it. A child with a plain name needs cx -> name. See syn-child-profiles.px or cx rule (fixture: xtrans/simple_ok_cx_1.sd has /bin/foo Cx, and no such child).ix also grants m on the same path (code).execve is not tested against the profile (code).EACCES.px or cx and no result the exec fails with EACCES and info="profile transition not found".PARENT//null-PATH is created and the exec continues under it (code).ix (code).no_new_privs: after the new label is chosen, an exec from a confined task that has no_new_privs set fails with EPERM and info="no new privs" unless the new label is a subset of the label held when the flag was set (code). See k-exec.ux only the member whose profile has the rule becomes unconfined. See stacking.info= | When | Result |
|---|---|---|
profile transition not found | px or cx found no profile, or two profiles attached equally well | EACCES; a learning profile in complain mode |
ix fallback | plain ix, or pix/cix after an empty search | the exec continues under the current profile |
ux fallback | plain ux, or pux/cux after an empty search | the exec continues unconfined |
conflicting profile attachments | two profiles attached equally well; under px and cx this text goes only to the kernel log and the record says profile transition not found | see the first row |
conflicting profile attachments - ix fallback | the same tie under pix or cix | the exec continues under the current profile and is audited |
conflicting profile attachments - ux fallback | the same tie under pux or cux | the exec continues unconfined and is audited |
no new privs | the task has no_new_privs and the new label is not a subset | EPERM |
libraries/libapparmor/testsuite/test_multi/exec01.in:apparmor="ALLOWED" operation="exec" profile="/home/cb/bin/hello.sh" name="/usr/bin/rm" pid=13108 comm="hello.sh" requested_mask="x" denied_mask="x" fsuid=1000 ouid=0 target="/home/cb/bin/hello.sh//null-/usr/bin/rm"
One path may have one exec mode. The parser tests this in three places.
| Where | Example | Message |
|---|---|---|
| inside one mode word | /usr/bin/demo-helper pxix, | Exec qualifier 'i' invalid, conflicting qualifier already specified |
| two rules with the same path text | /usr/bin/demo-helper Px, and /usr/bin/demo-helper px, | profile demo: has merged rule /usr/bin/demo-helper with conflicting x modifiers |
| two overlapping patterns | /usr/bin/demo-* Px, and /usr/bin/* ix, | profile has merged rule with conflicting x modifiers, then ERROR processing regexs for profile demo, failed to load |
px against Px on one path is a conflict.*, **, ? or [^...] overrides patterns that also match that path. Braces and plain sets still count as exact: /usr/bin/{demo-helper,x} Px, and /usr/bin/demo-[ab] Px, with /usr/bin/* ix, are accepted, /usr/bin/demo-? Px, conflicts (tree; parser/libapparmor_re/aare_rules.cc:98-105). /usr/bin/demo-helper Px, with /usr/bin/* ix, is accepted (tree; fixtures xtrans/minimize-x-conflict.sd passes and xtrans/x-conflict.sd fails).priority= replaces the mode of the lower one (code). See syn-priority.owner half and the other half of a rule are compared separately (code)./a pixpix, is accepted, tree), and two rules naming the same target profile.The full form of a parser error is AppArmor parser error for FILE in profile FILE at line N: MESSAGE. Errors from the later compile stage carry no line number.
| Message | Cause |
|---|---|
Exec qualifier 'i' invalid, conflicting qualifier already specified | a second exec mode in one mode word, as in pxix |
Exec qualifier '%c' invalid, conflicting qualifier already specified | the same for u, U, p, P, c, C, as in pxPx |
Exec qualifier '%c%c' invalid, conflicting qualifier already specified | the same for a fallback mode |
profile %s: has merged rule %s with conflicting x modifiers | two rules with the same path and different exec modes |
profile has merged rule with conflicting x modifiers | two overlapping patterns with different exec modes; the message names neither |
Invalid perms, 'x' must be preceded by exec qualifier 'i', 'p', or 'u' | a bare x in a rule that is not a deny rule, as in /bin/ls rx, |
Invalid perms, in deny rules 'x' must not be preceded by exec qualifier 'i', 'p', or 'u' | an exec mode in a deny rule, as in deny /a px, |
Unconfined exec qualifier (ux) allows some dangerous environment variables to be passed to the unconfined process; 'man 5 apparmor.d' for details. | warning for a lowercase ux; class dangerous, off by default (--warn=dangerous or --warn=all). Lowercase pux and cux do not print it |
Uppercase qualifiers "RWLIMX" are deprecated, please convert to lowercase | warning for Ix or a capital X; once per run |
| a syntax error | a combination outside the grammar, such as uix |
'i', 'p', or 'u' and omit c, although cx is equally valid.x is valid with a named target. The parser rejects /a x -> b, with the first "Invalid perms" message (tree).unsafe /a ix, together with /a ix, fails with "has merged rule /a with conflicting x modifiers" (tree), although the kernel does not look at the unsafe bit for ix.Parser bits per half, the other half shifted left by 14 (parser/immunix.h:35-48, 70, 80-82):
| Name | Value |
|---|---|
AA_MAY_EXEC | 0x1 |
AA_EXEC_PUX | 0x80 |
AA_EXEC_UNSAFE | 0x100 |
AA_EXEC_INHERIT | 0x200 |
| type, bits 10 to 13 | AA_EXEC_UNCONFINED 1, AA_EXEC_PROFILE 2, AA_EXEC_LOCAL 3, table slots 4 to 15 |
AA_EXEC_COUNT | 16 |
| Mode | Bits set (parser/parser_misc.c) | Kernel xindex (linux:security/apparmor/policy_compat.c:24-48) | |
|---|---|---|---|
ix | inherit (616-626) | AA_X_INHERIT | |
ux / Ux | type 1, unsafe for u (628-647) | AA_X_UNCONFINED (+ AA_X_UNSAFE) | |
px / Px | type 2, unsafe for p (649-687) | AA_X_NAME (+ AA_X_UNSAFE) | |
cx / Cx | type 3, unsafe for c (649-687) | `AA_X_NAME \ | AA_X_CHILD (+ AA_X_UNSAFE`) |
pix Pix cix Cix | as px or cx plus inherit (660-667) | as px or cx plus AA_X_INHERIT | |
pux PUx cux CUx | as px or cx plus pux (668-675) | as px or cx plus AA_X_UNCONFINED | |
any mode with -> name | type replaced by a table slot 4 to 15 (parser/block_rules.cc:581-596) | `AA_X_TABLE \ | (slot - 4)` |
| Step | Where |
|---|---|
lexer pattern for exec modes in MODE_CHARS | parser/parser_lex.l:257 |
parse_sub_perms: letters to bits; IS_DIFF_QUAL compares AA_EXEC_TYPE within one word | parser/parser_misc.c:563, 616-701 |
check_x_qualifier: bare x only in deny rules | parser/parser_misc.c:1090-1104 |
merge_file with is_merged_x_consistent: same path text | parser/block_rules.cc:322-327; parser/immunix.h:171-187 |
| conflict between overlapping patterns in one DFA state; exact match and priority | parser/libapparmor_re/hfa.cc:1549-1582, 1604-1637, 1703-1706; parser/libapparmor_re/aare_rules.cc:98-105 |
ix implies m | parser/libapparmor_re/hfa.cc:1497-1524 |
dfa_map_xindex | linux:security/apparmor/policy_compat.c:24-48 |
apparmor_bprm_creds_for_exec: one profile_transition per profile of the label, then no_new_privs and ptrace tests | linux:security/apparmor/domain.c:985-1108 |
profile_transition: name, aa_str_perms, MAY_EXEC, x_to_label, "profile transition not found", learning profile, AA_X_UNSAFE test | linux:security/apparmor/domain.c:665-784 |
x_to_label: switch on the type, then the ix and ux fallbacks | linux:security/apparmor/domain.c:574-663 |
find_attach | linux:security/apparmor/domain.c:394-507 |
| the open during exec is skipped | linux:security/apparmor/lsm.c:475-485 |
ix and plain ux have type AA_X_NONE: no lookup, then the fallback branch. AA_X_INHERIT is tested before AA_X_UNCONFINED.ix result profile_transition jumps to the audit step and skips the AA_X_UNSAFE test, so an ix exec does not request AT_SECURE.parser/tst/simple_tests/xtrans/, parser/tst/simple_tests/file/front_perms_ok_1.sd.A file rule is PATH MODE,: a path pattern and permission letters. A request with no matching rule is refused.
PATH MODE, as in /etc/demo/** r,: a path pattern, permission letters, a comma. The man page's grammar line for FILE RULE is at apparmor.d.pod:397.file_open, implemented by apparmor_file_open (lsm.c:1808, lsm.c:465), which calls aa_path_perm with the operation open.-EACCES (file.c:244-247).apparmor="DENIED" operation="open" profile="/usr/sbin/cupsd" name="/boot/" pid=19651 comm="ls" requested_mask="r" denied_mask="r" fsuid=0 ouid=0.demo, its files and its profile are invented for the map. Nothing on this slide was observed on a running kernel.frule: id_or_var file_perms opt_named_transition TOK_END_OF_RULE (parser_yacc.y:1072).[QUALIFIERS] [file] [safe|unsafe] (PATH MODE | MODE [subset] PATH) [-> TARGET],. The order of the parts is fixed. A path starts with / or a variable, or is quoted.
[QUALIFIERS] [file] [safe|unsafe] ( PATH MODE | MODE [subset] PATH ) [-> TARGET] , with QUALIFIERS being [priority=N] [audit] [allow|deny|prompt] [owner|other]. The order of the slots is fixed.FILE RULE = [ QUALIFIERS ] [ 'owner' ] ( 'file' | [ 'file' ] ( FILEGLOB ACCESS | ACCESS FILEGLOB ) [ '->' EXEC TARGET ] ) (apparmor.d.pod:397) and ACCESS = ( 'r' | 'w' | 'a' | 'l' | 'k' | 'm' | EXEC TRANSITION )+ (apparmor.d.pod:408).PATH starts with / or a variable @{...}, or is a quoted string (apparmor.d.pod:399-403).MODE is one word of permission letters, followed by white space or a comma.-Q -K --skip-kernel-load --warn=all, nothing loaded into a kernel): file /a r,, file r /a,, file /a px -> b,, file safe /a px,, file unsafe px /a,, file l /a -> /b,, deny file /a w,, audit deny owner /a rw,.safe or unsafe on a rule with no exec letters: unsafe rule missing exec permissions.file is a reserved word only in rule position; /etc/file r, is an ordinary rule (read from the source).opt_prefix: opt_priority opt_audit_flag opt_rule_mode opt_owner_flag (parser_yacc.y:705-711).opt_exec_mode, opt_file and the first frule (parser_yacc.y:1065-1072); the letters-first frule (parser_yacc.y:1085); file_rule: ... | opt_file file_rule_tail (parser_yacc.y:1114) and file_rule_tail: opt_exec_mode frule (parser_yacc.y:1117).LABEL: /, a variable, : or &, then word characters (parser_lex.l:301). The keyword table maps file to TOK_FILE (parser_misc.c:108)./etc/demo/** r, and r /etc/demo/**, are the same rule. Rules with identical path text are merged by adding their permissions.
/etc/demo/** r, and r /etc/demo/**, build the same rule (read from the source).r /foo1,, w /foo1,, px /foo1, and more, expected result PASS./a px -> b, and px /a -> b, (parser built from the AppArmor tree at 836052d21). px -> b /a, gives syntax error, unexpected TOK_ARROW, expecting TOK_ID or TOK_SET_VAR.subset exists in the letters-first form only and only with l: r subset /a, gives subset can only be used with link rules./a r, and /a w, are /a rw,. Exec modes that disagree stop the parser: profile NAME: has merged rule PATH with conflicting x modifiers.l with an exec letter and an arrow: path first gives the warning ambiguous rule specifies both link target and exec transition target. Using as exec transition (class deprecated, off by default); letters first gives the error link and exec perms conflict on a file rule using ->.subset and link checks. Both call do_file_rule.block_rules::merge_file sorts the entries and ORs the permissions of equal ones at block_rules.cc:329 (the function: block_rules.cc:285-343).The kernel matches the full name against the profile and refuses with EACCES when a requested permission is not allowed. Directory names end in /.
All statements are from the kernel source, read and not run.
file_open for an open, file_permission for later reads and writes on the open file, and the path_* hooks (path_unlink, path_mkdir, path_rename, path_chmod and others) for operations on names (lsm.c:1796-1816).aa_path_perm(op, subj_cred, label, path, flags, request, cond) runs the check once for each confined profile in the task's label (file.c:287-309).aa_str_perms walks the profile's file DFA over the name and looks up the permissions for the task's fsuid (file.c:221-231).if (request & ~perms->allow) e = -EACCES; (file.c:244-247). The result goes to aa_audit_file, which writes the log record./ before matching, except the root (path.c:167-177). /etc/demo/ r, matches the directory itself; /etc/demo r, does not.path_max bytes, by default twice PATH_MAX; readable by root in /sys/module/apparmor/parameters/path_max (lsm.c:1998-1999).fsuid= and ouid=.file, equals the path /{**,} with rwalkm and ix. owner file, keeps the owner half only.
file, is rewritten by the parser to the path /{**,} with the letters rwalkm and the exec mode ix, for the owner half and the other half (read from the source).-D rule-exprs) the path is /([^\x00]*|): / followed by anything, and / alone. The permission word is 0x9fc27f; for owner file, it is 0x27f.owner file, keeps the owner half only: the same access, for files owned by the task's fsuid.network, capability, mount and the other rule classes are still checked against their own rules./. A name that does not, such as the name of a disconnected object, is not matched (read from the source).deny file, is rejected with Invalid perms, in deny rules 'x' must not be preceded by exec qualifier 'i', 'p', or 'u', because the bare rule carries ix. The test ok_bare_1.sd expects it to pass and is marked #=TODO https://launchpad.net/bugs/1215637.file, is the widest file rule there is: it compiles to the pattern /{**,} with rwalkm and ix for owner and other (parser_yacc.y:1103-1113; run with the parser built from the AppArmor tree at 836052d21, nothing loaded into a kernel). Every program the task can name is then executable under the same profile.deny file, is rejected because the bare rule carries ix (parser_misc.c:1093-1096). deny /** rwlkmx, and deny /{**,} rwlkmx, are accepted by the same parser when a blanket denial is wanted./** does not cover the directory itself, and a rule without the trailing slash does not match a directory: check both forms when you review what a profile exposes (globbing).file_rule: TOK_FILE TOK_END_OF_RULE builds the path "/{**,}" and the permissions (AA_BASE_PERMS & ~AA_EXEC_TYPE) | (AA_EXEC_INHERIT | AA_MAY_EXEC), copied to the other half with << AA_OTHER_SHIFT (parser_yacc.y:1103-1113). AA_OTHER_SHIFT is 14 (immunix.h:25).entry_add_prefix, which ends with check_x_qualifier, the source of the deny file, error (parser_misc.c:1147-1159, parser_misc.c:1090-1096).frule (parser/parser_yacc.y:1072,1085) builds a cod_entry; merge_file ORs entries with identical names; process_dfa_entry (parser/parser_regex.c:648) compiles each.
LABEL or QUOTED_LABEL and returns TOK_ID; the letters return TOK_MODE only before white space or a comma, ({MODES})/([[:space:],]) (parser_lex.l:301, parser_lex.l:838-846).frule alternatives (parser_yacc.y:1072-1100); file_perms: TOK_MODE calls parse_perms (parser_yacc.y:1640-1646).perm32_t parse_perms(const char *str_perms) shifts the parsed letters into both halves, AA_USER_SHIFT (0) and AA_OTHER_SHIFT (14) (parser_misc.c:736-745, immunix.h:24-25). With AA_MAY_EXEC 1, AA_MAY_WRITE 2, AA_MAY_READ 4, AA_MAY_APPEND 8 (immunix.h:35-38), r is 0x10004 and rw is 0x3800e.struct cod_entry *do_file_rule(char *id, perm32_t perms, char *link_id, char *nt) calls new_entry and stores the target in nt_name (parser_yacc.y:1759-1769).bool entry_add_prefix(struct cod_entry *entry, const prefixes &p, const char *&error) applies audit, mode and priority, masks a half for owner or other, then runs check_x_qualifier (parser_misc.c:1147-1159).block_rules::process_variables expands variables in name and link_name (block_rules.cc:393-407).block_rules::merge_file sorts with file_comp, checks is_merged_x_consistent and ORs perms (block_rules.cc:285-343).bool process_dfa_entry(aare_rules *dfarules, struct cod_entry *entry) calls filter_slashes, convert_aaregex_to_pcre and dfarules->add_rule(pattern, priority, rule_mode, perms, audit, parseopts) (parser_regex.c:648-682).aa_str_perms from start state rules->file->start[AA_CLASS_FILE] (file.c:221-247).Missing comma: "missing an end of line character? (entry: ...)". Paths start with / or @{; quote paths with spaces. Qualifiers precede file; safe/unsafe follow it.
Messages from the parser built from the AppArmor tree at 836052d21 (-Q -K --skip-kernel-load --warn=all). The full form is AppArmor parser error for FILE in profile FILE at line N: MESSAGE.
/a r then /b w,: missing an end of line character? (entry: PATH), reported at the line of the following rule and naming the rule without the comma./a b r, or etc/x r,: syntax error, unexpected TOK_ID, expecting TOK_MODE. A space inside an unquoted path, or a first word that is not a path. Fixture: bad_embedded_spaces_1.sd.a r, or mark r,: syntax error, unexpected TOK_MODE, expecting TOK_ID or TOK_SET_VAR. The first word consists only of mode letters, so it is read as a mode.file deny /a w,: syntax error, unexpected TOK_DENY, expecting TOK_ID or TOK_MODE or TOK_SET_VAR. Qualifiers go before file.safe file /a px,: syntax error, unexpected TOK_FILE, expecting TOK_ID or TOK_MODE or TOK_SET_VAR. safe and unsafe go after file.file /a,: syntax error, unexpected TOK_END_OF_RULE, expecting TOK_MODE. A path with no mode.TOK_ID is a path or another word, TOK_MODE the permission letters, TOK_SET_VAR a variable, TOK_END_OF_RULE the comma.file_rule_tail: opt_exec_mode id_or_var file_perms id_or_var (parser_yacc.y:1132-1139).LABEL (parser_lex.l:301); a word of mode letters before white space or a comma is TOK_MODE (parser_lex.l:843-846).Next: syn-access-modes (letters), syn-globbing (patterns), syn-exec-modes and syn-named-transitions (exec), syn-link-rules (links), syn-allow-deny and syn-owner (qualifiers).
PATH MODE, or MODE PATH,, optionally with qualifiers in front, the word file, and -> TARGET at the end.file, alone allows every file access and ix for exec./ (path.c:167-177).Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the fragment (-Q -K --skip-kernel-load --warn=all), with nothing loaded into a kernel; "code" means the parser source or the kernel source of mainline Linux 7.4 (7.4-rc2, 97d73c825) was read, not run. Nothing here was observed on a running kernel.
FILE RULE: [QUALIFIERS] [file] [safe|unsafe] ( PATH MODE | MODE [subset] PATH ) [-> TARGET] , BARE RULE: [QUALIFIERS] file , QUALIFIERS: [priority=N] [audit] [allow|deny|prompt] [owner|other]
PATH starts with / or a variable @{...}, or is a quoted string. It ends at white space; a path that contains a space or a comma is quoted.MODE is one word of permission letters followed by white space or a comma. The letters: syn-access-modes and syn-exec-modes.file, then safe or unsafe, then the path and mode in either order, then the arrow and target, then the comma./a px -> b, and px /a -> b, (tree).l together with an exec mode and an arrow: see syn-link-rules.| Keyword | Where | Meaning |
|---|---|---|
file | before the rule, after the qualifiers | optional marker with no effect; alone with a comma it is the bare rule |
safe, unsafe | after file, before the path or mode | exec rules only: syn-safe-unsafe |
subset | letters-first spelling, between mode and path | link rules only: syn-link-rules |
-> | after the path and mode | a link target when the mode has l and no exec letters, otherwise an exec target: syn-named-transitions |
priority=N, audit, allow, deny, prompt | in front, in this order | syn-priority, syn-audit, syn-allow-deny |
owner, other | last qualifier | syn-owner |
file is a reserved word only in rule position. It stays usable inside a path, as in /etc/file r, (code).
Each of these lines is accepted by the tree's parser (tree).
| Line | Note |
|---|---|
file /a r, | keyword, path first |
file r /a, | keyword, letters first |
file /a px -> b, | exec target |
file safe /a px, | safe after file |
file unsafe px /a, | unsafe with letters first |
file l /a -> /b, | link target |
deny file /a w, | qualifier before file |
audit deny owner /a rw, | qualifiers in order |
file, | the bare rule |
owner file, | the bare rule, owner half |
"/foobar," r, | a quoted path that contains a comma |
file, is rewritten by the parser to the path /{**,} with the letters rwalkm and the exec mode ix, for both the owner and the other half (code). In the parser's rule dump the path is /([^\x00]*|): / followed by anything, and / alone (tree).owner file, keeps the owner half only: the same access, for files owned by the task's fsuid./. A name that does not, such as the name of a disconnected object, is not matched (code).file, outside a profile is an error.All statements in this section are from the kernel source (code).
/ before matching. /etc/demo/ r, matches the directory itself; /etc/demo r, does not.EACCES./a r, and /a w, are /a rw,.The full form of a parser error is AppArmor parser error for FILE in profile FILE at line N: MESSAGE (tree). The table gives MESSAGE. All of them are fatal except the last row.
| Message | Example | When |
|---|---|---|
| missing an end of line character? (entry: PATH) | /a r then /b w, | a rule has no comma; reported at the line of the following rule, naming the rule without the comma |
| syntax error, unexpected TOK_ID, expecting TOK_MODE | /a b r, and etc/x r, | a space inside an unquoted path, or a first word that is not a path. When the word after the space is a keyword the message names its token: /a file r, gives unexpected TOK_FILE (tree) |
| syntax error, unexpected TOK_MODE, expecting TOK_ID or TOK_SET_VAR | a r, and mark r, | the first word consists only of mode letters, so it is read as a mode |
| syntax error, unexpected TOK_DENY, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | file deny /a w, | a qualifier after file |
| syntax error, unexpected TOK_FILE, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | safe file /a px, | safe or unsafe before file |
| syntax error, unexpected TOK_LINK, ... | file link /a -> /b, | the link rule does not take the keyword |
| syntax error, unexpected TOK_END_OF_RULE, expecting TOK_MODE | file /a, | a path with no mode |
| syntax error, unexpected TOK_ARROW, expecting TOK_ID or TOK_SET_VAR | px -> b /a, | the target written before the path |
| subset can only be used with link rules. | r subset /a, | subset with a mode other than l |
| link and exec perms conflict on a file rule using -> | lpx /link/** -> /target, | letters first, l with an exec mode and an arrow |
| link perms are not allowed on a named profile transition. | l /a -> :ns:b, | letters first, l with a target that names a namespace |
| conflicting mode prefix | two of allow, deny, prompt reach the same rule | |
| conflicting audit prefix | audit given twice for the same rule | |
| ambiguous rule specifies both link target and exec transition target. Using as exec transition | /a lpx -> b, | warning, path first only; its class deprecated is off by default |
In these messages TOK_ID is a path or another word, TOK_MODE is the permission letters, TOK_SET_VAR is a variable and TOK_END_OF_RULE is the comma.
deny file, is rejected with "Invalid perms, in deny rules 'x' must not be preceded by exec qualifier 'i', 'p', or 'u'" (tree). The bare rule is built with ix, and a deny rule may not carry an exec qualifier. The tree's own test parser/tst/simple_tests/file/ok_bare_1.sd expects the rule to pass and is marked as a known failure (launchpad 1215637).x nor l, such as /a r -> b,, is accepted and takes a slot in the exec table. See syn-named-transitions.| Step | Where |
|---|---|
path as TOK_ID, LABEL start characters | parser/parser_lex.l:301, parser/parser_lex.l:838-841 |
letters as TOK_MODE, only before white space or a comma | parser/parser_lex.l:843-846 |
file keyword to TOK_FILE | parser/parser_misc.c:108 |
qualifiers, opt_prefix | parser/parser_yacc.y:705-711 |
frule, path first | parser/parser_yacc.y:1072 |
frule, letters first, with the subset and link checks | parser/parser_yacc.y:1085-1100 |
bare rule, file_rule: TOK_FILE TOK_END_OF_RULE | parser/parser_yacc.y:1103-1113 |
file_rule: opt_file file_rule_tail, opt_exec_mode frule | parser/parser_yacc.y:1114, parser/parser_yacc.y:1117 |
| the missing-comma error | parser/parser_yacc.y:1132-1139 |
parse_perms | parser/parser_misc.c:736-745 |
do_file_rule, builds the cod_entry | parser/parser_yacc.y:1759-1769 |
entry_add_prefix, with check_x_qualifier | parser/parser_misc.c:1147-1159 |
process_variables | parser/block_rules.cc:393-407 |
merge_file, ORs the perms of identical names | parser/block_rules.cc:285-343 |
process_dfa_entry | parser/parser_regex.c:648-682 |
kernel: aa_path_perm, profile_path_perm, __aa_path_perm, aa_str_perms | linux:security/apparmor/file.c:221-309 |
kernel: request & ~perms->allow gives -EACCES | linux:security/apparmor/file.c:244-247 |
kernel: trailing / on directory names | linux:security/apparmor/path.c:167-177 |
Permission words in the parser's rule dump (tree). Each half has x 0x1, w 0x2, r 0x4, a 0x8; the other half is shifted left by 14.
| Rule | Word |
|---|---|
/a r, | 0x10004 |
/a rw, | 0x3800e |
file, | 0x9fc27f |
owner file, | 0x27f |
The mode is a value in the flags=( ) list of the profile head. It decides what happens to an access that the rules neither allow nor deny.
flags=( ) list in the profile head. The six mode words are enforce, complain, kill, unconfined, prompt and default_allow (apparmor.d.pod:157-166).aa_apply_modes_to_perms (lib.c:364-372). Kill mode marks every permission that is not allowed; complain mode marks every permission that is neither allowed nor denied.aa_select_audit_type (audit.c:143-152). The names that appear in the log as apparmor="..." are AUDIT, ALLOWED, DENIED and KILLED (audit.c:29-38).demo (complain), in /proc/<pid>/attr/current and /proc/<pid>/attr/apparmor/current (label.c:1563-1571).flags=( VALUE ... ) or ( VALUE ... ), last in the head, one list only, at least one value. Mode values: enforce, complain, kill, unconfined, prompt, default_allow. No mode value means enforce.
PROFILE FLAG CONDS = [ 'flags=' ] '(' comma or white space separated list of PROFILE FLAGS ')' and PROFILE MODE = 'enforce' | 'complain' | 'kill' | 'default_allow' | 'unconfined' | 'prompt' (apparmor.d.pod:157-166).{. A head takes one list and the list needs at least one value.flags=(complain,,audit), flags = ( complain ) and the quoted flags=("complain").complain, not Complain; default_allow with an underscore.enforce.flags=(complain) (flags_ok.sd:7), the bare form (audit,debug) (flags_ok19.sd:7), a mode beside another value, flags=(enforce audit) (flags_ok15.sd:7).apparmor_parser -Q -K FILE (-Q, --skip-kernel-load, -K, --skip-cache).flags productions (empty, with flags =, bare parentheses) and the flagvals list: parser_yacc.y:593-629.flags is a keyword only when = follows (parser_lex.l:433-436); list values are read in LIST_VAL_MODE, where commas are skipped (parser_lex.l:479-488).str_to_mode compares with strcmp against profile_mode_table (profile.h:97-105, profile.cc:30-39).No mode and enforce load as enforce. default_allow loads as unconfined. prompt loads as the mode the kernel names user. The mode is shown after the profile name, as in demo (complain). The right-hand column is put together from the kernel code, not captured from a running system.
failed to unpack profile flags (policy_unpack.c:1213-1237, constants at policy_unpack.h:36-40).enforce, complain, kill, unconfined, user (policy.c:94-100).NAME (MODE), or :NS:NAME (MODE) with a namespace (label.c:1563-1571). The namespace's own unconfined label is printed without a mode.cat /proc/<pid>/attr/current, or from a program int aa_getcon(char **label, char **mode) and int aa_gettaskcon(pid_t target, char **label, char **mode) (apparmor.h:110-111)./sys/module/apparmor/parameters/mode, readable and writable by root only, which takes the same five names (lsm.c:1947-1949, lsm.c:2229-2247). A profile behaves as complain, kill or user when its own mode or the system-wide mode says so (policy.h:40-48).default_allow: such profiles "may be be reported as being in enforce mode or allow mode" (apparmor.d.pod:734-745). With the parser at 836052d21 the kernel's name for it is unconfined.profile_mode_packed rewrites DEFAULT_ALLOW to UNCONFINED and subtracts one; UNSPECIFIED stays 0 (profile.h:48-87).In complain mode an access that no rule allows or denies is permitted and logged with apparmor="ALLOWED". An access matched by a deny rule is still refused. This is what the kernel code says for a plain deny, and the manual agrees.
All kernel statements are read from the kernel source and were not run.
perms->complain |= ~(perms->allow | perms->deny) (lib.c:369-370). A permission in the deny set is not added, so a deny rule still refuses.aa_audit_file: a plain deny is quieted and returns the error before the complain conversion (file.c:142-149). Whether an audit deny file rule is still refused in complain mode is open (not run): its request is not quieted, reaches aa_audit, and there a complain-mode profile turns any error into ALLOWED (audit.c:206-212).ALLOWED only when every refused permission is in the complain set (audit.c:143-152).ALLOWED record aa_audit returns complain_error(ad->error) (audit.c:233-234), which turns EPERM and EACCES into success and passes every other error on (audit.h:206-211).-O filter-deny (apparmor.d.pod:604-616). It lists further cases that complain mode does not turn into an allow (apparmor.d.pod:618-731); those were not checked against the kernel here.apparmor_parser -C (--Complain) forces complain mode at load time (apparmor_parser.pod:168). For policy ABIs newer than 5 this travels in the policy version word, and the kernel then loads the profile as complain whatever the head says (policy_unpack.c:1224-1225, policy_compat.h:18)./sys/module/apparmor/parameters/mode set to complain has the same effect on every profile (policy.h:40-48).flags=(kill): by the kernel code, a refused access is logged with apparmor="KILLED" and the task is sent a signal, SIGKILL by default. kill.signal=NAME chooses another signal; it does not select kill mode by itself. The log line is put together from the kernel's type names, not copied from a log.
All kernel statements are read from the kernel source and were not run.
perms->kill = ~perms->allow (lib.c:367-368).KILLED (audit.c:147-148); aa_audit also turns a DENIED record of a kill-mode profile into KILLED (audit.c:221-222).send_sig_info(profile->signal, SEND_SIG_NOINFO, ...). The target is the task named in the audit data if there is one, otherwise the current task (audit.c:228-231).SIGKILL unless the policy sets another: profile->signal = SIGKILL when the profile is allocated (policy.c:412).kill.signal=NAME arrives as an optional number named kill. A value outside 1 to 35 fails the load with profile kill.signal invalid value (policy_unpack.c:1202-1207)./sys/kernel/security/apparmor/features/domain/kill.signal (apparmorfs.c:2612).flags=(kill) (flags_ok13.sd:7), flags=(kill, kill.signal=trap) (flags_ok46.sd:7). Signal names are lower case without sig (signal.cc:42-78).kill.signal.kill.signal= in full.unconfined: tasks are treated as unconfined. default_allow: loaded as unconfined by this parser, which is not what the manual describes. prompt: the kernel has no code that asks user space, so an access outside the rules works out to refused. All three rows are read from the code, not run. Distribution kernels with prompting behave differently.
All three rows are read from the kernel source and of the parser. None was run on a kernel.
unconfined: the kernel sets the profile's mode to unconfined and also marks its label as unconfined (policy_unpack.c:1230-1232). The file permission check returns success at once for such a profile: if (profile_unconfined(profile)) return 0; (file.c:263-264, policy.h:316). Which other checks still apply was not determined.default_allow: the parser at 836052d21 sends the same mode number as for unconfined, so everything above applies. The manual describes something else: "similar to unconfined but allows for allow and deny rules, specifying audit, and domain transitions" (apparmor.d.pod:734-745).prompt: the kernel's name is user, commented "modified complain mode to userspace" (policy.h:76). In this mode the permissions outside the rules are marked for prompting: perms->prompt |= ~(perms->allow | perms->deny) (lib.c:371-372).security/apparmor/ of the kernel reads that mark to ask user space or to decide; the record type is chosen from the kill and complain marks only, which leaves DENIED (audit.c:143-152).prompt: "send an up call to userspace ... If userspace does not respond then the access will be denied" (apparmor.d.pod:765-768). That describes kernels that carry the prompting patches.unconfined: "should not be used under regular deployment but can be useful during debugging" (apparmor.d.pod:747-763).prompt or default_allow on a kernel that does not act on them.profile_mode_packed: "until dominance is fixed use unconfined mode for default_allow" (profile.h:75-87).Profile::post_parse_profile checks features for interruptible, kill.signal and error only; no mode is checked (profile.cc:91-110).flagvals::init → merge → profile_mode_packed() → second u32 of struct flags → unpack_profile(): 0 enforce, 1 complain, 2 kill, 3 unconfined, 4 user. With prompt rules and the prompt compatibility mode FLAG, post-processing overwrites the declared mode with PROMPT (parser/parser_policy.c:161-162).
enum class profile_mode: UNSPECIFIED 0, ENFORCE 1, COMPLAIN 2, KILL 3, UNCONFINED 4, PROMPT 5, DEFAULT_ALLOW 6, CONFLICT 7 (profile.h:48-58). The spellings are in profile_mode_table (profile.cc:30-39).flagvals::init(const char *str) calls str_to_mode first; a word that is a mode sets mode (profile.h:211-220).merge_profile_mode(l, r) returns CONFLICT for two different specified modes (profile.h:66-73); flagvals::merge raises Profile flag '%s' conflicts with '%s' (profile.h:304-309).profile_mode_packed(mode) rewrites DEFAULT_ALLOW to UNCONFINED, then returns the value minus one; UNSPECIFIED gives 0 (profile.h:75-87).flags as three u32: flag bits, profile_mode_packed(profile->flags.mode), audit (parser_interface.c:524-528).FLAG, post-processing overwrites the declared mode with PROMPT (parser_policy.c:161-162).ENCODE_VERSION (parser_interface.c:670-671).unpack_profile: the second u32 of flags is compared with PACKED_MODE_ENFORCE 0 to PACKED_MODE_USER 4; FORCE_COMPLAIN_FLAG in the version wins over the number; anything else is goto fail (policy_unpack.c:1209-1237, policy_unpack.h:36-40).COMPLAIN_MODE, USER_MODE and KILL_MODE are true for the profile's mode or for the global aa_g_profile_mode (policy.h:40-48)."Profile flag 'A' conflicts with 'B'" means two mode words in one list. "Invalid profile flag: X." means an unknown or wrongly capitalised value. A head takes one flags list and the list cannot be empty. All five messages are what the parser built from the tree prints.
AppArmor parser error for FILE in profile FILE at line N: MESSAGE.Profile flag 'enforce' conflicts with 'complain' for flags=(enforce, complain) (flags_bad30.sd:7); likewise flags=(complain, kill) (flags_bad34.sd:7).Invalid profile flag: Complain. for a wrongly capitalised word; the fixture for an unknown word is flags=(capability) (flags_bad2.sd:7).syntax error, unexpected TOK_CLOSEPAREN, expecting TOK_VALUE for flags=() (flags_bad16.sd:6).syntax error, unexpected TOK_FLAGS, expecting TOK_OPEN for a second list, flags=(complain) flags=(audit).flags=(default_allow, unconfined) is a conflict too, although both load as the same mode (flags_bad72.sd:6).flags=(complain complain), is accepted (parser 5.0.2).profile missing flags and failed to unpack profile flags, the second also for a mode number it does not know (policy_unpack.c:1209-1237).apparmor_parser -Q -K FILE.audit goes in the same list.flagvals::merge (profile.h:304-309) through merge_profile_mode (profile.h:66-73); the invalid flag error is the last branch of flagvals::init (profile.h:261).flagvals needs at least one flagval, and profile_base takes one flags (parser_yacc.y:593-629).default_allow is loaded as unconfined. prompt on the kernel asks nobody and refuses what the rules do not cover. Whether an audit deny file rule is still refused in complain mode is open: the kernel code suggests it is not, and it has not been run. The tree's parser prints no warning for any of the three with --warn=all.
All kernel statements are read from the kernel source and were not run.
default_allow: profile_mode_packed rewrites it to the value of unconfined under the comment "until dominance is fixed use unconfined mode for default_allow" (profile.h:75-87). For a profile in unconfined mode the file permission check returns success before any rule is looked up (file.c:263-264). Which other checks still apply was not determined.prompt: the permissions outside the rules are marked for prompting (lib.c:364-372); nothing in security/apparmor/ reads that mark to ask user space or to decide, so the access stays refused. Kernels with the prompting patches differ: upstream and Ubuntu kernels.deny: for a file request the denied bits of a plain deny are in the quiet mask, aa_audit_file clears them from the request and returns the error before the complain conversion (file.c:142-149).audit deny (open, not run): an audit deny rule is not quieted, so the request reaches aa_audit with type AUDIT_APPARMOR_AUTO. There a complain-mode profile makes the record ALLOWED (audit.c:206-212) and the return value goes through complain_error(), which turns EACCES into success (audit.c:233-234). If that reading is right, adding audit to a deny file rule lifts the denial in complain mode. It needs a kernel run to confirm.-Q -K --skip-kernel-load --warn=all, nothing loaded): flags=(default_allow) with a deny rule, flags=(prompt), and flags=(complain) with an audit deny rule print no warning besides the missing-abi notice.Other values of the list: syn-flags-other. Deny rules: syn-allow-deny. Changing modes with tools: ut-modes. Reading the log: adm-denials. Kernels that act on prompt: upstream-and-ubuntu.
flags=( ) list; none means enforce.default_allow loads as unconfined and prompt as the mode the kernel names user.deny rule denies.Parser messages on this page were produced by the parser built from the AppArmor tree, or by apparmor_parser 5.0.2 where a row says so. Kernel behaviour was worked out by reading the kernel's code at the commit above. It was not run on a kernel.
flags: [ 'flags' '=' ] '(' VALUE { [','] VALUE } ')'
{. A head takes one list.flags is a keyword only when = follows it. The bare form ( VALUE ... ) means the same.complain, not Complain; default_allow with an underscore.flags=(complain,,audit), flags = ( complain ), flags=("complain").Fixtures: flags=(complain) (parser/tst/simple_tests/profile/flags/flags_ok.sd:7), (audit,debug) (flags_ok19.sd:7), flags=(enforce audit) (flags_ok15.sd:7). The tree's parser also accepts profile demo /usr/bin/demo (complain) {.
"Outside the rules" means an access that no rule allows and no deny rule denies. The last three columns are read from the kernel's code.
| Spelling | An access outside the rules | Log type | The kernel's name |
|---|---|---|---|
no mode, or enforce | refused | DENIED | enforce |
complain | permitted | ALLOWED | complain |
kill | refused, and the task is sent a signal (SIGKILL unless kill.signal= says otherwise) | KILLED | kill |
unconfined | not checked (file access returns early) | none | unconfined |
prompt | mainline Linux 7.4: refused, nobody is asked | DENIED | user |
default_allow | as unconfined: this parser loads it as unconfined | none | unconfined |
demo (complain), in /proc/PID/attr/current.kill.signal=NAME picks the signal and does not select kill mode: see syn-flags-other.prompt as a qualifier on a single rule is a different construct: syn-prompt.| The access is | Result | Log |
|---|---|---|
| allowed by a rule | permitted | nothing, unless the rule is audited |
| not mentioned by any rule | permitted | apparmor="ALLOWED" |
matched by a deny rule | refused (for an audit deny file rule this is open, see below) | depends on the deny rule: syn-allow-deny |
deny rule is still enforced.aa_audit_file: a plain deny is quieted and returns the error before the complain conversion (linux:security/apparmor/file.c:142-149). Whether an audit deny file rule is still refused in complain mode on mainline Linux 7.4 is open (not run): such a request is not quieted, goes on to aa_audit, and there a complain-mode profile turns the error into an ALLOWED record (linux:security/apparmor/audit.c:206-212, 233-234).-O filter-deny (parser/apparmor.d.pod:609-616).| Message | When |
|---|---|
Profile flag 'A' conflicts with 'B' | two mode values in one list: any pair, including enforce with another mode and default_allow with unconfined |
Invalid profile flag: X. | an unknown value or a wrongly capitalised one, for example flags=(Complain) |
syntax error, unexpected TOK_CLOSEPAREN, expecting TOK_VALUE | an empty list, flags=() |
syntax error, unexpected TOK_FLAGS, expecting TOK_OPEN | a second list, flags=(complain) flags=(audit) |
| a syntax error | a misspelt keyword, flogs=(audit) (flags_bad14.sd:6) |
kernel: profile missing flags | the loaded policy has no flags struct |
kernel: failed to unpack profile flags | the flags struct is malformed or carries a mode number the kernel does not know |
prompt or default_allow on a kernel that does not act on them. No mode is checked against kernel features.enforce, complain), flags_bad34.sd:7 (complain, kill), flags_bad72.sd:6 (default_allow, unconfined), all under parser/tst/simple_tests/profile/flags/.default_allow: the manual says the mode "allows for allow and deny rules, specifying audit, and domain transitions" and that such profiles "may be reported as being in enforce mode or allow mode" (parser/apparmor.d.pod:734-745). The parser at this commit packs the same value as for unconfined (parser/profile.h:75-87; a 5.0.2 dump of flags=(default_allow, audit, debug) shows mode 3), so the kernel's name for it is unconfined. The slides teach the code.prompt: the manual says the mode sends "an up call to userspace" and "If userspace does not respond then the access will be denied" (parser/apparmor.d.pod:765-768). That describes kernels with the prompting patches. Mainline Linux 7.4 only marks the permissions; no code reads the mark to decide or to notify user space.flags=(complain complain), is accepted (5.0.2), although two different modes are an error.flags=(default_allow, unconfined) is a conflict although both are packed as the same value.| Spelling | Parser enum | Packed u32 | Kernel mode | Kernel name |
|---|---|---|---|---|
| (no mode) | UNSPECIFIED 0 | 0 | APPARMOR_ENFORCE | enforce |
enforce | ENFORCE 1 | 0 | APPARMOR_ENFORCE | enforce |
complain | COMPLAIN 2 | 1 | APPARMOR_COMPLAIN | complain |
kill | KILL 3 | 2 | APPARMOR_KILL | kill |
unconfined | UNCONFINED 4 | 3 | APPARMOR_UNCONFINED + FLAG_UNCONFINED | unconfined |
prompt | PROMPT 5 | 4 | APPARMOR_USER | user |
default_allow | DEFAULT_ALLOW 6 | 3 | APPARMOR_UNCONFINED + FLAG_UNCONFINED | unconfined |
profile_mode_packed rewrites DEFAULT_ALLOW to UNCONFINED under the comment "until dominance is fixed use unconfined mode for default_allow", then subtracts one; UNSPECIFIED stays 0.APPARMOR_COMPLAIN when the version word carries FORCE_COMPLAIN_FLAG, whatever the packed mode is.FLAG, post-processing overwrites the declared mode with PROMPT.| What | Where |
|---|---|
| grammar of the list | parser/parser_yacc.y:593-629 |
flags keyword, list values | parser/parser_lex.l:433-436, 479-488 |
profile_mode enum, merge_profile_mode, profile_mode_packed, str_to_mode | parser/profile.h:48-57, 66-73, 75-87, 97-105 |
profile_mode_table | parser/profile.cc:30-39 |
flagvals::init, invalid flag error | parser/profile.h:211-263 |
flagvals::merge, conflict error | parser/profile.h:304-309 |
| feature checks (none for modes) | parser/profile.cc:91-110 |
struct flags written | parser/parser_interface.c:524-528 |
| no "mediates class" entries for unconfined and default_allow | parser/parser_regex.c:1396-1398 |
| prompt compatibility overwrites the mode | parser/parser_policy.c:161-162 |
| force-complain | parser/parser_yacc.y:443-447, parser/parser_interface.c:670 |
| kernel reads the mode | linux:security/apparmor/policy_unpack.c:1209-1237 |
| packed mode constants | linux:security/apparmor/include/policy_unpack.h:36-40 |
| mode names | linux:security/apparmor/policy.c:94-100 |
COMPLAIN_MODE, KILL_MODE, USER_MODE | linux:security/apparmor/include/policy.h:40-48 |
aa_apply_modes_to_perms | linux:security/apparmor/lib.c:364-372 |
| audit type choice, signal, complain return | linux:security/apparmor/audit.c:143-150, 200-237 |
name (mode) label format | linux:security/apparmor/label.c:1564-1571 |
Besides the mode, flags=( ) holds switches for path naming, logging, the kill signal and a few features of newer kernels. attach_disconnected lets the kernel name a file it cannot connect to the root. The path here is an illustration; the behaviour is read from the kernel code.
All kernel statements are read from the kernel source and were not run.
aa_path_name(). On failure the request is audited with the reason and refused; no rule is consulted (file.c:156-180).EACCES unless the profile has the connect flag, and the leading / is removed from the name (path.c:48-72). The reason in the log is info="Failed name lookup - disconnected path" (path.c:208-212).attach_disconnected the kernel puts / in front of the name and continues (path.c:62-68).PROFILE FLAGS (apparmor.d.pod:159-162). The parser accepts sixteen; five of them are missing from the manual: namespace_relative, chroot_attach, chroot_no_attach, delegate_deleted, no_attach_disconnected.flagvals::init (profile.h:211-263).Sixteen values: audit, debug, interruptible, kill.signal=NAME, error=ERRNO, attach_disconnected, attach_disconnected.path=PATH, attach_disconnected.ipc, attach_disconnected.ipc=PATH, no_attach_disconnected, mediate_deleted, delegate_deleted, chroot_relative, namespace_relative, chroot_attach, chroot_no_attach.
PROFILE FLAGS = PROFILE MODE | AUDIT_MODE | 'mediate_deleted' | 'attach_disconnected' | 'attach_disconnected.path='ABS PATH | 'chroot_relative' | 'attach_disconnected.ipc' | 'attach_disconnected.ipc='ABS PATH | 'debug' | 'interruptible' | 'kill.signal='SIGNAL | 'error='ERROR CODE (apparmor.d.pod:157-168).NAME=VALUE is one word of the list: no blanks around =.attach_disconnected or no_attach_disconnected; chroot_relative or namespace_relative; chroot_attach or chroot_no_attach; mediate_deleted or delegate_deleted. Writing both sides gives Profile flag X conflicts with Y.ERROR CODE is "case insensitive error code name starting with 'E'" (apparmor.d.pod:164).flags=(audit, attach_disconnected) (flags_ok5.sd:14), flags=(attach_disconnected.path=/foo) (flags_ok_disconnected_path1.sd:7), flags=(kill.signal=quit, kill) (flags_ok43.sd:7).kill.signal=: signal.cc:42-78.flagvals::init: bare words with strcmp, the name= forms with strncmp on the prefix, each marked "TODO: make this a proper parse" (profile.h:211-263).flagvals::merge (profile.h:314-329).Without the flag a disconnected path fails with "Failed name lookup - disconnected path". attach_disconnected prefixes /. attach_disconnected.path=/outside prefixes /outside, so rules can tell disconnected files apart. no_attach_disconnected states the default. Read from the kernel code, not run.
All kernel statements are read from the kernel source and were not run.
disconnect(): without the connect flag the result is EACCES and a name without leading /; with it the kernel prepends / if missing and then the profile's prefix string, if it has one (path.c:48-72).Failed name lookup - disconnected path (path.c:211-212); it is logged as info= and the request is refused before any rule is tried (file.c:169-177).attach_disconnected.path=PATH: the prefix is loaded as an optional string named disconnected (policy_unpack.c:1198-1200). The kernel shows support with /sys/kernel/security/apparmor/features/domain/disconnected.path (apparmorfs.c:2611).PATH, filters repeated slashes, requires a leading / and removes trailing slashes (parser_variable.c:42-56).no_attach_disconnected states the default.attach_disconnected sets PATH_ATTACH; the .path= form also stores disconnected_path (profile.h:231-242).PATH_ATTACH is packed as path_flags 0x4 (parser_interface.c:536-537), the kernel's PATH_CONNECT_PATH (path.h:20).chroot_relative names files from the task's chroot instead of the mount namespace root. chroot_attach only has an effect together with chroot_relative. A file deleted while still open is named only with mediate_deleted or delegate_deleted in effect; otherwise the kernel's code fails with "Failed name lookup - deleted entry". no_attach_disconnected, namespace_relative and chroot_no_attach only spell out the defaults. Writing both words of a pair is an error.
All kernel statements are read from the kernel source and were not run.
chroot_relative the path is resolved against the task's root directory, current->fs, with __d_path(); otherwise with d_absolute_path(), and a mount outside the task's mount namespace counts as not connected (path.c:118-128).disconnect() (path.c:48-72). chroot_attach connects only when chroot_relative is set as well and the mount belongs to the task's mount namespace (path.c:35, path.c:53-55).ENOENT unless one of the two deleted flags is set (path.c:160-164). The reason is Failed name lookup - deleted entry (path.c:209-210).PATH_CONNECT_PATH 0x4, PATH_CHROOT_REL 0x8, PATH_CHROOT_NSCONNECT 0x10, PATH_DELEGATE_DELETED 0x10000, PATH_MEDIATE_DELETED 0x20000 (path.h:17-26).path_flags field at all, the kernel uses PATH_MEDIATE_DELETED as the default (policy_unpack.c:1246-1252).mediate_deleted and chroot_relative (apparmor.d.pod:788-789, apparmor.d.pod:809-810). namespace_relative, chroot_attach, chroot_no_attach and delegate_deleted are accepted by the parser and not in the manual.Profile flag chroot_relative conflicts with namespace_relative, Profile flag mediate_deleted conflicts with delegate_deleted, Profile flag chroot_attach conflicts with chroot_no_attach.chroot_relative 0x8, mediate_deleted 0x10000, attach_disconnected 0x4, chroot_attach 0x10, attach_disconnected.ipc 0x20; the field is written only if some path flag was parsed (parser_interface.c:530-545). mediate_deleted is sent as 0x10000, which the kernel names PATH_DELEGATE_DELETED; the kernel tests both deleted bits together.audit logs every mediated request of the profile (apparmor="AUDIT" for allowed ones) and un-silences quieted denials. kill.signal=term makes kill mode send that signal. debug enables kernel debug output for the profile's label when kernel debugging is on. The log line is assembled from the kernel's audit type names, not captured.
All kernel statements are read from the kernel source and were not run.
audit: sent as the third number of the flags structure; non-zero sets the profile's audit mode to AUDIT_ALL (policy_unpack.c:1238-1241).AUDIT_ALL every permission is put in the audit set and the quiet set is emptied, on each check (lib.c:374-380). Allowed requests are then logged with apparmor="AUDIT" (audit.c:206-210) and denials that a deny rule had quieted are logged again./sys/module/apparmor/parameters/audit (lsm.c:1974-1976) with the values normal, quiet_denied, quiet.allowed, quiet, noquiet, all (audit.c:20-27).kill.signal=NAME: an optional number named kill; a value outside 1 to 35 fails the load with profile kill.signal invalid value (policy_unpack.c:1202-1207). The default is SIGKILL (policy.c:412) and the signal is sent when a KILLED record is written (audit.c:221-231).kill.signal= are lower case without sig: hup, int, quit, term, usr1 and the rest of the table at signal.cc:42-78.debug: the kernel marks the profile's label, and AA_DEBUG_LABEL messages are printed for marked labels only, and only when the kernel's debug setting /sys/module/apparmor/parameters/debug selects that message group (policy_unpack.c:1218-1221, lib.h:42-51, lsm.c:1969-1971).audit "causes all actions whether allowed or denied to be logged"; debug "should never appear in policy except when trying to debug kernel or policy problems"; kill.signal "changes the signal that will be sent by AppArmor when in kill mode or a kill rule has been violated" (apparmor.d.pod:779-780, apparmor.d.pod:812-821).flags=(complain audit) (flags_ok16.sd:7), flags=(kill.signal=quit, kill) (flags_ok43.sd:7).audit = 1, flags |= DEBUG1, signal = find_signal_mapping(...) (profile.h:216-222, profile.h:243-247).kill is written only when features_supports_flag_signal; then struct flags {bits, mode, audit} (parser_interface.c:514-528).kill.signal=, interruptible and error= need domain/kill.signal, domain/interruptible and policy/profile/error in both the kernel features and the policy ABI. Otherwise: "... not supported. Ignoring", shown only with --warn=rule-not-enforced. Both cases were run with the tree's parser, without loading into a kernel. The kernel advertises only kill.signal of the three.
interruptible needs domain/interruptible, kill.signal= needs domain/kill.signal, error= needs policy/profile/error (parser_main.c:1111-1119).aa_features_supports(a, str) && aa_features_supports(b, str) (parser_main.c:1000-1003). The policy ABI is the abi line of the file, for example abi <abi/5.0>,.flag interruptible not supported. Ignoring, kill.signal not supported. Ignoring, error flag not supported. Ignoring (profile.cc:91-110). The printed form is Warning from profile NAME (FILE): MESSAGE (parser_common.c:169-187).rule-not-enforced (parser_main.c:281), which is not in the default set (parser.h:77-78). Turn it on with apparmor_parser --warn=rule-not-enforced; --Werror=rule-not-enforced makes the parser exit with status 1 instead.kill.signal and disconnected.path under /sys/kernel/security/apparmor/features/domain/. It has no interruptible there and no policy/profile/error (apparmorfs.c:2600-2647).abi/5.0 file as the kernel features, and loaded nothing into a kernel.attach_disconnected.ipc=PATH is dropped silently without domain/disconnected.ipc (parser_interface.c:509-512).Fields in order: disconnected, disconnected_ipc, kill, error (all optional), struct flags {bits, mode, audit}, optional path_flags. Four values pack no bit: namespace_relative, delegate_deleted, no_attach_disconnected, chroot_no_attach.
flagvals::init(const char *str) parses one value (profile.h:211-263); flagvals::merge(const flagvals &rhs) combines two and raises the conflicts (profile.h:304-370).Profile::post_parse_profile warns about the gated values and clears INTERRUPTIBLE; signal and error stay in the parse data (profile.cc:91-112).disconnected (no feature check), string disconnected_ipc, u32 kill, u32 error (each only when its feature is supported), struct flags {u32 bits, u32 mode, u32 audit}, then u32 path_flags only if (profile->flags.path).HAT 1, DEBUG1 2, DEBUG2 4, INTERRUPTIBLE 8 (profile.h:133-139).PATH_ATTACH 0x4, PATH_CHROOT_REL 0x8, PATH_CHROOT_NSATTACH 0x10, PATH_IPC_ATTACH 0x20, PATH_MEDIATE_DELETED 0x10000. PATH_NS_REL, PATH_DELEGATE_DELETED, PATH_NO_ATTACH and PATH_CHROOT_NO_ATTACH pack no bit but still make flags.path non-zero.unpack_profile (policy_unpack.c:1198-1252): optional disconnected, optional kill (range check 1 to MAXMAPPED_SIG), struct flags, optional path_flags. It does not read disconnected_ipc or error.PATH_MEDIATE_DELETED is set only in the else branch, when path_flags is absent (policy_unpack.c:1246-1252). A profile with only namespace_relative therefore loads with path_flags 0.Pair conflicts read "Profile flag X conflicts with Y". kill.signal= takes lower-case names without sig; error= takes errno names, not numbers. "attach_disconnected path must begin with a /" is reported after the profile body. All five messages come from runs of the tree's parser.
AppArmor parser error for FILE in profile FILE at line N: MESSAGE.Profile flag attach_disconnected conflicts with no_attach_disconnected (flags_bad12.sd:7).unknown signal specified for kill.signal='foo' (flags_bad68.sd:7); the same for upper case HUP.Profile flag kill.signal set to conflicting values: '%d' and '%d': the numbers are printed, not the names.unknown error code specified for error='13' (flags_bad87.sd:5).attach_disconnected path must begin with a / for flags=(attach_disconnected.path=foo) (flags_bad_disconnected_path1.sd:7). It is reported after the profile body has been read, so the line number is not the head's line.error= takes errno names of the machine that built the parser; the lookup ignores case (apparmor.d.pod:164).Profile flag attach_disconnected set to conflicting values: '%s' and '%s'; the same text is printed for two .ipc= paths.flags_bad10.sd is described as a conflict test, misspells namepace_relative and so fails with Invalid profile flag instead (flags_bad10.sd:7).flagvals::merge (profile.h:314-370).process_variable_in_attach_disconnected, during variable expansion after parsing (parser_variable.c:42-56).find_error_code_mapping uses strcasecmp (profile.h:115-122).attach_disconnected gives a disconnected file the name of a path under /, so a rule can match two different objects; attach_disconnected.path= separates them. Any path flag makes the parser write path_flags (run with the tree's parser), and the kernel sets its deleted-file default only when that field is absent (read from the code, not run on a kernel).
All kernel statements are read from the kernel source and were not run.
attach_disconnected a path that does not connect to the task's root gets a leading / and is matched like any other name (path.c:48-72). A file from another mount whose partial name is data/report.txt and a real /data/report.txt then match the same rules. The manual: "WARNING this mode is unsafe and can result in aliasing and access to objects that should not be allowed" (apparmor.d.pod:791-795).attach_disconnected.path=/outside puts the prefix in front of disconnected names only, so rules under /outside/ cover them and no connected file has such a name unless that directory exists.path_flags field whenever any path flag was parsed, including the four that pack no bit (parser_interface.c:530-545). Run with the parser built from the AppArmor tree at 836052d21: the binary of a profile with flags=(no_attach_disconnected) contains the string path_flags, the binary of the same profile without flags does not.PATH_MEDIATE_DELETED only when the field is absent; on the other branch it ORs in a label flag that cannot be that bit (policy_unpack.c:1246-1252).PATH_DELEGATE_DELETED themselves (file.c:297-298); exec, link and mount use the profile's path_flags alone (domain.c:684, file.c:346-353, mount.c:214-221).info="Failed name lookup - deleted entry", so this reading fails closed. Whether it shows on a running system was not tested; it is recorded as a discrepancy between parser and kernel in the reference below.Disconnected paths at exec: attachment. Audit per rule: syn-audit. Kill mode: syn-flags-modes. The feature gate: syn-abi, adm-features, adm-parser. The kernel side: k-unpack.
audit, debug), the kill signal (kill.signal=NAME) and values gated by kernel features (interruptible, kill.signal=, error=).apparmor_parser --warn=rule-not-enforced.Parser results on this page marked "tree" come from running the parser of the source tree without loading into a kernel; in those runs the "kernel features" were the tree's abi/5.0 file. Results marked "5.0.2" come from the released parser. Kernel behaviour was read from the kernel's code and not run.
flags=( VALUE [,] VALUE ... ) VALUE = WORD | NAME=VALUE
NAME=VALUE is one word: no blanks around the =. Values may be quoted.| Spelling | What it does | Needs feature | Mainline Linux 7.4 |
|---|---|---|---|
audit | logs every mediated request of the profile, allowed ones too, and logs denials that rules had quieted | none | acted on |
debug | marks the profile for kernel debug messages, printed only when kernel debugging is on | none | acted on |
interruptible | documented as "Enables interrupts for prompt upcall to userspace" | domain/interruptible | not advertised |
kill.signal=NAME | the signal sent when the profile kills a task; does not select kill mode | domain/kill.signal | acted on |
error=ERRNO | documented as changing the error code returned on a denial | policy/profile/error | not advertised |
attach_disconnected | a path that does not connect to the root gets a leading / and is matched | none | acted on |
attach_disconnected.path=PATH | as above, with PATH put in front of the name | none | acted on |
attach_disconnected.ipc | documented as attach_disconnected limited to IPC namespaces | none | not advertised |
attach_disconnected.ipc=PATH | as above, with a prefix path | domain/disconnected.ipc for the path | not advertised |
no_attach_disconnected | states the default: a disconnected path fails name lookup | none | default behaviour |
mediate_deleted | a file that was deleted while still open is named and mediated; without either deleted flag mainline Linux 7.4 fails the lookup with "Failed name lookup - deleted entry" for exec, link and mount (file permission checks always name the file) | none | acted on |
delegate_deleted | the other word of the pair; this parser packs no bit for it | none | see Known discrepancies |
chroot_relative | names files relative to the task's chroot | none | acted on |
namespace_relative | states the default: names relative to the mount namespace root | none | default behaviour |
chroot_attach | with chroot_relative: connects a path outside the chroot but inside the task's mount namespace; no effect alone | none | acted on |
chroot_no_attach | states the default of that pair | none | default behaviour |
attach_disconnected or no_attach_disconnected; chroot_relative or namespace_relative; chroot_attach or chroot_no_attach; mediate_deleted or delegate_deleted.PATH_DELEGATE_DELETED themselves (linux:security/apparmor/file.c:297-298, 511); a profile loaded without a path flags word gets PATH_MEDIATE_DELETED (linux:security/apparmor/policy_unpack.c:1246-1252).PATH must begin with /. Variables are expanded, repeated slashes are filtered and trailing slashes removed.attach_disconnected "is unsafe and can result in aliasing and access to objects that should not be allowed".Lower case, without sig:
hup int quit ill trap abrt bus fpe kill usr1 segv usr2 pipe alrm term stkflt chld cont stop stp tstp ttin ttou urg xcpu xfsz vtalrm prof winch io poll pwr sys emt exists rtmin+N
rtmin+N, emt and exists are accepted by the parser; see Known discrepancies.EPERM, EACCES, ENOENT.error=eperm is accepted (5.0.2).error=13 is an error.A gated value is kept only when the feature is listed both in the kernel features and in the policy ABI (the abi line of the file, see syn-abi).
| Flag | Feature | Warning when dropped | Mainline Linux 7.4 advertises it |
|---|---|---|---|
interruptible | domain/interruptible | flag interruptible not supported. Ignoring | no |
kill.signal=NAME | domain/kill.signal | kill.signal not supported. Ignoring | yes |
error=ERRNO | policy/profile/error | error flag not supported. Ignoring | no |
attach_disconnected.ipc=PATH | domain/disconnected.ipc | no warning | no |
rule-not-enforced, which is not in the default set. Ask for it with --warn=rule-not-enforced; see adm-parser.--Werror for that class the parser exits with status 1.Warning from profile NAME (FILE): MESSAGE.abi line and kill.signal=term printed "kill.signal not supported. Ignoring"; with abi <abi/5.0>, the flag was kept and error=EPERM printed "error flag not supported. Ignoring".| Message | Cause |
|---|---|
Invalid profile flag: %s. | a word that is neither a mode nor a value of this page |
Profile flag chroot_relative conflicts with namespace_relative | both words of the pair |
Profile flag mediate_deleted conflicts with delegate_deleted | both words of the pair |
Profile flag attach_disconnected conflicts with no_attach_disconnected | both words of the pair |
Profile flag attach_disconnected.ipc conflicts with no_attach_disconnected | the ipc form with the negative word |
Profile flag chroot_attach conflicts with chroot_no_attach | both words of the pair |
Profile flag attach_disconnected set to conflicting values: '%s' and '%s' | two different prefix paths; also printed for two .ipc= paths |
Profile flag kill.signal set to conflicting values: '%d' and '%d' | two different signals; the numbers are printed, not the names |
Profile flag error set to conflicting values: '%s' and '%s' | two different error names |
unknown signal specified for kill.signal='%s' | a name not in the list, for example upper case HUP |
unknown error code specified for error='%s' | a number or an unknown name |
attach_disconnected path must begin with a / | a prefix path without leading /; reported after the profile body, so the line number is not the head's line |
Kernel messages, from the code of mainline Linux 7.4:
| Message | Where it appears |
|---|---|
Failed name lookup - disconnected path | info= of a log line: the path does not connect and the flag is absent |
Failed name lookup - deleted entry | info= of a log line: a deleted file could not be named |
profile kill.signal invalid value | at load: a kill value outside 1 to 35 |
Each of these is a known discrepancy between what is written and what the code does, recorded while researching this page. None is a statement of intended design.
namespace_relative, delegate_deleted, no_attach_disconnected, chroot_no_attach), makes the parser send the path flags word, and the kernel's code applies its default handling of deleted files only when that word is absent.mediate_deleted is sent as the bit that mainline Linux 7.4 names PATH_DELEGATE_DELETED. The kernel's code tests both deleted bits together, so the result is the same today.kill.signal= accepts rtmin+N, emt and exists, and sends AppArmor's own signal numbering. The kernel's code refuses values above 35 at load, so kill.signal=rtmin+1 compiles and then cannot load on a kernel with the feature. Not run on a kernel.attach_disconnected.ipc: the bit is sent without a feature check, and the path of attach_disconnected.ipc=PATH is dropped without any warning.namespace_relative, chroot_attach, chroot_no_attach, delegate_deleted, no_attach_disconnected.debug was written as 0 by the 5.0.2 parser and is written as a bit by the tree's parser.Fields in the order written by parser/parser_interface.c:503-545: string disconnected, string disconnected_ipc, u32 kill, u32 error (all optional), struct flags {u32 bits, u32 mode, u32 audit}, optional u32 path_flags.
| Spelling | Parser state (parser/profile.h) | Packed | |
|---|---|---|---|
audit | audit = 1 (221-222) | third u32 of flags = 1 | |
debug | `flags \ | = DEBUG1` (216-218) | bit 2 of the first u32 of flags |
interruptible | `flags \ | = INTERRUPTIBLE` (252-253) | bit 8 of the first u32 of flags |
kill.signal=NAME | signal = N (243-247) | u32 named kill, if supported | |
error=ERRNO | error = N (248-251) | u32 named error, if supported | |
attach_disconnected | `path \ | = PATH_ATTACH` (231-232) | path_flags 0x4 |
attach_disconnected.path=PATH | PATH_ATTACH and disconnected_path (239-242) | 0x4 and string disconnected, no feature check | |
attach_disconnected.ipc | `path \ | = PATH_IPC_ATTACH` (254-255) | path_flags 0x20 |
attach_disconnected.ipc=PATH | PATH_IPC_ATTACH and disconnected_ipc (256-259) | 0x20, and string disconnected_ipc if supported | |
no_attach_disconnected | `path \ | = PATH_NO_ATTACH` (233-234) | nothing |
mediate_deleted | `path \ | = PATH_MEDIATE_DELETED` (227-228) | path_flags 0x10000 |
delegate_deleted | `path \ | = PATH_DELEGATE_DELETED` (229-230) | nothing |
chroot_relative | `path \ | = PATH_CHROOT_REL` (223-224) | path_flags 0x8 |
namespace_relative | `path \ | = PATH_NS_REL` (225-226) | nothing |
chroot_attach | `path \ | = PATH_CHROOT_NSATTACH` (235-236) | path_flags 0x10 |
chroot_no_attach | `path \ | = PATH_CHROOT_NO_ATTACH` (237-238) | nothing |
parser/parser.h:219-227 and differ from the packed values.linux:security/apparmor/include/path.h:17-26 (PATH_CONNECT_PATH 0x4, PATH_CHROOT_REL 0x8, PATH_CHROOT_NSCONNECT 0x10, PATH_DELEGATE_DELETED 0x10000, PATH_MEDIATE_DELETED 0x20000).flagvals::init at parser/profile.h:211-263, merge at parser/profile.h:304-370.Profile::post_parse_profile at parser/profile.cc:91-110 warns and clears INTERRUPTIBLE; kill and error are left in the parse data and skipped by the serializer when unsupported (parser/parser_interface.c:514-522). Feature lookups at parser/parser_main.c:1111-1122.common_warn_once at parser/parser_common.c:169-187; default classes at parser/parser.h:77-78.parser/parser_variable.c:42-56.unpack_profile at linux:security/apparmor/policy_unpack.c:1198-1252; path_flags 5.0.2 dump of flags=(delegate_deleted) has the field with value 0. Naming: linux:security/apparmor/path.c:35, 48-72, 118-128, 160-164, 209-212. Audit and kill: linux:security/apparmor/lib.c:374-380, linux:security/apparmor/audit.c:206-231. Advertised features: linux:security/apparmor/apparmorfs.c:2596-2647.flags_bad10.sd is described as a conflict test but misspells namepace_relative and fails with "Invalid profile flag"; the description of flags_bad13.sd speaks of the debug flag while the file tests chroot_attach, chroot_no_attach.Paths in rules are AARE patterns: *, **, ?, [...], {a,b}. A pattern matches a name only if it matches all of it.
*, **, ?, [set] or [^set], and {alt,alt}. A backslash in front of one of these characters makes it literal.aa_dfa_match walks the compiled policy over the complete, NUL-terminated name and returns the state it finished in (match.c:507-519); the permissions are those of that final state (file.c:221-231). A pattern that covers only the beginning of a name ends in a state without the permission./ at the end if it is a directory (path.c:167-177).apparmor_parser -Q -K --skip-kernel-load -D rule-exprs FILE. It prints each pattern and the regular expression made from it, and loads nothing.demo and its files are invented for the map. Nothing on this slide was observed on a running kernel.* and ? do not match /. ** does. [^a] matches any character except a, including /. {a,b} is alternation.
*: any run of characters except /, also none; **: any run of characters including /, also none; ?: exactly one character except /; [set]: exactly one character of the set, with ranges such as [a-c]; [^set]: exactly one character not in the set, and that can be /; {alt,alt}: one of the comma-separated alternatives; at least one comma.* or ** that makes up a whole path component must match at least one character. See the scene "The directory itself".-Q -K --skip-kernel-load -D rule-exprs, nothing loaded into a kernel) prints for them: * becomes [^/\x00]*, ** becomes [^\x00]*, ? becomes [^/\x00], brackets are copied unchanged, {a,b} becomes (a|b).\*, \?, \[, \], \{, \} are the literal characters; \, is a literal comma inside braces; \\ is a backslash.--warn=format (or --warn=all) the parser says Character q was quotedunnecessarily, dropped preceding quote ('\') character; the missing space is in the parser's text./.\x41.convert_aaregex_to_pcre (parser_regex.c:118-431): * and ** at parser_regex.c:169-229, ? at parser_regex.c:231-254, brackets at parser_regex.c:256-280, braces and commas at parser_regex.c:282-357.[^...] is a NotCharSetNode: every character except the listed ones (expr-tree.h:683-709)./etc/demo/* matches one level; /etc/demo/** matches every level. Neither treats dot files specially.
-Q -K --skip-kernel-load -D rule-exprs, nothing loaded into a kernel): /etc/demo/* becomes /etc/demo/[^/\x00][^/\x00]*; /etc/demo/** becomes /etc/demo/[^/\x00][^\x00]*; /etc/demo/*.conf becomes /etc/demo/[^/\x00]*\.conf; /etc/demo/**.conf becomes /etc/demo/[^\x00]*\.conf./foo/* matches /foo/.hidden. The shell's rule about hidden files does not apply./foo/* does not match /foo/a/b or the directory /foo/a/. /foo/** matches /foo/a, /foo/a/ and /foo/a/b/c./foo/*bar matches /foo/bar and /foo/xbar; /a*b matches /ab and not /a/b./foo** (no slash before the stars) matches /foo, /foobar, /foo/ and /foo/a/b./**/foo matches /a/foo and /a/b/foo, and not /foo.** followed by *, which matches the same names as **.**: [^\x00]* and the TailGlob classification when the two stars end a pattern that had no other glob (parser_regex.c:206-221). *: [^/\x00]* (parser_regex.c:222-226).Directory names end in /. /etc/demo/** does not match /etc/demo/; /etc/demo/ r, or /etc/demo/{,**} r, does.
/ at the end before it is matched, except for the root directory, which is already / (path.c:167-177). The manual page says the same: "Only rules that match a trailing slash will match directories" (apparmor.d.pod:2506-2529).* or ** that stands directly after a / and is followed by a / or by the end of the pattern must match at least one character. The source gives the purpose: /foo/* should not match /foo/, /foo/*bar should match /foo/bar, and /*/foo should not match //foo (parser_regex.c:178-205)./dir/ r,; the directory and everything below: /dir/{,**} r,; everything below, not the directory: /dir/** r,; the files directly in it: /dir/* r,; the directories directly in it: /dir/*/ r,./foo/{*,bar} matches /foo/./** matches every name that starts with / except / itself; /{**,} includes /./etc//demo///x compiles as /etc/demo/x. A pattern that starts with exactly two slashes keeps them, and a trailing slash is kept./a/{/b,c} keeps the inner /.-Q -K --skip-kernel-load -D rule-exprs, nothing loaded into a kernel). The kernel behaviour is read from the kernel source, not observed.r on a directory allows./ and the stars are followed by / or the end of the pattern, emit a mandatory [^/\x00] first (parser_regex.c:178-205).filter_slashes, including the special case for a leading // (parser_regex.c:61-96). It is called for the pattern a profile attaches by (parser_regex.c:495), for a rule path (parser_regex.c:659) and for a link target (parser_regex.c:700).? is one non-slash character. [a-c] is one of a range. [^b] is any one character except b, including /; write [^b/] to exclude the slash.
? is exactly one character and never /: /a?c matches /abc, and not /ac, /a/c or /abbc.[bc] is one of the listed characters, [b-d] one of a range: /a[b-d]e matches /abe, /ace and /ade.[^b] is any one character except b, and / is such a character: /a[^b]c matches /axc and also /a/c. Write [^b/] to keep the match inside one path component.-Q -K --skip-kernel-load -D rule-exprs, nothing loaded into a kernel): /var/log/demo-?.log becomes /var/log/demo-[^/\x00]\.log; /var/lib/demo/[a-c]* becomes /var/lib/demo/[a-c][^/\x00]*; /var/lib/demo/[^.]* becomes /var/lib/demo/[^\.][^/\x00]*.{, } and , are literal.* and ? inside brackets are converted as globs instead of being literal. /a[?]b compiles without a message to /a[[^/\x00]]b, which does not match /a?b. Write \? outside brackets for a literal question mark./a[] r, prints only ERROR processing regexs for profile NAME, failed to load./foo[^me]bar r, (ok_inv_char_class.sd).[^b] matches / unless the slash is listed, as in [^b/] (run with the parser built from the AppArmor tree at 836052d21, nothing loaded into a kernel, -D rule-exprs). * and ? stop at a slash; [^...] does not.* and ? inside brackets are not literal. /a[?]b compiles to /a[[^/\x00]]b and /c[x*]d to /c[x[^/\x00]*]d, each a different set from the one written, with no message and exit status 0 (run with the parser built from the AppArmor tree at 836052d21, nothing loaded into a kernel; parser_regex.c:169-254 has no test for being inside a class, unlike the brace case at parser_regex.c:286-289). Write [\*] or [\?] for the literal character./foo/* needs at least one character after the slash, while /foo/{*,bar} compiles to /foo/([^/\x00]*|bar) and also matches the directory /foo/ (same run).attach_disconnected family of flags: other profile flags.? (parser_regex.c:231-254); [ and ], copied to the output (parser_regex.c:256-280).NotCharSetNode, "match all except one character" (expr-tree.h:683-709).{a,b} matches a or b. A variable with several values expands to {v1,v2}. {a} and {} are errors; {a,} is allowed.
{a,b} matches a or b. An alternative may be empty, may contain /, globs and further brace groups: /a{b,c{d,e}} matches /ab, /acd and /ace; /a{b,} matches /ab and /a.{a} and {} are refused with Regex grouping error: Invalid number of items between {}; {a,} is accepted.Regex grouping error: Exceeded maximum nesting of {}.\{ and \} are literal braces, \, a literal comma inside a group: /a{b\,c,d} matches /ab,c and /ad.@{APP_DATA} = /var/lib/demo /srv/demo, the path @{APP_DATA}/{cache,state}/** is expanded to {/srv/demo,/var/lib/demo}/{cache,state}/** and compiled to (/srv/demo|/var/lib/demo)/(cache|state)/[^/\x00][^\x00]*. Printed by the parser built from the AppArmor tree at 836052d21 (-Q -K --skip-kernel-load -D rule-exprs, nothing loaded into a kernel); the order of the values is the parser's.Failed to find declaration for: @{NAME}, then ERROR expanding variables for profile NAME, failed to load.{, , and } become (, | and ) (parser_regex.c:282-357); MAX_ALT_DEPTH is 50 (parser_regex.c:122); the nesting error is at parser_regex.c:295, the item count error at parser_regex.c:317.variable::expand_by_alternation builds the brace group and sets filter_leading_slash and filter_trailing_slash for the joins (variable.cc:252-340).convert_aaregex_to_pcre (parser/parser_regex.c:118-431) emits [^/\x00]* for *, [^\x00]* for ** and a leading [^/\x00] under the slash rule; filter_slashes (parser/parser_regex.c:61-96) runs first.
pattern_t convert_aaregex_to_pcre(const char *aare, int anchor, int glob, std::string& pcre, int *first_re_pos) (parser_regex.c:118-119; declared at parser.h:460).process_dfa_entry: filter_slashes(entry->name), then convert_aaregex_to_pcre(entry->name, 0, glob_default, tbuf, &pos) (parser_regex.c:658-660). Variables were expanded earlier (block_rules.cc:399-406). anchor is 0 at every call for rules./ and the run of stars is followed by / or the end, [^/\x00] is emitted first (parser_regex.c:178-205).** emits [^\x00]* (parser_regex.c:206-221); * emits [^/\x00]* (parser_regex.c:222-226); ? emits [^/\x00] (parser_regex.c:231-254).glob selects the second set of outputs: glob_default is 0 and glob_null is 1 (parser.h:458-459). With glob_null the globs may also match a NUL byte (.*, [^/]*, [^/]); it is used for xattrs= values (parser_regex.c:582-584).(, |, ), with MAX_ALT_DEPTH 50 (parser_regex.c:282-357, parser_regex.c:122).enum class pattern_t { Basic, TailGlob, Regex, Invalid } (immunix.h:139-144). Basic has no glob; TailGlob is a literal followed by one final **; everything else with a glob is Regex.Unable to parse input line '%s' message (parser_regex.c:411-431).filter_slashes (parser_regex.c:61-96).-D rule-exprs, "Dump rule to expr tree conversions" (common_optarg.c:31).Pattern errors read "Regex grouping error: ..." followed by "Unable to parse input line 'PATTERN'" and name the profile, not the line.
-Q -K --skip-kernel-load --warn=all, nothing loaded into a kernel)./var/lib/demo/{cache} rw,: Regex grouping error: Invalid number of items between {}. Test file: bad_re_brace_3.sd./var/lib/demo/{cache,state rw,: Regex grouping error: Unclosed grouping or character class, expecting close }. An unclosed [ gives the same text, also with "expecting close }"./var/lib/demo/cache] rw,: Regex grouping error: Invalid close ], no matching open [ detected.Unable to parse input line 'PATTERN' and ERROR processing regexs for profile NAME, failed to load, then ERROR generating policy re for profile NAME, failed to load and Errors found in file. Aborting.. The first two lines are prefixed with the path of the parser program. None has a file name or a line number.Regex error: trailing '\' escape character. This one is from the source and was not run.AppArmor parser error for FILE in profile FILE at line N: MESSAGE. /etc/demo/extra, r, gives one: syntax error, unexpected TOK_END_OF_RULE, expecting TOK_MODE./foobar, r, fails (bad_comma_1.sd) and "/foobar," r, is accepted (ok_comma_2.sd).convert_aaregex_to_pcre: close bracket (parser_regex.c:275), item count (parser_regex.c:317), unclosed group or set (parser_regex.c:414), trailing backslash (parser_regex.c:421), Unable to parse input line (parser_regex.c:430).ERROR processing regexs for profile %s, failed to load (parser_regex.c:1277).Next: syn-variables, syn-quoting, attachment (patterns in profile heads), fe-aare and re-tree (compilation).
* stays inside one path component; ** crosses slashes; ? is one character and not /; [set] is one character; {a,b} is a choice./ (the kernel, read from the source).[^set] can match /.apparmor_parser -Q -K --skip-kernel-load -D rule-exprs FILE prints what each pattern compiles to.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the pattern (-Q -K --skip-kernel-load --warn=all, with -D rule-exprs for the regular expressions), with nothing loaded into a kernel; "ran" means the researcher ran the pattern as recorded in the findings, without the run being repeated for this page; "code" means the parser or kernel source was read, not run. Match verdicts are derived from the regular expression the parser prints. Nothing here was observed on a running kernel.
PATTERN: a sequence of
* any run of characters except /, also none
** any run of characters including /, also none
? exactly one character except /
[set] exactly one character of the set; ranges with - ([a-c])
[^set] exactly one character not in the set (this can be /)
{alt,alt} one of the comma-separated alternatives; at least one comma
\c the character c, literally
c any other character, literally
* and ** that make up a whole path component must match at least one character: see The slash rules.*, ** and ? do not treat a leading dot specially. /foo/* matches /foo/.hidden (tree)./, globs and further brace groups.xattrs=(...) use the same syntax with one difference: there the globs may also match a NUL byte (code: glob_null, parser/parser_regex.c:582-587). See syn-xattrs.What apparmor_parser -D rule-exprs prints for each construct in a path (tree; lines in parser/parser_regex.c).
AARE regular expression lines
* [^/\x00]* 221-226
** [^\x00]* 207-220
* or ** right after / and
followed by / or the end [^/\x00] then the above 180-205
? [^/\x00] 231-254
[ ... ] copied unchanged 256-280
{ , } ( | ) 282-357
^ $ outside [ ] \^ \$ 361-368
. + | ( ) escaped with \ 374-379
\* \[ \] \{ \} kept escaped 169-177, 256-309
\? and \, outside [ ] ? and , 232-237, 333-346
\\ \\ 152-167
\ and any other character the character (warning) 382-403
Conversions of the patterns on the slides (tree):
| Pattern | Regular expression |
|---|---|
/etc/demo/* | /etc/demo/[^/\x00][^/\x00]* |
/etc/demo/** | /etc/demo/[^/\x00][^\x00]* |
/etc/demo/*.conf | /etc/demo/[^/\x00]*\.conf |
/etc/demo/**.conf | /etc/demo/[^\x00]*\.conf |
/etc/demo/{,**} | a group of two alternatives: empty, or [^\x00]* |
/var/log/demo-?.log | /var/log/demo-[^/\x00]\.log |
/var/lib/demo/[a-c]* | /var/lib/demo/[a-c][^/\x00]* |
/var/lib/demo/[^.]* | /var/lib/demo/[^\.][^/\x00]* |
/etc//demo///x | /etc/demo/x |
Verdicts are derived from the printed regular expression (tree for the conversion; /a[^b]c, /a[bc]d, /a[b-d]e and the brace rows were also run by the researcher).
| Pattern | Matches | Does not match |
|---|---|---|
/foo/*bar | /foo/bar, /foo/xbar | /foo/x/bar |
/foo/* | /foo/a, /foo/.hidden | /foo/ (the directory), /foo/a/, /foo/a/b |
/foo/*/ | the directories directly in /foo | /foo/, /foo/a |
/a*b | /ab, /axb | /a/b |
/foo/** | /foo/a, /foo/a/, /foo/a/b/c | /foo/, /foo |
/foo** | /foo, /foobar, /foo/, /foo/a/b | /fo |
/**/foo | /a/foo, /a/b/foo | /foo |
/** | every name that starts with / | / itself |
/{**,} | every name that starts with /, and / | names that do not start with / |
/a?c | /abc | /ac, /a/c, /abbc |
/a[bc]d | /abd, /acd | everything else |
/a[b-d]e | /abe, /ace, /ade | everything else |
/a[^b]c | /axc, /a/c | /abc, /ac |
/a{b,c{d,e}} | /ab, /acd, /ace | /ac |
/a{b,} | /ab, /a | /ac |
/a{b\,c,d} | /ab,c, /ad | /ab |
/*** | read as ** then *: the same names as /** | / itself |
* or ** that stands directly after a / and is followed by a / or by the end of the pattern must match at least one character (code: parser/parser_regex.c:180-205). The purpose, from the comment in the source: /foo/* should not match /foo/, /*/foo should not match //foo, and /foo/*bar should still match /foo/bar./. /foo/{*,bar} matches /foo/ (tree). /{*,x}/y matches //y, a name the kernel does not produce (code)./, except the root directory (code: linux:security/apparmor/path.c:167-177). A pattern matches a directory only if it can end in /.| To allow | Write |
|---|---|
| the directory itself (for listing it) | /dir/ r, |
| the directory and everything below | /dir/{,**} r, |
| everything below, not the directory | /dir/** r, |
| the files directly in it | /dir/* r, |
| the directories directly in it | /dir/*/ r, |
/ in a pattern are collapsed to one / (code: filter_slashes, parser/parser_regex.c:61-96). /a//b///c/ compiles as /a/b/c/ (tree).//a//b compiles as //a/b; ///usr becomes /usr./a/{/b,c} keeps the inner / and requires // in the name (tree).The variable syntax is in syn-variables. For patterns:
{v1,v2} (code: parser/variable.cc:252-340).@{APP_DATA} = /var/lib/demo /srv/demo, the path @{APP_DATA}/{cache,state}/** is expanded to {/srv/demo,/var/lib/demo}/{cache,state}/** (tree; the order of the values is the parser's).@{V}=/x/, @{V}/z becomes /x/z (tree).@{V}=a*b, /@{V} compiles as /a[^/\x00]*b (tree).Failed to find declaration for: @{NAME}, then ERROR expanding variables for profile NAME, failed to load (tree).| Written | Means |
|---|---|
\* \? \[ \] \{ \} | the literal character |
\, | a literal comma inside a brace group |
\\ | a backslash |
\ and any other character | that character; the backslash is dropped, with a warning of class format that is off by default |
Escape sequences such as \x41 are decoded earlier, by the lexer: see syn-quoting.
MAX_ALT_DEPTH is 50, parser/parser_regex.c:122).{a} and {} are errors; {a,} is accepted.{, } and , are literal./foobar, r, fails and "/foobar," r, is accepted (parser/tst/simple_tests/file/bad_comma_1.sd, ok_comma_2.sd). /a,b r, is accepted (ran).Syntax errors are printed as AppArmor parser error for FILE in profile FILE at line N: MESSAGE (tree). Pattern errors come from a later stage and have no line number. Each of them is followed by Unable to parse input line 'PATTERN' and ERROR processing regexs for profile NAME, failed to load, and every line is prefixed with the path of the parser program.
| Message | Cause | Example |
|---|---|---|
Regex grouping error: Invalid number of items between {} | a brace group without a comma | /var/lib/demo/{cache} rw, (tree) |
Regex grouping error: Unclosed grouping or character class, expecting close } | a { or a [ that is not closed | /var/lib/demo/{cache,state rw, (tree) |
Regex grouping error: Invalid close ], no matching open [ detected | a ] without a [ | /var/lib/demo/cache] rw, (tree) |
Regex grouping error: Invalid close }, no matching open { detected | a } without a {; printed after the "Invalid number of items" message | /a} r, (ran) |
Regex grouping error: Exceeded maximum nesting of {} | 50 nested brace groups | (tree) |
Regex error: trailing '\\' escape character | the pattern ends in a backslash | (code) |
Character %c was quotedunnecessarily, dropped preceding quote ('\\') character | a warning, class format, off by default; the missing space is in the parser's text | /a\qb r, (ran) |
Failed to find declaration for: @{NAME} then ERROR expanding variables for profile NAME, failed to load | an undeclared variable | @{HOME}/x r, without the tunables (ran) |
syntax error, unexpected TOK_END_OF_RULE, expecting TOK_MODE | an unquoted path that ends in a comma; a syntax error, with a line number | /etc/demo/extra, r, (tree) |
These are defects in the parser at the commit above, not intended behaviour. They are listed so that you can avoid them.
* and ? inside brackets are translated as globs instead of being literal. /a[?]b compiles without a message to /a[[^/\x00]]b, which matches /a[]b and not /a?b (tree). Write \? outside brackets, and [\*] for a star in a set.[ reports "expecting close }"./a[] r, prints only ERROR processing regexs for profile NAME, failed to load (tree).pattern_t convert_aaregex_to_pcre(const char *aare, int anchor, int glob,
std::string& pcre, int *first_re_pos)
parser/parser_regex.c:118
| What | Where |
|---|---|
the slash rule (mandatory [^/\x00]) | parser/parser_regex.c:180-205 |
** and the TailGlob classification | parser/parser_regex.c:207-220 |
* | parser/parser_regex.c:221-226 |
? | parser/parser_regex.c:231-254 |
[ and ] | parser/parser_regex.c:256-280 |
{, , and }; MAX_ALT_DEPTH | parser/parser_regex.c:282-357, 122 |
| error exits | parser/parser_regex.c:405-431 |
filter_slashes | parser/parser_regex.c:61-96 |
| the call for a rule path and for a link target | parser/parser_regex.c:659-660, 700-701 |
glob_default (0, paths) and glob_null (1, xattr values) | parser/parser.h:458-459 |
pattern_t: Basic, TailGlob, Regex, Invalid | parser/immunix.h:139-144 |
variable::expand_by_alternation | parser/variable.cc:252-340 |
negated sets: NotCharSetNode | parser/libapparmor_re/expr-tree.h:683-709 |
| the character set grammar | parser/libapparmor_re/parse.y:109-150 |
| unit tests | parser/parser_regex.c:1505-1516, 1576-1671 |
anchor is 0 at every call for rules.Basic means the pattern has no glob. Exec conflicts use a different test, made on the expression tree (parser/libapparmor_re/aare_rules.cc:98-105): a rule is exact when it has no star, any-character or negated-set node, so braces and plain sets are exact too: see syn-exec-modes.TailGlob is a literal followed by one final **; everything else with a glob is Regex.A hat is a nested profile that a running task switches into and out of with aa_change_hat(), without an exec. While the task is in the hat only the hat's rules apply.
int aa_change_hat(const char *subprofile, unsigned long magic_token); (apparmor.h:79). Include <sys/apparmor.h> and link with -lapparmor (aa_change_hat.pod:27-37).aa_change_hat() and replaces the label in the task's credentials (domain.c:1319-1332, task.c:167-173)./sys/kernel/security/apparmor/features/domain/change_hat and change_hatv (apparmorfs.c:2600-2602).^NAME { ... } or hat NAME { ... } inside a profile body. ^ must touch the name. A hat accepts the head parts of a profile except xattrs=( ).
HAT = ('hat' | '^') HATNAME [ PROFILE FLAG CONDS ] '{' ( RULES )* '}', and "If '^' is used to start a hat then there is no space between the '^' and HATNAME" (apparmor.d.pod:180-182).^stats /usr/bin/stats flags=(complain) { } inside a profile is accepted by the parser built from the AppArmor tree at 836052d21. What an attachment on a hat is for was not determined.xattrs=( ) on a hat is refused: hat profiles can't use xattrs matches.hat /does/not/exist//HAT1 { (new_style4.sd:16).change_hat rule. A task in a profile may ask for any hat of that profile.hat: hat_start profile_base (parser_yacc.y:490-504), hat_start: TOK_CARET | TOK_HAT (parser_yacc.y:1637-1638), rules: rules hat (parser_yacc.y:827-834). profile_base is the head rule of every profile (parser_yacc.y:391-399).{CARET} and {HAT} push the state SUB_ID (parser_lex.l:820, parser_lex.l:848), where the next id or quoted id is the name (parser_lex.l:456-461).A hat does not inherit the rules of the profile it is written in. By the kernel code, after change_hat only the hat's own rules apply. The outcomes shown follow from the rules; they were not run on a kernel.
demo//admin; the kernel does not combine it with demo./etc/passwd, changes into a hat without a rule for it, and shows that the read then fails, "even though we have a valid file descriptor at the time of the aa_change_hat() call" (aa_change_hat.pod:158-200).aa_change_hat("admin", token) writes changehat <token>^admin to /proc/<pid>/attr/current. The code of the kernel needs a child named admin that is a hat. aa_change_hat(NULL, token) returns; a different token is logged as "failed token match" and, by the kernel code, the task is sent the kill signal.
Kernel statements are read from the kernel source and were not run.
aa_change_hat() formats "changehat %016lx^%s", the token as 16 hex digits, and refuses a call where both the name and the token are empty with EINVAL (kernel.c:1028-1059). Afterwards it overwrites its copy of the token.aa_set_self_attr(LSM_ATTR_CURRENT, ...): the lsm_set_self_attr system call when the library has it enabled, otherwise a write to the thread's current file, /proc/<tid>/attr/apparmor/current or /proc/<tid>/attr/current (kernel.c:997-1012).setselfattr and setprocattr (lsm.c:1819-1821). do_setattr knows the commands changehat and permhat; permhat only tests (lsm.c:883-888).^. Several names may follow, separated by NUL bytes, at most 16 (procattr.c:80-94, procattr.c:104-135). The library call for a list is int aa_change_hatv(const char *subprofiles[], unsigned long token); (apparmor.h:83).change_hat() looks the name up among the children of the task's profile and requires the hat mark (domain.c:1215-1247). A task already in a hat is searched from the hat's parent, so it moves between sibling hats.EACCES (task.c:155-165). Returning compares the token again (task.c:185-194).info="failed token match" and the change_hat permission marked as kill, "to avoid brute force attacks" (domain.c:1414-1442). The manual says the same: "the current task will be killed" (aa_change_hat.pod:68-75).no_new_privs set on a confined task the switch is refused with EPERM unless the new label is a subset of the label saved when the flag was first seen; this is not logged (domain.c:1383-1390).lsm_set_self_attr and the attr files.Added to every hat and to every profile with a hat or child: /proc/*/attr/apparmor/ r, /sys/module/apparmor/parameters/enabled r, and /proc/[0-9]*/attr/{apparmor/,}current w,. The tree's parser prints them for demo and for the hat, and not for a plain child.
/proc/*/attr/apparmor/ r, then /sys/module/apparmor/parameters/enabled r, then /proc/[0-9]*/attr/{apparmor/,}current w, (block_rules.h:27)./proc/<tid>/attr/apparmor/, falls back to /proc/<tid>/attr/ unless /sys/module/apparmor/parameters/enabled says N, and writes the changehat line to current (kernel.c:93-106).apparmor_parser -Q -D rule-exprs FILE prints the rules of each profile after the additions; with the parser built from the AppArmor tree at 836052d21 they are shown for demo and for the hat, and not for a plain child.deny rule with a higher priority can override them.changeprofile request to that file. That request is checked separately against change_profile rules; see change_profile.ERROR adding hat access rule for profile NAME and carries on.profile_add_hat_rules returns early unless the profile has the HAT flag or defined_hats is not empty (profile.cc:78-89); called from Profile::add_implied_rules, where the error is printed and the return is commented out (profile.cc:114-126).block_rules::add_proc_access(const char *rule) creates the three entries; a FIXME says it "should use @{PROC}/@{PID}/attr/{apparmor/,}{current,exec}" (block_rules.cc:527-574).post_process_profile calls add_implied_rules() first (parser_policy.c:131).Each hat is loaded as a separate profile named parent//hat. Going by the kernel code, on apparmor_parser -r a hat that is no longer in the file stays loaded under the replaced parent; -R on the parent removes its hats.
Kernel statements are read from the kernel source and were not run.
apparmor_parser -N FILE (--names) lists what the file produces: demo, demo//admin, demo//worker (apparmor_parser.pod:102-104). Hats and children come out in name order, not source order.// (policy.c:523-544). If the parent is neither loaded nor in the same load it creates empty placeholder ancestors, "This allows for individual profile loading where the child is loaded before the parent" (policy.c:1293-1323).apparmor_parser -r: children of the old profile that the new one does not have are moved under the new profile, "inherit @child and its children" (policy.c:1066-1092). A hat deleted from the file therefore stays loaded.apparmor_parser -R: the parser removes the top profile only, and the kernel removes its children first (policy.c:200-235).apparmor_parser -R FILE, then load the file again.Unable to add "%s". and Unable to replace "%s"., with the short name.Profile::hname() builds parent//name (profile.h:454-460); a flattened profile is written under that name (parser_interface.c:488-490, parser_interface.c:666-681).load_flattened_hats runs after the parent is written and is skipped for OPTION_REMOVE (parser_interface.c:783-785, parser_policy.c:70-89).__list_lookup_parent searches the load set (policy.c:1031-1052); a new profile is added to its parent's base.profiles (policy.c:1402-1409).hat: hat_start profile_base sets profile_flag_t::HAT; it is written as value 1 (bit 0) of the flags word; the kernel sets FLAG_HAT; change_hat() requires PROFILE_IS_HAT.
CARET "^" (parser_lex.l:248); {CARET} returns TOK_CARET and {HAT} returns TOK_HAT, both pushing SUB_ID (parser_lex.l:820, parser_lex.l:848); in SUB_ID the next id is TOK_ID (parser_lex.l:456-461).hat: hat_start profile_base sets prof->flags.flags |= profile_flag_t::HAT and rejects xattrs (parser_yacc.y:490-504); rules: rules hat calls $1->add_hat($2) (parser_yacc.y:827-834).block::add_hat(Profile *hat) sets the parent and inserts into defined_hats and hats; a duplicate name prints Multiple definitions for profile %s exist,bailing out. and exits. add_subblock and add_cond_set copy hats out of inner blocks (block.cc:137-204).HAT is bit 0 of profile_flag_t (profile.h:135), written as the first u32 of struct flags with profile_flag_bits() (parser_interface.c:526).post_process_profile adds the implied rules and recurses into defined_hats (parser_policy.c:127-165, profile.cc:78-89); each nested profile is then written by load_flattened_hats (parser_policy.c:84-89, parser_interface.c:783-785).if (tmp & PACKED_FLAG_HAT) profile->label.flags |= FLAG_HAT; (policy_unpack.c:1216-1217); #define PROFILE_IS_HAT(_profile) ((_profile)->label.flags & FLAG_HAT) (policy.h:50).change_hat(): aa_find_child(root, name) by short name; a child without the mark gives info = "target not hat" and -EPERM (domain.c:1215-1266).FLAG_HAT too (policy.c:780-782).^ must touch the name. A hat and a child profile may not share a name. A top-level ^name { } is not reachable by change_hat in the kernel. Run-time failures, when they are logged, carry info="hat not found", "no hats defined" or "target not hat".
Kernel statements are read from the kernel source and were not run.
Lexer found unexpected character: ' ' (0x20) in state: SUB_ID: a blank between ^ and the name (parser built from the AppArmor tree at 836052d21).Multiple definitions for profile NAME exist,bailing out.: two hats, or a hat and a child profile, with one name in one profile. Parser 5.0.2 prints Multiple definitions for hat NAME in profile (null) exist,bailing out.^name { } without parent// is accepted and loaded with the hat mark. change_hat searches only the children of the task's profile, or of its parent when the task is in a hat, so nothing can switch into it (domain.c:1215-1233). The form that works at top level names the parent: hat /does/not/exist//HAT1 { (new_style4.sd:16).hat not found with ENOENT, no hats defined with ECHILD (domain.c:1257-1266), target not hat with EPERM (domain.c:1238-1243). The manual lists the same error codes (aa_change_hat.pod:87-122).EPERM with info="unconfined can not change_hat" (domain.c:1344-1362).operation="change_hat"; the libapparmor test corpus has examples (testcase_changehat_01.in).SUB_ID has no white-space rule.block::add_to_known_hats (block.cc:137-146).opt_profile_flag: hat_start gives 2, and the profile gets HAT (parser_yacc.y:381-383, parser_yacc.y:475-476).Entering a hat is checked only for a child with the hat mark; no rule of the profile is consulted, and the parser adds /proc/[0-9]*/attr/{apparmor/,}current w, to the profile and to each hat. Leaving, or changing to another hat, needs the token given on entry; a wrong token is logged as "failed token match" and the task is killed. Read from the kernel code, not run.
All kernel statements are read from the kernel source and were not run.
change_hat() looks the name up among the children of the task's profile (or, from inside a hat, among its siblings) and refuses a child without the hat flag. No permission of the profile's rule set is consulted (domain.c:1169-1300).changehat <token>^<name> to /proc/<tid>/attr/current or /proc/<tid>/attr/apparmor/current. The parser adds the file rule that allows that write to every hat and to every profile with a hat or a child: /proc/[0-9]*/attr/{apparmor/,}current w, (profile.cc:78-89, block_rules.h:27). Run with the parser built from the AppArmor tree at 836052d21 (-Q -D rule-exprs): the rule is printed for demo and for its hat.-EACCES from either check goes to the kill: label, "kill task in case of brute force attacks", which sets info="failed token match" and marks the request to be killed (domain.c:1319-1436); the audit step then sends the profile's signal, SIGKILL unless kill.signal= changed it (audit.c:228-231).changeprofile request; that one is checked against change_profile rules.no_new_privs set on a confined task a switch is refused unless the new label is a subset of the label saved when the flag was set.The API: lib-change-hat. The exec-time sibling: syn-child-profiles. Names: syn-profile-name.
^NAME { } or hat NAME { } inside a profile; loaded as parent//NAME; entered with aa_change_hat(NAME, token) and left with aa_change_hat(NULL, token).changehat request and nothing else.apparmor_parser -r; remove the parent with -R and load again.Rows marked "tree" were run with the parser built from the AppArmor tree at the commit above (-Q -K --skip-kernel-load --warn=all). Rows marked "5.0.2" were run with the installed parser 5.0.2. Kernel behaviour was read from the kernel's code and not run on a kernel.
( ^ | hat ) NAME [ ATTACHMENT ] { + identities=( ... ) } [ flags=( ... ) ] { rules }
^ is followed directly by the name: ^admin. After hat come blanks and then the name, on the same line.NAME is one word or one quoted string. It may start with /: ^/HAT1 { } is accepted (fixture change_hat/new_style2.sd).hat admin { } and ^stats /usr/bin/stats flags=(complain) { } are accepted inside demo (tree). xattrs=( ) is parsed and then rejected.hat parent//name { } and ^name { } are accepted by the same rule as profile. hat demo//late { } after demo produces demo//late (tree; fixture change_hat/new_style4.sd). ^name { } with no parent// produces a top-level profile with the hat mark and no parent.| Spelling | Where | Meaning |
|---|---|---|
^ | start of a nested head, touching the name | the block is a hat |
hat | start of a nested head, then blanks and the name | the same |
// | in loaded names | separates parent and hat: demo//admin; written by the parser |
change_hat rule keyword in the profile language. A program in demo may ask for any hat of demo.^ elsewhere is an ordinary character: /foo^bar r, is a plain path, and the old spelling /path^HAT { } is one profile named /path^HAT (5.0.2).| Rule added | Why |
|---|---|
/proc/*/attr/apparmor/ r, | the library looks for the AppArmor attribute directory |
/sys/module/apparmor/parameters/enabled r, | the library checks that AppArmor is enabled |
/proc/[0-9]*/attr/{apparmor/,}current w, | the file the changehat command is written to |
apparmor_parser -Q -D rule-exprs on demo with ^admin on demo with ^admin and profile kid prints the three rules for demo and for the hat admin, and not for the plain child kid (tree).parser/tst/equality.sh:955-975).changeprofile request. That request is checked separately against change_profile rules; see syn-change-profile.demo, demo//admin, demo//worker. apparmor_parser -N prints these names (tree).// and adds the new profile to the parent's children. Lookups use the short name after the last //.-r): children of the old profile that the new one does not have are moved under the new profile. A hat deleted from the file therefore stays loaded.-R): the parser removes the top profile only, and the kernel's code removes its children with it. To drop a deleted hat, remove the parent and load the file again.The library call is described in lib-change-hat. It writes changehat <16 hex digits of token>^<hat> to /proc/<pid>/attr/current. This table is read from the kernel's code.
| Situation | Result | info | Error |
|---|---|---|---|
| the task's profile has a child of that name with the hat mark | the task switches; the token is remembered | ||
| no child of that name, the profile has other children | refused | hat not found | ENOENT |
| the profile has no children | refused | no hats defined | ECHILD |
the child was declared with profile, not as a hat | refused | target not hat | EPERM |
| no name, the right token | the task returns to the profile it left | ||
| a token different from the one remembered | refused, and the task is killed | failed token match | EACCES |
| the task is unconfined and has no hats | refused | unconfined can not change_hat | EPERM |
no_new_privs set on a confined task the switch is refused with EPERM unless the new label is a subset of the label saved when the flag was set; this case is not audited.Log lines from the libapparmor test corpus (libraries/libapparmor/testsuite/test_multi/testcase_changehat_01.in and unconfined-change_hat.in):
apparmor="ALLOWED" operation="change_hat" profile="/usr/sbin/httpd{,2}-prefork" pid=8527 comm="httpd-prefork" target="/usr/sbin/httpd{,2}-prefork//HANDLING_UNTRUSTED_INPUT"
apparmor="ALLOWED" operation="change_hat" info="unconfined can not change_hat" error=-1 profile="unconfined" pid=19941 comm="apache2"| Message | Cause |
|---|---|
hat profiles can't use xattrs matches | xattrs=( ) in a hat's head (tree) |
Multiple definitions for profile %s exist,bailing out. | two hats, or a hat and a child profile, with one name in one profile (tree). 5.0.2 prints Multiple definitions for hat %s in profile (null) exist,bailing out. |
Lexer found unexpected character: ' ' (0x20) in state: SUB_ID | a blank between ^ and the name (tree) |
Profile names must begin with a '/', namespace or keyword 'profile' or 'hat'. | a top-level name with none of these |
Assert: 'hat rule' returned NULL. | internal error in the grammar |
ERROR adding hat access rule for profile %s | the implied rules could not be added; printed and then ignored |
Unable to add "%s". and Unable to replace "%s". | the kernel refused a profile on load; %s is the short name |
parser/apparmor.d.pod:182). The parser accepts ^/HAT1.HAT production shows no attachment (parser/apparmor.d.pod:180). The grammar accepts one.demo//worker//inner. Going by the kernel's code it cannot be reached by change_hat from the outer hat, because from inside a hat the siblings are searched.^name { } without parent// is accepted and loaded with the hat mark. change_hat looks only among the children of the task's profile, so nothing can switch into it.deny { ^blocked { /x w, } } inside demo lists demo//blocked with -N in the tree; 5.0.2 accepts the text and does not list the hat./path^HAT { } is a plain profile name, not a hat.cx -> hatname can enter a hat was not determined. The exec path in the kernel's code does not test the hat mark.| What | Where |
|---|---|
^ is {CARET}, hat{WS}* is {HAT}; both push SUB_ID | parser/parser_lex.l:248, 277, 820, 848 |
in SUB_ID the next {IDS} or {QUOTED_ID} is TOK_ID; no white-space rule | parser/parser_lex.l:372-373, 456-461; error at 930 |
hat: hat_start profile_base; sets profile_flag_t::HAT; rejects xattrs | parser/parser_yacc.y:490-504, 1637-1638 |
rules: rules hat | parser/parser_yacc.y:827-834 |
top-level hat_start in opt_profile_flag | parser/parser_yacc.y:381-383, 475-476 |
block::add_to_known_hats, block::add_hat; hats and defined_hats are sets ordered by namespace then name | parser/block.cc:137-155, parser/profilelist.h:28, parser/profile.h:431-443 |
block::add_subblock, block::add_cond_set copy hats out of inner blocks; block::update_parent | parser/block.cc:161-204 |
profile_add_hat_rules, Profile::add_implied_rules | parser/profile.cc:78-89, 114-126 |
block_rules::add_proc_access, CHANGEHAT_PATH | parser/block_rules.cc:527-574, parser/block_rules.h:27 |
post_process_profile recurses into defined_hats | parser/parser_policy.c:127-165 |
Profile::hname() builds parent//hat | parser/profile.h:454-460 |
HAT = 1 << 0; packed into the flags struct | parser/profile.h:135, parser/parser_interface.c:526 |
load_flattened_hats, called after the parent is written; skipped for remove | parser/parser_policy.c:70-89, parser/parser_interface.c:783-785 |
load_hats (hats embedded in the parent's stream) has no caller | parser/parser_policy.c:96-103 |
kernel: packed hat flag becomes FLAG_HAT; PROFILE_IS_HAT | linux:security/apparmor/policy_unpack.c:1216-1217, linux:security/apparmor/include/policy.h:50 |
kernel: __lookup_parent, __list_lookup_parent, __create_missing_ancestors | linux:security/apparmor/policy.c:523-590, 1031-1052, 1293-1323 |
kernel: replaced parent inherits old children; __remove_profile | linux:security/apparmor/policy.c:1071-1091, 200-239 |
kernel: do_setattr dispatches changehat and permhat | linux:security/apparmor/lsm.c:883-888 |
kernel: split_token_from_name, aa_setprocattr_changehat | linux:security/apparmor/procattr.c:70-128 |
kernel: change_hat, aa_change_hat | linux:security/apparmor/domain.c:1169-1300, 1319-1436 |
kernel: aa_set_current_hat, aa_restore_previous_label | linux:security/apparmor/task.c:156-195 |
library: "changehat %016lx^%s" | libraries/libapparmor/src/kernel.c:1033 |
+ identities=(demo-role) declares an extra name for the profile. The parser sends identities only to a kernel that advertises domain/identity; the kernel does not, so there they have no effect.
+ identities=(demo-role) in the profile head, after xattrs=( ) and before flags=( ).identities=(unconfined) "keeps working with peers that refer to it as peer=unconfined" (apparmor.d.pod:552-556). This was not verified in code; how a rule that names an identity as its peer is compiled was not determined.identity entry among the files of /sys/kernel/security/apparmor/features/domain/ (apparmorfs.c:2600-2615). Check a running kernel with ls /sys/kernel/security/apparmor/features/domain/.+ identities=( VALUE ... ), one or more groups, after xattrs=( ) and before flags=( ). Values are words or quoted strings separated by white space or commas; each group needs at least one.
{ '+' 'identities' '=' '(' VALUE { [','] VALUE } ')' }, in the head as [profile] NAME [ATTACHMENT] [xattrs=(...)] [+ identities=(...)]... [flags=(...)] {.+ and holds at least one value.+ is optional: profile p +identities=(foo) { (ok_identity_10.sd:5).identities is a keyword only when = follows it (white space may come between).profile demo /usr/bin/demo + identities=(demo-role, "/srv/demo svc") + identities=(web) {.SUBPROFILE and HAT (apparmor.d.pod:178-180), while its text says they are allowed there (apparmor.d.pod:549-550).profile_base: TOK_ID opt_id_or_var opt_cond_list identities flags TOK_OPEN (parser_yacc.y:391); the productions identities, identity_item and identitiesvals (parser_yacc.y:631-659).+ returns TOK_PLUS and pushes the state IDENTITY_VALUE (parser_lex.l:826); identities before = returns TOK_IDENTITIES (parser_lex.l:408-416); the list is read in LIST_VAL_MODE, where commas are skipped (parser_lex.l:479-488).+ identities=(a, b) and + identities=(a) + identities=(b) give the same list. A value containing a space must be quoted and begin with /.
+ identities=(a), + identities=(a, b) and + identities=(a) + identities=(b) are all accepted; the last two give the same list.profile test + identities=(foo, bar) { (ok_identity_02.sd:5) and profile test + identities=(foo)+ identities=("/bar") { (ok_identity_05.sd:5).profile p + identities=(foo) + identities=("/bar baz") {, which "declares the two identities foo and /bar baz" (apparmor.d.pod:541-547).Space character not allowed in identities: '%s'.identities: identities TOK_PLUS identity_item with list_append($$, $3) (parser_yacc.y:635-643); values are appended the same way (parser_yacc.y:650-659).$1[0] != '/' && strchr($1, ' ') (parser_yacc.y:661-664).Identities are written only when domain/identity is in both the kernel's features and the policy ABI. The kernel does not advertise it, and nothing is printed when identities are dropped.
domain/identity must be in the kernel's features and in the policy ABI; the two are intersected (parser_main.c:1000-1003, parser_main.c:1123-1125)./sys/kernel/security/apparmor/features/ (or --kernel-features FILE); the policy ABI comes from the abi <...>, rule in the profile file (or --policy-features FILE).identity with one string per value (parser_interface.c:333-344); when it fails it writes nothing (parser_interface.c:562-563) and prints nothing, also with --warn=all.features/domain/ has change_hat, change_hatv, unconfined_allowed_children, change_onexec, change_profile, stack, fix_binfmt_elf_mmap, post_nnp_subset, computed_longest_left, attach_conditions/, disconnected.path, kill.signal and version; no identity (apparmorfs.c:2600-2615).identity field: after the capability sets it goes on to xattrs (policy_unpack.c:1265-1293).domain/identity entry.+ identities=(demo-role) under abi <abi/5.0>,, dumped with -S, contains the strings flags, path_flags, xattrs and no identity.abi rule pins policy to a feature set.TOK_PLUS → IDENTITY_VALUE → TOK_IDENTITIES → Profile::identities → sd_serialize_identity() if features_supports_identity_names. In the kernel, unpack_profile() has no identity field.
{PLUS} returns TOK_PLUS and pushes IDENTITY_VALUE (parser_lex.l:826). In that state identities/{WS}*= returns TOK_IDENTITIES and switches to EXTCOND_MODE (parser_lex.l:408-416). IDENTITY_CHAR is [^ \t\r\n"!,{}\\=] (parser_lex.l:265); the state's own value rule is at parser_lex.l:472-477.+ followed by something that is not identities=, as in profile demo /usr/bin/demo + {, ends with flex scanner jammed and the parser exits (seen with the parser built from the AppArmor tree at 836052d21; the test file is bad_identity_02.sd).identities, identity_item, identitiesvals, identitiesval (parser_yacc.y:631-670); the result is stored in Profile::identities, a struct value_list * (profile.h:394), freed in the destructor (profile.cc:60-61).features_supports_identity_names = features_intersect(kernel_features, policy_features, "domain/identity") (parser_main.c:1123-1125).void sd_serialize_identity(std::ostringstream &buf, struct value_list* l) writes sd_write_array(buf, "identity", list_sz) and one string per value (parser_interface.c:333-344); the only call is guarded by the flag (parser_interface.c:562-563).unpack_profile() reads caps64, capsx, then calls unpack_xattrs(); there is no identity (policy_unpack.c:1265-1293).Identities go before flags=( ) and each group starts with +. identities=() is a syntax error. "Space character not allowed in identities: '...'" means a value with a space that does not begin with /.
Messages are verbatim, seen with the parser built from the AppArmor tree at 836052d21 (-Q -K --skip-kernel-load, nothing loaded into a kernel).
syntax error, unexpected TOK_PLUS, expecting TOK_OPEN.+, as in profile p identities=(foo) { (bad_identity_04.sd): syntax error, unexpected TOK_IDENTITIES, expecting TOK_OPEN.profile p + identities=() { (bad_identity_01.sd): syntax error, unexpected TOK_CLOSEPAREN, expecting TOK_VALUE./, as in profile p + identities=("a a" "b") { (bad_identity_05.sd:5): Space character not allowed in identities: '%s'.+ with nothing after it, profile p + { (bad_identity_02.sd): flex scanner jammed, and the parser exits.domain/identity.AppArmor parser error for FILE in profile FILE at line N: MESSAGE.profile_base (parser_yacc.y:391); the "at least one value" rule and the space check from identitiesvals and identitiesval (parser_yacc.y:650-664).Before identities: syn-xattrs. After: syn-flags-modes. The feature check: adm-features and syn-abi. What the kernel reads: k-unpack.
+ identities=( VALUE ... ): one or more groups after xattrs=( ) and before flags=( ); all values end up in one list.domain/identity is in both the kernel's features and the policy ABI. The kernel does not advertise it, and the parser is silent when it drops them.Parser results on this page come from the parser built from the AppArmor tree at the commit above, unless a row says otherwise. Kernel statements come from reading the source of mainline Linux 7.4-rc2 (97d73c825); nothing here was run on a kernel.
identities: { '+' 'identities' '=' '(' VALUE { [','] VALUE } ')' }
[profile] NAME [ATTACHMENT] [xattrs=(...)] [+ identities=(...)]... [flags=(...)] {
xattrs=( ) and before the flags. The order is fixed.+ and holds at least one value.+ identities=(a, b) and + identities=(a) + identities=(b) are the same.profile demo /usr/bin/demo + identities=(demo-role, "/srv/demo svc") + identities=(web) {.| Element | Meaning |
|---|---|
+ | starts a group. The blank after it is optional: +identities=(foo) |
identities | a keyword only when followed by = (white space may come between) |
( ... ) | the list; values are separated by white space, commas or both |
| VALUE | a word or a quoted string. A value that contains a space must be quoted and must start with / |
Fixtures in the AppArmor tree: parser/tst/simple_tests/profile/identities/ (ok_identity_02.sd: (foo, bar); ok_identity_05.sd: two groups and a quoted "/bar"; ok_identity_10.sd: +identities=(foo)).
| Condition | What the parser writes |
|---|---|
domain/identity is in the kernel's features and in the policy ABI | an array named identity, one string per value |
either side lacks domain/identity | nothing, and no warning, even with --warn=all |
domain/identity and its profile unpack code reads no identity field (read in the source, not run).abi/5.0 file in the AppArmor tree has no domain/identity entry.profile demo /usr/bin/demo xattrs=(user.demo=trusted) + identities=(demo-role) flags=(complain, attach_disconnected) { under abi <abi/5.0>,, compiled by the tree's parser and dumped with -S, contains the strings flags, path_flags, xattrs and user.demo and no identity.This section repeats apparmor.d(5). It was not verified in code, and how a rule that names an identity as its peer is compiled was not determined.
identities=(unconfined) keeps working with peers that refer to it as peer=unconfined, which eases a move from unconfined to confined.domain/identity. Without it they are not passed to the kernel and a peer that refers to the profile by an identity will not match it, "so policy must not rely on identities for confinement".| Message | Cause |
|---|---|
Space character not allowed in identities: '%s' | a value with a space that does not start with /, such as + identities=("demo role") |
syntax error, unexpected TOK_PLUS, expecting TOK_OPEN | identities written after the flags |
syntax error, unexpected TOK_IDENTITIES, expecting TOK_OPEN | identities=( ) without the + |
syntax error, unexpected TOK_CLOSEPAREN, expecting TOK_VALUE | an empty list: + identities=() |
flex scanner jammed (the parser exits) | a + followed by something that is not identities=, such as profile demo /usr/bin/demo + { |
| (no message) | identities dropped because the kernel or the policy ABI lacks domain/identity |
SUBPROFILE and HAT, while the text of the same page says identities can be declared on child profiles and hats, and the parser's grammar allows them.| Step | Where |
|---|---|
+ gives TOK_PLUS and pushes the IDENTITY_VALUE state | parser/parser_lex.l:826 |
identities before = gives TOK_IDENTITIES | parser/parser_lex.l:408-416 |
IDENTITY_CHAR and the IDENTITY_VALUE value rule | parser/parser_lex.l:265, 472-477 |
the list in LIST_VAL_MODE; commas are skipped | parser/parser_lex.l:479-488 |
profile_base: the seat between the conditions and the flags | parser/parser_yacc.y:391 |
identities, identity_item, identitiesvals, identitiesval | parser/parser_yacc.y:631-670 |
| the space check | parser/parser_yacc.y:663-664 |
prof->identities = $4 | parser/parser_yacc.y:441 |
Profile::identities, a struct value_list *; freed in the destructor | parser/profile.h:394, parser/profile.cc:60-61 |
features_supports_identity_names: kernel and policy features intersected for domain/identity | parser/parser_main.c:1123-1125, 1000-1003 |
sd_serialize_identity() and its call | parser/parser_interface.c:333-344, 562-563 |
kernel unpack_profile(): caps64, capsx, then unpack_xattrs(); no identity | linux:security/apparmor/policy_unpack.c:1265-1293 |
kernel aa_sfs_entry_domain[]: no identity entry | linux:security/apparmor/apparmorfs.c:2600-2615 |
| man page text | parser/apparmor.d.pod:540-561, grammar 178-180 |
| fixtures | parser/tst/simple_tests/profile/identities/ |
include replaces itself with a file's contents. apparmor_parser -p prints the assembled text.
-p on the 14-line example of this district, with the tree's own tunables/ and abstractions/ on the search path, prints 799 lines.profiles/apparmor.d of the tree there are 1126 include lines; 358 of them are include if exists.profiles/apparmor.d is drawn as /etc/apparmor.d, where it is installed.demo and its profile are invented for the map.include <magic/path> or include "path", no comma. #include is the older spelling of the same line.
include <...>, include "...", #include <...>, #include "...". A fifth, an unquoted path, is treated like the quoted form (include_tests/ok_16.sd, a test the parser is expected to accept).<"name"> is accepted.#include gives the warning deprecated use of '#include' only with --warn=pound-include or --warn=all (run with the tree's parser for this deck). Shipped policy has one #include left (locale:14).include/{WS} pushes the scanner state INCLUDE (parser_lex.l:804-809).#include/.*\r?\n is matched before the comment rule (parser_lex.l:796-802, parser_lex.l:815-818).< >: the -I directories in order, then the base directory. " ": the path as written, relative to the working directory.
-I, in the order given, and then in the base directory. The first directory that has the name is used. At most 100 -I directories are accepted./etc/apparmor.d, or the directory given with -b./srv/policy and "local/demo.rules" are invented names.AppArmor parser error for /work/inc-missing.sd in profile /work/inc-missing.sd at line 3: Could not open 'local/demo', exit status 1. The second error is recorded in the research notes. /work/inc-missing.sd is the scratch name of the file.-b and -I in terms that do not match the code. The deck follows the code; the man page says -b is "for resolving #include directives defined as relative paths" (apparmor_parser.pod:172-180).-I shadows files of the base directory for every magic path. Whoever chooses the parser's options, or can write to a directory on the path, chooses the text of every profile: see Who can change policy.include_filename(filename, search, if_exists) (parser_lex.l:162-225).search_path() (parser_include.c:154-187); the list of directories (parser_include.c:66-152).fopen() unchanged (parser_lex.l:185-186).apparmor_parser -p FILE prints the text after includes. Marker lines start with ##.
-p on the example file prints 799 lines. The markers of the preamble, in order: ##included <tunables/global>, <tunables/home>, <tunables/home.d>, <tunables/multiarch>, <tunables/multiarch.d>, <tunables/proc>, ##failed include <tunables/proc.d>, and so on through alias, kernelvars, system, xdg-user-dirs, share, etc and run. The slide leaves most of them out and keeps the order.##included <abstractions/base>, <abstractions/crypto>, <abstractions/openssl>, <abstractions/upki>, with ##failed include for their .d directories and for <local/demo>.##included <name>, ##skipped duplicate include <name>, ##failed include <name>. Quoted paths print with quotes: ##included "/path".-p stops after this step and compiles nothing. Other preamble lines (abi, assignments, alias) are printed unchanged, and variables are not expanded in this output.##failed include appears only for include if exists; a plain include of a missing file is an error.-p prints ##included "PATH" for a quoted include that does not exist.One include of a file per preamble and per profile, child profile or hat. Later ones are skipped silently.
-p. The output has ##included <tunables/global> and later ##skipped duplicate include <tunables/global>; inside demo, ##included <abstractions/base> and ##skipped duplicate include <abstractions/base>; inside demo-helper, ##included <abstractions/base> again. Exit status 0. The research notes record the same for one profile.if or qualifier block makes the same include in the rest of the profile a no-op.g_includecache is a std::set<std::string> (file_cache.h:27-47).parser_lex.l:804-809 matches the keyword, 162-225 opens the file and pushes a buffer, 400-406 pops it.
include_filename(): parser_lex.l:162-225. The pop at end of file: parser_lex.l:400-406. search_path(): parser_include.c:154-187.current_filename, current_lineno, parser_include.c:197-239). That is why they read in profile <included file> at line N.update_mru_tstamp, parser_lex.l:154, parser_lex.l:204, parser_lex.l:210).MAX_NEST_LEVEL is defined and not used (parser_include.c:58); no depth limit was found.if false { include <does/not/exist> } gives Could not open 'does/not/exist'.deny { } becomes deny rules.No comma after an include. Could not open 'NAME' means the name was not found on the search path.
AppArmor parser error for /work/i06a.sd in profile /work/i06a.sd at line 2: syntax error, unexpected TOK_END_OF_RULE, expecting TOK_ID or TOK_MODE or TOK_SET_VAR. The file names under /work/ are scratch names of the runs.AppArmor parser error for /work/i06d.sd in profile /work/i06d.sd at line 3: Could not open 'abstraction/base'.--warn=all: Warning from /work/i06e.sd (/work/i06e.sd line 3): deprecated use of '#include', exit status 0. The warning class is pound-include, which is not in the default set; --warn=pound-include turns it on alone.fstat failed for '%s', Failed to process filename.Onward: include if exists, abstractions and tunables, running the parser, comments.
Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run on the fragment (-Q -K --skip-kernel-load, with the tree's abi/5.0 file as kernel feature set and the tree's profiles/apparmor.d on the search path), with nothing loaded into a kernel; "code" means the parser source was read and not run; "derived" means the result was reasoned from that code. Nothing here was observed on a running kernel.
INCLUDE: ( 'include' | '#include' ) [ 'if' 'exists' ] ( <magic/path> | "path" | path )
include <...>, include "...", #include <...>, #include "..." and a bare path, which is treated like the quoted form (code; the test include_tests/ok_16.sd).<"name"> is accepted (code).if exists makes a missing file acceptable, and the name may be a directory: see syn-include-if-exists.| Form | Search path | Relative to | Example |
|---|---|---|---|
<name> | yes: each -I directory, then the base directory | the directory that has it | include <abstractions/base> |
"name" | no | the working directory of the parser, unless absolute | include "/etc/demo/extra.rules" |
| bare name | no | as the quoted form | include simple_tests/include_tests/includes/base |
The second and third example paths are illustrations (derived); the first is in the running example (tree).
-I DIR adds a directory; several are tried in the order given, at most 100 (code)./etc/apparmor.d, or the directory given with -b (code).-b is "for resolving #include directives defined as relative paths". The code uses it as the last directory of the search for magic paths and not for quoted relative paths. This page follows the code.apparmor_parser -p FILE prints the text after includes and compiles nothing.
| Marker | Meaning | Line in the running example |
|---|---|---|
##included <name> | the file was taken; its text follows | ##included <tunables/global> |
##skipped duplicate include <name> | already taken in this preamble or profile | none; see the scene "A file is taken once per profile" |
##failed include <name> | not found; only include if exists gets this far | ##failed include <local/demo> |
The running example gives 799 lines for 14 lines of input (tree).
The parser remembers which files it has included. A new, empty list starts at:
A second include of a file within one list is skipped without a message. A file that includes itself is stopped the same way (the test include_tests/recursive_2.sd).
| Message | Cause | Class, default | Basis |
|---|---|---|---|
Could not open 'NAME' | the name was not found; exit status 1 | error | tree |
syntax error, unexpected TOK_END_OF_RULE, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | a comma after an include in a profile | error | tree |
Lexer found unexpected character: '<' (0x3c) in state: INCLUDE | the closing bracket is missing | error | tree |
Lexer found unexpected character: '<' (0x3c) in state: INITIAL | no blank after the keyword | error | tree |
deprecated use of '#include' | the #include spelling | warning pound-include, off by default | tree |
fstat failed for 'NAME' | the opened file could not be examined | error | code |
Failed to process filename | the file name could not be taken from the line | error | code |
include/{WS} pushes INCLUDE (parser_lex.l:804-809); the #include form (parser_lex.l:796-802); file name patterns (parser_lex.l:376-398); end of file pops the buffer (parser_lex.l:400-406).include_filename(filename, search, if_exists) (parser_lex.l:162-225) and search_path() (parser_include.c:154-187).g_includecache (file_cache.h:27-47); one per profile (parser_yacc.y:396-397, parser_yacc.y:454-455).if or qualifier block makes the same include in the rest of the profile a no-op. Recorded in the research notes.-p prints ##included "PATH" for a quoted include that does not exist. Recorded in the research notes.-b and -I in terms that do not match the code (apparmor_parser.pod:172-180).include if exists <local/demo>: taken when the file is there, skipped without an error when it is not.
include <local/demo> gives AppArmor parser error for /work/inc-missing.sd in profile /work/inc-missing.sd at line 3: Could not open 'local/demo', exit status 1. /work/inc-missing.sd is the scratch name of the file.include if exists <local/demo> the example file of this district compiles with exit status 0 and the same 106 compiled lines, and -p prints ##failed include <local/demo> (run with the tree's parser for this deck).local/demo file, because the tree used for the runs cannot be changed. /srv/demo-extra/** r, is an invented line. A run with a file that is present is in the scene "Your change goes in your file".include lines under profiles/apparmor.d of the tree are include if exists.include if exists <magic/path> or "path". Same name forms and search as include; no comma.
exists.include: see include.if and exists are not keywords anywhere else in this position.#include if exists <includes-preamble-does-not-exist> (include_tests/preamble_good_6.sd, a test the parser is expected to accept).include.#include if exists gives the deprecated use of '#include' warning with --warn=pound-include.include{WS}+if{WS}+exists/{WS} pushes the scanner state INCLUDE_EXISTS (parser_lex.l:789-794); the #include form is at parser_lex.l:781-787.A directory include takes every regular file in it. Hidden files, README, package leftovers and backups are skipped.
., the name README, and names ending in .dpkg-new, .dpkg-old, .dpkg-dist, .dpkg-bak, .dpkg-remove, .pacsave, .pacnew.Ignoring: '<path>' on standard error: names ending in .rpmnew, .rpmsave, .orig, .rej and ~.if exists too; a missing directory is then an error.tunables/home.d/site.local only.-p line is from a run with the tree's parser for this deck, on the example file of this district.bad-include.dpkg-new, bad-include~ and one good-include compiles (include_tests/ignored_suffix_1.sd).fstat() decides between a file and a directory (parser_lex.l:199-217).dirat_for_each() and include_dir_cb() (parser_lex.l:128-160; private.c:498-565).Add a file to tunables/home.d/ with @{HOMEDIRS} += /srv/nfs/home/. Every rule written with @{HOME} follows.
-D rule-exprs dump has aare: {/home/*,/root}/.ssh/**. After: aare: {/home/*,/root,/srv/nfs/home/*}/.ssh/**, exit status 0.site.local (@{HOMEDIRS} += /srv/nfs/home/) stood in a directory given with -I and was included through include if exists <site.local> in the profile's own preamble, after include <tunables/global>. It stands in for a file in tunables/home.d/, which could not be added to the tree used for the runs. -p of that run shows ##included <site.local> followed by @{HOMEDIRS} += /srv/nfs/home/.+= is needed because = on a variable that is already declared is an error: see Variable assignment..d directories with a site.local of comments: tunables/home.d, tunables/multiarch.d, tunables/xdg-user-dirs.d.tunables/global includes ends with include if exists <tunables/NAME.d>, and shipped abstractions end with include if exists <abstractions/NAME.d> (base:184).site.local is itself a file of the tree; whether a package upgrade leaves a changed copy alone depends on the distribution's packaging, which was not examined.Files in abstractions/NAME.d/ and tunables/NAME.d/ are compiled into every profile that includes NAME. Absence is silent.
include if exists <abstractions/base.d> (base:184); tunables/global ends with include if exists <tunables/global.d>.anything and @{HOME} += / are illustrations derived from the include mechanism. No run added a file to the tree's .d directories.profiles/apparmor.d of the tree include abstractions/base (counted for this deck with grep).AppArmor parser error for /work/ie-bad.sd in profile /work/site-bad.local at line 1: Variable declarations do not accept trailing commas, exit status 1. The file site-bad.local held @{HOMEDIRS} += /srv/nfs/home/, and was included through include if exists from a directory given with -I.##failed include <name> in -p output is the only trace of a missing magic path./etc/apparmor.d, written by root and by packages: see Who can change policy.-p prints ##included "PATH" for a quoted include that does not exist.if or qualifier block makes the same include in the rest of the profile a no-op.include if exists <local/NAME> compiles with and without the file, and neither its presence nor its absence is reported..d directories of everything it includes, and the -I directories of the parser's invocation.parser_lex.l:789-794 is the pattern, 192-194 the quiet return, 128-160 the directory callback.
include_filename(): parser_lex.l:162-225; the quiet return: parser_lex.l:192-194. The directory callback include_dir_cb(): parser_lex.l:128-160.alphasort (_aa_dirat_for_each, private.c:516). Every file of the directory is pushed before any is parsed.10-define (@{V} = a) and 20-extend (@{V} += b) gives Failed to find declaration for: V and an error naming /work/10-define at line 1.Could not open '%s' in '%s' and Could not process include directory '%s' in '%s' (parser_lex.l:151, parser_lex.l:214-215).Could not open 'if' means the three words were not recognised. A misspelt file name is silent: check with -p.
AppArmor parser error for FILE in profile FILE at line N: Could not open 'if'. include if exists at the end of a line, with no file name, gives the same message (recorded in the research notes).--warn=all apart from warnings that do not concern the include; -p prints ##failed include <local/dmeo>.AppArmor parser error for /work/ie-bad.sd in profile /work/site-bad.local at line 1: Variable declarations do not accept trailing commas. The file was included through include if exists from a directory given with -I.AppArmor parser error for /work/ie06e.sd in profile /work/ie06e.sd at line 3: Could not open 'demo-extra'. @{EXTRA} is not defined in that file. The research notes record the same for if false { include <does/not/exist> }./work/ are scratch names of the runs.Onward: abstractions and tunables, variable assignment, who can change policy.
Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run on the fragment (-Q -K --skip-kernel-load, with the tree's abi/5.0 file as kernel feature set and the tree's profiles/apparmor.d on the search path), with nothing loaded into a kernel; "code" means the parser or library source was read and not run; "derived" means the result was reasoned from that code. Nothing here was observed on a running kernel.
INCLUDE IF EXISTS: ( 'include' | '#include' ) 'if' 'exists' ( <magic/path> | "path" | path )
exists (tree: without it the parser reports Could not open 'if').include: a name that cannot be opened is not an error (tree).include_tests/preamble_good_6.sd and ok_85.sd).| The name is | include | include if exists | -p marker |
|---|---|---|---|
| a file | its text is included | the same | ##included <name> |
| a directory | every regular file in it is included | the same | ##included <name> |
| missing | Could not open 'NAME', exit status 1 (tree) | nothing, exit status 0 (tree) | ##failed include <name> |
| a file with an error in it | the error, reported for the included file, exit status 1 | the same (tree) | none: the compile stops |
., README, and names ending in .dpkg-new, .dpkg-old, .dpkg-dist, .dpkg-bak, .dpkg-remove, .pacsave, .pacnew (code).Ignoring: '<path>' on standard error: names ending in .rpmnew, .rpmsave, .orig, .rej, ~ (code).tunables/global includes, and tunables/global itself, ends with include if exists <tunables/NAME.d>. Shipped abstractions end with include if exists <abstractions/NAME.d> (the last line of abstractions/base is line 184)..d directories the running example tries, three exist in the tree: tunables/home.d, tunables/multiarch.d, tunables/xdg-user-dirs.d, each with a site.local of comments. The others give ##failed include (tree).@{HOMEDIRS} += /srv/nfs/home/ changes demo's compiled rule from {/home/*,/root}/.ssh/** to {/home/*,/root,/srv/nfs/home/*}/.ssh/**. In the run the line stood in a file site.local in a directory given with -I and was included with include if exists <site.local> after include <tunables/global>, standing in for tunables/home.d/site.local.| Message | Cause | Basis |
|---|---|---|
Could not open 'if' | exist for exists, or no blank after exists, or no file name | tree |
Could not open 'NAME' | a plain include of a missing file, also inside a conditional block that is not taken | tree |
in profile .../site-bad.local at line 1: Variable declarations do not accept trailing commas | a syntax error in an optional file that exists | tree |
| no message | a misspelt name after include if exists | tree |
Ignoring: '<path>' | a backup or reject file in an included directory; not an error | code |
abstractions/NAME.d/ and tunables/NAME.d/ are extension points for every profile that includes NAME. Write access to them is write access to policy.##failed include in -p output is the only trace of a missing magic path..d directories of everything it includes and the -I directories of the parser's invocation..d directories.include{WS}+if{WS}+exists/{WS} pushes INCLUDE_EXISTS (parser_lex.l:789-794); the #include form (parser_lex.l:781-787).include_filename(name, search, if_exists) (parser_lex.l:162-225); file or directory by fstat() (parser_lex.l:199-217).include_dir_cb() (parser_lex.l:128-160) and libapparmor's directory walk (private.c:498-565); the skip lists (private.c:100-121, private.c:162-183, parser_misc.c:71-79).if or qualifier block makes the same include in the rest of the profile a no-op. Recorded in the research notes.10-define with @{V} = a and 20-extend with @{V} += b give Failed to find declaration for: V and an error naming /work/10-define at line 1.-p prints ##included "PATH" for a quoted include that does not exist. Recorded in the research notes.io_uring sqpoll, allows a ring with a submission-queue polling thread. A plain ring needs no rule.
uring_sqpoll (lsm.c:683-704, registered at lsm.c:1889). It is called when a ring is created with IORING_SETUP_SQPOLL (sqpoll.c:505)./sys/kernel/security/apparmor/features/io_uring/mask, which reads sqpoll override_creds (apparmorfs.c:2679-2682).io_uring sqpoll, is line 22 of demo's profile; it compiles with no warning (run with the tree's parser). The program demo and its profile are invented for the map.[QUALIFIERS] io_uring [sqpoll | override_creds | (sqpoll, override_creds)] [label=LABEL],.
sqpoll and override_creds. A rule without a permission has both.label takes = only, one value, and may appear once: only "=" allowed in conditions of io_uring rules, io_uring conditional "label" only supports a single value, io_uring conditional "label" can only be specified once. Blanks around = are allowed (label = /bar, ok_io_uring_09.sd).audit, allow, deny, prompt and priority= are taken; owner and other are refused: owner io_uring, gives owner prefix not allowed on io_uring rules (run with the tree's parser).io_uring ... label= are not expanded": the label does not take variables. io_uring override_creds label=@{profile_name}, fails when the policy is compiled, with Unable to parse input line '@{profile_name}' and no line number (run with the tree's parser).io_uring_rule productions: parser_yacc.y:1620-1627; the permissions: parser_yacc.y:1597-1618. sqpoll is 0x10 and override_creds 0x8 (io_uring.h:29-33); the conditional checks: io_uring.cc:35-50; the default to both: io_uring.cc:62-64; the owner refusal: io_uring.h:46-52.IOURING_MODE can never be entered": the keyword has no scanner state of its own and is scanned in INITIAL; the declared state IOURING_MODE is never entered. See Known bugs.Mediated: IORING_SETUP_SQPOLL and requests that use a registered personality. Not mediated by this class: creating a ring, submitting requests.
uring_override_creds and uring_sqpoll (lsm.c:1888-1889). security_uring_allowed (io_uring.c:3401) and security_uring_cmd (uring_cmd.c:236) have no AppArmor implementation.io_uring mediates the class, so both features are refused without a rule. Without the feature the rule is dropped (warning io_uring rules not enforced, class rule-not-enforced, off by default) and the kernel allows both, because there is nothing to check (lsm.c:627-654).abi/5.0 and abi/5.0-interface list io_uring.uring_cmd) are not seen by AppArmor.abi rule, cannot deny sqpoll or override_creds either; deny io_uring, there compiles to nothing.io_uring override_creds label=L, allows requests under registered credentials whose label matches L. Without label=, any.
uring_override_creds(const struct cred *new) (lsm.c:663-682, registered at lsm.c:1888). It is called when a request with registered credentials is submitted (io_uring.c:1989).override_creds permission is required (lsm.c:642-647, perms.h:51-53).tcontext equals profile.tcontext= with the label of the credentials.io_uring sqpoll label=demo-helper, compiles to the same rule as io_uring sqpoll, (run with the tree's parser).AA_MAY_OVERRIDE_CRED (0x8) (perms.h:51-53).operation="uring_sqpoll" and operation="uring_override", class="io_uring"; tcontext= is the label for label=.
operation="uring_sqpoll" class="io_uring" ... requested="sqpoll" denied="sqpoll") and testcase_io_uring_02.in (operation="uring_override" ... requested="override_creds" denied="override_creds" tcontext=...).requested= and denied= are sqpoll or override_creds; tcontext= is printed when there is a target label (lsm.c:598-625). The error is EACCES (lib.c:440): io_uring_setup returns it (sqpoll.c:505-507); for override_creds it is the res of the request's completion entry, and io_uring_enter itself succeeds (io_uring.c:1989-1993, io_uring.c:2000-2026).deny refuses without a record; in complain mode the record is ALLOWED.io_uring.cc:116-164 writes \x16 with the permissions, a marker, and \x16 + label for override_creds; lsm.c:627-654 reads them.
-D rule-exprs): io_uring sqpoll, gives \x16 with 0x10 and \x16 with 0x4; io_uring override_creds label=demo-helper, gives \x16 0x8, \x16 0x4 and \x16demo-helper 0x8; the line on the slide gives \x16 0x18, \x16 0x4 and \x16demo-helper 0x18; io_uring, gives \x16 0x18, \x16 0x4 and \x16[^\000]* 0x18. The generic marker is \d22 at priority -1001.AA_CLASS_IO_URING is 22 (policydb.h:46). The generic marker is added for confined profiles only (parser_regex.c:1450-1452).profile_uring (lsm.c:627-654).io_uring accepts a conditional group with any name": the grammar accepts one conditional group of any name after the conditionals and treats its contents as plain conditionals: io_uring override_creds peer=(label=foo), and io_uring override_creds xattrs=(label=foo), mean label=foo (run with the tree's parser).io_uring (sqpol), compiles exactly like io_uring, (parser_yacc.y:1597-1608, io_uring.cc:56-64). Checked with the tree's parser.
-D rule-exprs): io_uring (sqpol), gives \x16 0x18, \x16 0x4 and \x16[^\000]* 0x18, the same three rules as io_uring,; io_uring (sqpoll, bogus), gives \x16 0x10 and \x16 0x4; io_uring sqpol, gives syntax error, unexpected TOK_ID, expecting TOK_END_OF_RULE.mqueue (create, bogus) /q,, which gives Internal: unexpected mqueue perms character 'b' in input.io_uring ( ... ) is ignored, and a list of unknown words means all permissions". Nothing here was run on a kernel.override_creds for any label.deny, a misspelt single word denies both, which is wider than written; with a correct word beside it, the misspelt one is silently not denied.apparmor_parser -Q -K --skip-kernel-load -D rule-exprs. It is on the bug list as confirmed; see Known bugs.Words: sqpoll, override_creds. Conditional: label= with one value.
AppArmor parser error for FILE in profile FILE at line N: MESSAGE; the slide shows MESSAGE. All five rows were run with the tree's parser. In row 1 the unexpected token is TOK_READ because read is a keyword; an unknown word such as sqpol gives unexpected TOK_ID.io_uring, the rule is dropped; --warn=rule-not-enforced prints io_uring rules not enforced.perms contains invalid permissions for io_uring: io_uring.cc:58. The owner refusal: io_uring.h:46-52.io_uring rules cover sqpoll and override_creds only.
[QUALIFIERS] io_uring [PERMISSIONS] [label=LABEL],: the permissions are sqpoll and override_creds; without a list the rule has both.EACCES; a refused request completes with -EACCES. Both are logged, as operation="uring_sqpoll" or operation="uring_override".Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the line (-Q -K --skip-kernel-load --warn=all, -D rule-exprs for compiled forms), with nothing loaded into a kernel; "code" means the parser source or the kernel source was read, not run. Nothing here was observed on a running kernel.
IO_URING RULE: [QUALIFIERS] io_uring [PERMISSIONS] [label=LABEL] , PERMISSIONS: sqpoll | override_creds | ( sqpoll, override_creds ) QUALIFIERS: [priority=N] [audit] [allow|deny|prompt]
label takes =, one value, once; blanks around = are allowed (tree). It applies to override_creds only.| Seat | On an io_uring rule |
|---|---|
priority= | taken |
audit | taken |
allow, deny, prompt | taken: deny is not logged; prompt is in syn-prompt |
owner, other | refused: owner prefix not allowed on io_uring rules (tree) |
| Word | The io_uring feature | Kernel hook | Operation in the log |
|---|---|---|---|
sqpoll | a ring with a kernel thread that polls the submission queue (IORING_SETUP_SQPOLL) | uring_sqpoll | uring_sqpoll |
override_creds | a request that runs with credentials registered with the ring (a personality) | uring_override_creds | uring_override |
Hooks: linux:security/apparmor/lsm.c:663-704 (code).
| Operation | Seen by AppArmor through this class |
|---|---|
creating a ring (io_uring_setup without IORING_SETUP_SQPOLL) | no |
submitting requests (io_uring_enter) | no |
passthrough commands (LSM hook uring_cmd) | no: no AppArmor implementation |
the LSM hook uring_allowed | no: no AppArmor implementation |
Read from linux:security/apparmor/lsm.c:1785-1890 (code).
| The feature set | No io_uring rule | With a rule |
|---|---|---|
lists io_uring (abi/5.0, abi/5.0-interface) | both features refused | as the rule says |
does not list it (abi/3.0, abi/4.0, abi/4.0-ip, the kernel-5.4 files, no abi rule (the parser's built-in default)) | both allowed | the rule is dropped, also a deny; both allowed |
The warning for a dropped rule is io_uring rules not enforced, class rule-not-enforced, off by default (tree). The feature file is /sys/kernel/security/apparmor/features/io_uring/mask, which reads sqpoll override_creds (code).
| Field | Meaning |
|---|---|
operation= | uring_sqpoll or uring_override |
class="io_uring" | always |
requested=, denied= | sqpoll or override_creds |
tcontext= | the label of the credentials, for uring_override |
Records from the tree (libraries/libapparmor/testsuite/test_multi/testcase_io_uring_01.in and testcase_io_uring_02.in):
apparmor="DENIED" operation="uring_sqpoll" class="io_uring" profile="/root/apparmor/tests/regression/apparmor/io_uring" pid=1320 comm="io_uring" requested="sqpoll" denied="sqpoll" apparmor="DENIED" operation="uring_override" class="io_uring" profile="/root/apparmor/tests/regression/apparmor/io_uring" pid=1193 comm="io_uring" requested="override_creds" denied="override_creds" tcontext="/root/apparmor/tests/regression/apparmor/io_uring"
A refused setup returns EACCES; a refused request completes with -EACCES (linux:io_uring/sqpoll.c:505-507, linux:io_uring/io_uring.c:1989-1993, code).
| Rule | Message |
|---|---|
io_uring read, | syntax error, unexpected TOK_READ, expecting TOK_END_OF_RULE |
io_uring sqpol, | syntax error, unexpected TOK_ID, expecting TOK_END_OF_RULE |
io_uring sqpoll override_creds, | syntax error, unexpected TOK_OVERRIDE_CREDS, expecting TOK_END_OF_RULE |
io_uring override_creds peer=demo-helper, | invalid io_uring conditional "peer" |
io_uring sqpoll label=(a b), | io_uring conditional "label" only supports a single value |
label given twice | io_uring conditional "label" can only be specified once |
an operator other than = | only "=" allowed in conditions of io_uring rules |
owner io_uring, | owner prefix not allowed on io_uring rules |
io_uring override_creds label=@{profile_name}, | Unable to parse input line '@{profile_name}', no line number |
io_uring (sqpol), | none; compiles like io_uring, |
any io_uring rule, no io_uring in the feature set, --warn=rule-not-enforced | warning io_uring rules not enforced |
Rows with a rule are from the tree's parser; the two others are read from the parser source (code).
AA_CLASS_IO_URING 22 (parser/policydb.h:46); sqpoll 0x10, override_creds 0x8 (parser/io_uring.h:29-33).parser/io_uring.cc:116-164): \x16 with the permissions, \x16 with the marker 0x4 at the rule's priority, and, when override_creds is among the permissions, \x16 + label (or [^\000]*) with the permissions.\d22 is added at the minimum priority for confined profiles (parser/parser_regex.c:1450-1452); the scheme is the one of syn-userns.profile_uring (linux:security/apparmor/lsm.c:627-654) reads the class state for sqpoll and calls aa_label_match on the new credentials' label for override_creds.parser/parser_yacc.y:1597-1627.None of these is taught as intended behaviour. All are on the bug list as confirmed; see Known bugs.
io_uring (sqpol), equals io_uring, (tree).io_uring override_creds label=@{profile_name}, fails at compile time without a line number (tree).io_uring override_creds peer=(label=foo), means label=foo (tree).IOURING_MODE is declared and never entered (code).A hard link adds a path to an existing file. AppArmor checks the new name and the existing file's name before allowing it: link NEWNAME -> EXISTING,.
link NEWNAME -> EXISTING,. NEWNAME is the hard link to be created, EXISTING the file that is already there.link(2) and linkat(2). Both reach the LSM hook path_link (security_path_link, called at namei.c:6008); in the kernel AppArmor registers apparmor_path_link for it (lsm.c:1796).apparmor_path_link(old_dentry, new_dir, new_dentry) returns 0 without a check when the file system of the existing file is not mediated or the task is unconfined; otherwise it calls aa_path_link (lsm.c:367-384).aa_path_link builds two paths on the mount of the new link's directory, one for the new name and one for the existing file, and checks them against every profile that confines the task (file.c:437-467).operation="link", the new name in name= and the existing file in target= (testcase_dmesg_link_01.in).fs.protected_hardlinks. It is not part of AppArmor and applies to unconfined tasks too.demo and its profile are invented for the map. Nothing on this slide was observed on a running kernel; the kernel behaviour is stated from the kernel source.link [subset] NEWNAME -> EXISTING, or the letter l in a file rule: PATH l [-> EXISTING], and l [subset] PATH [-> EXISTING],.
[QUALIFIERS] link [subset] NEWNAME -> EXISTING,; [QUALIFIERS] [file] PATH MODE-with-l [-> EXISTING],; [QUALIFIERS] [file] MODE-with-l [subset] PATH [-> EXISTING],.QUALIFIERS is [priority=N] [audit] [allow|deny|prompt] [owner|other], in that order.link rule requires the arrow and the target. Run with the parser built from the AppArmor tree at 836052d21 (-Q -K --skip-kernel-load --warn=all, nothing loaded into a kernel), link /a, is rejected: syntax error, unexpected TOK_END_OF_RULE, expecting TOK_ARROW.link rule does not take the word file: file link /a -> /b, is a syntax error (unexpected TOK_LINK).l and no exec letter. With an exec letter the arrow names an exec target instead.link /alpha/beta -> /tmp/**, (ok_link_2.sd), link subset /alpha/beta -> /tmp/**, (ok_link_3.sd), /tmp/foo l -> /tmp/bar, (ok_link_4.sd).link_rule production: TOK_LINK opt_subset_flag id_or_var TOK_ARROW id_or_var TOK_END_OF_RULE (parser_yacc.y:1141-1152). It creates an entry with the link permission for both halves and the target as link_name.opt_subset_flag (parser_yacc.y:1085-1101).link and subset: parser_misc.c:94, parser_misc.c:98.opt_subset_flag also lists TOK_LE (parser_yacc.y:672-674), but link <= /a -> /b, cannot be written: the tree's parser answers Lexer found unexpected character: '<' (0x3c) in state: INITIAL.In the kernel a link needs l on the new name and a rule whose target matches the existing file. A refused target carries info="target restricted" and target= the existing file.
profile_path_link, file.c:331-416) and was not observed on a running kernel.info text (file.c:358-365).info="target restricted" (file.c:367-382).operation="link", name= the new name, requested_mask="l", denied_mask="l", fsuid=, ouid= and target= the existing file (file.c:52-75). ouid is the owner of the existing file.apparmor="DENIED" operation="link" ... name="/tmp/sdtest.19088-12382-HWH57d/linkfile" pid=19142 comm="link" requested_mask="l" denied_mask="l" fsuid=0 ouid=0 target="/tmp/sdtest.19088-12382-HWH57d/target". The record on the slide is adapted from it.profile_path_link in the kernel: path_name for the link and for the target (file.c:345-356); aa_str_perms on the link name from the start state of the file class; AA_MAY_LINK is required (file.c:360-365); aa_dfa_null_transition, then aa_str_perms on the target name from that state; the audit, quiet and kill masks are copied from this lookup (file.c:367-376); aa_audit_file with OP_LINK, the link name as name and the target name as target (file.c:413-415).link subset NEW -> OLD, also requires every permission the profile grants on NEW (other than link) to be granted on OLD. This is what the kernel code does; it was not run on a kernel.
link subset NEW -> OLD,, l subset NEW -> OLD, and the letter l without an arrow. Without the test: link NEW -> OLD, and NEW l -> OLD,.subset the kernel stops after the two name checks and allows the link (file.c:384-386).subset it looks up the existing file once more, as an ordinary file, and takes every permission the profile allows on the new name except link itself. If one of them is not allowed on the existing file, the link is refused (file.c:388-400).info text. Both masks of the record name the missing permissions, for example requested_mask="xm" denied_mask="xm" in file_xm.in.info="link not subset of target" (file.c:322-329, file.c:401-407).x rule on the new link must match the original exactly (apparmor.d.pod:1105-1110).link rule, or l with an arrow, written without subset lets the task give a file a name under which the profile grants more than it does under the old name: for example write access through a name in a writable directory. Read from the source of mainline linux 7.4 (97d73c825), not observed on a running kernel.subset closes that: every permission the profile grants on the new name, other than link, must also be granted on the existing file (file.c:384-407). The test compares what the profile allows on the two names; it does not look at what other profiles or other tasks may do with the new name.l in a file rule compiles to a link to any absolute path with the subset test: /e l, gives the pair /e NUL /[^/].* with the subset bit (run with the parser built from the AppArmor tree at 836052d21, nothing loaded into a kernel, -D rule-exprs). link /new -> /old, without subset has no such test.owner on a link rule compares the task's fsuid with the owner of the existing file, not of the directory or the new name (file.c:443-448).w on the new name, and the file it points to is checked under its own name when it is opened.lperms.allow & ~AA_MAY_LINK (file.c:395); xindex_is_subset masks AA_X_UNSAFE out of both exec indexes before comparing them (file.c:322-329).AA_LINK_SUBSET has the value of AA_MAY_LOCK (perms.h:34, perms.h:49). It is read from the state reached by the pair, where a lock bit has no other meaning.AA_LINK_SUBSET_TEST, the link bit shifted left by one (immunix.h:117-120); it is added to the pair when the entry has subset (parser_regex.c:704-705).PATH l, allows hard links named PATH to any file, subject to the subset test. PATH l -> TARGET, allows that target without the test. l is not needed on the existing file.
PATH l, compiles to: link permission on PATH, any absolute path as the target, and the subset test on. Checked with the parser built from the AppArmor tree at 836052d21 (-Q -K --skip-kernel-load -D rule-exprs, nothing loaded into a kernel).PATH l -> TARGET, allows the one target and has no subset test. l subset PATH -> TARGET, is the letters-first spelling that turns the test back on.PATH as usual: /var/lib/demo/state/* rwl, grants read and write on the names and lets them be created as hard links.l is not needed on the existing file. The manual page says the same: "the destination does not have to have link access" (apparmor.d.pod:1105-1110).l rule, the profile must grant on the existing file at least what it grants on the new name (the kernel, file.c:384-400; read, not run). This is why a state file can be linked to another state file and not to a read-only configuration file./foo l, as equal to link subset /foo -> /**, (apparmor.d.pod:1165-1171). The compiled targets differ slightly: the bare l accepts NUL bytes in the target and /** does not. No path name contains a NUL byte, so the two match the same files./alpha/beta rl, and /gamma/* rwl, (ok_link_1.sd); owner /tmp/foo l -> /tmp/bar1, (ok_link_4.sd).link_name the pair gets the fixed target expression /[^/].* and always the subset bit (parser_regex.c:706-709).-D rule-exprs (the link bit is 0x10 per half, 0x40010 for both; the subset bit is 0x20): /a l, gives /a with 0x40010 and /a\x00/[^/].* with 0x40030; /a rl -> /b, gives /a with 0x50014 and /a\x00/b with 0x40010; l subset /a -> /b, gives the pair with 0x40030.AA_OLD_MAY_LINK (parser_misc.c:606-609); the kernel maps the old bit 0x10 to AA_MAY_LINK and 0x20 to AA_MAY_LOCK | AA_LINK_SUBSET when it loads the policy (policy_compat.c:87-93).Link rules accept audit, deny and owner. In the kernel owner tests the owner of the existing file. A symlink needs w on its own name, not l.
[priority=N] [audit] [allow|deny|prompt] [owner|other] link [subset] NEWNAME -> EXISTING,.audit deny owner link subset /alpha/beta -> /tmp/**, (ok_link_audit_deny_owner_subset.sd), owner link subset /alpha/beta -> /tmp/**, (ok_link_owner.sd), deny link /alpha/beta -> /tmp/**, (ok_deny_link.sd), audit deny link /alpha/beta -> /tmp/**, (ok_audit_deny_link.sd).owner: in the kernel the owner used for a link check is the owner of the existing file's inode, translated through the mount's ID mapping (file.c:441-448). It is compared with the task's fsuid (file.c:226-228). The same value is logged as ouid=.audit and the quiet effect of deny are read from the pair of names (file.c:371-376).symlink(2) and symlinkat(2) reach the LSM hook path_symlink. apparmor_path_symlink asks for create permission on the new name and does not look at the text the symlink will hold (lsm.c:360-365).w in a file rule: when it loads a policy, the kernel maps the write bit to create, delete, setattr, chmod, chown and open (policy_compat.c:84-86).deny /a l, emits only the pair; deny /a rl, emits /a as a deny rule with 0x10004 and the pair.perms & AA_LINK_BITS when the rule has audit (parser_regex.c:710-716).link a -> b compiles to a and a\x00b (parser/parser_regex.c:684-716). profile_path_link (linux:security/apparmor/file.c:331-416, the kernel) walks name, NUL, target and tests AA_LINK_SUBSET.
process_dfa_entry (parser_regex.c:648-716) emits two rules per link entry: the link name with the entry's permissions (parser_regex.c:684-689), and the pair "link name, NUL, target" (parser_regex.c:692-716).add_rule_vec, which joins the expressions with cat_with_null_separator: CatNode(CatNode(l, CharNode(0)), r) (aare_rules.cc:64-67, aare_rules.cc:90).-D rule-exprs (link bit 0x10 per half, 0x40010 for both halves): link /a -> /b,: /a 0x40010 and /a\x00/b 0x40010; link subset /a -> /b,: /a 0x40010 and /a\x00/b 0x40030; /a l,: /a 0x40010 and /a\x00/[^/].* 0x40030.AA_LINK_SUBSET_TEST is AA_OLD_MAY_LINK << 1 and LINK_TO_LINK_SUBSET(X) is ((X) << 1) & AA_LINK_SUBSET_TEST (immunix.h:117-120). In the kernel AA_LINK_SUBSET is defined as AA_MAY_LOCK, with the comment "overlaid" (perms.h:34, perms.h:49).l has no link_name: the target is the fixed expression /[^/].* and the subset bit is always added (parser_regex.c:706-709).filter_slashes and convert_aaregex_to_pcre (parser_regex.c:658-660, parser_regex.c:699-701).profile_path_link in the kernel, read and not run: aa_str_perms on lname from rules->file->start[AA_CLASS_FILE]; needs AA_MAY_LINK (file.c:360-365); aa_dfa_null_transition, then aa_str_perms on tname; without AA_MAY_LINK: info = "target restricted" (file.c:367-382); no AA_LINK_SUBSET in that state: done (file.c:384-386); third match: aa_str_perms on tname from the start state, request = lperms.allow & ~AA_MAY_LINK, denied if request & ~lperms.allow after lperms.allow is limited to the target's permissions (file.c:388-400); xindex_is_subset for exec, info = "link not subset of target" (file.c:401-407).aa_path_link runs this for every confined profile of the label with fn_for_each_confined (file.c:437-467)."subset can only be used with link rules." "link and exec perms conflict on a file rule using ->". The link keyword requires -> TARGET; targets are absolute paths.
-Q -K --skip-kernel-load --warn=all, nothing loaded into a kernel). The full form is AppArmor parser error for FILE in profile FILE at line N: MESSAGE.link /a,: syntax error, unexpected TOK_END_OF_RULE, expecting TOK_ARROW.r subset /a,: subset can only be used with link rules.lpx /a -> /b,: link and exec perms conflict on a file rule using ->. Test file: bad_leading_link_x.sd.l /a -> :ns:b,: link perms are not allowed on a named profile transition./a lPx -> b, is accepted. With --warn=deprecated the parser prints ambiguous rule specifies both link target and exec transition target. Using as exec transition; that warning class is not in the default set (parser.h:77-78). The arrow is the exec target, and the link permission of such a rule gets any target with the subset test. Test files: depricated1.sd to depricated5.sd.link rule outside a profile is a syntax error (bad_link_outside.sd).link /a -> b, loads without a message. The kernel compares the target with an absolute path name, so a target that does not start with / matches no file.--warn option.yyerror calls are in the permissions-first file rule (parser_yacc.y:1087-1092); the deprecation warning is in the path-first one (parser_yacc.y:1074-1077).deprecated: parser_main.c:284.link <= /a -> /b,: the grammar accepts TOK_LE as a subset flag (parser_yacc.y:672-674), but the lexer does not return that token here; the message is Lexer found unexpected character: '<' (0x3c) in state: INITIAL (parser_lex.l:930).Next: syn-access-modes, syn-globbing, syn-owner, syn-named-transitions, prac-hardlinks (the security side), k-match.
link A -> B, and A l -> B,: target B, no subset test. link subset A -> B, and l subset A -> B,: target B, with the test. A l,: any target, with the test.w on their own name; link rules do not apply to them.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the fragment (-Q -K --skip-kernel-load --warn=all), with nothing loaded into a kernel; "code" means the parser source or the source of mainline Linux 7.4 was read, not run. Nothing here was observed on a running kernel.
LINK RULE: [QUALIFIERS] link [subset] NEWNAME -> EXISTING , FILE RULE: [QUALIFIERS] [file] PATH MODE-with-l [-> EXISTING] , FILE RULE: [QUALIFIERS] [file] MODE-with-l [subset] PATH [-> EXISTING] , QUALIFIERS: [priority=N] [audit] [allow|deny|prompt] [owner|other]
link rule does not take the file keyword. Its arrow and target are required.NEWNAME (or PATH) is the name of the link to be created; EXISTING is the file that already exists. The arrow points from the new name to the old one.l and no exec letters. With an exec letter see "Errors and warnings" below and syn-named-transitions.| Keyword | Where | Meaning |
|---|---|---|
link | start of the rule, after the qualifiers | a link rule: the new name, the arrow, the existing file |
subset | after link, or after the mode in a letters-first file rule | also require the new name to grant no more than the existing file |
-> | between the two names | separates the new name from the existing file |
l | in the mode of a file rule | link permission on that path; without an arrow, any target with the subset test |
Compiled forms are from the tree's parser (tree); what the kernel then does is from the source of mainline Linux 7.4 (code).
| Rule | Allowed target | Subset test |
|---|---|---|
link A -> B, | B | no |
link subset A -> B, | B | yes |
A l, | any absolute path | yes |
A l -> B, | B | no |
l subset A -> B, | B | yes |
A rwl, | any absolute path; r and w apply to A as usual | yes |
l is not needed on the existing file. To pass the subset test of a plain l rule, the profile must grant on the existing file at least what it grants on the new name.
All statements in this section are from the source of mainline Linux 7.4 (linux:security/apparmor/file.c:331-467), not from a run.
1. The kernel builds the name of the new link and the name of the existing file. 2. The new name must have link permission. If it does not, the request is denied. 3. Given the new name, the existing file must be an allowed target. If it is not, the request is denied with info="target restricted". 4. If the matching rule has no subset test, the link is allowed. 5. Otherwise every permission the profile allows on the new name, apart from link itself, must also be allowed on the existing file. If one is missing the request is denied, and the masks of the record name the missing permissions; no info text is set in this case. If the new name has exec permission, the exec mode of the two names must also agree (equal, or the new name safe where the existing file is unsafe); if not, the request is denied with info="link not subset of target".
owner on a link rule compares the task's fsuid with the owner of the existing file.A denial record, shortened, adapted from libraries/libapparmor/testsuite/test_multi/testcase_dmesg_link_01.in:
apparmor="DENIED" operation="link" profile="demo" name="/var/lib/demo/current" pid=19142 comm="demo" requested_mask="l" denied_mask="l" fsuid=1000 ouid=0 target="/etc/shadow"
A failed subset test can show other letters in the masks, for example requested_mask="xm" denied_mask="xm" (libraries/libapparmor/testsuite/test_multi/file_xm.in).
w on the symlink's own name, and no rule looks at where it points when it is made (linux:security/apparmor/lsm.c:360-365, mainline Linux 7.4).Messages are from the tree's parser (tree). A full error reads AppArmor parser error for FILE in profile FILE at line N: MESSAGE.
| Line | Message |
|---|---|
link /a, | syntax error, unexpected TOK_END_OF_RULE, expecting TOK_ARROW |
r subset /a, | subset can only be used with link rules. |
lpx /a -> /b, | link and exec perms conflict on a file rule using -> |
l /a -> :ns:b, | link perms are not allowed on a named profile transition. |
file link /a -> /b, | syntax error, unexpected TOK_LINK, ... |
/a lPx -> b, | warning: ambiguous rule specifies both link target and exec transition target. Using as exec transition |
deprecated warning class, which is off by default. The arrow of such a rule is the exec target, and its link permission gets the any-path target with the subset test (tree; fixtures parser/tst/simple_tests/link/depricated1.sd to depricated5.sd).link rule outside a profile is a syntax error (parser/tst/simple_tests/link/bad_link_outside.sd).<= as an alternative to subset, but it cannot be written: link <= /a -> /b, fails with "Lexer found unexpected character: '<' (0x3c) in state: INITIAL" (tree). Use subset./foo l, equals link subset /foo -> /**,. The compiled target of the bare l is /[^/].*, while /** compiles to /[^/\x00][^\x00]*; the two differ only in whether NUL bytes are accepted (tree, code)./ is accepted without a message: link /a -> b, loads and matches no file (tree).link not subset of target is set only when the exec modes disagree. A subset failure on other permissions is denied without an info text (code, mainline Linux 7.4).process_dfa_entry (parser/parser_regex.c:648-716) emits two rules per link entry: the link name, and the pair "link name, NUL, target" built by add_rule_vec with cat_with_null_separator (parser/libapparmor_re/aare_rules.cc:64-67,90). Values from -D rule-exprs (tree); the link bit is 0x10 per half, both halves 0x40010.
| Rule | First rule | Pair |
|---|---|---|
link /a -> /b, | /a 0x40010 | /a\x00/b 0x40010 |
link subset /a -> /b, | /a 0x40010 | /a\x00/b 0x40030 |
/a l, | /a 0x40010 | /a\x00/[^/].* 0x40030 |
/a rl -> /b, | /a 0x50014 | /a\x00/b 0x40010 |
l subset /a -> /b, | /a 0x40010 | /a\x00/b 0x40030 |
/var/lib/demo/state/* rwl, | the name, 0x7801e | the name, \x00/[^/].* 0x40030 |
LINK_TO_LINK_SUBSET(X) shifts the link bit left by one (parser/immunix.h:117-120); in the kernel AA_LINK_SUBSET has the value of AA_MAY_LOCK (linux:security/apparmor/include/perms.h:34,49).deny /a l, emits only the pair; deny /a rl, emits /a as a deny rule with 0x10004 and the pair (tree).filter_slashes and the AARE conversion (parser/parser_regex.c:659-660,700-701).profile_path_link in mainline Linux 7.4 (linux:security/apparmor/file.c):
| Lines | Step |
|---|---|
| 345-356 | path_name for the link and for the target |
| 360-365 | aa_str_perms on lname from the start state; needs AA_MAY_LINK |
| 367-382 | aa_dfa_null_transition, aa_str_perms on tname; audit, quiet and kill masks taken from this state; without AA_MAY_LINK: "target restricted" |
| 384-386 | no AA_LINK_SUBSET: done |
| 388-400 | aa_str_perms on tname from the start state; request = lperms.allow & ~AA_MAY_LINK; denied if request & ~perms.allow |
| 322-329, 401-407 | xindex_is_subset; "link not subset of target" |
| 437-467 | aa_path_link: cond.uid is the owner of the existing file's inode |
A mount rule describes the mount(2) calls a profile allows: type, flags, source and mount point. The program also needs capability sys_admin,.
sb_mount for mount(2) (lsm.c:707-742, registered at lsm.c:1792) and move_mount for move_mount(2) (lsm.c:744-758). An unconfined task is not checked.mount: the feature file /sys/kernel/security/apparmor/features/mount/mask reads mount umount pivot_root (apparmorfs.c:2650). Then a mount call without a matching rule is refused with EACCES.mount fstype=tmpfs options=(rw, nosuid) tmpfs -> /run/demo/, is line 14 of demo's profile. It and the three lines after it (remount, umount, pivot_root) compile together with no warning (run with the tree's parser). The program demo and its profile are invented for the map.CAP_SYS_ADMIN, which a confined task has only with capability sys_admin,. Without it the call fails with EPERM. mount(2) asks AppArmor first, so a call with no matching rule is refused with EACCES and logged whether or not the task has the capability (namespace.c:4279-4283).mount [fstype=...] [options=... | options in ...] [SOURCE] [-> MOUNTPOINT],. Everything after the keyword is optional.
fstype, vfstype, options and option. The operators are = and in. options:=ro is a scanner error: Lexer found unexpected character: ':' (0x3a) in state: MOUNT_MODE.fstype values are patterns (fstype=ext*, fstype={procfs,sysfs}). Several fstype conditionals in one rule are collected into one list of alternatives, and for fstype the operators = and in mean the same (run with the tree's parser).mount options=(rw) /a -> b, is accepted.mount rule also allows mounting anything onto that path": mount /dev/sdb1, also allows bind mounts, moves and remounts onto /dev/sdb1. Write the mount point (mount /dev/sdb1 -> /mnt/**,) or options=( ); options in does not avoid it.detached stands for a mount that is not attached anywhere yet, as seen at move_mount(2). The feature file is /sys/kernel/security/apparmor/features/mount/move_mount, which reads detached (apparmorfs.c:2651).audit, allow, deny, prompt and priority= are taken; owner and other are refused with owner prefix not allowed on mount rules.mnt_rule productions: parser_yacc.y:1277-1285; do_mnt_rule: parser_yacc.y:1798-1818; verify_mnt_conds: parser_yacc.y:1777-1796.MOUNT_MODE: parser_lex.l:876-879, parser_lex.l:681-695.= or in, parser_lex.l:437-453); collecting fstype values: mount.cc:408-431; variable expansion: mount.cc:641-670; the word detached: mount.cc:986-988; the owner refusal: mount.h:174-180.The kernel tests MS_REMOUNT, MS_BIND, the propagation flags and MS_MOVE in that order; anything else is a new mount. Only new mounts have a filesystem type to compare.
MS_KERNMOUNT, MS_NOSEC, MS_ACTIVE and MS_BORN (mount.h:26, lsm.c:718). The order of the tests is MS_REMOUNT, MS_BIND, the propagation flags, MS_MOVE, else a new mount (lsm.c:707-742).aa_remount): the mount point, no source, no type, all flags (mount.c:328-353); - bind (aa_bind_mount): the mount point, the resolved source path, the flags cut down to MS_REC | MS_BIND (mount.c:355-394); - propagation (aa_mount_change_type): the mount point, the flags cut down to MS_REC | MS_SILENT | MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE (mount.c:396-422); - move (aa_move_mount_old): the mount point, the source path, MS_MOVE (mount.c:424-474); - new mount (aa_new_mount): the mount point, the type, all flags, and as source a resolved path if the filesystem type needs a device, otherwise the source string as the caller gave it (mount.c:476-542).ENODEV before any policy check (mount.c:492-497).aa_move_mount; a mount that is not attached has no source name (mount.c:444-450).options in: the same kinds, each only if its own flag (remount, bind or rbind, a propagation flag, move) is in the list. With options=: the kind named by remount, by bind or rbind, by a propagation flag or by move, else a new mount (mount.cc:1089-1123).bind or rbind only: mount options=(bind ro) /a -> /b, does not require ro (run with the tree's parser; the compiled flags are the bind byte alone).move_mount, sb_mount, sb_umount and sb_pivotroot (lsm.c:1791-1794). None of the other calls of the new mount API (fsopen, fsconfig, fsmount, open_tree, mount_setattr) has an AppArmor hook. A mount built with them is checked only when move_mount attaches it, as a move with the source word detached.open_tree and move_mount is checked as a move without a source, so deny mount options in (bind) does not stop mount --bind": current mount(8) makes bind mounts this way, so a rule about bind mounts, allow or deny, does not apply to them, and a rule that allows moves onto the target allows them. See Known bugs.size= or upperdir=) cannot be written in a rule and are not compared: the parser refuses any word outside its flag table (mount.cc:492-496).options=(a b): exactly these flags. options in (a b): any of these flags or none. Both together: required plus optional.
nosuid; mount options in (ro, nosuid, nodev) fstype=tmpfs tmpfs -> /run/demo/, makes the three flags optional; mount options=(nosuid) options in (nodev) tmpfs -> /run/demo/, requires nosuid and makes nodev optional.rw, suid, dev, exec, async, atime, ...) add nothing to options= and only take part in the conflict check. In options in they make their flag optional, the same as the setting word: options in (ro, atime) makes ro and noatime optional.options at all means every flag is optional. options= with only clearing words (options=(rw)) means a mount with no flags.verbose, silent and loud share one flag. The full table of flag words and their synonyms (r, read-only, B, R, M, make-private, ...) is in the reference below.options in (...) also matches no flags and the opposite words; apparmor.d(5) says it does not": apparmor.d(5) says mount options in (ro,atime) /dev/foo -> /mnt/, does not match a mount with no flags or with rw,noatime (apparmor.d.pod:1745-1765); the compiled rule accepts both.nouser is accepted and has no effect, and no mount rule can match flag bit 31": nouser is accepted and has no effect, and no rule, mount, included, matches a call with that flag set (mount.h:72-92).in operator.extract_flags, conflicting_flags, extract_fstype and extract_options: mount.cc:364-454. Clearing words in options in: mount.cc:520-525; in options=: mount.cc:538-549.options= and options in entries: mount.cc:1149-1154.Refused mounts return EACCES and are logged as operation="mount" with name= (mount point), srcname=, fstype=, flags= and info="failed ... match". Directory mount points end in /.
class="mount" after operation from testcase_remount_01.in; the values are demo's and are illustrative.info texts are failed mntpnt match, failed srcname match, failed type match, failed flags match, failed data match and failed perms check (mount.c:145-153). The comparison order is fixed (mount.c:159-211). failed perms check means every field matched a rule that lacks the mount permission, for example a deny rule.fstype=, srcname=, trans=, flags="..." and options=; each is printed only when it has a value (mount.c:92-118). For a tmpfs the source is the string the caller passed, so srcname="tmpfs".rw or ro and has no word for lazytime (mount.c:31-85)./ (mount.c:214-221), so -> /run/demo, does not match and -> /run/demo/, does.fstype=fuse does not match a request for fuse.sshfs.ALLOWED with the same info (testcase_mount_02.in).error=-13 is EACCES.mnt_rule::gen_policy_re (mount.cc:1129-1192) writes \x07 mount point NUL source NUL type NUL flag bytes; do_match_mnt (mount.c:159-211) walks it.
-D rule-exprs): \x07/run/demo/\x00tmpfs\x00(tmpfs)\x00\x02, permission 0x2. mount, gives five rules.AA_CLASS_MOUNT is 7. Permissions: AA_MAY_PIVOTROOT 0x1, AA_MAY_MOUNT 0x2, AA_MAY_UMOUNT 0x4 (mount.h:20-22).build_mnt_flags writes \xNN for a required flag and (\xNN|) for an optional one and, when no flag byte results, (\xfe|) (mount.cc:716-755). The kernel's match_mnt_flags feeds one byte per set bit, from bit 0 up (mount.c:132-143).MS_REMOUNT_FLAGS, bind bind|rbind, propagation MS_MAKE_FLAGS, move move, new mount everything except the command flags (mount.h:106-121; mount.cc:817, mount.cc:890, mount.cc:948, mount.cc:996, mount.cc:1043). The choice of generator: mount.cc:1082-1127.mount options=(bind ro) /a -> /b, gives \x07/b\x00/a\x00[^\000]*\x00\x0d; mount options=(rprivate) -> /a, ends in \x00\x0f\x13; mount options=(move) detached -> /b, gives \x07/b\x00\x00[^\000]*\x00\x0e.\d7 is added at priority 1001 when the feature set has mount (parser_regex.c:1403-1405). Without it the rule is dropped with the warning mount rules not enforce (class rule-not-enforced, off by default; mount.cc:782, mount.cc:1139-1142). The spelling is the parser's; it is on the bug list under "Message typo and a stale message" (Known bugs).do_match_mnt: mount.c:159-211.AA_MNT_CONT_MATCH). The parser never writes that field: the member opts is never assigned (mount.cc:503; on the bug list under "Dead code and unused state in the mount rule"). No rule can constrain filesystem-specific options.mount and a umount rule with the same paths become one object whose strings carry both bits. The kernel reads the permission at a different point of the string for each operation, and no cross-grant was found by reading.mount SOURCE, also produces a rule with SOURCE as the mount point and a wide set of optional flags (mount.cc:936-948, 1097-1099). Read from the compiled rules.
--warn=all -D rule-exprs), mount /dev/sdb1, gives four rules, each with permission 0x2: - bind: \x07[^\000]*\x00/dev/sdb1\x00[^\000]*\x00(\x0d|)(\x0f|) - propagation: \x07/dev/sdb1\x00[^\000]*\x00[^\000]*\x00(\x01|)(\x05|)(\x06|)(\x07|)(\x08|)(\x09|)(\x0d|)(\x0e|)(\x0f|)(\x10|)(\x11|)(\x12|)(\x13|)(\x14|)(\x15|)(\x18|)(\x1a|) - move: \x07[^\000]*\x00/dev/sdb1\x00[^\000]*\x00(\x0e|) - new mount: \x07[^\000]*\x00/dev/sdb1\x00[^\000]*\x00 followed by sixteen optional flag bytes.The use of source as mount point for propagation type flags is deprecated. Its class is deprecated, which is off by default (mount.cc:937-938, parser.h:77); --warn=deprecated or --warn=all shows it.MS_MAKE_FLAGS, which is every flag except the per-mount ones, not only the propagation flags (mount.cc:948, mount.h:110).mount /dev/sdb1 -> /mnt/**, gives three rules (bind, move, new mount) and no warning (run with the tree's parser)./dev/sdb1 as the mount point: a bind mount of any path (the kernel sends mount point, source and the flag bind, mount.c:371-387), a move, a remount, and a new mount of any type with any of ro sync mand dirsync nosymfollow silent acl iversion lazytime, or no flags.mount rule also allows mounting anything onto that path": apparmor.d(5) documents the rule as source-only (apparmor.d.pod:1813).options nor ->. Writing mount options=(...) SOURCE -> MOUNTPOINT, gives one kind of call and no extra rule.Flag words only; no conflicting pairs; conditionals before paths. Encoding of mount rule failed means the rule describes no kind of mount call.
AppArmor parser error for FILE in profile FILE at line N: MESSAGE; the slide shows MESSAGE. All five rows were run with the tree's parser. Row 2 prints conflicting flag values = 1, 1 before the line shown.unsupported mount option value, conflicting flags in the rule, Encoding of mount rule failed) carry no file, profile or line.Encoding of mount rule failed is followed by ERROR processing policydb rules for profile demo, failed to load. Rules that fail this way: a command flag with fstype (mount options=(rbind) fstype=ext4 /a -> /b,), a propagation flag with both paths (mount options=(rprivate) /a -> /b,), remount alone with a source (mount options=(remount) /run/demo/,).fstype= or with a source compiles to a new-mount rule without the remount flag": with one more flag the same shape is accepted. mount options=(remount, ro) /run/demo/, compiles to a new-mount rule with the flag ro and no remount; see remount rules.invalid mount conditional with the name, then bad mount rule.mount options=defaults /a -> /b, gives unsupported mount option value 'defaults'. options:= is a scanner error./ is not an error; it does not match a directory.bad_*.sd files in parser/tst/simple_tests/mount.unsupported mount option value: mount.cc:471, mount.cc:494-495. The conflict check: mount.cc:545-546. Encoding of mount rule failed: mount.cc:1190. The conditional name check: parser_yacc.y:1788, parser_yacc.y:1803. The owner refusal: mount.h:176.Mount rules allow mounts. Remount, umount and pivot_root rules cover the rest.
[QUALIFIERS] mount [CONDITIONALS] [SOURCE] [-> MOUNTPOINT],: each part left out means any.EACCES and is logged as operation="mount" with the field that failed in info=.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the line (-Q -K --skip-kernel-load --warn=all, -D rule-exprs for compiled forms), with nothing loaded into a kernel; "code" means the parser source or the kernel source was read, not run. Nothing here was observed on a running kernel.
MOUNT RULE: [QUALIFIERS] mount [CONDITIONALS] [SOURCE] [-> MOUNTPOINT] ,
CONDITIONALS: fstype=TYPE | fstype=( TYPE ... ) | fstype in ( TYPE ... )
options=FLAG | options=( FLAG ... ) | options in ( FLAG ... )
QUALIFIERS: [priority=N] [audit] [allow|deny|prompt]
vfstype is the same as fstype; option is the same as options (code).mount, allows any mount; one path alone is the source; -> PATH alone is the mount point (tree).mount rule also allows mounting anything onto that path": mount /dev/sdb1, also allows bind mounts, moves and remounts onto /dev/sdb1. Write the mount point (mount /dev/sdb1 -> /mnt/**,) or options=( ) (tree; a kernel run is on the bug list, Known bugs).detached stands for a mount that is not attached anywhere, as seen at move_mount(2) (code).| Seat | On a mount rule |
|---|---|
priority= | taken |
audit | taken |
allow, deny, prompt | taken: deny is not logged; prompt is in syn-prompt |
owner, other | refused: owner prefix not allowed on mount rules (tree) |
"Sets" words name a flag that must be (or may be) present. "Clears" words name its absence: they add nothing to options= and make the flag optional in options in. The table is parser/mount.cc:247-311; bit values parser/mount.h:33-81.
| Sets | Clears | mount(2) flag | Belongs to |
|---|---|---|---|
ro, r, read-only | rw, w | MS_RDONLY | new mount, remount |
nosuid | suid | MS_NOSUID | new mount, remount |
nodev | dev | MS_NODEV | new mount, remount |
noexec | exec | MS_NOEXEC | new mount, remount |
sync | async | MS_SYNCHRONOUS | new mount, remount |
remount | MS_REMOUNT | remount | |
mand | nomand | MS_MANDLOCK | new mount, remount |
dirsync | MS_DIRSYNC | new mount, remount | |
nosymfollow | symfollow | MS_NOSYMFOLLOW | new mount, remount |
noatime | atime | MS_NOATIME | new mount, remount |
nodiratime | diratime | MS_NODIRATIME | new mount, remount |
bind, B | MS_BIND | bind | |
rbind, R | MS_BIND and MS_REC | bind | |
move, M | MS_MOVE | move | |
silent, verbose | loud | MS_SILENT | new mount, remount, propagation |
acl | noacl | MS_POSIXACL | new mount, remount |
unbindable, make-unbindable | MS_UNBINDABLE | propagation | |
runbindable, make-runbindable | MS_UNBINDABLE and MS_REC | propagation | |
private, make-private | MS_PRIVATE | propagation | |
rprivate, make-rprivate | MS_PRIVATE and MS_REC | propagation | |
slave, make-slave | MS_SLAVE | propagation | |
rslave, make-rslave | MS_SLAVE and MS_REC | propagation | |
shared, make-shared | MS_SHARED | propagation | |
rshared, make-rshared | MS_SHARED and MS_REC | propagation | |
relatime | norelatime | MS_RELATIME | new mount, remount |
iversion | noiversion | MS_I_VERSION | new mount, remount |
strictatime | nostrictatime | MS_STRICTATIME | new mount, remount |
lazytime | nolazytime | MS_LAZYTIME | new mount, remount |
nouser | user | MS_NOUSER | no effect (known discrepancy) |
move, the propagation flags included (parser/mount.h:114-120).size=1m or the word defaults included, is refused (tree).| The rule has | Meaning |
|---|---|
no options | every flag is optional; every kind of call the rest of the rule allows |
options=(a b) | exactly the flags a and b; every other flag absent |
options=(rw) (clearing words only) | a mount with no flags |
options in (a b) | any of a and b, or none |
options=(a) options in (b) | a required, b optional |
options=(a) options=(b) | two alternatives: exactly a, or exactly b |
The kernel tests the flags of mount(2) in this order (linux:security/apparmor/lsm.c:707-742, code).
| Kind | Selected by | The kernel compares | Covered by a rule with | Example |
|---|---|---|---|---|
| remount | MS_REMOUNT | mount point, flags | options= naming remount, no source, no fstype; or a remount rule | mount options=(remount, ro) -> /mnt/, |
| bind | MS_BIND in mount(2) | mount point, source, bind or rbind | options= naming bind or rbind, no fstype | mount options=(bind) /a/ -> /b/, |
| propagation | MS_SHARED, MS_PRIVATE, MS_SLAVE, MS_UNBINDABLE | mount point, propagation flags | options= naming a propagation flag, one path, no fstype | mount options=(rprivate) -> /mnt/, |
| move | MS_MOVE | mount point, source | options= naming move, no fstype | mount options=(move) /a/ -> /b/, |
| new mount | none of the above | mount point, source, type, flags | any other options=; any rule with fstype | mount fstype=tmpfs options=(rw, nosuid) tmpfs -> /run/demo/, |
A rule with no options covers every kind its other parts allow; with only options in a kind is covered when its flag is in the list (mount options in (ro, nodev) /a -> /b/, covers new mounts only) (parser/mount.cc:1089-1104, code; tree).
| Field | What it is |
|---|---|
| mount point | the path of the target; a directory ends in / |
| source | bind and move: the resolved path; new mount: a resolved path if the filesystem type needs a device, otherwise the string the caller passed; remount and propagation: none; detached for a mount that is not attached |
| type | the string the caller passed (fuse.sshfs is not fuse); new mounts only |
Read from linux:security/apparmor/mount.c:214-221, 328-542 (code).
| Field | Meaning |
|---|---|
operation="mount" | every kind of mount call, a remount included |
class="mount" | on current kernels; the fixture below is older |
info= | failed mntpnt match, failed srcname match, failed type match, failed flags match, failed data match or failed perms check: the first field that did not match |
error=-13 | EACCES |
name= | the mount point |
fstype= | the type, when the call has one |
srcname= | the source, when the call has one |
flags= | the flags as words, starting with rw or ro |
A record from the tree (libraries/libapparmor/testsuite/test_multi/testcase_mount_01.in):
apparmor="DENIED" operation="mount" info="failed mntpnt match" error=-13 ... name="/tmp/.../mountpoint/" ... comm="mount" fstype="ext2" srcname="/dev/loop0/" flags="rw, mand"
Format strings: linux:security/apparmor/mount.c:31-118, 145-153 (code).
| Rule | Message | Has line number |
|---|---|---|
mount options=(rw, nosuid, size=1m) tmpfs -> /run/demo/, | unsupported mount option value 'size=1m' | no |
mount options=defaults /a -> /b, | unsupported mount option value 'defaults' | no |
mount options=(rw, ro) tmpfs -> /run/demo/, | conflicting flag values = 1, 1 then conflicting flags in the rule | no |
mount tmpfs -> /run/demo/ options=(rw), | syntax error, unexpected TOK_CONDID, expecting TOK_END_OF_RULE | yes |
mount options=(remount) /dev/sda1 -> /run/demo/, | Encoding of mount rule failed | no |
mount options=(rbind) fstype=ext4 /a -> /b, | Encoding of mount rule failed | no |
mount options=(rprivate) /a -> /b, | Encoding of mount rule failed | no |
| an unknown conditional name | invalid mount conditional with the name, then bad mount rule | yes |
a conditional after -> | mount point conditions not currently supported | yes |
mount options:=ro /a -> /b, | Lexer found unexpected character: ':' (0x3a) in state: MOUNT_MODE | yes |
owner mount, | owner prefix not allowed on mount rules | yes |
mount /dev/sdb1, with --warn=deprecated | warning The use of source as mount point for propagation type flags is deprecated. | yes |
any mount rule, no mount in the feature set, --warn=rule-not-enforced | warning mount rules not enforce |
Rows with a rule are from the tree's parser; the others are read from the parser source (code).
File under /sys/kernel/security/apparmor/features/ | Content | Meaning |
|---|---|---|
mount/mask | mount umount pivot_root | the kernel mediates the mount class |
mount/move_mount | detached | the kernel reports a mount that is not attached as source detached |
Without mount in the feature set every rule of the mount class is dropped, and the warning for that is off by default (code). See syn-abi and adm-features.
mnt_rule, for mount, remount, umount and pivot_root; policydb class AA_CLASS_MOUNT 7; permissions AA_MAY_PIVOTROOT 0x1, AA_MAY_MOUNT 0x2, AA_MAY_UMOUNT 0x4 (parser/mount.h:129-131).\x07 mount point NUL source NUL type NUL flag bytes (parser/mount.cc:1129-1192). Demo's line is \x07/run/demo/\x00tmpfs\x00(tmpfs)\x00\x02 with 0x2 (tree).\xNN required, (\xNN|) optional, (\xfe|) when no flag byte results (parser/mount.cc:716-755).gen_flag_rules (parser/mount.cc:1082-1127): remount, bind, propagation, move, new mount, each with its own flag mask (parser/mount.h:106-121). mount, produces all five (tree).mount options=ro options in (nosuid) /dev/x -> /mnt/, compiles to the flag bytes \x01(\x02|); mount options=ro options=nosuid /dev/x -> /mnt/, to two rules (tree).sb_mount sorts the call (linux:security/apparmor/lsm.c:707-742); do_match_mnt walks mount point, NUL, source, NUL, type, NUL, one byte per set flag, and tests AA_MAY_MOUNT (linux:security/apparmor/mount.c:159-211); match_mnt_flags (linux:security/apparmor/mount.c:132-143).move_mount, sb_mount, sb_umount, sb_pivotroot (linux:security/apparmor/lsm.c:1791-1794).parser/parser_yacc.y:1277-1300, 1777-1838, parser/parser_lex.l:876-879.None of these is taught as intended behaviour. All are on the bug list as confirmed; see Known bugs.
mount SOURCE, also compiles to a rule with SOURCE as the mount point and seventeen optional flags, bind and move among them; reproduce with mount /dev/sdb1, and -D rule-exprs (tree). Confirmed by a kernel run on the bug list.options in (ro,atime) accepts a mount with no flags and one with noatime; apparmor.d(5) says it does not (tree, compiled flags (\x01|)(\x0b|)). Not run on a kernel.nouser is accepted and has no effect: mount options=(nouser) /a -> /b, compiles to a mount without flags, and no rule matches a call with that flag set (tree).unsupported mount option value, conflicting flags in the rule and Encoding of mount rule failed are printed without file, profile or line (tree).Not determined: which flags mount(8) passes for a given command line.
mqueue PERMISSIONS [type=...] NAME, says what a profile may do with a message queue.
mq_open, mq_unlink, mq_send, mq_receive, mq_getattr, mq_setattr for POSIX queues; msgget, msgsnd, msgrcv, msgctl for System V queues.ipc directory under /sys/kernel/security/apparmor/features/ (apparmorfs.c:2684-2701). See "Who enforces it".demo, its worker and the queue /demo-queue are invented for the map.[QUALIFIERS] mqueue [PERMISSIONS] [type=posix|sysv] [label=LABEL] [NAME],. Permissions before conditionals, the name last.
= only: only "=" allowed in conditions of mqueue rules (mqueue.cc:76). Each may be given once. An unknown name gives invalid mqueue rule conditional "%s" (mqueue.cc:91).audit, allow, deny, prompt and priority= are taken (prompt mqueue, is accepted by the parser built from the tree; deny mqueue, and audit allow mqueue, are in ok_12.sd). owner is refused: owner prefix not allowed on mqueue rules (mqueue.h:113-119).type=(posix sysv) and label=(a b) are accepted, and only the first value is used.mqueue_rule productions: parser_yacc.y:1586-1595; the permissions: parser_yacc.y:1541-1584.MQUEUE_MODE: parser_lex.l:899-900, parser_lex.l:636-695./name is a POSIX queue, digits are a System V key. type= is needed only without a name and must not contradict it.
mqueue /q*, is accepted by the parser built from the tree. A System V key must be all digits.type=posix or type=sysv says which family the rule is about; without either, the rule is about both.mqueue @{profile_name}, fails with the invalid-name message, because the name is checked before variables are expanded (mqueue.cc:106-107, mqueue.cc:179-183).mqueue r 99999999999, is accepted.Permissions: create open delete getattr setattr read write (r, w, rw). label= narrows the rule to queues with that label.
write added.create and label= in one rule, create and any read or write of the rule are also granted on the name without the label, because a queue has no label before it exists (mqueue.cc:262-272). Seen with mqueue (create read) label=l /q2, and the parser built from the tree.0x2, read 0x4, create 0x10, delete 0x20, open 0x40, setattr 0x100, getattr 0x200 (mqueue.h:31-40).On the mainline kernel mqueue rules are accepted and not enforced, deny mqueue, included; a POSIX queue is still refused there, as a file with a disconnected path. --warn=rule-not-enforced shows when the parser drops them. See Upstream and Ubuntu.
ipc/posix_mqueue and ipc/sysv_mqueue (parser_main.c:1102-1107). The tree's abi/4.0 and abi/5.0 list ipc/posix_mqueue (4.0:34, 5.0:49).abi rule of the profile if there is one, else the running kernel's; see the abi rule. With abi <abi/5.0>, the rule is compiled and loaded, and the mainline kernel never looks at it. With the mainline kernel's own feature set the rule is dropped.ipc/sysv_mqueue, so type=sysv rules compile to nothing under every shipped ABI: mqueue type=sysv rules not enforced under abi/5.0.rule-not-enforced: mqueue rules not enforced, mqueue type=posix rules not enforced, mqueue type=sysv rules not enforced (mqueue.cc:192-200). The line on the slide was printed by the parser built from the tree for a profile with abi <abi/3.0>,, a feature set without ipc. deny mqueue, under abi/3.0 gives mqueue rules not enforced.caps, capability, dbus, domain, file, io_uring, mount, namespaces, network_v8, network_v9, policy, ptrace, query, rlimit, signal. It was not taken from a running system.posix_mqueue are defined (apparmor.h:33, audit.c:58), class 18 is not, and no code walks either. The hook table: lsm.c:1785-1890.testcase_mqueue_01.in to testcase_mqueue_09.in in libraries/libapparmor/testsuite/test_multi/) come from kernels with the extra patches.mqueue rules, and that does not leave POSIX queues open: the queue is a file on an internal mount, and opening it reaches the file-open check with a path that does not connect to the root. Observed on Debian 13 and Debian sid, with and without an mqueue rule: mq_open fails with error 13 and the log has apparmor="DENIED" operation="open" class="file" info="Failed name lookup - disconnected path". See Kernel features and the policy ABI.mqueue rule to the profile did not change the refusal; a file rule for the queue was not tried in the recorded runs. Observed on Debian 13 and Debian sid, with and without an mqueue rule: mq_open fails with error 13 and the log has apparmor="DENIED" operation="open" class="file" info="Failed name lookup - disconnected path". See Kernel features and the policy ABI and What is not mediated.mqueue.cc:202-345 writes \x11 name NUL label (POSIX) and \x12 key NUL label (System V). The mainline kernel defines class 17 and never walks it.
-D rule-exprs for demo's line 20 under abi/5.0: \x11/demo-queue 0x50, \x11/demo-queue 0x10, \x11/demo-queue\x00[^\000]+ 0x50, and the class marker \d17 at priority 1001.gen_policy_re (mqueue.cc:202-345); the constructor: mqueue.cc:97-125.0x4000 and 0x8000 (map_mqueue_perms, mqueue.h:91-95), so the full set is 0xc076.mqueue read /q, gives \x11/q and \x11/q\x00[^\000]+ with 0x4; mqueue (create read) label=l /q2, gives \x11/q2 and \x11/q2\x00l, both 0x14.r and w come from the permission parser shared with dbus, signal and ptrace (parser_misc.c:763-772).\d17 and \d18 at priority 1001 (parser_regex.c:1444-1449).mqueue, under abi/5.0 also emits three class-18 rules (\x12....) although no class-18 marker is added (mqueue.cc:216-223, mqueue.cc:284-338).io_uring at index 18 (audit.c:58-59).mqueue (create read) label=l /q2, grants create and read on /q2 without the label. It follows the reasoning of the code comment (mqueue.cc:262-272) and is how the parser behaves. How an enforcing kernel queries the two forms is outside the trees.Permissions first and in parentheses when there are several; then type=, label=; the name last, starting with / or all digits.
-Q -K --skip-kernel-load --warn=all, nothing loaded into a kernel). The full form is AppArmor parser error for FILE in profile FILE at line N: MESSAGE.mqueue invalid type='%s' for a type other than posix or sysv (mqueue.cc:88).invalid mqueue rule conditional "%s" for an unknown conditional (mqueue.cc:91).mqueue type=sysv write 42, is a syntax error: permissions come first.mqueue invalidaccess /queuename, fails (bad_05.sd).TOK_OPEN because the word open is a token shared with {; see known bugs.perms contains invalid permissions for mqueue (mqueue.cc:112-116) exists for permission bits outside the set.mqueue rules are syntax everywhere and enforcement on some kernels. See Upstream and Ubuntu.
type=, label= and a queue name. A name starting with / is a POSIX queue; digits are a System V key.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the line (-Q -K --skip-kernel-load --warn=all, feature set abi/5.0 unless another is named), with nothing loaded into a kernel; "code" means the source was read, not run. Every statement about the kernel is read from the kernel source. What kernels with extra patches do is in Upstream and Ubuntu kernels.
MQUEUE RULE: [QUALIFIERS] mqueue [PERMISSIONS] [type=posix|sysv] [label=LABEL] [NAME] ,
PERMISSIONS: PERMISSION | ( PERMISSION [,] ... )
NAME: /PATTERN a POSIX queue
DIGITS a System V key
type and label may be written in either order, each once, with = only (tree).mqueue, covers every permission, both types and any queue (tree).| Seat | On an mqueue rule |
|---|---|
priority= | taken |
audit | taken |
allow, deny, prompt | taken |
owner, other | refused: owner prefix not allowed on mqueue rules |
| Word | Short form | Stands for |
|---|---|---|
create | - | making a new queue |
open | - | opening an existing queue |
delete | - | removing a queue |
getattr | - | reading the queue's attributes |
setattr | - | changing the queue's attributes |
read | r | receiving messages |
write | w | sending messages |
rw and wr are read and write. No permission word means all seven.
| Name | Type | Notes |
|---|---|---|
starts with / | POSIX | a pattern in the globbing syntax |
| digits only | System V | the key |
| anything else | error | mqueue invalid name 'NAME', message queue names must begin with a / or be a positive integer. |
| none | type= decides; without it, both | - |
type= must agree with the name: mqueue type=sysv /demo-queue, gives mqueue type=sysv invalid name '/demo-queue', sysv message queues must be identified by a positive integer. and mqueue type=posix 1234, gives mqueue type=posix invalid name '1234', posix message queues names must begin with a /.
| Feature set | POSIX rule | System V rule | Warning with --warn=rule-not-enforced | Enforced by the mainline kernel |
|---|---|---|---|---|
| abi/3.0 | dropped | dropped | mqueue type=posix rules not enforced; mqueue rules not enforced for an untyped rule | no |
| abi/4.0 | compiled | dropped | mqueue type=sysv rules not enforced | no |
| abi/5.0 | compiled | dropped | mqueue type=sysv rules not enforced | no |
the mainline kernel's own (no ipc) | dropped | dropped | as for abi/3.0 | no |
Which kernels do enforce the rules: Upstream and Ubuntu kernels.
| Line | Message |
|---|---|
mqueue create open /demo-queue, | syntax error, unexpected TOK_OPEN, expecting TOK_ID or TOK_CONDID or TOK_END_OF_RULE |
mqueue type=posix create /demo-queue, | syntax error, unexpected TOK_CREATE, expecting TOK_ID or TOK_CONDID or TOK_END_OF_RULE |
mqueue (create, open) demo-queue, | mqueue invalid name 'demo-queue', message queue names must begin with a / or be a positive integer. |
mqueue type=sysv /demo-queue, | mqueue type=sysv invalid name '/demo-queue', sysv message queues must be identified by a positive integer. |
mqueue type=posix 1234, | mqueue type=posix invalid name '1234', posix message queues names must begin with a / |
mqueue (create, bogus) /demo-queue, | Internal: unexpected mqueue perms character 'b' in input |
owner mqueue /demo-queue, | owner prefix not allowed on mqueue rules |
a type other than posix or sysv | mqueue invalid type='TYPE' |
| an unknown conditional | invalid mqueue rule conditional "NAME" |
an operator other than = | only "=" allowed in conditions of mqueue rules |
| feature set without message queues (warnings, off by default) | mqueue rules not enforced, mqueue type=posix rules not enforced, mqueue type=sysv rules not enforced |
\x11) for POSIX, 18 (\x12) for System V. A POSIX rule is the class byte, the name, a zero byte and the label; a System V rule is the class byte, the key as four bytes, a zero byte and the label (mqueue.cc:202-345).create (with any read and write) on the name alone; the permissions on the name and the label.0x2, read 0x4, create 0x10, delete 0x20, open 0x40, setattr 0x100, getattr 0x200 (mqueue.h:31-40).0x4000 and 0x8000 (mqueue.h:91-95).\d17 and \d18 at priority 1001 (parser_regex.c:1444-1449).posix_mqueue (apparmor.h:33, audit.c:58). It has no message-queue hook (lsm.c:1785-1890) and no ipc feature directory (apparmorfs.c:2684-2701).mqueue @{profile_name}, fails with the invalid-name message (tree).mqueue r 99999999999, is accepted (tree; latent).mqueue, under abi/5.0 emits class-18 rules although only POSIX queues are in the feature set (tree).io_uring at index 18 (code).type=(posix sysv) and label=(a b) are accepted and only the first value is used (tree).mqueue rule: mq_open fails with error 13 and the log has apparmor="DENIED" operation="open" class="file" info="Failed name lookup - disconnected path". See Kernel features and the policy ABI.PATH EXECMODE -> NAME, sends the exec to the profile called NAME. By the kernel source the attachment search is not used for such a rule.
PATH EXECMODE -> NAME, or EXECMODE PATH -> NAME,. The manual page calls these "Directed profile transitions" (apparmor.d.pod:1078-1091).&name target.Px -> name is the safe form: safe and unsafe.demo used across the map.opt_named_transition: TOK_ARROW id_or_var (parser_yacc.y:1043-1047).EXEC RULE = PATH EXECMODE -> TARGET,. TARGET is name, parent//child, :ns:name or &name: one literal word.
EXEC RULE: [QUALIFIERS] [file] [safe|unsafe] ( PATH EXECMODE | EXECMODE PATH ) -> TARGET,.TARGET: name | parent//child | :ns:name | :ns://name | &name. One word, unquoted or quoted, read literally.-> the lexer reads the next word as a plain name (parser_lex.l:822, parser_lex.l:456-462), so the target need not start with / and may equal a keyword or a mode word./a px -> b*, names a profile literally called b* (observed with the released parser 5.0.2).: marks a namespace; both :ns:name and :ns://name are recognised (parser_misc.c:863-882).l and no exec letters, the arrow is a link target: link rules./a px -> @{T},) is accepted and stored unexpanded by the parser built from the AppArmor tree at 836052d21. Do not rely on it.opt_named_transition: TOK_ARROW id_or_var (parser_yacc.y:1043-1047).The target is resolved at each exec, not at load. By the kernel source (read, not observed), a target that is not loaded gives info="profile transition not found" and, in enforce mode, EACCES, unless the mode has an i or u fallback.
Kernel facts are from the kernel source, read and not run.
x_table_lookup (domain.c:523-559), called for a table entry at domain.c:592-599.i: info="ix fallback", the program stays in the current profile. Mode with u: info="ux fallback", unconfined (domain.c:616-638).info="profile transition not found" and EACCES in enforce mode; in complain mode a learning profile is created instead (domain.c:740-754).ix -> name and ux -> name are accepted (released parser 5.0.2) with a changed meaning: ix -> name goes to name and falls back to inherit; ux -> name goes to name and does not run unconfined. The manual page lists targets for the p and c families only.post_parse_profile_file replaces the type bits with the slot number (block_rules.cc:581-596).In profile demo, Cx -> worker is stored as demo//worker. The prefix is always added with c modes; a target with a namespace is left as written.
c mode (cx Cx cix Cix cux CUx) the parser stores PROFILE//TARGET, where PROFILE is the name of the profile the rule is in (block_rules.cc:488-506).-S, reading the serialized table): in profile t, /a cx -> c, stores t//c; /a2 Cx -> t//c2, stores t//t//c2.c mode (block_rules.cc:479, block_rules.cc:515-522).cx (block_rules.cc:492-496).rcx -> pgrep: ok_link_4.sd.profile t { profile kid { /a cx -> gk, ... } } the table of t//kid holds kid//gk while the grandchild is t//kid//gk (parser built from the AppArmor tree at 836052d21, -S). By the kernel source that name does not resolve.A profile's exec table has 12 usable slots. Distinct target names beyond twelve fail with "Profile NAME has too many specified profile transitions."
AA_EXEC_COUNT is 16 (immunix.h:70), which leaves slots 4 to 15.Profile NAME has too many specified profile transitions. (block_rules.cc:584-587). Twelve px -> tN rules compile and the thirteenth gives the error (parser built from the AppArmor tree at 836052d21).c mode the stored string includes the parent prefix, so Cx -> a and Px -> a are different strings and take two slots (from the code, not run).x nor l (/z rw -> q,) is accepted and uses a slot (released parser 5.0.2). Do not rely on it.l -> /tmp/bar) do not use slots: ok_link_4.sd.-> :ns:name names a profile in another namespace. -> &name stacks name with the profile that attaches to the executable (the kernel source). See namespaces and stacking.
Kernel facts are from the kernel source, read and not run.
-> :ns:name: the parser recognises the namespace by the leading : (parser_misc.c:863-882) and writes the entry as :ns, a NUL byte, name (parser_interface.c:433-448). :ns://name is stored as :ns, NUL, //name (released parser 5.0.2, -S).: and rejects an entry where : is followed directly by a NUL (policy_unpack.c:499-512).-> &name: the kernel strips the & for the lookup (domain.c:540), then runs the ordinary attachment search for the executable (domain.c:597-602) and merges the two labels (domain.c:651-658).px.-> ::x, -> :ns: and -> :ns compile with exit status 0. By the kernel source ::x is expected to make the kernel refuse the whole profile at load; this was not run.A//&B (label.c:1672).add_named_transition (parser/block_rules.cc:474-525) fills exec_table; x_table_lookup (linux:security/apparmor/domain.c:523-559, the kernel) resolves the string with aa_label_parse.
do_file_rule stores the target in nt_name (parser_yacc.y:1759-1769).post_parse_profile_file runs at the end of the profile body, before variables are expanded, and calls add_named_transition for each entry with nt_name (block_rules.cc:576-596).add_named_transition: the c prefix "%s//%s" and the namespace test (block_rules.cc:474-525). add_entry_to_x_table: slots from (AA_EXEC_LOCAL >> 10) + 1, that is 4, up to AA_EXEC_COUNT, reusing equal strings (block_rules.cc:458-472).entry->perms = ((entry->perms & ~AA_ALL_EXEC_MODIFIERS) | (perms & AA_ALL_EXEC_MODIFIERS)) (block_rules.cc:591-596).sd_serialize_xtable writes struct xtable with an array of strings; in a namespace target the second : becomes NUL (parser_interface.c:413-456). apparmor_parser -S (--stdout, "Dump compiled profile to stdout", parser_main.c:232) shows the result.unpack_strs_table(e, "xtable", false, &pdb->trans) (policy_unpack.c:1075); the entry check restores the : (policy_unpack.c:499-512); every AA_X_TABLE index is range checked at load (policy_unpack.c:1542-1548).dfa_map_xindex: slot n becomes AA_X_TABLE | (n - 4) (policy_compat.c:36-45).x_table_lookup resolves the string with aa_label_parse(&profile->label, lookup, GFP_KERNEL, true, false) at each exec (domain.c:523-559). Its aa_find_child branch needs AA_X_CHILD with AA_X_TABLE, which dfa_map_xindex never produces.The target is not checked when the profile is compiled. By the kernel source, a wrong name loads and then fails each exec with "profile transition not found".
Messages of the parser built from the AppArmor tree at 836052d21, nothing loaded into a kernel.
/a x -> b,: Invalid perms, 'x' must be preceded by exec qualifier 'i', 'p', or 'u' (parser_misc.c:1099)./a px -> b c,: syntax error, unexpected TOK_ID, expecting TOK_END_OF_RULE.px -> b /a, (the arrow before the path): syntax error, unexpected TOK_ARROW, expecting TOK_ID or TOK_SET_VAR (released parser 5.0.2)./usr/bin/demo-* Px -> one, with /usr/bin/* Px -> two,: profile has merged rule with conflicting x modifiers, no line number. The slot number is part of the exec type, so two targets are two modes. Related test: x-conflict.sd.info="profile transition not found" and, in enforce mode, EACCES (domain.c:740-754). Not observed on a running kernel./a px -> b*, names a profile literally called b* (released parser 5.0.2).cx -> name inside a nested child is stored with the child's local name, not its full name: in profile t { profile kid { /a cx -> gk, profile gk { } } } the table of t//kid holds kid//gk (run with the parser built from the AppArmor tree at 836052d21, nothing loaded into a kernel, -S; block_rules.cc:498-504). The kernel parses the entry as a full name (domain.c:551-552; read from the kernel source, not observed on a running kernel), so it resolves to a top-level profile kid with a child gk if one is loaded, and to nothing otherwise./a px -> @{T}, asks the kernel for a profile literally named @{T} (block_rules.cc:581-596).-> ::x, -> :ns:, -> :ns) compile with exit status 0 (parser_misc.c:903-912).ux -> name does not run unconfined and ix -> name goes to name first; an arrow on a rule with no x and no l still takes one of the twelve table entries (parser_yacc.y:1080-1082). A reviewer who reads ux or counts targets by exec rules gets the wrong answer.Pix -> name, Pux -> name) a missing target is not an error: by reading the same kernel code, the exec continues under the current profile or unconfined.Next: syn-child-profiles, namespaces, stacking, syn-profile-name; syn-safe-unsafe for the case of the letter.
-> name: a profile in the same namespace. -> parent//child: a child by its full name. -> :ns:name: another namespace. -> &name: stack name with the profile that attaches to the executable.Cx -> name is stored as PROFILE//name. A profile can name 12 different targets.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above (6.0.0~alpha2) was run on the fragment (-Q -K --skip-kernel-load --warn=all, or -S to inspect the serialized table), with nothing loaded into a kernel; "code" means the parser or kernel source was read, not run. Kernel behaviour is that of the mainline Linux 7.4 source (7.4-rc2). Nothing here was observed on a running kernel.
EXEC RULE: [QUALIFIERS] [file] [safe|unsafe] ( PATH EXECMODE | EXECMODE PATH ) -> TARGET , TARGET: name | parent//child | :ns:name | :ns://name | &name
TARGET is one word, unquoted or quoted, and is read literally. After -> the lexer reads the next word as a plain name, so the target does not have to start with / and may equal a keyword or a mode word (code)./a px -> b, and px /a -> b, (tree)./a px -> b*, is accepted and names a profile literally called b* (tree).l and no exec letters, the arrow is a link target instead: syn-link-rules.| Form | Stored in the profile as | Resolved by the kernel as (code) |
|---|---|---|
name | name | a profile in the current namespace |
parent//child | parent//child | a child profile, by its full name |
:ns:name | :ns, a NUL byte, name | a profile in the namespace ns: namespaces |
:ns://name | :ns, a NUL byte, //name | the same (tree, -S) |
&name | &name | name stacked with the profile the attachment search finds for the executable: stacking |
With a c mode (cx, Cx, cix, Cix, cux, CUx) the parser stores PROFILE//TARGET, where PROFILE is the name of the profile the rule is in (code):
t, /a cx -> c, stores t//c (tree, -S)./a2 Cx -> t//c2, in profile t stores t//t//c2 (tree, -S).c mode (code).cx (code).| Letters | Meaning with -> TARGET |
|---|---|
p, P | go to TARGET |
c, C | go to the child TARGET of the current profile (the prefix above) |
i after them (pix, Cix, ...) | if TARGET is not found, stay in the current profile |
u after them (pux, CUx, ...) | if TARGET is not found, run unconfined |
| upper or lower case | safe or unsafe exec, as without a target: syn-safe-unsafe |
With a target, the letter no longer selects the kind of lookup: the kernel resolves the stored name in every case (code).
Profile NAME has too many specified profile transitions. Twelve px -> tN rules load and the thirteenth gives the error (tree).All statements in this section are from the mainline Linux 7.4 source (code); none was observed.
i fallback, the program stays in the current profile (info="ix fallback"); with a u fallback it runs unconfined (info="ux fallback").info="profile transition not found". In enforce mode the exec fails with EACCES. In complain mode the kernel creates a learning profile for the program instead of failing.&name: name is looked up first, then the ordinary attachment search runs for the executable and the two are stacked. If the search finds nothing, the fallback or the failure above applies.The parser prints errors as AppArmor parser error for FILE in profile FILE at line N: MESSAGE. Errors from the later compile stage have no line number and are followed by ERROR ... for profile NAME, failed to load.
| Message | Cause | Basis |
|---|---|---|
Profile NAME has too many specified profile transitions. | a 13th distinct target in one profile | tree |
Invalid perms, 'x' must be preceded by exec qualifier 'i', 'p', or 'u' | /a x -> b,: a bare x in front of the arrow | tree |
syntax error, unexpected TOK_ID, expecting TOK_END_OF_RULE | /a px -> b c,: a target of two words | tree |
syntax error, unexpected TOK_ARROW, expecting TOK_ID or TOK_SET_VAR | px -> b /a,: the arrow before the path | tree |
profile has merged rule with conflicting x modifiers | two rules with different targets whose patterns overlap, such as /usr/bin/demo-* Px -> one, and /usr/bin/* Px -> two, (compile stage, no line number) | tree |
link perms are not allowed on a named profile transition. | letters-first rule with l and a namespace target: l /a -> :ns:b, | code |
link and exec perms conflict on a file rule using -> | letters-first rule with both l and an exec mode and an arrow | code |
warning ambiguous rule specifies both link target and exec transition target. Using as exec transition | path-first rule with l, an exec mode and an arrow; warning class deprecated | tree |
kernel record info="profile transition not found" | the target is not loaded at exec and the mode has no fallback | code |
An exact path next to a pattern is not a conflict: the exact rule wins (syn-exec-modes). The conflict arises between two patterns because the slot number is part of the exec type.
Each item below is behaviour of the tree's parser that differs from the documentation or from what the syntax suggests. It is not intended behaviour; do not rely on it.
/a px -> @{T},) is accepted and stored unexpanded, so the kernel is given the name @{T} (tree, -S). The same variable in a link target or a change_profile target is expanded.cx -> name inside a nested child profile is prefixed with the child's local name, not its full name: in profile t { profile kid { /a cx -> gk, profile gk { } } } the table of t//kid holds kid//gk while the grandchild is t//kid//gk (tree, -S). By the kernel code the name does not resolve.px -> other//PATH, where the child's name equals the rule's path, is rewritten to a local (cx) transition (code; listed in the AppArmor bug sweep).-> ::x, -> :ns: and -> :ns compile with exit status 0 (tree). By the kernel code, ::x is expected to make the kernel refuse the whole profile at load; this was not run.x and no l (/z rw -> q,) is accepted and uses a slot of the exec table (tree). The manual page says a target requires an exec transition.ux -> name still prints the warning about an unconfined exec (Unconfined exec qualifier (ux) allows some dangerous environment variables ...) although no unconfined exec can result (tree).ix -> name and ux -> name are accepted with a meaning different from the plain modes: ix -> name goes to name and falls back to inherit; ux -> name goes to name and does not run unconfined (tree for acceptance, code for the meaning). The manual page lists targets for the p and c families only. This one may be intended.| Step | Where | |
|---|---|---|
grammar: opt_named_transition: TOK_ARROW id_or_var | parser/parser_yacc.y:1043-1047 | |
lexer state SUB_ID_WS after ->: the next word is a plain TOK_ID | parser/parser_lex.l:822, parser/parser_lex.l:456-462 | |
do_file_rule stores nt_name | parser/parser_yacc.y:1759-1769 | |
post_parse_profile_file: runs at the end of the profile body, before process_variables | parser/block_rules.cc:576-596 | |
add_named_transition: the c prefix, the namespace test | parser/block_rules.cc:474-525 | |
add_entry_to_x_table: slots 4 to 15, reuse of equal strings | parser/block_rules.cc:458-472 | |
slot limits: AA_EXEC_COUNT, the reserved values | parser/immunix.h:70, parser/immunix.h:80-82 | |
sd_serialize_xtable: struct xtable, the NUL in namespace targets | parser/parser_interface.c:413-456 | |
unpack_strs_table(e, "xtable", ...) into pdb->trans | linux:security/apparmor/policy_unpack.c:1075 | |
process_strs_entry: restores the :, rejects : followed by NUL | linux:security/apparmor/policy_unpack.c:499-512 | |
range check of every AA_X_TABLE index at load | linux:security/apparmor/policy_unpack.c:1542-1548 | |
dfa_map_xindex: slot n becomes `AA_X_TABLE \ | (n - 4)` | linux:security/apparmor/policy_compat.c:36-45 |
x_table_lookup: aa_label_parse relative to the current profile | linux:security/apparmor/domain.c:523-559 | |
x_to_label: the & stack, the ix and ux fallbacks | linux:security/apparmor/domain.c:574-650 | |
| "profile transition not found", the learning profile | linux:security/apparmor/domain.c:740-754 |
x_table_lookup also has an aa_find_child branch for an index carrying AA_X_CHILD (linux:security/apparmor/domain.c:542-550). dfa_map_xindex never sets AA_X_CHILD together with AA_X_TABLE, so policy written by this parser does not reach it.
network FAMILY TYPE, allows sockets of that family and type. Without a matching rule a confined task gets EACCES from socket().
socket_create asks for the permission create with the family, type and protocol of the call (lsm.c:1258-1291). It does nothing for sockets the kernel creates for itself and for an unconfined task (lsm.c:1265-1269). A refusal is EACCES.network_v8, or network_v9 with af_unix): every profile that is not in unconfined or default_allow mode then mediates networking, whether or not it has a network rule. The slide assumes such a feature set./sys/kernel/security/apparmor/features/network_v8/af_mask and network_v9/af_mask (net.c:24-36).network inet stream, is line 11 of demo's profile. The program demo and its profile are invented for the map.[QUALIFIERS] network [PERMISSIONS] [FAMILY] [TYPE] [CONDITIONALS],. Each part left out means "all".
network inet,, network inet tcp,, network tcp,, network stream,, network (create, bind listen) inet,, network create inet stream,, network rw inet,, network "inet",, audit deny network,, prompt network inet,.audit, deny, allow and prompt are taken. priority= and owner are refused: priority prefix not allowed on network rules, owner prefix not allowed on network rules (network.h:270-276).network_rule productions (parser_yacc.y:1154-1194); the permission list at parser_yacc.y:1409-1415.NETWORK_MODE (parser_lex.l:627-694, entered at parser_lex.l:870-872); the constructors at network.cc:489-603.Family = the AF_ name in lower case (45 of them); type = stream, dgram, seqpacket, rdm, raw, packet; tcp, udp, icmp are aliases. Names are case sensitive.
inet, tcp is stream, udp is dgram and icmp is raw; for inet6, tcp and udp. network inet stream, and network inet tcp, give identical output (run with the tree's parser).Invalid network entry.: network inet dccp,, network inet sctp,, network inet6 icmp,, network inet icmpv6,, network bogus,, network INET,, network local,.af_mask: a family the kernel lacks is compiled anyway.network_v8/sctp).af_inet, network inet icmp, carries protocol value 2 rather than 1 (network.cc:148-149). It is not relevant to the mainline kernel, which matches no protocol for inet rules.network_mappings[] is built from the generated af_names.h, six rows per family (network.cc:124-160); the names are checked against the build host's headers (Makefile:391-402).net_find_mapping: network.cc:288-333.create bind listen accept connect shutdown getattr setattr getopt setopt send receive. Each socket call requests one; a rule without a list grants all.
socket_create, create, create (lsm.c:1258-1291); socket_bind, bind, bind (lsm.c:1372-1388); socket_connect, connect, connect (lsm.c:1390-1407); socket_listen, listen, listen (lsm.c:1426-1440); socket_accept, accept, accept (lsm.c:1446-1461); socket_sendmsg, sendmsg, send (lsm.c:1483-1502); socket_recvmsg, recvmsg, receive (lsm.c:1504-1508); socket_getsockname and socket_getpeername, getattr (lsm.c:1527-1535); socket_getsockopt and socket_setsockopt, getopt and setopt (lsm.c:1555-1567); socket_shutdown, shutdown (lsm.c:1569-1572).read or r for receive, write or w for send, and rw.MSG_FASTOPEN on TCP or MPTCP is also checked as connect (lsm.c:1490-1499; feature tcp-fast-open).read and write, or passed over a unix socket, is checked again as send and receive when the label cached on the file does not cover the task (file.c:551-573).setattr.create, shutdown, setattr, getattr, bind, listen, setopt, getopt) cannot be combined with peer conditionals; the peer permissions are send, receive, connect and accept.map_perms() folds the bits before they go into the policydb (network.h:114-120); the kernel's map_other() unfolds them (policy_compat.c:197-202). Kernel names: net.h:22-39.Network denials return EACCES and log family=, sock_type=, protocol=, requested= and denied=. Records for connected inet sockets add laddr, lport, faddr, fport.
family=, sock_type=, protocol=, requested=, denied=; net.c:38-78, net.c:118-166) with demo's values, which are illustrative.requested= and denied= fields.laddr, lport, faddr and fport come from the common LSM audit code, for sockets other than unix (lsm_audit.c:297-314).unknown(N). The info= reasons are failed af match, failed type match and failed protocol match (net.c:234-247).create, bind, connect, listen, accept, sendmsg, recvmsg, getsockname, getpeername, getsockopt, setsockopt, socket_shutdown (audit.h:75-87). The class is always net.With network_v8 or network_v9 the rule keeps its permissions; with only the legacy network feature it is reduced to family and type; with none it is dropped. Use --warn=rule-not-enforced --warn=rule-downgraded to be told.
network (connect) inet stream, gives the same output as network inet stream,; with no network feature, every network rule gives the output of a profile without it. Nothing was loaded into a kernel.network, network_v8, network_v9, network_v8/af_inet, network_v9/af_inet, network/af_unix, network_v9/af_unix, network_v9_skb and network_v9_skb/iface. Each is the intersection of the kernel feature set and the policy ABI (parser_main.c:1044-1073).network_v8 with af_mask, tcp-fast-open and sctp, and network_v9 with af_mask, af_unix and tcp-fast-open (net.c:24-36, apparmorfs.c:2688-2689). It has no reader for the legacy per-family table.network rules not enforced, profile NAME network rules not enforced (network.cc:669-672), downgrading extended network unix socket rule to generic network rule (af_unix.cc:537)./sys/kernel/security/apparmor/features/network_v8/ and network_v9/, or aa-features-abi -x.ip=, port=, label=, interface=) are dropped without a message at any warning level, also from deny rules: see Network address conditionals.AF_UNIX also creates a unix rule. Known discrepancy (run with the tree's parser): the permission list is not carried into it, so with the mainline feature set network (create) unix stream, allows every operation on abstract and unnamed unix stream sockets, and network (create), does the same for all unix types (af_unix.cc:105-125): see Unix socket rules.network rules not enforced although it writes the table.network.cc:1000-1038 writes class, family, type; net.c:228-274 walks them and reads the permissions at the type state.
0f 00 02 00 01 and the permission value 0x40 were produced with the tree's parser and the mainline feature file, for network (connect) inet stream peer=(ip=10.0.0.1 port=80),, which compiles to the same single rule as the line on the slide.AA_CLASS_NET 4, AA_CLASS_NETV8 14, AA_CLASS_NETV9 15, AA_CLASS_NETV9_SKB 30 (policydb.h:28, policydb.h:38-39, policydb.h:54).RULE_MEDIATES_NET tries class 15 and falls back to the kernel's AA_CLASS_NET, which is 14 (policy.h:346-358, apparmor.h:30-31). The walk: net.c:192-274.ALL_TYPES, 0x43e) become .. in the match string (network.cc:40, network.cc:1009-1029).net_allowed_af holds, per family, three u16 values: allow without deny, allowed and audited, deny and quiet (parser_interface.c:572-582).At most a family and a type; permissions first and in parentheses when several; no priority= and no owner.
AppArmor parser error for FILE in profile FILE at line N: MESSAGE; the slide shows MESSAGE, produced by the tree's parser. The messages of rows 3 and 4 continue with the tokens the parser expected.network 'create', 'shutdown', 'setattr', 'getattr', 'bind', 'listen', 'setopt', and/or 'getopt' accesses cannot be used with peer socket conditionals (network.cc:526).r and w letters: network (bogus) inet, gives Internal: unexpected net perms character 'b' in input, and network (rwx) inet, the same for x.owner network inet, gives owner prefix not allowed on network rules (network.h:270-276).network inet xattrs=(a=b), gives network rule: invalid conditional group xattrs=().network_bad_*.sd files in parser/tst/simple_tests/network.Next: address conditionals, unix rules, and the feature set of your kernel.
[QUALIFIERS] network [PERMISSIONS] [FAMILY] [TYPE] [CONDITIONALS],: each part left out means all.EACCES and is logged with family=, sock_type= and denied=.--warn=rule-not-enforced --warn=rule-downgraded makes the parser say so.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the line (-Q -K --skip-kernel-load --warn=all), with nothing loaded into a kernel; "code" means the parser source or the kernel source was read, not run. Nothing here was observed on a running kernel.
NETWORK RULE: [QUALIFIERS] network [PERMISSIONS] [FAMILY] [TYPE] [CONDITIONALS] , PERMISSIONS: PERMISSION | ( PERMISSION ... ) QUALIFIERS: [audit] [allow|deny|prompt]
network tcp, is inet and inet6 stream (tree).ip=, port=, peer=( )) are in syn-network-inet.The name is the kernel's AF_ constant in lower case (parser/base_af_names.h).
| Name | Constant | Number |
|---|---|---|
unspec | AF_UNSPEC | 0 |
unix | AF_UNIX | 1 |
inet | AF_INET | 2 |
ax25 | AF_AX25 | 3 |
ipx | AF_IPX | 4 |
appletalk | AF_APPLETALK | 5 |
netrom | AF_NETROM | 6 |
bridge | AF_BRIDGE | 7 |
atmpvc | AF_ATMPVC | 8 |
x25 | AF_X25 | 9 |
inet6 | AF_INET6 | 10 |
rose | AF_ROSE | 11 |
netbeui | AF_NETBEUI | 13 |
security | AF_SECURITY | 14 |
key | AF_KEY | 15 |
netlink | AF_NETLINK | 16 |
packet | AF_PACKET | 17 |
ash | AF_ASH | 18 |
econet | AF_ECONET | 19 |
atmsvc | AF_ATMSVC | 20 |
rds | AF_RDS | 21 |
sna | AF_SNA | 22 |
irda | AF_IRDA | 23 |
pppox | AF_PPPOX | 24 |
wanpipe | AF_WANPIPE | 25 |
llc | AF_LLC | 26 |
ib | AF_IB | 27 |
mpls | AF_MPLS | 28 |
can | AF_CAN | 29 |
tipc | AF_TIPC | 30 |
bluetooth | AF_BLUETOOTH | 31 |
iucv | AF_IUCV | 32 |
rxrpc | AF_RXRPC | 33 |
isdn | AF_ISDN | 34 |
phonet | AF_PHONET | 35 |
ieee802154 | AF_IEEE802154 | 36 |
caif | AF_CAIF | 37 |
alg | AF_ALG | 38 |
nfc | AF_NFC | 39 |
vsock | AF_VSOCK | 40 |
kcm | AF_KCM | 41 |
qipcrtr | AF_QIPCRTR | 42 |
smc | AF_SMC | 43 |
xdp | AF_XDP | 44 |
mctp | AF_MCTP | 45 |
Rules that cover unix also create a unix rule; see syn-unix.
| Word | Constant | Alias |
|---|---|---|
stream | SOCK_STREAM | tcp for inet and inet6 |
dgram | SOCK_DGRAM | udp for inet and inet6 |
raw | SOCK_RAW | icmp for inet |
seqpacket | SOCK_SEQPACKET | |
rdm | SOCK_RDM | |
packet | SOCK_PACKET |
There is no word for a protocol number: network inet sctp, and network inet dccp, are refused (tree).
| Word | Also written | Side | Requested by (LSM hook) | Operation in the log |
|---|---|---|---|---|
create | local | socket_create | create | |
bind | local | socket_bind | bind | |
listen | local | socket_listen | listen | |
accept | peer | socket_accept | accept | |
connect | peer | socket_connect | connect | |
send | write, w | peer | socket_sendmsg | sendmsg |
receive | read, r | peer | socket_recvmsg | recvmsg |
getattr | local | socket_getsockname, socket_getpeername | getsockname, getpeername | |
setattr | local | none | ||
getopt | local | socket_getsockopt | getsockopt | |
setopt | local | socket_setsockopt | setsockopt | |
shutdown | local | socket_shutdown | socket_shutdown |
rw is send and receive.linux:security/apparmor/lsm.c:1258-1572, not from a run.| Seat | On a network rule |
|---|---|
priority= | refused: priority prefix not allowed on network rules (tree) |
audit | taken |
allow, deny, prompt | taken: deny is not logged; prompt is in syn-prompt |
owner, other | refused: owner prefix not allowed on network rules (tree) |
| The feature set has | The rule is compiled as | Lost |
|---|---|---|
network_v8 or network_v9 | family, type and permissions | conditionals, unless it also has af_inet: see syn-network-inet |
only the legacy network | family and type | the permission list and all conditionals |
| no network feature | nothing: the rule is dropped | everything; networking is not mediated |
--warn=rule-not-enforced and --warn=rule-downgraded; both are off by default (code).| Field | Meaning |
|---|---|
operation= | the socket operation, see the permission table |
class="net" | always |
family= | the family name, or unknown(N) |
sock_type= | the socket type |
protocol= | the protocol number |
requested=, denied= | permission names |
laddr=, lport=, faddr=, fport= | local and remote address and port, for sockets other than unix |
info= | failed af match, failed type match or failed protocol match |
Read from the kernel's format strings (linux:security/apparmor/net.c:38-166, linux:security/lsm_audit.c:297-314).
| Rule | Message |
|---|---|
network inet stream tcp, | syntax error, unexpected TOK_ID, expecting TOK_END_OF_RULE |
network INET stream, | Invalid network entry. |
network inet sctp, | Invalid network entry. |
network inet create, | syntax error, unexpected TOK_CREATE, expecting TOK_END_OF_RULE |
network send receive inet, | syntax error, unexpected TOK_RECEIVE, expecting TOK_END_OF_RULE |
network (bogus) inet, | Internal: unexpected net perms character 'b' in input |
priority=1 network inet, | priority prefix not allowed on network rules |
owner network inet, | owner prefix not allowed on network rules |
network (bind) inet peer=(port=8080), | network 'create', 'shutdown', 'setattr', 'getattr', 'bind', 'listen', 'setopt', and/or 'getopt' accesses cannot be used with peer socket conditionals |
network inet xattrs=(a=b), | network rule: invalid conditional group xattrs=() |
any network rule, no network feature, --warn=rule-not-enforced | warning network rules not enforced |
a unix rule on a feature set without unix mediation, --warn=rule-downgraded | warning downgrading extended network unix socket rule to generic network rule |
All rows are from the tree's parser.
AA_CLASS_NETV9 15, or AA_CLASS_NETV8 14), two bytes of family and two of type, big endian, with the folded permissions at that state (parser/network.cc:1000-1038). network (connect) inet stream, is \x0f\x00\x02\x00\x01 with 0x40 (tree)... (parser/network.cc:1009-1029).parser/parser_regex.c:1415-1440), which is why a profile without network rules refuses sockets.net_allowed_af: per family three u16 values (parser/parser_interface.c:572-582).aa_profile_af_perm starts at the class, feeds family and type and reads the permissions there (linux:security/apparmor/net.c:192-274).parser/parser_yacc.y:1154-1194, parser/parser_lex.l:627-694.None of these is taught as intended behaviour; the verdicts come from the review.
network (PERMISSIONS) unix ... creates a unix rule with every permission (tree): see syn-unix.af_inet, also from deny rules (tree): see syn-network-inet.network inet icmp, carries protocol value 2 on a feature set with af_inet (code).network rules not enforced although it writes the table (tree).ip= and port= restrict an inet or inet6 network rule to a local address and port. Whether they are enforced depends on the kernel's feature set.
inet and inet6 only. With one of them and no family word, the rule covers inet and inet6 (network.cc:503-511). With any other family it is an error: network family does not support local or peer conditionals (network.cc:551-554).network_v8/af_inet or network_v9/af_inet (network.cc:1031); see "Compiled only for a kernel that has af_inet" in this deck.network [PERMS] [inet|inet6] [TYPE] [ip=A] [port=N|N-M] [interface=I] [label=L] [peer=(ip=A port=N label=L)],.
network inet ip=::1 port=80-90,, network inet ip=none,, network inet6 ip=1.2.3.4,, network stream ip=1.2.3.4,, network (connect) inet peer=(ip=1.2.3.4 port=80),.network conditional "ip" can only be specified once (parser_misc.c:1243).interface is local only: interface cannot be set for peer in network rules (network.cc:497-498).label:=NAME is accepted only inside the group, and the parser marks its value unused (network.h:144; network/skb/ok_setlabel_peer_1.sd).network_rule::move_conditionals (network.cc:445-477); the group is passed with peer = true (network.cc:496).has_local_conds and has_peer_conds: network.h:225-226.ip= takes one IPv4 or IPv6 address or none: no prefix, no range. port= takes N or N-M up to 65535; port=0 means any port.
ip= is parsed as one address (network.cc:335-361, network.cc:415-423): ip=1.2.3 gives network invalid ip='1.2.3'. An IPv4 address is accepted in an inet6 rule.port=0 is compiled as any port number (network.cc:725-731).network ip=127.0.0.1 port=8080,, port=0 and port=65535 in network/network_ok_20.sd; network port=0-65534, and network peer=(port=1-65535), in network/port-torture.sd.network inet port=(80 81), and network inet port=80, give byte-identical output (run with the tree's parser).Local conditionals narrow any permission. peer=( ) can be combined only with connect, accept, send and receive.
network 'create', 'shutdown', 'setattr', 'getattr', 'bind', 'listen', 'setopt', and/or 'getopt' accesses cannot be used with peer socket conditionals (network.cc:526); produced by the tree's parser. Test file: network/perms/bad_opt_2.sd.network (accept) inet peer=(ip=1.2.3.4), is accepted.bind rule with a port below 1024 is marked as a privileged port (network.cc:815-868). The capability is a separate rule: Capability rules.label alone does not count as a peer conditional, so network (bind) peer=(label=foo), is accepted and the rule is not limited to inet and inet6 (network.h:226; run with the tree's parser).Without af_inet in the feature set, ip=, port= and the peer group are dropped at compile time and the rule is network FAMILY TYPE,. The mainline kernel exports no af_inet. No warning is printed.
network inet, and network inet ip=1.2.3.4 port=80, give byte-identical output and no warning with --warn=all; with abi/5.0 they differ. Nothing was loaded into a kernel.network_v8/af_inet and network_v9/af_inet, each the intersection of the kernel feature set and the policy ABI (parser_main.c:1044-1073). The tree's abi/5.0 lists af_inet (abi/5.0:66-80).laddr, lport, faddr and fport although no rule can match on them.EINVAL or EAFNOSUPPORT before the policy check (af_inet.c:116-135, af_inet.c:176-224).interface= needs network_v9_skb/iface, which only profiles/apparmor.d/abi/5.0-interface lists and the mainline kernel does not export. label= on inet sockets is not matched by the mainline kernel.ls /sys/kernel/security/apparmor/features/network_v8/ or aa-features-abi -x.Known discrepancies: without af_inet, address conditionals are dropped from allow and deny rules alike; peer=(label=...) alone compiles to network,; a value list keeps its first value. The parser prints nothing.
ip=1.2.3.4 port=80 and peer=(label=foo). Nothing was loaded into a kernel.deny rules, because the downgrade makes the rule less specific (af_unix.cc:204-229).has_peer_conds() tests only the peer address and port (network.h:226).apparmor_parser -S -K (or -Q -D rule-exprs) with and without the conditional, and compare.af_inet: see Upstream and Ubuntu kernels.af_inet.deny network inet ip=... as a block list loses all inet networking, which invites replacing it with a broad allow.abi: a profile pinned to abi/5.0 and loaded on a kernel without af_inet is compiled for the intersection.interface= behaves the same without network_v9_skb/iface.label:= that cannot be written.network.cc:870-998, 1058-1133 writes the inet layout; af_inet.c:233-325 in the mainline kernel checks only family, type and protocol.
-D rule-exprs: \x0f\x00\x02\x00\x01..\x02\x00\x50\x01\x0a\x00\x00\x01\x00[^\000]*\x00\x01..., followed by the three alternatives for the local address, with permission 0x40. demo's own line 11 under abi/5.0 gives a create rule on \x0f\x00\x02\x00\x01 and the address layout with 0x1fc076.port=0 becomes .. (network.cc:725-731).CMD_ADDR 1, listen 2, option 4 (network.cc:1096-1133). The layout: network.cc:870-998, network.cc:1058-1133.AA_CLASS_NETV9_SKB, 30 (network.cc:929-962, network.cc:1163-1165), which the kernel defines (apparmor.h:39) and uses nowhere else. set_label and the AA_SET_LABEL permission for send rules belong to that class (network.cc:955-956).network inet icmp, writes protocol value 2 where protocols are emitted.Values and placement are checked at parse time. A rule that parses is not proof that its conditionals are enforced.
AppArmor parser error for FILE in profile FILE at line N: MESSAGE; the slide shows MESSAGE, produced by the tree's parser.network invalid interface='NAME' (network.cc:471).unsupported operator in label conditional of network rules for label in (...) (network.cc:457).network inet port=90-80, gives network invalid port='90-80'. A conditional given twice: network conditional "ip" can only be specified once.Address conditionals need af_inet in the kernel's feature set. Family and type are enforced everywhere network mediation exists.
ip=, port=, interface=, label= and peer=(ip= port= label=) on inet and inet6 network rules.af_inet; otherwise dropped without a message, and the rule is its family and type.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the line (-Q -K --skip-kernel-load --warn=all), with nothing loaded into a kernel; "code" means the parser source or the kernel source was read, not run. Nothing here was observed on a running kernel. "The mainline kernel" is the kernel tree named on the page; other kernels are in upstream-and-ubuntu.
NETWORK RULE: [QUALIFIERS] network [PERMISSIONS] [inet|inet6] [TYPE] [LOCAL ...] [peer=( PEER ... )] , LOCAL: ip=ADDRESS | port=N | port=N-M | interface=NAME | label=PATTERN PEER: ip=ADDRESS | port=N | port=N-M | label=PATTERN | label:=NAME
inet and inet6; any other family is an error (tree).| Name | Side | Value | Operator | Needs in the feature set | On the mainline kernel |
|---|---|---|---|---|---|
ip | local, peer | one IPv4 or IPv6 address, or none | = | af_inet | dropped at compile time |
port | local, peer | N or N-M, 0 to 65535; 0 is any port | = | af_inet | dropped at compile time |
interface | local | a pattern | = | network_v9_skb/iface | dropped at compile time |
label | local, peer | a pattern | =; := inside peer=( ) | af_inet | not matched |
"Dropped" is from runs of the tree's parser with the mainline kernel's feature file; that the kernel checks only family, type and protocol for inet sockets is from its source (linux:security/apparmor/af_inet.c:233-325).
ip: parsed as a single address. No prefix length, no range, no host name. An IPv4 address is accepted in an inet6 rule (tree).port: decimal. A range is LOW-HIGH. port=0 compiles as any port number (code).interface, label: patterns in the globbing syntax (code).label:=NAME: accepted only inside peer=( ); the parser marks the value unused (code).port=(80 81) is accepted and only the first value is used (tree).| Side | Permissions |
|---|---|
| local | create, shutdown, setattr, getattr, bind, listen, setopt, getopt |
| peer | connect, accept, send, receive |
network 'create', 'shutdown', 'setattr', 'getattr', 'bind', 'listen', 'setopt', and/or 'getopt' accesses cannot be used with peer socket conditionals (tree).bind rule for a port below 1024 does not replace capability net_bind_service,; see syn-capability.| Feature set | af_inet | network_v9_skb/iface |
|---|---|---|
the tree's abi/5.0 | listed | not listed |
the tree's abi/5.0-interface | listed | listed |
| the mainline kernel | not exported | not exported |
abi rule (code).ls /sys/kernel/security/apparmor/features/network_v8/ or aa-features-abi -x.apparmor_parser -S -K with and without the conditional and compare the output. The parser prints no warning when it drops a conditional, at any warning level (tree).| Rule | Message |
|---|---|
network inet ip=127.0.0.1/8, | network invalid ip='127.0.0.1/8' |
network inet ip=1.2.3, | network invalid ip='1.2.3' |
network inet port=70000, | network invalid port='70000' |
network inet port=90-80, | network invalid port='90-80' |
network unix port=80, | network family does not support local or peer conditionals |
network inet stream peer=(interface=eth0), | interface cannot be set for peer in network rules |
network inet peer=(ip:=1.2.3.4), | unsupported operator used in conditions of network rules |
network inet label:=foo, | Lexer found unexpected character: ':' (0x3a) in state: NETWORK_MODE |
network inet label in (a), | unsupported operator in label conditional of network rules (code) |
network inet ip=1.2.3.4 ip=1.2.3.5, | network conditional "ip" can only be specified once |
network (bind) inet peer=(port=8080), | the peer permission message above |
| a bad interface name | network invalid interface='NAME' (code) |
All rows are from the tree's parser unless marked.
af_inet, after class, family and type the match string continues: protocol; peer port type (0 unprivileged, 1 privileged, 2 remote) and two port bytes; an address-size byte (0 none, 1 IPv4, 2 IPv6) and the address; NUL, the label pattern, NUL; then the command byte CMD_ADDR (1) and the same layout for the local address; command 2 with two bytes for listen, command 4 with four bytes for socket options (parser/network.cc:870-998, 1058-1133).network (connect) inet stream peer=(ip=10.0.0.1 port=80), gives \x0f\x00\x02\x00\x01..\x02\x00\x50\x01\x0a\x00\x00\x01\x00[^\000]*\x00\x01... with permission 0x40.parser/network.cc:719-765).AA_CLASS_NETV9_SKB (30) (parser/network.cc:929-962).af_inet the function returns after the generic form (parser/network.cc:1031-1039).af_inet.c collects local and remote addresses for the audit record and ends every permission function in the family, type and protocol check (linux:security/apparmor/af_inet.c:62-325).None of these is taught as intended behaviour; the verdicts come from the review (sec-bugs). Each was run with the tree's parser unless marked.
af_inet, inet conditionals are dropped without a message, also from deny rules: deny network inet ip=1.2.3.4, compiles as deny network inet,.label is not treated as a peer conditional: network peer=(label=foo), compiles as network,, and network (bind) peer=(label=foo), is accepted.network inet icmp, carries protocol value 2 where protocols are emitted (code).label:=; network inet label:=foo, fails in the scanner.network inet port=(80 81), equals network inet port=80,.other RULE, applies a file rule only to files whose owner uid differs from the task's fsuid. It is the complement of owner. (The kernel, read from the source.)
other is a rule qualifier for file rules. An other rule applies when the owner uid of the file differs from the task's fsuid; an owner rule applies when they are equal; a rule with neither keyword applies in both cases.owner /var/lib/demo/shared/** rw, and other /var/lib/demo/shared/** r,. The directory and the two file names are invented for this deck; demo is the map's example program.current_fsuid() (file.c:227) and the choice between the two cases is in aa_lookup_condperms (file.c:194-209). This was read from the kernel source; nothing in this deck was observed on a running kernel.TOK_OTHER in opt_owner_flag, parser_yacc.y:696-698; keyword table parser_misc.c:97.other: parser_misc.c:1155-1156.owner and no entry for other: apparmor.d(5), Rule Qualifiers[priority=N] [audit] [allow|deny|prompt] other FILE RULE,. owner and other share a seat; a rule with neither applies to all files.
[priority=N] [audit] [allow|deny|prompt] other FILE RULE,. The order of the qualifiers is fixed; owner and other are alternatives for the last seat.other /tmp/** rw, (ok_other_1.sd), deny other /tmp/** rw, (ok_other_2.sd), audit other /tmp/** rw, (ok_other_3.sd).owner other /foo r, is rejected with syntax error, unexpected TOK_OTHER, expecting TOK_ID or TOK_MODE or TOK_SET_VAR (run with the tree's parser at 836052d21, -Q -K --skip-kernel-load --warn=all). The slide shows the same rule with the path /tmp/**.AppArmor parser error for FILE in profile FILE at line N: MESSAGE.owner X (files the task's user owns), other X (files it does not own), X (both).'other' in its grammar; FILE RULE and LINK RULE show only [ 'owner' ] (apparmor.d.pod:397, apparmor.d.pod:416).opt_owner_flag: empty, TOK_OWNER or TOK_OTHER, parser_yacc.y:696-698. One production, so one keyword per rule.owner, user (both TOK_OWNER) and other: parser_misc.c:95-97.owner, and its undocumented alias user: syn-owneraudit in front: syn-auditowner P rw, with other P r, gives owners read-write and everyone else read-only on P. The kernel uses one half per access, chosen by comparing the task's fsuid with the file's owner.
owner /c rw, with other /c r, compile to one rule whose permission mask is 0x1000e: rw in the owner half, r in the other half (dump from the tree's parser at 836052d21 with -D rule-exprs -D dfa-states-initial; nothing was loaded into a kernel).x 0x1, w 0x2, r 0x4, a 0x8; the other half is shifted left by 14 bits, so r for others is 0x10000. w implies a, so the owner half rw is 0xe.aa_lookup_condperms returns the first permission entry of a file state when uid_eq(subj_uid, cond->uid) and the second otherwise (file.c:194-209); the subject uid is current_fsuid() (file.c:227).fsuid=... ouid=... (file.c:63-66, the kernel).owner keeps AA_USER_PERMS | AA_SHARED_PERMS, other keeps AA_OTHER_PERMS | AA_SHARED_PERMS: parser_misc.c:1152-1156.cur->perms |= next->perms in block_rules::merge_file: block_rules.cc:285-338.owner in the manual page: apparmor.d(5), ownerdeny other P rw, denies access to files under P that the task does not own; the task's own files are unaffected. Like any deny it is quiet unless you write audit deny other. (The kernel, read from the source.)
deny other /tmp/** rw, is a fixture in the tree: ok_other_2.sd./d rw, with deny other /d rw, compiles to the state (0x e/38000//0/0/38000) (dump from the tree's parser at 836052d21; format (allow/deny//prompt/audit/quiet)): the owner half allows rw; the other half is denied and quiet./tmp/demo-1000.sock and /tmp/other-user.txt are illustrations.owner /tmp/** rw, alone: both leave the other half without permissions. With deny other the refusals are quiet, and an allow rule from elsewhere (an included abstraction, for example) cannot add permissions for those files at the same priority. Rules with a higher priority=N can: syn-priority.audit deny other /tmp/** rw, keeps the refusal and makes it logged: syn-audit.deny and owner in the manual page: apparmor.d(5), deny, apparmor.d(5), ownerother → owner_t::NOT → perms &= AA_OTHER_PERMS | AA_SHARED_PERMS (parser/parser_misc.c:1155-1156) → entry index + 1 in aa_lookup_condperms (linux:security/apparmor/file.c:203-205, the kernel).
TOK_OTHER { $$ = owner_t::NOT; }, parser_yacc.y:698; enum class owner_t { UNSPECIFIED, SPECIFIED, NOT }, rule.h:193. The prefix dump prints !owner: rule.h:297-301.entry_add_prefix: entry->perms &= (AA_OTHER_PERMS | AA_SHARED_PERMS) for owner_t::NOT, parser_misc.c:1155-1156. It is the only place the qualifier is applied to file rules.-D rule-exprs): other /b r, is 0x10000; owner /c rw, with other /c r, is one rule with 0x1000e.block_rules::merge_file sorts the file entries and ORs the permission words of entries that compare equal, block_rules.cc:285-338 (the OR is at line 329).ACCEPT_FLAG_OWNER, aa_lookup_condperms returns perms[index + 1] when the uids differ, file.c:203-205.p.owner != owner_t::UNSPECIFIED in valid_prefix, for example signal.h:52, so other and owner get the same message.other is rejected wherever owner is, with messages that say "owner". An other rule alone does not cover the task's own files.
owner other /tmp/** r,: syntax error, unexpected TOK_OTHER, expecting TOK_ID or TOK_MODE or TOK_SET_VAR.other signal,: owner prefix not allowed on signal rules.other capability chown,: owner conditional not allowed on capability rules.-Q -K --skip-kernel-load --warn=all). Full form: AppArmor parser error for FILE in profile FILE at line N: MESSAGE.other P r, alone is accepted. It puts r in the other half only, so a file the task's user owns gets no permission from it (derived from the code and from the rule mask 0x10000; not run against a kernel).owner under "Rule Qualifiers" and has no item for other (apparmor.d.pod:2531-2572).owner { other /foo r, } is accepted with exit status 0 and no message (run with the tree's parser), and yields a rule that grants no file permission. It is a suspected bug, not a feature to rely on. See the reference below.entry_add_prefix: parser_misc.c:1147-1159; the "conflicting owner prefix" check for rule objects: rule.h:419-424.owner { other RULE } and other { owner RULE } are accepted without a message and leave a rule with the mask 0x0: the author believes a rule is in force and nothing is granted (run with the parser built from the AppArmor tree at 836052d21, nothing loaded into a kernel, -D rule-exprs; parser_misc.c:1147-1159). The failure is closed, but it is silent.other P r, alone grants nothing on files the task's user owns. A profile that means "everyone's files" needs the plain rule, or both owner and other.deny other P rw, protects other users' files only at equal or higher priority than the allow rules it meets, and it is quiet: add audit to see attempts.owner (file.c:202-205; read from the kernel source, not observed on a running kernel). A task that can change its fsuid moves files between the two halves.owner: syn-ownerNext: syn-owner (the comparison in detail), syn-qualifier-blocks, syn-allow-deny, syn-audit. Internals: re-perms.
priority=N, audit, the access type (allow, deny or prompt), and owner or other.other is compiled by the parser at AppArmor 836052d21 into the second permission entry of each file state; the kernel selects that entry when the task's fsuid differs from the file's owner (read from source, not run).owner and has no entry for otherdeny otheraudit otherother { ... }other applies toBasis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the fragment (-Q -K --skip-kernel-load --warn=all, plus -D rule-exprs -D dfa-states-initial for dumps), with nothing loaded into a kernel; "code" means the parser or kernel source was read, not run; "derived" means reasoned from the code and the dumps. Nothing here was observed on a running kernel. Kernel statements are for mainline Linux 7.4.
RULE LINE: [priority=N] [audit] [allow|deny|prompt] other FILE RULE ,
BLOCK: [audit] [allow|deny|prompt] other { RULES }
priority=N is not allowed in front of a block: priority is not allowed on rule blocks (tree).other. It has no alias (owner has one, user).owner, the last one before the rule. A rule has owner, other or neither; both on one rule is a syntax error (tree).file, rule, link rules and blocks of them (tree). Other rule classes reject it: see "Errors and warnings".parser/tst/simple_tests/file/ok_other_1.sd (other /tmp/** rw,), ok_other_2.sd (deny other /tmp/** rw,), ok_other_3.sd (audit other /tmp/** rw,).The test is the one described in syn-owner: the task's fsuid against the owner uid of the object, with the cases for creating a file, linking and exec explained there. other applies when the two differ.
| Rules | Task owns the file | Task does not own the file | Basis |
|---|---|---|---|
owner P rw, | rw | nothing | derived |
other P r, | nothing | r | derived; rule mask 0x10000 (tree) |
P r, | r | r | derived; rule mask 0x10004 (tree) |
owner P rw, and other P r, | rw | r | derived; merged rule mask 0x1000e (tree) |
P rw, and deny other P rw, | rw | denied, quiet | derived; state (0x e/38000//0/0/38000) (tree) |
owner P rw, and other P r, and deny owner P w, | r; write denied, quiet | r | derived; state (0x 10004/a//0/0/a) (tree) |
"Nothing" means the rule contributes no permission for that case: in enforce mode the request is refused and logged unless another rule allows it. In mainline Linux 7.4 the log record of a file request carries both ids as fsuid= and ouid= (code, linux:security/apparmor/file.c:63-66).
A parse error is printed as AppArmor parser error for FILE in profile FILE at line N: MESSAGE (tree). The messages say "owner" when the rule says other.
| Message | Cause | Basis |
|---|---|---|
syntax error, unexpected TOK_OTHER, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | owner other /foo r, | tree |
owner prefix not allowed on signal rules | other signal, | tree |
owner prefix not allowed on X rules, X one of ptrace, mount, dbus, unix, network, mqueue, io_uring, userns, all | other on a rule of that class | code |
owner conditional not allowed on capability rules | other capability chown, | tree |
owner prefix not allowed on capability rules | other reaching a capability rule through a block | tree |
owner conditional not allowed on change_profile rules | other change_profile ... | tree |
There is no warning for an other rule that leaves the task's own files uncovered.
Known discrepancy with the manual: apparmor.d(5) at this commit has no 'other' in its grammar (FILE RULE and LINK RULE show [ 'owner' ] only, parser/apparmor.d.pod:397 and 416) and no item for it under "Rule Qualifiers" (parser/apparmor.d.pod:2531-2572). The parser's keyword table and the three fixtures above define its use.
owner { other RULE }, and the reverse, is accepted with exit status 0 and no diagnostic (tree) and produces a file rule that grants no file permission: the two masks are applied in turn and only the shared bits remain (code, parser/parser_misc.c:1147-1159). -D rule-exprs shows the rule with mask 0x0 (tree). Suspected bug; do not rely on it.conflicting owner prefix exists for rule objects (parser/rule.h:419-424) and cannot be reached for file rules, which are the only rules that accept the qualifier (code).| Step | Where |
|---|---|
token TOK_OTHER, keyword other | parser/parser_yacc.y:117; parser/parser_misc.c:97 |
opt_owner_flag: TOK_OTHER gives owner_t::NOT | parser/parser_yacc.y:696-698; enum at parser/rule.h:193 |
prefix dump prints !owner | parser/rule.h:297-301 |
entry_add_prefix: perms &= AA_OTHER_PERMS or AA_SHARED_PERMS | parser/parser_misc.c:1155-1156 |
halves: AA_USER_SHIFT 0, AA_OTHER_SHIFT 14; AA_OTHER_PERMS; AA_SHARED_PERMS | parser/immunix.h:24-25, 59, 66 |
block_rules::merge_file: equal entries are ORed | parser/block_rules.cc:285-338 |
| two permission entries per file state, owner then other | parser/libapparmor_re/hfa.cc:1415-1417, 1427-1428 |
valid_prefix tests p.owner != owner_t::UNSPECIFIED | parser/signal.h:52 and the other rule class headers |
| capability and change_profile checks | parser/block_rules.cc:140-141; parser/block_rules.h:68-70; parser/parser_yacc.y:812-813 |
aa_lookup_condperms: perms[index + 1] when the uids differ (Linux 7.4) | linux:security/apparmor/file.c:203-205 |
subject uid current_fsuid() (Linux 7.4) | linux:security/apparmor/file.c:227 |
Dump format (-D dfa-states-initial): (allow/deny//prompt/audit/quiet) in hex; the doubled / is a known defect of the dump. Bits per half: x 0x1, w 0x2, r 0x4, a 0x8; the other half is shifted left by 14; w implies a.
| Rules | Dump | Basis |
|---|---|---|
other /b r, | rule mask 0x10000 | tree |
owner /c rw, other /c r, | one rule, mask 0x1000e | tree |
/d rw, deny other /d rw, | state (0x e/38000//0/0/38000) | tree |
owner /a rw, other /a r, deny owner /a w, | state (0x 10004/a//0/0/a) | tree |
owner RULE, applies a file rule only to files owned by the user the task acts as.
owner is a rule qualifier. A rule that carries it grants its permissions only when the file's owner uid equals the uid the task uses for file access (its fsuid).owner @{APP_DATA}/{cache,state}/** rwk,. The users alice and bob, their uids and the two cache files are illustrations./var/lib/demo/cache/** rwk, holds its permissions for both cases, files the task owns and files it does not (parser_misc.c:738-741).owner qualifies.demo and its profile.opt_owner_flag is empty, owner or other (parser_yacc.y:696-698).[priority=N] [audit] [allow|deny|prompt] owner FILE RULE,. Valid on file rules, file,, link rules and blocks of them.
[priority=N] [audit] [allow|deny|prompt] [owner|other], then the rule (parser_yacc.y:705-711). owner and other share the last seat, so a rule has at most one of them.-Q -K --skip-kernel-load, nothing loaded into a kernel): owner /path rw,, owner rw /path,, audit deny owner /path w,, owner file,, owner link /a -> /b,, owner /usr/bin/demo-helper Px, and owner { ... }.owner link subset /alpha/beta -> /tmp/**,).owner after the path is rejected: /foo owner rw, gives "syntax error, unexpected TOK_OWNER, expecting TOK_MODE" (bad_3.sd).user to the same token as owner (parser_misc.c:95-97). The map does not recommend it.owner { ... }.owner rules apply when the task's fsuid equals the file's owner uid. Denial records show both as fsuid= and ouid=.
...; it was not captured from a running system.current_fsuid(), passed by aa_str_perms (file.c:227).owner or other contributes to both.fsuid= (the task) and ouid= (the object's owner), printed as numbers in the initial user namespace (file.c:62-66).Creating a file: the creator counts as owner. Link: the existing file's owner. Exec: the owner of the executable.
{ current_fsuid(), mode }, so the owner compared is the creating task itself (lsm.c:316-319). An owner rule with w therefore covers creation.aa_path_link takes the owner from the existing inode and uses it for both names (file.c:443-448). ouid= in a link record is the existing file's owner.owner /usr/bin/demo-helper Px, applies only when the task's fsuid owns that file. That programs under /usr/bin belong to root is the usual layout of a distribution, not a fact from the source trees.owner /usr/bin/demo-helper Px, is accepted by the parser built from AppArmor 836052d21.owner in practice.owner is accepted on file rules, file, and link rules. Other classes fail with "owner prefix not allowed on X rules" (capability and change_profile say "owner conditional not allowed on ...").
owner capability chown,, owner signal, and owner change_profile -> x,. The full form is AppArmor parser error for FILE in profile FILE at line N: MESSAGE.owner { } block (block_rules.h:68-70).other is rejected in the same places with the same messages; they say "owner" for both.owner { change_profile -> x, } is accepted by the parser at this commit although the direct form owner change_profile -> x, is rejected. Do not rely on it.owner masks the permission word to the owner half (parser/parser_misc.c:1152-1154). aa_lookup_condperms (linux:security/apparmor/file.c:194-209, the kernel) picks entry index or index + 1 by uid_eq.
AA_USER_SHIFT 0, AA_OTHER_SHIFT 14 (immunix.h:24-25); AA_USER_PERMS, AA_OTHER_PERMS (immunix.h:58-59); AA_SHARED_PERMS is change_hat and change_profile (immunix.h:66).parse_perms sets both halves (parser_misc.c:738-741). entry_add_prefix masks: owner keeps AA_USER_PERMS | AA_SHARED_PERMS, other keeps AA_OTHER_PERMS | AA_SHARED_PERMS (parser_misc.c:1147-1159).-D rule-exprs): /a r, has rule mask 0x10004, owner /a r, 0x4, other /b r, 0x10000; owner /c rw, with other /c r, merge to 0x1000e.permsv 3 is written when the kernel feature set supports it (parser_interface.c:376-380).aa_lookup_condperms(kuid_t subj_uid, struct aa_policydb *rules, aa_state_t state, struct path_cond *cond) (file.c:194-209); ACCEPT_FLAG_OWNER = 1 (policy.h:62); caller passes current_fsuid() (file.c:227).struct path_cond is filled from the inode owner through the mount id mapping (lsm.c:248-251) or, on creation, from current_fsuid() (lsm.c:316).compute_fperms builds state * 2 and state * 2 + 1 (policy_compat.c:150-171) and remap_dfa_accept flags every state (policy_compat.c:288-299).permsv is below 3.owner goes before the path. It is an equality test between the task's fsuid and the file's owner uid; root is not the owner of other users' files. (The kernel, read from the source.)
-Q -K --skip-kernel-load), as AppArmor parser error for FILE in profile FILE at line N: MESSAGE./foo owner rw,: "syntax error, unexpected TOK_OWNER, expecting TOK_MODE" (fixture bad_3.sd).owner capability chown,: "owner conditional not allowed on capability rules" (fixture bad_1.sd; block_rules.cc:140-141).owner deny /foo w,: "syntax error, unexpected TOK_DENY, expecting TOK_ID or TOK_MODE or TOK_SET_VAR". The order is fixed by parser_yacc.y:705-711.uid_eq(subj_uid, cond->uid) (file.c:202-205), an equality of two uids. No capability and no uid, 0 included, makes it true for a file owned by someone else.owner is one equality test, the task's fsuid against the file's owner uid (file.c:202-205, file.c:227; read from the kernel source, not observed on a running kernel). It does not look at groups, the mode bits, ACLs or capabilities: root with CAP_DAC_OVERRIDE is still not the owner of other users' files, and a task that changes its fsuid changes which files an owner rule covers.owner always holds at creation (lsm.c:316-319). For a hard link the owner is that of the existing file (file.c:443-448); for an exec it is the owner of the executable (domain.c:995-998): an owner exec rule therefore admits any matching program the user owns, including one the user has just written.owner reaching a change_profile rule through a block is accepted and does nothing; on any other rule class it is an error.deny and its seat.Next: syn-other (the complement), syn-qualifier-blocks (owner { }), syn-file-rules.
owner and other are the two values of one qualifier seat (parser_yacc.y:696-698); a rule with neither applies in both cases.owner /c rw, with other /c r, gives owners read and write and everyone else read on one path (rule mask 0x1000e in the dump of the parser built from AppArmor 836052d21).Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the fragment (-Q -K --skip-kernel-load --warn=all), with nothing loaded into a kernel; "code" means the parser or kernel source was read, not run. Nothing here was observed on a running kernel. Kernel statements are for mainline Linux 7.4.
[priority=N] [audit] [allow|deny|prompt] ( owner | other ) FILE RULE ,
[audit] [allow|deny|prompt] ( owner | other ) { FILE RULES }
priority=N is not allowed in front of a block: priority is not allowed on rule blocks (tree).owner is the last qualifier, directly in front of the rule (code; parser_yacc.y:705-711).owner /path rw, and owner rw /path,), on the bare owner file,, on link rules and on blocks (tree).owner and other share the seat: a rule has one of them or neither. other: syn-other.user as an alias of owner (tree; parser_misc.c:95-96). It is not documented in apparmor.d(5).In mainline Linux 7.4 an owner rule applies when the task's fsuid (current_fsuid()) equals the owner uid of the object (code).
| Operation | Whose uid is the object's owner | Source |
|---|---|---|
| access to an existing file | the inode's owner, seen through the mount's id mapping | lsm.c:248-251 |
| creating a file or directory | the creating task's fsuid, so the rule matches | lsm.c:316-319 |
| hard link | the existing file's owner, for both names | file.c:443-448 |
| a check on an open file | the owner of the file's inode | file.c:497-500 |
| exec | the owner of the executable | domain.c:995-998 |
owner or other applies in both cases.owner /c rw, with other /c r, gives owners read and write and everyone else read (tree: one merged rule, mask 0x1000e).File records carry fsuid= (the task) and ouid= (the object's owner) after requested_mask= and denied_mask= (code; file.c:62-66). The shape of a denial under an owner rule, shortened, not captured from a running system:
apparmor="DENIED" operation="open" ... name="/var/lib/demo/cache/bob.db" ... requested_mask="rw" denied_mask="rw" fsuid=1000 ouid=1001
In a link record ouid= is the existing file's owner. Reading records: adm-denials.
| Rule class | Message | Basis |
|---|---|---|
file rules, file,, link | accepted | tree |
| capability | owner conditional not allowed on capability rules | tree |
capability inside owner { } | owner prefix not allowed on capability rules | tree |
| change_profile | owner conditional not allowed on change_profile rules | tree |
| signal | owner prefix not allowed on signal rules | tree |
| ptrace, mount, dbus, unix, network, mqueue, io_uring, userns, all | owner prefix not allowed on X rules, X being the class | tree |
other is rejected by the same checks with the same messages.
A parse error is printed as AppArmor parser error for FILE in profile FILE at line N: MESSAGE (tree).
| Message | Cause |
|---|---|
syntax error, unexpected TOK_OWNER, expecting TOK_MODE | /foo owner rw,: owner goes before the path (tree) |
syntax error, unexpected TOK_DENY, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | owner deny /foo w,: write deny owner (tree) |
syntax error, unexpected TOK_OTHER, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | owner other /foo r,: one of the two per rule (tree) |
owner conditional not allowed on capability rules | owner capability chown, (tree) |
owner prefix not allowed on X rules | owner or other on another rule class, directly or through a block (code) |
An owner { block without its closing brace is a syntax error as well.
Known discrepancies between apparmor.d(5) at the commit above and the code:
user and other are not documented.QUALIFIERS (apparmor.d.pod:200) omits owner and other; 'owner' appears only in the file and link rule lines.These are not intended behaviour and should not be relied on.
owner { change_profile -> x, } is accepted, while owner change_profile -> x, is rejected (tree).owner { other /foo r, } is accepted and yields a rule with no file permissions, without a diagnostic (tree; code: parser_misc.c:1147-1159 has no conflict check). See syn-other.owner change_profile -> foo,; the tree names change_profile.| Step | Where |
|---|---|
grammar: opt_owner_flag is empty, TOK_OWNER or TOK_OTHER | parser_yacc.y:696-698 |
keywords owner, user, other | parser_misc.c:95-97 |
owner_t { UNSPECIFIED, SPECIFIED, NOT }, field prefixes.owner | rule.h:193, rule.h:245 |
AA_USER_SHIFT 0, AA_OTHER_SHIFT 14; AA_USER_PERMS, AA_OTHER_PERMS, AA_SHARED_PERMS | immunix.h:24-25, immunix.h:58-66 |
parse_perms sets both halves | parser_misc.c:738-741 |
entry_add_prefix masks the word; the only place owner is applied | parser_misc.c:1147-1159 |
valid_prefix of each rule class rejects it | for example signal.h:51-54 |
| capability and change_profile checks | block_rules.cc:140-141, block_rules.h:68-70, parser_yacc.y:812-813 |
| two permission entries per file state | hfa.cc:1415-1428 |
| second accept table flag for file states | chfa.cc:116-122, chfa.cc:157-159 |
permsv 3 | parser_interface.c:376-380 |
aa_lookup_condperms, ACCEPT_FLAG_OWNER (Linux 7.4) | file.c:194-209, policy.h:62 |
current_fsuid() as subject uid (Linux 7.4) | file.c:227 |
struct path_cond construction (Linux 7.4) | lsm.c:248-251, lsm.c:316, file.c:443-448, file.c:497-500, domain.c:995-998 |
policy without a table: compute_fperms, remap_dfa_accept (Linux 7.4) | policy_compat.c:150-171, policy_compat.c:288-299 |
Dump format (-D rule-exprs -D dfa-states-initial): bits per half x 0x1, w 0x2, r 0x4, a 0x8; the other half is shifted left by 14.
| Rules | Rule mask | Basis |
|---|---|---|
/a r, | 0x10004 | tree |
owner /a r, | 0x4 | tree |
other /b r, | 0x10000 | tree |
owner /c rw, other /c r, | merged 0x1000e | tree |
owner /a rw, other /a r, deny owner /a w, | state (0x 10004/a//0/0/a): both get read; only the owner's write denial is quiet | tree |
Not determined: how a kernel treats a permission table whose permsv is below 3.
pivot_root oldroot=OLD NEW, allows pivot_root(2) with NEW as the new root and OLD as the place for the old one.
pivot_root(new_root, put_old). The LSM hook is sb_pivotroot (lsm.c:774-786, registered at lsm.c:1794), which calls aa_pivotroot (mount.c:663-709)./sys/kernel/security/apparmor/features/mount/mask reads mount umount pivot_root.pivot_root oldroot=/run/demo/old/ /run/demo/, is line 17 of demo's profile; it compiles with no warning (run with the tree's parser). The program demo and its profile are invented for the map.parser/tst/simple_tests/; the examples are those of apparmor.d(5) (apparmor.d.pod:2051-2067).CAP_SYS_ADMIN, which a confined task has only with capability sys_admin,. Without capability sys_admin, the call fails with EPERM before AppArmor's check of the rule is reached (namespace.c:4850-4853).AA_MAY_PIVOTROOT (0x1) (mount.h:20).[QUALIFIERS] pivot_root [oldroot=OLDROOT] [NEWROOT] [-> PROFILE],.
audit, allow, deny, prompt and priority= are taken; owner and other are refused: owner pivot_root, gives owner prefix not allowed on mount rules (run with the tree's parser).oldroot is the only conditional name: pivot_root putold=/run/demo/old/ /run/demo/, gives invalid pivotroot conditional 'putold' (run with the tree's parser).TOK_PIVOTROOT opt_conds opt_id opt_target TOK_END_OF_RULE: parser_yacc.y:1297-1300; the target: parser_yacc.y:1037-1041; do_pivot_rule: parser_yacc.y:1820-1838.INITIAL, and -> pushes SUB_ID_WS (parser_lex.l:419-453, parser_lex.l:822).System call: new root, old root. Rule: oldroot=OLD first, new root last. Both end in /.
/ (mount.c:214-221, mount.c:626-637), and matches the new root, then the old root (mount.c:639-643).pivot_root new, is accepted and matches no directory. pivot_root, compiles to "any new root, any old root" (run with the tree's parser).pivot_root ... -> PROFILE, is accepted and has no effect: no warning from the parser, no transition in the kernel (features/namespaces/pivot_root reads no).
pivot_root oldroot=/run/demo/old/ /run/demo/ -> demo//worker, and the same line without the arrow give identical output (run with the tree's parser). No warning is printed.todo: allow pivotroot to specify a transition other than profile (mount.c:645-655), and installs the combined, unchanged label (mount.c:682-687). The audit field trans= is set to the profile's own name (mount.c:646).pivot_root in the namespaces directory is a boolean with the value 0 (apparmorfs.c:2657), and booleans are printed as yes or no (apparmorfs.c:1266-1268). The file was not read on a running kernel.pivot_root ... -> confined-init, suggests the task is more confined after the pivot. It is not, and nothing in the parser's output says so; the trans= field of the kernel's record carries the profile's own name.post_parse_profile has only /* TODO: pivot_root profile transition */ (mount.cc:1194-1199). The target trans is expanded and compared (mount.cc:654, mount.cc:699).operation="pivotroot" name="NEWROOT/" srcname="OLDROOT/". srcname is the value for oldroot=.
apparmor="DENIED" operation="pivotroot" profile=... name="/tmp/.../new_root/" pid=21162 comm="pivot_root" srcname="/tmp/.../new_root/put_old/") with demo's values, which are illustrative. class="mount" is placed after operation as the newer fixtures of this class have it (testcase_umount_01.in); the pivot_root fixture itself is older than the class field.name= is the new root and srcname= the old root (mount.c:626-637). The error is EACCES.trans="demo" is the profile's own name; the kernel sets it before the check (mount.c:646) and it does not mean a transition. The fixture has no trans= field.mount the parser drops it (warning mount rules not enforce, off by default) and AppArmor does not check pivot_root. When the class is mediated and no rule matches, pivot_root is refused.parser_yacc.y:1820-1838 -> mnt_rule with AA_MAY_PIVOTROOT; mount.cc:1167-1181 writes new root NUL old root; mount.c:605-661 matches and keeps the label.
do_pivot_rule: parser_yacc.y:1820-1838. The pivot_root branch of gen_policy_re: mount.cc:1167-1181. post_parse_profile has only the TODO for the transition (mount.cc:1194-1199).-> demo//worker, gives \x07/run/demo/\x00/run/demo/old/ with 0x1; pivot_root, gives \x07[^\000]*\x00[^\000]*.all, the pivot_root object merges with mount and umount into the permissions 0x7 (run with the tree's parser).build_pivotroot (mount.c:605-661); aa_pivotroot combines the per-profile labels and calls aa_replace_current_label (mount.c:663-709).pivot_root checks only its last conditional and ignores the others": only the conditional nearest to the path is examined (parser_yacc.y:1820-1831). pivot_root bogus=/b oldroot=/a/ /new/, is accepted and the bogus conditional is dropped; the same content in the other order is an error.pivot_root oldroot in (/a/) /new/, is accepted) and only its first value is used (oldroot=(/a/ /b/) means /a/). A rule that reads as two old roots allows one.oldroot= first, both paths with a trailing /, and do not rely on -> PROFILE.
AppArmor parser error for FILE in profile FILE at line N: MESSAGE; the slide shows MESSAGE. Rows 1 to 3 were run with the tree's parser; rows 4 and 5 are accepted by it.pivotroot, without an underscore.mount, the rule is dropped; --warn=rule-not-enforced prints mount rules not enforce.in operator, a value list) are listed in the scene for security researchers.pivot_root rules name two directories. A profile change needs change_profile.
[QUALIFIERS] pivot_root [oldroot=OLDROOT] [NEWROOT] [-> PROFILE],: a part left out matches anything; the arrow target has no effect.EACCES and is logged as operation="pivotroot" with name= (new root) and srcname= (old root).Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the line (-Q -K --skip-kernel-load --warn=all, -D rule-exprs for compiled forms), with nothing loaded into a kernel; "code" means the parser source or the kernel source was read, not run. Nothing here was observed on a running kernel.
PIVOT ROOT RULE: [QUALIFIERS] pivot_root [oldroot=OLDROOT] [NEWROOT] [-> PROFILE] , QUALIFIERS: [priority=N] [audit] [allow|deny|prompt]
oldroot is the only conditional and comes before the path (tree).| Seat | On a pivot_root rule |
|---|---|
priority= | taken |
audit | taken |
allow, deny, prompt | taken: deny is not logged; prompt is in syn-prompt |
owner, other | refused: owner prefix not allowed on mount rules (tree) |
| pivot_root(2) argument | In the rule | In the log |
|---|---|---|
new_root, first | the path at the end | name= |
put_old, second | the value of oldroot=, before the path | srcname= |
Both are directories; the kernel's names end in / (code).
| Rule | Allows |
|---|---|
pivot_root, | any new root, any old root |
pivot_root /run/demo/, | this new root, the old root anywhere |
pivot_root oldroot=/run/demo/old/, | any new root with this place for the old root |
pivot_root oldroot=/run/demo/old/ /run/demo/, | this new root with this place for the old root |
pivot_root oldroot=/run/demo/old/ /run/demo/ -> demo//worker, | the same as the line above |
All five are accepted; the last two compile to the same rule (tree).
-> PROFILE is accepted, with no warning, stored, and not written into the compiled policy (tree, code).linux:security/apparmor/mount.c:645-655, code)./sys/kernel/security/apparmor/features/namespaces/pivot_root reads no (derived from linux:security/apparmor/apparmorfs.c:2657; not read on a running kernel).| Field | Meaning |
|---|---|
operation="pivotroot" | one word, no underscore |
class="mount" | on current kernels; the fixture below is older |
profile= | the profile that refused |
name= | the new root, with its trailing / |
srcname= | the old root, with its trailing / |
trans= | the profile's own name; no transition happens |
A record from the tree (libraries/libapparmor/testsuite/test_multi/testcase_pivotroot_01.in):
apparmor="DENIED" operation="pivotroot" profile="/home/ubuntu/bzr/apparmor/tests/regression/apparmor/pivot_root" name="/tmp/sdtest.21082-7446-EeefO6/new_root/" pid=21162 comm="pivot_root" srcname="/tmp/sdtest.21082-7446-EeefO6/new_root/put_old/"
A refused pivot returns EACCES.
| Rule | Message |
|---|---|
pivot_root /run/demo/ oldroot=/run/demo/old/, | syntax error, unexpected TOK_CONDID, expecting TOK_END_OF_RULE |
pivot_root putold=/run/demo/old/ /run/demo/, | invalid pivotroot conditional 'putold' |
owner pivot_root, | owner prefix not allowed on mount rules |
pivot_root oldroot=/run/demo/old /run/demo, | none; the rule matches no directory |
pivot_root /run/demo/ -> demo//worker, | none; the profile does not change |
any pivot_root rule, no mount in the feature set, --warn=rule-not-enforced | warning mount rules not enforce |
Rows with a rule are from the tree's parser.
do_pivot_rule builds mnt_rule(NULL, oldroot, NULL, newroot, AA_MAY_PIVOTROOT) and stores the target in trans (parser/parser_yacc.y:1820-1838).trans is expanded and compared (parser/mount.cc:654, 699) and never encoded: post_parse_profile has only a TODO (parser/mount.cc:1194-1199).AA_MAY_PIVOTROOT 0x1 (parser/mount.cc:1167-1181). Demo's line is \x07/run/demo/\x00/run/demo/old/ (tree).sb_pivotroot (linux:security/apparmor/lsm.c:774-786) calls aa_pivotroot (linux:security/apparmor/mount.c:663-709); build_pivotroot matches the two names, tests the bit and returns the profile's own label (linux:security/apparmor/mount.c:605-661).None of these is taught as intended behaviour. All are on the bug list as confirmed; see Known bugs.
pivot_root bogus=/b oldroot=/a/ /new/, is accepted and bogus is dropped (tree).pivot_root oldroot in (/a/) /new/, is accepted, and oldroot=(/a/ /b/) means /a/ (tree).The preamble is everything before the first profile of a file. It holds no rules.
PREAMBLE = ( COMMENT | VARIABLE ASSIGNMENT | ALIAS RULE | INCLUDE | ABI )* (apparmor.d.pod:107).abi <abi/5.0>, and then include <tunables/global>, for example lsblk:12-13. Under profiles/apparmor.d, 210 lines are abi <abi/5.0>, in column 0.-Q -K --skip-kernel-load --warn=all) it gives exit status 0 and no warning.demo and its profile are invented for the map.( comment | include | variable assignment | alias rule | abi rule )*, then the profiles. Order is free.
abi and alias lines end with a comma. An include ends with its file name and an assignment with the end of the line.if is not a preamble line: above the first profile it gives syntax error, unexpected TOK_IF, expecting end of file (run with the tree's parser for this deck).list: preamble { ... } profilelist (parser_yacc.y:345-371).preamble: | preamble alias | preamble varassign | preamble abi_rule (parser_yacc.y:506-509).The preamble sets the policy ABI, the variables and the aliases. -D variables prints the variables.
-D variables on the example file prints 85 lines, among them the four on the slide: @HOMEDIRS = "/home/", @HOME = "/root/" "@{HOMEDIRS}/*/", @APP_DATA = "/srv/demo" "/var/lib/demo" and $DEMO_DEBUG = false.$NAME = value (variable.cc:412-420)./var/lib/demo /srv/demo.aare: line of -D rule-exprs for line 10 of the example: {/srv/demo,/var/lib/demo}/{cache,state}/** (run with the tree's parser for this deck).new_alias() is called from the alias production (parser_yacc.y:511-517).global_symtab.add_var() from varassign (parser_yacc.y:524-570).abi_features() from abi_rule (parser_yacc.y:1052-1063).Nothing of the preamble is accepted after the first profile: syntax error, unexpected TOK_SET_VAR, expecting end of file.
AppArmor parser error for /work/p03a.sd in profile /work/p03a.sd at line 2: syntax error, unexpected TOK_SET_VAR, expecting end of file, exit status 1. /work/p03a.sd is the scratch name of the file.@{A}=/a between two profiles, with the same message.... at line 2: syntax error, unexpected TOK_ABI, expecting end of file, exit status 1 (run with the tree's parser for this deck).list: preamble profilelist: after preamble is reduced only profilelist can follow (parser_yacc.y:345-371).Variables, aliases and the policy ABI are reset for each file. Share them with an include in each preamble.
@{SHARED} = /shared and a profile using it, the second with only a profile using it, compiled by one command. Output: Failed to find declaration for: @{SHARED} and ERROR expanding variables for profile second, failed to load, exit status 1.tunables/demo with the one line @{SHARED} = /shared, found through -I, and two files that each begin with include <tunables/demo> and no longer assign the variable. Both compile /shared/**, exit status 0. It is what the shipped tunables files do for every profile that includes tunables/global.@{SHARED} = /shared in first next to the include is refused: variable @{SHARED} was previously declared (see variable assignment).reset_parser() empties the alias table, the symbol table, the policy list, the policy ABI and the include cache (parser_main.c:1254-1269). It is called for each file (parser_main.c:1314).parser_yacc.y:506-509 is the preamble; the action at 345-369 fixes the policy ABI; parser_main.c:1254-1269 resets per file.
new_alias() (parser_yacc.y:511-517), global_symtab.add_var() (parser_yacc.y:524-570), abi_features() (parser_yacc.y:1052-1063).preamble: the --override-policy-abi set if given, else the set from an abi rule, else the pinned set, else the built-in default with the warning File '%s' missing feature abi, falling back to default policy feature abi (parser_yacc.y:346-369). The warning's class is abi, which is not in DEFAULT_WARNINGS (parser.h:77-78).rules: rules abi_rule (parser_yacc.y:722; abi/ok_20.sd).reset_parser(): parser_main.c:1254-1269..d directories. See include if exists.Assignments and alias rules only above the first profile; rules and if blocks only inside one.
AppArmor parser error for /work/p06a.sd in profile /work/p06a.sd at line 2: syntax error, unexpected TOK_EQUALS, expecting TOK_MODE.unexpected TOK_ALIAS, expecting TOK_ID or TOK_MODE or TOK_SET_VAR. The parser's test rewrite/bad_alias_inside_profile.sd expects a failure for it.AppArmor parser error for /work/p-rule.sd in profile /work/p-rule.sd at line 2: syntax error, unexpected TOK_MODE, expecting TOK_OPEN.... at line 2: syntax error, unexpected TOK_IF, expecting end of file.AppArmor parser error for /work/p06e.sd in profile /src/apparmor/profiles/apparmor.d/tunables/home at line 15: syntax error, unexpected TOK_EQUALS, expecting TOK_MODE. "in profile" names the file being parsed; the slide shortens its directory to ..../work/ are scratch names of the runs.Preamble lines: abi, include, variables, alias. Then the profile head.
Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run on the fragment (-Q -K --skip-kernel-load, with the tree's abi/5.0 file as kernel feature set), with nothing loaded into a kernel; "code" means the parser source was read and not run; "derived" means the result was reasoned from that code. Nothing here was observed on a running kernel.
FILE: PREAMBLE PROFILE* PREAMBLE: ( COMMENT | INCLUDE | VARIABLE ASSIGNMENT | ALIAS RULE | ABI RULE )*
PREAMBLE = ( COMMENT | VARIABLE ASSIGNMENT | ALIAS RULE | INCLUDE | ABI )* (apparmor.d.pod:107).| Line | Form | Ends with | Deck |
|---|---|---|---|
| comment | # text | the line | syn-comments |
| include | include <magic/path>, include "path", include if exists ... | the file name | syn-include |
| set variable assignment | @{NAME} OP values | the line | syn-variable-assignment |
| boolean assignment | ${NAME} OP expression | the line | syn-boolean-variables |
| alias rule | alias FROM -> TO, | a comma | syn-alias |
| abi rule | abi <magic/path>, | a comma | syn-abi |
| Construct | Preamble | Profile body | After the first profile |
|---|---|---|---|
| comment | yes | yes | yes |
| include | yes | yes | yes, if the included text is profiles (derived) |
| set variable assignment | yes | unexpected TOK_EQUALS, expecting TOK_MODE (tree) | unexpected TOK_SET_VAR, expecting end of file (tree) |
| boolean assignment | yes | refused (the test boolean_bad_5.sd expects a failure) | refused (derived) |
| alias rule | yes | unexpected TOK_ALIAS, expecting TOK_ID or TOK_MODE or TOK_SET_VAR (tree) | refused (derived) |
| abi rule | yes | accepted by the grammar (code) | unexpected TOK_ABI, expecting end of file (tree) |
| rule | unexpected TOK_MODE, expecting TOK_OPEN for /etc/demo/** r, (tree) | yes | the same |
if block | unexpected TOK_IF, expecting end of file (tree) | yes | the same (derived) |
| profile | ends the preamble | child profile | yes |
Every message is prefixed AppArmor parser error for FILE in profile FILE at line N: syntax error, ; "in profile" names the file being parsed. Exit status 1.
Failed to find declaration for: @{SHARED}, ERROR expanding variables for profile second, failed to load, exit status 1 (tree, recorded in the research notes).include <tunables/global> does.When the first profile begins, the policy ABI of the file is settled, in this order: the --override-policy-abi option, the file's first abi rule, the --policy-features option, the parser's built-in default (code). See syn-abi.
| Message | Line that causes it | Basis |
|---|---|---|
syntax error, unexpected TOK_SET_VAR, expecting end of file | @{APP_DATA} = /var/lib/demo after a profile | tree |
syntax error, unexpected TOK_ABI, expecting end of file | abi <abi/5.0>, after a profile | tree |
syntax error, unexpected TOK_EQUALS, expecting TOK_MODE | @{APP_DATA} = /srv/demo inside a profile | tree |
syntax error, unexpected TOK_ALIAS, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | alias /usr/ -> /opt/demo/usr/, inside a profile | tree |
syntax error, unexpected TOK_MODE, expecting TOK_OPEN | /etc/demo/** r, above the profile | tree |
syntax error, unexpected TOK_IF, expecting end of file | if ${DEMO_DEBUG} { ... } above the profile | tree |
in profile .../tunables/home at line 15: syntax error, unexpected TOK_EQUALS, expecting TOK_MODE | include <tunables/global> inside a profile | tree |
Failed to find declaration for: @{SHARED} | a variable defined only in another file | tree, recorded |
list: preamble { ... } profilelist (parser_yacc.y:345-371); the action settles the policy ABI (parser_yacc.y:346-369).preamble: | preamble alias | preamble varassign | preamble abi_rule (parser_yacc.y:506-509).new_alias() (parser_yacc.y:511-517), global_symtab.add_var() (parser_yacc.y:524-570), abi_features() (parser_yacc.y:1052-1063).reset_parser() (parser_main.c:1254-1269).priority=N in front of a rule makes it outrank rules with a lower number. A higher-priority allow overrides a deny.
priority=N in front of a rule, as in priority=10 allow /etc/demo/override.conf r,. A rule without it has priority 0.deny /etc/demo/** r, and priority=10 allow /etc/demo/override.conf r, was run through the parser built from the AppArmor tree at 836052d21 (-Q -K --skip-kernel-load --warn=all -D rule-exprs -D dfa-states-initial, nothing loaded into a kernel). The state reached by /etc/demo/override.conf is (0x 10004/0//0/0/0): read allowed, nothing denied, nothing quieted. Every other name under /etc/demo/ reaches (0x 0/10004//0/0/10004): read denied and quiet.(allow/deny//prompt/audit/quiet); 0x10004 is r for the owner half and the other half together.override.conf and only for r, the permission it names. The deny keeps deciding every other file in the directory./etc/demo/** r, on line 25; the deny on this slide stands for one that arrives through an included abstraction.demo, its files and its profile are invented for the map. Nothing on this slide was observed on a running kernel.pri_update_perm: its score for the read bit, 0*4 + 3 = 3, is lower than the allow's 10*4 + 1 = 41, so the deny node is skipped for that bit (hfa.cc:1536-1560).priority=N RULE, with N from -1000 to 1000; the default is 0. priority is the first qualifier.
priority=N RULE, where N is an optional + or - followed by digits.priority=N, audit, allow | deny | prompt, owner | other. Each seat is optional.= is allowed. priority = -5 /a r, and priority=+5 /b r, were accepted by the parser built from the AppArmor tree at 836052d21.priority must be followed by =; white space in between is allowed. Without the = it is still the keyword: priority /a r, gives syntax error, unexpected TOK_ID, expecting TOK_EQUALS (run with the tree's parser).priority=1 against 0 behaves like priority=1000 against 0.opt_priority: empty gives 0; otherwise TOK_PRIORITY TOK_EQUALS TOK_VALUE, converted with strtol and checked against the bounds (parser_yacc.y:677-691).opt_prefix: opt_priority opt_audit_flag opt_rule_mode opt_owner_flag fixes the order (parser_yacc.y:705-711).priority/{WS}*=, with trailing context, and it pushes the state INTEGER_MODE (parser_lex.l:428-432). That state accepts = and an INTEGER, defined as [+-]?{NUMBER} (parser_lex.l:292, parser_lex.l:697-704).MIN_POLICY_PRIORITY is -1000 and MAX_POLICY_PRIORITY is 1000 (immunix.h:198-199).A deny with a negative priority loses to every default-priority allow and still applies where no allow matches.
priority=, because those have priority 0./a* rw, with priority=-1 deny /** w,. Names matching /a* reach the state (0x 3800e/0//0/0/0): read and write allowed. Other names reach (0x 0/2800a//0/0/2800a): write and append denied, and quiet./var/lib/demo/** rw, in place of /a* rw,). That pair gives the same two states with the same parser.w in a file rule carries the append permission with it, which is why the deny mask is 0x2800a and not only the write bit.priority=-1 the two rules have equal priority and the deny wins the write permission everywhere it matches, including under /var/lib/demo/. This is the equal-priority case of allow and deny (with the parser built from the tree, /a rw, deny /a w, gives (0x 10004/2800a//0/0/2800a)).deny marks its permissions quiet in the compiled policy. In the kernel a refused request whose denied permissions are all quiet returns the error without a log record (file.c:95-154, read and not run). priority=-1 audit deny /** w, would log the refusals.priority=-1 deny /usr/bin/foo r, (ok_deny_2.sd). Another test states that audit deny /[^a]* rwxlk, /a r, and priority=-1 audit deny /* rwxlk, /a r, compile to the same binary policy (equality.sh:1926-1928): the lowered deny replaces a hand-written carve-out pattern./etc/passwd stands for any file no allow rule matches.audit deny brings the record back.priority=1 /f r, with /f w, allows rw: a higher-priority rule overrides lower rules only for the permissions it names.
priority=1 /a r, with /a w, gives the state (0x 3800e/0//0/0/0) for /a: read, write and append allowed. The slide shows the same pair on /var/lib/demo/state, which gives the same state.priority=1 /x r, with deny /x rw, gives (0x 10004/2800a//0/0/2800a) for /x: read allowed; write and append denied and quiet.(allow/deny//prompt/audit/quiet). Per half x 0x1, w 0x2, r 0x4, a 0x8; the other half is shifted left by 14, so r is 0x10004, w with its implied append is 0x2800a and rw is 0x3800e.priority=1 /a r, audit /a rw, allows read and write and audits only write and append. See audit.perms | audit are visited when a state's permissions are built (hfa.cc:1680-1694), so a node cannot affect a bit it does not carry.Per permission: the highest priority wins; at equal priority deny > allow > prompt. The winning rule also sets audit and quiet for that permission.
priority;audit removes the audit of a lower rule./a: priority=-1 /a r, deny /a r, priority=5 audit /a r, gives the state (0x 10004/0//0/10004/0) with the parser built from the tree: read allowed and audited, no deny, no quiet.x. That is how an exact path settles two different exec modes; see exec modes.-1*4 + 1 = -3, then 0*4 + 3 = 3, then 5*4 + 1 = 21.perms_t::clear_bits clears allow, deny, prompt, audit and quiet for the bit (hfa.h:74-81).Per bit, priority*4 + kind (parser/libapparmor_re/hfa.cc:1536-1554); lower scores are skipped, higher ones replace (:1556-1582). Priorities are not in the compiled policy.
prefixes.priority for rule objects (rule.h:240-243) and cod_entry.priority for file rules (parser.h:140-141).add_rule and add_rule_vec call (file rules: parser_regex.c:675-688) and becomes part of the accept node: UniquePerm is { priority, mode, exact_match, perms, audit } (aare_rules.h:77-81).MatchFlag, ExactMatchFlag, DenyMatchFlag, PromptMatchFlag (expr-tree.h:1150-1201). An allow rule whose pattern has no wildcards gets an ExactMatchFlag (aare_rules.cc:98-110); it scores as an allow except on exec bits.perms_t::perms_t gives each of the 32 bits a score register starting at MIN_INTERNAL_PRIORITY*4, which is -4004, and calls pri_update_perm for every bit in a node's perms | audit (hfa.cc:1661-1694).pri_update_perm (hfa.cc:1529-1653):priority << 2, plus 3 for a deny node, 2 for an exact-match node on an exec bit, 1 for any other node that is not a prompt node, 0 for a prompt node (lines 1536-1554);clear_bits for the bit, which clears allow, deny, prompt, audit and quiet (1575-1582);priority=1 /x r, and deny /x rw,. The resulting state (0x 10004/2800a//0/0/2800a) is from a run of the parser built from the AppArmor tree at 836052d21; the per-bit steps are read from the code. The slide shows four of the 32 bits and one of the two halves.MIN_INTERNAL_PRIORITY is -1001 and MAX_INTERNAL_PRIORITY is 1001 (immunix.h:201-207). The rules that mark a class as mediated are added with mediates_priority = MAX_INTERNAL_PRIORITY, so that no rule from a profile, in particular no deny, can remove them (parser_regex.c:1359-1372).-D dfa-perms-build prints the comparisons while states are built (the DUMP_DFA_PERMS output in the same function).Range -1000 to 1000 ("invalid priority N > 1000"). Not allowed on blocks, network rules and all rules. Known limitation: accepted and ignored on capability rules.
AppArmor parser error for FILE in profile FILE at line N: MESSAGE. The slide shows MESSAGE.priority=1001 /etc/demo/** r,: invalid priority 1001 > 1000.priority=1 { /etc/demo/** r, }: priority is not allowed on rule blocks.priority=1 network inet,: priority prefix not allowed on network rules.audit priority=1 /etc/demo/** r,: syntax error, unexpected TOK_PRIORITY, expecting TOK_ID or TOK_MODE or TOK_SET_VAR.all rule: the message in the parser source is priority prefix not allowed on all rules (run as above with priority=1 all,).priority=1 capability chown, and deny capability chown, is accepted without a message (run as above). The pair compiles to the same binary as deny capability chown, alone (run): capabilities are kept as an allow set and a deny set and do not go through the per-permission comparison, and the check that would reject the prefix is commented out, with the note "priority is not supported on capability rules but this is currently not enforced". A denied capability stays denied.priority=-1001 /a r, prints invalid priority -1001 > -1000 (run as above).priority=abc prints only flex scanner jammed and exits with status 2, with no file name or line (run as above).priority levels not supported, while the same rule is accepted outside the block and file rules are accepted in both places. See qualifier blocks.priority=1 on an allow rule in any included file overrides every deny of lower priority for the same permission and name, so a review of what a profile denies has to read the priorities of every rule that can match, includes and abstractions too.priority= is accepted and ignored, with no message: priority=1 capability chown, with deny capability chown, compiles to the same binary as the deny alone (run with the parser built from the AppArmor tree at 836052d21, nothing loaded into a kernel; block_rules.cc:133-138). Here the failure is closed; a reader of the profile may think otherwise."invalid priority %ld > %d".all rule: all_rule.h:46-50.prefix_rule_t::add_prefix when their own priority is not 0 (rule.h:385-395); file rules go through generic_add_prefix, which has no such test (parser_misc.c:1121-1122).INTEGER_MODE has rules only for = and an integer (parser_lex.l:697-704) and is not in the state list of the rule that reports an unexpected character (parser_lex.l:926-931).Next: syn-allow-deny, syn-prompt, syn-audit, syn-exec-modes, syn-qualifier-blocks, re-perms.
priority=N, N from -1000 to 1000, default 0, first qualifier.network rules and all rules; accepted and ignored on capability rules (a known limitation).Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run on the fragment (-Q -K --skip-kernel-load --warn=all, with -D rule-exprs -D dfa-states-initial for state dumps), with nothing loaded into a kernel; "code" means the parser source, or the kernel source of mainline Linux 7.4, was read and not run; "derived" means the result was reasoned from that code. Nothing here was observed on a running kernel.
RULE: [priority=N] [audit] [allow|deny|prompt] [owner|other] RULE , priority: 'priority' '=' N N: [+-]? digits -1000 <= N <= 1000, default 0
priority=N is the first qualifier (code).= is allowed: priority = -5 /a r, and priority=+5 /b r, are accepted (tree).priority must be followed by =, after optional white space. Without it the rule is a syntax error (tree).MIN_POLICY_PRIORITY (-1000) and MAX_POLICY_PRIORITY (1000) (code).parser/tst/simple_tests/file/priority/ holds 81 files at this commit, for example priority=-1 deny /usr/bin/foo r, (ok_deny_2.sd), and bad_1.sd and bad_2.sd for the two bounds.For one permission on one name, among the rules of one profile that match the name and carry the permission:
| Step | Rule |
|---|---|
| 1 | The highest priority decides. |
| 2 | At equal priority: deny, then allow, then prompt. |
| 2a | For the exec permission only, a rule whose path has no wildcards ranks between deny and allow. See syn-exec-modes. |
| 3 | Rules of equal priority and equal kind accumulate. |
| 4 | The deciding rule sets allow, deny or prompt and also audit and quiet for that permission. What lower rules set for it is cleared. |
priority=1 /a r, /a w,).State reached by the path /a unless a column says otherwise, format (allow/deny//prompt/audit/quiet). Per half x 0x1, w 0x2, r 0x4, a 0x8; the other half is shifted left by 14, so r for both halves is 0x10004, w with its implied append is 0x2800a and rw is 0x3800e.
| Rules | State | Meaning | Basis |
|---|---|---|---|
/a rw, deny /a w, | (0x 10004/2800a//0/0/2800a) | read allowed; write denied and quiet | tree |
priority=1 /a rw, deny /a w, | (0x 3800e/0//0/0/0) | read and write allowed; nothing quiet | tree |
priority=1 /a rw, priority=1 deny /a w, | (0x 10004/2800a//0/0/2800a) | both raised: as the first row | tree |
/a* rw, priority=-1 deny /** w, | /a*: (0x 3800e/0//0/0/0); other names: (0x 0/2800a//0/0/2800a) | the lowered deny applies only where no allow matches | tree |
priority=-1 /a r, deny /a r, priority=5 audit /a r, | (0x 10004/0//0/10004/0) | allowed and audited; the deny and its quiet are gone | tree |
priority=1 /a r, /a w, | (0x 3800e/0//0/0/0) | read from the first rule, write from the second | tree |
priority=1 /a r, audit /a rw, | (0x 3800e/0//0/2800a/0) | read and write allowed; only write and append audited | tree |
prompt /a rw, /a r, | (0x 10004/0//2800a/0/0) | allow beats prompt for read | tree |
priority=1 prompt /a rw, /a r, | (0x 0/0//3800e/0/0) | the raised prompt takes read as well | tree |
prompt /a rw, deny /a w, | (0x 0/2800a//10004/0/2800a) | deny beats prompt for write | tree |
priority=10 allow /etc/demo/override.conf r, deny /etc/demo/** r, | override.conf: (0x 10004/0//0/0/0); other names under /etc/demo/: (0x 0/10004//0/0/10004) | one file lifted out of a denied directory | tree |
priority=1 /x r, deny /x rw, | /x: (0x 10004/2800a//0/0/2800a) | read allowed; write and append denied and quiet | tree |
| Rule class | Behaviour | Basis |
|---|---|---|
| file, link | accepted | tree |
| change_profile, signal, ptrace, mount, dbus, userns, io_uring, mqueue | accepted | tree, one rule of each |
| unix | accepted; "partially supported": rules downgraded to plain socket mediation lose the priority | tree for acceptance; code for the rest |
capability | accepted and ignored (known limitation) | tree: accepted, and priority=1 capability chown, with deny capability chown, compiles to the same binary as the deny alone |
network | refused: priority prefix not allowed on network rules | tree |
all | refused: priority prefix not allowed on all rules | tree |
a block priority=N { ... } | refused: priority is not allowed on rule blocks | tree |
| a file rule with a priority inside a block | accepted: owner { priority=1 /a r, } | tree |
| any other rule with a priority inside a block | refused: priority levels not supported (see Known discrepancies) | tree |
priority=1 allow (derived).The full form of a parser error is AppArmor parser error for FILE in profile FILE at line N: MESSAGE (tree). The table gives MESSAGE.
| Message | Example | When |
|---|---|---|
| invalid priority 1001 > 1000 | priority=1001 /etc/demo/** r, | N above 1000; the format is invalid priority %ld > %d (tree) |
| invalid priority -1001 > -1000 | priority=-1001 /a r, | N below -1000; the sign in the message is wrong (tree; see Known discrepancies) |
| invalid priority %s | none found | present in the parser source; cannot be reached, because the scanner passes only integers (code; see Known discrepancies) |
| priority is not allowed on rule blocks | priority=1 { /etc/demo/** r, } | a priority on a block (tree) |
| priority prefix not allowed on network rules | priority=1 network inet, | a priority on a network rule (tree) |
| priority prefix not allowed on all rules | priority=1 all, | a priority on an all rule (tree) |
| priority levels not supported | audit { priority=1 signal, } | a rule other than a file rule that has a priority, inside any block (tree) |
| syntax error, unexpected TOK_PRIORITY, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | audit priority=1 /etc/demo/** r, | priority=N after another qualifier (tree) |
| syntax error, unexpected TOK_ID, expecting TOK_EQUALS | priority /a r, | the word priority without = (tree) |
| flex scanner jammed | priority=abc /foo r, | anything but = and an integer after priority; exit status 2, no file or line (tree; see Known discrepancies) |
These are differences between the documentation, the messages and the behaviour, listed as such. They are not taught as intended behaviour. They are on the AppArmor bug sweep list under the same titles; see also sec-bugs.
invalid priority -1001 > -1000 (tree). The lower-bound check reuses the upper-bound format string (code).priority=abc /foo r, prints only flex scanner jammed, with exit status 2 and no file name or line number (tree). The scanner state entered after priority has rules only for = and an integer and is missing from the rule that reports unexpected characters (code). As a consequence the grammar's own invalid priority %s cannot be reached.{ }, a rule other than a file rule that carries a priority fails with priority levels not supported: audit { priority=1 signal, } and { priority=1 signal, } are refused, while priority=1 signal, outside a block, owner { priority=1 /a r, } and audit { priority=5 /etc/demo/override.conf r, } are accepted (tree). The refusal may be deliberate for now; the difference between file rules and the other classes is the discrepancy. See syn-qualifier-blocks.priority=1 capability chown, is accepted (tree) and the priority has no effect (code): with deny capability chown, in the same profile the capability is denied. The source says "priority is not supported on capability rules but this is currently not enforced", so this is known to the authors.priority=1 /a r, /a w, allows rw (tree).| What | Where |
|---|---|
opt_priority: value, range check, messages | parser_yacc.y:677-691 |
opt_prefix: the order of the four qualifiers | parser_yacc.y:705-711 |
scanner: priority/{WS}*=, INTEGER, INTEGER_MODE | parser_lex.l:428-432, parser_lex.l:292, parser_lex.l:697-704 |
scanner: the catch-all rules without INTEGER_MODE, and the comment naming "flex scanner jammed" | parser_lex.l:919-931, parser_lex.l:328-329 |
MIN_POLICY_PRIORITY, MAX_POLICY_PRIORITY, MIN_INTERNAL_PRIORITY, MAX_INTERNAL_PRIORITY | immunix.h:198-207 |
prefixes.priority | rule.h:240-243 |
cod_entry.priority | parser.h:140-141 |
prefix_rule_t::add_prefix: "priority levels not supported" | rule.h:385-395 |
generic_add_prefix (file rules in a block) | parser_misc.c:1121-1122 |
blocks, network rules, all rules: valid_prefix | block.h:46-51, network.h:269-273, all_rule.h:46-50 |
| capability rules: the check that is commented out | block_rules.cc:133-138, block_rules.h:61-66 |
| unix rules: "partially supported" | af_unix.h:52-55 |
file rules: priority passed to add_rule | parser_regex.c:675-688 |
UniquePermsCache::insert: the priority in the accept node | aare_rules.h:77-81 |
exact_match | aare_rules.cc:98-110 |
MatchFlag, ExactMatchFlag, DenyMatchFlag, PromptMatchFlag | expr-tree.h:1150-1201 |
pri_update_perm | hfa.cc:1529-1653 |
| score | hfa.cc:1536-1554 |
| lower score skipped | hfa.cc:1556-1560 |
| higher score clears the bit | hfa.cc:1575-1582 |
| deny, exact-match, allow, prompt branches | hfa.cc:1585-1650 |
perms_t::perms_t: registers start at -4004, loop over the bits | hfa.cc:1661-1694 |
perms_t::clear_bits | hfa.h:74-81 |
mediates_priority | parser_regex.c:1359-1372 |
| manual page text | apparmor.d.pod:2540-2548 |
| tests: fixtures | parser/tst/simple_tests/file/priority/, for example ok_deny_2.sd |
| tests: owner block keeps an inner priority on file rules | equality.sh:667-669 |
| tests: carve-out pattern equals a lowered deny | equality.sh:1926-1928 |
| kernel: quiet applied to a refused file request (mainline Linux 7.4) | file.c:95-154 |
Scores for the worked examples (priority*4 + kind): row 1, write bit: allow 1, deny 3. Row 2: allow 5, deny 3. Row 3: allow 5, deny 7. Row 4: allow 1, deny -1. Row 5, read bit: -3, 3, 21. Row 6: read 5, write and append 1. -D dfa-perms-build prints the comparisons while states are built.
The name in the profile head is the profile's identifier. The kernel's code prints it with the mode, as in demo (enforce); a denial carries it as profile="demo"; rules such as Px -> demo use it as their target.
profile, as in profile demo /usr/bin/demo {.demo (enforce), read from /proc/PID/attr/current or with aa_getcon(). The kernel prints the name followed by the mode (label.c:1563-1570);profile="demo" field of an audit record (audit.c:128-129);/sys/kernel/security/apparmor/profiles and the output of aa-status;/usr/bin/demo Px -> demo,, change_profile -> demo,, signal peer=demo,.apparmor_parser -N FILE (--names) prints the names a file defines without loading anything.demo and its program are invented for the map. The kernel statements are read from the kernel source, not observed on a running kernel.profile NAME [ATTACHMENT] [xattrs=( )] [+ identities=( )] [flags=( )] {. The order is fixed and only one attachment is accepted. Out of order, the tree's parser answers syntax error, unexpected TOK_ID, expecting TOK_OPEN.
[ profile | hat | ^ ] NAME [ ATTACHMENT ] [ xattrs=( ... ) ] { + identities=( ... ) } [ flags=( ... ) ] {. Only NAME is required; at most one ATTACHMENT.syntax error, unexpected TOK_ID, expecting TOK_OPEN (-Q -K --skip-kernel-load, nothing loaded into a kernel).AppArmor parser error for FILE in profile FILE at line N: MESSAGE.profile exist /does/not/exist { (profile_basic_named_ok1.sd), /does/not/exist flags=(complain) { (flags_ok.sd).profile_base: TOK_ID opt_id_or_var opt_cond_list identities flags TOK_OPEN (parser_yacc.y:391-399); the keyword slot is opt_profile_flag (parser_yacc.y:381-383) and the two meet in profile (parser_yacc.y:460).profile demo /usr/bin/demo { is named demo. /usr/bin/demo { is named /usr/bin/demo and attaches to the same path. --warn=deprecated prints "The use of file paths as profile names is deprecated. See man apparmor.d for more information" for any top-level name that starts with /.
profile demo /usr/bin/demo {: name demo, attachment /usr/bin/demo. /usr/bin/demo {: name /usr/bin/demo, and the same string is the attachment./, the parser copies the name into the attachment (parser_variable.c:67-77)./ or carry a namespace (:ns:name { }).The use of file paths as profile names is deprecated. See man apparmor.d for more information. It is raised for any top-level name that starts with /, with or without the keyword.deprecated (parser_main.c:284), which is not among the default warnings (parser.h:77-78). Turn it on with apparmor_parser --warn=deprecated or --warn=all./does/not/exist flags=(complain) { (flags_ok.sd:7) and profile exist /does/not/exist { (profile_basic_named_ok1.sd:8).profile action (parser_yacc.y:469-473).A name is one unquoted word (no blank, tab, ", ! or ,) or one double-quoted string. :ns:name selects a namespace. Without an attachment the name is compiled as a pattern, so {, [, * and ? act as in a path.
", ! and ,; a , is allowed when a word character follows it. Escapes: backslash blank, backslash tab, \", \!, \,.", with \" for a quote. The quotes are stripped and are not part of the name (parser_misc.c:509-535). profile "demo service" /usr/bin/demo { } is listed by apparmor_parser -N as demo service.:ns:name puts the profile in namespace ns.& is rejected: Profile names must begin with a '/' or a namespace.profile demo{v2 { } fails with Regex grouping error: Unclosed grouping or character class, expecting close } and Invalid profile name 'NAME' - bad regular expression; profile demo{v2 /usr/bin/demo { } is accepted. Seen with the parser built from the AppArmor tree at 836052d21.Failed to find declaration for: @{x} (seen with the installed parser 5.0.2).ID_CHARS, ID, IDS (parser_lex.l:262-267) and QUOTED_ID (parser_lex.l:287-288); the name token after the keyword is ({IDS}|{QUOTED_ID}) in state SUB_ID (parser_lex.l:456-461).parse_label() separates the namespace and reports a leading & (parser_misc.c:843-958).A nested profile is loaded as parent//name: demo//worker, demo//admin. apparmor_parser -N prints the full names in alphabetical order. A namespace is printed in front as :ns://name. The kernel side is read from the kernel code, not run.
//. apparmor_parser -N on the parser built from the AppArmor tree at 836052d21 lists:profile worker { } inside demo as demo//worker;^admin { } inside demo as demo//admin;profile /usr/lib/demo/helper { } inside demo as demo///usr/lib/demo/helper;profile :ops:demo /usr/bin/demo { } as :ops://demo.hname() (parent's name, //, own name) and fqname() (:ns:// in front) (profile.h:454-476), and writes it as the first string of each profile in the binary policy (parser_interface.c:487-493).// (policy.c:523-539).demo//worker (enforce) from /proc/PID/attr/current; the name and mode are printed at label.c:1563-1570.profile → state SUB_ID → TOK_ID → profile_base → parse_label() → Profile::hname() → first string of the profile struct → unpack_profile() in the kernel.
PROFILE is profile{WS}* (parser_lex.l:294); it returns TOK_PROFILE and pushes the state SUB_ID (parser_lex.l:850).SUB_ID the next ({IDS}|{QUOTED_ID}) is returned as TOK_ID after processid(), and the state is popped (parser_lex.l:456-461). Nothing looks at what the word is, which is why profile flags=(complain) { yields a name.profile_base takes the TOK_ID and calls parse_label(&self_stack, &prof->ns, &prof->name, $1, true); the profile production adds the keyword checks (parser_yacc.y:391-478).bool parse_label(bool *_stack, char **_ns, char **_name, const char *label, bool yyerr) and its helper split :ns:name and :ns://name (parser_misc.c:843-958).process_variables_in_name() (parser_variable.c:58-78).Profile::hname(), fqname() and get_name() build the full name (profile.h:454-476).sd_write_struct(buf, "profile"), then the name as an unnamed string; a nested profile gets get_name(false) (parser_interface.c:487-493).unpack_profile() reads the string, calls aa_splitn_fqname() and allocates the profile (policy_unpack.c:1138-1165); __lookup_parent() walks the // separators (policy.c:523-539).demo { fails with "Profile names must begin with a '/', namespace or keyword 'profile' or 'hat'." A second path is a syntax error. profile flags=(complain) { is accepted by the parser as it is today and defines a profile named flags=(complain), a known discrepancy: check names with apparmor_parser -N.
Messages are verbatim; "tree" means seen with the parser built from the AppArmor tree at 836052d21 (-Q -K --skip-kernel-load).
demo { }: Profile names must begin with a '/', namespace or keyword 'profile' or 'hat'. It is reported at the line of the closing brace (tree).profile demo /usr/bin/demo /usr/bin/demo2 {: syntax error, unexpected TOK_ID, expecting TOK_OPEN (tree).profile demo usr {: Profile attachment must begin with a '/' or variable. (tree).profile flags=(complain) { } is accepted and defines a profile named flags=(complain) in enforce mode, with no message (tree). So is profile profile { }. Whether this is intended is not settled; it is a known discrepancy.apparmor_parser -N FILE lists the names that were read.profile and the name gives Lexer found unexpected character: '\n' (0xa) in state: SUB_ID (tree), and a { } gives syntax error, unexpected TOK_MODE, because a single letter is read as a file permission (seen with the installed parser 5.0.2).&).Next in the head: attachment, syn-xattrs, syn-identities, syn-flags-modes. Nested names: syn-child-profiles, syn-hats. Names with a colon: namespaces.
profile NAME [ATTACHMENT] [xattrs=( )] [+ identities=( )] [flags=( )] {.parent//child for nested profiles, :ns:name in a namespace. apparmor_parser -N shows them.Rows marked "tree" were run with the parser built from the AppArmor tree at the commit above (-Q -K --skip-kernel-load, the tree's abi/5.0 features). Rows marked "5.0.2" were run with the installed parser 5.0.2. Kernel behaviour was read from the kernel's code and not run on a kernel.
[ profile | hat | ^ ] NAME [ ATTACHMENT ] [ xattrs=( ... ) ] { + identities=( ... ) } [ flags=( ... ) ] { rules }
NAME is the only required part. At most one ATTACHMENT is accepted.profile may be left out only when NAME starts with / or carries a namespace: :ns:a { } is accepted without the keyword (5.0.2).profile the next word or quoted string is always the name.hat NAME and ^NAME at top level use the same head; see syn-hats.| Spelling | Where | Meaning |
|---|---|---|
profile | start of a head, top level or nested | the next word is the name; the name may be any word |
hat, ^ | start of a head | a hat; same head, see syn-hats |
:ns: | prefix of the name | the profile belongs to namespace ns; see namespaces |
// | inside a loaded name | separates parent and child; written by the parser for nested profiles |
& | first character of the name | rejected in a profile head |
| Form | Allowed |
|---|---|
| unquoted word | any byte except blank, tab, carriage return, new line, ", ! and ,; a , is allowed when a word character follows it |
| escapes in an unquoted word | backslash blank, backslash tab, \", \!, \, |
| quoted string | any byte except NUL and "; \" for a quote. The quotes are not part of the name |
| first character without the keyword | /, @ (a variable), : or &; of these & is then rejected |
{, [, * and ? are compiled as a pattern when the name is used as the attachment, which is the case when no attachment is written. profile demo{v2 { } fails; profile demo{v2 /usr/bin/demo { } is accepted (tree).Failed to find declaration for: @{x} (5.0.2).Output of apparmor_parser -N (tree). The listing is in alphabetical order, not source order.
| Head | Name listed |
|---|---|
profile demo /usr/bin/demo { } | demo |
/usr/bin/demo { } | /usr/bin/demo (also the attachment) |
profile /usr/bin/demo { } | /usr/bin/demo (also the attachment) |
profile "demo service" /usr/bin/demo { } | demo service |
profile :ops:demo /usr/bin/demo { } | :ops://demo |
profile worker { } inside demo | demo//worker |
^admin { } inside demo | demo//admin |
profile /usr/lib/demo/helper { } inside demo | demo///usr/lib/demo/helper |
demo (enforce), splits a leading :ns: off the loaded name and finds the parent of a nested profile at the //.Errors are printed as AppArmor parser error for FILE in profile FILE at line N: MESSAGE (tree).
| Message | When | Basis |
|---|---|---|
Profile names must begin with a '/', namespace or keyword 'profile' or 'hat'. | no keyword, the name is not a path and has no namespace; reported at the line of the closing brace | tree |
Profile names must begin with a '/' or a namespace | the name starts with & | code |
Profile attachment must begin with a '/' or variable. | the attachment is another kind of word, as in profile demo usr { | tree |
syntax error, unexpected TOK_ID, expecting TOK_OPEN | a second attachment, head parts out of order, or profile demo usr/bin/demo { | tree |
Invalid profile name 'NAME' - bad regular expression | a pattern error in a name used as the attachment; preceded by Regex grouping error: Unclosed grouping or character class, expecting close } | tree |
Namespace not terminated: NAME | :ns without the closing colon | code |
Empty namespace: NAME | nothing between the two colons | code |
Empty named transition profile name: NAME | nothing after the namespace; also printed for profile "" { } | code; tree for the empty name |
Failed to find declaration for: @{x} | an undeclared variable in the name | 5.0.2 |
Lexer found unexpected character: '\n' (0xa) in state: SUB_ID | a new line between profile and the name | tree |
syntax error, unexpected TOK_MODE | no keyword and a single-letter name such as a { }, read as a file permission | 5.0.2 |
| Warning | When | Class |
|---|---|---|
The use of file paths as profile names is deprecated. See man apparmor.d for more information | a top-level name starts with /, with or without the keyword | deprecated (--warn=deprecated), off by default |
FILE: -n NS overriding policy specified namespace :NS: | --namespace-string replaces the namespace written in the file | code |
profile flags=(complain) { } and profile profile { } are accepted and name the profile flags=(complain) and profile. After the keyword the next word is taken as the name without looking at it. The first loads in enforce mode. Whether this is intended is not settled. Check names with apparmor_parser -N.| What | Where |
|---|---|
profile{WS}* pattern, push to state SUB_ID | parser/parser_lex.l:294, parser/parser_lex.l:850 |
name token in SUB_ID | parser/parser_lex.l:456-461 |
names without the keyword (LABEL, QUOTED_LABEL) | parser/parser_lex.l:301-302, parser/parser_lex.l:838-841 |
opt_profile_flag, profile_base, profile | parser/parser_yacc.y:381-383, parser/parser_yacc.y:391-478 |
local_profile, hat | parser/parser_yacc.y:480-504 |
processid() (quotes and escapes), parse_label() | parser/parser_misc.c:509-535, parser/parser_misc.c:843-958 |
| name copied into the attachment, variables in the name | parser/parser_variable.c:58-78 |
| name compiled as a pattern | parser/parser_regex.c:478-624 |
Profile::hname(), fqname(), get_name() | parser/profile.h:454-476 |
name written as the first string of the profile struct | parser/parser_interface.c:487-493 |
| kernel: namespace split and allocation | linux:security/apparmor/policy_unpack.c:1138-1165 |
kernel: parent lookup at // | linux:security/apparmor/policy.c:523-539 |
kernel: name (mode) | linux:security/apparmor/label.c:1564 |
prompt RULE, marks permissions to be decided by a user-space agent. The kernel unpacks them and does not act on them.
prompt is a qualifier in the access type seat of a rule, where allow and deny go. The example rule prompt @{HOME}/Documents/** r, is line 29 of the map's example profile for demo.prompt field (perms.h:78); it is read from the loaded policy and no access decision reads it (lib.c:425-464). This was read from the kernel source, not observed on a running kernel.TOK_PROMPT in opt_rule_mode, parser_yacc.y:700-703; keyword table parser_misc.c:102.[priority=N] [audit] prompt [owner|other] RULE,. One access type per rule: allow, deny or prompt.
[priority=N] [audit] prompt [owner|other] RULE, and prompt { RULES }. The order of the qualifiers is fixed.allow, deny or prompt. Two of them on one rule is a syntax error (run with the tree's parser at 836052d21).profile t { prompt /foo r, audit prompt signal, prompt capability chown, } is accepted (run with the tree's parser; nothing was loaded into a kernel). See the reference below before using prompt on capability rules.parser/tst/simple_tests/ uses a prompt rule. The block on the slide is from the equality tests, which check that /t { prompt { /foo r, audit /bar w, owner /baz rw, } } and /t { prompt /foo r, audit prompt /bar w, prompt owner /baz rw, } compile to the same binary policy: equality.sh:1443-1447.ACCESS TYPE = ( 'allow' | 'deny' ) (apparmor.d.pod:198) and uses prompt only in block examples (apparmor.d.pod:2691, apparmor.d.pod:2700).opt_rule_mode and the seat order: parser_yacc.y:700-711; keyword prompt: parser_misc.c:102.audit in front of an access type: syn-auditAt equal priority a permission goes to deny, else allow, else prompt. A prompt rule with higher priority overrides both.
-D dfa-states-initial, format (allow/deny//prompt/audit/quiet); r is 0x10004, w with append 0x2800a, rw 0x3800e):| Rules | State | Basis |
|---|---|---|
prompt /d r, | (0x 0/0//10004/0/0) | tree's parser at 836052d21 |
prompt /a rw, /a r, | (0x 10004/0//2800a/0/0): read allowed, write and append prompt | tree's parser at 836052d21 |
prompt /a rw, deny /a w, | (0x 0/2800a//10004/0/2800a): write denied and quiet, read prompt | tree's parser at 836052d21 |
priority=1 prompt /a rw, /a r, | (0x 0/0//3800e/0/0): read and write prompt | tree's parser at 836052d21 |
@{HOME}/Documents/**, private/) are the same rule shapes with the example profile's names; the lamps for them are derived from the scoring and the dumps above, not from a dump of those exact rules.deny also marks the permissions quiet, so the refusal is not logged: syn-allow-deny.priority*4 plus 3 for deny, 2 for an exact exec match, 1 for allow, 0 for prompt: hfa.cc:1536-1554; prompt bits collected at hfa.cc:1649-1650.priority=N: syn-priorityThe kernel unpacks and validates the prompt field and no decision path reads it. By the kernel source, the access is refused and logged as a normal denial.
All kernel statements here are for the kernel (commit 97d73c825) and come from reading security/apparmor/. Nothing was run on a kernel.
struct aa_perms has a prompt member: perms.h:78.prompt word of each permission entry is read at policy_unpack.c:916.prompt overlaps allow or deny, or if complain overlaps prompt: policy_unpack.c:1524-1527.aa_check_perms computes denied = request & (~perms->allow | perms->deny) and does not read prompt: lib.c:425-464. The file path does the same in aa_audit_file: file.c:95-154.EACCES and an apparmor="DENIED" record, as for any permission that is not allowed. The record on the slide is shortened; the fields kept are in the kernel's order.ALLOWED.prompt among the permission table fields (apparmorfs.c:2631); that describes the table layout, not prompting.PromptMatchFlag scores priority*4 + 0 (parser/libapparmor_re/hfa.cc:1552-1554); the bits are packed as the prompt field (policy_compat.cc). --prompt-compat=flag sets PACKED_MODE_USER.
rule_mode_t::PROMPT selects PromptMatchFlag (aare_rules.h:85-89); the class is expr-tree.h:1199-1205.pri_update_perm: priority << 2, plus 3 for DenyMatchFlag, 2 for an exact match on exec bits, 1 for allow, 0 for prompt: hfa.cc:1536-1554. Bits go to perms.prompt, audit bits to perms.audit: hfa.cc:1649-1650.map_perms_to_accept(accept1, accept2, accept3): allow, PACK_AUDIT_CTL(audit, quiet), prompt: hfa.h:132-138.prompt (policy_compat.cc:166-237: lines 166, 182, 207, 237); the two file builders also mask it with ~(perms.allow | perms.deny) (lines 172, 188). Written by sd_serialize_perm: parser_interface.c:355.kernel_supports_permstable32_version < 2) the third accept word is computed into a local and dropped, so the rule carries nothing: chfa.cc:129-136.prefix_rule_t::uses_prompt (rule.h:374-377) and block_rules::uses_prompt_rules (block_rules.cc:23-36).--prompt-compat=permsv2|default|ignore|flag: parser_main.c:892-905. --print-prompt-compat prints Prompt compat mode: and the mode set by a --prompt-compat option earlier on the command line; with none it prints Unknown prompt compat mode '0' (run with the tree's parser), because the default is chosen after the options are read (parser_main.c:1787-1790): parser_main.c:907-910, parser_common.c:214-229. Default selection, best supported of permsv2, flag, ignore: parser_common.c:189-212.flag mode a profile that uses prompt rules gets profile_mode::PROMPT (parser_policy.c:161-162), packed as mode 4, PACKED_MODE_USER (policy_unpack.h:40, policy_unpack.c:1233-1234).ignore does not strip prompt permissions: --prompt-compat=ignore, --prompt-compat=permsv2 and no option give the same binary for prompt /a r,, and flag differs from them in the mode word (run with the tree's parser). --prompt-compat=default selects ignore with the abi/5.0 feature set, because it is evaluated before the features are known. Whether that is intended was not determined. The option is not in apparmor_parser(8).perms->prompt |= ~(perms->allow | perms->deny) at lib.c:371-372. No decision path reads the field. Read from source, not run.prompt profile mode: syn-flags-modesprompt conflicts with allow and deny on the same rule or block ("conflicting mode prefix"). The parser does not warn when the kernel will not act on prompt rules.
prompt { deny /foo r, } is rejected with conflicting mode prefix (run with the tree's parser at 836052d21). The same message is given for an explicit allow inside a prompt block.prompt deny /x r, is rejected with syntax error, unexpected TOK_DENY, expecting TOK_ID or TOK_MODE or TOK_SET_VAR (run with the tree's parser).AppArmor parser error for FILE in profile FILE at line N: MESSAGE.priority=N on the prompt rule changes that: syn-priority.prompt capability chown, compiles to the same binary as capability chown,, so prompt capability X, is stored as an allowed capability. Do not use prompt on capability rules.prefix_rule_t::add_prefix: rule.h:409-416.prompt capability X, and prompt { capability X, } fail open: they compile to the same binary as capability X,, so the capability is granted on any kernel, with no message (run with the parser built from the AppArmor tree at 836052d21, nothing loaded into a kernel; block_rules.cc:143-152).prompt rules is compiled for a kernel that does not prompt. On the kernel a prompt permission is a permission that is not allowed: refused in enforce mode, permitted and logged as ALLOWED in complain mode (file.c:246-247; read from the kernel source, not observed on a running kernel).--prompt-compat=flag marks a profile that uses prompt rules with the user (prompt) profile mode instead; ignore and permsv2 give the same binary as no option (same run).Next: syn-priority, syn-allow-deny, re-perms, k-unpack. Kernels that act on prompt rules: upstream-and-ubuntu.
prompt is the third access type. The parser at AppArmor 836052d21 compiles and packs it; the kernel unpacks it and does not act on it (read from source, not run).audit promptprompt { ... }prompt profile modeBasis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the fragment (-Q -K --skip-kernel-load --warn=all), with nothing loaded into a kernel; "code" means the parser or kernel source was read, not run. Nothing here was observed on a running kernel. Kernel statements are for mainline Linux 7.4. What kernels with additional patches do with prompt rules: upstream-and-ubuntu.
RULE LINE: [priority=N] [audit] prompt [owner|other] RULE ,
BLOCK: [audit] prompt [owner|other] { RULES }
priority=N is not allowed in front of a block: priority is not allowed on rule blocks (tree).prompt takes the access type seat; a rule has at most one of allow, deny, prompt (tree).profile t { prompt /foo r, audit prompt signal, prompt capability chown, } is accepted (tree). For capability rules see "Known discrepancies and gaps".parser/tst/simple_tests/ uses a prompt rule. parser/tst/equality.sh:1445-1447 checks that /t { prompt { /foo r, audit /bar w, owner /baz rw, } } equals /t { prompt /foo r, audit prompt /bar w, prompt owner /baz rw, }.Per permission of one name, at equal priority: deny, then allow, then prompt. Scoring and priority=N: syn-priority.
| Rules | Result | Basis |
|---|---|---|
prompt /d r, | read is prompt | tree |
prompt /a rw, and /a r, | read allowed; write and append prompt | tree |
priority=1 prompt /a rw, and /a r, | read, write and append prompt; nothing allowed | tree |
prompt /a rw, and deny /a w, | write and append denied and quiet; read prompt | tree |
prompt field next to allow, deny, audit and quiet. A permission is in at most one of allow and prompt, because each bit goes to one kind of rule; the file table builders also mask the field with allow and deny (code).prompt overlaps allow or deny, or complain overlaps prompt (code; linux:security/apparmor/policy_unpack.c:1524-1527).Read from linux 97d73c825 (7.4-rc2), security/apparmor/; not run.
| Step | What happens | Where |
|---|---|---|
| unpack | the prompt word of each entry is read | linux:security/apparmor/policy_unpack.c:916 |
| validate | overlap with allow, deny or complain rejects the profile | linux:security/apparmor/policy_unpack.c:1524-1527 |
| accumulate | merged into combined permission sets, minus allow and deny | linux:security/apparmor/include/perms.h:118, 145 |
| user mode | a profile in user mode gets prompt for everything not allowed or denied | linux:security/apparmor/lib.c:371-372 |
| decide | aa_check_perms and aa_audit_file read allow, deny, audit, quiet and hide; not prompt | linux:security/apparmor/lib.c:425-464, file.c:95-154 |
Result: a prompt permission is a permission that is not in allow. In enforce mode the request is refused with EACCES and logged as DENIED. In complain mode it is permitted and logged as ALLOWED (derived from the same code). No question is put to user space.
| Option | Effect |
|---|---|
--prompt-compat=permsv2 | select the permsv2 mode |
--prompt-compat=flag | a profile that uses prompt rules is given the prompt profile mode, packed as kernel mode 4 (user) |
--prompt-compat=ignore | select the ignore mode; this does not remove prompt permissions from the output and produces the same binary as permsv2 (tree) |
--prompt-compat=default | meant as the best supported of permsv2 (needs permission table version 2 or later), flag (needs a permission table), ignore. Evaluated while options are read, before the kernel features are known: with the abi/5.0 feature set it selects ignore (tree). With no option the parser picks the best supported mode later |
--print-prompt-compat | prints Prompt compat mode: and the mode set so far on stderr, then exits; without an earlier --prompt-compat it prints Unknown prompt compat mode '0' (tree) |
The print rows and the ignore, permsv2 and flag comparison were run with the tree's parser; the rest is from the code (parser/parser_main.c:892-911, 1769-1790, parser/parser_common.c:189-229). Neither option is in apparmor_parser(8). The prompt profile mode itself: syn-flags-modes.
A parse error is printed as AppArmor parser error for FILE in profile FILE at line N: MESSAGE (tree).
| Message | Cause |
|---|---|
conflicting mode prefix | a rule's explicit access type against its block's, as in prompt { deny /foo r, } (tree) |
syntax error, unexpected TOK_DENY, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | prompt deny /x r,: one access type per rule (tree) |
%s: Invalid --prompt-compat option '%s' | an unknown value for --prompt-compat; the parser exits with status 1 (code) |
There is no warning for compiling prompt rules for a kernel that will not act on them (code).
prompt capability X, is stored as an allowed capability; only deny is distinguished for capabilities (code, parser/block_rules.cc:143-152; tree: prompt capability chown, compiles to the same binary as capability chown,). Do not use prompt on capability rules.prompt from ACCESS TYPE (parser/apparmor.d.pod:198) and uses it only in block examples (2691, 2700); --prompt-compat is not documented.prompt has any representation in the legacy network table.--prompt-compat=ignore is meant to strip prompt permissions; no code does.| Step | Where |
|---|---|
grammar: TOK_PROMPT in opt_rule_mode | parser/parser_yacc.y:703; keyword parser/parser_misc.c:102 |
prefix_rule_t::uses_prompt | parser/rule.h:374-377 |
| conflict check, "conflicting mode prefix" | parser/rule.h:409-416 |
block_rules::uses_prompt_rules | parser/block_rules.cc:23-36, 617-618 |
PromptMatchFlag | parser/libapparmor_re/expr-tree.h:1199-1205; chosen in aare_rules.h:87-88 |
pri_update_perm: score priority*4 + 0 for prompt; perms.prompt, perms.audit | parser/libapparmor_re/hfa.cc:1536-1554, 1649-1650 |
map_perms_to_accept: third accept word | parser/libapparmor_re/hfa.h:132-138 |
the table builders fill perms.prompt | parser/libapparmor_re/policy_compat.cc:166, 182, 207, 237 |
the two file builders mask it: perms.prompt &= ~(perms.allow or perms.deny) | parser/libapparmor_re/policy_compat.cc:172, 188 |
| third word dropped without a permission table | parser/libapparmor_re/chfa.cc:129-136, 160-163 |
sd_serialize_perm | parser/parser_interface.c:355 |
prompt_compat_mode, options | parser/parser_main.c:203-204, 892-910, 1787-1790; parser/parser_common.c:189-229 |
profile_mode::PROMPT in flag mode | parser/parser_policy.c:161-162 |
PACKED_MODE_USER (Linux 7.4) | linux:security/apparmor/include/policy_unpack.h:40, policy_unpack.c:1233-1234 |
unpack_perm, validation (Linux 7.4) | linux:security/apparmor/policy_unpack.c:916, 1524-1527 |
aa_compute_profile_perms user-mode line (Linux 7.4) | linux:security/apparmor/lib.c:371-372 |
Dump format (-D dfa-states-initial): (allow/deny//prompt/audit/quiet) in hex; the doubled / is a known defect of the dump. Bits per half: x 0x1, w 0x2, r 0x4, a 0x8; the other half is shifted left by 14.
| Rules | State | Basis |
|---|---|---|
prompt /d r, | (0x 0/0//10004/0/0) | tree |
prompt /a rw, /a r, | (0x 10004/0//2800a/0/0) | tree |
priority=1 prompt /a rw, /a r, | (0x 0/0//3800e/0/0) | tree |
prompt /a rw, deny /a w, | (0x 0/2800a//10004/0/2800a) | tree |
ptrace (read) peer=demo//worker, lets a profile pass the kernel's ptrace read check for tasks with that label. Attaching as a debugger needs trace.
ptrace_access_check and ptrace_traceme (lsm.c:128-164, registered at lsm.c:1786-1787).read is requested when the kernel's check carries PTRACE_MODE_READ; trace for every other mode and for PTRACE_TRACEME (lsm.c:139-141, lsm.c:158-159)./proc/<pid>/) is decided by the rest of the kernel, not by AppArmor, and was not read for this deck. The wiki page below is the place to look./sys/kernel/security/apparmor/features/ptrace/mask contains read trace (apparmorfs.c:2586-2589).gdb under a profile debugger is invented for the map, like demo and its worker.ptrace_scope, a separate restriction.[QUALIFIERS] ptrace [trace|read|tracedby|readby | ( ... )] [peer=LABEL],. No permission means all four; no peer means any.
peer may be written once, and only = is accepted (ptrace.cc:40-51).audit, deny, allow, prompt and priority= are taken (audit deny ptrace readby peer=/sbin/init, in ok_22.sd). owner is refused: owner prefix not allowed on ptrace rules (ptrace.h:50-56).abstractions/base: base:134-142.0x2, read 0x4, tracedby 0x8, readby 0x10 (ptrace.h:27-31).PTRACE_MODE (parser_lex.l:663-695, parser_lex.l:887-888).read and trace: this profile acts on the peer. readby and tracedby: the peer acts on this profile.
PTRACE_TRACEME), the parent is the tracer and the request is trace (lsm.c:147-164).read, trace, readby, tracedby (task.c:217-230).readby and tracedby are the tracer's read and trace as seen from the tracee (task.h:92-96); see "Both profiles are asked".Tracing needs trace (or read) in the tracer's profile and tracedby (or readby) in the tracee's. abstractions/base grants readby and tracedby for any peer.
aa_may_ptrace checks every profile of the tracer's label with the request, and every profile of the tracee's label with the request shifted to the ...by form (task.c:316-329; the shift: task.h:92-96). A refusal is -EACCES (lib.c:440).abstractions/base: ptrace (readby),, ptrace (tracedby), and ptrace (read) peer=@{profile_name}, (base:134-142). The comments there name the override: deny ptrace (readby) ... and deny ptrace (tracedby) ....requested_mask="tracedby" denied_mask="tracedby").The tracee-side check is skipped for an unconfined tracer (task.c:275). Without ptrace mediation the test is "same label or sys_ptrace" (task.c:293-303). A traced task's profile transition is checked against its tracer (domain.c:50-80).
profile_tracee_perm returns 0 if the tracee's profile is unconfined, if the tracer's label is unconfined, or if the tracee's profile does not mediate the ptrace class (task.c:270-280).profile_tracer_perm: nothing for an unconfined profile; the rule check when the profile mediates ptrace; otherwise the same label is allowed, and any other label goes to aa_capable(..., CAP_SYS_PTRACE, ...) with an audit of the result (task.c:282-304).change_profile of a traced task, with info="ptrace prevents transition": domain.c:50-80.ptrace rules not enforced (ptrace.cc:115, ptrace.cc:130-133), is off by default.abstractions/base grants readby and tracedby to any peer. In profiles that include it, the tracer's profile is the only gate between two confined tasks unless the tracee adds a deny.ptrace_scope and the kernel's credential checks are separate and still apply.operation="ptrace" requested_mask=... denied_mask=... peer="LABEL". trace/read: the tracer's profile refused. tracedby/readby: the tracee's.
requested_mask and denied_mask with one of read, trace, readby, tracedby, and peer= (task.c:217-250). The mask printer returns one name, and requests are single permissions (task.c:217-230).apparmor="DENIED" operation="ptrace" profile=... pid=22465 comm="ptrace" requested_mask="tracedby" denied_mask="tracedby" peer=...), with demo's names.pid and comm are those of the calling task, which for an attach is the tracer: by the code, the hook runs in the tracer's context (lsm.c:128-145). Hence comm="gdb" next to profile="demo".ALLOWED. A plain deny ptrace ... rule refuses without a record.sys_ptrace: see capability rules.ptrace.cc:118-162 emits (\x10|)\x09peer; task.c:316-329 asks the tracer with the request and the tracee with request << 2; the match is lib.c:393-405.
(\x10|)\x09demo//worker with 0x4 was printed by the parser built from the tree with -D rule-exprs for demo's line 19. Without a peer the pattern is [^\000]+ (ptrace.cc:118-162).\d9 is added at priority 1001 (parser_regex.c:1412-1414).ptrace (ptrace.cc:130-133).r and w reuse the bits 0x4 and 0x2 shared by all IPC classes (parser_misc.c:763-772).xcheck_labels in aa_may_ptrace (task.c:316-329); profile_ptrace_perm (task.c:253-268); aa_profile_match_label (lib.c:393-405); the shift (task.h:92-96).Lists in parentheses; trace, not attach; peer=LABEL without parentheses. A rule on one side only is valid and not sufficient.
-Q -K --skip-kernel-load --warn=all, nothing loaded into a kernel). The full form is AppArmor parser error for FILE in profile FILE at line N: MESSAGE.only "=" allowed in conditions of ptrace rules (ptrace.cc:43).invalid ptrace rule conditional "%s" (ptrace.cc:48), for example for set.ptrace conditional "peer" can only be specified once.perms contains invalid permissions for ptrace (ptrace.cc:59).capability ptrace trace, is a test file that must fail: bad_05.sd.ptrace rules not enforced is printed when the feature set has no ptrace; it needs --warn=rule-not-enforced.Ptrace rules work with file rules for /proc and with the peer's profile.
trace or read in the tracer's profile and tracedby or readby in the tracee's profile; either refusal is EACCES.abstractions/base grants readby and tracedby for any peer.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the line (-Q -K --skip-kernel-load --warn=all, feature set abi/5.0), with nothing loaded into a kernel; "code" means the source was read, not run. Every statement about the kernel is read from the kernel source.
PTRACE RULE: [QUALIFIERS] ptrace [PERMISSIONS] [peer=LABEL] ,
PERMISSIONS: PERMISSION | ( PERMISSION [,] ... )
PERMISSION: trace | read | tracedby | readby
r is read; w and write are trace; rw and wr are both
peer means any peer (tree).peer is a plain label pattern, written once and without parentheses (tree).| Word | Direction | Checked in | Kernel request that leads to it |
|---|---|---|---|
read | this profile looks at the peer | the tracer's profile | a ptrace access check with PTRACE_MODE_READ |
trace | this profile controls the peer | the tracer's profile | every other mode, and PTRACE_TRACEME (the parent is the tracer) |
readby | the peer looks at this profile | the tracee's profile | the tracer's read, shifted |
tracedby | the peer controls this profile | the tracee's profile | the tracer's trace, shifted |
| Tracer | Tracee | Checks |
|---|---|---|
| confined | confined | read or trace in every profile of the tracer, and readby or tracedby in every profile of the tracee |
| confined | unconfined | the tracer's profile only |
a profile that does not mediate ptrace (compiled for a feature set without ptrace) | any | the same label is allowed; another label needs the capability sys_ptrace |
A refusal is EACCES. The case of an unconfined tracer is in the section for security researchers below.
| Seat | On a ptrace rule |
|---|---|
priority= | taken |
audit | taken |
allow, deny, prompt | taken |
owner, other | refused: owner prefix not allowed on ptrace rules |
ptrace (readby),
ptrace (tracedby),
ptrace (read) peer=@{profile_name},
Source: base:134-142. The comments there give the override: deny ptrace (readby) ... and deny ptrace (tracedby) ....
apparmor="DENIED" operation="ptrace" profile=... pid=... comm=... requested_mask="tracedby" denied_mask="tracedby" peer=...
| Mask | The profile that refused | The rule to add there |
|---|---|---|
trace | the tracer's | ptrace (trace) peer=TRACEE, |
read | the tracer's | ptrace (read) peer=TRACEE, |
tracedby | the tracee's | ptrace (tracedby) peer=TRACER, |
readby | the tracee's | ptrace (readby) peer=TRACER, |
profile= names the profile that refused and peer= the label of the other task.
| Line | Message |
|---|---|
ptrace readby tracedby peer=demo//worker, | syntax error, unexpected TOK_TRACEDBY, expecting TOK_CONDID or TOK_END_OF_RULE |
ptrace attach peer=demo//worker, | syntax error, unexpected TOK_ID, expecting TOK_CONDID or TOK_END_OF_RULE |
ptrace read peer=(label=demo//worker), | syntax error, unexpected TOK_CONDLISTID, expecting TOK_CONDID or TOK_END_OF_RULE |
capability ptrace trace, | syntax error, unexpected TOK_PTRACE, expecting TOK_ID or TOK_END_OF_RULE |
owner ptrace, | owner prefix not allowed on ptrace rules |
ptrace read set=hup, | invalid ptrace rule conditional "set" |
ptrace peer=a peer=b, | ptrace conditional "peer" can only be specified once |
an operator other than = | only "=" allowed in conditions of ptrace rules |
feature set without ptrace (warning, off by default) | ptrace rules not enforced |
(\x10|)\x09 and the peer pattern, [^\000]+ when there is no peer (ptrace.cc:118-162). \x10 is the label class (16), \x09 the ptrace class (9).0x2, read 0x4, tracedby 0x8, readby 0x10 (ptrace.h:27-31). The kernel shifts the tracer's request left by two for the tracee (task.h:92-96).\d9 at priority 1001 (parser_regex.c:1412-1414).aa_may_ptrace (task.c:316-329), profile_tracer_perm and profile_tracee_perm (task.c:270-304), aa_profile_match_label (lib.c:393-405).abstractions/base grants readby and tracedby to any peer.sys_ptrace" (task.c:282-304).info="ptrace prevents transition" (domain.c:50-80).ptrace_scope and the kernel's credential checks are separate./proc/<pid>/). That is decided outside security/apparmor and was not read.QUALIFIERS { RULES } applies the qualifiers to every rule inside the braces. No comma follows the closing brace.
QUALIFIERS { RULES } inside a profile body. The qualifiers in front of the opening brace are applied to every rule inside when the block is parsed (parser_yacc.y:738-759, block.cc:273-284).deny { ... } block is accepted by the parser built from AppArmor 836052d21 (run with -Q -K --skip-kernel-load --warn=all; nothing was loaded into a kernel).prompt { /foo r, audit /bar w, owner /baz rw, } against the three separate rules (equality.sh:1445-1447).deny { /sys/** w, }, is rejected by the same parser: "syntax error, unexpected TOK_END_OF_RULE, expecting TOK_ID or TOK_MODE or TOK_SET_VAR".AppArmor parser error for FILE in profile FILE at line N: MESSAGE. The slides of this deck show MESSAGE only.deny { /proc/sys/** w, /sys/** w, }. The rule /boot/** w, is added on the slide to make the repetition visible.demo and its profile.deny does to a rule.[audit] [allow|deny|prompt] [owner|other] { RULES }. No priority. Blocks may be empty, bare and nested.
[audit] [allow|deny|prompt] [owner|other] '{' RULES '}'. The qualifiers keep the order they have in front of a rule; priority=N is refused on a block with "priority is not allowed on rule blocks" (block.h:46-51).BLOCK = '{' ( RULES )* '}' (apparmor.d.pod:196).if blocks, and by the grammar also hats and child profiles (parser_yacc.y:738-759).-Q -K --skip-kernel-load --warn=all): deny { audit /a r, }, audit { deny /b r, }, allow { /c r, }, { /d r, }, owner { } and audit deny { /proc/sys/** w, /sys/** w, }.deny, audit and bare blocks), ok_1.sd (owner { ... } and an empty owner { }), entry_mods_audit_ok1.sd (audit { ... }).allow { R } around a rule with no access type is the same as R. The difference between a plain rule and an allow rule shows only in a deny block: the plain rule becomes a deny, the allow rule is an error (see the conflicts scene of this deck).if blocks.A block's qualifiers are applied to each contained rule when the block is parsed. Compiled policy contains no blocks.
audit { } block with a file rule, a capability rule and a signal rule is accepted by the parser built from AppArmor 836052d21 (-Q -K --skip-kernel-load --warn=all).owner { capability chown, } gives "owner prefix not allowed on capability rules" (block_rules.h:69, fixture bad_7.sd); deny { set rlimit cpu <= 10, } gives "prefix not allowed on rlimit rules".audit { ^hat { /a r, } } compiles to the same binary as ^hat { audit /a r, }, and likewise for a child profile): a hat or child profile defined inside a qualifier block receives the block's qualifiers on its own rules (block.cc:259-268).rules: rules opt_prefix block calls subblock->add_prefix($2, error) and then current->add_subblock(subblock, error). block::add_prefix (block.cc:273-284) visits the block, nested blocks, every conditional branch and hats through for_each_recursive (block.cc:228-271). The next developer scene follows this path.owner is for file rules only.Qualifiers from the block and from the rule combine. deny { audit R } and audit { deny R } both mean audit deny R.
| Block | Rule inside | Result |
|---|---|---|
| any | no qualifier in that seat | the block's qualifier |
deny | plain | deny (quiet) |
deny | audit | audit deny |
audit | deny | audit deny |
audit | owner (file rule) | audit owner |
allow | plain or allow | allow |
deny | allow, prompt | error: "conflicting mode prefix" |
allow, prompt | deny | error: "conflicting mode prefix" |
deny { audit /sys/** w, }, audit { deny /sys/** w, }) are accepted by the parser built from AppArmor 836052d21 (-Q -K --skip-kernel-load --warn=all). That both compile like audit deny follows from the combination code above and is what the manual states (apparmor.d.pod:2679-2684); the three forms compile to the same binary with the parser built from this commit.deny is quiet: the refusal leaves no log record. audit deny is a refusal that is logged. See syn-allow-deny and syn-audit.deny block turns all of them into denials and keeps "audited" for those that had it (block_rules.h:76-110). The fixture on the slide is ok_block1.sd.deny { } block around a rule that is already audit deny, and deny { deny { audit R } }, lose the audit for rules other than capabilities, so the denial is quiet. The manual says the result is an audited denial. Confirmed with the parser built from this commit, for file, signal and ptrace rules, by comparing binary output and rule dumps; the code is rule.h:428-438, parser_misc.c:1132-1142. Write audit deny on the rule, in an audit block or in no block, and do not rely on this.deny { } block silently removes an audit trail. deny { audit deny R } and deny { deny { audit R } } compile to a quiet deny for file, signal and ptrace rules: the access is still refused, but the record the author asked for is never written (run with the parser built from the AppArmor tree at 836052d21, nothing loaded into a kernel; rule.h:428-438, parser_misc.c:1132-1140). Capability rules keep the audit.deny { }, audit { } or owner { } changes every rule inside, including rules in if branches, hats and child profiles defined in the block (same run).prompt { capability X, } grants the capability: see prompt.owner { change_profile -> x, } is accepted and compiles like the rule without the block, although the direct form is an error.audit and audit deny.Nested blocks apply inner qualifiers first, then outer ones. audit { deny { R } } equals deny { audit { R } } equals audit deny R.
audit { deny { network inet stream, } } and deny { audit { network inet stream, } } "both resolve to" audit deny network inet stream, (apparmor.d.pod:2600-2624).audit { deny { /etc/demo/** w, } owner { /var/lib/demo/** rw, } } is accepted exactly as written by the parser built from AppArmor 836052d21 (-Q -K --skip-kernel-load --warn=all). The two rules under it are what the combination code gives, and the two forms compile to the same binary.deny { deny { audit R } }, which ends as a quiet deny for rules other than capabilities (see the details of the combining scene and the reference below).deny { allow { R } } names two access types for R and is refused like deny { allow R } (both forms run with the same parser: conflicting mode prefix).block::add_prefix (parser/block.cc:273-284) pushes the prefix through nested blocks, conditionals and hats; conflicts are detected in prefix_rule_t::add_prefix (parser/rule.h:385-440) and generic_add_prefix (parser/parser_misc.c:1111-1142).
block: TOK_OPEN rules TOK_CLOSE and rules: rules opt_prefix block; the action calls subblock->add_prefix($2, error) and then current->add_subblock(subblock, error) (parser_yacc.y:738-759).class block: public prefix_rule_t with subblocks, conds, rules (a block_rules) and hats; block::valid_prefix returns "priority is not allowed on rule blocks" when p.priority != 0 (block.h:34-52).bool block::add_prefix(const prefixes &p, const char *&error) first runs prefix_rule_t::add_prefix on the block itself, then for_each_recursive(..., false, true): eval_cond=false visits every cond_block of every conditional set, apply_to_hats=true descends into each hat's main_block (block.cc:228-284).bool block_rules::add_prefix(const prefixes &p, const char *&error) sets uses_prompt_rules for a prompt prefix, calls entry_add_prefix on each cod_entry (file and change_profile entries), add_prefix on each rule object, net.apply_compat_prefix(p) for the legacy network table, then caps.add_prefix and rlimits.add_prefix (block_rules.cc:612-640).prefix_rule_t::add_prefix (rule.h:385-440): valid_prefix, then priority != 0 gives "priority levels not supported" (the test looks at the rule's own priority, not at the prefix), then the audit, mode and owner conflict tests, then the audit and deny combination.generic_add_prefix and entry_add_prefix (parser_misc.c:1111-1159): mode conflict, if (p.priority != 0) entry->priority = p.priority;, audit conflict, the audit and deny combination, then the owner or other mask and check_x_qualifier. There is no owner conflict test and no change_profile test here. That is why owner { other /foo r, } and owner { change_profile -> x, } are accepted by the parser built from this commit; both are known discrepancies, see the reference below.allow, audit, deny, quiet are decomposed into four exclusive groups and rebuilt for the prefix (block_rules.h:62-110). Rlimits: any prefix on a block that sets an rlimit gives "prefix not allowed on rlimit rules" (parser.h:170-180).add_subblock merges capabilities, rlimits, the legacy network table and the uses-prompt flag into the enclosing block, because those are encoded once per profile (block.cc:155-175, block_rules.cc:181-200). Each block later emits its own rules in block::gen_policy_re (block.cc:86-110).prefix_rule_t and valid_prefix per rule class."conflicting mode prefix": the block and a rule name different access types. "priority is not allowed on rule blocks". Non-file rules with priority= are rejected inside blocks ("priority levels not supported").
All six rows were run with the parser built from AppArmor 836052d21 (-Q -K --skip-kernel-load --warn=all), each as the only content of a profile.
| Input | Message |
|---|---|
deny { allow /etc/demo/** r, } | conflicting mode prefix |
priority=1 { /etc/demo/** r, } | priority is not allowed on rule blocks |
audit { priority=1 signal, } | priority levels not supported |
owner { capability chown, } | owner prefix not allowed on capability rules |
deny { set rlimit cpu <= 10, } | prefix not allowed on rlimit rules |
owner { /var/lib/demo/** rw, and no closing brace | syntax error, unexpected end of file, expecting TOK_ID or TOK_MODE or TOK_SET_VAR |
deny block is not a conflict; it becomes a deny. Only an explicit allow or prompt contradicts deny.{ priority=1 signal, } fails like row 3; audit { priority=5 /etc/demo/override.conf r, } and owner { priority=1 /a r, } are accepted, and the tree tests the second (equality.sh:665-669).priority= inside a block. The slide states what the parser does at this commit; whether the restriction or the exception is intended is open. A comment above the test reads like an unfinished feature (rule.h:385-394).owner { other /foo r, } and audit { audit /a r, } are accepted. The first is a known discrepancy (the rule ends with no file permission); see the reference below.deny { allow R }; the parser built from this commit refuses it.other, and what owner { other ... } does.Next: syn-allow-deny, syn-audit, syn-owner (the qualifiers a block can carry), syn-boolean-conditionals (the other brace block).
audit, one of allow, deny or prompt, and one of owner or other. Not priority (block.h:46-51).if belong to a conditional block, which decides at compile time whether the rules inside are part of the profile. A conditional takes no qualifiers of its own, but it may stand inside a qualifier block and then its rules receive the block's qualifiers (from the code, block.cc:228-284).Basis of the statements on this page: "tree" means the parser built from AppArmor 836052d21 (6.0.0~alpha2) was run on the fragment (-Q -K --skip-kernel-load --warn=all), with nothing loaded into a kernel; "5.0.2" means apparmor_parser 5.0.2 was run the same way; "code" means the statement comes from reading the parser source at that commit and was not run. Blocks exist only in the profile text: compiled policy contains rules, so there is no kernel behaviour specific to blocks.
BLOCK = [audit] [allow|deny|prompt] [owner|other] '{' ( RULE | BLOCK | CONDITIONAL | HAT | PROFILE )* '}'
}. deny { /sys/** w, }, gives "syntax error, unexpected TOK_END_OF_RULE, expecting TOK_ID or TOK_MODE or TOK_SET_VAR" (tree).owner { }) and a bare block ({ capability setuid, }) are valid (tree).priority=N is not allowed in front of a block (tree).BLOCK = '{' ( RULES )* '}' (apparmor.d.pod:196); the parser's productions are at parser_yacc.y:738-759.| Block | Rule inside | Result | Basis |
|---|---|---|---|
| none (bare) | any | the rule's own qualifiers | tree |
audit | plain | audit | tree |
deny | plain | deny, quiet | tree |
deny | audit | audit deny | accepted: tree; result: code |
audit | deny | audit deny | accepted: tree; result: code |
allow | plain | allow | tree |
allow | deny | error: conflicting mode prefix | code |
deny | allow | error: conflicting mode prefix | tree |
prompt | deny | error: conflicting mode prefix | code |
owner | file rule | owner | tree |
owner | rule of another class | error: owner prefix not allowed on X rules | tree for capability; code for the others |
audit { deny { R } }, deny { audit { R } } | audit deny R | accepted: tree; result: code and the manual |
Nested blocks apply inner qualifiers first, then outer ones. For audit and deny the manual states that the order does not matter (apparmor.d.pod:2600-2624); the exception is listed under known discrepancies.
owner and other blocks: file rules, the bare file, rule and link rules only. Any other rule class is an error (code; capability: tree).deny block all become denied; those written with audit stay audited (code: block_rules.h:76-110; accepted by the tree's fixture ok_block1.sd).prompt block treats capabilities as allowed: prompt { capability chown, } compiles to the same binary as capability chown, (tree).priority=: file rules only (tree); see known discrepancies.The full form of an error is AppArmor parser error for FILE in profile FILE at line N: MESSAGE.
| Message | Example that triggers it | Basis |
|---|---|---|
conflicting mode prefix | deny { allow /etc/demo/** r, } | tree |
priority is not allowed on rule blocks | priority=1 { /etc/demo/** r, } | tree |
priority levels not supported | audit { priority=1 signal, }, { priority=1 signal, } | tree |
owner prefix not allowed on capability rules | owner { capability chown, } | tree |
owner prefix not allowed on X rules (unix, mqueue, ptrace, network, dbus, all, signal, io_uring, mount, userns) | an owner or other block around such a rule | code |
prefix not allowed on rlimit rules | deny { set rlimit cpu <= 10, } | tree |
conflicting audit prefix, conflicting owner prefix | present in the parser; not produced by audit { audit /a r, } or owner { other /foo r, }, which are accepted | tree |
syntax error, unexpected end of file, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | owner { /var/lib/demo/** rw, without } | tree |
syntax error, unexpected TOK_END_OF_RULE, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | deny { /sys/** w, }, | tree |
No warning is specific to blocks.
These are not intended behaviour and should not be relied on. The map's sec-bugs deck collects such findings.
deny { audit deny R } and deny { deny { audit R } } lose the audit for rules other than capabilities: the result is a quiet deny. The manual says a deny applied to a rule that carries audit is an audited denial (apparmor.d.pod:2679-2684). Basis: tree, for file, signal and ptrace rules; the code is rule.h:428-438, parser_misc.c:1132-1142.owner { other R } is accepted and R ends with no file permission, with no message (tree; parser_misc.c:1147-1159 has no conflict test). See syn-other.owner { change_profile -> x, } is accepted although owner change_profile -> x, is rejected with "owner conditional not allowed on change_profile rules" (tree). The compiled rule is identical to the one without the block (tree).priority= is rejected in any block, even a bare one, while a file rule with priority= is accepted (tree; rule.h:385-394 against parser_misc.c:1121-1122). The restriction may be deliberate; the difference between rule classes is the discrepancy. See syn-priority.deny { allow R }; the tree refuses it with "conflicting mode prefix".audit { ^hat { /a r, } } compiles to the same binary as ^hat { audit /a r, }, and the same holds for a child profile (tree).if or else branch that stands in a qualifier block receive the qualifiers whichever branch is later chosen (block.cc:240-257); the rule taken from audit { if $FOO { /a r, } else { /b r, } } is dumped with the audit mask (tree).| Step | Where |
|---|---|
productions block and rules: rules opt_prefix block | parser_yacc.y:738-759 |
class block: public prefix_rule_t, block::valid_prefix | block.h:34-52 |
block::for_each_recursive(func, eval_cond, apply_to_hats) | block.cc:228-271 |
block::add_prefix (eval_cond=false, apply_to_hats=true) | block.cc:273-284 |
block_rules::add_prefix | block_rules.cc:612-640 |
prefix_rule_t::add_prefix: priority test, conflict tests, audit and deny combination | rule.h:385-440 |
generic_add_prefix, entry_add_prefix for cod_entry (file and change_profile entries) | parser_misc.c:1111-1159 |
| capability sets recomputed for a prefix | block_rules.h:62-110 |
| rlimits refuse any prefix | parser.h:170-180 |
add_subblock: per-profile data (capabilities, rlimits, legacy network table, uses-prompt flag) merged upward | block.cc:155-175, block_rules.cc:181-200 |
block::gen_policy_re: each block emits its rules | block.cc:86-110 |
A space ends a word. /srv/demo/My Files/** r, fails with "syntax error, unexpected TOK_ID, expecting TOK_MODE". Quoted, "/srv/demo/My Files/**" r, is one path. Both were run through the tree's parser.
/srv/demo/My Files/** r, fails with syntax error, unexpected TOK_ID, expecting TOK_MODE; "/srv/demo/My Files/**" r, is accepted. Both run with the parser built from the AppArmor tree at 836052d21 (-Q -K --skip-kernel-load --warn=all, nothing loaded into a kernel).TOK_ID is a word (here Files/**) and TOK_MODE is a permission string such as r./abc def r,, expected FAIL) and ok_embedded_spaces_2.sd ("/abc def" r,, expected PASS).My Files and the profile are invented for the map.IDS, built from ID_CHARS, [^ \t\r\n"!,] (parser_lex.l:264-267). The quoted form accepted at the start of a rule is QUOTED_LABEL (parser_lex.l:302); both return TOK_ID (parser_lex.l:838-841).A word is bare or "quoted". Quotes admit blanks, tabs, new lines, ! and ,. Escapes work in both: \", \\, \t, \n, \r, \a, \e, \f, \NNN (octal), \xHH (hex), \dDDD (decimal). The pattern escapes such as \* are a second group, in the scenes that follow. As a path in a rule a quoted string must begin with /, @, : or &.
" or !; a comma belongs to it only when a word character follows.", any bytes except NUL and ", and ". A quote inside is written \".\\, \", \a, \e (ESC, octal 033), \f, \n, \r, \t, \NNN (one to three octal digits), \xHH (one or two hex digits), \dDDD (one to three decimal digits). The numeric forms stop at the value 255: \378 is \37 followed by 8 (lib.c:158-219).profile "demo" { } and profile demo { } define the same profile.profile "demo service" /usr/bin/demo { ^"night shift" { } } gives the names demo service and demo service//night shift (apparmor_parser -N, parser built from the AppArmor tree at 836052d21)./, @, : or &.=, list values such as flags, variable values and change_profile operands."/bin/alpha\tbeta" rix,) and ok_octal_1.sd (/bin/\141bcde rix,).ID_FIRST_CHARS, ID_FIRST, ID_CHARS, ID, IDS (parser_lex.l:262-267); QUOTED_LIST_VALUE_ID (parser_lex.l:273-275); ALLOWED_QUOTED_ID and QUOTED_ID (parser_lex.l:287-288); QUOTED_LABEL (parser_lex.l:302).char *processid(const char *string, int len) and its helpers (parser_misc.c:468-535), using int strn_escseq(const char **pos, const char *chrs, size_t n) (lib.c:158-219)."/srv/demo/My Files/**" and /srv/demo/My\ Files/** are the same path. The backslash form draws the --warn=format warning "Character was quotedunnecessarily, dropped preceding quote ('\') character"; the character it names is the blank. Run with the tree's parser.
"/srv/demo/My Files/**" r, and /srv/demo/My\ Files/** r, compile to the same expression, /srv/demo/My Files/[^/\x00][^\x00]*. Printed by the parser built from the AppArmor tree at 836052d21 with -D rule-exprs (-Q -K --skip-kernel-load, nothing loaded into a kernel).Warning from FILE (FILE line N): Character was quotedunnecessarily, dropped preceding quote ('\') character. The text has no blank between "quoted" and "unnecessarily", and the character it names is the blank.format, "warn on unnecessary or confusing formatting" (parser_main.c:291). It is off by default; turn it on with --warn=format or --warn=all. The line number it prints is past the end of the profile./srv/demo/end\ r, gives syntax error, unexpected TOK_END_OF_RULE, expecting TOK_MODE."/abc\ def" r,), ok_embedded_spaces_2.sd ("/abc def" r,), ok_embedded_spaces_4.sd (/abc\ def r,).--warn and [-D, --dump](https://apparmor.net/man/master/apparmor_parser/#D-n---dump-n).ID definition (parser_lex.l:266).pwarn(WARN_FORMAT, ...), in the default branch of convert_aaregex_to_pcre (parser_regex.c:382-401)."/srv/demo/report*.txt" is still a glob. \*, \?, \[, \], \{, \}, \, and \\ stand for the characters themselves, inside or outside quotes. The matches drawn follow from the expressions the tree's parser printed; they were not run against a kernel.
"/srv/demo/q*" is converted to /srv/demo/q[^/\x00]*: still a glob. /srv/demo/report\*.txt is converted to /srv/demo/report\*\.txt: a literal star. Both printed by the parser built from the AppArmor tree at 836052d21 with -D rule-exprs.\*, \?, \[, \], \{, \}, \, and \\.\, matters inside { } and character classes: /srv/demo/c\,d is converted to /srv/demo/c,d.., +, (, ) and the vertical bar are always literal, escaped or not. ^ and $ are literal outside a character class.[\^a] loses its escape and becomes the negated class [^a]; /k[\^a] r, and /k[^a] r, compile to identical output (run with the released parser 5.0.2). Put ^ anywhere but first in the class.*?[]{}^,\ on purpose (parser_misc.c:480-503).convert_aaregex_to_pcre: a backslash sets bEscape (parser_regex.c:152-167); * with bEscape is emitted as \* (parser_regex.c:168-176), ? as itself (parser_regex.c:231-237); brackets, braces and the comma follow (parser_regex.c:257-345); ^, $ and the always-escaped characters are at parser_regex.c:356-380.Stage 1 (every word): remove quotes, decode \t, \NNN, \xHH, \dDDD and the like to bytes. Stage 2 (patterns): \*, \?, \[, \{, \,, \\ become literal characters. apparmor_parser -D rule-exprs shows the text between the stages; the line drawn is what the tree's parser printed.
apparmor_parser -D rule-exprs ("Dump rule to expr tree conversions", common_optarg.c:31) prints each path as aare: BEFORE -> AFTER. BEFORE is the text after stage one, AFTER the regular expression that stage two produced."/srv/demo/My Files/\x41\*.txt" gives /srv/demo/My Files/A\*.txt -> /srv/demo/My Files/A\*\.txt.\a \e \f \n \r \t, \NNN, \xHH, \dDDD, \" decoded to one byte.\000, \x00, \d0), whose escape text is kept; a decoded value that is one of * ? [ ] { } ^ , or a backslash, which is stored with a backslash in front (\d123 becomes \{, run with the released parser 5.0.2); and a backslash before anything else.\*, \?, \[, \], \{, \}, \,, \\ become literal characters; \000 and \x00 become a zero byte./srv/demo/\141bc gives /srv/demo/abc; /srv/demo/e\x41\d066\103 gives /srv/demo/eABC.processid, processquoted, processunquoted (parser_misc.c:468-535) with strn_escseq (lib.c:158-219).convert_aaregex_to_pcre (parser_regex.c:118-445).Stage 1: processid() → processquoted() → processunquoted() using strn_escseq(). Stage 2: convert_aaregex_to_pcre() with bEscape; leftovers go through str_escseq() and reach the regex scanner in libapparmor_re/parse.y.
char *processid(const char *string, int len) calls processquoted when the text starts with ", else processunquoted; processquoted strips the quotes and calls processunquoted(string + 1, len) (parser_misc.c:506-535).char *processunquoted(const char *string, int len) (parser_misc.c:468-503): for each backslash it calls strn_escseq(&pos, "", len). A result of 0 copies the escape text; a result in "*?[]{}^,\\" is stored as backslash plus the character; any other result is stored as the byte; -1 copies the backslash unchanged.int strn_escseq(const char **pos, const char *chrs, size_t n) (lib.c:158-219): octal by strntol(*pos, &end, 8, 255, min(3, n)), \d decimal with at most 3 digits, \x hex with at most 2, then the letters a e f n r t; returns -1 for anything else.pattern_t convert_aaregex_to_pcre(const char *aare, int anchor, int glob, std::string& pcre, int *first_re_pos) (parser_regex.c:118-445). A backslash sets bEscape (parser_regex.c:152-167).bEscape, str_escseq(&pos, "") is tried; a valid escape is passed on with its backslash, anything else gets pwarn(WARN_FORMAT, "Character %c was quotedunnecessarily, dropped preceding quote ('\\') character\n", ...) (parser_regex.c:382-401).., +, |, (, ) always get a backslash; ^ and $ outside a character class too (parser_regex.c:356-380).Regex error: trailing '\' escape character (parser_regex.c:418-422; read, not run).str_escseq(pos, "*+.|^$-[](){}") (parse.y:182).escape_re() puts a backslash before {}[]*? when @{profile_name} is expanded (parser_variable.c:87-103).test_processunquoted, test_processquoted (parser_misc.c:1387-1460).A quoted path in a rule must begin with /, @, : or &. ! needs a backslash or quotes. A missing closing quote extends the string to the next " in the file; the resulting error and its line number point elsewhere. The uncounted new lines are a known discrepancy, not intended behaviour.
Run with the parser built from the AppArmor tree at 836052d21 (-Q -K --skip-kernel-load --warn=all, nothing loaded into a kernel):
/, @, : or &: Lexer found unexpected character: '"' (0x22) in state: INITIAL.!: Lexer found unexpected character: '!' (0x21) in state: INITIAL. Write \! or quote the word." in the file, and the usual result is syntax error, unexpected TOK_ID, expecting TOK_MODE. With no later quote at all the unexpected character message above is reported at the line of the opening quote."/a\\", is extended to the next " in the file, because the second backslash and the quote are read as the pair \".profile "" { }: Empty named transition profile name: .\q or \., is dropped; with --warn=format the parser prints Character C was quotedunnecessarily, dropped preceding quote ('\') character. Fixture: ok_slashquote_1.sd (/bingo/bang\o/bongo rw,).Regex error: trailing '\' escape character, then Unable to parse input line (read from the source, not run).ALLOWED_QUOTED_ID is [^\0"]|\\\": a new line is an ordinary character, and \\ is not treated as a unit (parser_lex.l:287-288). QUOTED_LABEL requires the first character (parser_lex.l:302); its action does not touch current_lineno (parser_lex.l:838-841).Pattern characters: syn-globbing. Structure characters: syn-comments. Zero bytes in socket names: syn-unix. The two stages: fe-lexer, fe-aare.
\t, \NNN, \xHH, \dDDD) are decoded in every word; pattern escapes (\*, \?, \[, \{, \,) only where a pattern is expected._2 and _3 (\000, \x00, \d00 in a file path) are marked as passing despite their names; the parser has no check for a zero byte in a file path.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the fragment (-Q -K --skip-kernel-load --warn=all, with -D rule-exprs for conversions) and nothing was loaded into a kernel; "5.0.2" means the released parser 5.0.2 was run; "code" means the parser source was read, not run. What a pattern matches is derived from the expression the parser printed.
WORD: BARE | QUOTED
BARE: one or more of: any character except blank, tab, CR, LF, " ! ,
, followed by a word character
the pairs \blank \tab \" \! \,
\# (as the first character only)
QUOTED: '"' { any byte except NUL and " | \" } '"'
profile "demo" { } and profile demo { } define the same profile./, @, : or &.profile, hat, ^ and ->, values after =, identity values, list values such as flags, variable values, change_profile operands, ids in keyword rules and if expressions. A quoted value in a conditional list needs at least one character.profile "demo service" /usr/bin/demo { ^"night shift" { } } gives the names demo service and demo service//night shift (tree, -N)."/srv/demo/q*" is a glob (tree).Decoded in quoted and bare words alike, in paths, profile names, flag values, variable values and conditional values (code).
| Escape | Result |
|---|---|
\\ | a backslash, kept escaped for the pattern stage |
\" | " |
\a | BEL |
\e | ESC (octal 033) |
\f | form feed |
\n | new line |
\r | carriage return |
\t | tab |
\NNN | one to three octal digits, value at most 255; \378 is \37 followed by 8 |
\xHH | one or two hex digits |
\dDDD | one to three decimal digits, value at most 255; not a digit class |
\0, \000, \x00, \d0) is not stored as a byte: the escape text is kept for the pattern stage.* ? [ ] { } ^ , or a backslash is stored with a backslash in front, so the pattern stage reads it as literal: \d123 becomes \{ (tree).| Written | Meaning |
|---|---|
\* \? \[ \] \{ \} | the character itself |
\, | a literal comma; matters inside { } and character classes |
\\ | a literal backslash |
. + ( ) and the vertical bar | always literal, escaped or not |
^ $ | literal outside a character class, escaped or not |
\000 \x00 \d0 | a zero byte |
any other escaped character, such as \q, \!, \. or backslash blank | the backslash is dropped, with the format warning below |
Pattern characters themselves: syn-globbing.
Printed by the tree's parser with -D rule-exprs as aare: BEFORE -> AFTER.
| Written | Before conversion | After conversion |
|---|---|---|
"/srv/demo/My Files/**" | /srv/demo/My Files/** | /srv/demo/My Files/[^/\x00][^\x00]* |
/srv/demo/My\ Docs/** | /srv/demo/My\ Docs/** | /srv/demo/My Docs/[^/\x00][^\x00]*, with the format warning |
"/srv/demo/q*" | /srv/demo/q* | /srv/demo/q[^/\x00]* |
/srv/demo/report\*.txt | /srv/demo/report\*.txt | /srv/demo/report\*\.txt |
"/srv/demo/My Files/\x41\*.txt" | /srv/demo/My Files/A\*.txt | /srv/demo/My Files/A\*\.txt |
/srv/demo/\141bc | /srv/demo/abc | /srv/demo/abc |
/srv/demo/e\x41\d066\103 | /srv/demo/eABC | /srv/demo/eABC |
"/srv/demo/a\tb" | /srv/demo/a, a tab byte, b | the same |
/srv/demo/nul\000x | /srv/demo/nul\000x | /srv/demo/nul\x0x (in the rule line) |
/srv/demo/c\,d | /srv/demo/c\,d | /srv/demo/c,d |
"/srv/demo/a,b" | /srv/demo/a,b | the same |
"/srv/demo/trailing," | /srv/demo/trailing, | the same |
/srv/demo/it\"s | /srv/demo/it"s | the same |
"/srv/demo/My Files/**" r, and /srv/demo/My\ Files/** r, are the same rule (tree). The second draws the format warning./srv/demo/end\ r, is a syntax error (tree)./: syn-identities.| Message | Cause |
|---|---|
syntax error, unexpected TOK_ID, expecting TOK_MODE | an unquoted space in a path; also the usual result of a missing closing quote (tree) |
Lexer found unexpected character: '"' (0x22) in state: INITIAL | a quoted path that does not start with /, @, : or &; or an opening quote with no later quote in the file, reported at the line of the opening quote (tree) |
Lexer found unexpected character: '!' (0x21) in state: INITIAL | a bare !; write \! or quote the word (tree) |
syntax error, unexpected TOK_END_OF_RULE, expecting TOK_MODE | a backslash before the blank that precedes the permissions (tree) |
Empty named transition profile name: | profile "" { } (tree) |
Regex error: trailing '\' escape character, then Unable to parse input line | a pattern that ends in a backslash (code; not run) |
Warning: Character C was quotedunnecessarily, dropped preceding quote ('\') character | a backslash before a character that needs none; class format, off by default, enabled by --warn=format or --warn=all; printed as Warning from FILE (FILE line N): ... with a line number past the end of the profile (tree) |
C is the blank, so the message reads Character was quotedunnecessarily, ....\., although the output is the same with or without the backslash."/a\\", is extended to the next " in the file, because the scanner reads the second backslash and the quote as the pair \". Two quoted paths, the first ending in \\, fail with syntax error, unexpected TOK_ID, expecting TOK_MODE (tree).\\ before a blank is read as a backslash plus an escaped blank: /a\\ r, fails with syntax error, unexpected TOK_END_OF_RULE, expecting TOK_MODE (tree).[\^a] loses its escape and becomes the negated class [^a], broader than written: /k[\^a] r, and /k[^a] r, compile to identical output (tree). Put ^ anywhere but first in the class.parser/tst/simple_tests/file/bad_embedded_0_1.sd, _2 and _3 (\000, \x00, \d00 in a file path) are marked as passing despite their names; the parser has no check for a zero byte in a file path.| Step | Where |
|---|---|
bare word character classes ID_CHARS, ID_FIRST, ID | parser/parser_lex.l:262-267 |
QUOTED_LIST_VALUE_ID | parser/parser_lex.l:273-275 |
ALLOWED_QUOTED_ID, QUOTED_ID; \\ is not treated as a unit, the cause of the two backslash discrepancies | parser/parser_lex.l:287-288 |
QUOTED_LABEL, the quoted form accepted at the start of a rule, and its action | parser/parser_lex.l:302, 838-841 |
processid(), processquoted(), processunquoted() | parser/parser_misc.c:468-535 |
strn_escseq() | parser/lib.c:158-219 |
unit tests test_processunquoted, test_processquoted | parser/parser_misc.c:1387-1460 |
convert_aaregex_to_pcre(); bEscape set at 152-167 | parser/parser_regex.c:118-445 |
^ $ and the always-escaped characters | parser/parser_regex.c:358-380 |
other escaped characters: str_escseq(), else pwarn(WARN_FORMAT) | parser/parser_regex.c:382-401 |
| trailing backslash error | parser/parser_regex.c:418-422 |
--warn=format | parser/parser_main.c:291 |
the regex scanner decodes passed-on escapes with str_escseq() | parser/libapparmor_re/parse.y:182 |
escape_re() adds a backslash before pattern characters when @{profile_name} is expanded | parser/parser_variable.c:87-103 |
remount [options...] MOUNTPOINT, allows changing the flags of an existing mount.
MS_REMOUNT as a remount before testing anything else (lsm.c:722-724) and compares the mount point and the full flags, with no source and no type (mount.c:328-353). The hook is sb_mount (lsm.c:707-742).EPERM without capability sys_admin,, after the rule has been checked (namespace.c:4279-4283).remount options=(ro) /run/demo/, is line 15 of demo's profile; it compiles with no warning (run with the tree's parser). The program demo and its profile are invented for the map.AA_MAY_MOUNT (0x2) (mount.h:21).[QUALIFIERS] remount [options=... | options in ...] [MOUNTPOINT],. The one path is the mount point.
options, option, fstype, vfstype), but a remount has no filesystem type to compare.fstype= or with a source compiles to a new-mount rule without the remount flag": remount fstype=ext4 /a, is accepted and allows new ext4 mounts onto /a, and no remount. Do not write fstype= in a remount rule./.audit, allow, deny, prompt and priority= are taken; owner and other are refused with owner prefix not allowed on mount rules.remount /foo, (ok_22.sd); remount, (plasmashell:14).syntax error, unexpected TOK_ARROW, expecting TOK_END_OF_RULE (run with the tree's parser).TOK_REMOUNT opt_conds opt_id TOK_END_OF_RULE calls do_mnt_rule($2, NULL, NULL, $3, AA_DUMMY_REMOUNT) (parser_yacc.y:1287-1290).remount options=(F) PATH, = mount options=(remount, F) -> PATH,.
remount options=(ro) /run/demo/, and mount options=(remount, ro) -> /run/demo/, compile to the same rule: the mount point /run/demo/, any source, any type, and the two flags ro and remount, both required.remount /a, requires the remount flag and lets every other remount flag be present or absent, while mount options=(remount) -> /a, requires the remount flag alone (run with the tree's parser).mount options=(remount) /run/demo/, prints Encoding of mount rule failed, without a line number, followed by ERROR processing policydb rules for profile demo, failed to load (run with the tree's parser). A failing example in the tree: bad_opt_8.sd.MS_REMOUNT to every options= set (mount.cc:541-542) and the placeholder permission is replaced by the mount permission (mount.cc:578-580).\x07/run/demo/\x00[^\000]*\x00[^\000]*\x00\x01\x06, permission 0x2.remount options=(ro) P,: exactly remount + ro. remount options in (ro, nosuid) P,: remount plus any of those. remount P,: remount plus anything.
ro and remount; row 2 requires remount and makes ro and nosuid optional; row 3 requires remount and makes every other remount flag optional.move: remount options=(move) /a, is accepted and the move is dropped (run with the tree's parser).remount options=(bind) /a, requires bind and remount: that is the call that changes the per-mount flags of a bind mount.rw, suid, ...) add nothing to options=: remount options=(rw) /a, allows a remount with no other flag.remount options=(rw, ro) /a, gives conflicting flag values = 33, 1, then conflicting flags in the rule.options= set: mount.cc:541-542; the defaults without options: mount.cc:561-563, mount.cc:570-571; the flags a remount rule keeps (MS_REMOUNT_FLAGS) and why propagation flags are among them: mount.h:114-120.A remount is logged as operation="mount" with remount in flags=. info="failed flags match" means the path matched and the flags did not.
apparmor="DENIED" operation="mount" class="mount" info="failed mntpnt match" error=-13 profile="/home/user/test/testmount" name="/tmp/foo/" pid=14155 comm="testmount" flags="ro, remount") with demo's values, which are illustrative. info="failed flags match" is from the kernel's table of texts (mount.c:145-153) and the order of the words in flags= from the kernel's format code (mount.c:31-85).operation="mount"; remount appears among the flags (lsm.c:722-724, mount.c:328-353).srcname= and no fstype=, and both are compared as empty. info is usually failed mntpnt match or failed flags match. It is failed srcname match or failed type match when the mount point matches only rules that name a source or a type, as demo's line 14 does before line 15 is added, and failed perms check when every field matched a rule without the permission (mount.c:179-189)./ for a directory.flags="rw, nosuid, nodev, remount, bind, silent, relatime").error=-13 is EACCES.info texts.AA_DUMMY_REMOUNT (mount.h:134) -> MS_REMOUNT added (mount.cc:541-542, 561-571) -> gen_policy_remount (mount.cc:786-859); kernel aa_remount (mount.c:328-353).
AA_DUMMY_REMOUNT is 0x40000000 (mount.h:134). The constructor adds MS_REMOUNT to every options= set (mount.cc:541-542), uses it as the required set when there is no options= (mount.cc:559-571) and replaces the placeholder by AA_MAY_MOUNT (mount.cc:578-580).gen_policy_remount: mount.cc:786-859. It is chosen when the flags contain remount and the rule has neither source nor fstype (mount.cc:1105-1107). MS_REMOUNT_FLAGS is every flag except move (mount.h:114-120).ro is \x01, remount is \x06 (bit number + 1).\x07/run/demo/\x00[^\000]*\x00[^\000]*\x00\x01\x06 with 0x2; remount /run/demo/, gives ...\x00(\x01|)(\x02|)(\x03|)(\x04|)(\x05|)\x06(\x07|)...; remount options in (ro) /a, gives (\x01|)\x06; remount options=(bind) /a, gives \x06\x0d.aa_remount (mount.c:328-353).fstype= or with a source compiles to a new-mount rule without the remount flag": mount options=(remount, ro) /run/demo/, (the long form with the path in the source position and one more flag) is accepted and compiles to \x07[^\000]*\x00/run/demo/\x00[^\000]*\x00\x01: a new mount with source /run/demo/ onto any mount point with the flag ro, and no remount (run with the tree's parser). With remount alone the same shape fails to encode.fstype= or with a source compiles to a new-mount rule without the remount flag": remount fstype=ext4 /a, is accepted and compiles to a new-mount rule without the remount flag, \x07/a\x00[^\000]*\x00(ext4)\x00(\x01|)(\x02|)(\x03|)(\x04|)(\x05|)(\x07|)...: new mounts of that type from any source onto /a with any combination of the ordinary flags, and no remount. The cause is the order of the tests: with an fstype the remount branch is skipped and the last branch still sees optional flags (mount.cc:559-571, mount.cc:1105-1106, mount.cc:1118-1123, mount.cc:1043). The long form mount options=(remount) fstype=ext4 -> /a, fails with Encoding of mount rule failed.remount rules with fstype= or vfstype=. Both are on the bug list as confirmed on the parser side; see Known bugs. They were not run on a kernel.deny remount included, is not asked about it (read from the kernel source, lsm.c:1791-1794; not run on a kernel). See what is not mediated.nosuid, nodev or noexec. That is how the rule reads, but it is worth a second look in a profile meant to keep a mount restricted.One path with a trailing /, flag words only, no arrow.
AppArmor parser error for FILE in profile FILE at line N: MESSAGE; the slide shows MESSAGE. Rows 1 to 4 were run with the tree's parser.conflicting flag values = 33, 1 and conflicting flags in the rule. The numbers are the two flag masks in decimal: 33 is remount plus ro.invalid mount conditional foo, then bad mount rule. The long form with a source, mount options=(remount) /run/demo/,, gives Encoding of mount rule failed.Remount rules are mount rules with the remount flag. The flag table is in the mount deck.
[QUALIFIERS] remount [options=... | options in ...] [MOUNTPOINT], is the same rule as mount options=(remount, ...) -> MOUNTPOINT,.EACCES and is logged as operation="mount" with remount in flags=.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the line (-Q -K --skip-kernel-load --warn=all, -D rule-exprs for compiled forms), with nothing loaded into a kernel; "code" means the parser source or the kernel source was read, not run. Nothing here was observed on a running kernel.
REMOUNT RULE: [QUALIFIERS] remount [CONDITIONALS] [MOUNTPOINT] , CONDITIONALS: options=FLAG | options=( FLAG ... ) | options in ( FLAG ... ) QUALIFIERS: [priority=N] [audit] [allow|deny|prompt]
remount options=(F) P, is the same rule as mount options=(remount, F) -> P, (tree).option is the same word as options (code).| Seat | On a remount rule |
|---|---|
priority= | taken |
audit | taken |
allow, deny, prompt | taken: deny is not logged; prompt is in syn-prompt |
owner, other | refused: owner prefix not allowed on mount rules (tree) |
| Rule | Required flags | Optional flags |
|---|---|---|
remount P, | remount | every other flag except move |
remount options=(ro) P, | remount, ro | none |
remount options in (ro, nosuid) P, | remount | ro, nosuid |
mount options=(remount) -> P, | remount | none |
mount options=(remount, ro) -> P, | remount, ro | none |
mount options=(remount) S -> P, | error: Encoding of mount rule failed |
All rows are from the tree's parser.
move; the table is in syn-mount. remount options=(move) P, is accepted and the move is dropped (tree).remount options=(bind) P, requires bind and remount: the call that changes the per-mount flags of a bind mount (tree).rw, suid, ...) add nothing to options=; remount options=(rw) P, allows a remount with no other flag (tree).parser/mount.h:114-120, code).| Field | Meaning |
|---|---|
operation="mount" | a remount is logged as a mount |
class="mount" | always |
info= | failed mntpnt match, failed flags match or failed perms check; failed srcname match, failed type match (the mount point matched only a rule with a source or a type) |
error=-13 | EACCES |
name= | the mount point; a directory ends in / |
flags= | the flags as words; remount is among them |
A record from the tree (libraries/libapparmor/testsuite/test_multi/testcase_remount_01.in):
apparmor="DENIED" operation="mount" class="mount" info="failed mntpnt match" error=-13 profile="/home/user/test/testmount" name="/tmp/foo/" pid=14155 comm="testmount" flags="ro, remount"
| Rule | Message | Has line number |
|---|---|---|
remount /run/demo/ -> /mnt/, | syntax error, unexpected TOK_ARROW, expecting TOK_END_OF_RULE | yes |
remount options=(rw, ro) /run/demo/, | conflicting flag values = 33, 1 then conflicting flags in the rule | no |
remount options=(ro, size=1m) /run/demo/, | unsupported mount option value 'size=1m' | no |
owner remount /run/demo/, | owner prefix not allowed on mount rules | yes |
mount options=(remount) /run/demo/, | Encoding of mount rule failed | no |
remount /run/demo, | none; the rule does not match a directory | |
any remount rule, no mount in the feature set, --warn=rule-not-enforced | warning mount rules not enforce |
Rows with an error message are from the tree's parser.
do_mnt_rule($2, NULL, NULL, $3, AA_DUMMY_REMOUNT) (parser/parser_yacc.y:1287-1290); the placeholder is 0x40000000 (parser/mount.h:134).MS_REMOUNT is added to every options= set (parser/mount.cc:541-542); without options= the required set is {remount} and the optional set every other remount flag (parser/mount.cc:559-571); the permission becomes AA_MAY_MOUNT (parser/mount.cc:578-580).gen_policy_remount writes mount point, any source, any type, flags masked with MS_REMOUNT_FLAGS (parser/mount.cc:786-859, parser/mount.h:114-120). Demo's line is \x07/run/demo/\x00[^\000]*\x00[^\000]*\x00\x01\x06 with 0x2 (tree).sb_mount tests MS_REMOUNT first (linux:security/apparmor/lsm.c:722-724); aa_remount passes the mount point and the flags (linux:security/apparmor/mount.c:328-353).None of these is taught as intended behaviour. All are on the bug list as confirmed; see Known bugs.
remount fstype=ext4 /a, is accepted and compiles to a new-mount rule for type ext4 onto /a with every ordinary flag optional and no remount flag; reproduce with -D rule-exprs (tree). Not run on a kernel.mount options=(remount, ro) /run/demo/, is accepted and compiles to a new mount with source /run/demo/ and the flag ro, without remount (tree). Not run on a kernel.set rlimit RESOURCE <= VALUE, caps a resource limit for tasks confined by the profile. Raising the hard limit above it fails with EACCES.
rlim_max) of one resource. A profile without a rule for a resource leaves that resource alone.setrlimit calls (resource.c:88-100)./sys/kernel/security/apparmor/features/rlimit/mask lists the kernel's resource names (resource.c:24-27). The parser does not read it.set rlimit nofile <= 1024, is line 24 of demo's profile. The program demo and its profile are invented for the map; the starting hard limit 1048576 is an illustration.set rlimit RESOURCE <= VALUE [UNIT],. Both keywords are required; <= is the only operator; no qualifiers.
100M and 100 M give identical output; blanks around <= are optional (set rlimit nproc<=10,).infinity stores "no limit"; a unit after it is ignored (set rlimit cpu <= infinity weeks, is accepted).Cannot merge rlimits, more than one value specified for a single rlimit (block_rules.cc:188).set rlimit gives prefix not allowed on rlimit rules.set rlimit, is a syntax error.rules: rules TOK_SET TOK_RLIMIT TOK_ID TOK_LE TOK_VALUE opt_id TOK_END_OF_RULE, with no opt_prefix (parser_yacc.y:852-859).RLIMIT_MODE: parser_lex.l:611-625, entered at parser_lex.l:867-869.Counts take a number. Sizes take K, M, G (or KB, MB, GB). cpu and rttime take time units from us to weeks; without a unit cpu is seconds and rttime microseconds.
nofile (alias ofile), nproc, locks, sigpending, rtprio: a number, no unit (block_rules.cc:82-92).fsize, data, stack, core, rss, as, memlock, msgqueue: bytes, or K, KB, M, MB, G, GB, powers of 1024 (block_rules.cc:102-124). rss is accepted although Linux does not enforce it.cpu is stored in seconds, and a result below one second is an error (block_rules.cc:57-68); rttime is stored in microseconds (block_rules.cc:70-80).us, microsecond(s), ms, millisecond(s), s, sec, second(s), min, minute(s), h, hour(s), d, day(s), week(s) (parser_misc.c:1306-1346). Division is integer division: cpu <= 1500ms equals cpu <= 1.data <= 100M, 100MB, 100 M and 104857600 give identical output; so do cpu <= 60, 1min and 1 minute; rttime <= 10 equals 10us. The stored values 600 for cpu <= 10 minutes and 10000 for rttime <= 10ms follow from the unit table; they were not run.0 is octal: nofile <= 010 is 8. Hexadecimal cannot be written.RLIMIT 'cpu' no units specified using default units of seconds, RLIMIT 'rttime' no units specified using default units of microseconds) are off by default; --warn=missing turns them on.K, M and G (apparmor.d.pod:385).set rlimit nice <= N stores N + 20 (5 gives 25, -20 gives 0, 19 gives 39, run with the tree's parser; block_rules.cc:94-100), while the kernel's scale for RLIMIT_NICE is 20 - nice (prio.h:33-36). The manual page says only "a number between -20 and 19" (apparmor.d.pod:394). It is confirmed (see Known bugs): do not rely on what a given nice ceiling permits.set rlimit data <= 9999999999G, exits 0 and stores an unrelated number.0 makes a value octal, so set rlimit nofile <= 010, is a ceiling of 8 and a reviewer who reads it as ten sees a looser limit than the kernel gets. The parser prints nothing.Limits are applied when an exec changes the task's confinement: hard = min(hard, ceiling). Profile changes without exec, hats and profile reloads do not apply them. This is what the kernel code does; it was not run.
bprm_committing_creds. apparmor_bprm_committing_creds returns early when the label does not change or the new label is unconfined (lsm.c:957-973).__aa_transition_rlimits (resource.c:153-206) does two things. For every resource the old profiles controlled, the soft limit is reset to the smaller of the hard limit and the soft limit of init (resource.c:166-181). Then, for every resource in the new profiles, the hard limit becomes the smaller of itself and the ceiling, the soft limit is pulled down to the hard limit, and the CPU timer is updated for the CPU time limit (resource.c:184-205).setrlimit with a hard limit above the ceiling fails with EACCES and is logged with operation="setrlimit" rlimit=NAME value=N. Changing another label's task needs capability sys_resource,.
task_setrlimit; AppArmor's handler (lsm.c:1006-1021, registered at lsm.c:1871) is skipped for an unconfined caller.EACCES when the resource is one the profile has a rule for and the new hard limit is larger than the ceiling (resource.c:88-100). Only the hard limit is compared.capability sys_resource, the call fails with EACCES, and the record has info="cap_sys_resource" and a peer= field (resource.c:133-138). That capability test itself is not logged. The whole function: resource.c:114-146. rlimit=%s value=%lu (resource.c:30-42) and the operation name setrlimit (audit.h:101). The tree has no sample record with rlimit=; the values are illustrative.block_rules.cc:38-131 fills aa_rlimits; parser_interface.c:398-411 writes it; policy_unpack.c:667-700 stores the ceilings.
struct aa_rlimits (parser.h:166-181) also carries the error prefix not allowed on rlimit rules (parser.h:177). It is filled at block_rules.cc:38-131 and merged into the profile at block.cc:132-135.sd_serialize_rlimits: parser_interface.c:398-411. The kernel side: policy_unpack.c:667-700.rlim_map[] and aa_map_resource: resource.c:83-86; the table is generated at build time (Makefile:89-99).KB, MB or GB" (block_rules.cc:114-119); times go through convert_time_units (parser_misc.c:1331-1346).nofile is index 7, so specified is 0x80. Observed with the tree's parser: nice is index 13, specified=0x2000.set is required, names are lower case, size units are capitals, counts take no unit, and a leading 0 makes a number octal.
AppArmor parser error for FILE in profile FILE at line N: MESSAGE; the slide shows MESSAGE, produced by the tree's parser. The message of the fourth row continues with the tokens the parser expected.set rlimit nproc < 10, gives Lexer found unexpected character: '<' (0x3c) in state: RLIMIT_MODE.set rlimit nofile 1024, gives syntax error, unexpected TOK_VALUE, expecting TOK_LE.set rlimit data <= 100m, gives RLIMIT 'data' invalid value 100 m. set rlimit nproc <= -1, is refused.set rlimit nice <= 20, gives RLIMIT 'nice' out of range (-20 .. 19) 20.set rlimit rttime <= 60m, fails (rlimits/bad_rlimit_01.sd).set rlimit gives prefix not allowed on rlimit rules (rlimits/bad_rlimit_block_audit.sd, and the _deny and _owner files next to it).A ceiling applied at exec. See the exec decks for when that happens.
set rlimit RESOURCE <= VALUE [UNIT], stores a ceiling for the hard limit of one resource. No qualifiers.setrlimit calls; refusals return EACCES.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the line (-Q -K --skip-kernel-load --warn=all), with nothing loaded into a kernel; "code" means the parser source or the kernel source was read, not run. Nothing here was observed on a running kernel.
RLIMIT RULE: set rlimit RESOURCE <= VALUE [UNIT] , VALUE: a number, or infinity
set and rlimit are both required; <= is the only operator (tree).<= and between value and unit are optional (tree).infinity means no ceiling; a unit after it is ignored (tree).prefix not allowed on rlimit rules (tree).Cannot merge rlimits, more than one value specified for a single rlimit (code).| Resource | Kernel constant | Value | Units | Without a unit | Stored as |
|---|---|---|---|---|---|
cpu | RLIMIT_CPU | number | time units | seconds | seconds; below 1 s is an error |
rttime | RLIMIT_RTTIME | number | time units | microseconds | microseconds |
nofile, ofile | RLIMIT_NOFILE | number | none | - | the number |
nproc | RLIMIT_NPROC | number | none | - | the number |
locks | RLIMIT_LOCKS | number | none | - | the number |
sigpending | RLIMIT_SIGPENDING | number | none | - | the number |
rtprio | RLIMIT_RTPRIO | number | none | - | the number |
nice | RLIMIT_NICE | -20 .. 19 | none | - | the number plus 20 (see Known discrepancies in the slide details of "Numbers, sizes and times") |
fsize | RLIMIT_FSIZE | number | size units | bytes | bytes |
data | RLIMIT_DATA | number | size units | bytes | bytes |
stack | RLIMIT_STACK | number | size units | bytes | bytes |
core | RLIMIT_CORE | number | size units | bytes | bytes |
rss | RLIMIT_RSS | number | size units | bytes | bytes (Linux does not enforce this limit) |
as | RLIMIT_AS | number | size units | bytes | bytes |
memlock | RLIMIT_MEMLOCK | number | size units | bytes | bytes |
msgqueue | RLIMIT_MSGQUEUE | number | size units | bytes | bytes |
Any resource takes infinity. ofile is an alias of nofile, which makes seventeen names.
| Size unit | Multiplier |
|---|---|
K, KB | 1024 |
M, MB | 1024 x 1024 |
G, GB | 1024 x 1024 x 1024 |
| Time unit | Length |
|---|---|
us, microsecond, microseconds | one microsecond |
ms, millisecond, milliseconds | 1000 microseconds |
s, sec, second, seconds | one second |
min, minute, minutes | 60 seconds |
h, hour, hours | 3600 seconds |
d, day, days | 86400 seconds |
week, weeks | 604800 seconds |
Size units are capitals only. The manual page lists K, M and G.
0 makes the number octal: nofile <= 010 is 8 (tree). Hexadecimal cannot be written.cpu <= 1500ms equals cpu <= 1 (tree). cpu below one second is an error.All statements in this section are from the kernel source (linux:security/apparmor/resource.c, linux:security/apparmor/lsm.c:957-1021), not from a run.
setrlimit and prlimit by a confined task: a new hard limit above the ceiling is refused with EACCES; resources without a rule are not checked; changing a task with a different label needs capability sys_resource,.Read from the kernel's format strings; the tree has no sample record.
| Field | Meaning |
|---|---|
operation="setrlimit" | the operation |
rlimit=NAME | the resource, by the kernel's name |
value=N | the hard limit that was asked for |
peer=LABEL | the label of the other task, when another task's limits were to be changed |
info="cap_sys_resource" | the refusal was for lack of capability sys_resource |
| Rule | Message |
|---|---|
rlimit nofile <= 1024, | syntax error, unexpected TOK_RLIMIT, expecting TOK_ID or TOK_MODE or TOK_SET_VAR |
set rlimit, | syntax error, unexpected TOK_END_OF_RULE, expecting TOK_ID |
set rlimit nofile 1024, | syntax error, unexpected TOK_VALUE, expecting TOK_LE |
set rlimit nproc < 10, | Lexer found unexpected character: '<' (0x3c) in state: RLIMIT_MODE |
set rlimit NOFILE <= 1024, | INVALID RLIMIT 'NOFILE' |
set rlimit nofile <= 1k, | RLIMIT 'nofile' invalid value 1 k |
set rlimit data <= 100m, | RLIMIT 'data' invalid value 100 m |
set rlimit cpu <= 500ms, | RLIMIT 'cpu 500' < minimum value of 1s |
set rlimit nice <= 20, | RLIMIT 'nice' out of range (-20 .. 19) 20 |
audit set rlimit nofile <= 1024, | syntax error, unexpected TOK_SET, expecting TOK_ID or TOK_MODE or TOK_SET_VAR |
audit { set rlimit nofile <= 1024, } | prefix not allowed on rlimit rules |
set rlimit cpu <= 60, with --warn=missing | warning RLIMIT 'cpu' no units specified using default units of seconds |
set rlimit rttime <= 60, with --warn=missing | warning RLIMIT 'rttime' no units specified using default units of microseconds |
All rows are from the tree's parser. The two warnings are off by default.
block_rules::add_rlimit (parser/block_rules.cc:38-131) sets rlimits.specified |= 1 << index and rlimits.limits[index] in struct aa_rlimits (parser/parser.h:166-181).sd_serialize_rlimits (parser/parser_interface.c:398-411) writes a struct rlimits with the u32 mask and an array of RLIM_NLIMITS u64 values, only when a limit is set.unpack_rlimits (linux:security/apparmor/policy_unpack.c:667-700) copies the mask and stores each value as rlim_max at aa_map_resource(i) (linux:security/apparmor/resource.c:83-86).opt_prefix (parser/parser_yacc.y:852-859); the scanner state is RLIMIT_MODE (parser/parser_lex.l:611-625).None of these is taught as intended behaviour; the verdicts come from the review.
set rlimit nice <= N stores N + 20; the kernel's scale for RLIMIT_NICE is 20 - nice (tree for the stored value, code for the kernel's scale).set rlimit data <= 9999999999G, exits 0), and a leading zero means octal (tree).linux:security/apparmor/policy_unpack.c:678-688), so rss, nproc, nofile, memlock and as would be tested against the wrong slot (code, not run).Conditionals are the name=value words after a rule's permissions. Without them the rule covers everything in its class.
NAME=VALUE or NAME=(VALUE ...), written after the permission list. The name is a word of letters, digits and _ that starts with a letter (parser_lex.l:296).capability, set rlimit, change_profile, link, file rules and all.signal, alone grants both permissions, for every signal and every peer (signal.cc:193-195).signal (send) set=(term, hup) peer=demo//worker, is line 18 of demo's profile. set=(term, hup) names the signals, peer=demo//worker the label of the other process.demo and its profile are invented for the map. Parser results were produced with the parser built from the AppArmor tree, with nothing loaded into a kernel.name=value, name=(a b), name in (a b) (mount), name:=value (network label) and the group peer=(name=value ...). Conditionals follow the permissions; the group comes last.
= are allowed (signal set = hup,). A line break between the name and = is not.signal Set=hup, gives invalid signal rule conditional "Set" (signal.cc:180).in needs parentheses: signal set in hup, is a syntax error.:= can only be written inside peer=( ).name=value, name=(a b), name in (a b), name:=value, peer=(name=value ...).:=.in.NONE, EQ, IN and SET (parser.h:119-124).cond productions: parser_yacc.y:1196-1259. opt_conds prepends each new entry, so the list is in reverse order of writing (parser_yacc.y:1261-1266).cond_list and opt_cond_list (parser_yacc.y:1268-1275).A bare value ends at a blank. name=(a b) or name=(a, b) gives several. Quote or escape blanks inside a value.
", !, or a , that is followed by one of those (parser_lex.l:262-267).( and ) also end a value and , is discarded (parser_lex.l:272-274, parser_lex.l:482). Test file: signal/ok_12.sd.unix addr=@a\ b, is accepted; with --warn=all it prints Character was quotedunnecessarily, dropped preceding quote ('\') character, and nothing by default.signal set=, gives Lexer found unexpected character: ',' (0x2c) in state: SUB_VALUE.signal peer=/bin/bash /bin/dash, is a conditional followed by a stray word (signal/bad_04.sd).signal peer=@{profile_name}, works, signal set=@{sigs}, gives unknown signal "@{sigs}".dbus, io_uring and unix rules refuse it (... only supports a single value). network rules (ip, port, interface, label), mqueue rules (type, label) and pivot_root (oldroot) take the first value and drop the rest without a message (parser_misc.c:1240-1249, network.cc:451-469).network inet port=(80 81), and network inet port=80, compile to byte-identical output (run with the tree's parser). A rule that reads as two ports is one port, also under deny.peer=( ... ) is a group in unix, dbus and network rules, written last and once. In signal and ptrace rules peer=LABEL is a plain conditional. mqueue and io_uring write label=LABEL.
network rules ip, port, label (interface is refused: interface cannot be set for peer in network rules, network.cc:497-498); unix rules addr, label; dbus rules name, label.peer is the group only when ( follows the =. signal peer=a, works; signal peer=(a), is a syntax error.unix peer=(), is accepted and equals no group.unix peer=(addr=@b) type=stream, gives unexpected TOK_CONDID, expecting TOK_END_OF_RULE; two groups give unexpected TOK_CONDLISTID, expecting TOK_END_OF_RULE.unix peer=(label=(a b)), is a syntax error.xattrs, valid only on the profile head: network rule: invalid conditional group xattrs=() and profile id: invalid conditional group peer=() (parser_yacc.y:436, parser_yacc.y:1160).(peer|xattrs) followed by = and ( returns TOK_CONDLISTID (parser_lex.l:420-427).: in names (parser_lex.l:524-549).in is accepted only by mount rules: "a subset of this list". := is accepted only for label inside peer=( ) of a network rule.
= and in (mount.cc:415-416); what the two mean for mount flags is in Mount rules.in: only "=" allowed in conditions of <class> rules for signal (signal.cc:169), ptrace, dbus, mqueue, io_uring and userns rules; unknown rule: operator used is not allowed in '%s' socket conditional for unix rules (af_rule.cc:51); unsupported operator used in conditions of network rules (network.cc:459).:= is accepted for label in the group of a network rule (network.cc:450-459); the field it fills is marked unused (network.h:144). Test file: network/skb/ok_setlabel_peer_1.sd.network inet peer=(ip:=1.2.3.4), gives the network message above. signal set:=hup, gives syntax error, unexpected TOK_ID, expecting TOK_CONDID or TOK_END_OF_RULE. Inside peer=( ) there is no in.label:= for network rules (apparmor.d.pod:224); the scanner cannot produce it outside the group.pivot_root oldroot in (/a/) /new/, is accepted, because that rule does not look at the operator (parser_yacc.y:1820-1831).Each rule class validates conditional names itself. An unknown name is an error that names the class and the conditional.
invalid ptrace rule conditional "set" (ptrace.cc:48), unix rule: invalid conditional 'set' (af_unix.cc:61) and unknown rule: 'label' conditional is only valid in the peer expression (the text at af_rule.cc:47, the prefix at af_rule.cc:66). All three are as printed by the tree's parser for ptrace set=hup,, unix set=hup, and unix label=demo-helper,.<class> conditional "peer" can only be specified once in most classes (parser_misc.c:1243-1245); signal set=hup set=int, accumulates instead.capability set=hup, gives syntax error, unexpected TOK_CONDID, expecting TOK_ID or TOK_END_OF_RULE and file fstype=ext4 /a r, gives syntax error, unexpected TOK_CONDID, expecting TOK_ID or TOK_MODE or TOK_SET_VAR. userns create foo=bar, fails in the scanner.type, protocol and label begin unknown rule: instead of unix rule: (af_rule.cc:66).attr= and opt= for unix rules and a local label; the parser has neither.pivot_root checks only the name of the last conditional written: pivot_root bogus=/b oldroot=/a/ /new/, is accepted.struct supported_cond (af_rule.h:32-38), with the tables at af_rule.cc:30-35 and af_unix.cc:48-51.move_conditionals.TOK_CONDID comes from scanner lookahead (parser_lex.l:437-453). The grammar builds a cond_entry list; each class's move_conditionals validates it.
INITIAL, MOUNT_MODE, DBUS_MODE, SIGNAL_MODE, PTRACE_MODE, UNIX_MODE, MQUEUE_MODE and NETWORK_MODE (parser_lex.l:419); the two lookahead rules are at parser_lex.l:437-453.{WS} is blanks only, which is why a newline before = defeats the lookahead (parser_lex.l:259).EXTCONDLIST_MODE, LIST_COND_MODE, LIST_COND_VAL, LIST_COND_PAREN_VAL (parser_lex.l:508-562).move_conditional_value takes the first value and frees the entry (parser_misc.c:1240-1249).term and hup are signals 15 and 1.:= scanner rules outside the group are unreachable (parser_lex.l:495-497);pivot_root ignores all but the last conditional written;USERNS_MODE is not in the state list above although userns.cc:31-43 validates conditionals.The group goes last; signal and ptrace take peer=LABEL without parentheses; only mount rules take in. if blocks are a different feature.
AppArmor parser error for FILE in profile FILE at line N: MESSAGE; the slide shows MESSAGE. Every message on the slide was produced by the tree's parser.socket rule at af_rule.cc:70).signal set, gives syntax error, unexpected TOK_ID, expecting TOK_CONDID or TOK_END_OF_RULE: without = after it, set is an ordinary word.if expression shares only the word "conditional": if EXPR { } else { }, with the operators ==, !=, in, >, >=, <, <=, defined, not, and, or (parser_yacc.y:862-1035, cond_expr.cc:29-161). Nothing of an if reaches the kernel.Conditionals narrow a rule; each rule class deck says what its names mean.
name=value, name=(a b), name in (a b) (mount rules), name:=value (the label in the group of a network rule), peer=(name=value ...) (unix, dbus and network rules).Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the line (-Q -K --skip-kernel-load --warn=all, feature set abi/5.0), with nothing loaded into a kernel; "code" means the parser source was read, not run. Conditionals have no kernel side of their own: a value becomes part of what the kernel matches for its rule class.
RULE: [QUALIFIERS] KEYWORD [PERMISSIONS] [CONDITIONAL ...] [peer=( CONDITIONAL ... )] ,
CONDITIONAL: NAME = VALUE
NAME = ( VALUE ... )
NAME in ( VALUE ... ) mount rules only
NAME := VALUE label inside peer=( ) of a network rule only
GROUP: peer = ( NAME=VALUE ... ) unix, dbus and network rules
NAME is a word of letters, digits and _ that starts with a letter (code). Names are case sensitive (tree).VALUE runs to a blank, a newline, ", !, or a , followed by one of those (code). Quote a value or escape a blank with \ to keep a blank inside it (tree).( and ) end a value. A list needs at least one value (tree).= are allowed; a line break between the name and = is not (tree).peer=LABEL is a plain conditional, not a group (tree).| Rule class | Plain conditionals | Inside peer=( ) | Operators |
|---|---|---|---|
capability | none | no group | - |
set rlimit | none | no group | - |
network | ip, port, interface, label | ip, port, label | =; label also := |
unix | type, addr (protocol is named but refused; label is refused outside the group) | addr, label | = |
dbus | bus, path, interface, member, name | name, label | = |
signal | set, peer | no group | = |
ptrace | peer | no group | = |
mqueue | type, label | no group | = |
io_uring | label | no group | = |
userns | none that can be written | no group | - |
mount, remount, umount | fstype, vfstype, options, option | no group | =, in |
pivot_root | oldroot | no group | not checked |
change_profile, link, file rules, all | none | no group | - |
| profile head | none | xattrs=( ) | = or a bare name |
The label of the other party is one idea with three spellings: peer=LABEL (signal, ptrace), label=LABEL (mqueue, io_uring) and peer=(label=LABEL) (unix, dbus, network).
| Operator | Accepted by | Meaning |
|---|---|---|
= | every class with conditionals | the value, or the list of values |
in | mount rules (options, fstype) | within this list; see syn-mount |
:= | label inside peer=( ) of a network rule | "set"; the parser marks the value unused (code) |
| bare name in a group | reaches the class and is refused, except in xattrs=( ) | - |
| Class | Conditional | A list name=(a b) |
|---|---|---|
signal | set | accepted: every value is a signal; repeated set= accumulate (tree) |
mount | options, fstype | accepted (tree) |
dbus | all | refused: dbus conditional "bus" only supports a single value (tree) |
io_uring | label | refused: io_uring conditional "label" only supports a single value (code) |
unix | type, addr, label | refused: ... conditional 'type' only supports a single value (tree) |
network | ip, port, interface, label | Known discrepancy: the first value is used, the rest dropped without a message (tree) |
mqueue | type, label | Known discrepancy: as for network (tree) |
pivot_root | oldroot | Known discrepancy: as for network (tree) |
Printed as AppArmor parser error for FILE in profile FILE at line N: MESSAGE. All rows are from the tree's parser unless marked (code).
| Rule | Message |
|---|---|
unix peer=(addr=@b) type=stream, | syntax error, unexpected TOK_CONDID, expecting TOK_END_OF_RULE |
unix peer=(addr=@a) peer=(addr=@b), | syntax error, unexpected TOK_CONDLISTID, expecting TOK_END_OF_RULE |
signal send peer=(label=demo//worker), | syntax error, unexpected TOK_CONDLISTID, expecting TOK_CONDID or TOK_END_OF_RULE |
signal set, | syntax error, unexpected TOK_ID, expecting TOK_CONDID or TOK_END_OF_RULE |
signal set=(), | syntax error, unexpected TOK_CLOSEPAREN, expecting TOK_VALUE |
signal set=, | Lexer found unexpected character: ',' (0x2c) in state: SUB_VALUE |
signal set=hup,int, | unknown signal "hup,int" |
signal Set=hup, | invalid signal rule conditional "Set" |
signal set in (hup, int), | only "=" allowed in conditions of signal rules |
ptrace peer in (a), | only "=" allowed in conditions of ptrace rules |
signal set:=hup, | syntax error, unexpected TOK_ID, expecting TOK_CONDID or TOK_END_OF_RULE |
network inet label:=foo, | Lexer found unexpected character: ':' (0x3a) in state: NETWORK_MODE |
network inet peer=(ip:=1.2.3.4), | unsupported operator used in conditions of network rules |
network inet xattrs=(a=b), | network rule: invalid conditional group xattrs=() |
profile t /bin/x peer=(a=b) { } | profile id: invalid conditional group peer=() |
dbus send bus=(session system), | dbus conditional "bus" only supports a single value |
dbus send bus=session label=unconfined, | dbus "label" conditional can only be used inside of the "peer=()" grouping |
unix type=stream type=dgram, | socket rule conditional "type" can only be specified once |
unix label=a, | unknown rule: 'label' conditional is only valid in the peer expression |
unix protocol=0, | unknown rule: 'protocol' conditional is not currently supported |
unix peer=(type=stream), | unknown rule: 'type' conditional is not allowed in the peer expression |
unix peer=(label=(a b)), | syntax error, unexpected TOK_VALUE, expecting TOK_CONDID or TOK_CLOSEPAREN |
| a unix rule with an unknown name | unix rule: invalid conditional 'NAME' |
| a ptrace rule with an unknown name | invalid ptrace rule conditional "NAME" |
capability set=hup, | syntax error, unexpected TOK_CONDID, expecting TOK_ID or TOK_END_OF_RULE |
file fstype=ext4 /a r, | syntax error, unexpected TOK_CONDID, expecting TOK_ID or TOK_MODE or TOK_SET_VAR |
pivot_root oldroot=/a/ bogus=/b /new/, | invalid pivotroot conditional 'bogus' |
None of these is a warning: a rule with a wrong conditional is refused and the profile is not compiled.
if EXPR { ... } else { ... } is evaluated while the profile is read; only the block of the first true branch is kept, and nothing of it reaches the kernel (code). Operators: ==, !=, in, >, >=, <, <=, defined, not, and, or. Its messages: Invalid boolean : '%s' is not true or false, Unset boolean variable %s used in if-expression, Error retrieving variable %s, Can only compare numbers with numbers, Value out of valid range (code). See syn-boolean-conditionals.xattrs=( ... ) on the profile head is the other group. See syn-xattrs.=, or by blanks and in (, returns TOK_CONDID (parser/parser_lex.l:437-453) in the states INITIAL, MOUNT_MODE, DBUS_MODE, SIGNAL_MODE, PTRACE_MODE, UNIX_MODE, MQUEUE_MODE, NETWORK_MODE (parser/parser_lex.l:419). (peer|xattrs)=( returns TOK_CONDLISTID (parser/parser_lex.l:420-427).EXTCOND_MODE, LIST_VAL_MODE (parser/parser_lex.l:462-505); group states EXTCONDLIST_MODE, LIST_COND_MODE, LIST_COND_VAL, LIST_COND_PAREN_VAL (parser/parser_lex.l:508-562).cond, opt_conds, cond_list (parser/parser_yacc.y:1196-1275) build a cond_entry list in reverse order, with the comparison kinds NONE, EQ, IN, SET (parser/parser.h:119-124).move_conditional_value moves the first value into the rule and frees the entry (parser/parser_misc.c:1240-1249).parser/signal.cc:162, parser/ptrace.cc:36, parser/dbus.cc:39, parser/mqueue.cc:69, parser/io_uring.cc:31, parser/af_unix.cc:53 and 84, parser/network.cc:445, parser/mount.cc:407-447, parser/parser_yacc.y:1820.Each was reproduced with the tree's parser; none is taught as intended behaviour.
name:=value cannot be written outside peer=( ), although the manual page lists a local label:= for network rules: network inet label:=foo, fails in the scanner, network inet peer=(label:=foo), is accepted.pivot_root validates only the last conditional written and ignores the rest: pivot_root bogus=/b oldroot=/a/ /new/, is accepted; pivot_root oldroot in (/a/) /new/, is accepted.network inet port=(80 81), compiles to the same bytes as network inet port=80,.unknown: unix label=a, gives unknown rule: 'label' conditional is only valid in the peer expression.An exec that changes profile can ask for secure-execution mode, in which the C library ignores variables such as LD_PRELOAD. Rules that ask are "safe"; rules that do not are "unsafe". The path /tmp/evil.so is only an illustration.
execve passes the caller's environment to the new program unchanged. AppArmor does not filter it; it can only mark the exec as secure.Px, Cx, Ux, or the keyword safe) asks for that mark when the exec changes profile. An unsafe rule (px, cx, ux, or unsafe) does not.Ux: AppArmor sets "ld.so(8) secure-execution mode" to "clear environment variables such as LD_PRELOAD, similar to setuid programs" (apparmor.d.pod:974-977).LD_PRELOAD is the usual example./tmp/evil.so on the slide is an illustration, not a file from either tree.LD_PRELOAD.Uppercase P, C, U = safe; lowercase = unsafe. safe and unsafe before a rule override the case. change_profile [safe|unsafe] EXEC -> TARGET, takes the same keywords.
[QUALIFIERS] [file] [safe|unsafe] PATH MODE [-> TARGET], or with the mode first: [QUALIFIERS] [file] [safe|unsafe] MODE PATH [-> TARGET],.change_profile [safe|unsafe] [EXEC PATH] [-> TARGET],.Px Cx Ux Pix Cix PUx CUx; unsafe px cx ux pix cix pux cux. ix has one form.UNCONFINED = 'U', UNSAFE_UNCONFINED = 'u', PROFILE = 'P', UNSAFE_PROFILE = 'p', LOCAL = 'C', UNSAFE_LOCAL = 'c' (parser.h:198-203).safe and unsafe are keywords of the profile language (parser_misc.c:92-93).file unsafe /usr/bin/demo-helper Px, and audit unsafe /usr/bin/demo-helper Px, are accepted; safe file /x Px, gives syntax error, unexpected TOK_FILE, expecting TOK_ID or TOK_MODE or TOK_SET_VAR; unsafe audit /x Px, gives syntax error, unexpected TOK_AUDIT, expecting TOK_ID or TOK_MODE or TOK_SET_VAR.opt_exec_mode is empty, TOK_UNSAFE or TOK_SAFE (parser_yacc.y:1065-1067); it is used by file_rule_tail (parser_yacc.y:1117-1130) and by change_profile (parser_yacc.y:1648).A safe exec sets AT_SECURE for the new program; ld.so then runs in secure-execution mode. Which variables are ignored is decided by the C library, not by AppArmor. Read from the kernel source; not observed on a running kernel.
All of this is read from the kernel source; none of it was observed on a running kernel.
bprm_creds_for_exec, implemented by apparmor_bprm_creds_for_exec. When the chosen rule is safe, profile_transition sets *secure_exec = true (domain.c:776-784).bprm->secureexec = 1 (domain.c:1070-1078).NEW_AUX_ENT(AT_SECURE, bprm->secureexec); (binfmt_elf.c:262).PER_CLEAR_ON_SETID personality bits to be cleared (domain.c:1080-1089).secureexec flag.bprm->secureexec, which reaches the new program as AT_SECURE (domain.c:1070-1078, binfmt_elf.c:262; read from the kernel source, not observed on a running kernel). What is ignored afterwards is the C library's decision, and the variables are still in the environment: code that reads the environment itself sees every one.AT_SECURE covers only what the C library ties to it. Open file descriptors are a separate mechanism: when the exec changes the label to a confined one, aa_inherit_files revalidates the inherited descriptors against the new label (file.c:721, called at lsm.c:967), whether the rule was safe or unsafe.PER_CLEAR_ON_SETID personality bits to be cleared (domain.c:1080-1089).ix, and an ix fallback, do not set the flag: the test is skipped when the new label is the profile's own (domain.c:730-739). A learning profile created in complain mode is always unsafe (domain.c:767).px, cx, pix, cix, pux and cux are the unsafe forms and print no warning; only lowercase ux does, and only on request.change_profile safe EXEC -> TARGET, compiled without stacking support prints "downgrading change_profile safe rule to unsafe" but the compiled rule is byte-identical to the rule with no keyword (run with the parser built from the AppArmor tree at 836052d21, nothing loaded into a kernel; parser_yacc.y:1663-1670). The warning describes what such a kernel does, not what the parser wrote.AA_X_UNSAFE in dfa_map_xindex (policy_compat.c:29-30). The test in profile_transition is !(perms.xindex & AA_X_UNSAFE).unsafe PATH Px, equals PATH px,; safe PATH px, equals PATH Px,. An exec that stays in the same profile (ix, or an ix fallback) does not set AT_SECURE. The table is worked out from the kernel source; it was not measured on a kernel.
unsafe /a Px, equals /a px,; safe /a px, equals /a Px,. Each pair merges without a conflict (the parser was run on the fragments).unsafe px /foo6,, unsafe Px /foo7, (front_perms_ok_2.sd); unsafe cx /bin/bar, (simple_ok_cx_1.sd).AT_SECURE is set, worked out from the kernel source and not measured:Px Cx Ux, a different profile or unconfined: set. px cx ux: not set.ix: not set, with or without a keyword.Pix Cix: set when a profile was found, not set after the ix fallback. PUx CUx: set in both cases.ix: when the result is the profile's own label, the kernel jumps past the test (domain.c:730-739); otherwise the test is at domain.c:776-784.unsafe /a ix, is accepted, but together with a plain /a ix, it fails with has merged rule /a with conflicting x modifiers, although the bit has no effect on an ix exec.unsafe sets the bit in each half that has exec, safe clears it (parser_yacc.y:1122-1127).change_profile [safe|unsafe] EXEC -> TARGET,. Without a keyword the change at exec is safe in the kernel. The keywords require the exec path. The full rule is in syn-change-profile.
change_profile [safe|unsafe] EXEC -> TARGET,. Tests: change_profile safe /usr/bin/bar, (safe_ok_2.sd); change_profile unsafe /usr/bin/bar -> unsafe,, where the word after -> is a target called unsafe (unsafe_ok_3.sd).change_profile safe /onexec -> /bin/foo, and change_profile /onexec -> /bin/foo, do not conflict (onx_no_conflict_safe1.sd).domain/stack is in the feature set the profile is compiled for (parser_main.c:1093-1095). Without it the parser only warns about an explicit safe; the compiled rule is the same as with no keyword (run with the parser built from the tree at 836052d21), and by the comment at parser_yacc.y:1663-1670 kernels without stacking support only the unsafe behaviour.int aa_change_onexec(const char *profile); (apparmor.h:81). It sends exec PROFILE as the task's exec attribute (kernel.c:1088-1107): through the lsm_set_self_attr syscall when available, else by writing /proc/<tid>/attr/apparmor/exec or the older /proc/<tid>/attr/exec (kernel.c:997-1012, kernel.c:424-426).aa_change_profile(args, AA_CHANGE_ONEXEC) (lsm.c:897-899). At the next exec profile_onexec sets the secure flag unless the rule's unsafe bit is set (domain.c:855-863).aa_change_profile()) involves no exec, so the keywords do not apply to it.aa_change_onexec.change_profile action: exec bits with an exec condition, the unsafe bits for unsafe, the downgrade warning (parser_yacc.y:1648-1675).safe and unsafe are keywords in the CHANGE_PROFILE_MODE state until -> (parser_lex.l:593-603).AA_EXEC_UNSAFE (parser/immunix.h) → AA_X_UNSAFE → *secure_exec in profile_transition (linux:security/apparmor/domain.c:776-784) → bprm->secureexec → AT_SECURE.
AA_EXEC_UNSAFE is 1 << 8 per half (immunix.h:43); ALL_AA_EXEC_UNSAFE covers both halves (immunix.h:91-92).parse_sub_perms: the lowercase cases set tperms = AA_EXEC_UNSAFE and fall through to the uppercase case (parser_misc.c:628-629, parser_misc.c:649-651).file_rule_tail: unsafe sets the bit in each half that has exec, safe clears it; a rule without exec gives "unsafe rule missing exec permissions" (parser_yacc.y:1117-1130).dfa_map_xindex maps 0x100 to AA_X_UNSAFE (policy_compat.c:29-30).profile_transition: the own-label case jumps to the audit step (domain.c:730-739); a learning profile forces AA_X_UNSAFE (domain.c:767); *secure_exec = true when the bit is clear (domain.c:776-784).profile_onexec has the same test for a change requested for exec (domain.c:855-863).apparmor_bprm_creds_for_exec: the local bool unsafe (domain.c:994) is passed as secure_exec to every profile of the label (domain.c:1032-1035) and becomes bprm->secureexec = 1 (domain.c:1070-1078).create_elf_tables: NEW_AUX_ENT(AT_SECURE, bprm->secureexec) (binfmt_elf.c:262)."unsafe rule missing exec permissions"; "Exec condition is required when unsafe or safe keywords are present"; px with Px on one path is "conflicting x modifiers". A downgrade of change_profile safe is a warning. All four were produced with the parser built from the tree.
Messages of the parser built from the AppArmor tree at 836052d21, nothing loaded into a kernel. Errors are printed as AppArmor parser error for FILE in profile FILE at line N: MESSAGE.
safe /etc/demo/demo.conf r,: unsafe rule missing exec permissions. The text is the same for both keywords.change_profile unsafe -> demo-helper,: Exec condition is required when unsafe or safe keywords are present (test unsafe_bad_2.sd).change_profile unsafe a -> b,: Exec condition must begin with '/'.Px and px for one path: profile demo: has merged rule PATH with conflicting x modifiers, with no line number, followed by ERROR merging rules for profile demo, failed to load.downgrading change_profile safe rule to unsafe due to lack of necessary kernel support: an explicit safe on change_profile when the feature domain/stack is missing (parser_main.c:1093-1095). Class rule-downgraded (parser_main.c:282). Printed for a file with no abi line, not printed with abi <abi/5.0>,.change_profile rule with no keyword is compiled the same way on such a feature set and prints nothing.ux warning is tied to the lowercase letter: unsafe /usr/bin/demo-helper Ux, has the effect of ux and prints nothing.change_profile errors: parser_yacc.y:1672-1675.Next: syn-exec-modes, syn-named-transitions, syn-change-profile, lib-change-profile, k-exec. Rule layout: syn-file-rules, syntax-map.
Px Cx Ux Pix Cix PUx CUx, or the keyword safe. Unsafe: the lowercase forms, or unsafe. The keyword overrides the case.AT_SECURE for the new program; ix and an ix fallback never do (source of the kernel, not observed on a running kernel).change_profile EXEC -> TARGET, is safe without a keyword when the feature domain/stack is available.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the fragment, with the tree's abi/5.0 file as the kernel features and nothing loaded into a kernel; "ran" means the researcher ran a parser on the fragment, as recorded in the findings; "code" means the kernel source of mainline Linux 7.4 (7.4-rc2, 97d73c825) or the parser source was read, not run. Nothing on this page was observed on a running kernel: every statement about AT_SECURE is derived from the kernel source.
FILE RULE: [QUALIFIERS] [file] [safe|unsafe] PATH MODE [-> TARGET] ,
[QUALIFIERS] [file] [safe|unsafe] MODE PATH [-> TARGET] ,
CHANGE PROFILE RULE: change_profile [safe|unsafe] [EXEC PATH] [-> TARGET] ,
MODE.change_profile the keyword needs EXEC PATH.| Safe | Unsafe | Mode |
|---|---|---|
Px | px | profile transition |
Cx | cx | child profile transition |
Ux | ux | unconfined |
Pix Cix | pix cix | transition, falling back to ix |
PUx CUx | pux cux | transition, falling back to ux |
| (none) | ix | inherit: one form only |
The modes themselves: syn-exec-modes. Targets: syn-named-transitions.
| Keyword | Position | Effect |
|---|---|---|
safe | after the qualifiers and after file; before the path or the mode | clears the unsafe bit of the rule: same as the uppercase letter |
unsafe | the same | sets the unsafe bit on the owner half and the other half where each has x: same as the lowercase letter |
unsafe /a Px, and /a px, merge without a conflict, and so do safe /a px, and /a Px, (ran).unsafe px /foo6,, unsafe Px /foo7, (parser/tst/simple_tests/file/front_perms_ok_2.sd), unsafe cx /bin/bar, (parser/tst/simple_tests/xtrans/simple_ok_cx_1.sd).file unsafe /usr/bin/demo-helper Px, and audit unsafe /usr/bin/demo-helper Px, are accepted (tree).-> in a change_profile rule the words are ordinary names: change_profile unsafe /usr/bin/bar -> unsafe, names a target called unsafe (parser/tst/simple_tests/change_profile/unsafe_ok_3.sd).Derived from linux:security/apparmor/domain.c (code); not measured on a kernel.
| Rule | Result of the exec | AT_SECURE |
|---|---|---|
Px Cx Ux | a different profile, or unconfined | set |
px cx ux | a different profile, or unconfined | not set |
ix | the same profile | not set, with or without a keyword |
Pix Cix | a profile was found | set |
Pix Cix | ix fallback | not set |
pix cix | either | not set |
PUx CUx | a profile was found, or ux fallback | set |
pux cux | either | not set |
change_profile EXEC -> TARGET, and a change requested for the next exec | the target | set |
change_profile unsafe EXEC -> TARGET, and the same request | the target | not set |
| no exec rule, profile in complain mode | a learning profile is created | not set |
| a stacked label | each profile decides for itself | set if the rule of any one profile asks |
aa_change_profile()) does not exec, and the keywords do not apply to it. See lib-change-profile.change_profile default: without a keyword the rule is safe when the feature domain/stack is in the feature set the profile is compiled for. Without that feature the parser only warns (parser/parser_yacc.y:1663-1670): the compiled rule is unchanged (tree: the -S output of change_profile safe X -> Y, equals that of change_profile X -> Y, and differs from unsafe). The comment there says kernels without stacking support only the unsafe behaviour.bprm->secureexec; the ELF loader copies it into the AT_SECURE entry of the new program's auxiliary vector (code).AT_SECURE; the manual describes the result as "ld.so(8) secure-execution mode" (parser/apparmor.d.pod:974-977). Which variables are ignored is the C library's list and is in neither tree; LD_PRELOAD is the usual example.PER_CLEAR_ON_SETID personality bits to be cleared (code: linux:security/apparmor/domain.c:1080-1089).Errors are printed as AppArmor parser error for FILE in profile FILE at line N: MESSAGE. The conflict comes from the later compile stage: it has no line number and is followed by ERROR merging rules for profile demo, failed to load.
| Message | Cause | Basis |
|---|---|---|
unsafe rule missing exec permissions | safe or unsafe on a file rule without x, such as safe /etc/demo/demo.conf r,; the text is the same for both keywords | tree |
Exec condition is required when unsafe or safe keywords are present | change_profile unsafe -> demo-helper, | tree |
Exec condition must begin with '/'. | change_profile unsafe a -> b, | tree |
profile demo: has merged rule PATH with conflicting x modifiers | Px and px (or any safe and unsafe pair) for one path | tree |
syntax error, unexpected TOK_FILE, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | safe file /x Px,: the keyword goes after file | tree |
syntax error, unexpected TOK_AUDIT, expecting TOK_ID or TOK_MODE or TOK_SET_VAR | unsafe audit /x Px,: the keyword goes after the qualifiers | tree |
warning downgrading change_profile safe rule to unsafe due to lack of necessary kernel support | an explicit safe on change_profile when the feature domain/stack is missing; class rule-downgraded | tree: printed for a file with no abi line, not printed with abi <abi/5.0>, |
warning Unconfined exec qualifier (ux) allows some dangerous environment variables to be passed to the unconfined process; 'man 5 apparmor.d' for details. | a lowercase ux; class dangerous, shown with --warn=dangerous or --warn=all | tree |
safe. A change_profile rule with no keyword compiles to the same bytes and prints nothing (tree).ux warning is tied to the lowercase letter. unsafe /usr/bin/demo-helper Ux, has the same effect as ux and prints nothing (tree); pux and cux print nothing either (code).unsafe /a ix, is accepted. By the kernel code the bit has no effect on an ix exec, yet the parser treats the rule as a different exec mode: together with a plain /a ix, it fails with has merged rule /a with conflicting x modifiers (tree).secureexec flag described above.| Step | Where |
|---|---|
mode letters: cod_t::PROFILE = 'P', UNSAFE_PROFILE = 'p', LOCAL = 'C', UNSAFE_LOCAL = 'c', UNCONFINED = 'U', UNSAFE_UNCONFINED = 'u' | parser/parser.h:198-203 |
AA_EXEC_UNSAFE (0x100 per half), ALL_AA_EXEC_UNSAFE, AA_EXEC_BITS | parser/immunix.h:43, 89-92 |
parse_sub_perms: the lowercase cases set tperms = AA_EXEC_UNSAFE and fall through; the ux warning | parser/parser_misc.c:628-632, 649-651 |
keywords safe, unsafe; opt_exec_mode | parser/parser_misc.c:92-93; parser/parser_yacc.y:1065-1067 |
file_rule_tail: the keyword sets or clears the bit; "missing exec permissions" | parser/parser_yacc.y:1117-1130 |
change_profile action: AA_EXEC_BITS with an exec condition, ALL_AA_EXEC_UNSAFE for unsafe, the downgrade warning, the two errors | parser/parser_yacc.y:1648-1675 |
lexer: safe and unsafe are keywords in CHANGE_PROFILE_MODE until -> | parser/parser_lex.l:593-603 |
features_supports_stacking from domain/stack | parser/parser_main.c:1093-1095 |
process_dfa_entry: the bits go on the pair rule exec condition, NUL, target | parser/parser_regex.c:767-775 |
kernel: dfa_map_xindex maps 0x100 to AA_X_UNSAFE | linux:security/apparmor/policy_compat.c:29-30 |
profile_transition: the own-label case jumps past the test | linux:security/apparmor/domain.c:730-739 |
profile_transition: a learning profile forces AA_X_UNSAFE | linux:security/apparmor/domain.c:767 |
profile_transition: *secure_exec = true when the bit is clear | linux:security/apparmor/domain.c:776-784 |
profile_onexec: the same test for a change requested for exec | linux:security/apparmor/domain.c:837-863 |
apparmor_bprm_creds_for_exec: the local unsafe holds "secure exec requested"; one flag for all profiles of the label; bprm->secureexec = 1; PER_CLEAR_ON_SETID | linux:security/apparmor/domain.c:994, 1032-1035, 1070-1089 |
create_elf_tables: NEW_AUX_ENT(AT_SECURE, bprm->secureexec) | linux:fs/binfmt_elf.c:262 |
parser/tst/simple_tests/file/front_perms_ok_2.sd, parser/tst/simple_tests/xtrans/, parser/tst/simple_tests/change_profile/ (safe_ok_*, unsafe_ok_*, safe_bad_*, unsafe_bad_*, onx_conflict_unsafe*, onx_no_conflict_safe*).signal (send) set=(term, hup) peer=demo//worker, lets a profile send two signals to tasks with one label.
task_kill; AppArmor's function is apparmor_task_kill (lsm.c:1023-1049, registered at lsm.c:1872)./sys/kernel/security/apparmor/features/signal/mask lists the signal names the kernel knows (apparmorfs.c:2591-2594).kill capability) still apply first. capability kill, is a separate rule: see capability rules.demo, its worker and their profiles are invented for the map.demo//worker comes from.[QUALIFIERS] signal [send|receive|(send, receive)] [set=SIG|set=(SIG ...)] [peer=LABEL],. Each part left out matches everything.
set may be repeated and the sets add up: signal send set=stp set=tstp, is accepted by the parser built from the tree. peer may be written once. Only = is accepted.audit, deny, allow, prompt and priority= are taken. owner is refused: owner prefix not allowed on signal rules (signal.h:51-57).abstractions/base on the slide: base:145-151.SIGNAL_MODE (parser_lex.l:658-695, parser_lex.l:884-885).Names are lower case without SIG. exists is signal 0. rtmin+N (0 to 32) counts from the kernel's SIGRTMIN (32), not the C library's.
hup int quit ill trap abrt bus fpe kill usr1 segv usr2 pipe alrm term stkflt chld cont stop stp tstp ttin ttou urg xcpu xfsz vtalrm prof winch io poll pwr sys emt exists. stp and tstp are one signal, and so are io and poll.set matches every signal, including exists.unknown signal "...": sigterm, TERM, HUP, 9, rtmax, cld, iot, lost, rtmin+33.rtmin+0 to rtmin+32 (signal.cc:129-134; test file rtsig_01.sd).SIGRTMAX it is unknown, from SIGRTMIN (32 in the kernel) it is 128 plus the offset, otherwise it comes from a table (ipc.c:21-30, sig_names.h:8-55). Signal 0, the existence test, is in that table (sig_names.h:9).lost and unused, for which the parser has no names. The log name for SIGTSTP is stp (sig_names.h:79).rtmin+2": C libraries reserve the first real-time signals for themselves, so the SIGRTMIN a program sees is higher than the kernel's.set=rtmin+ is accepted as rtmin+0 and set=rtmin+5x as rtmin+5 (signal.cc:129-134).A signal needs send in the sender's profile and receive in the target's profile. Either refusal gives EACCES.
aa_may_signal, ipc.c:102-116; profile_signal_perm, ipc.c:87-99).-EACCES (lib.c:440).:ns:name (label.c:1301-1309).requested_mask="send") and testcase_signal_02.in (requested_mask="receive").profile worker { all, }. This slide imagines a stricter worker.An unconfined target is not consulted. An unconfined sender is not consulted, but the target's profile still needs signal (receive) peer=unconfined,; abstractions/base has it.
profile_signal_perm returns 0 for an unconfined profile and for a profile that does not mediate the signal class (ipc.c:87-97). The receive check has no exception for an unconfined sender (ipc.c:114-115).abstractions/base, with their comments (base:143-151): "Allow unconfined processes to send us signals by default", "Allow us to signal ourselves", "Checking for PID existence is quite common so add it by default for now".peer=unconfined is a label pattern like any other.peer=unconfined. The base abstraction grants it.signal has no signal rules at all and the class is not mediated: both checks return 0 for it (ipc.c:93-95). This is derived, not run. The parser's warning signal rules not enforced is off by default.kill(pid, 0) is mediated as exists, so a confined task without that permission cannot probe for processes by signal. The base abstraction grants exists in both directions to every peer.operation="signal" requested_mask="send"|"receive" denied_mask=... signal=NAME peer="LABEL"; profile= is the side that refused.
requested_mask and denied_mask (send or receive), signal=NAME or signal=rtmin+N, peer= (ipc.c:52-76).operation="signal" profile=... pid=2531 comm=... requested_mask=... denied_mask=... signal=term peer=...), with demo's names. In both fixtures pid and comm are the sender's.signal=stp (sig_names.h:79).ALLOWED. A plain deny signal ... rule refuses without a record.signal=unknown(N) without a leading blank, glued to the previous field (ipc.c:66).signal.cc:288-351 emits \x0a[signals]peer; ipc.c:87-99 walks class, signal byte, label.
\x0a[\x01\x0f]demo//worker with 0x2 was printed by the parser built from the tree with -D rule-exprs for demo's line 18; (\x10\xa|\x0a.)[^\000]+ with 0x4 for signal receive,.find_signal_mapping: signal.cc:127-144. exists is 35 in the parser, and the kernel maps signal 0 to the same value (sig_names.h:9).gen_policy_re (signal.cc:288-351). audit uses the same bits as the audit mask (signal.cc:339-344).0x2, receive 0x4 (signal.h:29-31), shared with the short forms w and r of every IPC class (parser_misc.c:763-772).\d10 is added at priority 1001 (parser_regex.c:1409-1411).signal (signal.cc:300-303, parser_main.c:1087-1089).map_signal_num (ipc.c:21-30), profile_signal_perm (ipc.c:87-99), xcheck_labels in aa_may_signal (ipc.c:102-116).\x10\x0a alternative. The only reader of the label class start in the kernel is the ptrace path.Lower-case names without SIG, lists in parentheses, peer=LABEL without parentheses. The parser cannot see a missing rule in the peer's profile.
-Q -K --skip-kernel-load --warn=all, nothing loaded into a kernel). The full form is AppArmor parser error for FILE in profile FILE at line N: MESSAGE.invalid signal rule conditional "%s" (signal.cc:180). Names are case sensitive: Set is refused.signal conditional "peer" can only be specified once (parser_misc.c:1244).perms contains invalid permission for signals (signal.cc:192).signal set=@{sigs}, gives unknown signal "@{sigs}": variables are not expanded in signal names.peer=/bin/bash /bin/dash fails (bad_04.sd).signal rules not enforced (signal.cc:285) is printed when the feature set has no signal; it needs --warn=rule-not-enforced.Both profiles are asked: the same holds for ptrace and unix rules.
send in the sender's profile and receive in the target's profile; either refusal is EACCES.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the line (-Q -K --skip-kernel-load --warn=all, feature set abi/5.0), with nothing loaded into a kernel; "code" means the source was read, not run. Every statement about the kernel is read from the kernel source.
SIGNAL RULE: [QUALIFIERS] signal [PERMISSIONS] [set=SIGNAL | set=( SIGNAL ... )] ... [peer=LABEL] ,
PERMISSIONS: send | receive | ( send [,] receive )
write and w are send; read and r are receive; rw is both
SIGNAL: a name from the table below | rtmin+N (N from 0 to 32)
set means every signal, exists included. No peer means any peer (tree).set may be repeated and the sets add up; peer is written once and without parentheses (tree).| Name | Signal | Internal number |
|---|---|---|
hup | SIGHUP | 1 |
int | SIGINT | 2 |
quit | SIGQUIT | 3 |
ill | SIGILL | 4 |
trap | SIGTRAP | 5 |
abrt | SIGABRT | 6 |
bus | SIGBUS | 7 |
fpe | SIGFPE | 8 |
kill | SIGKILL | 9 |
usr1 | SIGUSR1 | 10 |
segv | SIGSEGV | 11 |
usr2 | SIGUSR2 | 12 |
pipe | SIGPIPE | 13 |
alrm | SIGALRM | 14 |
term | SIGTERM | 15 |
stkflt | SIGSTKFLT | 16 |
chld | SIGCHLD | 17 |
cont | SIGCONT | 18 |
stop | SIGSTOP | 19 |
stp, tstp | SIGTSTP | 20 |
ttin | SIGTTIN | 21 |
ttou | SIGTTOU | 22 |
urg | SIGURG | 23 |
xcpu | SIGXCPU | 24 |
xfsz | SIGXFSZ | 25 |
vtalrm | SIGVTALRM | 26 |
prof | SIGPROF | 27 |
winch | SIGWINCH | 28 |
io, poll | SIGIO, SIGPOLL | 29 |
pwr | SIGPWR | 30 |
sys | SIGSYS | 31 |
emt | SIGEMT | 32 |
exists | signal 0, the existence test of kill(pid, 0) | 35 |
rtmin+0 to rtmin+32 | real-time signals, counted from the kernel's SIGRTMIN (32) | 128 to 160 |
The internal numbers are the parser's (signal.cc:42-78); they are not the signal numbers of any architecture.
| Sender | Target | Checks |
|---|---|---|
| confined | confined | send in every profile of the sender toward the target's label, and receive in every profile of the target toward the sender's label |
| confined | unconfined | send in the sender's profile with a peer that matches unconfined |
| unconfined | confined | receive in the target's profile with a peer that matches unconfined |
a profile compiled without signal rules for a feature set that lacks signal | any | none for that profile (by the code) |
A peer in another namespace is matched as :ns:name. A refusal is EACCES.
| Seat | On a signal rule |
|---|---|
priority= | taken |
audit | taken |
allow, deny, prompt | taken |
owner, other | refused: owner prefix not allowed on signal rules |
# Allow unconfined processes to send us signals by default
signal (receive) peer=unconfined,
# Allow us to signal ourselves
signal peer=@{profile_name},
# Checking for PID existence is quite common so add it by default for now
signal (receive, send) set=("exists"),
Source: base:143-151.
apparmor="DENIED" operation="signal" profile=... pid=... comm=... requested_mask="send" denied_mask="send" signal=term peer=...
| Field | Meaning |
|---|---|
profile | the profile that refused |
requested_mask, denied_mask | send (the sender's profile refused) or receive (the target's profile refused) |
signal | the name as written in rules; rtmin+N for real-time signals; stp for SIGTSTP |
peer | the label of the other task |
| Line | Message |
|---|---|
signal send set=sigterm, | unknown signal "sigterm" |
signal send set=TERM, | unknown signal "TERM" |
signal send set=9, | unknown signal "9" |
signal send set=hup,int, | unknown signal "hup,int" |
signal send peer=(label=demo//worker), | syntax error, unexpected TOK_CONDLISTID, expecting TOK_CONDID or TOK_END_OF_RULE |
signal send set in (hup, int), | only "=" allowed in conditions of signal rules |
owner signal, | owner prefix not allowed on signal rules |
signal Set=hup, | invalid signal rule conditional "Set" |
signal peer=a peer=b, | signal conditional "peer" can only be specified once |
feature set without signal (warning, off by default) | signal rules not enforced |
\x0a (10), a character class with the internal number of each signal in the set, the peer pattern (signal.cc:288-351).set the signal byte is .; the form printed for signal receive, is (\x10\xa|\x0a.)[^\000]+, with a second alternative under the label class (tree).0x2, receive 0x4 (signal.h:29-31). Class marker \d10 at priority 1001 (parser_regex.c:1409-1411).map_signal_num (ipc.c:21-30), profile_signal_perm (ipc.c:87-99), aa_may_signal (ipc.c:102-116).set=rtmin+ is accepted as rtmin+0, and set=rtmin+5x as rtmin+5 (tree; signal.cc:129-134).signal=unknown(N) without a leading blank (code; ipc.c:66).umount MOUNTPOINT, allows unmounting. A mount rule for the same path does not.
sb_umount (lsm.c:760-772, registered at lsm.c:1793), called for umount(2) and umount2(2)./sys/kernel/security/apparmor/features/mount/mask reads mount umount pivot_root.capability sys_admin, the call fails with EPERM before AppArmor's check of the rule is reached (namespace.c:2082).umount /run/demo/, is line 16 of demo's profile; it compiles with no warning (run with the tree's parser). The program demo and its profile are invented for the map.AA_MAY_UMOUNT (0x4), separate from AA_MAY_MOUNT (0x2) (mount.h:21-22).[QUALIFIERS] umount [MOUNTPOINT],. unmount is the same keyword. No arrow.
umount and unmount, are one keyword.umount "/", (ok_quoted_1.sd), umount @{HOME}/**/, (fusermount3:28). The plain form is umount /foo, (ok_23.sd).audit, allow, deny, prompt and priority= are taken; owner and other are refused with owner prefix not allowed on mount rules (run with the tree's parser). audit deny umount /boot/, and unmount /run/demo/, are accepted (run with the tree's parser).syntax error, unexpected TOK_ARROW, expecting TOK_END_OF_RULE (run with the tree's parser).fstype= and options= are accepted; see the scene "Only the path is compared".TOK_UMOUNT opt_conds opt_id TOK_END_OF_RULE calls do_mnt_rule($2, NULL, NULL, $3, AA_MAY_UMOUNT) (parser_yacc.y:1292-1295). The keyword table: parser_misc.c:111-112. The scanner state MOUNT_MODE: parser_lex.l:876-879.Write the mount point with a trailing /. umount /mnt/{,**/}, covers /mnt/ and every directory below it.
/ (mount.c:214-221, mount.c:544-576). A mount on a regular file (a bind mount of a file) is named without the slash.name="/mnt/a/" (testcase_umount_01.in); it was not run.umount, compiles to "any name" (run with the tree's parser)./run/demo/** does not match /run/demo/ itself. umount /mnt/{,**/}, is used in the tree (fusermount3:29).An umount rule matches the mount point only. Lazy and forced unmounts, the filesystem type and the mount flags are not compared.
aa_umount receives the umount flags (MNT_FORCE, MNT_DETACH, MNT_EXPIRE, UMOUNT_NOFOLLOW) and does not use them (mount.c:578-599). profile_umount matches the name of the mount point and checks AA_MAY_UMOUNT (mount.c:544-576).umount accepts options= and fstype= and ignores them": umount options=ro fstype=ext4 /a, compiles to the same rule as umount /a, (run with the tree's parser). The grammar summary of apparmor.d(5) lists mount conditions for umount (apparmor.d.pod:252).umount foo=bar /a, gives invalid mount conditional foo, then bad mount rule.umount fstype=tmpfs /run/**/,) allows unmounting anything mounted on a matching path.operation="umount" class="mount" name="/run/demo/". The name is the mount point as the rule must write it.
apparmor="DENIED" operation="umount" class="mount" profile="/home/user/test/testmount" name="/mnt/a/" pid=26697 comm="testmount") with demo's values, which are illustrative.info, fstype, srcname or flags field because none of those is compared. The error is EACCES (lib.c:440).mount does not mediate the class, and AppArmor does not check unmounts for it. The parser then drops the rule; its warning mount rules not enforce is in the class rule-not-enforced, which is off by default.deny umount refuses without a log record; audit deny logs. In complain mode the record is ALLOWED.mount: mount.cc:782. The check: profile_umount, mount.c:544-576.mount.cc:1155-1166 writes \x07 + mount point with AA_MAY_UMOUNT (0x4); profile_umount (mount.c:544-576) reads the permission after the name.
-D rule-exprs): umount /run/demo/, gives \x07/run/demo/ with 0x4; umount /a, gives \x07/a; umount, gives \x07[^\000]*; umount /run/demo/{,**/}, gives \x07/run/demo/(|[^\x00]*/).gen_policy_re: mount.cc:1155-1166. The generators for the kinds of mount call all test perms & AA_MAY_MOUNT (mount.cc:1089-1123).profile_umount: mount.c:544-576.all, shows the merged value 0x7 on the mount, umount and pivot_root strings; its separate remount string has 0x2 (run with the tree's parser).\d7 is added at priority 1001 (parser_regex.c:1403-1405).End the mount point with /. No arrow, no owner.
AppArmor parser error for FILE in profile FILE at line N: MESSAGE; the slide shows MESSAGE. Rows 2, 3 and 4 were run with the tree's parser; row 4 is followed by bad mount rule.umount options=(rw, ro) /a, gives conflicting flag values = 1, 1, then conflicting flags in the rule, and umount options=bogus /a, gives unsupported mount option value 'bogus': the conditionals are checked although an umount rule does not use them.Umount rules name mount points. Mount, remount and pivot_root rules are the same class.
[QUALIFIERS] umount [MOUNTPOINT],; unmount is the same keyword. Without a path the rule covers every mount point./.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the line (-Q -K --skip-kernel-load --warn=all, -D rule-exprs for compiled forms), with nothing loaded into a kernel; "code" means the parser source or the kernel source was read, not run. Nothing here was observed on a running kernel.
UMOUNT RULE: [QUALIFIERS] ( umount | unmount ) [MOUNTPOINT] , QUALIFIERS: [priority=N] [audit] [allow|deny|prompt]
umount and unmount are one keyword (code).| Seat | On an umount rule |
|---|---|
priority= | taken |
audit | taken |
allow, deny, prompt | taken: deny is not logged; prompt is in syn-prompt |
owner, other | refused: owner prefix not allowed on mount rules (tree) |
| Rule | Covers |
|---|---|
umount, | every mount point (tree) |
umount /a/, | a mount on the directory /a |
umount /a/{,**/}, | /a/ and every directory below it |
umount /a/**, | what is below /a/, not /a/ itself |
umount /a, | a mount on a regular file /a; not a directory |
The last four rows follow from the kernel's naming of mount points (linux:security/apparmor/mount.c:214-221) and the globbing rules (code); they were not run on a kernel.
| Compared | Not compared |
|---|---|
the name of the mount point; a directory ends in / | the umount2 flags (MNT_FORCE, MNT_DETACH, MNT_EXPIRE, UMOUNT_NOFOLLOW) |
| the filesystem type | |
| the mount flags | |
| what is mounted (the source) |
Read from linux:security/apparmor/mount.c:544-599 (code).
| Field | Meaning |
|---|---|
operation="umount" | the unmount |
class="mount" | always |
profile= | the profile that refused |
name= | the mount point as compared, with its trailing / |
A record from the tree (libraries/libapparmor/testsuite/test_multi/testcase_umount_01.in):
apparmor="DENIED" operation="umount" class="mount" profile="/home/user/test/testmount" name="/mnt/a/" pid=26697 comm="testmount"
A refused unmount returns EACCES.
| Rule | Message |
|---|---|
umount /run/demo/ -> /mnt/, | syntax error, unexpected TOK_ARROW, expecting TOK_END_OF_RULE |
owner umount /run/demo/, | owner prefix not allowed on mount rules |
umount foo=bar /run/demo/, | invalid mount conditional foo then bad mount rule |
umount options=(rw, ro) /a, | conflicting flag values = 1, 1 then conflicting flags in the rule |
umount options=bogus /a, | unsupported mount option value 'bogus' |
umount /run/demo, | none; the rule does not match a directory |
any umount rule, no mount in the feature set, --warn=rule-not-enforced | warning mount rules not enforce |
Rows with an error message are from the tree's parser.
TOK_UMOUNT opt_conds opt_id TOK_END_OF_RULE calls do_mnt_rule($2, NULL, NULL, $3, AA_MAY_UMOUNT) (parser/parser_yacc.y:1292-1295). The class is mnt_rule, shared with mount, remount and pivot_root.AA_MAY_UMOUNT 0x4 (parser/mount.cc:1155-1166). umount /run/demo/, is \x07/run/demo/ (tree).parser/rule.h:540-554, parser/mount.cc:688-714).sb_umount (linux:security/apparmor/lsm.c:760-772) calls aa_umount, which calls profile_umount for each profile of the label (linux:security/apparmor/mount.c:544-599): build the name, match it from start[AA_CLASS_MOUNT], test AA_MAY_UMOUNT.None of these is taught as intended behaviour. All are on the bug list as confirmed; see Known bugs.
umount options=ro fstype=ext4 /a, compiles to the same rule as umount /a,: the conditionals are accepted and not used, while apparmor.d(5) lists them in the grammar of umount (tree).unix PERMISSIONS type=T addr=A peer=(addr=A label=L), mediates unix sockets by the local socket and by the peer's address and label.
network_v9/af_unix: the file /sys/kernel/security/apparmor/features/network_v9/af_unix (net.c:24-36).unix (send receive) type=stream, (glycin.loaders:16), unix (receive, send) type=stream peer=(label=dovecot), (usr.lib.dovecot.anvil:23), unix (accept, bind, listen, receive, send) type=stream addr="@/tmp/.X11-unix/X[0-9]*", (Xorg:65).demo, its helper and their profiles are invented for the map.network unix rule.[QUALIFIERS] unix [PERMISSIONS] [type=T] [addr=A] [peer=(addr=A label=L)],. Conditionals come before the peer group.
audit, deny, allow, prompt and priority= are taken (network rules take fewer). owner is refused: owner prefix not allowed on unix rules (af_unix.h:52-61).type=: one value, on the local side only. Names: stream, dgram, seqpacket. Also accepted, and matching nothing on Linux: none, raw, rdm, dccp, packet (network.cc:66-93).protocol= is named and refused: 'protocol' conditional is not currently supported.unix stream, is refused by the parser built from the tree: syntax error, unexpected TOK_ID, expecting TOK_END_OF_RULE.addr, in the peer addr and in the peer label (af_rule.cc:161-171, af_unix.cc:166-181).unix addr=@SomeService,), ok_msg_7.sd (unix (send) addr=none,).unix_rule: TOK_UNIX opt_net_perm opt_conds opt_cond_list TOK_END_OF_RULE (parser_yacc.y:1418-1432).UNIX_MODE shares the permission tokens with NETWORK_MODE (parser_lex.l:627-679, parser_lex.l:890-892).type, protocol, label) and af_unix.cc:48-51 (addr). The constructor: af_unix.cc:127-147.addr=@name (abstract, a pattern), addr=none (unnamed), addr=auto (autobind). A socket bound to a path needs a file rule for the path; addr=/path is an error.
unix addr=none,, unix addr=auto,, unix addr=@foo*,, unix addr=@,, unix addr="@a b",, unix (connect) peer=(addr=none),. A rule without addr matches any address and no address (af_unix.cc:65-71, af_unix.cc:257-290).match_addr, af_unix.c:63-83).unix_fs_perm instead, which checks the profile's file rules for the socket's path with the request reduced to the file permissions in NET_FS_PERMS (af_unix.c:34-61, af_unix.c:240-243, af_unix.c:302-305, net.h:41-45). bind to a path returns at once in the unix code because the file hooks handle it (af_unix.c:269-271).rw on the slide is illustrative, and so are /run/demo.sock and the autobind name @00a3f (five characters from [0-9a-f], af_unix.cc:39-40).addr surfaces late and without a line number: unix addr=@foo[, gives Regex grouping error: Unclosed grouping or character class, expecting close }, Unable to parse input line 'foo[', ERROR processing policydb rules for profile demo, failed to load and ERROR generating policy re for profile demo, failed to load; the exit status is 255. addr=none, a path, or "@name" (net.c:80-115).create bind listen setopt getopt getattr setattr shutdown look at the local socket. send receive connect accept can also be limited by peer=(addr= label=).
unix socket 'create', 'shutdown', 'setattr', 'getattr', 'bind', 'listen', 'setopt', and/or 'getopt' accesses cannot be used with peer socket conditionals (af_unix.cc:138-139). Test file: bad_bind_1.sd.unix label=a, gives unknown rule: 'label' conditional is only valid in the peer expression (af_rule.cc:76-80).unix peer=(label=unconfined), and unix peer=(label=@{profile_name}), are accepted by the parser built from the tree.todo: local label matching (af_unix.c:97-98).attr= and opt= conditionals; the parser has none of them. See known bugs.A unix stream connection needs connect send receive in the connecting profile and accept send receive in the listener's, each toward the other's label. Datagrams need send in the sender and receive in the receiver.
unix_stream_connect and unix_may_send (lsm.c:1189-1256). For a connection the kernel requests connect send receive from the connecting label toward the listener's label and accept send receive from the listener's label toward the connecting one; both checks run and either refusal fails the call (lsm.c:1127-1149). For a datagram the sender needs send and the receiving socket's label receive (lsm.c:1235-1256).EACCES.operation="connect" class="net" profile=... family="unix" sock_type="stream" protocol=0 requested="send receive connect" denied="send receive connect" addr=none peer_addr="@test_abstract_socket" peer=...), turned to the listener's side with demo's values. The words send receive accept and their order follow from the request the kernel builds for the listener and the order of its name table (net.c:38-78). addr=, peer_addr=, peer= (net.c:80-166). Real records: testcase_unix_01.in to testcase_unix_03.in in the same directory.info=: failed local address match, failed local label match, failed cmd selection match, failed peer address match, failed peer label match, failed listen backlog match, failed sockopt match (af_unix.c:100-102, af_unix.c:150, af_unix.c:167, af_unix.c:188, af_unix.c:313, af_unix.c:379).socketpair labels both ends and links them (lsm.c:1328-1357).network_v9/af_unix.A network rule covering AF_UNIX also creates a unix rule; a unix rule also creates network unix TYPE. Kernels with fine-grained unix mediation use the unix rules; others use the network rule. deny unix rules are not downgraded: there they are dropped.
RULE_MEDIATES_UNIX, policy.h:360-363) and falls back to the family and type check otherwise (af_unix.c:212-223).network unix, generates six unix rules, one per type name (stream, dgram, seqpacket, rdm, raw, packet); unix, is one rule for any type. Seen with the parser built from the tree.deny unix rule is not turned into a network rule "because the downgrade makes the rule less specific" (af_unix.cc:204-229). With a feature set that has family and type only, deny unix (connect) type=stream peer=(addr=@foo), compiles to the same output as an empty profile.downgrading extended network unix socket rule to generic network rule (af_unix.cc:537), extended network unix socket rules not enforced (af_unix.cc:184-187), deny unix socket rule not enforced, can't be downgraded to generic network rule (af_unix.cc:227). Turn them on with --warn=rule-downgraded --warn=rule-not-enforced.network (send, receive) unix stream, rule.network rule is built from the socket type only and gets every permission (parser_yacc.y:762-777, af_unix.cc:105-125). network (create) unix stream, therefore compiles a generic rule with create and unix rules that allow bind, listen, accept, connect, send, receive, getopt and setopt on abstract and unnamed stream sockets toward any peer. The unix rules are the ones the kernel consults.network (create), and any network (...) rule without a family, since they include unix. With deny, deny network (bind) unix, denies every unix operation.deny unix rules are dropped when the kernel lacks fine-grained unix mediation, even where the downgrade would be exact": the drop also covers deny rules without an address, label or peer conditional (deny unix,, deny unix type=stream,), whose downgrade to deny network unix would be exact; network, deny unix, then allows every unix socket operation and prints nothing by default (af_unix.cc:204-229). Seen with the parser built from the tree and a feature set without fine-grained unix mediation.deny unix socket rule not enforced ... is printed also when the rule is compiled.\x0f\x00\x01\x00\x01 with send and receive (0x6), printed by the parser built from the tree with -D rule-exprs.af_unix.cc:516-666 emits the chain; af_unix.c in the kernel walks it per hook, with command bytes 1 (peer), 2 (listen), 4 (options).
AF_UNIX (2 bytes), type (2 bytes or ..), protocol (..). 1: create, the prefix. 2: bind without addr or with addr=auto: prefix, \x00, label pattern, \x00 (af_unix.cc:558-584). 3: shutdown setattr getattr bind accept: prefix, address, \x00, label pattern, \x00. 4: listen: rule 3 plus \x02 and .. (the backlog). 5: getopt setopt: rule 3 plus \x04 and .. (the option name). 6: send receive connect accept: rule 3 plus \x01, peer address, \x00, peer label pattern.none is the byte 0x01; auto is a zero byte and five [0-9a-f]; absent is .* (af_unix.cc:257-290).network_v9, else 14 with network_v8, else 4. The source calls the middle case wrong and keeps it for compatibility (af_unix.cc:233-245).-D rule-exprs for demo's line 12 under abi/5.0.-EINVAL (af_unix.c:478-487). The label slot on the local side is a null transition in the kernel.audit unix (getopt), marks both option bits as audited at that position (af_unix.cc:631-637).type= is required for the type; no path in addr=; label only inside peer=( ); the group last; no attr= or opt=; no owner.
-Q -K --skip-kernel-load --warn=all, nothing loaded into a kernel). The full form is AppArmor parser error for FILE in profile FILE at line N: MESSAGE.unix type=bogus,: socket rule: invalid socket type 'bogus'.unix type=stream type=dgram,: socket rule conditional "type" can only be specified once.unix type=(stream dgram),: unknown rule: conditional 'type' only supports a single value.unix peer=(type=stream),: unknown rule: 'type' conditional is not allowed in the peer expression.unix addr=@x addr=@y,: unix socket conditional "addr" can only be specified once.unix protocol=0,: unknown rule: 'protocol' conditional is not currently supported.perms contains invalid permissions for unix socket rules (af_unix.cc:137).unix send type in (dgram, stream),), bad_peer_1.sd (unix send peer(addr=wat),), bad_attr_3.sd (unix setattr peer=(label=orange),).unknown rule: prefix comes from a literal rule name passed for the shared conditionals (af_rule.cc:66).attr=, opt= and a local label (apparmor.d.pod:367, apparmor.d.pod:375-377); the parser has none of them. See known bugs.Abstract and unnamed unix sockets: this deck. Sockets with a path: file rules. Messages on the bus: D-Bus rules.
connect send receive in the connecting profile and accept send receive in the listener's.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the line (-Q -K --skip-kernel-load --warn=all, feature set abi/5.0 unless another is named), with nothing loaded into a kernel; "code" means the source was read, not run. Every statement about the kernel is read from the kernel source.
UNIX RULE: [QUALIFIERS] unix [PERMISSIONS] [type=TYPE] [addr=ADDRESS] [peer=( [addr=ADDRESS] [label=LABEL] )] ,
PERMISSIONS: PERMISSION | ( PERMISSION [,] ... )
PERMISSION: create bind listen accept connect shutdown getattr setattr getopt setopt send receive
send is also write or w; receive is also read or r; rw is both
TYPE: stream | dgram | seqpacket
ADDRESS: @PATTERN | none | auto
unix, allows every operation on unix sockets with an abstract address or no address (tree).| Conditional | Side | Value | Notes |
|---|---|---|---|
type | local | one of stream, dgram, seqpacket | one value; also accepted and matching nothing on Linux: none, raw, rdm, dccp, packet |
addr | local, or inside the group | @pattern, none, auto | absent: any address or none; a path is an error |
label | inside the group only | a pattern for the peer's profile name | unconfined and variables are accepted |
protocol | - | - | named and refused |
attr, opt, a local label | - | - | in apparmor.d(5), not in the parser (known discrepancy) |
| Permission | Looks at | Kernel entry point |
|---|---|---|
create | family, type, protocol | aa_unix_create_perm |
bind | the address being bound | aa_unix_bind_perm |
listen | local address, backlog | aa_unix_listen_perm |
accept | local address; with a group, the peer too | aa_unix_accept_perm, aa_unix_peer_perm |
getopt, setopt | local address, option name | aa_unix_opt_perm |
getattr, setattr, shutdown | local address | aa_unix_sock_perm |
send, receive, connect | local address, peer address, peer label | aa_unix_peer_perm |
| Operation | Asked of the caller's profile | Asked of the other end's profile |
|---|---|---|
| stream connect | connect send receive toward the listener | accept send receive toward the caller (not for a listener with a file name) |
| datagram send | send toward the receiver | receive toward the sender |
| Kind | In a rule | In the log | Mediated by |
|---|---|---|---|
| abstract | addr=@name (a pattern) | addr="@name" | the unix rule |
| unnamed | addr=none | addr=none | the unix rule |
| autobind | addr=auto | addr="@xxxxx", five hex digits | the unix rule |
| file name | not written in addr | the path | the file rule for the path |
| Seat | On a unix rule |
|---|---|
priority= | taken |
audit | taken |
allow, deny, prompt | taken |
owner, other | refused: owner prefix not allowed on unix rules |
| You write | The parser adds | Used by |
|---|---|---|
network unix TYPE, (or any network rule that covers unix) | a unix rule for that type | kernels with fine-grained unix mediation |
unix ... type=TYPE ..., | network PERMISSIONS unix TYPE, | kernels with family and type only |
deny unix ..., | nothing | - |
| Warning (off by default) | Option |
|---|---|
downgrading extended network unix socket rule to generic network rule | --warn=rule-downgraded |
extended network unix socket rules not enforced | --warn=rule-not-enforced |
deny unix socket rule not enforced, can't be downgraded to generic network rule | --warn=rule-not-enforced |
apparmor="DENIED" operation="connect" class="net" profile=... pid=... comm=... family="unix" sock_type="stream" protocol=0 requested="..." denied="..." addr=... peer_addr=... peer=...
profile= is the profile that refused; peer= is the label of the other end.info= reasons: failed local address match, failed local label match, failed cmd selection match, failed peer address match, failed peer label match, failed listen backlog match, failed sockopt match.EACCES, or EINVAL for a malformed address.| Line | Message |
|---|---|
unix stream, | syntax error, unexpected TOK_ID, expecting TOK_END_OF_RULE |
unix addr=/run/demo.sock, | unix rule: invalid value for addr='/run/demo.sock' |
unix label=a, | unknown rule: 'label' conditional is only valid in the peer expression |
unix (send) peer=(label=a) type=stream, | syntax error, unexpected TOK_CONDID, expecting TOK_END_OF_RULE |
unix type=stream attr=foo, | unix rule: invalid conditional 'attr' |
owner unix, | owner prefix not allowed on unix rules |
unix (bind) peer=(addr=@demo), | unix socket 'create', 'shutdown', 'setattr', 'getattr', 'bind', 'listen', 'setopt', and/or 'getopt' accesses cannot be used with peer socket conditionals |
unix type=bogus, | socket rule: invalid socket type 'bogus' |
unix type=stream type=dgram, | socket rule conditional "type" can only be specified once |
unix type=(stream dgram), | unknown rule: conditional 'type' only supports a single value |
unix peer=(type=stream), | unknown rule: 'type' conditional is not allowed in the peer expression |
unix addr=@x addr=@y, | unix socket conditional "addr" can only be specified once |
unix protocol=0, | unknown rule: 'protocol' conditional is not currently supported |
unix addr=@foo[, | Regex grouping error: Unclosed grouping or character class, expecting close }, then Unable to parse input line 'foo[', ERROR processing policydb rules for profile t, failed to load and ERROR generating policy re for profile t, failed to load (no line number; exit status 255) |
Prefix: class byte (15 with network_v9, else 14 with network_v8, else 4), AF_UNIX in two bytes, the type in two bytes or .., the protocol as .. (af_unix.cc:231-255).
| Rule | Permissions | Match string after the prefix |
|---|---|---|
| 1 | create | nothing |
| 2 | bind without addr or with addr=auto | \x00, label pattern, \x00 |
| 3 | shutdown setattr getattr bind accept | address, \x00, label pattern, \x00 |
| 4 | listen | rule 3, \x02, .. (backlog) |
| 5 | getopt setopt | rule 3, \x04, .. (option name) |
| 6 | send receive connect accept | rule 3, \x01, peer address, \x00, peer label pattern |
none is byte 0x01; auto is a zero byte and five [0-9a-f]; absent is .* (af_unix.cc:257-290).profile_peer_perm (af_unix.c:389-426).-D rule-exprs): \x0f\x00\x01\x00\x01...*\x00[^\000]*\x00\x01.*\x00demo-helper with 0x6.network (PERMISSIONS) unix gets every permission (tree, mainline feature set; parser_yacc.y:762-777, af_unix.cc:105-125).audit unix (getopt), marks both option bits as audited (code; af_unix.cc:631-637).deny unix rules are dropped when the kernel lacks fine-grained unix mediation, even where the downgrade would be exact: deny unix, and deny unix type=stream, have no address, label or peer conditional and could be written as deny network unix, but are dropped like the others; network, deny unix, then allows every unix socket operation and prints nothing by default (tree, feature set without fine-grained unix mediation; af_unix.cc:204-229).deny unix socket rule not enforced ... is printed also when the rule is compiled (tree; af_unix.cc:204-229).type, protocol and label begin unknown rule: (af_rule.cc:66).attr=, opt= and a local label that the parser does not have (apparmor.d.pod:367).userns create, (or just userns,) lets a confined task create a user namespace.
userns_create (lsm.c:1051-1071, registered at lsm.c:1873). It is called from create_user_ns (user_namespace.c:122), which unshare(CLONE_NEWUSER) and clone(CLONE_NEWUSER) reach. It is the hook's only call site./sys/kernel/security/apparmor/features/namespaces/mask, which reads userns_create (apparmorfs.c:2658).user.max_user_namespaces, is separate from AppArmor.userns create, is line 21 of demo's profile; it compiles with no warning (run with the tree's parser). The program demo and its profile are invented for the map.max_user_namespaces.[QUALIFIERS] userns [create],. No parentheses, no conditionals.
create; a rule without the word means the same.audit, allow, deny, prompt and priority= are accepted (run with the tree's parser); owner and other are refused: owner userns, gives owner prefix not allowed on userns rules.userns (create), gives Lexer found unexpected character: '(' (0x28) in state: USERNS_MODE (run with the tree's parser).userns_rule productions: parser_yacc.y:1527-1539. The permission create is 0x8 (userns.h:24-25); no word means the same (userns.cc:54-56); the owner refusal: userns.h:35-41.USERNS_MODE (parser_lex.l:896-897) is not in the state lists that produce (, TOK_CONDID or TOK_ID (parser_lex.l:419, parser_lex.l:669, parser_lex.l:690); its one word is create (parser_lex.l:636-638).userns cannot take a permission list or a conditional; the grammar and checks for them are unreachable": the grammar and the rule class have code for a parenthesised permission list and for conditionals (parser_yacc.y:1515-1535, userns.cc:31-44), but the scanner state for this keyword produces neither, so userns (create), and userns peer=foo, end in a scanner error. The example files bad_userns_02.sd and bad_userns_03.sd fail for that reason.With a feature set that lists namespaces/mask/userns_create, every confined profile denies user namespace creation unless it has userns,.
namespaces/mask/userns_create. The feature set is that of the profile's abi rule. A profile without an abi rule is compiled for the parser's built-in default (unless a feature set is pinned with --policy-features), which does not list the feature, so it is in the left column on every kernel (run with the tree's parser: the warning is missing feature abi, falling back to default policy feature abi). In both cases a feature the running kernel lacks is left out as well; see feature ABI.userns_create is listed by abi/4.0, abi/4.0-ip, abi/5.0 and abi/5.0-interface, and not by abi/3.0 or the kernel-5.4 files.abi <abi/3.0>, with userns, prints Warning from profile demo (...): userns rules not enforced; the warning class rule-not-enforced is off by default. The kernel is then told nothing about the class and does not check that profile (task.c:389-391).create permission.abi rule: parser_yacc.y:353-361. The kernel's permission is AA_USERNS_CREATE (8, task.h:112).The kernel checks every confined profile of the label; unconfined labels are skipped. Restricting unconfined tasks is an Ubuntu addition: see Upstream and Ubuntu.
if (!unconfined(label)) (lsm.c:1063). For each profile of the label, aa_profile_ns_perm skips an unconfined profile (task.c:384), returns 0 when the class is not mediated (task.c:389-391), and otherwise checks the permission.kernel.apparmor_restrict_unprivileged_userns* are not in security/apparmor/ of the kernel tree read for this map. The sysctls that do exist nearby are kernel.unprivileged_userns_apparmor_policy (lsm.c:2454: whether a root user inside a user namespace may load policy) and kernel.apparmor_restrict_unprivileged_unconfined (lsm.c:2469).info="Userns create - transitioning profile" profile="unconfined" ... target="unprivileged_userns") is from a kernel with the Ubuntu addition.operation="userns_create" class="namespace" requested="userns_create" denied="userns_create"; the call returns EACCES.
apparmor="DENIED" operation="userns_create" class="namespace" profile="/usr/bin/userns_child_exec" pid=1785 comm="userns_child_ex" requested="userns_create" denied="userns_create") with demo's values, which are illustrative.requested= and denied= come from the audit callback of this class, which can also add execpath= (task.c:353-372). The error is EACCES (lib.c:440).ALLOWED. audit userns, logs each allowed creation. audit deny userns, compiles (run with the tree's parser).userns.cc:101-133 writes \x15 with 0x8 and a marker at the rule's priority; parser_regex.c:1392-1394 adds \d21 at the minimum priority to every profile; task.c:374-399 reads the state.
-D rule-exprs): userns, gives \x15 with 0x8 and \x15 with 0x4 at the rule's priority, plus \d21 with 0x4 at priority -1001; priority=3 userns, puts the first two at priority 3; audit deny userns, gives a deny of 0x8 on \x15 and the marker \x15 0x4.AA_CLASS_NS is 21 (policydb.h:45).perms_onclass_mediates_priority = MIN_INTERNAL_PRIORITY: parser_regex.c:1374-1383. The generic marker is added when the feature is supported, before the mode test that exempts unconfined and default_allow profiles from the other markers (parser_regex.c:1392-1397). io_uring uses the same scheme inside that test (parser_regex.c:1450-1452).aa_profile_ns_perm (task.c:374-399).default_allow profile is packed as unconfined mode (profile.h:75-79), so aa_profile_ns_perm skips it (task.c:384) and its \d21 marker is not read. Read from the code, not run.The check is skipped for unconfined labels and for profiles whose feature set lacks userns_create. The rule covers creation only: not setns, not what happens inside.
TODO: add flag to complain about unmediated (task.c:389-391).userns_create is silent by default. Run with the tree's parser under abi <abi/3.0>,, both userns create, and deny userns, give the warning userns rules not enforced and no entry for class 21.abi <abi/3.0>,, or with no abi rule at all, cannot deny user namespace creation; deny userns, there compiles to nothing.userns, and broad capability rules (or all,) gives the task those capabilities inside its own namespace, which is where much kernel attack surface for unprivileged users starts; see User namespaces and AppArmor.setns into an existing user namespace is not covered by this hook.Only userns, and userns create, exist. Use --warn=rule-not-enforced to see a dropped rule.
AppArmor parser error for FILE in profile FILE at line N: MESSAGE; the slide shows MESSAGE. All five rows were run with the tree's parser. The warning of row 5 is printed as Warning from profile demo (FILE): userns rules not enforced.userns create foo=bar, also fails in the scanner, and so does any other word: userns read, gives Lexer found unexpected character: 'r' (0x72) in state: USERNS_MODE.--warn=.perms contains invalid permissions for userns, only "=" allowed in conditions of userns rules and invalid userns rule conditional "%s" (userns.cc:38-51).userns, allows creating a user namespace. Why it matters: User namespaces and AppArmor.
[QUALIFIERS] userns [create],: one permission, no conditionals.EACCES, logged as operation="userns_create", when its profile was compiled for a feature set that lists userns_create.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the line (-Q -K --skip-kernel-load --warn=all, -D rule-exprs for compiled forms), with nothing loaded into a kernel; "code" means the parser source or the kernel source was read, not run. Nothing here was observed on a running kernel.
USERNS RULE: [QUALIFIERS] userns [create] , QUALIFIERS: [priority=N] [audit] [allow|deny|prompt]
create is the only permission; userns, and userns create, are the same rule (tree).userns (create),), a conditional (userns peer=foo,), a second word (tree).| Seat | On a userns rule |
|---|---|
priority= | taken |
audit | taken |
allow, deny, prompt | taken: deny is not logged; prompt is in syn-prompt |
owner, other | refused: owner prefix not allowed on userns rules (tree) |
| The task | Checked by AppArmor | Result | Source |
|---|---|---|---|
| unconfined label | no | allowed | linux:security/apparmor/lsm.c:1063 |
confined, feature set without userns_create | no | allowed, with or without a rule, also with deny userns, | linux:security/apparmor/task.c:389-391 |
confined, profile without an abi rule | no | allowed, with or without a rule | the built-in default lacks userns_create (tree) |
confined, feature set with userns_create, no rule | yes | EACCES | linux:security/apparmor/task.c:392-395 |
confined, with userns, | yes | allowed | the same |
confined, with deny userns, | yes | EACCES, not logged | the same |
| a stack of profiles | each confined profile | allowed only if every one allows it | linux:security/apparmor/lsm.c:1063-1066 |
All rows are read from the kernel source (code), except where marked.
| Feature set | Lists namespaces/mask/userns_create |
|---|---|
no abi rule (built-in default) | no |
abi/3.0 | no |
abi/kernel-5.4-vanilla, abi/kernel-5.4-outoftree-network | no |
abi/4.0, abi/4.0-ip | yes |
abi/5.0, abi/5.0-interface | yes |
Without the feature the rule is dropped; --warn=rule-not-enforced prints userns rules not enforced (tree). See syn-abi and adm-features.
setns into an existing user namespace (code).| Field | Meaning |
|---|---|
operation="userns_create" | the creation |
class="namespace" | always |
profile= | the profile that refused |
requested=, denied= | userns_create |
A record from the tree (libraries/libapparmor/testsuite/test_multi/testcase_userns_01.in):
apparmor="DENIED" operation="userns_create" class="namespace" profile="/usr/bin/userns_child_exec" pid=1785 comm="userns_child_ex" requested="userns_create" denied="userns_create"
testcase_userns_02.in in the same directory is from a kernel with the Ubuntu addition. A refused creation returns EACCES.
| Rule | Message |
|---|---|
userns (create), | Lexer found unexpected character: '(' (0x28) in state: USERNS_MODE |
userns read, | Lexer found unexpected character: 'r' (0x72) in state: USERNS_MODE |
userns peer=foo, | Lexer found unexpected character: 'p' (0x70) in state: USERNS_MODE |
userns create create, | syntax error, unexpected TOK_CREATE, expecting TOK_CONDID or TOK_END_OF_RULE |
owner userns, | owner prefix not allowed on userns rules |
userns, under abi <abi/3.0>, | warning userns rules not enforced (class rule-not-enforced, off by default) |
| none (unreachable) | perms contains invalid permissions for userns |
| none (unreachable) | only "=" allowed in conditions of userns rules |
| none (unreachable) | invalid userns rule conditional "%s" |
Rows with a rule are from the tree's parser; the unreachable messages are read from the parser source (code).
AA_CLASS_NS 21 (parser/policydb.h:45); permission create 0x8 (parser/userns.h:24-25).\x15 with 0x8 and a marker \x15 0x4 at the rule's priority (parser/userns.cc:101-133). The generic marker \d21 0x4 goes to every profile at the minimum priority (parser/parser_regex.c:1374-1394), because a top-priority marker on the class state would hide the permission.apparmor_userns_create (linux:security/apparmor/lsm.c:1051-1071) calls aa_profile_ns_perm for each profile of a confined label (linux:security/apparmor/task.c:374-399); the permission is AA_USERNS_CREATE 8 (linux:security/apparmor/include/task.h:112).None of these is taught as intended behaviour. All are on the bug list as confirmed; see Known bugs.
bad_userns_02.sd and bad_userns_03.sd fail in the scanner for that reason (code, tree).Not run on a kernel.
= declares a new variable and is an error for an existing one. +=, ?= and := say what to do with an existing name.
= creates the variable and is an error if the name exists.include <tunables/global> on line 1 and @{HOMEDIRS} = /srv/nfs/home/ on line 2. Output: '@{HOMEDIRS}' is already defined, then AppArmor parser error for /work/va-home.sd in profile /work/va-home.sd at line 3: variable @{HOMEDIRS} was previously declared, exit status 1.@{APP_DATA} = /var/lib/demo, then @{APP_DATA} = /srv/demo) prints '@{APP_DATA}' is already defined and variable @{APP_DATA} was previously declared, exit status 1 (run with the tree's parser for this deck).@{HOMEDIRS}=/home/ in home, which tunables/global includes. The shipped tunables files use only =.@{FOO}=foo then @{FOO}=bar (vars_reassignment_1.sd, expected to fail).global_symtab.add_var(); on failure yyerror("variable %s was previously declared") (parser_yacc.y:539-545).'%s' is already defined, is printed by add_var itself (symtab.cc:30-36).VARIABLE ( = | += | ?= | := ) ... to the end of the line. Booleans take =, ?= and :=.
= declares, += adds values to an existing set, ?= declares unless the name is declared, := replaces.=, ?= and :=. ${NAME} += ... is the error Invalid assignment += not allowed with boolean variables.assign_op (parser_yacc.y:519-522).TOK_EQUALS, TOK_ADD_ASSIGN (\+=), TOK_COND_ASSIGN (\?=), TOK_OVERRIDE_ASSIGN (:=) (parser_lex.l:308-310, parser_lex.l:824-832).varassign: TOK_SET_VAR assign_op valuelist (parser_yacc.y:524-548) and varassign: TOK_BOOL_VAR assign_op expr (parser_yacc.y:550-570).= creates, += adds to the set, ?= creates if the name is free, := replaces.
-D variables:@APP_DATA = "/var/lib/demo";@APP_DATA = "/srv/demo" "/var/lib/demo";@CACHE = "/var/cache/demo";@LOGS = "/var/log/demo";@LOGS = "/srv/log/demo", @CACHE = "/var/cache/demo", @APP_DATA = "/srv/demo" "/var/lib/demo".${DEMO_DEBUG} = false and ${DEMO_DEBUG} := true; its dump has the three rows above and $DEMO_DEBUG = true, exit status 0, nothing on standard error.owner @{APP_DATA}/** rw, prints aare: {/srv/demo,/var/lib/demo}/** with -D rule-exprs (run with the tree's parser for this deck).@{A} = /a /b then @{A} += /c gives @A = "/a" "/b" "/c" and the rule {/a,/b,/c}/x; @{C} = /c1 then @{C} := /c2 /c3 gives @C = "/c2" "/c3".?= then += (vars_simple_assignment_combination_1.sd, expected to pass); = then := (vars_simple_assignment_20.sd, expected to pass).add_var(), add_set_value(), and delete_var() followed by add_var() (parser_yacc.y:527-545, symtab.cc:25-112).The owner uses =, a site file +=, a default ?=, an override :=. Order matters.
#@{HOMEDIRS}+=/srv/nfs/home/ /mnt/home/.@{HOMEDIRS} += /srv/nfs/home/ was put in a file of its own and included with include if exists after tunables/global; it stands in for a file in tunables/home.d/. The rule audit deny @{HOME}/.ssh/** rw, then prints aare: {/home/*,/root,/srv/nfs/home/*}/.ssh/**, exit status 0.?= on a name that is declared leaves the value alone: @{FOO}=foo then @{FOO} ?=bar (vars_simple_assignment_16.sd, expected to pass). Recorded in the research notes: @{B} ?= /first then @{B} ?= /second leaves @B = "/first", exit status 0.?= on a declared variable prints '@{NAME}' is already defined.?= must come after the assignment it yields to. A = after ?= or := has created the variable is the "previously declared" error (vars_bad_assign_after_cond_1.sd, vars_bad_assign_after_over_1.sd, both expected to fail).:= also changes the kind of a variable. ${A} = true then @{A} := /a prints @A = "/a". Whether that is intended was not determined.= in one site file is met before a += in another, so do not make two files of one directory depend on each other.Booleans take =, ?= and :=. += is Invalid assignment += not allowed with boolean variables.
-D variables dump prints $DEMO_DEBUG = true (run with the tree's parser for this deck). With ${DEMO_DEBUG} = false alone the dump prints $DEMO_DEBUG = false.${DEMO_DEBUG} += true in full, run with the tree's parser for this deck: AppArmor parser error for /work/va-boolplus.sd in profile /work/va-boolplus.sd at line 3: Invalid assignment += not allowed with boolean variables, exit status 1. The assignment is on line 2.${DEBUG} = true then @{DEBUG} = /var/log/debug, run with the tree's parser for this deck: '@{DEBUG}' is already defined, then ... at line 3: variable @{DEBUG} was previously declared, exit status 1.$VAR = True then $VAR ?= False (boolean_cond_2.sd, expected to pass); $VAR := False (boolean_over_1.sd, expected to pass).+= on a boolean reports that the variable was not declared. This is the set-variable form: ${A} = true then @{A} += /a prints Variable A is not a set variable and then variable @{A} was not previously declared, but is being assigned additional values (recorded in the research notes).+=: parser_yacc.y:553-567.add_var for a boolean: symtab.cc:42-45.parser_yacc.y:519-570: = and ?= call add_var, += calls add_set_value, := calls delete_var then add_var.
assign_op yields one of four token values (parser_yacc.y:519-522). The action of varassign: TOK_SET_VAR assign_op valuelist switches on it (parser_yacc.y:524-548); the boolean production is at parser_yacc.y:550-570.add_var prints '%s' is already defined itself, whatever the caller (symtab.cc:30-36).add_set_value (symtab.cc:90-101) prints Failed to find declaration for: NAME for an unknown name.delete_var: symtab.cc:103-112.?= on a declared variable prints '@{NAME}' is already defined.+= on a boolean reports that the variable was not declared.+= and := let any later preamble text change what every rule written with a shipped variable means..d directory: see include if exists.-D variables, not the shipped assignment.= needs a free name, += needs an existing set. The reported line can be the one after the assignment.
'@{APP_DATA}' is already defined, then ... at line 3: variable @{APP_DATA} was previously declared. The second assignment is on line 2.Failed to find declaration for: APP_DATA, then ... at line 2: variable @{APP_DATA} was not previously declared, but is being assigned additional values. The assignment is on line 1.'@{CACHE}' is already defined, then ... at line 3: variable @{CACHE} was previously declared. The second assignment is on line 2. The parser's own test of this case is vars_bad_assign_after_cond_1.sd.+= on a boolean, ... at line 3: Invalid assignment += not allowed with boolean variables for an assignment on line 2 (run with the tree's parser for this deck; see the scene "Booleans: three of the four").... at line 2: Variable declarations do not accept trailing commas, for a += line on line 2 (run with the tree's parser for this deck). This message comes from the scanner and names the line itself; it is shown in variables.Assignment fills the table of variables; expansion and conditional blocks use it.
= declares and fails if the name exists. += adds to an existing set. ?= declares unless the name is declared. := replaces.=, ?= and :=.-D variables prints the final table.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run on the fragment (-Q -K --skip-kernel-load, with the tree's abi/5.0 as kernel feature set and the dump option named), with nothing loaded into a kernel; "code" means the parser source was read and not run; "derived" means the result was reasoned from that code. Nothing here was observed on a running kernel.
assignment: VARIABLE OP REST up to the end of the line, no comma
VARIABLE: @{NAME} | ${NAME}
OP: = | += | ?= | :=
REST: VALUE ... for @{NAME}
EXPRESSION for ${NAME}
| Operator | Token | Meaning |
|---|---|---|
= | TOK_EQUALS | declare: create the variable; an error if the name exists |
+= | TOK_ADD_ASSIGN | add: add values to a set that exists; an error if it does not |
?= | TOK_COND_ASSIGN | declare unless declared: assign only if the name is free |
:= | TOK_OVERRIDE_ASSIGN | replace: assign, replacing any variable of that name |
| Operator | The name is free | The name is a set | The name is a boolean |
|---|---|---|---|
@{N} = v | created (tree) | variable @{N} was previously declared (tree) | variable @{N} was previously declared (tree) |
@{N} += v | variable @{N} was not previously declared, but is being assigned additional values (tree) | the values are added (tree) | see the known discrepancies |
@{N} ?= v | created (tree) | the value is kept (tree) | not run |
@{N} := v | created (code) | replaced (tree) | replaced by a set (tree; intent not determined) |
${N} = e | created (tree) | not run | variable %s was previously declared (code) |
${N} += e | Invalid assignment += not allowed with boolean variables (code) | the same message (code) | the same message (tree) |
${N} ?= e | created (code) | not run | the value is kept (tree) |
${N} := e | created (code) | replaced by a boolean (tree; intent not determined) | replaced (tree) |
@{APP_DATA} = /var/lib/demo
@{APP_DATA} += /srv/demo
@{CACHE} ?= /var/cache/demo
@{LOGS} = /var/log/demo
@{LOGS} := /srv/log/demo
${DEMO_DEBUG} = false
${DEMO_DEBUG} := true
profile demo /usr/bin/demo {
owner @{APP_DATA}/** rw,
}
-D variables prints $DEMO_DEBUG = true, @LOGS = "/srv/log/demo", @CACHE = "/var/cache/demo", @APP_DATA = "/srv/demo" "/var/lib/demo"; exit status 0; nothing on standard error (tree).-D rule-exprs prints aare: {/srv/demo,/var/lib/demo}/** for the rule (tree).| Who | Operator | Example |
|---|---|---|
| the file that owns the variable | = | @{HOMEDIRS}=/home/ in tunables/home |
| a site file | += | @{HOMEDIRS} += /srv/nfs/home/ in tunables/home.d/site.local |
| a profile that offers a default | ?= | @{CACHE} ?= /var/cache/demo |
| a profile that overrides | := | @{LOGS} := /srv/log/demo |
+= works only after the declaration. ?= is a default only if it comes after the assignment it yields to (code).tunables/global, @{HOME}/.ssh/** compiles as {/home/*,/root,/srv/nfs/home/*}/.ssh/** (tree; the line was included through an include if exists of its own, standing in for a file in tunables/home.d/).| Message | First line printed before it | Cause | Reported line | Basis |
|---|---|---|---|---|
variable @{N} was previously declared | '@{N}' is already defined | = on a name that exists, also after ?= or := created it | the line of the next token | tree |
variable @{N} was not previously declared, but is being assigned additional values | Failed to find declaration for: N | += on a name that does not exist | the line of the next token | tree |
Invalid assignment += not allowed with boolean variables | none | += on ${N} | the line of the next token | tree |
Variable declarations do not accept trailing commas | none | a comma at the end of the line | the line itself | tree |
+= and := let any later preamble text change what every rule written with a shipped variable means. The later text can come from a .d directory: see include if exists.-D variables prints the final table.assign_op (parser_yacc.y:519-522); the scanner rules (parser_lex.l:308-310, parser_lex.l:824-832).varassign: TOK_SET_VAR assign_op valuelist (parser_yacc.y:524-548); varassign: TOK_BOOL_VAR assign_op expr (parser_yacc.y:550-570).add_var (symtab.cc:25-76), add_set_value (symtab.cc:90-101), delete_var (symtab.cc:103-112).= in one site file is met before a += in another.?= on a declared variable prints '@{NAME}' is already defined. Run: @{B} ?= /first then @{B} ?= /second leaves @B = "/first", prints '@{B}' is already defined, exit status 0.+= on a boolean reports that the variable was not declared. Run: ${A} = true then @{A} += /a prints Variable A is not a set variable and then ... at line 3: variable @{A} was not previously declared, but is being assigned additional values.:= changing the kind of a variable is intended. Run: ${A} = true then @{A} := /a prints @A = "/a"; @{S} = /s then ${S} := false prints $S = false.@{APP_DATA} = /var/lib/demo /srv/demo names two directories. A rule that uses the variable is compiled for both.
@{APP_DATA} = /var/lib/demo /srv/demo. The rule is its line 10: owner @{APP_DATA}/{cache,state}/** rwk,.-Q -K --skip-kernel-load -D rule-exprs): aare: {/srv/demo,/var/lib/demo}/{cache,state}/** -> (/srv/demo|/var/lib/demo)/(cache|state)/[^/\x00][^\x00]*. The slide shows the text left of the arrow.@{...} covers a logged path.demo, its files and its profile are invented for the map.process_profile_variables (parser_variable.c:137-179).variable::expand_by_alternation (variable.cc:252-340).@{NAME} = value value ... up to the end of the line. Names are case sensitive; values may be quoted.
@{NAME}. The name is a letter followed by letters, digits and underscores, and it is case sensitive: @{Case} and @{case} are two variables (run with the tree's parser for this deck: -D variables prints @case = "/lower" and @Case = "/upper").VARIABLE = '@{' ALPHA [ ( ALPHANUMERIC | '_' ) ... ] '}' (apparmor.d.pod:112)."" is the empty value.@{LIBVIRT} = "libvirt," (vars_simple_assignment_13.sd, expected to pass).Variable declarations do not accept trailing commas.@{APP_DATA} = /var/lib/demo \ followed by /srv/demo # two places gives @APP_DATA = "/srv/demo" "/var/lib/demo", exit status 0.@NAME without braces in an assignment, and it is the same variable as @{NAME}.@NAME without braces is accepted in a rule and compiled as literal text. Recorded in the research notes: @NOBRACE = /nb and the rule @NOBRACE/x r, print aare: @NOBRACE/x, exit status 0.VARIABLE_NAME [[:alpha:]][[:alnum:]_]* and SET_VARIABLE @(\{VARIABLE_NAME\}|VARIABLE_NAME) (parser_lex.l:296-298).ASSIGN_MODE until the end of the line (parser_lex.l:564-590, parser_lex.l:824-832): each word or quoted string is one TOK_VALUE, \ at the end of a line continues the list, a comma is the error.varassign: TOK_SET_VAR assign_op valuelist (parser_yacc.y:524-548).@{HOME}/.ssh/** becomes {/home/*,/root}/.ssh/**: the values joined as an alternation, with slashes trimmed at the joint.
audit deny @{HOME}/.ssh/** rw,.-D variables, which prints the table as written: @HOME = "/root/" "@{HOMEDIRS}/*/" and @HOMEDIRS = "/home/". Both variables come from the shipped file tunables/home: see abstractions and tunables.-D expanded-variables: @HOME = "/home//*/" "/root/".aare: line of -D rule-exprs: {/home/*,/root}/.ssh/**. All three dumps were run with the tree's parser for this deck./home//*/ is what the dump prints. The compiled rule has /home/*: file rule paths pass through a filter that turns repeated slashes into one./, leading slashes of each value are trimmed; when the text after it begins with /, trailing slashes are trimmed. Recorded in the research notes: /srv/@{HOME}/x r, compiles as /srv/{home/*,root}/x.@{b} = @{A}/fwd before @{A} = /a is accepted (recorded in the research notes).tunables/global included, @{PROC}/sys/ r, prints aare: /proc/sys/. The shipped value is @{PROC}=/proc/./, so the rule starts with // and never matches.variable::expand_by_alternation (variable.cc:252-340); the trimming is at lines 288-295 and 310-322.expand_variable resolves nested references and keeps the result in expanded (variable.cc:342-404).filter_slashes.Values are stored as a set: no duplicates, and printed in text order. "" is the empty value.
@{D} = "with space" plain with /q/@{D} r, prints aare: /q/{plain,with space}; @{E} = "" with /e/@{E}/x r, prints aare: /e/x.-D variables prints @APP_DATA = "/srv/demo" "/var/lib/demo" for it (run with the tree's parser for this deck). The whole dump has 85 lines, because tunables/global defines the rest.@{DUP} = /a /a /b prints @DUP = "/a" "/b", and @{DUP}/x r, compiles as {/a,/b}/x (run with the tree's parser for this deck).-D variables prints the table as written (@HOME = "/root/" "@{HOMEDIRS}/*/"), -D expanded-variables after expansion (@HOME = "/home//*/" "/root/"). Both print names as @NAME without braces, and boolean variables as $NAME = true.@{A} = /a, is the error Variable declarations do not accept trailing commas.std::set<std::string> (variable.h:35): no duplicates, ordered as strings.Variables are expanded in the paths, names and labels of most rule classes and in the profile head, once per profile after parsing.
tunables/global included, and compile with exit status 0. The dump shows {/srv/demo,/var/lib/demo}/**, {/srv/demo,/var/lib/demo}/current and {/srv/demo,/var/lib/demo}/releases/*, demo//worker, {/run,/var/run}/demo/ and /org/demo/ followed by the alternation of digit patterns that @{pid} stands for.attach_disconnected.path and attach_disconnected.ipc values; file rule paths and link targets; mount point, device, transition and option and fstype values; dbus bus, name, peer label, path, interface and member; signal and ptrace peer labels; labels and unix addresses; mqueue name and label.network, io_uring and userns rules (from the code). That a capability rule has no text to expand is derived: it is a list of fixed words.@{b} = @{A}/fwd before @{A} = /a is accepted (recorded in the research notes).io_uring ... label= are not expanded.profile keyword.process_profile_variables (parser_variable.c:137-179), called from parser_policy.c:133; the head and the attach_disconnected values at parser_variable.c:58-85.expand_variables of network, io_uring and userns return 0: network.cc:664, io_uring.cc:106, userns.cc:91.variable.cc:252-340 expands the first @{...} and repeats; parser_variable.c:137-179 runs it per profile.
variable (symtab.cc:25-151): add_var (25-76), add_set_value (90-101), delete_var (103-112), get_set_var (135-151).is_var (74-131), process_var (133-151), extract_variable (variable.cc:169-221), expand_by_alternation (variable.cc:252-340), expand_variable (variable.cc:342-404).@{ starts a reference inside a string; \@ does not (variable.cc:184-194).expanded (variable.cc:353-355).Variable @{A} is referenced recursively (by @{B}) (variable.cc:378-383).process_profile_variables (parser_variable.c:137-179) is called once per profile from parser_policy.c:133.std::bad_alloc instead of an error. Recorded in the research notes: @{A} = /a/@{UNDEF} with the rule @{A}/x r, prints Failed to find declaration for: @{UNDEF} and then terminate called after throwing an instance of 'std::bad_alloc'.@{profile_name}, @{attach_path} or @{exec_path} keeps the value of the first profile that uses it. Recorded in the research notes: @{DIR} = /var/lib/@{profile_name} used in the profiles one and two compiles /var/lib/one/** in both..d directory: see include if exists.-D rule-exprs.* or ** is a glob in every rule that uses the variable (derived from the substitution being textual; not run).No comma after an assignment. Failed to find declaration for: @{NAME} means the name was never assigned in this file's preamble.
AppArmor parser error for /work/v-comma.sd in profile /work/v-comma.sd at line 1: Variable declarations do not accept trailing commas. The words in profile are followed by the name of the file being parsed, not by a profile name.... at line 2: syntax error, unexpected TOK_PROFILE, expecting TOK_VALUE. The token named is whatever follows the empty assignment; here it is the profile keyword of the next line.@{4DATA} for a variable, so it stops at the @.@{APPDATA}/** rw, in the profile demo, with tunables/global included.Variable DEMO_DEBUG is not a set variable, Failed to find declaration for: @{DEMO_DEBUG}, ERROR expanding variables for profile demo, failed to load. The slide shows the first two.Variable '%s' must start with alphabet letters and Variable '%s' contains invalid characters, for a malformed name inside a string.@{a,b} in a rule is left as it is and, with --warn=all, draws The usage of comma in the variable formatting to indicate alternation is deprecated. Escape the character @ to indicate it is not a variable. The warning class is deprecated, off by default (recorded in the research notes).@{a,b} advises escaping @, the escape draws a warning of its own, and a later variable in the same string is left unexpanded.@NAME without braces is accepted in a rule and compiled as literal text.Onward: syn-variable-assignment, syn-builtin-variables, syn-boolean-variables, syn-globbing.
@{NAME} is a set of strings, assigned in the preamble, case sensitive.{v1,v2,...} when there are several. Slashes at the joint are trimmed.-D variables and -D expanded-variables print the table; -D rule-exprs prints the rules after expansion.Basis of the statements on this page: "tree" means the parser built from the AppArmor commit 836052d21 (6.0.0~alpha2) was run on the fragment (-Q -K --skip-kernel-load, with the tree's abi/5.0 as kernel feature set and the dump option named), with nothing loaded into a kernel; "code" means the parser source was read and not run; "derived" means the result was reasoned from that code. Nothing here was observed on a running kernel.
reference: @{NAME}
NAME: a letter, then letters, digits and _ (case sensitive)
assignment: @{NAME} ( = | += | ?= | := ) VALUE ... up to the end of the line
VALUE: a word | "a quoted string" | ""
@{LIBVIRT} = "libvirt," (the parser's test vars_simple_assignment_13.sd)."" is the empty value (tree).# comment may follow the values, and \ at the end of a line continues the list on the next line (tree).@{Case} and @{case} are two variables (tree).@NAME without braces is accepted in an assignment and is the same variable as @{NAME} (tree).| Case | Written | Compiled | Basis |
|---|---|---|---|
| one value | @{PROC}/sys/ with @{PROC}=/proc/ | /proc/sys/ | tree |
| several values | @{HOME}/.ssh/** | {/home/*,/root}/.ssh/** | tree |
text before ends in / | /srv/@{HOME}/x | /srv/{home/*,root}/x | tree |
| quoted value | /q/@{D} with @{D} = "with space" plain | /q/{plain,with space} | tree |
| empty value | /e/@{E}/x with @{E} = "" | /e/x | tree |
| duplicate value | @{DUP}/x with @{DUP} = /a /a /b | {/a,/b}/x | tree |
/, leading slashes of each value are trimmed. When the text after it begins with /, trailing slashes are trimmed (code).@{b} = @{A}/fwd before @{A} = /a (tree).| Place | Fields | Source |
|---|---|---|
| profile head | the name, the attachment, the attach_disconnected.path and .ipc values | parser_variable.c:58-85 |
| file rules | the path | block_rules.cc:393-407 |
| link rules | the link and the target | block_rules.cc:393-407 |
| mount rules | mount point, device, transition, option and fstype values | mount.cc:641 |
| dbus rules | bus, name, peer label, path, interface, member | dbus.cc:176 |
| signal rules | the peer label | signal.cc:249 |
| ptrace rules | the peer label | ptrace.cc:108 |
| unix rules | labels and addresses | af_rule.cc:161, af_unix.cc:166 |
| mqueue rules | the name and the label | mqueue.cc:179 |
network, io_uring, userns (code).| Option | Prints | For the example file |
|---|---|---|
-D variables | the table as written | @HOME = "/root/" "@{HOMEDIRS}/*/", @HOMEDIRS = "/home/", @APP_DATA = "/srv/demo" "/var/lib/demo", $DEMO_DEBUG = false; 85 lines |
-D expanded-variables | the table after expansion | @HOME = "/home//*/" "/root/"; the others unchanged |
-D rule-exprs | each rule after expansion | aare: {/home/*,/root}/.ssh/**, aare: {/srv/demo,/var/lib/demo}/{cache,state}/** |
@NAME without braces, boolean variables as $NAME = true (tree).| Message | Cause | Exit | Basis |
|---|---|---|---|
Variable declarations do not accept trailing commas | a comma at the end of an assignment | 1 | tree |
syntax error, unexpected TOK_PROFILE, expecting TOK_VALUE | no value after the operator; the token named is the next one in the file | 1 | tree |
Lexer found unexpected character: '@' (0x40) in state: INITIAL | a name that starts with a digit | 1 | tree |
Failed to find declaration for: @{NAME} then ERROR expanding variables for profile P, failed to load | a name that was never assigned | 1 | tree |
Variable NAME is not a set variable then the two lines above | a boolean variable used as a set | 1 | tree |
Variable @{A} is referenced recursively (by @{B}) | two variables that refer to each other | see the known discrepancies | tree |
Variable '%s' must start with alphabet letters, Variable '%s' contains invalid characters | a malformed name inside a string | code | |
The usage of comma in the variable formatting to indicate alternation is deprecated. Escape the character @ to indicate it is not a variable. | @{a,b} in a rule; class deprecated, off by default | warning | tree, with --warn=all |
.d directory: see include if exists.-D rule-exprs prints it; the profile text does not.* or ** is a glob in every rule that uses the variable (derived).VARIABLE_NAME, SET_VARIABLE (parser_lex.l:296-298); ASSIGN_MODE (parser_lex.l:564-590, parser_lex.l:824-832).varassign: TOK_SET_VAR assign_op valuelist (parser_yacc.y:524-548).std::set<std::string> (variable.h:35).extract_variable (variable.cc:169-221), expand_by_alternation (variable.cc:252-340), expand_variable (variable.cc:342-404).process_profile_variables (parser_variable.c:137-179), called from parser_policy.c:133.@{profile_name}, @{attach_path} or @{exec_path} keeps the value of the first profile that uses it. Run: @{DIR} = /var/lib/@{profile_name} used in the profiles one and two compiles /var/lib/one/** in both; -D expanded-variables prints @DIR = "/var/lib/one"; exit status 0.std::bad_alloc instead of an error. Runs: @{A} = /a/@{UNDEF} with the rule @{A}/x r,; @{A} = @{B} and @{B} = @{A} with the rule /x/@{A} r,.@NAME without braces is accepted in a rule and compiled as literal text. Run: @NOBRACE = /nb and the rule @NOBRACE/x r, print aare: @NOBRACE/x, exit status 0.@{a,b} advises escaping @, the escape draws a warning of its own, and a later variable in the same string is left unexpanded. Runs: /a/@{x,y}/@{H} r, prints the warning and then Regex grouping error: Invalid number of items between {}, exit status 255; /a/\@{x,y} r, prints Character @ was quotedunnecessarily, dropped preceding quote ('\') character./, so the rule starts with // and never matches.io_uring ... label= are not expanded.profile keyword.@{...} covers a logged path.xattrs=(user.demo=trusted) adds a condition to the attachment: the executable must have the extended attribute user.demo with the value trusted. Set it with setfattr -n user.demo -v trusted /usr/bin/demo.
setfattr -n 'security.apparmor' -v 'trusted' /usr/bin/example-tool and getfattr --absolute-names -d -m - /usr/bin/example-tool (apparmor_xattrs.pod:53-59). The attribute name and value are arbitrary.bprm_creds_for_exec (lsm.c:1862), by aa_xattrs_match() with vfs_getxattr_alloc() on the executable (domain.c:313-370)./sys/kernel/security/apparmor/features/domain/attach_conditions/xattr (apparmorfs.c:2596-2599, apparmorfs.c:2610).unconfined; with both attributes set to the listed values it runs under the profile (xattrs_profile.sh:51-59).xattrs=( ENTRY ... ) with ENTRY = name=value or name. Values may be quoted and are patterns. One group per head, written after the attachment and before + identities=( ) and flags=( ).
ATTACHMENT SPECIFICATION = [ PROFILE_EXEC_COND ] [ PROFILE XATTR CONDS ], PROFILE XATTR CONDS = [ 'xattrs=' ] '(' comma or white space separated list of PROFILE XATTR ')', PROFILE XATTR = extended attribute name '=' XATTR VALUE FILEGLOB (apparmor.d.pod:141-149).xattrs= is required: a bare ( ... ) in the head is a flags list. And an entry may be a bare name without =value, as in xattrs=(user.foo=bar myvalue) (ok_13.sd:5).+ identities=( ) and flags=( ). One group per head./usr/bin/xattrs-test xattrs=(myvalue=foo) { (ok_01.sd:5). xattrs=() with no entries is accepted by the parser built from the AppArmor tree.profile_base: TOK_ID opt_id_or_var opt_cond_list identities flags TOK_OPEN (parser_yacc.y:391); only the group name xattrs is accepted (parser_yacc.y:434-439).cond: TOK_CONDID and cond: TOK_CONDID TOK_EQUALS TOK_VALUE (parser_yacc.y:1196-1217); cond_list and opt_cond_list (parser_yacc.y:1261-1275).TOK_CONDLISTID for peer or xattrs followed by = and ( (parser_lex.l:420-427) and reads entries in LIST_COND_MODE, where commas are skipped (parser_lex.l:508-549).get_xattr_value returns NULL for a bare name (parser_regex.c:462-469).xattrs=(user.demo=trusted user.signed) requires both attributes. A bare name requires presence only. A value such as "stable/*" is matched as a pattern. getfattr -d -m - FILE lists a file's attributes.
xattrs=(myvalue=foo) (ok_01.sd:5).xattrs=(user.foo=bar myvalue) (ok_13.sd:5). A bare name is compiled as the pattern **: the attribute must exist, with any value.profile trusted /usr/bin/* xattrs=(user.trust="tier/*") { (apparmor_xattrs.pod:46-51).getfattr -d -m - FILE lists a file's attributes with their values, setfattr -n NAME -v VALUE FILE sets one (apparmor_xattrs.pod:53-59).user.foo = hello/* and user.bar = * (xattrs_profile.sh:63-75).if (!xattr_value) xattr_value = "**"; // Default to allowing any value. and the conversion of each value with convert_aaregex_to_pcre (parser_regex.c:556-586).All listed attributes are required; a missing attribute or a value that does not match removes the profile from the candidates for that exec. Attributes not listed are ignored. How a profile with xattrs ranks against others is in the attachment deck.
Kernel statements are read from the kernel source; the rows marked tested are asserted by the AppArmor regression test.
aa_xattrs_match() walks the listed names in order and reads each one from the executable with vfs_getxattr_alloc() (domain.c:333-335).-EINVAL (domain.c:336-354). A listed attribute that is missing gives -EINVAL as well, because the parser generates no optional entries (domain.c:357-369).continue to the next profile in the list (domain.c:456-461).user.foo=hello and user.bar=bye: no attributes, only one attribute, or a wrong value all leave the task unconfined; both values right attaches the profile; an extra user.spam changes nothing (xattrs_profile.sh:43-59).aa_dfa_match_len() over the value and aa_dfa_outofband_transition() to the next entry (domain.c:339-356).The condition needs domain/attach_conditions/xattr in both the kernel features and the policy ABI, and policy/outofband in the kernel features. Otherwise the parser prints "xattr attachment conditional ignored" (class rule-not-enforced, off by default) and the profile attaches by path alone. Checked with the source tree's parser, given the tree's abi/5.0 file as the kernel features.
if (features_supports_domain_xattr && kernel_supports_oob); otherwise it warns, frees the list and builds the attachment from the path alone (parser_regex.c:548-553).domain/attach_conditions/xattr must be in both the kernel features and the policy ABI (parser_main.c:1096-1098, parser_main.c:1000-1003).policy/outofband is looked up in the kernel features (parser_main.c:1758-1759). At 836052d21 this is the only place that sets it; no lookup in the policy ABI was found for this one.Warning from profile NAME (FILE): xattr attachment conditional ignored (parser_regex.c:472-476, parser_common.c:169-187). It is in the class rule-not-enforced, which is off by default: apparmor_parser --warn=rule-not-enforced or --warn=all. It is printed once per profile.abi/5.0 file lists both features (5.0:11, 5.0:91), so abi <abi/5.0>, in the file keeps the condition./sys/kernel/security/apparmor/features/domain/attach_conditions/xattr and /sys/kernel/security/apparmor/features/policy/outofband (apparmorfs.c:2596-2599, apparmorfs.c:2610, apparmorfs.c:2637).abi/5.0 file as the kernel features, no parser.conf, and loaded nothing into a kernel. A system whose parser.conf sets another default policy ABI may differ.TOK_CONDLISTID → cond_list → DFA tail in process_profile_name_xmatch() (out-of-band transitions between values) → xattrs name array → aa_xattrs_match() with vfs_getxattr_alloc().
(peer|xattrs)/{WS}*={WS}*\( returns TOK_CONDLISTID and enters EXTCONDLIST_MODE (parser_lex.l:420-427); entries are read in LIST_COND_MODE, values in LIST_COND_VAL or LIST_COND_PAREN_VAL (parser_lex.l:508-549).cond_list: TOK_CONDLISTID TOK_EQUALS TOK_OPENPAREN opt_conds TOK_CLOSEPAREN (parser_yacc.y:1261-1275); opt_conds prepends, so the stored list is in reverse source order. profile_base rejects any name but xattrs with profile id: invalid conditional group %s=() (parser_yacc.y:434-439).process_profile_name_xmatch(Profile *prof): each value is prefixed with \x00 and converted; the tail has one rule per prefix of the list, x1 | x1 \x-1 x2 | x1 \x-1 x2 \x-1 x3 ..., the separators being out-of-band transitions (parser_regex.c:548-607).{\x00{value_match},}\x-1; the parser does not generate it (parser_regex.c:576-580).sd_serialize_xattrs writes struct xattrs holding an array of strings, in the order of the same list (parser_interface.c:458-478, called at parser_interface.c:565).unpack_xattrs fills profile->attach.xattrs and xattr_count (policy_unpack.c:591-615); failure is failed to unpack profile xattrs (policy_unpack.c:1290-1293).static int aa_xattrs_match(const struct path *path, const struct aa_profile *profile, aa_state_t state): out-of-band transition from the exec match, then per name vfs_getxattr_alloc(), aa_dfa_null_transition(), aa_dfa_match_len(), a check for MAY_EXEC, and another out-of-band transition. Returns the number matched or -EINVAL (domain.c:313-370)."syntax error, unexpected TOK_CONDLISTID, expecting TOK_OPEN" means the group is after the flags or written twice. "hat profiles can't use xattrs matches" means the condition is on a hat inside a profile.
syntax error, unexpected TOK_CONDLISTID, expecting TOK_OPEN: the group is written after the flags, as in flags=(complain) xattrs=(myvalue=foo) (bad_03.sd:5), or a second xattrs=( ) group follows the first.profile id: invalid conditional group peer=(): a group other than xattrs in that seat (bad_01.sd:5). It is reported one line after the head.hat profiles can't use xattrs matches: the condition is on a hat inside a profile (hats_01.sd:6). This message is not translated.syntax error, unexpected TOK_VALUE, expecting TOK_CONDID or TOK_CLOSEPAREN for name=(a b): more than one value in parentheses.profile c /x xattrs=(...) { } inside a profile is accepted (parser 5.0.2).^a xattrs=(user.a=b) { }, is accepted (parser 5.0.2). What the kernel does with it was not determined.AppArmor parser error for FILE in profile FILE at line N: MESSAGE.hat production only; a top-level hat goes through opt_profile_flag and is not checked (parser_yacc.y:475-476).A user.* attribute can be set by anyone with write permission on the file; trusted.* and security.* need CAP_SYS_ADMIN. The kernel has no AppArmor hook for setting attributes. A dropped condition makes the profile attach to unmarked files at the path; --warn=rule-not-enforced shows it. Kernel statements are read from the code, not run.
All kernel statements are read from the kernel source and were not run.
user.*: on a regular file, anyone who passes the ordinary write permission check on the inode;trusted.*: only a task with CAP_SYS_ADMIN;security.*: left to the filesystem and the security modules. The capability module asks for CAP_SYS_ADMIN in the user namespace of the filesystem, except for security.capability (security/commoncap.c:1025-1045).vfs_getxattr_alloc() from the file being executed (domain.c:313-370).domain/attach_conditions/xattr is in the kernel features and the policy ABI and policy/outofband is in the kernel features; otherwise it frees the list and builds the attachment from the path alone (parser_regex.c:548-553).rule-not-enforced, off by default (parser_common.c:169-187). Seen with the parser built from the AppArmor tree at 836052d21 for a file without an abi line and --warn=all.security.apparmor as the attribute name and says the name is arbitrary (apparmor_xattrs.pod:33-57).Ranking and ties: attachment. The feature check: syn-abi, adm-features. Value patterns: syn-globbing. Neighbours in the head: syn-profile-name, syn-identities, syn-hats.
xattrs=( NAME=VALUE ... ) after the attachment path: every listed attribute must be present on the executable and match; a bare name requires presence only.domain/attach_conditions/xattr and policy/outofband the parser drops the condition and the profile attaches by path alone. See it with apparmor_parser --warn=rule-not-enforced./sys/kernel/security/apparmor/features/domain/attach_conditions/xattr (apparmorfs.c:2596-2599).Basis of the statements on this page: "tree" means the parser built from the AppArmor commit above was run on the fragment, with the tree's abi/5.0 file as the kernel features and nothing loaded into a kernel; "5.0.2" means the released parser 5.0.2 was run; "code" means the kernel or parser source was read, not run; "tested" means a regression test in the AppArmor tree asserts it.
HEAD: [profile] NAME [ATTACHMENT] [XATTRS] [+ identities=( ... )] [flags=( ... )] {
XATTRS: 'xattrs' '=' '(' { ENTRY [','] } ')'
ENTRY: NAME | NAME '=' VALUE | NAME '=' '(' VALUE ')'
VALUE is a word or a quoted string. It is a pattern in the same syntax as a path: see syn-globbing.NAME is compiled as the pattern **: the attribute must be present, with any value.+ identities=( ) and flags=( ). One group per head.xattrs=() with no entries is accepted (tree).profile a xattrs=(user.a=b) { } is accepted (tree). What such a profile matches is in attachment.| Token | Meaning |
|---|---|
xattrs | the only group name accepted in this position of the head |
= | the only comparison; name in (...) is not accepted |
white space, ,, new line | separators between entries |
At exec, for a profile whose path pattern matched, the kernel reads each listed attribute from the executable and matches its value against the pattern (code; the rows marked tested are asserted by tests/regression/apparmor/xattrs_profile.sh).
| The file has | Result | Basis |
|---|---|---|
| every listed attribute, each value matching | the profile is a candidate | tested |
| one listed attribute missing | not a candidate | tested |
| one listed attribute with a value that does not match | not a candidate | tested |
| attributes that the profile does not list | ignored | tested |
| an attribute listed as a bare name, with any value | matches | code |
| Needs | Where | If missing |
|---|---|---|
domain/attach_conditions/xattr | the kernel features and the policy ABI | the condition is ignored |
policy/outofband | the kernel features | the condition is ignored |
Warning from profile NAME (FILE): xattr attachment conditional ignored. It belongs to the class rule-not-enforced, which is off by default (--warn=rule-not-enforced or --warn=all turns it on), and is printed once per profile.abi <abi/5.0>, in the file the condition is kept and no warning is printed; without an abi line the warning above is printed. The runs used no parser.conf; a system whose parser.conf sets another default policy ABI may differ.| Where | Allowed | Basis |
|---|---|---|
| a top-level profile | yes | tree |
a child profile (profile c /x xattrs=(...) { } inside a profile) | yes | tree |
a hat inside a profile (^hat or hat) | no: hat profiles can't use xattrs matches | tree |
| a hat written at the top level of a file | accepted by the parser | tree; known discrepancy, see below |
Hats: syn-hats.
| Message | Cause |
|---|---|
syntax error, unexpected TOK_CONDLISTID, expecting TOK_OPEN | the group is written after flags=( ), or a second xattrs=( ) group follows the first |
profile id: invalid conditional group NAME=() | a group other than xattrs in the head, such as peer=( ); reported one line after the head |
hat profiles can't use xattrs matches | the condition is on a hat inside a profile; this message is not translated |
syntax error, unexpected TOK_VALUE, expecting TOK_CONDID or TOK_CLOSEPAREN | name=(a b): more than one value in parentheses |
Lexer found unexpected character: '(' (0x28) in state: LIST_COND_MODE | name in (b) |
Warning from profile NAME (FILE): xattr attachment conditional ignored | a required feature is missing; see Feature gating |
kernel: failed to unpack profile xattrs | the kernel could not read the list of names from the loaded policy (code) |
^a xattrs=(user.a=b) { } or hat a xattrs=(user.a=b) { }, is accepted, while the same line inside a profile is rejected. What the kernel does with such a hat was not determined.| Step | Where |
|---|---|
xattrs=( returns TOK_CONDLISTID; entries read in LIST_COND_MODE, commas skipped | parser/parser_lex.l:420-427, 508-549 |
opt_cond_list in profile_base; only the name xattrs accepted | parser/parser_yacc.y:391, 434-439 |
entries: bare name, name=value; cond_list | parser/parser_yacc.y:1196-1217, 1261-1275 |
| hat check | parser/parser_yacc.y:490-504 |
| feature test, warning | parser/parser_regex.c:472-476, 549-553; parser/parser_main.c:1096-1098, 1758-1759; parser/parser_common.c:169-187 |
DFA tail in process_profile_name_xmatch(): one rule per prefix of the list, out-of-band transition between values, bare name as ** | parser/parser_regex.c:462-469, 548-607 |
names written as struct xattrs, an array of strings | parser/parser_interface.c:458-478, 565 |
| kernel unpacks the names | linux:security/apparmor/policy_unpack.c:591-615, 1290-1293 |
aa_xattrs_match(): vfs_getxattr_alloc() per name, DFA walk over the value, mismatch returns -EINVAL | linux:security/apparmor/domain.c:313-370 |
| count of matched attributes as tie-breaker | linux:security/apparmor/domain.c:442-474 |
| kernel feature files | linux:security/apparmor/apparmorfs.c:2596-2599, 2610, 2637 |
opt_conds prepends each entry (parser/parser_yacc.y:1262-1266), so the stored list is in reverse source order. The DFA tail and the name array are built by walking the same list, so they agree.parser/apparmor_xattrs.pod. Regression test: tests/regression/apparmor/xattrs_profile.sh. Parser fixtures: parser/tst/simple_tests/xattrs/.A policy file is a preamble followed by profiles. A profile is a head and a body of rules and nested blocks. The example shows syntax and is not a recommended policy; its full text is in the reference, with a line-by-line index.
apparmor_parser -Q -K --skip-kernel-load --warn=all, with --base set to the tree's profiles/apparmor.d and --kernel-features to the tree's abi/5.0. Exit status 0, no warning. -N printed demo, demo//admin and demo//worker. Nothing was loaded into a kernel.PROFILE FILE = ( [ PREAMBLE ] [ PROFILE ] )* and PROFILE = ( PROFILE HEAD ) [ ATTACHMENT SPECIFICATION ] [ PROFILE IDENTITIES ] [ PROFILE FLAG CONDS ] '{' ( RULES )* '}' (apparmor.d.pod:105, apparmor.d.pod:131).RULES are line rules (comments, includes), comma rules and block rules (apparmor.d.pod:170-176).apparmor_parser -Q -K FILE; add -N to list the profile names in it.list: preamble ... profilelist (parser_yacc.y:345); the head is profile_base: TOK_ID opt_id_or_var opt_cond_list identities flags TOK_OPEN (parser_yacc.y:391).Rules end with ,. Bodies sit in { }. include takes no comma and # starts a comment. A rule without its comma, followed by another rule, is reported as missing an end of line character? (entry: ...).
RULES = [ ( LINE RULES | COMMA RULES ',' | BLOCK RULES ); line rules are comments and includes (apparmor.d.pod:170-172).# to the end of the line (parser_lex.l:815). The exception is #include, the old spelling of include, which still includes and warns deprecated use of '#include' (parser_lex.l:796-800). The warning class is include.@{X} = a, is the error Variable declarations do not accept trailing commas (parser_lex.l:573).missing an end of line character? (entry: PATH). It is reported at the line of the following rule and names the path of the rule that lacks the comma.syntax error, unexpected TOK_CLOSE, expecting TOK_END_OF_RULE (observed with the parser built from the AppArmor tree at 836052d21).AppArmor parser error for FILE in profile FILE at line N:.file_rule_tail: opt_exec_mode id_or_var file_perms id_or_var (parser_yacc.y:1132-1138).CLOSE_BRACE (parser_lex.l:250).The preamble holds abi, include, variable assignments and alias. Variables and aliases cannot be defined after the first profile starts; abi and include can also appear inside a profile.
PREAMBLE = ( COMMENT | VARIABLE ASSIGNMENT | ALIAS RULE | INCLUDE | ABI )*, with the note "Variable assignment and alias rules must come before the profile." (apparmor.d.pod:107-108).abi <abi/5.0>, ends with a comma. Besides a file it accepts <kernel> and <default> (apparmor.d.pod:120). The file is /etc/apparmor.d/abi/5.0.include <tunables/global>: the path in angle brackets is relative to /etc/apparmor.d/ (apparmor.d.pod:124-125). tunables/global includes tunables/home, which defines @{HOME} (home:21).@{NAME} = value value, with the operators =, +=, ?= and := (apparmor.d.pod:110). A second = for the same name is the error variable @{NAME} was previously declared.${NAME} = true or false.alias /usr/ -> /opt/demo/usr/,; rewrite is another spelling of alias (parser_misc.c:105-106).apparmor_parser -p FILE prints the file with the includes resolved, which shows what the preamble pulls in.preamble is the grammar rule at parser_yacc.y:506-509; abi inside a profile body is rules: rules abi_rule (parser_yacc.y:722). The redeclaration error is at parser_yacc.y:542.profile NAME ATTACHMENT xattrs=( ) + identities=( ) flags=( ) {. Only the name is required. The mode is one of the flags.
PROFILE = ( PROFILE HEAD ) [ ATTACHMENT SPECIFICATION ] [ PROFILE IDENTITIES ] [ PROFILE FLAG CONDS ] '{' ( RULES )* '}' (apparmor.d.pod:131).profile NAME. A head that is only a path, /usr/bin/demo {, still works and warns The use of file paths as profile names is deprecated.; the path is then both the name and the attachment.Profile attachment must begin with a '/' or variable.xattrs=(user.demo=trusted); the list is separated by commas or white space (apparmor.d.pod:145-147).+ identities=(demo-role) (apparmor.d.pod:151). They are not sent to the kernel; see identities.flags=(complain, attach_disconnected); the word flags= is optional (apparmor.d.pod:157). The six mode names are enforce, complain, kill, default_allow, unconfined, prompt (apparmor.d.pod:166); the other flag names are checked at profile.h:216-257. An unknown one is the error Invalid profile flag: NAME. (profile.h:261).apparmor_parser -N prints, what the profile= field of a log record holds and what /proc/PID/attr/current shows.profile_base (parser_yacc.y:391); the attachment check is at parser_yacc.y:431-433; flags at parser_yacc.y:593 and identities at parser_yacc.y:631. The deprecation warning is at parser_yacc.y:470.PATH PERMISSIONS, with globs in the path. Access letters r w a l k m; exec modes such as ix, Px, Cx choose the profile of the program being started, and -> name names it.
PATH PERMS, or PERMS PATH,, optionally after the word file (parser_misc.c:108).r read, w write, a append (not together with w), l link, k lock, m memory map with PROT_EXEC.ix inherit, px and Px the profile of the program, cx and Cx a child profile, ux and Ux unconfined; the capital letter scrubs the environment. Fallbacks such as pix and cix exist.x in an allow rule is the error Invalid perms, 'x' must be preceded by exec qualifier 'i', 'p', or 'u' (parser_misc.c:1099). deny PATH x, is the one place where x stands alone./usr/bin/demo-helper Px -> demo-helper,. With Cx -> worker the kernel looks the name up among the children of the current profile (domain.c:603-606).* within one directory level, ** across levels, ?, [a-z], {a,b}.link [subset] PATH -> TARGET, (parser_misc.c:94-98).frule: id_or_var file_perms opt_named_transition TOK_END_OF_RULE (parser_yacc.y:1072); the arrow is opt_named_transition (parser_yacc.y:1043); link rule: link_rule: TOK_LINK opt_subset_flag id_or_var TOK_ARROW id_or_var TOK_END_OF_RULE (parser_yacc.y:1141).Order: priority=N audit allow|deny|prompt owner|other. A qualifier can be put before a { } block of rules. prompt is loaded but not acted on by the kernel.
[priority=N] [audit] [allow|deny|prompt] [owner|other] RULE,. Another order is a syntax error; deny audit /foo r, gives syntax error, unexpected TOK_AUDIT, expecting TOK_ID or TOK_MODE or TOK_SET_VAR (observed with the parser built from the AppArmor tree at 836052d21).audit, deny, allow, prompt, owner, other; user is another spelling of owner (parser_misc.c:95-102).priority=N takes an integer from -1000 to 1000 (immunix.h:198-199); the default is 0.deny without audit refuses without a log record; audit deny refuses and logs apparmor="DENIED".QUALIFIERS line lists only priority, audit and allow or deny (apparmor.d.pod:200); the parser also accepts prompt, owner and other in front of every rule class.prompt: in mainline Linux the permission is unpacked and no kernel code acts on it. See prompt and upstream and Ubuntu kernels.deny { /proc/sys/** w, /sys/** w, }. set rlimit rules take no qualifier.opt_prefix: opt_priority opt_audit_flag opt_rule_mode opt_owner_flag (parser_yacc.y:705); priority is opt_priority (parser_yacc.y:677) and the block is block: TOK_OPEN rules TOK_CLOSE (parser_yacc.y:738).Fifteen keyword rule classes, plus all, which allows everything. They share one condition syntax: name=value, name=(a b) and peer=( ). dbus is enforced by the bus daemon; mqueue is not enforced by the kernel.
capability, set rlimit, network, unix, dbus, mount, remount, umount, pivot_root, signal, ptrace, userns, io_uring, mqueue, change_profile. Most are plain words in the parser's keyword table (parser_misc.c:81-138); unmount is another spelling of umount.name=value, name=(a b), name in (a b) and peer=( ... ). Examples from the example profile: unix (send, receive) type=stream peer=(label=demo-helper), and signal (send) set=(term, hup) peer=demo//worker,.all, allows everything: the parser expands it to one bare rule of each class (all_rule.cc:33-40).dbus is enforced by the bus daemon, not the kernel; mqueue has no kernel check point. See D-Bus mediation and upstream and Ubuntu kernels.apparmor_parser --warn=rule-not-enforced prints, for example, Warning from profile demo (demo.sd): mqueue type=posix rules not enforced (observed with the parser built from the AppArmor tree at 836052d21 and --kernel-features /dev/null).ls /sys/kernel/security/apparmor/features.COMMA RULES line omits ptrace and signal rules (apparmor.d.pod:174); the parser accepts both.cond rule (parser_yacc.y:1196), shared by every keyword class. Class numbers and the rule classes behind them are in rule classes in the parser.if blocks are decided at compile time. Child profiles and hats are written inside their parent and loaded as separate profiles named parent//child.
BLOCK RULES = ( SUBPROFILE | HAT | QUALIFIER BLOCK | IF_BLOCK ) (apparmor.d.pod:176).if EXPR { } else if EXPR { } else { }, with not, and, or and defined (apparmor.d.pod:188-192). It is decided by the parser; the kernel never sees the block or the variable.profile worker { ... } inside a body, reached by /usr/lib/demo/worker Cx -> worker,.^admin { ... } or hat admin { ... } (apparmor.d.pod:180). The program enters and leaves it with int aa_change_hat(const char *subprofile, unsigned long magic_token); (apparmor.h:79).apparmor_parser -N on the example printed demo, demo//admin and demo//worker (observed with the parser built from the AppArmor tree at 836052d21). The separator // is added at profile.h:454-459./sys/kernel/security/apparmor/profiles, the profile= field of a log record and /proc/PID/attr/current.-N prints the hat and the child in the same form; the parser does not mark which is which in the name.cond_rule: TOK_IF expr block (parser_yacc.y:862), rules: rules hat (parser_yacc.y:827), rules: rules local_profile (parser_yacc.y:836).load_flattened_hats (parser_interface.c:783-786).Each district has an entry deck: the preamble, the profile name, file rules, allow and deny, capability, hats. The reference below lists every syntax deck and maps each line of the example to its deck.
:ns:name, belong to namespaces; targets with an ampersand, a//&b, belong to stacking.rewrite and alias, unmount and umount, user and owner (parser_misc.c:96-112).# Example policy for the AppArmor map. Lines 2-6 are the preamble.
abi <abi/5.0>,
include <tunables/global>
@{APP_DATA} = /var/lib/demo /srv/demo
${DEMO_DEBUG} = false
alias /usr/ -> /opt/demo/usr/,
profile demo /usr/bin/demo xattrs=(user.demo=trusted) + identities=(demo-role) flags=(complain, attach_disconnected) {
include <abstractions/base>
include if exists <local/demo>
capability net_bind_service,
network inet stream,
unix (send, receive) type=stream peer=(label=demo-helper),
dbus send bus=session path=/org/demo interface=org.demo.Api peer=(name=org.demo),
mount fstype=tmpfs options=(rw, nosuid) tmpfs -> /run/demo/,
remount options=(ro) /run/demo/,
umount /run/demo/,
pivot_root oldroot=/run/demo/old/ /run/demo/,
signal (send) set=(term, hup) peer=demo//worker,
ptrace (read) peer=demo//worker,
mqueue (create, open) type=posix /demo-queue,
userns create,
io_uring sqpoll,
change_profile -> demo//worker,
set rlimit nofile <= 1024,
/etc/demo/** r,
owner @{APP_DATA}/{cache,state}/** rwk,
audit deny @{HOME}/.ssh/** rw,
priority=10 allow /etc/demo/override.conf r,
prompt @{HOME}/Documents/** r,
link /var/lib/demo/current -> /var/lib/demo/releases/*,
/usr/bin/demo-helper Px -> demo-helper,
/usr/lib/demo/worker Cx -> worker,
/usr/bin/[a-z]* ix,
deny { /proc/sys/** w, /sys/** w, }
if ${DEMO_DEBUG} { /tmp/demo-debug.log w, }
profile worker { all, }
^admin { /etc/demo/admin.conf rw, }
}
The program, the paths and the names are invented. The profile shows syntax and is not a recommended policy. It was checked with the tree's parser (6.0.0~alpha2) through tools/head-parser, with -Q -K --skip-kernel-load --warn=all, --base set to the tree's profiles/apparmor.d and the tree's abi/5.0 features: exit status 0 and no warning. With -N the parser printed demo, demo//admin and demo//worker. The profile is in complain mode to show the flag; the descriptions of deny and audit deny in the deck are for enforce mode.
Lines 13 (dbus), 20 (mqueue), 29 (prompt) and the identities on line 7 compile, but mainline Linux 7.4 does not enforce them itself. For dbus see dbus-mediation; for mqueue and prompt see upstream-and-ubuntu; for identities see syn-identities. When the kernel feature set given to the parser lacks a rule class, the line is dropped and the profile still loads; the warning for it is off by default (--warn=rule-not-enforced).
Line numbers count from the comment on line 1 of the example.
| Line | Construct | Deck |
|---|---|---|
| 1 | comment | Comments |
| 2-6 | the preamble as a whole | The preamble |
| 2 | feature ABI | abi |
| 3 | include of a tunables file (it defines @{HOME}, used on lines 27 and 29) | include, Abstractions and tunables |
| 4 | variable with two values | Variables |
| 5 | boolean variable | Boolean variables |
| 6 | alias | alias |
| 7 | profile keyword and name | Profile name |
| 7 | attachment /usr/bin/demo | Attachment |
| 7 | xattrs=( ) | xattrs |
| 7 | + identities=( ) | Identities |
| 7 | flags=(complain, …) | Mode flags |
| 7 | attach_disconnected | Other flags |
| 8 | include of an abstraction | include, Abstractions and tunables |
| 9 | include if exists | include |
| 10 | capability | capability |
| 11 | network | network |
| 12 | unix; the conditions type= and peer=( ) | unix, Rule conditionals |
| 13 | dbus; conditions | dbus, Rule conditionals |
| 14 | mount; fstype=, options=( ) | mount, Rule conditionals |
| 15 | remount | remount |
| 16 | umount | umount |
| 17 | pivot_root | pivot_root |
| 18 | signal; set=( ), peer= | signal, Rule conditionals |
| 19 | ptrace | ptrace |
| 20 | mqueue | mqueue |
| 21 | userns | userns |
| 22 | io_uring | io_uring |
| 23 | change_profile | change_profile |
| 24 | rlimit | rlimit |
| 25 | file rule, r, ** | File rules, Access modes, Globbing |
| 26 | owner, use of a variable, {a,b}, rwk | owner, Variables, Globbing, Access modes |
| 27 | audit deny | audit, allow and deny |
| 28 | priority=10 allow | priority, allow and deny |
| 29 | prompt | prompt |
| 30 | link rule | Link rules |
| 31 | Px with -> profile | Exec modes, Named transitions |
| 32 | Cx to the child on line 36 | Exec modes, Named transitions, Child profiles |
| 33 | ix, [a-z]* | Exec modes, Globbing |
| 34 | qualifier block | Qualifier blocks, allow and deny |
| 35 | conditional testing the boolean of line 5 | Conditionals, Boolean variables |
| 36 | child profile containing all, | Child profiles, all |
| 37 | hat | Hats |
| 38 | closing brace | Comments (line structure) |
45 of the 50 syntax decks appear in this table.
Five decks have no line in the example. One line for each; all five were accepted together in one scratch profile by the tree's parser (6.0.0~alpha2), exit status 0, no warning.
| Deck | A line that uses it |
|---|---|
| network conditionals | network inet stream ip=127.0.0.1 port=8080, |
| other | other /srv/shared/** r, |
| safe and unsafe | safe Px /usr/bin/extra-tool, |
| Quoting | "/srv/my files/**" r, |
| Built-in variables | /run/@{profile_name}.pid w, |
safe and unsafe go first, with the permissions before the path. PATH safe Px, was rejected with "syntax error, unexpected TOK_SAFE, expecting TOK_MODE".
Also not shown, each belonging to a deck listed below: subset on link rules, else, the assignment operators += ?= :=, hat NAME, the PERMS PATH order and the bare file, rule, names in a namespace (Namespaces) and stacked targets (Stacking).
profile keyword and the name; path names without the keyword are deprecated.+ identities=( … ) after the attachment and xattrs, before the flags.flags=( … ) with a mode: enforce, complain, kill, unconfined, prompt, default_allow.attach_disconnected, mediate_deleted, kill.signal=, error=, audit.xattrs=( name=value … ), attach only to files whose extended attributes match.^name { } or hat name { }, a sub-profile the program switches into itself.profile name { } inside a body, reached with cx transitions.# comments, commas, and how a file is split into rules."…" around names, paths and values, and the backslash escapes.PATH PERMS, or PERMS PATH,, the optional file keyword and bare file,.r w a l k m.ix px Px cx Cx ux Ux and the fallback forms such as pix.-> target after an exec permission.safe and unsafe before exec rules and change_profile.link [subset] PATH -> TARGET,.* ** ? [abc] [^a] {a,b} in any path or pattern.allow and deny before a rule or block, and how a deny overrides an allow.audit, log what a rule matches.prompt in the place of allow or deny; not acted on by mainline Linux 7.4.owner (also spelled user), only files the task owns.other, only files the task does not own.priority=N, N from -1000 to 1000, written first.{ rules }, applied to every rule inside.capability [name …], with names written without CAP_.network [perms] [family] [type or protocol],.ip=, port=, interface= and label= conditions on network rules.unix [perms] [conds] [peer=( … )], for unix domain sockets.dbus [perms] [conds] [peer=( … )],; enforced by the bus daemon, see dbus-mediation.mount [conds] [source] [-> mountpoint],.umount [conds] [mountpoint], (also spelled unmount).remount [conds] [mountpoint],.pivot_root [oldroot=PATH] [newroot] [-> profile],.signal [perms] [set=( … )] [peer=LABEL],.ptrace [perms] [peer=LABEL], with trace, tracedby, read, readby.mqueue [perms] [type=posix|sysv] [label=…] [name],; not enforced by mainline Linux 7.4, see upstream-and-ubuntu.userns [create],.io_uring [sqpoll|override_creds] [label=…],.change_profile [[safe|unsafe] EXEC] [-> TARGET],.set rlimit NAME <= VALUE,.all,, one rule that allows every class.name=value, name=(a b), name in (a b), peer=( … ).include <path>, include "path", include if exists, and the deprecated #include.abstractions/ and tunables/.@{NAME} and the operators = += ?= :=.@{profile_name}, @{attach_path}, @{exec_path}.${NAME} = true|false.if, else if, else blocks with not, and, or, defined.alias /from/ -> /to/, (also spelled rewrite).abi <abi/5.0>,, the feature ABI the policy was written for.:ns:name.a//&b.| Message | When |
|---|---|
| "missing an end of line character? (entry: %s)" | a rule without its comma followed by another rule; reported at the following line, with the path of the rule that lacks the comma |
| "syntax error, unexpected TOK_CLOSE, expecting TOK_END_OF_RULE" | the last rule of a body without its comma |
| "Profile names must begin with a '/', namespace or keyword 'profile' or 'hat'." | a name without profile in front |
| "The use of file paths as profile names is deprecated." (warning) | /path { as a head |
| "Profile attachment must begin with a '/' or variable." | a bad attachment |
| "Invalid profile flag: %s." | an unknown flag |
| "Variable declarations do not accept trailing commas" | @{X} = a, |
| "variable %s was previously declared" | a second = for the same variable |
| "deprecated use of '#include'" (warning) | the old spelling of include |
The parser prints these translated when a translation is installed; the English text is the one in the source. Every other error belongs to the deck of its construct.
Read at AppArmor 836052d21 (6.0.0~alpha2). "Scanner" is parser/parser_lex.l and "Grammar" is parser/parser_yacc.y unless another file is named. The process is in The lexer and The grammar.
A policy file is list: preamble ... profilelist (parser_yacc.y:345-371; preamble 506-509). Each rule ends with TOK_END_OF_RULE (parser_lex.l:250, 911-917).
How keywords are recognised: profile, hat, include, #include, all, flags, xattrs, peer, identities and priority are scanner patterns (parser_lex.l:409-436, 781-813, 848-850). Every other keyword is a plain word looked up in keyword_table (parser/parser_misc.c:81-138) by the {VARIABLE_NAME} rule (parser_lex.l:856-909). Permission words inside a rule, such as send, create and trace, are recognised only in that rule's scanner state (parser_lex.l:627-688).
| Deck | Scanner | Grammar |
|---|---|---|
| syn-profile-name | 850 (PROFILE, defined 278); names in state SUB_ID 464-470 | profile 460-478, profile_base 391, opt_profile_flag 381-383 |
| syn-identities | 409-416, + at 826 | 631-670 |
| syn-flags-modes | 433-436 | 593-629; names parser/profile.cc:30-39; values parser/profile.h:212-258 |
| syn-flags-other | 433-436 | parser/profile.h:216-257; error at parser/profile.h:261 |
| syn-xattrs | 420-427 | opt_cond_list 1274-1275, cond_list 1268, used at 433-438 |
| attachment | part of ids | opt_id_or_var 388-389, check at 431-433 |
| Deck | Scanner | Grammar |
|---|---|---|
| syn-hats | ^ 820, hat 848 (HAT, defined 277) | hat 490-504, hat_start 1637-1638; in a body 827-834 |
| syn-child-profiles | 850 | local_profile 480-488; stored with add_hat 836-843 |
| syn-comments | 815-818; #include exception 796-803 | not a grammar construct |
| syn-quoting | 259-263, 295-296, processid | not a grammar construct |
| Deck | Scanner | Grammar |
|---|---|---|
| syn-file-rules | file via keyword_table (parser/parser_misc.c:108); paths 838-841 | rule 1049-1050, file_rule 1103-1115, frule 1072-1101, file_rule_tail 1131-1139 |
| syn-access-modes | MODE_CHARS 257, token at 843-846 | file_perms 1640-1646, then parse_perms parser/parser_misc.c:736 and parse_sub_perms parser/parser_misc.c:560 |
| syn-exec-modes | 257 | parser/parser_misc.c:606-700 |
| syn-named-transitions | -> 822 (state SUB_ID_WS) | opt_named_transition 1043-1047, used 1072-1101 |
| syn-safe-unsafe | keyword_table parser/parser_misc.c:92-93 | opt_exec_mode 1065-1067; file rules 1117-1130; change_profile 1648 |
| syn-link-rules | link, subset via keyword_table (parser/parser_misc.c:94, 98) | link_rule 1141-1152; opt_subset_flag 672-675 |
| syn-globbing | part of ids | convert_aaregex_to_pcre parser/parser_regex.c:118-445 |
The fixed order is opt_prefix (parser_yacc.y:705-711).
| Deck | Scanner | Grammar |
|---|---|---|
| syn-allow-deny | keyword_table parser/parser_misc.c:100-101 | opt_rule_mode 700-703 |
| syn-audit | parser/parser_misc.c:99 | opt_audit_flag 693-694 |
| syn-prompt | parser/parser_misc.c:102 | 703 |
| syn-owner, syn-other | parser/parser_misc.c:95-97 | opt_owner_flag 696-698 |
| syn-priority | 428-432; integer in INTEGER_MODE 697-705 | opt_priority 677-691; bounds parser/immunix.h:198-199 |
| syn-qualifier-blocks | { 834 | block 738-741; rules opt_prefix block 743-759 |
| Deck | Grammar | Permission and condition words |
|---|---|---|
| syn-capability | 1694-1716; added at 821-825 | names without CAP_; "Invalid capability %s." (1708) |
| syn-network, syn-network-inet | 1154-1194; rules action 761-783 | perms 1356-1408; conditions ip port interface label (parser/network.cc:450-468) |
| syn-unix | 1418-1432 | conditions type protocol label (parser/af_rule.cc:30-33), addr (parser/af_unix.cc:49) |
| syn-dbus | 1340-1354 | perms 1302-1330; conditions parser/dbus.cc:51-61 |
| syn-mount | 1277-1285 | conditions parser/mount.cc:418-442; flag names parser/mount.cc:247-266 |
| syn-umount | 1292-1295 | as mount |
| syn-remount | 1287-1290 | as mount |
| syn-pivot-root | 1297-1300 | condition oldroot (1824) |
| syn-signal | 1466-1470 | perms 1434-1456; conditions set, peer (parser/signal.cc:170-177) |
| syn-ptrace | 1509-1513 | perms 1472-1499; condition peer (parser/ptrace.cc:45) |
| syn-mqueue | 1586-1595 | perms 1541-1576; conditions label, type (parser/mqueue.cc:78-85) |
| syn-userns | 1535-1539 | create (1515-1525) |
| syn-io-uring | 1620-1627 | override_creds, sqpoll (1597-1610); condition label (parser/io_uring.cc:44) |
| syn-change-profile | 1648-1692; added at 804-819 | default target ** (1681) |
| syn-rlimit | 852-859 | names parser/parser_misc.c:146-168 |
| syn-all | 1629-1635; scanner 811-813 | expands to one bare rule of each class (parser/all_rule.cc:33) |
| syn-rule-conditionals | 1196-1275 | scanner 420-452, 490-560 |
| Deck | Scanner | Grammar |
|---|---|---|
| syn-include | 781-809; file name 376-398; include_filename 162 | scanner only |
| syn-preamble | none of its own | preamble 506-509 |
| syn-abstractions-tunables | as include | not grammar; the files are under profiles/apparmor.d/abstractions/ and tunables/ |
| syn-variables | 714-717; values in ASSIGN_MODE 564-592; operators 303-307, 824-832 | varassign 524-548, assign_op 519-522 |
| syn-builtin-variables | as variables | not grammar; parser/parser.h:335-337, parser/parser_variable.c:137-177 |
| syn-boolean-variables | 707-722 | varassign 550-570 |
| syn-boolean-conditionals | EXPR_MODE 725-767 | cond_rule 862-900; expr, term, notfactor, factor 902-1035 |
| syn-alias | parser/parser_misc.c:105-106 | 511-517 |
| syn-abi | state ABI_MODE, 376-398 | abi_rule 1052-1063; in the preamble 509 and in a body 722; abi_features 1884 |
TOK_PEER (keyword_table, parser/parser_misc.c:123), TOK_COLON (parser_lex.l:852), TOK_SOFT_RLIMIT and the TOK_RLIMIT_* tokens (parser_yacc.y:168-184) are declared and not used in any grammar rule.IOURING_MODE is declared (parser_lex.l:355) and has rules (685-688), but the keyword switch has no case TOK_IO_URING (parser_lex.l:860-906), so the state is not entered. override_creds and sqpoll are recognised through keyword_table instead (parser/parser_misc.c:133-134).opt_subset_flag accepts TOK_LE (parser_yacc.y:674), but the scanner returns it only in RLIMIT_MODE and EXPR_MODE (parser_lex.l:624, 763), so link <= A -> B, is a lexer error.COMMA RULES omits PTRACE RULE and SIGNAL RULE (parser/apparmor.d.pod:174); both are prefix_rule alternatives (parser_yacc.y:785-793).QUALIFIERS lists priority, audit and an access type of allow or deny (parser/apparmor.d.pod:198-200); the grammar also accepts prompt, owner and other for every rule class (parser_yacc.y:696-711).attr and opt (parser/apparmor.d.pod:375-377); neither string occurs in the parser sources. The supported ones are type, protocol, label (parser/af_rule.cc:30-33) and addr (parser/af_unix.cc:49).PROFILE FLAGS (parser/apparmor.d.pod:159-164) omits namespace_relative, delegate_deleted, no_attach_disconnected, chroot_attach and chroot_no_attach, which flagvals::init accepts (parser/profile.h:226-237).SUBPROFILE and HAT (parser/apparmor.d.pod:178-180) show no identities and HAT no attachment; the grammar uses the same profile_base for all three (parser_yacc.y:480, 490).RLIMIT RULE (parser/apparmor.d.pod:379) marks the limit as optional; the grammar requires it (parser_yacc.y:852).PREAMBLE does not mention that abi is also accepted inside a profile body (parser_yacc.y:722).The same profile compiles to 24 rules on a mainline-based kernel 7.3 and to 67 on Ubuntu's kernel 7.3. Ubuntu kernels carry AppArmor patches that mainline does not have.
-Q, features of the running kernel).capability net_bind_service,, network inet stream,, network inet tcp ip=127.0.0.1 port=8080,, unix (connect) type=stream peer=(addr=@demo),, dbus send bus=session path=/org/demo,, signal send set=hup,, ptrace read,, mount fstype=tmpfs -> /mnt/demo/,, mqueue (create) type=posix /demo,, userns,, io_uring sqpoll,.rule: lines of -D rule-exprs: 24 on Debian sid, 67 on Ubuntu 26.10. The numbers are not "rules enforced": one rule of the profile can compile to many lines, and the address and port conditions and unix rules compile to more lines where the kernel can check more.--warn=all, Debian sid printed Warning from profile demo-all (demo-all.sd): mqueue type=posix rules not enforced; Ubuntu 26.10 printed nothing. Without --warn=all neither printed anything. Exit status 0 everywhere.network_v8/sctp, which no rule of this profile needs.Mainline 7.3 publishes 49 feature files; Ubuntu's 7.3 publishes the same 49 and 19 more: message queues, af_inet, prompting, two restrictions, packet mediation and the old network table.
/sys/kernel/security/apparmor/features, 49 on Debian sid (kernel 7.3.4, equal to the mainline tables) and 68 on Ubuntu 26.10 (7.3.0-10). No file of the first is missing from the second. The lists also match the feature tables in the two kernel sources line for line.ipc/posix_mqueue; network_v8/af_inet; network/af_mask, network/af_unix; network_v9_skb/af_mask, iface, localout, postroute, rcv_skb, relabel; domain/interruptible, domain/disconnected.ipc; namespaces/userns_create; policy/notify/user, policy/notify_versions/v3, policy/notify_versions/v5, policy/metadata_tagging_version; policy/unconfined_restrictions/io_uring, policy/unconfined_restrictions/userns.domain/disconnected.ipc belongs to message queues (a profile flag for queues reached through a disconnected path); namespaces/userns_create belongs to the user namespace restriction. The slide puts domain/interruptible with prompting because a profile flag of that name lets a prompt wait be interrupted./sys/kernel/security/apparmor/.notify and six more sysctls: kernel.apparmor_restrict_unprivileged_userns, ..._userns_force, ..._userns_complain, kernel.apparmor_restrict_unprivileged_io_uring, kernel.apparmor_cache_timeout, kernel.apparmor_packet_mediation (seen on Ubuntu 26.04 and 26.10; the first four on 24.04).network/; in mainline that class number is marked deprecated (read from the source).Ubuntu kernels enforce mqueue rules. On mainline the rule is left out, and a confined program cannot open a POSIX queue at all: the open is refused as a file with a disconnected path.
mq_open(NAME, O_CREAT|O_RDWR) under a profile holding the rule on the slide./demo-ok opened; /demo-other failed with EACCES and the record apparmor="DENIED" operation="create" class="posix_mqueue" profile="demo-mq" name="/demo-other" pid=... comm="python3" requested="create" denied="create" class="posix_mqueue" fsuid=0 ouid=0 (26.04). Under a profile without any mqueue rule every name was denied with the same kind of record.mqueue type=posix rules not enforced under --warn=all and loaded the profile with exit status 0. Both names failed with EACCES and the record apparmor="DENIED" operation="open" class="file" info="Failed name lookup - disconnected path" error=-13 profile="demo-mq" name="demo-ok" pid=... comm="python3" requested_mask="wrc" denied_mask="wrc" fsuid=0 ouid=0.flags=(attach_disconnected) and a file rule for the resulting name gets around it on such kernels was not run: see The other profile flags and What is not mediated. An mqueue rule does not: the profile on the slide has one.ipc/posix_mqueue (permissions create read write open delete setattr getattr, and label from 6.17); the patch is first listed in Ubuntu's 6.2 changelog. No mainline version advertises it; the class number exists in mainline and is unused. From 6.14 Ubuntu also has the flag entry domain/disconnected.ipc.ipc/sysv_mqueue).class="posix_mqueue" twice, on 24.04 the second time without a space before it.Ubuntu-7.3.0-10.10): the queue's inode is marked at creation and checks go to aa_mqueue_perm (security/apparmor/ipc.c:209); the feature entry is in security/apparmor/apparmorfs.c.ip= and port= are enforced only where the kernel has network_v8/af_inet: Ubuntu kernels since 6.8. On mainline the condition is dropped without a warning, which widens allow and deny rules alike.
network inet stream ip=10.9.9.9, on Ubuntu 26.04: both connects failed with EACCES; the record: apparmor="DENIED" operation="connect" class="net" info="failed local addr match" error=-13 profile="n-localx" pid=... comm="python3" daddr=127.0.0.1 dest=22 family="inet" sock_type="stream" protocol=6 requested="connect" denied="connect". daddr and dest are fields that mainline records do not have. With ip=127.0.0.1 the connects passed.--warn=all printed nothing when the profile was compiled.network inet stream, with deny network (connect) inet stream peer=(ip=127.0.0.1 port=25),: on Ubuntu 26.04 port 22 connected and port 25 failed with EACCES. On Debian sid both failed with EACCES.af_inet, so deny rules get wider.network inet ip=1.2.3.4 port=80, refuses a connect on Ubuntu 24.04, 26.04 and 26.10 and lets it through on Debian 13 and Debian sid.peer=(ip=... port=...) does not limit connect on Ubuntu 26.04. With network inet stream peer=(ip=127.0.0.1 port=22), a connect to port 25 passed the check. Whether the parser or the kernel is the cause is not determined.network_v8/af_inet is advertised by every Ubuntu kernel from 6.8 to 7.3; the patch arrived with 24.04. No mainline version advertises it. Mainline 7.3 has a file af_inet.c whose checks compare family, type and protocol only; Ubuntu 7.3 replaces about a thousand lines of it. The parser also asks for network_v9/af_inet, which no kernel read has.interface=) need network_v9_skb/iface: Ubuntu 7.0 and 7.3 list it and keep packet mediation switched off (kernel.apparmor_packet_mediation = 0 on both guests). Not run.network_v8/af_inet or network_v9/af_inet in both feature sets (parser_main.c:1062-1067, network.cc:1031).Everywhere, a confined program needs userns,. On Ubuntu an unprivileged unconfined program that creates a user namespace is moved into the profile unprivileged_userns, which denies capabilities.
userns, rule, unshare -U true failed on all five: apparmor="DENIED" operation="userns_create" class="namespace" profile="demo" pid=... comm="unshare" requested="userns_create" denied="userns_create" (with execpath="/usr/bin/unshare" appended on Debian sid, Ubuntu 26.04 and 26.10). Under a profile with userns, it worked.runuser -u tester -- unshare ...), Debian 13 and Debian sid: -U, -Ur and -Urm all exited with status 0 and no record was logged.-U exited with status 0; -Ur and -Urm failed with unshare: write failed /proc/self/uid_map: Operation not permitted. Records: apparmor="AUDIT" operation="userns_create" class="namespace" info="Userns create - transitioning profile" profile="unconfined" pid=... comm="unshare" requested="userns_create" target="unprivileged_userns" and apparmor="DENIED" operation="capable" class="cap" profile="unprivileged_userns" pid=... comm="unshare" capability=21 capname="sys_admin".unprivileged_userns ships with AppArmor; its first rules are audit deny capability, and audit deny change_profile,, and it allows most other things. The file exists on the Debian guests too, where nothing is moved into it.kernel.apparmor_restrict_unprivileged_userns = 1, kernel.apparmor_restrict_unprivileged_userns_force = 0, kernel.apparmor_restrict_unprivileged_userns_complain = 0. The Debian guests have none of the three._force extends the check to confined profiles without a userns rule; _complain turns denials into complain-mode records.policy/unconfined_restrictions/userns.kernel.apparmor_restrict_unprivileged_unconfined. It is 1 on Ubuntu 26.04 and 26.10 and 0 on the other three guests. With 1, aa-exec -p demo by an unprivileged user ran under the stack demo//&unconfined and logged apparmor="AUDIT" operation="change_onexec" class="file" info="change_profile unprivileged unconfined converted to stacking" profile="unconfined" name="demo" ... target="demo//&unconfined".kernel.apparmor_restrict_unprivileged_io_uring, Ubuntu only, 0 on all three Ubuntu guests. Not run.Ubuntu-7.3.0-10.10): the move to unprivileged_userns is in security/apparmor/task.c:478-499; the sysctls in security/apparmor/lsm.c:2912-2941.A prompt rule asks a listener on .notify, a file only Ubuntu kernels have. With no listener the access was denied on all five kernels tested.
--warn=all. With no listener, cat /etc/demo/prompted.conf under the profile failed with "Permission denied" and the record was an ordinary denial: apparmor="DENIED" operation="open" class="file" profile="demo-prompt" name="/etc/demo/prompted.conf" pid=... comm="cat" requested_mask="r" denied_mask="r" fsuid=0 ouid=0./sys/kernel/security/apparmor/.notify exists, with mode 0666, on Ubuntu 24.04, 26.04 and 26.10, and on neither Debian guest.prompt is sent to it. The protocol version is 3 in Ubuntu 6.8 to 6.14 and 5 from 6.17. Ubuntu 7.0 adds a cache of answers with a timeout, kernel.apparmor_cache_timeout (5 on the 26.04 and 26.10 guests).domain/interruptible (from 6.8), policy/notify/user (file from 6.11, file tags from 6.17), policy/notify_versions/v3 and v5 and policy/metadata_tagging_version (from 6.17).prompt permission in its permission table, and unpacks it. What a mainline kernel does with it beyond denying, when no listener can exist, was not determined; in the run it denied.prompt capability X, is compiled as an allowed capability.prompt among the permission table's fields: apparmorfs.c:2631.Ubuntu-7.3.0-10.10): the listener file in security/apparmor/apparmorfs.c:3112, the ioctls at 1147-1153, the upcall aa_do_notification in security/apparmor/notify.c:613, called from security/apparmor/file.c:160.Ubuntu 6.8 has mqueue, inet conditions, the userns restriction and prompting. 6.11, 6.14, 6.17 and 7.0 each add a little; 7.3 adds nothing new. The full table is in the reference below.
Ubuntu-6.8.0-147.147, Ubuntu-6.11.0-29.29, Ubuntu-6.14.0-37.37, Ubuntu-6.17.0-41.41, Ubuntu-7.0.0-43.43, Ubuntu-7.3.0-10.10) or the mainline tag of the same version was read and nothing was run. One tag per series was read, the newest of each. The feature lists of the three tags that match a guest (6.8, 7.0, 7.3) equal the guests' feature files line for line.ipc/posix_mqueue, network_v8/af_inet, network/af_mask and network/af_unix, domain/interruptible, namespaces/userns_create, policy/unconfined_restrictions/userns and io_uring, the file .notify, and the four sysctls kernel.apparmor_restrict_unprivileged_userns, _userns_force, _userns_complain and kernel.apparmor_restrict_unprivileged_io_uring. Ahead of mainline, which got them in 6.17: caps/extended, dbus/mask, domain/kill.signal, domain/unconfined_allowed_children, and permission table version 3.policy/state32 (mainline: 6.13) and policy/notify/user with the value file.network_v9 directory with af_unix, as a backport of what became mainline 6.17, and domain/disconnected.ipc.policy/notify_versions/v3 and v5, policy/metadata_tagging_version, the value file tags in policy/notify/user, the word label in ipc/posix_mqueue, and execpath= in the user namespace record.network_v9_skb directory, the sysctls kernel.apparmor_packet_mediation and kernel.apparmor_cache_timeout, and, as backports from mainline's development branch, policy/diff_encode and policy/compressed_load. The packet mediation build option was switched on in one upload and off again two uploads later; the guest reports the sysctl as 0.policy/diff-encode with a hyphen, policy/extended_policy_header). The 26.04 hardware enablement kernel is this kernel.policy/state32, a table format for policy with more states than the older format can number.security/apparmor against mainline of the same version: 51 files at 6.8, 40 at 6.17, 39 at 7.3 (the count also contains stable fixes).Mainline 6.17 took over fine-grained unix sockets, the dbus entry, extended capabilities, the kill signal and permission table version 3. Still Ubuntu-only at 7.3: mqueue, inet conditions, prompting, the restrictions and packet mediation.
v6.8, v6.11 to v6.17, v7.0 to v7.3. Equal tables: 6.8 to 6.12, 6.13 to 6.16, and 6.17 to 7.1.policy/state32.network_v9/af_mask and network_v9/af_unix, dbus/mask, caps/extended, domain/kill.signal, domain/unconfined_allowed_children, and policy/permstable32_version from 1 to 3. The parser treats versions below 2 as "no extended permission table", so on mainline up to 6.16 (and on Debian 13's 6.12) that table is not used.network_v8/tcp-fast-open and network_v9/tcp-fast-open (a marker that the implicit connect of a TCP fast open sendmsg is checked), and policy/diff-encode.policy/compressed_load and policy/extended_policy_header. Mainline 7.3 also carries a file for inet mediation and the class number of packet mediation, without a feature entry for either: the parser emits no rules for them there.network_v8/tcp-fast-open through a stable update. On Debian 13 the twelve-rule profile lost its unix rule to a downgrade and its dbus rule ("dbus rules not enforced"), and a confined busctl call that four other guests' bus daemons refused went through.ipc/posix_mqueue and domain/disconnected.ipc; network_v8/af_inet; .notify, policy/notify*, policy/metadata_tagging_version, domain/interruptible; namespaces/userns_create, policy/unconfined_restrictions/* and their sysctls; network_v9_skb; network/.network_v8/sctp.A feature file means the code exists, not that it is on. The userns restriction is a sysctl set by user space and depends on a named profile. The same policy means something else on a kernel with fewer features.
network_v9_skb feature files are listed and kernel.apparmor_packet_mediation = 0. Read from the source: the feature tables are static, and packet mediation runs only when that switch is on; its default is a build option that Ubuntu's configuration sets to off.kernel.apparmor_restrict_unprivileged_userns = 1 on the three Ubuntu guests. Read from the source: the build option behind its default is off in every Ubuntu series read, so the value is set from user space (what sets it was not determined); the kernel moves the task into the profile named unprivileged_userns and, if no profile of that name is loaded, denies the creation ("Userns create restricted - failed to find unprivileged_userns profile"). That last case was not run. The sysctl has mode 0644; _force and _complain have 0600.unprivileged_userns profile includes local/unprivileged_userns if it exists, so a site file can widen it.af_inet): with network inet stream, and the deny rule on the slide, connects to port 22 and to port 25 both failed with EACCES; on Ubuntu 26.04 only port 25 did. The mqueue rule: left out on Debian sid and Debian 13 with a message only under --warn=all.af_inet, so deny rules get wider.peer=(ip=... port=...) does not limit connect on Ubuntu 26.04. Seen there with the tree's parser; the cause is not determined.kernel.apparmor_restrict_unprivileged_unconfined is 1 on Ubuntu 26.04 and 26.10 and 0 on 24.04 and both Debian guests: the same question, "is it on here", applies to it..notify has mode 0666 on Ubuntu kernels (seen). Who may register as a listener and for which tasks is decided in the kernel; it was not examined here. Fourteen security fixes to the notification and inet code went into all supported Ubuntu series in 2026 (read from the changelogs).apparmor_restrict_unprivileged_userns*, apparmor_restrict_unprivileged_unconfined, apparmor_restrict_unprivileged_io_uring, apparmor_packet_mediation, apparmor_cache_timeout.List /sys/kernel/security/apparmor/features to see what your kernel has. Roads: kernel features, the four kinds of rule that differ, the userns restriction, D-Bus, the records, and what no kernel mediates.
Basis of the statements on this page: "seen" means observed in a disposable guest: Debian 13 (kernel 6.12.116), Debian sid (7.3.4), Ubuntu 24.04 (6.8.0-147), Ubuntu 26.04 (7.0.0-43) or Ubuntu 26.10 (7.3.0-10), with profiles compiled by the parser of the AppArmor commit 836052d21 against the running kernel's features. "source" means read from a kernel tree and not run: the Ubuntu release tags Ubuntu-6.8.0-147.147 (24.04), Ubuntu-6.11.0-29.29 (24.10), Ubuntu-6.14.0-37.37 (25.04), Ubuntu-6.17.0-41.41 (25.10), Ubuntu-7.0.0-43.43 (26.04), Ubuntu-7.3.0-10.10 (26.10), and the mainline tags of the same versions. Debian's kernels stand for mainline where something was seen running: Debian sid's feature files equal mainline 7.3's tables (the later mainline commit the rest of the map describes has one more entry, network_v8/sctp). One tag per Ubuntu series was read; derivative kernels and 22.04 were not.
| Mainline | Ubuntu kernels | Basis | |
|---|---|---|---|
| POSIX message queues | no mediation of queues; the mqueue rule is left out; a confined open is refused as a file with a disconnected path | mqueue rules enforced, records with class="posix_mqueue" | seen (Debian 13, sid; Ubuntu 24.04, 26.04, 26.10); source for 6.11 to 6.17 |
ip= and port= | not compiled; the rule stays a family and type rule; no warning | enforced where checked: a local address mismatch is denied with info="failed local addr match", daddr=, dest=; a deny with peer=( ) works | seen (sid; 26.04); source |
an allow rule limited by peer=(ip= port=) | not compiled | did not limit connect on 26.04 | seen; cause not determined |
interface=, packet mediation | no feature entry | listed from 7.0, switched off (kernel.apparmor_packet_mediation = 0) | seen (sysctl); source |
| a confined task creating a user namespace | needs userns, | needs userns, | seen on all five |
| an unprivileged unconfined task creating one | allowed | moved into the profile unprivileged_userns when kernel.apparmor_restrict_unprivileged_userns is 1; the guests have 1 | seen |
prompt rules | no listener file; denied in the test | listener on .notify; denied when nobody listens | seen without a listener; source with one |
| fine-grained unix sockets | from 6.17 (network_v9/af_unix) | since before 6.8 (network/af_unix), network_v9/af_unix from 6.14 | seen (13: none; sid, 24.04, 26.04, 26.10: enforced); source |
the dbus entry | from 6.17 | since 6.8 | seen (Debian 13 has none); source |
unprivileged unconfined change_profile | kernel.apparmor_restrict_unprivileged_unconfined, 0 on the Debian guests | the same sysctl, 0 on 24.04, 1 on 26.04 and 26.10: converted to a stack with unconfined | seen |
| io_uring for unconfined tasks | not restricted | kernel.apparmor_restrict_unprivileged_io_uring, 0 on the guests | seen (sysctl); source |
| Kernel | Ubuntu | New against the previous Ubuntu kernel | Basis |
|---|---|---|---|
| 6.8 | 24.04 | ipc/posix_mqueue; network_v8/af_inet; network/af_unix, network/af_mask; domain/interruptible, .notify; namespaces/userns_create, policy/unconfined_restrictions/{userns,io_uring} and four sysctls; ahead of mainline: caps/extended, dbus/mask, domain/kill.signal, domain/unconfined_allowed_children, permission table version 3 | source; seen |
| 6.11 | 24.10 | policy/state32; policy/notify/user = file | source |
| 6.14 | 25.04 | network_v9/af_unix and af_mask (backport); domain/disconnected.ipc | source |
| 6.17 | 25.10 | policy/notify_versions/{v3,v5}, policy/metadata_tagging_version, policy/notify/user = file tags; label in ipc/posix_mqueue; execpath= in the userns record | source |
| 7.0 | 26.04 | network_v9_skb/*; kernel.apparmor_packet_mediation, kernel.apparmor_cache_timeout; backports policy/diff_encode, policy/compressed_load; network_v8/tcp-fast-open, network_v9/tcp-fast-open | source; seen |
| 7.3 | 26.10 | policy/diff-encode (hyphen) and policy/extended_policy_header, both also in mainline 7.3 | source; seen |
| Mainline | Entries | Basis |
|---|---|---|
| 6.13 | policy/state32 | source |
| 6.17 | network_v9/{af_mask,af_unix}, dbus/mask, caps/extended, domain/kill.signal, domain/unconfined_allowed_children, policy/permstable32_version 1 to 3 | source; seen as present on Debian sid and absent on Debian 13 |
| 7.2 | network_v8/tcp-fast-open, network_v9/tcp-fast-open, policy/diff-encode | source |
| 7.3 | policy/compressed_load, policy/extended_policy_header; inet and packet mediation as code without feature entries | source |
Every feature entry that differs between mainline (M) and Ubuntu (U) of the same version, plus two that both gained in 7.3. - means absent. Read from the source; the 6.8, 7.0 and 7.3 Ubuntu columns and the 7.3 mainline column equal what the guests listed.
| feature | 6.8 M | 6.8 U | 6.11 M | 6.11 U | 6.14 M | 6.14 U | 6.17 M | 6.17 U | 7.0 M | 7.0 U | 7.3 M | 7.3 U |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| caps/extended | - | yes | - | yes | - | yes | yes | yes | yes | yes | yes | yes |
| dbus/mask | - | yes | - | yes | - | yes | yes | yes | yes | yes | yes | yes |
| domain/disconnected.ipc | - | - | - | - | - | yes | - | yes | - | yes | - | yes |
| domain/interruptible | - | yes | - | yes | - | yes | - | yes | - | yes | - | yes |
| domain/kill.signal | - | yes | - | yes | - | yes | yes | yes | yes | yes | yes | yes |
| domain/unconfined_allowed_children | - | yes | - | yes | - | yes | yes | yes | yes | yes | yes | yes |
| ipc/posix_mqueue | - | yes | - | yes | - | yes | - | yes | - | yes | - | yes |
| namespaces/userns_create | - | pciu& | - | pciu& | - | pciu& | - | pciu& | - | pciu& | - | pciu& |
| network/af_mask | - | yes | - | yes | - | yes | - | yes | - | yes | - | yes |
| network/af_unix | - | yes | - | yes | - | yes | - | yes | - | yes | - | yes |
| network/tcp-fast-open | - | yes | - | - | - | - | - | - | - | - | - | - |
| network_v8/af_inet | - | yes | - | yes | - | yes | - | yes | - | yes | - | yes |
| network_v8/tcp-fast-open | - | yes | - | - | - | - | - | - | - | yes | yes | yes |
| network_v9/af_mask | - | - | - | - | - | yes | yes | yes | yes | yes | yes | yes |
| network_v9/af_unix | - | - | - | - | - | yes | yes | yes | yes | yes | yes | yes |
| network_v9/tcp-fast-open | - | - | - | - | - | - | - | - | - | yes | yes | yes |
| network_v9_skb/af_mask | - | - | - | - | - | - | - | - | - | inet inet6 | - | inet inet6 |
| network_v9_skb/iface | - | - | - | - | - | - | - | - | - | receive connect, secmark_postroute | - | receive connect, secmark_postroute |
| network_v9_skb/localout | - | - | - | - | - | - | - | - | - | secmark_set | - | secmark_set |
| network_v9_skb/postroute | - | - | - | - | - | - | - | - | - | secmark_send | - | secmark_send |
| network_v9_skb/rcv_skb | - | - | - | - | - | - | - | - | - | secmark_receive | - | secmark_receive |
| network_v9_skb/relabel | - | - | - | - | - | - | - | - | - | setcred | - | setcred |
| policy/compressed_load | - | - | - | - | - | - | - | - | - | yes | yes | yes |
| policy/diff_encode | - | - | - | - | - | - | - | - | - | yes | - | - |
| policy/metadata_tagging_version | - | - | - | - | - | - | - | 1 | - | 1 | - | 1 |
| policy/notify/user | - | - | - | file | - | file | - | file tags | - | file tags | - | file tags |
| policy/notify_versions/v3 | - | - | - | - | - | - | - | yes | - | yes | - | yes |
| policy/notify_versions/v5 | - | - | - | - | - | - | - | yes | - | yes | - | yes |
| policy/permstable32_version | 1 | 3 | 1 | 3 | 1 | 3 | 3 | 3 | 3 | 3 | 3 | 3 |
| policy/state32 | - | - | - | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
| policy/unconfined_restrictions/io_uring | - | yes | - | yes | - | yes | - | yes | - | yes | - | yes |
| policy/unconfined_restrictions/userns | - | yes | - | yes | - | yes | - | yes | - | yes | - | yes |
| policy/diff-encode | - | - | - | - | - | - | - | - | - | - | yes | yes |
| policy/extended_policy_header | - | - | - | - | - | - | - | - | - | - | yes | yes |
The values of policy/unconfined_restrictions/* print as yes in Ubuntu 6.8 and 6.11 and as 1 from 6.14. Equal in both trees at every version: policy/versions v5 to v9, policy/set_load, policy/outofband, policy/permstable32, mount/*, signal/mask, ptrace/mask, io_uring/mask, namespaces/mask, file/mask, query/label/*, rlimit/mask, caps/mask.
Sysctl (kernel.) | Mainline | Ubuntu | Seen |
|---|---|---|---|
unprivileged_userns_apparmor_policy | yes | yes | 1 on all five |
apparmor_display_secid_mode | yes | yes | 0 on all five |
apparmor_restrict_unprivileged_unconfined | yes | yes | 0 on Debian 13, sid and Ubuntu 24.04; 1 on 26.04 and 26.10 |
apparmor_restrict_unprivileged_userns | no | from 6.8 | 1 on 24.04, 26.04, 26.10 |
apparmor_restrict_unprivileged_userns_force, _complain | no | from 6.8 | 0 |
apparmor_restrict_unprivileged_io_uring | no | from 6.8 | 0 |
apparmor_cache_timeout | no | from 7.0 | 5 on 26.04 and 26.10 |
apparmor_packet_mediation | no | from 7.0 | 0 on 26.04 and 26.10 |
The kernel's default of apparmor_restrict_unprivileged_userns is a build option that Ubuntu's configuration sets to off in every series read (source); the value 1 is set from user space.
| Record | Seen on |
|---|---|
operation="create" class="posix_mqueue" ... name="/demo" ... requested="create" denied="create" class="posix_mqueue" fsuid=0 ouid=0 | 24.04, 26.04, 26.10 |
operation="connect" class="net" info="failed local addr match" error=-13 ... daddr=127.0.0.1 dest=22 family="inet" sock_type="stream" protocol=6 requested="connect" denied="connect" | 26.04 (and 24.04, 26.10 in earlier recorded runs) |
apparmor="AUDIT" operation="userns_create" class="namespace" info="Userns create - transitioning profile" profile="unconfined" ... target="unprivileged_userns" | 24.04, 26.04, 26.10 |
apparmor="AUDIT" operation="change_onexec" class="file" info="change_profile unprivileged unconfined converted to stacking" profile="unconfined" name="demo" ... target="demo//&unconfined" | 26.04, 26.10 |
two extra apparmor="ALLOWED" operation="file_perm" records for one complain-mode read | 26.04, 26.10 |
The twelve-rule profile with abi <abi/5.0>,, compiled in each guest by the tree's parser with -Q -K --warn=all (seen).
| Guest kernel | Feature files | Warnings | rule: lines |
|---|---|---|---|
| Debian 13, 6.12.116 | 38 | unix rule downgraded; dbus and mqueue rules not enforced | 19 |
| Ubuntu 24.04, 6.8.0-147 | 51 | none | 66 |
| Ubuntu 26.04, 7.0.0-43 | 67 | none | 67 |
| Debian sid, 7.3.4 | 49 | mqueue rules not enforced | 24 |
| Ubuntu 26.10, 7.3.0-10 | 68 | none | 67 |
af_inet, so deny rules get wider (seen on Debian sid).peer=(ip=... port=...) does not limit connect on Ubuntu 26.04 (seen; cause not determined).mqueue rule for the queue).class="posix_mqueue" twice.prompt capability X, is compiled as an allowed capability.network inet icmp carries protocol number 2, which is IGMP (it matters only where af_inet is present)._force and _complain variants of the userns restriction: not run.prompt permission beyond the denial seen.Ubuntu-7.3.0-10.10, paths under security/apparmor/): the listener file apparmorfs.c:3112; the userns transition task.c:478-499; mqueue checks ipc.c:209; inet matching af_inet.c:271-312; the sysctls lsm.c:2912-2955; packet mediation's switch lsm.c:1887; the unix fallback to older classes include/policy.h:373-388.aa-genprof PROGRAM creates a starter profile in complain mode, then loops: you run the program, (S)can turns the new log records into questions, your answers become rules. (F)inish sets enforce mode. The deck follows one recorded session.
aa-genprof [-d DIR] [-f LOGFILE] [--no-abstraction] [-o OUTDIR] program. Run it as root: it writes into the profile directory, loads profiles and reads the audit log.demo (/usr/bin/demo), the map's example: it reads /etc/demo/demo.conf, looks up a user, reads a word list under /usr/share/demo, writes /var/lib/demo/state.db and /var/log/demo.log, makes a temporary file, opens a TCP connection, raises its priority and runs /usr/bin/demo-helper.demo, three for the helper's profile, one save prompt, then Finish.apparmor="ALLOWED". Explicit deny rules are still enforced in complain mode.aa-logprof asks the same questions without the loop, for every profile at once. See aa-logprof.utils/ (aa-genprof, aa-logprof, aa-autodep and their Python package) and the tree's profiles/apparmor.d were run in a disposable Debian forky/sid guest (kernel 7.3.4+deb14-cloud-amd64; apparmor_parser and the Python binding of libapparmor 5.0.2 from Debian; auditd), as root. Keys were sent by a script on a terminal; the transcripts are findings/tools/observed/session1.txt and session2.txt. The slides quote session 2.do_logprof_pass: aa.py:1501-1516.Before the first question aa-genprof checks the program against logprof.conf, writes a starter profile (abstractions/base and mr on the binary) in complain mode, loads it, sets kernel.printk_ratelimit to 0 and marks the end of the log.
PATH when it has no slash. Errors: Can't find NAME in the system path list..., NAME does not exists, please double-check the path.flags=(complain), include <abstractions/base>, and /usr/bin/demo mr,; abi <abi/5.0>, and include <tunables/global> are added when those files exist in the profile directory. The file is named after the path, /etc/apparmor.d/usr.bin.demo, and the profile has the path as its name, without the profile keyword./proc/sys/kernel/printk_ratelimit is set to 0 so that bursts of records are not dropped, and restored when the tool exits. When that fails: Can't set printk_ratelimit, some events might be lost./var/log/audit/audit.log present the tool notes the time of the last audit record; otherwise it writes a line GenProf: logmark-<time> to the kernel log with logger and scans from there.It seems AppArmor was not started. Please enable AppArmor and try again.utils/ (aa-genprof, aa-logprof, aa-autodep and their Python package) and the tree's profiles/apparmor.d were run in a disposable Debian forky/sid guest (kernel 7.3.4+deb14-cloud-amd64; apparmor_parser and the Python binding of libapparmor 5.0.2 from Debian; auditd), as root. Keys were sent by a script on a terminal; the transcripts are findings/tools/observed/session1.txt and session2.txt. The slides quote session 2.create_new_profile: aa.py:386-428; autodep: aa.py:484-520; check_qualifiers: aa.py:2501-2511.While the profile is in complain mode the program runs normally and every missing permission is logged as apparmor="ALLOWED". (S)can reads the log from the mark, skips what the profile covers and asks about the rest, exec events first.
apparmor="ALLOWED" operation="open" class="file" profile="/usr/bin/demo" name="/etc/demo/demo.conf" comm="demo" requested_mask="r" denied_mask="r" fsuid=0 ouid=0; apparmor="ALLOWED" operation="capable" class="cap" profile="/usr/bin/demo" comm="demo" capability=23 capname="sys_nice"; apparmor="ALLOWED" operation="exec" class="file" profile="/usr/bin/demo" name="/usr/bin/demo-helper" comm="demo" requested_mask="x" denied_mask="x" fsuid=0 ouid=0 target="/usr/bin/demo//null-/usr/bin/demo-helper". The slide shortens them.demo; several records about one path are merged into one question./usr/bin/demo//null-/usr/bin/demo-helper: in complain mode the kernel runs a program the profile has no exec rule for under a temporary profile and logs its accesses under that name. The tool assigns those records to a real profile after you answer the exec question.Complain-mode changes: and Enforce-mode changes: and returns to the prompt.utils/ (aa-genprof, aa-logprof, aa-autodep and their Python package) and the tree's profiles/apparmor.d were run in a disposable Debian forky/sid guest (kernel 7.3.4+deb14-cloud-amd64; apparmor_parser and the Python binding of libapparmor 5.0.2 from Debian; auditd), as root. Keys were sent by a script on a terminal; the transcripts are findings/tools/observed/session1.txt and session2.txt. The slides quote session 2.do_logprof_pass: aa.py:1501-1516; reading from the mark: logparser.py:397-430.An exec record becomes a choice of exec mode: In(h)erit writes ix, (P)rofile px, (C)hild cx, (N)amed an arrow rule, (U)nconfined ux, (D)eny a deny rule. Answering yes to secure execution capitalises the letter. Choosing a profile that does not exist creates it.
Keys of the exec question and what each writes into the profile of the program that ran the exec:
| Key | Rule written | Then |
|---|---|---|
| H, In(h)erit | /usr/bin/demo-helper ix, (with mr) | the helper's records are asked about under the caller's profile |
| P, (P)rofile | /usr/bin/demo-helper px,; Px after yes to secure execution | a profile for the helper is created in complain mode if none exists |
| C, (C)hild | cx or Cx | a child profile is created inside the caller's profile |
| N, (N)amed | asks "Are you specifying a transition to a local profile?" and "Enter profile name to transition to: "; writes px -> NAME or cx -> NAME | |
| U, (U)nconfined | after two warnings ux, or Ux | the helper's records are ignored |
| X, (X) ix On / Off | switches the list to the fallback modes pix, cix | |
| D, (D)eny | deny /usr/bin/demo-helper x, | the helper's records are ignored |
| I, (I)gnore | nothing | asked again at the next scan |
[qualifiers] in logprof.conf: for shells the list has no (P)rofile, for core utilities such as cat neither (P)rofile nor (U)nconfined.Severity: is a number from severity.db for the path with x, or unknown.Adding /usr/bin/demo-helper Px, to profile. and Writing updated profile for /usr/bin/demo-helper.aa-logprof --allow-all answers the secure-execution question with no and writes lowercase px.utils/ (aa-genprof, aa-logprof, aa-autodep and their Python package) and the tree's profiles/apparmor.d were run in a disposable Debian forky/sid guest (kernel 7.3.4+deb14-cloud-amd64; apparmor_parser and the Python binding of libapparmor 5.0.2 from Debian; auditd), as root. Keys were sent by a script on a terminal; the transcripts are findings/tools/observed/session1.txt and session2.txt. The slides quote session 2.ask_exec: aa.py:740-1019; the key list build_x_functions: aa.py:622-661; [qualifiers]: logprof.conf:42-130.Every rule question lists offers and keys. The bracketed default was (D)eny for every question of the session, so Return writes a deny rule; A allows the selected offer. Offers are sorted by name with the first selected: a digit picks another one.
demo in the session, in order: capability sys_nice (answered D: deny capability sys_nice,), /tmp/demo.22t5Sb (A on include <abstractions/user-tmp>), /var/log/demo.log (O then A: /var/log/demo.log w,), /var/lib/demo/state.db (A), /usr/share/demo/words-1.txt (G then A: owner /usr/share/demo/* r,), /etc/passwd, /etc/nsswitch.conf, /etc/demo/demo.conf (A each), the connect event (3 then A), the socket create event (A on the selected offer, the Apache abstraction).(A)llow / [(D)eny]. Known discrepancy: the comparison that should select Allow never matches. Do not press Return to accept. With an include offer selected, Deny writes nothing: the tool prints "Denying via an include file isn't supported by the AppArmor tools" and asks again.abstractions/apache2-common is offered for any inet or inet6 stream socket: it contains network inet stream,. It also allows being traced, signals from Apache's profiles and everything in abstractions/nameservice.Accesses: connect, Network Family: inet, Socket Type: stream, Local: ALL, Peer: {'ip': '127.0.0.1', 'port': 9}. The slide shows two of them on one line and wraps the long offer.(G)lob / Glob with (E)xtension / (N)ew and (O)wner permissions off. Each key is explained in aa-logprof.utils/ (aa-genprof, aa-logprof, aa-autodep and their Python package) and the tree's profiles/apparmor.d were run in a disposable Debian forky/sid guest (kernel 7.3.4+deb14-cloud-amd64; apparmor_parser and the Python binding of libapparmor 5.0.2 from Debian; auditd), as root. Keys were sent by a script on a terminal; the transcripts are findings/tools/observed/session1.txt and session2.txt. The slides quote session 2.ask_rule_questions: aa.py:1128-1292; the default: aa.py:1177-1182; the offers: aa.py:1150-1161.The saved profile holds exactly what was answered: an unrelated abstraction from one accepted offer, owner on files because the session ran as their owner, and exact paths. The file is written sorted, with the path as the profile name. Review it before relying on it.
The file as written after the first save (/etc/apparmor.d/usr.bin.demo on an installed system; the slide leaves out the first four lines and the blank lines):
# Last Modified: Mon Nov 16 12:26:18 2026 abi <abi/5.0>,
include <tunables/global>
/usr/bin/demo { include <abstractions/apache2-common> include <abstractions/base> include <abstractions/user-tmp>
deny capability sys_nice,
network (connect) inet stream peer=(ip=127.0.0.1 port=9),
/usr/bin/demo mr, /usr/bin/demo-helper Px, /var/log/demo.log w, owner /etc/demo/demo.conf r, owner /etc/nsswitch.conf r, owner /etc/passwd r, owner /usr/share/demo/* r, owner /var/lib/demo/state.db w,
}
flags=(complain) is gone from this listing because it was taken after Finish; during the session the profile carries it.include <abstractions/apache2-common> came from accepting the selected offer of the socket create question. It grants network inet stream, and network inet6 stream,, ptrace (readby) and ptrace (tracedby), several signal rules and abstractions/nameservice. With it in place the exact network (connect) rule is redundant.owner: the tool adds it when the record's fsuid equals its ouid. Seen later in the same guest: demo run by an ordinary user under this profile was denied /etc/demo/demo.conf, /usr/share/demo/words-1.txt and /var/lib/demo/state.db (fsuid=1000 ouid=0)./etc/nsswitch.conf and /etc/passwd got their own rules. abstractions/nameservice covers both, but it was not offered for them. Known discrepancy: the tools do not expand variables such as @{etc_ro} when they test whether an abstraction covers a path.deny capability sys_nice, is enforced silently: demo prints setpriority: Permission denied and nothing is logged.usr.bin.demo-helper).utils/ (aa-genprof, aa-logprof, aa-autodep and their Python package) and the tree's profiles/apparmor.d were run in a disposable Debian forky/sid guest (kernel 7.3.4+deb14-cloud-amd64; apparmor_parser and the Python binding of libapparmor 5.0.2 from Debian; auditd), as root. Keys were sent by a script on a terminal; the transcripts are findings/tools/observed/session1.txt and session2.txt. The slides quote session 2.serialize_profile and write_profile, aa.py:2210-2303; the owner decision: file.py:477-479; the abstraction: apache2-common:7-24.(F)inish sets every profile the session created to enforce mode and reloads it. What was not exercised has no rule: observed, a run with a new option is denied /etc/demo/extra.conf. aa-logprof adds such rules later without starting over.
apparmor_parser -r. Messages: Setting /usr/bin/demo to enforce mode., Setting /usr/bin/demo-helper to enforce mode., Reloaded AppArmor profiles in enforce mode., a paragraph inviting you to contribute the profile, Finished generating profile for /usr/bin/demo./usr/bin/demo (enforce), /usr/bin/demo-helper (enforce), and still /usr/bin/demo//null-/usr/bin/demo-helper (complain), the temporary profile from the first run. It is not used again and disappears when the profile is removed or the system restarts.demo as profiled: setpriority: Permission denied (the deny capability sys_nice, answered with D; the program goes on), demo-helper: done, demo: done. The slide shows the last line only. demo extra: /etc/demo/extra.conf: Permission denied, with apparmor="DENIED" operation="open" class="file" profile="/usr/bin/demo" name="/etc/demo/extra.conf" comm="demo" requested_mask="r" denied_mask="r" fsuid=0 ouid=0.aa-complain), run aa-logprof until it asks nothing, then aa-enforce.utils/ (aa-genprof, aa-logprof, aa-autodep and their Python package) and the tree's profiles/apparmor.d were run in a disposable Debian forky/sid guest (kernel 7.3.4+deb14-cloud-amd64; apparmor_parser and the Python binding of libapparmor 5.0.2 from Debian; auditd), as root. Keys were sent by a script on a terminal; the transcripts are findings/tools/observed/session1.txt and session2.txt. The slides quote session 2.aa-autodep PROGRAM writes the starter profile and nothing more. For a script it allows the script with r, the interpreter with ix and adds the interpreter's abstraction. Programs marked in [qualifiers] of logprof.conf are refused. Observed.
aa-autodep [--force] [-d DIR] [--no-reload] program... writes the starter profile for each program that has none (--force overwrites) and loads it in complain mode.#! gets ix, the script itself r. The abstraction is abstractions/bash when the interpreter is sh, bash or dash, and abstractions/perl, abstractions/python or abstractions/ruby for those interpreters; any other interpreter gets none./usr/bin/demo-script (#!/bin/sh) in the session, complete:# Last Modified: Mon Nov 16 12:18:54 2026 abi <abi/5.0>,
include <tunables/global>
/usr/bin/demo-script flags=(complain) { include <abstractions/base> include <abstractions/bash>
/usr/bin/dash ix, /usr/bin/demo-script r,
}
/bin/sh was resolved to /usr/bin/dash: the rule names the file the symlink leads to. See Symlinks.ix the interpreter runs under the script's profile, so the profile must allow everything the script does through it.bash, dash, ksh, zsh), mount, utilities such as awk, cat, chmod, cp, grep, ls, sed, and the perl and python interpreters. A profile attached to /usr/bin/cat would apply to every unconfined use of cat./usr/share/apparmor/extra-profiles), the tool offers to use it instead of the starter profile. Read from the tool's code, not run.utils/ (aa-genprof, aa-logprof, aa-autodep and their Python package) and the tree's profiles/apparmor.d were run in a disposable Debian forky/sid guest (kernel 7.3.4+deb14-cloud-amd64; apparmor_parser and the Python binding of libapparmor 5.0.2 from Debian; auditd), as root. Keys were sent by a script on a terminal; the transcripts are findings/tools/observed/session1.txt and session2.txt. The slides quote session 2.get_interpreter_and_abstraction: aa.py:347-383; check_qualifiers: aa.py:2501-2511; the list: logprof.conf:42-130.Next: ut-logprof, prac-general-purpose, prac-abstractions, syn-exec-modes, syn-owner, ut-modes, adm-denials.
aa-genprof PROGRAM: starter profile in complain mode, then run, (S)can, answer, save, repeat; (F)inish sets enforce mode.owner qualifiers and the width of the paths before relying on it.What each deck answers:
logprof.conf, what goes wrong.Basis of the statements on this page: "observed" means the utilities of the AppArmor tree at 836052d21 (6.0.0~alpha2) were run on 2026-11-16 in a disposable Debian forky/sid guest (kernel 7.3.4+deb14-cloud-amd64, apparmor_parser and the libapparmor Python binding 5.0.2 from Debian, auditd), as root, with keys sent by a script; transcripts are in findings/tools/observed/. "Code" means read from the tree and not run.
| Command | Does |
|---|---|
aa-genprof [-d DIR] [-f LOGFILE] [-j] [--no-abstraction] [-o OUTDIR] program | starter profile if needed, complain mode, the Scan and Finish loop, enforce mode at the end |
aa-autodep [--force] [-d DIR] [--no-reload] program... | writes the starter profile in complain mode |
| Option | Meaning |
|---|---|
-d DIR | profile directory instead of /etc/apparmor.d |
-f LOGFILE | log file to read |
-j | dialogs as JSON, for front ends |
--no-abstraction | do not offer or add abstractions |
-o OUTDIR | write changed profiles to this directory instead |
| Step | Message or effect | Basis |
|---|---|---|
| find the program | errors Can't find ... in the system path list or ... does not exists, please double-check the path. | code |
check [qualifiers] | "... is currently marked as a program that should not have its own profile." | observed |
| read all profiles | Updating AppArmor profiles in DIR. | observed |
| starter profile if none exists | Writing updated profile for PROGRAM. | observed |
| complain mode and reload | Setting PROGRAM to complain mode. | observed |
kernel.printk_ratelimit = 0 | warning Can't set printk_ratelimit, some events might be lost on failure | code |
| mark the log | time of the last audit record, or a GenProf: logmark-... line | code |
| prompt | [(S)can system log for AppArmor events] / (F)inish | observed |
| Scan | Reading log entries from FILE., exec questions, Complain-mode changes:, Enforce-mode changes:, save prompt | observed |
| Finish | Setting PROGRAM to enforce mode. for each profile of the session, Reloaded AppArmor profiles in enforce mode., Finished generating profile for PROGRAM. | observed |
| Program is | Rules |
|---|---|
| a binary | include <abstractions/base>, PROGRAM mr, |
a script with #! | include <abstractions/base>, the interpreter's abstraction (bash, perl, python, ruby) when known, SCRIPT r,, INTERPRETER ix, |
Always with flags=(complain); abi <abi/5.0>, and include <tunables/global> when those files exist in the profile directory. The profile is named by the program's path and stored as that path with slashes turned into dots.
| Key | Rule | Notes |
|---|---|---|
| H | TARGET ix, | |
| P | TARGET px, or Px, | creates a profile for the target if none exists |
| C | TARGET cx, or Cx, | creates a child profile |
| N | px -> NAME or cx -> NAME | asks for the name |
| U | TARGET ux, or Ux, | two confirmations |
| X | toggles pix / cix forms | |
| D | deny TARGET x, | |
| I | nothing | asked again later |
| R, F | abort, finish |
Capital letters result from answering yes to the secure-execution question. The letters offered for a target come from [qualifiers] in logprof.conf.
| Question | Key | Rule written |
|---|---|---|
Execute /usr/bin/demo-helper | P, Y | /usr/bin/demo-helper Px, and a new profile |
capability sys_nice | D | deny capability sys_nice, |
/tmp/demo.22t5Sb owner rw | A | include <abstractions/user-tmp> |
/var/log/demo.log owner w | O, A | /var/log/demo.log w, |
/var/lib/demo/state.db owner w | A | owner /var/lib/demo/state.db w, |
/usr/share/demo/words-1.txt owner r | G, A | owner /usr/share/demo/* r, |
/etc/passwd, /etc/nsswitch.conf, /etc/demo/demo.conf owner r | A | one owner ... r, rule each |
| network connect inet stream | 3, A | network (connect) inet stream peer=(ip=127.0.0.1 port=9), |
| network create inet stream | A | include <abstractions/apache2-common> (the selected offer) |
helper: /var/lib/demo/helper.out, /etc/demo/helper.conf, /etc/ld.so.cache | A | one owner rule each in the helper's profile |
| Changed Local Profiles | S | both files written and reloaded |
abstractions/apache2-common is the first offer for any inet stream socket./etc/ld.so.cache is proposed although abstractions/base covers it, and abstractions/nameservice is not offered for /etc/nsswitch.conf: the tools do not expand variables in abstraction rules.aa-logprof reads the system log, asks one question for each AppArmor record that no rule of the profile covers, writes the answers into the profile file and reloads it. It works on every profile in the profile directory at once.
aa-logprof [-d DIR] [-f LOGFILE] [-m MARK] [-j] [-a] [--no-abstraction] [-o OUTDIR]. Run it as root.apparmor="ALLOWED" from profiles in complain mode (printed under Complain-mode changes:) and apparmor="DENIED" from profiles in enforce mode (under Enforce-mode changes:). Both headers are printed even when a section is empty.demo extra under the enforced profile printed /etc/demo/extra.conf: Permission denied; the log had apparmor="DENIED" operation="open" class="file" profile="/usr/bin/demo" name="/etc/demo/extra.conf" comm="demo" requested_mask="r" denied_mask="r" fsuid=0 ouid=0; aa-logprof asked one question, A wrote owner /etc/demo/extra.conf r,, and after S the next demo extra worked.aa-genprof asks during a scan; aa-genprof adds the starter profile, complain mode and the loop around them. See Generating a profile.deny rule in a profile produces no log record, so aa-logprof never asks about what it blocks.utils/ (aa-genprof, aa-logprof and their Python package) and the tree's profiles/apparmor.d were run in a disposable Debian forky/sid guest (kernel 7.3.4+deb14-cloud-amd64; apparmor_parser and the Python binding of libapparmor 5.0.2 from Debian; auditd), as root. Keys were sent by a script on a terminal; the transcripts are findings/tools/observed/session1.txt and session2.txt.do_logprof_pass: aa.py:1501-1516.The log is the first existing file of /var/log/audit/audit.log, /var/log/syslog, /var/log/messages, or -f FILE. It is read from the top, or after the mark given with -m. Covered records and records of profiles without a file are skipped silently.
logfiles setting of logprof.conf: /var/log/audit/audit.log /var/log/syslog /var/log/messages. The first that exists is used.ERROR: Can't find system log "/var/log/syslog". Please check permissions., exit status 1. Observed after moving audit.log aside in the guest. Install auditd, or write the kernel log to a file (for example journalctl -k > FILE) and pass it with -f; whether every field survives that route was not checked.-f and a missing file: The logfile FILE does not exist. Please check the path.apparmor=, operation= or type=AVC are parsed. Records of kind AUDIT, STATUS (profile loads) and ERROR are dropped.audit.log held denials for four other loaded profiles, and no question was asked about them.aa-logprof run of the session asked nothing.-m MARK skips every line before the first one that contains MARK; that line and the ones after it are read. aa-genprof uses this with its own mark. Observed: aa-logprof -m no-such-mark printed the two section headers and exited with status 0.utils/ (aa-genprof, aa-logprof and their Python package) and the tree's profiles/apparmor.d were run in a disposable Debian forky/sid guest (kernel 7.3.4+deb14-cloud-amd64; apparmor_parser and the Python binding of libapparmor 5.0.2 from Debian; auditd), as root. Keys were sent by a script on a terminal; the transcripts are findings/tools/observed/session1.txt and session2.txt.set_logfile: aa.py:1478-1498; the line filter: logparser.py:59; dropped records: logparser.py:297-320; the mark: logparser.py:397-430.A question has headers (profile, what was requested, severity), numbered offers with one selected, and a row of keys. A adds the selected offer, D adds it as a deny rule, I skips it. The bracketed default was (D)eny throughout the session.
Keys of a rule question:
| Key | Effect |
|---|---|
| A, (A)llow | add the selected offer; an include offer also removes rules it makes redundant ("Deleted N previous matching profile entries.") |
| D, (D)eny | add the selected rule with deny; on an include offer: "Denying via an include file isn't supported by the AppArmor tools" |
| I, (I)gnore | write nothing; the record is asked about again on the next run |
| G, (G)lob | file questions: add a wider path to the offers |
| E, Glob with (E)xtension | file questions: the same, keeping the file extension |
| N, (N)ew | file questions: type a path |
| T, Audi(t) | toggle the audit qualifier on the offers |
| O, (O)wner permissions on / off | file questions: toggle owner on the offers |
| R, Abo(r)t | "Are you sure you want to abandon this set of profile changes and exit?" |
| F, (F)inish | stop asking and go to the save prompt |
| 1 to 9, arrow keys | select another offer |
| Return | the bracketed default |
Path and New Mode for files; Capability; Accesses, Network Family, Socket Type, Local, Peer for network; and so on for signals, ptrace, mounts and D-Bus.Old Mode appears when rules of the profile already give some permission on the path; the offer then holds the merged permissions.Severity comes from severity.db: for example CAP_SYS_ADMIN 10, CAP_NET_RAW 8; paths have a number per access letter; unknown when nothing matches. It changes no default.[(D)eny]. Known discrepancy: the test that should select Allow never matches.utils/ (aa-genprof, aa-logprof and their Python package) and the tree's profiles/apparmor.d were run in a disposable Debian forky/sid guest (kernel 7.3.4+deb14-cloud-amd64; apparmor_parser and the Python binding of libapparmor 5.0.2 from Debian; auditd), as root. Keys were sent by a script on a terminal; the transcripts are findings/tools/observed/session1.txt and session2.txt.ask_rule_questions: aa.py:1128-1292; available_buttons: aa.py:1331-1361; the prompt loop: ui.py:407-564; the default: aa.py:1177-1182.The tool proposes an owner rule when the record's fsuid equals its ouid. A profile made as root on root's files then fails for other users. Observed: the later question shows Old Mode: owner r, New Mode: r and replaces the rule. O toggles owner.
fsuid (the user the program ran as) and ouid (the file's owner). When they are equal the tool sets owner on the proposed rule and shows New Mode: owner r.(O)wner permissions off removes owner from every offer of the question; the key then reads (O)wner permissions on. Session: O then A on /var/log/demo.log wrote /var/log/demo.log w,.owner /etc/demo/demo.conf r,. demo started by the user tester: /etc/demo/demo.conf: Permission denied, /usr/share/demo/words-1.txt: Permission denied, /var/lib/demo/state.db: Permission denied, with records such as apparmor="DENIED" operation="open" class="file" profile="/usr/bin/demo" name="/etc/demo/demo.conf" comm="demo" requested_mask="r" denied_mask="r" fsuid=1000 ouid=0.aa-logprof run asked with Old Mode: owner r and New Mode: r; A printed Adding /etc/demo/demo.conf r, to profile. and Deleted 1 previous matching profile entries.owner /usr/share/demo/* r, next to /usr/share/** r,.owner, which then also allow that user's program to read other users' files matched by the same path.default_owner_prompt setting of logprof.conf describes ways to change this behaviour. Known discrepancy: the setting is cleared when the file is read and has no effect.utils/ (aa-genprof, aa-logprof and their Python package) and the tree's profiles/apparmor.d were run in a disposable Debian forky/sid guest (kernel 7.3.4+deb14-cloud-amd64; apparmor_parser and the Python binding of libapparmor 5.0.2 from Debian; auditd), as root. Keys were sent by a script on a terminal; the transcripts are findings/tools/observed/session1.txt and session2.txt.fsuid and ouid fields)owner from fsuid == ouid: file.py:477-479; merging with existing permissions, propose_file_rules: aa.py:2378-2417; the toggle: aa.py:1204-1212.(G)lob replaces the last path component with *; pressed again it removes a directory and ends in /**. Glob with (E)xtension keeps the extension. Each press adds an offer and selects it. Observed: one press gave /usr/share/demo/*; a press on that offer in a later run gave /usr/share/**.
/usr/share/demo/words-1.txt → /usr/share/demo/* → /usr/share/** → /usr/** → /**. A path that already ends in /* or /** loses one more directory and ends in /**. Directory paths keep their trailing slash (/*/, /**/)./var/lib/demo/state.db → /var/lib/demo/*.db → /var/lib/**.db → /var/**.db. A file without an extension is left as it is.Enter new path: with the current path to edit. When the typed path does not match the logged one the tool asks: "The specified path does not match this log entry ... Do you really want to use this path?" (default no). A path that does not start with / or a variable: "The path you entered is invalid (not starting with / or a variable)!"/usr/share/demo/* r, was listed first for words-1.txt), and substitutions from the [globs] section of logprof.conf, for example /home/NAME to /home/*, /proc/PID/ to /proc/*/, and library names with their version replaced.words-1.txt (after the denial for another user) G was pressed once on the selected offer /usr/share/demo/* r, and A wrote /usr/share/** r,. That rule lets demo read every file under /usr/share.utils/ (aa-genprof, aa-logprof and their Python package) and the tree's profiles/apparmor.d were run in a disposable Debian forky/sid guest (kernel 7.3.4+deb14-cloud-amd64; apparmor_parser and the Python binding of libapparmor 5.0.2 from Debian; auditd), as root. Keys were sent by a script on a terminal; the transcripts are findings/tools/observed/session1.txt and session2.txt.glob_path and glob_path_withext: aare.py:97-146; the keys in ask_rule_questions: aa.py:1248-1287; [globs]: logprof.conf:140-179.(S)ave Changes writes each changed profile completely from the tool's model (sorted, with a # Last Modified line) to a temporary file, renames it over the profile and reloads it with apparmor_parser -r. (V)iew Changes shows a diff first.
(S)ave Changes (all), Save Selec(t)ed Profile, (V)iew Changes (the default; diff -u of the file on disk against the new text, shown with less), View Changes b/w (C)lean profiles (both sides as the tool would write them, so that only rule changes show), Abo(r)t.~ in the profile directory (or the directory given with -o), given the permissions of the old file, and renamed over it. A new file is created with mode 0600.apparmor_parser -I DIR --base DIR -r FILE. If the parser reports an error, the error is printed and the tool continues; the file on disk is the new one and the kernel keeps the old profile.# Last Modified: DATE, the abi line, preamble includes, then the profile with its includes, capability rules, network rules and file rules, each group sorted, separated by blank lines. Hand formatting and rule order of the previous file are not kept./etc/demo/demo.conf r,, /usr/share/** r,, /var/lib/demo/*.db w,, /var/log/demo.log w,, owner /etc/demo/extra.conf r,, owner /usr/share/demo/* r,. The last one is covered by /usr/share/** r, and was not removed.aa-cleanprof removes rules that other rules or includes cover. See Cleaning and merging profiles.utils/ (aa-genprof, aa-logprof and their Python package) and the tree's profiles/apparmor.d were run in a disposable Debian forky/sid guest (kernel 7.3.4+deb14-cloud-amd64; apparmor_parser and the Python binding of libapparmor 5.0.2 from Debian; auditd), as root. Keys were sent by a script on a terminal; the transcripts are findings/tools/observed/session1.txt and session2.txt.save_profiles: aa.py:1519-1580; serialize_profile and write_profile: aa.py:2210-2303; reload_profile: aa.py:2420-2438; the diff: ui.py:276-319./etc/apparmor/logprof.conf: [settings] names the profile directory, the log files and the parser; [qualifiers] lists per program the exec answers offered and whether it may be profiled; [globs] adds ready-made path offers. severity.db holds the severity numbers.
[settings]:
| Setting | Shipped value | Meaning |
|---|---|---|
profiledir | /etc/apparmor.d /etc/subdomain.d | first existing directory is used; -d overrides |
inactive_profiledir | /usr/share/apparmor/extra-profiles | profiles offered instead of a starter profile |
logfiles | /var/log/audit/audit.log /var/log/syslog /var/log/messages | first existing file is read; -f overrides |
parser | /sbin/apparmor_parser /sbin/subdomain_parser | used to reload profiles |
logger | /bin/logger /usr/bin/logger | used by aa-genprof to write its mark |
default_owner_prompt | 1 | described with four values; cleared when the file is read (known discrepancy) |
custom_includes | empty | extra directories under the profile directory searched for include offers |
json_log | 0 | with --json, log the dialog to a temporary file |
[qualifiers]: PROGRAM = LETTERS. The letters are the exec answers offered when another program runs this one: i inherit, c child, n named, u unconfined, p its own profile. Programs not listed get all five. Shipped: shells icnu; mount and a few others u; utilities such as awk, cat, chmod, cp, grep, ls, sed and the perl and python interpreters icn. aa-genprof and aa-autodep refuse a listed program unless its value is exactly p.
[globs]: REGEX = REPLACEMENT. When the regular expression matches a logged path, the replaced path is added to the offers. Shipped entries cover library names, kernel module directories, /proc/PID/, /home/NAME, perl module trees, locale and timezone data, fonts and PAM files.
[required_hats] and [defaulthat]: hats that new profiles for Apache get.
severity.db lists a number from 0 to 10 for each capability (CAP_SYS_ADMIN 10, CAP_DAC_OVERRIDE 9, CAP_NET_RAW 8) and for path patterns with their access letters. It is shown as Severity: and has no other effect.--configdir DIR (not shown in --help) makes the tools read logprof.conf and severity.db from another directory.init_aa: aa.py:2573-2611; qualifiers in the exec question: aa.py:771; glob_common: aa.py:2537-2554.Seen in the recorded sessions: the default answer is Deny; offers are sorted by name with the first selected; rules written with variables are not recognised as covering a path; owner is derived from one record; only what ran is logged. --allow-all accepts the selected offer every time.
(A)llow / [(D)eny], under Complain-mode changes: as well. Pressing Return writes a deny rule; the program then fails at that point and, because deny rules are not logged, later runs of the tool show nothing. Known discrepancy.demo's TCP socket: [1 - include <abstractions/apache2-common>], 2 - include <abstractions/nameservice>, 3 - network (connect) inet stream peer=(ip=127.0.0.1 port=9),. Accepting the selected offer gave demo Apache's ptrace and signal rules. --no-abstraction turns the include offers off.@{etc_ro} or @{PROC}. Seen: owner /etc/ld.so.cache r, proposed for a profile that includes abstractions/base; /etc/nsswitch.conf and /etc/passwd proposed as single rules with no offer of abstractions/nameservice.owner from one record: see the scene "owner, and the merged mode".deny rules and denials silenced with deny never reach the log.aa-logprof -a / --allow-all answers every rule question with Allow on the selected offer, every exec question with (P)rofile when the target has a profile and In(h)erit otherwise, and every yes/no question with no. Read from the tool's code, not run in these sessions. Known discrepancy: because the secure-execution question is answered no, it writes lowercase px.port= is not seen as covering a logged event, so the same question returns on every run; events of children and hats defined in included files are dropped.(V)iew Changes before (S)ave Changes is the review step.utils/ (aa-genprof, aa-logprof and their Python package) and the tree's profiles/apparmor.d were run in a disposable Debian forky/sid guest (kernel 7.3.4+deb14-cloud-amd64; apparmor_parser and the Python binding of libapparmor 5.0.2 from Debian; auditd), as root. Keys were sent by a script on a terminal; the transcripts are findings/tools/observed/session1.txt and session2.txt.allow_all mode: ui.py:78-80, ui.py:518-526.Next: ut-genprof, prac-abstractions, prac-general-purpose, syn-owner, syn-globbing, adm-denials, ut-cleanprof.
aa-logprof reads the log, asks about records no rule covers, writes the whole profile again with the answers and reloads it.owner, and how far Glob goes; view the changes before saving.What each deck answers:
Basis of the statements on this page: "observed" means the utilities of the AppArmor tree at 836052d21 (6.0.0~alpha2) were run on 2026-11-16 in a disposable Debian forky/sid guest (kernel 7.3.4+deb14-cloud-amd64, apparmor_parser and the libapparmor Python binding 5.0.2 from Debian, auditd), as root, with keys sent by a script; transcripts are in findings/tools/observed/. "Code" means read from the tree and not run.
aa-logprof [-d DIR] [-f LOGFILE] [-m MARK] [-j] [-a] [--no-abstraction] [-o OUTDIR]
| Option | Meaning |
|---|---|
-d DIR, --dir | profile directory instead of the one from logprof.conf |
-f FILE, --file | log file to read |
-m MARK, --mark | start after the first log line containing MARK |
-j, --json | dialogs as JSON on standard output, answers on standard input |
-a, --allow-all | accept the selected offer for every question without asking |
--no-abstraction | do not offer abstractions |
-o DIR, --output-dir | write changed profiles into DIR |
| Step | What happens | Basis |
|---|---|---|
| 1 | Updating AppArmor profiles in DIR.: every profile in the directory is read | observed |
| 2 | Reading log entries from FILE. | observed |
| 3 | exec questions | observed |
| 4 | hat and child profile requests | code |
| 5 | Complain-mode changes: then Enforce-mode changes:, per profile, rule questions | observed |
| 6 | = Changed Local Profiles =: view, save | observed |
| 7 | Writing updated profile for NAME., reload | observed |
| Key | Menu text | Effect |
|---|---|---|
| A | (A)llow | add the selected offer |
| D | (D)eny | add it as a deny rule |
| I | (I)gnore | skip for now |
| G | (G)lob | add a wider path (files) |
| E | Glob with (E)xtension | add a wider path keeping the extension (files) |
| N | (N)ew | type a path (files) |
| T | Audi(t) / Audi(t) off | toggle audit |
| O | (O)wner permissions on / off | toggle owner (files) |
| R | Abo(r)t | leave without saving, after a confirmation |
| F | (F)inish | go to the save prompt |
| digits, arrows | select an offer | |
| Return | the bracketed default; observed to be (D)eny for every rule question |
| Offer | Source |
|---|---|
include <abstractions/...> | every abstraction with a rule covering the record, in name order; not those already included; not those marked # LOGPROF-SUGGEST: no; none with --no-abstraction |
| the exact rule | the log record, with owner when fsuid equals ouid, and with the permissions the profile already grants on the path merged in |
| paths of existing rules | rules of the profile whose path matches the logged path |
[globs] substitutions | logprof.conf |
| Glob, Glob with Extension, New | added by key |
| Start | (G)lob | again |
|---|---|---|
/usr/share/demo/words-1.txt | /usr/share/demo/* | /usr/share/** |
/var/lib/demo/ | /var/lib/*/ | /var/**/ |
| Start | Glob with (E)xtension | again |
|---|---|---|
/var/lib/demo/state.db | /var/lib/demo/*.db | /var/lib/**.db |
The first row of each table was observed; the others follow the tool's code.
| Message | When |
|---|---|
ERROR: Can't find system log "/var/log/syslog". Please check permissions. | none of the configured log files exists (observed) |
The logfile FILE does not exist. Please check the path. | -f names a missing file |
It seems AppArmor was not started. Please enable AppArmor and try again. | AppArmor's interface is not mounted |
Adding RULE to profile. | after Allow or Deny (observed) |
Deleted N previous matching profile entries. | the new rule replaced exact duplicates (observed) |
Denying via an include file isn't supported by the AppArmor tools | Deny pressed on an include offer |
The specified path does not match this log entry ... | (N)ew with a path that does not match |
Writing updated profile for NAME. | on save (observed) |
Named by the titles used in the project's bug list where one exists:
abstractions/apache2-common is offered first for any inet stream socket (seen; reported with this deck).@{...} covers a logged path" (seen).aa-logprof --allow-all writes lowercase px, without environment scrubbing".port= as covering a logged event".default_owner_prompt in logprof.conf has no effect (read from the code; reported with this deck).AppArmor confines a program to what its profile allows. The check is made by the kernel, in addition to ordinary file permissions.
apparmor (lsm.c:2648). In the kernel it registers one table of 81 hooks, apparmor_hooks[] (lsm.c:1785, registered at lsm.c:2621).aa_path_perm(op, current_cred(), label, path, 0, mask, cond), made only when the label of the calling process is not unconfined (lsm.c:229-232).-EACCES, "Permission denied" (file.c:246-247)./sys/module/apparmor/parameters/enabled reads Y (lsm.c:2018); the boot parameter is apparmor= (lsm.c:2029). The command aa-enabled prints Yes and exits 0 (aa_enabled.c:92-99).demo, its files and the SSH key scenario are invented for the map. Nothing on this slide was observed on a running kernel.A profile is a named set of rules kept as text under /etc/apparmor.d. What no rule allows is refused. The language has many more rule kinds; the syntax map lists them.
-Q -K --skip-kernel-load --warn=all: exit status 0, no warning. It was not loaded into a kernel./etc/apparmor.d (parser_include.c:63-67); apparmor_parser -b DIR (--base) changes it (parser_main.c:153).include <abstractions/base> reads abstractions/base from the base directory: base.-EACCES (file.c:246-247). In enforce mode the record type is DENIED (audit.c:211-214).aa-genprof PROGRAM and aa-logprof read the log and propose rules (aa.py:1501-1507).network inet stream, (network), path rules with r and rwk (access modes), owner (owner), Px -> demo-helper (named transitions)./etc/apparmor.d) on apparmor.net.apparmor_parser loads a profile; the kernel attaches it at exec, by the program's path. A process started before the load stays unconfined until it is restarted. Its label reads demo (enforce).
apparmor_parser -r FILE (--replace, parser_main.c:156). It writes the compiled policy to /sys/kernel/security/apparmor/.replace (apparmorfs.c:2942).apparmor.service runs /lib/apparmor/apparmor.systemd reload (apparmor.service:22), which runs the parser over each profile directory (rc.apparmor.functions:137).bprm_creds_for_exec (lsm.c:1862). For an unconfined task the kernel searches the loaded profiles for one whose attachment matches the path of the program (domain.c:697-699). Nothing does this for a task that is already running.cat /proc/PID/attr/current, or /proc/PID/attr/apparmor/current, the name libapparmor tries first (kernel.c:424-426). The kernel answers in apparmor_getprocattr (lsm.c:828-835).unconfined, or LABEL (MODE) such as demo (enforce). libapparmor splits it at the last ( (kernel.c:578-615).int aa_getcon(char **label, char **mode); and int aa_gettaskcon(pid_t target, char **label, char **mode); (apparmor.h:110-111)./sys/kernel/security/apparmor/profiles (apparmorfs.c:2709), which aa-status reads (aa_status.c:175-179)./proc output on the slide are invented; they follow the format above and are not a captured session.The kernel checks files, exec, capabilities, resource limits, mounts, network and unix sockets, signals, ptrace, user namespace creation and io_uring. Each has a rule kind in the profile language.
All of this is read from the kernel source, not observed on a running kernel. The full table, with the operation names that appear in the log, is in the reference under this deck.
apparmor_hooks[] (lsm.c:1785).path_link, path_unlink, path_symlink, path_mkdir, path_rmdir, path_mknod, path_rename, path_chmod, path_chown, path_truncate, inode_getattr (lsm.c:1796-1806). Open files: file_open, file_permission, mmap_file, file_lock and others (lsm.c:1808-1816).bprm_creds_for_exec (lsm.c:1862). Capabilities: capable (lsm.c:1789). Resource limits: task_setrlimit (lsm.c:1871).sb_mount, move_mount, sb_umount, sb_pivotroot (lsm.c:1791-1794). Sockets: socket_create to socket_shutdown (lsm.c:1830-1843); unix sockets also unix_stream_connect and unix_may_send (lsm.c:1827-1828).task_kill; user namespaces: userns_create (lsm.c:1872-1873). Ptrace: ptrace_access_check, ptrace_traceme (lsm.c:1786-1787). io_uring: uring_override_creds, uring_sqpoll (lsm.c:1888-1889).if (!unconfined(label)) before asking the profile (lsm.c:229-232)./sys/kernel/security/apparmor/features/network_v9/af_unix (net.c:31-35).AA_CLASS_FILE 2, AA_CLASS_CAP 3, AA_CLASS_MOUNT 7, AA_CLASS_NETV9 15, AA_CLASS_NS 21, AA_CLASS_IO_URING 22 and the rest) are at apparmor.h:19-41.apparmor_capable has the same shape as the file wrapper (lsm.c:199); signals are checked in apparmor_task_kill (lsm.c:1023) and user namespace creation in apparmor_userns_create (lsm.c:1051).A rule is enforced only where a check for it exists. This map describes mainline Linux; features/ shows what your kernel supports. Which kernel enforces what is in the deck Upstream and Ubuntu kernels; dbus rules, enforced by the bus daemon, are in D-Bus mediation.
ls /sys/kernel/security/apparmor/features. In the kernel the entries are policy, domain, file, network_v8, network_v9, mount, namespaces, capability, rlimit, caps, ptrace, signal, dbus, query, io_uring (apparmorfs.c:2684-2700). The listing on the slide is that table sorted as ls prints it; it is not a captured session.aa-features-abi -x prints the feature set of the running kernel in the form used by the abi rule (aa-features-abi.pod:64)./sys/kernel/security/apparmor/features (features.c:53). A rule class the kernel lacks is left out and the profile still loads; apparmor_parser --warn=rule-not-enforced reports it (parser_main.c:281).features/dbus/mask contains acquire send receive (apparmorfs.c:2662-2663), but the kernel has no D-Bus check point: the bus daemon asks the kernel through /sys/kernel/security/apparmor/.access (apparmorfs.c:2704).mqueue rules; the prompt qualifier is unpacked and not acted on.features directory is one row of the top-level table of the AppArmor filesystem (apparmorfs.c:2714).enforce refuses and logs DENIED. complain allows and logs ALLOWED. kill logs KILLED and signals the process. unconfined is not checked. The mode is a flag: flags=(complain).
Kernel behaviour is read from the kernel source, not observed on a running kernel.
profile demo /usr/bin/demo flags=(complain) {. The mode names the parser accepts are enforce, complain, kill, unconfined, prompt and default_allow (profile.cc:30-39); no flag means enforce.-EACCES (file.c:246-247) and the record type is DENIED.ALLOWED (audit.c:211-212) and the errors -EPERM and -EACCES become success (audit.h:206-211). Other errors are returned unchanged.KILLED and the process is sent the profile's signal (audit.c:221-231). The signal is SIGKILL (policy.c:412) unless the flag kill.signal=NAME names another.AUDIT, ALLOWED, DENIED, HINT, STATUS, ERROR, KILLED are the table at audit.c:29-38.~(perms->allow | perms->deny), so a permission named by a deny rule stays refused (file.c:117-118).Profile flag 'complain' conflicts with 'kill' (profile.h:307), Invalid profile flag: NAME. (profile.h:261)./etc/apparmor.d/force-complain/ forces complain mode; the parser prints Warning: found NAME in /etc/apparmor.d/force-complain, forcing complain mode (parser_main.c:1330-1332). aa-complain and aa-enforce edit the flags and reload.aa_apply_modes_to_perms (lib.c:364-372): kill sets perms->kill, complain sets perms->complain, the user mode (flag prompt) sets perms->prompt.profile_mode_packed (profile.h:75-87): no mode packs as enforce, default_allow as unconfined.A denial names the profile, the operation, the object and the refused permission. name plus denied_mask is the rule that would allow it. In complain mode the same line says ALLOWED.
dmesg, journalctl -k), or /var/log/audit/audit.log when auditd runs. The record is type=1400 (AVC).apparmor=, operation=, class=, info=, error=, namespace=, profile= (or label= for a stack), name= (audit.c:93-141).requested_mask=, denied_mask=, fsuid=, ouid=, target= (file.c:45-76). pid= and comm= are added by the kernel's common LSM audit code (audit.c:164).name is the path and denied_mask the permission letters. For the corpus line above the rule is /home/user/.ssh/ r, (avc_audit_01.profile:2).aa-logprof parses each line with libapparmor's parse_record (logparser.py:288) and asks what to do with it.name taken from a user-controlled source can appear hex-encoded; aa-decode decodes it.Next: the pipeline for how policy is compiled and loaded, the syntax map for the language, attachment for how profiles are picked.
/etc/apparmor.d, apparmor_parser -r FILE, attachment at exec, a check at each LSM hook, a mode, a record in the log.aa-status (loaded profiles and confined processes), cat /proc/PID/attr/current (the label of one process), journalctl -k | grep apparmor= (the records).The program demo and its files are invented for this map. Its profile is the nine lines below.
abi <abi/5.0>,
include <tunables/global>
profile demo /usr/bin/demo {
include <abstractions/base>
network inet stream,
/etc/demo/** r,
owner /var/lib/demo/** rwk,
/usr/bin/demo-helper Px -> demo-helper,
}
The profile was compiled, without loading it, by the tree's parser (6.0.0~alpha2) through tools/head-parser, with -Q -K --skip-kernel-load --warn=all, --base set to the tree's profiles/apparmor.d and the tree's abi/5.0 features. The parser exited 0 and printed no warning.
No kernel with AppArmor was available when this deck was written. The log line in the denial scene and the output of /proc/4242/attr/current are built from the kernel's format strings and from lines of the libapparmor test corpus. They are not a captured session, and the process ids are invented.
| Operation group | Rule kind in a profile | Operation names in the log |
|---|---|---|
| Files, by path | path rules, link | link, unlink, symlink, mkdir, rmdir, mknod, rename_src, rename_dest, chmod, chown, truncate, getattr |
| Open files | path rules (r w a k m) | open, file_receive, file_perm, file_mmap, file_mprotect, file_lock |
| Starting programs and changing profile | exec modes (ix, Px, Cx, Ux), change_profile, hats | exec, change_hat, change_profile, change_onexec, stack, stack_onexec |
| Capabilities | capability | capable |
| Resource limits | set rlimit | setrlimit |
| Mounts | mount, remount, umount, pivot_root | mount, umount, pivotroot |
| Network sockets | network | create, post_create, bind, connect, listen, accept, sendmsg, recvmsg, getsockname, getpeername, getsockopt, setsockopt, socket_shutdown |
| Unix sockets | unix | the socket operations above |
| Signals | signal | signal |
| Tracing | ptrace | ptrace |
| User namespaces | userns | userns_create |
| io_uring | io_uring | uring_override, uring_sqpoll |
open is checked when the file is opened and a later read is checked again as file_perm.A rule in a profile is enforced only where a check for it exists. This deck describes mainline Linux 7.4, read at commit 97d73c825 (7.4-rc2). The answer changes between releases and between mainline and distribution kernels.
mqueue and prompt are covered there.dbus rules are enforced by the bus daemon, not by the kernel. See dbus-mediation./sys/kernel/security/apparmor/features on the running system instead of assuming. See adm-features.| Flag in the profile | Kernel mode | When no rule allows the access | Log type |
|---|---|---|---|
none, or enforce | enforce | The operation fails. For a file the error is EACCES, "Permission denied" | DENIED |
complain | complain | The operation goes ahead | ALLOWED |
kill | kill | The operation fails and the process is sent a signal, SIGKILL unless kill.signal= names another | KILLED |
unconfined | unconfined | Not checked | none |
prompt | user | Not acted on in mainline Linux 7.4, see upstream-and-ubuntu | |
default_allow | unconfined | The parser packs it as unconfined | none |
flags=(complain), or the short form (complain).deny rule still refuses, silently. By the code of mainline Linux 7.4 an audit deny file rule is the exception: it is logged as ALLOWED and let through (file.c:142-149, audit.c:211-234; read, not run). A stacked profile or a peer's profile that is in enforce mode can still refuse too.EPERM and EACCES into success. Other errors are returned unchanged.kill.signal=NAME chooses the signal of kill mode. An unknown name is the error unknown signal specified for kill.signal='NAME'.Profile flag 'complain' conflicts with 'kill'.Invalid profile flag: NAME.force-complain directory under the base directory forces complain mode. The parser prints Warning: found NAME in /etc/apparmor.d/force-complain, forcing complain mode.See syn-flags-modes.
Two real lines from the libapparmor test corpus. The first is libraries/libapparmor/testsuite/test_multi/avc_audit_01.in:
type=AVC msg=audit(1279948288.415:39): apparmor="DENIED" operation="open" parent=12332 profile="/usr/sbin/cupsd" name="/home/user/.ssh/" pid=12333 comm="ls" requested_mask="r" denied_mask="r" fsuid=0 ouid=1000
The rule that allows it, from avc_audit_01.profile beside it:
/usr/sbin/cupsd {
/home/user/.ssh/ r,
}
The second is newer and carries class=. It is libraries/libapparmor/testsuite/test_multi/file_without_filename.in:
Mar 03 07:48:21 examplehost.internal kernel: audit: type=1400 audit(1772549301.213:78826): apparmor="DENIED" operation="open" class="file" profile="firefox" pid=16417 comm="vaapitest" requested_mask="wr" denied_mask="wr" fsuid=1000 ouid=0
| Field | Meaning |
|---|---|
apparmor | The record type: AUDIT, ALLOWED, DENIED, HINT, STATUS, ERROR or KILLED |
operation | What was attempted, see the table of operation names above |
class | The rule class that was consulted, such as file |
info, error | An explanation and an error number, when the kernel has one |
namespace | The policy namespace, when the profile is not in the root namespace |
profile | The profile that made the decision. For a stack of profiles the field is label |
name | The object: for a file, its path |
requested_mask | Everything that was asked for |
denied_mask | Only the part that was refused |
fsuid, ouid | The user id of the process and the owner of the file |
target | A second name or a target label, when the operation has one |
pid, comm | The process id and command name |
apparmor="ALLOWED" is the same event in complain mode. apparmor="AUDIT" is an allowed access that an audit rule asked to log.deny rule without audit writes no record.name, can appear hex-encoded instead of quoted.See adm-denials.
/etc/apparmor.d.apparmor_parser -r FILE compiles a profile and loads it, replacing a loaded profile of the same name.apparmor.service runs /lib/apparmor/apparmor.systemd reload, which loads every profile.aa-load loads already compiled policy from the cache without running the compiler.EACCES when that permission is missing or when policy is locked.Cache read/write disabled: interface file missing. (Kernel needs AppArmor 2.4 compatibility patch.)/proc/PID/attr/current. It is the word unconfined, or the label followed by the mode: demo (enforce).See pipeline, adm-loading and ut-status.
AppArmor registers one table, apparmor_hooks[] (linux:security/apparmor/lsm.c:1785), with security_add_hooks in apparmor_init (lsm.c:2621). It has 81 LSM_HOOK_INIT entries; 55 of them decide an access. The number after each hook is its line in lsm.c.
| Group | Hooks | Class and code |
|---|---|---|
| Files by path | path_link 1796, path_unlink 1797, path_symlink 1798, path_mkdir 1799, path_rmdir 1800, path_mknod 1801, path_rename 1802, path_chmod 1803, path_chown 1804, path_truncate 1805, inode_getattr 1806 | AA_CLASS_FILE; operation names at include/audit.h:50-61 |
| Open files | file_open 1808, file_receive 1809, file_permission 1810, mmap_file 1813, file_mprotect 1814, file_lock 1815, file_truncate 1816 | AA_CLASS_FILE; include/audit.h:62-68 |
| Exec and domain change | bprm_creds_for_exec 1862, bprm_committing_creds 1863, bprm_committed_creds 1864, setprocattr 1821, setselfattr 1819 | apparmor_bprm_creds_for_exec at domain.c:985 |
| Capabilities | capable 1789, capget 1788 | AA_CLASS_CAP; aa_capable |
| Resource limits | task_setrlimit 1871 | AA_CLASS_RLIMITS |
| Mount | sb_mount 1792, move_mount 1791, sb_umount 1793, sb_pivotroot 1794 | AA_CLASS_MOUNT; apparmor_sb_mount dispatches on the flags at lsm.c:707-742 |
| Network sockets | socket_create 1830, socket_post_create 1831, socket_socketpair 1832, socket_bind 1833, socket_connect 1834, socket_listen 1835, socket_accept 1836, socket_sendmsg 1837, socket_recvmsg 1838, socket_getsockname 1839, socket_getpeername 1840, socket_getsockopt 1841, socket_setsockopt 1842, socket_shutdown 1843, sctp_bind_connect 1844 | AA_CLASS_NET, AA_CLASS_NETV9; include/audit.h:75-87 |
| Unix sockets | unix_stream_connect 1827, unix_may_send 1828, and the socket hooks for AF_UNIX | af_unix.c; feature network_v9/af_unix at net.c:33 |
| Packets (secmark) | socket_sock_rcv_skb 1846, inet_conn_request 1854, under CONFIG_NETWORK_SECMARK; netfilter hook apparmor_ip_postroute at lsm.c:1726 | AA_CLASS_NETV9_SKB |
| Signals | task_kill 1872 | AA_CLASS_SIGNAL; aa_may_signal at lsm.c:1023-1049 |
| Ptrace | ptrace_access_check 1786, ptrace_traceme 1787 | AA_CLASS_PTRACE |
| User namespaces | userns_create 1873 | AA_CLASS_NS; lsm.c:1051-1071 |
| io_uring | uring_override_creds 1888, uring_sqpoll 1889, under CONFIG_IO_URING | AA_CLASS_IO_URING |
| Reading labels | getprocattr 1820, getselfattr 1818, socket_getpeersec_stream 1848, socket_getpeersec_dgram 1850, secid_to_secctx 1882, lsmprop_to_secctx 1883, secctx_to_secid 1884, release_secctx 1885, current_getlsmprop_subj 1868, task_getlsmprop_obj 1870 | no decision |
| Label bookkeeping | cred_alloc_blank 1857, cred_free 1858, cred_prepare 1859, cred_transfer 1860, task_alloc 1867, task_free 1866, file_alloc_security 1811, file_free_security 1812, sk_alloc_security 1823, sk_free_security 1824, sk_clone_security 1825, sock_graft 1852 | no decision |
| Audit filter rules | audit_rule_init 1876, audit_rule_known 1877, audit_rule_match 1878, audit_rule_free 1879, under CONFIG_AUDIT | no decision; audit.c:254-301 |
lsm.c:230-232: if (!unconfined(label)) error = aa_path_perm(op, current_cred(), label, path, 0, mask, cond);. apparmor_capable (lsm.c:199-211) does the same with aa_capable.linux:security/apparmor/include/apparmor.h:19-41.prompt field is at include/perms.h:78, unpacked at policy_unpack.c:916 and set at lib.c:371-372; no other kernel code reads it. Identities are serialized under features_supports_identity_names at parser/parser_interface.c:562. The code behind mqueue and dbus is in upstream-and-ubuntu and dbus-mediation.aa_apply_modes_to_perms (linux:security/apparmor/lib.c:364-381): kill mode sets perms->kill = ~perms->allow; complain mode sets perms->complain |= ~(perms->allow | perms->deny); user mode sets perms->prompt the same way. File rules do not go through it: aa_audit_file (linux:security/apparmor/file.c:95-153) computes the complain mask itself (117-118) and returns the error early only for a quieted request (142-149).aa_audit (linux:security/apparmor/audit.c:200-237) picks the record type: ALLOWED in complain mode, otherwise DENIED, changed to KILLED in kill mode. It calls send_sig_info(profile->signal, ...) for a kill record and returns complain_error(ad->error) for an allowed one.complain_error (linux:security/apparmor/include/audit.h:206-211) maps -EPERM and -EACCES to 0.profile->signal = SIGKILL is the default, set at linux:security/apparmor/policy.c:412.linux:security/apparmor/audit.c:29-38.linux:security/apparmor/policy_unpack.c:1222-1237. The parser packs it with profile_mode_packed (parser/profile.h:75-87): no mode packs as enforce and default_allow as unconfined.profile_mode_table (parser/profile.cc:30-39). The flag errors are at parser/profile.h:247, 261 and 307; the force-complain warning at parser/parser_main.c:1330-1331.audit_pre (linux:security/apparmor/audit.c:93-141) writes apparmor, operation, class, info, error, namespace, profile or label and name, in that order. file_audit_cb (linux:security/apparmor/file.c:45-76) writes requested_mask, denied_mask, fsuid, ouid and target. pid and comm come from common_lsm_audit, called at audit.c:164.-EACCES is set at linux:security/apparmor/file.c:247.apparmor_bprm_creds_for_exec (linux:security/apparmor/domain.c:985), profile_transition (domain.c:665), find_attach (domain.c:394), x_to_label (domain.c:574). An unconfined task reaches find_attach at domain.c:697-698.__replace_profile and aa_label_replace (linux:security/apparmor/policy.c:1066, 1099).aa_may_manage_policy (linux:security/apparmor/policy.c:1001, called at apparmorfs.c:625); policy_locked is reported at policy.c:1014-1015.label (mode) in splitcon (libraries/libapparmor/src/kernel.c:578-615).