Hats

^hat subprofiles for application developers for administrators for security researchers

A hat is a nested profile that a running program switches into with change_hat and leaves again with a token. Written with a caret or the hat keyword. The parser loads it as parent//hat and adds the rules that let the program ask for the switch.

On the map: profile structure

▶ Watch this deck — 10 scenes, ~8 min

Worth seeing first

Part of journeys

01 One process, two jobs

HATS demo one process ordinary request admin request demo /etc/demo/** r, demo//admin /etc/demo/admin.conf rw, hat of admin request for this request only set aside same process, no exec: the program asks for the switch itself
One process named demo receives ordinary and admin requests; the profile demo is applied to it, and for the admin request the nested profile demo//admin is applied to the same process instead.

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.

Demo is one process, and it does two kinds of work. Most requests only need to read its configuration. Once in a while an administrator's request comes in, and for that one demo has to rewrite a config file. You don't want every ordinary request to run with permission to do that. But a profile is chosen when a program starts, and demo isn't starting anything. That's what hats are for. A hat is a second rule set, written inside the profile. The running program asks the kernel to switch to it, does the sensitive bit, and switches back. This deck is for people who write profiles and people who run them.

Details and sources

Details

  • The library call: 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).
  • The manual: "if a portion of the program needs different access permissions than other portions, the program can "change hats" to a different role, also known as a subprofile" (aa_change_hat.pod:41-49).
  • No exec is involved. The kernel handles the request in aa_change_hat() and replaces the label in the task's credentials (domain.c:1319-1332, task.c:167-173).
  • A hat is not a memory barrier: "aa_change_hat(2) provides no memory barriers between different areas of a program; if address space separation is required, then separate processes should be used" (aa_change_hat.pod:248-254).
  • Kernels list support as /sys/kernel/security/apparmor/features/domain/change_hat and change_hatv (apparmorfs.c:2600-2602).

02 A caret, or the word hat

GRAMMAR ^ or hat NAME ATTACHMENT + identities=( ) flags=( ) { rules } ^admin the name follows the caret at once hat admin a space, then the name on the same line xattrs=( ) not on a hat profile demo /usr/bin/demo { ^admin { /etc/demo/admin.conf rw, } } hat admin { /etc/demo/admin.conf rw, } the same hat no comma after the closing brace: a hat is a block, not a rule
Syntax diagram of a hat: a caret or the keyword hat, the name, optional attachment, identities and flags, then a body in braces; xattrs is struck out; below, the hat admin inside the profile demo in both spellings.

^NAME { ... } or hat NAME { ... } inside a profile body. ^ must touch the name. A hat accepts the head parts of a profile except xattrs=( ).

You write a hat inside the body of its profile. There are two spellings. A caret glued to the name, ^admin. Or the keyword hat, a space, and the name. Then braces and rules, exactly like a profile. In fact it's the same grammar rule as a profile head, so a hat can carry flags, its own complain mode for instance. One part is refused: a hat can't have an xattrs condition. Here's demo with its hat, and below it the same hat spelled with the keyword. Notice there's no comma after the closing brace. A hat is a block, not a rule.

Details and sources

Details

  • The manual's grammar: 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).
  • A hat is written inside a profile body and takes no comma after its closing brace. Fixture with three hats: new_style1.sd:12.
  • The parser accepts more head parts than the manual shows: ^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.
  • The keyword form also works at the top level of a file with a full name: hat /does/not/exist//HAT1 { (new_style4.sd:16).
  • The profile language has no change_hat rule. A task in a profile may ask for any hat of that profile.

for AppArmor developers for security researchers

In the code

03 The hat does not inherit

EXAMPLE profile demo /usr/bin/demo { /etc/demo/** r, ^admin { /etc/demo/admin.conf rw, } } the hat is inside demo's braces it is still a rule set of its own in demo in demo//admin read /etc/demo/demo.conf allowed denied the hat has no rule for it write /etc/demo/admin.conf denied: only r allowed whatever the hat needs must be written in the hat, includes too ^admin { include <abstractions/base> /etc/demo/admin.conf rw, }
The profile demo with its hat admin, and a table of two accesses: reading demo.conf is allowed in demo and denied in the hat, writing admin.conf is denied in demo and allowed in the hat.

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.

Here's the part that catches people. The hat sits inside demo's braces, so it looks as if it adds to demo's rules. It doesn't. A hat is a complete rule set of its own. Going by the rules as written: in demo, reading the ordinary config works. Put the hat on and that same read is refused, because the hat doesn't mention the file. Writing the admin file is the other way round: refused in demo, which only has read, and allowed in the hat. So whatever the code needs while the hat is on has to be written inside the hat, abstractions included.

Details and sources

Details

  • The manual: "As both read(2) and write(2) are mediated, a file must be listed in a subprofile definition if the file is to be accessed while the process is in a "hat"" (aa_change_hat.pod:78-80).
  • The kernel, read from the source and not run: the switch replaces the task's label with the hat's label (task.c:155-173). The hat is a profile of its own, loaded as demo//admin; the kernel does not combine it with demo.
  • The parser adds three rules to a hat and nothing else; see the scene "Three rules you did not write". Abstractions the hat's code needs are included inside the hat, as the fixture does for the parent (new_style1.sd).
  • A descriptor opened before the switch does not carry over its access: the manual's example opens /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).
  • The outcomes on the slide follow from the rules as written. They were not run on a kernel.

04 Putting the hat on and taking it off

AT RUN TIME demo label: demo demo demo//admin aa_change_hat("admin", token) changehat 5f3a...^admin to /proc/PID/attr/current kernel child named admin? is it a hat? switch the task remember the token label: demo//admin aa_change_hat(NULL, token) label: demo wrong token: info="failed token match", task killed the token is the only lock on the way back
The process demo writes a changehat command with a token to the kernel; the kernel checks for a child named admin that is a hat, remembers the token and labels the process demo//admin; the same token brings it back and a wrong token gets the task killed.

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.

At run time it goes like this. Demo makes up a random number, the token, and calls aa_change_hat with the name admin. The library writes one line to a file under /proc: the word changehat, the token, a caret, the name. The kernel then does a lookup: among demo's children, is there one called admin, and is it marked as a hat? If so it switches the task and remembers the token. From then on the process is labelled demo//admin. To come back, demo calls again with no name and the same token. Code that doesn't know the token can't take the hat off: a wrong guess gets the task killed.

Details and sources

Details

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.
  • The string goes through 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).
  • Kernel entry points: the LSM hooks setselfattr and setprocattr (lsm.c:1819-1821). do_setattr knows the commands changehat and permhat; permhat only tests (lsm.c:883-888).
  • The token is parsed as hexadecimal up to ^. 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.
  • On the first switch the previous label and the token are saved; a later call with another token fails with EACCES (task.c:155-165). Returning compares the token again (task.c:185-194).
  • A wrong token is more than an error: the request is audited with 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).
  • With 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).

05 Three rules you did not write

IMPLIED RULES profile demo /usr/bin/demo { /etc/demo/** r, ^admin { /etc/demo/admin.conf rw, } } apparmor_parser demo, as loaded /etc/demo/** r, /proc/*/attr/apparmor/ r, /sys/module/apparmor/parameters/enabled r, /proc/[0-9]*/attr/{apparmor/,}current w, current: where the changehat line is written demo//admin, as loaded /etc/demo/admin.conf rw, /proc/*/attr/apparmor/ r, /sys/module/apparmor/parameters/enabled r, /proc/[0-9]*/attr/{apparmor/,}current w, $ apparmor_parser -Q -D rule-exprs demo prints the added rules with the ones you wrote
The source of demo with its hat goes through apparmor_parser; the loaded profile demo and the loaded hat demo//admin each hold the rules the author wrote plus three added rules for the AppArmor files under /proc and /sys.

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.

