Skip to main content

openmoat_core/engine/
trifecta.rs

1//! The lethal trifecta (ADR-113): a session that read private data and
2//! content someone else may have written, then makes a call that can send data
3//! out. Each part is ordinary on its own; together they are how an injected
4//! instruction carries private data away, even to a host the policy allows.
5//!
6//! The facts are kept on the session's [`Taint`] (no second store):
7//! `private_data_read` is [`Taint::secrets`] or [`Taint::private`],
8//! `untrusted_seen` is [`Taint::untrusted`] or [`Taint::seen`], both folded by
9//! the caller from the calls that ran ([`CompiledPolicy::exposure`]). The third
10//! part is this call: [`CompiledPolicy::egress_targets`]. A session that never
11//! read private data is never touched.
12
13use super::{CompiledPolicy, Taint};
14use crate::action::{Action, AtomicAction};
15use crate::pattern::any_match;
16use crate::realpath::PathResolver;
17use crate::repo::REPO_RULE_PREFIX;
18use crate::rule_id;
19use crate::verdict::{Decision, Verdict};
20use crate::{host, shell};
21
22/// Rule groups whose matches read private data, wherever the policy puts
23/// them: credentials of the agents, the build tools and Kerberos, decoy keys,
24/// the whole environment and secret variables, and the commands that print a
25/// stored token (`secrets-paths`' shell patterns; its reads are secret
26/// material already, [`Taint::secrets`]).
27const PRIVATE_RULES: &[&str] = &[
28    rule_id::SECRETS_PATHS,
29    rule_id::AGENT_CREDENTIALS,
30    rule_id::BUILD_CREDENTIALS,
31    rule_id::KERBEROS_TICKETS,
32    rule_id::CANARY,
33    rule_id::ENV_DUMP,
34    rule_id::ENV_SECRETS,
35];
36
37/// Commands that publish what they are given, by program and the words that
38/// follow it: `git push` and its kin send data to a host their arguments may
39/// not name. A command that only reads (`gh pr view`) is not one.
40const PUBLISHERS: &[(&str, &[&str])] = &[
41    ("git", &["push", "send-email"]),
42    (
43        "gh",
44        &[
45            "gist create",
46            "gist edit",
47            "pr create",
48            "pr comment",
49            "pr edit",
50            "issue create",
51            "issue comment",
52            "issue edit",
53            "release create",
54            "release upload",
55            "api",
56            "repo create",
57        ],
58    ),
59    (
60        "glab",
61        &[
62            "mr create",
63            "mr note",
64            "issue create",
65            "issue note",
66            "release create",
67            "api",
68            "snippet create",
69        ],
70    ),
71    ("npm", &["publish"]),
72    ("pnpm", &["publish"]),
73    ("yarn", &["publish", "npm publish"]),
74    ("bun", &["publish"]),
75    ("cargo", &["publish"]),
76    ("twine", &["upload"]),
77    ("gem", &["push"]),
78    ("docker", &["push"]),
79    ("podman", &["push"]),
80    ("poetry", &["publish"]),
81    ("uv", &["publish"]),
82];
83
84/// Words in an MCP tool's name that make it act rather than read (ADR-061).
85pub(super) const ACTING: &[&str] = &[
86    "send", "post", "upload", "create", "write", "put", "publish", "share", "comment", "message",
87];
88
89impl CompiledPolicy<'_> {
90    /// The first private data `atoms` read that is not secret material
91    /// ([`Taint::secrets`]): a match of a [`PRIVATE_RULES`] group, a read of a
92    /// path `taint.private_paths` names, or a read of a folder that holds such
93    /// a group's paths (`tar czf x ~/.ssh`).
94    pub(super) fn private_read(&self, atoms: &[AtomicAction]) -> Option<String> {
95        atoms.iter().find_map(|atom| {
96            let private = match atom {
97                AtomicAction::FsRead { path } => {
98                    (!self.names_secret(atom) && self.names_private(atom))
99                        || any_match(&self.private, path.as_str())
100                        || self
101                            .folders
102                            .rules_held(atom)
103                            .iter()
104                            .any(|rule| is_private_rule(rule))
105                }
106                AtomicAction::Shell { .. } | AtomicAction::EnvRead { .. } => {
107                    self.names_private(atom)
108                }
109                _ => false,
110            };
111            private.then(|| atom.describe())
112        })
113    }
114
115    /// Whether a [`PRIVATE_RULES`] group of any list matches `atom`.
116    fn names_private(&self, atom: &AtomicAction) -> bool {
117        [&self.deny, &self.repo_review, &self.allow, &self.review]
118            .into_iter()
119            .flatten()
120            .any(|g| is_private_rule(&g.id) && g.matches(atom))
121    }
122
123    /// Where `action`, whose atoms are `atoms`, can send data: each host off
124    /// this machine it connects to or fetches from, a web search (the query
125    /// leaves), an MCP tool that acts (`mcp:<server>`), and a command that
126    /// publishes (`git-push`, `npm-publish`). Each once, in the order found.
127    pub(super) fn egress_targets(&self, action: &Action, atoms: &[AtomicAction]) -> Vec<String> {
128        let mut out: Vec<String> = Vec::new();
129        let mut add = |target: String| {
130            if !out.contains(&target) {
131                out.push(target);
132            }
133        };
134        for atom in atoms {
135            match atom {
136                AtomicAction::Net { host } | AtomicAction::Fetch { host }
137                    if !host::is_loopback(host) =>
138                {
139                    add(host.clone());
140                }
141                AtomicAction::WebSearch { .. } => add("web-search".to_owned()),
142                AtomicAction::Shell { argv } => {
143                    if let Some(publish) = publishes(argv) {
144                        add(publish);
145                    }
146                }
147                _ => {}
148            }
149        }
150        for push in self.pushes(action) {
151            let words: Vec<&str> = push.argv.iter().take(2).map(String::as_str).collect();
152            add(words.join("-"));
153        }
154        if let Action::McpTool {
155            name,
156            writes,
157            hosts,
158            ..
159        } = action.shown()
160        {
161            let tool = name
162                .rsplit("__")
163                .next()
164                .unwrap_or(name)
165                .to_ascii_lowercase();
166            if !writes.is_empty() || !hosts.is_empty() || ACTING.iter().any(|w| tool.contains(w)) {
167                let server = name.split("__").nth(1).unwrap_or(name);
168                add(format!("mcp:{server}"));
169            }
170        }
171        out
172    }
173
174    /// `decision` for `action`, tightened when the session read private data
175    /// (`taint.secrets`, `taint.private`) and untrusted content
176    /// (`taint.untrusted`, `taint.seen`) and this call can send data out:
177    /// `review` by default, `deny` under `taint: { trifecta: deny }`, rule
178    /// `lethal-trifecta`, with a reason naming the three parts. A secret with
179    /// its own host (a brokered one) going to that host alone is no part.
180    /// Merging keeps the strictest verdict, so this never loosens a decision.
181    #[must_use]
182    pub fn with_trifecta(
183        &self,
184        decision: Decision,
185        action: &Action,
186        paths: &dyn PathResolver,
187        taint: &Taint,
188    ) -> Decision {
189        let untrusted = taint.untrusted.as_ref().or(taint.seen.as_ref());
190        let private_read = !taint.secrets.is_empty() || taint.private.is_some();
191        let (Some(untrusted), true) = (untrusted, private_read) else {
192            return decision;
193        };
194        if decision.verdict == Verdict::Deny {
195            return decision;
196        }
197        let (atoms, _) = self.atoms(action, paths);
198        let targets: Vec<String> = self
199            .egress_targets(action, &atoms)
200            .into_iter()
201            .filter(|target| taint.private.is_some() || !owned_by_secrets(taint, target))
202            .collect();
203        if targets.is_empty() {
204            return decision;
205        }
206        let private = taint.private.clone().unwrap_or_else(|| {
207            taint
208                .secrets
209                .iter()
210                .find(|s| s.host.is_none())
211                .or(taint.secrets.first())
212                .map(|s| s.source.clone())
213                .unwrap_or_default()
214        });
215        let verdict = crate::taint::TaintSettings::trifecta_under(self.policy.taint.as_ref());
216        // The facts only: the block message's `why` line explains the three
217        // together, and a reason longer than the message's limit loses its
218        // middle, which is where the untrusted source is named.
219        let reason = format!(
220            "this session read private data ({private}) and content someone else may have \
221             written ({untrusted}), and this call can send data to {}",
222            targets.join(", ")
223        );
224        let mut out = decision;
225        out.merge(Decision::single(verdict, rule_id::LETHAL_TRIFECTA, reason));
226        out
227    }
228}
229
230/// Whether every secret of `taint` belongs to `target`, its own host: a
231/// brokered secret may go there.
232fn owned_by_secrets(taint: &Taint, target: &str) -> bool {
233    !taint.secrets.is_empty()
234        && taint.secrets.iter().all(|s| {
235            s.host
236                .as_deref()
237                .is_some_and(|own| own.eq_ignore_ascii_case(target))
238        })
239}
240
241/// Whether `id` names one of [`PRIVATE_RULES`], or a repository's copy of one.
242fn is_private_rule(id: &str) -> bool {
243    let base = id.strip_prefix(REPO_RULE_PREFIX).unwrap_or(id);
244    PRIVATE_RULES.contains(&base)
245}
246
247/// The publishing command `argv` runs (`npm-publish`, `gh-pr-create`), if it
248/// is one: its program and the first words after it that are not options.
249fn publishes(argv: &[String]) -> Option<String> {
250    let program = shell::program_name(argv);
251    let (_, commands) = PUBLISHERS.iter().find(|(p, _)| *p == program)?;
252    let words: Vec<&str> = argv
253        .iter()
254        .skip(1)
255        .filter(|w| !w.starts_with('-'))
256        .take(2)
257        .map(String::as_str)
258        .collect();
259    commands.iter().find_map(|command| {
260        let wanted: Vec<&str> = command.split(' ').collect();
261        (words.len() >= wanted.len() && words[..wanted.len()] == wanted[..])
262            .then(|| format!("{program}-{}", wanted.join("-")))
263    })
264}