openmoat-core 0.27.0

Policy model and decision engine for OpenMoat. Pure: no I/O, no OS calls.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! Known token shapes and broker placeholders on their way out of the machine
//! (docs/POLICY.md §3, `token-egress` and `placeholder-egress`).
//!
//! What leaves: a URL a fetch or network tool opens or an MCP call names, a web
//! search query, and the arguments of a command that connects where its
//! arguments say (`curl`, `wget`, `git push`, …) with every command piped into
//! it. Where it goes: the hosts named there. A token of a well-known format
//! ([`crate::token`]) going to a host that is not its service's, or a
//! placeholder of a brokered secret going to a host other than the one the
//! proxy puts the secret in, becomes an atom the default policy denies:
//! `@token-egress <service> <host>` and `@placeholder-egress <id> <host>`. The
//! token itself is never put in an atom, so it never reaches a reason.
//!
//! The same text is scanned for personal data ([`crate::personal`], ADR-052):
//! a payment card number or a list of mail addresses going to a host other
//! than this machine becomes `@pii-egress <class> <host>` (`card`, `emails`).
//! Those atoms count only where a policy rule names them ([`counts_where_named`]),
//! so a policy without such a rule decides as it did before; the default policy
//! denies `card` (`card-egress`) and names no rule for `emails`.
//!
//! Credentials with no vendor prefix are found in the same texts
//! ([`token::credentials`]): an AWS secret access key or a private key going
//! to a host that is not its own is a `@token-egress` atom; a JWT or a
//! database URL with a password is `@credential-egress <kind> <host>`, which
//! also counts only where a rule names it (`credential-egress` holds it for
//! review). Loopback hosts are left out of both.

use crate::action::{Action, AtomicAction};
use crate::host::web;
use crate::secret::Secret;
use crate::{host, personal, shell, token};

mod encoded;

pub(super) use encoded::atoms as encoded_atoms;

/// First word of an atom for a token sent to a host not its service's.
const TOKEN_ATOM: &str = "@token-egress";
/// First word of an atom for a placeholder sent where the broker does not map it.
const PLACEHOLDER_ATOM: &str = "@placeholder-egress";
/// First word of an atom for personal data sent off this machine.
const PERSONAL_ATOM: &str = "@pii-egress";
/// First word of an atom for a credential whose shape names no owner it could
/// be checked against (a JWT, a database URL with a password), sent off this
/// machine to a host that is not its own.
const CREDENTIAL_ATOM: &str = "@credential-egress";
/// The host of an atom when what is sent names no host the classifier can read.
const UNKNOWN_HOST: &str = "(unknown-host)";
/// The host of an atom for a web search query: the host's search provider.
const WEB_SEARCH: &str = "(web-search)";
/// Words between the commands of a pipeline or list.
const LIST_SEPARATORS: &[&str] = &[";", "&&", "||", "&", "\n"];
const PIPES: &[&str] = &["|", "|&"];

/// Text sent out, and the hosts it goes to.
pub(super) struct Send<'a> {
    pub(super) texts: Vec<&'a str>,
    pub(super) hosts: Vec<String>,
    /// Whether it carries a file or a body beyond the URL: an upload, form or
    /// data option, a file-copying program, or input piped into the sender
    /// (ADR-061). A plain `GET` does not.
    pub(super) body: bool,
}

/// The `@token-egress`, `@placeholder-egress` and `@pii-egress` atoms of
/// `action`, whose classified atoms are `atoms`; `secrets` are the policy's
/// brokered secrets.
pub(super) fn atoms(
    action: &Action,
    atoms: &[AtomicAction],
    secrets: &[Secret],
) -> Vec<AtomicAction> {
    let mut out: Vec<AtomicAction> = Vec::new();
    for send in sends(action, atoms) {
        let hosts = if send.hosts.is_empty() {
            vec![UNKNOWN_HOST.to_owned()]
        } else {
            send.hosts
        };
        for class in personal::classes_in(&send.texts) {
            for host in hosts.iter().filter(|h| !host::is_loopback(h)) {
                push(&mut out, PERSONAL_ATOM, class.id(), host);
            }
        }
        for text in send.texts {
            for shape in token::shapes_in(text) {
                for host in hosts.iter().filter(|h| !shape.owns(h)) {
                    push(&mut out, TOKEN_ATOM, shape.id, host);
                }
            }
            // credentials found only in context, which this machine may keep
            for found in token::credentials::in_text(text) {
                let first = if found.denied {
                    TOKEN_ATOM
                } else {
                    CREDENTIAL_ATOM
                };
                for host in hosts
                    .iter()
                    .filter(|h| !found.owns(h) && !host::is_loopback(h))
                {
                    push(&mut out, first, found.id, host);
                }
            }
            for id in placeholders(text) {
                let mapped = secrets.iter().find(|s| s.id == id).map(|s| s.host.as_str());
                for host in hosts.iter().filter(|h| mapped != Some(h.as_str())) {
                    push(&mut out, PLACEHOLDER_ATOM, &id, host);
                }
            }
        }
    }
    out
}

