apparmor-policy 0.1.0

Typed, lossless parser and serializer for the AppArmor policy language.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
//! Parsing and rendering of AppArmor file-path globs (AARE).
//!
//! AppArmor uses a glob language that is *not* shell globbing and *not*
//! PCRE: it has its own semantics for `*` (zero or more non-`/` characters),
//! `**` (zero or more of any character, crossing directories), `?`, `[...]`
//! character classes, `{...}` alternation and `@{}` variables. Getting these
//! right is the single most common source of bugs in hand-written AppArmor
//! tooling, which is exactly why this crate does it once, correctly.
//!
//! This module parses an AARE string into a structured
//! [`FileRulePattern`] tree and can render it back to canonical text. The
//! rendering is *canonicalizing*: special characters are re-escaped so that
//! `pattern -> text -> pattern` is the identity.

use crate::error::{ParseError, line_col};

/// A single element of a parsed AppArmor file pattern (AARE).
///
/// A pattern is either a leaf ([`Star`](Self::Star),
/// [`Question`](Self::Question), [`Literal`](Self::Literal), …) or a
/// compound node ([`Sequence`](Self::Sequence) for concatenation,
/// [`Alternation`](Self::Alternation) for `{...}`).
///
/// The enum is `#[non_exhaustive]` so new pattern kinds can be added as the
/// AppArmor language evolves without breaking downstream matches.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum FileRulePattern {
    /// A run of literal characters (glob specials are escaped in the
    /// original source).
    Literal(String),
    /// `*` — zero or more characters that are *not* `/` (one directory level).
    Star,
    /// `**` — zero or more characters, including `/` (crosses directories).
    StarStar,
    /// `?` — exactly one character that is not `/`.
    Question,
    /// A `[...]` character class (or `[^...]` when `negated` is true).
    CharClass {
        /// Whether the class is negated (`[^...]`).
        negated: bool,
        /// Inclusive character ranges (`(a, b)` means `a..=b`; `(c, c)` is a
        /// single character).
        ranges: Vec<(char, char)>,
    },
    /// A `{a,b,c}` alternation. Empty alternatives are preserved (so
    /// `{foo,}` and `{,foo}` round-trip correctly).
    Alternation(Vec<FileRulePattern>),
    /// An `@{NAME}` variable reference. Variables are *not* expanded here:
    /// expansion is deliberately left to the caller (see the crate docs).
    Variable(String),
    /// A sequence of sub-patterns (concatenation).
    Sequence(Vec<FileRulePattern>),
}

impl FileRulePattern {
    /// Parse an AARE string into a pattern tree.
    ///
    /// Returns an error with a precise position if the pattern contains
    /// malformed syntax (unterminated `[...]`, `{...}` or `@{...}`).
    ///
    /// # Examples
    ///
    /// ```
    /// use apparmor_policy::glob::FileRulePattern;
    ///
    /// let p = FileRulePattern::parse("/home/{alice,bob}/**").unwrap();
    /// assert_eq!(p.to_string(), "/home/{alice,bob}/**");
    /// ```
    pub fn parse(input: &str) -> Result<FileRulePattern, ParseError> {
        let mut parser = GlobParser {
            input,
            pos: 0,
            source: input,
        };
        let atoms = parser.parse_sequence()?;
        if parser.pos != input.len() {
            return Err(parser.error_at(parser.pos, "unexpected trailing characters in pattern"));
        }
        Ok(collapse(atoms))
    }

    /// Build a pattern from a single literal string.
    ///
    /// The resulting pattern has no glob semantics (`*`, `?`, `[...]`,
    /// `{...}` in the input are treated as plain characters and re-escaped
    /// on render).
    ///
    /// # Examples
    ///
    /// ```
    /// use apparmor_policy::glob::FileRulePattern;
    ///
    /// let p = FileRulePattern::literal("*");
    /// assert_eq!(p.to_string(), "\\*");
    /// ```
    pub fn literal(s: impl Into<String>) -> FileRulePattern {
        FileRulePattern::Literal(s.into())
    }

