use std::{fs, path::Path};
use anyhow::{Context, Result};
const APPARMOR_ENABLED_PATH: &str = "/sys/module/apparmor/parameters/enabled";
const APPARMOR_INTERFACE: &str = "/proc/self/attr/apparmor/exec";
const APPARMOR_LEGACY_INTERFACE: &str = "/proc/self/attr/exec";
pub fn is_enabled() -> Result<bool> {
let enabled = fs::read_to_string(APPARMOR_ENABLED_PATH)
.with_context(|| format!("Failed to read {}", APPARMOR_ENABLED_PATH))?;
Ok(enabled.starts_with('Y'))
}
pub fn apply_profile(profile: &str) -> Result<()> {
if profile.is_empty() {
return Ok(());
}
match activate_profile(Path::new(APPARMOR_INTERFACE), profile) {
Ok(_) => Ok(()),
Err(_) => activate_profile(Path::new(APPARMOR_LEGACY_INTERFACE), profile)
.with_context(|| "Failed to apply apparmor profile"),
}
}
fn activate_profile(path: &Path, profile: &str) -> Result<()> {
fs::write(path, format!("exec {}", profile))?;
Ok(())
}