openmoat 0.28.0

Policy checks for AI coding agents: decides allow, defer, review or deny for each tool call the hook of Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot CLI and seven more agents reports, configures Claude Code's, Codex's and Cursor'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
//! `moat run` on Linux without `--isolate`: a network namespace of the
//! agent's own, where bubblewrap can make one.
//!
//! Landlock restricts TCP connections by port only (`NetPort`), and a seccomp
//! filter cannot read the address `connect()` is given, which it gets as a
//! pointer. With those two alone a command could reach any host on the
//! proxy's port and go around the proxy. So the agent starts in new user and
//! network namespaces whose only interface is loopback. Nothing else changes:
//! the whole root is bound in as it is, there is no PID namespace, and the same
//! Landlock rules and seccomp filter apply inside. `moat isolated` serves the
//! proxy's port on that loopback and relays each connection over a Unix socket
//! to the proxy outside, as under `--isolate`.
//!
//! Where bubblewrap is missing or cannot create the namespaces, `moat run`
//! starts with Landlock and seccomp alone and says so on every start, and
//! `moat doctor` warns; with `--netns=require` it refuses to start instead.

use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{Context as _, Result};

use super::isolate::{Session, relay_to_proxy, system_bwrap};
use super::{Confined, Rules};
use crate::context::path_string;
use crate::sandbox::Report;
use crate::sandbox::bwrap::shared::Shared;
use crate::sandbox::bwrap::{self, Mount, Placeholder};
use crate::sandbox::landlock::TCP_PORT_ALLOWANCE;

/// The namespaces: a user namespace, needed to create the network one
/// unprivileged, and the network namespace, where bubblewrap brings up
/// loopback alone.
const UNSHARE: [&str; 3] = ["--unshare-user", "--unshare-net", "--die-with-parent"];

/// The whole root, devices included, at the same paths.
const ROOT: [&str; 3] = ["--dev-bind", "/", "/"];

/// bubblewrap's monitoring process stays in the terminal's foreground group
/// and dies of Ctrl-C's `SIGINT`, which would end the agent through
/// `--die-with-parent`. The shell ignores `SIGINT` for it (ignored signals stay
/// ignored across `exec`); `moat isolated` handles `SIGINT` itself, so the
/// agent it starts gets the default back and decides what Ctrl-C means.
const IGNORE_INTERRUPT: &str = "trap '' INT; exec \"$0\" \"$@\"";

/// How the agent's network is confined.
#[derive(Debug, PartialEq, Eq)]
pub enum Network {
    /// A network namespace with loopback alone, made by this bubblewrap.
    Namespace(PathBuf),
    /// The machine's network, with connections limited to the proxy's port
    /// on every host; why there is no namespace.
    PortOnly(String),
}

/// This machine's choice.
pub fn network() -> Network {
    if without_namespace_for_tests() {
        return Network::PortOnly(format!("{NO_NETNS_ENV} is set (a test build)"));
    }
    decide(system_bwrap(), refused)
}

/// Debug builds start `moat run` without a network namespace where this
/// variable is set, so the end-to-end tests can assert on a machine with
/// bubblewrap what a machine without it does (the project granted entry by
/// entry, ADR-090). Release builds do not read it.
#[cfg(debug_assertions)]
const NO_NETNS_ENV: &str = "MOAT_TEST_NO_NETNS";
#[cfg(not(debug_assertions))]
const NO_NETNS_ENV: &str = "";

/// Whether [`NO_NETNS_ENV`] is set in a debug build.
fn without_namespace_for_tests() -> bool {
    cfg!(debug_assertions) && std::env::var_os(NO_NETNS_ENV).is_some()
}