    /// Returns `true` if this pattern contains any glob meta character
    /// (`*`, `?`, `[...]`, `{...}`). A pattern of only literals and
    /// variables matches exactly one path.
    ///
    /// # Examples
    ///
    /// ```
    /// use apparmor_policy::glob::FileRulePattern;
    ///
    /// assert!(!FileRulePattern::parse("/etc/passwd").unwrap().is_meta());
    /// assert!(FileRulePattern::parse("/etc/*").unwrap().is_meta());
    /// assert!(FileRulePattern::parse("/d/{a,b}").unwrap().is_meta());
    /// ```
    pub fn is_meta(&self) -> bool {
        match self {
            FileRulePattern::Literal(_) => false,
            FileRulePattern::Variable(_) => false,
            FileRulePattern::Star
            | FileRulePattern::StarStar
            | FileRulePattern::Question
            | FileRulePattern::CharClass { .. } => true,
            FileRulePattern::Alternation(_) => true,
            FileRulePattern::Sequence(seq) => seq.iter().any(|a| a.is_meta()),
        }
    }

    /// Returns `true` if this is an [`Alternation`](Self::Alternation)
    /// (`{...}`).
    ///
    /// # Examples
    ///
    /// ```
    /// use apparmor_policy::glob::FileRulePattern;
    ///
    /// assert!(FileRulePattern::parse("{a,b}").unwrap().is_alternation());
    /// assert!(!FileRulePattern::parse("/a/b").unwrap().is_alternation());
    /// ```
    pub fn is_alternation(&self) -> bool {
        matches!(self, FileRulePattern::Alternation(_))
    }

    /// Render the pattern back to canonical AARE text.
    ///
    /// The output is normalized (glob specials escaped, control characters
    /// emitted as octal) but `parse(render(p)) == p` always holds.
    ///
    /// # Examples
    ///
    /// ```
    /// use apparmor_policy::glob::FileRulePattern;
    ///
    /// let p = FileRulePattern::parse("/tmp/*").unwrap();
    /// assert_eq!(p.to_string(), "/tmp/*");
    ///
    /// // A literal `*` is re-escaped so it round-trips.
    /// let star = FileRulePattern::literal("*");
    /// assert_eq!(star.to_string(), "\\*");
    /// ```
    pub fn render(&self) -> String {
        let mut out = String::new();
        self.write_to(&mut out);
        out
    }

    fn write_to(&self, out: &mut String) {
        match self {
            FileRulePattern::Literal(s) => {
                for c in s.chars() {
                    escape_literal(c, out);
                }
            }
            FileRulePattern::Star => out.push('*'),
            FileRulePattern::StarStar => out.push_str("**"),
            FileRulePattern::Question => out.push('?'),
            FileRulePattern::CharClass { negated, ranges } => {
                out.push('[');
                if *negated {
                    out.push('^');
                }
                for (lo, hi) in ranges {
                    if lo == hi {
                        escape_class_char(*lo, out);
                    } else {
                        escape_class_char(*lo, out);
                        out.push('-');
                        escape_class_char(*hi, out);
                    }
                }
                out.push(']');
            }
            FileRulePattern::Alternation(alts) => {
                out.push('{');
                for (i, alt) in alts.iter().enumerate() {
                    if i > 0 {
                        out.push(',');
                    }
                    alt.write_to(out);
                }
                out.push('}');
            }
            FileRulePattern::Variable(name) => {
                out.push_str("@{");
                out.push_str(name);
                out.push('}');
            }
            FileRulePattern::Sequence(seq) => {
                for s in seq {
                    s.write_to(out);
                }
            }
        }
    }
}

impl std::fmt::Display for FileRulePattern {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.render())
    }
}

/// Escape a literal character for use *outside* a character class.
fn escape_literal(c: char, out: &mut String) {
    match c {
        '*' | '?' | '[' | ']' | '{' | '}' | '\\' | ',' | '^' => {
            out.push('\\');
            out.push(c);
        }
        c if c.is_control() => {
            let mut buf = [0u8; 4];
            let bytes = c.encode_utf8(&mut buf).as_bytes();
            for &b in bytes {
                out.push_str(&format!("\\{:03o}", b));
            }
        }
        c => out.push(c),
    }
}

