landstrip 0.17.0

Sandbox for coding agents with parametrized state
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
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2026 Jarkko Sakkinen

//! macOS Seatbelt (SBPL) sandbox platform.

use crate::engine::error::{Cause, Error, Mechanism};
use crate::engine::policy::{AccessPolicy, NetworkAccess, ReadAccess, UnixSocketAccess};
use crate::engine::trap_fd::TrapFd;
use anyhow::Result;
use std::ffi::{CStr, CString, OsStr, OsString};
use std::fmt::{self, Write};
use std::fs;
use std::io;
use std::os::fd::RawFd;
use std::os::unix::process::CommandExt;
use std::path::PathBuf;
use std::process::Command;
use std::ptr;

const SBPL_PROFILE_FLAGS: u64 = 0;
const FIRST_INHERITED_FD: RawFd = 3;
const FALLBACK_FD_LIMIT: RawFd = 1_048_576;

pub(crate) fn execute(
    policy: &AccessPolicy,
    tool: &OsStr,
    args: &[OsString],
    trap_fd: &TrapFd,
) -> Result<()> {
    let profile = render_profile(policy).map_err(setup_failed)?;
    apply_profile(&profile)?;
    close_inherited_fds(trap_fd.fd()).map_err(setup_failed)?;
    let error = Command::new(tool).args(args).exec();
    Err(Error::LaunchFailed {
        tool: PathBuf::from(tool),
        source: error.into(),
    }
    .into())
}

/// A Seatbelt profile landstrip could not render or install.
fn setup_failed(source: impl Into<Cause>) -> Error {
    Error::SandboxSetupFailed {
        mechanism: Mechanism::Seatbelt,
        source: source.into(),
    }
}

/// Close every descriptor the launcher left open so the tool cannot reach them:
/// an inherited descriptor is writable regardless of the Seatbelt profile, which
/// would be a hole in the write policy.
///
/// The trap descriptor is the exception. landstrip still owes the launcher a
/// launch trap on it right up until `exec` replaces this process, so it is
/// marked close-on-exec instead: the kernel drops it the instant the tool
/// starts, and it survives long enough to report an `exec` that never did.
fn close_inherited_fds(trap_fd: Option<RawFd>) -> io::Result<()> {
    if let Some(fd) = trap_fd {
        set_cloexec(fd)?;
    }

    if let Ok(mut entries) = fs::read_dir("/dev/fd") {
        let mut fds = Vec::new();
        for entry in entries.by_ref().flatten() {
            let name = entry.file_name();
            let Some(name) = name.to_str() else {
                continue;
            };
            let Ok(fd) = name.parse::<RawFd>() else {
                continue;
            };
            if fd >= FIRST_INHERITED_FD {
                fds.push(fd);
            }
        }

        drop(entries);

        fds.sort_unstable();
        fds.dedup();
        for fd in fds {
            close_fd(fd, trap_fd);
        }
        return Ok(());
    }

    for fd in FIRST_INHERITED_FD..open_fd_limit() {
        close_fd(fd, trap_fd);
    }
    Ok(())
}

fn set_cloexec(fd: RawFd) -> io::Result<()> {
    // SAFETY: fcntl(2) copies scalar arguments only.
    let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
    if flags < 0 {
        return Err(io::Error::last_os_error());
    }

    // SAFETY: fcntl(2) copies scalar arguments only.
    if unsafe { libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC) } < 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(())
}

fn open_fd_limit() -> RawFd {
    clamp_fd_limit(unsafe { libc::sysconf(libc::_SC_OPEN_MAX) })
}

fn clamp_fd_limit(limit: libc::c_long) -> RawFd {
    if limit < i64::from(FIRST_INHERITED_FD) {
        return FALLBACK_FD_LIMIT;
    }
    RawFd::try_from(limit).map_or(FALLBACK_FD_LIMIT, |limit| limit.min(FALLBACK_FD_LIMIT))
}