/// A namespace where `bwrap` exists and `refused` finds no reason it cannot
/// make one.
fn decide(bwrap: Option<PathBuf>, refused: impl FnOnce(&Path) -> Option<String>) -> Network {
    let Some(bwrap) = bwrap else {
        return Network::PortOnly(
            "bubblewrap is not installed (`bwrap` in /usr/bin, /bin or /usr/local/bin)".to_owned(),
        );
    };
    match refused(&bwrap) {
        None => Network::Namespace(bwrap),
        Some(why) => Network::PortOnly(format!(
            "bubblewrap cannot create a network namespace here ({why}; unprivileged user \
             namespaces must be allowed, and on Ubuntu 24.04 AppArmor restricts them: \
             kernel.apparmor_restrict_unprivileged_userns)"
        )),
    }
}

/// Why `bwrap` cannot create [`UNSHARE`]'s namespaces, if it cannot.
fn refused(bwrap: &Path) -> Option<String> {
    let out = Command::new(bwrap)
        .args(UNSHARE)
        .args(ROOT)
        .arg("--")
        .arg(bwrap)
        .arg("--version")
        .output();
    match out {
        Ok(out) if out.status.success() => None,
        Ok(out) => Some(String::from_utf8_lossy(&out.stderr).trim().to_owned()),
        Err(error) => Some(format!("starting {}: {error}", bwrap.display())),
    }
}

/// What `moat run` prints on every start without a namespace (`why`), naming
/// the `masks` only a namespace could have applied.
pub fn port_only_notice(port: u16, why: &str, masks: &[Mount]) -> String {
    let mut notice = format!(
        "moat run: the network is restricted by port only: {why}, so a command in the sandbox \
         can reach any host on port {port} and go around the proxy's checks and audit, and can \
         create an agent's hook settings the project lacks, which `openmoat run` names when the \
         agent exits. With \
         bubblewrap (`apt install bubblewrap`) `openmoat run` gives the agent a network of its own \
         whose only exit is the proxy; `openmoat run --isolate` needs it too and also hides the \
         rest of the machine"
    );
    let open: Vec<&str> = masks
        .iter()
        .filter_map(|m| match m {
            Mount::ReadOnly(p) | Mount::Hide { path: p, .. } => Some(p.as_str()),
            Mount::ReadWrite(_) | Mount::Tmpfs(_) => None,
        })
        .collect();
    if !open.is_empty() {
        notice = format!(
            "{notice}.\nmoat run: without it, these paths the policy denies stay open to \
             commands, because a read root or `--write` path holds them: {}",
            open.join(", ")
        );
    }
    notice
}

/// One line for each of `watched`, the hook settings missing when the agent
/// started, that `exists` finds now: a command may have written it to turn
/// the next session's hook off.
pub fn created_during_run(watched: &[String], exists: impl Fn(&str) -> bool) -> Vec<String> {
    watched
        .iter()
        .filter(|path| exists(path))
        .map(|path| {
            format!(
                "moat run: {path} did not exist when the agent started and does now; an agent \
                 reads it as its hook settings in its next session, where it can turn OpenMoat's \
                 hook off. Look at it before you start an agent here, and remove it if you did \
                 not write it"
            )
        })
        .collect()
}

/// What `moat doctor` warns where there is no namespace, if there is none.
pub fn doctor_warning() -> Option<String> {
    match network() {
        Network::Namespace(_) => None,
        Network::PortOnly(why) => Some(format!(
            "openmoat run     network restricted by port only: {why}; commands could reach any \
             host on the proxy's port. Install bubblewrap for a network namespace (also needed \
             by `openmoat run --isolate`)"
        )),
    }
}

/// Why the agent would have no network of its own here, and how to get one;
/// `None` when it would.
pub fn missing() -> Option<String> {
    match network() {
        Network::Namespace(_) => None,
        Network::PortOnly(why) => Some(format!(
            "the agent cannot get a network of its own: {why}; install bubblewrap \
             (`apt install bubblewrap`)"
        )),
    }
}

