apparmor-policy 0.1.0

Typed, lossless parser and serializer for the AppArmor policy language.
Documentation
//! Parser and AST for the [AppArmor policy language](https://apparmor.net/):
//! profiles, hats, file globs, variables, aliases, and the full rule grammar.
//!
//! This crate is a **mechanism layer** (see the project's `DESIGN.md`): it
//! solves the *correctness* problem of turning AppArmor policy text into a
//! typed, lossless AST and back — a problem every tool that reads or writes
//! profiles (policy linters, `aa-logprof`-style repair tools, LXD-style
//! containers, security tooling) would otherwise reimplement, usually
//! incorrectly.
//!
//! # What you get
//!
//! - **Complete grammar**: `profile` / `hat` / sub-profile headers, file
//!   rules with the full AARE glob language (`*`, `**`, `?`, `[...]`,
//!   `{...}`, `@{}` variables), and the typed rule set: `file`,
//!   `capability`, `network`, `mount`, `pivot_root`, `link`,
//!   `change_profile`, `set rlimit`, `dbus`, `unix`, `mqueue`, `userns`,
//!   `io_uring`, `signal`, `ptrace` and `all`.
//! - **Lossless AST**: variables are kept as `@{...}` references (never
//!   expanded — expansion is the caller's job), and unknown rules degrade to
//!   [`ast::RawRule`] nodes carrying their original text, so no information
//!   is ever dropped.
//! - **Round-trippable**: a [`Policy`] renders back to canonical policy text
//!   via its [`Display`](std::fmt::Display) impl, with
//!   `parse(render(ast)) == ast`.
//! - **Precise errors**: structural failures carry 1-based line/column plus
//!   the offending source line, for incremental-repair tooling.
//!
//! # Example
//!
//! ```
//! use apparmor_policy::parse_str;
//!
//! let src = r#"
//! #include <tunables/global>
//!
//! profile /usr/bin/foo flags=(complain) {
//!   #include <abstractions/base>
//!   /etc/foo.conf r,
//!   owner @{HOME}/** rw,
//!   /bin/bash ix,
//!   capability setuid,
//!   network inet stream,
//!   deny /proc/*/mem rw,
//! }
//! "#;
//!
//! let profiles = parse_str(src).unwrap();
//! assert_eq!(profiles[0].name, "/usr/bin/foo");
//! assert_eq!(profiles[0].rules.len(), 6);
//!
//! // Round trip: AST -> text -> AST is the identity.
//! let text = profiles[0].to_string();
//! let again = parse_str(&text).unwrap();
//! assert_eq!(again, profiles);
//! ```
//!
//! # Module map
//!
//! - [`glob`] — AARE file-glob parsing (the subtlest part of the language).
//! - [`ast`] — the AST types.
//! - [`error`] — [`ParseError`] and [`Error`].
//!
//! The lexer and grammar are internal modules.
//!
//! # Scope and stopping point
//!
//! This crate parses and serializes policy text. It deliberately does *not*:
//! evaluate rules against paths (the kernel does that), read
//! `/sys/kernel/security/apparmor` state, merge or generate profiles, load
//! profiles into the kernel, or bind an async runtime. Those are policy /
//! runtime-layer concerns; constraining them here would force every caller
//! into one choice.

#![warn(missing_docs)]
#![forbid(unsafe_code)]
#![cfg_attr(docsrs, feature(doc_cfg))]

pub mod ast;
pub mod error;
pub mod glob;

mod grammar;
mod lexer;
mod serialize;

pub use error::{Error, ParseError};

use ast::{Policy, Profile};
use std::path::Path;

