apparmor_policy/lib.rs
1//! Parser and AST for the [AppArmor policy language](https://apparmor.net/):
2//! profiles, hats, file globs, variables, aliases, and the full rule grammar.
3//!
4//! This crate is a **mechanism layer** (see the project's `DESIGN.md`): it
5//! solves the *correctness* problem of turning AppArmor policy text into a
6//! typed, lossless AST and back — a problem every tool that reads or writes
7//! profiles (policy linters, `aa-logprof`-style repair tools, LXD-style
8//! containers, security tooling) would otherwise reimplement, usually
9//! incorrectly.
10//!
11//! # What you get
12//!
13//! - **Complete grammar**: `profile` / `hat` / sub-profile headers, file
14//! rules with the full AARE glob language (`*`, `**`, `?`, `[...]`,
15//! `{...}`, `@{}` variables), and the typed rule set: `file`,
16//! `capability`, `network`, `mount`, `pivot_root`, `link`,
17//! `change_profile`, `set rlimit`, `dbus`, `unix`, `mqueue`, `userns`,
18//! `io_uring`, `signal`, `ptrace` and `all`.
19//! - **Lossless AST**: variables are kept as `@{...}` references (never
20//! expanded — expansion is the caller's job), and unknown rules degrade to
21//! [`ast::RawRule`] nodes carrying their original text, so no information
22//! is ever dropped.
23//! - **Round-trippable**: a [`Policy`] renders back to canonical policy text
24//! via its [`Display`](std::fmt::Display) impl, with
25//! `parse(render(ast)) == ast`.
26//! - **Precise errors**: structural failures carry 1-based line/column plus
27//! the offending source line, for incremental-repair tooling.
28//!
29//! # Example
30//!
31//! ```
32//! use apparmor_policy::parse_str;
33//!
34//! let src = r#"
35//! #include <tunables/global>
36//!
37//! profile /usr/bin/foo flags=(complain) {
38//! #include <abstractions/base>
39//! /etc/foo.conf r,
40//! owner @{HOME}/** rw,
41//! /bin/bash ix,
42//! capability setuid,
43//! network inet stream,
44//! deny /proc/*/mem rw,
45//! }
46//! "#;
47//!
48//! let profiles = parse_str(src).unwrap();
49//! assert_eq!(profiles[0].name, "/usr/bin/foo");
50//! assert_eq!(profiles[0].rules.len(), 6);
51//!
52//! // Round trip: AST -> text -> AST is the identity.
53//! let text = profiles[0].to_string();
54//! let again = parse_str(&text).unwrap();
55//! assert_eq!(again, profiles);
56//! ```
57//!
58//! # Module map
59//!
60//! - [`glob`] — AARE file-glob parsing (the subtlest part of the language).
61//! - [`ast`] — the AST types.
62//! - [`error`] — [`ParseError`] and [`Error`].
63//!
64//! The lexer and grammar are internal modules.
65//!
66//! # Scope and stopping point
67//!
68//! This crate parses and serializes policy text. It deliberately does *not*:
69//! evaluate rules against paths (the kernel does that), read
70//! `/sys/kernel/security/apparmor` state, merge or generate profiles, load
71//! profiles into the kernel, or bind an async runtime. Those are policy /
72//! runtime-layer concerns; constraining them here would force every caller
73//! into one choice.
74
75#![warn(missing_docs)]
76#![forbid(unsafe_code)]
77#![cfg_attr(docsrs, feature(doc_cfg))]
78
79pub mod ast;
80pub mod error;
81pub mod glob;
82
83mod grammar;
84mod lexer;
85mod serialize;
86
87pub use error::{Error, ParseError};
88
89use ast::{Policy, Profile};
90use std::path::Path;
91
92/// Parse AppArmor policy text into a lossless [`Policy`].
93///
94/// The parse is *fault tolerant*: unknown preamble items and rules are kept
95/// as `Raw` nodes (see [`ast::RawItem`] / [`ast::RawRule`]) rather than
96/// failing, so a partially supported policy never loses text. Structural
97/// errors (unbalanced braces, unterminated strings, a missing profile body)
98/// return a [`ParseError`] with a precise position.
99///
100/// # Examples
101///
102/// ```
103/// use apparmor_policy::parse_policy;
104///
105/// let policy = parse_policy("profile foo {\n capability net_raw,\n}\n").unwrap();
106/// assert_eq!(policy.items.len(), 1);
107/// assert_eq!(policy.to_string().contains("net_raw"), true);
108/// ```
109pub fn parse_policy(input: &str) -> Result<Policy, ParseError> {
110 grammar::parse_policy(input)
111}
112
113/// Parse AppArmor policy text and return just the [`Profile`]s it contains.
114///
115/// This is a convenience over [`parse_policy`] for the common case where the
116/// preamble (variables, aliases, includes, abi) is of no interest. Variables
117/// and includes that belong to a profile (including the immediately
118/// preceding preamble) are still carried by that profile. Preamble-only
119/// items with no following profile are dropped; use [`parse_policy`] for a
120/// fully lossless parse.
121///
122/// # Examples
123///
124/// ```
125/// use apparmor_policy::parse_str;
126///
127/// let profiles = parse_str("profile /usr/bin/foo {\n /etc/passwd r,\n}\n").unwrap();
128/// assert_eq!(profiles.len(), 1);
129/// assert_eq!(profiles[0].name, "/usr/bin/foo");
130/// ```
131pub fn parse_str(input: &str) -> Result<Vec<Profile>, ParseError> {
132 let policy = parse_policy(input)?;
133 Ok(policy
134 .items
135 .into_iter()
136 .filter_map(|item| match item {
137 ast::PolicyItem::Profile(p) => Some(p),
138 _ => None,
139 })
140 .collect())
141}
142
143/// Read an AppArmor policy file from disk and parse it.
144///
145/// Returns [`Error::Io`] if the file cannot be read, or
146/// [`Error::Parse`] if it is structurally invalid.
147///
148/// # Examples
149///
150/// ```no_run
151/// use apparmor_policy::parse_file;
152///
153/// let policy = parse_file("/etc/apparmor.d/usr.bin.foo").unwrap();
154/// assert!(!policy.items.is_empty());
155/// ```
156pub fn parse_file<P: AsRef<Path>>(path: P) -> Result<Policy, Error> {
157 let path = path.as_ref();
158 let text = std::fs::read_to_string(path).map_err(|source| Error::io(path, source))?;
159 parse_policy(&text).map_err(Error::parse)
160}
161
162/// Render a policy back to canonical AppArmor text.
163///
164/// Equivalent to the [`Display`](std::fmt::Display) impl on [`Policy`];
165/// provided as a free function for discoverability.
166///
167/// # Examples
168///
169/// ```
170/// use apparmor_policy::{parse_policy, render};
171///
172/// let policy = parse_policy("profile foo {\n capability setuid,\n}\n").unwrap();
173/// let text = render(&policy);
174/// assert!(text.contains("capability setuid"));
175/// ```
176pub fn render(policy: &Policy) -> String {
177 policy.to_string()
178}
179
180impl std::fmt::Display for Policy {
181 /// Render the policy back to canonical AppArmor text.
182 ///
183 /// Rendering is canonicalizing: `parse(render(x)) == x` holds for the
184 /// typed nodes (see the crate docs for the round-trip example).
185 ///
186 /// # Examples
187 ///
188 /// ```
189 /// use apparmor_policy::parse_policy;
190 ///
191 /// let policy = parse_policy("profile /usr/bin/foo {\n capability setuid,\n}\n").unwrap();
192 /// let text = policy.to_string();
193 /// assert!(text.contains("profile /usr/bin/foo"));
194 /// assert!(text.contains("capability setuid"));
195 /// ```
196 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197 f.write_str(&serialize::render_policy(self))
198 }
199}
200
201impl std::fmt::Display for Profile {
202 /// Render this profile back to policy text.
203 ///
204 /// # Examples
205 ///
206 /// ```
207 /// use apparmor_policy::parse_str;
208 ///
209 /// let profiles = parse_str("profile foo {\n capability audit,\n}\n").unwrap();
210 /// let text = profiles[0].to_string();
211 /// assert!(text.starts_with("profile foo"));
212 /// assert!(text.ends_with("}\n"));
213 /// ```
214 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215 let mut out = String::new();
216 serialize::render_profile_only(self, &mut out);
217 f.write_str(&out)
218 }
219}