/// Whether `atom` is a `@pii-egress` or `@credential-egress` atom: it carries
/// a verdict only where a rule names it, never the policy's defaults, so a
/// policy without such a rule decides as it did before.
pub(super) fn counts_where_named(atom: &AtomicAction) -> bool {
    matches!(atom, AtomicAction::Shell { argv }
        if argv.first().is_some_and(|w| w == PERSONAL_ATOM || w == CREDENTIAL_ATOM))
}

fn push(out: &mut Vec<AtomicAction>, first: &str, what: &str, host: &str) {
    let atom = AtomicAction::Shell {
        argv: vec![first.to_owned(), what.to_owned(), host.to_owned()],
    };
    if !out.contains(&atom) {
        out.push(atom);
    }
}

pub(super) fn sends<'a>(action: &'a Action, atoms: &'a [AtomicAction]) -> Vec<Send<'a>> {
    match action {
        Action::Net { url } => vec![url_send(url)],
        // read as a browser opens a page, so the URLs inside it are hosts too
        Action::Fetch { url } => vec![open_send(url)],
        Action::WebSearch { query } => vec![Send {
            texts: vec![query],
            hosts: vec![WEB_SEARCH.to_owned()],
            body: false,
        }],
        // A tool's arguments: each URL it names, and what each shell command
        // among them sends.
        Action::McpTool {
            hosts,
            opens,
            commands,
            ..
        } => hosts
            .iter()
            .map(|url| url_send(url))
            .chain(opens.iter().map(|url| open_send(url)))
            .chain(
                (!commands.is_empty())
                    .then(|| atoms.iter().flat_map(command_sends))
                    .into_iter()
                    .flatten(),
            )
            .collect(),
        Action::UnknownTool {
            hosts, commands, ..
        } => hosts
            .iter()
            .map(|url| url_send(url))
            .chain(
                (!commands.is_empty())
                    .then(|| atoms.iter().flat_map(command_sends))
                    .into_iter()
                    .flatten(),
            )
            .collect(),
        Action::Shell { .. } => atoms.iter().flat_map(command_sends).collect(),
        Action::Unchecked { action, .. } => sends(action, atoms),
        _ => Vec::new(),
    }
}

/// A URL a tool reads or connects to: sent to every host a client may read it
/// as reaching ([`web::readings`]).
fn url_send(url: &str) -> Send<'_> {
    Send {
        texts: vec![url],
        hosts: web::readings(url),
        body: false,
    }
}

/// The page a read-only call opens (ADR-047): sent to its hosts, as a browser
/// opens it, and to the hosts of the URLs inside it, which a redirect reaches.
fn open_send(url: &str) -> Send<'_> {
    let opened = web::with_scheme(url);
    let mut hosts = web::readings(&opened);
    hosts.extend(web::embedded_hosts(&opened));
    Send {
        texts: vec![url],
        hosts,
        body: false,
    }
}

/// A command that connects where its arguments say sends them there; so does
/// every command of a pipeline that has one, through the pipe.
fn command_sends(atom: &AtomicAction) -> Vec<Send<'_>> {
    match atom {
        AtomicAction::Shell { argv } if shell::names_hosts(argv) => vec![Send {
            texts: argv.iter().skip(1).map(String::as_str).collect(),
            hosts: argument_hosts(argv),
            body: carries_body(argv),
        }],
        AtomicAction::Pipeline { argv } => argv
            .split(|w| LIST_SEPARATORS.contains(&w.as_str()))
            .filter_map(pipeline_send)
            .collect(),
        _ => Vec::new(),
    }
}

fn pipeline_send(words: &[String]) -> Option<Send<'_>> {
    let commands: Vec<&[String]> = words
        .split(|w| PIPES.contains(&w.as_str()))
        .filter(|c| !c.is_empty())
        .collect();
    let connecting: Vec<&[String]> = commands
        .iter()
        .copied()
        .filter(|c| shell::names_hosts(c))
        .collect();
    if commands.len() < 2 || connecting.is_empty() {
        return None;
    }
    Some(Send {
        texts: commands
            .iter()
            .flat_map(|c| c.iter())
            .map(String::as_str)
            .collect(),
        hosts: connecting.iter().flat_map(|c| argument_hosts(c)).collect(),
        // what runs before the sender reaches it through the pipe
        body: true,
    })
}

/// Options that put a file or data in a request, as `curl` and `wget` spell
/// them; a value may follow attached (`-d@x`, `--data=x`).
const BODY_OPTIONS: &[&str] = &[
    "-F",
    "--form",
    "-T",
    "--upload-file",
    "-d",
    "--data",
    "--json",
    "--post-data",
    "--post-file",
    "--body-data",
    "--body-file",
];

/// Programs that copy files to where their arguments say.
const FILE_SENDERS: &[&str] = &["scp", "sftp", "rsync", "nc", "ncat", "netcat", "socat"];

