diff --git a/crates/sandlock-cli/Cargo.toml b/crates/sandlock-cli/Cargo.toml index 9772cb12..a9fce1ff 100644 --- a/crates/sandlock-cli/Cargo.toml +++ b/crates/sandlock-cli/Cargo.toml @@ -21,6 +21,6 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" jiff = "0.2" libc = "0.2" +tempfile = "3" [dev-dependencies] -tempfile = "3" diff --git a/crates/sandlock-cli/src/learn.rs b/crates/sandlock-cli/src/learn.rs new file mode 100644 index 00000000..db0fb29e --- /dev/null +++ b/crates/sandlock-cli/src/learn.rs @@ -0,0 +1,375 @@ +//! Implementation of `sandlock learn -o `. +//! +//! Runs a workload under observation and emits a sandlock profile TOML +//! usable by `sandlock run -p`. + +use std::collections::{BTreeSet, HashSet}; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use anyhow::{anyhow, Result}; +use sandlock_core::policy_fn::{SyscallEvent, Verdict}; +use sandlock_core::profile::{FilesystemSection, ProfileInput}; +use sandlock_core::sandbox::BranchAction; +use sandlock_core::Sandbox; + +use crate::LearnArgs; + +// openat flags (from fcntl.h) +const O_WRONLY: u64 = 0o1; +const O_RDWR: u64 = 0o2; +const O_CREAT: u64 = 0o100; + +fn is_write_open(flags: u64) -> bool { + // No valid open flag has bits 32+; a value that large is a pointer or + // garbage (e.g. from a mis-decoded syscall arg). Treat it as read-only + // so a misdecoded flag never puts a file in writes incorrectly. + if flags >> 32 != 0 { + return false; + } + flags & (O_WRONLY | O_RDWR | O_CREAT) != 0 +} + +/// Read the dynamic linker path from `/proc//maps`. The kernel loads it +/// during execve (bypassing seccomp), so this is the way to discover it +/// after the execve completes and `/proc//maps` reflects the new binary. +fn read_linker_from_maps(pid: u32) -> Option { + use std::io::BufRead; + let file = std::fs::File::open(format!("/proc/{pid}/maps")).ok()?; + for line in std::io::BufReader::new(file).lines() { + let line = line.ok()?; + // Format: "addr-addr perms offset dev inode pathname" + let pathname = line.splitn(6, ' ').nth(5).map(str::trim).unwrap_or(""); + if !pathname.is_empty() && !pathname.starts_with('[') { + let p = std::path::Path::new(pathname); + if p.file_name() + .and_then(|n| n.to_str()) + .map(|n| n.starts_with("ld-")) + .unwrap_or(false) + { + return Some(p.to_path_buf()); + } + } + } + None +} + +/// Accumulated observations from the policy_fn callback during learn. +#[derive(Clone)] +struct LearnObserver { + reads: Arc>>, + writes: Arc>>, + connects: Arc>>, + /// PIDs that just completed an execve — on the NEXT event from that PID, + /// /proc//maps will reflect the new binary's dynamic linker. + pending_maps: Arc>>, +} + +impl LearnObserver { + fn new() -> Self { + Self { + reads: Arc::new(Mutex::new(BTreeSet::new())), + writes: Arc::new(Mutex::new(BTreeSet::new())), + connects: Arc::new(Mutex::new(BTreeSet::new())), + pending_maps: Arc::new(Mutex::new(HashSet::new())), + } + } + + /// The policy_fn callback: classifies each intercepted syscall into + /// reads, writes, or connects for profile generation. + fn on_event(&self, event: SyscallEvent) -> Verdict { + // After an execve, the NEXT event from that PID fires once the + // new binary is running — /proc//maps now shows the dynamic + // linker loaded by the kernel (which bypassed seccomp). + if self.pending_maps.lock().unwrap().remove(&event.pid) { + if let Some(linker) = read_linker_from_maps(event.pid) { + self.reads.lock().unwrap().insert(linker); + } + } + + match event.syscall.as_str() { + "execve" | "execveat" => { + if let Some(path) = event.path { + self.reads.lock().unwrap().insert(path); + } + // Mark PID: read maps on next event after execve completes. + self.pending_maps.lock().unwrap().insert(event.pid); + } + "openat" | "open" => { + if let Some(path) = event.path { + if let Some(fl) = event.flags { + if is_write_open(fl) { + self.writes.lock().unwrap().insert(path); + } else { + self.reads.lock().unwrap().insert(path); + } + } + } + } + // mkdir/unlink/rmdir/symlink: Landlock MAKE_*/REMOVE_* are directory + // rights, so the parent dir is what sandlock run needs, not the target. + "mkdirat" | "unlinkat" | "symlinkat" => { + if let Some(p) = event.path { + if let Some(parent) = p.parent() { + self.writes.lock().unwrap().insert(parent.to_path_buf()); + } + } + } + // rename: needs RENAME_OLD on parent of old path + RENAME_NEW on parent of new path. + "renameat2" => { + for p in [event.path, event.path2].into_iter().flatten() { + if let Some(parent) = p.parent() { + self.writes.lock().unwrap().insert(parent.to_path_buf()); + } + } + } + // link: source needs read access (ln doesn't open() it); dst parent needs MAKE_HARDLINK. + "linkat" => { + if let Some(src) = event.path { + self.reads.lock().unwrap().insert(src); + } + if let Some(dst) = event.path2 { + if let Some(parent) = dst.parent() { + self.writes.lock().unwrap().insert(parent.to_path_buf()); + } + } + } + // truncate: LANDLOCK_ACCESS_FS_TRUNCATE applies to the file itself. + "truncate" => { + if let Some(p) = event.path { + self.writes.lock().unwrap().insert(p); + } + } + // Simplified: connect is assumed TCP, sendto/sendmsg UDP. + // Ideally we'd check SO_PROTOCOL on the socket fd (need emit_policy_event to expose that info in SyscallEvent) + "connect" => { + if let (Some(ip), Some(port)) = (event.host, event.port) { + self.connects.lock().unwrap().insert(format!("tcp://{ip}:{port}")); + } + } + "sendto" | "sendmsg" | "sendmmsg" => { + if let (Some(ip), Some(port)) = (event.host, event.port) { + self.connects.lock().unwrap().insert(format!("udp://{ip}:{port}")); + } + } + _ => {} + } + Verdict::Allow + } +} + + +pub async fn run(args: LearnArgs) -> Result<()> { + if args.cmd.is_empty() { + anyhow::bail!("no command given — use: sandlock learn [flags] -- [args...]"); + } + + let cmd_str = args.cmd.join(" "); + let cmd_refs: Vec<&str> = args.cmd.iter().map(String::as_str).collect(); + + // COW workdir="/" covers every path: seccomp fires before Landlock, so the + // supervisor intercepts every write openat and redirects it to an upper layer + // the real filesystem is untouched and no write is blocked. + let observer = LearnObserver::new(); + let observer_cb = observer.clone(); + let policy = Sandbox::builder() + .fs_read("/") + .workdir("/") + // Discard all COW changes after observation; learn is read-only from + // the real filesystem's perspective. + .on_exit(BranchAction::Abort) + .on_error(BranchAction::Abort) + .net_allow("*") + .net_allow("udp://*") + .net_allow("icmp://*") + .policy_fn(move |event, _ctx| observer_cb.on_event(event)) + .build() + .map_err(|e| anyhow!("failed to build sandbox policy: {e}"))?; + + eprintln!("sandlock learn: observing {cmd_str} ..."); + + // Use the three-step lifecycle (create/start/wait) so we can get the child + // PID from sandbox.pid() and sample /proc/ for resource peaks. + let mut sandbox = policy.with_name("sandlock-learn"); + sandbox.create_interactive(&cmd_refs).await + .map_err(|e| anyhow!("sandbox error: {e}"))?; + let child_pid = sandbox.pid().expect("child pid after create") as u32; + sandbox.start() + .map_err(|e| anyhow!("sandbox error: {e}"))?; + + // Resource peak sampler: polls /proc/ every 100ms until the process exits. + let max_threads = Arc::new(AtomicU64::new(0)); + let max_fds = Arc::new(AtomicU64::new(0)); + let peak_rss_kb_atomic = Arc::new(AtomicU64::new(0)); + let (max_threads_s, max_fds_s, peak_rss_s) = ( + Arc::clone(&max_threads), Arc::clone(&max_fds), Arc::clone(&peak_rss_kb_atomic), + ); + let sampler = tokio::spawn(async move { + loop { + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + match std::fs::read_to_string(format!("/proc/{child_pid}/status")) { + Err(_) => break, // process gone + Ok(s) => { + for line in s.lines() { + if let Some(v) = line.strip_prefix("Threads:") { + if let Ok(n) = v.trim().parse::() { + max_threads_s.fetch_max(n, Ordering::Relaxed); + } + } + if let Some(v) = line.strip_prefix("VmHWM:") { + if let Ok(n) = v.trim().trim_end_matches("kB").trim().parse::() { + peak_rss_s.fetch_max(n, Ordering::Relaxed); + } + } + } + } + } + if let Ok(entries) = std::fs::read_dir(format!("/proc/{child_pid}/fd")) { + max_fds_s.fetch_max(entries.count() as u64, Ordering::Relaxed); + } + } + }); + + // Wait for the process, optionally with a timeout. + let timed_out = if let Some(secs) = args.timeout { + let deadline = std::time::Duration::from_secs(secs); + match tokio::time::timeout(deadline, sandbox.wait()).await { + Ok(r) => { + let result = r.map_err(|e| anyhow!("sandbox error: {e}"))?; + sampler.abort(); + match result.exit_status { + sandlock_core::ExitStatus::Code(0) => eprintln!("sandlock learn: done"), + sandlock_core::ExitStatus::Code(n) => { + eprintln!("sandlock learn: process exited with code {n}, not writing profile"); + std::process::exit(1); + } + sandlock_core::ExitStatus::Signal(sig) => { + eprintln!("sandlock learn: process killed by signal {sig}, not writing profile"); + std::process::exit(1); + } + sandlock_core::ExitStatus::Killed | sandlock_core::ExitStatus::Timeout => { + eprintln!("sandlock learn: process terminated abnormally, not writing profile"); + std::process::exit(1); + } + } + false + } + Err(_elapsed) => { + // Timeout: kill the child, drain the supervisor, write a partial profile. + eprintln!("sandlock learn: timeout after {secs}s, killing process"); + unsafe { libc::kill(child_pid as i32, libc::SIGKILL); } + // Drain without timeout so the supervisor releases its resources cleanly. + let _ = sandbox.wait().await; + sampler.abort(); + true + } + } + } else { + let result = sandbox.wait().await + .map_err(|e| anyhow!("sandbox error: {e}"))?; + sampler.abort(); + match result.exit_status { + sandlock_core::ExitStatus::Code(0) => eprintln!("sandlock learn: done"), + sandlock_core::ExitStatus::Code(n) => { + eprintln!("sandlock learn: process exited with code {n}, not writing profile"); + std::process::exit(1); + } + sandlock_core::ExitStatus::Signal(sig) => { + eprintln!("sandlock learn: process killed by signal {sig}, not writing profile"); + std::process::exit(1); + } + sandlock_core::ExitStatus::Killed | sandlock_core::ExitStatus::Timeout => { + eprintln!("sandlock learn: process terminated abnormally, not writing profile"); + std::process::exit(1); + } + } + false + }; + + if timed_out { + eprintln!("sandlock learn: writing partial profile from observations before timeout"); + } + + let peak_rss_kb = peak_rss_kb_atomic.load(Ordering::Relaxed); + let threads = max_threads.load(Ordering::Relaxed); + let fds = max_fds.load(Ordering::Relaxed); + + // Build the profile. + let mut profile_out = ProfileInput::default(); + + // Record the observed command so `sandlock run -p profile.toml` works + // without repeating the command on the CLI. + profile_out.program.exec = Some(PathBuf::from(&args.cmd[0])); + profile_out.program.args = args.cmd[1..].to_vec(); + + profile_out.filesystem = FilesystemSection { + // Filter reads by existence to drop failed PATH-probe openats. + // Executed binaries are merged into read. + read: observer.reads.lock().unwrap().iter() + .filter(|p| p.exists()) + .cloned() + .collect(), + // For writes: if the file exists on the real FS, record the specific path + // (COW kept the original intact; the file was there before the run). + // If it doesn't exist (COW intercepted a create → new file in upper layer), + // record the parent directory instead; Landlock requires existing paths, + // and the program needs directory write access to create new files. + write: observer.writes.lock().unwrap().iter() + .filter_map(|p| { + if p.exists() { + Some(p.clone()) + } else { + p.parent().filter(|d| d.exists()).map(|d| d.to_path_buf()) + } + }) + .collect(), + ..Default::default() + }; + profile_out.network.allow = observer.connects.lock().unwrap().iter().cloned().collect(); + + // Fill limits with observed peaks + headroom so the profile is usable with sandlock run. + if peak_rss_kb > 0 { + let mib = (peak_rss_kb + 1023) / 1024; // ceil to MiB + let headroom = (mib * 5 / 4).max(16); // +25%, min 16M + profile_out.limits.memory = Some(format!("{headroom}M")); + } + if threads > 0 { + profile_out.limits.processes = Some((threads * 2).max(4) as u32); + } + if fds > 0 { + profile_out.limits.open_files = Some((fds * 2).max(32) as u32); + } + + let kernel = std::fs::read_to_string("/proc/version") + .unwrap_or_default() + .split_whitespace() + .nth(2) + .unwrap_or("unknown") + .to_string(); + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs().to_string()) + .unwrap_or_default(); + let header = format!( + "# generated by sandlock learn\n\ + # command: {}\n\ + # kernel: {kernel}\n\ + # timestamp: {timestamp}\n\n", + cmd_str.replace('\n', " ") + ); + let body = profile_out.to_toml() + .map_err(|e| anyhow!("failed to serialize profile: {e}"))?; + let toml_out = format!("{header}{body}"); + + match args.output { + Some(ref path) => { + std::fs::write(path, &toml_out) + .map_err(|e| anyhow!("failed to write {}: {e}", path.display()))?; + eprintln!("sandlock learn: profile written to {}", path.display()); + } + None => print!("{toml_out}"), + } + + Ok(()) +} diff --git a/crates/sandlock-cli/src/main.rs b/crates/sandlock-cli/src/main.rs index ad973bf3..62d8d10a 100644 --- a/crates/sandlock-cli/src/main.rs +++ b/crates/sandlock-cli/src/main.rs @@ -7,6 +7,7 @@ use std::path::PathBuf; use std::time::SystemTime; mod network_registry; +mod learn; #[derive(Parser)] #[command(name = "sandlock", about = "Lightweight process sandbox", version)] @@ -33,6 +34,8 @@ enum Command { #[command(subcommand)] action: ProfileAction, }, + /// Observe a workload and emit a sandlock profile + Learn(LearnArgs), } /// Arguments for the `run` subcommand. @@ -200,6 +203,22 @@ enum ProfileAction { Delete { name: String }, } +/// Arguments for the `learn` subcommand. +#[derive(clap::Args)] +struct LearnArgs { + /// Write observed profile to this file (default: print to stdout) + #[arg(short = 'o', long, value_name = "PATH")] + output: Option, + + /// Kill the observed process after this many seconds and write a partial profile + #[arg(long, value_name = "SECS")] + timeout: Option, + + /// Command to observe (everything after --) + #[arg(last = true, required = true)] + cmd: Vec, +} + #[derive(serde::Serialize)] struct SandboxStatus { exit_code: i32, @@ -303,6 +322,10 @@ async fn main() -> Result<()> { println!(" Platform: {}", std::env::consts::ARCH); } + Command::Learn(args) => { + learn::run(args).await?; + } + Command::Profile { action } => { match action { ProfileAction::List => { diff --git a/crates/sandlock-cli/tests/cli_test.rs b/crates/sandlock-cli/tests/cli_test.rs index 3a5facf9..3704d17c 100644 --- a/crates/sandlock-cli/tests/cli_test.rs +++ b/crates/sandlock-cli/tests/cli_test.rs @@ -281,7 +281,449 @@ fn test_cow_commit_runs_on_cli_exit() { assert_eq!(contents.trim(), "committed"); } -/// Regression: `--user N:N` maps the sandbox to UID `N` via an unprivileged +/// `sandlock learn` must capture filesystem reads in the generated profile. +/// Runs `cat /etc/hostname` and verifies `/etc/hostname` appears under `read`. +#[test] +fn test_learn_captures_fs_read() { + let output = sandlock_bin() + .args(["learn", "--", "cat", "/etc/hostname"]) + .output() + .expect("failed to run sandlock learn"); + assert!( + output.status.success(), + "sandlock learn failed: stderr={}", + String::from_utf8_lossy(&output.stderr), + ); + let stdout = String::from_utf8_lossy(&output.stdout); + let read_line = stdout.lines().find(|l| l.starts_with("read = [")).unwrap_or(""); + assert!( + read_line.contains("/etc/hostname"), + "expected /etc/hostname under read = [...], got: {read_line}", + ); +} + +/// End-to-end: `sandlock learn` generates a profile, `sandlock run` uses it. +/// Verifies the full round-trip works for a simple read-only workload. +#[test] +fn test_learn_then_run() { + let profile = tempfile::NamedTempFile::new().expect("tempfile"); + let profile_path = profile.path().to_str().unwrap().to_owned(); + + let learn = sandlock_bin() + .args(["learn", "-o", &profile_path, "--", "cat", "/etc/hostname"]) + .output() + .expect("failed to run sandlock learn"); + assert!( + learn.status.success(), + "sandlock learn failed: stderr={}", + String::from_utf8_lossy(&learn.stderr), + ); + + let run = sandlock_bin() + .args(["run", "--profile-file", &profile_path, "--", "cat", "/etc/hostname"]) + .output() + .expect("failed to run sandlock run"); + assert!( + run.status.success(), + "sandlock run with learned profile failed: stderr={}", + String::from_utf8_lossy(&run.stderr), + ); + assert!( + !String::from_utf8_lossy(&run.stdout).trim().is_empty(), + "expected output from cat /etc/hostname", + ); +} + +/// `sandlock learn` must classify file opens with write flags under `write`. +/// Writes to two pre-existing temp files in different directories (no error +/// handling in the script; any blocked write would exit sh non-zero). +#[test] +fn test_learn_captures_fs_write() { + let tmp1 = tempfile::NamedTempFile::new().expect("tempfile"); + let tmp2 = tempfile::Builder::new().tempdir_in("/var/tmp").expect("tempdir"); + let tmp2_file = tmp2.path().join("sandlock-learn-write2.txt"); + let path1 = tmp1.path().to_str().unwrap().to_owned(); + let path2 = tmp2_file.to_str().unwrap().to_owned(); + let cmd = format!("echo x > {path1} && echo y > {path2}"); + let output = sandlock_bin() + .args(["learn", "--", "sh", "-c", &cmd]) + .output() + .expect("failed to run sandlock learn"); + assert!( + output.status.success(), + "sandlock learn failed: stderr={}", + String::from_utf8_lossy(&output.stderr), + ); + let stdout = String::from_utf8_lossy(&output.stdout); + let write_line = stdout.lines().find(|l| l.starts_with("write = [")).unwrap_or(""); + assert!(write_line.contains(&path1), "expected {path1} under write = [...], got: {write_line}"); + assert!(write_line.contains(&path2) || write_line.contains(tmp2.path().to_str().unwrap()), + "expected {path2} (or its parent) under write = [...], got: {write_line}"); +} + +/// New file creates must be collapsed to the parent directory in the profile. +/// The specific file path is useless to Landlock (it doesn't exist yet); +/// the parent dir is what `sandlock run` needs to create new files. +/// COW must also confirm the real filesystem is not touched during learn. +#[test] +fn test_learn_new_file_collapses_to_parent() { + let path = "/var/tmp/sandlock-learn-write-test.txt"; + let output = sandlock_bin() + .args(["learn", "--", "sh", "-c", &format!("echo x > {path}")]) + .output() + .expect("failed to run sandlock learn"); + assert!( + output.status.success(), + "sandlock learn failed: stderr={}", + String::from_utf8_lossy(&output.stderr), + ); + let stdout = String::from_utf8_lossy(&output.stdout); + // New-file creates are collapsed to the parent directory (file didn't exist on real FS). + let parent = std::path::Path::new(path).parent().unwrap().to_str().unwrap(); + let write_line = stdout.lines().find(|l| l.starts_with("write = [")).unwrap_or(""); + assert!( + write_line.contains(parent), + "expected parent dir {parent} under write = [...], got: {write_line}", + ); + // COW must have intercepted the write, real file must not exist. + assert!( + !std::path::Path::new(path).exists(), + "real filesystem was modified, COW isolation failed", + ); +} + +/// mkdir records the parent directory in write (Landlock MAKE_DIR is a dir right). +/// COW must intercept the create so the real directory does not appear. +#[test] +fn test_learn_captures_mkdir() { + let dir = "/var/tmp/sandlock-learn-mkdir-test"; + let output = sandlock_bin() + .args(["learn", "--", "sh", "-c", &format!("mkdir {dir}")]) + .output() + .expect("failed to run sandlock learn"); + assert!(output.status.success(), + "sandlock learn failed: stderr={}", String::from_utf8_lossy(&output.stderr)); + let stdout = String::from_utf8_lossy(&output.stdout); + let write_line = stdout.lines().find(|l| l.starts_with("write = [")).unwrap_or(""); + assert!(write_line.contains("/var/tmp"), + "expected /var/tmp in write = [...], got: {write_line}"); + assert!(!std::path::Path::new(dir).exists(), "COW isolation failed: dir was created on real FS"); +} + +/// unlink records the parent directory in write (Landlock REMOVE_FILE is a dir right). +/// COW must intercept the delete so the real file still exists after learn. +#[test] +fn test_learn_captures_unlink() { + let file = tempfile::NamedTempFile::new().expect("tempfile"); + let path = file.path().to_str().unwrap().to_owned(); + let parent = std::path::Path::new(&path).parent().unwrap().to_str().unwrap().to_owned(); + let output = sandlock_bin() + .args(["learn", "--", "sh", "-c", &format!("rm {path}")]) + .output() + .expect("failed to run sandlock learn"); + assert!(output.status.success(), + "sandlock learn failed: stderr={}", String::from_utf8_lossy(&output.stderr)); + let stdout = String::from_utf8_lossy(&output.stdout); + let write_line = stdout.lines().find(|l| l.starts_with("write = [")).unwrap_or(""); + assert!(write_line.contains(&parent), + "expected parent {parent} in write = [...], got: {write_line}"); + assert!(std::path::Path::new(&path).exists(), "COW isolation failed: file was deleted on real FS"); +} + +/// rename records parent dirs of both old and new path (RENAME_OLD + RENAME_NEW are dir rights). +/// Cross-directory rename so both /var/tmp and /tmp appear in write. +#[test] +fn test_learn_captures_rename() { + let src = tempfile::NamedTempFile::new_in("/var/tmp").expect("tempfile in /var/tmp"); + let src_path = src.path().to_str().unwrap().to_owned(); + let dst = "/tmp/sandlock-learn-rename-dst-test"; + let cmd = format!("mv {src_path} {dst}"); + let output = sandlock_bin() + .args(["learn", "--", "sh", "-c", &cmd]) + .output() + .expect("failed to run sandlock learn"); + assert!(output.status.success(), + "sandlock learn failed: stderr={}", String::from_utf8_lossy(&output.stderr)); + let stdout = String::from_utf8_lossy(&output.stdout); + let write_line = stdout.lines().find(|l| l.starts_with("write = [")).unwrap_or(""); + assert!(write_line.contains("/var/tmp"), "expected /var/tmp (src parent) in: {write_line}"); + assert!(write_line.contains("/tmp"), "expected /tmp (dst parent) in: {write_line}"); + // COW: src file still exists, dst was not created on real FS. + assert!(src.path().exists(), "COW isolation failed: src was deleted on real FS"); + assert!(!std::path::Path::new(dst).exists(), "COW isolation failed: dst was created on real FS"); +} + +/// symlink records the parent of the created linkpath (args[2] of symlinkat), +/// NOT the parent of the target string (args[0]). +/// This verifies we read the right argument for symlinkat. +/// Uses a relative target so COW can intercept the create. +#[test] +fn test_learn_captures_symlink() { + let link = "/var/tmp/sandlock-learn-symlink-test"; + // Relative target so COW can intercept. Key check: /tmp (target's dir) must NOT appear + // as write -- only /var/tmp (the linkpath's parent) should. + let cmd = format!("ln -s hostname {link}"); + let output = sandlock_bin() + .args(["learn", "--", "sh", "-c", &cmd]) + .output() + .expect("failed to run sandlock learn"); + assert!(output.status.success(), + "sandlock learn failed: stderr={}", String::from_utf8_lossy(&output.stderr)); + let stdout = String::from_utf8_lossy(&output.stdout); + let write_line = stdout.lines().find(|l| l.starts_with("write = [")).unwrap_or(""); + assert!(write_line.contains("/var/tmp"), "expected /var/tmp (link parent) in: {write_line}"); + assert!(!std::path::Path::new(link).exists(), "COW isolation failed: symlink created on real FS"); +} + +/// hardlink records only the destination parent (MAKE_HARDLINK is a dst-dir right; +/// the source only needs read access which fs_read already grants). +#[test] +fn test_learn_captures_hardlink() { + let src = tempfile::NamedTempFile::new_in("/var/tmp").expect("tempfile in /var/tmp"); + let src_path = src.path().to_str().unwrap().to_owned(); + let dst = "/tmp/sandlock-learn-hardlink-dst-test"; + let cmd = format!("ln {src_path} {dst}"); + let output = sandlock_bin() + .args(["learn", "--", "sh", "-c", &cmd]) + .output() + .expect("failed to run sandlock learn"); + assert!(output.status.success(), + "sandlock learn failed: stderr={}", String::from_utf8_lossy(&output.stderr)); + let stdout = String::from_utf8_lossy(&output.stdout); + let write_line = stdout.lines().find(|l| l.starts_with("write = [")).unwrap_or(""); + let read_line = stdout.lines().find(|l| l.starts_with("read = [")).unwrap_or(""); + // dst parent /tmp must appear in writes (MAKE_HARDLINK is a dst-dir right). + assert!(write_line.contains("/tmp"), "expected /tmp (dst parent) in: {write_line}"); + // src parent /var/tmp must NOT appear as a write (only read access is needed for src). + assert!(!write_line.contains("/var/tmp"), "src parent /var/tmp wrongly recorded as write in: {write_line}"); + // src file must appear in reads (ln never calls open() on it, so we add it explicitly). + assert!(read_line.contains(&src_path), "expected src {src_path} in reads: {read_line}"); + assert!(!std::path::Path::new(dst).exists(), "COW isolation failed: hardlink created on real FS"); +} + +/// All filesystem mutation syscalls in one run: mkdir, unlink, rename, symlink, hardlink. +/// Verifies they are all captured without any one operation blocking the others. +#[test] +fn test_learn_captures_all_fs_mutations() { + let existing = tempfile::NamedTempFile::new_in("/var/tmp").expect("tempfile"); + let existing_path = existing.path().to_str().unwrap().to_owned(); + let newdir = "/var/tmp/sandlock-learn-allops-dir"; + let symlink = "/var/tmp/sandlock-learn-allops-link"; + let cmd = format!( + "mkdir {newdir} && rmdir {newdir} && rm {existing_path} && ln -s hostname {symlink}", + ); + let output = sandlock_bin() + .args(["learn", "--", "sh", "-c", &cmd]) + .output() + .expect("failed to run sandlock learn"); + assert!(output.status.success(), + "one or more mutations blocked: stderr={}", String::from_utf8_lossy(&output.stderr)); + let stdout = String::from_utf8_lossy(&output.stdout); + let write_line = stdout.lines().find(|l| l.starts_with("write = [")).unwrap_or(""); + assert!(write_line.contains("/var/tmp"), "expected /var/tmp in: {write_line}"); + // COW: existing file must still be present, new dir and symlink must not exist. + assert!(existing.path().exists(), "COW isolation failed: file deleted on real FS"); + assert!(!std::path::Path::new(newdir).exists(), "COW isolation failed: dir created on real FS"); + assert!(!std::path::Path::new(symlink).exists(), "COW isolation failed: symlink created on real FS"); +} + +/// truncate records the file path itself (LANDLOCK_ACCESS_FS_TRUNCATE is a file right, +/// not a directory right, so we record the file, not the parent). +#[test] +fn test_learn_captures_truncate() { + let tmp = tempfile::NamedTempFile::new().expect("tempfile"); + let path = tmp.path().to_str().unwrap().to_owned(); + let output = sandlock_bin() + .args(["learn", "--", "sh", "-c", &format!("truncate -s 0 {path}")]) + .output() + .expect("failed to run sandlock learn"); + assert!(output.status.success(), + "sandlock learn failed: stderr={}", String::from_utf8_lossy(&output.stderr)); + let stdout = String::from_utf8_lossy(&output.stdout); + let write_line = stdout.lines().find(|l| l.starts_with("write = [")).unwrap_or(""); + assert!(write_line.contains(&path), + "expected file path {path} in write = [...], got: {write_line}"); +} + +/// End-to-end write round-trip: learn captures write path, run actually writes the file. +/// During learn, COW intercepts the write (file not created on real FS). +/// During run, the profile grants write access to parent dir, so the file is created for real. +#[test] +fn test_learn_then_run_write() { + let profile = tempfile::NamedTempFile::new().expect("tempfile"); + let profile_path = profile.path().to_str().unwrap().to_owned(); + let write_path = "/var/tmp/sandlock-learn-run-write-test.txt"; + let _ = std::fs::remove_file(write_path); // clean state + + // No pre-creation needed: learn collapses new-file creates to the parent directory, + // so sandlock run gets write access to the directory and can create the file. + let learn = sandlock_bin() + .args(["learn", "-o", &profile_path, "--", "sh", "-c", &format!("echo hello > {write_path}")]) + .output() + .expect("failed to run sandlock learn"); + assert!(learn.status.success() || learn.status.code() == Some(2), + "learn failed unexpectedly: {}", String::from_utf8_lossy(&learn.stderr)); + assert!(!std::path::Path::new(write_path).exists(), "COW isolation failed during learn"); + + let run = sandlock_bin() + .args(["run", "--profile-file", &profile_path, "--", "sh", "-c", &format!("echo hello > {write_path}")]) + .output() + .expect("failed to run sandlock run"); + assert!(run.status.success(), "run failed: {}", String::from_utf8_lossy(&run.stderr)); + assert_eq!(std::fs::read_to_string(write_path).unwrap_or_default().trim(), "hello", "file not written during run"); + let _ = std::fs::remove_file(write_path); +} + + +/// `sandlock learn` must record observed TCP connections under `[network] allow`. +/// Binds a real listener so the connect succeeds cleanly. +#[test] +fn test_learn_captures_net_connect() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + // Accept one connection so the child doesn't hang waiting for handshake. + let _t = std::thread::spawn(move || { let _ = listener.accept(); }); + + let script = format!( + "import socket; s=socket.socket(); s.connect(('127.0.0.1',{port})); s.close()" + ); + let output = sandlock_bin() + .args(["learn", "--", "python3", "-c", &script]) + .output() + .expect("failed to run sandlock learn"); + assert!( + output.status.success(), + "sandlock learn failed: stderr={}", + String::from_utf8_lossy(&output.stderr), + ); + let stdout = String::from_utf8_lossy(&output.stdout); + let expected = format!("127.0.0.1:{port}"); + assert!( + stdout.contains(&expected), + "expected {expected} in network output, got:\n{stdout}", + ); + let net_line = stdout.lines().find(|l| l.starts_with("allow = [")).unwrap_or(""); + assert!( + net_line.contains(&expected), + "expected {expected} under [network] allow = [...], got: {net_line}", + ); +} + +/// `sandlock learn` must capture reads done via the `openat2` syscall (not just +/// `openat`). +#[test] +fn test_learn_captures_openat2() { + // SYS_openat2 = 437 on x86_64; struct open_how { u64 flags; u64 mode; u64 resolve; } + // class can't follow ';' in Python one-liners; use embedded newlines. + let script = concat!( + "import ctypes, os\n", + "libc = ctypes.CDLL(None)\n", + "class How(ctypes.Structure):\n", + " _fields_ = [('f',ctypes.c_uint64),('m',ctypes.c_uint64),('r',ctypes.c_uint64)]\n", + "how = How(f=os.O_RDONLY)\n", + "fd = libc.syscall(437, -100, b'/etc/hostname', ctypes.byref(how), ctypes.sizeof(how))\n", + "os.read(fd, 4); os.close(fd)", + ); + let output = sandlock_bin() + .args(["learn", "--", "python3", "-c", script]) + .output() + .expect("failed to run sandlock learn"); + assert!( + output.status.success(), + "sandlock learn failed: stderr={}", + String::from_utf8_lossy(&output.stderr), + ); + let stdout = String::from_utf8_lossy(&output.stdout); + let read_line = stdout.lines().find(|l| l.starts_with("read = [")).unwrap_or(""); + assert!( + read_line.contains("/etc/hostname"), + "expected /etc/hostname under read = [...] (via openat2), got: {read_line}", + ); +} + +/// `sandlock learn` must record UDP sendto destinations under `[network] allow` +/// with a `udp://` scheme. +#[test] +fn test_learn_captures_udp_sendto() { + let sock = std::net::UdpSocket::bind("127.0.0.1:0").unwrap(); + let port = sock.local_addr().unwrap().port(); + + let script = format!( + "import socket; s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM); \ + s.sendto(b'hi',('127.0.0.1',{port})); s.close()" + ); + let output = sandlock_bin() + .args(["learn", "--", "python3", "-c", &script]) + .output() + .expect("failed to run sandlock learn"); + assert!( + output.status.success(), + "sandlock learn failed: stderr={}", + String::from_utf8_lossy(&output.stderr), + ); + let stdout = String::from_utf8_lossy(&output.stdout); + let expected = format!("udp://127.0.0.1:{port}"); + assert!( + stdout.contains(&expected), + "expected {expected} in network output, got:\n{stdout}", + ); +} + +/// `sandlock learn` must record UDP sendmsg destinations under `[network] allow` +/// with a `udp://` scheme. Uses Python's `socket.sendmsg()` which invokes the +/// sendmsg syscall (not sendto), verifying the msghdr.msg_name extraction path. +#[test] +fn test_learn_captures_udp_sendmsg() { + let sock = std::net::UdpSocket::bind("127.0.0.1:0").unwrap(); + let port = sock.local_addr().unwrap().port(); + + let script = format!( + "import socket; s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM); \ + s.sendmsg([b'hi'],[],0,('127.0.0.1',{port})); s.close()" + ); + let output = sandlock_bin() + .args(["learn", "--", "python3", "-c", &script]) + .output() + .expect("failed to run sandlock learn"); + assert!( + output.status.success(), + "sandlock learn failed: stderr={}", + String::from_utf8_lossy(&output.stderr), + ); + let stdout = String::from_utf8_lossy(&output.stdout); + let expected = format!("udp://127.0.0.1:{port}"); + assert!( + stdout.contains(&expected), + "expected {expected} in network output, got:\n{stdout}", + ); +} + +/// End-to-end network round-trip: learn captures a TCP connection, run allows it. +/// A single listener accepts two connections, one from learn, one from run. +#[test] +fn test_learn_then_run_network() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + std::thread::spawn(move || { let _ = listener.accept(); let _ = listener.accept(); }); + + let profile = tempfile::NamedTempFile::new().expect("tempfile"); + let profile_path = profile.path().to_str().unwrap().to_owned(); + let script = format!("import socket; s=socket.socket(); s.connect(('127.0.0.1',{port})); s.close()"); + + let learn = sandlock_bin() + .args(["learn", "-o", &profile_path, "--", "python3", "-c", &script]) + .output() + .expect("failed to run sandlock learn"); + assert!(learn.status.success(), "learn failed: {}", String::from_utf8_lossy(&learn.stderr)); + + let run = sandlock_bin() + .args(["run", "--profile-file", &profile_path, "--", "python3", "-c", &script]) + .output() + .expect("failed to run sandlock run"); + assert!(run.status.success(), "run failed: {}", String::from_utf8_lossy(&run.stderr)); +} + +/// `--user N:N` maps the sandbox to UID `N` via an unprivileged /// user namespace, even when the host UID is non-zero. This is the only /// remaining `CLONE_NEWUSER` site after the overlayfs backend removal; /// the test guards against accidentally tearing it out. @@ -311,6 +753,35 @@ fn test_uid_mapping_fakes_root() { ); } +/// Verify that `sandlock learn` populates `[limits]` with memory, processes, +/// and open_files when the workload runs long enough for the sampler to capture +/// resource peaks. +#[test] +fn test_learn_captures_resource_limits() { + let output = sandlock_bin() + .args(["learn", "--", "sleep", "0.2"]) + .output() + .expect("failed to run sandlock learn"); + assert!( + output.status.success(), + "sandlock learn failed: stderr={}", + String::from_utf8_lossy(&output.stderr), + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + stdout.contains("memory = \""), + "expected memory limit in learn output, got:\n{stdout}", + ); + assert!( + stdout.contains("processes = "), + "expected processes limit in learn output, got:\n{stdout}", + ); + assert!( + stdout.contains("open_files = "), + "expected open_files limit in learn output, got:\n{stdout}", + ); +} + #[test] fn test_uid_mapping_arbitrary_uid() { // Arbitrary --user value should also map cleanly (not just 0). diff --git a/crates/sandlock-core/src/policy_fn.rs b/crates/sandlock-core/src/policy_fn.rs index 2b96f0bf..3949c296 100644 --- a/crates/sandlock-core/src/policy_fn.rs +++ b/crates/sandlock-core/src/policy_fn.rs @@ -105,6 +105,18 @@ pub struct SyscallEvent { pub argv: Option>, /// Whether the supervisor denied this syscall. pub denied: bool, + /// Resolved absolute path for file syscalls (openat, execve/execveat, + /// mkdirat, unlinkat, symlinkat, truncate, renameat2 src, linkat src). + /// Read from child user memory, not TOCTOU-safe for enforcement but + /// sufficient for learn-mode observation. + /// `None` for non-file syscalls or when resolution fails. + pub path: Option, + /// Second resolved path for two-path syscalls (renameat2 dst, linkat dst). + /// `None` for single-path syscalls. + pub path2: Option, + /// Open flags for openat (the `flags` argument, e.g. `O_RDONLY`, + /// `O_WRONLY`, `O_CREAT`). `None` for non-openat syscalls. + pub flags: Option, } impl SyscallEvent { @@ -483,6 +495,9 @@ mod tests { size: None, argv: Some(vec!["python3".into(), "-c".into(), "print(1)".into()]), denied: false, + path: None, + path2: None, + flags: None, }; assert!(event.argv_contains("python3")); assert!(event.argv_contains("-c")); @@ -502,6 +517,9 @@ mod tests { size: None, argv: None, denied: false, + path: None, + path2: None, + flags: None, }; assert!(!event.argv_contains("anything")); } diff --git a/crates/sandlock-core/src/profile.rs b/crates/sandlock-core/src/profile.rs index 065c6dd2..1640abe4 100644 --- a/crates/sandlock-core/src/profile.rs +++ b/crates/sandlock-core/src/profile.rs @@ -1,6 +1,6 @@ use crate::sandbox::{ByteSize, Sandbox}; use crate::error::SandlockError; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use std::path::PathBuf; use std::collections::HashMap; use std::time::SystemTime; @@ -14,67 +14,104 @@ pub struct ProgramSpec { } /// Top-level profile input. Each section maps to one schema section. -#[derive(Debug, Clone, Default, Deserialize, PartialEq)] +#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)] #[serde(deny_unknown_fields, default)] pub struct ProfileInput { + #[serde(skip_serializing_if = "is_default")] pub config: ConfigSection, + #[serde(skip_serializing_if = "is_default")] pub determinism: DeterminismSection, + #[serde(skip_serializing_if = "is_default")] pub program: ProgramSection, + #[serde(skip_serializing_if = "is_default")] pub filesystem: FilesystemSection, + #[serde(skip_serializing_if = "is_default")] pub network: NetworkSection, + #[serde(skip_serializing_if = "is_default")] pub http: HttpSection, + #[serde(skip_serializing_if = "is_default")] pub syscalls: SyscallsSection, + #[serde(skip_serializing_if = "is_default")] pub limits: LimitsSection, } +fn is_false(b: &bool) -> bool { !b } +fn is_default(v: &T) -> bool { *v == T::default() } + // Field names follow the schema vocabulary and match `Sandbox`'s field names 1:1. -#[derive(Debug, Clone, Default, Deserialize, PartialEq)] +#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)] #[serde(deny_unknown_fields, default)] pub struct ConfigSection { + #[serde(skip_serializing_if = "Option::is_none")] pub http_ca: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub http_key: Option, + #[serde(skip_serializing_if = "Vec::is_empty")] pub http_inject_ca: Vec, + #[serde(skip_serializing_if = "Option::is_none")] pub http_ca_out: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub fs_storage: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub workdir: Option, } -#[derive(Debug, Clone, Default, Deserialize, PartialEq)] +#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)] #[serde(deny_unknown_fields, default)] pub struct DeterminismSection { + #[serde(skip_serializing_if = "Option::is_none")] pub random_seed: Option, /// RFC3339 timestamp string. Maps to `Sandbox::time_start`. + #[serde(skip_serializing_if = "Option::is_none")] pub time_start: Option, + #[serde(skip_serializing_if = "is_false")] pub deterministic_dirs: bool, + #[serde(skip_serializing_if = "is_false")] pub no_randomize_memory: bool, } -#[derive(Debug, Clone, Default, Deserialize, PartialEq)] +#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)] #[serde(deny_unknown_fields, default)] pub struct ProgramSection { + #[serde(skip_serializing_if = "Option::is_none")] pub exec: Option, + #[serde(skip_serializing_if = "Vec::is_empty")] pub args: Vec, + #[serde(skip_serializing_if = "HashMap::is_empty")] pub env: HashMap, + #[serde(skip_serializing_if = "Option::is_none")] pub cwd: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub uid: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub gid: Option, + #[serde(skip_serializing_if = "is_false")] pub clean_env: bool, + #[serde(skip_serializing_if = "is_false")] pub no_coredump: bool, + #[serde(skip_serializing_if = "is_false")] pub no_huge_pages: bool, } -#[derive(Debug, Clone, Default, Deserialize, PartialEq)] +#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)] #[serde(deny_unknown_fields, default)] pub struct FilesystemSection { + #[serde(skip_serializing_if = "Vec::is_empty")] pub read: Vec, + #[serde(skip_serializing_if = "Vec::is_empty")] pub write: Vec, + #[serde(skip_serializing_if = "Vec::is_empty")] pub deny: Vec, + #[serde(skip_serializing_if = "Option::is_none")] pub chroot: Option, /// Each entry has the form `"VIRTUAL:HOST"`, matching `--fs-mount` syntax. + #[serde(skip_serializing_if = "Vec::is_empty")] pub mount: Vec, /// One of `"commit"`, `"abort"`, `"keep"`. Maps to `Sandbox::on_exit`. + #[serde(skip_serializing_if = "Option::is_none")] pub on_exit: Option, /// One of `"commit"`, `"abort"`, `"keep"`. Maps to `Sandbox::on_error`. + #[serde(skip_serializing_if = "Option::is_none")] pub on_error: Option, } @@ -82,61 +119,86 @@ pub struct FilesystemSection { /// quoted string holding a comma list and/or `lo-hi` range (`"9000-9005"`). /// The untagged form lets a TOML array mix the two, e.g. /// `allow_bind = [8080, "9000-9005"]`. -#[derive(Debug, Clone, Deserialize, PartialEq)] +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] #[serde(untagged)] pub enum PortSpec { Port(u16), Spec(String), } -#[derive(Debug, Clone, Default, Deserialize, PartialEq)] +#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)] #[serde(deny_unknown_fields, default)] pub struct NetworkSection { + #[serde(skip_serializing_if = "Vec::is_empty")] pub allow_bind: Vec, + #[serde(skip_serializing_if = "Vec::is_empty")] pub deny_bind: Vec, + #[serde(skip_serializing_if = "Vec::is_empty")] pub allow: Vec, + #[serde(skip_serializing_if = "Vec::is_empty")] pub deny: Vec, + #[serde(skip_serializing_if = "is_false")] pub port_remap: bool, } -#[derive(Debug, Clone, Default, Deserialize, PartialEq)] +#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)] #[serde(deny_unknown_fields, default)] pub struct HttpSection { + #[serde(skip_serializing_if = "Vec::is_empty")] pub ports: Vec, + #[serde(skip_serializing_if = "Vec::is_empty")] pub allow: Vec, + #[serde(skip_serializing_if = "Vec::is_empty")] pub deny: Vec, } -#[derive(Debug, Clone, Default, Deserialize, PartialEq)] +#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)] #[serde(deny_unknown_fields, default)] pub struct SyscallsSection { + #[serde(skip_serializing_if = "Vec::is_empty")] pub extra_allow: Vec, + #[serde(skip_serializing_if = "Vec::is_empty")] pub extra_deny: Vec, } // Field names drop the `max_` prefix that `Sandbox` uses (`memory`, not // `max_memory`) — the section name `[limits]` makes the prefix redundant. // `parse_input` maps each of these to the corresponding `Sandbox::max_*` field. -#[derive(Debug, Clone, Default, Deserialize, PartialEq)] +#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)] #[serde(deny_unknown_fields, default)] pub struct LimitsSection { /// `ByteSize` string, e.g. `"512M"` (suffixes K/M/G only; IEC `MiB`/`GiB` /// not yet supported). Maps to `Sandbox::max_memory`. + #[serde(skip_serializing_if = "Option::is_none")] pub memory: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub processes: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub open_files: Option, /// CPU cap as a percentage (0–100). Maps to `Sandbox::max_cpu`. + #[serde(skip_serializing_if = "Option::is_none")] pub cpu: Option, /// `ByteSize` string, e.g. `"256M"` (suffixes K/M/G only; IEC `MiB`/`GiB` /// not yet supported). Maps to `Sandbox::max_disk`. + #[serde(skip_serializing_if = "Option::is_none")] pub disk: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub gpu_devices: Option>, + #[serde(skip_serializing_if = "Option::is_none")] pub cpu_cores: Option>, + #[serde(skip_serializing_if = "Option::is_none")] pub num_cpus: Option, } /// Convert a parsed `ProfileInput` into a `(Sandbox, ProgramSpec)` pair. /// +impl ProfileInput { + /// Serialize the profile to a TOML string. + pub fn to_toml(&self) -> Result { + toml::to_string(self) + } +} + /// Forwards each schema section's fields to the corresponding `SandboxBuilder` /// method calls. The two private helpers (`parse_branch_action`, /// `parse_mount_spec`) handle string-to-typed-value conversions for fields diff --git a/crates/sandlock-core/src/sandbox/builder.rs b/crates/sandlock-core/src/sandbox/builder.rs index 0cdd3b70..c0966d02 100644 --- a/crates/sandlock-core/src/sandbox/builder.rs +++ b/crates/sandlock-core/src/sandbox/builder.rs @@ -197,6 +197,7 @@ pub struct SandboxBuilder { // COW fork work function: runs in each COW clone. #[cfg_attr(feature = "cli", clap(skip))] pub(crate) work_fn: Option>, + } impl std::fmt::Debug for SandboxBuilder { diff --git a/crates/sandlock-core/src/seccomp/notif.rs b/crates/sandlock-core/src/seccomp/notif.rs index aeac354a..7647d183 100644 --- a/crates/sandlock-core/src/seccomp/notif.rs +++ b/crates/sandlock-core/src/seccomp/notif.rs @@ -1253,7 +1253,7 @@ fn maybe_patch_vdso(pid: i32, procfs: &mut super::state::ProcfsState, policy: &N /// Map a syscall number to a human-readable name for the policy callback. fn syscall_name(nr: i64) -> &'static str { match nr { - n if n == libc::SYS_openat => "openat", + n if n == libc::SYS_openat || n == arch::SYS_OPENAT2 => "openat", n if n == libc::SYS_connect => "connect", n if n == libc::SYS_sendto => "sendto", n if n == libc::SYS_sendmsg => "sendmsg", @@ -1271,6 +1271,17 @@ fn syscall_name(nr: i64) -> &'static str { n if n == libc::SYS_getrandom => "getrandom", n if n == libc::SYS_unlinkat => "unlinkat", n if n == libc::SYS_mkdirat => "mkdirat", + n if n == libc::SYS_renameat2 => "renameat2", + n if n == libc::SYS_linkat => "linkat", + n if n == libc::SYS_symlinkat => "symlinkat", + n if n == libc::SYS_truncate => "truncate", + // Legacy single-path variants (x86_64 only). + n if Some(n) == arch::sys_mkdir() => "mkdirat", + n if Some(n) == arch::sys_rmdir() => "unlinkat", + n if Some(n) == arch::sys_unlink() => "unlinkat", + n if Some(n) == arch::sys_symlink() => "symlinkat", + n if Some(n) == arch::sys_link() => "linkat", + n if Some(n) == arch::sys_rename() => "renameat2", _ => "unknown", } } @@ -1279,7 +1290,7 @@ fn syscall_name(nr: i64) -> &'static str { fn syscall_category(nr: i64) -> crate::policy_fn::SyscallCategory { use crate::policy_fn::SyscallCategory; match nr { - n if n == libc::SYS_openat || n == libc::SYS_unlinkat + n if n == libc::SYS_openat || n == arch::SYS_OPENAT2 || n == libc::SYS_unlinkat || n == libc::SYS_mkdirat || n == libc::SYS_renameat2 || n == libc::SYS_symlinkat || n == libc::SYS_linkat || n == libc::SYS_fchmodat || n == libc::SYS_fchownat @@ -1394,10 +1405,43 @@ fn resolve_path_for_notif(notif: &SeccompNotif, notif_fd: RawFd) -> Option { + let path = read_path_for_event(notif, notif.data.args[1], notif_fd)?; + resolve_at_path_for_event(notif, notif.data.args[0] as i64, &path) + } + // unlinkat(dirfd, pathname, flags) + n if n == libc::SYS_unlinkat => { + let path = read_path_for_event(notif, notif.data.args[1], notif_fd)?; + resolve_at_path_for_event(notif, notif.data.args[0] as i64, &path) + } + // symlinkat(target, newdirfd, linkpath): args[2] is the created symlink path. + // args[0] is the target string (not a filesystem path to grant rights on). + n if n == libc::SYS_symlinkat => { + let path = read_path_for_event(notif, notif.data.args[2], notif_fd)?; + resolve_at_path_for_event(notif, notif.data.args[1] as i64, &path) + } + // truncate(path, length): absolute path, no dirfd. + n if n == libc::SYS_truncate => { + let path = read_path_for_event(notif, notif.data.args[0], notif_fd)?; + resolve_at_path_for_event(notif, libc::AT_FDCWD as i64, &path) + } + // Legacy single-path variants: mkdir, rmdir, unlink share args[0]=path. + n if Some(n) == arch::sys_mkdir() || Some(n) == arch::sys_rmdir() + || Some(n) == arch::sys_unlink() => + { + let path = read_path_for_event(notif, notif.data.args[0], notif_fd)?; + resolve_at_path_for_event(notif, libc::AT_FDCWD as i64, &path) + } + // symlink(target, linkpath): args[1] is the created symlink path. + n if Some(n) == arch::sys_symlink() => { + let path = read_path_for_event(notif, notif.data.args[1], notif_fd)?; + resolve_at_path_for_event(notif, libc::AT_FDCWD as i64, &path) + } + // symlinkat/symlink intentionally omitted from deny-path gating: creating + // a symlink does not access its target, so there is nothing to gate here. + // Any later open through the symlink resolves to the real target and is + // denied race-free on the open path (issue #111). See `on_behalf_open_for_deny`. // link(oldpath, newpath) — legacy, AT_FDCWD implied for both n if Some(n) == arch::sys_link() => { let path = read_path_for_event(notif, notif.data.args[0], notif_fd)?; @@ -1551,6 +1595,9 @@ async fn emit_policy_event( let mut port = None; let mut size = None; let mut argv = None; + let mut path = None; + let mut path2 = None; + let mut flags = None; if !denied && (nr == libc::SYS_execve || nr == libc::SYS_execveat) { // execve(pathname, argv, envp): args[1] = argv ptr @@ -1561,22 +1608,66 @@ async fn emit_policy_event( notif.data.args[1] }; argv = read_argv_for_event(notif, argv_ptr, notif_fd); + path = resolve_path_for_notif(notif, notif_fd) + .map(std::path::PathBuf::from); + } + + // connect(fd, addr, addrlen) and bind(fd, addr, addrlen): sockaddr in args[1]/args[2]. + if nr == libc::SYS_connect || nr == libc::SYS_bind { + let (h, p) = read_sockaddr_for_event(notif, notif.data.args[1], notif.data.args[2] as usize, notif_fd); + host = h; + port = p; } - if nr == libc::SYS_connect || nr == libc::SYS_sendto || nr == libc::SYS_bind { - // connect(fd, addr, addrlen): args[1]=addr, args[2]=len - let addr_ptr = notif.data.args[1]; - let addr_len = notif.data.args[2] as usize; - let (h, p) = read_sockaddr_for_event(notif, addr_ptr, addr_len, notif_fd); + // sendto(fd, buf, len, flags, addr, addrlen): sockaddr in args[4]/args[5]. + if nr == libc::SYS_sendto { + let (h, p) = read_sockaddr_for_event(notif, notif.data.args[4], notif.data.args[5] as usize, notif_fd); host = h; port = p; } + // sendmsg/sendmmsg: sockaddr is inside struct msghdr at args[1]. + // msghdr layout: msg_name ptr (u64 @ offset 0), msg_namelen u32 (@ offset 8). + // For sendmmsg the first mmsghdr entry's msghdr starts at offset 0, same layout. + if nr == libc::SYS_sendmsg || nr == libc::SYS_sendmmsg { + if let Ok(hdr) = read_child_mem(notif_fd, notif.id, notif.pid, notif.data.args[1], 12) { + if hdr.len() >= 12 { + let name_ptr = u64::from_ne_bytes(hdr[0..8].try_into().unwrap()); + let name_len = u32::from_ne_bytes(hdr[8..12].try_into().unwrap()) as usize; + let (h, p) = read_sockaddr_for_event(notif, name_ptr, name_len, notif_fd); + host = h; + port = p; + } + } + } + if nr == libc::SYS_mmap { // mmap(addr, length, ...): args[1] = length size = Some(notif.data.args[1]); } + // openat/openat2/open: resolved path + flags. + if nr == libc::SYS_openat || nr == arch::SYS_OPENAT2 || Some(nr) == arch::sys_open() { + if let Some(open_args) = decode_open_args(notif, notif_fd) { + path = resolve_path_for_notif(notif, notif_fd) + .map(std::path::PathBuf::from); + flags = Some(open_args.flags); + } + } + + // mkdirat, unlinkat, symlinkat, truncate: single resolved path. + // renameat2, linkat (and their legacy equivalents): src path + dst path2. + let is_fs_mutating = nr == libc::SYS_mkdirat || nr == libc::SYS_unlinkat + || nr == libc::SYS_symlinkat || nr == libc::SYS_truncate + || nr == libc::SYS_renameat2 || nr == libc::SYS_linkat + || Some(nr) == arch::sys_mkdir() || Some(nr) == arch::sys_rmdir() + || Some(nr) == arch::sys_unlink() || Some(nr) == arch::sys_symlink() + || Some(nr) == arch::sys_link() || Some(nr) == arch::sys_rename(); + if is_fs_mutating { + path = resolve_path_for_notif(notif, notif_fd).map(std::path::PathBuf::from); + path2 = resolve_second_path_for_notif(notif, notif_fd).map(std::path::PathBuf::from); + } + let event = crate::policy_fn::SyscallEvent { syscall: name.to_string(), category, @@ -1587,6 +1678,9 @@ async fn emit_policy_event( size, argv, denied, + path, + path2, + flags, }; // Hold syscalls where the callback's verdict matters. diff --git a/crates/sandlock-core/src/seccomp_plan.rs b/crates/sandlock-core/src/seccomp_plan.rs index 8ffaaa21..6ea51946 100644 --- a/crates/sandlock-core/src/seccomp_plan.rs +++ b/crates/sandlock-core/src/seccomp_plan.rs @@ -354,8 +354,11 @@ pub(crate) fn notif_syscalls_resolved(resolved: &ResolvedSandbox) -> Vec { } // Dynamic policy callback: intercept key syscalls for event emission. + // Also includes the legacy open(2) syscall (absent on some arches) so + // path events fire on kernels that still dispatch it. if features.policy_fn { nrs.extend(POLICY_EVENT_SYSCALLS); + nrs.push_optional(arch::sys_open()); } // Port remapping