Remember that the hat is requested by writing to a file under /proc. Demo is confined, so that write needs a rule. You didn't write one, and it works anyway, because the parser adds it. Any profile that has a hat or a child profile gets three extra file rules: read access to the AppArmor attribute directory, read access to the flag that says AppArmor is enabled, and write access to the current attribute, the file the changehat line goes to. Every hat gets the same three. You can see them if you ask the parser to dump its rules.

Details and sources

Details

  • The three rules: /proc/*/attr/apparmor/ r, then /sys/module/apparmor/parameters/enabled r, then /proc/[0-9]*/attr/{apparmor/,}current w, (block_rules.h:27).
  • Why these files: the library first looks for the directory /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).
  • They are added to every hat and to every profile that has a hat or a child profile. A child profile with no hats or children of its own does not get them.
  • See them: 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.
  • The rules have priority 0 and merge with yours; the parser's test suite relies on that: "the change_hat implied rule has a priority of 0" (equality.sh:955-975). A deny rule with a higher priority can override them.
  • The same write access lets the task write a changeprofile request to that file. That request is checked separately against change_profile rules; see change_profile.
  • If the rules cannot be added the parser prints ERROR adding hat access rule for profile NAME and carries on.

for AppArmor developers for security researchers

In the code

  • 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).

06 Nested in the file, side by side in the kernel