/// Whether the command `argv` sends a file or a body (ADR-061): a file-copying
/// program, a data or upload option of `curl` or `wget`, or `gh gist create`
/// and `gh release upload`.
fn carries_body(argv: &[String]) -> bool {
    let program = shell::program_name(argv);
    if FILE_SENDERS.contains(&program) {
        return true;
    }
    let words: Vec<&str> = argv.iter().skip(1).map(String::as_str).collect();
    if program == "gh" {
        return matches!(
            words.as_slice(),
            ["gist", "create", ..] | ["release", "upload", ..]
        );
    }
    words.iter().any(|&word| {
        word.starts_with("--data")
            || BODY_OPTIONS.iter().any(|&option| {
                word == option
                    || word.strip_prefix(option).is_some_and(|rest| {
                        rest.starts_with('=') || (!option.starts_with("--") && !rest.is_empty())
                    })
            })
    })
}

/// Every host the arguments of `argv` name: each argument as the classifier
/// reads it, the value of `--option=value`, and each `:`-separated part of an
/// argument that is no URL (`--connect-to a.com:443:b.com:443`, `--resolve`,
/// a `Host:` header), so a request redirected elsewhere is judged by both. A
/// mail address or login in its option (`curl -u me@example.com:token`) is none.
fn argument_hosts(argv: &[String]) -> Vec<String> {
    let program = shell::program_name(argv);
    let mut hosts = Vec::new();
    for (i, arg) in argv.iter().enumerate().skip(1) {
        if shell::mailbox::names_no_host(argv, i) {
            continue;
        }
        let value = match arg.split_once('=') {
            Some((option, value)) if option.starts_with('-') => value,
            _ => arg.as_str(),
        };
        hosts.extend(host::of_argument(program, value));
        if !value.contains("://") && value.contains(':') {
            hosts.extend(
                value
                    .split(':')
                    .filter_map(|part| host::of_word(part.trim())),
            );
        }
    }
    hosts.sort();
    hosts.dedup();
    hosts
}

/// The ids of every `moat-secret:<id>:placeholder` in `text`, in any letter case.
fn placeholders(text: &str) -> Vec<String> {
    const START: &str = "moat-secret:";
    const END: &str = ":placeholder";
    let lower = text.to_ascii_lowercase();
    let mut ids = Vec::new();
    let mut rest = lower.as_str();
    while let Some(at) = rest.find(START) {
        rest = &rest[at + START.len()..];
        let id_len = rest
            .find(|c: char| !(c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'))
            .unwrap_or(rest.len());
        if id_len > 0 && rest[id_len..].starts_with(END) {
            ids.push(rest[..id_len].to_owned());
        }
    }
    ids
}

#[cfg(test)]
mod tests {
    use super::{argument_hosts, atoms, placeholders};
    use crate::action::{Action, AtomicAction};
    use crate::secret::{Secret, Source};

    fn argv(words: &[&str]) -> Vec<String> {
        words.iter().map(|w| (*w).to_owned()).collect()
    }

    #[test]
    fn a_placeholder_may_go_to_its_secrets_host_only() {
        let secrets = [Secret {
            id: "gh".into(),
            host: "api.github.com".into(),
            header: "Authorization".into(),
            source: Source::Env("GH_TOKEN".into()),
            plain_http: false,
            port: None,
            tls: None,
            allow: Vec::new(),
            helper: None,
        }];
        let fetch = |url: &str| atoms(&Action::Fetch { url: url.into() }, &[], &secrets);
        assert_eq!(
            fetch("https://api.github.com/?t=moat-secret:gh:placeholder"),
            Vec::<AtomicAction>::new()
        );
        assert_eq!(
            fetch("https://uploads.github.com/?t=moat-secret:gh:placeholder"),
            [AtomicAction::Shell {
                argv: argv(&["@placeholder-egress", "gh", "uploads.github.com"])
            }]
        );
        assert_eq!(
            fetch("https://api.github.com/?t=moat-secret:other:placeholder"),
            [AtomicAction::Shell {
                argv: argv(&["@placeholder-egress", "other", "api.github.com"])
            }]
        );
    }

    #[test]
    fn redirections_and_option_values_are_hosts_too() {
        let hosts = argument_hosts(&argv(&[
            "curl",
            "--connect-to",
            "api.github.com:443:evil.com:443",
            "--url=https://example.com/x",
            "-H",
            "Accept: application/vnd.github+json",
            "https://api.github.com/user",
        ]));
        assert_eq!(hosts, ["api.github.com", "evil.com", "example.com"]);
    }

    #[test]
    fn a_login_or_mail_address_in_its_option_is_no_host() {
        let hosts = argument_hosts(&argv(&[
            "curl",
            "-u",
            "me@users.noreply.github.com:token",
            "-d",
            "email=me@example.org",
            "https://api.github.com/user",
        ]));
        assert_eq!(hosts, ["api.github.com"]);
    }

    #[test]
    fn placeholders_are_found_in_any_case_and_only_whole() {
        assert_eq!(
            placeholders("a=moat-secret:gh-api:placeholder b=MOAT-SECRET:x:PLACEHOLDER"),
            ["gh-api", "x"]
        );
        assert_eq!(
            placeholders("moat-secret::placeholder moat-secret:gh"),
            Vec::<String>::new()
        );
    }
}