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
- Child profiles — child profiles; a hat is one with a flag set
Part of journeys
- Exec, transitions and labels, step 6 of 13 · previous: Child profiles · next: change_profile rules
01 One process, two jobs
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_hatandchange_hatv(apparmorfs.c:2600-2602).
Read more
- aa_change_hat(2)
- apparmor.net: Profiles quick reference, hats
- mod_apparmor(8) and AppArmor wiki: Pam_apparmor: two programs that use hats.
- aa_change_hat in the library, child profiles.
02 A caret, or the word hat
^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_hatrule. A task in a profile may ask for any hat of that profile.
Read more
for AppArmor developers for security researchers
In the code
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_baseis the head rule of every profile (parser_yacc.y:391-399).- Scanner:
{CARET}and{HAT}push the stateSUB_ID(parser_lex.l:820, parser_lex.l:848), where the next id or quoted id is the name (parser_lex.l:456-461).
03 The hat does not inherit
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 withdemo. - 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
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 withEINVAL(kernel.c:1028-1059). Afterwards it overwrites its copy of the token.- The string goes through
aa_set_self_attr(LSM_ATTR_CURRENT, ...): thelsm_set_self_attrsystem call when the library has it enabled, otherwise a write to the thread'scurrentfile,/proc/<tid>/attr/apparmor/currentor/proc/<tid>/attr/current(kernel.c:997-1012). - Kernel entry points: the LSM hooks
setselfattrandsetprocattr(lsm.c:1819-1821).do_setattrknows the commandschangehatandpermhat;permhatonly 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 isint 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_privsset on a confined task the switch is refused withEPERMunless the new label is a subset of the label saved when the flag was first seen; this is not logged (domain.c:1383-1390).
Read more
- aa_change_hat(2): ERRORS and the example.
- kernel docs: Linux Security Modules, userspace API:
lsm_set_self_attrand theattrfiles. - aa_change_hat in the library, the label a task carries.
05 Three rules you did not write
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/enabledsaysN, and writes thechangehatline tocurrent(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 FILEprints the rules of each profile after the additions; with the parser built from the AppArmor tree at 836052d21 they are shown fordemoand 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
denyrule with a higher priority can override them. - The same write access lets the task write a
changeprofilerequest to that file. That request is checked separately againstchange_profilerules; see change_profile. - If the rules cannot be added the parser prints
ERROR adding hat access rule for profile NAMEand carries on.
Read more
for AppArmor developers for security researchers
In the code
profile_add_hat_rulesreturns early unless the profile has theHATflag ordefined_hatsis not empty (profile.cc:78-89); called fromProfile::add_implied_rules, where the error is printed and thereturnis 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_profilecallsadd_implied_rules()first (parser_policy.c:131).
06 Nested in the file, side by side in the kernel
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".andUnable to replace "%s"., with the short name.
Read more
for AppArmor developers for security researchers
In the code
Profile::hname()buildsparent//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_hatsruns after the parent is written and is skipped forOPTION_REMOVE(parser_interface.c:783-785, parser_policy.c:70-89).- Kernel:
__list_lookup_parentsearches the load set (policy.c:1031-1052); a new profile is added to its parent'sbase.profiles(policy.c:1402-1409).
07 A hat is a profile with one bit set for AppArmor developers for security researchers
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
- Scanner:
CARET "^"(parser_lex.l:248);{CARET}returnsTOK_CARETand{HAT}returnsTOK_HAT, both pushingSUB_ID(parser_lex.l:820, parser_lex.l:848); inSUB_IDthe next id isTOK_ID(parser_lex.l:456-461). - Grammar:
hat: hat_start profile_basesetsprof->flags.flags |= profile_flag_t::HATand rejectsxattrs(parser_yacc.y:490-504);rules: rules hatcalls$1->add_hat($2)(parser_yacc.y:827-834). block::add_hat(Profile *hat)sets the parent and inserts intodefined_hatsandhats; a duplicate name printsMultiple definitions for profile %s exist,bailing out.and exits.add_subblockandadd_cond_setcopy hats out of inner blocks (block.cc:137-204).HATis bit 0 ofprofile_flag_t(profile.h:135), written as the first u32 of structflagswithprofile_flag_bits()(parser_interface.c:526).post_process_profileadds the implied rules and recurses intodefined_hats(parser_policy.c:127-165, profile.cc:78-89); each nested profile is then written byload_flattened_hats(parser_policy.c:84-89, parser_interface.c:783-785).- The kernel:
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 givesinfo = "target not hat"and-EPERM(domain.c:1215-1266).- A learning hat created in complain mode gets
FLAG_HATtoo (policy.c:780-782).
08 A space, a twin and a hat with no parent
^ 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 printsMultiple definitions for hat NAME in profile (null) exist,bailing out.- A top-level
^name { }withoutparent//is accepted and loaded with the hat mark.change_hatsearches 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 foundwithENOENT,no hats definedwithECHILD(domain.c:1257-1266),target not hatwithEPERM(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
EPERMwithinfo="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).
Read more
for AppArmor developers for security researchers
In the code
- The scanner's catch-all error (parser_lex.l:930);
SUB_IDhas no white-space rule. block::add_to_known_hats(block.cc:137-146).- Top-level hats:
opt_profile_flag: hat_startgives 2, and the profile getsHAT(parser_yacc.y:381-383, parser_yacc.y:475-476).
09 The token is the only lock for security researchers
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/currentor/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 fordemoand 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:
-EACCESfrom either check goes to thekill:label, "kill task in case of brute force attacks", which setsinfo="failed token match"and marks the request to be killed (domain.c:1319-1436); the audit step then sends the profile's signal,SIGKILLunlesskill.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
changeprofilerequest; that one is checked againstchange_profilerules. - With
no_new_privsset 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
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 { }orhat NAME { }inside a profile; loaded asparent//NAME; entered withaa_change_hat(NAME, token)and left withaa_change_hat(NULL, token).- A hat does not inherit its parent's rules. The parser adds three rules for the
changehatrequest 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-Rand load again. - Commits read for this deck: AppArmor 836052d21 (6.0.0~alpha2), the kernel-rc2 (97d73c825).
Read more
- aa_change_hat(2)
- apparmor.net: Profiles quick reference, hats and apparmor.net: Profiles quick reference, child profiles
- aa_change_hat in the library, child profiles, profile names, extended attribute conditions, profile modes.
- Comments and braces, the label a task carries, the profile grammar, the syntax map.
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. Afterhatcome blanks and then the name, on the same line.NAMEis one word or one quoted string. It may start with/:^/HAT1 { }is accepted (fixturechange_hat/new_style2.sd).- The head is the head of a profile:
hat admin { }and^stats /usr/bin/stats flags=(complain) { }are accepted insidedemo(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 asprofile.hat demo//late { }afterdemoproducesdemo//late(tree; fixturechange_hat/new_style4.sd).^name { }with noparent//produces a top-level profile with the hat mark and no parent.
Keywords
| 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 |
- There is no
change_hatrule keyword in the profile language. A program indemomay ask for any hat ofdemo. ^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 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 |
- 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-exprsondemowith^adminondemowith^adminandprofile kidprints the three rules fordemoand for the hatadmin, and not for the plain childkid(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
changeprofilerequest. That request is checked separately againstchange_profilerules; 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 -Nprints 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.
| 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 |
- 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_privsset on a confined task the switch is refused withEPERMunless 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
| 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 |
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
HATproduction 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 bychange_hatfrom the outer hat, because from inside a hat the siblings are searched. - A top-level
^name { }withoutparent//is accepted and loaded with the hat mark.change_hatlooks 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, } }insidedemolistsdemo//blockedwith-Nin 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 -> hatnamecan 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
| 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 |
Roads from here
START HERE
- The profile language at a glance — back to the whole profile on one page
PROFILE HEAD
- The profile name — how nested names are built
- Extended attribute conditions — the one head part a hat may not have
- Profile mode flags — complain mode creates missing hats
PROFILE STRUCTURE
- Child profiles — the other nested profile entered at exec
- Comments and line structure — braces and bodies
LIBAPPARMOR
- aa_change_hat (no slides yet) — the library call that puts the hat on and takes it off
IN THE KERNEL
- Labels in the kernel — the label a task carries while in a hat
INSIDE THE PARSER
- The grammar — the grammar rule shared by profiles and hats