Conditional blocks
if, else, defined for application developers
An if block holds rules that are compiled only when its expression is true. The expression is worked out when the profile is compiled from boolean variables and comparisons and the defined test combined with not and and or. Blocks may have else if and else branches. A block that is not taken must still be valid text and its includes are still read.
On the map: preamble and reuse
▶ Watch this deck — 8 scenes, ~6 min
Worth seeing first
- Boolean variables — the switches an if block tests
01 One profile text, two compiled profiles
if EXPR { rules } compiles the rules in only when the expression is true at compile time.
Sometimes one program needs slightly different rules in different places: a debug log on test machines, an extra directory at one site. You could keep two profiles and watch them drift apart. Or you write one, and put the part that differs inside an if block. When the profile is compiled, the parser works out the condition from values in the preamble, and either leaves the block's rules out or compiles them in. The kernel gets an ordinary profile either way. It's a decision made once, at compile time, not a check while demo runs.
Details and sources
Details
- The block is line 13 of this district's example file:
if ${DEMO_DEBUG} { /tmp/demo-debug.log w, }. The panel shows a shortened profile; the counts are those of the whole example file. - The counts on this slide are the lines of
-D rule-exprsthat beginaare:: 106 with${DEMO_DEBUG} = false, 107 withtrue. They are compiled lines, not rules of the file: two are the attachment and its alias twin, three are peer labels (aare: demo) fromabstractions/base, 17 are alias twins, and the rest are the rules of the file and of the included abstraction. The extra line isaare: /tmp/demo-debug.log. Both were run with the tree's parser for this deck. - No shipped profile uses
if(grep ofprofiles/). The parser's tests have 67 files inparser/tst/simple_tests/conditional/. - Nothing of the block structure reaches the kernel: the compiled profile holds the rules of the taken blocks as ordinary rules.
- The program
demoand its profile are invented for the map. Nothing on this slide was observed on a running kernel.
02 if, an expression, a block, and optional else branches
if EXPR { } else if EXPR { } else { }. The first true branch is compiled; the others are left out.
The shape is familiar from other languages: the word if, an expression, and a block of rules in curly braces. After the closing brace you may continue with else if and another expression, as often as you like, and finish with a plain else. There's no comma after the brace. Of the whole chain, the first branch whose expression is true is compiled, and the rest are left out. In this example the debug switch is false, the version test is true, so the middle rule is the one that ends up in the profile. The else branch isn't reached. An if block can stand anywhere a rule can.
Details and sources
Details
- apparmor.d(5):
IF_BLOCK = 'if' EXPR BLOCK [ ( 'else' 'if' EXPR BLOCK )* ] [ 'else' BLOCK ](apparmor.d.pod:188). - The chain on the slide is from a profile recorded in the research notes; it stands inside
profile demo /usr/bin/demo { }. Of the chain only/ver9is compiled. The profile changed: this is not the district's example file. - Recorded in the research notes:
if true { /first r, } else if true { /second r, } else { /third r, }compiles only/first. - Recorded placements: in a hat (
^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/zonly). - Empty blocks and nested chains are valid (else_if_3.sd, expected to pass).
- Not around a part of a rule (bad_2.sd, bad_3.sd, expected to fail), and not in the preamble.
for AppArmor developers for security researchers
In the code
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).ifandelseare keywords (parser_misc.c:87-88).
03 What an expression is made of
Factors: ${VAR}, true, false, defined @{VAR}, a comparison, ( ). Operators: not, then and, then or.
What goes between if and the brace? Start at the bottom. A factor is one thing that's true or false: a boolean variable; the words true or false; the word defined followed by a set variable, which asks whether it exists; a comparison; or a whole expression in parentheses. Factors are combined with not, and, or. Not binds tightest, then and, then or. So true or false and false is true, because the and is worked out first. Not applies only to what follows it directly, unless parentheses say otherwise. And defined is handy for rules that should exist only when a site has set a particular variable.
Details and sources
Details
- The four examples are from two profiles recorded in the research notes; "compiled" means the rule of the block appears in
-D rule-exprs. In the fourth,@{SET}is assigned in the preamble and@{NOPE}is not. defined @{HOME}and@{VER} >= 9on the chips are forms, not runs.notbinds tightest, thenand, thenor.orandandare left associative.- A bare word must be
trueorfalse, in any case:if TRUE { /upper r, }is compiled (recorded in the research notes). definedtests 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).- The parser's tests also have
if $FOO and (($BAR and $THREE)) { }(ok_16.sd) andif (($FOO and $BAR) or $THREE) { }(ok_20.sd), both expected to pass. - The man page's sentence "Boolean operators are evaluated left to write with priority in order of the following list" lists
infirst andnot,and,orlast (apparmor.d.pod:2909-2964). The deck follows the grammar. - Known discrepancy: apparmor.d(5): the grammar summary and text disagree with the parser in several places.
- Known discrepancy: Conditionals:
defined ${bool}is false for a defined boolean, andand/orand nestedifdo not short-circuit.
for AppArmor developers for security researchers
In the code
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.
04 Comparing sets, text and numbers
==, !=, in: sets of text. <, <=, >, >=: numbers if both sides are single integers, text if neither is.
Comparisons take two operands, each a word, a quoted string or a set variable, and each is treated as a set of text values. The in operator asks whether everything on the left is among the values on the right: whole values, not part of a string. == asks whether the two sets are the same, so a variable with two values isn't equal to either of them. The ordering operators look at the operands first. Two whole numbers are compared as numbers: nine is less than ten. Two non-numbers are compared as text, where b10 sorts before b9. A number against a word is an error.
Details and sources
Details
- Every row is from the profiles recorded in the research notes, with
@{SET} = /a /b,@{ONE} = /aand@{VER} = 10in 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. - Also recorded:
@{ONE} in @{SET}true;/a in /a/bfalse (no substring match);"a b" == "a b"true;@{SET} == @{SET}true. - The error row in full:
AppArmor parser error for /work/c3.sd in profile /work/c3.sd at line 3: Can only compare numbers with numbers, exit status 1. - A set variable with several values next to a number is the same error:
@{SET} = 1 2andif @{SET} > 0(recorded in the research notes). - An undefined set variable in a comparison is
Error retrieving variable @{NOPE}(recorded in the research notes). - From the code, not run:
Value out of valid range. - The man page has an example with
@{TEST_VERSION} >= @{BAZ}(apparmor.d.pod:2981-2998). - Known discrepancy: Ordering comparisons in
ifread numbers in base 0 while==and!=compare text. Recorded in the research notes:0x10 >= 16and010 <= 8are true,0x10 == 16is false, and08 < 9isCan only compare numbers with numbers.
Read more
for AppArmor developers for security researchers
In the code
factor: id_or_var OP id_or_var(parser_yacc.y:966-1038).get_set,str_set_to_longwithstrtol(text, &end, 0), andstd::includesforin(cond_expr.cc:70-161).
05 What a block that is not taken still does
A branch that is not taken is parsed and its includes are followed. Its rules, hats, child profiles and variables are not used.
What happens to a block whose condition is false? Less than you might hope, and more. Its rules are left out of the profile, and so are capabilities, hats and child profiles declared inside it. Variables in it aren't even expanded, so a name that doesn't exist there is no error. But the text itself is still parsed: a typo inside a block that's switched off stops the compile. And include lines in it are still followed, because includes are resolved before any block is evaluated. So a file included only inside a false block must still exist. The block hides rules, not text.
Details and sources
Details
- The panel was run with the tree's parser for this deck, inside
profile demo /usr/bin/demonext to the rule/etc/demo/** r,:-D rule-exprsprints the attachment and/etc/demo/**only,-Nprints onlydemo, exit status 0, no message./srv/xis an invented path. - Recorded in the research notes, with more inside the block (an exec rule with a target, a capability, an rlimit, a network rule, a hat, a child profile and a change_profile rule):
-Nprints onlydemo, the compiled profile contains none of the names, and the only file rule is the one outside the block. - Recorded in the research notes:
if false { /x/@{UNDEFINED} r, }compiles, exit status 0. - Recorded in the research notes: the same kind of block with
bogus_keyword foo,in it printssyntax error, unexpected TOK_ID, expecting TOK_MODE, exit status 1;if false { include <does/not/exist> }printsCould not open 'does/not/exist', exit status 1. - A hat in a taken block that repeats a hat outside it is
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 existsdoes: see include if exists.- Alias rules are applied to the rules of every branch, taken or not. That has no effect on the result.
- Known discrepancy: An include inside an
ifor qualifier block makes the same include in the rest of the profile a no-op.
for security researchers
Attack surface
- The set of rules a profile has depends on preamble state: a boolean, a set variable, whether a variable is defined. That state can come from included files and
.ddirectories. - Reading the profile text does not tell which branch is compiled.
-D rule-exprsdoes. - Includes in a branch are followed whatever the condition is, so a condition does not gate which files are opened.
Read more
for AppArmor developers for security researchers
In the code
block::add_cond_setregisters hats and merges capability, rlimit and network data for the taken block only (block.cc:175-184).- Later passes walk only the taken block (block.cc:227-257, block.cc:285-293, block.cc:312-329, block.cc:85-109); the comment at block.cc:287-289 says why variables of the other blocks are not expanded.
- Includes are done by the scanner, which knows nothing of the block.
06 Evaluated while parsing, chosen once, skipped later for AppArmor developers for security researchers
parser_yacc.y:862-1038 builds the chain; cond_expr.h:63-95 keeps the taken block; block.cc walks only it.
The word if puts the scanner into an expression mode that lasts until the opening brace. Inside it, each factor is evaluated as soon as the grammar reduces it: a boolean variable is looked up right then, a comparison is computed right then. The result is kept together with the block that follows, and an else is just a condition with the negated result. A whole chain becomes a set that remembers the block of the first true condition. From there on, variable expansion, post-processing and code generation walk only that one block, while a few structural passes, like applying aliases, still visit them all.
Details and sources
for AppArmor developers for security researchers
Details
ifputs the scanner intoEXPR_MODE(parser_lex.l:902-904) until{(parser_lex.l:725-769).- The productions: parser_yacc.y:862-1038. For
elsethe parser builds a condition with the negated result (parser_yacc.y:876-879). - Each
cond_exprholds its result and its block; acond_expr_setis one whole chain and remembers the block of the first true condition (set_block, cond_expr.h:63-95). block::add_cond_setadds the chain to the enclosing block (block.cc:175-184).- Passes that walk only
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). - Passes that walk every block: qualifier push-down, alias application and duplicate merging (block.cc:273-283, block.cc:295-310).
- Every factor is evaluated as it is parsed, on both sides of
andandorand in branches that are not taken. - Known discrepancy: Conditionals:
defined ${bool}is false for a defined boolean, andand/orand nestedifdo not short-circuit.
Read more
07 Mistakes and their messages
if only inside a profile, always with braces. A condition is a boolean, a comparison or defined.
The mistakes. An if block above the profile: conditions select rules, and the preamble has none, so if only works inside a profile. A boolean that was never set, usually a typo: the message names it. A set variable used as if it were a truth value: compare it with something, or ask whether it's defined. A comparison with a set variable that doesn't exist. Forgetting the braces around a single rule: unlike some languages, they're always required. And an else that has lost its if.
Details and sources
Details
- Exit status 1 for each.
- Row 1 was run with the tree's parser for this deck:
${DEMO_DEBUG} = falseon line 1 andif ${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. - Rows 2 to 6 are recorded in the research notes. Row 2 in full:
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} = 9in the preamble. - Also recorded:
elsefollowed by}issyntax error, unexpected TOK_CLOSE, expecting TOK_OPEN or TOK_IF. - The parser's own tests: a boolean assigned in the profile before the
if(bad_1.sd),if truish { }(bad_id.sd),else ^FOO { }(else_if_8.sd), all expected to fail. - Guarding a comparison with
defined ... anddoes not avoid the "Error retrieving variable" error: both sides ofandare evaluated. See the entry named in the scene "Evaluated while parsing, chosen once, skipped later".
08 The other block, and the other conditionals
if blocks are decided at compile time. Rule conditionals such as peer= are checked by the kernel.
That's the conditional block: a compile-time choice between sets of rules. The switches that drive an if are in the boolean variables deck. Two neighbours are easy to mix up with it. Qualifier blocks use the same braces, with a qualifier like deny in front and no condition. And rule conditionals, like peer=, are part of a single rule and are checked by the kernel on every access, which is the opposite of compile time. The preamble deck says where the values come from.
Details and sources
Details
if EXPR { rules }, with any number ofelse if EXPR { }branches and at most oneelse { }. The first true branch is compiled.- Expressions: boolean variables,
true,false,defined, comparisons and parentheses, combined withnot,and,or. - A branch that is not taken is still parsed, and its includes are still followed.
- Qualifier blocks (
deny { }) have no condition. Rule conditionals (peer=,fstype=) are part of one rule and belong to the compiled profile; conditional blocks do not. - Commit read for this deck: AppArmor 836052d21 (6.0.0~alpha2). Conditional blocks have no kernel side.
Read more
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.
Grammar
IF_BLOCK = 'if' EXPR BLOCK [ ( 'else' 'if' EXPR BLOCK )* ] [ 'else' BLOCK ]
- The line is apparmor.d(5)'s (apparmor.d.pod:188).
BLOCKis rules in braces. There is no comma after the closing brace. - Of a chain, the first branch whose expression is true is compiled; the others are left out (tree).
| 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 |
Expressions
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 > >= < <=
notbinds tightest, thenand, thenor;andandorare left associative (code).if true or false and falseis true;if not true or trueis true;if not (true or true)is false (tree).- A bare word must be
trueorfalse, in any case:if TRUE { }is taken (tree).
Comparison operators
| 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 |
- An undefined set variable as an operand is
Error retrieving variable @{NOPE}(tree).
defined
defined @{NAME}is true when a set variable of that name exists (tree:if defined @{SET} and not defined @{NOPE}is taken).- It tests existence, not truth: a variable assigned
""is defined (the parser's testdefined_1.sd). - In an assignment:
${D} = defined @{NOPE}gives$D = false(tree,-D variables). - For
defined ${NAME}see the known discrepancies.
A branch that is not taken
| 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 |
Errors
| 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 |
- Exit status 1 for each.
The man page
- apparmor.d(5): "Boolean operators are evaluated left to write with priority in order of the following list", and the list puts
infirst andnot,and,orlast (apparmor.d.pod:2909-2964). In the grammar the comparisons are factors, andnotbinds beforeandbeforeor. This page follows the grammar.
for security researchers
Attack surface
- Which rules a profile has depends on preamble state: a boolean, a set variable, whether a variable is defined. That state can come from included files and
.ddirectories: see include if exists. - The profile text does not say which branch is compiled.
-D rule-exprsprints the rules that were. - Includes in a branch are followed whatever the condition is. A condition does not gate which files are opened.
for AppArmor developers for security researchers
In the code
- Scanner:
EXPR_MODE(parser_lex.l:725-769, parser_lex.l:902-904); the wordsand,or,not,defined,inare tokens only there and inASSIGN_EXPR_MODE(parser_lex.l:750-763). - Grammar:
cond_rule(parser_yacc.y:862-899),expr,term,notfactor,factor(parser_yacc.y:902-1038). cond_exprandcond_expr_set(cond_expr.h:63-95); evaluation (cond_expr.cc:29-161).- The block passes: block.cc:175-184, block.cc:227-257, block.cc:273-329.
for AppArmor developers for security researchers
Known discrepancies
- An include inside an
ifor qualifier block makes the same include in the rest of the profile a no-op. - Ordering comparisons in
ifread numbers in base 0 while==and!=compare text. Runs:if 0x10 >= 16 { /hexge r, }andif 010 <= 8 { /octle r, }are taken,if 0x10 == 16 { /hexeq r, }is not;if 08 < 9 { /x r, }isCan only compare numbers with numbers, exit status 1. - Conditionals:
defined ${bool}is false for a defined boolean, andand/orand nestedifdo not short-circuit. Adefined ... andguard therefore does not avoidError retrieving variable. - apparmor.d(5): the grammar summary and text disagree with the parser in several places (the precedence sentence above).
- Not determined: whether reading numbers in base 0 is intended; how the policy cache treats a changed boolean in an included file (derived from the time stamp code, not run).
Roads from here
START HERE
- The profile language at a glance — every kind of line on one page
PREAMBLE AND REUSE
- Boolean variables — the switches an expression tests
- Variables — the set variables that comparisons and defined look at
- The preamble — where the values come from and where if may not stand
- include if exists — the optional include that is not an if block
QUALIFIERS
- Qualifier blocks — the other kind of brace block
RULE CLASSES
- Rule conditionals — the unrelated conditionals inside a rule
PROFILE STRUCTURE
- Hats — hats inside a block
- Child profiles — child profiles inside a block
INSIDE THE PARSER
- The grammar — how the blocks are parsed