LOADING profile demo /usr/bin/demo { /etc/demo/** r, ^admin { ... } profile worker { ... } } one file, nested demo demo//admin demo//worker $ apparmor_parser -N demo kernel demo admin worker hat parent found by the name before // delete ^admin from the file, then replace: $ apparmor_parser -r demo the kernel's code keeps demo//admin: it is moved under the new demo $ apparmor_parser -R demo removes demo and its children; then load the file again
One profile file with a nested hat and child becomes three separate profiles named demo, demo//admin and demo//worker; the kernel arranges them as a tree again; after the hat is deleted from the file and the profile replaced, the hat stays loaded until the parent is removed.

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.

In the file, the hat is inside demo. On the way to the kernel that nesting is flattened. The parser writes demo first, then each nested profile as a profile of its own, under its full name: demo//admin, demo//worker. The kernel reads the names and hangs each one under its parent again. That has a consequence for reloads. Delete the hat from the file and replace the profile, and the kernel keeps the old hat: children that the new version doesn't mention are moved under it. To really get rid of the hat, remove the parent profile, which takes its children with it, and load the file again.

Details and sources

Details

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.
  • Each nested profile is a separate write to the kernel after its parent, and a cache file holds the same binary profiles one after another.
  • The kernel finds the parent by walking the name at each // (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).
  • Replace, 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.
  • Remove, apparmor_parser -R: the parser removes the top profile only, and the kernel removes its children first (policy.c:200-235).
  • To drop a deleted hat: apparmor_parser -R FILE, then load the file again.
  • Parser messages when the kernel refuses a profile: Unable to add "%s". and Unable to replace "%s"., with the short name.

for AppArmor developers for security researchers

In the code

07 A hat is a profile with one bit set for AppArmor developers for security researchers

PARSER AND KERNEL scanner ^ = {CARET} hat{WS}* = {HAT} both push SUB_ID parser_lex.l:820, 848, 456-461 grammar hat: hat_start profile_base parser_yacc.y:490-504 block::add_hat hats, defined_hats: std::set ordered by namespace, name block.cc:148-155, profilelist.h:28 flags |= profile_flag_t::HAT xattrs -> yyerror post-process, write profile_add_hat_rules() load_flattened_hats() profile.cc:78-89, parser_policy.c:84-89, parser_interface.c:783-785 "flags" u32 word HAT = 1 << 0 -> kernel FLAG_HAT profile.h:135, parser_interface.c:526, linux: policy_unpack.c:1216-1217 change_hat() aa_find_child(); !PROFILE_IS_HAT -> "target not hat" linux: domain.c:1232-1243 in the tree, a hat inside deny { } or an if block is copied out to the enclosing profile
Six stages a hat passes through: the scanner, the grammar rule that sets the HAT flag, block::add_hat, post-processing and writing, the flags word of the binary profile, and the kernel's change_hat function that tests the flag.

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.

For developers: a hat and a child profile are the same thing in the parser. The scanner turns either spelling into a token and waits for a name. Both kinds are Profile objects, both come from profile_base, and both are stored by add_hat. The hat rule does two extra things: it sets the hat bit in the flags, and it rejects xattrs. The bit is bit zero of the flags word in the binary profile, and the kernel maps it to FLAG_HAT. The reader that matters is change_hat: it looks up the child by short name and refuses it with target not hat if the bit is missing.

Details and sources

for AppArmor developers for security researchers

Details

08 A space, a twin and a hat with no parent

COMMON MISTAKES ^ admin { } Lexer found unexpected character: ' ' (0x20) in state: SUB_ID ^admin { } profile admin { } Multiple definitions for profile admin exist,bailing out. hats and children share one set of names # top level, outside any profile ^orphan { } no error apparmor_parser -N prints: orphan a hat nobody can put on at run time, in the log, when the failure is logged: info="hat not found" info="no hats defined" info="target not hat" target not hat: the name belongs to a child written with profile, not ^ not every failed switch is logged: see the reference below
Three mistaken hats and the parser's answer: a space after the caret is a lexer error, a hat and a child with one name is a multiple definitions error, a top-level hat is accepted but unreachable; below, three kernel info strings for failed switches.

^ 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".

Three things go wrong when you write hats. A space after the caret is a scanner error; the name has to touch it. A hat and a child profile with the same name in one profile is an error too, because they share one set of names. The third is accepted and useless: a hat written at the top level of a file becomes a top-level profile with the hat mark, and on the kernel change_hat only looks among the children of the task's own profile. At run time the kernel has its own messages: hat not found, no hats defined, and target not hat, which means the name belongs to a child profile.

Details and sources

Details

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.
  • A top-level ^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).
  • Run-time reasons and the error the caller sees: 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).
  • These failures are logged only when more than one name was given or the profile is in complain mode: "change_hat uses probing and should not log failures related to missing hats" (domain.c:1269-1283). Do not expect a log line for every failed switch.
  • A task that is unconfined and whose profile has no children gets EPERM with info="unconfined can not change_hat" (domain.c:1344-1362).
  • A log line has operation="change_hat"; the libapparmor test corpus has examples (testcase_changehat_01.in).

for AppArmor developers for security researchers

In the code

09 The token is the only lock for security researchers

ATTACK SURFACE the way in demo changehat TOKEN^admin a child named admin? with the hat bit? no rule of the profile is consulted /proc/[0-9]*/attr/{apparmor/,}current w, added by the parser, to demo and to every hat the way out, or into another hat demo demo//admin changehat TOKEN^ the token remembered on entry? the token is in the process's own memory code that takes over inside the hat can look for it info="failed token match", task killed the hat holds while the token stays secret read from the kernel code, not run
The way into a hat: a changehat line to the kernel, which checks only for a child with the hat bit; the write rule for the attribute file is added by the parser. The way out: the same line with the token, which is kept in the process's memory; a wrong token kills the task.

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.

What does a hat hold against? Look at the locks. Getting into a hat needs no rule in the profile: the kernel checks for a child with the hat mark, and nothing else. The parser even adds the write rule for the attribute file, to the profile and to every hat. Getting out, or into another hat, needs the token, and the token lives in the process's own memory. Code that takes over the process inside the hat can look for it. A wrong guess is fatal: the task is sent the kill signal. So a hat holds only as long as the code inside it can't read the token.

Details and sources

Details

All kernel statements are read from the kernel source and were not run.

  • The way in: 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).
  • The request is one write of 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.
  • The token: the first switch stores it in the task's context; a later switch to another hat needs the same token, and so does the return (task.c:156-195). The token is chosen by the program and kept in its memory; the kernel does not hand it out.
  • A wrong token: -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).
  • The manual says the same: with a wrong token "the current task will be killed" (aa_change_hat.pod:68-74).
  • The same write access lets the task send a changeprofile request; that one is checked against change_profile rules.
  • With 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.

