use super::PRIVILEGED_HEADS;
const SYSTEM_MODULES: &[&str] = &["os", "posix", "shutil", "fs"];
const PRIVILEGED_FUNCTIONS: &[&str] = &[
"fchmod",
"lchmod",
"fchown",
"lchown",
"chmodsync",
"fchmodsync",
"lchmodsync",
"chownsync",
"fchownsync",
"lchownsync",
];
pub(super) fn privileged_call_in(cmd: &str) -> bool {
let is_name = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '.';
cmd.split(|c: char| !is_name(c)).any(|t| {
let Some((module, _)) = t.split_once('.') else {
return false;
};
let func = t.rsplit('.').next().unwrap_or(t);
SYSTEM_MODULES.contains(&module)
&& (PRIVILEGED_HEADS.contains(&func) || PRIVILEGED_FUNCTIONS.contains(&func))
})
}
#[cfg(test)]
mod tests {
use super::super::classify;
use crate::hitl::RiskTier;
fn tier(cmd: &str) -> RiskTier {
classify("bash", Some(&serde_json::json!({ "command": cmd })))
}
#[test]
fn module_qualified_privileged_calls_are_privileged() {
for cmd in [
"python3 - <<'EOF'\nimport os\nos.chmod('x', 0o755)\nEOF",
"python3 - <<'EOF'\nimport os\nos.chown('x', 0, 0)\nEOF",
"python3 -c 'import os; os.chmod(\"x\", 0o755)'",
"python3 -c 'import os; os.chown(\"x\", 0, 0)'",
"python3 -c 'import os; os.lchown(\"x\", 0, 0)'",
"python3 -c 'import posix; posix.chmod(\"x\", 0o777)'",
"python3 -c 'import shutil; shutil.chown(\"x\", \"root\")'",
"node -e 'require(\"fs\"); fs.chmodSync(\"x\", 0o777)'",
"node -e 'fs.promises.chown(\"x\", 0, 0)'",
"python3 -c 'import os; list(map(os.chmod, [\"x\"], [0o777]))'",
"python3 -c 'import os; f=os.chmod; f(\"x\", 0o777)'",
"node -e '{fs.chmodSync(\"x\", 0o777)}'",
"python3 -c 'import os; [os.chmod][0](\"x\", 0o777)'",
] {
assert_eq!(tier(cmd), RiskTier::Privileged, "cmd: {cmd}");
}
}
#[test]
fn method_calls_and_lookalikes_are_not_privileged() {
for cmd in [
"node -e 'wrapper.mount(App)'",
"python3 -c 'obj.chmod(1)'",
"python3 -c 'import os; os.path.join(\"a\", \"b\")'",
"python3 -c 'import os; os.chdir(\"/tmp\")'",
] {
let got = tier(cmd);
assert!(got < RiskTier::Privileged, "cmd: {cmd}\ngot {got:?}");
}
}
}