Skip to main content

openmoat_core/
programs.rs

1//! Executable pinning: which binary a command name really runs.
2//!
3//! A policy can pin program names to absolute paths (`executables:`), and the
4//! kernel records where common programs lived when it was installed. At decision
5//! time the first word of every shell command is resolved through a resolver the
6//! caller supplies (the core itself never touches the filesystem) and compared
7//! with those pins. A `git` that now resolves somewhere else is denied before it
8//! runs, which defeats planted binaries and search-path poisoning.
9
10use std::collections::BTreeMap;
11
12use crate::packages::Ecosystem;
13use crate::rule_id::EXECUTABLES as RULE;
14use crate::verdict::{Decision, Verdict};
15
16/// Resolves program names using a search path the kernel controls.
17pub trait ProgramResolver {
18    /// Absolute path `program` would run from, or `None` if it is not found.
19    fn resolve(&self, program: &str) -> Option<String>;
20
21    /// Path recorded for `program` when the kernel was installed, if any.
22    fn pinned(&self, _program: &str) -> Option<String> {
23        None
24    }
25
26    /// Where OpenMoat's own binary and its alias are installed. A command
27    /// whose program word reaches one of these files, through a link under
28    /// another name or on the search path, is decided as `openmoat` too, so
29    /// the rules that keep OpenMoat's person-only commands from an agent see
30    /// it. By default the pins of `openmoat` and `moat`.
31    fn own_binaries(&self) -> Vec<String> {
32        ["openmoat", "moat"]
33            .iter()
34            .filter_map(|name| self.pinned(name))
35            .collect()
36    }
37
38    /// Whether a package runner's word `name` names a program the project
39    /// installed: `node_modules/.bin/<name>` in one of `dirs` (the working
40    /// directory, then each parent up to the project root), which `npx` and
41    /// its kind run without fetching anything (ADR-102). Asked only for a word
42    /// that names no version and no package option. By default no.
43    fn local_bin(&self, _dirs: &[String], _name: &str) -> bool {
44        false
45    }
46
47    /// Whether the nearest manifest in `dirs` declares the package `name` of
48    /// `ecosystem` (`package.json` dependencies, `pyproject.toml` or
49    /// `uv.lock`): the project chose it, so a runner fetching it is no
50    /// unknown package (ADR-102). By default no.
51    fn declared(&self, _dirs: &[String], _ecosystem: Ecosystem, _name: &str) -> bool {
52        false
53    }
54}
55
56/// Resolver for callers without a search path (tests, `policy check` without state).
57#[derive(Debug, Default, Clone, Copy)]
58pub struct NoResolver;
59
60impl ProgramResolver for NoResolver {
61    fn resolve(&self, _program: &str) -> Option<String> {
62        None
63    }
64}
65
66/// In-memory resolver for tests and conformance fixtures.
67#[derive(Debug, Default, Clone)]
68pub struct MapResolver {
69    /// Program name → path it resolves to on the search path.
70    pub resolved: BTreeMap<String, String>,
71    /// Program name → path recorded at install time.
72    pub pins: BTreeMap<String, String>,
73}
74
75impl ProgramResolver for MapResolver {
76    fn resolve(&self, program: &str) -> Option<String> {
77        self.resolved.get(program).cloned()
78    }
79
80    fn pinned(&self, program: &str) -> Option<String> {
81        self.pins.get(program).cloned()
82    }
83}
84
85/// Check one command's program against policy pins and installation pins.
86///
87/// `argv0` is the command as written; `policy_pins` is the policy's
88/// `executables` table. Returns a deny decision on mismatch, `None` when the
89/// program is unpinned or runs from an expected path.
90pub fn check(
91    argv0: &str,
92    policy_pins: &BTreeMap<String, Vec<String>>,
93    resolver: &dyn ProgramResolver,
94) -> Option<Decision> {
95    let name = basename(argv0);
96    let mut expected: Vec<String> = policy_pins.get(name).cloned().unwrap_or_default();
97    if let Some(installed) = resolver.pinned(name)
98        && !expected.contains(&installed)
99    {
100        expected.push(installed);
101    }
102    if expected.is_empty() {
103        return None;
104    }
105    let actual = if argv0.contains('/') || argv0.contains('\\') {
106        Some(argv0.replace('\\', "/"))
107    } else {
108        resolver.resolve(name)
109    };
110    let reason = match actual {
111        Some(path) if expected.iter().any(|e| e == &path) => return None,
112        Some(path) => format!(
113            "`{name}` resolves to {path}, not a pinned path ({})",
114            expected.join(", ")
115        ),
116        None => format!(
117            "`{name}` is pinned ({}) but was not found on the kernel search path",
118            expected.join(", ")
119        ),
120    };
121    Some(Decision::single(Verdict::Deny, RULE, reason))
122}
123
124fn basename(program: &str) -> &str {
125    program.rsplit(['/', '\\']).next().unwrap_or(program)
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    fn pins(name: &str, path: &str) -> BTreeMap<String, Vec<String>> {
133        BTreeMap::from([(name.to_owned(), vec![path.to_owned()])])
134    }
135
136    fn resolver(name: &str, path: &str) -> MapResolver {
137        MapResolver {
138            resolved: BTreeMap::from([(name.to_owned(), path.to_owned())]),
139            pins: BTreeMap::new(),
140        }
141    }
142
143    #[test]
144    fn unpinned_programs_are_not_checked() {
145        assert!(check("git", &BTreeMap::new(), &NoResolver).is_none());
146        assert!(check("git", &BTreeMap::new(), &resolver("git", "/tmp/evil/git")).is_none());
147    }
148
149    #[test]
150    fn pinned_program_from_expected_path_passes() {
151        let p = pins("git", "/usr/bin/git");
152        assert!(check("git", &p, &resolver("git", "/usr/bin/git")).is_none());
153        assert!(check("/usr/bin/git", &p, &NoResolver).is_none());
154    }
155
156    #[test]
157    fn planted_or_missing_binary_is_denied() {
158        let p = pins("git", "/usr/bin/git");
159        let d = check("git", &p, &resolver("git", "/p/node_modules/.bin/git")).unwrap();
160        assert_eq!(d.verdict, Verdict::Deny);
161        assert_eq!(d.rules, [RULE]);
162        assert!(d.reasons[0].contains("/p/node_modules/.bin/git"));
163        let d = check("/tmp/x/git", &p, &NoResolver).unwrap();
164        assert!(d.reasons[0].contains("/tmp/x/git"));
165        let d = check("git", &p, &NoResolver).unwrap();
166        assert!(d.reasons[0].contains("not found"));
167    }
168
169    #[test]
170    fn installation_pins_count_without_policy_pins() {
171        let r = MapResolver {
172            resolved: BTreeMap::from([("npm".to_owned(), "/tmp/npm".to_owned())]),
173            pins: BTreeMap::from([("npm".to_owned(), "/opt/homebrew/bin/npm".to_owned())]),
174        };
175        assert!(check("npm", &BTreeMap::new(), &r).is_some());
176        let ok = MapResolver {
177            resolved: BTreeMap::from([("npm".to_owned(), "/opt/homebrew/bin/npm".to_owned())]),
178            ..r
179        };
180        assert!(check("npm", &BTreeMap::new(), &ok).is_none());
181    }
182}