openmoat 0.25.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
//! `moat run --isolate` on Linux: the Isolated tier (ADR-018) with
//! bubblewrap, rootless and without a daemon or an image.
//!
//! bubblewrap starts the agent in new user, mount, PID, IPC, UTS, cgroup and
//! network namespaces. Its root holds only the mounts `crate::sandbox::bwrap`
//! generates: the project with its denied paths covered, the read roots,
//! `--write` paths and an empty temp directory. The network namespace has only
//! loopback. `moat` itself runs first inside it (`moat isolated`): it serves
//! the proxy's port on that loopback and relays each connection over a Unix
//! socket bound in from outside, where this process relays it on to the proxy.
//! Then it applies the same Landlock rules and seccomp filter as the
//! Lightweight tier to a thread of its own, which starts the agent.

use std::fs::{DirBuilder, File, Permissions};
use std::io;
use std::net::{Ipv4Addr, Shutdown, TcpListener, TcpStream};
use std::os::unix::fs::{DirBuilderExt as _, PermissionsExt as _};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, OnceLock};

use anyhow::{Context as _, Result, bail};
use openmoat_core::{EvalContext, Policy};

use super::super::temp::socket_parent;
use super::launch::{Reports, reporter};
use super::{Confined, Rules, refuse_exposed, restricted};
use crate::cli::IsolatedArgs;
use crate::context::path_string;
use crate::exit::Code;
use crate::sandbox::bwrap::Placeholder;
use crate::sandbox::bwrap::shared::Shared;
use crate::sandbox::{Grants, Report, bwrap, bwrap_mounts};

/// Where bubblewrap is taken from. Not `PATH`: `bwrap` starts unconfined and
/// builds the sandbox, so a `bwrap` a project ships (a relative `PATH` entry,
/// `node_modules/.bin`) must never be the one that runs.
const BWRAP_DIRS: [&str; 3] = ["/usr/bin", "/bin", "/usr/local/bin"];

/// The system's bubblewrap, symlinks resolved.
pub(super) fn system_bwrap() -> Option<PathBuf> {
    let dirs: Vec<PathBuf> = BWRAP_DIRS.iter().map(PathBuf::from).collect();
    crate::environment::find_in(&dirs, &[], "bwrap").and_then(|p| std::fs::canonicalize(p).ok())
}

/// Namespaces bubblewrap creates; a user namespace is required, not tried.
const UNSHARE: [&str; 3] = ["--unshare-all", "--unshare-user", "--die-with-parent"];

/// Keeps the agent from creating user namespaces of its own inside the
/// sandbox. bubblewrap 0.8 and later know it; an older one refuses to start
/// with it, so it is passed only when [`usable`] found it accepted.
const DISABLE_USERNS: &str = "--disable-userns";

/// [`UNSHARE`], with [`DISABLE_USERNS`] when this bubblewrap knows it.
fn unshare(disable_userns: bool) -> Vec<&'static str> {
    let mut args = UNSHARE.to_vec();
    if disable_userns {
        args.push(DISABLE_USERNS);
    }
    args
}

/// The system's bubblewrap and whether it takes [`DISABLE_USERNS`], or why it
/// cannot make the Isolated tier here. Probed once per process: `openmoat run`
/// asks first to choose its tier (ADR-080), then to build it.
pub(super) fn probe() -> std::result::Result<(PathBuf, bool), String> {
    static PROBED: OnceLock<std::result::Result<(PathBuf, bool), String>> = OnceLock::new();
    PROBED
        .get_or_init(|| {
            let bwrap = system_bwrap().ok_or_else(|| {
                "bubblewrap is not installed (`bwrap` in /usr/bin, /bin or /usr/local/bin; \
                 `apt install bubblewrap`)"
                    .to_owned()
            })?;
            let disable_userns = usable(&bwrap).map_err(|error| format!("{error:#}"))?;
            Ok((bwrap, disable_userns))
        })
        .clone()
}