/// Parse AppArmor policy text into a lossless [`Policy`].
///
/// The parse is *fault tolerant*: unknown preamble items and rules are kept
/// as `Raw` nodes (see [`ast::RawItem`] / [`ast::RawRule`]) rather than
/// failing, so a partially supported policy never loses text. Structural
/// errors (unbalanced braces, unterminated strings, a missing profile body)
/// return a [`ParseError`] with a precise position.
///
/// # Examples
///
/// ```
/// use apparmor_policy::parse_policy;
///
/// let policy = parse_policy("profile foo {\n  capability net_raw,\n}\n").unwrap();
/// assert_eq!(policy.items.len(), 1);
/// assert_eq!(policy.to_string().contains("net_raw"), true);
/// ```
pub fn parse_policy(input: &str) -> Result<Policy, ParseError> {
    grammar::parse_policy(input)
}

/// Parse AppArmor policy text and return just the [`Profile`]s it contains.
///
/// This is a convenience over [`parse_policy`] for the common case where the
/// preamble (variables, aliases, includes, abi) is of no interest. Variables
/// and includes that belong to a profile (including the immediately
/// preceding preamble) are still carried by that profile. Preamble-only
/// items with no following profile are dropped; use [`parse_policy`] for a
/// fully lossless parse.
///
/// # Examples
///
/// ```
/// use apparmor_policy::parse_str;
///
/// let profiles = parse_str("profile /usr/bin/foo {\n  /etc/passwd r,\n}\n").unwrap();
/// assert_eq!(profiles.len(), 1);
/// assert_eq!(profiles[0].name, "/usr/bin/foo");
/// ```
pub fn parse_str(input: &str) -> Result<Vec<Profile>, ParseError> {
    let policy = parse_policy(input)?;
    Ok(policy
        .items
        .into_iter()
        .filter_map(|item| match item {
            ast::PolicyItem::Profile(p) => Some(p),
            _ => None,
        })
        .collect())
}

/// Read an AppArmor policy file from disk and parse it.
///
/// Returns [`Error::Io`] if the file cannot be read, or
/// [`Error::Parse`] if it is structurally invalid.
///
/// # Examples
///
/// ```no_run
/// use apparmor_policy::parse_file;
///
/// let policy = parse_file("/etc/apparmor.d/usr.bin.foo").unwrap();
/// assert!(!policy.items.is_empty());
/// ```
pub fn parse_file<P: AsRef<Path>>(path: P) -> Result<Policy, Error> {
    let path = path.as_ref();
    let text = std::fs::read_to_string(path).map_err(|source| Error::io(path, source))?;
    parse_policy(&text).map_err(Error::parse)
}

/// Render a policy back to canonical AppArmor text.
///
/// Equivalent to the [`Display`](std::fmt::Display) impl on [`Policy`];
/// provided as a free function for discoverability.
///
/// # Examples
///
/// ```
/// use apparmor_policy::{parse_policy, render};
///
/// let policy = parse_policy("profile foo {\n  capability setuid,\n}\n").unwrap();
/// let text = render(&policy);
/// assert!(text.contains("capability setuid"));
/// ```
pub fn render(policy: &Policy) -> String {
    policy.to_string()
}

impl std::fmt::Display for Policy {
    /// Render the policy back to canonical AppArmor text.
    ///
    /// Rendering is canonicalizing: `parse(render(x)) == x` holds for the
    /// typed nodes (see the crate docs for the round-trip example).
    ///
    /// # Examples
    ///
    /// ```
    /// use apparmor_policy::parse_policy;
    ///
    /// let policy = parse_policy("profile /usr/bin/foo {\n  capability setuid,\n}\n").unwrap();
    /// let text = policy.to_string();
    /// assert!(text.contains("profile /usr/bin/foo"));
    /// assert!(text.contains("capability setuid"));
    /// ```
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&serialize::render_policy(self))
    }
}

impl std::fmt::Display for Profile {
    /// Render this profile back to policy text.
    ///
    /// # Examples
    ///
    /// ```
    /// use apparmor_policy::parse_str;
    ///
    /// let profiles = parse_str("profile foo {\n  capability audit,\n}\n").unwrap();
    /// let text = profiles[0].to_string();
    /// assert!(text.starts_with("profile foo"));
    /// assert!(text.ends_with("}\n"));
    /// ```
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut out = String::new();
        serialize::render_profile_only(self, &mut out);
        f.write_str(&out)
    }
}