fn close_fd(fd: RawFd, trap_fd: Option<RawFd>) {
    if fd >= FIRST_INHERITED_FD && Some(fd) != trap_fd {
        unsafe { libc::close(fd) };
    }
}

fn apply_profile(profile: &str) -> Result<()> {
    let profile = CString::new(profile).map_err(|source| {
        setup_failed(format!(
            "profile: interior nul at offset {}",
            source.nul_position()
        ))
    })?;
    let mut errorbuf = ptr::null_mut();

    // SAFETY: profile is a live NULL-terminated C string and errorbuf points to writable
    // storage through a raw out pointer.
    let rc = unsafe { ffi::sandbox_init(profile.as_ptr(), SBPL_PROFILE_FLAGS, &raw mut errorbuf) };
    if rc == 0 {
        Ok(())
    } else {
        Err(setup_failed(take_sandbox_error(errorbuf)).into())
    }
}

fn render_profile(policy: &AccessPolicy) -> std::result::Result<String, fmt::Error> {
    let mut sb = String::new();
    writeln!(sb, "(version 1)")?;
    writeln!(sb, "(deny default)")?;

    render_process_rules(&mut sb)?;
    render_mach_rules(&mut sb)?;
    render_write_rules(
        &mut sb,
        &policy.write_roots,
        &policy.write_denied_roots,
        &policy.write_denied_patterns,
    )?;
    render_read_rules(
        &mut sb,
        &policy.read_access,
        &policy.read_denied_roots,
        &policy.read_symlinks,
    )?;
    render_network_rules(&mut sb, &policy.network_access)?;

    Ok(sb)
}

fn render_process_rules(sb: &mut String) -> fmt::Result {
    writeln!(sb, "(allow process-exec)")?;
    writeln!(sb, "(allow process-fork)")?;
    writeln!(sb, "(allow sysctl-read)")
}

/// Default Mach services, matching the Anthropic sandbox-runtime (srt) base
/// profile plus `SecurityServer` and trustd for Keychain / TLS trust.
fn render_mach_rules(sb: &mut String) -> fmt::Result {
    writeln!(sb, "(allow mach-lookup")?;
    writeln!(sb, "  (global-name \"com.apple.SecurityServer\")")?;
    writeln!(sb, "  (global-name \"com.apple.trustd.agent\")")?;
    writeln!(sb, "  (global-name \"com.apple.audio.systemsoundserver\")")?;
    writeln!(sb, "  (global-name \"com.apple.bsd.dirhelper\")")?;
    writeln!(
        sb,
        "  (global-name \"com.apple.coreservices.launchservicesd\")"
    )?;
    writeln!(
        sb,
        "  (global-name \"com.apple.distributed_notifications@Uv3\")"
    )?;
    writeln!(sb, "  (global-name \"com.apple.FontObjectsServer\")")?;
    writeln!(sb, "  (global-name \"com.apple.fonts\")")?;
    writeln!(sb, "  (global-name \"com.apple.logd\")")?;
    writeln!(sb, "  (global-name \"com.apple.lsd.mapdb\")")?;
    writeln!(sb, "  (global-name \"com.apple.PowerManagement.control\")")?;
    writeln!(sb, "  (global-name \"com.apple.securityd.xpc\")")?;
    writeln!(sb, "  (global-name \"com.apple.system.logger\")")?;
    writeln!(
        sb,
        "  (global-name \"com.apple.system.notification_center\")"
    )?;
    writeln!(
        sb,
        "  (global-name \"com.apple.system.opendirectoryd.libinfo\")"
    )?;
    writeln!(
        sb,
        "  (global-name \"com.apple.system.opendirectoryd.membership\")"
    )?;
    writeln!(sb, ")")?;
    writeln!(
        sb,
        "(allow system-socket (require-all (socket-domain AF_SYSTEM) (socket-protocol 2)))"
    )
}