10 Around hats

ROADS demo//admin lib-change-hat the call, the token, the errors syn-child-profiles same nesting, entered by exec syn-profile-name parent//name syn-xattrs not on a hat syn-flags-modes complain creates missing hats k-labels fe-grammar syn-comments syntax-map the task's label profile_base braces and bodies the whole profile
The hat demo//admin in the centre with roads to the change_hat library deck, the child profile deck, the profile name, xattrs and flags decks, and to labels, the grammar, comments and the syntax map.

The API: lib-change-hat. The exec-time sibling: syn-child-profiles. Names: syn-profile-name.

A hat is half a feature without the call that uses it, so the first road is the change hat deck in the library district: tokens, lists of hat names, error codes. Next door is the child profile, written almost the same way but entered when a new program starts. Names, xattrs and flags each have a deck of their own. If you're debugging a hat in complain mode, know that the kernel creates a missing hat as a learning profile; the modes deck has the background. And below are the label a task carries, the grammar rule that hats share with profiles, and the whole profile on one page.

Details and sources

Details

  • ^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).
  • A hat does not inherit its parent's rules. The parser adds three rules for the changehat request and nothing else.
  • Complain mode, the kernel, read and not run: a hat that does not exist is created as a learning profile (domain.c:1137-1147), in complain mode and with the hat mark (policy.c:780-782).
  • A hat deleted from the file stays loaded after apparmor_parser -r; remove the parent with -R and load again.
  • Commits read for this deck: AppArmor 836052d21 (6.0.0~alpha2), the kernel-rc2 (97d73c825).

