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/// The kind of place a call can send data to (ADR-113 ยง1), as the data-flow
85/// atoms name it (ADR-126).
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub(super) enum EgressSink {
88    /// A connection to or fetch from a host off this machine.
89    Network,
90    /// A web search: the query leaves.
91    WebSearch,
92    /// A command that publishes (`git push`, `npm publish`).
93    Publish,
94    /// An MCP tool that acts (`mcp:<server>`).
95    McpSend,
96}
97
98impl EgressSink {
99    /// The word the data-flow atom carries.
100    pub(super) fn as_str(self) -> &'static str {
101        match self {
102            Self::Network => "network",
103            Self::WebSearch => "web-search",
104            Self::Publish => "publish",
105            Self::McpSend => "mcp-send",
106        }
107    }
108}
109
110/// Words in an MCP tool's name that make it act rather than read (ADR-061).
111pub(super) const ACTING: &[&str] = &[
112    "send", "post", "upload", "create", "write", "put", "publish", "share", "comment", "message",
113];
114
115impl CompiledPolicy<'_> {
116    /// The first private data `atoms` read that is not secret material
117    /// ([`Taint::secrets`]): a match of a [`PRIVATE_RULES`] group, a read of a
118    /// path `taint.private_paths` names, or a read of a folder that holds such
119    /// a group's paths (`tar czf x ~/.ssh`).
120    pub(super) fn private_read(&self, atoms: &[AtomicAction]) -> Option<String> {
121        atoms.iter().find_map(|atom| {
122            let private = match atom {
123                AtomicAction::FsRead { path } => {
124                    (!self.names_secret(atom) && self.names_private(atom))
125                        || any_match(&self.private, path.as_str())
126                        || self
127                            .folders
128                            .rules_held(atom)
129                            .iter()
130                            .any(|rule| is_private_rule(rule))
131                }
132                AtomicAction::Shell { .. } | AtomicAction::EnvRead { .. } => {
133                    self.names_private(atom)
134                }
135                _ => false,
136            };
137            private.then(|| atom.describe())
138        })
139    }
140
141    /// Whether a [`PRIVATE_RULES`] group of any list matches `atom`.
142    fn names_private(&self, atom: &AtomicAction) -> bool {
143        [&self.deny, &self.repo_review, &self.allow, &self.review]
144            .into_iter()
145            .flatten()
146            .any(|g| is_private_rule(&g.id) && g.matches(atom))
147    }
148
149    /// Where `action`, whose atoms are `atoms`, can send data: each host off
150    /// this machine it connects to or fetches from, a web search (the query
151    /// leaves), an MCP tool that acts (`mcp:<server>`), and a command that
152    /// publishes (`git-push`, `npm-publish`). Each once, in the order found.
153    pub(super) fn egress_targets(&self, action: &Action, atoms: &[AtomicAction]) -> Vec<String> {
154        self.egress_sinks(action, atoms)
155            .into_iter()
156            .map(|(_, target)| target)
157            .collect()
158    }
159
160    /// [`Self::egress_targets`] with the kind of sink each target is, for the
161    /// data-flow atoms (ADR-126).
162    pub(super) fn egress_sinks(
163        &self,
164        action: &Action,
165        atoms: &[AtomicAction],
166    ) -> Vec<(EgressSink, String)> {
167        let mut out: Vec<(EgressSink, String)> = Vec::new();
168        let mut add = |sink: EgressSink, target: String| {
169            if !out.iter().any(|(_, t)| *t == target) {
170                out.push((sink, target));
171            }
172        };
173        for atom in atoms {
174            match atom {
175                AtomicAction::Net { host } | AtomicAction::Fetch { host }
176                    if !host::is_loopback(host) =>
177                {
178                    add(EgressSink::Network, host.clone());
179                }
180                AtomicAction::WebSearch { .. } => {
181                    add(EgressSink::WebSearch, "web-search".to_owned());
182                }
183                AtomicAction::Shell { argv } => {
184                    if let Some(publish) = publishes(argv) {
185                        add(EgressSink::Publish, publish);
186                    }
187                }
188                _ => {}
189            }
190        }
191        for push in self.pushes(action) {
192            let words: Vec<&str> = push.argv.iter().take(2).map(String::as_str).collect();
193            add(EgressSink::Publish, words.join("-"));
194        }
195        if let Action::McpTool {
196            name,
197            writes,
198            hosts,
199            ..
200        } = action.shown()
201        {
202            let tool = name
203                .rsplit("__")
204                .next()
205                .unwrap_or(name)
206                .to_ascii_lowercase();
207            if !writes.is_empty() || !hosts.is_empty() || ACTING.iter().any(|w| tool.contains(w)) {
208                let server = name.split("__").nth(1).unwrap_or(name);
209                add(EgressSink::McpSend, format!("mcp:{server}"));
210            }
211        }
212        out
213    }
214
215    /// `decision` for `action`, tightened when the session read private data
216    /// (`taint.secrets`, `taint.private`) and untrusted content
217    /// (`taint.untrusted`, `taint.seen`) and this call can send data out:
218    /// `review` by default, `deny` under `taint: { trifecta: deny }`, rule
219    /// `lethal-trifecta`, with a reason naming the three parts. A secret with
220    /// its own host (a brokered one) going to that host alone is no part.
221    /// Merging keeps the strictest verdict, so this never loosens a decision.
222    #[must_use]
223    pub fn with_trifecta(
224        &self,
225        decision: Decision,
226        action: &Action,
227        paths: &dyn PathResolver,
228        taint: &Taint,
229    ) -> Decision {
230        let untrusted = taint.untrusted.as_ref().or(taint.seen.as_ref());
231        let private_read = !taint.secrets.is_empty() || taint.private.is_some();
232        let (Some(untrusted), true) = (untrusted, private_read) else {
233            return decision;
234        };
235        if decision.verdict == Verdict::Deny {
236            return decision;
237        }
238        let (atoms, _) = self.atoms(action, paths);
239        let targets: Vec<String> = self
240            .egress_targets(action, &atoms)
241            .into_iter()
242            .filter(|target| taint.private.is_some() || !owned_by_secrets(taint, target))
243            .collect();
244        if targets.is_empty() {
245            return decision;
246        }
247        let private = taint.private.clone().unwrap_or_else(|| {
248            taint
249                .secrets
250                .iter()
251                .find(|s| s.host.is_none())
252                .or(taint.secrets.first())
253                .map(|s| s.source.clone())
254                .unwrap_or_default()
255        });
256        let verdict = crate::taint::TaintSettings::trifecta_under(self.policy.taint.as_ref());
257        // The facts only: the block message's `why` line explains the three
258        // together, and a reason longer than the message's limit loses its
259        // middle, which is where the untrusted source is named.
260        let reason = format!(
261            "this session read private data ({private}) and content someone else may have \
262             written ({untrusted}), and this call can send data to {}",
263            targets.join(", ")
264        );
265        let mut out = decision;
266        out.merge(Decision::single(verdict, rule_id::LETHAL_TRIFECTA, reason));
267        out
268    }
269}
270
271/// Whether every secret of `taint` belongs to `target`, its own host: a
272/// brokered secret may go there.
273pub(super) fn owned_by_secrets(taint: &Taint, target: &str) -> bool {
274    !taint.secrets.is_empty()
275        && taint.secrets.iter().all(|s| {
276            s.host
277                .as_deref()
278                .is_some_and(|own| own.eq_ignore_ascii_case(target))
279        })
280}
281
282/// Whether `id` names one of [`PRIVATE_RULES`], or a repository's copy of one.
283fn is_private_rule(id: &str) -> bool {
284    let base = id.strip_prefix(REPO_RULE_PREFIX).unwrap_or(id);
285    PRIVATE_RULES.contains(&base)
286}
287
288/// The publishing command `argv` runs (`npm-publish`, `gh-pr-create`), if it
289/// is one: its program and the first words after it that are not options.
290fn publishes(argv: &[String]) -> Option<String> {
291    let program = shell::program_name(argv);
292    let (_, commands) = PUBLISHERS.iter().find(|(p, _)| *p == program)?;
293    let words: Vec<&str> = argv
294        .iter()
295        .skip(1)
296        .filter(|w| !w.starts_with('-'))
297        .take(2)
298        .map(String::as_str)
299        .collect();
300    commands.iter().find_map(|command| {
301        let wanted: Vec<&str> = command.split(' ').collect();
302        (words.len() >= wanted.len() && words[..wanted.len()] == wanted[..])
303            .then(|| format!("{program}-{}", wanted.join("-")))
304    })
305}