Skip to main content

openmoat_core/engine/
injection.rs

1//! Injected input (ADR-057): which call outputs are untrusted, what of them is
2//! kept, and how a later call that acts on it is tightened.
3//!
4//! Only tightens: a later shell command or write whose network target, path
5//! or command came from untrusted content needs review, unless the policy
6//! allows that part of it outright (a host on the allow list, a project
7//! file, `cargo build`). A fetch, a search, an MCP call or an unknown tool
8//! is not checked: following a link or a search result is how reading works,
9//! and the host's own prompt decides those (`fetch: defer`).
10
11use super::{CompiledPolicy, EvalContext, UntrustedKind, checked_atoms};
12use crate::action::{Action, AtomicAction};
13use crate::injection::{
14    self, InjectedLookup, MAX_COMMAND_LEN, MAX_TOKENS_PER_OUTPUT, MIN_COMMAND_LEN, Token, TokenKind,
15};
16use crate::programs::NoResolver;
17use crate::realpath::PathResolver;
18use crate::verdict::{Decision, Verdict};
19
20/// Programs whose output is text from a forge's issues, pull requests and
21/// comments, which anyone may write: their hosts are on the allow list
22/// (`registries`), so they are named here.
23const REMOTE_TEXT_PROGRAMS: [&str; 3] = ["gh", "glab", "tea"];
24
25impl CompiledPolicy<'_> {
26    /// What the output of `action`, run in `cwd`, is, when it is content an
27    /// attacker may control (`fetch https://docs.example/page`): what session
28    /// taint calls untrusted (a fetch, a web search, an MCP result, an unknown
29    /// tool; a metadata tool too, which does not taint the session, since a
30    /// page sets the title and URL a tab list shows), and a shell command that
31    /// reads from a network host the policy does not allow or from a forge's
32    /// command-line client (`gh issue view`). `None` for everything else: a
33    /// read of a file, a local command. Never cut: a caller that keeps it
34    /// redacts the whole of it first, then shortens it (the audit store), so
35    /// a credential in the command is never split where no pattern sees it.
36    #[must_use]
37    pub fn output_source(
38        &self,
39        action: &Action,
40        cwd: &str,
41        paths: &dyn PathResolver,
42    ) -> Option<String> {
43        let ctx = EvalContext {
44            cwd: cwd.to_owned(),
45            ..self.ctx.clone()
46        };
47        let (atoms, _) = checked_atoms(action, &ctx, self.opens_as(), paths);
48        self.output_source_in(action, &atoms)
49    }
50
51    /// [`Self::output_source`] of `action`, whose checked atoms are `atoms`.
52    pub(super) fn output_source_in(
53        &self,
54        action: &Action,
55        atoms: &[AtomicAction],
56    ) -> Option<String> {
57        if let Some(exposed) = atoms.iter().find(|atom| UntrustedKind::of(atom).is_some()) {
58            let source = match action.shown() {
59                Action::Fetch { url } => format!("the page fetched from {url}"),
60                Action::WebSearch { query } => format!("the web search results for \"{query}\""),
61                Action::McpTool { name, .. } => format!("the result of MCP tool {name}"),
62                Action::UnknownTool { tool, .. } => format!("the output of tool {tool}"),
63                Action::Shell { command } => format!("the output of `{command}`"),
64                _ => exposed.describe(),
65            };
66            return Some(source);
67        }
68        let command = match action.shown() {
69            Action::Shell { command } => command,
70            Action::ForeignShell { command, .. } => {
71                return self
72                    .foreign_reads_remote(command)
73                    .then(|| format!("the output of `{command}`"));
74            }
75            _ => return None,
76        };
77        let reads_remote = atoms.iter().any(|atom| match atom {
78            AtomicAction::Net { host } | AtomicAction::Fetch { host } => {
79                !crate::host::is_loopback(host) && !self.allows(atom)
80            }
81            AtomicAction::Shell { argv } => argv
82                .first()
83                .is_some_and(|p| REMOTE_TEXT_PROGRAMS.contains(&program_name(p))),
84            _ => false,
85        });
86        reads_remote.then(|| format!("the output of `{command}`"))
87    }
88
89    /// The tokens of `output`, the output of `source` (an action
90    /// [`Self::output_source`] names), worth keeping: hosts other than the
91    /// ones `source` itself reached and than loopback, absolute paths outside
92    /// the project, and commands of its code spans as the classifier reads
93    /// them. Hosts are kept in their canonical spelling
94    /// (`host::canonical`, ADR-063 §4), as a later call's hosts are
95    /// compared. De-duplicated, at most [`MAX_TOKENS_PER_OUTPUT`]: URL hosts
96    /// first, then commands, paths, and words that look like hosts.
97    #[must_use]
98    pub fn injected_tokens(&self, source: &Action, cwd: &str, output: &str) -> Vec<Token> {
99        let found = injection::candidates(output);
100        let ctx = EvalContext {
101            cwd: cwd.to_owned(),
102            ..self.ctx.clone()
103        };
104        let (source_atoms, _) = checked_atoms(source, &ctx, self.opens_as(), &NoResolver);
105        // Never kept, so never a parent a later call links to (ADR-063 §4):
106        // `docs.github.com` named by a page on `github.com` links nothing new.
107        let foreign_hosts = match source.shown() {
108            Action::ForeignShell { command, .. } => foreign::named(command).remote,
109            _ => Vec::new(),
110        };
111        let own_hosts: Vec<String> = source_atoms
112            .iter()
113            .filter_map(host_of)
114            .chain(foreign_hosts.iter().map(String::as_str))
115            .map(crate::host::canonical)
116            .collect();
117        let host_token = |kind: TokenKind| {
118            let own_hosts = &own_hosts;
119            move |host: String| {
120                let text = crate::host::canonical(&host);
121                let foreign = !own_hosts.contains(&text) && !crate::host::is_loopback(&host);
122                foreign.then_some(Token { kind, text })
123            }
124        };
125        let commands = found
126            .commands
127            .iter()
128            .flat_map(|line| self.commands_of(line, &ctx));
129        // a relative path is placed against the directory the output was
130        // read in, as the agent would place it (ADR-113)
131        let paths = found.paths.iter().chain(&found.relative).filter_map(|raw| {
132            let path =
133                crate::paths::resolve(raw, &ctx.home, ctx.project.as_deref(), Some(&ctx.cwd))?;
134            (path.len() > 1 && !self.in_project(&path)).then(|| Token {
135                kind: TokenKind::Path,
136                text: self.path_key(&path),
137            })
138        });
139        let mut tokens: Vec<Token> = Vec::new();
140        let all = found
141            .url_hosts
142            .into_iter()
143            .filter_map(host_token(TokenKind::UrlHost))
144            .chain(commands)
145            .chain(paths)
146            .chain(
147                found
148                    .word_hosts
149                    .into_iter()
150                    .filter_map(host_token(TokenKind::WordHost)),
151            );
152        for token in all {
153            if tokens.len() >= MAX_TOKENS_PER_OUTPUT {
154                break;
155            }
156            if !tokens.contains(&token) {
157                tokens.push(token);
158            }
159        }
160        tokens
161    }
162
163    /// `decision` for `action`, tightened by the tokens of untrusted content
164    /// `seen` knows: a shell command or a write needs review when a host it
165    /// reaches, a file it writes or a command it runs came from that content,
166    /// and the policy does not allow that atom. A command counts only when the
167    /// call also reaches a host or a file outside the project that the policy
168    /// does not allow. A command of a shell the classifier cannot read
169    /// (PowerShell) is checked on its text: a host or a path outside the
170    /// project it names ([`foreign`]). Never loosens; a deny stays.
171    #[must_use]
172    pub fn with_injected(
173        &self,
174        decision: Decision,
175        action: &Action,
176        paths: &dyn PathResolver,
177        seen: &dyn InjectedLookup,
178    ) -> Decision {
179        let checked = matches!(
180            action.shown(),
181            Action::Shell { .. }
182                | Action::ForeignShell { .. }
183                | Action::FsWrite { .. }
184                | Action::Patch { .. }
185        );
186        if !checked || decision.verdict == Verdict::Deny {
187            return decision;
188        }
189        if let Action::ForeignShell { command, .. } = action.shown() {
190            return planted(decision, self.foreign_injected(command, seen));
191        }
192        let (atoms, _) = self.atoms(action, paths);
193        // A command copied from the content counts only when it reaches past
194        // what the policy allows outside the project: a host or a file. Docs
195        // tell people to run `git push origin main`; that is daily work.
196        let reaches_outside = atoms.iter().any(|atom| match atom {
197            AtomicAction::Net { .. } | AtomicAction::Fetch { .. } => !self.allows(atom),
198            AtomicAction::FsRead { path } | AtomicAction::FsWrite { path } => {
199                !self.in_project(path) && !self.allows(atom)
200            }
201            _ => false,
202        });
203        let found = atoms
204            .iter()
205            .filter(|atom| reaches_outside || !matches!(atom, AtomicAction::Shell { .. }))
206            .filter_map(|atom| self.injected(atom, seen))
207            .collect();
208        planted(decision, found)
209    }
210
211    /// The part of `atom` that came from untrusted content, unless the policy
212    /// allows the atom; `None` when no part did.
213    fn injected(&self, atom: &AtomicAction, seen: &dyn InjectedLookup) -> Option<Found> {
214        let (token, source) = match atom {
215            AtomicAction::Net { host } | AtomicAction::Fetch { host } => {
216                let kinds = [TokenKind::UrlHost, TokenKind::WordHost];
217                probe(seen, host_tokens(host, &kinds))
218                    .or_else(|| self.parent_source(atom, host, seen))
219            }
220            // a word that only looks like a host (`app.run`) is compared with
221            // hosts of URLs alone, which prose does not invent, and not with
222            // their parents: it is not a request to any of them
223            AtomicAction::NetWord { host } => probe(seen, host_tokens(host, &[TokenKind::UrlHost])),
224            AtomicAction::FsWrite { path } => probe(
225                seen,
226                [Token {
227                    kind: TokenKind::Path,
228                    text: self.path_key(path),
229                }],
230            ),
231            // a command is compared as the classifier reads it, which also
232            // yields the command a wrapper runs (`sudo`, `env`, `nohup`,
233            // `sh -c`) and leaves `VAR=value` out, at keep and at check alike
234            // and with its program's directory, `./` and `~` taken out, and
235            // its paths placed against the working directory (ADR-113)
236            AtomicAction::Shell { argv } => probe(
237                seen,
238                command_texts(argv, &self.ctx)
239                    .into_iter()
240                    .map(|text| Token {
241                        kind: TokenKind::Command,
242                        text,
243                    }),
244            ),
245            _ => None,
246        }?;
247        if self.allows(atom) {
248            return None;
249        }
250        let what = match token.kind {
251            TokenKind::UrlHost | TokenKind::WordHost => "host",
252            TokenKind::Path => "path",
253            TokenKind::Command => "command",
254        };
255        Some(Found {
256            part: format!("the {what} `{}`", token.text),
257            source,
258        })
259    }
260
261    /// The kept URL host a parent domain of `host` matches, and its source:
262    /// a kept URL host links a request to any of its subdomains (ADR-063 §4).
263    /// One probe per parent, nearest first; a parent the policy allows on its
264    /// own (`github.com`) links nothing, so a page naming an allowed site
265    /// does not tighten every call to its subdomains. Word hosts are compared
266    /// exactly: a name in prose is weaker evidence than a URL (ADR-057 §4).
267    fn parent_source(
268        &self,
269        atom: &AtomicAction,
270        host: &str,
271        seen: &dyn InjectedLookup,
272    ) -> Option<(Token, String)> {
273        let host = crate::host::canonical(host);
274        crate::host::parents(&host).find_map(|parent| {
275            let token = Token {
276                kind: TokenKind::UrlHost,
277                text: parent.to_owned(),
278            };
279            let source = seen.source_of(&token)?;
280            (!self.allows(&with_host(atom, parent))).then_some((token, source))
281        })
282    }
283
284    /// Whether the policy decides `atom` `allow` on its own.
285    fn allows(&self, atom: &AtomicAction) -> bool {
286        self.evaluate_atomic(atom)
287            .is_some_and(|d| d.verdict == Verdict::Allow)
288    }
289
290    /// The commands `line` runs, as [`Self::with_injected`] compares them.
291    fn commands_of(&self, line: &str, ctx: &EvalContext) -> Vec<Token> {
292        let action = Action::Shell {
293            command: line.to_owned(),
294        };
295        let (atoms, _) = checked_atoms(&action, ctx, self.opens_as(), &NoResolver);
296        atoms
297            .iter()
298            .filter_map(|atom| match atom {
299                AtomicAction::Shell { argv } => command_texts(argv, ctx).into_iter().next(),
300                _ => None,
301            })
302            .map(|text| Token {
303                kind: TokenKind::Command,
304                text,
305            })
306            .collect()
307    }
308
309    /// Whether `path` is the project or below it, under either spelling.
310    fn in_project(&self, path: &str) -> bool {
311        let key = self.path_key(path);
312        [&self.ctx.project, &self.ctx.real_project]
313            .into_iter()
314            .flatten()
315            .any(|root| {
316                let root = self.path_key(root);
317                let root = root.trim_end_matches('/');
318                key == root
319                    || key
320                        .strip_prefix(root)
321                        .is_some_and(|rest| rest.starts_with('/'))
322            })
323    }
324
325    /// `path` as tokens compare it: lowercase where file names ignore case.
326    pub(super) fn path_key(&self, path: &str) -> String {
327        if self.ctx.case_insensitive_paths {
328            path.to_lowercase()
329        } else {
330            path.to_owned()
331        }
332    }
333}
334
335/// The texts a command is compared by, when it has arguments and is long
336/// enough to be distinctive: its words normalised ([`normalised_words`]) and
337/// joined by spaces, which is what is kept; then, when that differs, its words
338/// as the classifier gave them, which rows kept before ADR-113 hold.
339fn command_texts(argv: &[String], ctx: &EvalContext) -> Vec<String> {
340    let fits = |text: &String| {
341        argv.len() >= 2 && (MIN_COMMAND_LEN..=MAX_COMMAND_LEN).contains(&text.len())
342    };
343    let normalised = normalised_words(argv, ctx).join(" ");
344    let written = argv.join(" ");
345    let mut out: Vec<String> = [normalised, written].into_iter().filter(fits).collect();
346    out.dedup();
347    out
348}
349
350/// A command's words in one spelling (ADR-113): the program without its
351/// directory (`/usr/bin/tar` is `tar`; lowercase where file names ignore
352/// case), a leading `./` taken off a word (`./out.tgz` is `out.tgz`), and a
353/// home path, an absolute path or one that climbs (`../x`) placed against the
354/// home and working directories. Options and other words stay as written:
355/// flags are not re-ordered, nothing is dropped.
356fn normalised_words(argv: &[String], ctx: &EvalContext) -> Vec<String> {
357    argv.iter()
358        .enumerate()
359        .map(|(n, word)| {
360            if n == 0 {
361                let program = program_name(word);
362                return if ctx.case_insensitive_paths {
363                    program.to_lowercase()
364                } else {
365                    program.to_owned()
366                };
367            }
368            let mut rest = word.as_str();
369            while let Some(tail) = rest.strip_prefix("./") {
370                rest = tail;
371            }
372            let placed = rest == "~"
373                || rest.starts_with("~/")
374                || rest.starts_with('/')
375                || rest.starts_with("../");
376            if placed
377                && let Some(path) =
378                    crate::paths::resolve(rest, &ctx.home, ctx.project.as_deref(), Some(&ctx.cwd))
379            {
380                return path;
381            }
382            rest.to_owned()
383        })
384        .collect()
385}
386
387/// One part of a call that came from untrusted content, worded as the reason
388/// names it (the host `x`), and where it came from.
389struct Found {
390    part: String,
391    source: String,
392}
393
394/// `decision` with one review per source of `found` merged in, naming each
395/// part once: "the command `x`,
396/// the host `h` and the path `p` came from …". A planted command makes several
397/// atoms (the command, the host it reaches, the file it writes), and the
398/// person reads one sentence for them, not one per atom.
399fn planted(decision: Decision, found: Vec<Found>) -> Decision {
400    let mut sources: Vec<(String, Vec<String>)> = Vec::new();
401    for Found { part, source } in found {
402        match sources.iter_mut().find(|(known, _)| *known == source) {
403            Some((_, parts)) if !parts.contains(&part) => parts.push(part),
404            Some(_) => {}
405            None => sources.push((source, vec![part])),
406        }
407    }
408    sources
409        .into_iter()
410        .map(|(source, parts)| {
411            Decision::single(
412                Verdict::Review,
413                crate::rule_id::INJECTED_INPUT,
414                format!(
415                    "{} came from {source}, untrusted content this session read; the call may \
416                     follow an instruction planted there",
417                    listed(&parts)
418                ),
419            )
420        })
421        .fold(decision, |mut acc, next| {
422            acc.merge(next);
423            acc
424        })
425}
426
427/// `a`, `a and b`, `a, b and c`.
428fn listed(parts: &[String]) -> String {
429    match parts {
430        [] => String::new(),
431        [one] => one.clone(),
432        [init @ .., last] => format!("{} and {last}", init.join(", ")),
433    }
434}
435
436/// The first of `tokens` the session kept, with its source.
437fn probe(
438    seen: &dyn InjectedLookup,
439    tokens: impl IntoIterator<Item = Token>,
440) -> Option<(Token, String)> {
441    tokens
442        .into_iter()
443        .find_map(|token| seen.source_of(&token).map(|source| (token, source)))
444}
445
446/// The tokens a call's `host` is compared with, one per kind of `kinds`: in
447/// its canonical spelling ([`crate::host::canonical`]), which tokens are kept
448/// in, then as written (lowercase, no trailing dot) when that differs, which
449/// rows kept before ADR-063 hold for an address spelled another way.
450pub(super) fn host_tokens(host: &str, kinds: &[TokenKind]) -> Vec<Token> {
451    let canonical = crate::host::canonical(host);
452    let written = host.trim_end_matches('.').to_ascii_lowercase();
453    let spellings = if written == canonical {
454        vec![canonical]
455    } else {
456        vec![canonical, written]
457    };
458    spellings
459        .iter()
460        .flat_map(|text| {
461            kinds.iter().map(|kind| Token {
462                kind: *kind,
463                text: text.clone(),
464            })
465        })
466        .collect()
467}
468
469/// `atom`, a `Net` or `Fetch` atom, reaching `host` instead.
470fn with_host(atom: &AtomicAction, host: &str) -> AtomicAction {
471    let host = host.to_owned();
472    if matches!(atom, AtomicAction::Fetch { .. }) {
473        AtomicAction::Fetch { host }
474    } else {
475        AtomicAction::Net { host }
476    }
477}
478
479/// The host a network atom reaches.
480fn host_of(atom: &AtomicAction) -> Option<&str> {
481    match atom {
482        AtomicAction::Net { host }
483        | AtomicAction::Fetch { host }
484        | AtomicAction::NetWord { host } => Some(host),
485        _ => None,
486    }
487}
488
489/// The file name of a program word (`/usr/bin/gh` → `gh`).
490fn program_name(word: &str) -> &str {
491    word.rsplit(['/', '\\']).next().unwrap_or(word)
492}
493
494mod foreign;
495#[cfg(test)]
496mod tests;