openmoat 0.7.0

Policy checks for AI coding agents: decides allow, defer, ask or deny for every tool call from Claude Code, Codex and Cursor, configures Claude Code's and Codex's own OS sandboxes from the same policy, and keeps a local audit log.
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! Lightweight tier on macOS: a Seatbelt (SBPL) profile around the whole
//! agent, generated from the IR of one session (ADR-018).
//!
//! What the generator relies on, verified with `sandbox-exec` on macOS 26:
//! - the last matching rule wins, so the policy's deny rules come last and no
//!   allow above them can re-open what they name (ADR-002);
//! - a read deny of `file-read-data` (contents) and `file-read-xattr` leaves
//!   `stat` working, so `git status` does not fail on `.env`;
//! - `require-all`/`require-not` express a rule's `!` exceptions exactly;
//! - paths are compared resolved (`/tmp` is `/private/tmp`) and in their
//!   on-disk spelling, even when a program names them in another case;
//! - a program cannot start from a file it cannot read, and the dynamic loader
//!   needs to read `/` itself;
//! - a network address can only be `*` or `localhost`, so egress goes to the
//!   loopback port of OpenMoat's proxy, which decides each host by the policy.

use std::fmt::Write as _;

use openmoat_core::Kind;
use openmoat_core::ir::{Access, Effect, Enforcement, Rule};

use super::patterns::{RUNS_LATER, literal_tree, runs_later_exclusion, split};
use super::{Grants, Report};

/// Paths every process reads: `/` (the dynamic loader), the terminal and
/// random devices, and `/private/var/select` (where `/bin/sh` finds its shell).
const PLATFORM_READ: [&str; 9] = [
    "/",
    "/dev/null",
    "/dev/zero",
    "/dev/random",
    "/dev/urandom",
    "/dev/tty",
    "/dev/ttys[0-9]*",
    "/dev/fd/**",
    "/private/var/select/**",
];

/// Devices every process writes.
const PLATFORM_WRITE: [&str; 6] = [
    "/dev/null",
    "/dev/zero",
    "/dev/tty",
    "/dev/dtracehelper",
    "/dev/ttys[0-9]*",
    "/dev/fd/**",
];

