use anyhow::{Context, Result, bail};
use std::ffi::{CStr, CString};
use std::fmt::Write as _;
use std::os::raw::{c_char, c_int};
use std::path::Path;
use crate::SandboxConfig;
pub(super) struct SeatbeltResult {
pub applied: bool,
pub message: String,
pub fs_restricted: bool,
pub net_blocked: bool,
}
unsafe extern "C" {
fn sandbox_init_with_parameters(
profile: *const c_char,
flags: u64,
parameters: *const *const c_char,
errorbuf: *mut *mut c_char,
) -> c_int;
fn sandbox_free_error(errorbuf: *mut c_char);
}
const SBPL_PROFILE_BASE: &str = r#"(version 1)
;; Allow-default: everything permitted unless explicitly denied
(allow default)
;; Block reads from user home directories
;; Prevents reading SSH keys, AWS credentials, browser profiles, cookies, etc.
;; if a vulnerability in DPI/packet parsing is exploited.
;; SBPL specificity: more specific allow rules for the configured read paths
;; below will take precedence over these broader deny rules.
(deny file-read-data
(subpath "/Users")
(subpath "/var/root"))
;; Block reads of system credential stores outside the user homes above.
;; RustNet never needs these, so denying them limits credential theft if a
;; DPI/packet-parsing vulnerability is exploited. This matters in particular
;; when running as root: Seatbelt is enforced regardless of uid, so it covers
;; secrets that DAC file permissions would otherwise expose to a root process.
;; Both the symlink and resolved forms are listed because macOS resolves
;; /etc -> /private/etc and /var -> /private/var.
(deny file-read*
(subpath "/Library/Keychains")
(subpath "/private/var/db/dslocal")
(subpath "/var/db/dslocal")
(subpath "/private/etc/ssh")
(subpath "/etc/ssh"))
;; Block writes to user home directories
;; Regular user homes on macOS are under /Users; root's home is /var/root.
;; Protects SSH keys, AWS credentials, GPG keys, browser profiles, etc.
;; SBPL specificity: more specific allow rules for the configured write paths
;; below will take precedence over these broader deny rules.
(deny file-write*
(subpath "/Users")
(subpath "/var/root"))
"#;
const SBPL_PROFILE_EXEC: &str = r#"
;; Block execution of all binaries except lsof
;; Prevents shell escapes (/bin/sh, /usr/bin/curl, etc.) if code execution
;; is achieved through a DPI parsing vulnerability.
(deny process-exec)
(allow process-exec
(literal "/usr/sbin/lsof"))
"#;
const SBPL_NETWORK_DENY: &str = r#"
;; Block outbound TCP and UDP connections
;; RustNet only reads from BPF/PKTAP — already-open fds are unaffected
(deny network-outbound
(remote tcp)
(remote udp))
;; Allow Unix domain socket IPC (required for threading, Mach port bridge)
(allow network-outbound
(remote unix-socket))
"#;
fn build_sbpl_profile(config: &SandboxConfig) -> String {
let mut profile = String::from(SBPL_PROFILE_BASE);
let read_rules: Vec<String> = config
.read_paths
.iter()
.map(|p| {
let path = sbpl_path(p);
format!(" (literal \"{path}\")\n (subpath \"{path}\")")
})
.collect();
if !read_rules.is_empty() {
let _ = write!(
profile,
"\n;; Allow reads from configured read paths (e.g. GeoIP databases)\n\
(allow file-read-data\n{})\n",
read_rules.join("\n")
);
}
let write_rules: Vec<String> = config
.write_paths
.iter()
.map(|p| {
let path = sbpl_path(p);
if Path::new(&resolve_to_absolute(p)).is_dir() {
format!(" (literal \"{path}\")\n (subpath \"{path}\")")
} else {
format!(" (literal \"{path}\")")
}
})
.collect();
if !write_rules.is_empty() {
let _ = write!(
profile,
"\n;; Allow writes to configured output paths (log files, exports)\n\
(allow file-write*\n{})\n",
write_rules.join("\n")
);
}
profile.push_str(SBPL_PROFILE_EXEC);
if config.block_network {
profile.push_str(SBPL_NETWORK_DENY);
}
profile
}
pub(super) fn apply_seatbelt(config: &SandboxConfig) -> Result<SeatbeltResult> {
let profile = build_sbpl_profile(config);
let profile_cstr = CString::new(profile).context("Profile contains null byte")?;
let ptrs_with_null: Vec<*const c_char> = vec![std::ptr::null()];
let mut errorbuf: *mut c_char = std::ptr::null_mut();
let ret = unsafe {
sandbox_init_with_parameters(
profile_cstr.as_ptr(),
0,
ptrs_with_null.as_ptr(),
&mut errorbuf,
)
};
let error_message = if !errorbuf.is_null() {
let msg = unsafe { CStr::from_ptr(errorbuf) }
.to_string_lossy()
.into_owned();
unsafe { sandbox_free_error(errorbuf) };
Some(msg)
} else {
None
};
if ret != 0 {
let detail = error_message.unwrap_or_else(|| "unknown error".to_string());
bail!("sandbox_init_with_parameters failed ({}): {}", ret, detail);
}
if let Some(warn) = &error_message {
log::warn!("Seatbelt: warning from sandbox_init: {}", warn);
}
log::info!(
"Seatbelt sandbox applied (fs_restricted=true, net_blocked={})",
config.block_network
);
Ok(SeatbeltResult {
applied: true,
message: format!(
"Seatbelt applied (fs restricted, net {})",
if config.block_network {
"blocked"
} else {
"allowed"
}
),
fs_restricted: true,
net_blocked: config.block_network,
})
}
fn sbpl_path(path: &Path) -> String {
escape_sbpl_path(&resolve_to_absolute(path))
}
fn resolve_to_absolute(path: &Path) -> String {
if let Ok(canonical) = std::fs::canonicalize(path) {
return canonical.to_string_lossy().into_owned();
}
if path.is_absolute() {
path.to_string_lossy().into_owned()
} else {
std::env::current_dir()
.map(|cwd| cwd.join(path).to_string_lossy().into_owned())
.unwrap_or_else(|_| path.to_string_lossy().into_owned())
}
}
fn escape_sbpl_path(path: &str) -> String {
path.replace('\\', "\\\\").replace('"', "\\\"")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::SandboxMode;
use std::path::PathBuf;
fn config(read: &[&str], write: &[&str], block_network: bool) -> SandboxConfig {
SandboxConfig {
mode: SandboxMode::BestEffort,
block_network,
read_paths: read.iter().map(PathBuf::from).collect(),
write_paths: write.iter().map(PathBuf::from).collect(),
drop_uid: None,
}
}
#[test]
fn test_profile_includes_configured_paths() {
let profile = build_sbpl_profile(&config(
&["/usr/share/GeoIP"],
&["/private/var/rustnet/events.jsonl"],
true,
));
assert!(profile.contains(r#"(subpath "/usr/share/GeoIP")"#));
assert!(profile.contains(r#"(literal "/usr/share/GeoIP")"#));
assert!(profile.contains(r#"(literal "/private/var/rustnet/events.jsonl")"#));
assert!(!profile.contains(r#"(subpath "/private/var/rustnet/events.jsonl")"#));
}
#[test]
fn test_profile_without_paths_has_no_empty_allow_sections() {
let profile = build_sbpl_profile(&config(&[], &[], true));
assert!(!profile.contains("(allow file-read-data\n)"));
assert!(!profile.contains("(allow file-write*\n)"));
assert!(profile.contains("deny file-read-data"));
assert!(profile.contains("deny file-write*"));
}
#[test]
fn test_profile_denies_system_credential_stores() {
for block_network in [true, false] {
let profile = build_sbpl_profile(&config(&[], &[], block_network));
for store in ["/Library/Keychains", "/private/var/db/dslocal", "/etc/ssh"] {
assert!(
profile.contains(store),
"Expected credential-store deny for {store} (block_network={block_network})"
);
}
}
}
#[test]
fn test_profile_network_deny_toggle() {
assert!(build_sbpl_profile(&config(&[], &[], true)).contains("deny network-outbound"));
assert!(!build_sbpl_profile(&config(&[], &[], false)).contains("deny network-outbound"));
}
#[test]
fn test_profile_includes_process_exec_deny() {
let profile = build_sbpl_profile(&config(&[], &[], false));
assert!(profile.contains("(deny process-exec)"));
assert!(profile.contains(r#"(literal "/usr/sbin/lsof")"#));
}
#[test]
fn test_profile_is_valid_cstring_and_escaped() {
let profile =
build_sbpl_profile(&config(&[], &[r#"/private/tmp/path"with\special"#], true));
CString::new(profile.clone()).expect("profile must not contain null bytes");
assert!(profile.contains(r#"/private/tmp/path\"with\\special"#));
}
#[test]
fn test_relative_path_is_resolved_to_absolute() {
let abs = resolve_to_absolute(Path::new("logs"));
assert!(abs.starts_with('/'), "Expected absolute path, got: {}", abs);
assert!(
abs.ends_with("/logs"),
"Expected path ending with /logs, got: {}",
abs
);
}
#[test]
fn test_absolute_nonexistent_path_is_unchanged() {
assert_eq!(
resolve_to_absolute(Path::new("/tmp/rustnet-does-not-exist")),
"/tmp/rustnet-does-not-exist"
);
}
#[test]
fn test_symlink_resolved_by_canonicalize() {
let resolved = resolve_to_absolute(Path::new("/tmp"));
assert_eq!(
resolved, "/private/tmp",
"Expected /tmp to resolve to /private/tmp via canonicalize, got: {}",
resolved
);
}
#[test]
fn test_escape_sbpl_path_with_quotes_and_backslashes() {
assert_eq!(escape_sbpl_path("/tmp/rustnet/logs"), "/tmp/rustnet/logs");
assert_eq!(
escape_sbpl_path(r#"/tmp/path"with\special"#),
r#"/tmp/path\"with\\special"#
);
}
}