pub fn isolate(
    policy: &Policy,
    ctx: &EvalContext,
    grants: Grants,
    program: &Path,
    state: &Path,
) -> Result<Confined> {
    let (bwrap, disable_userns) = match probe() {
        Ok(found) => found,
        Err(why) => bail!(
            "`openmoat run --isolate` needs bubblewrap, and {why}; refusing rather than \
             starting the agent in a weaker tier"
        ),
    };
    let port = grants.proxy_port.context("no proxy port")?;
    // The run's CA files are in the temp directory, which starts empty here.
    let trust = grants.trust.clone();
    // The tool-shell wrapper, in a directory of its own outside the empty temp
    // directory (ADR-075).
    let wrapper = grants.tool_shell.as_ref().map(|w| w.dir.clone());
    // Held before the project is looked at, so a session ending meanwhile
    // does not remove a placeholder this one finds and covers.
    let shared = Shared::take(state, project_of(ctx))?;
    let generated = bwrap_mounts(policy, ctx, grants)?;
    // The mounts hide the state directory only under the empty temp directory.
    refuse_exposed(state, &generated.rules, true)?;
    let session = Session::create(&generated.placeholders, shared)?;
    relay_to_proxy(&session.socket, port)?;
    let moat = std::env::current_exe().and_then(std::fs::canonicalize)?;
    let (moat, dir) = (path_string(&moat), path_string(&session.dir));
    let mut command = Command::new(&bwrap);
    command
        .args(unshare(disable_userns))
        .args(["--dev", "/dev", "--proc", "/proc"])
        .args(bwrap::args(
            &generated.mounts,
            &path_string(&session.dir.join("file")),
            &path_string(&session.dir.join("dir")),
        ))
        // Read-only: connecting to the socket needs no write access to the
        // mount, and the placeholders stay as they are.
        .args(["--ro-bind", &moat, &moat, "--ro-bind", &dir, &dir])
        .args(
            trust
                .iter()
                .chain(wrapper.iter())
                .flat_map(|t| ["--ro-bind", t.as_str(), t.as_str()]),
        )
        .args(["--chdir", &ctx.cwd, "--", &moat, "isolated", "--socket"])
        .arg(&session.socket)
        .args(["--port", &port.to_string(), "--rules"])
        .arg(serde_json::to_string(&generated.rules)?)
        .arg("--report")
        .arg(&session.report)
        .arg("--")
        .arg(program);
    Ok(Confined {
        command,
        report: generated.report,
        restrict: None,
        _session: Some(session),
        warning: None,
        project: None,
        top_open: false,
        watch: Vec::new(),
    })
}

/// The project of `ctx`, resolved, which keys its placeholders' lock
/// ([`Shared`]); the working directory where there is no project.
pub(super) fn project_of(ctx: &EvalContext) -> &str {
    ctx.real_project
        .as_deref()
        .or(ctx.project.as_deref())
        .unwrap_or(&ctx.cwd)
}

/// Outside the sandbox: relay each connection to `socket` on to the proxy's
/// `port` on loopback.
pub(super) fn relay_to_proxy(socket: &Path, port: u16) -> Result<()> {
    let listener =
        UnixListener::bind(socket).with_context(|| format!("listening on {}", socket.display()))?;
    std::thread::spawn(move || {
        for unix in listener.incoming().flatten() {
            std::thread::spawn(move || {
                if let Ok(tcp) = TcpStream::connect((Ipv4Addr::LOCALHOST, port)) {
                    splice(&tcp, &unix);
                }
            });
        }
    });
    Ok(())
}