/// `program` under `bwrap` in its own network namespace, `moat isolated`
/// applying `rules` inside, in `cwd`, with the proxy on `port` relayed in,
/// `masks` over the denied paths inside the grants and `placeholders` created
/// in the project for the session, recorded in the project's lock `shared`.
#[expect(
    clippy::too_many_arguments,
    reason = "one call site, which hands over what `confine` generated"
)]
pub fn namespaced(
    bwrap: &Path,
    rules: &Rules,
    masks: &[Mount],
    (placeholders, shared): (&[Placeholder], Shared),
    mut report: Report,
    program: &Path,
    cwd: &str,
    port: u16,
) -> Result<Confined> {
    report.allowances.retain(|a| a.rule != TCP_PORT_ALLOWANCE);
    let session = Session::create(placeholders, shared)?;
    relay_to_proxy(&session.socket, port)?;
    if let Some(listen) = rules.bind_port {
        super::serve::forward_in(&super::serve::socket_beside(&session.socket), listen)?;
    }
    let moat = std::env::current_exe()
        .and_then(std::fs::canonicalize)
        .context("locating the moat binary")?;
    let (blank_file, blank_dir) = session.blanks();
    let masks = bwrap::args(masks, &blank_file, &blank_dir);
    let mut command = Command::new("/bin/sh");
    command.args(arguments(
        bwrap,
        &moat,
        (&session.socket, &session.report),
        port,
        &serde_json::to_string(rules)?,
        cwd,
        &masks,
    ));
    command.arg(program);
    Ok(Confined {
        command,
        report,
        restrict: None,
        _session: Some(session),
        warning: None,
        project: None,
        top_open: false,
        watch: Vec::new(),
    })
}