/// Escape a literal character for use *inside* a character class.
fn escape_class_char(c: char, out: &mut String) {
    match c {
        ']' | '\\' | '^' | '-' => {
            out.push('\\');
            out.push(c);
        }
        c => out.push(c),
    }
}

/// Flatten a single-element sequence into the element itself.
fn collapse(seq: Vec<FileRulePattern>) -> FileRulePattern {
    match seq.len() {
        0 => FileRulePattern::Literal(String::new()),
        1 => seq.into_iter().next().unwrap(),
        _ => FileRulePattern::Sequence(seq),
    }
}

struct GlobParser<'a> {
    input: &'a str,
    pos: usize,
    source: &'a str,
}

impl<'a> GlobParser<'a> {
    fn peek(&self) -> Option<char> {
        self.input[self.pos..].chars().next()
    }

    fn bump(&mut self) -> Option<char> {
        let c = self.peek()?;
        self.pos += c.len_utf8();
        Some(c)
    }

    fn error_at(&self, pos: usize, msg: impl Into<String>) -> ParseError {
        let (line, col) = line_col(self.source, pos);
        let context = self
            .source
            .lines()
            .nth(line.saturating_sub(1))
            .unwrap_or("")
            .to_string();
        ParseError {
            line,
            col,
            message: msg.into(),
            context,
        }
    }

    /// Parse a sequence of atoms until `}`, `,` or EOF.
    ///
    /// `}` and `,` are left unconsumed for the caller (an alternation
    /// parser) to interpret.
    fn parse_sequence(&mut self) -> Result<Vec<FileRulePattern>, ParseError> {
        let mut atoms = Vec::new();
        loop {
            let c = match self.peek() {
                None => break,
                Some(c) => c,
            };
            match c {
                '}' | ',' => break, // caller's responsibility
                _ => {}
            }
            match c {
                '*' => {
                    self.bump();
                    if self.peek() == Some('*') {
                        self.bump();
                        atoms.push(FileRulePattern::StarStar);
                    } else {
                        atoms.push(FileRulePattern::Star);
                    }
                }
                '?' => {
                    self.bump();
                    atoms.push(FileRulePattern::Question);
                }
                '[' => {
                    self.bump();
                    let cls = self.parse_char_class()?;
                    atoms.push(cls);
                }
                '{' => {
                    self.bump();
                    let alts = self.parse_alternation()?;
                    atoms.push(alts);
                }
                '@' => {
                    if self.input[self.pos..].starts_with("@{") {
                        self.bump();
                        self.bump();
                        let name = self.parse_variable_name()?;
                        atoms.push(FileRulePattern::Variable(name));
                    } else {
                        self.bump();
                        atoms.push(FileRulePattern::Literal("@".to_string()));
                    }
                }
                '\\' => {
                    self.bump();
                    let esc = self.parse_escape()?;
                    atoms.push(FileRulePattern::Literal(esc));
                }
                _ => {
                    // Accumulate a run of plain literal characters.
                    let mut lit = String::new();
                    while let Some(c) = self.peek() {
                        if matches!(c, '*' | '?' | '[' | '{' | '}' | '@' | '\\' | ',') {
                            break;
                        }
                        lit.push(c);
                        self.bump();
                    }
                    if lit.is_empty() {
                        // Unknown char (e.g. `}` handled above); consume one to progress.
                        let c = self.bump().unwrap();
                        lit.push(c);
                    }
                    atoms.push(FileRulePattern::Literal(lit));
                }
            }
        }
        Ok(atoms)
    }

