use std::path::Path;
use serde::Serialize;
pub const LOADED: &str = "/sys/kernel/security/apparmor/profiles";
pub const PROFILE_DIR: &str = "/etc/apparmor.d";
pub const USERNS_RESTRICT: &str = "bwrap-userns-restrict";
const DOCUMENTED_FILE: &str = "bwrap";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum BwrapProfile {
None,
UsernsRestrict,
Unconfined,
Other,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Seen {
Loaded,
Installed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct BwrapProfileSeen {
pub profile: BwrapProfile,
pub seen: Seen,
}
impl BwrapProfileSeen {
pub fn here() -> Option<Self> {
if let Ok(list) = std::fs::read_to_string(LOADED) {
return Some(Self {
profile: from_loaded(&list),
seen: Seen::Loaded,
});
}
let dir = Path::new(PROFILE_DIR);
let names = file_names(dir)?;
let disabled = file_names(&dir.join("disable")).unwrap_or_default();
let documented = std::fs::read_to_string(dir.join(DOCUMENTED_FILE)).ok();
Some(Self {
profile: from_installed(&names, &disabled, documented.as_deref()),
seen: Seen::Installed,
})
}
}
fn file_names(dir: &Path) -> Option<Vec<String>> {
let entries = std::fs::read_dir(dir).ok()?;
Some(
entries
.filter_map(Result::ok)
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect(),
)
}
pub fn from_loaded(list: &str) -> BwrapProfile {
let mut bwrap = None;
let mut unpriv = false;
for line in list.lines() {
let (name, mode) = line
.trim()
.rsplit_once(" (")
.map_or((line.trim(), ""), |(n, m)| (n, m.trim_end_matches(')')));
match name {
"bwrap" => bwrap = Some(mode.to_owned()),
"unpriv_bwrap" => unpriv = true,
_ => {}
}
}
match bwrap.as_deref() {
None => BwrapProfile::None,
Some("unconfined") => BwrapProfile::Unconfined,
Some(_) if unpriv => BwrapProfile::UsernsRestrict,
Some(_) => BwrapProfile::Other,
}
}
pub fn from_installed(
names: &[String],
disabled: &[String],
documented: Option<&str>,
) -> BwrapProfile {
let has = |name: &str| names.iter().any(|n| n == name) && !disabled.iter().any(|n| n == name);
if has(USERNS_RESTRICT) {
return BwrapProfile::UsernsRestrict;
}
match documented.filter(|_| has(DOCUMENTED_FILE)) {
None => BwrapProfile::None,
Some(text) if text.contains("flags=(unconfined)") && text.contains("userns") => {
BwrapProfile::Unconfined
}
Some(_) => BwrapProfile::Other,
}
}