fn glob_to_sbpl_regex(pattern: &str) -> String {
    let mut regex = String::from("^");
    let mut rest = pattern;

    while !rest.is_empty() {
        if let Some(tail) = rest.strip_prefix("**/") {
            regex.push_str("(.*/)?");
            rest = tail;
        } else if let Some(tail) = rest.strip_prefix("**") {
            regex.push_str(".*");
            rest = tail;
        } else if let Some(tail) = rest.strip_prefix('*') {
            regex.push_str("[^/]*");
            rest = tail;
        } else if let Some(tail) = rest.strip_prefix('?') {
            regex.push_str("[^/]");
            rest = tail;
        } else if rest.starts_with('[') {
            if let Some(offset) = rest[1..].find(']') {
                let end = 1 + offset;
                regex.push_str(&rest[..=end]);
                rest = &rest[end + 1..];
            } else {
                regex.push_str("\\[");
                rest = &rest[1..];
            }
        } else {
            let mut chars = rest.chars();
            let Some(ch) = chars.next() else {
                break;
            };
            match ch {
                '.' | '(' | ')' | '{' | '}' | '+' | '|' | '^' | '$' | '\\' => {
                    regex.push('\\');
                    regex.push(ch);
                }
                _ => regex.push(ch),
            }
            rest = chars.as_str();
        }
    }

    regex.push('$');
    regex
}

fn render_write_rules(
    sb: &mut String,
    write_roots: &[PathBuf],
    write_denied_roots: &[PathBuf],
    write_denied_patterns: &[String],
) -> fmt::Result {
    for root in write_roots {
        let escaped = escape_sbpl_literal(&root.to_string_lossy());
        writeln!(sb, "(allow file-write* (subpath \"{escaped}\"))")?;
    }

    // Deny rules follow the allow rules so SBPL's last-match-wins precedence
    // subtracts the denied subtrees from the granted write roots.
    for root in write_denied_roots {
        let escaped = escape_sbpl_literal(&root.to_string_lossy());
        writeln!(sb, "(deny file-write* (subpath \"{escaped}\"))")?;
    }

    // Regex rules are evaluated at syscall time, so unlike expand_glob_path
    // they also cover paths created after sandbox_init.
    for pattern in write_denied_patterns {
        let escaped = escape_sbpl_literal(&glob_to_sbpl_regex(pattern));
        writeln!(sb, "(deny file-write* (regex #\"{escaped}\"))")?;
    }

    Ok(())
}

fn render_read_rules(
    sb: &mut String,
    read_access: &ReadAccess,
    read_denied_roots: &[PathBuf],
    read_symlinks: &[PathBuf],
) -> fmt::Result {
    match read_access {
        ReadAccess::Unrestricted => sb.push_str("(allow file-read*)\n"),
        ReadAccess::AllowRoots(roots) => {
            writeln!(sb, "(deny file-read*)")?;
            writeln!(sb, "(allow file-read* (literal \"/\"))")?;
            for root in roots {
                let escaped = escape_sbpl_literal(&root.to_string_lossy());
                writeln!(sb, "(allow file-read* (subpath \"{escaped}\"))")?;
            }
            render_parent_dir_rules(sb, roots)?;

            render_symlink_metadata_rules(sb, read_symlinks)?;

            // Deny rules follow the allow rules so SBPL's last-match-wins
            // precedence subtracts the denied subtrees from the read roots.
            for root in read_denied_roots {
                let escaped = escape_sbpl_literal(&root.to_string_lossy());
                writeln!(sb, "(deny file-read* (subpath \"{escaped}\"))")?;
            }
        }
    }

    Ok(())
}

