use std::ffi::OsString; use std::fs; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; use std::process::{Child, Command, Stdio}; use nix::sched::{CloneFlags, unshare}; use nix::sys::signal::{Signal, kill}; use nix::unistd::Pid; use super::SandboxError; pub const NET_HELPER_CMD: &str = "__sandbox-net"; pub const DNS_ADDR: &str = "192.0.2.3"; const PASTA_PATHS: [&str; 3] = ["/usr/bin/pasta", "/usr/local/bin/pasta", "/bin/pasta"]; const IP_DIRS: [&str; 4] = ["/usr/sbin", "/usr/bin", "/sbin", "/bin"]; const BLOCKED: [&str; 9] = [ "0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "169.254.0.0/16", "172.16.0.0/12", "192.168.0.0/16", "198.18.0.0/15", "224.0.0.0/4", "240.0.0.0/4", ]; pub fn pid_file(job_dir: &Path) -> PathBuf { job_dir.join("pasta.pid") } pub fn find_pasta() -> Option { PASTA_PATHS.iter().map(PathBuf::from).find(|p| p.is_file()) } pub struct PendingNet { child: Child, } pub fn prepare(pasta: &Path, pid_file: &Path) -> Result { let exe = std::env::current_exe().map_err(SandboxError::io("cannot find the runner binary"))?; let child = Command::new(exe) .arg(NET_HELPER_CMD) .arg(pasta) .arg(std::process::id().to_string()) .arg(pid_file) .stdin(Stdio::piped()) .stdout(Stdio::null()) .stderr(Stdio::piped()) .spawn() .map_err(SandboxError::io("cannot start the network helper"))?; Ok(PendingNet { child }) } impl PendingNet { pub fn attach(mut self) -> Result<(), SandboxError> { let Some(mut go) = self.child.stdin.take() else { self.stop(); return Err(SandboxError::Setup( "no stdin for the network helper".into(), )); }; let signalled = unshare(CloneFlags::CLONE_NEWNET) .map_err(|e| SandboxError::Setup(format!("cannot create a network namespace: {e}"))) .and_then(|()| { go.write_all(b"1") .map_err(SandboxError::io("cannot signal the network helper")) }); drop(go); if let Err(e) = signalled { self.stop(); return Err(e); } let output = self .child .wait_with_output() .map_err(SandboxError::io("waiting for the network helper"))?; if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); let detail = match stderr.trim() { "" => output.status.to_string(), text => text.to_owned(), }; return Err(SandboxError::Setup(format!("cannot start pasta: {detail}"))); } configure_routes() } fn stop(&mut self) { let _ = self.child.kill(); let _ = self.child.wait(); } } fn configure_routes() -> Result<(), SandboxError> { let ip = IP_DIRS .iter() .map(|dir| Path::new(dir).join("ip")) .find(|p| p.is_file()) .ok_or_else(|| SandboxError::Setup("`ip` (iproute2) is not installed".into()))?; let mut script = String::from("link set lo up\n"); for range in BLOCKED { script.push_str(&format!("route add blackhole {range}\n")); } let mut child = Command::new(ip) .args(["-batch", "-"]) .stdin(Stdio::piped()) .stdout(Stdio::null()) .stderr(Stdio::piped()) .spawn() .map_err(SandboxError::io("cannot run ip"))?; if let Some(mut stdin) = child.stdin.take() { stdin .write_all(script.as_bytes()) .map_err(SandboxError::io("cannot write to ip"))?; } let output = child .wait_with_output() .map_err(SandboxError::io("waiting for ip"))?; if output.status.success() { Ok(()) } else { Err(SandboxError::Setup(format!( "cannot set up the job's routes: {}", String::from_utf8_lossy(&output.stderr).trim() ))) } } pub fn stop_pasta(pid_file: &Path) { let Ok(text) = fs::read_to_string(pid_file) else { return; }; let Ok(pid) = text.trim().parse::() else { return; }; if pid <= 1 { return; } let comm = fs::read_to_string(format!("/proc/{pid}/comm")).unwrap_or_default(); if matches!(comm.trim(), "pasta" | "passt" | "pasta.avx2" | "passt.avx2") { let _ = kill(Pid::from_raw(pid), Signal::SIGTERM); } } pub fn net_helper_main(args: &[OsString]) -> i32 { match net_helper(args) { Ok(()) => 0, Err(message) => { super::report(message); 125 } } } fn net_helper(args: &[OsString]) -> Result<(), String> { let [pasta, parent, pid_file] = args else { return Err("usage: __sandbox-net ".into()); }; let parent: u32 = parent .to_str() .and_then(|s| s.parse().ok()) .filter(|&p| p > 1) .ok_or("parent must be a pid")?; let mut byte = [0u8; 1]; loop { match io::stdin().lock().read(&mut byte) { Ok(1) => break, Ok(_) => return Err("network setup was cancelled".into()), Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, Err(e) => return Err(format!("cannot read from the parent: {e}")), } } let output = Command::new(pasta) .args(pasta_args(parent, Path::new(pid_file))) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::piped()) .output() .map_err(|e| format!("cannot run pasta: {e}"))?; if output.status.success() { Ok(()) } else { Err(format!( "pasta failed ({}): {}", output.status, String::from_utf8_lossy(&output.stderr).trim() )) } } fn pasta_args(parent: u32, pid_file: &Path) -> Vec { let mut args: Vec = [ "-q", "--config-net", "-4", "-a", "192.0.2.2", "-n", "24", "-g", "192.0.2.1", "--no-map-gw", "--dns-forward", DNS_ADDR, "-t", "none", "-u", "none", "-T", "none", "-U", "none", "--no-netns-quit", "--pid", ] .into_iter() .map(OsString::from) .collect(); args.push(pid_file.into()); args.push("--userns".into()); args.push(format!("/proc/{parent}/ns/user").into()); args.push("--netns".into()); args.push(format!("/proc/{parent}/ns/net").into()); args }