From 570e5920c047dc7c86c82577ac025a151536fc00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 18:38:57 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=92=20harden:=20a=20builtin=20job=20wi?= =?UTF-8?q?th=20network=20=3D=20true=20gets=20its=20own=20network=20namesp?= =?UTF-8?q?ace=20through=20pasta=20(internet=20yes;=20the=20runner's=20loc?= =?UTF-8?q?alhost,=20private=20and=20link-local=20ranges=20no;=20IPv6=20no?= =?UTF-8?q?ne),=20and=20shares=20the=20host's=20only=20when=20pasta=20is?= =?UTF-8?q?=20missing,=20saying=20so=20in=20the=20job=20log;=20a=20job=20m?= =?UTF-8?q?ay=20fill=20limits.job=5Fdisk=5Fgb=20(20,=20on=20the=20runner?= =?UTF-8?q?=20page)=20of=20disk=20before=20it=20is=20stopped;=20the=20runn?= =?UTF-8?q?er=20removes=20leftover=20job=20dirs,=20cgroups,=20pasta=20proc?= =?UTF-8?q?esses=20and=20workspaces=20at=20startup?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-core/src/ci.rs | 5 + crates/forge-runner/src/check.rs | 1 + crates/forge-runner/src/cli.rs | 3 + crates/forge-runner/src/config.rs | 14 + crates/forge-runner/src/disk.rs | 64 +++++ crates/forge-runner/src/executor.rs | 161 ++++++++++- crates/forge-runner/src/lib.rs | 1 + crates/forge-runner/src/sandbox/helper.rs | 25 +- crates/forge-runner/src/sandbox/mod.rs | 9 +- crates/forge-runner/src/sandbox/net.rs | 264 ++++++++++++++++++ crates/forge-runner/src/sandbox/spec.rs | 25 +- .../forge-runner/tests/integration/builtin.rs | 27 ++ .../forge-runner/tests/integration/sandbox.rs | 1 + crates/forge-web/src/pages/admin_runners.rs | 10 + docs/ci.md | 23 +- 15 files changed, 613 insertions(+), 20 deletions(-) create mode 100644 crates/forge-runner/src/disk.rs create mode 100644 crates/forge-runner/src/sandbox/net.rs diff --git a/crates/forge-core/src/ci.rs b/crates/forge-core/src/ci.rs index 11e72b5..0028c13 100644 --- a/crates/forge-core/src/ci.rs +++ b/crates/forge-core/src/ci.rs @@ -245,6 +245,10 @@ pub const RUNNER_FIELDS: &[RunnerField] = &[ key: "limits.image_max_gb", kind: FieldKind::Restart, }, + RunnerField { + key: "limits.job_disk_gb", + kind: FieldKind::Restart, + }, RunnerField { key: "images.keep_days", kind: FieldKind::Restart, @@ -385,6 +389,7 @@ pub fn validate_runner_field( } "limits.pids" => int_in(raw, 1, 4_194_304, "pids"), "limits.image_max_gb" => int_in(raw, 1, 100_000, "image_max_gb"), + "limits.job_disk_gb" => int_in(raw, 0, 1_000_000, "job_disk_gb"), "images.keep_days" => int_in(raw, 0, 3650, "keep_days"), "cache_max_gib" => int_in(raw, 0, 1_000_000, "cache_max_gib"), _ => Err("this field cannot be changed from the forge".into()), diff --git a/crates/forge-runner/src/check.rs b/crates/forge-runner/src/check.rs index f371e5e..346f821 100644 --- a/crates/forge-runner/src/check.rs +++ b/crates/forge-runner/src/check.rs @@ -174,6 +174,7 @@ async fn run_probe(helper: &Path, work_dir: &Path, map: &IdMap) -> Result i32 { match args.first().map(|arg| arg.as_encoded_bytes()) { Some(b"__sandbox") => crate::sandbox::helper_main(), Some(b"__sandbox-rm") => crate::sandbox::idmap::rm_helper_main(&args[1..]), + Some(b"__sandbox-net") => crate::sandbox::net::net_helper_main(&args[1..]), Some(b"__sandbox-map") => crate::sandbox::idmap::map_helper_main(&args[1..]), Some(b"__sandbox-unpack") => crate::oci::unpack_helper_main(), _ => { @@ -265,6 +266,8 @@ async fn run(cli: Cli) -> Result> { let images = ImageStore::new(root) .with_max_unpacked_bytes(gib(cfg.limits.image_max_gb)) .with_idmap(map.clone(), helper.clone()); + // Before the first job: what an earlier run left behind. + crate::executor::sweep_leftovers(&cfg.work_dir, &map, &helper).await; let jobs_dir = cfg.work_dir.join("jobs"); let executor = BuiltinExecutor::new(images, cfg.limits.clone(), helper, jobs_dir) diff --git a/crates/forge-runner/src/config.rs b/crates/forge-runner/src/config.rs index c0d6da1..9e80ba3 100644 --- a/crates/forge-runner/src/config.rs +++ b/crates/forge-runner/src/config.rs @@ -40,6 +40,10 @@ pub struct Limits { /// The cap on the unpacked size of one image, in GB. Used by the builtin executor. #[serde(default = "default_image_max_gb")] pub image_max_gb: u64, + /// The disk one job may fill, in GB: its workspace, its `/tmp` and what it writes over the + /// image. Past it the job is stopped and fails. 0 means no cap. Used by the builtin executor. + #[serde(default = "default_job_disk_gb")] + pub job_disk_gb: u64, /// What a job that declares no `memory` reserves when it is admitted, and the floor for its /// cgroup limit. Live: an admin can change it from the forge without a restart. #[serde(default = "default_reserve_memory")] @@ -72,6 +76,7 @@ impl Default for Limits { cpus: "2".to_owned(), pids: 4096, image_max_gb: default_image_max_gb(), + job_disk_gb: default_job_disk_gb(), reserve_memory: default_reserve_memory(), memory_budget: None, memory_headroom: default_memory_headroom(), @@ -240,6 +245,10 @@ pub fn default_image_max_gb() -> u64 { 20 } +pub fn default_job_disk_gb() -> u64 { + 20 +} + impl fmt::Debug for RunnerConfig { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("RunnerConfig") @@ -330,6 +339,7 @@ impl RunnerConfig { "limits.image_max_gb".into(), json!(self.limits.image_max_gb), ); + m.insert("limits.job_disk_gb".into(), json!(self.limits.job_disk_gb)); let executor = match self.executor { ExecutorKind::Builtin => "builtin", ExecutorKind::Podman => "podman", @@ -399,6 +409,10 @@ impl RunnerConfig { .as_u64() .map(|v| self.limits.image_max_gb = v) .is_some(), + "limits.job_disk_gb" => value + .as_u64() + .map(|v| self.limits.job_disk_gb = v) + .is_some(), "images.keep_days" => value .as_u64() .and_then(|v| u32::try_from(v).ok()) diff --git a/crates/forge-runner/src/disk.rs b/crates/forge-runner/src/disk.rs new file mode 100644 index 0000000..2714c38 --- /dev/null +++ b/crates/forge-runner/src/disk.rs @@ -0,0 +1,64 @@ +//! The disk cap of a builtin job (`limits.job_disk_gb`). +//! +//! A rootless runner has no quotas, so the runner measures what the job wrote every few seconds +//! and stops it once that passes the cap. A job can overshoot by what it writes between two +//! checks. In subuid mode a dir the job made unreadable to the runner is not counted. + +use std::collections::HashSet; +use std::fs; +use std::os::unix::fs::MetadataExt; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use tokio_util::sync::CancellationToken; + +/// How often the job's disk use is measured, at most. A measurement that takes long (a huge tree) +/// spaces the next one out to four times its own length, so the walk stays a small share of the +/// runner's time. +const INTERVAL: Duration = Duration::from_secs(2); + +/// The bytes allocated under `roots`. Symlinks are not followed, and a file with several hard +/// links counts once. Entries that can't be read are skipped. +pub fn usage(roots: &[PathBuf]) -> u64 { + let mut seen = HashSet::new(); + let mut total = 0u64; + let mut stack: Vec = roots.to_vec(); + while let Some(path) = stack.pop() { + let Ok(meta) = fs::symlink_metadata(&path) else { + continue; + }; + if meta.nlink() > 1 && !meta.is_dir() && !seen.insert((meta.dev(), meta.ino())) { + continue; + } + total = total.saturating_add(meta.blocks().saturating_mul(512)); + if meta.is_dir() + && let Ok(entries) = fs::read_dir(&path) + { + stack.extend(entries.flatten().map(|entry| entry.path())); + } + } + total +} + +/// Measures `roots` about every [`INTERVAL`] until it passes `cap` bytes, then sets `over` and cancels +/// `job`. Runs until it fires or is aborted. +pub async fn watch(roots: Vec, cap: u64, job: CancellationToken, over: Arc) { + let roots = Arc::new(roots); + let mut pause = INTERVAL; + loop { + tokio::time::sleep(pause).await; + let measured = Arc::clone(&roots); + let started = Instant::now(); + let Ok(used) = tokio::task::spawn_blocking(move || usage(&measured)).await else { + return; + }; + pause = INTERVAL.max(started.elapsed() * 4); + if used > cap { + over.store(true, Ordering::SeqCst); + job.cancel(); + return; + } + } +} diff --git a/crates/forge-runner/src/executor.rs b/crates/forge-runner/src/executor.rs index 897750c..b82b6c3 100644 --- a/crates/forge-runner/src/executor.rs +++ b/crates/forge-runner/src/executor.rs @@ -15,6 +15,8 @@ use std::fs; use std::future::Future; use std::path::{Path, PathBuf}; use std::pin::Pin; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::process::{ExitStatus, Stdio}; use std::time::Duration; @@ -647,6 +649,7 @@ impl BuiltinExecutor { memory_budget, } = req; let limits = self.limits.for_builtin_job(job.memory_bytes, memory_budget); + let disk_gb = limits.job_disk_gb; if let Err(e) = validate_job_id(&job.job_id) { return error_result(e.to_string()); } @@ -672,10 +675,27 @@ impl BuiltinExecutor { .await; let job_dir = self.jobs_dir.join(&job.job_id); - // A leftover from an earlier run of this job id would hold stale overlay state. + // A leftover from an earlier run of this job id would hold stale overlay state, and maybe + // the pid of a pasta that outlived its helper. + crate::sandbox::net::stop_pasta(&crate::sandbox::net::pid_file(&job_dir)); if let Err(e) = remove_job_dir(&self.idmap, &self.helper, &job_dir).await { tracing::warn!("cannot remove stale {}: {e}", job_dir.display()); } + let pasta = if job.network { + let pasta = crate::sandbox::net::find_pasta(); + if pasta.is_none() { + let _ = logs + .send( + b"runner: pasta is not installed, so this job shares the runner's network; \ + install passt to isolate it\n" + .to_vec(), + ) + .await; + } + pasta + } else { + None + }; let request = SandboxRequest { job_id: job.job_id.clone(), rootfs: image.rootfs, @@ -685,6 +705,7 @@ impl BuiltinExecutor { env, run: job.run.clone(), network: job.network, + pasta, limits, idmap: self.idmap.clone(), }; @@ -716,6 +737,25 @@ impl BuiltinExecutor { } drop(json); + // The disk cap stops the job through its own token, so a stop for disk can be told apart + // from a cancel. + let job_cancel = cancel.child_token(); + let over_disk = Arc::new(AtomicBool::new(false)); + let disk_cap = disk_gb.saturating_mul(1 << 30); + let watcher = (disk_cap > 0).then(|| { + let job_dir = self.jobs_dir.join(&job.job_id); + let roots = vec![ + workspace.to_owned(), + job_dir.join("tmp"), + job_dir.join("overlay/upper"), + ]; + tokio::spawn(crate::disk::watch( + roots, + disk_cap, + job_cancel.clone(), + Arc::clone(&over_disk), + )) + }); let Supervised { cancelled, status, @@ -724,7 +764,7 @@ impl BuiltinExecutor { } = supervise( child, logs, - cancel, + job_cancel, Stopper::Helper { pid }, Some(JobCleanup { helper_pid: pid, @@ -735,9 +775,22 @@ impl BuiltinExecutor { }), ) .await; + if let Some(watcher) = watcher { + watcher.abort(); + } if let Some(events) = oom { oom_sink.record(events); } + if over_disk.load(Ordering::SeqCst) && !cancel.is_cancelled() { + return ExecResult { + outcome: Outcome::Failure, + exit_code: None, + message: Some(format!( + "job was stopped: it filled more than {disk_gb} GB of disk (workspace, /tmp \ + and writes over the image)" + )), + }; + } if cancelled { return cancelled_result(); } @@ -808,7 +861,7 @@ struct JobCleanup { /// Cleans up after a job's helper has exited, whatever the reason. A helper killed with SIGKILL /// cannot delete its container, so the container could otherwise keep running. This kills what is -/// left in the job cgroup, removes the cgroup, and removes the job dir. +/// left in the job cgroup, removes the cgroup, stops a leftover pasta, and removes the job dir. async fn reap_job(job: &JobCleanup) { if let Ok(relative) = job_cgroup_path(&job.job_id, job.helper_pid) { let dir = Path::new(CGROUP_ROOT).join(relative.strip_prefix("/").unwrap_or(&relative)); @@ -823,11 +876,97 @@ async fn reap_job(job: &JobCleanup) { } } } + // A helper killed with SIGKILL could not stop its pasta either. + crate::sandbox::net::stop_pasta(&crate::sandbox::net::pid_file(&job.job_dir)); if let Err(e) = remove_job_dir(&job.idmap, &job.helper, &job.job_dir).await { tracing::warn!("cannot remove {}: {e}", job.job_dir.display()); } } +/// Cleans up after an earlier run of the runner that did not get to (a crash, a SIGKILL, a power +/// cut): for every leftover `work_dir/jobs/` it stops a pasta, kills the job's cgroups and +/// removes the dir, and it removes leftover workspaces `work_dir/`. Call it at startup, +/// before any job runs. Only job ids found in this runner's own dirs are touched, so another +/// runner's jobs in a shared cgroup are left alone. +pub async fn sweep_leftovers(work_dir: &Path, map: &IdMap, helper: &Path) { + let (work_dir, map, helper) = (work_dir.to_owned(), map.clone(), helper.to_owned()); + let swept = tokio::task::spawn_blocking(move || sweep_blocking(&work_dir, &map, &helper)).await; + if let Err(e) = swept { + tracing::warn!("cannot sweep leftover jobs: {e}"); + } +} + +fn sweep_blocking(work_dir: &Path, map: &IdMap, helper: &Path) { + let jobs_dir = work_dir.join("jobs"); + let cgroup_bases: Vec = crate::sandbox::helper::job_cgroup_base() + .map(|base| { + let base = Path::new(CGROUP_ROOT).join(base.strip_prefix("/").unwrap_or(&base)); + vec![base.join(crate::sandbox::helper::BOX_NAME), base] + }) + .unwrap_or_default(); + for job_id in job_ids_in(&jobs_dir) { + let job_dir = jobs_dir.join(&job_id); + tracing::info!("removing leftover job {job_id}"); + crate::sandbox::net::stop_pasta(&crate::sandbox::net::pid_file(&job_dir)); + let prefix = format!("forge-job-{job_id}-"); + for base in &cgroup_bases { + let Ok(entries) = fs::read_dir(base) else { + continue; + }; + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(pid) = name.to_str().and_then(|n| n.strip_prefix(&prefix)) else { + continue; + }; + if pid.parse::().is_err() { + continue; + } + let dir = entry.path(); + kill_cgroup(&dir); + for _ in 0..REAP_POLLS { + if fs::remove_dir(&dir).is_ok() || !dir.exists() { + break; + } + std::thread::sleep(REAP_POLL); + } + } + } + if let Err(e) = remove_tree(map, &job_dir, helper) { + tracing::warn!("cannot remove {}: {e}", job_dir.display()); + } + } + // `work_dir` may be shared with other files (an operator could point it at a home dir), so + // only names shaped like the forge's job ids (ULIDs) count as workspaces. + for job_id in job_ids_in(work_dir).into_iter().filter(|id| is_ulid(id)) { + let workspace = work_dir.join(&job_id); + tracing::info!("removing leftover workspace {job_id}"); + if let Err(e) = remove_tree(map, &workspace, helper) { + tracing::warn!("cannot remove {}: {e}", workspace.display()); + } + } +} + +/// 26 Crockford base32 digits, the shape of every job id the forge hands out. +fn is_ulid(name: &str) -> bool { + name.len() == 26 + && name + .bytes() + .all(|b| b.is_ascii_digit() || (b.is_ascii_uppercase() && !b"ILOU".contains(&b))) +} + +/// The names of the dirs in `dir` that are valid job ids. Symlinks are skipped. +fn job_ids_in(dir: &Path) -> Vec { + let Ok(entries) = fs::read_dir(dir) else { + return Vec::new(); + }; + entries + .flatten() + .filter(|entry| entry.file_type().is_ok_and(|t| t.is_dir())) + .filter_map(|entry| entry.file_name().into_string().ok()) + .filter(|name| validate_job_id(name).is_ok()) + .collect() +} + /// Removes a job dir under `map`. Its files may be owned by subordinate ids, so this goes through /// the helper in subuid mode (see [`remove_tree`]). The removal blocks, so it runs off the async /// runtime. @@ -849,6 +988,22 @@ mod tests { use super::*; use std::collections::BTreeMap; + #[test] + fn sweep_removes_only_leftover_jobs_and_ulid_workspaces() { + let dir = tempfile::tempdir().unwrap(); + let work = dir.path(); + for d in ["jobs/job_01/overlay", "01JD6Z8Q4XW3N5R7T9V2B4C6E8/src", "oci", "notes", "check-7"] { + fs::create_dir_all(work.join(d)).unwrap(); + } + fs::create_dir_all(work.join(".cache")).unwrap(); + sweep_blocking(work, &IdMap::single(), Path::new("/nonexistent")); + assert!(!work.join("jobs/job_01").exists()); + assert!(!work.join("01JD6Z8Q4XW3N5R7T9V2B4C6E8").exists()); + for kept in ["jobs", "oci", "notes", "check-7", ".cache"] { + assert!(work.join(kept).exists(), "{kept} was removed"); + } + } + const SECRET: &str = "hunter2-SUPER-SECRET-value"; pub(crate) fn fixture_job(run: &str) -> JobAssignment { diff --git a/crates/forge-runner/src/lib.rs b/crates/forge-runner/src/lib.rs index 91b0aec..e2bd41d 100644 --- a/crates/forge-runner/src/lib.rs +++ b/crates/forge-runner/src/lib.rs @@ -10,6 +10,7 @@ pub mod check; pub mod cli; pub mod client; pub mod config; +pub mod disk; pub mod executor; pub mod limiter; pub mod logs; diff --git a/crates/forge-runner/src/sandbox/helper.rs b/crates/forge-runner/src/sandbox/helper.rs index 1cda787..fe4b7c5 100644 --- a/crates/forge-runner/src/sandbox/helper.rs +++ b/crates/forge-runner/src/sandbox/helper.rs @@ -9,6 +9,8 @@ //! 1. Enter a user namespace with the request's [`IdMap`](super::idmap::IdMap): root is the //! runner's uid, and in subuid mode container ids `1..=n` are the subordinate range. The //! overlay mount needs CAP_SYS_ADMIN in a user namespace that owns the mount namespace. +//! A job with network gets its own network namespace too, connected by pasta (see +//! [`net`](super::net)). //! 2. An overlay mount of the image rootfs. If that fails, the rootfs is copied instead. //! 3. The OCI spec is written to `bundle/config.json` (0600) and libcontainer builds the //! container from it. The file is deleted right after `build()`, since libcontainer has @@ -44,6 +46,7 @@ use signal_hook::low_level::pipe; use super::exec::FilteredExecutor; use super::idmap::enter_mapped_userns; +use super::net; use super::seccomp::build_filter; use super::spec::{HOSTNAME, build_spec}; use super::{SandboxError, SandboxRequest}; @@ -110,11 +113,21 @@ fn run() -> Result { prepare_dirs(&layout)?; write_etc_files(&layout)?; + // The job's own network, when it asked for one and pasta is installed. See `net`. + let pasta_pid = net::pid_file(&layout.job_dir); + let pending_net = match (&req.pasta, req.network) { + (Some(pasta), true) => Some(net::prepare(pasta, &pasta_pid)?), + _ => None, + }; enter_mapped_userns(&req.idmap).map_err(|e| SandboxError::Setup(e.to_string()))?; - let rootfs = mount_rootfs(&req, &layout)?; - + let result = match pending_net { + Some(pending) => pending.attach(), + None => Ok(()), + } + .and_then(|()| mount_rootfs(&req, &layout)) // Clean up on failure too: the state dir holds the job env. - let result = run_job(&req, &layout, &rootfs, &signals); + .and_then(|rootfs| run_job(&req, &layout, &rootfs, &signals)); + net::stop_pasta(&pasta_pid); // The container is gone, so nothing writes to the workspace now. In subuid mode the job may // have left files owned by subordinate ids, which the runner can't remove, so they go back // to the runner. @@ -247,7 +260,11 @@ fn write_etc_files(layout: &Layout) -> Result<(), SandboxError> { let hostname = layout.etc.join("hostname"); fs::write(&hostname, format!("{HOSTNAME}\n")) .map_err(SandboxError::io("cannot write hostname"))?; - for file in [&hosts, &hostname] { + // Only bind mounted when the job has its own network (see `spec`). + let resolv = layout.etc.join("resolv.conf"); + fs::write(&resolv, format!("nameserver {}\n", net::DNS_ADDR)) + .map_err(SandboxError::io("cannot write resolv.conf"))?; + for file in [&hosts, &hostname, &resolv] { fs::set_permissions(file, fs::Permissions::from_mode(0o644)) .map_err(SandboxError::io(format!("cannot chmod {}", file.display())))?; } diff --git a/crates/forge-runner/src/sandbox/mod.rs b/crates/forge-runner/src/sandbox/mod.rs index faa0123..19f01b3 100644 --- a/crates/forge-runner/src/sandbox/mod.rs +++ b/crates/forge-runner/src/sandbox/mod.rs @@ -8,6 +8,7 @@ pub mod exec; pub mod helper; pub mod idmap; +pub mod net; pub mod seccomp; pub mod spec; @@ -40,8 +41,14 @@ pub struct SandboxRequest { pub env: Vec<(String, String)>, /// The job's `run` script, executed as `sh -eu -c `. pub run: String, - /// `false` gives the job an empty network namespace. `true` shares the host's. + /// `false` gives the job an empty network namespace. `true` gives it the internet: through + /// `pasta` in its own namespace when `pasta` is set (see `helper::isolate_network`), or the + /// host's namespace when it is not. pub network: bool, + /// The `pasta` binary (from the passt package) that connects an isolated job network to the + /// internet. `None` when it is not installed. + #[serde(default)] + pub pasta: Option, pub limits: Limits, /// The id mapping the helper enters before anything else. Missing means single mode. #[serde(default)] diff --git a/crates/forge-runner/src/sandbox/net.rs b/crates/forge-runner/src/sandbox/net.rs new file mode 100644 index 0000000..861fa75 --- /dev/null +++ b/crates/forge-runner/src/sandbox/net.rs @@ -0,0 +1,264 @@ +//! The network of a builtin job that asked for one. +//! +//! The job gets its own network namespace, and `pasta` (from the passt package) connects it to +//! the internet through the runner's own sockets. Inside, the job sees `192.0.2.2/24` with the +//! gateway at `192.0.2.1` and DNS at `192.0.2.3`. The host's loopback is not mapped, and +//! blackhole routes send private, link-local (cloud metadata) and multicast ranges nowhere, so +//! a job cannot reach the runner's own services or its LAN. There is no IPv6. +//! +//! pasta has to start in the host's namespaces and attach to the helper's new ones, so it can't +//! be a child of the helper after the unshare. A `__sandbox-net` helper of this same binary is +//! started before it, and blocks on stdin until the helper has unshared. It then runs pasta, +//! which forks into the background once the namespace is set up and exits 0. pasta writes its +//! pid to a file, and [`stop_pasta`] ends it after the job. + +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; + +/// The hidden subcommand that waits for the go byte and starts pasta. +pub const NET_HELPER_CMD: &str = "__sandbox-net"; +/// The job's resolver, which pasta forwards to the host's. +pub const DNS_ADDR: &str = "192.0.2.3"; +/// Where pasta is looked for, in order. +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"]; +/// Ranges the job must not reach: "this network", private, carrier-grade NAT, link-local (cloud +/// metadata), benchmarking, multicast and reserved. +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", +]; + +/// Where pasta writes its pid: in the job dir itself, since libcontainer removes `state` with the +/// container. +pub fn pid_file(job_dir: &Path) -> PathBuf { + job_dir.join("pasta.pid") +} + +/// The installed pasta binary, if any. +pub fn find_pasta() -> Option { + PASTA_PATHS.iter().map(PathBuf::from).find(|p| p.is_file()) +} + +/// A started `__sandbox-net` helper that is waiting for its go byte. +pub struct PendingNet { + child: Child, +} + +/// Starts the `__sandbox-net` helper. Call it before entering the user namespace, then call +/// [`PendingNet::attach`] right after. +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 { + /// Moves this process into a new network namespace, has pasta connect it, and sets up the + /// routes. Must run inside the job's user namespace, which owns the new network namespace. + 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")) + }); + // Closing stdin ends the helper's wait if the byte never landed. + 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(); + } +} + +/// Brings loopback up and blackholes [`BLOCKED`]. pasta has already added the address and the +/// default route. +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() + ))) + } +} + +/// Ends the pasta whose pid is in `pid_file`, if it is still running. The pid is only signalled +/// when it still names a pasta process, so a reused pid is left alone. +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); + } +} + +/// ` __sandbox-net `, with the go byte on stdin. Exit 0 once +/// pasta has connected the parent's network namespace, or 125 with a `forge-sandbox:` line. +pub fn net_helper_main(args: &[OsString]) -> i32 { + match net_helper(args) { + Ok(()) => 0, + Err(message) => { + eprintln!("forge-sandbox: {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() + )) + } +} + +/// No ports are forwarded in either direction, the gateway does not map to the host's loopback, +/// and pasta does not watch the namespace (that needs a netns dir SELinux may deny), so it is +/// stopped through its pid file. +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 +} diff --git a/crates/forge-runner/src/sandbox/spec.rs b/crates/forge-runner/src/sandbox/spec.rs index de81684..c201f57 100644 --- a/crates/forge-runner/src/sandbox/spec.rs +++ b/crates/forge-runner/src/sandbox/spec.rs @@ -377,12 +377,23 @@ fn build_mounts(req: &SandboxRequest) -> Result, SandboxError> { "/sys", &["rbind", "nosuid", "noexec", "nodev", "ro"], )?); - mounts.push(mount( - "/etc/resolv.conf", - "bind", - "/etc/resolv.conf", - &["bind", "ro"], - )?); + // An isolated network asks pasta's DNS forwarder; the host's resolver may be on its + // loopback, which the job cannot reach. + if req.pasta.is_some() { + mounts.push(mount_path( + "/etc/resolv.conf", + "bind", + &req.job_dir.join("etc/resolv.conf"), + &["bind", "ro"], + )?); + } else { + mounts.push(mount( + "/etc/resolv.conf", + "bind", + "/etc/resolv.conf", + &["bind", "ro"], + )?); + } } else { mounts.push(mount( "/sys", @@ -462,11 +473,13 @@ mod tests { ], run: "echo hi".to_owned(), network, + pasta: None, limits: Limits { memory: "2g".to_owned(), cpus: "1.5".to_owned(), pids: 512, image_max_gb: 20, + job_disk_gb: 20, ..Limits::default() }, idmap: IdMap::single(), diff --git a/crates/forge-runner/tests/integration/builtin.rs b/crates/forge-runner/tests/integration/builtin.rs index 03baab8..f418c06 100644 --- a/crates/forge-runner/tests/integration/builtin.rs +++ b/crates/forge-runner/tests/integration/builtin.rs @@ -323,3 +323,30 @@ async fn sigkilled_helper_leaves_no_process_behind() { } assert!(!dir.path().join("jobs").join(job_id).exists(), "job dir was kept"); } + +#[tokio::test] +async fn network_job_gets_its_own_network_without_private_ranges() { + let _serial = serial().await; + if !can_run() || forge_runner::sandbox::net::find_pasta().is_none() { + eprintln!("skipping: needs user namespaces and pasta"); + return; + } + let dir = tempfile::tempdir().expect("tempdir"); + let (exec, workspace) = executor(dir.path()); + let mut job = job("read -r l < /etc/resolv.conf; echo \"dns=$l\"; \ + if (echo > /dev/tcp/169.254.169.254/80) 2>/dev/null; then echo meta=open; \ + else echo meta=blocked; fi"); + job.network = true; + let (result, logs) = run_job(&exec, &job, &workspace, CancellationToken::new()).await; + + assert_eq!(result.outcome, Outcome::Success, "{result:?}\n{logs}"); + assert!(logs.contains("dns=nameserver 192.0.2.3"), "{logs}"); + assert!(logs.contains("meta=blocked"), "{logs}"); + assert!(!logs.contains("pasta is not installed"), "{logs}"); + let pid_file = dir.path().join("jobs/job_01/pasta.pid"); + let leftover = fs::read_dir("/proc").expect("read /proc").flatten().any(|entry| { + fs::read(entry.path().join("cmdline")) + .is_ok_and(|cmd| String::from_utf8_lossy(&cmd).contains(&*pid_file.to_string_lossy())) + }); + assert!(!leftover, "pasta outlived the job"); +} diff --git a/crates/forge-runner/tests/integration/sandbox.rs b/crates/forge-runner/tests/integration/sandbox.rs index a57240e..fda3ee7 100644 --- a/crates/forge-runner/tests/integration/sandbox.rs +++ b/crates/forge-runner/tests/integration/sandbox.rs @@ -102,6 +102,7 @@ fn request(dir: &Path, rootfs: &Path, run: &str, network: bool) -> SandboxReques env: vec![("FORGE_TEST".to_owned(), "yes".to_owned())], run: run.to_owned(), network, + pasta: None, limits: Limits::default(), idmap: IdMap::single(), } diff --git a/crates/forge-web/src/pages/admin_runners.rs b/crates/forge-web/src/pages/admin_runners.rs index 201c7f0..d6a03fe 100644 --- a/crates/forge-web/src/pages/admin_runners.rs +++ b/crates/forge-web/src/pages/admin_runners.rs @@ -810,6 +810,7 @@ const TABS: [(&str, &[&str]); 5] = [ &[ "work_dir", "limits.image_max_gb", + "limits.job_disk_gb", "images.keep_days", "cache_max_gib", ], @@ -936,6 +937,14 @@ fn field_text(lang: Lang, key: &str) -> (&'static str, &'static str) { "Saklanan kapsayıcı kalıpları için üst sınır.", ), ), + "limits.job_disk_gb" => ( + s(lang, "Disk per job (GB)", "İş başına disk (GB)"), + s( + lang, + "A job that fills more than this (workspace, /tmp and its writes over the image) is stopped. 0 means no cap.", + "Bundan fazlasını (çalışma alanı, /tmp ve kalıbın üstüne yazdıkları) dolduran iş durdurulur. 0 sınır yok demektir.", + ), + ), "images.keep_days" => ( s(lang, "Keep images (days)", "Kalıpları sakla (gün)"), s( @@ -1032,6 +1041,7 @@ fn detail_fields(lang: Lang, tab: &str, fields: &[FieldRow]) -> Vec f.key, "limits.pids" | "limits.image_max_gb" + | "limits.job_disk_gb" | "images.keep_days" | "cache_max_gib" | "concurrency" diff --git a/docs/ci.md b/docs/ci.md index 2080d04..fbad61d 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -58,7 +58,7 @@ There must be at least one job, and at most 20. | `timeout_minutes` | integer | `60` | Range 1 to 360. | | `memory` | string | none | The job's expected peak memory, such as `4g` or `512m`. 64m to 1024g. See [Memory](#memory). | | `matrix` | table | none | Expands the job into one job per combination. See [Matrix builds](#matrix-builds). | -| `network` | bool | `true` | `false` gives the job an empty network namespace (loopback only). `true` shares the runner host's network namespace. Read [the caveats](#builtin-executor-caveats). | +| `network` | bool | `true` | `false` gives the job an empty network namespace (loopback only). `true` gives it internet access, isolated through `pasta` when it is installed. Read [the caveats](#builtin-executor-caveats). | Job names match `^[a-z0-9][a-z0-9_-]{0,39}$`. @@ -580,6 +580,7 @@ budget_swap_percent = 0 # in auto mode: percent of swap that counts toward the b cpus = "2" # the job cgroup's cpu.max, or podman --cpus pids = 4096 # the job cgroup's pids.max, or podman --pids-limit image_max_gb = 20 # cap on the unpacked size of one image (builtin) +job_disk_gb = 20 # disk one job may fill: workspace, /tmp, writes over the image; 0 = no cap (builtin) [images] keep_days = 7 # images unused for this many days are deleted (builtin) @@ -647,10 +648,20 @@ Image garbage collection runs at startup and then daily. Unpacked images are kep Read these before you run untrusted or sensitive jobs on a runner: -- **`network = true` shares the host's network namespace.** The builtin executor does not set up - a separate network, so a job with `network = true` can reach every service that the runner host - can reach, including services bound to the host's `localhost`. Use `network = false` for any job - that does not need the network. It gets only a loopback interface. +- **`network = true` needs `pasta` to be isolated.** With `pasta` installed (the `passt` + package: `dnf install passt`, `apt install passt`), a job with `network = true` gets its own + network namespace with internet access through `pasta`. The runner host's `localhost`, private + ranges (10/8, 172.16/12, 192.168/16, 100.64/10) and link-local addresses such as cloud + metadata are blocked, and there is no IPv6. Without `pasta` the job shares the runner host's + network namespace and can reach everything the host can, including its `localhost`; the job + log then says so. Use `network = false` for any job that does not need the network. It gets + only a loopback interface. +- **Disk is capped per job** by `limits.job_disk_gb` (default 20): the workspace, `/tmp` and what + the job writes over the image. The runner measures it every few seconds and stops a job past + the cap, so a fast writer can overshoot a little. +- **Leftovers are cleaned at startup.** After a crash the runner removes leftover job dirs, job + cgroups, `pasta` processes and workspaces (dirs in `work_dir` named like a job id) before it + takes a job. - **Subordinate ids are mapped in subuid mode.** Container ids `1` to `n` map to your subordinate range, so a command can change file ownership to another user or group, as `apt` and `useradd` do. This needs the setup in [Subordinate ids](#subordinate-ids). Without it, the runner falls @@ -659,7 +670,7 @@ Read these before you run untrusted or sensitive jobs on a runner: have the ownership a job sees. A file that is owner `1000` inside a job is owned by `start + 999` on the host, for example `525287` with the range `524288`. `ls -ln` shows the numbers. The runner removes these files through a helper, so it can still clean them up. -- **With `network = true`, `/sys` is the host's `/sys`,** bind-mounted read-only. The job can read +- **With `network = true`, `/sys` may be the host's `/sys`,** bind-mounted read-only. The job can read host hardware and kernel details from it. - **The job cgroup is placed in the parent slice.** It is named `forge-job--` and sits next to the runner's own cgroup, not under it. The runner's cgroup is never used for a