Read more

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.

Grammar

( ^ | hat ) NAME [ ATTACHMENT ] { + identities=( ... ) } [ flags=( ... ) ] { rules }
  • Written inside a profile body. No comma after the closing brace.
  • ^ 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).
  • The head is the head of a profile: hat admin { } and ^stats /usr/bin/stats flags=(complain) { } are accepted inside demo (tree). xattrs=( ) is parsed and then rejected.
  • What an attachment on a hat is for was not determined.
  • At top level, 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.

Keywords

SpellingWhereMeaning
^start of a nested head, touching the namethe block is a hat
hatstart of a nested head, then blanks and the namethe same
//in loaded namesseparates parent and hat: demo//admin; written by the parser
  • There is no 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).

A hat's rules

  • The body of a hat is a complete, separate rule set. It does not inherit from the profile it is written in. After the switch only the hat's rules apply.
  • The parser adds the three rules below and nothing else. Abstractions the hat's code needs are included inside the hat.

Implied rules

Rule addedWhy
/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
  • Added to every hat, and to every profile that contains a hat or a child profile. A child profile with no hats or children of its own does not get them.
  • 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).
  • The rules have priority 0 and merge with the rules you wrote; a deny rule with a higher priority can override them (parser/tst/equality.sh:955-975).
  • The same write access lets the task attempt a changeprofile request. That request is checked separately against change_profile rules; see syn-change-profile.