    fn parse_char_class(&mut self) -> Result<FileRulePattern, ParseError> {
        let negated = if self.peek() == Some('^') {
            self.bump();
            true
        } else {
            false
        };
        let mut ranges: Vec<(char, char)> = Vec::new();
        loop {
            match self.peek() {
                None => {
                    return Err(self.error_at(self.pos, "unterminated character class `[...]`"));
                }
                Some(']') => {
                    self.bump();
                    break;
                }
                Some('\\') => {
                    self.bump();
                    let c = self.parse_escape_char()?;
                    ranges.push((c, c));
                }
                Some(c) => {
                    self.bump();
                    if self.peek() == Some('-')
                        && self.input[self.pos..].chars().nth(1) != Some(']')
                    {
                        self.bump();
                        match self.peek() {
                            Some('\\') => {
                                self.bump();
                                let hi = self.parse_escape_char()?;
                                ranges.push((c, hi));
                            }
                            Some(hi) => {
                                self.bump();
                                ranges.push((c, hi));
                            }
                            None => {
                                return Err(
                                    self.error_at(self.pos, "unterminated character class `[...]`")
                                );
                            }
                        }
                    } else {
                        ranges.push((c, c));
                    }
                }
            }
        }
        Ok(FileRulePattern::CharClass { negated, ranges })
    }

    fn parse_alternation(&mut self) -> Result<FileRulePattern, ParseError> {
        let mut alts = Vec::new();
        loop {
            // Parse one alternative (which may itself contain nested braces).
            let inner = self.parse_sequence()?;
            alts.push(collapse(inner));
            match self.peek() {
                Some(',') => {
                    self.bump();
                }
                Some('}') => {
                    self.bump();
                    break;
                }
                _ => {
                    return Err(self.error_at(self.pos, "unterminated alternation `{...}`"));
                }
            }
        }
        Ok(FileRulePattern::Alternation(alts))
    }

    fn parse_variable_name(&mut self) -> Result<String, ParseError> {
        let mut name = String::new();
        loop {
            match self.peek() {
                Some('}') => {
                    self.bump();
                    break;
                }
                Some(c) if c.is_alphanumeric() || c == '_' => {
                    name.push(c);
                    self.bump();
                }
                None => {
                    return Err(self.error_at(self.pos, "unterminated variable `@{...}`"));
                }
                Some(_) => {
                    return Err(self.error_at(
                        self.pos,
                        "invalid character in variable name (expected alphanumeric or `_`)",
                    ));
                }
            }
        }
        if name.is_empty() {
            return Err(self.error_at(self.pos, "empty variable name `@{}`"));
        }
        Ok(name)
    }

    /// Parse an escape sequence, returning the decoded text (handles `\x`,
    /// `\ooo` and `\\`).
    fn parse_escape(&mut self) -> Result<String, ParseError> {
        let c = self.parse_escape_char()?;
        Ok(c.to_string())
    }