/// Refuse, with bubblewrap's reason, where it cannot create the namespaces:
/// a kernel or distribution that restricts unprivileged user namespaces.
/// Otherwise whether it accepts [`DISABLE_USERNS`]: tried first, and the
/// sandbox is tried without it only when bubblewrap does not know the option
/// ([`unknown_disable_userns`]). Any other failure with it refuses: a
/// bubblewrap that knows the option but cannot apply it must not start an
/// agent that may create user namespaces of its own.
fn usable(bwrap: &Path) -> Result<bool> {
    let probe = |disable_userns: bool| {
        Command::new(bwrap)
            .args(unshare(disable_userns))
            .args(["--ro-bind", "/", "/", "--"])
            .arg(bwrap)
            .arg("--version")
            .output()
            .with_context(|| format!("starting {}", bwrap.display()))
    };
    let with = probe(true)?;
    if with.status.success() {
        return Ok(true);
    }
    let out = if unknown_disable_userns(&String::from_utf8_lossy(&with.stderr)) {
        probe(false)?
    } else {
        with
    };
    if !out.status.success() {
        bail!(
            "bubblewrap cannot create its namespaces here: {} (unprivileged user namespaces \
             must be allowed; on Ubuntu 24.04 AppArmor restricts them: \
             kernel.apparmor_restrict_unprivileged_userns)",
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(false)
}

/// Whether bubblewrap's `stderr` says it does not know [`DISABLE_USERNS`]:
/// bubblewrap before 0.8 answers `bwrap: Unknown option --disable-userns`.
fn unknown_disable_userns(stderr: &str) -> bool {
    stderr.lines().any(|line| {
        line.to_ascii_lowercase().contains("unknown option") && line.contains(DISABLE_USERNS)
    })
}

/// Inside the sandbox: relay the proxy's port to the socket, then start the
/// agent with the Landlock rules and seccomp filter applied.
pub fn inside(args: &IsolatedArgs) -> Result<Code> {
    let rules: Rules = serde_json::from_str(&args.rules).context("reading the Landlock rules")?;
    let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, args.port))
        .context("listening on the proxy's port inside the sandbox")?;
    let socket = args.socket.clone();
    std::thread::spawn(move || {
        for tcp in listener.incoming().flatten() {
            let socket = socket.clone();
            std::thread::spawn(move || {
                if let Ok(unix) = UnixStream::connect(&socket) {
                    splice(&tcp, &unix);
                }
            });
        }
    });
    // Ctrl-C belongs to the agent, as outside.
    signal_hook::flag::register(
        signal_hook::consts::SIGINT,
        Arc::new(AtomicBool::new(false)),
    )
    .context("keeping OpenMoat running on Ctrl-C")?;
    let (program, rest) = args.command.split_first().context("no agent to run")?;
    let mut agent = restricted(&rules, Report::default(), Command::new(program))?;
    agent.command().args(rest);
    // Connected before the agent starts, so the run reads this report first.
    let report = reporter(&args.report)?;
    let status = agent.status(report)?;
    Ok(if status.success() {
        Code::Ok
    } else {
        Code::Failed
    })
}

/// Copy both ways between `tcp` and `unix`; each side's end of data closes
/// the other's sending half.
fn splice(tcp: &TcpStream, unix: &UnixStream) {
    let (Ok(tcp_out), Ok(unix_in)) = (tcp.try_clone(), unix.try_clone()) else {
        return;
    };
    let back = std::thread::spawn(move || {
        let _ = io::copy(&mut &unix_in, &mut &tcp_out);
        let _ = tcp_out.shutdown(Shutdown::Write);
    });
    let _ = io::copy(&mut &*tcp, &mut &*unix);
    let _ = unix.shutdown(Shutdown::Write);
    let _ = back.join();
}

/// The proxy's socket, in the session's directory.
const SOCKET: &str = "proxy.sock";

/// The launch report's socket (ADR-089), no longer than [`SOCKET`].
const REPORT: &str = "check.sock";

/// A private directory for the session (mode `0700`) with the proxy's socket
/// and the placeholders hidden paths are covered with (mode `000`), and the
/// placeholders created in the project. All are removed when it drops, the
/// project's only while still as made.
pub struct Session {
    dir: PathBuf,
    pub(super) socket: PathBuf,
    /// The project's lock, which records the placeholders made here and
    /// removes them when the last session in the project ends ([`Shared`]).
    shared: Option<Shared>,
    /// Where `moat isolated` reports the agent's start.
    pub(super) report: PathBuf,
    reports: Option<Reports>,
}