Loading

  • Each nested profile leaves the parser as a binary profile of its own, written after its parent and named with the full path: demo, demo//admin, demo//worker. apparmor_parser -N prints these names (tree).
  • Hats and children are written in name order, not in source order.
  • Each profile is one write to the kernel. A cache file holds the same binary profiles one after another.
  • The kernel's code finds the parent by the name before the last // and adds the new profile to the parent's children. Lookups use the short name after the last //.
  • If the parent is not loaded and not in the same load, the kernel's code creates empty placeholder ancestors.
  • Replacing (-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.
  • Removing (-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.

change_hat at run time

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.

SituationResultinfoError
the task's profile has a child of that name with the hat markthe task switches; the token is remembered
no child of that name, the profile has other childrenrefusedhat not foundENOENT
the profile has no childrenrefusedno hats definedECHILD
the child was declared with profile, not as a hatrefusedtarget not hatEPERM
no name, the right tokenthe task returns to the profile it left
a token different from the one rememberedrefused, and the task is killedfailed token matchEACCES
the task is unconfined and has no hatsrefusedunconfined can not change_hatEPERM
  • The token is the only protection on the way back. The hat's rules cannot forbid the return.
  • When the task is already in a hat, the children of the hat's parent are searched: a task moves between sibling hats.
  • One call may list up to 16 names; the first one that exists is used.
  • In complain mode a missing hat is created as a learning profile with the hat mark.
  • "hat not found" and "no hats defined" are audited only when more than one name was given or the profile is in complain mode. Do not expect a log line for every failed switch.
  • With 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.
  • Mainline Linux 7.4 checks no permission in the profile's rules for the switch itself.

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"

Errors and warnings

MessageCause
hat profiles can't use xattrs matchesxattrs=( ) 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_IDa 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 %sthe 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

Known discrepancies

  • The man page apparmor.d(5) says a hat name "must start with alphanumeric character" (parser/apparmor.d.pod:182). The parser accepts ^/HAT1.
  • The man page's HAT production shows no attachment (parser/apparmor.d.pod:180). The grammar accepts one.
  • A hat inside a hat is accepted and loaded as 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.
  • A top-level ^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.
  • A hat inside a qualifier block: 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.
  • The old spelling /path^HAT { } is a plain profile name, not a hat.
  • Whether an exec rule cx -> hatname can enter a hat was not determined. The exec path in the kernel's code does not test the hat mark.
  • The parser's exit status when a hat fails to load is doubtful: the error of the parent or of a hat can be lost. Not reproduced; it needs a kernel that rejects one of the writes.
  • A failure to add the implied rules is printed and then ignored.

for AppArmor developers for security researchers

Code map

WhatWhere
^ is {CARET}, hat{WS}* is {HAT}; both push SUB_IDparser/parser_lex.l:248, 277, 820, 848
in SUB_ID the next {IDS} or {QUOTED_ID} is TOK_ID; no white-space ruleparser/parser_lex.l:372-373, 456-461; error at 930
hat: hat_start profile_base; sets profile_flag_t::HAT; rejects xattrsparser/parser_yacc.y:490-504, 1637-1638
rules: rules hatparser/parser_yacc.y:827-834
top-level hat_start in opt_profile_flagparser/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 nameparser/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_parentparser/block.cc:161-204
profile_add_hat_rules, Profile::add_implied_rulesparser/profile.cc:78-89, 114-126
block_rules::add_proc_access, CHANGEHAT_PATHparser/block_rules.cc:527-574, parser/block_rules.h:27
post_process_profile recurses into defined_hatsparser/parser_policy.c:127-165
Profile::hname() builds parent//hatparser/profile.h:454-460
HAT = 1 << 0; packed into the flags structparser/profile.h:135, parser/parser_interface.c:526
load_flattened_hats, called after the parent is written; skipped for removeparser/parser_policy.c:70-89, parser/parser_interface.c:783-785
load_hats (hats embedded in the parent's stream) has no callerparser/parser_policy.c:96-103
kernel: packed hat flag becomes FLAG_HAT; PROFILE_IS_HATlinux:security/apparmor/policy_unpack.c:1216-1217, linux:security/apparmor/include/policy.h:50
kernel: __lookup_parent, __list_lookup_parent, __create_missing_ancestorslinux:security/apparmor/policy.c:523-590, 1031-1052, 1293-1323
kernel: replaced parent inherits old children; __remove_profilelinux:security/apparmor/policy.c:1071-1091, 200-239
kernel: do_setattr dispatches changehat and permhatlinux:security/apparmor/lsm.c:883-888
kernel: split_token_from_name, aa_setprocattr_changehatlinux:security/apparmor/procattr.c:70-128
kernel: change_hat, aa_change_hatlinux:security/apparmor/domain.c:1169-1300, 1319-1436
kernel: aa_set_current_hat, aa_restore_previous_labellinux:security/apparmor/task.c:156-195
library: "changehat %016lx^%s"libraries/libapparmor/src/kernel.c:1033

Roads from here

START HERE

PROFILE HEAD

PROFILE STRUCTURE

LIBAPPARMOR

  • aa_change_hat (no slides yet) — the library call that puts the hat on and takes it off

IN THE KERNEL

INSIDE THE PARSER

  • The grammar — the grammar rule shared by profiles and hats