fn render_parent_dir_rules(sb: &mut String, roots: &[PathBuf]) -> fmt::Result {
    let mut ancestors: Vec<PathBuf> = Vec::new();
    for root in roots {
        let mut current = root.as_path();
        while let Some(parent) = current.parent() {
            if parent.as_os_str().is_empty() {
                break;
            }
            ancestors.push(parent.to_path_buf());
            current = parent;
        }
    }
    ancestors.sort_unstable();
    ancestors.dedup();
    for ancestor in &ancestors {
        let escaped = escape_sbpl_literal(&ancestor.to_string_lossy());
        writeln!(sb, "(allow file-read* (literal \"{escaped}\"))")?;
    }
    Ok(())
}

/// Allow `readlink` on the lexical symlink inodes the read scan skipped.
///
/// Mirrors Apple's system.sb: `readlink` only permits resolution; the target
/// is still gated by the existing allow/deny rules, so this grants no new read
/// access.
fn render_symlink_metadata_rules(sb: &mut String, symlinks: &[PathBuf]) -> fmt::Result {
    if symlinks.is_empty() {
        return Ok(());
    }
    sb.push_str("(allow file-read-metadata");
    for sym in symlinks {
        let escaped = escape_sbpl_literal(&sym.to_string_lossy());
        write!(sb, "\n  (literal \"{escaped}\")")?;
    }
    sb.push_str(")\n");
    Ok(())
}

fn render_network_rules(sb: &mut String, network: &NetworkAccess) -> fmt::Result {
    if network.is_unrestricted() {
        sb.push_str("(allow network*)\n");
        return Ok(());
    }

    // AF_UNIX socket creation stays allowed regardless of the socket policy.
    sb.push_str("(allow system-socket (socket-domain AF_UNIX))\n");

    if network.restrict_connect_tcp {
        sb.push_str("(deny network-outbound)\n");
        for port in &network.connect_tcp_ports {
            writeln!(
                sb,
                "(allow network-outbound (remote tcp \"localhost:{port}\"))"
            )?;
        }
    }

    if network.local_tcp_bind {
        sb.push_str("(allow network-bind (local tcp \"localhost:*\"))\n");
        sb.push_str("(allow network-inbound (local tcp \"localhost:*\"))\n");
    }

    match &network.unix_socket_access {
        UnixSocketAccess::Unrestricted => {
            sb.push_str("(allow network-outbound (remote unix-socket))\n");
            sb.push_str("(allow network-bind (local unix-socket))\n");
        }
        UnixSocketAccess::AllowPaths(paths) if !paths.is_empty() => {
            for path in paths {
                let escaped = escape_sbpl_literal(&path.to_string_lossy());
                writeln!(
                    sb,
                    "(allow network-outbound (remote unix-socket (subpath \"{escaped}\")))"
                )?;
                writeln!(
                    sb,
                    "(allow network-bind (local unix-socket (subpath \"{escaped}\")))"
                )?;
            }
        }
        UnixSocketAccess::AllowPaths(_) => {}
    }

    Ok(())
}

fn escape_sbpl_literal(path: &str) -> String {
    let mut escaped = String::with_capacity(path.len());
    for ch in path.chars() {
        match ch {
            '"' => escaped.push_str("\\\""),
            '\\' => escaped.push_str("\\\\"),
            '\n' => escaped.push_str("\\n"),
            _ => escaped.push(ch),
        }
    }
    escaped
}

fn take_sandbox_error(errorbuf: *mut libc::c_char) -> String {
    if errorbuf.is_null() {
        return "sandbox_init failed without an error message".to_string();
    }

    let message = unsafe { CStr::from_ptr(errorbuf) }
        .to_string_lossy()
        .into_owned();
    unsafe { ffi::sandbox_free_error(errorbuf) };
    message
}

mod ffi {
    use libc::{c_char, c_int};

    #[link(name = "sandbox")]
    unsafe extern "C" {
        pub(super) fn sandbox_init(
            profile: *const c_char,
            flags: u64,
            errorbuf: *mut *mut c_char,
        ) -> c_int;
        pub(super) fn sandbox_free_error(errorbuf: *mut c_char);
    }
}