/// What every process may do besides files: start programs, signal and
/// inspect its own processes, use terminals and shared memory, and look up
/// users and groups. No other system service: not the keychain
/// (`SecurityServer`), not DNS (the proxy resolves), not `trustd`, which
/// fetches certificate status from the network.
const PROCESS: &str = "\
(allow process-exec process-fork)
(allow signal (target same-sandbox))
(allow process-info* (target same-sandbox))
(allow sysctl-read)
(allow pseudo-tty)
(allow file-ioctl)
(allow ipc-posix-shm* ipc-posix-sem)
(allow mach-lookup
  (global-name \"com.apple.system.opendirectoryd.libinfo\")
  (global-name \"com.apple.system.opendirectoryd.membership\"))
";

/// The keychain's services, denied whatever the policy says: the agent and
/// every script it starts share this profile, so a token the agent could read
/// from the keychain, a project script could send away.
const KEYCHAIN: &str = "\
; never the keychain: the agent and its scripts share this profile
(deny mach-lookup
  (global-name \"com.apple.SecurityServer\")
  (global-name \"com.apple.securityd\"))
";

/// `TIOCSTI`, denied whatever the policy says: it pushes characters into the
/// input of the terminal the agent shares with the user, whose shell reads and
/// runs them once the agent exits, outside the sandbox (CVE-2017-5226).
const TERMINAL_INPUT: &str = "\
; never typing into the user's terminal: its shell would run it after the session
(deny file-ioctl (ioctl-command TIOCSTI))
";

/// A generated profile.
#[derive(Debug, Clone)]
pub struct Generated {
    /// The SBPL text `sandbox-exec -p` takes.
    pub profile: String,
    /// Losses and allowances of this backend.
    pub report: Report,
}

/// Generate the profile for `ir`, lowered for one session's project.
pub fn generate(ir: &Enforcement, grants: &Grants) -> Generated {
    let mut p = Generated {
        profile: String::from(
            "(version 1)\n\
             ; generated by OpenMoat from policy.yaml for `moat run` (Lightweight tier, ADR-018)\n\
             (deny default)\n",
        ),
        report: Report::default(),
    };
    p.profile.push_str(PROCESS);
    p.profile
        .push_str("; seatbelt.metadata\n(allow file-read-metadata)\n");
    let metadata = "the existence, size and times of every file stay visible (stat); \
                    contents follow the rules";
    p.report
        .allowance(Kind::FsRead, "seatbelt.metadata", Vec::new(), metadata);
    let platform = |list: &[&str]| list.iter().map(|p| (*p).to_owned()).collect();
    let (read, write) = (Kind::FsRead, Kind::FsWrite);
    let starts = "every process reads these to start";
    p.grant(
        read,
        "seatbelt.platform",
        "file-read*",
        platform(&PLATFORM_READ),
        starts,
    );
    let devices = "the devices every process writes";
    p.grant(
        write,
        "seatbelt.platform",
        "file-write-data",
        platform(&PLATFORM_WRITE),
        devices,
    );
    if let Some(program) = &grants.program {
        let message = "the program `moat run` starts, which must be readable to start";
        p.grant(
            read,
            "seatbelt.program",
            "file-read*",
            vec![program.clone()],
            message,
        );
    }
    p.allows(&ir.fs.read, "allow file-read*");
    for allowance in &ir.allowances {
        rule(
            &mut p.profile,
            &allowance.rule,
            "allow file-read*",
            &allowance.patterns,
        );
        p.report.allowances.push(allowance.clone());
    }
    p.allows(&ir.fs.write, "allow file-write*");
    let both = "file-read* file-write*";
    if let Some(tmpdir) = &grants.tmpdir {
        let message = "commands may read and write the temp directory; the hook asks";
        p.grant(
            write,
            "seatbelt.tmpdir",
            both,
            vec![format!("{tmpdir}/**")],
            message,
        );
    }
    if !grants.writes.is_empty() {
        let trees = grants.writes.iter().map(|w| format!("{w}/**")).collect();
        let message = "`moat run --write`: commands may read and write these; deny rules still win";
        p.grant(write, "seatbelt.write", both, trees, message);
    }
    rules(
        &mut p.profile,
        &ir.fs.read.deny,
        "deny file-read-data file-read-xattr",
    );
    rules(&mut p.profile, &ir.fs.write.deny, "deny file-write*");
    p.profile.push_str(KEYCHAIN);
    p.profile.push_str(TERMINAL_INPUT);
    network(&mut p, &ir.egress.net, grants.proxy_port);
    if ir.fs.case_insensitive {
        let message = "Seatbelt compares paths in their on-disk spelling, so a pattern spelled in \
                       another case than the file on disk does not match it";
        p.report
            .allowance(read, "seatbelt.case", Vec::new(), message);
    }
    p
}

impl Generated {
    /// Allow `operation` on `patterns` and list it as an allowance.
    fn grant(&mut self, kind: Kind, id: &str, operation: &str, patterns: Vec<String>, why: &str) {
        rule(
            &mut self.profile,
            id,
            &format!("allow {operation}"),
            &patterns,
        );
        self.report.allowance(kind, id, patterns, why);
    }

    /// The access's default, then its allow rules.
    fn allows(&mut self, access: &Access, operation: &str) {
        if access.default == Effect::Allow {
            let _ = writeln!(self.profile, "; default\n({operation})");
        }
        rules(&mut self.profile, &access.allow, operation);
        let runs_later = access
            .allow
            .iter()
            .any(|r| split(&r.patterns).1.iter().any(|p| runs_later_exclusion(p)));
        if runs_later {
            self.report.allowance(
                Kind::FsWrite,
                "seatbelt.runs-later",
                RUNS_LATER.iter().map(|f| (*f).to_owned()).collect(),
                "commands may write CI configuration, commit-hook managers' files and editor \
                 tasks (an install runs `husky`); the hook asks before the agent writes one \
                 (`runs-later`)",
            );
        }
    }
}

/// One `(<operation> โ€ฆ)` per IR rule, named in a comment.
fn rules(out: &mut String, rules: &[Rule], operation: &str) {
    let verb = operation.split(' ').next().unwrap_or_default();
    for r in rules {
        let comment = format!("{verb} {} ({})", r.id, r.list);
        rule(out, &comment, operation, &with_real_paths(&r.patterns));
    }
}

/// `patterns` and, for each under a symlinked directory, the same pattern where
/// the link points: Seatbelt sees the path the kernel opens (`/tmp/x` is
/// `/private/tmp/x` on macOS). Only for the policy's rules; the platform's own
/// paths are listed in every spelling already, and the profile must not depend
/// on links elsewhere on the machine that generates it.
fn with_real_paths(patterns: &[String]) -> Vec<String> {
    let mut out = patterns.to_vec();
    for real in patterns.iter().filter_map(|p| through_links(p)) {
        if !out.contains(&real) {
            out.push(real);
        }
    }
    out
}

/// `(<operation> โ€ฆ)` matching what `patterns` match: at least one positive
/// pattern and none of the `!` exceptions.
fn rule(out: &mut String, comment: &str, operation: &str, patterns: &[String]) {
    // `~/{.ssh/**,.aws/**}`: each alternative on its own, so `/**` inside braces
    // is recursive here as it is in the engine
    let patterns: Vec<String> = patterns.iter().flat_map(|p| alternatives(p)).collect();
    let patterns = &patterns[..];
    let (mut positive, mut excluded) = split(patterns);
    // files run later are the hook's to ask about: a deny here would fail installs
    excluded.retain(|p| !runs_later_exclusion(p));
    // `dir/**` becomes `(subpath dir)`, which covers `dir` itself.
    positive.retain(|p| !patterns.contains(&format!("{p}/**")));
    if positive.is_empty() {
        return;
    }
    let lines = |list: &[&str], indent: &str| {
        let filters: Vec<String> = list.iter().map(|p| filter(p)).collect();
        format!("\n{indent}{}", filters.join(&format!("\n{indent}")))
    };
    let _ = write!(out, "; {comment}\n({operation}");
    if excluded.is_empty() {
        out.push_str(&lines(&positive, "  "));
    } else {
        let _ = write!(
            out,
            "\n  (require-all\n    (require-any{})\n    (require-not (require-any{})))",
            lines(&positive, "      "),
            lines(&excluded, "      ")
        );
    }
    out.push_str(")\n");
}

/// Egress goes only to the proxy's loopback port: Seatbelt cannot name a host.
fn network(p: &mut Generated, net: &Access, port: Option<u16>) {
    match port {
        Some(port) => {
            let _ = writeln!(
                p.profile,
                "; network: only OpenMoat's egress proxy, which decides each host by the policy\n\
                 (allow network-outbound (remote ip \"localhost:{port}\"))"
            );
        }
        None => p.profile.push_str("; network: none\n"),
    }
    p.report.proxy_only(net);
}

/// Most patterns one brace group may expand to; past it the pattern is
/// translated as written.
const MAX_ALTERNATIVES: usize = 64;

/// `pattern` with its brace groups expanded (`src/{a,b}.rs` โ†’ `src/a.rs`,
/// `src/b.rs`), as the
/// engine's glob reads them; nested groups too. A pattern without braces, with
/// an unclosed group, or with more than [`MAX_ALTERNATIVES`] results is
/// returned as it is.
fn alternatives(pattern: &str) -> Vec<String> {
    let mut out = Vec::new();
    if expand(pattern, &mut out) {
        out
    } else {
        vec![pattern.to_owned()]
    }
}

/// Append every expansion of `pattern` to `out`; `false` when it cannot be
/// expanded within the bound.
fn expand(pattern: &str, out: &mut Vec<String>) -> bool {
    let Some((open, close, options)) = first_group(pattern) else {
        out.push(pattern.to_owned());
        return true;
    };
    let (head, tail) = (&pattern[..open], &pattern[close + 1..]);
    options.iter().all(|option| {
        expand(&format!("{head}{option}{tail}"), out) && out.len() <= MAX_ALTERNATIVES
    })
}

/// The first top-level brace group: its byte range and its comma-separated
/// options (nested groups left in them). `None` without a closed group.
fn first_group(pattern: &str) -> Option<(usize, usize, Vec<&str>)> {
    let (mut depth, mut open, mut start) = (0usize, None, 0);
    let mut options = Vec::new();
    let mut chars = pattern.char_indices();
    while let Some((i, c)) = chars.next() {
        match c {
            '\\' => {
                chars.next();
            }
            '{' => {
                if depth == 0 {
                    open = Some(i);
                    start = i + 1;
                }
                depth += 1;
            }
            ',' if depth == 1 => {
                options.push(&pattern[start..i]);
                start = i + 1;
            }
            '}' if depth > 0 => {
                depth -= 1;
                if depth == 0 {
                    options.push(&pattern[start..i]);
                    return Some((open?, i, options));
                }
            }
            _ => {}
        }
    }
    None
}

/// `pattern` (an absolute glob, `!` for an exclusion) with its literal
/// directory prefix written as the filesystem resolves it, when that differs:
/// `/tmp/x/**` โ†’ `/private/tmp/x/**` on macOS. The deepest existing directory
/// of the prefix is resolved; `None` when nothing changes.
fn through_links(pattern: &str) -> Option<String> {
    // Seatbelt runs on macOS only; elsewhere the profile is shown, not enforced,
    // and resolving there would only write that machine's links into it.
    if !cfg!(target_os = "macos") {
        return None;
    }
    let (bang, body) = match pattern.strip_prefix('!') {
        Some(rest) => ("!", rest),
        None => ("", pattern),
    };
    if !body.starts_with('/') {
        return None;
    }
    let literal_end = body.find(['*', '?', '[', '{', '\\']).unwrap_or(body.len());
    let literal = &body[..literal_end];
    let dir_end = literal.rfind('/')?;
    let mut dir = std::path::Path::new(&literal[..dir_end.max(1)]);
    loop {
        if let Ok(real) = std::fs::canonicalize(dir) {
            let (dir, real) = (dir.to_str()?, real.to_str()?.to_owned());
            if real == dir {
                return None;
            }
            return Some(format!("{bang}{real}{}", &body[dir.len()..]));
        }
        dir = dir.parent()?;
    }
}

/// One IR glob as a Seatbelt path filter.
fn filter(pattern: &str) -> String {
    match literal_tree(pattern) {
        Some(dir) if pattern.ends_with("/**") => format!("(subpath {})", quote(dir)),
        Some(path) => format!("(literal {})", quote(path)),
        None => format!("(regex {})", quote(&regex(pattern))),
    }
}

/// An SBPL string literal.
fn quote(text: &str) -> String {
    format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
}

/// A path glob as an anchored regular expression with the engine's semantics
/// (`docs/POLICY.md` ยง3): `*` and `?` stop at `/`, `**` as a whole component
/// crosses it, and `dir/**` also matches `dir`.
fn regex(glob: &str) -> String {
    let mut re = String::from("^");
    let mut depth = 0usize;
    let mut i = 0;
    while let Some(c) = glob[i..].chars().next() {
        let rest = &glob[i..];
        let (piece, used) = if rest == "/**" {
            ("(/.*)?".to_owned(), 3)
        } else if rest.starts_with("/**/") {
            ("/(.*/)?".to_owned(), 4)
        } else if i == 0 && rest == "**" {
            (".*".to_owned(), 2)
        } else if i == 0 && rest.starts_with("**/") {
            ("(.*/)?".to_owned(), 3)
        } else {
            match c {
                '*' => ("[^/]*".to_owned(), 1),
                '?' => ("[^/]".to_owned(), 1),
                '{' => {
                    depth += 1;
                    ("(".to_owned(), 1)
                }
                '}' if depth > 0 => {
                    depth -= 1;
                    (")".to_owned(), 1)
                }
                ',' if depth > 0 => ("|".to_owned(), 1),
                '[' => class(rest).unwrap_or_else(|| (escape('['), 1)),
                '\\' => match rest[1..].chars().next() {
                    Some(next) => (escape(next), 1 + next.len_utf8()),
                    None => (escape('\\'), 1),
                },
                other => (escape(other), other.len_utf8()),
            }
        };
        re.push_str(&piece);
        i += used;
    }
    re.push('$');
    re
}

/// A glob character class at the start of `rest` (`[ab]`, `[!ab]`) and its
/// length, or `None` when it is not closed.
fn class(rest: &str) -> Option<(String, usize)> {
    let body = &rest[1..];
    let (negated, body) = match body.strip_prefix(['!', '^']) {
        Some(b) => (true, b),
        None => (false, body),
    };
    // A `]` right after the opening bracket is a member, not the end.
    let end = body.char_indices().skip(1).find(|(_, c)| *c == ']')?.0;
    let members = body[..end].replace('\\', "\\\\");
    let negation = if negated { "^/" } else { "" };
    Some((
        format!("[{negation}{members}]"),
        rest.len() - body.len() + end + 1,
    ))
}

fn escape(c: char) -> String {
    if ".^$|()+[]{}\\*?".contains(c) {
        format!("\\{c}")
    } else {
        c.to_string()
    }
}

#[cfg(test)]
mod tests;