/// `/bin/sh`'s arguments up to the agent; `masks` are bubblewrap's mount
/// arguments over the whole root; `socket` reaches the proxy and `report`
/// takes the launch report (`launch.rs`).
fn arguments(
    bwrap: &Path,
    moat: &Path,
    (socket, report): (&Path, &Path),
    port: u16,
    rules: &str,
    cwd: &str,
    masks: &[String],
) -> Vec<String> {
    let mut args = vec![
        "-c".to_owned(),
        IGNORE_INTERRUPT.to_owned(),
        path_string(bwrap),
    ];
    args.extend(UNSHARE.map(str::to_owned));
    args.extend(ROOT.map(str::to_owned));
    args.extend(masks.iter().cloned());
    args.extend(["--chdir", cwd, "--"].map(str::to_owned));
    args.extend([
        path_string(moat),
        "isolated".to_owned(),
        "--socket".to_owned(),
    ]);
    args.push(path_string(socket));
    args.extend(["--port".to_owned(), port.to_string(), "--rules".to_owned()]);
    args.extend([rules.to_owned(), "--report".to_owned(), path_string(report)]);
    args.push("--".to_owned());
    args
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_working_bubblewrap_gives_a_namespace() {
        let bwrap = PathBuf::from("/usr/bin/bwrap");
        let chosen = decide(Some(bwrap.clone()), |_| None);
        assert_eq!(chosen, Network::Namespace(bwrap));
    }

    #[test]
    fn without_bubblewrap_the_network_is_port_only_and_says_why() {
        let Network::PortOnly(why) = decide(None, |_| unreachable!("nothing to probe")) else {
            panic!("no bubblewrap, no namespace");
        };
        assert!(why.contains("bubblewrap is not installed"), "{why}");
        let notice = port_only_notice(41_000, &why, &[]);
        for expected in [
            "restricted by port only",
            "any host on port 41000",
            "apt install bubblewrap",
            "openmoat run --isolate",
        ] {
            assert!(notice.contains(expected), "{expected}: {notice}");
        }
        assert!(!notice.contains("stay open"), "{notice}");
        let masks = [
            Mount::ReadWrite("/home/me/.claude".into()),
            Mount::ReadOnly("/home/me/.claude/settings.json".into()),
        ];
        let notice = port_only_notice(41_000, &why, &masks);
        assert!(
            notice.contains("stay open to commands")
                && notice.ends_with(": /home/me/.claude/settings.json"),
            "{notice}"
        );
    }

    #[test]
    fn hook_settings_created_during_a_port_only_run_are_named() {
        let watched = [
            "/p/.gemini/settings.json".to_owned(),
            "/p/.claude/settings.local.json".to_owned(),
        ];
        let lines = created_during_run(&watched, |p| p == watched[0]);
        assert_eq!(lines.len(), 1, "{lines:?}");
        assert!(lines[0].starts_with("moat run: /p/.gemini/settings.json did not exist"));
        assert!(
            lines[0].contains("turn OpenMoat's hook off"),
            "{}",
            lines[0]
        );
        assert_eq!(created_during_run(&watched, |_| false), [] as [String; 0]);
        let notice = port_only_notice(41_000, "no bwrap", &[]);
        assert!(
            notice.contains("hook settings the project lacks"),
            "{notice}"
        );
    }

    #[test]
    fn a_bubblewrap_that_cannot_make_namespaces_is_port_only_with_its_reason() {
        let bwrap = PathBuf::from("/usr/bin/bwrap");
        let chosen = decide(Some(bwrap), |_| {
            Some("setting up uid map: Permission denied".to_owned())
        });
        let Network::PortOnly(why) = chosen else {
            panic!("a refused namespace is not used");
        };
        assert!(why.contains("uid map: Permission denied"), "{why}");
        assert!(
            why.contains("apparmor_restrict_unprivileged_userns"),
            "{why}"
        );
    }

    /// The namespace holds the whole root and the agent starts through
    /// `moat isolated`, which serves the proxy's port inside.
    #[test]
    fn bubblewrap_gets_a_network_namespace_over_the_whole_root() {
        let args = arguments(
            Path::new("/usr/bin/bwrap"),
            Path::new("/opt/moat"),
            (
                Path::new("/tmp/moat-run-1/proxy.sock"),
                Path::new("/tmp/moat-run-1/check.sock"),
            ),
            41_000,
            "{}",
            "/work/project",
            &[
                "--ro-bind-try".to_owned(),
                "/home/me/.claude/settings.json".to_owned(),
                "/home/me/.claude/settings.json".to_owned(),
            ],
        );
        let expected = [
            "-c",
            IGNORE_INTERRUPT,
            "/usr/bin/bwrap",
            "--unshare-user",
            "--unshare-net",
            "--die-with-parent",
            "--dev-bind",
            "/",
            "/",
            // the masks over the whole root, after it
            "--ro-bind-try",
            "/home/me/.claude/settings.json",
            "/home/me/.claude/settings.json",
            "--chdir",
            "/work/project",
            "--",
            "/opt/moat",
            "isolated",
            "--socket",
            "/tmp/moat-run-1/proxy.sock",
            "--port",
            "41000",
            "--rules",
            "{}",
            "--report",
            "/tmp/moat-run-1/check.sock",
            "--",
        ];
        assert_eq!(args, expected);
        assert!(
            !args
                .iter()
                .any(|a| a == "--unshare-all" || a == "--unshare-pid")
        );
    }

    /// The shell runs bubblewrap with its arguments as given and `SIGINT`
    /// ignored.
    #[test]
    fn the_shell_execs_bubblewrap_with_sigint_ignored() {
        let out = Command::new("/bin/sh")
            .args(["-c", IGNORE_INTERRUPT, "/bin/sh", "-c"])
            .arg("grep '^SigIgn' /proc/self/status; echo \"$0|$1\"")
            .args(["first arg", "second"])
            .output()
            .expect("sh runs");
        let shown = String::from_utf8_lossy(&out.stdout);
        assert!(shown.contains("first arg|second"), "{shown}");
        let ignored = shown
            .lines()
            .find_map(|l| l.strip_prefix("SigIgn:"))
            .and_then(|mask| u64::from_str_radix(mask.trim(), 16).ok())
            .expect("the mask");
        assert_ne!(ignored & (1 << (libc::SIGINT - 1)), 0, "{shown}");
    }
}