    /// Parse a single escaped character: `\c` or `\ooo` (octal).
    fn parse_escape_char(&mut self) -> Result<char, ParseError> {
        match self.bump() {
            None => Err(self.error_at(self.pos, "trailing backslash in pattern")),
            Some(c) if c.is_ascii_digit() => {
                // Octal escape: up to three octal digits.
                let mut val = c.to_digit(8).unwrap();
                for _ in 0..2 {
                    match self.peek() {
                        Some(d) if d.is_ascii_digit() && d.is_digit(8) => {
                            let d = self.bump().unwrap();
                            val = val * 8 + d.to_digit(8).unwrap();
                        }
                        _ => break,
                    }
                }
                if val > 0x10FFFF {
                    return Err(self.error_at(self.pos, "octal escape out of range"));
                }
                let decoded = char::from_u32(val).ok_or_else(|| {
                    self.error_at(self.pos, "octal escape is not a valid character")
                })?;
                Ok(decoded)
            }
            Some(c) => Ok(c),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::FileRulePattern as P;

    fn parse(s: &str) -> P {
        P::parse(s).unwrap()
    }

    #[test]
    fn plain_literal() {
        let p = parse("/etc/passwd");
        assert!(!p.is_meta());
        assert_eq!(p.to_string(), "/etc/passwd");
    }

    #[test]
    fn star_is_single_level() {
        let p = parse("/tmp/*");
        assert!(p.is_meta());
        assert_eq!(p.to_string(), "/tmp/*");
    }

    #[test]
    fn starstar_crosses_dirs() {
        let p = parse("/dir/**");
        assert_eq!(p.to_string(), "/dir/**");
    }

    #[test]
    fn question_mark() {
        let p = parse("/a?b");
        assert_eq!(p.to_string(), "/a?b");
    }

    #[test]
    fn char_class() {
        let p = parse("/x/[a-z0-9]");
        assert!(matches!(
            p,
            P::Sequence(ref s) if matches!(s.last(), Some(P::CharClass { negated: false, .. }))
        ));
        assert_eq!(p.to_string(), "/x/[a-z0-9]");
    }

    #[test]
    fn negated_char_class() {
        let p = parse("[^/]");
        assert!(matches!(p, P::CharClass { negated: true, .. }));
        assert_eq!(p.to_string(), "[^/]");
    }

    #[test]
    fn alternation_round_trip() {
        let p = parse("/dir{,1,2}/**");
        assert_eq!(p.to_string(), "/dir{,1,2}/**");
    }

    #[test]
    fn empty_alternation_preserved() {
        let p = parse("{foo,}");
        assert!(matches!(p, P::Alternation(ref a) if a.len() == 2));
        assert_eq!(p.to_string(), "{foo,}");
    }

    #[test]
    fn nested_alternation() {
        let p = parse("{a,{b,c},d}");
        assert_eq!(p.to_string(), "{a,{b,c},d}");
    }

    #[test]
    fn variable_kept_unespanded() {
        let p = parse("@{HOME}/**");
        assert!(matches!(
            p,
            P::Sequence(ref s)
                if matches!(s.first(), Some(P::Variable(n)) if n == "HOME")
        ));
        assert_eq!(p.to_string(), "@{HOME}/**");
    }

    #[test]
    fn escaped_star_is_literal() {
        let p = parse("/a/\\*");
        assert_eq!(p.to_string(), "/a/\\*");
        // Round trip: parse(render(p)) == p
        let again = parse(&p.to_string());
        assert_eq!(p, again);
    }

    #[test]
    fn escaped_comma_is_literal() {
        let p = parse("/a\\,b");
        assert_eq!(p.to_string(), "/a\\,b");
    }

    #[test]
    fn octal_escape() {
        let p = parse("/\\001");
        assert!(
            matches!(p, P::Sequence(ref s) if s.iter().any(|x| matches!(x, P::Literal(l) if l.starts_with('\u{1}'))))
        );
        assert_eq!(p.to_string(), "/\\001");
    }

    #[test]
    fn round_trip_is_identity() {
        let cases = [
            "/etc/passwd",
            "/etc/**",
            "/home/*/bin/*",
            "/opt/{a,b,c}/**",
            "/dev/[a-z]*",
            "/x/[^/]*",
            "/a?b*c",
            "@{PROC}/**",
            "/tmp/\\*",
            "/tmp/{foo,bar,baz}",
            "/usr/bin/**",
        ];
        for c in cases {
            let p = parse(c);
            let rendered = p.to_string();
            assert_eq!(
                p,
                parse(&rendered),
                "round trip failed for {c:?} -> {rendered:?}"
            );
        }
    }

    #[test]
    fn starstar_plus_star() {
        let p = parse("/x/***");
        assert_eq!(p.to_string(), "/x/***");
    }

    #[test]
    fn unterminated_class_errors() {
        let e = P::parse("/x/[abc").unwrap_err();
        assert!(e.message.contains("unterminated"));
        assert!(e.line >= 1);
    }

    #[test]
    fn unterminated_alternation_errors() {
        let e = P::parse("/x/{a,b").unwrap_err();
        assert!(e.message.contains("unterminated"));
    }

    #[test]
    fn unterminated_variable_errors() {
        let e = P::parse("/x/@{HOME").unwrap_err();
        assert!(e.message.contains("unterminated"));
    }

    #[test]
    fn trailing_backslash_errors() {
        let e = P::parse("/x/\\").unwrap_err();
        assert!(e.message.contains("backslash"));
    }
}