impl Session {
    pub(super) fn create(placeholders: &[Placeholder], shared: Shared) -> Result<Self> {
        let name = format!("moat-run-{}", std::process::id());
        let dir = socket_parent(&std::env::temp_dir(), &name, SOCKET).join(name);
        DirBuilder::new()
            .mode(0o700)
            .create(&dir)
            .with_context(|| format!("creating {}", dir.display()))?;
        let mut session = Self {
            socket: dir.join(SOCKET),
            report: dir.join(REPORT),
            reports: None,
            dir,
            shared: Some(shared),
        };
        session.reports = Some(Reports::bind(&session.report)?);
        File::create_new(session.dir.join("file"))?
            .set_permissions(Permissions::from_mode(0o000))?;
        std::fs::create_dir(session.dir.join("dir"))?;
        std::fs::set_permissions(session.dir.join("dir"), Permissions::from_mode(0o000))?;
        // Outermost first; each is recorded once made, so a failure part way
        // removes what was made. One that another session in the project made
        // meanwhile is covered all the same, and is that session's to record.
        for placeholder in placeholders {
            let path = &placeholder.path;
            let made = if placeholder.dir {
                std::fs::create_dir(path)
            } else {
                File::create_new(path).and_then(|mut file| {
                    io::Write::write_all(&mut file, placeholder.contents.as_bytes())
                })
            };
            match made {
                Ok(()) => {
                    if let Some(shared) = &mut session.shared {
                        shared.record(placeholder)?;
                    }
                }
                Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
                Err(error) => {
                    return Err(error).with_context(|| format!("creating a placeholder at {path}"));
                }
            }
        }
        Ok(session)
    }

    /// The launch report's socket, bound when the session was made; taken
    /// once, by the start.
    pub(super) fn take_reports(&mut self) -> Option<Reports> {
        self.reports.take()
    }

    /// The empty file and directory no one may open, which hidden paths are
    /// covered with ([`bwrap::args`]).
    pub(super) fn blanks(&self) -> (String, String) {
        (
            path_string(&self.dir.join("file")),
            path_string(&self.dir.join("dir")),
        )
    }
}

impl Drop for Session {
    fn drop(&mut self) {
        // Innermost first, each only while it is still as it was made, and
        // only by the last session in the project ([`Shared::finish`]).
        if let Some(shared) = self.shared.take() {
            shared.finish(remove_placeholder);
        }
        let _ = std::fs::remove_file(&self.socket);
        let _ = std::fs::remove_file(&self.report);
        let _ = std::fs::remove_file(self.dir.join("file"));
        let _ = std::fs::remove_dir(self.dir.join("dir"));
        let _ = std::fs::remove_dir(&self.dir);
    }
}

/// Remove `placeholder` if it is still as made: a folder while empty, a file
/// while it holds what was written; anything changed or replaced stays.
fn remove_placeholder(placeholder: &Placeholder) {
    let path = Path::new(&placeholder.path);
    let Ok(meta) = std::fs::symlink_metadata(path) else {
        return;
    };
    if placeholder.dir {
        if meta.is_dir() {
            // fails, and keeps it, unless it is empty
            let _ = std::fs::remove_dir(path);
        }
    } else if meta.is_file()
        && std::fs::read(path).is_ok_and(|held| held == placeholder.contents.as_bytes())
    {
        let _ = std::fs::remove_file(path);
    }
}

#[cfg(test)]
mod tests {
    use super::{DISABLE_USERNS, UNSHARE, unknown_disable_userns, unshare};

    #[test]
    fn only_an_unknown_disable_userns_drops_it() {
        assert!(unknown_disable_userns(
            "bwrap: Unknown option --disable-userns\n"
        ));
        for other in [
            "bwrap: setting up uid map: Permission denied",
            "bwrap: Failed to disable user namespaces: Permission denied (--disable-userns)",
            "bwrap: Unknown option --frobnicate",
            "",
        ] {
            assert!(!unknown_disable_userns(other), "{other}");
        }
    }

    #[test]
    fn user_namespaces_are_disabled_only_where_bubblewrap_knows_how() {
        let with = unshare(true);
        assert_eq!(with[..UNSHARE.len()], UNSHARE);
        assert_eq!(with.last(), Some(&DISABLE_USERNS));
        // `--disable-userns` needs the user namespace bubblewrap creates.
        assert!(with.contains(&"--unshare-user"));
        assert_eq!(unshare(false), UNSHARE.to_vec());
    }
}