diff --git a/.github/workflows/audit.yml b/.github/workflows/audit.yml new file mode 100644 index 000000000..f512682b4 --- /dev/null +++ b/.github/workflows/audit.yml @@ -0,0 +1,46 @@ +# Checks Rust dependency advisories, licenses, bans, and sources against +# deny.toml on dependency changes, pushes to main, and a weekly schedule. +# +# Safe for pull requests from forks: read-only token, no secrets, no build +# scripts executed (cargo-deny inspects Cargo.toml and Cargo.lock only). +name: Dependency audit + +on: + pull_request: + paths: + - Cargo.toml + - Cargo.lock + - crates/*/Cargo.toml + - xtask/Cargo.toml + - deny.toml + - .github/workflows/audit.yml + push: + branches: [main] + paths: + - Cargo.toml + - Cargo.lock + - crates/*/Cargo.toml + - xtask/Cargo.toml + - deny.toml + - .github/workflows/audit.yml + schedule: + - cron: "17 5 * * 1" + +permissions: + contents: read + +concurrency: + group: audit-${{ github.event.pull_request.number || github.ref }}-${{ github.event_name }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + deny: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: EmbarkStudios/cargo-deny-action@bb119f768ea239e765aeaef5769558d4f21213aa # v2.1.5 + with: + command: check --all-features diff --git a/.github/workflows/page-read-reset.yml b/.github/workflows/page-read-reset.yml new file mode 100644 index 000000000..81f401ef5 --- /dev/null +++ b/.github/workflows/page-read-reset.yml @@ -0,0 +1,28 @@ +# Removes the `page-read` approval label whenever new commits are pushed to a +# pull request, so a review of an earlier commit cannot approve JS added later +# in `crates/kiri/src/ui/index.html` or `crates/kiri-win/src/setup.html`. +# +# Runs on `pull_request_target` with no checkout of PR code and minimal +# `pull-requests: write` permission (only deletes one fixed label name). +name: Reset page-read label + +on: + pull_request_target: + types: [synchronize] + +permissions: + pull-requests: write + +jobs: + reset: + if: contains(github.event.pull_request.labels.*.name, 'page-read') + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - name: Remove page-read label after new commits + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPO: ${{ github.repository }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + gh api -X DELETE "repos/$REPO/issues/$PR_NUMBER/labels/page-read" || true diff --git a/.github/workflows/perf.yml b/.github/workflows/perf.yml index d91ed2936..af5986775 100644 --- a/.github/workflows/perf.yml +++ b/.github/workflows/perf.yml @@ -6,7 +6,10 @@ # system calls one container costs. # # The limits come from main's copy of the script when it has one, so a pull -# request can't loosen them for itself. +# request can't accidentally loosen them for itself. (Because the PR binary +# runs in a `--privileged` container on the same runner as `base`, this guards +# against accidental threshold edits rather than adversarial tampering; the +# job itself has only a read-only token and no secrets.) # # Safe for pull requests from forks: it runs on GitHub's machines with a # read-only token and no secrets, and uses pull_request (never diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 15ceb341b..362616bec 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -186,8 +186,8 @@ jobs: read -r cv csum <<< "$(pin COMPOSE)" [ -n "$dsum" ] && [ -n "$csum" ] || { echo "could not read the pins from cli_pins.rs"; exit 1; } cd "$RUNNER_TEMP" - curl -fsSL --proto '=https' -o docker.tgz "https://download.docker.com/mac/static/stable/aarch64/docker-$dv.tgz" - curl -fsSL --proto '=https' -o compose "https://github.com/docker/compose/releases/download/$cv/docker-compose-darwin-aarch64" + curl -fsSL --proto '=https' --proto-redir '=https' -o docker.tgz "https://download.docker.com/mac/static/stable/aarch64/docker-$dv.tgz" + curl -fsSL --proto '=https' --proto-redir '=https' -o compose "https://github.com/docker/compose/releases/download/$cv/docker-compose-darwin-aarch64" echo "$dsum docker.tgz" | shasum -a 256 -c echo "$csum compose" | shasum -a 256 -c mkdir -p bin "$HOME/.docker/cli-plugins" @@ -254,8 +254,9 @@ jobs: # pull request adds to the page that needs one (new addresses, new ways to # reach the network, code that builds or hides code, reads of what is # worth stealing) and fails until a maintainer who has read it adds the - # label page-read. Remove the label when new commits come in: it stays on - # the pull request and accepts them too. + # label page-read. `.github/workflows/page-read-reset.yml` removes `page-read` + # automatically whenever new commits are pushed so earlier approval cannot + # carry over to unreviewed JS. page-scan: needs: scope if: needs.scope.outputs.page == 'true' diff --git a/Cargo.lock b/Cargo.lock index 5e90618d5..23c9e226a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -330,7 +330,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1235,15 +1235,15 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags 2.13.2", "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] diff --git a/contrib/windows/kiri.ps1 b/contrib/windows/kiri.ps1 index e43cdb1f3..70c26f3e7 100644 --- a/contrib/windows/kiri.ps1 +++ b/contrib/windows/kiri.ps1 @@ -45,6 +45,7 @@ if ($Update) { Say "waiting for kiri-win $WaitFor" while ($WaitFor -and (Get-Process -Id $WaitFor -ErrorAction SilentlyContinue)) { Start-Sleep -Milliseconds 200 } if (-not (Test-Path -LiteralPath $Msi -PathType Leaf)) { throw "staged MSI not found: $Msi" } + if ((Get-Item -LiteralPath $Msi -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "refusing silent install: staged MSI is a reparse point" } $actualHash = (Get-FileHash -LiteralPath $Msi -Algorithm SHA256).Hash if ($actualHash -notlike $Sha256 -or $actualHash.ToLowerInvariant() -ne $Sha256.ToLowerInvariant()) { throw "refusing silent install: SHA-256 mismatch for $Msi (expected $Sha256, got $actualHash)" diff --git a/crates/kiri-image/src/archive.rs b/crates/kiri-image/src/archive.rs index d197dce92..6cf5cb585 100644 --- a/crates/kiri-image/src/archive.rs +++ b/crates/kiri-image/src/archive.rs @@ -7,8 +7,8 @@ //! content-addressed blobs already in the store are verified in memory without //! rewriting disk files. -use std::collections::HashMap; -use std::io::{self, Read, Write}; +use std::collections::{HashMap, HashSet}; +use std::io::{self, BufReader, BufWriter, Read, Write}; use std::time::{SystemTime, UNIX_EPOCH}; use serde_json::{Value, json}; @@ -36,15 +36,15 @@ pub fn load_with_platform(store: &Store, archive: impl Read, platform: Option<&P /// As [`load`], filtering a multi-platform OCI index to `platforms` when non-empty. pub fn load_platforms(store: &Store, archive: impl Read, platforms: &[Platform]) -> io::Result> { - let mut tar = tar::Archive::new(archive); + let mut tar = tar::Archive::new(BufReader::with_capacity(128 << 10, archive)); // Archive path → blob digest and size, for every regular file. let mut files: HashMap = HashMap::new(); let mut manifest: Option> = None; let mut index: Option> = None; let mut oci_layout: Option> = None; - let before: Vec = store.images()?; - let existed = |d: &str| before.iter().any(|i| i.referenced_digests().any(|r| r == d)); - let mut ingested: Vec = Vec::new(); + let before = store.images_arc()?; + let before_digests: HashSet<&str> = before.iter().flat_map(|i| i.referenced_digests()).collect(); + let mut ingested: HashSet = HashSet::new(); let mut pins = Vec::new(); let read = (|| -> io::Result> { for entry in tar.entries()? { @@ -96,8 +96,8 @@ pub fn load_platforms(store: &Store, archive: impl Read, platforms: &[Platform]) // that shares the blob must not delete it meanwhile. let (digest, size, pin) = w.finish_pinned()?; pins.push(pin); - if !existed(&digest) && !ingested.contains(&digest) { - ingested.push(digest.clone()); + if !before_digests.contains(digest.as_str()) { + ingested.insert(digest.clone()); } files.insert(path, (digest, size)); } @@ -162,9 +162,7 @@ fn load_docker(store: &Store, files: &HashMap, manifest: loaded.push(from_config(name, &config_digest, &config, layers.clone())); } } - for image in &loaded { - store.put_image(image.clone())?; - } + store.put_images(loaded.clone())?; Ok(loaded) } @@ -374,9 +372,7 @@ fn load_oci( let name = candidate.tag.unwrap_or_else(|| config_digest.clone()); loaded.push(from_config(name, &config_digest, &config, layers)); } - for image in &loaded { - store.put_image(image.clone())?; - } + store.put_images(loaded.clone())?; Ok(loaded) } @@ -402,8 +398,8 @@ pub fn hold(store: &Store, images: &[Image]) -> io::Result io::Result<()> { let _held = hold(store, images)?; - let mut tar = tar::Builder::new(out); - let mut written: Vec = Vec::new(); + let mut tar = tar::Builder::new(BufWriter::with_capacity(128 << 10, out)); + let mut written: HashSet<&str> = HashSet::new(); let mut manifest = Vec::new(); // Images that share a config are one entry with several tags. let mut by_config: Vec<(&Image, Vec)> = Vec::new(); @@ -420,18 +416,18 @@ pub fn save(store: &Store, images: &[Image], out: impl Write) -> io::Result<()> for (image, tags) in &by_config { let blob = |d: &str| format!("blobs/sha256/{}", d.strip_prefix("sha256:").unwrap_or(d)); for d in std::iter::once(&image.config_digest).chain(image.layers.iter().map(|l| &l.digest)) { - if written.contains(d) { + if !written.insert(d.as_str()) { continue; } let path = store.blob_path(d)?; - let mut f = std::fs::File::open(&path)?; + let f = std::fs::File::open(&path)?; let mut h = tar::Header::new_ustar(); h.set_size(f.metadata()?.len()); h.set_mode(0o644); h.set_mtime(0); h.set_entry_type(tar::EntryType::Regular); - tar.append_data(&mut h, blob(d), &mut f)?; - written.push(d.clone()); + let mut br = BufReader::with_capacity(128 << 10, f); + tar.append_data(&mut h, blob(d), &mut br)?; } manifest.push(json!({ "Config": blob(&image.config_digest), diff --git a/crates/kiri-image/src/registry.rs b/crates/kiri-image/src/registry.rs index 9d38888a2..353351fee 100644 --- a/crates/kiri-image/src/registry.rs +++ b/crates/kiri-image/src/registry.rs @@ -1172,6 +1172,10 @@ impl Client { .collect(), }); }; + // Validate the digest from the untrusted index before interpolating + // it into an authenticated manifest URL. + crate::store::digest_hex(&entry.digest) + .map_err(|_| Error::Manifest(format!("invalid manifest digest {:?}", entry.digest)))?; let (entry_bytes, _) = self.manifest_with(r, &entry.digest, Some(cancel)).map_err(stopped)?; if sha256_digest(&entry_bytes) != entry.digest { return Err(Error::Manifest(format!("manifest {} failed digest check", entry.digest))); @@ -1746,7 +1750,7 @@ impl Client { /// `postgres` gives `latest`, `17-alpine`, `17`… Hub's own API, since /// the registry's tag list is unordered and has no dates. pub fn hub_tags(&self, repo: &str, limit: u32) -> Result, Error> { - let repo = if repo.contains('/') { repo.to_owned() } else { format!("library/{repo}") }; + let repo = validate_hub_repo(repo)?; let url = format!("https://hub.docker.com/v2/repositories/{repo}/tags"); let mut resp = self.agent.get(&url).query("page_size", limit.to_string()).query("ordering", "last_updated").config().max_redirects(5).https_only(true).build().call()?; if resp.status().as_u16() != 200 { @@ -2110,6 +2114,27 @@ fn not_found(e: Error, r: &Reference) -> Error { } } +/// Validates a Docker Hub repository name (`alpine` or `namespace/name`) before +/// interpolating it into a `hub.docker.com` API URL (`SEC-V-13`). +fn validate_hub_repo(repo: &str) -> Result { + if repo.is_empty() || repo.len() > 255 { + return Err(Error::Manifest(format!("invalid Docker Hub repository {repo:?}"))); + } + let alnum = |b: u8| b.is_ascii_lowercase() || b.is_ascii_digit(); + let valid_seg = |s: &str| { + !s.is_empty() + && s.as_bytes().first().is_some_and(|&b| alnum(b)) + && s.as_bytes().last().is_some_and(|&b| alnum(b)) + && s.bytes().all(|b| alnum(b) || b".-_".contains(&b)) + }; + let mut parts = repo.split('/'); + match (parts.next(), parts.next(), parts.next()) { + (Some(name), None, None) if valid_seg(name) => Ok(format!("library/{name}")), + (Some(ns), Some(name), None) if valid_seg(ns) && valid_seg(name) => Ok(format!("{ns}/{name}")), + _ => Err(Error::Manifest(format!("invalid Docker Hub repository {repo:?}"))), + } +} + #[cfg(test)] mod tests { use super::*; @@ -4438,4 +4463,92 @@ mod tests { assert!(got.starts_with(b"{\"schemaVersion\":2")); assert_eq!(server.join().unwrap(), 3); } + + #[test] + fn resolve_rejects_malformed_index_entry_digest_without_requesting_it() { + let index = serde_json::json!({ + "schemaVersion": 2, + "mediaType": "application/vnd.docker.distribution.manifest.list.v2+json", + "manifests": [{ + "mediaType": "application/vnd.docker.distribution.manifest.v2+json", + "size": 10, + "digest": "sha256:../../other-repo/manifests/secret?foo=bar", + "platform": {"architecture": "amd64", "os": "linux"}, + }], + }) + .to_string(); + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let host = listener.local_addr().unwrap().to_string(); + let served = std::thread::spawn(move || { + let mut seen = Vec::new(); + 'conns: for c in listener.incoming() { + let mut c = c.unwrap(); + let mut first = [0u8; 1]; + if c.peek(&mut first).unwrap_or(0) == 1 && first[0] == 0x16 { + let _ = c.write_all(b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); + continue; + } + let mut head = Vec::new(); + let mut b = [0u8; 1]; + while !head.ends_with(b"\r\n\r\n") && c.read(&mut b).unwrap_or(0) == 1 { + head.push(b[0]); + } + let head = String::from_utf8_lossy(&head).to_string(); + if head.starts_with("QUIT") { + break 'conns; + } + if head.is_empty() { + continue 'conns; + } + let path = head.lines().next().and_then(|l| l.split_whitespace().nth(1)).unwrap_or("").to_string(); + seen.push(path.clone()); + let (status, body, kind) = if path == "/v2/" { + (200, b"{}".as_slice(), "application/json") + } else { + (200, index.as_bytes(), "application/vnd.oci.image.index.v1+json") + }; + let resp = format!("HTTP/1.1 {status} OK\r\nContent-Type: {kind}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()); + let _ = c.write_all(resp.as_bytes()); + let _ = c.write_all(body); + } + seen + }); + + let client = test_client(); + let r = Reference::parse(&format!("{host}/app/test:latest")).unwrap(); + let platform = Platform::parse("linux/amd64").unwrap(); + let err = match client.resolve(&r, &platform, &Cancel::new()) { + Ok(_) => panic!("malformed index digest should be rejected"), + Err(e) => e, + }; + assert!(matches!(err, Error::Manifest(_)), "unexpected error: {err:?}"); + quit(&host); + let seen = served.join().unwrap(); + assert!(!seen.iter().any(|p| p.contains("other-repo") || p.contains("..")), "malformed digest was requested: {seen:?}"); + } + + #[test] + fn hub_tags_rejects_malformed_repository_names() { + assert_eq!(validate_hub_repo("postgres").unwrap(), "library/postgres"); + assert_eq!(validate_hub_repo("bitnami/redis").unwrap(), "bitnami/redis"); + assert_eq!(validate_hub_repo("my_org/my-app.1").unwrap(), "my_org/my-app.1"); + let client = Client::new(); + for bad in [ + "", + "../users/me#", + "library/alpine?page_size=999", + "library/alpine#frag", + "a/b/c", + "/alpine", + "alpine/", + "..", + ".", + "library/..", + "Alpine", + "foo bar", + ] { + assert!(validate_hub_repo(bad).is_err(), "{bad:?}"); + assert!(matches!(client.hub_tags(bad, 10), Err(Error::Manifest(_))), "{bad:?}"); + } + } } diff --git a/crates/kiri-image/src/store.rs b/crates/kiri-image/src/store.rs index 15bf97008..56e792155 100644 --- a/crates/kiri-image/src/store.rs +++ b/crates/kiri-image/src/store.rs @@ -17,10 +17,11 @@ //! aside as `images.json.corrupt-*` and what can be read from it is kept. use std::fs::{self, File}; -use std::io::{self, Write}; +use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Mutex, MutexGuard, OnceLock}; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock}; +use std::time::SystemTime; /// The most an image config may be: real ones are a few KB. pub const MAX_CONFIG: u64 = 16 << 20; @@ -135,9 +136,21 @@ impl Image { } } +/// Identifies one on-disk version of `images.json`: `(mtime, len, ino)`. +type IndexStamp = (SystemTime, u64, u64); + +fn stamp_of(m: &fs::Metadata) -> IndexStamp { + #[cfg(unix)] + let ino = std::os::unix::fs::MetadataExt::ino(m); + #[cfg(not(unix))] + let ino = 0; + (m.modified().unwrap_or(SystemTime::UNIX_EPOCH), m.len(), ino) +} + #[derive(Debug)] pub struct Store { root: PathBuf, + index_cache: Mutex, Arc>)>>, } static TMP_SEQ: AtomicU64 = AtomicU64::new(0); @@ -217,6 +230,12 @@ enum Index { Corrupt(Vec, serde_json::Error), } +/// [`Index`] paired with the file stamp read from the same file descriptor. +enum StampedIndex { + Valid(Option, Vec), + Corrupt(Vec, serde_json::Error), +} + /// The images that can still be read from a damaged index, see /// [`crate::jsonfile::salvage`]. fn salvage(bytes: &[u8]) -> Vec { @@ -306,7 +325,10 @@ impl Store { if !tmp.is_dir() { fs::create_dir_all(tmp)?; } - Ok(Store { root }) + Ok(Store { + root, + index_cache: Mutex::new(None), + }) } pub fn root(&self) -> &Path { @@ -339,7 +361,7 @@ impl Store { pub fn blob_writer(&self, digest: &str) -> io::Result { let tmp = self.root.join("tmp").join(format!("{}.{}.{}", digest_hex(digest)?, std::process::id(), TMP_SEQ.fetch_add(1, Ordering::Relaxed))); Ok(BlobWriter { - file: File::create(&tmp)?, + file: io::BufWriter::with_capacity(BLOB_WRITE_BUF, File::create(&tmp)?), hasher: Sha256::new(), tmp, dest: self.blob_path(digest)?, @@ -352,21 +374,59 @@ impl Store { /// it is named after what was written once `finish` is called. pub fn ingest(&self) -> io::Result { let tmp = self.root.join("tmp").join(format!("ingest.{}.{}", std::process::id(), TMP_SEQ.fetch_add(1, Ordering::Relaxed))); - Ok(Ingest { file: File::create(&tmp)?, hasher: Sha256::new(), tmp, root: self.root.clone(), written: 0 }) + Ok(Ingest { + file: io::BufWriter::with_capacity(BLOB_WRITE_BUF, File::create(&tmp)?), + hasher: Sha256::new(), + tmp, + root: self.root.clone(), + written: 0, + }) } - /// The image index. One that does not parse is repaired first, see - /// [`Store::recover`], rather than failing every caller from then on. - pub fn images(&self) -> io::Result> { - match self.read_index()? { - Index::Valid(images) => Ok(images), - Index::Corrupt(..) => { + /// The image index, shared via `Arc` from an mtime/size/inode-validated + /// in-memory cache so repeated reads (`/info`, `/images/json`) avoid + /// re-reading and re-parsing `images.json` when unchanged. + pub fn images_arc(&self) -> io::Result>> { + let path = self.root.join("images.json"); + let stamp = match fs::metadata(&path) { + Ok(m) => Some(stamp_of(&m)), + Err(e) if e.kind() == io::ErrorKind::NotFound => None, + Err(e) => return Err(e), + }; + if let Some((cached_stamp, cached)) = self.index_cache.lock().unwrap_or_else(|e| e.into_inner()).as_ref() + && *cached_stamp == stamp + { + return Ok(Arc::clone(cached)); + } + match self.read_index_stamped()? { + StampedIndex::Valid(read_stamp, images) => { + let arc = Arc::new(images); + *self.index_cache.lock().unwrap_or_else(|e| e.into_inner()) = Some((read_stamp, Arc::clone(&arc))); + Ok(arc) + } + StampedIndex::Corrupt(..) => { + *self.index_cache.lock().unwrap_or_else(|e| e.into_inner()) = None; let _lock = self.lock_index()?; - self.read_locked() + let images = self.read_locked()?; + let arc = Arc::new(images); + let new_stamp = fs::metadata(&path).ok().map(|m| stamp_of(&m)); + *self.index_cache.lock().unwrap_or_else(|e| e.into_inner()) = Some((new_stamp, Arc::clone(&arc))); + Ok(arc) } } } + /// Number of images in the index without cloning image entries. + pub fn image_count(&self) -> io::Result { + Ok(self.images_arc()?.len()) + } + + /// The image index. One that does not parse is repaired first, see + /// [`Store::recover`], rather than failing every caller from then on. + pub fn images(&self) -> io::Result> { + Ok((*self.images_arc()?).clone()) + } + /// Reads the image index under the in-process index lock and passes it to /// `f`, so `f` can pin blobs ([`Store::pin`], [`Store::hold_image`]) /// atomically before a concurrent [`Store::put_image`] or @@ -374,9 +434,26 @@ impl Store { /// `f` must not call methods that re-acquire the index lock. pub fn with_images(&self, f: impl FnOnce(&[Image]) -> T) -> io::Result { let guard = INDEX_LOCK.lock().unwrap_or_else(|e| e.into_inner()); - let images = match self.read_index()? { - Index::Valid(images) => images, - Index::Corrupt(..) => { + let path = self.root.join("images.json"); + let stamp = match fs::metadata(&path) { + Ok(m) => Some(stamp_of(&m)), + Err(e) if e.kind() == io::ErrorKind::NotFound => None, + Err(e) => return Err(e), + }; + if let Some((cached_stamp, cached)) = self.index_cache.lock().unwrap_or_else(|e| e.into_inner()).as_ref() + && *cached_stamp == stamp + { + let arc = Arc::clone(cached); + return Ok(f(&arc)); + } + let images = match self.read_index_stamped()? { + StampedIndex::Valid(read_stamp, images) => { + let arc = Arc::new(images); + *self.index_cache.lock().unwrap_or_else(|e| e.into_inner()) = Some((read_stamp, Arc::clone(&arc))); + arc + } + StampedIndex::Corrupt(..) => { + *self.index_cache.lock().unwrap_or_else(|e| e.into_inner()) = None; drop(guard); let _lock = self.lock_index()?; let images = self.read_locked()?; @@ -386,14 +463,26 @@ impl Store { Ok(f(&images)) } + fn read_index_stamped(&self) -> io::Result { + let path = self.root.join("images.json"); + let mut file = match File::open(&path) { + Ok(f) => f, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(StampedIndex::Valid(None, Vec::new())), + Err(e) => return Err(e), + }; + let stamp = Some(stamp_of(&file.metadata()?)); + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes)?; + Ok(match serde_json::from_slice(&bytes) { + Ok(images) => StampedIndex::Valid(stamp, images), + Err(e) => StampedIndex::Corrupt(bytes, e), + }) + } + fn read_index(&self) -> io::Result { - match fs::read(self.root.join("images.json")) { - Ok(bytes) => Ok(match serde_json::from_slice(&bytes) { - Ok(images) => Index::Valid(images), - Err(e) => Index::Corrupt(bytes, e), - }), - Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(Index::Valid(Vec::new())), - Err(e) => Err(e), + match self.read_index_stamped()? { + StampedIndex::Valid(_, images) => Ok(Index::Valid(images)), + StampedIndex::Corrupt(bytes, e) => Ok(Index::Corrupt(bytes, e)), } } @@ -489,7 +578,8 @@ impl Store { pub fn find(&self, name: &str) -> io::Result> { let r = Reference::parse(name).ok(); - Ok(self.images()?.into_iter().find(|i| i.name == name || i.digest == name || r.as_ref().is_some_and(|r| i.matches(r)))) + let images = self.images_arc()?; + Ok(images.iter().find(|i| i.name == name || i.digest == name || r.as_ref().is_some_and(|r| i.matches(r))).cloned()) } /// As [`Store::find`], holding every blob the found image references @@ -511,9 +601,29 @@ impl Store { /// the replaced image used go, as [`Store::remove_image`] deletes them: /// nothing would name them any more (#864). pub fn put_image(&self, image: Image) -> io::Result<()> { + self.put_images(vec![image]) + } + + /// Adds every image in `new_images` in a single atomic index rewrite so + /// multi-image `docker load` archives pay one index lock + fsync instead of N. + pub fn put_images(&self, new_images: Vec) -> io::Result<()> { + if new_images.is_empty() { + return Ok(()); + } let _lock = self.lock_index()?; - let (replaced, mut images): (Vec, Vec) = self.read_locked()?.into_iter().partition(|i| i.name == image.name); - images.push(image); + let mut images = self.read_locked()?; + let mut replaced = Vec::new(); + for image in new_images { + let mut i = 0; + while i < images.len() { + if images[i].name == image.name { + replaced.push(images.remove(i)); + } else { + i += 1; + } + } + images.push(image); + } self.write_index(&images)?; for old in &replaced { self.remove_unused_blobs(old, &images); @@ -617,16 +727,22 @@ impl Store { /// Replaces the index with `images`, see [`crate::jsonfile::replace`]. /// Callers hold the index lock. fn write_index(&self, images: &[Image]) -> io::Result<()> { + let path = self.root.join("images.json"); let bytes = serde_json::to_vec_pretty(images).map_err(io::Error::other)?; - crate::jsonfile::replace(&self.root.join("images.json"), &bytes, crate::jsonfile::Durable::Now) + crate::jsonfile::replace(&path, &bytes, crate::jsonfile::Durable::Now)?; + let stamp = fs::metadata(&path).ok().map(|m| stamp_of(&m)); + *self.index_cache.lock().unwrap_or_else(|e| e.into_inner()) = stamp.map(|s| (Some(s), Arc::new(images.to_vec()))); + Ok(()) } } +const BLOB_WRITE_BUF: usize = 128 << 10; + /// Writes a blob to a temporary file, hashing as it goes, and only moves it /// into the store if the digest matches. #[derive(Debug)] pub struct BlobWriter { - file: File, + file: io::BufWriter, hasher: Sha256, tmp: PathBuf, dest: PathBuf, @@ -667,7 +783,8 @@ impl BlobWriter { format!("digest mismatch: expected {}, got {actual}", self.expected), )); } - self.file.sync_all()?; + self.file.flush()?; + self.file.get_ref().sync_all()?; let _one = BLOB_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let pin = Pin::take(self.dest.clone()); if blob_ready(&self.dest, self.written) { @@ -690,7 +807,7 @@ impl Drop for BlobWriter { /// See [`Store::ingest`]. #[derive(Debug)] pub struct Ingest { - file: File, + file: io::BufWriter, hasher: Sha256, tmp: PathBuf, root: PathBuf, @@ -723,7 +840,8 @@ impl Ingest { let _ = fs::remove_file(&self.tmp); return Ok((format!("sha256:{hex}"), self.written)); } - self.file.sync_all()?; + self.file.flush()?; + self.file.get_ref().sync_all()?; fs::rename(&self.tmp, dest)?; Ok((format!("sha256:{hex}"), self.written)) } @@ -741,7 +859,8 @@ impl Ingest { let _ = fs::remove_file(&self.tmp); return Ok((format!("sha256:{hex}"), self.written, pin)); } - self.file.sync_all()?; + self.file.flush()?; + self.file.get_ref().sync_all()?; fs::rename(&self.tmp, &dest)?; Ok((format!("sha256:{hex}"), self.written, pin)) } @@ -1389,4 +1508,44 @@ mod tests { fs::remove_dir_all(&root).unwrap(); } + + #[test] + fn images_arc_caches_unchanged_index_and_invalidates_on_external_write() { + let root = std::env::temp_dir().join(format!("kiri-store-cache-{}-{}", std::process::id(), TMP_SEQ.fetch_add(1, Ordering::Relaxed))); + let _ = fs::remove_dir_all(&root); + let store1 = Store::open(&root).unwrap(); + let store2 = Store::open(&root).unwrap(); + + let empty1 = store1.images_arc().unwrap(); + let empty2 = store1.images_arc().unwrap(); + assert_eq!(store1.image_count().unwrap(), 0); + assert!(Arc::ptr_eq(&empty1, &empty2)); + + let mk = |name: &str| Image { + name: name.into(), + digest: "sha256:0000000000000000000000000000000000000000000000000000000000000001".into(), + index_digest: None, + config_digest: "sha256:0000000000000000000000000000000000000000000000000000000000000001".into(), + layers: Vec::new(), + size: 1024, + platform: "linux/arm64".into(), + created: "2026-11-27T00:00:00Z".into(), + pulled_at: 1, + config: RunConfig::default(), + mirror: None, + }; + store2.put_image(mk("alpine:3.21")).unwrap(); + let after_ext = store1.images_arc().unwrap(); + assert_eq!(after_ext.len(), 1); + assert_eq!(store1.image_count().unwrap(), 1); + assert!(Arc::ptr_eq(&after_ext, &store1.images_arc().unwrap())); + + store1.put_image(mk("redis:7")).unwrap(); + let after_local = store1.images_arc().unwrap(); + assert_eq!(after_local.len(), 2); + assert!(!Arc::ptr_eq(&after_ext, &after_local)); + assert!(Arc::ptr_eq(&after_local, &store1.images_arc().unwrap())); + + fs::remove_dir_all(&root).unwrap(); + } } diff --git a/crates/kiri-init/src/linux/agent.rs b/crates/kiri-init/src/linux/agent.rs index 8b2b4ae5d..7babd2b6f 100644 --- a/crates/kiri-init/src/linux/agent.rs +++ b/crates/kiri-init/src/linux/agent.rs @@ -379,7 +379,7 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap: only a // container still running, never one exited under a freed pid. // The container's own seccomp profile goes with it, if it has one. - match running_pid(procs, spec.container_id).and_then(|pid| procs.get(&pid).map(|p| (pid, p.run.seccomp.clone()))) { + match running_pid(procs, spec.container_id) + .and_then(|pid| procs.get(&pid).map(|p| (pid, p.run.seccomp.clone(), p.run.device_filtered))) + { None => Msg::Error(&format!("container {} is not running", spec.container_id)).encode(&mut out), - Some((pid, profile)) => match container::exec(&spec, pid, paths, &profile) { + Some((pid, profile, device_filtered)) => match container::exec(&spec, pid, paths, &profile, device_filtered) { Ok(run) => { let cloned_ns = sys::boottime_ns(); Msg::Started { id: &run.id, pid: run.pid as u32, starting: false }.encode(&mut out); diff --git a/crates/kiri-init/src/linux/container.rs b/crates/kiri-init/src/linux/container.rs index fcd7459e1..afd73e283 100644 --- a/crates/kiri-init/src/linux/container.rs +++ b/crates/kiri-init/src/linux/container.rs @@ -39,7 +39,82 @@ const KEEP_CAPS: [u32; 14] = [ 29, // AUDIT_WRITE 31, // SETFCAP ]; -const LAST_CAP: u32 = 40; +const DEFAULT_LAST_CAP: u32 = 40; + +const LINUX_CAPABILITY_VERSION_3: u32 = 0x2008_0522; +const PR_CAP_AMBIENT: libc::c_int = 47; +const PR_CAP_AMBIENT_CLEAR_ALL: libc::c_ulong = 4; + +#[repr(C)] +struct CapHeader { + version: u32, + pid: i32, +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct CapData { + effective: u32, + permitted: u32, + inheritable: u32, +} + +fn parse_cap_last_cap(text: &str) -> Option { + let n: u32 = text.trim().parse().ok()?; + (n <= 1024).then_some(n) +} + +fn cap_last_cap() -> u32 { + fs::read_to_string("/proc/sys/kernel/cap_last_cap") + .ok() + .and_then(|s| parse_cap_last_cap(&s)) + .unwrap_or(DEFAULT_LAST_CAP) +} + +/// Computes the target `[CapData; 2]` for `capset(2)` from current permitted +/// capabilities (`SEC-V-02`). Intersecting with `cur.permitted` ensures we +/// never attempt to raise a capability the parent did not hold while dropping +/// every unwanted bit from `CapEff`, `CapPrm`, and clearing `CapInh`. +fn compute_cap_data(cur: [CapData; 2], uid: libc::uid_t, privileged: bool, caps: u64) -> [CapData; 2] { + if uid != 0 { + return [CapData::default(); 2]; + } + let want = if privileged { u64::MAX } else { caps }; + let lo = cur[0].permitted & (want as u32); + let hi = cur[1].permitted & ((want >> 32) as u32); + [ + CapData { effective: lo, permitted: lo, inheritable: 0 }, + CapData { effective: hi, permitted: hi, inheritable: 0 }, + ] +} + +fn apply_effective_caps(uid: libc::uid_t, privileged: bool, caps: u64) -> io::Result<()> { + // SAFETY: clearing ambient caps takes no pointers; EINVAL on old kernels is fine. + unsafe { + libc::prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0); + } + let mut hdr = CapHeader { version: LINUX_CAPABILITY_VERSION_3, pid: 0 }; + let mut cur = [CapData::default(); 2]; + // SAFETY: valid CapHeader and 2-element CapData array for version 3. + sys::check(unsafe { libc::syscall(libc::SYS_capget, &mut hdr as *mut CapHeader, cur.as_mut_ptr()) }, "capget")?; + let next = compute_cap_data(cur, uid, privileged, caps); + hdr.version = LINUX_CAPABILITY_VERSION_3; + hdr.pid = 0; + // SAFETY: valid CapHeader and 2-element CapData array for version 3. + sys::check(unsafe { libc::syscall(libc::SYS_capset, &hdr as *const CapHeader, next.as_ptr()) }, "capset")?; + Ok(()) +} + +/// Computes the effective capability mask for `docker exec`, stripping +/// `CAP_MKNOD` whenever the container's device eBPF filter failed to attach +/// (`SEC-V-03`). +fn effective_exec_caps(caps: u64, privileged: bool, device_filtered: bool) -> u64 { + if !device_filtered && !privileged { + caps & !(1 << super::devices::CAP_MKNOD) + } else { + caps + } +} const DEFAULT_PATH: &str = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; @@ -104,6 +179,10 @@ pub struct Process { /// A container's own compiled seccomp program, empty when it runs under /// the default. Its execs run under the same one. pub seccomp: Vec, + /// Whether the container's device cgroup eBPF filter attached (or the + /// container is privileged). When false, `docker exec` must also strip + /// `CAP_MKNOD` (`SEC-V-03`). + pub device_filtered: bool, /// What to undo when a container exits; None for execs. teardown: Option, /// A container whose root was not in place when `spawn` returned: the @@ -285,6 +364,7 @@ impl Process { filling: false, cancelled: false, exec_go: None, + device_filtered: false, } } @@ -979,6 +1059,7 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

, target_pid: libc::pid_t, paths: &Paths, profile: &[u8]) -> io::Result { +pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile: &[u8], device_filtered: bool) -> io::Result { if spec.argv.is_empty() { return Err(io::Error::new(io::ErrorKind::InvalidInput, "no command to run")); } @@ -1168,6 +1249,7 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile let cgroup_fd = fs::File::open(paths.cgroup.join(spec.container_id))?; let mut prepared = prepare(spec.argv, spec.env, spec.cwd, spec.user, None, spec.flags, spec.caps)?; + prepared.caps = effective_exec_caps(prepared.caps, prepared.privileged, device_filtered); // The container's ulimits, groups and AppArmor profile apply to its // execs too, as with runc. let host = super::hostopts::parse(spec.opts)?; @@ -1270,6 +1352,7 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile netns: 0, joins_netns: false, seccomp: Vec::new(), + device_filtered, teardown: None, starting: None, ended_before_ready: None, @@ -2046,7 +2129,15 @@ pub(super) fn parse_mounts(list: StrList<'_>) -> io::Result> { let target = CString::new(if rel.is_empty() { "." } else { rel })?; let ro = flags.contains(&"ro"); if flags.contains(&"tmpfs") { - let opts: Vec<&str> = flags.iter().copied().filter(|f| f.contains('=')).collect(); + let mut opts = Vec::new(); + for &f in &flags { + if f.contains('=') { + if !valid_tmpfs_opt(f) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("disallowed tmpfs option {f:?}"))); + } + opts.push(f); + } + } let opts = if opts.is_empty() { "mode=1777".to_owned() } else { opts.join(",") }; let tmpfs_flags = tmpfs_flags(&flags); let ro = tmpfs_flags & libc::MS_RDONLY != 0; @@ -2054,6 +2145,9 @@ pub(super) fn parse_mounts(list: StrList<'_>) -> io::Result> { continue; } check_vm_mount_source(src)?; + if !valid_bind_source(src, super::transport::is_host_process()) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("invalid mount source {src:?}"))); + } // A missing source becomes a directory, as Docker does; one that is // there already (a file such as /etc/hostname, too) is used as it is. // Never create a directory at /etc/localtime or /etc/timezone (#938). @@ -2217,6 +2311,25 @@ mod mount_and_etc_security_tests { } } +/// Validates a `key=val` tmpfs mount option against an explicit allowlist (`SEC-D-04`). +fn valid_tmpfs_opt(opt: &str) -> bool { + let Some((key, val)) = opt.split_once('=') else { return false }; + !val.is_empty() && matches!(key, "size" | "mode" | "uid" | "gid" | "nr_inodes" | "nr_blocks" | "mpol") +} + +/// Validates a bind mount source path (`SEC-D-04`): must be absolute with no +/// `..` traversal components, and in VM mode must not name an ancestor of +/// `/mnt/mac` whose recursive bind would bypass share isolation. +fn valid_bind_source(src: &str, host_process: bool) -> bool { + if !src.starts_with('/') || src.split('/').any(|c| c == "..") { + return false; + } + if !host_process && super::volmount::is_vm_share_ancestor(src) { + return false; + } + true +} + /// How deep a mount target is: `.` is 0, `app` 1, `app/node_modules` 2. fn depth(target: &CStr) -> usize { let t = target.to_bytes(); @@ -3079,11 +3192,19 @@ fn finish_child(p: &Prepared, io: &ChildStdio, console: bool) -> ! { apply_timer_slack(ns); } - for cap in 0..=LAST_CAP { - if !p.privileged && p.caps & (1 << cap) == 0 { - // SAFETY: PR_CAPBSET_DROP takes a capability number; EINVAL for - // capabilities this kernel does not know is fine to ignore. - unsafe { libc::prctl(libc::PR_CAPBSET_DROP, cap as libc::c_ulong, 0, 0, 0) }; + let last_cap = cap_last_cap(); + for cap in 0..=last_cap { + let keep = p.privileged || (cap < 64 && p.caps & (1u64 << cap) != 0); + if !keep { + // SAFETY: PR_CAPBSET_DROP takes a capability number; ignore only + // EINVAL (unknown capability on this kernel) and fail closed on + // any other error such as EPERM (`SEC-V-02`). + if unsafe { libc::prctl(libc::PR_CAPBSET_DROP, cap as libc::c_ulong, 0, 0, 0) } != 0 { + let e = io::Error::last_os_error(); + if e.raw_os_error() != Some(libc::EINVAL) { + fail("drop capability", e); + } + } } } @@ -3135,6 +3256,12 @@ fn finish_child(p: &Prepared, io: &ChildStdio, console: bool) -> ! { if libc::setgroups(groups.len() as _, groups.as_ptr()) != 0 || libc::setgid(gid) != 0 || libc::setuid(uid) != 0 { fail("switch user", io::Error::last_os_error()); } + } + // Explicitly reduce CapEff/CapPrm/CapInh via capset(2) before chdir, + // pid1::run() (--init never execs), or execve() (`SEC-V-02`). + apply_effective_caps(uid, p.privileged, p.caps).unwrap_or_else(|e| fail("capabilities", e)); + // SAFETY: valid NUL-terminated path in the container root. + unsafe { if libc::chdir(p.cwd.as_ptr()) != 0 { // Docker creates the whole working directory path, like mkdir -p. let _ = fs::create_dir_all(std::ffi::OsStr::from_encoded_bytes_unchecked(p.cwd.as_bytes())); @@ -3581,17 +3708,11 @@ fn api_paths(root: BorrowedFd<'_>, privileged: bool, readonly: &[CString], maske let target = proc_fd(&fd); sys::mount(&target, &target, c"none", libc::MS_BIND | libc::MS_REC, None)?; // The first descriptor is under the new bind mount; look again to - // reach the mount itself, and keep its nosuid, nodev and noexec flags. + // reach the mount itself, and remount recursively so nested submounts + // beneath `ReadonlyPaths` also become read-only (`SEC-V-10`). let Some((fd, _)) = lookup_existing(root, path)? else { continue }; let target = proc_fd(&fd); - // SAFETY: statvfs is plain data; all-zero is a valid value. - let mut st: libc::statvfs = unsafe { std::mem::zeroed() }; - // SAFETY: valid NUL-terminated path and a writable struct. - if unsafe { libc::statvfs(target.as_ptr(), &mut st) } != 0 { - return Err(io::Error::last_os_error()); - } - let keep = st.f_flag & (libc::ST_NOSUID | libc::ST_NODEV | libc::ST_NOEXEC); - sys::remount(&target, (libc::MS_BIND | libc::MS_REMOUNT | libc::MS_RDONLY) as libc::c_ulong | keep)?; + remount_ro_recursive(&target, sys::MOUNT_ATTR_RDONLY, libc::MS_RDONLY)?; } for p in masked { let null = null.ok_or_else(|| io::Error::other("no /dev/null to mask with"))?; @@ -5158,4 +5279,87 @@ mod tests { assert_eq!(std::io::Error::last_os_error().raw_os_error(), Some(libc::ESRCH)); } } + + #[test] + fn capset_data_and_dynamic_last_cap_drop_unwanted_capabilities() { + use super::{CapData, compute_cap_data, default_caps, parse_cap_last_cap}; + + assert_eq!(parse_cap_last_cap("40\n"), Some(40)); + assert_eq!(parse_cap_last_cap("45\n"), Some(45)); + assert_eq!(parse_cap_last_cap("bad"), None); + assert_eq!(parse_cap_last_cap("9999"), None); + + let full = [ + CapData { effective: u32::MAX, permitted: u32::MAX, inheritable: u32::MAX }, + CapData { effective: 0x1ff, permitted: 0x1ff, inheritable: 0x1ff }, + ]; + // --cap-drop ALL as uid 0 (encoded with high sentinel bit 63) clears all effective/permitted/inheritable caps. + let dropped = compute_cap_data(full, 0, false, 1u64 << 63); + assert_eq!(dropped, [CapData::default(); 2]); + + // Default caps as uid 0 keep only those bits in effective and permitted, with inheritable cleared. + let def = default_caps(); + let kept = compute_cap_data(full, 0, false, def); + assert_eq!(kept[0], CapData { effective: def as u32, permitted: def as u32, inheritable: 0 }); + assert_eq!(kept[1], CapData { effective: (def >> 32) as u32, permitted: (def >> 32) as u32, inheritable: 0 }); + + // Non-root user clears all capabilities even when privileged or caps set. + assert_eq!(compute_cap_data(full, 1000, true, u64::MAX), [CapData::default(); 2]); + assert_eq!(compute_cap_data(full, 1000, false, def), [CapData::default(); 2]); + + // Privileged uid 0 retains only capabilities already held in current permitted set. + let priv_caps = compute_cap_data(full, 0, true, 0); + assert_eq!(priv_caps[0], CapData { effective: u32::MAX, permitted: u32::MAX, inheritable: 0 }); + assert_eq!(priv_caps[1], CapData { effective: 0x1ff, permitted: 0x1ff, inheritable: 0 }); + } + + #[test] + fn exec_strips_cap_mknod_when_device_filter_unavailable() { + use super::{default_caps, effective_exec_caps}; + use crate::linux::devices; + + let def = default_caps(); + assert_ne!(def & (1 << devices::CAP_MKNOD), 0); + // Unfiltered non-privileged container drops CAP_MKNOD in exec. + let stripped = effective_exec_caps(def, false, false); + assert_eq!(stripped & (1 << devices::CAP_MKNOD), 0); + assert_eq!(stripped, def & !(1 << devices::CAP_MKNOD)); + // Filtered or privileged containers keep CAP_MKNOD. + assert_eq!(effective_exec_caps(def, false, true), def); + assert_eq!(effective_exec_caps(def, true, false), def); + } + + #[test] + fn submounts_under_covers_nested_readonly_paths() { + use std::path::{Path, PathBuf}; + + let mi = "\ +25 1 0:30 / /proc rw,nosuid,nodev,noexec - proc proc rw +26 25 0:31 / /proc/bus rw,nosuid,nodev,noexec - proc proc rw +27 26 0:32 / /proc/bus/usb rw,relatime - tmpfs tmpfs rw +28 25 0:33 / /proc/bus2 rw,relatime - tmpfs tmpfs rw +"; + let subs: Vec = super::submounts_under(mi, Path::new("/proc/bus")).into_iter().map(|e| e.mount_point).collect(); + assert_eq!(subs, vec![PathBuf::from("/proc/bus"), PathBuf::from("/proc/bus/usb")]); + } + + #[test] + fn bind_source_and_tmpfs_option_validation_blocks_escapes() { + use super::{valid_bind_source, valid_tmpfs_opt}; + + assert!(valid_tmpfs_opt("size=64m")); + assert!(valid_tmpfs_opt("mode=1777")); + assert!(!valid_tmpfs_opt("size=")); + assert!(!valid_tmpfs_opt("lowerdir=/mnt/mac")); + assert!(!valid_tmpfs_opt("nosuid")); + + assert!(valid_bind_source("/mnt/mac/Users/alice/app", false)); + assert!(valid_bind_source("/var/lib/kiri/volumes/v/_data", false)); + assert!(!valid_bind_source("relative/path", true)); + assert!(!valid_bind_source("/mnt/mac/Users/..", false)); + for ancestor in ["/", "/.", "///", "/mnt", "/mnt/", "/mnt/.", "//mnt", "/mnt//mac", "/mnt/./mac", "/mnt/mac", "/mnt/mac/."] { + assert!(!valid_bind_source(ancestor, false), "{ancestor:?}"); + } + assert!(valid_bind_source("/srv/app", true)); + } } diff --git a/crates/kiri-init/src/linux/copy.rs b/crates/kiri-init/src/linux/copy.rs index c23c1b6b9..50f56de2b 100644 --- a/crates/kiri-init/src/linux/copy.rs +++ b/crates/kiri-init/src/linux/copy.rs @@ -97,10 +97,12 @@ pub fn interest(fds: &mut Vec) { /// Whether `fd` is a copy child's socket; if so, answers its request: /// `m` and the container's layers, one per line, to mount its root or -/// share the mount it has; `h` to only hold a mount there is (a copy -/// into a running container, which must not outlive a restart's unmount). -/// The answer is `+`, or `-` and why not. -pub fn on_readable(fd: i32, paths: &Paths) -> bool { +/// share the mount it has; `h` to only hold a mount there is; `r` to +/// verify the container is still live in the agent, hold its root, and pass an +/// open directory descriptor for `/proc//root` via `SCM_RIGHTS` (so the +/// copy child can never chroot into a recycled PID). +/// The answer is `+` (plus an `SCM_RIGHTS` fd for `r`), or `-` and why not. +pub fn on_readable(fd: i32, paths: &Paths, live_pid: impl Fn(&str) -> Option) -> bool { CHILDREN.with_borrow_mut(|c| { let Some(ch) = c.iter_mut().find(|ch| ch.chan.as_raw_fd() == fd) else { return false }; let mut buf = vec![0u8; 64 << 10]; @@ -119,6 +121,39 @@ pub fn on_readable(fd: i32, paths: &Paths) -> bool { let mut lines = rest.split('\n'); let id = lines.next().unwrap_or(""); let layers: Vec<&str> = lines.collect(); + if kind == "r" { + let live_root = (|| -> io::Result<(PathBuf, OwnedFd)> { + let Some(pid) = live_pid(id) else { + return Err(io::Error::new(io::ErrorKind::NotFound, "container is not running")); + }; + let root = super::roots::hold(paths, id)?; + let proc_root = sys::cstr(format!("/proc/{pid}/root"))?; + // SAFETY: `pid` is an unreaped child of this single-threaded agent, + // so it cannot have been recycled; `proc_root` is NUL-terminated. + let rfd = unsafe { libc::open(proc_root.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC) }; + if rfd < 0 { + let e = io::Error::last_os_error(); + if let Some(base) = root.parent() { + super::roots::release(base); + } + return Err(e); + } + // SAFETY: `rfd` is a fresh descriptor owned only here. + Ok((root, unsafe { OwnedFd::from_raw_fd(rfd) })) + })(); + match live_root { + Ok((root, root_fd)) => { + ch.root = Some(root); + let _ = send_reply_fd(fd, root_fd.as_raw_fd()); + } + Err(e) => { + let answer = format!("-{e}"); + // SAFETY: sending from a buffer we own on a descriptor we own. + unsafe { libc::send(fd, answer.as_ptr().cast(), answer.len(), libc::MSG_NOSIGNAL) }; + } + } + return true; + } let got = match kind { "m" => super::roots::acquire(paths, id, &layers, false), "h" => super::roots::hold(paths, id), @@ -139,6 +174,30 @@ pub fn on_readable(fd: i32, paths: &Paths) -> bool { }) } +/// Sends `+` along with one descriptor (`SCM_RIGHTS`) over a `SOCK_SEQPACKET` channel. +fn send_reply_fd(sock: libc::c_int, fd: libc::c_int) -> io::Result<()> { + let mut byte = [b'+'; 1]; + let mut iov = libc::iovec { iov_base: byte.as_mut_ptr().cast(), iov_len: 1 }; + // SAFETY: CMSG_SPACE is a pure size computation. + let space = unsafe { libc::CMSG_SPACE(std::mem::size_of::() as u32) } as usize; + let mut control = vec![0u8; space]; + // SAFETY: zeroed msghdr is valid before initialization. + let mut msg: libc::msghdr = unsafe { std::mem::zeroed() }; + msg.msg_iov = &mut iov; + msg.msg_iovlen = 1; + msg.msg_control = control.as_mut_ptr().cast(); + msg.msg_controllen = space as _; + // SAFETY: `msg` points to a control buffer sized for one fd. + unsafe { + let cmsg = libc::CMSG_FIRSTHDR(&msg); + (*cmsg).cmsg_level = libc::SOL_SOCKET; + (*cmsg).cmsg_type = libc::SCM_RIGHTS; + (*cmsg).cmsg_len = libc::CMSG_LEN(std::mem::size_of::() as u32) as _; + std::ptr::write_unaligned(libc::CMSG_DATA(cmsg).cast::(), fd); + sys::check(libc::sendmsg(sock, &msg, libc::MSG_NOSIGNAL) as _, "sendmsg live root").map(drop) + } +} + /// Linux host, the agent leaving: copies still running end with it, and /// their roots go back before the exit sweep unmounts what's left. pub fn stop_all() { @@ -279,13 +338,13 @@ fn enter(spec: &CopySpec<'_>, running: &[(&str, libc::pid_t)], paths: &Paths, ch chroot_into(&paths.containers.join(spec.id).join("rootfs"))?; Ok(Vec::new()) } - // Through /proc the root shows the container's live mounts (including - // tmpfs). The copy holds the container's root meanwhile, so a restart - // can't mount a second one over the same layer while it still writes. - Some((_, pid)) => { - let _ = ask(chan, 'h', spec); + // Through an agent-validated `/proc//root` fd, showing the + // container's live mounts (including tmpfs). Never chroots by stale PID. + Some(_) => { + let root_fd = ask_live_root(chan, spec)?; let mut access = parse_mount_access(spec.mounts)?; - chroot_into(&PathBuf::from(format!("/proc/{pid}/root")))?; + chroot_into_fd(&root_fd)?; + drop(root_fd); resolve_mount_targets(&mut access); Ok(access) } @@ -348,6 +407,58 @@ fn chroot_into(root: &Path) -> io::Result<()> { Ok(()) } +fn chroot_into_fd(root_fd: &OwnedFd) -> io::Result<()> { + // SAFETY: `root_fd` is an open directory descriptor obtained from the agent. + unsafe { + sys::check(libc::fchdir(root_fd.as_raw_fd()) as _, "fchdir")?; + sys::check(libc::chroot(c".".as_ptr()) as _, "chroot")?; + sys::check(libc::chdir(c"/".as_ptr()) as _, "chdir")?; + } + Ok(()) +} + +/// Asks the agent to verify `spec.id` is still running, hold its root, and +/// return an open descriptor to its live `/proc//root`. Fails closed if +/// the container stopped or was reaped. +fn ask_live_root(chan: &OwnedFd, spec: &CopySpec<'_>) -> io::Result { + let req = format!("r{}", spec.id); + // SAFETY: sending from a buffer we own on a descriptor we own. + sys::check(unsafe { libc::send(chan.as_raw_fd(), req.as_ptr().cast(), req.len(), libc::MSG_NOSIGNAL) } as _, "ask for live root")?; + let mut buf = [0u8; 4096]; + let mut iov = libc::iovec { iov_base: buf.as_mut_ptr().cast(), iov_len: buf.len() }; + // SAFETY: CMSG_SPACE is a pure size computation. + let space = unsafe { libc::CMSG_SPACE(std::mem::size_of::() as u32) } as usize; + let mut control = vec![0u8; space]; + // SAFETY: zeroed msghdr is valid before initialization. + let mut msg: libc::msghdr = unsafe { std::mem::zeroed() }; + msg.msg_iov = &mut iov; + msg.msg_iovlen = 1; + msg.msg_control = control.as_mut_ptr().cast(); + msg.msg_controllen = space as _; + // SAFETY: receiving into buffers we own; MSG_CMSG_CLOEXEC prevents fd leaks. + let n = sys::check(unsafe { libc::recvmsg(chan.as_raw_fd(), &mut msg, libc::MSG_CMSG_CLOEXEC) } as _, "recvmsg live root")? as usize; + let mut received_fd: Option = None; + // SAFETY: inspecting control messages populated by recvmsg. + unsafe { + let cmsg = libc::CMSG_FIRSTHDR(&msg); + if !cmsg.is_null() + && (*cmsg).cmsg_level == libc::SOL_SOCKET + && (*cmsg).cmsg_type == libc::SCM_RIGHTS + && (*cmsg).cmsg_len as usize >= libc::CMSG_LEN(std::mem::size_of::() as u32) as usize + { + let fd = std::ptr::read_unaligned(libc::CMSG_DATA(cmsg).cast::()); + if fd >= 0 { + received_fd = Some(OwnedFd::from_raw_fd(fd)); + } + } + } + match buf[..n].split_first() { + Some((b'+', _)) => received_fd.ok_or_else(|| io::Error::other("agent did not send live root descriptor")), + Some((_, why)) => Err(io::Error::other(String::from_utf8_lossy(why).into_owned())), + None => Err(io::Error::other("the agent did not answer")), + } +} + /// Asks the agent for the container's root (`m`: mounted, or shared with /// whatever has it mounted now, such as the container starting meanwhile) /// or to hold the mount a running container has (`h`). Either stays until @@ -590,6 +701,16 @@ fn unpack_in( archive.set_preserve_ownerships(owner.is_none()); archive.set_unpack_xattrs(false); archive.set_overwrite(true); + let dest_fd = if owner.is_some() { + let c = sys::cstr(dest)?; + // SAFETY: `dest` is a validated existing directory. + let fd = unsafe { libc::open(c.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC) }; + sys::check(fd as _, "open dest")?; + // SAFETY: fresh descriptor owned only here. + Some(unsafe { OwnedFd::from_raw_fd(fd) }) + } else { + None + }; for entry in archive.entries()? { let mut entry = entry?; let path = entry.path()?.into_owned(); @@ -623,27 +744,18 @@ fn unpack_in( // `docker cp` and the classic build's context keep a time of 0. let target_for_err = check_path.as_deref().unwrap_or(canonical_dest); if entry.unpack_in(dest).map_err(|e| map_erofs(e, target_for_err, mounts, readonly_rootfs))? { - if let Some((uid, gid)) = owner + if let (Some((uid, gid)), Some(root_fd)) = (owner, dest_fd.as_ref()) && !etype.is_pax_global_extensions() { - let mut file_dst = dest.to_path_buf(); - for part in path.components() { - if let std::path::Component::Normal(p) = part { - file_dst.push(p); - } - } - if file_dst != dest { - let c = sys::cstr(&file_dst)?; - // SAFETY: valid NUL-terminated path inside the container chroot. - sys::check(unsafe { libc::lchown(c.as_ptr(), uid, gid) } as _, "lchown")?; - if !fs::symlink_metadata(&file_dst)?.file_type().is_symlink() - && let Ok(mode) = entry.header().mode() - && mode & 0o6000 != 0 - { - // SAFETY: valid NUL-terminated non-symlink path. - sys::check(unsafe { libc::chmod(c.as_ptr(), (mode & 0o7777) as libc::mode_t) } as _, "chmod")?; - } - } + let restore_mode = if !etype.is_symlink() + && let Ok(mode) = entry.header().mode() + && mode & 0o6000 != 0 + { + Some((mode & 0o7777) as libc::mode_t) + } else { + None + }; + chown_and_chmod_in(root_fd.as_fd(), &path, uid, gid, restore_mode)?; } super::layers::keep_zero_time(dest, &path, entry.header())?; } @@ -651,6 +763,61 @@ fn unpack_in( Ok(()) } +/// Applies `fchownat(..., AT_SYMLINK_NOFOLLOW)` and optional `fchmod` to `rel` +/// under `dest_fd` without ever following a symlink in any parent or leaf +/// component (`SEC-V-06`), preventing live-container symlink-swap TOCTOU. +fn chown_and_chmod_in( + dest_fd: std::os::fd::BorrowedFd<'_>, + rel: &Path, + uid: libc::uid_t, + gid: libc::gid_t, + restore_mode: Option, +) -> io::Result<()> { + let parts: Vec<&std::ffi::OsStr> = rel + .components() + .filter_map(|c| match c { + std::path::Component::Normal(p) => Some(p), + _ => None, + }) + .collect(); + let Some((leaf, parents)) = parts.split_last() else { + return Ok(()); + }; + let mut cur: Option = None; + for part in parents { + let dir = cur.as_ref().map_or(dest_fd.as_raw_fd(), |f| f.as_raw_fd()); + let c = sys::cstr(Path::new(part))?; + // SAFETY: valid directory fd and NUL-terminated single component; + // O_DIRECTORY | O_NOFOLLOW refuses any symlink swapped in by a live container. + let next = unsafe { libc::openat(dir, c.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC) }; + sys::check(next as _, "open parent for chown")?; + // SAFETY: fresh descriptor owned only here. + cur = Some(unsafe { OwnedFd::from_raw_fd(next) }); + } + let parent = cur.as_ref().map_or(dest_fd.as_raw_fd(), |f| f.as_raw_fd()); + let leaf_c = sys::cstr(Path::new(leaf))?; + // SAFETY: confined non-symlink parent fd and single NUL-terminated component; + // AT_SYMLINK_NOFOLLOW never follows a leaf symlink. + sys::check(unsafe { libc::fchownat(parent, leaf_c.as_ptr(), uid, gid, libc::AT_SYMLINK_NOFOLLOW) } as _, "fchownat")?; + if let Some(mode) = restore_mode { + // SAFETY: open without following symlinks and without blocking on FIFOs. + let fd = unsafe { libc::openat(parent, leaf_c.as_ptr(), libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC) }; + sys::check(fd as _, "open for fchmod")?; + // SAFETY: fresh descriptor owned only here. + let fd = unsafe { OwnedFd::from_raw_fd(fd) }; + // SAFETY: zeroed stat filled from our own descriptor. + let mut st: libc::stat = unsafe { std::mem::zeroed() }; + sys::check(unsafe { libc::fstat(fd.as_raw_fd(), &mut st) } as _, "fstat for fchmod")?; + let kind = st.st_mode & libc::S_IFMT; + if kind != libc::S_IFREG && kind != libc::S_IFDIR { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "refusing to chmod special file")); + } + // SAFETY: fchmod operates directly on the pinned non-symlink descriptor. + sys::check(unsafe { libc::fchmod(fd.as_raw_fd(), mode) } as _, "fchmod")?; + } + Ok(()) +} + /// A `copy_flags::CHUNKED` archive: chunks of `len: u32 LE | bytes`, read /// as one stream that ends at the empty chunk, with the connection still /// open for the answer. @@ -1027,6 +1194,7 @@ fn in_lower_layers(lowers: &[OwnedFd], rel: &std::path::Path) -> bool { /// `docker diff` and `docker commit`, from the writable layer. fn layer_job(conn: &mut fs::File, spec: &CopySpec<'_>, paths: &Paths) -> io::Result<()> { + container::valid_id(spec.id)?; if spec.layers.is_empty() { return reply_error(conn, "no such container"); } @@ -1156,7 +1324,12 @@ fn upper_job(conn: &mut fs::File, spec: &CopySpec<'_>, running: &[(&str, libc::p /// beside it first and moved in whole, so a copy cut short leaves the /// container as it was; overlayfs's own attributes are stripped, and the /// layer is marked plain (`container::mark_plain_upper`). -fn import_upper(mut reader: impl Read, base: &Path) -> io::Result<()> { +fn import_upper(reader: impl Read, base: &Path) -> io::Result<()> { + import_upper_capped(reader, base, super::layers::MAX_IMPORT_BYTES) +} + +fn import_upper_capped(reader: impl Read, base: &Path, max_bytes: u64) -> io::Result<()> { + let mut reader = super::layers::Capped::new(reader, max_bytes); let upper = base.join("upper"); let staging = base.join("upper.import"); fs::create_dir_all(base)?; @@ -1753,4 +1926,95 @@ mod tests { assert_eq!(sizes, vec![PACED_CHUNK, 1234]); assert_eq!(received, expected); } + + #[test] + fn layer_job_rejects_path_traversal_id() { + let base = std::env::temp_dir().join(format!("kiri-copy-layer-id-{}", std::process::id())); + let _ = fs::remove_dir_all(&base); + fs::create_dir_all(&base).unwrap(); + let paths = Paths { layers: base.join("layers"), containers: base.join("containers"), cgroup: base.join("cg"), cgroup_root: base.join("cg") }; + let mut buf = Vec::new(); + kiri_proto::encode_copy(&mut buf, copy_op::DIFF, "../escape", "", 0, &["sha256:0000000000000000000000000000000000000000000000000000000000000000"], &[] as &[&str]); + let kiri_proto::Msg::Copy(spec) = kiri_proto::decode(&buf).unwrap() else { panic!() }; + let mut dummy = fs::File::open("/dev/null").unwrap(); + let err = layer_job(&mut dummy, &spec, &paths).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidInput); + let _ = fs::remove_dir_all(&base); + } + + #[test] + fn import_upper_enforces_byte_cap() { + let base = std::env::temp_dir().join(format!("kiri-import-cap-{}", std::process::id())); + let _ = fs::remove_dir_all(&base); + let mut b = tar::Builder::new(Vec::new()); + let data = vec![b'a'; 4096]; + let mut h = tar::Header::new_ustar(); + h.set_entry_type(tar::EntryType::Regular); + h.set_size(data.len() as u64); + h.set_mode(0o644); + h.set_uid(0); + h.set_gid(0); + h.set_mtime(1); + b.append_data(&mut h, "big", &data[..]).unwrap(); + let bytes = b.into_inner().unwrap(); + let err = import_upper_capped(&bytes[..], &base, 1024).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + assert!(!base.join("upper").exists() && !base.join("upper.import").exists()); + let _ = fs::remove_dir_all(&base); + } + + #[test] + fn chown_and_chmod_in_refuses_parent_and_leaf_symlinks() { + let base = std::env::temp_dir().join(format!("kiri-copy-toctou-{}", std::process::id())); + let _ = fs::remove_dir_all(&base); + let dest = base.join("dest"); + let outside = base.join("outside"); + fs::create_dir_all(&dest).unwrap(); + fs::create_dir_all(&outside).unwrap(); + fs::write(outside.join("secret"), b"ok").unwrap(); + // Swapped parent directory symlink pointing outside `dest`. + std::os::unix::fs::symlink(&outside, dest.join("dir")).unwrap(); + // Swapped leaf symlink pointing outside `dest`. + std::os::unix::fs::symlink(outside.join("secret"), dest.join("leaf")).unwrap(); + + let c = sys::cstr(&dest).unwrap(); + // SAFETY: `dest` is a directory we just created. + let fd = unsafe { libc::open(c.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC) }; + assert!(fd >= 0); + // SAFETY: fresh descriptor. + let dest_fd = unsafe { OwnedFd::from_raw_fd(fd) }; + + // SAFETY: plain getters. + let (uid, gid) = unsafe { (libc::geteuid(), libc::getegid()) }; + // Intermediate symlink must fail (never traverse into `outside`). + assert!(chown_and_chmod_in(dest_fd.as_fd(), Path::new("dir/secret"), uid, gid, Some(0o4755)).is_err()); + // Leaf symlink with chmod must fail with ELOOP (never chmod target). + assert!(chown_and_chmod_in(dest_fd.as_fd(), Path::new("leaf"), uid, gid, Some(0o4755)).is_err()); + assert_eq!(fs::symlink_metadata(outside.join("secret")).unwrap().mode() & 0o6000, 0); + let _ = fs::remove_dir_all(&base); + } + + #[test] + fn ask_live_root_fails_closed_when_agent_refuses_stopped_container() { + let mut pair = [0; 2]; + // SAFETY: socketpair creates two fresh descriptors. + assert_eq!(unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_SEQPACKET | libc::SOCK_CLOEXEC, 0, pair.as_mut_ptr()) }, 0); + // SAFETY: fresh descriptors from socketpair. + let (agent_end, child_end) = unsafe { (OwnedFd::from_raw_fd(pair[0]), OwnedFd::from_raw_fd(pair[1])) }; + let mut buf = Vec::new(); + kiri_proto::encode_copy(&mut buf, copy_op::STAT, "dead123", "/", 0, &[] as &[&str], &[] as &[&str]); + let kiri_proto::Msg::Copy(spec) = kiri_proto::decode(&buf).unwrap() else { panic!() }; + let t = std::thread::spawn(move || { + let mut req = [0u8; 64]; + // SAFETY: reading from descriptor we own. + let n = unsafe { libc::recv(agent_end.as_raw_fd(), req.as_mut_ptr().cast(), req.len(), 0) }; + assert_eq!(&req[..n as usize], b"rdead123"); + let reply = b"-container is not running"; + // SAFETY: writing to descriptor we own. + unsafe { libc::send(agent_end.as_raw_fd(), reply.as_ptr().cast(), reply.len(), libc::MSG_NOSIGNAL) }; + }); + let err = ask_live_root(&child_end, &spec).unwrap_err(); + assert!(err.to_string().contains("not running"), "{err}"); + t.join().unwrap(); + } } diff --git a/crates/kiri-init/src/linux/firewall.rs b/crates/kiri-init/src/linux/firewall.rs index e63aa7cb0..4f82310f7 100644 --- a/crates/kiri-init/src/linux/firewall.rs +++ b/crates/kiri-init/src/linux/firewall.rs @@ -480,7 +480,12 @@ const ZONE_TRUSTED: &str = "trusted"; const POLICY_FORWARDING: &str = "kiri-forwarding"; fn firewall_cmd_out(cmd: &Path, args: &[&str]) -> Result { - match std::process::Command::new(cmd).args(args).stdin(std::process::Stdio::null()).output() { + match std::process::Command::new(cmd) + .env("PATH", TRUSTED_PATH) + .args(args) + .stdin(std::process::Stdio::null()) + .output() + { Ok(o) if o.status.success() => Ok(String::from_utf8_lossy(&o.stdout).into_owned()), Ok(o) => Err(String::from_utf8_lossy(&o.stderr).trim().to_owned()), Err(e) => Err(e.to_string()), @@ -620,6 +625,7 @@ fn stop(st: &mut State) { /// Runs an administrator's program; its output when it succeeded. fn run(tool: &Path, args: &[&str]) -> Option { let mut cmd = std::process::Command::new(tool); + cmd.env("PATH", TRUSTED_PATH); if tool.file_name().is_some_and(|n| n.to_string_lossy().contains("tables")) { // Waits for another program holding the xtables lock (ufw, Docker). cmd.args(["-w", "5"]); @@ -648,15 +654,20 @@ fn write_warnings(st: &mut State, text: String) { st.warnings = text; } -/// An administrator's program (iptables) by name, wherever the host keeps -/// it: the agent's PATH may lack the sbin folders. +const TRUSTED_SBIN_DIRS: [&str; 4] = ["/usr/sbin", "/sbin", "/usr/bin", "/bin"]; +const TRUSTED_PATH: &str = "/usr/sbin:/sbin:/usr/bin:/bin"; + +/// An administrator's program (`iptables`, `firewall-cmd`) by name, resolved +/// exclusively from trusted system directories — never from inherited `PATH`. fn sbin(name: &str) -> Option { - let path = std::env::var("PATH").unwrap_or_default(); - path.split(':') - .chain(["/usr/sbin", "/sbin", "/usr/local/sbin", "/usr/bin", "/bin"]) - .filter(|d| !d.is_empty()) + sbin_in(name, &TRUSTED_SBIN_DIRS) +} + +fn sbin_in(name: &str, dirs: &[&str]) -> Option { + use std::os::unix::fs::MetadataExt; + dirs.iter() .map(|d| Path::new(d).join(name)) - .find(|p| p.is_file()) + .find(|p| std::fs::metadata(p).is_ok_and(|m| m.is_file() && (m.mode() & 0o111 != 0))) } #[cfg(test)] @@ -804,4 +815,29 @@ mod tests { assert!(compute_forwarding_blocked(false, true, false)); assert!(compute_forwarding_blocked(false, false, true)); } + + #[test] + fn sbin_ignores_inherited_path_and_requires_executable_bit() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("kiri-firewall-sbin-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let fake = dir.join("kiri-fake-iptables-tool"); + std::fs::write(&fake, "#!/bin/sh\nexit 0\n").unwrap(); + std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o644)).unwrap(); + + // Non-executable file in a searched directory is ignored. + let dir_str = dir.to_str().unwrap(); + assert_eq!(sbin_in("kiri-fake-iptables-tool", &[dir_str]), None); + + // Executable file in an explicitly searched directory is found. + std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap(); + assert_eq!(sbin_in("kiri-fake-iptables-tool", &[dir_str]), Some(fake.clone())); + + // `sbin()` never searches inherited `PATH` (only TRUSTED_SBIN_DIRS). + assert!(!TRUSTED_SBIN_DIRS.contains(&dir_str)); + assert_eq!(sbin("kiri-fake-iptables-tool"), None); + + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/kiri-init/src/linux/hostopts.rs b/crates/kiri-init/src/linux/hostopts.rs index 827271e2e..908e277e1 100644 --- a/crates/kiri-init/src/linux/hostopts.rs +++ b/crates/kiri-init/src/linux/hostopts.rs @@ -105,7 +105,19 @@ pub fn parse(list: StrList<'_>) -> io::Result { let first = path.split('/').next().unwrap_or(""); let allowed = match ns { Ns::Net => first == "net", - Ns::Ipc => (first == "kernel" && path.split('/').count() == 2) || path.starts_with("fs/mqueue/"), + Ns::Ipc => { + matches!( + *path, + "kernel/msgmax" + | "kernel/msgmnb" + | "kernel/msgmni" + | "kernel/sem" + | "kernel/shmall" + | "kernel/shmmax" + | "kernel/shmmni" + | "kernel/shm_rmid_forced" + ) || path.starts_with("fs/mqueue/") + } Ns::Uts => *path == "kernel/domainname", }; if !allowed || path.split('/').any(|c| c.is_empty() || c == "." || c == "..") { @@ -115,10 +127,13 @@ pub fn parse(list: StrList<'_>) -> io::Result { } ["device", host, container, perms] => { for p in [host, container] { - if !p.starts_with('/') || p.split('/').any(|c| c == "..") { + if !p.starts_with('/') || p.contains(['\r', '\0']) || p.split('/').any(|c| c == "..") { return Err(bad(line)); } } + if !is_dev_path(host) { + return Err(bad(line)); + } devices::access_bits(perms).ok_or_else(|| bad(line))?; o.devices.push(Device { host: (*host).to_owned(), container: (*container).to_owned(), perms: (*perms).to_owned() }); } @@ -158,6 +173,16 @@ fn valid_profile(name: &str) -> bool { !name.is_empty() && name.len() <= 255 && name.bytes().all(|b| b.is_ascii_graphic()) } +/// Maximum recursion depth for `--device

` walks (prevents stack exhaustion). +const MAX_DEVICE_DEPTH: usize = 16; +/// Maximum number of device nodes gathered from one `--device` entry. +const MAX_DEVICE_NODES: usize = 1024; + +/// Whether a host device path stays under `/dev`. +fn is_dev_path(path: &str) -> bool { + path == "/dev" || path.starts_with("/dev/") +} + /// Docker's error for a device it cannot add. fn gather_error(path: &str, e: impl std::fmt::Display) -> io::Error { io::Error::other(format!("error gathering device information while adding custom device {path:?}: {e}")) @@ -169,11 +194,18 @@ pub fn resolve_devices(opts: &HostOpts) -> io::Result<(Vec, Vec)> { let mut nodes = Vec::new(); let mut rules = opts.rules.clone(); for d in &opts.devices { + if !is_dev_path(&d.host) { + return Err(gather_error(&d.host, "device path must be under /dev")); + } let access = devices::access_bits(&d.perms).unwrap_or(devices::MKNOD | devices::READ | devices::WRITE); - let meta = fs::metadata(&d.host).map_err(|e| gather_error(&d.host, errno_text(&e)))?; + let real = fs::canonicalize(&d.host).map_err(|e| gather_error(&d.host, errno_text(&e)))?; + if !real.starts_with("/dev") { + return Err(gather_error(&d.host, "resolved device path escapes /dev")); + } + let meta = fs::symlink_metadata(&real).map_err(|e| gather_error(&d.host, errno_text(&e)))?; let mut found = Vec::new(); if meta.is_dir() { - walk(Path::new(&d.host), Path::new(&d.container), &mut found)?; + walk(&real, Path::new(&d.container), 0, &mut found)?; } else if meta.file_type().is_char_device() || meta.file_type().is_block_device() { found.push((d.container.clone(), meta)); } else { @@ -191,13 +223,23 @@ pub fn resolve_devices(opts: &HostOpts) -> io::Result<(Vec, Vec)> { } /// Device nodes under `host`, each with its path under `container`. -fn walk(host: &Path, container: &Path, out: &mut Vec<(String, fs::Metadata)>) -> io::Result<()> { +/// Never follows symlinks and enforces bounded depth and node count (`FS-10`). +fn walk(host: &Path, container: &Path, depth: usize, out: &mut Vec<(String, fs::Metadata)>) -> io::Result<()> { + if depth >= MAX_DEVICE_DEPTH { + return Err(gather_error(&host.to_string_lossy(), "device directory exceeds maximum depth")); + } for e in fs::read_dir(host).map_err(|e| gather_error(&host.to_string_lossy(), errno_text(&e)))?.flatten() { - let Ok(m) = fs::metadata(e.path()) else { continue }; + let Ok(m) = fs::symlink_metadata(e.path()) else { continue }; + if m.file_type().is_symlink() { + continue; + } let target = container.join(e.file_name()); if m.is_dir() { - walk(&e.path(), &target, out)?; + walk(&e.path(), &target, depth + 1, out)?; } else if m.file_type().is_char_device() || m.file_type().is_block_device() { + if out.len() >= MAX_DEVICE_NODES { + return Err(gather_error(&host.to_string_lossy(), "too many device nodes")); + } out.push((target.to_string_lossy().into_owned(), m)); } } @@ -538,4 +580,61 @@ mod tests { let e = apply_sysctls(me, None, &[s]).unwrap_err(); assert_eq!(e.to_string(), "sysctl \"net.ipv4.ip_unprivileged_port_start\" not allowed in host net namespace"); } + + #[test] + fn ipc_sysctls_allow_only_ipc_namespaced_keys() { + for ok in [ + "sysctl\tipc\tkernel/msgmax\t8192", + "sysctl\tipc\tkernel/msgmnb\t16384", + "sysctl\tipc\tkernel/msgmni\t32000", + "sysctl\tipc\tkernel/sem\t250 32000 32 128", + "sysctl\tipc\tkernel/shmall\t4294967296", + "sysctl\tipc\tkernel/shmmax\t68719476736", + "sysctl\tipc\tkernel/shmmni\t4096", + "sysctl\tipc\tkernel/shm_rmid_forced\t1", + "sysctl\tipc\tfs/mqueue/msg_max\t10", + ] { + let buf = list(&[ok]); + let kiri_proto::Msg::Retain(l) = kiri_proto::decode(&buf).unwrap() else { panic!() }; + assert!(parse(l).is_ok(), "{ok}"); + } + for bad in [ + "sysctl\tipc\tkernel/core_pattern\t|/bin/sh", + "sysctl\tipc\tkernel/modprobe\t/tmp/x", + "sysctl\tipc\tkernel/poweroff_cmd\t/tmp/x", + "sysctl\tipc\tkernel/sysrq\t1", + "sysctl\tipc\tkernel/hostname\tx", + ] { + let buf = list(&[bad]); + let kiri_proto::Msg::Retain(l) = kiri_proto::decode(&buf).unwrap() else { panic!() }; + assert!(parse(l).is_err(), "{bad}"); + } + } + + #[test] + fn device_walk_ignores_symlinks_enforces_depth_and_dev_containment() { + for bad in ["device\t/tmp/fake\t/dev/fake\trwm", "device\t/etc/passwd\t/dev/x\trwm", "device\t/dev2/null\t/dev/null\trwm", "device\t/dev/null\r\t/dev/null\trwm"] { + let buf = list(&[bad]); + let kiri_proto::Msg::Retain(l) = kiri_proto::decode(&buf).unwrap() else { panic!() }; + assert!(parse(l).is_err(), "{bad:?}"); + } + let dir = std::env::temp_dir().join(format!("kiri-hostopts-devwalk-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + // Self-loop symlink and symlink to /dev must be skipped without recursing or escaping. + std::os::unix::fs::symlink(".", dir.join("loop")).unwrap(); + std::os::unix::fs::symlink("/dev", dir.join("escape")).unwrap(); + let mut out = Vec::new(); + walk(&dir, Path::new("/dev/test"), 0, &mut out).unwrap(); + assert!(out.is_empty(), "symlinks must not be followed: {out:?}"); + + // Excessive directory nesting fails cleanly at MAX_DEVICE_DEPTH. + let mut deep = dir.join("deep"); + for i in 0..=MAX_DEVICE_DEPTH { + deep.push(format!("d{i}")); + } + fs::create_dir_all(&deep).unwrap(); + assert!(walk(&dir.join("deep"), Path::new("/dev/deep"), 0, &mut out).is_err()); + let _ = fs::remove_dir_all(&dir); + } } diff --git a/crates/kiri-init/src/linux/layers.rs b/crates/kiri-init/src/linux/layers.rs index c10deaea9..cade804c9 100644 --- a/crates/kiri-init/src/linux/layers.rs +++ b/crates/kiri-init/src/linux/layers.rs @@ -158,6 +158,33 @@ pub fn retain<'a>(root: &Path, keep: impl Iterator) { } } +/// Maximum uncompressed bytes accepted by `copy::import_upper` (the same +/// ceiling as one layer, `kiri_proto::LAYER_UNPACK_MAX`). +pub(super) const MAX_IMPORT_BYTES: u64 = kiri_proto::LAYER_UNPACK_MAX; + +/// A reader that fails once more than `left` bytes have come through. +pub(super) struct Capped { + pub(super) inner: R, + pub(super) left: u64, +} + +impl Capped { + pub(super) fn new(inner: R, max_bytes: u64) -> Self { + Self { inner, left: max_bytes } + } +} + +impl Read for Capped { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let n = self.inner.read(buf)?; + if n as u64 > self.left { + return Err(io::Error::new(io::ErrorKind::InvalidData, "layer expands beyond its allowed size")); + } + self.left -= n as u64; + Ok(n) + } +} + struct Packed<'a, R> { inner: R, meter: &'a UnpackMeter, @@ -246,7 +273,9 @@ fn untar_in(reader: impl Read, dest: &Path, detect_userns: fn() -> bool) -> io:: archive.set_preserve_permissions(true); archive.set_preserve_ownerships(true); archive.set_preserve_mtime(true); - archive.set_unpack_xattrs(true); + // Unpack xattrs selectively via `allowed_xattrs` so untrusted OCI layers + // cannot plant `trusted.overlay.*` or `user.kiri.*` xattrs as root. + archive.set_unpack_xattrs(false); archive.set_overwrite(true); let mut total = 0u64; // Each directory's time, set once the layer is unpacked: tar-rs gives a @@ -312,14 +341,18 @@ fn untar_in(reader: impl Read, dest: &Path, detect_userns: fn() -> bool) -> io:: } } make_special(dest, &path, entry.header(), kind, userns)?; - } else if unpack_replacing(&mut entry, dest, &path)? { - keep_zero_time(dest, &path, entry.header())?; - if entry.header().entry_type().is_dir() - && let Ok(mtime) = entry.header().mtime() - { - // By its plain names: `./usr` and `usr` are one directory. - let plain = path.components().filter(|c| matches!(c, std::path::Component::Normal(_))).collect(); - dir_times.push((plain, mtime)); + } else { + let xattrs = if entry.header().entry_type().is_symlink() { Vec::new() } else { allowed_xattrs(&mut entry)? }; + if unpack_replacing(&mut entry, dest, &path)? { + apply_xattrs(dest, &path, &xattrs)?; + keep_zero_time(dest, &path, entry.header())?; + if entry.header().entry_type().is_dir() + && let Ok(mtime) = entry.header().mtime() + { + // By its plain names: `./usr` and `usr` are one directory. + let plain = path.components().filter(|c| matches!(c, std::path::Component::Normal(_))).collect(); + dir_times.push((plain, mtime)); + } } } } @@ -328,6 +361,86 @@ fn untar_in(reader: impl Read, dest: &Path, detect_userns: fn() -> bool) -> io:: Ok(total) } +/// Whether a PAX `SCHILY.xattr.` extended attribute from an untrusted +/// archive is permitted on an unpacked layer entry (`SEC-V-05`). +/// +/// Only `security.capability` and non-Kiri `user.*` xattrs are allowed; +/// `trusted.*` (including `trusted.overlay.*`) and `user.kiri.*` are rejected +/// so untrusted OCI layers cannot forge overlayfs or Kiri internal metadata. +fn xattr_allowed(name: &[u8]) -> bool { + if name == b"security.capability" { + return true; + } + name.starts_with(b"user.") && !name.starts_with(b"user.kiri.") && name.len() > b"user.".len() +} + +fn allowed_xattrs(entry: &mut tar::Entry<'_, R>) -> io::Result)>> { + let mut out = Vec::new(); + let Some(exts) = entry.pax_extensions()? else { + return Ok(out); + }; + for ext in exts { + let ext = ext?; + let Some(name) = ext.key_bytes().strip_prefix(b"SCHILY.xattr.") else { + continue; + }; + if !xattr_allowed(name) { + continue; + } + let Ok(cname) = CString::new(name) else { + continue; + }; + out.push((cname, ext.value_bytes().to_vec())); + } + Ok(out) +} + +fn apply_xattrs(dest: &Path, path: &Path, xattrs: &[(CString, Vec)]) -> io::Result<()> { + if xattrs.is_empty() { + return Ok(()); + } + let mut has_normal = false; + for c in path.components() { + match c { + std::path::Component::Normal(_) => has_normal = true, + std::path::Component::CurDir | std::path::Component::RootDir => {} + std::path::Component::ParentDir | std::path::Component::Prefix(_) => return Err(escapes()), + } + } + let root = inroot::open_root(dest)?; + let fd = if has_normal { + let (parent, name) = hardlink_parent(root.as_fd(), path)?; + // SAFETY: confined parent directory fd and NUL-terminated leaf name. + let raw = unsafe { libc::openat(parent.as_raw_fd(), name.as_ptr(), libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC) }; + if raw < 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: fresh descriptor owned only here. + unsafe { OwnedFd::from_raw_fd(raw) } + } else { + root + }; + // SAFETY: zeroed stat filled from our own descriptor. + let mut st: libc::stat = unsafe { std::mem::zeroed() }; + sys::check(unsafe { libc::fstat(fd.as_raw_fd(), &mut st) } as _, "fstat xattr target")?; + if st.st_mode & libc::S_IFMT == libc::S_IFLNK { + return Ok(()); + } + let proc_path = CString::new(format!("/proc/self/fd/{}", fd.as_raw_fd())).expect("no NUL"); + for (attr, val) in xattrs { + // SAFETY: `proc_path` resolves directly to our pinned non-symlink inode; + // `attr` is NUL-terminated and `val` is valid for `val.len()` bytes. + let ret = unsafe { libc::setxattr(proc_path.as_ptr(), attr.as_ptr(), val.as_ptr().cast(), val.len(), 0) }; + if ret != 0 { + let e = io::Error::last_os_error(); + if !matches!(e.raw_os_error(), Some(libc::EOPNOTSUPP | libc::EPERM | libc::EACCES)) { + return Err(io::Error::new(e.kind(), format!("setxattr {}: {e}", attr.to_string_lossy()))); + } + } + } + Ok(()) +} + /// Sets each directory's time once the layer is unpacked (#676): deepest /// first, as Docker sets them, and the last entry's time for a directory /// named twice. One a later entry removed, or made something else, is @@ -1882,4 +1995,69 @@ mod tests { let _ = fs::remove_dir_all(&root); } + + #[test] + fn xattr_allowlist_blocks_overlay_and_kiri_internal_xattrs() { + assert!(xattr_allowed(b"security.capability")); + assert!(xattr_allowed(b"user.app.tag")); + for bad in [ + &b"trusted.overlay.redirect"[..], + b"trusted.overlay.metacopy", + b"trusted.overlay.origin", + b"trusted.overlay.impure", + b"trusted.overlay.opaque", + b"trusted.anything", + b"user.kiri.mountpoint", + b"user.kiri.other", + b"user.", + b"security.selinux", + b"system.posix_acl_access", + ] { + assert!(!xattr_allowed(bad), "{:?}", String::from_utf8_lossy(bad)); + } + + // Unpacking an archive carrying forged overlay/kiri xattrs never writes them to disk. + let mut b = tar::Builder::new(Vec::new()); + b.append_pax_extensions([ + ("SCHILY.xattr.trusted.overlay.redirect", &b"/etc"[..]), + ("SCHILY.xattr.trusted.overlay.metacopy", &b""[..]), + ("SCHILY.xattr.trusted.overlay.opaque", &b"y"[..]), + ("SCHILY.xattr.user.kiri.mountpoint", &b"1"[..]), + ]) + .unwrap(); + b.append_data(&mut header(4, 0o644), "file", &b"data"[..]).unwrap(); + let bytes = b.into_inner().unwrap(); + let dest = scratch("xattr-filter"); + untar(Capped::new(&bytes[..], u64::MAX), &dest).unwrap(); + let c = sys::cstr(dest.join("file")).unwrap(); + for attr in [c"trusted.overlay.redirect", c"trusted.overlay.metacopy", c"trusted.overlay.opaque", c"user.kiri.mountpoint"] { + // SAFETY: valid NUL-terminated path and xattr name; size query. + let n = unsafe { libc::lgetxattr(c.as_ptr(), attr.as_ptr(), std::ptr::null_mut(), 0) }; + assert!(n < 0, "forbidden xattr {:?} persisted on disk", attr); + } + let _ = fs::remove_dir_all(&dest); + } + + #[test] + fn root_dot_entry_with_allowed_xattr_unpacks_cleanly() { + let mut b = tar::Builder::new(Vec::new()); + b.append_pax_extensions([("SCHILY.xattr.user.root_tag", &b"ok"[..])]).unwrap(); + let mut h = tar::Header::new_ustar(); + h.set_entry_type(tar::EntryType::Directory); + h.set_path(".").unwrap(); + h.set_size(0); + h.set_mode(0o755); + h.set_cksum(); + b.append(&h, &[][..]).unwrap(); + b.append_data(&mut header(2, 0o644), "ok", &b"hi"[..]).unwrap(); + let bytes = b.into_inner().unwrap(); + let dest = scratch("xattr-root-dot"); + untar(Capped::new(&bytes[..], u64::MAX), &dest).unwrap(); + assert_eq!(fs::read(dest.join("ok")).unwrap(), b"hi"); + // Direct apply_xattrs on `.` succeeds while `..` is rejected as an escape. + let allowed = vec![(CString::new("user.root_tag").unwrap(), b"v".to_vec())]; + apply_xattrs(&dest, Path::new("."), &allowed).unwrap(); + assert!(apply_xattrs(&dest, Path::new("../escape"), &allowed).is_err()); + let _ = fs::remove_dir_all(&dest); + } } diff --git a/crates/kiri-init/src/linux/mod.rs b/crates/kiri-init/src/linux/mod.rs index fd902dd7d..b1204694e 100644 --- a/crates/kiri-init/src/linux/mod.rs +++ b/crates/kiri-init/src/linux/mod.rs @@ -129,6 +129,7 @@ fn run(init_start_ns: u64) -> io::Result<()> { } else { leave_initramfs()?; mount_kernel_filesystems()?; + spread_vm_irqs(); sys::sethostname(b"kiri")?; // Containers may bind the VM's /etc/hostname, as on a Linux host. let _ = std::fs::write("/etc/hostname", "kiri\n"); @@ -191,6 +192,125 @@ fn leave_initramfs() -> io::Result<()> { Ok(()) } +/// Parses a Linux sysfs CPU list (e.g. `"0-7"` or `"0,2,4-5"`) into sorted, +/// deduplicated online CPU IDs. +pub(crate) fn parse_cpu_list(raw: &str) -> Vec { + let mut cpus = Vec::new(); + for part in raw.trim().split(',').filter(|p| !p.is_empty()) { + if let Some((a, b)) = part.split_once('-') { + if let (Ok(start), Ok(end)) = (a.trim().parse::(), b.trim().parse::()) { + if start <= end && end - start < 4096 { + cpus.extend(start..=end); + } + } + } else if let Ok(id) = part.trim().parse::() { + cpus.push(id); + } + } + cpus.sort_unstable(); + cpus.dedup(); + cpus +} + +/// Returns the guest's online CPU IDs from `/sys/devices/system/cpu/online`, +/// falling back to `0..available_parallelism()`. +pub(crate) fn online_cpu_ids() -> Vec { + if let Ok(raw) = std::fs::read_to_string("/sys/devices/system/cpu/online") { + let ids = parse_cpu_list(&raw); + if !ids.is_empty() { + return ids; + } + } + let n = std::thread::available_parallelism().map_or(1, std::num::NonZero::get); + (0..n).collect() +} + +/// Distributes virtio device interrupts across online vCPUs inside the VM so +/// `virtio-blk`, `vsock`, and `virtio-balloon` do not pile onto CPU 0 alongside +/// `virtio-net` hardirqs (GICv3 defaults all SPIs to CPU 0). Best-effort: +/// missing `/proc/irq` entries or fixed-affinity controllers are skipped. +fn spread_vm_irqs() { + let cpus = online_cpu_ids(); + if cpus.len() <= 1 { + return; + } + let Ok(interrupts) = std::fs::read_to_string("/proc/interrupts") else { return }; + let net_dev = virtio_net_dev_name(); + // Only pin the uplink to CPU 0 when it uses a single RX queue (Apple VZ); + // multiqueue MSI-X uplinks keep their own per-queue affinities untouched. + let pin_net_to_cpu0 = net::rx_queue_count(net::UPLINK) <= 1; + for (irq, cpu) in plan_virtio_irq_cpus(&interrupts, net_dev.as_deref(), pin_net_to_cpu0, &cpus) { + let _ = std::fs::write(format!("/proc/irq/{irq}/smp_affinity_list"), format!("{cpu}\n")); + } +} + +/// Resolves `eth0`'s backing virtio device name (e.g. `"virtio0"`) from sysfs. +fn virtio_net_dev_name() -> Option { + let target = std::fs::read_link(format!("/sys/class/net/{}/device", net::UPLINK)).ok()?; + let name = target.file_name()?.to_str()?; + name.starts_with("virtio").then(|| name.to_owned()) +} + +/// Matches a `/proc/interrupts` handler token to a virtio device name +/// (`"virtio0"` matches `"virtio0"` and `"virtio0-input.0"`, not `"virtio00"`). +fn handler_matches_dev(handler: &str, dev: &str) -> bool { + handler == dev || handler.strip_prefix(dev).is_some_and(|rest| rest.starts_with('-')) +} + +/// Plans `(irq, target_cpu)` assignments from `/proc/interrupts`: when +/// `pin_net_to_cpu0` is true (single-queue uplink), pins the uplink +/// `virtio-net` device to the first online CPU so `eth0` hardirq/NAPI aligns +/// with RPS steering; when false (multiqueue uplink), skips uplink IRQs so +/// driver-managed per-queue affinities stay intact. All other virtio IRQs are +/// spread round-robin across the remaining online CPUs. +fn plan_virtio_irq_cpus( + proc_interrupts: &str, + net_virtio_dev: Option<&str>, + pin_net_to_cpu0: bool, + online_cpus: &[usize], +) -> Vec<(u32, usize)> { + if online_cpus.len() <= 1 { + return Vec::new(); + } + let net_cpu = online_cpus[0]; + let other_cpus = &online_cpus[1..]; + let mut plan = Vec::new(); + let mut other_idx = 0usize; + for line in proc_interrupts.lines() { + let mut tokens = line.split_whitespace(); + let Some(first) = tokens.next() else { continue }; + let Some(irq_str) = first.strip_suffix(':') else { continue }; + let Ok(irq) = irq_str.parse::() else { continue }; + // Check all action names on shared INTx lines so assignment is order-independent. + let mut saw_virtio = false; + let mut is_net = false; + for tok in tokens { + let clean = tok.trim_end_matches(','); + if clean.starts_with("virtio") { + saw_virtio = true; + if net_virtio_dev.is_some_and(|dev| handler_matches_dev(clean, dev)) { + is_net = true; + } + } + } + if !saw_virtio { + continue; + } + let cpu = if is_net { + if !pin_net_to_cpu0 { + continue; + } + net_cpu + } else { + let slot = other_cpus[other_idx % other_cpus.len()]; + other_idx += 1; + slot + }; + plan.push((irq, cpu)); + } + plan +} + fn mount_kernel_filesystems() -> io::Result<()> { let nosuid_nodev_noexec = libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC; let m = |src, target: &std::ffi::CStr, fstype, flags, data| { @@ -408,11 +528,13 @@ fn take_over(root: &std::path::Path, leftovers: impl Fn()) -> io::Result<()> { let _ = (&file).read_to_string(&mut text); let _ = std::io::Seek::rewind(&mut file); let old: libc::pid_t = text.trim().parse().unwrap_or(0); - let daemon = parent_of(old); - let orphan = old > 0 && !daemon.is_some_and(is_daemon); + let old_is_agent = old > 0 && is_kiri_init(old); + let daemon = old_is_agent.then(|| parent_of(old)).flatten(); + let orphan = old_is_agent && !daemon.is_some_and(is_daemon); let waited = start.elapsed(); - // Gone: whatever holds the lock now is something it left running. - if orphan && !swept && daemon.is_none() { + // Gone (or PID recycled to a non-kiri-init host process): whatever + // holds the lock now is something the dead agent left running. + if (!old_is_agent || (orphan && daemon.is_none())) && !swept { eprintln!("kiri-init: agent {old} is gone but its lock is held: stopping the containers it left"); leftovers(); swept = true; @@ -420,7 +542,7 @@ fn take_over(root: &std::path::Path, leftovers: impl Fn()) -> io::Result<()> { } if orphan && signalled.is_none() { eprintln!("kiri-init: stopping agent {old}, left running by a daemon that is gone"); - // SAFETY: signalling the process that holds our data directory's lock. + // SAFETY: signalling a verified `kiri-init` process that holds our data directory's lock. unsafe { libc::kill(old, libc::SIGTERM) }; signalled = Some(waited); } else if orphan && signalled.is_some_and(|t| waited - t > std::time::Duration::from_secs(5)) { @@ -442,6 +564,41 @@ fn take_over(root: &std::path::Path, leftovers: impl Fn()) -> io::Result<()> { Ok(()) } +/// Whether `pid` is actually a `kiri-init` agent process (and not an unrelated +/// host process that recycled the dead agent's PID). +fn is_kiri_init(pid: libc::pid_t) -> bool { + if pid <= 0 || pid == std::process::id() as libc::pid_t { + return false; + } + if let Ok(exe) = std::fs::read_link(format!("/proc/{pid}/exe")) { + if std::fs::read_link("/proc/self/exe").is_ok_and(|me| exe == me) { + return true; + } + if exe_is_kiri_init(&exe) { + return true; + } + return false; + } + std::fs::read(format!("/proc/{pid}/cmdline")).is_ok_and(|c| cmdline_is_kiri_init(&c)) +} + +fn exe_is_kiri_init(exe: &std::path::Path) -> bool { + exe.file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n == "kiri-init" || n == "kiri-init (deleted)") +} + +fn cmdline_is_kiri_init(cmdline: &[u8]) -> bool { + use std::os::unix::ffi::OsStrExt; + let Some(argv0) = cmdline.split(|&b| b == 0).next().filter(|a| !a.is_empty()) else { + return false; + }; + std::path::Path::new(std::ffi::OsStr::from_bytes(argv0)) + .file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n == "kiri-init") +} + /// A live process's parent, from /proc//stat. fn parent_of(pid: libc::pid_t) -> Option { if pid <= 0 { @@ -690,6 +847,11 @@ fn delegated(own: &std::path::Path, pids: &[String]) -> bool { !pids.is_empty() && pids.iter().all(|p| *p == me || *p == parent) } +/// Mount flags for the macOS virtiofs share at `/mnt/mac`: `MS_NOSUID` and +/// `MS_NODEV` block setuid/setgid privilege escalation and device nodes on +/// host-backed bind mounts whose server synthesizes caller ownership. +const MAC_SHARE_MOUNT_FLAGS: libc::c_ulong = libc::MS_NOATIME | libc::MS_NOSUID | libc::MS_NODEV; + /// Mounts the data disk (or a tmpfs without one), creates the layer and /// container directories and the cgroup that all containers live under. fn data_dirs() -> io::Result { @@ -712,7 +874,7 @@ fn data_dirs() -> io::Result { // The Mac's filesystem over virtiofs, for bind mounts. sys::mkdir(c"/mnt", 0o755); sys::mkdir(c"/mnt/mac", 0o755); - if let Err(e) = mount(c"kiri-mac", c"/mnt/mac", c"virtiofs", libc::MS_NOATIME, None) { + if let Err(e) = mount(c"kiri-mac", c"/mnt/mac", c"virtiofs", MAC_SHARE_MOUNT_FLAGS, None) { eprintln!("kiri-init: no Mac file share ({e}); bind mounts of Mac paths will fail"); } else if let Err(e) = mac_readahead() { eprintln!("kiri-init: keeping the Mac file share's default read-ahead ({e})"); @@ -913,6 +1075,58 @@ mod take_over_tests { assert_eq!(text.trim(), std::process::id().to_string()); let _ = std::fs::remove_dir_all(&root); } + + #[test] + fn take_over_does_not_kill_unrelated_process_on_pid_reuse() { + use std::os::fd::AsRawFd; + assert!(super::exe_is_kiri_init(std::path::Path::new("/usr/local/bin/kiri-init"))); + assert!(super::exe_is_kiri_init(std::path::Path::new("/usr/local/bin/kiri-init (deleted)"))); + assert!(!super::exe_is_kiri_init(std::path::Path::new("/bin/sleep"))); + assert!(super::cmdline_is_kiri_init(b"/usr/local/bin/kiri-init\0")); + assert!(!super::cmdline_is_kiri_init(b"/bin/sleep\x0060\0")); + assert!(!super::cmdline_is_kiri_init(b"")); + + let root = std::env::temp_dir().join(format!("kiri-take-over-reuse-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let mut bystander = std::process::Command::new("sleep").arg("60").spawn().unwrap(); + let bystander_pid = bystander.id(); + let lock = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(true).open(root.join("agent.lock")).unwrap(); + std::io::Write::write_all(&mut &lock, format!("{bystander_pid}\n").as_bytes()).unwrap(); + // SAFETY: flock on a descriptor we own. + assert_eq!(unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, 0); + // SAFETY: child holds the lock until leftovers() reaps it. + let left = unsafe { libc::fork() }; + if left == 0 { + loop { + // SAFETY: plain pause in child. + unsafe { libc::pause() }; + } + } + drop(lock); + let swept = std::cell::Cell::new(0); + super::take_over(&root, || { + swept.set(swept.get() + 1); + // SAFETY: killing and reaping the child forked above. + unsafe { + libc::kill(left, libc::SIGKILL); + libc::waitpid(left, std::ptr::null_mut(), 0); + } + }) + .unwrap(); + assert_eq!(swept.get(), 1); + assert!(bystander.try_wait().unwrap().is_none(), "unrelated process must not be killed"); + let _ = bystander.kill(); + let _ = bystander.wait(); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn mac_share_mount_enforces_nosuid_and_nodev() { + assert_ne!(super::MAC_SHARE_MOUNT_FLAGS & libc::MS_NOSUID, 0); + assert_ne!(super::MAC_SHARE_MOUNT_FLAGS & libc::MS_NODEV, 0); + assert_ne!(super::MAC_SHARE_MOUNT_FLAGS & libc::MS_NOATIME, 0); + } } #[cfg(test)] @@ -1084,4 +1298,55 @@ mod panic_hook_tests { let mut empty = []; assert_eq!(super::format_panic_message(&mut empty, Some(("a.rs", 1)), Some("x")), b""); } + + #[test] + fn virtio_irq_plan_pins_net_to_cpu0_and_spreads_other_devices() { + let interrupts = "\ + CPU0 CPU1 CPU2 CPU3 CPU4 CPU5 CPU6 CPU7 + 1: 0 0 0 0 0 0 0 0 GICv3 30 Level arch_timer + 13: 53301234 0 0 0 0 0 0 0 GICv3 36 Level virtio0 + 15: 15523456 0 0 0 0 0 0 0 GICv3 38 Level virtio2 + 18: 990123 0 0 0 0 0 0 0 GICv3 41 Level virtio5 + 20: 2154321 0 0 0 0 0 0 0 GICv3 43 Level virtio7 +IPI1: 43300000 0 0 0 0 0 0 0 Function call interrupts +"; + assert_eq!( + super::plan_virtio_irq_cpus(interrupts, Some("virtio0"), true, &[0, 1, 2, 3, 4, 5, 6, 7]), + vec![(13, 0), (15, 1), (18, 2), (20, 3)] + ); + // Sparse online CPU IDs (`0,2,4,6`) target actual online IDs, not 1,2,3. + assert_eq!( + super::parse_cpu_list("0,2,4-6\n"), + vec![0, 2, 4, 5, 6] + ); + assert_eq!( + super::plan_virtio_irq_cpus(interrupts, Some("virtio0"), true, &[0, 2, 4, 6]), + vec![(13, 0), (15, 2), (18, 4), (20, 6)] + ); + // On a 2-vCPU VM all non-net virtio devices land on CPU 1, keeping CPU 0 clear for eth0. + assert_eq!( + super::plan_virtio_irq_cpus(interrupts, Some("virtio0"), true, &[0, 1]), + vec![(13, 0), (15, 1), (18, 1), (20, 1)] + ); + // Single-vCPU VM skips affinity programming. + assert!(super::plan_virtio_irq_cpus(interrupts, Some("virtio0"), true, &[0]).is_empty()); + // Shared INTx lines assign identically regardless of handler order. + let shared_a = " 42: 0 0 IO-APIC 21-fasteoi virtio2, virtio1\n"; + let shared_b = " 42: 0 0 IO-APIC 21-fasteoi virtio1, virtio2\n"; + assert_eq!(super::plan_virtio_irq_cpus(shared_a, Some("virtio1"), true, &[0, 1]), vec![(42, 0)]); + assert_eq!(super::plan_virtio_irq_cpus(shared_b, Some("virtio1"), true, &[0, 1]), vec![(42, 0)]); + // MSI-X per-queue names match their owning device prefix; multiqueue skips uplink IRQs. + let msix = "\ + 30: 0 0 0 0 PCI-MSI 0 Edge virtio1-input.0 + 31: 0 0 0 0 PCI-MSI 1 Edge virtio10-req.0 +"; + assert_eq!( + super::plan_virtio_irq_cpus(msix, Some("virtio1"), true, &[0, 1, 2, 3]), + vec![(30, 0), (31, 1)] + ); + assert_eq!( + super::plan_virtio_irq_cpus(msix, Some("virtio1"), false, &[0, 1, 2, 3]), + vec![(31, 1)] + ); + } } diff --git a/crates/kiri-init/src/linux/net.rs b/crates/kiri-init/src/linux/net.rs index eeb34794e..87a3b85fd 100644 --- a/crates/kiri-init/src/linux/net.rs +++ b/crates/kiri-init/src/linux/net.rs @@ -865,6 +865,76 @@ fn raise_sysctl_min(path: &std::path::Path, min: u64) { } } +/// Counts sysfs `rx-*` queues exposed for `iface`. +pub(crate) fn rx_queue_count(iface: &str) -> usize { + let queues_dir = std::path::PathBuf::from(format!("/sys/class/net/{iface}/queues")); + let Ok(entries) = std::fs::read_dir(&queues_dir) else { return 0 }; + entries + .filter_map(|e| e.ok()) + .filter(|e| e.file_name().to_str().is_some_and(|n| n.starts_with("rx-"))) + .count() +} + +/// Formats a Linux sysfs `rps_cpus` hex bitmask from actual `online_cpus` IDs. +/// With >= 4 online CPUs, excludes the first online CPU (dedicated to +/// `virtio-net` hardirq/NAPI polling) so the remaining CPUs handle `NET_RX` +/// softirq work; with 2-3 CPUs, includes all online CPUs so steering still fans +/// out across multiple cores. +fn format_rps_cpu_mask(online_cpus: &[usize]) -> Option { + if online_cpus.len() <= 1 { + return None; + } + let selected = if online_cpus.len() >= 4 { &online_cpus[1..] } else { online_cpus }; + let max_cpu = *selected.iter().max()?; + let words = max_cpu / 32 + 1; + let mut chunks = vec![0u32; words]; + for &cpu in selected { + chunks[cpu / 32] |= 1u32 << (cpu % 32); + } + let mut out = String::new(); + for &bits in chunks.iter().rev() { + if out.is_empty() { + out.push_str(&format!("{bits:x}")); + } else { + out.push_str(&format!(",{bits:08x}")); + } + } + Some(out) +} + +/// Enables Receive Packet Steering (RPS) on the VM's uplink interface so Apple +/// Virtualization.framework's single-queue `virtio-net` spreads `NET_RX` +/// softirq work across vCPUs instead of pinning it onto CPU 0. When >= 4 CPUs +/// isolate CPU 0 from `rps_cpus`, RFS (`rps_flow_cnt`) is intentionally left +/// disabled so Linux's RFS lookup cannot steer packets back onto CPU 0. +/// Best-effort: silently skipped if the kernel omits `CONFIG_RPS`. +fn configure_uplink_rps(iface: &str) { + const RFS_FLOW_ENTRIES: u64 = 32_768; + let cpus = super::online_cpu_ids(); + let Some(mask) = format_rps_cpu_mask(&cpus) else { return }; + let queues_dir = std::path::PathBuf::from(format!("/sys/class/net/{iface}/queues")); + let Ok(entries) = std::fs::read_dir(&queues_dir) else { return }; + let rx_queues: Vec = entries + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("rx-"))) + .collect(); + if rx_queues.is_empty() { + return; + } + let enable_rfs = cpus.len() < 4; + if enable_rfs { + raise_sysctl_min(std::path::Path::new("/proc/sys/net/core/rps_sock_flow_entries"), RFS_FLOW_ENTRIES); + } + let per_queue = (RFS_FLOW_ENTRIES / rx_queues.len() as u64).max(1).to_string(); + for q in rx_queues { + let _ = std::fs::write(q.join("rps_cpus"), &mask); + if enable_rfs { + let _ = std::fs::write(q.join("rps_flow_cnt"), &per_queue); + } + } +} + /// Brings the uplink up and returns a DHCP client for it, or None if the VM /// has no network card (shared NAT disabled: installs the VM nftables table /// and a fallback default route on `lo` so host-network and bridged containers @@ -885,6 +955,7 @@ pub fn uplink() -> io::Result> { Ok(index) => { let mut nl = Netlink::open(libc::NETLINK_ROUTE)?; netlink::set_up(&mut nl, index)?; + configure_uplink_rps(UPLINK); install_nat(Nat { uplink: index, redirect: true, dnat: Vec::new(), gateway: [0; 4] })?; let _ = VM_UPLINK_INDEX.set(index); Ok(Some(Dhcp::start(index)?)) @@ -1889,4 +1960,19 @@ mod tests { let rebound = try_bind_abstract_socket(name.as_bytes()).expect("rebind succeeds once first fd closes"); drop(rebound); } + + #[test] + fn rps_cpu_mask_formats_single_and_multi_word_cpumasks() { + let seq = |n: usize| (0..n).collect::>(); + assert_eq!(format_rps_cpu_mask(&[]), None); + assert_eq!(format_rps_cpu_mask(&[0]), None); + assert_eq!(format_rps_cpu_mask(&seq(2)).as_deref(), Some("3")); + assert_eq!(format_rps_cpu_mask(&seq(3)).as_deref(), Some("7")); + assert_eq!(format_rps_cpu_mask(&seq(4)).as_deref(), Some("e")); + assert_eq!(format_rps_cpu_mask(&seq(8)).as_deref(), Some("fe")); + assert_eq!(format_rps_cpu_mask(&[0, 2, 4, 6]).as_deref(), Some("54")); + assert_eq!(format_rps_cpu_mask(&seq(32)).as_deref(), Some("fffffffe")); + assert_eq!(format_rps_cpu_mask(&seq(33)).as_deref(), Some("1,fffffffe")); + assert_eq!(format_rps_cpu_mask(&seq(64)).as_deref(), Some("ffffffff,fffffffe")); + } } diff --git a/crates/kiri-init/src/linux/seccomp.rs b/crates/kiri-init/src/linux/seccomp.rs index a2db95d3a..f14e95df8 100644 --- a/crates/kiri-init/src/linux/seccomp.rs +++ b/crates/kiri-init/src/linux/seccomp.rs @@ -24,7 +24,6 @@ const RET_ERRNO: u32 = 0x0005_0000; const LD_W_ABS: u16 = 0x20; const JEQ_K: u16 = 0x15; const JSET_K: u16 = 0x45; -#[cfg(target_arch = "x86_64")] const JGE_K: u16 = 0x35; const RET_K: u16 = 0x06; @@ -55,6 +54,7 @@ const OFF_ARG0: u32 = 16; const CAP_SYS_MODULE: u32 = 16; #[cfg(target_arch = "x86_64")] const CAP_SYS_RAWIO: u32 = 17; +const CAP_SYS_CHROOT: u32 = 18; const CAP_SYS_PTRACE: u32 = 19; const CAP_SYS_PACCT: u32 = 20; const CAP_SYS_ADMIN: u32 = 21; @@ -64,6 +64,20 @@ const CAP_SYS_TIME: u32 = 25; const CAP_PERFMON: u32 = 38; const CAP_BPF: u32 = 39; +/// Highest known Linux syscall number allowed through the default profile +/// (blocks unknown/future kernel syscalls by default, matching Docker's +/// fail-closed posture for new kernel attack surface). +const MAX_KNOWN_SYSCALL: u32 = 475; + +/// Socket address families allowed by Docker's default seccomp profile +/// (`< 3` is checked separately; `AF_VSOCK` is always refused with +/// `EAFNOSUPPORT`). Exotic families such as `AF_ALG` (38), `AF_AX25` (3), +/// `AF_IPX` (4), `AF_APPLETALK` (5), `AF_ISDN` (34), `AF_CAIF` (37), and +/// unknown families `>= 46` are refused with `EPERM`. +const ALLOWED_SOCKET_FAMILIES: [u32; 29] = [ + 7, 8, 9, 10, 13, 14, 15, 16, 17, 18, 21, 22, 24, 26, 27, 28, 29, 30, 31, 32, 33, 35, 36, 39, 41, 42, 43, 44, 45, +]; + const NS_FLAGS: u32 = (libc::CLONE_NEWNS | libc::CLONE_NEWUTS | libc::CLONE_NEWIPC @@ -181,10 +195,19 @@ fn denied() -> Vec<(libc::c_long, Option)> { (SYS_PROCESS_MADVISE, Some(CAP_SYS_PTRACE)), (SYS_get_mempolicy, Some(CAP_SYS_NICE)), (SYS_SET_MEMPOLICY_HOME_NODE, Some(CAP_SYS_NICE)), + (SYS_chroot, Some(CAP_SYS_CHROOT)), #[cfg(target_arch = "x86_64")] (SYS_ioperm, Some(CAP_SYS_RAWIO)), #[cfg(target_arch = "x86_64")] (SYS_iopl, Some(CAP_SYS_RAWIO)), + #[cfg(target_arch = "x86_64")] + (SYS_uselib, None), + #[cfg(target_arch = "x86_64")] + (SYS_ustat, None), + #[cfg(target_arch = "x86_64")] + (SYS_sysfs, None), + #[cfg(target_arch = "x86_64")] + (SYS__sysctl, None), ] } @@ -243,6 +266,39 @@ fn deny_vsock(p: &mut Vec) { p.push(stmt(LD_W_ABS, OFF_NR)); } +/// Rejects unknown/future syscall numbers above [`MAX_KNOWN_SYSCALL`] so the +/// default profile fails closed on future kernel syscalls (`FS-11`). +fn deny_unknown_syscalls(p: &mut Vec) { + p.push(jump(JGE_K, MAX_KNOWN_SYSCALL + 1, 0, 1)); + p.push(stmt(RET_K, RET_ERRNO | libc::EPERM as u32)); +} + +/// Restricts `socket(domain, ...)` to Docker's allowlisted address families. +/// `deny_vsock` runs first so `AF_VSOCK` still returns `EAFNOSUPPORT`. +/// Leaves the syscall number loaded on fallthrough. +fn deny_exotic_sockets(p: &mut Vec) { + let n = ALLOWED_SOCKET_FAMILIES.len(); + p.push(jump(JEQ_K, libc::SYS_socket as u32, 0, n as u8 + 4)); + p.push(stmt(LD_W_ABS, OFF_ARG0)); + p.push(jump(JGE_K, 3, 0, n as u8 + 1)); + for (i, &af) in ALLOWED_SOCKET_FAMILIES.iter().enumerate() { + p.push(jump(JEQ_K, af, (n - i) as u8, 0)); + } + p.push(stmt(RET_K, RET_ERRNO | libc::EPERM as u32)); + p.push(stmt(LD_W_ABS, OFF_NR)); +} + +/// Restricts `socketpair(domain, ...)` to `AF_UNIX` (1) and `AF_TIPC` (30), +/// matching Docker's default profile. Leaves the syscall number loaded. +fn deny_exotic_socketpair(p: &mut Vec) { + p.push(jump(JEQ_K, libc::SYS_socketpair as u32, 0, 5)); + p.push(stmt(LD_W_ABS, OFF_ARG0)); + p.push(jump(JEQ_K, libc::AF_UNIX as u32, 2, 0)); + p.push(jump(JEQ_K, 30, 1, 0)); + p.push(stmt(RET_K, RET_ERRNO | libc::EPERM as u32)); + p.push(stmt(LD_W_ABS, OFF_NR)); +} + /// The filter for `--privileged` and `seccomp=unconfined`: nothing of the /// default profile, only the host boundary. io_uring goes too, since its /// socket operation makes a socket without the syscall a filter sees. @@ -260,6 +316,7 @@ fn boundary() -> Vec { fn program(caps: u64) -> Vec { let has = |cap: u32| caps & (1u64 << cap) != 0; let mut p = head(); + deny_unknown_syscalls(&mut p); for (nr, cap) in denied() { if cap.is_some_and(has) { continue; @@ -268,6 +325,8 @@ fn program(caps: u64) -> Vec { } deny_personality(&mut p); deny_vsock(&mut p); + deny_exotic_sockets(&mut p); + deny_exotic_socketpair(&mut p); if !has(CAP_SYS_ADMIN) { // clone3 hides its flags in memory a filter cannot read: ENOSYS // makes libc fall back to clone, whose flags it can. @@ -360,7 +419,7 @@ mod tests { // Every jump lands inside the program. for p in [program(0), program(u64::MAX)] { for (i, insn) in p.iter().enumerate() { - if insn.code == JEQ_K || insn.code == JSET_K { + if matches!(insn.code, JEQ_K | JSET_K | JGE_K) { assert!(i + 1 + (insn.jt.max(insn.jf) as usize) < p.len()); } } @@ -420,7 +479,6 @@ mod tests { } RET_K => return i.k, JEQ_K => pc += if acc == i.k { i.jt } else { i.jf } as usize, - #[cfg(target_arch = "x86_64")] JGE_K => pc += if acc >= i.k { i.jt } else { i.jf } as usize, JSET_K => pc += if acc & i.k != 0 { i.jt } else { i.jf } as usize, other => panic!("opcode {other:#x}"), @@ -507,4 +565,30 @@ mod tests { assert!(decode(&vec![0; 8 * (MAX_INSNS + 1)]).is_err(), "too long"); assert!(decode(&vec![0; 8 * MAX_INSNS]).is_ok()); } + + #[test] + fn default_profile_blocks_exotic_sockets_and_unknown_syscalls() { + let p = program(0); + let eperm = RET_ERRNO | libc::EPERM as u32; + let eafnosupport = RET_ERRNO | libc::EAFNOSUPPORT as u32; + // Standard socket families pass. + for af in [libc::AF_UNIX as u32, libc::AF_INET as u32, libc::AF_INET6 as u32, libc::AF_NETLINK as u32, libc::AF_PACKET as u32] { + assert_eq!(answer(&p, libc::SYS_socket as u32, af), RET_ALLOW, "AF {af}"); + } + // AF_VSOCK returns EAFNOSUPPORT; exotic/unknown families return EPERM. + assert_eq!(answer(&p, libc::SYS_socket as u32, libc::AF_VSOCK as u32), eafnosupport); + for af in [3 /* AF_AX25 */, 4 /* AF_IPX */, 5 /* AF_APPLETALK */, 34 /* AF_ISDN */, 37 /* AF_CAIF */, 38 /* AF_ALG */, 99] { + assert_eq!(answer(&p, libc::SYS_socket as u32, af), eperm, "AF {af}"); + } + // socketpair allows only AF_UNIX and AF_TIPC. + assert_eq!(answer(&p, libc::SYS_socketpair as u32, libc::AF_UNIX as u32), RET_ALLOW); + assert_eq!(answer(&p, libc::SYS_socketpair as u32, 30), RET_ALLOW); + assert_eq!(answer(&p, libc::SYS_socketpair as u32, libc::AF_INET as u32), eperm); + // Unknown / future syscall numbers fail closed with EPERM. + assert_eq!(answer(&p, 999, 0), eperm); + assert_eq!(answer(&p, MAX_KNOWN_SYSCALL + 1, 0), eperm); + // chroot requires CAP_SYS_CHROOT. + assert_eq!(answer(&p, libc::SYS_chroot as u32, 0), eperm); + assert_eq!(answer(&program(1 << CAP_SYS_CHROOT), libc::SYS_chroot as u32, 0), RET_ALLOW); + } } diff --git a/crates/kiri-init/src/linux/tarnum.rs b/crates/kiri-init/src/linux/tarnum.rs index 75c39ef7a..ed3538525 100644 --- a/crates/kiri-init/src/linux/tarnum.rs +++ b/crates/kiri-init/src/linux/tarnum.rs @@ -7,6 +7,11 @@ use std::io::{self, Read}; const BLOCK: usize = 512; +/// Upper bound on buffered PAX `x` extension data (1 MiB). Prevents a tiny +/// compressed tar stream with a multi-gigabyte PAX header from OOM-killing +/// PID 1 (`kiri-init`) or the host root agent. +pub const MAX_PAX_SIZE: u64 = 1 << 20; + /// The size field, which tar-rs reads in every header, as (start, end). const SIZE: (usize, usize) = (124, 136); /// mode, uid, gid and mtime, which it reads for an entry it unpacks, not for @@ -68,11 +73,11 @@ impl GoNumbers { Ok(()) } - fn header(&mut self) { + fn header(&mut self) -> io::Result<()> { let h = &mut self.block; if h.iter().all(|&b| b == 0) || Some(checksum(h)) != octal(&h[148..156]) { self.passthrough = true; - return; + return Ok(()); } let ustar = &h[257..263] == b"ustar\0" && &h[263..265] == b"00"; let gnu = &h[257..263] == b"ustar " && &h[263..265] == b" \0"; @@ -105,7 +110,7 @@ impl GoNumbers { let Some(mut size) = number(&h[SIZE.0..SIZE.1]) else { self.passthrough = true; - return; + return Ok(()); }; if !continues && let Some(pax) = self.pax_size.take() @@ -116,9 +121,16 @@ impl GoNumbers { self.sparse_ext = sparse && h[482] == 1; self.data = size.div_ceil(BLOCK as u64).saturating_mul(BLOCK as u64); if kind == b'x' && (ustar || gnu) { + if size > MAX_PAX_SIZE { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("PAX extended header exceeds maximum size ({size} > {MAX_PAX_SIZE})"), + )); + } self.pax = Some((Vec::new(), size)); self.end_of_data(); } + Ok(()) } /// An entry's data has all gone: a PAX entry's records take effect. @@ -159,6 +171,9 @@ impl Read for GoNumbers { } if let Some((pax, left)) = &mut self.pax { let take = (n as u64).min(*left) as usize; + if pax.len().saturating_add(take) > MAX_PAX_SIZE as usize { + return Err(io::Error::new(io::ErrorKind::InvalidData, "PAX extended header exceeds maximum size")); + } pax.extend_from_slice(&buf[..take]); *left -= take as u64; } @@ -168,7 +183,7 @@ impl Read for GoNumbers { } self.next_block()?; if !self.passthrough { - self.header(); + self.header()?; } } } @@ -600,4 +615,17 @@ mod tests { assert_eq!(body, b"world"); assert!(list.next().is_none()); } + + #[test] + fn oversized_pax_header_is_rejected_without_allocating() { + let mut x = tar::Header::new_ustar(); + x.set_entry_type(tar::EntryType::XHeader); + x.set_size(MAX_PAX_SIZE + 1); + x.set_cksum(); + let stream = x.as_bytes().chain(io::repeat(0)); + let mut r = GoNumbers::new(stream); + let mut buf = [0u8; 512]; + let err = r.read(&mut buf).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + } } diff --git a/crates/kiri-init/src/linux/volmount.rs b/crates/kiri-init/src/linux/volmount.rs index 16ecfc4b6..e233df800 100644 --- a/crates/kiri-init/src/linux/volmount.rs +++ b/crates/kiri-init/src/linux/volmount.rs @@ -449,6 +449,85 @@ fn validate_volume_mount(kind: &str, device: &str, flags: libc::c_ulong, data: & Ok(()) } +/// Allowed non-bind volume filesystem types (`SEC-D-04`). Any other fstype +/// (e.g. `overlay`, `ext4`, `devtmpfs`, `proc`, `sysfs`, `virtiofs`) is refused. +const ALLOWED_FS_TYPES: [&str; 5] = ["nfs", "nfs4", "cifs", "smb3", "tmpfs"]; + +/// Safe mount(2) flags accepted for bind volumes. Propagation and remount/move +/// flags are rejected. +const ALLOWED_BIND_FLAGS: libc::c_ulong = libc::MS_BIND + | libc::MS_REC + | libc::MS_RDONLY + | libc::MS_NOSUID + | libc::MS_NODEV + | libc::MS_NOEXEC + | libc::MS_NOATIME + | libc::MS_NODIRATIME + | libc::MS_RELATIME + | libc::MS_STRICTATIME; + +/// Safe mount(2) flags accepted for non-bind local driver volumes. +const ALLOWED_FS_FLAGS: libc::c_ulong = libc::MS_RDONLY + | libc::MS_NOSUID + | libc::MS_NODEV + | libc::MS_NOEXEC + | libc::MS_NOATIME + | libc::MS_NODIRATIME + | libc::MS_RELATIME + | libc::MS_STRICTATIME + | libc::MS_SYNCHRONOUS + | libc::MS_DIRSYNC + | libc::MS_MANDLOCK + | libc::MS_SILENT; + +/// Flags applied during the bind remount step. +const BIND_REMOUNT_ATTRS: libc::c_ulong = libc::MS_RDONLY + | libc::MS_NOSUID + | libc::MS_NODEV + | libc::MS_NOEXEC + | libc::MS_NOATIME + | libc::MS_NODIRATIME + | libc::MS_RELATIME + | libc::MS_STRICTATIME; + +/// Validates volume mount target, filesystem type, device, and flags before +/// calling `mount(2)`. +fn validate_mount(path: &str, kind: &str, device: &str, flags: libc::c_ulong, host_process: bool) -> io::Result { + if !path.starts_with(ROOT) || path.split('/').any(|c| c == "..") { + return Err(invalid("volume mount outside the volume store")); + } + let bind = flags & libc::MS_BIND != 0; + if bind { + if kind != "none" && !kind.is_empty() { + return Err(invalid(&format!("bind volume cannot specify filesystem type {kind:?}"))); + } + if flags & !ALLOWED_BIND_FLAGS != 0 { + return Err(invalid(&format!("disallowed bind volume mount flags 0x{flags:x}"))); + } + if !device.starts_with('/') || device.split('/').any(|c| c == "..") { + return Err(invalid(&format!("invalid bind volume device path {device:?}"))); + } + if !host_process && is_vm_share_ancestor(device) { + return Err(invalid(&format!("bind volume device {device:?} exposes protected VM mount hierarchy"))); + } + } else { + if !ALLOWED_FS_TYPES.contains(&kind) { + return Err(invalid(&format!("unsupported volume filesystem type {kind:?}"))); + } + if flags & !ALLOWED_FS_FLAGS != 0 { + return Err(invalid(&format!("disallowed volume mount flags 0x{flags:x}"))); + } + } + Ok(bind) +} + +/// In VM mode, binding `/` or `/mnt` recursively (`MS_REC`) would expose +/// `/mnt/mac` and `/var/lib/kiri` past the macOS share guard. +pub(super) fn is_vm_share_ancestor(path: &str) -> bool { + let segs: Vec<&str> = path.split('/').filter(|c| !c.is_empty() && *c != ".").collect(); + matches!(segs.as_slice(), [] | ["mnt"] | ["mnt", "mac"]) +} + /// Mounts the volume at `path` unless something already is: `kind` is the /// filesystem (`none` for a bind), `flags_hex` and `data` are `o` split as /// mount(2) takes it. Errors read as Docker's. @@ -458,6 +537,7 @@ pub fn ensure(path: &str, kind: &str, device: &str, flags_hex: &str, data: &str) } let flags = u64::from_str_radix(flags_hex, 16).map_err(|_| invalid("bad volume mount flags"))? as libc::c_ulong; validate_volume_mount(kind, device, flags, data)?; + let bind = validate_mount(path, kind, device, flags, super::transport::is_host_process())?; if mounted(path) { return Ok(()); } @@ -470,7 +550,6 @@ pub fn ensure(path: &str, kind: &str, device: &str, flags_hex: &str, data: &str) // at start, as Docker does. return Err(fail(format!("error resolving passed in network volume address: lookup {addr}: no such host"))); } - let bind = flags & libc::MS_BIND != 0; let c = |s: &str| CString::new(s).map_err(|_| invalid("volume option contains NUL")); let (src, target, fstype) = (c(device)?, c(path)?, c(if bind { "none" } else { kind })?); let data_c = c(data)?; @@ -480,12 +559,18 @@ pub fn ensure(path: &str, kind: &str, device: &str, flags_hex: &str, data: &str) if r == 0 { Ok(()) } else { Err(io::Error::last_os_error()) } }; let result = if bind { - // A bind takes no other flags at first; read-only is a remount. + // A bind takes no other flags at first; attributes such as ro/nosuid/nodev/noexec are applied by remount. + let remount_attrs = flags & BIND_REMOUNT_ATTRS; mount(flags & (libc::MS_BIND | libc::MS_REC), None).and_then(|()| { - if flags & libc::MS_RDONLY != 0 { mount(libc::MS_BIND | libc::MS_REMOUNT | libc::MS_RDONLY | (flags & libc::MS_REC), None) } else { Ok(()) } + if remount_attrs != 0 { + mount(libc::MS_BIND | libc::MS_REMOUNT | remount_attrs | (flags & libc::MS_REC), None) + } else { + Ok(()) + } }) } else { - mount(flags, (!data.is_empty()).then_some(&data_c)) + // Enforce MS_NOSUID | MS_NODEV on network/tmpfs volumes for defense in depth. + mount(flags | libc::MS_NOSUID | libc::MS_NODEV, (!data.is_empty()).then_some(&data_c)) }; result.map_err(|e| { // As Docker's mount error: `mount src:target, flags: 0x…, data: …: errno`, @@ -625,6 +710,33 @@ mod tests { } } + #[test] + fn volume_mount_validation_rejects_disallowed_fstypes_flags_and_devices() { + let vol = "/var/lib/kiri/volumes/v1/_data"; + // Allowed non-bind fstypes. + for kind in ["nfs", "nfs4", "cifs", "smb3", "tmpfs"] { + assert!(!validate_mount(vol, kind, "src", libc::MS_RDONLY | libc::MS_NOATIME, false).unwrap(), "{kind}"); + } + // Disallowed non-bind fstypes (SEC-D-04). + for bad in ["overlay", "ext4", "devtmpfs", "proc", "sysfs", "virtiofs", "none", ""] { + assert!(validate_mount(vol, bad, "src", 0, false).is_err(), "{bad:?}"); + } + // Disallowed flags on non-bind mounts. + assert!(validate_mount(vol, "tmpfs", "tmpfs", libc::MS_REMOUNT, false).is_err()); + assert!(validate_mount(vol, "tmpfs", "tmpfs", libc::MS_MOVE, false).is_err()); + // Bind volumes: valid under /mnt/mac/Users or host paths. + assert!(validate_mount(vol, "none", "/mnt/mac/Users/alice/app", libc::MS_BIND | libc::MS_RDONLY, false).unwrap()); + assert!(validate_mount(vol, "none", "/srv/data", libc::MS_BIND | libc::MS_REC, true).unwrap()); + // Bind volumes: reject non-none fstype, relative/traversal device, disallowed flags, and VM share ancestors. + assert!(validate_mount(vol, "overlay", "/tmp/a", libc::MS_BIND, true).is_err()); + assert!(validate_mount(vol, "none", "relative/path", libc::MS_BIND, true).is_err()); + assert!(validate_mount(vol, "none", "/mnt/mac/Users/..", libc::MS_BIND, false).is_err()); + for ancestor in ["/", "/.", "///", "/mnt", "/mnt/", "/mnt/.", "//mnt", "/mnt//mac", "/mnt/./mac", "/mnt/mac", "/mnt/mac/."] { + assert!(validate_mount(vol, "none", ancestor, libc::MS_BIND | libc::MS_REC, false).is_err(), "{ancestor:?}"); + } + assert!(validate_mount(vol, "none", "/tmp/a", libc::MS_BIND | libc::MS_REMOUNT, true).is_err()); + } + #[test] fn k8s_ext4_paths_and_loop_info_layout() { assert!(is_k8s_volume_data("/var/lib/kiri/volumes/kiri-k8s/_data")); diff --git a/crates/kiri-proto/src/lib.rs b/crates/kiri-proto/src/lib.rs index 625aaa49d..337d92bad 100644 --- a/crates/kiri-proto/src/lib.rs +++ b/crates/kiri-proto/src/lib.rs @@ -946,6 +946,7 @@ impl<'a> StrList<'a> { /// Encodes `items` as a list. Used by senders, which hold plain slices. pub fn put>(out: &mut Vec, items: &[S]) { + out.reserve(str_list_wire_len(items)); out.extend_from_slice(&(items.len() as u32).to_le_bytes()); for s in items { put_str(out, s.as_ref()); @@ -1056,6 +1057,11 @@ pub enum DecodeError { BadUtf8, } +#[inline] +fn str_list_wire_len>(items: &[S]) -> usize { + 4 + items.iter().map(|s| 4 + s.as_ref().len()).sum::() +} + fn put_u32(out: &mut Vec, v: u32) { out.extend_from_slice(&v.to_le_bytes()); } @@ -1087,6 +1093,17 @@ pub fn encode_exec>( caps: u64, opts: &[S], ) { + let exact = HEADER + + (4 + container_id.len()) + + (4 + exec_id.len()) + + str_list_wire_len(argv) + + str_list_wire_len(env) + + (4 + cwd.len()) + + (4 + user.len()) + + 4 + + 8 + + str_list_wire_len(opts); + out.reserve(exact); frame(out, kind::EXEC, |out| { put_str(out, container_id); put_str(out, exec_id); @@ -1212,6 +1229,26 @@ pub fn encode_run>( opts: &[S], seccomp: &[u8], ) { + let exact = HEADER + + (4 + id.len()) + + str_list_wire_len(layers) + + str_list_wire_len(argv) + + str_list_wire_len(env) + + (4 + cwd.len()) + + (4 + user.len()) + + (4 + hostname.len()) + + 4 + + (4 + net.bridge.len()) + + 9 + + str_list_wire_len(net.extra_hosts) + + str_list_wire_len(net.dns_names) + + str_list_wire_len(mounts) + + 44 + + 8 + + str_list_wire_len(net.opts) + + str_list_wire_len(opts) + + (4 + seccomp.len()); + out.reserve(exact); frame(out, kind::RUN, |out| { put_str(out, id); StrList::put(out, layers); @@ -1318,21 +1355,27 @@ impl Msg<'_> { }), Msg::AwaitStart { id } => frame(out, kind::AWAIT_START, |o| put_str(o, id)), Msg::CancelStart { id } => frame(out, kind::CANCEL_START, |o| put_str(o, id)), - Msg::Output { id, stream, data } => frame(out, kind::OUTPUT, |o| { - put_str(o, id); - o.push(stream as u8); - put_bytes(o, data); - }), + Msg::Output { id, stream, data } => { + out.reserve(HEADER + 4 + id.len() + 1 + 4 + data.len()); + frame(out, kind::OUTPUT, |o| { + put_str(o, id); + o.push(stream as u8); + put_bytes(o, data); + }); + } Msg::Kill { id, signal } => frame(out, kind::KILL, |o| { put_str(o, id); put_u32(o, signal); }), Msg::Remove { id } => frame(out, kind::REMOVE, |o| put_str(o, id)), Msg::SetTime(ns) => frame(out, kind::SET_TIME, |o| put_u64(o, ns)), - Msg::Input { id, data } => frame(out, kind::INPUT, |o| { - put_str(o, id); - put_bytes(o, data); - }), + Msg::Input { id, data } => { + out.reserve(HEADER + 4 + id.len() + 4 + data.len()); + frame(out, kind::INPUT, |o| { + put_str(o, id); + put_bytes(o, data); + }); + } Msg::CloseStdin { id } => frame(out, kind::CLOSE_STDIN, |o| put_str(o, id)), Msg::Resize { id, rows, cols } => frame(out, kind::RESIZE, |o| { put_str(o, id); diff --git a/crates/kiri-share-proto/src/lib.rs b/crates/kiri-share-proto/src/lib.rs index febf609e6..1c12824bb 100644 --- a/crates/kiri-share-proto/src/lib.rs +++ b/crates/kiri-share-proto/src/lib.rs @@ -250,10 +250,12 @@ impl Msg<'_> { put_u32(o, stream); o.extend_from_slice(remote.as_bytes()); }), - Msg::Data { stream, data } => frame(out, kind::DATA, |o| { - put_u32(o, stream); - o.extend_from_slice(data); - }), + Msg::Data { stream, data } => { + let hdr = data_header(stream, data.len()); + out.reserve(hdr.len() + data.len()); + out.extend_from_slice(&hdr); + out.extend_from_slice(data); + } Msg::Window { stream, credit } => frame(out, kind::WINDOW, |o| { put_u32(o, stream); put_u32(o, credit); @@ -274,12 +276,12 @@ impl Msg<'_> { }), Msg::Join { key } => frame(out, kind::JOIN, |o| o.extend_from_slice(key.as_bytes())), Msg::Joined => frame(out, kind::JOINED, |_| {}), - Msg::Chunk { stream, seq, fin, data } => frame(out, kind::CHUNK, |o| { - put_u32(o, stream); - put_u32(o, seq); - o.push(fin as u8); - o.extend_from_slice(data); - }), + Msg::Chunk { stream, seq, fin, data } => { + let hdr = chunk_header(stream, seq, fin, data.len()); + out.reserve(hdr.len() + data.len()); + out.extend_from_slice(&hdr); + out.extend_from_slice(data); + } } } } diff --git a/crates/kiri-vmm/src/apple.rs b/crates/kiri-vmm/src/apple.rs index 18043ea2a..1618a9153 100644 --- a/crates/kiri-vmm/src/apple.rs +++ b/crates/kiri-vmm/src/apple.rs @@ -76,15 +76,60 @@ struct Inner { extra: RefCell, Retained)>>, } -/// Wraps a value that may only be used on the VM's queue. -/// -/// Objective-C objects are not `Send`, but the queue serialises all access, so -/// moving them across threads is sound as long as they are only touched from -/// inside closures that run on that queue — which is the only way this module -/// ever reaches them. -struct OnQueue(T); -// SAFETY: see the type's documentation; values are only touched on the queue. -unsafe impl Send for OnQueue {} +/// Encapsulates values that may only be touched or dropped on a VM's serial +/// `DispatchQueue`. Making the inner field private to this submodule ensures +/// callers cannot access ObjC objects off-queue without a [`QueueToken`]. +mod on_queue { + use dispatch2::DispatchQueue; + + /// Zero-sized witness proving execution is currently on a VM's serial queue. + pub(super) struct QueueToken(()); + + /// Wraps a value that may only be used on the VM's queue. + /// + /// Objective-C objects are not `Send`, but the queue serialises all access, + /// so moving them across threads is sound as long as they are only touched + /// and dropped on that queue. + pub(super) struct OnQueue(T); + + // SAFETY: access to the inner `T` requires a `QueueToken` (only constructed + // inside a serial-queue closure), and owners drop `OnQueue` on that queue. + unsafe impl Send for OnQueue {} + + impl OnQueue { + pub(super) fn new(value: T) -> Self { + Self(value) + } + + pub(super) fn get<'a>(&'a self, _token: &QueueToken) -> &'a T { + &self.0 + } + + pub(super) fn get_mut<'a>(&'a mut self, _token: &QueueToken) -> &'a mut T { + &mut self.0 + } + + pub(super) fn into_inner(self, _token: &QueueToken) -> T { + self.0 + } + } + + pub(super) fn exec_sync(queue: &DispatchQueue, f: F) { + queue.exec_sync(move || { + let token = QueueToken(()); + f(&token); + }); + } + + pub(super) fn exec_async(queue: &DispatchQueue, f: F) { + queue.exec_async(move || { + let token = QueueToken(()); + f(&token); + }); + } +} + +use on_queue::OnQueue; impl std::fmt::Debug for OnQueue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { @@ -109,7 +154,7 @@ impl std::fmt::Debug for ConnectionOwner { impl Drop for ConnectionOwner { fn drop(&mut self) { if let Some(vm) = self.vm.get_mut().unwrap_or_else(|e| e.into_inner()).take() { - self.queue.exec_sync(move || drop(vm)); + on_queue::exec_sync(&self.queue, move |tok| drop(vm.into_inner(tok))); } } } @@ -132,7 +177,7 @@ impl ConnectionOwner { let old = vm.take(); drop(vm); if let Some(old) = old { - self.queue.exec_sync(move || drop(old)); + on_queue::exec_sync(&self.queue, move |tok| drop(old.into_inner(tok))); } return Ok(()); } @@ -153,12 +198,15 @@ impl Vm { let (started_tx, started_rx) = mpsc::sync_channel::>(1); let mut built: Option>> = None; - let slot = OnQueue(&mut built); + let mut vm_ref: Option>> = None; + let mut slot = OnQueue::new(&mut built); + let mut vm_slot = OnQueue::new(&mut vm_ref); let q = queue.clone(); - queue.exec_sync(move || { - let slot = slot; - *slot.0 = Some(build(cfg, &q, tx).map(OnQueue)); - if let Some(Ok(inner)) = slot.0.as_ref() { + on_queue::exec_sync(&queue, move |tok| { + let built_res = build(cfg, &q, tx); + if let Ok(inner) = built_res.as_ref() { + // Clone the ObjC VM reference on the VM's queue before leaving it. + **vm_slot.get_mut(tok) = Some(OnQueue::new(inner.vm.clone())); let started_tx = started_tx.clone(); let done = RcBlock::new(move |err: *mut NSError| { // SAFETY: the framework passes either null or a valid NSError. @@ -166,11 +214,12 @@ impl Vm { let _ = started_tx.try_send(res); }); // SAFETY: called on the VM's queue, as the framework requires. - unsafe { inner.0.vm.startWithCompletionHandler(&done) }; + unsafe { inner.vm.startWithCompletionHandler(&done) }; } + **slot.get_mut(tok) = Some(built_res.map(OnQueue::new)); }); let inner = built.expect("build ran synchronously")?; - let connection = Arc::new(ConnectionOwner { queue: queue.clone(), vm: RwLock::new(Some(OnQueue(inner.0.vm.clone()))) }); + let connection = Arc::new(ConnectionOwner { queue: queue.clone(), vm: RwLock::new(vm_ref) }); let vm = Vm { queue, inner: Some(inner), events, closing: Arc::new(AtomicBool::new(false)), connection: Some(connection) }; match started_rx.recv_timeout(Duration::from_secs(30)) { Ok(Ok(())) => Ok(vm), @@ -192,19 +241,19 @@ impl Vm { fn force_stop_checked(&self, timeout: Duration) -> io::Result<()> { let Some(inner) = self.inner.as_ref() else { return Ok(()) }; - let inner = OnQueue(&inner.0); + let inner = OnQueue::new(inner); let (tx, rx) = mpsc::sync_channel::>(1); - self.queue.exec_sync(move || { - let inner = inner; + on_queue::exec_sync(&self.queue, move |tok| { + let inner = inner.get(tok).get(tok); // SAFETY: on the VM's queue. unsafe { - if inner.0.vm.canStop() { + if inner.vm.canStop() { let done = RcBlock::new(move |err: *mut NSError| { let result = err.as_ref().map_or(Ok(()), |e| Err(describe(e))); let _ = tx.try_send(result); }); - inner.0.vm.stopWithCompletionHandler(&done); - } else if matches!(inner.0.vm.state(), VZVirtualMachineState::Stopped | VZVirtualMachineState::Error) { + inner.vm.stopWithCompletionHandler(&done); + } else if matches!(inner.vm.state(), VZVirtualMachineState::Stopped | VZVirtualMachineState::Error) { let _ = tx.try_send(Ok(())); } else { let _ = tx.try_send(Err("the VM cannot be stopped in its current state".into())); @@ -220,15 +269,15 @@ impl Vm { fn is_stopped(&self) -> bool { let Some(inner) = self.inner.as_ref() else { return true }; - let inner = OnQueue(&inner.0); + let inner = OnQueue::new(inner); let mut stopped = false; - let out = OnQueue(&mut stopped); - self.queue.exec_sync(move || { - let (inner, out) = (inner, out); + let mut out = OnQueue::new(&mut stopped); + on_queue::exec_sync(&self.queue, move |tok| { + let inner = inner.get(tok).get(tok); // SAFETY: on the VM's queue, as the framework requires. // Error is where a VM ends up when its process dies: it is not // running and never will again, so it has let go of its disk. - *out.0 = matches!(unsafe { inner.0.vm.state() }, VZVirtualMachineState::Stopped | VZVirtualMachineState::Error); + **out.get_mut(tok) = matches!(unsafe { inner.vm.state() }, VZVirtualMachineState::Stopped | VZVirtualMachineState::Error); }); stopped } @@ -243,20 +292,20 @@ impl Vm { } self.connection.take(); if let Some(inner) = self.inner.take() { - self.queue.exec_sync(move || drop(inner)); + on_queue::exec_sync(&self.queue, move |tok| drop(inner.into_inner(tok))); } Ok(()) } pub fn is_running(&self) -> bool { let Some(inner) = self.inner.as_ref() else { return false }; - let inner = OnQueue(&inner.0); + let inner = OnQueue::new(inner); let mut running = false; - let out = OnQueue(&mut running); - self.queue.exec_sync(move || { - let (inner, out) = (inner, out); + let mut out = OnQueue::new(&mut running); + on_queue::exec_sync(&self.queue, move |tok| { + let inner = inner.get(tok).get(tok); // SAFETY: on the VM's queue. - *out.0 = unsafe { inner.0.vm.state() } == VZVirtualMachineState::Running; + **out.get_mut(tok) = unsafe { inner.vm.state() } == VZVirtualMachineState::Running; }); running } @@ -280,7 +329,7 @@ impl std::fmt::Debug for VsockStream { impl Drop for VsockStream { fn drop(&mut self) { if let Some(conn) = self.conn.take() { - self.queue.exec_async(move || drop(conn)); + on_queue::exec_async(&self.queue, move |tok| drop(conn.into_inner(tok))); } } } @@ -293,16 +342,16 @@ impl Vm { /// Asks the guest (through the balloon) to run in `bytes` of memory. The /// guest gives the rest back to macOS. Returns the previous target. pub fn set_memory_target(&self, bytes: u64) -> Option { - let inner = OnQueue(&self.inner.as_ref()?.0); + let inner = OnQueue::new(self.inner.as_ref()?); let mut previous = None; - let out = OnQueue(&mut previous); - self.queue.exec_sync(move || { - let (inner, out) = (inner, out); + let mut out = OnQueue::new(&mut previous); + on_queue::exec_sync(&self.queue, move |tok| { + let inner = inner.get(tok).get(tok); // SAFETY: on the VM's queue, as the framework requires. unsafe { - let Some(dev) = inner.0.vm.memoryBalloonDevices().firstObject() else { return }; + let Some(dev) = inner.vm.memoryBalloonDevices().firstObject() else { return }; let Ok(dev) = Retained::downcast::(dev) else { return }; - *out.0 = Some(dev.targetVirtualMachineMemorySize()); + **out.get_mut(tok) = Some(dev.targetVirtualMachineMemorySize()); dev.setTargetVirtualMachineMemorySize(bytes); } }); @@ -316,23 +365,23 @@ impl Vm { return Err(io::Error::new(io::ErrorKind::NotConnected, "the VM is retiring")); } let Some(inner) = self.inner.as_ref() else { return Err(io::Error::other("VM is gone")) }; - let inner = OnQueue(&inner.0); - let handler = OnQueue(handler); + let inner = OnQueue::new(inner); + let handler = OnQueue::new(handler); let queue = self.queue.clone(); let mut result = Err(io::Error::other("vsock device missing")); - let out = OnQueue(&mut result); - self.queue.exec_sync(move || { - let (inner, handler, out) = (inner, handler, out); + let mut out = OnQueue::new(&mut result); + on_queue::exec_sync(&self.queue, move |tok| { + let inner = inner.get(tok).get(tok); // SAFETY: on the VM's queue, as the framework requires. unsafe { - let device = inner.0.vm.socketDevices().firstObject(); + let device = inner.vm.socketDevices().firstObject(); let Some(device) = device.and_then(|d| Retained::downcast::(d).ok()) else { return }; let listener = VZVirtioSocketListener::new(); - let delegate = PortDelegate::new(handler.0, queue); + let delegate = PortDelegate::new(handler.into_inner(tok), queue); listener.setDelegate(Some(ProtocolObject::from_ref(&*delegate))); device.setSocketListener_forPort(&listener, port); - inner.0.extra.borrow_mut().push((listener, delegate)); - *out.0 = Ok(()); + inner.extra.borrow_mut().push((listener, delegate)); + **out.get_mut(tok) = Ok(()); } }); result @@ -375,42 +424,49 @@ impl Connector { return Err(io::Error::new(io::ErrorKind::NotConnected, "the VM is retiring")); } let Some(vm) = vm.as_ref() else { return Err(io::Error::other("VM is gone")) }; - let vm = OnQueue(&vm.0); - let (tx, rx) = mpsc::sync_channel::>, String>>(1); - owner.queue.exec_sync(move || { - let vm = vm; + let vm = OnQueue::new(vm); + let (tx, rx) = mpsc::sync_channel::>)>>(1); + on_queue::exec_sync(&owner.queue, move |tok| { + let vm = vm.get(tok).get(tok); // SAFETY: on the VM's queue, as the framework requires. unsafe { - let device = vm.0.socketDevices().firstObject(); + let device = vm.socketDevices().firstObject(); let Some(device) = device.and_then(|d| Retained::downcast::(d).ok()) else { - let _ = tx.try_send(Err("VM has no vsock device".into())); + let _ = tx.try_send(Err(io::Error::new(io::ErrorKind::ConnectionRefused, "VM has no vsock device"))); return; }; let done = RcBlock::new(move |conn: *mut VZVirtioSocketConnection, err: *mut NSError| { + // Completion handler runs on `owner.queue`: invoke `fileDescriptor()` + // and `dup()` here so `conn` is never touched or dropped off-queue. let result = match (conn.as_ref(), err.as_ref()) { - (Some(c), _) => Ok(OnQueue(c.retain())), - (None, Some(e)) => Err(describe(e)), - (None, None) => Err("vsock connect failed".into()), + (Some(c), _) => { + let fd = libc::dup(c.fileDescriptor()); + if fd < 0 { + Err(io::Error::last_os_error()) + } else { + // SAFETY: `fd` is a fresh descriptor that nothing else owns. + let owned = OwnedFd::from_raw_fd(fd); + Ok((owned, OnQueue::new(c.retain()))) + } + } + (None, Some(e)) => Err(io::Error::new(io::ErrorKind::ConnectionRefused, describe(e))), + (None, None) => Err(io::Error::new(io::ErrorKind::ConnectionRefused, "vsock connect failed")), }; let _ = tx.try_send(result); }); device.connectToPort_completionHandler(port, &done); } }); - let conn = match rx.recv_timeout(Duration::from_secs(5)) { - Ok(Ok(c)) => c, - Ok(Err(e)) => return Err(io::Error::new(io::ErrorKind::ConnectionRefused, e)), - Err(_) => return Err(io::Error::new(io::ErrorKind::TimedOut, "vsock connect timed out")), - }; - // SAFETY: the connection owns a valid descriptor while it is alive; - // the duplicate is ours and independent of it. - let fd = unsafe { libc::dup(conn.0.fileDescriptor()) }; - if fd < 0 { - return Err(io::Error::last_os_error()); + match rx.recv_timeout(Duration::from_secs(5)) { + Ok(Ok((fd, conn))) => Ok(VsockStream { fd, conn: Some(conn), queue: owner.queue.clone() }), + Ok(Err(e)) => Err(e), + Err(_) => { + // Drop `rx` on `owner.queue` so a racing completion that buffered an + // `OnQueue>` releases it on-queue. + on_queue::exec_async(&owner.queue, move |_tok| drop(rx)); + Err(io::Error::new(io::ErrorKind::TimedOut, "vsock connect timed out")) + } } - // SAFETY: `fd` is a fresh descriptor that nothing else owns. - let fd = unsafe { OwnedFd::from_raw_fd(fd) }; - Ok(VsockStream { fd, conn: Some(conn), queue: owner.queue.clone() }) } } @@ -422,7 +478,7 @@ impl Drop for Vm { } // Release every framework object on the queue that owns it. if let Some(inner) = self.inner.take() { - self.queue.exec_sync(move || drop(inner)); + on_queue::exec_sync(&self.queue, move |tok| drop(inner.into_inner(tok))); } } } @@ -639,7 +695,7 @@ define_class!( } // SAFETY: `fd` is a fresh descriptor that nothing else owns. let fd = unsafe { OwnedFd::from_raw_fd(fd) }; - let stream = VsockStream { fd, conn: Some(OnQueue(conn.retain())), queue: self.ivars().queue.clone() }; + let stream = VsockStream { fd, conn: Some(OnQueue::new(conn.retain())), queue: self.ivars().queue.clone() }; (self.ivars().handler)(stream); Bool::YES } @@ -713,3 +769,46 @@ impl ListenerDelegate { unsafe { msg_send![super(this), init] } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn on_queue_executes_and_drops_value_on_serial_queue() { + let queue = DispatchQueue::new("dev.kiri.vm.test", DispatchQueueAttr::SERIAL); + let dropped = Arc::new(AtomicBool::new(false)); + let dropped_on_queue = Arc::new(AtomicBool::new(false)); + struct Guard { + flag: Arc, + on_queue: Arc, + queue_tid: Arc>>, + } + impl Drop for Guard { + fn drop(&mut self) { + self.flag.store(true, Ordering::Release); + if *self.queue_tid.lock().unwrap() == Some(std::thread::current().id()) { + self.on_queue.store(true, Ordering::Release); + } + } + } + let queue_tid = Arc::new(std::sync::Mutex::new(None)); + let mut cell: Option> = None; + let mut slot = OnQueue::new(&mut cell); + let qtid = queue_tid.clone(); + let d1 = dropped.clone(); + let d2 = dropped_on_queue.clone(); + on_queue::exec_sync(&queue, move |tok| { + *qtid.lock().unwrap() = Some(std::thread::current().id()); + **slot.get_mut(tok) = Some(OnQueue::new(Guard { flag: d1, on_queue: d2, queue_tid: qtid })); + }); + assert!(!dropped.load(Ordering::Acquire)); + let guard = cell.take().unwrap(); + on_queue::exec_sync(&queue, move |tok| { + *queue_tid.lock().unwrap() = Some(std::thread::current().id()); + drop(guard.into_inner(tok)); + }); + assert!(dropped.load(Ordering::Acquire)); + assert!(dropped_on_queue.load(Ordering::Acquire)); + } +} diff --git a/crates/kiri-vmm/src/process.rs b/crates/kiri-vmm/src/process.rs index 96e778446..74b1869fc 100644 --- a/crates/kiri-vmm/src/process.rs +++ b/crates/kiri-vmm/src/process.rs @@ -81,6 +81,21 @@ pub fn rosetta_installed() -> bool { false } +/// Sanitized `PATH` passed to the privileged Linux host agent (`kiri-init`), +/// avoiding any user-writable directories inherited via `sudo -E` or a root shell. +const TRUSTED_AGENT_PATH: &str = "/usr/sbin:/sbin:/usr/bin:/bin"; + +fn configure_agent_command(cmd: &mut Command, dir: &Path, disk: Option<&Path>) { + cmd.env("PATH", TRUSTED_AGENT_PATH) + .env("KIRI_AGENT_DIR", dir) + .env_remove("KIRI_SOCKET"); + if let Some(data) = disk { + cmd.env("KIRI_AGENT_DATA", data); + } else { + cmd.env_remove("KIRI_AGENT_DATA"); + } +} + /// Watches the agent process: says when it exits, then runs the hook given /// to `Vm::on_stop`. fn watch(waiter: Arc>, tx: mpsc::Sender, on_stop: Arc>) -> io::Result<()> { @@ -131,12 +146,7 @@ impl Vm { } })?; let mut cmd = Command::new(&cfg.initrd); - cmd.env("KIRI_AGENT_DIR", &dir).env_remove("KIRI_SOCKET"); - if let Some(data) = &cfg.disk { - cmd.env("KIRI_AGENT_DATA", data); - } else { - cmd.env_remove("KIRI_AGENT_DATA"); - } + configure_agent_command(&mut cmd, &dir, cfg.disk.as_deref()); if let Some(fd) = cfg.console { cmd.stderr(std::process::Stdio::from(fd.try_clone()?)).stdout(std::process::Stdio::from(fd)); } else { @@ -382,4 +392,15 @@ mod tests { let root = Path::new("/run"); assert_ne!(runtime_directory(root), runtime_directory(root)); } + + #[test] + fn agent_command_sanitizes_path_and_sets_agent_env() { + let mut cmd = Command::new("/bin/sh"); + configure_agent_command(&mut cmd, Path::new("/run/kiri-agent-test"), Some(Path::new("/var/lib/kiri-custom"))); + let envs: std::collections::HashMap<_, _> = cmd.get_envs().collect(); + assert_eq!(envs.get(std::ffi::OsStr::new("PATH")), Some(&Some(std::ffi::OsStr::new(TRUSTED_AGENT_PATH)))); + assert_eq!(envs.get(std::ffi::OsStr::new("KIRI_AGENT_DIR")), Some(&Some(std::ffi::OsStr::new("/run/kiri-agent-test")))); + assert_eq!(envs.get(std::ffi::OsStr::new("KIRI_AGENT_DATA")), Some(&Some(std::ffi::OsStr::new("/var/lib/kiri-custom")))); + assert_eq!(envs.get(std::ffi::OsStr::new("KIRI_SOCKET")), Some(&None)); + } } diff --git a/crates/kiri-win/src/app.rs b/crates/kiri-win/src/app.rs index e59dec39a..b98ba94d0 100644 --- a/crates/kiri-win/src/app.rs +++ b/crates/kiri-win/src/app.rs @@ -1020,10 +1020,9 @@ unsafe fn serve_page(wv: &ICoreWebView2, env: &ICoreWebView2Environment) -> wind // SAFETY: the caller's live webview and environment, on their thread. unsafe { let mut token = 0; - // Every request to the page's host comes here, from any frame - // (WebView2 before 124 has only the main frame's filter), and is - // answered from memory: it never reaches the network. - let filter = HSTRING::from(crate::page::FILTER); + // Every request (any origin, any frame) comes here: only PAGE_URL is + // answered from memory, and everything else gets 404 without touching the network. + let filter = HSTRING::from(crate::page::ALL_RESOURCES_FILTER); match wv.cast::() { Ok(wv22) => wv22.AddWebResourceRequestedFilterWithRequestSourceKinds(&filter, COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL, COREWEBVIEW2_WEB_RESOURCE_REQUEST_SOURCE_KINDS_ALL)?, Err(_) => wv.AddWebResourceRequestedFilter(&filter, COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL)?, @@ -1102,6 +1101,16 @@ unsafe fn serve_page(wv: &ICoreWebView2, env: &ICoreWebView2Environment) -> wind })), &mut token, )?; + // Cancel all subframe navigations: Kiri's UI never uses iframes. + wv.add_FrameNavigationStarting( + &NavigationStartingEventHandler::create(Box::new(|_, args: Option| { + if let Some(a) = args { + let _ = a.SetCancel(true); + } + Ok(()) + })), + &mut token, + )?; // The page has a real origin now, and could ask for the camera, // notifications or the like: it needs none, so none is given. wv.add_PermissionRequested( diff --git a/crates/kiri-win/src/detail.rs b/crates/kiri-win/src/detail.rs index fbbb89dbe..822b7edff 100644 --- a/crates/kiri-win/src/detail.rs +++ b/crates/kiri-win/src/detail.rs @@ -383,9 +383,10 @@ pub fn preview(name: String, path: String) { emit(e.to_string()); }; let Some(file) = container_path(&path) else { return with("error", json!("not a path in the container")) }; - match read_file(&name, &file) { - Ok(bytes) if bytes.len() > PREVIEW_MAX || bytes.contains(&0) => with("binary", json!(true)), - Ok(bytes) => match String::from_utf8(bytes) { + match read_file_capped(&name, &file, Some(PREVIEW_MAX)) { + Ok(None) => with("binary", json!(true)), + Ok(Some(bytes)) if bytes.len() > PREVIEW_MAX || bytes.contains(&0) => with("binary", json!(true)), + Ok(Some(bytes)) => match String::from_utf8(bytes) { Ok(text) => with("text", json!(text)), Err(_) => with("binary", json!(true)), }, @@ -403,10 +404,12 @@ pub(crate) fn safe_filename(leaf: &str) -> String { .chars() .map(|c| if "\\/:*?\"<>|".contains(c) || (c as u32) < 0x20 || matches!(c as u32, 0x200B..=0x200F | 0x202A..=0x202E | 0x2066..=0x2069) { '_' } else { c }) .collect(); - // No leading/trailing dots or spaces (Windows strips them, which could - // re-expose an extension or an empty name). + // Truncate on a UTF-8 char boundary BEFORE stripping trailing dots/spaces, + // so multi-byte characters never panic and truncation cannot re-expose + // trailing dots or spaces (which Windows strips). + let cut = s.floor_char_boundary(200); + s.truncate(cut); s = s.trim_matches(|c| c == '.' || c == ' ').to_owned(); - s.truncate(200); if s.is_empty() { s = "file".into(); } @@ -467,13 +470,9 @@ fn escape(s: &str) -> String { s.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-._~/".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect() } -/// One regular file's contents, from the archive API's tar. -fn read_file(container: &str, file: &str) -> std::io::Result> { - let r = client::request("GET", &format!("/containers/{container}/archive?path={}", escape(file)), None)?; - if !r.ok() { - return Err(std::io::Error::other(r.error())); - } - let tar = r.body; +/// Extracts the first regular file from a tar buffer with overflow-safe bounds +/// checks; returns `Ok(None)` when `max_bytes` is exceeded. +fn extract_tar_file(tar: &[u8], max_bytes: Option) -> std::io::Result>> { if tar.len() < 512 { return Err(std::io::Error::other("empty archive")); } @@ -481,8 +480,28 @@ fn read_file(container: &str, file: &str) -> std::io::Result> { return Err(std::io::Error::other("a directory")); } let size_field = String::from_utf8_lossy(&tar[124..136]); - let size = usize::from_str_radix(size_field.trim_matches(|c: char| c == '\0' || c.is_whitespace()), 8).map_err(|_| std::io::Error::other("bad archive"))?; - tar.get(512..512 + size).map(<[u8]>::to_vec).ok_or_else(|| std::io::Error::other("short archive")) + let size = usize::from_str_radix(size_field.trim_matches(|c: char| c == '\0' || c.is_whitespace()), 8) + .map_err(|_| std::io::Error::other("bad archive"))?; + if let Some(cap) = max_bytes + && size > cap + { + return Ok(None); + } + let end = 512usize.checked_add(size).ok_or_else(|| std::io::Error::other("archive size overflow"))?; + tar.get(512..end).map(|b| Some(b.to_vec())).ok_or_else(|| std::io::Error::other("short archive")) +} + +/// One regular file's contents, from the archive API's tar. +fn read_file(container: &str, file: &str) -> std::io::Result> { + read_file_capped(container, file, None)?.ok_or_else(|| std::io::Error::other("file too large")) +} + +fn read_file_capped(container: &str, file: &str, max_bytes: Option) -> std::io::Result>> { + let r = client::request("GET", &format!("/containers/{}/archive?path={}", escape(container), escape(file)), None)?; + if !r.ok() { + return Err(std::io::Error::other(r.error())); + } + extract_tar_file(&r.body, max_bytes) } /// The docker CLI installed beside kiri-win (kiri.ps1 puts it in bin\), @@ -507,7 +526,7 @@ pub fn docker_cli() -> String { /// A console with a shell in the container, as the Mac opens Terminal. pub fn terminal(name: &str, pipe: &str) { - if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c)) { + if name.is_empty() || name.starts_with('-') || !name.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c)) { return; } // \\.\pipe\kiri is npipe:////./pipe/kiri to the docker CLI. Launch the @@ -518,7 +537,7 @@ pub fn terminal(name: &str, pipe: &str) { let mut cmd = crate::win::tool(&docker_cli()); std::os::windows::process::CommandExt::creation_flags(&mut cmd, CREATE_NEW_CONSOLE); let spawned = cmd - .args(["--host", &host, "exec", "-it", name, "sh", "-c", "exec $(command -v bash || command -v sh)"]) + .args(["--host", &host, "exec", "-it", "--", name, "sh", "-c", "exec $(command -v bash || command -v sh)"]) .spawn(); if let Err(e) = spawned { emit(notice("error", &trf("Could not open a terminal: {error}", &[("error", &e)]))); @@ -545,5 +564,27 @@ mod tests { assert_eq!(safe_filename("com1.txt"), "_com1.txt"); // Ordinary names pass through. assert_eq!(safe_filename("report.pdf"), "report.pdf"); + // Multi-byte UTF-8 straddling byte 200 never panics, and truncation cannot leave a trailing dot. + let long_utf8 = format!("{}é.txt", "a".repeat(199)); + let got = safe_filename(&long_utf8); + assert!(got.len() <= 200 && !got.ends_with('.'), "{got:?}"); + let trailing_dot = format!("{}.txt", "a".repeat(199)); + assert!(!safe_filename(&trailing_dot).ends_with('.')); + } + + #[test] + fn extract_tar_file_checks_overflow_and_preview_cap() { + let mut tar = vec![0u8; 1024]; + // Oversized octal size (11 octal 7s = 8 GiB - 1) must fail cleanly. + tar[124..135].copy_from_slice(b"77777777777"); + assert!(super::extract_tar_file(&tar, None).is_err()); + assert_eq!(super::extract_tar_file(&tar, Some(super::PREVIEW_MAX)).unwrap(), None); + + // Valid 5-byte payload. + let mut ok_tar = vec![0u8; 1024]; + ok_tar[124..135].copy_from_slice(b"00000000005"); + ok_tar[512..517].copy_from_slice(b"hello"); + assert_eq!(super::extract_tar_file(&ok_tar, Some(super::PREVIEW_MAX)).unwrap(), Some(b"hello".to_vec())); + assert_eq!(super::extract_tar_file(&ok_tar, Some(4)).unwrap(), None); } } diff --git a/crates/kiri-win/src/engine.rs b/crates/kiri-win/src/engine.rs index e732d7e31..3536eaa41 100644 --- a/crates/kiri-win/src/engine.rs +++ b/crates/kiri-win/src/engine.rs @@ -641,17 +641,25 @@ fn refresh() { let images = client::get_quick("/images/json")?; let volumes = client::get_quick("/volumes")?; let networks = client::get_quick("/networks")?; - let add_icon = |mut v: Value, name_of: &dyn Fn(&Value) -> String| { + let mut used_brands = serde_json::Map::new(); + let mut add_icon = |mut v: Value, name_of: &dyn Fn(&Value) -> String| { if let Some(list) = v.as_array_mut() { for item in list { - item["icon"] = json!(brand(&name_of(item))); + if let Some(slug) = brand(&name_of(item)) { + if !used_brands.contains_key(slug) + && let Some(svg) = brand_svg(slug) + { + used_brands.insert(slug.to_owned(), json!(svg)); + } + item["icon"] = Value::String(slug.to_owned()); + } } } v }; let containers = add_icon(containers, &|c| c["Image"].as_str().unwrap_or_default().to_owned()); let images = add_icon(images, &|i| i["RepoTags"][0].as_str().unwrap_or_default().to_owned()); - Ok(json!({"type": "lists", "containers": containers, "images": images, "volumes": volumes["Volumes"], "networks": networks})) + Ok(json!({"type": "lists", "brands": used_brands, "containers": containers, "images": images, "volumes": volumes["Volumes"], "networks": networks})) })(); match lists { Ok(v) => { @@ -747,16 +755,19 @@ fn unanswered(kind: io::ErrorKind, shown: bool) -> Option<&'static str> { } } -/// The brand logo for an image name like `bitnami/redis:7`: first by the +/// The brand slug for an image name like `bitnami/redis:7`: first by the /// whole repository path, then by its last component. -pub(crate) fn brand(name: &str) -> Option<[&'static str; 2]> { +pub(crate) fn brand(name: &str) -> Option<&'static str> { let name = name.split_once('@').map_or(name, |(n, _)| n); let repo = match name.rfind(':') { Some(i) if !name[i..].contains('/') => &name[..i], _ => name, }; let last = repo.rsplit('/').next().unwrap_or(repo); - let slug = [repo, last].into_iter().find_map(|key| brands::IMAGES.binary_search_by_key(&key, |(k, _)| k).ok().map(|i| brands::IMAGES[i].1))?; + [repo, last].into_iter().find_map(|key| brands::IMAGES.binary_search_by_key(&key, |(k, _)| k).ok().map(|i| brands::IMAGES[i].1)) +} + +pub(crate) fn brand_svg(slug: &str) -> Option<[&'static str; 2]> { let i = brands::BRANDS.binary_search_by_key(&slug, |(s, _, _)| s).ok()?; let (_, hex, path) = brands::BRANDS[i]; Some([hex, path]) @@ -910,7 +921,7 @@ fn pull(name: String) { Err(_) if stopped => emit(json!({"type": "pull", "state": "done", "name": reference, "cancelled": true}).to_string()), Ok(()) => { emit(json!({"type": "pull", "state": "done", "name": reference}).to_string()); - emit(json!({"type": "pulled", "name": reference, "ms": began.elapsed().as_millis() as u64, "icon": brand(&reference)}).to_string()); + emit(json!({"type": "pulled", "name": reference, "ms": began.elapsed().as_millis() as u64, "icon": brand(&reference).and_then(brand_svg)}).to_string()); } Err(e) => emit(json!({"type": "pull", "state": "done", "name": reference, "error": e.to_string()}).to_string()), } @@ -1377,6 +1388,9 @@ fn set_pref(name: &str, value: Value) { if !matches!(name, "font" | "mono" | "scale" | "termH" | "termFs" | "termFont" | "domainsAsked" | "theme" | "accent" | "starAsked" | "updateAuto" | "lang" | "langAsked" | "closeButton" | "startAtLogin" | "stopOnQuit") { return; } + if name == "lang" && !value.as_str().is_some_and(crate::lang::valid_pick) { + return; + } let Some(path) = prefs_path() else { return }; let mut p = prefs(); p[name] = value; @@ -1760,6 +1774,8 @@ pub fn on_message(msg: &str) { Handle.eval(js); } } + "loadxterm" => Handle.eval(crate::assemble::xterm_js().to_owned()), + "loadpanels" => Handle.eval(crate::assemble::panels_js().to_owned()), // Off the window's thread: GDI lists every installed face, twice. "fonts" => { std::thread::spawn(|| emit(fonts_event().to_owned())); diff --git a/crates/kiri-win/src/hub.rs b/crates/kiri-win/src/hub.rs index a5a2b2b51..45083d500 100644 --- a/crates/kiri-win/src/hub.rs +++ b/crates/kiri-win/src/hub.rs @@ -33,6 +33,9 @@ const MAX_CACHE_AGE: u64 = 7 * 24 * 60 * 60; const KEEP: usize = 256; /// curl's whole-request limit, so a Hub that does not answer cannot pin a thread. const TIMEOUT_SECS: &str = "20"; +/// Maximum response bytes accepted from an external registry or Docker Hub API. +const MAX_RESPONSE_BYTES: usize = 4 * 1024 * 1024; +const MAX_RESPONSE_STR: &str = "4194304"; /// One writer at a time for the cache file. static CACHE: Mutex<()> = Mutex::new(()); @@ -70,7 +73,7 @@ fn cached(kind: Kind, key: &str) -> Option<(u64, Value)> { let entry = load()[kind.key()][key].clone(); // The file is anyone's to edit: read back as Docker Hub's answer is. let items = match kind { - Kind::Search => hubrows::search_rows(&entry["items"], crate::engine::brand), + Kind::Search => hubrows::search_rows(&entry["items"], |n| crate::engine::brand(n).and_then(crate::engine::brand_svg)), Kind::Tags => hubrows::tags(&entry["items"]), }; Some((entry["at"].as_u64()?, items)) @@ -127,7 +130,7 @@ fn search(term: &str) -> Result { // Hub's own order puts empty namesakes first: official images lead, // then the most starred. rows.sort_by_key(|r| (!r["is_official"].as_bool().unwrap_or(false), std::cmp::Reverse(r["star_count"].as_u64().unwrap_or(0)))); - Ok(hubrows::search_rows(&Value::Array(rows), crate::engine::brand)) + Ok(hubrows::search_rows(&Value::Array(rows), |n| crate::engine::brand(n).and_then(crate::engine::brand_svg))) } /// A Hub repository's tags, most recently pushed first (`postgres` gives @@ -142,12 +145,13 @@ fn tags(repo: &str) -> Result, String> { let url = format!("https://hub.docker.com/v2/repositories/{repo}/tags?page_size=100&ordering=last_updated"); let mut cmd = crate::win::tool("curl.exe"); std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); - let out = cmd.args(["-fsSL", "--max-time", TIMEOUT_SECS, "--"]).arg(&url).stdin(Stdio::null()).stderr(Stdio::piped()).output().map_err(|e| format!("curl.exe: {e}"))?; - if !out.status.success() { - let err = String::from_utf8_lossy(&out.stderr); + cmd.args(["-fsSL", "--proto", "=https", "--proto-redir", "=https", "--globoff", "--max-time", TIMEOUT_SECS, "--max-filesize", MAX_RESPONSE_STR, "--"]).arg(&url); + let (status, stdout, stderr) = run_curl_capped(cmd, None)?; + if !status.success() { + let err = String::from_utf8_lossy(&stderr); return Err(err.lines().find(|l| !l.trim().is_empty()).unwrap_or("Docker Hub did not answer").trim().to_owned()); } - let body: Value = serde_json::from_slice(&out.stdout).map_err(|e| e.to_string())?; + let body: Value = serde_json::from_slice(&stdout).map_err(|e| e.to_string())?; Ok(order_tags(body["results"].as_array().into_iter().flatten().filter_map(|t| t["name"].as_str().map(str::to_owned)).collect())) } @@ -187,7 +191,7 @@ fn registry_tags(name: &str) -> Result, String> { while pages < 20 { let (status, headers, body) = curl(&url, token.as_deref())?; if status == 401 && token.is_none() { - token = Some(bearer_token(header(&headers, "www-authenticate").ok_or_else(|| format!("{host} wants a sign-in"))?)?); + token = Some(bearer_token(header(&headers, "www-authenticate").ok_or_else(|| format!("{host} wants a sign-in"))?, host)?); continue; } if status != 200 { @@ -200,9 +204,9 @@ fn registry_tags(name: &str) -> Result, String> { let body: Value = serde_json::from_slice(&body).map_err(|e| e.to_string())?; tags.extend(body["tags"].as_array().into_iter().flatten().filter_map(|t| t.as_str()).filter(|t| !t.starts_with("sha256-")).map(str::to_owned)); pages += 1; - // Only a next page on the same registry is followed. + // Only a next page on the same registry is followed, with no control/glob/whitespace chars. match header(&headers, "link").and_then(tagorder::next_link) { - Some(n) if n.starts_with("/v2/") => url = format!("{base}{n}"), + Some(n) if valid_next_link(n) => url = format!("{base}{n}"), _ => break, } } @@ -212,20 +216,157 @@ fn registry_tags(name: &str) -> Result, String> { Ok(tags) } +fn valid_next_link(n: &str) -> bool { + n.starts_with("/v2/") + && !n.contains("..") + && !n.bytes().any(|b| b <= 0x20 || b == 0x7f || b"{}[]\\".contains(&b)) +} + +fn valid_bearer_token(t: &str) -> bool { + !t.is_empty() && t.len() <= 16_384 && t.bytes().all(|b| b.is_ascii_alphanumeric() || b"-._~+/=".contains(&b)) +} + +fn is_local_or_private_host(host: &str) -> bool { + let bare = host.trim_start_matches('[').trim_end_matches(']').trim_end_matches('.').to_ascii_lowercase(); + if bare.is_empty() + || bare.contains('%') + || bare == "localhost" + || bare.ends_with(".localhost") + || bare.ends_with(".local") + || bare.ends_with(".internal") + { + return true; + } + if let Ok(ip) = bare.parse::() { + return match ip.to_canonical() { + std::net::IpAddr::V4(v4) => { + v4.is_loopback() + || v4.is_private() + || v4.is_link_local() + || v4.is_unspecified() + || v4.is_broadcast() + || (v4.octets()[0] == 100 && (v4.octets()[1] & 0xc0) == 64) + } + std::net::IpAddr::V6(v6) => { + v6.is_loopback() + || v6.is_unspecified() + || (v6.segments()[0] & 0xfe00) == 0xfc00 + || (v6.segments()[0] & 0xffc0) == 0xfe80 + } + }; + } + // Reject non-dotted-quad numeric/octal/hex/short IPv4 literals (e.g. + // `127.1`, `2130706433`, `0x7f000001`, `0177.0.0.1`) that curl/getaddrinfo + // resolve to loopback/private IPs; valid DNS TLDs never begin with a digit. + bare.rsplit('.').next().is_some_and(|tld| tld.as_bytes().first().is_some_and(u8::is_ascii_digit)) +} + +fn host_of_authority(authority: &str) -> &str { + if authority.starts_with('[') { + authority.find(']').map_or(authority, |i| &authority[..=i]) + } else { + authority.split(':').next().unwrap_or(authority) + } +} + +/// Validates a Bearer `realm` URL: HTTPS only, no whitespace/control/glob/userinfo, +/// and blocks loopback/private/link-local SSRF targets for public registries. +fn allowed_realm(realm: &str, registry_host: &str) -> Result<(), String> { + let Some(rest) = realm.strip_prefix("https://") else { + return Err("the registry's sign-in isn't https".to_owned()); + }; + if realm.bytes().any(|b| b <= 0x20 || b == 0x7f || b"{}[]\\@".contains(&b)) { + return Err("the registry's sign-in URL is invalid".to_owned()); + } + let authority = rest.split(['/', '?', '#']).next().unwrap_or(""); + let realm_host = host_of_authority(authority); + if realm_host.is_empty() { + return Err("the registry's sign-in URL has no host".to_owned()); + } + let reg_host = host_of_authority(registry_host); + if !is_local_or_private_host(reg_host) && is_local_or_private_host(realm_host) { + return Err("the registry's sign-in points at a private or local address".to_owned()); + } + Ok(()) +} + +fn run_curl_capped(mut cmd: std::process::Command, stdin_bytes: Option<&[u8]>) -> Result<(std::process::ExitStatus, Vec, Vec), String> { + use std::io::{Read, Write}; + if stdin_bytes.is_some() { + cmd.stdin(Stdio::piped()); + } else { + cmd.stdin(Stdio::null()); + } + let mut child = cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().map_err(|e| format!("curl.exe: {e}"))?; + if let Some(bytes) = stdin_bytes + && let Some(mut stdin) = child.stdin.take() + { + let _ = stdin.write_all(bytes); + } + let mut stdout_pipe = child.stdout.take().ok_or("curl.exe: no stdout")?; + let mut stderr_pipe = child.stderr.take().ok_or("curl.exe: no stderr")?; + let err_reader = std::thread::spawn(move || { + let mut buf = Vec::new(); + let _ = stderr_pipe.by_ref().take(65_536).read_to_end(&mut buf); + buf + }); + let mut stdout = Vec::new(); + let mut chunk = [0u8; 16_384]; + let mut too_big = false; + loop { + match stdout_pipe.read(&mut chunk) { + Ok(0) => break, + Ok(n) => { + if stdout.len() + n > MAX_RESPONSE_BYTES { + too_big = true; + break; + } + stdout.extend_from_slice(&chunk[..n]); + } + Err(e) => { + let _ = child.kill(); + let _ = child.wait(); + let _ = err_reader.join(); + return Err(format!("curl.exe: {e}")); + } + } + } + if too_big { + let _ = child.kill(); + let _ = child.wait(); + let _ = err_reader.join(); + return Err("the registry's answer was too large".to_owned()); + } + let status = child.wait().map_err(|e| format!("curl.exe: {e}"))?; + let stderr = err_reader.join().unwrap_or_default(); + Ok((status, stdout, stderr)) +} + /// GET through curl.exe: the status, the headers and the body. fn curl(url: &str, token: Option<&str>) -> Result<(u16, String, Vec), String> { + if !url.starts_with("https://") || url.bytes().any(|b| b <= 0x20 || b == 0x7f || b"{}[]\\".contains(&b)) { + return Err("invalid registry URL".to_owned()); + } let mut cmd = crate::win::tool("curl.exe"); std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); - cmd.args(["-sS", "-i", "--max-time", TIMEOUT_SECS]); - if let Some(t) = token { - cmd.arg("-H").arg(format!("Authorization: Bearer {t}")); - } - let out = cmd.arg("--").arg(url).stdin(Stdio::null()).stderr(Stdio::piped()).output().map_err(|e| format!("curl.exe: {e}"))?; - if !out.status.success() { - let err = String::from_utf8_lossy(&out.stderr); + cmd.args(["-sS", "-i", "--proto", "=https", "--proto-redir", "=https", "--globoff", "--max-time", TIMEOUT_SECS, "--max-filesize", MAX_RESPONSE_STR]); + let cfg = match token { + Some(t) => { + if !valid_bearer_token(t) { + return Err("the registry returned an invalid bearer token".to_owned()); + } + cmd.args(["-K", "-"]); + Some(format!("header = \"Authorization: Bearer {t}\"\n")) + } + None => None, + }; + cmd.arg("--").arg(url); + let (status, stdout, stderr) = run_curl_capped(cmd, cfg.as_deref().map(str::as_bytes))?; + if !status.success() { + let err = String::from_utf8_lossy(&stderr); return Err(err.lines().find(|l| !l.trim().is_empty()).unwrap_or("the registry did not answer").trim().to_owned()); } - split_response(&out.stdout).ok_or_else(|| "the registry's answer couldn't be read".to_owned()) + split_response(&stdout).ok_or_else(|| "the registry's answer couldn't be read".to_owned()) } /// `curl -i`'s output: the last header block (after any `100 Continue`) and the body. @@ -246,20 +387,29 @@ fn header<'a>(head: &'a str, name: &str) -> Option<&'a str> { head.lines().find_map(|l| l.split_once(':').filter(|(k, _)| k.trim().eq_ignore_ascii_case(name)).map(|(_, v)| v.trim())) } +fn query_escape(s: &str) -> String { + s.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-._~:/".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect() +} + /// The anonymous token a Bearer challenge's realm hands out /// (`Bearer realm="https://ghcr.io/token",service="ghcr.io",scope="repository:o/r:pull"`). -fn bearer_token(challenge: &str) -> Result { +fn bearer_token(challenge: &str, registry_host: &str) -> Result { let rest = challenge.get(..7).filter(|b| b.eq_ignore_ascii_case("bearer ")).map(|_| &challenge[7..]).ok_or("the registry wants a password")?; let param = |k: &str| rest.split(',').find_map(|p| p.trim().strip_prefix(k).and_then(|v| v.strip_prefix('='))).map(|v| v.trim_matches('"').to_owned()); - let realm = param("realm").filter(|r| r.starts_with("https://")).ok_or("the registry's sign-in isn't https")?; - let query: Vec = ["service", "scope"].iter().filter_map(|k| param(k).map(|v| format!("{k}={}", v.replace(' ', "%20")))).collect(); + let realm = param("realm").ok_or("the registry's sign-in isn't https")?; + allowed_realm(&realm, registry_host)?; + let query: Vec = ["service", "scope"].iter().filter_map(|k| param(k).map(|v| format!("{k}={}", query_escape(&v)))).collect(); let url = if query.is_empty() { realm } else { format!("{realm}{}{}", if realm.contains('?') { "&" } else { "?" }, query.join("&")) }; let (status, _, body) = curl(&url, None)?; if status != 200 { return Err(format!("the registry's token service answered {status}")); } let v: Value = serde_json::from_slice(&body).map_err(|e| e.to_string())?; - v["token"].as_str().or(v["access_token"].as_str()).map(str::to_owned).ok_or_else(|| "the registry gave no token".to_owned()) + let tok = v["token"].as_str().or(v["access_token"].as_str()).map(str::to_owned).ok_or_else(|| "the registry gave no token".to_owned())?; + if !valid_bearer_token(&tok) { + return Err("the registry returned an invalid bearer token".to_owned()); + } + Ok(tok) } fn fetch(kind: Kind, key: &str) -> Result { @@ -367,4 +517,41 @@ mod tests { assert!(!entries.contains_key("fresh-000")); assert!(entries.contains_key("fresh-299")); } + + #[test] + fn bearer_realm_blocks_ssrf_and_token_and_link_reject_injection() { + assert!(allowed_realm("https://ghcr.io/token", "ghcr.io").is_ok()); + for bad in [ + "http://ghcr.io/token", + "https://127.0.0.1/token", + "https://127.1/token", + "https://2130706433/token", + "https://0x7f000001/token", + "https://0177.0.0.1/token", + "https://localhost:8443/token", + "https://localhost./token", + "https://metadata.google.internal/token", + "https://[::1]/token", + "https://169.254.169.254/latest/meta-data", + "https://10.0.0.1/token", + "https://192.168.1.1/token", + "https://ghcr.io/{1..100}", + "https://ghcr.io/a b", + "https://user@ghcr.io/token", + ] { + assert!(allowed_realm(bad, "ghcr.io").is_err(), "accepted unsafe realm {bad:?}"); + } + // A local registry may use a local realm. + assert!(allowed_realm("https://localhost:5001/token", "localhost:5000").is_ok()); + + assert!(valid_bearer_token("eyJhbGciOiJSUzI1NiJ9.abc_123-+/=")); + for bad in ["", "tok\r\nX-Inject: 1", "tok with space", "tok\"quote"] { + assert!(!valid_bearer_token(bad), "accepted unsafe token {bad:?}"); + } + + assert!(valid_next_link("/v2/o/r/tags/list?last=b&n=1000")); + for bad in ["/v1/foo", "/v2/../secret", "/v2/a{1..10}", "/v2/a b", "/v2/a\r\n"] { + assert!(!valid_next_link(bad), "accepted unsafe next link {bad:?}"); + } + } } diff --git a/crates/kiri-win/src/page.rs b/crates/kiri-win/src/page.rs index 63fe64a7c..ee27fe39a 100644 --- a/crates/kiri-win/src/page.rs +++ b/crates/kiri-win/src/page.rs @@ -25,8 +25,12 @@ pub const PAGE_URL: &str = "https://kiri.invalid/"; /// The WebResourceRequested filter: the whole host, so the handler sees /// (and refuses) whatever else is asked of it. pub const FILTER: &str = "https://kiri.invalid/*"; -/// The page's headers: UTF-8 HTML, and kept out of the HTTP cache. -pub const PAGE_HEADERS: &str = "Content-Type: text/html; charset=utf-8\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff"; +/// Catch-all WebResourceRequested filter for defense-in-depth: intercepts +/// any subresource request to external origins and returns 404. +#[cfg_attr(not(windows), allow(dead_code))] +pub const ALL_RESOURCES_FILTER: &str = "*"; +/// The page's headers: UTF-8 HTML, strict CSP, and kept out of the HTTP cache. +pub const PAGE_HEADERS: &str = "Content-Type: text/html; charset=utf-8\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\nContent-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; font-src data:; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'"; pub const NOT_FOUND_HEADERS: &str = "Cache-Control: no-store"; /// What the handler answers a request for `uri` with. @@ -93,7 +97,7 @@ mod tests { } assert_eq!(answer("POST", PAGE_URL), Answer::NotFound); assert!(FILTER.starts_with(PAGE_URL) && FILTER.ends_with("/*")); - assert!(PAGE_HEADERS.contains("text/html; charset=utf-8") && PAGE_HEADERS.contains("no-store") && NOT_FOUND_HEADERS.contains("no-store")); + assert!(PAGE_HEADERS.contains("text/html; charset=utf-8") && PAGE_HEADERS.contains("no-store") && PAGE_HEADERS.contains("Content-Security-Policy:") && NOT_FOUND_HEADERS.contains("no-store")); } #[test] diff --git a/crates/kiri-win/src/pipe.rs b/crates/kiri-win/src/pipe.rs index eee391e69..72a92a08a 100644 --- a/crates/kiri-win/src/pipe.rs +++ b/crates/kiri-win/src/pipe.rs @@ -338,8 +338,10 @@ pub(crate) fn current_user_sid() -> Option { CloseHandle(token); return None; } - let mut buf = vec![0u8; len as usize]; - let got = GetTokenInformation(token, TokenUser, buf.as_mut_ptr().cast(), len, &mut len); + let words = (len as usize).div_ceil(std::mem::size_of::()); + let mut buf = vec![0usize; words]; + let mut cap = (words * std::mem::size_of::()) as u32; + let got = GetTokenInformation(token, TokenUser, buf.as_mut_ptr().cast(), cap, &mut cap); CloseHandle(token); if got == 0 { return None; diff --git a/crates/kiri-win/src/ports.rs b/crates/kiri-win/src/ports.rs index 0cfdd462e..c5d7a70e8 100644 --- a/crates/kiri-win/src/ports.rs +++ b/crates/kiri-win/src/ports.rs @@ -209,13 +209,104 @@ pub struct TcpForwarder { thread: Option>, } +#[cfg(windows)] +fn bind_winsock_exclusive(bind_addr: SocketAddr, sock_type: i32, proto: i32, listen_backlog: Option) -> io::Result { + use windows_sys::Win32::Networking::WinSock::{ + bind, closesocket, listen, setsockopt, socket, WSAStartup, AF_INET, AF_INET6, IN6_ADDR, IN6_ADDR_0, INVALID_SOCKET, IN_ADDR, IN_ADDR_0, + SOCKADDR, SOCKADDR_IN, SOCKADDR_IN6, SOCKADDR_IN6_0, SOL_SOCKET, SO_REUSEADDR, WSADATA, + }; + const SO_EXCLUSIVEADDRUSE: i32 = !SO_REUSEADDR; + // SAFETY: plain Winsock calls; socket is closed on every error path. + unsafe { + let mut data: WSADATA = std::mem::zeroed(); + if WSAStartup(0x0202, &mut data) != 0 { + return Err(io::Error::other("Winsock did not start")); + } + let family = if bind_addr.is_ipv6() { AF_INET6 } else { AF_INET }; + let s = socket(i32::from(family), sock_type, proto); + if s == INVALID_SOCKET { + return Err(io::Error::last_os_error()); + } + let one: i32 = 1; + if setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (&one as *const i32).cast(), 4) != 0 { + let e = io::Error::last_os_error(); + closesocket(s); + return Err(e); + } + let bound = match bind_addr { + SocketAddr::V4(v4) => { + let addr = SOCKADDR_IN { + sin_family: AF_INET, + sin_port: v4.port().to_be(), + sin_addr: IN_ADDR { S_un: IN_ADDR_0 { S_addr: u32::from_ne_bytes(v4.ip().octets()) } }, + sin_zero: [0; 8], + }; + bind(s, (&addr as *const SOCKADDR_IN).cast::(), std::mem::size_of::() as i32) + } + SocketAddr::V6(v6) => { + let addr = SOCKADDR_IN6 { + sin6_family: AF_INET6, + sin6_port: v6.port().to_be(), + sin6_flowinfo: v6.flowinfo(), + sin6_addr: IN6_ADDR { u: IN6_ADDR_0 { Byte: v6.ip().octets() } }, + Anonymous: SOCKADDR_IN6_0 { sin6_scope_id: v6.scope_id() }, + }; + bind(s, (&addr as *const SOCKADDR_IN6).cast::(), std::mem::size_of::() as i32) + } + }; + if bound != 0 { + let e = io::Error::last_os_error(); + closesocket(s); + return Err(e); + } + if let Some(backlog) = listen_backlog + && listen(s, backlog) != 0 + { + let e = io::Error::last_os_error(); + closesocket(s); + return Err(e); + } + Ok(s as std::os::windows::io::RawSocket) + } +} + +fn bind_tcp_exclusive(bind_addr: SocketAddr) -> io::Result { + #[cfg(windows)] + { + use std::os::windows::io::FromRawSocket; + use windows_sys::Win32::Networking::WinSock::{IPPROTO_TCP, SOCK_STREAM}; + let s = bind_winsock_exclusive(bind_addr, SOCK_STREAM, IPPROTO_TCP, Some(128))?; + // SAFETY: `bind_winsock_exclusive` returns a bound, listening TCP socket owned solely by us. + Ok(unsafe { TcpListener::from_raw_socket(s) }) + } + #[cfg(not(windows))] + { + TcpListener::bind(bind_addr) + } +} + +fn bind_udp_exclusive(bind_addr: SocketAddr) -> io::Result { + #[cfg(windows)] + { + use std::os::windows::io::FromRawSocket; + use windows_sys::Win32::Networking::WinSock::{IPPROTO_UDP, SOCK_DGRAM}; + let s = bind_winsock_exclusive(bind_addr, SOCK_DGRAM, IPPROTO_UDP, None)?; + // SAFETY: `bind_winsock_exclusive` returns a bound UDP socket owned solely by us. + Ok(unsafe { UdpSocket::from_raw_socket(s) }) + } + #[cfg(not(windows))] + { + UdpSocket::bind(bind_addr) + } +} + impl TcpForwarder { pub fn start(bind_addr: SocketAddr, target_addr: SocketAddr) -> io::Result { Self::start_with_limit(bind_addr, target_addr, MAX_TCP_CONNS) } pub fn start_with_limit(bind_addr: SocketAddr, target_addr: SocketAddr, max_conns: usize) -> io::Result { - let listener = TcpListener::bind(bind_addr)?; + let listener = bind_tcp_exclusive(bind_addr)?; listener.set_nonblocking(true)?; let local_addr = listener.local_addr()?; let stop = Arc::new(AtomicBool::new(false)); @@ -554,7 +645,7 @@ pub struct UdpForwarder { impl UdpForwarder { pub fn start(bind_addr: SocketAddr, target_addr: SocketAddr) -> io::Result { - let listener = UdpSocket::bind(bind_addr)?; + let listener = bind_udp_exclusive(bind_addr)?; disable_udp_connreset(&listener); listener.set_read_timeout(Some(UDP_POLL))?; let local_addr = listener.local_addr()?; @@ -697,7 +788,7 @@ mod runtime { use std::sync::Condvar; use serde_json::json; use windows_sys::Win32::Networking::WinSock::{ - AF_INET, AF_INET6, SIO_ADDRESS_LIST_QUERY, SOCKADDR_IN, SOCKADDR_IN6, SOCKET, SOCKET_ADDRESS_LIST, WSAIoctl, + AF_INET, AF_INET6, SIO_ADDRESS_LIST_QUERY, SOCKADDR_IN, SOCKADDR_IN6, SOCKET, SOCKET_ADDRESS, SOCKET_ADDRESS_LIST, WSAIoctl, }; const RESYNC_INTERVAL: Duration = Duration::from_secs(3); @@ -748,13 +839,17 @@ mod runtime { ) }; if rc == 0 && (returned as usize) >= std::mem::size_of::() { - // SAFETY: WSAIoctl succeeded and filled ` SOCKET_ADDRESS_LIST` inside `buf`. + // SAFETY: WSAIoctl succeeded and filled `SOCKET_ADDRESS_LIST` inside `buf`; + // `count` is bounded by `returned` bytes so `from_raw_parts` stays within `buf`. unsafe { let list = &*(buf.as_ptr() as *const SOCKET_ADDRESS_LIST); - let count = (list.iAddressCount.max(0) as usize).min(256); + let hdr = std::mem::offset_of!(SOCKET_ADDRESS_LIST, Address); + let max_fit = (returned as usize).saturating_sub(hdr) / std::mem::size_of::(); + let count = (list.iAddressCount.max(0) as usize).min(max_fit).min(256); let addrs = std::slice::from_raw_parts(list.Address.as_ptr(), count); for entry in addrs { if !entry.lpSockaddr.is_null() + && entry.iSockaddrLength > 0 && (entry.iSockaddrLength as usize) >= std::mem::size_of::() && (*entry.lpSockaddr).sa_family == AF_INET { @@ -791,13 +886,17 @@ mod runtime { ) }; if rc == 0 && (returned as usize) >= std::mem::size_of::() { - // SAFETY: WSAIoctl succeeded and filled `SOCKET_ADDRESS_LIST` inside `buf`. + // SAFETY: WSAIoctl succeeded and filled `SOCKET_ADDRESS_LIST` inside `buf`; + // `count` is bounded by `returned` bytes so `from_raw_parts` stays within `buf`. unsafe { let list = &*(buf.as_ptr() as *const SOCKET_ADDRESS_LIST); - let count = (list.iAddressCount.max(0) as usize).min(256); + let hdr = std::mem::offset_of!(SOCKET_ADDRESS_LIST, Address); + let max_fit = (returned as usize).saturating_sub(hdr) / std::mem::size_of::(); + let count = (list.iAddressCount.max(0) as usize).min(max_fit).min(256); let addrs = std::slice::from_raw_parts(list.Address.as_ptr(), count); for entry in addrs { if !entry.lpSockaddr.is_null() + && entry.iSockaddrLength > 0 && (entry.iSockaddrLength as usize) >= std::mem::size_of::() && (*entry.lpSockaddr).sa_family == AF_INET6 { diff --git a/crates/kiri-win/src/relay.rs b/crates/kiri-win/src/relay.rs index a7e792080..26c835b2f 100644 --- a/crates/kiri-win/src/relay.rs +++ b/crates/kiri-win/src/relay.rs @@ -129,13 +129,41 @@ fn current_distro_and_kiri() -> Option<(String, String)> { Some((distro, crate::serve::kiri())) } +/// Sensitive internal loopback ports (e.g. Kiri's Kubernetes API on 6443) that +/// are never exposed via the catch-all `host.docker.internal` relay unless +/// explicitly listed in `allowed`. +const INTERNAL_DENY_PORTS: &[u16] = &[6443]; + +/// Whether a container connection to Windows loopback `port` is permitted. +fn port_allowed(port: u16, host_enabled: bool, allowed: &HashSet) -> bool { + if port == 0 { + return false; + } + if allowed.contains(&port) { + return true; + } + host_enabled && !INTERNAL_DENY_PORTS.contains(&port) +} + +/// Toggles catch-all `host.docker.internal` forwarding to Windows loopback +/// (explicit static proxy ports in `allowed` continue to work). +#[allow(dead_code)] +pub fn set_host_enabled(on: bool) { + HOST_ENABLED_DEFAULT.store(on, Ordering::SeqCst); + if let Some(r) = lock(&RELAY).as_ref() { + r.host_enabled.store(on, Ordering::SeqCst); + } +} + +static HOST_ENABLED_DEFAULT: AtomicBool = AtomicBool::new(true); + fn start(distro: Option, kiri: String) -> io::Result> { let mut cmd = crate::win::tool("wsl.exe"); if let Some(d) = &distro { cmd.args(["-d", d]); } let mut child = cmd - .args(["-u", "root", "--", &kiri, "hostrelay"]) + .args(["-u", "root", "-e", &kiri, "hostrelay"]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::null()) @@ -154,7 +182,7 @@ fn start(distro: Option, kiri: String) -> io::Result> { child: child_slot.clone(), distro, kiri, - host_enabled: AtomicBool::new(true), + host_enabled: AtomicBool::new(HOST_ENABLED_DEFAULT.load(Ordering::SeqCst)), host_port: AtomicU16::new(0), allowed: Mutex::new(HashSet::new()), ports: Mutex::new(HashMap::new()), @@ -170,7 +198,7 @@ fn start(distro: Option, kiri: String) -> io::Result> { let end = hostrelay::dial_side_with_host( output, &r.out, - move |port| port != 0 && (a.host_enabled.load(Ordering::SeqCst) || lock(&a.allowed).contains(&port)), + move |port| port_allowed(port, a.host_enabled.load(Ordering::SeqCst), &lock(&a.allowed)), move |target, local| { lock(&p.ports).insert(target, local); p.changed.notify_all(); @@ -324,3 +352,23 @@ pub fn ports(targets: &[u16]) -> HashMap { } map } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn port_allowed_enforces_host_toggle_and_internal_deny_list() { + let empty = HashSet::new(); + assert!(!port_allowed(0, true, &empty)); + assert!(port_allowed(8080, true, &empty)); + assert!(!port_allowed(8080, false, &empty)); + // Kiri's k8s API port (6443) is denied unless explicitly allowlisted. + assert!(!port_allowed(6443, true, &empty)); + let mut explicit = HashSet::new(); + explicit.insert(6443); + explicit.insert(8080); + assert!(port_allowed(6443, true, &explicit)); + assert!(port_allowed(8080, false, &explicit)); + } +} diff --git a/crates/kiri-win/src/setup.rs b/crates/kiri-win/src/setup.rs index 75d4c3d47..20262dae0 100644 --- a/crates/kiri-win/src/setup.rs +++ b/crates/kiri-win/src/setup.rs @@ -556,7 +556,13 @@ fn download(pin: &Pin, task_index: usize) -> io::Result { let _ = std::fs::remove_file(&part); let label = trf("Downloading {name} from {source}", &[("name", &pin.name), ("source", &if pin.url.contains("github.com/microsoft") { "Microsoft" } else { "ubuntu.com" })]); task(task_index, "active", &format!("0 / {} MB", mb(pin.size))); - let mut child = quiet("curl.exe").args(["-fsSL", "--retry", "3", "-o"]).arg(&part).arg(pin.url).spawn()?; + let max_size = pin.size.saturating_add(16 * 1024 * 1024).to_string(); + let mut child = quiet("curl.exe") + .args(["-fsSL", "--proto", "=https", "--proto-redir", "=https", "--retry", "3", "--max-time", "3600", "--max-filesize", &max_size, "-o"]) + .arg(&part) + .arg("--") + .arg(pin.url) + .spawn()?; let (start, mut last, mut rate) = (Instant::now(), (Instant::now(), 0u64), 0f64); loop { if CANCEL.load(Ordering::SeqCst) { @@ -764,7 +770,7 @@ fn install_linux(kind: &str) -> io::Result<()> { } task(1, "done", ""); task(2, "active", ""); - wsl_ok(quiet("wsl.exe").args(["-d", KIRI_DISTRO, "-u", "root", "--", "/usr/local/bin/kiri-start"]))?; + wsl_ok(quiet("wsl.exe").args(["-d", KIRI_DISTRO, "-u", "root", "-e", "/usr/local/bin/kiri-start"]))?; task(2, "done", ""); KIRI_DISTRO.to_owned() } else { @@ -797,7 +803,7 @@ fn install_linux(kind: &str) -> io::Result<()> { verified("kiri")?; verified("kiri-init")?; let install = to_wsl(&distro, &verified("install.sh")?)?; - wsl_ok(quiet("wsl.exe").args(["-d", &distro, "-u", "root", "--", "sh", &install]))?; + wsl_ok(quiet("wsl.exe").args(["-d", &distro, "-u", "root", "-e", "sh", &install]))?; task(1, "done", ""); task(2, "done", ""); distro @@ -813,9 +819,21 @@ fn install_linux(kind: &str) -> io::Result<()> { /// A Windows path as `distro` sees it. Killed after WSL_LIMIT, as the /// other calls into WSL to start or restart the engine. +/// Uses `-e` (`--exec`) rather than `--` so the Windows path is passed as a +/// single argv element without login-shell word splitting or command substitution. pub(crate) fn to_wsl(distro: &str, path: &Path) -> io::Result { - let out = crate::update::output_within(quiet("wsl.exe").args(["-d", distro, "--", "wslpath", "-a"]).arg(path.to_string_lossy().replace('\\', "/")), crate::update::WSL_LIMIT)?; - Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned()) + let win_path = path.to_string_lossy().replace('\\', "/"); + let out = crate::update::output_within(quiet("wsl.exe").args(["-d", distro, "-e", "wslpath", "-a"]).arg(&win_path), crate::update::WSL_LIMIT)?; + if !out.status.success() { + let text = wsl_output(&out.stdout, &out.stderr); + let line = text.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("wslpath failed"); + return Err(io::Error::other(line.to_owned())); + } + let converted = String::from_utf8_lossy(&out.stdout).trim().to_owned(); + if converted.is_empty() { + return Err(io::Error::other("wslpath returned an empty path")); + } + Ok(converted) } fn wsl_ok(cmd: &mut Command) -> io::Result<()> { diff --git a/crates/kiri-win/src/storage.rs b/crates/kiri-win/src/storage.rs index 4950693b5..d691fde12 100644 --- a/crates/kiri-win/src/storage.rs +++ b/crates/kiri-win/src/storage.rs @@ -28,6 +28,23 @@ pub const MARKER: &str = ".kiri-storage"; const MOVING: &str = ".kiri-moving"; const IGNORED: &[&str] = &["desktop.ini", "Thumbs.db", MOVING, MARKER]; +/// Constant PowerShell command for `compact_vhdx`: the VHDX path is passed +/// solely through the `KIRI_VHDX` environment variable, never interpolated into +/// command text (avoiding ASCII and Unicode single-quote breakout). +#[cfg_attr(not(windows), allow(dead_code))] +const OPTIMIZE_VHD_CMD: &str = "Optimize-VHD -Path $env:KIRI_VHDX -Mode Full"; + +/// Builds a `diskpart.exe` script to compact `vhdx`, rejecting characters +/// (`\r`, `\n`, `\0`, `"`) that could inject extra diskpart commands. +#[cfg_attr(not(windows), allow(dead_code))] +fn diskpart_script_content(vhdx: &Path) -> io::Result { + let s = vhdx.to_string_lossy(); + if s.is_empty() || s.contains(['\r', '\n', '\0', '"']) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "VHDX path contains characters not allowed in a diskpart script")); + } + Ok(format!("select vdisk file=\"{s}\"\r\nattach vdisk readonly\r\ncompact vdisk\r\ndetach vdisk\r\n")) +} + /// What `storage.json` holds. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Choice { @@ -781,26 +798,47 @@ mod imp { fn compact_vhdx(vhdx: &Path) -> io::Result<()> { // First try Hyper-V's Optimize-VHD via PowerShell if installed. - let escaped = vhdx.to_string_lossy().replace('\'', "''"); + // Pass the path via env var (never interpolated into -Command) so ASCII + // or Unicode quotes and metacharacters cannot break out of a literal. let ps = crate::win::tool("powershell.exe") .creation_flags(CREATE_NO_WINDOW) - .args([ - "-NoProfile", - "-NonInteractive", - "-Command", - &format!("Optimize-VHD -Path '{escaped}' -Mode Full"), - ]) + .env("KIRI_VHDX", vhdx) + .args(["-NoProfile", "-NonInteractive", "-Command", OPTIMIZE_VHD_CMD]) .output(); if ps.as_ref().is_ok_and(|o| o.status.success()) { return Ok(()); } // Fallback: diskpart compact vdisk on an offline VHDX. - let script = std::env::temp_dir().join(format!("kiri-compact-{}.txt", std::process::id())); - let vhdx_str = vhdx.to_string_lossy().replace('"', ""); - let content = format!( - "select vdisk file=\"{vhdx_str}\"\r\nattach vdisk readonly\r\ncompact vdisk\r\ndetach vdisk\r\n" - ); - fs::write(&script, content.as_bytes())?; + // Write to a newly created private script file inside %LOCALAPPDATA%\Kiri + // (never a predictable filename in shared %TEMP%). + let content = diskpart_script_content(vhdx)?; + let private_dir = config_path().parent().map(Path::to_path_buf).unwrap_or_else(default_root); + fs::create_dir_all(&private_dir)?; + let (script, mut file) = { + use std::sync::atomic::AtomicU64; + static SEQ: AtomicU64 = AtomicU64::new(0); + let pid = std::process::id(); + let mut created = None; + for _ in 0..32 { + let n = SEQ.fetch_add(1, Ordering::Relaxed); + let candidate = private_dir.join(format!("compact-{pid}-{n}.txt")); + match fs::OpenOptions::new().write(true).create_new(true).open(&candidate) { + Ok(f) => { + created = Some((candidate, f)); + break; + } + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e), + } + } + created.ok_or_else(|| io::Error::new(io::ErrorKind::AlreadyExists, "could not create private diskpart script"))? + }; + if let Err(e) = io::Write::write_all(&mut file, content.as_bytes()) { + drop(file); + let _ = fs::remove_file(&script); + return Err(e); + } + drop(file); let res = crate::win::tool("diskpart.exe") .creation_flags(CREATE_NO_WINDOW) .arg("/s") @@ -859,7 +897,7 @@ mod imp { std::ffi::OsStr::new(&distro), std::ffi::OsStr::new("-u"), std::ffi::OsStr::new("root"), - std::ffi::OsStr::new("--"), + std::ffi::OsStr::new("-e"), std::ffi::OsStr::new("sh"), std::ffi::OsStr::new("-c"), std::ffi::OsStr::new("fstrim /var/lib/kiri 2>/dev/null || true; fstrim / 2>/dev/null || true"), @@ -1033,4 +1071,24 @@ mod tests { assert_eq!((eff2, clamp2), (Some(17_400_000_000), Some(1_400_000_000))); let _ = fs::remove_dir_all(&d); } + + #[test] + fn compact_vhdx_helpers_block_powershell_and_diskpart_injection() { + assert_eq!(OPTIMIZE_VHD_CMD, "Optimize-VHD -Path $env:KIRI_VHDX -Mode Full"); + assert!(!OPTIMIZE_VHD_CMD.contains('\'')); + // Unicode quotes and semicolons are valid Windows filenames, safe in diskpart quotes. + let ok = diskpart_script_content(Path::new(r"C:\Users\o’neil;calc\ext4.vhdx")).unwrap(); + assert!(ok.starts_with("select vdisk file=\"C:\\Users\\o’neil;calc\\ext4.vhdx\"\r\n")); + // Newlines, NULs, and embedded double quotes must be rejected. + for bad in [ + "", + "C:\\a\"\r\nselect disk 0\r\nclean", + "C:\\a\nclean", + "C:\\a\rclean", + "C:\\a\0b\\ext4.vhdx", + "C:\\a\"b\\ext4.vhdx", + ] { + assert!(diskpart_script_content(Path::new(bad)).is_err(), "accepted unsafe path: {bad:?}"); + } + } } diff --git a/crates/kiri-win/src/term.rs b/crates/kiri-win/src/term.rs index 9b63c5bc0..fb50ffea0 100644 --- a/crates/kiri-win/src/term.rs +++ b/crates/kiri-win/src/term.rs @@ -215,8 +215,10 @@ fn end_running(console: Arc, process: Arc) { /// its exit code. #[allow(clippy::type_complexity)] pub fn captured(program: &std::path::Path, args: &[&str]) -> std::io::Result<(std::sync::mpsc::Receiver>, Sender>, Box, std::sync::mpsc::Receiver>)> { - let quote = |s: &str| if s.is_empty() || s.contains([' ', '\t', '"']) { format!("\"{}\"", s.replace('"', "\\\"")) } else { s.to_owned() }; - let command = std::iter::once(quote(&program.to_string_lossy())).chain(args.iter().map(|a| quote(a))).collect::>().join(" "); + let command = std::iter::once(crate::win::quote(&program.to_string_lossy())) + .chain(args.iter().map(|a| crate::win::quote(a))) + .collect::>() + .join(" "); let (con_in, typed_w) = pipe()?; let (screen_r, con_out) = pipe()?; let mut hpc: HPCON = 0; @@ -282,8 +284,7 @@ pub fn captured(program: &std::path::Path, args: &[&str]) -> std::io::Result<(st } fn system32(exe: &str) -> PathBuf { - let root = std::env::var_os("SystemRoot").map_or_else(|| PathBuf::from(r"C:\Windows"), PathBuf::from); - root.join("System32").join(exe) + crate::win::resolve(exe) } fn pwsh() -> Option { @@ -308,7 +309,7 @@ fn shells() -> Vec { // Kiri's own distro runs the engine; Docker Desktop's aren't for logging into. for d in crate::setup::distros().unwrap_or_default() { let lower = d.to_ascii_lowercase(); - if !lower.starts_with("kiri") && !lower.starts_with("docker-desktop") && d.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)) { + if !lower.starts_with("kiri") && !lower.starts_with("docker-desktop") && crate::wslsync::valid_distro_name(&d) { list.push(Shell { id: format!("wsl:{d}"), label: format!("WSL · {d}"), group: "WSL" }); } } @@ -317,11 +318,11 @@ fn shells() -> Vec { /// The command line for a listed shell's id. fn command_line(id: &str) -> String { - let quoted = |p: PathBuf| format!("\"{}\"", p.display()); + let quoted = |p: PathBuf| crate::win::quote(&p.to_string_lossy()); match id { - "pwsh" => pwsh().map_or_else(|| quoted(system32(r"WindowsPowerShell\v1.0\powershell.exe")), quoted) + " -NoLogo", - "powershell" => quoted(system32(r"WindowsPowerShell\v1.0\powershell.exe")) + " -NoLogo", - // Distro names were checked to be plain in shells(). + "pwsh" => pwsh().map_or_else(|| quoted(system32("powershell.exe")), quoted) + " -NoLogo", + "powershell" => quoted(system32("powershell.exe")) + " -NoLogo", + // Distro names were checked by wslsync::valid_distro_name in shells(). _ if id.starts_with("wsl:") => format!("{} -d {} --cd ~", quoted(system32("wsl.exe")), &id[4..]), _ => quoted(system32("cmd.exe")), } @@ -546,11 +547,12 @@ fn spawn(command: &str, hpc: HPCON) -> std::io::Result { /// The clipboard's text, handed to `done` on a thread of its own. pub fn paste(done: impl FnOnce(String) + Send + 'static) { use windows_sys::Win32::System::DataExchange::{CloseClipboard, GetClipboardData, OpenClipboard}; - use windows_sys::Win32::System::Memory::{GlobalLock, GlobalUnlock}; + use windows_sys::Win32::System::Memory::{GlobalLock, GlobalSize, GlobalUnlock}; const CF_UNICODETEXT: u32 = 13; std::thread::spawn(move || { - // SAFETY: the clipboard is opened, read and closed here; the locked - // memory is a NUL-terminated UTF-16 string while it stays locked. + // SAFETY: the clipboard is opened, read and closed here; we bound the + // UTF-16 scan by both `GlobalSize(h) / 2` and `COPY_MAX` so malformed + // non-NUL-terminated or oversized clipboard data cannot OOB-read or OOM. let text = unsafe { // Another program may have it open for a moment. let mut opened = false; @@ -567,10 +569,12 @@ pub fn paste(done: impl FnOnce(String) + Send + 'static) { let h = GetClipboardData(CF_UNICODETEXT); let mut text = String::new(); if h != 0 { + let max_units = (GlobalSize(h as _) / 2).min(termwire::COPY_MAX); let p = GlobalLock(h as _) as *const u16; if !p.is_null() { - let len = (0..).take_while(|&i| *p.add(i) != 0).count(); - text = String::from_utf16_lossy(std::slice::from_raw_parts(p, len)); + let slice = std::slice::from_raw_parts(p, max_units); + let len = slice.iter().position(|&u| u == 0).unwrap_or(slice.len()); + text = String::from_utf16_lossy(&slice[..len]); GlobalUnlock(h as _); } } diff --git a/crates/kiri-win/src/update.rs b/crates/kiri-win/src/update.rs index 1d47c9c18..03ad2f28e 100644 --- a/crates/kiri-win/src/update.rs +++ b/crates/kiri-win/src/update.rs @@ -889,10 +889,14 @@ pub fn install_staged() -> io::Result { #[cfg(windows)] pub fn restart_engine() -> io::Result<()> { let distro = crate::setup::saved_distro().ok_or_else(|| io::Error::other("Kiri's Linux is not set up"))?; + // Verify bundled binaries against embedded KIRI_BUNDLE_SHA256 before copying + // or executing them as root inside WSL. + crate::setup::verified("kiri")?; + crate::setup::verified("kiri-init")?; let script = if distro == crate::setup::KIRI_DISTRO { format!("( {} ) >/dev/null || exit 1; pkill -f '/usr/local/bin/[k]iri bridge'; /usr/local/bin/kiri-start --restart", crate::wslsync::sync_script(&dir(), "", true)) } else { - let install = crate::setup::to_wsl(&distro, &dir().join("install.sh"))?; + let install = crate::setup::to_wsl(&distro, &crate::setup::verified("install.sh")?)?; format!("sh {} && pkill -f '/usr/local/bin/[k]iri bridge'; true", crate::wslsync::sh_quote(&install)) }; let mut cmd = crate::win::tool("wsl.exe"); @@ -1153,6 +1157,8 @@ pub fn sync_engine() -> io::Result { if !dir().join("kiri").is_file() || !dir().join("kiri-init").is_file() { return Ok(false); } + crate::setup::verified("kiri")?; + crate::setup::verified("kiri-init")?; let distro = crate::setup::saved_distro().ok_or_else(|| io::Error::other("Kiri's Linux is not set up"))?; let script = crate::wslsync::sync_script(&dir(), "", distro == crate::setup::KIRI_DISTRO); let mut cmd = crate::win::tool("wsl.exe"); diff --git a/crates/kiri-win/src/usb.rs b/crates/kiri-win/src/usb.rs index 7c7a3d1f8..522bc3dce 100644 --- a/crates/kiri-win/src/usb.rs +++ b/crates/kiri-win/src/usb.rs @@ -15,13 +15,43 @@ use crate::engine::{emit, notice}; const CREATE_NO_WINDOW: u32 = 0x0800_0000; -fn usbipd_path() -> Option { - let installed = std::env::var_os("ProgramFiles").map(|p| PathBuf::from(p).join("usbipd-win").join("usbipd.exe")); - if let Some(p) = installed.filter(|p| p.is_file()) { - return Some(p); +/// Resolves `usbipd.exe` exclusively under a known `Program Files` directory +/// returned by Windows' shell API — never the mutable `ProgramFiles` env var or +/// `PATH`, because `attach()` elevates this executable via UAC (`runas`). +fn trusted_usbipd_in(program_files_dirs: &[PathBuf]) -> Option { + program_files_dirs + .iter() + .map(|d| d.join("usbipd-win").join("usbipd.exe")) + .find(|p| p.is_file()) +} + +fn known_program_files() -> Vec { + use windows_sys::Win32::System::Com::CoTaskMemFree; + use windows_sys::Win32::UI::Shell::{FOLDERID_ProgramFiles, SHGetKnownFolderPath}; + let mut dirs = Vec::new(); + let mut ptr: windows_sys::core::PWSTR = std::ptr::null_mut(); + // SAFETY: known folder GUID; `ptr` is freed with `CoTaskMemFree`. + let hr = unsafe { SHGetKnownFolderPath(&FOLDERID_ProgramFiles, 0, 0, &mut ptr) }; + if hr == 0 && !ptr.is_null() { + // SAFETY: `SHGetKnownFolderPath` returns a NUL-terminated UTF-16 string. + let path = unsafe { + let mut n = 0usize; + while *ptr.add(n) != 0 { + n += 1; + } + String::from_utf16_lossy(std::slice::from_raw_parts(ptr, n)) + }; + // SAFETY: allocated by `SHGetKnownFolderPath`. + unsafe { CoTaskMemFree(ptr.cast()) }; + if !path.is_empty() { + dirs.push(PathBuf::from(path)); + } } - // On PATH, from another install. - std::env::var_os("PATH").and_then(|path| std::env::split_paths(&path).map(|d| d.join("usbipd.exe")).find(|p| p.is_file())) + dirs +} + +fn usbipd_path() -> Option { + trusted_usbipd_in(&known_program_files()) } fn run(args: &[&str]) -> io::Result { @@ -232,4 +262,19 @@ mod tests { assert!(valid("1-3") && valid("12-10")); assert!(!valid("") && !valid("1-3 & calc") && !valid("--busid")); } + + #[test] + fn trusted_usbipd_only_resolves_inside_known_program_files() { + let base = std::env::temp_dir().join(format!("kiri-usb-trust-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let pf = base.join("Program Files"); + let dir = pf.join("usbipd-win"); + std::fs::create_dir_all(&dir).unwrap(); + let exe = dir.join("usbipd.exe"); + std::fs::write(&exe, b"stub").unwrap(); + assert_eq!(trusted_usbipd_in(&[pf.clone()]), Some(exe)); + assert_eq!(trusted_usbipd_in(&[base.join("Other")]), None); + assert_eq!(trusted_usbipd_in(&[]), None); + let _ = std::fs::remove_dir_all(&base); + } } diff --git a/crates/kiri-win/src/watch.rs b/crates/kiri-win/src/watch.rs index adf91b5eb..3f9f50ae3 100644 --- a/crates/kiri-win/src/watch.rs +++ b/crates/kiri-win/src/watch.rs @@ -431,7 +431,7 @@ fn collapse_specs(specs: Vec) -> Vec { if exclude_self && parent.eq_ignore_ascii_case(path) { return false; } - if path.len() < parent.len() { + if path.len() < parent.len() || !path.is_char_boundary(parent.len()) { return false; } let head = &path[..parent.len()]; @@ -1031,4 +1031,19 @@ mod tests { assert_eq!(tail.last(), Some(&('U', wsl_root))); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn collapse_specs_handles_multibyte_utf8_boundaries() { + // Parent "C:\proj\ap" (10 bytes) vs sibling "C:\proj\aé" (byte 10 splits 'é'): + // must not panic on UTF-8 char boundary slicing. + let specs = vec![ + WatchSpec { dir: r"C:\proj\ap".into(), recursive: true, only_file: None }, + WatchSpec { dir: r"C:\proj\aé".into(), recursive: true, only_file: None }, + WatchSpec { dir: r"C:\proj\ap\sub".into(), recursive: true, only_file: None }, + ]; + let collapsed = collapse_specs(specs); + assert_eq!(collapsed.len(), 2); + assert!(collapsed.iter().any(|s| s.dir == r"C:\proj\ap")); + assert!(collapsed.iter().any(|s| s.dir == r"C:\proj\aé")); + } } diff --git a/crates/kiri-win/src/win.rs b/crates/kiri-win/src/win.rs index 4ae742d79..d8c34a89a 100644 --- a/crates/kiri-win/src/win.rs +++ b/crates/kiri-win/src/win.rs @@ -131,7 +131,7 @@ pub fn elevated(program: &Path, args: &[&str]) -> io::Result { /// One argument as Windows' command-line parsing (CommandLineToArgvW, and /// PowerShell's) reads it back: quoted when it has a space, tab or quote, /// with backslashes doubled only before a quote. -fn quote(arg: &str) -> String { +pub(crate) fn quote(arg: &str) -> String { if !arg.is_empty() && !arg.contains([' ', '\t', '"']) { return arg.to_owned(); } diff --git a/crates/kiri-win/src/wslsync.rs b/crates/kiri-win/src/wslsync.rs index 8eb56a822..85eb48368 100644 --- a/crates/kiri-win/src/wslsync.rs +++ b/crates/kiri-win/src/wslsync.rs @@ -373,19 +373,41 @@ pub fn wsl_enable_script(distro: &str, root: &str) -> String { elif pgrep -x dockerd >/dev/null 2>&1 || pidof dockerd >/dev/null 2>&1; then busy=1; fi; \ fi; \ [ \"$busy\" = 0 ] && ln -sfn {sock_target} \"$vr/docker.sock\"; \ - if [ -n \"$uhome\" ] && [ -d {host_prefix}\"$uhome\" ] && [ ! -L {host_prefix}\"$uhome/.docker\" ]; then \ - dctx={host_prefix}\"$uhome/.docker/contexts\"; \ - if [ -L \"$dctx\" ]; then \ - dt=$(readlink \"$dctx\" 2>/dev/null || true); \ - case \"$dt\" in */mnt/*) \ - tmp=\"$dctx.kiri.$$\"; rm -rf \"$tmp\"; mkdir -p \"$tmp\" && cp -r \"$dctx/.\" \"$tmp/\" 2>/dev/null || true; \ - rm -f \"$dctx\" && mv \"$tmp\" \"$dctx\" ;; \ - esac; \ + if [ -n \"$uhome\" ] && [ -d {host_prefix}\"$uhome\" ] && [ ! -L {host_prefix}\"$uhome\" ]; then \ + cbase={host_prefix}\"$uhome\"; \ + if [ ! -L \"$cbase/.docker\" ]; then \ + dctx=\"$cbase/.docker/contexts\"; \ + if [ -L \"$dctx\" ]; then \ + dt=$(readlink \"$dctx\" 2>/dev/null || true); \ + case \"$dt\" in */mnt/*) \ + tmp=\"$dctx.kiri.$$\"; \ + if [ ! -e \"$tmp\" ] && [ ! -L \"$tmp\" ] && mkdir \"$tmp\" 2>/dev/null; then \ + cp -rP \"$dctx/.\" \"$tmp/\" 2>/dev/null || true; \ + [ -n \"$uuid\" ] && [ -n \"$ugid\" ] && chown -hR \"$uuid:$ugid\" \"$tmp\" 2>/dev/null || true; \ + rm -f \"$dctx\" && mv \"$tmp\" \"$dctx\" || rm -rf \"$tmp\" 2>/dev/null || true; \ + fi ;; \ + esac; \ + fi; \ fi; \ - if [ ! -L \"$dctx\" ]; then \ - cdir=\"$dctx/meta/{KIRI_CONTEXT_HASH}\"; \ - mkdir -p \"$cdir\" 2>/dev/null && printf %s {} | base64 -d >\"$cdir/meta.json\" 2>/dev/null; \ - [ -n \"$uuid\" ] && [ -n \"$ugid\" ] && chown -R \"$uuid:$ugid\" {host_prefix}\"$uhome/.docker\" 2>/dev/null || true; \ + safe=1; \ + for seg in .docker .docker/contexts .docker/contexts/meta .docker/contexts/meta/{KIRI_CONTEXT_HASH}; do \ + p=\"$cbase/$seg\"; \ + if [ -L \"$p\" ]; then safe=0; break; fi; \ + if [ ! -e \"$p\" ]; then \ + mkdir \"$p\" 2>/dev/null || {{ safe=0; break; }}; \ + [ -n \"$uuid\" ] && [ -n \"$ugid\" ] && chown -h \"$uuid:$ugid\" \"$p\" 2>/dev/null || true; \ + elif [ ! -d \"$p\" ]; then safe=0; break; fi; \ + done; \ + if [ \"$safe\" = 1 ]; then \ + cdir=\"$cbase/.docker/contexts/meta/{KIRI_CONTEXT_HASH}\"; \ + tmp=\"$cdir/.meta.json.kiri.$$\"; \ + if [ ! -L \"$tmp\" ]; then \ + rm -f \"$tmp\" 2>/dev/null; \ + if (set -C; printf %s {} | base64 -d >\"$tmp\") 2>/dev/null; then \ + [ -n \"$uuid\" ] && [ -n \"$ugid\" ] && chown -h \"$uuid:$ugid\" \"$tmp\" 2>/dev/null || true; \ + if [ ! -L \"$cdir/meta.json\" ]; then mv -f \"$tmp\" \"$cdir/meta.json\" 2>/dev/null || rm -f \"$tmp\"; else rm -f \"$tmp\"; fi; \ + else rm -f \"$tmp\" 2>/dev/null; fi; \ + fi; \ fi; \ fi; \ echo \"$gid\"", @@ -778,6 +800,16 @@ mod tests { assert!(out.status.success()); assert!(own_sock.exists(), "running dockerd socket must not be removed on disable"); + // 5. Symlinked meta.json or parent dir in user's home must never overwrite a target outside $HOME. + let sentinel = dir.join("root-sentinel.txt"); + std::fs::write(&sentinel, "DO NOT OVERWRITE").unwrap(); + let meta_file = root.join(format!("home/alice/.docker/contexts/meta/{KIRI_CONTEXT_HASH}/meta.json")); + let _ = std::fs::remove_file(&meta_file); + std::os::unix::fs::symlink(&sentinel, &meta_file).unwrap(); + let out = Command::new("sh").args(["-c", &enable]).env("PATH", &path).output().unwrap(); + assert!(out.status.success()); + assert_eq!(std::fs::read_to_string(&sentinel).unwrap(), "DO NOT OVERWRITE", "symlinked meta.json must not clobber target"); + let _ = std::fs::remove_dir_all(&dir); } } diff --git a/crates/kiri/src/bridge.rs b/crates/kiri/src/bridge.rs index 3833a9e56..4bdb86581 100644 --- a/crates/kiri/src/bridge.rs +++ b/crates/kiri/src/bridge.rs @@ -509,6 +509,19 @@ fn gone(e: &io::Error) -> bool { matches!(e.kind(), io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused) } +/// Trusted absolute paths for `systemctl` when `kiri bridge` runs as root. +const SYSTEMCTL_PATHS: &[&str] = &["/usr/bin/systemctl", "/bin/systemctl", "/run/current-system/sw/bin/systemctl"]; +const SAFE_PATH: &str = "/usr/sbin:/sbin:/usr/bin:/bin:/run/current-system/sw/bin"; + +fn find_systemctl_in(paths: &[&Path]) -> Option { + paths.iter().find(|p| p.is_file()).map(|p| p.to_path_buf()) +} + +fn find_systemctl() -> Option { + let paths: Vec<&Path> = SYSTEMCTL_PATHS.iter().map(Path::new).collect(); + find_systemctl_in(&paths) +} + /// Starts the daemon as this distro does: kiri-start in Kiri Linux, /// systemd's `kiri` service in a distro with systemd (contrib/wsl/install.sh). /// Killed at `until`. kiri-start's exit 1 (no socket yet) may still end @@ -516,10 +529,13 @@ fn gone(e: &io::Error) -> bool { fn start_engine(until: Instant) -> Result<(), String> { let kiri_start = Path::new(KIRI_START).exists(); let mut cmd = if kiri_start { - Command::new(KIRI_START) + let mut c = Command::new(KIRI_START); + c.env("PATH", SAFE_PATH); + c } else if Path::new("/run/systemd/system").exists() { - let mut c = Command::new("systemctl"); - c.args(["start", "kiri"]); + let systemctl = find_systemctl().ok_or_else(|| "systemctl not found in trusted system directories".to_owned())?; + let mut c = Command::new(systemctl); + c.env_clear().env("PATH", SAFE_PATH).env("LC_ALL", "C").args(["start", "kiri"]); c } else { return Err("nothing in this Linux starts it (no kiri-start, no systemd)".to_owned()); @@ -1257,4 +1273,21 @@ mod tests { } assert_eq!(reply, b"ping"); } + + #[test] + fn find_systemctl_only_uses_trusted_paths() { + let dir = std::env::temp_dir().join(format!("kiri-bridge-systemctl-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let untrusted = dir.join("untrusted/systemctl"); + let missing = dir.join("missing/systemctl"); + let trusted = dir.join("trusted/systemctl"); + std::fs::create_dir_all(untrusted.parent().unwrap()).unwrap(); + std::fs::create_dir_all(trusted.parent().unwrap()).unwrap(); + std::fs::write(&untrusted, "#!/bin/sh\nexit 0\n").unwrap(); + std::fs::write(&trusted, "#!/bin/sh\nexit 0\n").unwrap(); + + assert_eq!(find_systemctl_in(&[missing.as_path(), trusted.as_path()]), Some(trusted.clone())); + assert_eq!(find_systemctl_in(&[missing.as_path()]), None); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/kiri/src/buildwith.rs b/crates/kiri/src/buildwith.rs index 68a927ee3..c4e94126a 100644 --- a/crates/kiri/src/buildwith.rs +++ b/crates/kiri/src/buildwith.rs @@ -96,14 +96,41 @@ fn read_object(path: &Path) -> io::Result { } /// Through a temporary file, so a crash never leaves half a file. +/// Creates missing parent directories with `0o700` and temp files with `0o600` +/// on Unix so `~/.docker/config.json` registry credentials stay owner-only. fn write_bytes(path: &Path, bytes: &[u8]) -> io::Result<()> { + use std::io::Write; static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + std::fs::DirBuilder::new().recursive(true).mode(0o700).create(dir)?; + } + #[cfg(not(unix))] std::fs::create_dir_all(dir)?; let file = path.file_name().and_then(|n| n.to_str()).unwrap_or("tmp"); - let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let tmp = dir.join(format!(".{file}.kiri-tmp-{}-{seq}", std::process::id())); - let res = std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, path)); + let mut attempt = 0u32; + let (tmp, mut f) = loop { + let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let candidate = dir.join(format!(".{file}.kiri-tmp-{}-{seq}", std::process::id())); + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + match opts.open(&candidate) { + Ok(f) => break (candidate, f), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists && attempt < 32 => attempt += 1, + Err(e) => return Err(e), + } + }; + let res = f.write_all(bytes).and_then(|()| f.flush()).and_then(|()| { + drop(f); + std::fs::rename(&tmp, path) + }); if res.is_err() { let _ = std::fs::remove_file(&tmp); } @@ -665,4 +692,21 @@ mod tests { } let _ = std::fs::remove_dir_all(&d); } + + #[cfg(unix)] + #[test] + fn write_bytes_preserves_0600_docker_config_permissions() { + use std::os::unix::fs::PermissionsExt; + let d = scratch("mode-0600"); + let p = places(&d); + builder(&p); + write_json(&p.config(), &json!({"auths": {"ghcr.io": {"auth": "dG9r"}}})).unwrap(); + assert_eq!(std::fs::metadata(&p.docker).unwrap().permissions().mode() & 0o777, 0o700); + assert_eq!(std::fs::metadata(p.config()).unwrap().permissions().mode() & 0o777, 0o600); + p.choose(With::Kiri).unwrap(); + assert_eq!(std::fs::metadata(p.config()).unwrap().permissions().mode() & 0o777, 0o600); + p.choose(With::Docker).unwrap(); + assert_eq!(std::fs::metadata(p.config()).unwrap().permissions().mode() & 0o777, 0o600); + let _ = std::fs::remove_dir_all(&d); + } } diff --git a/crates/kiri/src/client.rs b/crates/kiri/src/client.rs index b070f7165..de6f3ee5c 100644 --- a/crates/kiri/src/client.rs +++ b/crates/kiri/src/client.rs @@ -261,11 +261,13 @@ impl Write for WinPipe { } } -fn head(r: &mut impl BufRead) -> io::Result<(u16, Option, bool)> { +fn head(r: &mut impl BufRead) -> io::Result<(u16, Option, bool, bool)> { let mut line = String::new(); - r.read_line(&mut line)?; + if r.read_line(&mut line)? == 0 { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "eof reading status")); + } let status = line.split_whitespace().nth(1).and_then(|s| s.parse().ok()).ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "bad status line"))?; - let (mut len, mut chunked) = (None, false); + let (mut len, mut chunked, mut close) = (None, false, false); loop { line.clear(); if r.read_line(&mut line)? == 0 { @@ -276,14 +278,16 @@ fn head(r: &mut impl BufRead) -> io::Result<(u16, Option, bool)> { break; } if let Some((k, v)) = l.split_once(':') { - match k.to_ascii_lowercase().as_str() { - "content-length" => len = v.trim().parse().ok(), - "transfer-encoding" => chunked = v.trim().eq_ignore_ascii_case("chunked"), - _ => {} + if k.eq_ignore_ascii_case("content-length") { + len = v.trim().parse().ok(); + } else if k.eq_ignore_ascii_case("transfer-encoding") { + chunked = v.trim().eq_ignore_ascii_case("chunked"); + } else if k.eq_ignore_ascii_case("connection") && v.to_ascii_lowercase().contains("close") { + close = true; } } } - Ok((status, len, chunked)) + Ok((status, len, chunked, close)) } /// Reads one chunk of a chunked body; `None` at the end. @@ -317,17 +321,99 @@ pub fn get_background(path: &str) -> io::Result { Ok(r.json()) } +/// Validates an HTTP/1.1 request target before formatting a raw request line +/// onto the daemon socket/pipe (rejects missing leading `/`, `..` traversal +/// segments, whitespace, CRLF, and ASCII control characters). +pub(crate) fn validate_request_path(path: &str) -> io::Result<()> { + if !path.starts_with('/') || path.bytes().any(|b| b <= 0x20 || b == 0x7f) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid HTTP request path")); + } + let path_only = path.split('?').next().unwrap_or(path); + if path_only.split('/').any(|seg| seg == "..") { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "HTTP request path must not contain traversal segments")); + } + Ok(()) +} + +fn validate_header_value(value: &str) -> io::Result<()> { + if value.bytes().any(|b| b == b'\r' || b == b'\n' || b == 0) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "header contains a line break")); + } + Ok(()) +} + #[cfg(unix)] fn send(method: &str, path: &str, body: Option<&Value>, extra: &str) -> io::Result { send_to(&socket()?, method, path, body, extra) } +#[cfg(unix)] +struct PooledConn { + sock: PathBuf, + reader: BufReader, + used_at: std::time::Instant, +} + +#[cfg(unix)] +static CONN_POOL: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +#[cfg(unix)] +const CONN_POOL_MAX: usize = 4; + +#[cfg(unix)] +const CONN_POOL_TTL: Duration = Duration::from_secs(30); + +#[cfg(unix)] +fn take_pooled(sock: &Path) -> Option> { + let now = std::time::Instant::now(); + let mut pool = CONN_POOL.lock().unwrap_or_else(|e| e.into_inner()); + pool.retain(|c| now.duration_since(c.used_at) < CONN_POOL_TTL); + let idx = pool.iter().rposition(|c| c.sock == sock)?; + Some(pool.swap_remove(idx).reader) +} + +#[cfg(unix)] +fn return_pooled(sock: &Path, reader: BufReader) { + if !reader.buffer().is_empty() { + return; + } + let mut pool = CONN_POOL.lock().unwrap_or_else(|e| e.into_inner()); + if pool.len() >= CONN_POOL_MAX { + pool.remove(0); + } + pool.push(PooledConn { sock: sock.to_path_buf(), reader, used_at: std::time::Instant::now() }); +} + #[cfg(unix)] fn send_to(sock: &Path, method: &str, path: &str, body: Option<&Value>, extra: &str) -> io::Result { + validate_request_path(path)?; + // Reuse idle HTTP/1.1 keep-alive connections for idempotent bodyless GET/HEAD + // polls (such as the UI's 4-endpoint refresh cycle), retrying once on a fresh + // connection if the daemon closed an idle socket. + let op = op_header(); + if body.is_none() && (method == "GET" || method == "HEAD") { + let req = format!("{method} {path} HTTP/1.1\r\nHost: kiri\r\nConnection: keep-alive\r\n{extra}{op}\r\n"); + if let Some(mut reader) = take_pooled(sock) { + if reader.get_mut().write_all(req.as_bytes()).is_ok() + && let Ok((resp, reusable)) = answer_keepalive(&mut reader) + { + if reusable { + return_pooled(sock, reader); + } + return Ok(resp); + } + } + let s = connect_to(sock, Some(Duration::from_secs(120)))?; + let mut reader = BufReader::new(s); + reader.get_mut().write_all(req.as_bytes())?; + let (resp, reusable) = answer_keepalive(&mut reader)?; + if reusable { + return_pooled(sock, reader); + } + return Ok(resp); + } let mut s = connect_to(sock, Some(Duration::from_secs(120)))?; let payload = body.map(Value::to_string).unwrap_or_default(); - // The window's action this is part of, for the engine's log lines. - let op = op_header(); let req = format!( "{method} {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{extra}{op}Content-Type: application/json\r\nContent-Length: {}\r\n\r\n{payload}", payload.len() @@ -343,6 +429,7 @@ fn send(method: &str, path: &str, body: Option<&Value>, extra: &str) -> io::Resu #[cfg(windows)] fn send_to_pipe(name: &str, method: &str, path: &str, body: Option<&Value>, extra: &str) -> io::Result { + validate_request_path(path)?; let mut s = WinPipe::open(name)?; let payload = body.map(Value::to_string).unwrap_or_default(); let op = op_header(); @@ -358,23 +445,31 @@ fn send_to_pipe(name: &str, method: &str, path: &str, body: Option<&Value>, extr /// The answer to a request just sent; the whole body is read, chunked or not. fn answer(s: impl Read) -> io::Result { let mut r = BufReader::new(s); - let (status, len, chunked) = head(&mut r)?; + let (resp, _) = answer_keepalive(&mut r)?; + Ok(resp) +} + +fn answer_keepalive(r: &mut impl BufRead) -> io::Result<(Response, bool)> { + let (status, len, chunked, close) = head(r)?; let mut body = Vec::new(); // These never have a body, and the daemon keeps the connection open. if status == 204 || status == 304 { - return Ok(Response { status, body }); + return Ok((Response { status, body }, !close)); } - if chunked { - while let Some(c) = chunk(&mut r)? { + let framed = if chunked { + while let Some(c) = chunk(r)? { body.extend_from_slice(&c); } + true } else if let Some(n) = len { body.resize(n, 0); r.read_exact(&mut body)?; + true } else { r.read_to_end(&mut body)?; - } - Ok(Response { status, body }) + false + }; + Ok((Response { status, body }, framed && !close)) } /// A POST whose body `write` streams, chunked, so its length need not be @@ -384,6 +479,8 @@ fn answer(s: impl Read) -> io::Result { /// refused the request), its answer is returned, which says why. #[cfg(unix)] pub fn post_stream(path: &str, content_type: &str, write: impl FnOnce(&mut dyn Write) -> io::Result<()>) -> io::Result { + validate_request_path(path)?; + validate_header_value(content_type)?; let s = connect(Some(Duration::from_secs(300)))?; let op = op_header(); (&s).write_all(format!("POST {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{op}Content-Type: {content_type}\r\nTransfer-Encoding: chunked\r\n\r\n").as_bytes())?; @@ -399,6 +496,8 @@ pub fn post_stream(path: &str, content_type: &str, write: impl FnOnce(&mut dyn W #[cfg(windows)] pub fn post_stream(path: &str, content_type: &str, write: impl FnOnce(&mut dyn Write) -> io::Result<()>) -> io::Result { + validate_request_path(path)?; + validate_header_value(content_type)?; let mut s = WinPipe::open(&pipe())?; let op = op_header(); let req = format!( @@ -585,8 +684,9 @@ pub fn post_lines_unbounded(path: &str, on_line: impl FnMut(Value)) -> io::Resul #[cfg(unix)] fn post_lines_inner(path: &str, auth: Option<&str>, timeout: Option, opened: impl FnOnce(&UnixStream), mut on_line: impl FnMut(Value)) -> io::Result { - if auth.is_some_and(|a| a.contains(['\r', '\n'])) { - return Err(io::Error::new(io::ErrorKind::InvalidInput, "header contains a line break")); + validate_request_path(path)?; + if let Some(a) = auth { + validate_header_value(a)?; } let auth = auth.map(|a| format!("X-Registry-Auth: {a}\r\n")).unwrap_or_default(); let mut s = connect(timeout)?; @@ -594,7 +694,7 @@ fn post_lines_inner(path: &str, auth: Option<&str>, timeout: Option, o let req = format!("POST {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{auth}{}Content-Type: application/json\r\nContent-Length: 0\r\n\r\n", op_header()); s.write_all(req.as_bytes())?; let mut r = BufReader::new(s); - let (status, len, chunked) = head(&mut r)?; + let (status, len, chunked, _) = head(&mut r)?; let mut pending = Vec::new(); let mut lines = |pending: &mut Vec| { while let Some(i) = pending.iter().position(|&b| b == b'\n') { @@ -627,7 +727,7 @@ pub fn events(mut on_event: impl FnMut(Value) -> bool) -> io::Result<()> { let mut s = connect(None)?; s.write_all(b"GET /events HTTP/1.1\r\nHost: kiri\r\nX-Kiri-Background: 1\r\n\r\n")?; let mut r = BufReader::new(s); - let (status, _, chunked) = head(&mut r)?; + let (status, _, chunked, _) = head(&mut r)?; if status != 200 || !chunked { return Err(io::Error::other(format!("events: HTTP {status}"))); } @@ -656,10 +756,11 @@ pub struct Stream { #[cfg(unix)] impl Stream { pub fn open(path: &str) -> io::Result { + validate_request_path(path)?; let mut s = connect(None)?; s.write_all(format!("GET {path} HTTP/1.1\r\nHost: kiri\r\n\r\n").as_bytes())?; let mut reader = BufReader::new(s); - let (status, _, chunked) = head(&mut reader)?; + let (status, _, chunked, _) = head(&mut reader)?; if status != 200 || !chunked { return Err(io::Error::other(format!("{path}: HTTP {status}"))); } @@ -703,17 +804,19 @@ fn exec_stream_at(sock: &Path, container: &str, cmd: &[&str], mut on_chunk: impl return Err(io::Error::other(created.error())); } let id = created.json()["Id"].as_str().unwrap_or_default().to_owned(); + let start_path = format!("/exec/{id}/start"); + validate_request_path(&start_path)?; let mut out = Vec::new(); { let mut s = connect_to(sock, Some(Duration::from_secs(120)))?; let body = r#"{"Detach":false,"Tty":true}"#; let req = format!( - "POST /exec/{id}/start HTTP/1.1\r\nHost: kiri\r\nConnection: Upgrade\r\nUpgrade: tcp\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", + "POST {start_path} HTTP/1.1\r\nHost: kiri\r\nConnection: Upgrade\r\nUpgrade: tcp\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", body.len() ); s.write_all(req.as_bytes())?; let mut r = BufReader::new(s); - let (status, _, _) = head(&mut r)?; + let (status, _, _, _) = head(&mut r)?; if status != 101 && status != 200 { return Err(io::Error::other(format!("exec: HTTP {status}"))); } @@ -1048,4 +1151,91 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn request_path_and_header_validation_blocks_crlf_and_smuggling() { + assert!(super::validate_request_path("/containers/abc/json?all=1").is_ok()); + for bad in [ + "", + "containers/abc", + "/containers/a b/json", + "/containers/a\r\nPOST /kiri/stop HTTP/1.1", + "/containers/a\n/json", + "/containers/a\x00/json", + "/containers/a\x7f/json", + "/containers/../kiri/stop", + "/../kiri/stop", + ] { + assert_eq!(super::validate_request_path(bad).unwrap_err().kind(), io::ErrorKind::InvalidInput, "{bad:?}"); + } + assert!(super::validate_header_value("application/json").is_ok()); + assert!(super::validate_header_value("application/json\r\nX-Injected: 1").is_err()); + + #[cfg(unix)] + { + match super::send_to(Path::new("/nonexistent"), "GET", "/bad path\r\n", None, "") { + Err(err) => assert_eq!(err.kind(), io::ErrorKind::InvalidInput), + Ok(_) => panic!("expected InvalidInput"), + } + match super::Stream::open("/bad\r\npath") { + Err(err) => assert_eq!(err.kind(), io::ErrorKind::InvalidInput), + Ok(_) => panic!("expected InvalidInput"), + } + } + } + + #[cfg(unix)] + #[test] + fn keepalive_pool_reuses_connection_and_retries_on_idle_close() { + use std::io::{BufRead, BufReader}; + let dir = temp_dir("keepalive-pool"); + let sock = dir.join("docker.sock"); + let listener = UnixListener::bind(&sock).unwrap(); + let accepts = std::sync::Arc::new(AtomicU64::new(0)); + let accepts_srv = accepts.clone(); + let server = std::thread::spawn(move || { + // Connection 1 serves 2 keep-alive requests, then closes. + let (mut conn, _) = listener.accept().unwrap(); + accepts_srv.fetch_add(1, Ordering::SeqCst); + let mut r = BufReader::new(conn.try_clone().unwrap()); + for body in [b"one", b"two"] { + let mut line = String::new(); + loop { + line.clear(); + if r.read_line(&mut line).unwrap() == 0 || line == "\r\n" { + break; + } + } + write!(conn, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", body.len()).unwrap(); + conn.write_all(body).unwrap(); + conn.flush().unwrap(); + } + drop(r); + drop(conn); + // Connection 2 serves the retry after connection 1 closed while pooled. + let (mut conn2, _) = listener.accept().unwrap(); + accepts_srv.fetch_add(1, Ordering::SeqCst); + let mut r2 = BufReader::new(conn2.try_clone().unwrap()); + let mut line = String::new(); + loop { + line.clear(); + if r2.read_line(&mut line).unwrap() == 0 || line == "\r\n" { + break; + } + } + conn2.write_all(b"HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 5\r\n\r\nthree").unwrap(); + conn2.flush().unwrap(); + }); + + let r1 = super::send_to(&sock, "GET", "/_ping", None, "").unwrap(); + assert_eq!((r1.status, r1.body.as_slice()), (200, &b"one"[..])); + let r2 = super::send_to(&sock, "GET", "/_ping", None, "").unwrap(); + assert_eq!((r2.status, r2.body.as_slice()), (200, &b"two"[..])); + assert_eq!(accepts.load(Ordering::SeqCst), 1, "second GET should reuse pooled keep-alive socket"); + let r3 = super::send_to(&sock, "GET", "/_ping", None, "").unwrap(); + assert_eq!((r3.status, r3.body.as_slice()), (200, &b"three"[..])); + assert_eq!(accepts.load(Ordering::SeqCst), 2, "third GET should transparently redial after idle close"); + server.join().unwrap(); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/kiri/src/daemon/access.rs b/crates/kiri/src/daemon/access.rs index ce175796d..173053f0e 100644 --- a/crates/kiri/src/daemon/access.rs +++ b/crates/kiri/src/daemon/access.rs @@ -1848,11 +1848,38 @@ impl Gate { /// Writes the socket's access list: its owner and group (rw, as the mode /// says), each of `uids` (rw), nobody else. +/// +/// Opens `socket` with `O_PATH | O_NOFOLLOW | O_CLOEXEC`, verifies via `fstat` +/// that it is a Unix domain socket owned by our effective UID, and applies the +/// xattr through `/proc/self/fd/` so a symlink planted at `socket` can +/// never redirect root `setxattr(2)` onto an arbitrary host file. pub fn set(socket: &Path, uids: &[u32]) -> io::Result<()> { + use std::os::fd::{FromRawFd, OwnedFd}; let blob = acl(uids); let path = CString::new(socket.as_os_str().as_bytes()).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; + // SAFETY: `path` is valid NUL-terminated; O_PATH | O_NOFOLLOW opens the + // inode itself without connecting or following symlinks. + let raw = unsafe { libc::open(path.as_ptr(), libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC) }; + if raw < 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: `raw >= 0` is a fresh descriptor owned exclusively here. + let fd = unsafe { OwnedFd::from_raw_fd(raw) }; + let mut st: libc::stat = unsafe { std::mem::zeroed() }; + // SAFETY: `fd` is valid and `st` is writable. + if unsafe { libc::fstat(fd.as_raw_fd(), &mut st) } != 0 { + return Err(io::Error::last_os_error()); + } + if (st.st_mode & libc::S_IFMT) != libc::S_IFSOCK { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "refusing to set socket ACL on non-socket path")); + } + // SAFETY: geteuid has no preconditions. + if st.st_uid != unsafe { libc::geteuid() } { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "refusing to set socket ACL on socket owned by another user")); + } + let proc_fd = CString::new(format!("/proc/self/fd/{}", fd.as_raw_fd())).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; // SAFETY: both strings are valid and NUL-terminated; blob outlives the call. - let r = unsafe { libc::setxattr(path.as_ptr(), c"system.posix_acl_access".as_ptr(), blob.as_ptr().cast(), blob.len(), 0) }; + let r = unsafe { libc::setxattr(proc_fd.as_ptr(), c"system.posix_acl_access".as_ptr(), blob.as_ptr().cast(), blob.len(), 0) }; if r == 0 { Ok(()) } else { Err(io::Error::last_os_error()) } } @@ -3353,4 +3380,19 @@ mod tests { assert!(g.sweep_subjects_with(|_| unreachable!(), |_, _| Ok(Membership::MissingFromDirectory)).is_empty()); assert!(g.open.lock().unwrap().is_empty()); } + + #[test] + fn set_refuses_symlinks_and_regular_files() { + let dir = std::env::temp_dir().join(format!("kiri-access-symlink-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let regular = dir.join("target.txt"); + std::fs::write(®ular, b"secret").unwrap(); + let link = dir.join("fake.sock"); + std::os::unix::fs::symlink(®ular, &link).unwrap(); + + assert!(set(®ular, &[1000]).is_err()); + assert!(set(&link, &[1000]).is_err()); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index bbac30007..db4afe6b3 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -102,7 +102,18 @@ pub(super) fn reply(w: &mut UnixStream, result: Result, ok: u16) - // 201 for a tag, 200 for a network connect or disconnect. Client // libraries that check the exact status need it. Ok(Value::Null) => http::empty(w, ok)?, - Ok(v) => http::json(w, ok, &v.to_string())?, + Ok(v) => { + let bytes = serde_json::to_vec(&v).map_err(io::Error::other)?; + http::respond(w, ok, "application/json", &bytes)?; + } + Err(e) => error(w, e)?, + } + Ok(Next::KeepAlive) +} + +fn reply_json_bytes(w: &mut UnixStream, result: Result, Error>, ok: u16) -> io::Result { + match result { + Ok(bytes) => http::respond(w, ok, "application/json", &bytes)?, Err(e) => error(w, e)?, } Ok(Next::KeepAlive) @@ -288,7 +299,7 @@ fn route(req: &Request, engine: &Arc, caller: &Caller, w: &mut UnixStrea } return Ok(Next::KeepAlive); } - ("GET", "/info") => return reply(w, Ok(info(engine)), 200), + ("GET", "/info") => return reply_json_bytes(w, info_json_bytes(engine), 200), ("POST", "/build") => return super::builder::build(req, engine, w, r), ("POST", "/build/cancel") => return reply(w, super::builder::cancel(req, engine), 200), ("POST", "/build/prune") => return reply(w, super::builder::prune(req, engine), 200), @@ -307,7 +318,7 @@ fn route(req: &Request, engine: &Arc, caller: &Caller, w: &mut UnixStrea ("POST", "/kiri/fs-events") => return reply(w, fs_events(req, engine), 204), ("GET", "/kiri/win-ports") => return reply(w, Ok(win_ports(engine)), 200), ("POST", "/kiri/win-ports") => return reply(w, sync_win_ports(req, engine), 200), - ("GET", "/images/json") => return reply(w, images(req, engine), 200), + ("GET", "/images/json") => return reply_json_bytes(w, images_json_bytes(req, engine), 200), ("POST", "/images/create") if req.query("fromSrc").is_some_and(|s| !s.is_empty()) => return image_import(req, engine, w, r), ("POST", "/images/create") => return pull(req, engine, w), ("POST", "/images/load") => return image_load(req, engine, w, r), @@ -316,12 +327,12 @@ fn route(req: &Request, engine: &Arc, caller: &Caller, w: &mut UnixStrea return image_save(engine, &names, w); } ("POST", "/containers/create") => { - if let Some(made) = super::builder::create_for_buildx(engine, req) { + if let Some(made) = super::builder::create_for_buildx(engine, req, caller) { return reply(w, made, 201); } return reply(w, create_by(req, engine, caller), 201); } - ("GET", "/containers/json") => return reply(w, list(req, engine), 200), + ("GET", "/containers/json") => return reply_json_bytes(w, list_json_bytes(req, engine), 200), ("GET", "/networks") => return reply(w, networks(req, engine), 200), ("POST", "/networks/create") => return reply(w, network_create(req, engine), 201), ("POST", "/networks/prune") => return reply(w, network_prune(req, engine), 200), @@ -537,57 +548,152 @@ pub(super) fn version() -> Value { }) } -fn info(engine: &Engine) -> Value { - let states = engine.each(|c| Some(c.status)); - let running = states.iter().filter(|s| **s == Status::Running).count(); - let images = engine.store.images().map(|v| v.len()).unwrap_or(0); +#[derive(serde::Serialize)] +struct InfoKiriRuntime { + path: &'static str, +} + +#[derive(serde::Serialize)] +struct InfoRuntimes { + kiri: InfoKiriRuntime, +} + +#[inline] +fn is_false(b: &bool) -> bool { + !*b +} + +#[inline] +fn is_zero_u8(v: &u8) -> bool { + *v == 0 +} + +#[inline] +fn is_zero_i32(v: &i32) -> bool { + *v == 0 +} + +#[inline] +fn is_zero_u64(v: &u64) -> bool { + *v == 0 +} + +#[inline] +fn is_zero_f64(v: &f64) -> bool { + *v == 0.0 +} + +#[inline] +fn is_empty_values(v: &&[Value]) -> bool { + v.is_empty() +} + +#[derive(serde::Serialize)] +#[allow(non_snake_case)] +struct InfoSummary { + ID: &'static str, + Name: &'static str, + Containers: usize, + ContainersRunning: usize, + ContainersPaused: usize, + ContainersStopped: usize, + Images: usize, + Driver: &'static str, + ServerVersion: &'static str, + KiriVersion: &'static str, + OperatingSystem: &'static str, + OSType: &'static str, + Architecture: &'static str, + KernelVersion: String, + NCPU: usize, + MemTotal: u64, + DockerRootDir: &'static str, + CgroupDriver: &'static str, + CgroupVersion: &'static str, + DefaultRuntime: &'static str, + Runtimes: InfoRuntimes, + SecurityOptions: Vec<&'static str>, + SystemTime: String, + BuilderVersion: &'static str, + IndexServerAddress: &'static str, + RegistryConfig: Value, + #[serde(skip_serializing_if = "is_zero_u64")] + KiriAgentMemory: u64, + KiriVmAwake: bool, + #[serde(skip_serializing_if = "Value::is_null")] + KiriVmUplink: Value, + #[serde(skip_serializing_if = "is_false")] + KiriStopped: bool, + KiriMemoryCeiling: u64, + #[serde(skip_serializing_if = "is_zero_u64")] + KiriMemoryTarget: u64, + #[serde(skip_serializing_if = "is_zero_u64")] + KiriMemoryUsed: u64, + #[serde(skip_serializing_if = "is_zero_f64")] + KiriMemoryStall: f64, + #[serde(skip_serializing_if = "is_zero_u64")] + KiriOomKills: u64, + #[serde(skip_serializing_if = "is_zero_f64")] + KiriCpuPercent: f64, + KiriStorageReadOnly: Option, + KiriStorageZfs: bool, + #[serde(skip_serializing_if = "Vec::is_empty")] + Warnings: Vec, +} + +fn info_json_bytes(engine: &Engine) -> Result, Error> { + let (total, running) = engine.status_counts(); + let images = engine.store.image_count().unwrap_or(0); let (mem_total, _) = engine.guest_memory().unwrap_or((0, 0)); - json!({ - "ID": "kiri", - "Name": "kiri", - "Containers": states.len(), - "ContainersRunning": running, - "ContainersPaused": 0, - "ContainersStopped": states.len() - running, - "Images": images, - "Driver": "overlayfs", - "ServerVersion": ENGINE_VERSION, - "KiriVersion": env!("CARGO_PKG_VERSION"), - "OperatingSystem": "Kiri", - "OSType": "linux", - "Architecture": std::env::consts::ARCH, - "KernelVersion": kernel_version(), - "NCPU": engine.cpus(), - "MemTotal": mem_total, - "DockerRootDir": "/var/lib/kiri", - "CgroupDriver": "cgroupfs", - "CgroupVersion": "2", - "DefaultRuntime": "kiri", - "Runtimes": {"kiri": {"path": "kiri-init"}}, - "SecurityOptions": super::apparmor::info_option().into_iter().chain(["name=seccomp,profile=builtin", "name=cgroupns"]).collect::>(), + let (mem_ceiling, mem_target) = engine.memory(); + let (mem_stall, oom_kills) = engine.memory_trouble(); + let summary = InfoSummary { + ID: "kiri", + Name: "kiri", + Containers: total, + ContainersRunning: running, + ContainersPaused: 0, + ContainersStopped: total - running, + Images: images, + Driver: "overlayfs", + ServerVersion: ENGINE_VERSION, + KiriVersion: env!("CARGO_PKG_VERSION"), + OperatingSystem: "Kiri", + OSType: "linux", + Architecture: std::env::consts::ARCH, + KernelVersion: kernel_version(), + NCPU: engine.cpus(), + MemTotal: mem_total, + DockerRootDir: "/var/lib/kiri", + CgroupDriver: "cgroupfs", + CgroupVersion: "2", + DefaultRuntime: "kiri", + Runtimes: InfoRuntimes { kiri: InfoKiriRuntime { path: "kiri-init" } }, + SecurityOptions: super::apparmor::info_option().into_iter().chain(["name=seccomp,profile=builtin", "name=cgroupns"]).collect(), // Compose needs it to attach in `up` and `logs -f` (#346). - "SystemTime": time::rfc3339(std::time::SystemTime::now()), + SystemTime: time::rfc3339(std::time::SystemTime::now()), // Not in Docker's /info (the ping's Builder-Version header is), but // tools print it: the classic builder API, served by builder.rs. - "BuilderVersion": "1", + BuilderVersion: "1", // `docker info`'s Registry, Insecure Registries and Registry Mirrors: // daemon.json's, as Docker reports its own. - "IndexServerAddress": "https://index.docker.io/v1/", - "RegistryConfig": super::daemon_json::info(), - "KiriAgentMemory": engine.agent_rss().unwrap_or(0), - "KiriVmAwake": engine.is_awake(), - "KiriVmUplink": engine.uplink_info(), - "KiriStopped": engine.is_stopped(), - "KiriMemoryCeiling": engine.memory().0, - "KiriMemoryTarget": engine.memory().1, - "KiriMemoryUsed": engine.memory_used(), - "KiriMemoryStall": engine.memory_trouble().0, - "KiriOomKills": engine.memory_trouble().1, - "KiriCpuPercent": engine.cpu_percent(), - "KiriStorageReadOnly": engine.storage_readonly(), - "KiriStorageZfs": engine.storage_zfs(), - "Warnings": engine.records_damage().into_iter().chain(engine.image_damage()).chain(engine.host_warnings()).collect::>(), - }) + IndexServerAddress: "https://index.docker.io/v1/", + RegistryConfig: super::daemon_json::info(), + KiriAgentMemory: engine.agent_rss().unwrap_or(0), + KiriVmAwake: engine.is_awake(), + KiriVmUplink: engine.uplink_info(), + KiriStopped: engine.is_stopped(), + KiriMemoryCeiling: mem_ceiling, + KiriMemoryTarget: mem_target, + KiriMemoryUsed: engine.memory_used(), + KiriMemoryStall: mem_stall, + KiriOomKills: oom_kills, + KiriCpuPercent: engine.cpu_percent(), + KiriStorageReadOnly: engine.storage_readonly(), + KiriStorageZfs: engine.storage_zfs(), + Warnings: engine.records_damage().into_iter().chain(engine.image_damage()).chain(engine.host_warnings()).collect(), + }; + serde_json::to_vec(&summary).map_err(|e| Error::Io(io::Error::other(e))) } pub(super) fn filters(req: &Request, known: &[&str]) -> Result { @@ -675,11 +781,58 @@ fn merge_labels(image_cfg: &Value, body_labels: &Value) -> Value { } } +/// Serializes `Option` as a 0- or 1-element JSON array without allocating a `Vec`. +struct OptSeq(Option); + +impl serde::Serialize for OptSeq { + fn serialize(&self, serializer: S) -> Result { + use serde::ser::SerializeSeq; + match &self.0 { + Some(v) => { + let mut seq = serializer.serialize_seq(Some(1))?; + seq.serialize_element(v)?; + seq.end() + } + None => serializer.serialize_seq(Some(0))?.end(), + } + } +} + +#[derive(serde::Serialize)] +#[allow(non_snake_case)] +struct ImageSummary<'a> { + Id: &'a str, + #[serde(skip_serializing_if = "str::is_empty")] + ParentId: &'static str, + RepoTags: OptSeq<&'a str>, + RepoDigests: OptSeq>, + Created: i64, + Size: u64, + #[serde(skip_serializing_if = "Option::is_none")] + SharedSize: Option, + #[serde(skip_serializing_if = "Option::is_none")] + VirtualSize: Option, + #[serde(skip_serializing_if = "Value::is_null")] + Labels: &'a Value, + #[serde(skip_serializing_if = "Option::is_none")] + Containers: Option, + // Not Docker's: when this image arrived here, for the window. + #[serde(skip_serializing_if = "is_zero_u64")] + Pulled: u64, +} + +#[cfg(test)] fn images(req: &Request, engine: &Engine) -> Result { + let bytes = images_json_bytes(req, engine)?; + serde_json::from_slice(&bytes).map_err(|e| Error::Io(io::Error::other(e))) +} + +fn images_json_bytes(req: &Request, engine: &Engine) -> Result, Error> { let f = filters(req, &["reference", "dangling", "label", "label!", "before", "since", "until"])?; - let mut list = engine.store.images()?; - // Newest first, as Docker lists them (#364). - list.sort_by_key(|i| std::cmp::Reverse(time::parse_unix(&i.created))); + let list = engine.store.images_arc()?; + // Newest first, as Docker lists them (#364). Parse each timestamp once and sort indices. + let mut order: Vec<(i64, usize)> = list.iter().enumerate().map(|(idx, i)| (time::parse_unix(&i.created), idx)).collect(); + order.sort_by_key(|&(t, _)| std::cmp::Reverse(t)); let now = std::time::SystemTime::now(); let created = |i: &kiri_image::Image| time::docker_timestamp(&i.created, now); // Docker's rules (moby daemon/images/image_list.go): `dangling` is a @@ -706,51 +859,61 @@ fn images(req: &Request, engine: &Engine) -> Result { before = Some(before.map_or(t, |b| b.min(t))); } let labels = engine.image_labels(&list); - Ok(Value::Array( - list.iter() - .zip(labels) - .filter_map(|(i, labels)| { - // Kiri keeps an untagged image under its ID. - let untagged = i.name.starts_with("sha256:") && !list.iter().any(|o| o.config_digest == i.config_digest && !o.name.starts_with("sha256:")); - if i.name.starts_with("sha256:") && !untagged { - return None; - } - if dangling.is_some_and(|d| d != untagged) { - return None; - } - if (untagged && f.values("reference").is_some()) || (!untagged && !f.any("reference", |p| reference_matches(p, &i.name))) { - return None; - } - if !f.labels(&labels) { - return None; - } + let need_ts = before.is_some() || since.is_some(); + let legacy_none = req.api_version.is_some_and(|v| v < (1, 43)); + let tagged_configs: Option> = list + .iter() + .any(|i| i.name.starts_with("sha256:")) + .then(|| list.iter().filter(|o| !o.name.starts_with("sha256:")).map(|o| o.config_digest.as_str()).collect()); + let rows: Vec> = order + .into_iter() + .filter_map(|(created_unix, idx)| { + let i = &list[idx]; + let labels = &labels[idx]; + // Kiri keeps an untagged image under its ID. + let is_sha = i.name.starts_with("sha256:"); + let untagged = is_sha && !tagged_configs.as_ref().is_some_and(|s| s.contains(i.config_digest.as_str())); + if is_sha && !untagged { + return None; + } + if dangling.is_some_and(|d| d != untagged) { + return None; + } + if (untagged && f.values("reference").is_some()) || (!untagged && !f.any("reference", |p| reference_matches(p, &i.name))) { + return None; + } + if !f.labels(labels) { + return None; + } + if need_ts { let t = created(i); if before.is_some_and(|b| !t.is_some_and(|t| t < b)) || since.is_some_and(|s| !t.is_some_and(|t| t > s)) { return None; } - // Untagged: no names; before API 1.43 Docker wrote `` ones. - let (tags, digests) = match (untagged, req.api_version.is_some_and(|v| v < (1, 43))) { - (false, _) => (json!([i.name]), json!(i.repo_digest().into_iter().collect::>())), - (true, false) => (json!([]), json!([])), - (true, true) => (json!([":"]), json!(["@"])), - }; - Some(json!({ - "Id": i.config_digest, - "ParentId": "", - "RepoTags": tags, - "RepoDigests": digests, - "Created": time::parse_unix(&i.created), - "Size": i.size, - "SharedSize": -1, - "VirtualSize": i.size, - "Labels": labels, - "Containers": -1, - // Not Docker's: when this image arrived here, for the window. - "Pulled": i.pulled_at, - })) + } + // Untagged: no names; before API 1.43 Docker wrote `` ones. + let (tags, digests) = match (untagged, legacy_none) { + (false, _) => (OptSeq(Some(i.name.as_str())), OptSeq(i.repo_digest().map(std::borrow::Cow::Owned))), + (true, false) => (OptSeq(None), OptSeq(None)), + (true, true) => (OptSeq(Some(":")), OptSeq(Some(std::borrow::Cow::Borrowed("@")))), + }; + let legacy_virtual_size = req.api_version.is_some_and(|v| v < (1, 44)); + Some(ImageSummary { + Id: &i.config_digest, + ParentId: "", + RepoTags: tags, + RepoDigests: digests, + Created: created_unix, + Size: i.size, + SharedSize: None, + VirtualSize: legacy_virtual_size.then_some(i.size), + Labels: labels, + Containers: None, + Pulled: i.pulled_at, }) - .collect(), - )) + }) + .collect(); + serde_json::to_vec(&rows).map_err(|e| Error::Io(io::Error::other(e))) } /// The image list's `dangling` filter as Docker's `GetBoolOrDefault` reads @@ -1307,11 +1470,7 @@ fn save_resources( } else if let Some(prev) = existing_shared_nat { out["shared_nat"] = json!(prev); } - if let Some(dir) = path.parent() { - std::fs::create_dir_all(dir).map_err(Error::Io)?; - } - let tmp = path.with_extension("json.tmp"); - std::fs::write(&tmp, out.to_string()).and_then(|()| std::fs::rename(&tmp, path)).map_err(Error::Io) + super::write_atomic_mode(path, out.to_string().as_bytes(), 0o600).map_err(Error::Io) } fn set_ports(req: &Request, engine: &Engine, id: &str) -> Result { @@ -1921,23 +2080,40 @@ fn resolve_mac_deepest(raw_src: &str, clean: &str) -> Result { } } -/// A bind source that is the Mac's, as the path the Mac really keeps it at; -/// `Ok(None)` for one that is the VM's own, or `Err(BadRequest)` if a path in -/// `MAC_SHARES` traverses a symlink escaping `MAC_SHARES`. -/// -/// Links are followed here, on the Mac, as Docker follows a bind source's: -/// the guest sees the Mac under /mnt/mac, where a link to an absolute path -/// (/private/etc/localtime, a project folder linked from elsewhere) leads -/// nowhere. -/// -/// /etc is the Mac's link to /private/etc, and Compose files written for a -/// Linux host mount paths in it: -/// - /etc/passwd, /etc/os-release and the others in `hostetc::FILES` are -/// expected to be Linux's, so they are the ones Kiri keeps; and /etc -/// itself is the folder of them. -/// - anything else the Mac has there (/etc/hosts, /etc/localtime) is the -/// Mac's. -/// - what the Mac lacks stays the VM's. +/// Whether `src` names one of the synthetic macOS `/etc` paths backed by +/// `~/.kiri/etc` (`hostetc`), either via `/etc` or directly via `~/.kiri/etc`. +fn is_mac_hostetc(src: &str) -> bool { + let etc_dir = super::state_dir().ok().map(|s| s.join("etc")); + is_mac_hostetc_with(src, etc_dir.as_deref()) +} + +fn is_mac_hostetc_with(src: &str, etc_dir: Option<&std::path::Path>) -> bool { + if !cfg!(target_os = "macos") { + return false; + } + let norm = lexical_path(src); + if norm == "/etc" || norm.strip_prefix("/etc/").is_some_and(|name| super::hostetc::FILES.contains(&name)) { + return true; + } + if let Some(etc_dir) = etc_dir { + let etc_str = etc_dir.to_string_lossy(); + let etc_lex = lexical_path(&etc_str); + let etc_canon = canonical_or_ancestor(&etc_str); + let matches_etc = |p: &str| { + p == etc_lex + || p.strip_prefix(&etc_lex).is_some_and(|r| r.starts_with('/')) + || etc_canon.as_deref().is_some_and(|c| p == c || p.strip_prefix(c).is_some_and(|r| r.starts_with('/'))) + }; + if matches_etc(&norm) + || canonical_or_ancestor(src).as_deref().is_some_and(matches_etc) + || canonical_or_ancestor(&norm).as_deref().is_some_and(matches_etc) + { + return true; + } + } + false +} + fn mac_source(src: &str) -> Result, Error> { let clean = lexical_path(src); if mac_shared(&clean) { @@ -1979,6 +2155,22 @@ fn guest_bind_source(src: &str) -> Result { Ok(mac_source(src)?.map_or_else(|| src.to_owned(), |real| format!("{MAC_ROOT}{real}"))) } +/// The mount words of a guest line's tail (`dst\tflags[\t…]`) with `ro` among them. +fn ensure_ro_in_rest(rest: &str) -> String { + let Some((dst, tail)) = rest.split_once('\t') else { + return rest.to_owned(); + }; + let (flags, after) = tail.split_once('\t').map_or((tail, None), |(f, a)| (f, Some(a))); + let mut parts: Vec<&str> = flags.split(',').filter(|x| !x.is_empty()).collect(); + if !parts.contains(&"ro") { + parts.push("ro"); + } + match after { + Some(a) => format!("{dst}\t{}\t{a}", parts.join(",")), + None => format!("{dst}\t{}", parts.join(",")), + } +} + #[cfg(test)] fn fresh_bind_sources(guest: &[String], info: &[Value]) -> Vec { fresh_bind_sources_with(guest, info, super::binds::engine_socket, cfg!(target_os = "macos")) @@ -2022,8 +2214,46 @@ fn fresh_bind_sources_with(guest: &[String], info: &[Value], engine_socket: impl /// and `docker cp` time, refusing stale pre-fix `/mnt/mac` shares, symlink /// escapes, tab-smuggled `Destination` fields, and disallowed volume drivers, /// while refreshing Mac bind symlinks and Linux/WSL socket paths. -pub(super) fn revalidate_and_refresh_mounts(engine: &Engine, guest: &[String], info: &[Value]) -> Result, Error> { - revalidate_mounts_for(engine, guest, info, super::binds::engine_socket, cfg!(target_os = "macos")) +pub(super) fn revalidate_and_refresh_mounts(engine: &Engine, guest: &[String], info: &[Value], non_host: bool) -> Result, Error> { + let fresh = revalidate_mounts_for(engine, guest, info, super::binds::engine_socket, cfg!(target_os = "macos"))?; + if !cfg!(target_os = "macos") { + return Ok(fresh); + } + confine_mac_binds(fresh, info, non_host, is_mac_hostetc, is_host_socket_ancestor) +} + +/// The checks a Mac bind's freshly followed path still needs after +/// `revalidate_mounts_for` (one line out per line in): a link re-pointed +/// since create at Kiri's synthetic `/etc` mounts read-only, and one +/// re-pointed at a folder holding Kiri's host socket is refused for a +/// container a non-Host caller made. +fn confine_mac_binds( + fresh: Vec, + info: &[Value], + non_host: bool, + hostetc: impl Fn(&str) -> bool, + socket_ancestor: impl Fn(&str) -> bool, +) -> Result, Error> { + if fresh.len() != info.len() { + // Unpaired: revalidation lets no Mac share through. + return Ok(fresh); + } + fresh + .into_iter() + .zip(info) + .map(|(line, m)| { + let (Some("bind"), Some(src)) = (m["Type"].as_str(), m["Source"].as_str()) else { return Ok(line) }; + let Some((resolved, rest)) = line.split_once('\t') else { return Ok(line) }; + let Some(resolved_host) = resolved.strip_prefix(MAC_ROOT).filter(|p| p.starts_with('/')) else { return Ok(line) }; + if non_host && (socket_ancestor(src) || socket_ancestor(resolved_host)) { + return Err(Error::BadRequest(format!("invalid mount source {src}: cannot mount a directory containing Kiri's host socket"))); + } + if hostetc(src) || hostetc(resolved_host) { + return Ok(format!("{resolved}\t{}", ensure_ro_in_rest(rest))); + } + Ok(line) + }) + .collect() } fn revalidate_mounts_for( @@ -2451,18 +2681,116 @@ fn volume_bind_source(device: &str, wsl: Option<&super::binds::Wsl>, wsl_distro: } } +/// Canonicalizes `p` if it exists, or canonicalizes its deepest existing ancestor +/// (following dangling symlinks up to 40 hops) and re-appends the remaining tail +/// components so symlinked parents (such as `/var/run/kiri -> /run/kiri` or +/// `/tmp/evil/nonexistent/..`) are resolved even when the leaf does not exist +/// or ends in `..`. +fn canonical_or_ancestor(p: &str) -> Option { + if let Ok(canon) = std::fs::canonicalize(p) { + return canon.into_os_string().into_string().ok().map(|s| lexical_path(&s)); + } + let walk = |start: &std::path::Path| -> Option { + let mut cur = start.to_path_buf(); + let mut tail: Vec = Vec::new(); + let mut hops = 0usize; + loop { + if let Ok(canon) = std::fs::canonicalize(&cur) { + let mut full = canon; + for seg in tail.into_iter().rev() { + full.push(seg); + } + return full.into_os_string().into_string().ok().map(|s| lexical_path(&s)); + } + if hops < 40 + && let Ok(target) = std::fs::read_link(&cur) + { + hops += 1; + let next = if target.is_absolute() { + target + } else { + cur.parent().map_or(target.clone(), |p| p.join(&target)) + }; + cur = next; + continue; + } + let name = cur.file_name()?.to_os_string(); + tail.push(name); + cur = cur.parent()?.to_path_buf(); + } + }; + walk(std::path::Path::new(p)).or_else(|| { + let norm = lexical_path(p); + walk(std::path::Path::new(&norm)) + }) +} + +/// Whether `src` (lexically or after resolving symlinks) is `/` or a directory +/// holding Kiri's own host Unix socket (such as `~/.kiri/run`), which would let +/// a non-Host caller reach the host-privileged socket without going through +/// `engine_socket_for_distro`. +fn is_host_socket_ancestor(src: &str) -> bool { + let socks: Vec = [super::socket_path(), super::home_socket_path()] + .into_iter() + .filter_map(|p| p.ok().and_then(|p| p.to_str().map(str::to_owned))) + .collect(); + is_host_socket_ancestor_against(src, &socks) +} + +fn is_host_socket_ancestor_against(src: &str, socket_candidates: &[String]) -> bool { + let norm = lexical_path(src); + let mut src_forms = vec![norm.clone()]; + for candidate in [canonical_or_ancestor(src), canonical_or_ancestor(&norm)].into_iter().flatten() { + if !src_forms.contains(&candidate) { + src_forms.push(candidate); + } + } + let parent_of = |sock: &str| -> Option { + let (parent, _) = sock.rsplit_once('/')?; + Some(if parent.is_empty() { "/".to_owned() } else { parent.to_owned() }) + }; + socket_candidates.iter().any(|sock| { + let mut parents = Vec::new(); + if let Some(p) = parent_of(&lexical_path(sock)) { + parents.push(p); + } + if let Some(canon_sock) = canonical_or_ancestor(sock) + && let Some(p) = parent_of(&canon_sock) + && !parents.contains(&p) + { + parents.push(p); + } + src_forms.iter().any(|sp| { + parents + .iter() + .any(|parent| sp == "/" || sp == parent || parent.strip_prefix(sp.as_str()).is_some_and(|r| r.starts_with('/'))) + }) + }) +} + fn validate_volume_options( options: &std::collections::BTreeMap, wsl: Option<&super::binds::Wsl>, wsl_distro: Option<&str>, + caller: &super::caller::Caller, ) -> Result<(), Error> { let (flags, _) = super::volumes::mount_options(options.get("o").map_or("", String::as_str)); - if flags & 4096 != 0 && (wsl.is_some() || wsl_distro.is_some()) { + if flags & 4096 != 0 { let device = options.get("device").map_or("", String::as_str); - let translated = volume_bind_source(device, wsl, wsl_distro)?; - let mut checked = options.clone(); - checked.insert("device".into(), translated); - return check_volume_device(&checked); + let translated = if wsl.is_some() || wsl_distro.is_some() { volume_bind_source(device, wsl, wsl_distro)? } else { device.to_owned() }; + if *caller != super::caller::Caller::Host + && super::binds::engine_socket_for_distro(&translated, wsl_distro).is_none() + && is_host_socket_ancestor(&translated) + { + return Err(Error::BadRequest(format!( + "invalid volume option device={device}: cannot mount a directory containing Kiri's host socket" + ))); + } + if wsl.is_some() || wsl_distro.is_some() { + let mut checked = options.clone(); + checked.insert("device".into(), translated); + return check_volume_device(&checked); + } } check_volume_device(options) } @@ -2662,19 +2990,35 @@ fn mounts_for(body: &Value, engine: &Engine, image: &kiri_image::Image, caller: if !src.starts_with('/') { return Err(Error::BadRequest(format!("invalid mount source {src}: must be an absolute path"))); } + if *caller != super::caller::Caller::Host && is_host_socket_ancestor(src) { + return Err(Error::BadRequest(format!( + "invalid mount source {src}: cannot mount a directory containing Kiri's host socket" + ))); + } + // Synthetic macOS `/etc` files live in shared `~/.kiri/etc`: always + // mount read-only so a container cannot plant symlinks or poison + // shared `/etc` entries for other containers. + let bind_ro = ro || is_mac_hostetc(src); + let bind_flag = |more: &str| { + let mut f: Vec<&str> = more.split(',').filter(|x| !x.is_empty()).collect(); + if bind_ro { + f.push("ro"); + } + f.join(",") + }; // Where the source is on this machine: itself, or on a Mac // the path it leads to (a file Kiri keeps for /etc/passwd). let here = if cfg!(target_os = "macos") { mac_source(src)? } else { Some(src.to_owned()) }; let Some(here) = here else { // The guest makes a missing source itself, as Docker does on Linux. - out.guest.push(format!("{src}\t{dst}\t{}", flag(if create_missing { "create" } else { "" }))); - out.info.push(json!({"Type": "bind", "Source": src, "Destination": dst, "Mode": "", "RW": !ro, "Propagation": "rprivate"})); + out.guest.push(format!("{src}\t{dst}\t{}", bind_flag(if create_missing { "create" } else { "" }))); + out.info.push(json!({"Type": "bind", "Source": src, "Destination": dst, "Mode": "", "RW": !bind_ro, "Propagation": "rprivate"})); return Ok(()); }; prepare_bind_source(src, &here, create_missing)?; // After a missing source was made, so its links are followed too. - out.guest.push(format!("{}\t{dst}\t{}", guest_bind_source(src)?, flag(""))); - out.info.push(json!({"Type": "bind", "Source": src, "Destination": dst, "Mode": "", "RW": !ro, "Propagation": "rprivate"})); + out.guest.push(format!("{}\t{dst}\t{}", guest_bind_source(src)?, bind_flag(""))); + out.info.push(json!({"Type": "bind", "Source": src, "Destination": dst, "Mode": "", "RW": !bind_ro, "Propagation": "rprivate"})); } "volume" => { let (name, anonymous) = if src.is_empty() { (super::engine::random_hex(32), true) } else { (src.to_owned(), false) }; @@ -2688,26 +3032,42 @@ fn mounts_for(body: &Value, engine: &Engine, image: &kiri_image::Image, caller: // must not be reachable this way either: not as a virtiofs // tag, and not as a bind of /mnt/mac. let vol_distro = v.wsl_distro.as_deref().or(wsl_distro); - validate_volume_options(&v.options, super::binds::wsl(), vol_distro)?; + validate_volume_options(&v.options, super::binds::wsl(), vol_distro, caller)?; let (opt_flags, _) = super::volumes::mount_options(v.options.get("o").map_or("", String::as_str)); + let mut force_ro = false; let bind_guest_dev = if opt_flags & 4096 != 0 { let raw_dev = v.options.get("device").map_or("", String::as_str); let translated = volume_bind_source(raw_dev, super::binds::wsl(), vol_distro)?; + force_ro = is_mac_hostetc(&translated); Some(guest_bind_source(&translated)?) } else { None }; + let vol_ro = ro || force_ro; + let vol_flag = |more: &str| { + let mut f: Vec<&str> = more.split(',').filter(|x| !x.is_empty()).collect(); + if vol_ro { + f.push("ro"); + } + f.join(",") + }; + // Shared hostetc files stay read-only in the volume mount too. + let mut guest_opts = v.options.clone(); + if force_ro { + let o = guest_opts.get("o").map_or_else(|| "ro".to_owned(), |o| format!("{o},ro")); + guest_opts.insert("o".into(), o); + } let path = super::volumes::guest_path(&name); let copy = if extra.contains("nocopy") { "create" } else { "create,copyup" }; // A volume with driver options (`type=nfs`, `o=bind` …) is // mounted at its path by the guest at start, then bound in. let vol = super::volumes::guest_mount_fields( - &v.options, + &guest_opts, |_| bind_guest_dev.clone().unwrap_or_default(), resolve_server, ); - out.guest.push(format!("{path}\t{dst}\t{}{vol}", flag(copy))); - out.info.push(json!({"Type": "volume", "Name": name, "Source": path, "Destination": dst, "Driver": "local", "Mode": "z", "RW": !ro, "Propagation": ""})); + out.guest.push(format!("{path}\t{dst}\t{}{vol}", vol_flag(copy))); + out.info.push(json!({"Type": "volume", "Name": name, "Source": path, "Destination": dst, "Driver": "local", "Mode": "z", "RW": !vol_ro, "Propagation": ""})); if anonymous { out.anon.push(name); } else { @@ -2776,7 +3136,7 @@ fn mounts_for(body: &Value, engine: &Engine, image: &kiri_image::Image, caller: d => return Err(Error::BadRequest(format!("Kiri supports only local volumes, not {d}"))), } let options = super::volumes::local_options(&driver_opts["Options"]).map_err(Error::BadRequest)?; - validate_volume_options(&options, wsl, wsl_distro)?; + validate_volume_options(&options, wsl, wsl_distro, caller)?; engine.volume_ensure_with_distro(src, m["VolumeOptions"]["Labels"].clone(), options, wsl_distro.map(str::to_owned))?; } add(kind, src, dst, ro, &extra, false, &mut out)?; @@ -2906,15 +3266,19 @@ fn inspect_mounts(spec: &Spec, is_anon_volume: impl Fn(&str) -> bool) -> Value { } fn volume_json(v: &super::volumes::Volume) -> Value { - json!({ - "Name": v.name, - "Driver": "local", - "Mountpoint": super::volumes::guest_path(&v.name), - "CreatedAt": time::rfc3339(std::time::UNIX_EPOCH + Duration::from_nanos(v.created_ns)), - "Labels": if v.labels.is_object() { v.labels.clone() } else { json!({}) }, - "Scope": "local", - "Options": v.options, - }) + let mut m = serde_json::Map::with_capacity(7); + m.insert("Name".into(), v.name.clone().into()); + m.insert("Driver".into(), "local".into()); + m.insert("Mountpoint".into(), super::volumes::guest_path(&v.name).into()); + m.insert("CreatedAt".into(), time::rfc3339(std::time::UNIX_EPOCH + Duration::from_nanos(v.created_ns)).into()); + if v.labels.as_object().is_some_and(|o| !o.is_empty()) { + m.insert("Labels".into(), v.labels.clone()); + } + m.insert("Scope".into(), "local".into()); + if !v.options.is_empty() { + m.insert("Options".into(), serde_json::to_value(&v.options).unwrap_or(Value::Null)); + } + Value::Object(m) } fn volume_create(req: &Request, engine: &Engine, caller: &super::caller::Caller) -> Result { @@ -2929,7 +3293,7 @@ fn volume_create(req: &Request, engine: &Engine, caller: &super::caller::Caller) }; let options = super::volumes::local_options(&body["DriverOpts"]).map_err(Error::BadRequest)?; let wsl_distro = caller.wsl_distro(); - validate_volume_options(&options, super::binds::wsl(), wsl_distro)?; + validate_volume_options(&options, super::binds::wsl(), wsl_distro, caller)?; let v = engine.volume_ensure_with_distro(&name, body["Labels"].clone(), options, wsl_distro.map(str::to_owned))?; Ok(volume_json(&v)) } @@ -2980,7 +3344,7 @@ fn volumes(req: &Request, engine: &Engine) -> Result { }) .map(volume_json) .collect(); - Ok(json!({"Volumes": list, "Warnings": []})) + Ok(json!({"Volumes": list})) } /// The image's and create request's ExposedPorts keys; a bare port means TCP. @@ -2998,17 +3362,6 @@ fn exposed_ports(body: &Value, image_cfg: &Value) -> Vec { ports } -/// What is published right now: Docker's `Ports` list for `ps`. -fn ports_list(c: &Container) -> Value { - let Some(fw) = &c.forwards else { return json!([]) }; - Value::Array( - fw.bound - .iter() - .map(|(b, ip, port)| json!({"IP": ip, "PrivatePort": b.container_port, "PublicPort": port, "Type": b.proto})) - .collect(), - ) -} - /// What `-p` asked for, as Docker's inspect keeps it in HostConfig: the /// container port and protocol, each with the host address and port given /// (an empty HostPort for "any free port"). Empty, not null, with none. @@ -3626,6 +3979,7 @@ fn create_inner(req: &Request, engine: &Engine, caller: &Caller, record_wsl_dist volumes_from: strings(&host["VolumesFrom"]).unwrap_or_default(), pid_mode, wsl_distro: record_wsl_distro, + non_host_creator: *caller != Caller::Host, mounts: mounts.guest, mount_info: mounts.info, mount_request: mount_request(&body, &image_cfg), @@ -3856,7 +4210,7 @@ fn container_inspect(engine: &Engine, key: &str) -> Result { let health = engine.health(&id); let anon_vols: Vec = engine.volume_list().into_iter().filter(|v| v.anonymous).map(|v| v.name).collect(); engine.with(&id, |c| { - let net = engine.lock_net(); + let net = engine.read_net(); let networks = net.all(); let mut v = inspect(c, networks, &anon_vols); v["NetworkSettings"]["Networks"] = endpoints(c, networks); @@ -3908,7 +4262,177 @@ fn spec_wsl_distro(spec: &super::engine::Spec) -> Option { None } +struct SlashName<'a>(&'a str); + +impl serde::Serialize for SlashName<'_> { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_str(&format_args!("/{}", self.0)) + } +} + +#[derive(serde::Serialize)] +#[allow(non_snake_case)] +struct PortSummary<'a> { + IP: &'a str, + PrivatePort: u16, + PublicPort: u16, + Type: &'a str, +} + +#[derive(serde::Serialize)] +#[allow(non_snake_case)] +struct IpamConfigSummary<'a> { + #[serde(skip_serializing_if = "str::is_empty")] + IPv4Address: &'a str, + #[serde(skip_serializing_if = "str::is_empty")] + IPv6Address: &'a str, +} + +#[derive(serde::Serialize)] +#[allow(non_snake_case)] +struct EndpointSummary<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + IPAMConfig: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + Links: Option<()>, + #[serde(skip_serializing_if = "Option::is_none")] + Aliases: Option<&'a [String]>, + #[serde(skip_serializing_if = "str::is_empty")] + MacAddress: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + DriverOpts: Option<()>, + #[serde(skip_serializing_if = "str::is_empty")] + NetworkID: &'a str, + #[serde(skip_serializing_if = "str::is_empty")] + EndpointID: &'a str, + #[serde(skip_serializing_if = "String::is_empty")] + Gateway: String, + #[serde(skip_serializing_if = "String::is_empty")] + IPAddress: String, + #[serde(skip_serializing_if = "is_zero_u8")] + IPPrefixLen: u8, + #[serde(skip_serializing_if = "String::is_empty")] + IPv6Gateway: String, + #[serde(skip_serializing_if = "String::is_empty")] + GlobalIPv6Address: String, + #[serde(skip_serializing_if = "is_zero_u8")] + GlobalIPv6PrefixLen: u8, + #[serde(skip_serializing_if = "Option::is_none")] + DNSNames: Option<()>, +} + +#[derive(serde::Serialize)] +#[allow(non_snake_case)] +struct HostConfigSummary<'a> { + NetworkMode: &'a str, +} + +#[derive(serde::Serialize)] +#[allow(non_snake_case)] +struct NetworkSettingsSummary<'a> { + Networks: std::collections::BTreeMap<&'a str, EndpointSummary<'a>>, +} + +#[derive(serde::Serialize)] +#[allow(non_snake_case)] +struct ContainerSummary<'a> { + Id: &'a str, + Names: [SlashName<'a>; 1], + Image: &'a str, + ImageID: &'a str, + Command: String, + Created: i64, + State: &'static str, + Status: String, + #[serde(skip_serializing_if = "Option::is_none")] + KiriStartedAt: Option, + #[serde(skip_serializing_if = "Option::is_none")] + KiriFinishedAt: Option, + #[serde(skip_serializing_if = "is_zero_i32")] + KiriExitCode: i32, + #[serde(skip_serializing_if = "is_false")] + KiriOOMKilled: bool, + #[serde(skip_serializing_if = "is_false")] + KiriVmStopped: bool, + #[serde(skip_serializing_if = "is_false")] + KiriStoppedByUser: bool, + Ports: Vec>, + Labels: &'a Value, + HostConfig: HostConfigSummary<'a>, + NetworkSettings: NetworkSettingsSummary<'a>, + #[serde(skip_serializing_if = "is_empty_values")] + Mounts: &'a [Value], + #[serde(skip_serializing_if = "Option::is_none")] + KiriWslDistro: Option, +} + +fn endpoints_typed<'a>(c: &'a Container, networks: &'a [super::network::Network]) -> std::collections::BTreeMap<&'a str, EndpointSummary<'a>> { + let mut out = std::collections::BTreeMap::new(); + if c.spec.network_mode.starts_with("container:") || c.spec.left_all_networks { + return out; + } + let running = c.status == Status::Running; + let mut add = |name: &'a str, ip: Option<[u8; 4]>, ip6: Option<[u8; 16]>, aliases: &'a [String], want4: &'a str, want6: &'a str| { + let net = networks.iter().find(|n| n.name == name || n.id == name); + let ip = ip.filter(|_| running && !net.is_some_and(|n| n.no_ipv4)); + let ip6 = ip6.filter(|_| running); + let gateway = match (ip, net) { + (Some(_), Some(n)) if n.gateway != [0; 4] => super::network::ip_str(n.gateway), + _ => String::new(), + }; + let v6 = net.and_then(|n| n.v6.as_ref()).filter(|_| ip6.is_some()); + let ipam = (!want4.is_empty() || !want6.is_empty()).then_some(IpamConfigSummary { + IPv4Address: want4, + IPv6Address: want6, + }); + out.insert( + name, + EndpointSummary { + IPAMConfig: ipam, + Links: None, + Aliases: (!aliases.is_empty()).then_some(aliases), + MacAddress: "", + DriverOpts: None, + NetworkID: net.map_or("", |n| n.id.as_str()), + EndpointID: if running { c.id.as_str() } else { "" }, + Gateway: gateway, + IPAddress: ip.map(super::network::ip_str).unwrap_or_default(), + IPPrefixLen: if ip.is_some() { net.map_or(16, |n| n.prefix) } else { 0 }, + IPv6Gateway: v6.map(|v| super::network::ip6_str(v.gateway)).unwrap_or_default(), + GlobalIPv6Address: ip6.map(super::network::ip6_str).unwrap_or_default(), + GlobalIPv6PrefixLen: v6.map_or(0, |v| v.prefix), + DNSNames: None, + }, + ); + }; + add(&c.spec.network_mode, c.ip, c.ip6, &c.spec.aliases, &c.spec.ipv4_address, &c.spec.ipv6_address); + for x in &c.spec.extra_networks { + let ip6 = c.extra_ip6s.iter().find(|(n, _)| *n == x.name).map(|(_, ip)| *ip); + add(&x.name, c.extra_ips.iter().find(|(n, _)| *n == x.name).map(|(_, ip)| *ip), ip6, &x.aliases, &x.ipv4_address, &x.ipv6_address); + } + out +} + +fn ports_list_typed(c: &Container) -> Vec> { + let Some(fw) = &c.forwards else { return Vec::new() }; + fw.bound + .iter() + .map(|(b, ip, port)| PortSummary { + IP: ip.as_str(), + PrivatePort: b.container_port, + PublicPort: *port, + Type: b.proto.as_str(), + }) + .collect() +} + +#[cfg(test)] fn list(req: &Request, engine: &Engine) -> Result { + let bytes = list_json_bytes(req, engine)?; + serde_json::from_slice(&bytes).map_err(|e| Error::Io(io::Error::other(e))) +} + +fn list_json_bytes(req: &Request, engine: &Engine) -> Result, Error> { let f = filters(req, &["id", "name", "label", "label!", "status", "ancestor", "network", "exited", "volume", "health"])?; if let Some(bad) = f.values("health").and_then(|v| v.iter().find(|v| !super::health::valid_filter(v))) { return Err(Error::BadRequest(format!("Unrecognised filter value for health: {bad}"))); @@ -3930,65 +4454,71 @@ fn list(req: &Request, engine: &Engine) -> Result { || limit.is_some() || f.values("status").is_some() || f.values("exited").is_some(); - let mut rows = engine.each_with_networks(|c, networks| { - if !all && c.status != Status::Running { - return None; - } - let labels = if c.spec.labels.is_object() { c.spec.labels.clone() } else { json!({}) }; - let first = (!c.spec.left_all_networks) - .then(|| networks.iter().find(|n| n.name == c.spec.network_mode || n.id == c.spec.network_mode || (c.spec.network_mode == "default" && n.name == "bridge"))) - .flatten(); - let keep = f.any("id", |v| c.id.starts_with(v)) - && f.name(&c.name) - && f.labels(&labels) - && f.any("status", |v| v == state_word(c)) - && f.any("exited", |v| c.status == Status::Exited && v.parse() == Ok(c.exit_code)) - && ancestors.as_ref().is_none_or(|ids| ids.contains(&c.spec.image_id)) - && f.any("network", |v| { - first.is_some_and(|n| n.name == v || n.id.starts_with(v)) - || c.spec.extra_networks.iter().any(|x| networks.iter().find(|n| n.name == x.name).is_some_and(|n| n.name == v || n.id.starts_with(v))) + let empty_obj = Value::Object(serde_json::Map::new()); + let has_net_filter = f.values("network").is_some(); + engine.with_containers_and_networks(|containers, networks| { + let mut matched: Vec<&Container> = containers + .iter() + .copied() + .filter(|c| { + if !all && c.status != Status::Running { + return false; + } + let labels_ref = if c.spec.labels.is_object() { &c.spec.labels } else { &empty_obj }; + f.any("id", |v| c.id.starts_with(v)) + && f.any("status", |v| v == state_word(c)) + && f.any("exited", |v| c.status == Status::Exited && v.parse() == Ok(c.exit_code)) + && f.labels(labels_ref) + && f.name(&c.name) + && ancestors.as_ref().is_none_or(|ids| ids.contains(&c.spec.image_id)) + && (!has_net_filter || { + let first = (!c.spec.left_all_networks) + .then(|| networks.iter().find(|n| n.name == c.spec.network_mode || n.id == c.spec.network_mode || (c.spec.network_mode == "default" && n.name == "bridge"))) + .flatten(); + f.any("network", |v| { + first.is_some_and(|n| n.name == v || n.id.starts_with(v)) + || c.spec.extra_networks.iter().any(|x| networks.iter().find(|n| n.name == x.name).is_some_and(|n| n.name == v || n.id.starts_with(v))) + }) + }) + && f.any("volume", |v| c.spec.volumes.iter().chain(&c.spec.anon_volumes).any(|n| n == v) || c.spec.mount_info.iter().any(|m| m["Destination"] == v || m["Source"] == v)) + && f.any("health", |v| v == health.get(&c.id).map_or("none", |h| h.status.as_str())) }) - && f.any("volume", |v| c.spec.volumes.iter().chain(&c.spec.anon_volumes).any(|n| n == v) || c.spec.mount_info.iter().any(|m| m["Destination"] == v || m["Source"] == v)) - && f.any("health", |v| v == health.get(&c.id).map_or("none", |h| h.status.as_str())); - if !keep { - return None; - } - let mut row = json!({ - "Id": c.id, - "Names": [format!("/{}", c.name)], - "Image": c.spec.image, - "ImageID": c.spec.image_id, - "Command": c.argv().join(" "), - "Created": time::unix(c.created), - "State": state_word(c), - "Status": ps_status(c, health.get(&c.id)), - // Kiri's own: the window counts "Up 3 s" from these every second. - // Docker clients ignore fields they don't know. - "KiriStartedAt": c.started.map(time::unix), - "KiriFinishedAt": c.finished.map(time::unix), - "KiriExitCode": c.exit_code, - "KiriOOMKilled": c.oom_killed, - "KiriVmStopped": c.vm_stopped, - "KiriStoppedByUser": c.stopped_by_user, - "Ports": ports_list(c), - "Labels": if c.spec.labels.is_object() { c.spec.labels.clone() } else { json!({}) }, - "HostConfig": {"NetworkMode": c.spec.network_mode}, - "NetworkSettings": {"Networks": endpoints(c, networks)}, - "Mounts": c.spec.mount_info, - }); - if let Some(distro) = spec_wsl_distro(&c.spec) { - row["KiriWslDistro"] = json!(distro); + .collect(); + // Sort and truncate BEFORE building any JSON rows! + matched.sort_by(|a, b| b.created.cmp(&a.created).then_with(|| a.id.cmp(&b.id))); + if let Some(limit) = limit { + matched.truncate(limit); } - Some((c.created, row)) - }); - rows.sort_by(|a, b| { - b.0.cmp(&a.0) - .then_with(|| a.1["Id"].as_str().cmp(&b.1["Id"].as_str())) - }); - if let Some(limit) = limit { - rows.truncate(limit); - } - Ok(Value::Array(rows.into_iter().map(|(_, v)| v).collect())) + let rows: Vec> = matched + .into_iter() + .map(|c| { + let labels_ref = if c.spec.labels.is_object() { &c.spec.labels } else { &empty_obj }; + ContainerSummary { + Id: &c.id, + Names: [SlashName(&c.name)], + Image: &c.spec.image, + ImageID: &c.spec.image_id, + Command: c.argv().join(" "), + Created: time::unix(c.created), + State: state_word(c), + Status: ps_status(c, health.get(&c.id)), + KiriStartedAt: c.started.map(time::unix), + KiriFinishedAt: c.finished.map(time::unix), + KiriExitCode: c.exit_code, + KiriOOMKilled: c.oom_killed, + KiriVmStopped: c.vm_stopped, + KiriStoppedByUser: c.stopped_by_user, + Ports: ports_list_typed(c), + Labels: labels_ref, + HostConfig: HostConfigSummary { NetworkMode: &c.spec.network_mode }, + NetworkSettings: NetworkSettingsSummary { Networks: endpoints_typed(c, networks) }, + Mounts: &c.spec.mount_info, + KiriWslDistro: spec_wsl_distro(&c.spec), + } + }) + .collect(); + serde_json::to_vec(&rows).map_err(|e| Error::Io(io::Error::other(e))) + }) } fn inspect(c: &Container, nets: &[super::network::Network], anon_vols: &[String]) -> Value { @@ -4181,23 +4711,48 @@ fn network_json(engine: &Engine, n: &super::network::Network, with_members: bool } Value::Array(configs) }; - json!({ - "Name": n.name, - "Id": n.id, - "Created": time::rfc3339(std::time::UNIX_EPOCH + Duration::from_nanos(n.created_ns)), - "Scope": "local", - "Driver": n.driver, - "EnableIPv4": !n.no_ipv4, - "EnableIPv6": n.v6.is_some(), - "IPAM": {"Driver": "default", "Options": if n.ipam_options.is_object() { n.ipam_options.clone() } else { Value::Null }, "Config": ipam}, - "Internal": n.internal, - "Attachable": n.attachable, - "Ingress": false, - "ConfigOnly": false, - "Containers": containers, - "Options": super::network::shown_options(n), - "Labels": if n.labels.is_object() { n.labels.clone() } else { json!({}) }, - }) + let mut ipam_obj = serde_json::Map::with_capacity(3); + ipam_obj.insert("Driver".into(), "default".into()); + if n.ipam_options.is_object() { + ipam_obj.insert("Options".into(), n.ipam_options.clone()); + } else if with_members { + ipam_obj.insert("Options".into(), Value::Null); + } + ipam_obj.insert("Config".into(), ipam); + let mut obj = serde_json::Map::with_capacity(15); + obj.insert("Name".into(), n.name.clone().into()); + obj.insert("Id".into(), n.id.clone().into()); + obj.insert("Created".into(), time::rfc3339(std::time::UNIX_EPOCH + Duration::from_nanos(n.created_ns)).into()); + obj.insert("Scope".into(), "local".into()); + obj.insert("Driver".into(), n.driver.clone().into()); + obj.insert("EnableIPv4".into(), (!n.no_ipv4).into()); + if with_members || n.v6.is_some() { + obj.insert("EnableIPv6".into(), n.v6.is_some().into()); + } + obj.insert("IPAM".into(), Value::Object(ipam_obj)); + if with_members || n.internal { + obj.insert("Internal".into(), n.internal.into()); + } + if with_members || n.attachable { + obj.insert("Attachable".into(), n.attachable.into()); + } + if with_members { + obj.insert("Ingress".into(), false.into()); + obj.insert("ConfigOnly".into(), false.into()); + obj.insert("Containers".into(), Value::Object(containers)); + } else if !containers.is_empty() { + obj.insert("Containers".into(), Value::Object(containers)); + } + let opts = super::network::shown_options(n); + if with_members || opts.as_object().is_some_and(|m| !m.is_empty()) { + obj.insert("Options".into(), opts); + } + if n.labels.as_object().is_some_and(|m| !m.is_empty()) { + obj.insert("Labels".into(), n.labels.clone()); + } else if with_members { + obj.insert("Labels".into(), json!({})); + } + Value::Object(obj) } fn network_matches(f: &Filters, engine: &Engine, n: &super::network::Network) -> bool { @@ -4215,12 +4770,12 @@ const NETWORK_FILTERS: &[&str] = &["name", "id", "driver", "label", "label!", "s fn networks(req: &Request, engine: &Engine) -> Result { let f = filters(req, NETWORK_FILTERS)?; - let list: Vec = engine.lock_net().all().to_vec(); + let list: Vec = engine.read_net().all().to_vec(); Ok(Value::Array(list.iter().filter(|n| network_matches(&f, engine, n)).map(|n| network_json(engine, n, false)).collect())) } fn network_inspect(engine: &Engine, key: &str) -> Result { - let n = engine.lock_net().find(key).cloned().ok_or_else(|| Error::NotFound(format!("network {key} not found")))?; + let n = engine.read_net().find(key).cloned().ok_or_else(|| Error::NotFound(format!("network {key} not found")))?; Ok(network_json(engine, &n, true)) } @@ -4458,7 +5013,7 @@ fn exec_inspect(e: &super::engine::Exec) -> Value { } fn logs(req: &Request, engine: &Engine, id: &str, w: &mut UnixStream) -> io::Result { - use super::logfile::{Record, parse_tail, parse_time}; + use super::logfile::{parse_tail, parse_time}; let (want_out, want_err, stamps) = (req.flag("stdout"), req.flag("stderr"), req.flag("timestamps")); if !want_out && !want_err { error(w, Error::BadRequest("Bad parameters: you must choose at least one stream".into()))?; @@ -4487,40 +5042,62 @@ fn logs(req: &Request, engine: &Engine, id: &str, w: &mut UnixStream) -> io::Res // Frames are gathered into chunks of up to 32 KiB: one write per line // would make a long log slow to read. let mut out = Vec::with_capacity(40 << 10); - let mut line = Vec::new(); - let mut put = |r: &Record, out: &mut Vec| -> io::Result<()> { - let wanted = match r.stream { + let mut ts_cache = time::Rfc3339Cache::new(); + // Coalesce consecutive lines of the same multiplexed stream into a single + // Docker mux frame within each 32 KiB HTTP chunk to cut per-line 8-byte headers. + let mut open_mux: Option<(u8, usize)> = None; + let finish_mux = |out: &mut Vec, open_mux: &mut Option<(u8, usize)>| { + if let Some((_, hdr_pos)) = open_mux.take() { + let payload_len = (out.len() - hdr_pos - 8) as u32; + out[hdr_pos + 4..hdr_pos + 8].copy_from_slice(&payload_len.to_be_bytes()); + } + }; + let mut put = |stream: Stream, time_ns: u64, data: &[u8], out: &mut Vec, open_mux: &mut Option<(u8, usize)>| { + let wanted = match stream { Stream::Stdout => want_out, Stream::Stderr => want_err, }; - if !wanted || since.is_some_and(|s| r.time < s) { - return Ok(()); + if !wanted || since.is_some_and(|s| time_ns < s) { + return; } - let data = if stamps { - line.clear(); - line.extend_from_slice(time::rfc3339(std::time::UNIX_EPOCH + std::time::Duration::from_nanos(r.time)).as_bytes()); - line.push(b' '); - line.extend_from_slice(&r.data); - &line[..] + if tty { + if stamps { + ts_cache.write_ns(out, time_ns); + out.push(b' '); + } + out.extend_from_slice(data); } else { - &r.data[..] - }; - if tty { out.extend_from_slice(data) } else { http::mux_frame(out, r.stream as u8, data)? } - Ok(()) + let s_byte = stream as u8; + if open_mux.is_none_or(|(prev, _)| prev != s_byte) { + finish_mux(out, open_mux); + let hdr_pos = out.len(); + out.extend_from_slice(&[s_byte, 0, 0, 0, 0, 0, 0, 0]); + *open_mux = Some((s_byte, hdr_pos)); + } + if stamps { + ts_cache.write_ns(out, time_ns); + out.push(b' '); + } + out.extend_from_slice(data); + } }; - let past_until = |r: &Record| until.is_some_and(|u| r.time > u); + let past_until = |time_ns: u64| until.is_some_and(|u| time_ns > u); let mut ended = false; - for r in logs.past.tail(tail) { - if past_until(&r) { + let mut past = logs.past.tail(tail); + let mut rec_buf = Vec::with_capacity(256); + while let Some((stream, time_ns)) = past.next_into(&mut rec_buf) { + if past_until(time_ns) { ended = true; break; } - put(&r, &mut out)?; + put(stream, time_ns, &rec_buf, &mut out, &mut open_mux); if out.len() >= 32 << 10 { + finish_mux(&mut out, &mut open_mux); http::chunk(w, &out)?; out.clear(); } } + finish_mux(&mut out, &mut open_mux); http::chunk(w, &out)?; out.clear(); if let (Some(rx), false) = (logs.live, ended) { @@ -4528,13 +5105,15 @@ fn logs(req: &Request, engine: &Engine, id: &str, w: &mut UnixStream) -> io::Res let mut next = Some(r); // Whatever else is already waiting goes in the same chunk. while let Some(r) = next { - if past_until(&r) { + if past_until(r.time) { + finish_mux(&mut out, &mut open_mux); http::chunk(w, &out)?; break 'live; } - put(&r, &mut out)?; + put(r.stream, r.time, &r.data, &mut out, &mut open_mux); next = if out.len() < 32 << 10 { rx.try_recv().ok() } else { None }; } + finish_mux(&mut out, &mut open_mux); http::chunk(w, &out)?; out.clear(); } @@ -7153,6 +7732,58 @@ mod tests { std::fs::remove_dir_all(&dir).unwrap(); } + /// Re-pointing a macOS bind symlink between container create and start + /// must re-enforce `is_mac_hostetc` (forcing `ro`) and reject + /// `is_host_socket_ancestor` for non-Host callers. + #[cfg(target_os = "macos")] + #[test] + fn bind_links_recheck_hostetc_ro_and_socket_ancestor_at_start() { + let dir = std::env::temp_dir().join(format!("kiri-fresh-binds-sec-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let safe = dir.join("safe"); + let fake_etc = dir.join("state/etc"); + let fake_sock_dir = dir.join("state/run"); + for d in [&safe, &fake_etc, &fake_sock_dir] { + std::fs::create_dir_all(d).unwrap(); + } + let fake_sock = fake_sock_dir.join("docker.sock").to_string_lossy().into_owned(); + let link = dir.join("current"); + std::os::unix::fs::symlink(&safe, &link).unwrap(); + let src = link.to_str().unwrap().to_owned(); + let guest = vec![format!("{}\t/app\t", guest_bind_source(&src).unwrap())]; + let guest_with_flag = vec![format!("{}\t/app\tcreate", guest_bind_source(&src).unwrap())]; + let info = vec![json!({"Type": "bind", "Source": src})]; + let hostetc = |p: &str| is_mac_hostetc_with(p, Some(&fake_etc)); + let sock_anc = |p: &str| is_host_socket_ancestor_against(p, std::slice::from_ref(&fake_sock)); + let at_start = |guest: &[String], non_host: bool| confine_mac_binds(fresh_bind_sources_with(guest, &info, |_| None, true), &info, non_host, hostetc, sock_anc); + + // 1. Re-point symlink to synthetic hostetc dir: start must force `ro`. + std::fs::remove_file(&link).unwrap(); + std::os::unix::fs::symlink(&fake_etc, &link).unwrap(); + let etc_real = std::fs::canonicalize(&fake_etc).unwrap(); + assert_eq!( + at_start(&guest, false).unwrap(), + [format!("/mnt/mac{}\t/app\tro", etc_real.display())] + ); + assert_eq!( + at_start(&guest_with_flag, false).unwrap(), + [format!("/mnt/mac{}\t/app\tcreate,ro", etc_real.display())] + ); + + // 2. Re-point symlink to host socket ancestor dir: non-Host caller is rejected, Host still works. + std::fs::remove_file(&link).unwrap(); + std::os::unix::fs::symlink(&fake_sock_dir, &link).unwrap(); + let err = at_start(&guest, true).unwrap_err(); + assert!(matches!(err, Error::BadRequest(ref m) if m.contains("host socket")), "unexpected error: {err:?}"); + let sock_real = std::fs::canonicalize(&fake_sock_dir).unwrap(); + assert_eq!( + at_start(&guest, false).unwrap(), + [format!("/mnt/mac{}\t/app\t", sock_real.display())] + ); + + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn signals_like_docker() { for (raw, n) in [ @@ -8352,12 +8983,103 @@ mod network_option_tests { assert!(super::check_volume_device_for(&opts(&[("type", "none"), ("o", "bind"), ("device", "/proc/self/root/mnt/mac")]), "/mnt/mac").is_err()); // Ordinary volumes are untouched. assert!(super::check_volume_device(&opts(&[("type", "none"), ("o", "bind"), ("device", "/Users/me/data")])).is_ok()); + // A container's bind volume may not expose the directory holding Kiri's host socket. + if let Ok(own) = super::super::socket_path() { + let run = own.parent().unwrap().to_string_lossy().into_owned(); + let bind = opts(&[("type", "none"), ("o", "bind"), ("device", run.as_str())]); + assert!(super::validate_volume_options(&bind, None, None, &Caller::Container).is_err()); + assert!(super::validate_volume_options(&opts(&[("type", "none"), ("o", "bind"), ("device", "/")]), None, None, &Caller::Container).is_err()); + assert!(super::is_host_socket_ancestor(&run) && super::is_host_socket_ancestor("/")); + assert!(!super::is_host_socket_ancestor(&format!("{run}-other"))); + } + if cfg!(target_os = "macos") { + assert!(super::is_mac_hostetc("/etc") && super::is_mac_hostetc("/etc/passwd") && super::is_mac_hostetc("/etc//passwd")); + assert!(!super::is_mac_hostetc("/etc/hosts")); + } assert!(super::check_volume_device(&opts(&[("type", "nfs"), ("o", "addr=10.0.0.1"), ("device", ":/export")])).is_ok()); assert!(super::check_volume_device(&opts(&[("type", "nfs4"), ("device", "10.0.0.1:/export")])).is_ok()); assert!(super::check_volume_device(&opts(&[("type", "cifs"), ("device", "//10.0.0.1/share")])).is_ok()); assert!(super::check_volume_device(&opts(&[("type", "smb3"), ("device", "//10.0.0.1/share")])).is_ok()); assert!(super::check_volume_device(&opts(&[("type", "tmpfs"), ("device", "tmpfs")])).is_ok()); assert!(super::check_volume_device(&opts(&[])).is_ok()); + + // Host socket ancestor guard catches direct parent, ancestors, and symlinked parents. + let tmp = std::env::temp_dir().join(format!("kiri-sock-anc-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&tmp); + let real_sock_dir = tmp.join("real_run/kiri"); + std::fs::create_dir_all(&real_sock_dir).unwrap(); + let sym_sock_dir = tmp.join("var_run_kiri"); + std::os::unix::fs::symlink(&real_sock_dir, &sym_sock_dir).unwrap(); + let sibling_dir = tmp.join("other"); + std::fs::create_dir_all(&sibling_dir).unwrap(); + let cands = vec![real_sock_dir.join("docker.sock").to_string_lossy().into_owned()]; + assert!(super::is_host_socket_ancestor_against(&real_sock_dir.to_string_lossy(), &cands)); + assert!(super::is_host_socket_ancestor_against(&tmp.join("real_run").to_string_lossy(), &cands)); + assert!(super::is_host_socket_ancestor_against(&sym_sock_dir.to_string_lossy(), &cands)); + assert!(super::is_host_socket_ancestor_against( + &format!("{}/nonexistent/..", sym_sock_dir.display()), + &cands, + )); + assert!(!super::is_host_socket_ancestor_against(&sibling_dir.to_string_lossy(), &cands)); + + // Regular binds from Caller::Container cannot bind the host socket parent directory or a symlink to it. + let engine = super::super::engine::boot_without_vm(&tmp.join("store")); + let img = kiri_image::Image { + mirror: None, + name: "demo:local".into(), + digest: "sha256:test".into(), + index_digest: None, + config_digest: "sha256:test".into(), + layers: Vec::new(), + size: 0, + platform: "linux/arm64".into(), + created: String::new(), + pulled_at: 0, + config: Default::default(), + }; + if let Ok(sock) = super::super::socket_path() + && let Some(parent) = sock.parent() + { + let body = json!({"HostConfig": {"Binds": [format!("{}:/host-sock", parent.display())]}}); + assert!(super::mounts_for(&body, &engine, &img, &Caller::Container).is_err()); + if parent.exists() { + let sym_to_parent = tmp.join("sym-sock-parent"); + std::os::unix::fs::symlink(parent, &sym_to_parent).unwrap(); + let sym_body = json!({"HostConfig": {"Binds": [format!("{}:/host-sock", sym_to_parent.display())]}}); + assert!(super::mounts_for(&sym_body, &engine, &img, &Caller::Container).is_err()); + } + } + + // On macOS, a local bind volume targeting `/etc` must be forced read-only on both + // the container mount (`ro`, `RW: false`) and the volume mount flags (`MS_RDONLY`). + #[cfg(target_os = "macos")] + { + let vol_opts = opts(&[("type", "none"), ("o", "bind,rw"), ("device", "/etc")]); + engine.volume_ensure_with("etc-bind", json!({}), vol_opts).unwrap(); + let body = json!({"HostConfig": {"Binds": ["etc-bind:/mnt/etc"]}}); + let mounts = super::mounts_for(&body, &engine, &img, &Caller::Host).unwrap(); + assert_eq!(mounts.info.len(), 1); + assert_eq!(mounts.info[0]["RW"], json!(false)); + let parts: Vec<&str> = mounts.guest[0].split('\t').collect(); + assert!(parts[2].split(',').any(|f| f == "ro"), "container mount must carry ro: {}", mounts.guest[0]); + let vol_flags = u64::from_str_radix(parts[5], 16).unwrap(); + assert_ne!(vol_flags & 1, 0, "volume mount flags must set MS_RDONLY: {}", mounts.guest[0]); + let fake_etc = tmp.join("state/etc"); + std::fs::create_dir_all(&fake_etc).unwrap(); + let etc_link = tmp.join("evil-etc-link"); + std::os::unix::fs::symlink(&fake_etc, &etc_link).unwrap(); + assert!(super::is_mac_hostetc_with(&etc_link.to_string_lossy(), Some(&fake_etc))); + assert!(super::is_mac_hostetc_with(&format!("{}/nonexistent/..", etc_link.display()), Some(&fake_etc))); + // Also catches dangling symlinks pointing at a not-yet-created `state/etc`. + let missing_etc = tmp.join("missing-state/etc"); + let dangling_link = tmp.join("dangling-etc-link"); + std::os::unix::fs::symlink(&missing_etc, &dangling_link).unwrap(); + assert!(super::is_mac_hostetc_with(&dangling_link.to_string_lossy(), Some(&missing_etc))); + assert!(super::is_mac_hostetc_with(&format!("{}/nonexistent/..", dangling_link.display()), Some(&missing_etc))); + } + + drop(engine); + let _ = std::fs::remove_dir_all(&tmp); } #[test] @@ -8383,7 +9105,10 @@ mod network_option_tests { super::fresh_bind_sources_with(&guest, &info, |_| None, false), ["/run/kiri/host-services/ssh-auth.sock\t/run/host-services/ssh-auth.sock\tro"] ); - assert_eq!(super::fresh_bind_sources_with(&guest, &[], |_| None, false), ["/run/kiri/host-services/ssh-auth.sock\t/run/host-services/ssh-auth.sock\tro"]); + assert_eq!( + super::fresh_bind_sources_with(&guest, &[], |_| None, false), + ["/run/kiri/host-services/ssh-auth.sock\t/run/host-services/ssh-auth.sock\tro"] + ); let slash_guest = vec!["/run/host-services//ssh-auth.sock\t/run/host-services/ssh-auth.sock\tro".to_owned()]; assert_eq!( super::fresh_bind_sources_with(&slash_guest, &[], |_| None, false), diff --git a/crates/kiri/src/daemon/binds.rs b/crates/kiri/src/daemon/binds.rs index 4288f0c35..adc8aa9f4 100644 --- a/crates/kiri/src/daemon/binds.rs +++ b/crates/kiri/src/daemon/binds.rs @@ -659,29 +659,79 @@ pub fn make_source(path: &Path) -> std::io::Result<()> { return super::localtime::ensure_timezone(); } } - use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; let missing: Vec<&Path> = path.ancestors().take_while(|a| std::fs::symlink_metadata(a).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound)).collect(); if missing.is_empty() { - // There but not a folder (a link to nowhere): refused as before. + // There already: refuse symlinks / non-directories without modifying targets. + let meta = std::fs::symlink_metadata(path)?; + if meta.file_type().is_dir() { + return Ok(()); + } return std::fs::create_dir_all(path); } + // Open the deepest existing ancestor once, then create and chown/chmod each + // new component strictly via dirfd (`mkdirat` + `openat(O_DIRECTORY|O_NOFOLLOW)` + // + `fchown` + `fchmod`) so a local race swapping a new directory for a symlink + // can never redirect `chown`/`chmod` onto an arbitrary host file. + use std::ffi::CString; + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + use std::os::unix::ffi::OsStrExt; + let base = missing.last().and_then(|p| p.parent()).filter(|p| !p.as_os_str().is_empty()).unwrap_or_else(|| Path::new(".")); + let base_c = CString::new(base.as_os_str().as_bytes()).map_err(|_| std::io::Error::from(std::io::ErrorKind::InvalidInput))?; + // SAFETY: `base_c` is a valid NUL-terminated path; returned fd is immediately owned. + let base_fd = unsafe { libc::open(base_c.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC) }; + if base_fd < 0 { + return Err(std::io::Error::last_os_error()); + } + // SAFETY: `base_fd >= 0` is a fresh open descriptor owned exclusively here. + let mut parent = unsafe { OwnedFd::from_raw_fd(base_fd) }; // SAFETY: geteuid only reads this process's effective user. let root = unsafe { libc::geteuid() } == 0; for dir in missing.into_iter().rev() { - match std::fs::DirBuilder::new().mode(0o755).create(dir) { - Ok(()) => {} - // Made at the same moment by another container's start: its own. - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && dir.is_dir() => continue, - Err(e) => return Err(e), - } - if root { - std::os::unix::fs::chown(dir, Some(0), Some(0))?; + let Some(name) = dir.file_name() else { + return Err(std::io::Error::from(std::io::ErrorKind::InvalidInput)); + }; + let name_c = CString::new(name.as_bytes()).map_err(|_| std::io::Error::from(std::io::ErrorKind::InvalidInput))?; + // SAFETY: `parent` is a valid directory fd and `name_c` is NUL-terminated. + let mk = unsafe { libc::mkdirat(parent.as_raw_fd(), name_c.as_ptr(), 0o755) }; + let created = if mk == 0 { + true + } else { + let e = std::io::Error::last_os_error(); + if e.raw_os_error() == Some(libc::EEXIST) { + false + } else { + return Err(e); + } + }; + // SAFETY: `parent` is a valid directory fd; O_NOFOLLOW refuses any symlink race. + let child_raw = unsafe { libc::openat(parent.as_raw_fd(), name_c.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC) }; + if child_raw < 0 { + return Err(std::io::Error::last_os_error()); } - let mode = std::fs::metadata(dir)?.permissions().mode() & 0o7777; - let want = 0o755 | (mode & 0o2000); - if mode != want { - std::fs::set_permissions(dir, std::fs::Permissions::from_mode(want))?; + // SAFETY: `child_raw >= 0` is a fresh open descriptor owned exclusively here. + let child = unsafe { OwnedFd::from_raw_fd(child_raw) }; + if created { + if root { + // SAFETY: `child` is a valid open directory fd (never a symlink). + if unsafe { libc::fchown(child.as_raw_fd(), 0, 0) } != 0 { + return Err(std::io::Error::last_os_error()); + } + } + let mut st: libc::stat = unsafe { std::mem::zeroed() }; + // SAFETY: `child` is a valid fd and `st` is writable. + if unsafe { libc::fstat(child.as_raw_fd(), &mut st) } != 0 { + return Err(std::io::Error::last_os_error()); + } + let mode = (st.st_mode as u32) & 0o7777; + let want = 0o755 | (mode & 0o2000); + if mode != want { + // SAFETY: `child` is a valid open directory fd. + if unsafe { libc::fchmod(child.as_raw_fd(), want as libc::mode_t) } != 0 { + return Err(std::io::Error::last_os_error()); + } + } } + parent = child; } Ok(()) } @@ -1029,6 +1079,22 @@ mod tests { "/mnt/wsl/kiri/roots/Ubuntu/mnt/custom-share" ); assert!(distro_source("/home/me", "../evil", Some(&w)).is_err()); + // Double-slash (`//...`) and cross-distro / engine UNC paths must not bypass confinement. + assert_eq!(distro_source("//etc/shadow", "Ubuntu", Some(&w)).unwrap(), "/mnt/wsl/kiri/roots/Ubuntu/etc/shadow"); + assert_eq!(distro_source("//var/lib/kiri", "Ubuntu", Some(&w)).unwrap(), "/mnt/wsl/kiri/roots/Ubuntu/var/lib/kiri"); + assert!(distro_source("//mnt/wsl/kiri/roots/Debian/etc", "Ubuntu", Some(&w)).is_err()); + assert!(distro_source("//mnt/wsl/kiri/sockets/Ubuntu", "Ubuntu", Some(&w)).is_err()); + assert!(distro_source(r"\\wsl$\kiri\etc\shadow", "Ubuntu", Some(&w)).is_err()); + assert!(distro_source(r"\\wsl.localhost\kiri\var\lib\kiri", "Ubuntu", Some(&w)).is_err()); + assert!(distro_source(r"\\wsl$\Debian\etc\shadow", "Ubuntu", Some(&w)).is_err()); + assert!(distro_source(r"\\wsl.localhost\Debian\home\me", "Ubuntu", Some(&w)).is_err()); + assert_eq!( + distro_source(r"\\wsl.localhost\Ubuntu\home\me", "Ubuntu", Some(&w)).unwrap(), + "/mnt/wsl/kiri/roots/Ubuntu/home/me" + ); + assert_eq!(distro_source(r"C:\proj", "Ubuntu", Some(&w)).unwrap(), "/mnt/c/proj"); + // A Unix path with redundant slashes is the distro's own, not a drive. + assert_eq!(distro_source("//c/proj", "Ubuntu", Some(&w)).unwrap(), "/mnt/wsl/kiri/roots/Ubuntu/c/proj"); // Redundant leading slashes on Unix paths stay confined to ``. assert_eq!( @@ -1131,4 +1197,21 @@ mod tests { assert_eq!(resolve_in_root(&root.join("missing"), "/etc/../x").unwrap(), ("/x".to_owned(), false)); let _ = std::fs::remove_dir_all(&root); } + + #[test] + fn make_source_refuses_symlinks_without_changing_target_mode() { + use std::os::unix::fs::PermissionsExt; + let base = std::env::temp_dir().join(format!("kiri-make-source-symlink-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + let secret = base.join("secret.txt"); + std::fs::write(&secret, b"private").unwrap(); + std::fs::set_permissions(&secret, std::fs::Permissions::from_mode(0o600)).unwrap(); + let link = base.join("link"); + std::os::unix::fs::symlink(&secret, &link).unwrap(); + + assert!(make_source(&link).is_err()); + assert_eq!(std::fs::metadata(&secret).unwrap().permissions().mode() & 0o777, 0o600); + let _ = std::fs::remove_dir_all(&base); + } } diff --git a/crates/kiri/src/daemon/builder.rs b/crates/kiri/src/daemon/builder.rs index e4579c17c..f4c4ad95e 100644 --- a/crates/kiri/src/daemon/builder.rs +++ b/crates/kiri/src/daemon/builder.rs @@ -176,8 +176,7 @@ pub fn set_settings(req: &Request) -> Result<(), Error> { s["idle_secs"] = body["idle_secs"].as_u64().filter(|v| *v <= 7 * 86400).ok_or_else(|| Error::BadRequest("idle_secs must be 0 to 604800".into()))?.into(); } let path = settings_path().ok_or_else(|| Error::Io(io::Error::other("HOME is not set")))?; - let tmp = path.with_extension("json.tmp"); - std::fs::write(&tmp, s.to_string()).and_then(|()| std::fs::rename(&tmp, &path)).map_err(Error::Io) + super::write_atomic_mode(&path, s.to_string().as_bytes(), 0o600).map_err(Error::Io) } // --- The container ------------------------------------------------------- @@ -596,7 +595,7 @@ fn hide_amd64_qemu(engine: &Engine, id: &str) { /// ls`, `inspect`, the window's Builds view) makes and pulls nothing, so a /// fresh Kiri has no builder, image or cache volume until the first build. /// None for any other name, or when the builder exists (the usual 409). -pub fn create_for_buildx(engine: &Engine, req: &Request) -> Option> { +pub fn create_for_buildx(engine: &Engine, req: &Request, caller: &super::caller::Caller) -> Option> { if req.query("name").map(|n| n.trim_start_matches('/')) != Some(container_name().as_str()) { return None; } @@ -608,6 +607,9 @@ pub fn create_for_buildx(engine: &Engine, req: &Request) -> Option return Some(Err(Error::BadRequest(format!("invalid JSON: {e}")))), } }; + // Only a host caller may customize Env/Dns/ExtraHosts/NetworkMode on the + // shared privileged BuildKit container. + let requested = if *caller == super::caller::Caller::Host { requested } else { None }; let _g = ENSURE.lock().unwrap_or_else(|e| e.into_inner()); if let Some((id, _)) = find(engine) { if container_is_pinned(engine, &id) { @@ -763,13 +765,21 @@ pub(super) fn internal_exec(argv: &[String], stdin: bool, env: Vec) -> E /// A tar archive, as `docker cp` takes it, from (path, contents) entries; a /// path ending in `/` with no contents is a directory. fn tar(entries: &[(&str, Option<&[u8]>)]) -> Vec { + let entries: Vec<(&str, Option<&[u8]>, u32)> = entries + .iter() + .map(|(n, d)| (*n, *d, if d.is_some() { 0o644 } else { 0o755 })) + .collect(); + tar_with_modes(&entries) +} + +fn tar_with_modes(entries: &[(&str, Option<&[u8]>, u32)]) -> Vec { let mut out = Vec::new(); - for (name, data) in entries { + for &(name, data, mode) in entries { let mut h = [0u8; 512]; let field = |h: &mut [u8; 512], at: usize, len: usize, v: &[u8]| h[at..at + v.len().min(len)].copy_from_slice(&v[..v.len().min(len)]); field(&mut h, 0, 100, name.as_bytes()); let size = data.map_or(0, <[u8]>::len); - field(&mut h, 100, 8, if data.is_some() { b"0000644\0" } else { b"0000755\0" }); + field(&mut h, 100, 8, format!("{mode:07o}\0").as_bytes()); field(&mut h, 108, 8, b"0000000\0"); field(&mut h, 116, 8, b"0000000\0"); field(&mut h, 124, 12, format!("{size:011o}\0").as_bytes()); @@ -934,12 +944,33 @@ impl Options { .flatten() .filter_map(|u| Some(format!("{}={}:{}", u["Name"].as_str()?, u["Soft"].as_i64()?, u["Hard"].as_i64()?))) .collect(); - let cache_from = json_query(req, "cachefrom")?.as_array().into_iter().flatten().filter_map(|c| c.as_str().map(str::to_owned)).filter(|c| !c.is_empty()).collect(); + let mut cache_from = Vec::new(); + for c in json_query(req, "cachefrom")?.as_array().into_iter().flatten().filter_map(|c| c.as_str()).filter(|c| !c.is_empty()) { + // `--import-cache` takes RFC-4180 CSV `key=value` pairs; reject CSV + // delimiters/controls and require a valid image reference so callers + // cannot inject `,type=local,src=...` into BuildKit. + if c.contains([',', '"', '\r', '\n', '\0']) || Reference::parse(c).is_err() { + return Err(Error::BadRequest(format!("invalid cachefrom reference: {c:?}"))); + } + cache_from.push(c.to_owned()); + } + let remote = match req.query("remote").filter(|r| !r.is_empty()) { + Some(r) => { + if r.contains([',', '"', '\r', '\n', '\0']) + || r.starts_with('-') + || !(r.starts_with("http://") || r.starts_with("https://") || r.starts_with("git://") || r.starts_with("github.com/")) + { + return Err(Error::BadRequest(format!("invalid remote build context: {r:?}"))); + } + Some(r.to_owned()) + } + None => None, + }; let dockerfile = clean_path(req.query("dockerfile").filter(|d| !d.is_empty()).unwrap_or("Dockerfile"))?; Ok(Options { tags, dockerfile: if dockerfile.is_empty() { "Dockerfile".into() } else { dockerfile }, - remote: req.query("remote").filter(|r| !r.is_empty()).map(str::to_owned), + remote, target: req.query("target").unwrap_or_default().to_owned(), build_args: pairs(json_query(req, "buildargs")?), labels: pairs(json_query(req, "labels")?), @@ -1214,7 +1245,13 @@ fn run(req: &Request, engine: &Engine, o: &mut Options, r: &mut BufReader { - copy_in(engine, &id, &dir, &mut io::Cursor::new(tar(&[("docker/", None), ("docker/config.json", Some(&config))]))).map_err(|e| format!("{e:?}"))?; + copy_in( + engine, + &id, + &dir, + &mut io::Cursor::new(tar_with_modes(&[("docker/", None, 0o700), ("docker/config.json", Some(&config), 0o600)])), + ) + .map_err(|e| format!("{e:?}"))?; vec![format!("DOCKER_CONFIG={dir}/docker")] } None => Vec::new(), @@ -1577,17 +1614,24 @@ mod tests { let engine = Engine::boot(store).unwrap(); let other = Request::internal("POST", "/containers/create", &[("name", "not-builder")], serde_json::to_vec(&asked).unwrap()); - assert!(create_for_buildx(&engine, &other).is_none()); + assert!(create_for_buildx(&engine, &other, &super::super::caller::Caller::Host).is_none()); let name = container_name(); let bad = Request::internal("POST", "/containers/create", &[("name", &name)], b"{not-json".to_vec()); - assert!(matches!(create_for_buildx(&engine, &bad), Some(Err(Error::BadRequest(_))))); + assert!(matches!(create_for_buildx(&engine, &bad, &super::super::caller::Caller::Host), Some(Err(Error::BadRequest(_))))); + + // Non-Host callers must not be able to inject custom Env/Dns/NetworkMode onto the shared builder. + let non_host_req = Request::internal("POST", "/containers/create", &[("name", &name)], serde_json::to_vec(&asked).unwrap()); + let non_host_created = create_for_buildx(&engine, &non_host_req, &super::super::caller::Caller::Container).expect("intercepted").expect("created"); + let nh_id = non_host_created["Id"].as_str().unwrap(); + assert!(!builder_host_net(&engine, nh_id), "Caller::Container must not customize shared builder NetworkMode"); + engine.remove(nh_id, true, false).unwrap(); let create_req = Request::internal("POST", "/containers/create", &[("name", &name)], serde_json::to_vec(&asked).unwrap()); - let created = create_for_buildx(&engine, &create_req).expect("intercepted").expect("created"); + let created = create_for_buildx(&engine, &create_req, &super::super::caller::Caller::Host).expect("intercepted").expect("created"); let id = created["Id"].as_str().unwrap(); assert!(builder_host_net(&engine, id), "builder container kept HostConfig.NetworkMode = host"); - assert!(create_for_buildx(&engine, &create_req).is_none(), "existing builder falls through to 409"); + assert!(create_for_buildx(&engine, &create_req, &super::super::caller::Caller::Host).is_none(), "existing builder falls through to 409"); drop(engine); let _ = std::fs::remove_dir_all(&dir); @@ -2197,6 +2241,19 @@ mod tests { let root_df = Options::parse(&req(&[("dockerfile", r".\Dockerfile")])).unwrap(); assert_eq!(root_df.dockerfile, "Dockerfile"); assert_eq!(Options::parse(&req(&[("dockerfile", r".\")])).unwrap().dockerfile, "Dockerfile"); + + // cachefrom CSV option injection and unsafe remote build context URLs are rejected. + assert!(Options::parse(&req(&[("cachefrom", r#"["alpine:3,type=local,src=/etc"]"#)])).is_err()); + assert!(Options::parse(&req(&[("cachefrom", r#"["\"bad\""]"#)])).is_err()); + assert!(Options::parse(&req(&[("cachefrom", r#"["alpine:3.20"]"#)])).is_ok()); + assert!(Options::parse(&req(&[("remote", "file:///etc/passwd")])).is_err()); + assert!(Options::parse(&req(&[("remote", "https://example.com/repo.git,foo=bar")])).is_err()); + assert!(Options::parse(&req(&[("remote", "https://github.com/org/repo.git")])).is_ok()); + + // docker/config.json archive uses 0700 dir and 0600 file mode. + let priv_tar = tar_with_modes(&[("docker/", None, 0o700), ("docker/config.json", Some(b"{}"), 0o600)]); + assert_eq!(&priv_tar[100..108], b"0000700\0"); + assert_eq!(&priv_tar[512 + 100..512 + 108], b"0000600\0"); } #[test] diff --git a/crates/kiri/src/daemon/domains.rs b/crates/kiri/src/daemon/domains.rs index 7cba43721..4ca40c3cb 100644 --- a/crates/kiri/src/daemon/domains.rs +++ b/crates/kiri/src/daemon/domains.rs @@ -48,12 +48,40 @@ struct Router { /// The routers, for a container that publishes their port (`step_aside`). static ROUTERS: Mutex>> = Mutex::new(Vec::new()); +const MAX_DOMAIN_CONNS: usize = 256; +const HEADER_DEADLINE: Duration = Duration::from_secs(10); +const DOMAIN_WRITE_TIMEOUT: Duration = Duration::from_secs(30); + +static ACTIVE_DOMAIN_CONNS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +struct DomainConnGuard; + +impl Drop for DomainConnGuard { + fn drop(&mut self) { + ACTIVE_DOMAIN_CONNS.fetch_sub(1, std::sync::atomic::Ordering::AcqRel); + } +} + +fn acquire_domain_conn() -> Option { + ACTIVE_DOMAIN_CONNS + .try_update(std::sync::atomic::Ordering::AcqRel, std::sync::atomic::Ordering::Acquire, |n| (n < MAX_DOMAIN_CONNS).then_some(n + 1)) + .ok() + .map(|_| DomainConnGuard) +} + impl Router { /// Binds the router's addresses and starts their accept threads; an /// error when fewer than `min` (at least one) could be bound, so a /// router never comes back on IPv6 alone while a container has IPv4. fn listen(self: &Arc, min: usize) -> io::Result)>> { - let listeners: Vec = router_addrs(self.port).iter().filter_map(|a| TcpListener::bind(a).ok()).collect(); + let listeners: Vec = router_addrs(self.port) + .iter() + .filter_map(|a| a.parse::().ok()) + // On macOS, wildcard low-port sockets bind `IP_BOUND_IF`/`IPV6_BOUND_IF` + // to `lo0` so LAN peers never reach the listener at the kernel level. + .filter_map(|addr| super::ports::bind_socket_on_if(addr, false, cfg!(target_os = "macos")).ok()) + .map(TcpListener::from) + .collect(); if listeners.len() < min.max(1) { return Err(io::Error::new(io::ErrorKind::AddrInUse, format!("port {} is taken", self.port))); } @@ -85,12 +113,21 @@ impl Router { if fds[1].revents != 0 { return; // stepped aside } - while let Ok((conn, _)) = listener.accept() { + while let Ok((conn, peer)) = listener.accept() { + // Reject non-loopback peers synchronously before spawning a thread. + if !peer.ip().to_canonical().is_loopback() { + continue; + } + let Some(permit) = acquire_domain_conn() else { + continue; + }; let _ = conn.set_nonblocking(false); - // A client that never finishes its request must not hold a thread forever. - let _ = conn.set_read_timeout(Some(Duration::from_secs(30))); + // Bound initial request header arrival and stalled writes. + let _ = conn.set_read_timeout(Some(HEADER_DEADLINE)); + let _ = conn.set_write_timeout(Some(DOMAIN_WRITE_TIMEOUT)); let (engine, tls) = (self.engine.clone(), self.tls.clone()); let _ = std::thread::Builder::new().name("kiri-domain-conn".into()).spawn(move || { + let _permit = permit; let _ = match tls { Some(config) => serve_tls(conn, &engine, config), None => serve(conn, &engine), @@ -470,11 +507,14 @@ pub fn reset(engine: &Arc) -> Result { fn serve(mut client: TcpStream, engine: &Engine) -> io::Result<()> { // The listener faces the network; only this Mac may use it. - if !client.peer_addr()?.ip().is_loopback() { + if !client.peer_addr()?.ip().to_canonical().is_loopback() { return Ok(()); } client.set_nodelay(true)?; let Some((head, guest)) = route(&mut client, engine, "http")? else { return Ok(()) }; + // Clear the header read deadline once proxying begins; keep write stall timeout. + let _ = client.set_read_timeout(None); + let _ = client.set_write_timeout(Some(DOMAIN_WRITE_TIMEOUT)); let mut to_guest = std::fs::File::from(guest.fd.try_clone()?); // What the client sent so far goes first, unchanged. to_guest.write_all(&head)?; @@ -492,13 +532,17 @@ fn serve(mut client: TcpStream, engine: &Engine) -> io::Result<()> { Ok(()) } -/// Reads the request head, finds the container its Host names and connects -/// to it. `None` once it has answered by itself (no such container, an -/// unreachable one, or a client that went away). +/// Reads the request head within an absolute deadline, finds the container its +/// Host names, and connects to it. `None` once it has answered by itself. fn route(client: &mut impl ReadWrite, engine: &Engine, scheme: &str) -> io::Result, kiri_vmm::VsockStream)>> { + let deadline = std::time::Instant::now() + HEADER_DEADLINE; let mut head = Vec::with_capacity(2048); let mut buf = [0u8; 4096]; let end = loop { + let Some(rem) = deadline.checked_duration_since(std::time::Instant::now()).filter(|d| !d.is_zero()) else { + return Err(io::Error::new(io::ErrorKind::TimedOut, "request header deadline exceeded")); + }; + let _ = client.set_header_read_timeout(Some(rem)); let n = client.read(&mut buf)?; if n == 0 { return Ok(None); @@ -630,13 +674,28 @@ fn web_port(engine: &Engine, t: &Target) -> u16 { port } -trait ReadWrite: Read + Write {} -impl ReadWrite for T {} +trait ReadWrite: Read + Write { + fn set_header_read_timeout(&self, _timeout: Option) -> io::Result<()> { + Ok(()) + } +} + +impl ReadWrite for TcpStream { + fn set_header_read_timeout(&self, timeout: Option) -> io::Result<()> { + self.set_read_timeout(timeout) + } +} + +impl ReadWrite for rustls::StreamOwned { + fn set_header_read_timeout(&self, timeout: Option) -> io::Result<()> { + self.sock.set_read_timeout(timeout) + } +} /// One HTTPS connection: TLS with the browser, plain bytes to the container, /// pumped in one poll loop (a TLS session cannot be split across threads). fn serve_tls(tcp: TcpStream, engine: &Engine, config: Arc) -> io::Result<()> { - if !tcp.peer_addr()?.ip().is_loopback() { + if !tcp.peer_addr()?.ip().to_canonical().is_loopback() { return Ok(()); } tcp.set_nodelay(true)?; @@ -647,6 +706,8 @@ fn serve_tls(tcp: TcpStream, engine: &Engine, config: Arc) let _ = tls.flush(); return Ok(()); }; + let _ = tls.sock.set_read_timeout(None); + let _ = tls.sock.set_write_timeout(Some(DOMAIN_WRITE_TIMEOUT)); let mut container = std::fs::File::from(guest.fd.try_clone()?); container.write_all(&head)?; let (conn, sock) = (&mut tls.conn, &mut tls.sock); @@ -901,4 +962,15 @@ mod tests { assert_eq!(reset["https"]["port"], 443); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn domain_conn_permit_is_bounded_and_releases_on_drop() { + let mut guards = Vec::new(); + for _ in 0..super::MAX_DOMAIN_CONNS { + guards.push(super::acquire_domain_conn().unwrap()); + } + assert!(super::acquire_domain_conn().is_none()); + drop(guards); + assert!(super::acquire_domain_conn().is_some()); + } } diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 565d1602f..8f26a1ab4 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -9,7 +9,7 @@ use std::collections::{HashMap, HashSet, VecDeque}; use std::io; use std::path::PathBuf; use std::sync::mpsc::{self, Receiver, Sender}; -use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, Weak}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, RwLock, RwLockReadGuard, RwLockWriteGuard, Weak}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use serde::{Deserialize, Serialize}; @@ -35,6 +35,14 @@ const MEMORY_DEADBAND: u64 = 64 << 20; /// Hold working-set peak this long after any grow, pressure event, or new peak /// before decaying it gently. const SHRINK_COOLDOWN: Duration = Duration::from_secs(60); +/// Upper bound for adaptive sawtooth backoff when active containers repeatedly +/// grow back shortly after shrinking. +const SHRINK_COOLDOWN_MAX: Duration = Duration::from_secs(600); +/// A grow or pressure event within this window after a shrink counts as a +/// balloon sawtooth reversal. +const CHURN_WINDOW: Duration = Duration::from_secs(300); +/// Maximum exponential backoff exponent (`60s * 2^4`, clamped to `SHRINK_COOLDOWN_MAX`). +const CHURN_MAX_LEVEL: u32 = 4; const WS_PEAK_DECAY_INTERVAL: Duration = Duration::from_secs(5); const WS_PEAK_DECAY_STEP: u64 = 64 << 20; @@ -175,8 +183,19 @@ struct BalloonState { last_target: Option, pending: Option, ws_peak: u64, + hold_started: Option, hold_until: Option, last_decay: Option, + /// Most recent shrink timestamp, used to detect shrink->grow sawtooth churn. + last_shrink: Option, + /// Most recent qualifying shrink->grow reversal (or calm step-down anchor). + /// Aged independently of `hold_until` so sustained periodic churn escalates + /// and non-churn grows cannot pin backoff at the cap indefinitely. + last_reversal: Option, + /// Number of consecutive shrink->grow reversals within `CHURN_WINDOW`. + /// Level 0 (`reversals <= 1`) preserves the base 60 s cooldown; sustained + /// sawtooth (`reversals >= 2`) backs off exponentially up to `SHRINK_COOLDOWN_MAX`. + churn_reversals: u32, } impl BalloonState { @@ -184,8 +203,71 @@ impl BalloonState { self.last_target = None; self.pending = None; self.ws_peak = 0; + self.hold_started = None; self.hold_until = None; self.last_decay = None; + self.last_shrink = None; + self.last_reversal = None; + self.churn_reversals = 0; + } + + fn churn_level(&self) -> u32 { + self.churn_reversals.saturating_sub(1).min(CHURN_MAX_LEVEL) + } + + fn effective_cooldown(&self) -> Duration { + let shift = self.churn_level(); + SHRINK_COOLDOWN + .checked_mul(1u32 << shift) + .unwrap_or(SHRINK_COOLDOWN_MAX) + .min(SHRINK_COOLDOWN_MAX) + } + + fn effective_decay_interval(&self) -> Duration { + let shift = self.churn_level(); + WS_PEAK_DECAY_INTERVAL + .checked_mul(1u32 << shift) + .unwrap_or(SHRINK_COOLDOWN_MAX) + } + + fn arm_hold(&mut self, now: std::time::Instant) { + self.hold_started = Some(now); + self.hold_until = Some(now + self.effective_cooldown()); + self.last_decay = None; + } + + fn age_churn(&mut self, now: std::time::Instant) { + // Keep the current reversal count while the latest shrink's reversal + // detection window is still open so a qualifying regrow escalates cleanly. + if self.last_shrink.is_some_and(|t| now.saturating_duration_since(t) <= CHURN_WINDOW) { + return; + } + while self.churn_reversals > 0 { + let Some(anchor) = self.last_reversal else { + self.churn_reversals = 0; + break; + }; + // A qualifying reversal needs the current hold + at least one decay + // step to shrink, plus up to `CHURN_WINDOW` for the next regrow. + let step = self + .effective_cooldown() + .saturating_add(self.effective_decay_interval()) + .saturating_add(CHURN_WINDOW); + if now.saturating_duration_since(anchor) < step { + break; + } + self.churn_reversals -= 1; + self.last_reversal = if self.churn_reversals > 0 { Some(anchor + step) } else { None }; + } + } + + fn note_grow(&mut self, active_containers: usize, now: std::time::Instant) { + if active_containers > 0 && self.last_shrink.is_some_and(|t| now.saturating_duration_since(t) <= CHURN_WINDOW) { + self.churn_reversals = self.churn_reversals.saturating_add(1).min(CHURN_MAX_LEVEL + 1); + self.last_reversal = Some(now); + // Consume this shrink so simultaneous pressure + target growth only count once. + self.last_shrink = None; + } } fn next_target_at( @@ -244,28 +326,45 @@ impl BalloonState { let u_live = live_memory_need(used, mem_total, mem_available, balloon, ceiling).min(ceiling); let u_commit = committed_memory_need(used, mem_total, committed_as, ceiling); - // Hold working-set peak for `SHRINK_COOLDOWN` after any grow, pressure - // event, or new peak, then decay gently (at most 64 MiB per 5 s). - // During legacy fallback deflation lag (`PendingFallback::Grow`), - // `used` is temporarily inflated by `ceiling - target`, so don't raise - // `ws_peak` from that lag reading. + // Reset sawtooth backoff once all containers have stopped and clamp any + // outstanding hold deadline to the base 60 s cooldown so an idle VM + // returns memory to macOS promptly. + if policy.active_containers == 0 { + self.churn_reversals = 0; + self.last_shrink = None; + self.last_reversal = None; + if let (Some(started), Some(until)) = (self.hold_started, self.hold_until) { + let base_until = started + SHRINK_COOLDOWN; + if until > base_until { + self.hold_until = Some(base_until); + } + } + } else { + self.age_churn(now); + } + + // Hold working-set peak for `effective_cooldown()` after any grow, + // pressure event, or new peak, then decay gently (at most 64 MiB per + // `effective_decay_interval()`). During legacy fallback deflation lag + // (`PendingFallback::Grow`), `used` is temporarily inflated by + // `ceiling - target`, so don't raise `ws_peak` from that lag reading. let legacy_grow_lag = legacy_fallback && matches!(self.pending, Some(PendingFallback::Grow { .. })); if external_grow || pressure { + self.note_grow(policy.active_containers, now); self.ws_peak = self.ws_peak.max(target.min(ceiling).saturating_sub(headroom)); - self.hold_until = Some(now + SHRINK_COOLDOWN); - self.last_decay = None; + self.arm_hold(now); } if !legacy_grow_lag && u_live > self.ws_peak { self.ws_peak = u_live; - self.hold_until = Some(now + SHRINK_COOLDOWN); - self.last_decay = None; + self.arm_hold(now); } + let decay_interval = self.effective_decay_interval(); if !legacy_grow_lag && self.ws_peak > u_live { if let Some(hold_until) = self.hold_until { if now >= hold_until { let decay_from = self.last_decay.map_or(hold_until, |t| t.max(hold_until)); let elapsed = now.saturating_duration_since(decay_from); - let steps = (elapsed.as_nanos() / WS_PEAK_DECAY_INTERVAL.as_nanos()) as u64; + let steps = (elapsed.as_nanos() / decay_interval.as_nanos()) as u64; if steps > 0 { let drop = steps.saturating_mul(WS_PEAK_DECAY_STEP); if self.ws_peak.saturating_sub(drop) <= u_live { @@ -275,7 +374,7 @@ impl BalloonState { self.ws_peak -= drop; let next_anchor = u32::try_from(steps) .ok() - .and_then(|s| WS_PEAK_DECAY_INTERVAL.checked_mul(s)) + .and_then(|s| decay_interval.checked_mul(s)) .and_then(|d| decay_from.checked_add(d)) .unwrap_or(now); self.last_decay = Some(next_anchor); @@ -306,12 +405,14 @@ impl BalloonState { if let Some(n) = next { if n > target { + self.note_grow(policy.active_containers, now); let demand = u_live.max(u_commit).min(ceiling); if demand.saturating_add(headroom) > target { self.ws_peak = self.ws_peak.max(demand); } - self.hold_until = Some(now + SHRINK_COOLDOWN); - self.last_decay = None; + self.arm_hold(now); + } else if n < target && policy.active_containers > 0 { + self.last_shrink = Some(now); } if legacy_fallback { self.pending = if n > target { @@ -730,6 +831,11 @@ pub struct Spec { /// own WSL distro on `Caller::Host`), when created in WSL. #[serde(default, skip_serializing_if = "Option::is_none")] pub wsl_distro: Option, + /// Whether this container was created by a non-Host caller (`Caller::Container` + /// or `Caller::Wsl`), so start-time symlink re-resolution keeps rejecting + /// binds that resolve to an ancestor of Kiri's host socket. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub non_host_creator: bool, } /// Normalizes an ExposedPorts key (`"53"`, `"53/UDP"`, `"132/sctp"`) to @@ -1710,8 +1816,9 @@ pub struct Engine { /// a file in the state dir (`stopped`). stopped: std::sync::atomic::AtomicBool, pub store: Store, - pub networks: Mutex, - state: Mutex, + pub networks: RwLock, + state: RwLock, + changed_seq: Mutex, changed: Condvar, /// Serialises sending layers, so two creates of a new image don't send /// the same layers twice. @@ -1851,8 +1958,7 @@ impl VolumeSizesCache { fn save(&self) { if let Ok(json) = serde_json::to_vec(&self.sizes) { - let tmp = self.path.with_extension("json.tmp"); - if let Err(e) = std::fs::write(&tmp, json).and_then(|()| std::fs::rename(&tmp, &self.path)) { + if let Err(e) = super::write_atomic_mode(&self.path, &json, 0o600) { crate::diag::error!("saving volume sizes failed", error = e); } } @@ -1944,7 +2050,7 @@ impl Engine { pub fn boot(store: Store) -> io::Result> { let records = store.root().join("containers.json"); let ceiling = memory_ceiling(); - let networks = Mutex::new(Networks::load(store.root())?); + let networks = RwLock::new(Networks::load(store.root())?); let loaded_volumes = super::volumes::Volumes::load(store.root())?; let volume_sizes_cache = Mutex::new(VolumeSizesCache::load(store.root(), loaded_volumes.all())); let volumes = Mutex::new(loaded_volumes); @@ -1959,7 +2065,8 @@ impl Engine { stopped: std::sync::atomic::AtomicBool::new(stopped_marker().is_some_and(|f| f.exists())), networks, store, - state: Mutex::default(), + state: RwLock::default(), + changed_seq: Mutex::new(0), changed: Condvar::new(), layers: Mutex::new(()), records, @@ -2304,7 +2411,7 @@ impl Engine { } let delay = st.vm_recovery_at.map_or(Duration::ZERO, |at| at.saturating_duration_since(std::time::Instant::now())); if !delay.is_zero() { - drop(self.changed.wait_timeout(st, delay).unwrap_or_else(|e| e.into_inner())); + drop(self.wait_changed_timeout(st, delay)); continue; } let generation = st.vm_recovery_generation; @@ -2362,7 +2469,13 @@ impl Engine { /// boots in a tenth of a second can afford to sleep, and sleeping is the /// one thing that gives all its memory back to macOS: Apple's balloon /// device takes pages from the guest but does not release them. - /// Runs a command in a running container and collects its output. + /// Maximum output collected by [`Self::exec_capture`] so a misbehaving + /// container cannot exhaust host daemon memory. + const MAX_EXEC_CAPTURE: usize = 1024 * 1024; + /// Maximum LoadBalancer ports reconciled for `kiri-k8s`. + const MAX_K8S_LB_PORTS: usize = 256; + + /// Runs a command in a running container and collects its output (bounded). pub fn exec_capture(&self, key: &str, argv: &[&str]) -> Result<(i32, String), Error> { let config = ExecConfig { console_size: None, @@ -2379,7 +2492,10 @@ impl Engine { let (_, rx) = self.exec_start(&id)?; let mut out = Vec::new(); for (_, data) in rx { - out.extend_from_slice(&data); + let room = Self::MAX_EXEC_CAPTURE.saturating_sub(out.len()); + if room > 0 { + out.extend_from_slice(&data[..data.len().min(room)]); + } } let code = self.with_exec(&id, |e| e.exit_code.unwrap_or(-1)).unwrap_or(-1); self.lock().execs.remove(&id); @@ -2481,8 +2597,14 @@ impl Engine { .split_whitespace() .filter_map(|p| { let (port, proto) = p.split_once('/')?; - Some((port.parse().ok()?, proto.to_ascii_lowercase())) + let proto = proto.to_ascii_lowercase(); + if proto != "tcp" && proto != "udp" { + return None; + } + let port: u16 = port.parse().ok()?; + (port != 0).then_some((port, proto)) }) + .take(Self::MAX_K8S_LB_PORTS) .collect(); let Some(vm) = self.awake() else { return false }; let host_ip = if crate::k8s::config().lan { "0.0.0.0" } else { "127.0.0.1" }; @@ -3065,8 +3187,34 @@ impl Engine { self.awake().is_some() } - fn lock(&self) -> MutexGuard<'_, State> { - self.state.lock().unwrap_or_else(|e| e.into_inner()) + fn read(&self) -> RwLockReadGuard<'_, State> { + self.state.read().unwrap_or_else(|e| e.into_inner()) + } + + fn lock(&self) -> RwLockWriteGuard<'_, State> { + self.state.write().unwrap_or_else(|e| e.into_inner()) + } + + fn notify_changed(&self) { + let mut seq = self.changed_seq.lock().unwrap_or_else(|e| e.into_inner()); + *seq = seq.wrapping_add(1); + self.changed.notify_all(); + } + + fn wait_changed<'a>(&'a self, st: RwLockWriteGuard<'a, State>) -> RwLockWriteGuard<'a, State> { + let seq = self.changed_seq.lock().unwrap_or_else(|e| e.into_inner()); + let cur = *seq; + drop(st); + drop(self.changed.wait_while(seq, |s| *s == cur).unwrap_or_else(|e| e.into_inner())); + self.lock() + } + + fn wait_changed_timeout<'a>(&'a self, st: RwLockWriteGuard<'a, State>, dur: Duration) -> RwLockWriteGuard<'a, State> { + let seq = self.changed_seq.lock().unwrap_or_else(|e| e.into_inner()); + let cur = *seq; + drop(st); + drop(self.changed.wait_timeout_while(seq, dur, |s| *s == cur).unwrap_or_else(|e| e.into_inner())); + self.lock() } /// Restores saved containers. Ones that were running when the daemon @@ -3339,7 +3487,7 @@ impl Engine { e.attached.clear(); let (container, exec_id, internal) = (e.container_id.clone(), e.id.clone(), e.config.internal); drop(st); - self.changed.notify_all(); + self.notify_changed(); if !internal { self.emit_container("exec_die", &container, &[("execID", exec_id), ("exitCode", code.to_string())]); } @@ -3467,7 +3615,7 @@ impl Engine { me.prune_layers(); }); } - self.changed.notify_all(); + self.notify_changed(); if persist { self.save(); } @@ -3557,7 +3705,7 @@ impl Engine { self.k8s_routes.lock().unwrap_or_else(|e| e.into_inner()).take(); *self.uplink.lock().unwrap_or_else(|e| e.into_inner()) = serde_json::Value::Null; super::ports::set_shared_nat_active(None); - self.changed.notify_all(); + self.notify_changed(); match end { // sleep_if_idle says why it slept. VmEnd::Slept => {} @@ -4097,7 +4245,7 @@ impl Engine { /// Resolves an id, an id prefix or a name to the full id. pub fn resolve(&self, key: &str) -> Result { - let st = self.lock(); + let st = self.read(); resolve(&st, key) } @@ -4247,8 +4395,9 @@ impl Engine { let (gate, exits, earlier, halted_at_claim) = gate; // A bind source that is a link is followed again at every start, as // Docker does: re-pointing it between runs (a `current` release - // link) mounts the new target; stale pre-fix mounts are refused here. - spec.mounts = match super::api::revalidate_and_refresh_mounts(self, &spec.mounts, &spec.mount_info) { + // link) mounts the new target; stale pre-fix mounts are refused here, and + // the new target is held to the create-time /etc and host-socket rules. + spec.mounts = match super::api::revalidate_and_refresh_mounts(self, &spec.mounts, &spec.mount_info, spec.non_host_creator) { Ok(m) => m, Err(e) => { self.fail_start(&id, &spec, &e); @@ -4946,7 +5095,7 @@ impl Engine { note_removed(&mut st, id, code); } drop(st); - self.changed.notify_all(); + self.notify_changed(); if let Some(c) = removed { if let Some(vm) = self.awake() { let _ = vm.remove(id); @@ -4964,12 +5113,16 @@ impl Engine { } } - pub fn lock_net(&self) -> MutexGuard<'_, Networks> { + pub fn read_net(&self) -> RwLockReadGuard<'_, Networks> { + self.networks.read().unwrap_or_else(|e| e.into_inner()) + } + + pub fn lock_net(&self) -> RwLockWriteGuard<'_, Networks> { self.lock_networks() } - fn lock_networks(&self) -> MutexGuard<'_, Networks> { - self.networks.lock().unwrap_or_else(|e| e.into_inner()) + fn lock_networks(&self) -> RwLockWriteGuard<'_, Networks> { + self.networks.write().unwrap_or_else(|e| e.into_inner()) } fn release_ip(&self, network: &str, ip: [u8; 4]) { @@ -5291,6 +5444,11 @@ impl Engine { lock_log(&c.log).path() } + /// Maximum stdin bytes buffered for a `Created` container before it starts + /// (`attach?stdin=1`), matching `vmlink::INPUT_WINDOW` so an unstarted + /// container cannot OOM-kill the host daemon. + const MAX_EARLY_INPUT: usize = 256 * 1024; + pub fn input(&self, id: &str, data: &[u8]) -> io::Result<()> { { let mut st = self.lock(); @@ -5299,6 +5457,9 @@ impl Engine { if c.status == Status::Exited { return Err(io::Error::new(io::ErrorKind::BrokenPipe, "container has exited")); } + if c.early_input.len().saturating_add(data.len()) > Self::MAX_EARLY_INPUT { + return Err(io::Error::new(io::ErrorKind::WriteZero, "container pre-start stdin buffer full")); + } c.early_input.extend_from_slice(data); return Ok(()); } @@ -5360,7 +5521,7 @@ impl Engine { _ => {} }, } - st = self.changed.wait(st).unwrap_or_else(|e| e.into_inner()); + st = self.wait_changed(st); } } @@ -5700,7 +5861,7 @@ impl Engine { if let Some(h) = self.lock().health.get_mut(&id) { close_monitor(h); } - self.changed.notify_all(); + self.notify_changed(); } else { self.health_resume(&id); } @@ -6040,13 +6201,13 @@ impl Engine { if left.is_zero() { return Err(Error::Io(io::Error::other(format!("cannot stop container: {}: it did not exit after SIGKILL", &id[..12])))); } - exited = self.changed.wait_timeout(exited, left).unwrap_or_else(|e| e.into_inner()).0; + exited = self.wait_changed_timeout(exited, left); } drop(exited); self.emit_container("stop", &id, &[]); return Ok(true); } - st = self.changed.wait_timeout(st, left).unwrap_or_else(|e| e.into_inner()).0; + st = self.wait_changed_timeout(st, left); } drop(st); self.emit_container("stop", &id, &[]); @@ -6167,7 +6328,7 @@ impl Engine { if left.is_zero() { break; } - st = self.changed.wait_timeout(st, left).unwrap_or_else(|e| e.into_inner()).0; + st = self.wait_changed_timeout(st, left); } } Ok(()) @@ -6197,7 +6358,7 @@ impl Engine { } let mut st = self.lock(); while st.containers.get(&id).is_some_and(|c| c.status == Status::Running) { - st = self.changed.wait_timeout(st, Duration::from_secs(5)).unwrap_or_else(|e| e.into_inner()).0; + st = self.wait_changed_timeout(st, Duration::from_secs(5)); } } *removing = removing.wrapping_add(1); @@ -6216,7 +6377,7 @@ impl Engine { // before waking waiters or returning to callers that may rebind ports. drop(removed.as_mut().and_then(|c| c.forwards.take())); self.clear_stopping_op(&id); - self.changed.notify_all(); + self.notify_changed(); let anon = self.unshared(removed.as_ref().map(|c| c.spec.anon_volumes.clone()).unwrap_or_default()); if let Some(c) = &removed { lock_log(&c.log).remove(); @@ -6468,7 +6629,7 @@ impl Engine { x.attached.clear(); } drop(st); - self.changed.notify_all(); + self.notify_changed(); return Err(Error::Conflict(msg)); } let started = self.vm()?.exec(&container_id, exec_id, &config.argv, &env, &config.cwd, &config.user, flags, exec_security.1, &exec_security.2); @@ -6485,7 +6646,7 @@ impl Engine { x.attached.clear(); } drop(st); - self.changed.notify_all(); + self.notify_changed(); return Err(Error::Io(e)); } if let (true, Some((rows, cols))) = (config.tty, console) { @@ -6505,14 +6666,14 @@ impl Engine { } pub fn with_exec(&self, exec_id: &str, f: impl FnOnce(&Exec) -> T) -> Result { - let st = self.lock(); + let st = self.read(); st.execs.get(exec_id).map(f).ok_or_else(|| Error::NotFound(format!("No such exec instance: {exec_id}"))) } /// Execs running in a container now (buildx's `buildctl dial-stdio` /// while it builds, for one): the managed builder isn't idle while any are. pub fn running_execs(&self, container_id: &str) -> usize { - self.lock().execs.values().filter(|e| e.container_id == container_id && e.running).count() + self.read().execs.values().filter(|e| e.container_id == container_id && e.running).count() } /// Drops a finished exec's record: Kiri's own, which nobody inspects. @@ -6521,7 +6682,7 @@ impl Engine { } fn is_running(&self, id: &str) -> bool { - self.lock().containers.get(id).is_some_and(|c| c.status == Status::Running) + self.read().containers.get(id).is_some_and(|c| c.status == Status::Running) } /// Remembers the op under which these containers are being stopped, so @@ -6562,29 +6723,36 @@ impl Engine { None => (false, false), } }; - self.changed.notify_all(); + self.notify_changed(); if persist { self.save(); } cancelled } - /// Runs `f` over every container, under the lock. + /// Runs `f` over every container, under the shared read lock. pub fn each(&self, mut f: impl FnMut(&Container) -> Option) -> Vec { - self.lock().containers.values().filter_map(&mut f).collect() + self.read().containers.values().filter_map(&mut f).collect() } /// Runs `f` over every container alongside the current networks slice, - /// locking container state before networks. - pub fn each_with_networks(&self, mut f: impl FnMut(&Container, &[super::network::Network]) -> Option) -> Vec { - let s = self.lock(); - let net = self.lock_net(); - let networks = net.all(); - s.containers.values().filter_map(|c| f(c, networks)).collect() + /// taking shared read locks (container state before networks). + pub fn with_containers_and_networks(&self, f: impl FnOnce(&[&Container], &[super::network::Network]) -> T) -> T { + let s = self.read(); + let net = self.read_net(); + let containers: Vec<&Container> = s.containers.values().collect(); + f(&containers, net.all()) + } + + pub fn status_counts(&self) -> (usize, usize) { + let s = self.read(); + let total = s.containers.len(); + let running = s.containers.values().filter(|c| c.status == Status::Running).count(); + (total, running) } pub fn with(&self, key: &str, f: impl FnOnce(&Container) -> T) -> Result { - let st = self.lock(); + let st = self.read(); let id = resolve(&st, key)?; Ok(f(st.containers.get(&id).expect("resolved"))) } @@ -7567,6 +7735,179 @@ mod memory_target_tests { assert_eq!(CEILING - ceil_target, WS_PEAK_DECAY_STEP); } + /// Repeated shrink -> grow reversals while containers are active indicate + /// balloon sawtooth churn: cooldown and decay interval back off exponentially + /// (60s -> 120s -> 240s -> 480s -> 600s cap), and reset immediately when the + /// VM goes idle (0 active containers). + #[test] + fn balloon_sawtooth_backs_off_cooldown_and_resets_when_idle() { + let policy = active_policy(CEILING); + let headroom = memory_headroom(CEILING); + let mut state = BalloonState::default(); + let mut t = Instant::now(); + let mut target = 6 * GIB; + + let poll_with = |state: &mut BalloonState, policy: BalloonPolicy, target: u64, used: u64, pressure: bool, at: Instant| { + let unavail = used + 128 * MIB; + let balloon = CEILING.saturating_sub(target); + let avail = MEM_TOTAL.saturating_sub(balloon).saturating_sub(unavail); + let st = stats_sample(MEM_TOTAL, avail, used, Some(balloon), Some(used)); + state.next_target_at(&st, used, policy, target, pressure, at) + }; + + // Prime an initial peak, wait out base 60 s cooldown, then trigger a shrink. + if let Some(n) = poll_with(&mut state, policy, target, 4 * GIB, false, t) { + target = n; + } + t += SHRINK_COOLDOWN + WS_PEAK_DECAY_INTERVAL; + let shrunk1 = poll_with(&mut state, policy, target, 2 * GIB, false, t).expect("initial shrink after 65 s"); + assert!(shrunk1 < target); + target = shrunk1; + + // 1st reversal: keeps base 60 s cooldown (level 0). + t += Duration::from_secs(10); + target = (target + MEMORY_GROW).min(CEILING); + assert_eq!(poll_with(&mut state, policy, target, 4 * GIB, true, t), None); + assert_eq!(state.effective_cooldown(), SHRINK_COOLDOWN); + + // Shrink again, then hit a 2nd reversal -> backs off to 120 s cooldown / 10 s decay. + t += SHRINK_COOLDOWN + WS_PEAK_DECAY_INTERVAL; + let shrunk2 = poll_with(&mut state, policy, target, 2 * GIB, false, t).expect("second shrink after base cooldown"); + assert!(shrunk2 < target); + target = shrunk2; + + t += Duration::from_secs(10); + target = (target + MEMORY_GROW).min(CEILING); + assert_eq!(poll_with(&mut state, policy, target, 4 * GIB, true, t), None); + assert_eq!(state.effective_cooldown(), SHRINK_COOLDOWN * 2); + assert_eq!(state.effective_decay_interval(), WS_PEAK_DECAY_INTERVAL * 2); + + // Must NOT shrink at +65 s or +120 s (120 s cooldown now active). + assert_eq!(poll_with(&mut state, policy, target, 2 * GIB, false, t + Duration::from_secs(65)), None); + assert_eq!(poll_with(&mut state, policy, target, 2 * GIB, false, t + Duration::from_secs(120)), None); + // Must NOT shrink at +125 s (decay interval is now 10 s). + assert_eq!(poll_with(&mut state, policy, target, 2 * GIB, false, t + Duration::from_secs(125)), None); + // Shrinks at +130 s (120 s cooldown + 10 s decay). + let shrunk3 = poll_with(&mut state, policy, target, 2 * GIB, false, t + Duration::from_secs(130)) + .expect("should shrink after backed-off 120 s cooldown + 10 s decay"); + assert_eq!(target - shrunk3, WS_PEAK_DECAY_STEP); + target = shrunk3; + + // Further reversals cap at SHRINK_COOLDOWN_MAX (600 s). + for _ in 0..5 { + t += Duration::from_secs(135); + target = (target + MEMORY_GROW).min(CEILING); + let _ = poll_with(&mut state, policy, target, 4 * GIB, true, t); + t += state.effective_cooldown() + state.effective_decay_interval(); + if let Some(n) = poll_with(&mut state, policy, target, 2 * GIB, false, t) { + target = n; + } + } + assert_eq!(state.effective_cooldown(), super::SHRINK_COOLDOWN_MAX); + + // Transitioning to 0 active containers right after arming a 600 s hold + // clamps the outstanding hold deadline to the base 60 s cooldown so + // the first actual shrink lands at +65 s rather than +605 s. + t += Duration::from_secs(10); + target = CEILING; + let _ = poll_with(&mut state, policy, target, 4 * GIB, true, t); + assert_eq!(state.effective_cooldown(), super::SHRINK_COOLDOWN_MAX); + let hold_start = t; + t += Duration::from_secs(1); + let _ = poll_with(&mut state, idle_policy(CEILING), target, 200 * MIB, false, t); + assert_eq!(state.effective_cooldown(), SHRINK_COOLDOWN); + assert_eq!(state.effective_decay_interval(), WS_PEAK_DECAY_INTERVAL); + let idle_shrunk = poll_with(&mut state, idle_policy(CEILING), target, 200 * MIB, false, hold_start + SHRINK_COOLDOWN + WS_PEAK_DECAY_INTERVAL) + .expect("idle VM must shrink after clamped 60 s base cooldown + 5 s decay"); + assert!(idle_shrunk < target); + + // Periodic 180 s churn cycle (shrink at +65 s, regrow 115 s later): + // reversal #1 must not age out before reversal #2 at t=360 s. + let mut periodic = BalloonState::default(); + let t0 = Instant::now(); + let mut p_target = 5120 * MIB; + let reserved = CEILING - MEM_TOTAL; + let poll_live = |state: &mut BalloonState, target: u64, live_need: u64, at: Instant| { + let unavail = live_need.saturating_sub(reserved); + let balloon = CEILING.saturating_sub(target); + let avail = MEM_TOTAL.saturating_sub(balloon).saturating_sub(unavail); + let st = stats_sample(MEM_TOTAL, avail, unavail, Some(balloon), Some(unavail)); + state.next_target_at(&st, unavail, policy, target, false, at) + }; + for sec in 0..=360u64 { + let live = if sec % 180 == 0 { 3072 * MIB } else { 3008 * MIB }; + if let Some(n) = poll_live(&mut periodic, p_target, live, t0 + Duration::from_secs(sec)) { + p_target = n; + } + } + assert!( + periodic.effective_cooldown() >= SHRINK_COOLDOWN * 2, + "180 s periodic churn must escalate cooldown, got {:?}", + periodic.effective_cooldown() + ); + + // Non-churn grows (> CHURN_WINDOW after last shrink) must not keep + // capped backoff pinned indefinitely: once a full hold + decay + + // CHURN_WINDOW elapses without a qualifying reversal, backoff steps down. + let mut calm = BalloonState::default(); + let mut ct = Instant::now(); + let mut c_target = 6 * GIB; + for _ in 0..6 { + if let Some(n) = poll_with(&mut calm, policy, c_target, 4 * GIB, true, ct) { + c_target = n; + } + ct += calm.effective_cooldown() + calm.effective_decay_interval(); + if let Some(n) = poll_with(&mut calm, policy, c_target, 2 * GIB, false, ct) { + c_target = n; + } + ct += Duration::from_secs(10); + c_target = (c_target + MEMORY_GROW).min(CEILING); + } + assert_eq!(calm.effective_cooldown(), super::SHRINK_COOLDOWN_MAX); + // Repeated grows outside CHURN_WINDOW (>300 s after shrink) do not + // refresh `last_reversal`, so backoff decays smoothly from 600 s. + for _ in 0..4 { + ct += Duration::from_secs(310); + let _ = poll_with(&mut calm, policy, c_target, 4 * GIB, true, ct); + } + assert!( + calm.effective_cooldown() < super::SHRINK_COOLDOWN_MAX, + "non-churn grows must allow capped backoff to step down, got {:?}", + calm.effective_cooldown() + ); + + // Regression: at 120 s cooldown, a shrink at +140 s followed by a + // qualifying regrow 295 s later (+435 s, still within CHURN_WINDOW) + // must escalate to 240 s rather than stepping down at +430 s. + let mut late_regrow = BalloonState::default(); + let mut lt = Instant::now(); + let mut l_target = 6 * GIB; + for _ in 0..2 { + if let Some(n) = poll_with(&mut late_regrow, policy, l_target, 4 * GIB, true, lt) { + l_target = n; + } + lt += late_regrow.effective_cooldown() + late_regrow.effective_decay_interval(); + if let Some(n) = poll_with(&mut late_regrow, policy, l_target, 2 * GIB, false, lt) { + l_target = n; + } + lt += Duration::from_secs(10); + l_target = (l_target + MEMORY_GROW).min(CEILING); + } + if let Some(n) = poll_with(&mut late_regrow, policy, l_target, 4 * GIB, true, lt) { + l_target = n; + } + assert_eq!(late_regrow.effective_cooldown(), SHRINK_COOLDOWN * 2); + lt += Duration::from_secs(140); + let shrunk = poll_with(&mut late_regrow, policy, l_target, 2 * GIB, false, lt).expect("shrink at +140 s"); + assert!(shrunk < l_target); + l_target = shrunk; + lt += Duration::from_secs(295); + l_target = (l_target + MEMORY_GROW).min(CEILING); + let _ = poll_with(&mut late_regrow, policy, l_target, 4 * GIB, true, lt); + assert_eq!(late_regrow.effective_cooldown(), SHRINK_COOLDOWN * 4); + assert!(headroom > 0); + } + /// Idle VMs (0 active containers) use the 256 MiB idle floor instead of /// the active container floor `(C / 4).max(1 GiB).min(C)`, and optional /// `memory_min_mib` in `vm.json` is honored and clamped to `0..=ceiling`. @@ -7719,7 +8060,7 @@ fn copy_mounts_and_flags(engine: &Engine, spec: &Spec, op: u8, flags: u32) -> Re if !matches!(op, kiri_proto::copy_op::IN | kiri_proto::copy_op::OUT | kiri_proto::copy_op::STAT) { return Ok((Vec::new(), flags)); } - let mounts = super::api::revalidate_and_refresh_mounts(engine, &spec.mounts, &spec.mount_info)?; + let mounts = super::api::revalidate_and_refresh_mounts(engine, &spec.mounts, &spec.mount_info, spec.non_host_creator)?; let flags = if op == kiri_proto::copy_op::IN && spec.readonly_rootfs { flags | kiri_proto::copy_flags::READONLY_ROOTFS } else { @@ -7801,7 +8142,7 @@ impl Engine { break; } let next = pending.iter().filter(|(_, _, k)| k.is_none()).map(|(_, d, _)| d.saturating_duration_since(now)).min().unwrap_or(Duration::from_millis(100)); - st = self.changed.wait_timeout(st, next.clamp(Duration::from_millis(10), Duration::from_millis(250))).unwrap_or_else(|e| e.into_inner()).0; + st = self.wait_changed_timeout(st, next.clamp(Duration::from_millis(10), Duration::from_millis(250))); } drop(st); if engine { @@ -7814,12 +8155,12 @@ impl Engine { /// `State.Health` of a container with a healthcheck. pub fn health(&self, id: &str) -> Option { - self.lock().health.get(id).map(|h| h.health.clone()) + self.read().health.get(id).map(|h| h.health.clone()) } /// Health status by container id, for `docker ps`. pub fn health_statuses(&self) -> HashMap { - self.lock().health.iter().map(|(id, h)| (id.clone(), h.health.clone())).collect() + self.read().health.iter().map(|(id, h)| (id.clone(), h.health.clone())).collect() } /// Docker's `initHealthMonitor` at every start: status back to @@ -7893,7 +8234,7 @@ impl Engine { if left.is_zero() { break; } - st = self.changed.wait_timeout(st, left).unwrap_or_else(|e| e.into_inner()).0; + st = self.wait_changed_timeout(st, left); } } let start = SystemTime::now(); @@ -7911,7 +8252,7 @@ impl Engine { (run.health.status != before).then(|| (run.health.status.clone(), auto_remove)) }; if let Some((status, auto_remove)) = changed { - self.changed.notify_all(); + self.notify_changed(); self.emit_container(&format!("health_status: {status}"), id, &[]); if !auto_remove { self.save(); @@ -8016,7 +8357,7 @@ mod vm_recovery_tests { while !ids[..2].iter().all(|id| st.containers[id].status == Status::Running && st.containers[id].restart_count == count) { let left = until.saturating_duration_since(std::time::Instant::now()); assert!(!left.is_zero(), "policy containers stayed down without a new VM request"); - st = engine.changed.wait_timeout(st, left.min(Duration::from_millis(100))).unwrap().0; + st = engine.wait_changed_timeout(st, left.min(Duration::from_millis(100))); } for id in &ids[2..] { assert_eq!(st.containers[id].status, Status::Exited); @@ -8072,7 +8413,7 @@ mod vm_recovery_tests { while !ids[..2].iter().all(|id| st.containers[id].status == Status::Running && st.containers[id].restart_count == count) { let left = until.saturating_duration_since(std::time::Instant::now()); assert!(!left.is_zero(), "retirement must allow recovery after confirmed stop"); - st = engine.changed.wait_timeout(st, left.min(Duration::from_millis(100))).unwrap().0; + st = engine.wait_changed_timeout(st, left.min(Duration::from_millis(100))); } assert!(st.containers[&canceled[0]].stopped_by_user); assert_eq!(st.containers[&canceled[0]].status, Status::Exited); @@ -8099,7 +8440,7 @@ mod vm_recovery_tests { while ids[..2].iter().any(|id| st.containers[id].status == Status::Running) { let left = until.saturating_duration_since(std::time::Instant::now()); assert!(!left.is_zero(), "the lost VM must finish exit accounting"); - st = engine.changed.wait_timeout(st, left).unwrap().0; + st = engine.wait_changed_timeout(st, left); } assert!(st.vm_recovery_at.unwrap() > std::time::Instant::now() + Duration::from_secs(50)); let spec = st.containers[&ids[0]].spec.clone(); @@ -8121,7 +8462,7 @@ mod vm_recovery_tests { while st.vm_recovery_running { let left = until.saturating_duration_since(std::time::Instant::now()); assert!(!left.is_zero(), "stopping the candidates cancels the recovery worker"); - st = engine.changed.wait_timeout(st, left.min(Duration::from_millis(100))).unwrap().0; + st = engine.wait_changed_timeout(st, left.min(Duration::from_millis(100))); } drop(st); assert!(!engine.is_awake(), "no eligible containers means the VM stays down"); @@ -8287,14 +8628,14 @@ mod vm_recovery_tests { if left.is_zero() { return; } - st = engine.changed.wait_timeout(st, left).unwrap().0; + st = engine.wait_changed_timeout(st, left); } let c = st.containers.get_mut(&id).unwrap(); c.status = Status::Exited; c.exit_code = 137; c.exits += 1; drop(st); - engine.changed.notify_all(); + engine.notify_changed(); }) }; let r = match op { @@ -10790,6 +11131,7 @@ mod volume_remove_tests { volumes_from: vec!["seed-data:ro".into()], pid_mode: "host".into(), wsl_distro: Some("Ubuntu".into()), + non_host_creator: false, }; let log_dir = dir.join("containers").join("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"); @@ -11241,6 +11583,62 @@ mod exit_forwards_tests { drop(engine); let _ = std::fs::remove_dir_all(dir); } + + #[test] + fn early_input_is_bounded_and_k8s_node_requires_canonical_name() { + let (engine, id, dir) = engine_running("early-input-and-k8s-name"); + // Mark back to Created/not-live so `Engine::input` exercises `early_input`. + { + let mut st = engine.lock(); + let c = st.containers.get_mut(&id).unwrap(); + c.status = Status::Created; + c.live = false; + } + let exact = vec![b'x'; Engine::MAX_EARLY_INPUT]; + engine.input(&id, &exact).unwrap(); + let err = engine.input(&id, &[b'y']).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::WriteZero); + { + let st = engine.lock(); + let c = st.containers.get(&id).unwrap(); + assert_eq!(c.early_input.len(), Engine::MAX_EARLY_INPUT); + assert!(!super::is_k8s_node(c)); + } + + // An arbitrary container carrying `dev.kiri.k8s` must NOT qualify as the managed k8s node. + let image = Image { + mirror: None, + name: "test:local".into(), + digest: "sha256:test".into(), + index_digest: None, + config_digest: "sha256:test".into(), + layers: Vec::new(), + size: 0, + platform: "linux/arm64".into(), + created: String::new(), + pulled_at: 0, + config: Default::default(), + }; + let fake_k8s_spec: Spec = serde_json::from_value(serde_json::json!({ + "image": "test:local", "image_id": "sha256:test", "entrypoint": [], "cmd": ["sleep", "60"], + "env": [], "cwd": "/", "user": "", "auto_remove": false, "network_mode": "none", + "labels": {"dev.kiri.k8s": "1"}, + "restart": {"name": "no", "max_retries": 0} + })) + .unwrap(); + let fake_id = engine.create(Some("evil-k8s".into()), fake_k8s_spec.clone(), &image).unwrap(); + let mut real_spec = fake_k8s_spec; + real_spec.privileged = true; + let real_id = engine.create(Some("kiri-k8s".into()), real_spec, &image).unwrap(); + { + let st = engine.lock(); + assert!(!super::is_k8s_node(st.containers.get(&fake_id).unwrap())); + assert!(super::is_k8s_node(st.containers.get(&real_id).unwrap())); + } + + drop(engine); + let _ = std::fs::remove_dir_all(dir); + } } /// 10 ms timer slack applied to `kiri-k8s` (`dev.kiri.k8s`) so `k3s`'s dozens of diff --git a/crates/kiri/src/daemon/filters.rs b/crates/kiri/src/daemon/filters.rs index 516681185..8e246aa97 100644 --- a/crates/kiri/src/daemon/filters.rs +++ b/crates/kiri/src/daemon/filters.rs @@ -70,8 +70,19 @@ impl Filters { return true; } let bare = name.trim_start_matches('/'); + if self.names.iter().any(|p| p.matches(bare)) { + return true; + } + if bare.len() < 255 { + let mut buf = [0u8; 256]; + buf[0] = b'/'; + buf[1..1 + bare.len()].copy_from_slice(bare.as_bytes()); + if let Ok(slashed) = std::str::from_utf8(&buf[..1 + bare.len()]) { + return self.names.iter().any(|p| p.matches(slashed)); + } + } let slashed = format!("/{bare}"); - self.names.iter().any(|p| p.matches(bare) || p.matches(&slashed)) + self.names.iter().any(|p| p.matches(&slashed)) } /// A network's `id` filter, which Docker matches like `name`: exactly, diff --git a/crates/kiri/src/daemon/grpc.rs b/crates/kiri/src/daemon/grpc.rs index 1d253b381..ea39297e6 100644 --- a/crates/kiri/src/daemon/grpc.rs +++ b/crates/kiri/src/daemon/grpc.rs @@ -50,7 +50,82 @@ const MAX_FRAME_LIMIT: usize = 4 << 20; const MAX_SOLVE_BODY: usize = 16 << 20; const MAX_SOLVE_REQ_BYTES: usize = MAX_SOLVE_BODY; const MAX_TOTAL_SOLVE_REQ_BYTES: usize = 32 << 20; +/// Daemon-wide cap on buffered SolveRequest bytes across all concurrent `/grpc` +/// connections so 128 container connections cannot pin 4 GiB of host RAM. +const MAX_GLOBAL_SOLVE_REQ_BYTES: usize = 128 << 20; +const MAX_CONCURRENT_GRPC_STREAMS: usize = 64; const MAX_CONCURRENT_SOLVE_STREAMS: usize = 16; +const GRPC_HANDSHAKE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); + +static GLOBAL_SOLVE_REQ_BYTES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static ACTIVE_GRPC_STREAMS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +struct GrpcStreamPermit; + +impl Drop for GrpcStreamPermit { + fn drop(&mut self) { + ACTIVE_GRPC_STREAMS.fetch_sub(1, std::sync::atomic::Ordering::AcqRel); + } +} + +fn acquire_grpc_stream() -> Option { + ACTIVE_GRPC_STREAMS + .try_update(std::sync::atomic::Ordering::AcqRel, std::sync::atomic::Ordering::Acquire, |n| (n < MAX_CONCURRENT_GRPC_STREAMS).then_some(n + 1)) + .ok() + .map(|_| GrpcStreamPermit) +} + +/// RAII tracker for global SolveRequest bytes reserved by one `proxy_grpc` call, +/// guaranteeing release on normal completion, RST_STREAM, or early error. +struct GlobalSolveBudget<'a> { + counter: &'a std::sync::atomic::AtomicUsize, + cap: usize, + held: usize, +} + +impl GlobalSolveBudget<'static> { + fn new() -> Self { + Self::with_counter(&GLOBAL_SOLVE_REQ_BYTES, MAX_GLOBAL_SOLVE_REQ_BYTES) + } +} + +impl<'a> GlobalSolveBudget<'a> { + fn with_counter(counter: &'a std::sync::atomic::AtomicUsize, cap: usize) -> Self { + Self { counter, cap, held: 0 } + } + + fn try_add(&mut self, bytes: usize) -> bool { + let cap = self.cap; + let ok = self + .counter + .try_update(std::sync::atomic::Ordering::AcqRel, std::sync::atomic::Ordering::Acquire, |n| { + let next = n.checked_add(bytes)?; + (next <= cap).then_some(next) + }) + .is_ok(); + if ok { + self.held += bytes; + } + ok + } + + fn release(&mut self, bytes: usize) { + let drop_n = bytes.min(self.held); + if drop_n > 0 { + self.held -= drop_n; + self.counter.fetch_sub(drop_n, std::sync::atomic::Ordering::AcqRel); + } + } +} + +impl Drop for GlobalSolveBudget<'_> { + fn drop(&mut self) { + if self.held > 0 { + self.counter.fetch_sub(self.held, std::sync::atomic::Ordering::AcqRel); + self.held = 0; + } + } +} const MAX_CONTINUATION_FRAMES: usize = 32; const MAX_HEADER_BLOCK: usize = 1 << 20; const MAX_HPACK_TABLE_SIZE: usize = 1 << 20; @@ -73,18 +148,25 @@ pub fn grpc(req: &Request, engine: &Arc, w: &mut UnixStream, r: &mut Buf api::error(w, Error::BadRequest("POST /grpc requires Upgrade: h2c".into()))?; return Ok(Next::KeepAlive); } + let Some(_stream_permit) = acquire_grpc_stream() else { + api::error(w, Error::Conflict("too many concurrent BuildKit gRPC streams".into()))?; + return Ok(Next::Close); + }; http::upgrade_h2c(w)?; // buildx's driver priority probe dials `/grpc`, checks for 101, and closes // immediately without sending any HTTP/2 bytes: wait for the first byte - // before touching the builder so probes never wake or pull BuildKit. + // (with a bounded handshake timeout) before touching the builder so probes + // or idle connections never wake or pull BuildKit. let mut initial = r.buffer().to_vec(); r.consume(initial.len()); let mut client_r = r.get_ref().try_clone()?; if initial.is_empty() { - api::wait_readable(&client_r); + let _ = client_r.set_read_timeout(Some(GRPC_HANDSHAKE_TIMEOUT)); let mut buf = [0u8; 4096]; - match client_r.read(&mut buf) { + let first = client_r.read(&mut buf); + let _ = client_r.set_read_timeout(None); + match first { Ok(0) | Err(_) => return Ok(Next::Close), Ok(n) => initial.extend_from_slice(&buf[..n]), } @@ -152,11 +234,27 @@ pub fn session(req: &Request, engine: &Arc, w: &mut UnixStream, r: &mut .filter(|(k, _)| k.to_ascii_lowercase().starts_with("x-docker-expose-session-")) .map(|(k, v)| (k.to_ascii_lowercase(), v.clone())) .collect(); + let Some(_stream_permit) = acquire_grpc_stream() else { + api::error(w, Error::Conflict("too many concurrent BuildKit session streams".into()))?; + return Ok(Next::Close); + }; http::upgrade_h2c(w)?; - let early = r.buffer().to_vec(); + let mut early = r.buffer().to_vec(); r.consume(early.len()); - let client_r = r.get_ref().try_clone()?; + let mut client_r = r.get_ref().try_clone()?; + // Mirror `grpc()`: wait for at least one client byte (with a bounded + // handshake timeout) before waking BuildKit or spawning `buildctl dial-stdio`. + if early.is_empty() { + let _ = client_r.set_read_timeout(Some(GRPC_HANDSHAKE_TIMEOUT)); + let mut buf = [0u8; 4096]; + let first = client_r.read(&mut buf); + let _ = client_r.set_read_timeout(None); + match first { + Ok(0) | Err(_) => return Ok(Next::Close), + Ok(n) => early.extend_from_slice(&buf[..n]), + } + } let (builder_id, _busy) = match builder::ensure_running(engine, &mut |_| {}) { Ok(v) => v, @@ -454,6 +552,7 @@ where let mut header_block = Vec::new(); let mut solve_req_bufs: HashMap, usize)> = HashMap::new(); let mut total_solve_req_bytes = 0usize; + let mut global_budget = GlobalSolveBudget::new(); let res = (|| -> io::Result<()> { while let Some(frame) = read_frame(&mut client_r)? { @@ -487,6 +586,7 @@ where if header_end_stream { if let Some((buf, _)) = solve_req_bufs.remove(&frame.stream_id) { total_solve_req_bytes = total_solve_req_bytes.saturating_sub(buf.len()); + global_budget.release(buf.len()); } shared.lock().unwrap_or_else(|e| e.into_inner()).solve_streams.remove(&frame.stream_id); } else if headers.iter().any(|(k, v)| k == b":path" && v == SOLVE_PATH.as_bytes()) { @@ -498,6 +598,7 @@ where } if let Some((old_buf, _)) = solve_req_bufs.insert(frame.stream_id, (Vec::new(), 0)) { total_solve_req_bytes = total_solve_req_bytes.saturating_sub(old_buf.len()); + global_budget.release(old_buf.len()); } shared.lock().unwrap_or_else(|e| e.into_inner()).solve_streams.insert(frame.stream_id, None); } @@ -515,6 +616,7 @@ where let (buf, credited) = solve_req_bufs.get_mut(&sid).unwrap(); if buf.len().saturating_add(unpadded.len()) > MAX_SOLVE_REQ_BYTES || total_solve_req_bytes.saturating_add(unpadded.len()) > MAX_TOTAL_SOLVE_REQ_BYTES + || !global_budget.try_add(unpadded.len()) { return Err(io::Error::new(io::ErrorKind::InvalidData, "SolveRequest exceeds limit")); } @@ -534,6 +636,7 @@ where } let (raw_grpc, credited) = solve_req_bufs.remove(&sid).unwrap(); total_solve_req_bytes = total_solve_req_bytes.saturating_sub(raw_grpc.len()); + global_budget.release(raw_grpc.len()); let orig_len = raw_grpc.len(); let (out_grpc, rewrite_state) = rewrite_grpc_solve_request(&raw_grpc, engine, host_net)?; if let Some(rw) = rewrite_state { @@ -559,6 +662,7 @@ where FRAME_RST_STREAM => { if let Some((buf, _)) = solve_req_bufs.remove(&frame.stream_id) { total_solve_req_bytes = total_solve_req_bytes.saturating_sub(buf.len()); + global_budget.release(buf.len()); } shared.lock().unwrap_or_else(|e| e.into_inner()).solve_streams.remove(&frame.stream_id); write_server_frame(&frame)?; @@ -2269,4 +2373,41 @@ mod tests { drop(engine); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn session_probe_returns_101_without_waking_builder_and_global_budget_caps_memory() { + let (engine, dir) = test_engine("session-probe"); + let (mut client, server) = UnixStream::pair().unwrap(); + let handle = std::thread::spawn({ + let engine = engine.clone(); + move || super::super::api::serve(server, engine, super::super::caller::Caller::Container) + }); + client + .write_all(b"POST /session HTTP/1.1\r\nHost: \r\nContent-Length: 0\r\nConnection: Upgrade\r\nUpgrade: h2c\r\n\r\n") + .unwrap(); + let mut resp = Vec::new(); + let mut buf = [0u8; 512]; + while !resp.windows(4).any(|w| w == b"\r\n\r\n") { + let n = client.read(&mut buf).unwrap(); + assert!(n > 0); + resp.extend_from_slice(&buf[..n]); + } + assert!(String::from_utf8_lossy(&resp).starts_with("HTTP/1.1 101 ")); + drop(client); + handle.join().unwrap().unwrap(); + assert!(engine.each(|c| Some(c.name.clone())).is_empty()); + + let counter = std::sync::atomic::AtomicUsize::new(0); + let mut b1 = GlobalSolveBudget::with_counter(&counter, MAX_GLOBAL_SOLVE_REQ_BYTES); + assert!(b1.try_add(MAX_GLOBAL_SOLVE_REQ_BYTES)); + let mut b2 = GlobalSolveBudget::with_counter(&counter, MAX_GLOBAL_SOLVE_REQ_BYTES); + assert!(!b2.try_add(1), "global budget must reject allocation above daemon cap"); + drop(b1); + assert!(b2.try_add(1), "dropping budget releases reserved bytes"); + drop(b2); + assert_eq!(counter.load(std::sync::atomic::Ordering::Acquire), 0); + + drop(engine); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/kiri/src/daemon/hillclimb_bench.rs b/crates/kiri/src/daemon/hillclimb_bench.rs new file mode 100644 index 000000000..c06c50655 --- /dev/null +++ b/crates/kiri/src/daemon/hillclimb_bench.rs @@ -0,0 +1,924 @@ +//! Frozen Rust benchmark suite for the Kiri Hillclimb (daemon, HTTP/API, +//! seccomp, logfile, kiri-proto, kiri-share-proto, kiri-image). +//! +//! Excluded from production binaries (`#[cfg(test)]`) and skipped by normal +//! `cargo test` (`#[ignore]`). Run via the frozen harness script in scratch: +//! cargo test --profile fast --bin kiri daemon::hillclimb_bench::run_daemon_bench -- --ignored --exact --nocapture + +use std::hint::black_box; +use std::io::{self, BufRead, BufReader, Read, Write}; +use std::os::unix::net::{UnixListener, UnixStream}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; + +use kiri_image::{Image, Layer, RunConfig, Store}; +use kiri_proto::{FsEntry, Limits, Msg, Net, Stats, Stream, run_flags}; +use kiri_share_proto::Msg as ShareMsg; + +use super::api; +use super::caller::Caller; +use super::engine::{Engine, Spec, boot_without_vm}; +use super::logfile::{self, Log, LogConfig}; +use super::network::Settings as NetSettings; +use super::seccomp; + +static SEQ: AtomicU64 = AtomicU64::new(1); + +fn temp_dir(tag: &str) -> PathBuf { + let id = SEQ.fetch_add(1, Ordering::Relaxed); + let p = std::env::temp_dir().join(format!("kiri-hc-{tag}-{}-{id}", std::process::id())); + let _ = std::fs::remove_dir_all(&p); + std::fs::create_dir_all(&p).expect("create bench tempdir"); + p +} + +struct MetricSummary { + median: f64, + p95: f64, + p99: f64, + iqr: f64, + cv_pct: f64, + n: usize, +} + +fn summarize(samples: &[f64]) -> MetricSummary { + let mut s = samples.to_vec(); + s.sort_by(|a, b| a.total_cmp(b)); + let n = s.len(); + let median = if n % 2 == 1 { s[n / 2] } else { (s[n / 2 - 1] + s[n / 2]) / 2.0 }; + let p95 = s[((n * 95) / 100).min(n - 1)]; + let p99 = s[((n * 99) / 100).min(n - 1)]; + let q1 = s[(n / 4).min(n - 1)]; + let q3 = s[((n * 3) / 4).min(n - 1)]; + let mean = s.iter().sum::() / n as f64; + let var = s.iter().map(|x| (x - mean).powi(2)).sum::() / n as f64; + let cv_pct = if mean > 0.0 { var.sqrt() / mean * 100.0 } else { 0.0 }; + MetricSummary { median, p95, p99, iqr: q3 - q1, cv_pct, n } +} + +fn emit_metric(name: &str, pillar: &str, workload: &str, unit: &str, samples: &[f64], bytes: u64, work_ops: u64, errors: u64) { + let st = summarize(samples); + let row = json!({ + "name": name, + "pillar": pillar, + "workload": workload, + "unit": unit, + "median": st.median, + "p95": st.p95, + "p99": st.p99, + "iqr": st.iqr, + "cv_pct": st.cv_pct, + "n": st.n, + "bytes": bytes, + "work_ops": work_ops, + "errors": errors, + }); + println!("HILLCLIMB_JSON:{row}"); +} + +struct BenchServer { + root: PathBuf, + sock: PathBuf, + stop: Arc, + handle: Option>, + container_ids: Vec, + log_container_id: String, +} + +impl Drop for BenchServer { + fn drop(&mut self) { + self.stop.store(true, Ordering::SeqCst); + let _ = UnixStream::connect(&self.sock); + if let Some(h) = self.handle.take() { + let _ = h.join(); + } + let _ = std::fs::remove_dir_all(&self.root); + } +} + +fn populate_fixture(root: &Path, n_containers: usize, n_images: usize, n_volumes: usize, n_networks: usize, log_lines: usize) -> (Arc, Vec, String) { + let engine = boot_without_vm(root); + let repos = ["postgres", "redis", "nginx", "node", "python", "alpine"]; + + // 1. Populate realistic image store (config blobs + images.json) + let mut dummy_img_for_create = None; + for i in 0..n_images { + let repo = repos[i % repos.len()]; + let cfg = json!({ + "architecture": "arm64", + "os": "linux", + "created": format!("2026-11-{:02}T10:{:02}:00Z", (i % 27) + 1, i % 60), + "config": { + "Env": ["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", format!("APP_VERSION=v{i}")], + "Cmd": ["/bin/sh"], + "Labels": { + "org.opencontainers.image.source": format!("https://github.com/example/{repo}"), + "org.opencontainers.image.version": format!("1.{i}.0"), + "com.kiri.bench": "1" + } + } + }); + let cfg_bytes = serde_json::to_vec(&cfg).unwrap(); + let mut w = engine.store.ingest().unwrap(); + w.write_all(&cfg_bytes).unwrap(); + let (cfg_digest, _sz, _pin) = w.finish_pinned().unwrap(); + let img = Image { + name: format!("{repo}:v{i}"), + digest: cfg_digest.clone(), + index_digest: None, + config_digest: cfg_digest, + layers: Vec::new(), + size: 16_000_000 + (i as u64) * 512_000, + platform: "linux/arm64".into(), + created: format!("2026-11-{:02}T10:{:02}:00Z", (i % 27) + 1, i % 60), + pulled_at: 1_764_000_000 + i as u64, + config: RunConfig { + env: vec!["PATH=/usr/bin:/bin".into()], + entrypoint: Vec::new(), + cmd: vec!["/bin/sh".into()], + working_dir: "/app".into(), + user: String::new(), + }, + mirror: None, + }; + if dummy_img_for_create.is_none() { + dummy_img_for_create = Some(img.clone()); + } + engine.store.put_image(img).unwrap(); + } + let base_img = dummy_img_for_create.expect("at least 1 image"); + + // 2. Populate volumes + for i in 0..n_volumes { + engine + .volume_ensure_with(&format!("vol-data-{i}"), json!({"env": "bench", "idx": i.to_string()}), Default::default()) + .unwrap(); + } + + // 3. Populate networks + for i in 0..n_networks { + let _ = engine.lock_net().create( + &format!("net-bench-{i}"), + NetSettings { labels: json!({"tier": "app"}), ..Default::default() }, + ); + } + + // 4. Populate containers (mix of running and exited, Compose labels, ports, mounts) + let mut ids = Vec::with_capacity(n_containers); + for i in 0..n_containers { + let repo = repos[i % repos.len()]; + let labels = if i % 4 == 0 { + json!({ + "com.docker.compose.project": format!("proj-{}", i % 3), + "com.docker.compose.service": format!("svc-{i}"), + "tier": "backend", + "env": "bench" + }) + } else { + json!({ + "app": format!("svc-{i}"), + "tier": if i % 2 == 0 { "web" } else { "worker" }, + "env": "bench" + }) + }; + let spec: Spec = serde_json::from_value(json!({ + "image": format!("{repo}:v{}", i % n_images), + "image_id": base_img.config_digest, + "entrypoint": ["/usr/local/bin/entrypoint.sh"], + "cmd": ["--port", format!("{}", 8000 + i), "--workers", "4"], + "env": ["PATH=/usr/bin:/bin", format!("SERVICE_ID={i}"), "RUST_LOG=info"], + "cwd": "/app", + "user": "", + "auto_remove": true, + "network_mode": "bridge", + "labels": labels, + "restart": {"name": "no", "max_retries": 0} + })) + .unwrap(); + let id = engine.create(Some(format!("svc-app-{i}")), spec, &base_img).unwrap(); + if i % 5 != 0 { + engine.mark_running_for_test(&id, [172, 17, 0, ((i % 240) + 2) as u8]); + } + ids.push(id); + } + + // 5. Populate a realistic container log file on disk for the first container + let log_cid = ids[0].clone(); + { + let mut lg = Log::new(logfile::dir(engine.store.root(), &log_cid), &LogConfig::default()); + let base_ns: u64 = 1_764_260_000_000_000_000; + for i in 0..log_lines { + let stream = if i % 10 == 0 { Stream::Stderr } else { Stream::Stdout }; + let line = format!( + "level={} req_id={:06} method=GET path=/v1/orders/{} status=200 latency_ms={} bytes=4096\n", + if i % 10 == 0 { "ERROR" } else { "INFO" }, + i, + i % 1000, + (i % 45) + 1 + ); + lg.append(stream, base_ns + (i as u64) * 1_000_000, line.as_bytes()); + } + lg.flush(); + } + + (engine, ids, log_cid) +} + +fn start_server(tag: &str, n_containers: usize, n_images: usize, n_volumes: usize, n_networks: usize, log_lines: usize) -> BenchServer { + let root = temp_dir(tag); + let sock = root.join("docker.sock"); + let (engine, container_ids, log_container_id) = populate_fixture(&root, n_containers, n_images, n_volumes, n_networks, log_lines); + let listener = UnixListener::bind(&sock).expect("bind bench unix socket"); + let stop = Arc::new(AtomicBool::new(false)); + let stop_bg = stop.clone(); + let handle = std::thread::spawn(move || { + for conn in listener.incoming() { + if stop_bg.load(Ordering::SeqCst) { + break; + } + let Ok(stream) = conn else { break }; + let eng = engine.clone(); + std::thread::spawn(move || { + let _ = api::serve(stream, eng, Caller::Host); + }); + } + }); + BenchServer { root, sock, stop, handle: Some(handle), container_ids, log_container_id } +} + +/// Reads one HTTP/1.1 response from `r`, returning `(status, body_bytes, total_wire_bytes)`. +fn read_http_response(r: &mut BufReader) -> io::Result<(u16, Vec, u64)> { + let mut line = String::new(); + let mut wire = 0u64; + let n = r.read_line(&mut line)?; + if n == 0 { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "eof reading status")); + } + wire += n as u64; + let status: u16 = line.split_whitespace().nth(1).and_then(|s| s.parse().ok()).unwrap_or(0); + let mut content_len: Option = None; + let mut chunked = false; + loop { + line.clear(); + let n = r.read_line(&mut line)?; + if n == 0 { + break; + } + wire += n as u64; + let l = line.trim_end_matches(['\r', '\n']); + if l.is_empty() { + break; + } + if let Some((k, v)) = l.split_once(':') { + if k.eq_ignore_ascii_case("content-length") { + content_len = v.trim().parse().ok(); + } else if k.eq_ignore_ascii_case("transfer-encoding") && v.to_ascii_lowercase().contains("chunked") { + chunked = true; + } + } + } + let mut body = Vec::new(); + if chunked { + loop { + line.clear(); + let n = r.read_line(&mut line)?; + wire += n as u64; + let sz = usize::from_str_radix(line.trim().split(';').next().unwrap_or(""), 16) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "bad chunk size"))?; + if sz == 0 { + line.clear(); + let n = r.read_line(&mut line)?; + wire += n as u64; + break; + } + let prev = body.len(); + body.resize(prev + sz, 0); + r.read_exact(&mut body[prev..])?; + let mut crlf = [0u8; 2]; + r.read_exact(&mut crlf)?; + wire += (sz + 2) as u64; + } + } else if let Some(len) = content_len { + body.resize(len, 0); + r.read_exact(&mut body)?; + wire += len as u64; + } + Ok((status, body, wire)) +} + +fn http_keepalive_get(w: &mut UnixStream, r: &mut BufReader, path: &str) -> io::Result<(u16, Vec, u64)> { + let req = format!("GET {path} HTTP/1.1\r\nHost: kiri\r\nX-Kiri-Background: 1\r\n\r\n"); + w.write_all(req.as_bytes())?; + read_http_response(r) +} + +fn http_close_get(sock: &Path, path: &str) -> io::Result<(u16, Vec, u64)> { + let mut s = UnixStream::connect(sock)?; + s.set_read_timeout(Some(Duration::from_secs(30)))?; + let req = format!("GET {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\nX-Kiri-Background: 1\r\n\r\n"); + s.write_all(req.as_bytes())?; + let mut r = BufReader::new(s); + read_http_response(&mut r) +} + +fn bench_http_endpoint( + sock: &Path, + name: &str, + pillar: &str, + workload: &str, + path: &str, + reqs_per_sample: usize, + samples_n: usize, + verify: impl Fn(&[u8]) -> bool, +) { + let stream = UnixStream::connect(sock).expect("connect keepalive"); + stream.set_read_timeout(Some(Duration::from_secs(30))).unwrap(); + let mut w = stream.try_clone().unwrap(); + let mut r = BufReader::new(stream); + + // Warmup + for _ in 0..3 { + let (st, body, _) = http_keepalive_get(&mut w, &mut r, path).unwrap(); + assert_eq!(st, 200); + assert!(verify(&body)); + } + + let mut samples = Vec::with_capacity(samples_n); + let mut last_wire = 0u64; + let mut work_ops = 0u64; + let mut errors = 0u64; + for _ in 0..samples_n { + let mut last_body = Vec::new(); + let t0 = Instant::now(); + for _ in 0..reqs_per_sample { + match http_keepalive_get(&mut w, &mut r, path) { + Ok((200, body, wire)) if !body.is_empty() => { + black_box(&body); + last_wire = wire; + last_body = body; + work_ops += 1; + } + _ => errors += 1, + } + } + let per_req_us = t0.elapsed().as_secs_f64() * 1e6 / reqs_per_sample as f64; + if !last_body.is_empty() && !verify(&last_body) { + errors += 1; + } + samples.push(per_req_us); + } + emit_metric(name, pillar, workload, "us", &samples, last_wire, work_ops, errors); +} + +fn bench_ui_refresh_cycle(sock: &Path, name: &str, workload: &str, samples_n: usize) { + let paths = ["/containers/json?all=1", "/images/json", "/volumes", "/networks"]; + // Warmup + for _ in 0..2 { + for p in paths { + let (st, _, _) = http_close_get(sock, p).unwrap(); + assert_eq!(st, 200); + } + } + let mut samples = Vec::with_capacity(samples_n); + let mut cycle_bytes = 0u64; + let mut work_ops = 0u64; + let mut errors = 0u64; + for _ in 0..samples_n { + let t0 = Instant::now(); + let mut total_wire = 0u64; + for p in paths { + match http_close_get(sock, p) { + Ok((200, body, wire)) if !body.is_empty() => { + black_box(&body); + total_wire += wire; + work_ops += 1; + } + _ => errors += 1, + } + } + cycle_bytes = total_wire; + samples.push(t0.elapsed().as_secs_f64() * 1e6); + } + emit_metric(name, "latency", workload, "us", &samples, cycle_bytes, work_ops, errors); +} + +fn bench_concurrent_contention(sock: &Path, cid: &str) { + let threads = 4usize; + let iters_per_thread = 25usize; + let paths = [ + "/containers/json?all=1".to_owned(), + "/info".to_owned(), + "/images/json".to_owned(), + format!("/containers/{cid}/json"), + ]; + let barrier = Arc::new(std::sync::Barrier::new(threads)); + let mut handles = Vec::with_capacity(threads); + for t in 0..threads { + let s = sock.to_path_buf(); + let p = paths[t % paths.len()].clone(); + let b = barrier.clone(); + handles.push(std::thread::spawn(move || { + let stream = UnixStream::connect(&s).unwrap(); + stream.set_read_timeout(Some(Duration::from_secs(30))).unwrap(); + let mut w = stream.try_clone().unwrap(); + let mut r = BufReader::new(stream); + // Warmup before synchronized contention burst + for _ in 0..2 { + let (st, _, _) = http_keepalive_get(&mut w, &mut r, &p).unwrap(); + assert_eq!(st, 200); + } + b.wait(); + let mut times = Vec::with_capacity(iters_per_thread); + let mut wire_sum = 0u64; + let mut ok = 0u64; + let mut err = 0u64; + for _ in 0..iters_per_thread { + let t0 = Instant::now(); + match http_keepalive_get(&mut w, &mut r, &p) { + Ok((200, body, wire)) if !body.is_empty() => { + black_box(&body); + wire_sum += wire; + ok += 1; + } + _ => err += 1, + } + times.push(t0.elapsed().as_secs_f64() * 1e6); + } + (times, wire_sum, ok, err) + })); + } + let mut all_times = Vec::new(); + let mut total_bytes = 0u64; + let mut total_ops = 0u64; + let mut total_err = 0u64; + for h in handles { + let (times, b, ok, err) = h.join().unwrap(); + all_times.extend(times); + total_bytes += b; + total_ops += ok; + total_err += err; + } + emit_metric( + "api_concurrent_contention_heavy", + "lag", + "heavy", + "us", + &all_times, + total_bytes / total_ops.max(1), + total_ops, + total_err, + ); +} + +fn bench_seccomp() { + let small_json = r#"{"defaultAction":"SCMP_ACT_ERRNO","syscalls":[{"names":["read","write","close","exit_group","brk"],"action":"SCMP_ACT_ALLOW"}]}"#; + let default_json = include_str!("seccomp_docker_default.json"); + let default_caps: u64 = 0x0000_0000_a804_25fb; + + for (name, workload, json, reps, samples_n) in [ + ("seccomp_compile_small", "small", small_json, 20usize, 15usize), + ("seccomp_compile_heavy", "heavy", default_json, 5usize, 21usize), + ] { + // Warmup + let first = seccomp::compile(json, default_caps).expect("seccomp compile"); + assert!(!first.is_empty()); + + let mut samples = Vec::with_capacity(samples_n); + let mut work_ops = 0u64; + let mut errors = 0u64; + let mut bytes = 0u64; + for _ in 0..samples_n { + let t0 = Instant::now(); + for _ in 0..reps { + match seccomp::compile(black_box(json), default_caps) { + Ok(prog) if prog.len() == first.len() => { + bytes = prog.len() as u64; + black_box(&prog); + work_ops += 1; + } + _ => errors += 1, + } + } + samples.push(t0.elapsed().as_secs_f64() * 1e6 / reps as f64); + } + emit_metric(name, "latency", workload, "us", &samples, bytes, work_ops, errors); + } +} + +fn bench_kiri_proto() { + let mut buf = Vec::with_capacity(128 * 1024); + + // Small: Ping + Stats + Started roundtrip + { + let stats = Stats { + uptime_ns: 12_345_678_900, + mem_total_kib: 8 * 1024 * 1024, + mem_available_kib: 6 * 1024 * 1024, + agent_rss_kib: 4096, + mem_used_kib: 512 * 1024, + mem_stall: 0, + oom_kills: 0, + mem_balloon_kib: Some(2 * 1024 * 1024), + mem_committed_kib: Some(700 * 1024), + }; + let mut samples = Vec::with_capacity(15); + let mut bytes = 0u64; + let mut work_ops = 0u64; + let mut errors = 0u64; + // Warmup + for i in 0..200u64 { + buf.clear(); + Msg::Ping(i).encode(&mut buf); + let _ = black_box(kiri_proto::decode(&buf)); + buf.clear(); + Msg::Stats(stats).encode(&mut buf); + let _ = black_box(kiri_proto::decode(&buf)); + } + for _ in 0..15 { + let t0 = Instant::now(); + for i in 0..500u64 { + buf.clear(); + Msg::Ping(i).encode(&mut buf); + if kiri_proto::decode(&buf).is_err() { errors += 1; } + bytes = buf.len() as u64; + buf.clear(); + Msg::Stats(stats).encode(&mut buf); + if kiri_proto::decode(&buf).is_err() { errors += 1; } + bytes += buf.len() as u64; + buf.clear(); + Msg::Started { id: "abcdef0123456789abcdef0123456789", pid: 42, starting: false }.encode(&mut buf); + if kiri_proto::decode(&buf).is_err() { errors += 1; } + bytes += buf.len() as u64; + black_box(&buf); + work_ops += 3; + } + samples.push(t0.elapsed().as_secs_f64() * 1e6 / 500.0); + } + emit_metric("kiri_proto_roundtrip_small", "latency", "small", "us", &samples, bytes, work_ops, errors); + } + + // Heavy: encode_run (10 layers, 24 env vars, 6 mounts, 2 KB seccomp) + 64 KiB Output + 200-entry FsList + { + let layers: Vec = (0..10).map(|i| format!("sha256:{i:064x}")).collect(); + let argv = vec!["/usr/local/bin/server".to_owned(), "--bind".to_owned(), "0.0.0.0:8080".to_owned()]; + let env: Vec = (0..24).map(|i| format!("ENV_VAR_{i}=value_number_{i}_with_payload")).collect(); + let mounts: Vec = (0..6).map(|i| format!("/mnt/mac/src-{i}\t/app/dir-{i}\trw")).collect(); + let extra_hosts = vec!["host.docker.internal:172.17.0.1".to_owned()]; + let dns_names = vec!["web".to_owned(), "web.app".to_owned()]; + let net_opts = vec!["mtu=1500".to_owned()]; + let host_opts = vec!["rlimit=nofile:65536:65536".to_owned()]; + let seccomp_bytes = vec![0x06u8; 2048]; + let out_chunk = vec![b'A'; 64 * 1024]; + let fs_names: Vec = (0..200).map(|i| format!("module_file_{i:04}.rs")).collect(); + let fs_entries: Vec> = fs_names + .iter() + .enumerate() + .map(|(i, n)| FsEntry { name: n.as_str(), mode: 0o100644, size: (i as u64 + 1) * 4096, mtime: 1_764_000_000, mtime_nsec: 123, ino: i as u64 + 1 }) + .collect(); + let limits = Limits::default(); + + let mut samples = Vec::with_capacity(15); + let mut bytes = 0u64; + let mut work_ops = 0u64; + let mut errors = 0u64; + // Warmup + for _ in 0..20 { + buf.clear(); + kiri_proto::encode_fs_list(&mut buf, &fs_entries); + let _ = black_box(kiri_proto::decode(&buf)); + } + for _ in 0..15 { + let t0 = Instant::now(); + for _ in 0..200 { + let mut total_b = 0u64; + buf.clear(); + kiri_proto::encode_run( + &mut buf, + "c0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcd", + &layers, + &argv, + &env, + "/app", + "1000:1000", + "web-01", + run_flags::STDIN, + Net { + bridge: "kiri0", + ip: [172, 17, 0, 12], + prefix: 16, + gateway: [172, 17, 0, 1], + extra_hosts: &extra_hosts, + dns_names: &dns_names, + opts: &net_opts, + }, + &mounts, + &limits, + 0, + &host_opts, + &seccomp_bytes, + ); + total_b += buf.len() as u64; + match kiri_proto::decode(&buf) { + Ok(Msg::Run(r)) if r.layers.iter().count() == 10 && r.env.iter().count() == 24 => {} + _ => errors += 1, + } + buf.clear(); + Msg::Output { id: "c0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcd", stream: Stream::Stdout, data: &out_chunk }.encode(&mut buf); + total_b += buf.len() as u64; + match kiri_proto::decode(&buf) { + Ok(Msg::Output { data, .. }) if data.len() == out_chunk.len() => {} + _ => errors += 1, + } + buf.clear(); + kiri_proto::encode_fs_list(&mut buf, &fs_entries); + total_b += buf.len() as u64; + match kiri_proto::decode(&buf) { + Ok(Msg::FsList { count, raw }) if count == 200 => { + let iterated = kiri_proto::fs_entries(count, raw).count(); + if iterated != 200 { errors += 1; } + } + _ => errors += 1, + } + bytes = total_b; + black_box(&buf); + work_ops += 3; + } + samples.push(t0.elapsed().as_secs_f64() * 1e6 / 200.0); + } + emit_metric("kiri_proto_roundtrip_heavy", "latency", "heavy", "us", &samples, bytes, work_ops, errors); + } +} + +fn bench_kiri_share_proto() { + let mut buf = Vec::with_capacity(64 * 1024); + // Small: Window + Ping + { + let mut samples = Vec::with_capacity(15); + let mut bytes = 0u64; + let mut work_ops = 0u64; + let mut errors = 0u64; + // Warmup + for i in 0..200u32 { + buf.clear(); + ShareMsg::Window { stream: i, credit: 32768 }.encode(&mut buf); + let _ = black_box(kiri_share_proto::decode(&buf)); + buf.clear(); + ShareMsg::Ping(u64::from(i)).encode(&mut buf); + let _ = black_box(kiri_share_proto::decode(&buf)); + } + for _ in 0..15 { + let t0 = Instant::now(); + for i in 0..1000u32 { + buf.clear(); + ShareMsg::Window { stream: i, credit: 32768 }.encode(&mut buf); + if kiri_share_proto::decode(&buf).is_err() { errors += 1; } + bytes = buf.len() as u64; + buf.clear(); + ShareMsg::Ping(u64::from(i)).encode(&mut buf); + if kiri_share_proto::decode(&buf).is_err() { errors += 1; } + bytes += buf.len() as u64; + black_box(&buf); + work_ops += 2; + } + samples.push(t0.elapsed().as_secs_f64() * 1e6 / 1000.0); + } + emit_metric("kiri_share_proto_roundtrip_small", "latency", "small", "us", &samples, bytes, work_ops, errors); + } + // Heavy: 32 KiB Data + 32 KiB Chunk + { + let payload = vec![0x5Au8; 32 * 1024]; + let mut samples = Vec::with_capacity(15); + let mut bytes = 0u64; + let mut work_ops = 0u64; + let mut errors = 0u64; + // Warmup + for i in 0..50u32 { + buf.clear(); + ShareMsg::Data { stream: 1, data: &payload }.encode(&mut buf); + let _ = black_box(kiri_share_proto::decode(&buf)); + buf.clear(); + ShareMsg::Chunk { stream: 1, seq: i, fin: false, data: &payload }.encode(&mut buf); + let _ = black_box(kiri_share_proto::decode(&buf)); + } + for _ in 0..15 { + let t0 = Instant::now(); + for i in 0..500u32 { + buf.clear(); + ShareMsg::Data { stream: 1, data: &payload }.encode(&mut buf); + let mut total_b = buf.len() as u64; + match kiri_share_proto::decode(&buf) { + Ok(ShareMsg::Data { data, .. }) if data.len() == payload.len() => {} + _ => errors += 1, + } + buf.clear(); + ShareMsg::Chunk { stream: 1, seq: i, fin: false, data: &payload }.encode(&mut buf); + total_b += buf.len() as u64; + match kiri_share_proto::decode(&buf) { + Ok(ShareMsg::Chunk { data, .. }) if data.len() == payload.len() => {} + _ => errors += 1, + } + bytes = total_b; + black_box(&buf); + work_ops += 2; + } + samples.push(t0.elapsed().as_secs_f64() * 1e6 / 500.0); + } + emit_metric("kiri_share_proto_roundtrip_heavy", "latency", "heavy", "us", &samples, bytes, work_ops, errors); + } +} + +fn bench_image_archive() { + for (name, workload, n_layers, layer_kb, samples_n) in [ + ("image_archive_load_save_small", "small", 2usize, 64usize, 9usize), + ("image_archive_load_save_heavy", "heavy", 8usize, 256usize, 9usize), + ] { + let src_dir = temp_dir(&format!("arch-src-{workload}")); + let src_store = Store::open(&src_dir).unwrap(); + let mut layers = Vec::with_capacity(n_layers); + let mut total_layer_size = 0u64; + for l in 0..n_layers { + // Deterministic pseudo-random compressible/incompressible mix + let mut blob = vec![0u8; layer_kb * 1024]; + for (j, b) in blob.iter_mut().enumerate() { + *b = ((j.wrapping_mul(31) ^ l.wrapping_mul(17)) & 0xff) as u8; + } + let mut w = src_store.ingest().unwrap(); + w.write_all(&blob).unwrap(); + let (digest, size, _pin) = w.finish_pinned().unwrap(); + total_layer_size += size; + layers.push(Layer { digest, size, media_type: "application/vnd.oci.image.layer.v1.tar".into() }); + } + let cfg = json!({ + "architecture": "arm64", + "os": "linux", + "created": "2026-11-27T10:00:00Z", + "config": {"Env": ["PATH=/usr/bin:/bin"], "Cmd": ["/bin/sh"]}, + "rootfs": {"type": "layers", "diff_ids": layers.iter().map(|l| l.digest.clone()).collect::>()} + }); + let mut cw = src_store.ingest().unwrap(); + cw.write_all(&serde_json::to_vec(&cfg).unwrap()).unwrap(); + let (cfg_digest, _, _pin) = cw.finish_pinned().unwrap(); + let img = Image { + name: format!("bench/app:{workload}"), + digest: cfg_digest.clone(), + index_digest: None, + config_digest: cfg_digest, + layers, + size: total_layer_size, + platform: "linux/arm64".into(), + created: "2026-11-27T10:00:00Z".into(), + pulled_at: 1_764_000_000, + config: RunConfig::default(), + mirror: None, + }; + src_store.put_image(img.clone()).unwrap(); + + let mut samples = Vec::with_capacity(samples_n); + let mut archive_bytes = 0u64; + let mut work_ops = 0u64; + let mut errors = 0u64; + for s in 0..samples_n { + let dst_dir = temp_dir(&format!("arch-dst-{workload}-{s}")); + let dst_store = Store::open(&dst_dir).unwrap(); + let mut tar_buf = Vec::new(); + let t0 = Instant::now(); + let save_res = kiri_image::archive::save(&src_store, std::slice::from_ref(&img), &mut tar_buf); + let load_res = save_res.and_then(|()| kiri_image::archive::load(&dst_store, &tar_buf[..])); + let elapsed_us = t0.elapsed().as_secs_f64() * 1e6; + match load_res { + Ok(loaded) if loaded.len() == 1 && loaded[0].layers.len() == n_layers => { + archive_bytes = tar_buf.len() as u64; + black_box(&loaded); + work_ops += 1; + } + _ => errors += 1, + } + samples.push(elapsed_us); + let _ = std::fs::remove_dir_all(&dst_dir); + } + let _ = std::fs::remove_dir_all(&src_dir); + emit_metric(name, "latency", workload, "us", &samples, archive_bytes, work_ops, errors); + } +} + +fn bench_logfile_append() { + for (name, workload, n_lines, samples_n) in [ + ("logfile_append_throughput_small", "small", 200usize, 15usize), + ("logfile_append_throughput_heavy", "heavy", 10_000usize, 15usize), + ] { + // Build realistic 64-line chunks + let mut chunks: Vec> = Vec::new(); + let mut cur = Vec::with_capacity(8192); + for i in 0..n_lines { + let line = format!("2026-11-27T18:00:00Z INFO worker={} req={:06} latency_ms=12 status=200\n", i % 8, i); + cur.extend_from_slice(line.as_bytes()); + if (i + 1) % 32 == 0 || i + 1 == n_lines { + chunks.push(std::mem::take(&mut cur)); + } + } + let mut samples = Vec::with_capacity(samples_n); + let mut disk_bytes = 0u64; + let mut work_ops = 0u64; + let mut errors = 0u64; + // Warmup + { + let dir = temp_dir(&format!("log-{workload}-warm")); + let mut lg = Log::new(dir.clone(), &LogConfig::default()); + for (idx, c) in chunks.iter().enumerate() { + lg.append(Stream::Stdout, 1_764_260_000_000_000_000 + idx as u64 * 1000, c); + } + lg.flush(); + let _ = std::fs::remove_dir_all(&dir); + } + for s in 0..samples_n { + let dir = temp_dir(&format!("log-{workload}-{s}")); + let mut lg = Log::new(dir.clone(), &LogConfig::default()); + let (tx, rx) = std::sync::mpsc::channel(); + let _snap = lg.snapshot(Some(tx)); + let t0 = Instant::now(); + for (idx, c) in chunks.iter().enumerate() { + lg.append(Stream::Stdout, 1_764_260_000_000_000_000 + idx as u64 * 1000, c); + } + lg.flush(); + let elapsed_us = t0.elapsed().as_secs_f64() * 1e6; + let mut got = 0usize; + while rx.try_recv().is_ok() { + got += 1; + } + if got == n_lines { + work_ops += got as u64; + } else { + errors += 1; + } + disk_bytes = std::fs::metadata(dir.join("container.log")).map(|m| m.len()).unwrap_or(0); + samples.push(elapsed_us); + let _ = std::fs::remove_dir_all(&dir); + } + emit_metric(name, "latency", workload, "us", &samples, disk_bytes, work_ops, errors); + } +} + +#[ignore] +#[test] +fn run_daemon_bench() { + // 1. Small/idle fixture (5 containers, 5 images, 3 volumes, 2 networks, 100 log lines) + let small = start_server("small", 5, 5, 3, 2, 100); + // 2. Heavy/realistic fixture (100 containers, 150 images, 40 volumes, 15 networks, 5000 log lines) + let heavy = start_server("heavy", 100, 150, 40, 15, 5000); + + // HTTP/API benchmarks (contrasting small vs heavy) + bench_http_endpoint(&small.sock, "api_ping_keepalive_small", "latency", "small", "/_ping", 100, 15, |b| b == b"OK"); + bench_http_endpoint(&heavy.sock, "api_ping_keepalive_heavy", "latency", "heavy", "/_ping", 300, 15, |b| b == b"OK"); + + bench_http_endpoint(&small.sock, "api_info_poll_small", "latency", "small", "/info", 20, 15, |b| { + serde_json::from_slice::(b).is_ok_and(|v| v["Containers"].as_u64() == Some(5) && v["Images"].as_u64() == Some(5)) + }); + bench_http_endpoint(&heavy.sock, "api_info_poll_heavy", "latency", "heavy", "/info", 20, 15, |b| { + serde_json::from_slice::(b).is_ok_and(|v| v["Containers"].as_u64() == Some(100) && v["Images"].as_u64() == Some(150)) + }); + + bench_http_endpoint(&small.sock, "api_containers_list_small", "latency", "small", "/containers/json?all=1", 25, 15, |b| { + serde_json::from_slice::(b).is_ok_and(|v| v.as_array().is_some_and(|a| a.len() == 5)) + }); + bench_http_endpoint(&heavy.sock, "api_containers_list_heavy", "latency", "heavy", "/containers/json?all=1", 15, 15, |b| { + serde_json::from_slice::(b).is_ok_and(|v| v.as_array().is_some_and(|a| a.len() == 100)) + }); + + let filter_path = "/containers/json?all=1&filters=%7B%22name%22%3A%5B%22%5E%2F%3Fsvc-app-%5B0-9%5D%2B%24%22%5D%2C%22label%22%3A%5B%22env%3Dbench%22%5D%2C%22status%22%3A%5B%22running%22%5D%7D"; + bench_http_endpoint(&heavy.sock, "api_containers_filtered_heavy", "latency", "heavy", filter_path, 15, 15, |b| { + serde_json::from_slice::(b).is_ok_and(|v| v.as_array().is_some_and(|a| a.len() == 80)) + }); + + bench_http_endpoint(&small.sock, "api_images_list_small", "latency", "small", "/images/json", 25, 15, |b| { + serde_json::from_slice::(b).is_ok_and(|v| v.as_array().is_some_and(|a| a.len() == 5)) + }); + bench_http_endpoint(&heavy.sock, "api_images_list_heavy", "latency", "heavy", "/images/json", 15, 15, |b| { + serde_json::from_slice::(b).is_ok_and(|v| v.as_array().is_some_and(|a| a.len() == 150)) + }); + + let small_log_path = format!("/containers/{}/logs?stdout=1&stderr=1&tail=100×tamps=1", small.log_container_id); + let heavy_log_path = format!("/containers/{}/logs?stdout=1&stderr=1&tail=2000×tamps=1", heavy.log_container_id); + bench_http_endpoint(&small.sock, "api_logs_tail_stream_small", "latency", "small", &small_log_path, 15, 15, |b| b.len() > 5_000); + bench_http_endpoint(&heavy.sock, "api_logs_tail_stream_heavy", "latency", "heavy", &heavy_log_path, 5, 15, |b| b.len() > 150_000); + + // Exact 4-request UI refresh cycle (Connection: close per request, as client.rs does) + bench_ui_refresh_cycle(&small.sock, "api_ui_refresh_cycle_small", "small", 15); + bench_ui_refresh_cycle(&heavy.sock, "api_ui_refresh_cycle_heavy", "heavy", 15); + + // Concurrent lock contention / p99 tail latency + bench_concurrent_contention(&heavy.sock, &heavy.container_ids[0]); + + drop(small); + drop(heavy); + + // Compute, protocol, archive, and log ingestion benchmarks + bench_seccomp(); + bench_kiri_proto(); + bench_kiri_share_proto(); + bench_image_archive(); + bench_logfile_append(); +} diff --git a/crates/kiri/src/daemon/hostetc.rs b/crates/kiri/src/daemon/hostetc.rs index aa0b86938..de0665d0e 100644 --- a/crates/kiri/src/daemon/hostetc.rs +++ b/crates/kiri/src/daemon/hostetc.rs @@ -59,8 +59,9 @@ fn file_in(dir: &Path, name: &str, who: &Who) -> io::Result { let path = dir.join(name); let text = match name { // Made once and kept: a machine-id that changed would not be one. - "machine-id" => match std::fs::read_to_string(&path) { - Ok(id) if is_machine_id(&id) => return Ok(path), + // Only trust an existing regular file (never follow a container-planted symlink). + "machine-id" => match std::fs::symlink_metadata(&path).ok().filter(|m| m.file_type().is_file()).and_then(|_| std::fs::read_to_string(&path).ok()) { + Some(id) if is_machine_id(&id) => return Ok(path), _ => format!("{}\n", super::engine::random_hex(16)), }, "timezone" => format!("{}\n", zone_of(std::fs::read_link("/etc/localtime").ok().as_deref())), @@ -70,16 +71,14 @@ fn file_in(dir: &Path, name: &str, who: &Who) -> io::Result { Ok(path) } -/// Writes `text` unless the file says it already, so a mount does not -/// change a file other containers have open for nothing. +/// Writes `text` unless `path` is already a regular file with the same text, +/// replacing any symlink or modified file atomically without following links. fn put(path: &Path, text: &str) -> io::Result<()> { - if std::fs::read_to_string(path).is_ok_and(|old| old == text) { + let is_regular = std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_file()); + if is_regular && std::fs::read_to_string(path).is_ok_and(|old| old == text) { return Ok(()); } - if let Some(dir) = path.parent() { - std::fs::create_dir_all(dir)?; - } - std::fs::write(path, text) + super::write_atomic_mode(path, text.as_bytes(), 0o644) } fn is_machine_id(id: &str) -> bool { @@ -190,4 +189,29 @@ mod tests { assert!(file_in(&dir, "shadow", &me()).is_err()); std::fs::remove_dir_all(&dir).unwrap(); } + + #[test] + fn planted_symlinks_are_replaced_without_overwriting_targets() { + let base = std::env::temp_dir().join(format!("kiri-hostetc-symlink-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let dir = base.join("etc"); + std::fs::create_dir_all(&dir).unwrap(); + let canary_passwd = base.join("canary-passwd"); + let canary_mid = base.join("canary-machine-id"); + std::fs::write(&canary_passwd, "do-not-overwrite-passwd").unwrap(); + std::fs::write(&canary_mid, "do-not-overwrite-machine-id").unwrap(); + std::os::unix::fs::symlink(&canary_passwd, dir.join("passwd")).unwrap(); + std::os::unix::fs::symlink(&canary_mid, dir.join("machine-id")).unwrap(); + + file_in(&dir, "passwd", &me()).unwrap(); + file_in(&dir, "machine-id", &me()).unwrap(); + + assert_eq!(std::fs::read_to_string(&canary_passwd).unwrap(), "do-not-overwrite-passwd"); + assert_eq!(std::fs::read_to_string(&canary_mid).unwrap(), "do-not-overwrite-machine-id"); + assert!(std::fs::symlink_metadata(dir.join("passwd")).unwrap().file_type().is_file()); + assert!(std::fs::symlink_metadata(dir.join("machine-id")).unwrap().file_type().is_file()); + assert!(std::fs::read_to_string(dir.join("passwd")).unwrap().starts_with("root:x:0:0:")); + assert!(is_machine_id(&std::fs::read_to_string(dir.join("machine-id")).unwrap())); + let _ = std::fs::remove_dir_all(&base); + } } diff --git a/crates/kiri/src/daemon/hostopts.rs b/crates/kiri/src/daemon/hostopts.rs index 764f9bc48..72f7a8ea6 100644 --- a/crates/kiri/src/daemon/hostopts.rs +++ b/crates/kiri/src/daemon/hostopts.rs @@ -147,7 +147,7 @@ pub fn guest_lines(opts: &Value, net_host: bool) -> Result, String> for (key, value) in map { let value = value.as_str().map(str::to_owned).unwrap_or_else(|| value.to_string()); let (ns, path) = sysctl(key, net_host)?; - if value.contains(['\t', '\n']) { + if value.contains(['\t', '\n', '\r', '\0']) { return Err(format!("invalid value for sysctl {key:?}")); } out.push(format!("sysctl\t{ns}\t{path}\t{value}")); @@ -161,7 +161,7 @@ pub fn guest_lines(opts: &Value, net_host: bool) -> Result, String> if !p.starts_with('/') { return Err(format!("{p} is not an absolute path")); } - if p.contains(['\t', '\n']) || p.split('/').any(|c| c == "..") { + if p.contains(['\t', '\n', '\r', '\0']) || p.split('/').any(|c| c == "..") { return Err(format!("invalid device path {p:?}")); } } @@ -175,7 +175,7 @@ pub fn guest_lines(opts: &Value, net_host: bool) -> Result, String> out.push(format!("devrule\t{t}\t{major}\t{minor}\t{perms}")); } for g in strings(&opts["GroupAdd"]) { - if g.is_empty() || g.contains(['\t', '\n', ':']) { + if g.is_empty() || g.contains(['\t', '\n', '\r', '\0', ':']) { return Err(format!("invalid group {g:?}")); } out.push(format!("group\t{g}")); diff --git a/crates/kiri/src/daemon/http.rs b/crates/kiri/src/daemon/http.rs index 70f389a07..9891baf5f 100644 --- a/crates/kiri/src/daemon/http.rs +++ b/crates/kiri/src/daemon/http.rs @@ -4,7 +4,7 @@ //! one thread per connection and never parses more than it needs. use std::cell::Cell; -use std::io::{self, BufRead, BufReader, Read, Write}; +use std::io::{self, BufRead, BufReader, IoSlice, Read, Write}; use std::os::unix::net::UnixStream; /// API version this daemon speaks. The Docker CLI negotiates down to it. @@ -152,13 +152,60 @@ pub const HEADER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3 /// `SO_RCVTIMEO` applies to the underlying kernel socket on both Linux and /// macOS, so clearing it here clears it for cloned handles (`w`, /// `forward_stdin`, USB passthrough) as well. +/// Bounds the total elapsed time across all `read`/`fill_buf` syscalls on a +/// `BufReader` so a Slowloris peer trickling 1 byte per read +/// cannot keep extending `SO_RCVTIMEO` indefinitely. +struct DeadlineBuf<'a> { + inner: &'a mut BufReader, + deadline: Option, +} + +impl DeadlineBuf<'_> { + fn apply_remaining(&self) -> io::Result<()> { + let Some(dl) = self.deadline else { return Ok(()) }; + let Some(rem) = dl.checked_duration_since(std::time::Instant::now()).filter(|d| !d.is_zero()) else { + return Err(io::Error::new(io::ErrorKind::TimedOut, "request header deadline exceeded")); + }; + self.inner.get_ref().set_read_timeout(Some(rem)) + } +} + +impl Read for DeadlineBuf<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if self.inner.buffer().is_empty() { + self.apply_remaining()?; + } + self.inner.read(buf) + } +} + +impl BufRead for DeadlineBuf<'_> { + fn fill_buf(&mut self) -> io::Result<&[u8]> { + if self.inner.buffer().is_empty() { + self.apply_remaining()?; + } + self.inner.fill_buf() + } + + fn consume(&mut self, amt: usize) { + self.inner.consume(amt); + } +} + pub fn read_request_with_timeout( r: &mut BufReader, timeout: std::time::Duration, stream: impl Fn(&str, &str) -> bool, ) -> io::Result> { - r.get_ref().set_read_timeout(Some(timeout))?; - let res = read_request(r, stream); + let deadline = std::time::Instant::now() + timeout; + // When the buffer is empty (the common non-pipelined case), DeadlineBuf + // sets SO_RCVTIMEO to the remaining deadline before the first socket read, + // avoiding a redundant setsockopt syscall. When pipelined bytes are already + // buffered, set the timeout upfront in case the body still needs a socket read. + if !r.buffer().is_empty() { + r.get_ref().set_read_timeout(Some(timeout))?; + } + let res = read_request_deadline(r, Some(deadline), stream); if matches!(res, Ok(Some(_))) { r.get_ref().set_read_timeout(None)?; } @@ -169,13 +216,22 @@ pub fn read_request_with_timeout( /// When `stream(method, path)` is true the body stays unread: the handler /// reads it through [`Body`]. pub fn read_request(r: &mut BufReader, stream: impl Fn(&str, &str) -> bool) -> io::Result> { + read_request_deadline(r, None, stream) +} + +fn read_request_deadline( + r: &mut BufReader, + deadline: Option, + stream: impl Fn(&str, &str) -> bool, +) -> io::Result> { SERVING.with(|s| *s.borrow_mut() = (String::new(), String::new())); CLOSING.with(|c| c.set(false)); PENDING_CONTINUE.with(|c| c.set(false)); - // The request line and headers are read through a cap, so a client - // cannot exhaust memory with an endless line. The body is read after. + // The request line and headers are read through a cap and an absolute + // deadline, so a client cannot exhaust memory or pin a worker with an + // endless or trickled header. The body is read after. let (method, path, api_version, query, headers, http10) = { - let mut head = (&mut *r).take(MAX_HEAD); + let mut head = DeadlineBuf { inner: r, deadline }.take(MAX_HEAD); let mut line = String::new(); if head.read_line(&mut line)? == 0 { return Ok(None); @@ -805,35 +861,108 @@ pub fn current_serving() -> (String, String) { SERVING.with(|s| s.borrow().clone()) } -fn head(w: &mut impl Write, status: u16, extra: &str) -> io::Result<()> { +fn write_all_vectored(w: &mut impl Write, slices: &[&[u8]]) -> io::Result<()> { + let mut idx = 0; + let mut off = 0; + let mut io_bufs = [IoSlice::new(&[]); 4]; + while idx < slices.len() { + let mut count = 0; + for (i, &s) in slices[idx..].iter().enumerate() { + let chunk = if i == 0 { &s[off..] } else { s }; + if !chunk.is_empty() { + io_bufs[count] = IoSlice::new(chunk); + count += 1; + } + } + if count == 0 { + return Ok(()); + } + match w.write_vectored(&io_bufs[..count]) { + Ok(0) => return Err(io::Error::new(io::ErrorKind::WriteZero, "failed to write whole vectored buffer")), + Ok(mut n) => { + while n > 0 && idx < slices.len() { + let rem = slices[idx].len() - off; + if n >= rem { + n -= rem; + idx += 1; + off = 0; + } else { + off += n; + n = 0; + } + } + } + Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, + Err(e) => return Err(e), + } + } + Ok(()) +} + +fn format_head(buf: &mut Vec, status: u16, extra: &str) { if status >= 400 { note_failure(status); } // A response that names its own Connection (an upgrade, `CLOSE`) keeps it. let closing = if (CLOSING.with(std::cell::Cell::get) || PENDING_CONTINUE.with(std::cell::Cell::get)) && !extra.contains("Connection:") { CLOSE } else { "" }; - write!( - w, + let _ = write!( + buf, "HTTP/1.1 {status} {}\r\nApi-Version: {API_VERSION}\r\nDocker-Experimental: false\r\nOstype: linux\r\nServer: Kiri/{} (linux)\r\n{extra}{closing}\r\n", reason(status), env!("CARGO_PKG_VERSION") - ) + ); +} + +fn head(w: &mut impl Write, status: u16, extra: &str) -> io::Result<()> { + let mut buf = Vec::with_capacity(160 + extra.len()); + format_head(&mut buf, status, extra); + w.write_all(&buf) } pub fn respond(w: &mut impl Write, status: u16, content_type: &str, body: &[u8]) -> io::Result<()> { - let extra = if status == 204 || status == 304 { - String::new() + let mut hdr = Vec::with_capacity(224); + if status == 204 || status == 304 { + format_head(&mut hdr, status, ""); } else { - format!("Content-Type: {content_type}\r\nContent-Length: {}\r\n", body.len()) - }; - head(w, status, &extra)?; - w.write_all(body)?; + if status >= 400 { + note_failure(status); + } + let closing = if CLOSING.with(std::cell::Cell::get) || PENDING_CONTINUE.with(std::cell::Cell::get) { CLOSE } else { "" }; + let _ = write!( + hdr, + "HTTP/1.1 {status} {}\r\nApi-Version: {API_VERSION}\r\nDocker-Experimental: false\r\nOstype: linux\r\nServer: Kiri/{} (linux)\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\n{closing}\r\n", + reason(status), + env!("CARGO_PKG_VERSION"), + body.len(), + ); + } + if body.is_empty() { + w.write_all(&hdr)?; + } else { + write_all_vectored(w, &[&hdr, body])?; + } w.flush() } /// `respond` plus extra header lines, each ending in CRLF. pub fn respond_with(w: &mut impl Write, status: u16, content_type: &str, extra: &str, body: &[u8]) -> io::Result<()> { - head(w, status, &format!("Content-Type: {content_type}\r\nContent-Length: {}\r\n{extra}", body.len()))?; - w.write_all(body)?; + if status >= 400 { + note_failure(status); + } + let closing = if (CLOSING.with(std::cell::Cell::get) || PENDING_CONTINUE.with(std::cell::Cell::get)) && !extra.contains("Connection:") { CLOSE } else { "" }; + let mut hdr = Vec::with_capacity(224 + extra.len()); + let _ = write!( + hdr, + "HTTP/1.1 {status} {}\r\nApi-Version: {API_VERSION}\r\nDocker-Experimental: false\r\nOstype: linux\r\nServer: Kiri/{} (linux)\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\n{extra}{closing}\r\n", + reason(status), + env!("CARGO_PKG_VERSION"), + body.len(), + ); + if body.is_empty() { + w.write_all(&hdr)?; + } else { + write_all_vectored(w, &[&hdr, body])?; + } w.flush() } @@ -884,9 +1013,13 @@ pub fn chunk(w: &mut impl Write, data: &[u8]) -> io::Result<()> { if data.is_empty() { return Ok(()); } - write!(w, "{:x}\r\n", data.len())?; - w.write_all(data)?; - w.write_all(b"\r\n")?; + let mut len_buf = [0u8; 20]; + let n = { + let mut cur = io::Cursor::new(&mut len_buf[..]); + let _ = write!(cur, "{:x}\r\n", data.len()); + cur.position() as usize + }; + write_all_vectored(w, &[&len_buf[..n], data, b"\r\n"])?; w.flush() } @@ -929,8 +1062,7 @@ pub fn mux_frame(w: &mut impl Write, stream: u8, data: &[u8]) -> io::Result<()> let mut header = [0u8; 8]; header[0] = stream; header[4..].copy_from_slice(&(data.len() as u32).to_be_bytes()); - w.write_all(&header)?; - w.write_all(data)?; + write_all_vectored(w, &[&header, data])?; w.flush() } @@ -1640,5 +1772,21 @@ mod tests { let req = read_request_with_timeout(&mut r, header_timeout, |_, _| false).unwrap().unwrap(); assert_eq!(req.path, "/_ping"); assert_eq!(r.get_ref().read_timeout().unwrap(), None); + + // 5. Slowloris: trickling 1 byte at a time must still hit the total header deadline. + let (mut client, server) = UnixStream::pair().unwrap(); + let mut r = BufReader::new(server); + let trickle = std::thread::spawn(move || { + let payload = b"GET /_ping HTTP/1.1\r\nHost: d\r\nX-Slow: 1\r\n\r\n"; + for &b in payload { + if client.write_all(&[b]).is_err() { + break; + } + std::thread::sleep(Duration::from_millis(25)); + } + }); + let err = read_request_with_timeout(&mut r, Duration::from_millis(120), |_, _| false).unwrap_err(); + assert!(matches!(err.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut), "expected absolute header deadline, got {err:?}"); + let _ = trickle.join(); } } diff --git a/crates/kiri/src/daemon/logfile.rs b/crates/kiri/src/daemon/logfile.rs index e8abe216d..94a8a86bf 100644 --- a/crates/kiri/src/daemon/logfile.rs +++ b/crates/kiri/src/daemon/logfile.rs @@ -156,6 +156,32 @@ pub fn dir(root: &Path, id: &str) -> PathBuf { root.join("containers").join(id) } +/// Fast SWAR search for `b'\n'` within `haystack` (8 bytes per step, zero dependencies). +#[inline] +fn find_nl(haystack: &[u8]) -> Option { + const LO: u64 = 0x0101_0101_0101_0101; + const HI: u64 = 0x8080_8080_8080_8080; + const NL: u64 = 0x0a0a_0a0a_0a0a_0a0a; + let mut i = 0; + let chunks_end = haystack.len() & !7; + while i < chunks_end { + let word = u64::from_le_bytes(haystack[i..i + 8].try_into().expect("8 bytes")); + let x = word ^ NL; + let has_zero = x.wrapping_sub(LO) & !x & HI; + if has_zero != 0 { + return Some(i + (has_zero.trailing_zeros() as usize >> 3)); + } + i += 8; + } + while i < haystack.len() { + if haystack[i] == b'\n' { + return Some(i); + } + i += 1; + } + None +} + /// Splits a chunk of output into records: one per line (with its newline), /// a trailing piece without one, and lines over 16 KiB in pieces. pub fn split(data: &[u8]) -> impl Iterator { @@ -164,7 +190,8 @@ pub fn split(data: &[u8]) -> impl Iterator { if rest.is_empty() { return None; } - let end = rest.iter().position(|&b| b == b'\n').map_or(rest.len(), |i| i + 1).min(MAX_LINE); + let window = &rest[..rest.len().min(MAX_LINE)]; + let end = find_nl(window).map_or(window.len(), |i| i + 1); let (line, more) = rest.split_at(end); rest = more; Some(line) @@ -173,11 +200,15 @@ pub fn split(data: &[u8]) -> impl Iterator { fn encode(out: &mut Vec, stream: Stream, time: u64, data: &[u8]) { let len = (9 + data.len()) as u32; - out.extend_from_slice(&len.to_be_bytes()); - out.push(stream as u8); - out.extend_from_slice(&time.to_be_bytes()); + let len_bytes = len.to_be_bytes(); + let mut header = [0u8; 13]; + header[..4].copy_from_slice(&len_bytes); + header[4] = stream as u8; + header[5..13].copy_from_slice(&time.to_be_bytes()); + out.reserve(17 + data.len()); + out.extend_from_slice(&header); out.extend_from_slice(data); - out.extend_from_slice(&len.to_be_bytes()); + out.extend_from_slice(&len_bytes); } fn stream_of(b: u8) -> Option { @@ -273,10 +304,22 @@ impl Log { if self.gone { return; } + if !self.off && self.ring.is_none() && self.buf.capacity() < FLUSH_BYTES { + self.buf.reserve(FLUSH_BYTES + 256 - self.buf.len()); + } for line in split(data) { - if !self.followers.is_empty() { - let rec = Record { stream, time, data: line.to_vec() }; - self.followers.retain(|tx| tx.send(rec.clone()).is_ok()); + match self.followers.len() { + 0 => {} + 1 => { + let rec = Record { stream, time, data: line.to_vec() }; + if self.followers[0].send(rec).is_err() { + self.followers.clear(); + } + } + _ => { + let rec = Record { stream, time, data: line.to_vec() }; + self.followers.retain(|tx| tx.send(rec.clone()).is_ok()); + } } if self.off { continue; @@ -298,7 +341,7 @@ impl Log { encode(&mut self.buf, stream, time, line); self.size += len; } - if self.buf.len() >= FLUSH_BYTES || self.flushed.elapsed() >= FLUSH_AFTER { + if !self.buf.is_empty() && (self.buf.len() >= FLUSH_BYTES || self.flushed.elapsed() >= FLUSH_AFTER) { self.flush(); } } @@ -374,13 +417,32 @@ impl Log { /// `records` in a file of their own, deleted as soon as it is open. fn memory_file(&self, records: &[u8]) -> io::Result { + use std::sync::atomic::{AtomicU64, Ordering}; + static SEQ: AtomicU64 = AtomicU64::new(0); fs::create_dir_all(&self.dir)?; - let p = self.dir.join(format!("{FILE}.memory")); - let mut f = OpenOptions::new().create(true).truncate(true).write(true).read(true).open(&p)?; - let _ = fs::remove_file(&p); - f.write_all(records)?; - io::Seek::seek(&mut f, io::SeekFrom::Start(0))?; - Ok(f) + let pid = std::process::id(); + for _ in 0..16 { + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let p = self.dir.join(format!(".{FILE}.{pid}.{seq}.memory")); + let mut opts = OpenOptions::new(); + opts.create_new(true).write(true).read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + match opts.open(&p) { + Ok(mut f) => { + let _ = fs::remove_file(&p); + f.write_all(records)?; + io::Seek::seek(&mut f, io::SeekFrom::Start(0))?; + return Ok(f); + } + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e), + } + } + Err(io::Error::new(io::ErrorKind::AlreadyExists, "could not create temporary log file")) } fn file_path(&self, i: u32) -> PathBuf { @@ -473,11 +535,17 @@ impl Snapshot { if left == 0 { break; } - let starts = match back_starts(f, *len, left) { - Some(s) => s, - // Not walkable backwards: read it forwards. - None => forward_starts(f, *len), - }; + if let Some((count, earliest)) = back_tail(f, *len, left) { + if count >= left { + start = (i, earliest); + break 'files; + } + left -= count; + start = (i, 0); + continue; + } + // Not walkable backwards: read it forwards. + let starts = forward_starts(f, *len); if starts.len() >= left { start = (i, starts[starts.len() - left]); break 'files; @@ -493,9 +561,9 @@ impl Snapshot { const BLOCK: u64 = 64 << 10; -/// The start offsets of up to the last `want` records of a file, in file -/// order; `None` if a length does not add up. -fn back_starts(f: &File, len: u64, want: usize) -> Option> { +/// `(count, earliest_start)` of up to the last `want` records of a file without +/// allocating a start-offset vector; `None` if a length does not add up. +fn back_tail(f: &File, len: u64, want: usize) -> Option<(usize, u64)> { let mut block: Vec = Vec::new(); let mut block_at = 0u64; let mut read_u32 = |pos: u64| -> Option { @@ -509,9 +577,9 @@ fn back_starts(f: &File, len: u64, want: usize) -> Option> { let i = (pos - block_at) as usize; Some(u32::from_be_bytes(block[i..i + 4].try_into().ok()?)) }; - let mut starts = Vec::new(); + let mut count = 0usize; let mut pos = len; - while pos > 0 && starts.len() < want { + while pos > 0 && count < want { if pos < 8 { return None; } @@ -523,11 +591,10 @@ fn back_starts(f: &File, len: u64, want: usize) -> Option> { if read_u32(start)? != n { return None; } - starts.push(start); pos = start; + count += 1; } - starts.reverse(); - Some(starts) + Some((count, pos)) } fn forward_starts(f: &File, len: u64) -> Vec { @@ -553,10 +620,10 @@ pub struct Reader { pos: u64, } -impl Iterator for Reader { - type Item = Record; - - fn next(&mut self) -> Option { +impl Reader { + /// Reads the next record's payload into `buf` (reusing its allocation) and + /// returns `(stream, time_ns)`, avoiding a heap allocation per log line. + pub fn next_into(&mut self, buf: &mut Vec) -> Option<(Stream, u64)> { loop { if self.cur.is_none() { if self.files.is_empty() { @@ -571,10 +638,10 @@ impl Iterator for Reader { self.cur = Some((r.take(len.saturating_sub(off)), len)); } let (r, _) = self.cur.as_mut().expect("set"); - match read_record(r) { - Some(rec) => { - self.pos += 17 + rec.data.len() as u64; - return Some(rec); + match read_record_into(r, buf) { + Some((stream, time)) => { + self.pos += 17 + buf.len() as u64; + return Some((stream, time)); } // The end of this file, or a torn record: on to the next. None => self.cur = None, @@ -583,7 +650,17 @@ impl Iterator for Reader { } } -fn read_record(r: &mut impl Read) -> Option { +impl Iterator for Reader { + type Item = Record; + + fn next(&mut self) -> Option { + let mut data = Vec::new(); + let (stream, time) = self.next_into(&mut data)?; + Some(Record { stream, time, data }) + } +} + +fn read_record_into(r: &mut impl Read, buf: &mut Vec) -> Option<(Stream, u64)> { let mut head = [0u8; 13]; r.read_exact(&mut head).ok()?; let n = u32::from_be_bytes(head[..4].try_into().ok()?); @@ -592,11 +669,12 @@ fn read_record(r: &mut impl Read) -> Option { } let stream = stream_of(head[4])?; let time = u64::from_be_bytes(head[5..13].try_into().ok()?); - let mut data = vec![0u8; n as usize - 9]; - r.read_exact(&mut data).ok()?; + buf.clear(); + buf.resize(n as usize - 9, 0); + r.read_exact(buf).ok()?; let mut tail = [0u8; 4]; r.read_exact(&mut tail).ok()?; - (u32::from_be_bytes(tail) == n).then_some(Record { stream, time, data }) + (u32::from_be_bytes(tail) == n).then_some((stream, time)) } /// `since`/`until` as the CLI sends them: Unix seconds with an optional diff --git a/crates/kiri/src/daemon/mirror.rs b/crates/kiri/src/daemon/mirror.rs index 41acb1876..2b0b6776d 100644 --- a/crates/kiri/src/daemon/mirror.rs +++ b/crates/kiri/src/daemon/mirror.rs @@ -555,6 +555,47 @@ fn find_load_slot(nonce: &str) -> Option> { LOADS.lock().unwrap_or_else(|e| e.into_inner()).as_ref()?.get(nonce).cloned() } +const MIRROR_HEADER_DEADLINE: Duration = Duration::from_secs(10); +const MIRROR_BODY_TIMEOUT: Duration = Duration::from_secs(30); + +/// Bounds total elapsed time while reading HTTP request headers on a mirror +/// TCP connection so an unauthenticated Slowloris client cannot pin workers. +struct DeadlineTcpBuf<'a> { + inner: &'a mut BufReader, + deadline: std::time::Instant, +} + +impl DeadlineTcpBuf<'_> { + fn apply_remaining(&self) -> io::Result<()> { + let Some(rem) = self.deadline.checked_duration_since(std::time::Instant::now()).filter(|d| !d.is_zero()) else { + return Err(io::Error::new(io::ErrorKind::TimedOut, "mirror header deadline exceeded")); + }; + self.inner.get_ref().set_read_timeout(Some(rem)) + } +} + +impl Read for DeadlineTcpBuf<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if self.inner.buffer().is_empty() { + self.apply_remaining()?; + } + self.inner.read(buf) + } +} + +impl BufRead for DeadlineTcpBuf<'_> { + fn fill_buf(&mut self) -> io::Result<&[u8]> { + if self.inner.buffer().is_empty() { + self.apply_remaining()?; + } + self.inner.fill_buf() + } + + fn consume(&mut self, amt: usize) { + self.inner.consume(amt); + } +} + fn serve(listener: TcpListener, engine: Weak) { for conn in listener.incoming() { let Ok(conn) = conn else { continue }; @@ -568,7 +609,8 @@ fn serve(listener: TcpListener, engine: Weak) { let guard = WorkerGuard; let _ = std::thread::Builder::new().name("kiri-build-mirror".into()).spawn(move || { let _guard = guard; - let _ = conn.set_read_timeout(Some(Duration::from_secs(30))); + let _ = conn.set_read_timeout(Some(MIRROR_HEADER_DEADLINE)); + let _ = conn.set_write_timeout(Some(MIRROR_BODY_TIMEOUT)); let _ = answer(conn, &engine); }); } @@ -668,87 +710,143 @@ fn percent_decode(s: &str) -> String { /// One request, then the connection closes. fn answer(conn: TcpStream, engine: &Engine) -> io::Result<()> { + answer_with_header_deadline(conn, engine, MIRROR_HEADER_DEADLINE) +} + +fn answer_with_header_deadline(conn: TcpStream, engine: &Engine, header_deadline: Duration) -> io::Result<()> { let mut w = conn.try_clone()?; let mut r = BufReader::new(conn); - answer_stream(&mut r, &mut w, engine) + let deadline = std::time::Instant::now() + header_deadline; + let res = answer_stream_with(&mut r, &mut w, engine, Some(deadline)); + res } +#[cfg(test)] fn answer_stream(r: &mut R, w: &mut W, engine: &Engine) -> io::Result<()> { + answer_stream_inner(r, w, engine, None) +} + +fn answer_stream_with(r: &mut BufReader, w: &mut TcpStream, engine: &Engine, header_deadline: Option) -> io::Result<()> { + let head = |w: &mut TcpStream, status: &str, extra: &str, len: u64| write!(w, "HTTP/1.1 {status}\r\nConnection: close\r\nContent-Length: {len}\r\n{extra}\r\n"); + let parsed = if let Some(deadline) = header_deadline { + let mut dl = DeadlineTcpBuf { inner: r, deadline }; + let res = read_request_head(&mut dl, w, head)?; + let _ = dl.inner.get_ref().set_read_timeout(Some(MIRROR_BODY_TIMEOUT)); + res + } else { + read_request_head(r, w, head)? + }; + let Some((method, target, framing, expect_continue)) = parsed else { + return Ok(()); + }; + dispatch_request(r, w, engine, &method, &target, framing, expect_continue) +} + +#[cfg(test)] +fn answer_stream_inner(r: &mut R, w: &mut W, engine: &Engine, _unused: Option<()>) -> io::Result<()> { let head = |w: &mut W, status: &str, extra: &str, len: u64| write!(w, "HTTP/1.1 {status}\r\nConnection: close\r\nContent-Length: {len}\r\n{extra}\r\n"); - let (method, target, framing, expect_continue) = { - let mut head_reader = (&mut *r).take(16 << 10); - let mut raw_line = Vec::new(); - if head_reader.read_until(b'\n', &mut raw_line)? == 0 { - return Ok(()); + let Some((method, target, framing, expect_continue)) = read_request_head(r, w, head)? else { + return Ok(()); + }; + dispatch_request(r, w, engine, &method, &target, framing, expect_continue) +} + +fn read_request_head( + r: &mut R, + w: &mut W, + head: impl Fn(&mut W, &str, &str, u64) -> io::Result<()>, +) -> io::Result> { + let mut head_reader = (&mut *r).take(16 << 10); + let mut raw_line = Vec::new(); + if head_reader.read_until(b'\n', &mut raw_line)? == 0 { + return Ok(None); + } + let Ok(line) = std::str::from_utf8(&raw_line) else { + head(w, "400 Bad Request", "", 0)?; + w.flush()?; + return Ok(None); + }; + if !line.ends_with('\n') { + head(w, "400 Bad Request", "", 0)?; + w.flush()?; + return Ok(None); + } + let mut parts = line.split_whitespace(); + let (method, target) = (parts.next().unwrap_or_default().to_owned(), parts.next().unwrap_or_default().to_owned()); + let mut content_length: Option = None; + let mut chunked = false; + let mut expect_continue = false; + let mut saw_end = false; + loop { + let mut raw_h = Vec::new(); + if head_reader.read_until(b'\n', &mut raw_h)? == 0 { + break; } - let Ok(line) = std::str::from_utf8(&raw_line) else { + let Ok(h) = std::str::from_utf8(&raw_h) else { head(w, "400 Bad Request", "", 0)?; - return w.flush(); + w.flush()?; + return Ok(None); }; - if !line.ends_with('\n') { + if !h.ends_with('\n') { head(w, "400 Bad Request", "", 0)?; - return w.flush(); + w.flush()?; + return Ok(None); } - let mut parts = line.split_whitespace(); - let (method, target) = (parts.next().unwrap_or_default().to_owned(), parts.next().unwrap_or_default().to_owned()); - let mut content_length: Option = None; - let mut chunked = false; - let mut expect_continue = false; - let mut saw_end = false; - loop { - let mut raw_h = Vec::new(); - if head_reader.read_until(b'\n', &mut raw_h)? == 0 { - break; - } - let Ok(h) = std::str::from_utf8(&raw_h) else { - head(w, "400 Bad Request", "", 0)?; - return w.flush(); - }; - if !h.ends_with('\n') { - head(w, "400 Bad Request", "", 0)?; - return w.flush(); - } - if h.trim().is_empty() { - saw_end = true; - break; - } - if let Some((k, v)) = h.split_once(':') { - let k = k.trim(); - let v = v.trim(); - if k.eq_ignore_ascii_case("content-length") { - let Ok(parsed) = v.parse::() else { - head(w, "400 Bad Request", "", 0)?; - return w.flush(); - }; - if content_length.is_some_and(|prev| prev != parsed) { - head(w, "400 Bad Request", "", 0)?; - return w.flush(); - } - content_length = Some(parsed); - } else if k.eq_ignore_ascii_case("transfer-encoding") && v.to_ascii_lowercase().contains("chunked") { - chunked = true; - } else if k.eq_ignore_ascii_case("expect") && v.to_ascii_lowercase().contains("100-continue") { - expect_continue = true; + if h.trim().is_empty() { + saw_end = true; + break; + } + if let Some((k, v)) = h.split_once(':') { + let k = k.trim(); + let v = v.trim(); + if k.eq_ignore_ascii_case("content-length") { + let Ok(parsed) = v.parse::() else { + head(w, "400 Bad Request", "", 0)?; + w.flush()?; + return Ok(None); + }; + if content_length.is_some_and(|prev| prev != parsed) { + head(w, "400 Bad Request", "", 0)?; + w.flush()?; + return Ok(None); } + content_length = Some(parsed); + } else if k.eq_ignore_ascii_case("transfer-encoding") && v.to_ascii_lowercase().contains("chunked") { + chunked = true; + } else if k.eq_ignore_ascii_case("expect") && v.to_ascii_lowercase().contains("100-continue") { + expect_continue = true; } } - if !saw_end || (chunked && content_length.is_some()) { - head(w, "400 Bad Request", "", 0)?; - return w.flush(); - } - let framing = if chunked { - BodyFraming::Chunked - } else if let Some(n) = content_length.filter(|n| *n > 0) { - BodyFraming::Length(n) - } else { - BodyFraming::None - }; - (method, target, framing, expect_continue) + } + if !saw_end || (chunked && content_length.is_some()) { + head(w, "400 Bad Request", "", 0)?; + w.flush()?; + return Ok(None); + } + let framing = if chunked { + BodyFraming::Chunked + } else if let Some(n) = content_length.filter(|n| *n > 0) { + BodyFraming::Length(n) + } else { + BodyFraming::None }; - let (path, query) = target.split_once('?').unwrap_or((&target, "")); + Ok(Some((method, target, framing, expect_continue))) +} + +fn dispatch_request( + r: &mut R, + w: &mut W, + engine: &Engine, + method: &str, + target: &str, + framing: BodyFraming, + expect_continue: bool, +) -> io::Result<()> { + let head = |w: &mut W, status: &str, extra: &str, len: u64| write!(w, "HTTP/1.1 {status}\r\nConnection: close\r\nContent-Length: {len}\r\n{extra}\r\n"); + let (path, query) = target.split_once('?').unwrap_or((target, "")); // Registry v2 ping (`GET /v2/` / `HEAD /v2/`). - if matches!(method.as_str(), "GET" | "HEAD") && (path == "/v2/" || path == "/v2") { + if matches!(method, "GET" | "HEAD") && (path == "/v2/" || path == "/v2") { let body = if method == "GET" { b"{}".as_slice() } else { b"".as_slice() }; head(w, "200 OK", "Docker-Distribution-Api-Version: registry/2.0\r\nContent-Type: application/json\r\n", body.len() as u64)?; w.write_all(body)?; @@ -758,7 +856,7 @@ fn answer_stream(r: &mut R, w: &mut W, engine: &Engine) -> // Ephemeral one-shot image upload for BuildKit's `docker` driver. if let Some(rest) = path.strip_prefix("/v2/load/") { if let Some((nonce, sub)) = rest.split_once("/image/") { - return handle_load(engine, nonce, sub, &method, query, framing, expect_continue, r, w); + return handle_load(engine, nonce, sub, method, query, framing, expect_continue, r, w); } head(w, "404 Not Found", "", 0)?; return w.flush(); @@ -1164,9 +1262,24 @@ fn manifest(store: &kiri_image::Store, i: &Image) -> Option<(Vec, String)> { Some((bytes, digest)) } +fn ct_eq(a: &[u8], b: &[u8]) -> bool { + if a.len() != b.len() { + return false; + } + let mut diff = 0u8; + for (&x, &y) in a.iter().zip(b.iter()) { + diff |= x ^ y; + } + diff == 0 +} + /// `/v2////manifests/` or `…/blobs/`. fn parse(path: &str, token: &str) -> Option<(String, String, bool, String)> { - let rest = path.strip_prefix("/v2/")?.strip_prefix(token)?.strip_prefix('/')?; + let after_v2 = path.strip_prefix("/v2/")?; + let (seg, rest) = after_v2.split_once('/')?; + if token.is_empty() || !ct_eq(seg.as_bytes(), token.as_bytes()) { + return None; + } let (registry, rest) = rest.split_once('/')?; let (repo, kind, reference) = if let Some((repo, r)) = rest.rsplit_once("/manifests/") { (repo, true, r) @@ -1701,4 +1814,36 @@ mod tests { drop(engine); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn mirror_enforces_header_deadline_and_constant_time_token_match() { + assert!(ct_eq(b"0123456789abcdef", b"0123456789abcdef")); + assert!(!ct_eq(b"0123456789abcdef", b"0123456789abcdee")); + assert!(!ct_eq(b"0123456789abcdef", b"0123456789abcde")); + assert!(parse("/v2/tok123/docker.io/library/alpine/manifests/latest", "tok123").is_some()); + assert!(parse("/v2/tok124/docker.io/library/alpine/manifests/latest", "tok123").is_none()); + assert!(parse("/v2//docker.io/library/alpine/manifests/latest", "").is_none()); + + let dir = std::env::temp_dir().join(format!("kiri-mirror-slowloris-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let store = kiri_image::Store::open(&dir).unwrap(); + let engine = Engine::boot(store).unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let trickle = std::thread::spawn(move || { + let mut c = TcpStream::connect(addr).unwrap(); + for &b in b"GET /v2/ HTTP/1.1\r\nHost: d\r\nX-Slow: 1\r\n\r\n" { + if c.write_all(&[b]).is_err() { + break; + } + std::thread::sleep(Duration::from_millis(25)); + } + }); + let (srv, _) = listener.accept().unwrap(); + let err = answer_with_header_deadline(srv, &engine, Duration::from_millis(120)).unwrap_err(); + assert!(matches!(err.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut), "expected slowloris deadline timeout, got {err:?}"); + let _ = trickle.join(); + drop(engine); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/kiri/src/daemon/mod.rs b/crates/kiri/src/daemon/mod.rs index 90bff0146..dd35b74ca 100644 --- a/crates/kiri/src/daemon/mod.rs +++ b/crates/kiri/src/daemon/mod.rs @@ -259,6 +259,12 @@ pub fn run(_args: &[String]) -> io::Result<()> { if UnixStream::connect(&path).is_ok() { return None; } + // When running as root, never bind or apply POSIX ACLs to a socket + // inside a non-root-owned directory (prevents symlink ACL escalation). + if !safe_root_socket_dir(&path) { + diag::warn!("skipping extra home socket in non-root-owned directory", path = path.display()); + return None; + } bind_daemon_socket(&path, access_group.as_deref()).ok().map(|l| (l, path)) }); // Each member by name too, so one just added needn't sign in again; and @@ -743,11 +749,112 @@ fn finder(engine: &std::sync::Arc) { } } +/// Atomically writes `bytes` to `path` via a unique sibling temp file created +/// with `O_EXCL` (`create_new(true)`) and Unix mode `mode` (never following +/// symlinks at a predictable temp path). +pub(super) fn write_atomic_mode(path: &std::path::Path, bytes: &[u8], mode: u32) -> io::Result<()> { + use std::io::Write; + static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let dir = path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or_else(|| std::path::Path::new(".")); + std::fs::create_dir_all(dir)?; + let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("tmp"); + let pid = std::process::id(); + for _ in 0..16 { + let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let tmp = dir.join(format!(".{name}.{pid}.{seq}.tmp")); + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(mode); + } + match opts.open(&tmp) { + Ok(mut f) => { + if let Err(e) = f.write_all(bytes) { + drop(f); + let _ = std::fs::remove_file(&tmp); + return Err(e); + } + drop(f); + if let Err(e) = std::fs::rename(&tmp, path) { + let _ = std::fs::remove_file(&tmp); + return Err(e); + } + return Ok(()); + } + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e), + } + } + Err(io::Error::new(io::ErrorKind::AlreadyExists, "could not create unique temporary file")) +} + +/// Whether `socket`'s parent directory is safe for a root-run daemon to place a +/// gated socket in: every existing ancestor up to the parent must be owned by +/// root and not writable by group/other (when running as root). +#[cfg(target_os = "linux")] +fn safe_root_socket_dir(socket: &std::path::Path) -> bool { + // SAFETY: geteuid cannot fail. + safe_root_socket_dir_for_euid(socket, unsafe { libc::geteuid() }) +} + +#[cfg(any(target_os = "linux", test))] +fn safe_root_socket_dir_for_euid(socket: &std::path::Path, euid: u32) -> bool { + use std::os::unix::fs::MetadataExt; + safe_root_socket_dir_with(socket, euid, |p| { + let meta = std::fs::symlink_metadata(p)?; + Ok((meta.file_type().is_symlink(), meta.file_type().is_dir(), meta.uid(), meta.mode())) + }) +} + +#[cfg(any(target_os = "linux", test))] +fn safe_root_socket_dir_with( + socket: &std::path::Path, + euid: u32, + stat: impl Fn(&std::path::Path) -> io::Result<(bool, bool, u32, u32)>, +) -> bool { + if euid != 0 { + return true; + } + if socket.components().any(|c| matches!(c, std::path::Component::ParentDir)) { + return false; + } + let Some(dir) = socket.parent() else { return false }; + if !dir.is_absolute() { + return false; + } + let mut cur = dir; + loop { + match stat(cur) { + Ok((is_symlink, is_dir, uid, mode)) => { + if is_symlink || !is_dir || uid != 0 || (mode & 0o022) != 0 { + return false; + } + } + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(_) => return false, + } + let Some(parent) = cur.parent() else { + break; + }; + if parent == cur { + break; + } + cur = parent; + } + true +} + fn bind_daemon_socket(socket: &std::path::Path, access_group: Option<&std::ffi::OsStr>) -> io::Result { if let Some(dir) = socket.parent() { std::fs::create_dir_all(dir)?; if dir == std::path::Path::new("/run/kiri") { std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o755))?; + } else if !cfg!(target_os = "linux") { + // Protect the socket directory before bind(2) so there is no brief + // window where another local user can reach the socket prior to chmod(0600). + let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)); } } let _ = std::fs::remove_file(socket); // stale, from a daemon that died @@ -1479,4 +1586,71 @@ mod tests { assert_eq!(cap.open(), 0, "all connection slots must be released"); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn write_atomic_mode_replaces_symlink_and_enforces_private_mode() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("kiri-atomic-mode-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let canary = dir.join("canary"); + std::fs::write(&canary, b"keep-me").unwrap(); + let target = dir.join("secret.json"); + std::os::unix::fs::symlink(&canary, &target).unwrap(); + write_atomic_mode(&target, br#"{"secret":1}"#, 0o600).unwrap(); + assert_eq!(std::fs::read(&canary).unwrap(), b"keep-me"); + let meta = std::fs::symlink_metadata(&target).unwrap(); + assert!(meta.file_type().is_file()); + assert_eq!(meta.permissions().mode() & 0o777, 0o600); + // Root must refuse binding a gated socket inside a non-root or symlinked directory, + // and must validate every ancestor all the way up to `/` (never stopping at a root-owned leaf). + assert!(!safe_root_socket_dir_for_euid(&dir.join("docker.sock"), 0)); + let link_dir = dir.join("linkdir"); + std::os::unix::fs::symlink(&dir, &link_dir).unwrap(); + assert!(!safe_root_socket_dir_for_euid(&link_dir.join("docker.sock"), 0)); + assert!(safe_root_socket_dir_for_euid(&dir.join("docker.sock"), 1000)); + // Leaf `/home/alice/.kiri/run` owned by root 0755, but ancestor `/home/alice/.kiri` owned by uid 1000 -> refused. + assert!(!safe_root_socket_dir_with( + std::path::Path::new("/home/alice/.kiri/run/docker.sock"), + 0, + |p| match p.to_str() { + Some("/home/alice/.kiri/run") => Ok((false, true, 0, 0o755)), + Some("/home/alice/.kiri") | Some("/home/alice") => Ok((false, true, 1000, 0o755)), + Some("/home") | Some("/") => Ok((false, true, 0, 0o755)), + _ => Err(io::Error::from(io::ErrorKind::NotFound)), + }, + )); + // Non-NotFound stat error fails closed. + assert!(!safe_root_socket_dir_with( + std::path::Path::new("/run/kiri/docker.sock"), + 0, + |p| match p.to_str() { + Some("/run/kiri") => Ok((false, true, 0, 0o755)), + _ => Err(io::Error::from(io::ErrorKind::PermissionDenied)), + }, + )); + // Any `..` traversal component is rejected even if existing prefixes are root-owned. + assert!(!safe_root_socket_dir_with( + std::path::Path::new("/run/kiri/nonexistent/../../home/alice/docker.sock"), + 0, + |p| match p.to_str() { + Some("/run/kiri") | Some("/run") | Some("/") => Ok((false, true, 0, 0o755)), + Some("/home/alice") => Ok((false, true, 1000, 0o755)), + _ => Err(io::Error::from(io::ErrorKind::NotFound)), + }, + )); + // Full root-owned non-group/world-writable chain -> allowed. + assert!(safe_root_socket_dir_with( + std::path::Path::new("/run/kiri/docker.sock"), + 0, + |p| match p.to_str() { + Some("/run/kiri") | Some("/run") | Some("/") => Ok((false, true, 0, 0o755)), + _ => Err(io::Error::from(io::ErrorKind::NotFound)), + }, + )); + let _ = std::fs::remove_dir_all(&dir); + } } + +#[cfg(test)] +mod hillclimb_bench; diff --git a/crates/kiri/src/daemon/network.rs b/crates/kiri/src/daemon/network.rs index e5e65c4b3..904301626 100644 --- a/crates/kiri/src/daemon/network.rs +++ b/crates/kiri/src/daemon/network.rs @@ -595,6 +595,47 @@ fn parse_cidr6(s: &str, what: &str) -> Result<([u8; 16], u8), String> { Ok((ip, bits)) } +/// Whether two IPv4 CIDRs overlap. +fn cidrs_overlap(a: [u8; 4], a_prefix: u8, b: [u8; 4], b_prefix: u8) -> bool { + let min_prefix = a_prefix.min(b_prefix); + let mask = if min_prefix == 0 { 0 } else { u32::MAX << (32 - min_prefix as u32) }; + (u32::from_be_bytes(a) & mask) == (u32::from_be_bytes(b) & mask) +} + +/// Whether an IPv4 subnet overlaps a reserved range (unspecified, loopback, +/// link-local/IMDS, multicast, reserved/Class-E, or Kiri's host-gateway IPs). +fn reserved_v4_subnet(net: [u8; 4], prefix: u8) -> Option<&'static str> { + const RESERVED: &[([u8; 4], u8, &str)] = &[ + ([0, 0, 0, 0], 8, "0.0.0.0/8 (unspecified)"), + ([127, 0, 0, 0], 8, "127.0.0.0/8 (loopback)"), + ([169, 254, 0, 0], 16, "169.254.0.0/16 (link-local)"), + ([224, 0, 0, 0], 4, "224.0.0.0/4 (multicast)"), + ([240, 0, 0, 0], 4, "240.0.0.0/4 (reserved)"), + ([198, 19, 248, 254], 32, "198.19.248.254 (Kiri host gateway)"), + ([192, 168, 65, 254], 32, "192.168.65.254 (WSL host gateway)"), + ]; + RESERVED.iter().find_map(|&(rnet, rprefix, label)| cidrs_overlap(net, prefix, rnet, rprefix).then_some(label)) +} + +/// Whether two IPv6 CIDRs overlap. +fn cidrs6_overlap(a: [u8; 16], a_prefix: u8, b: [u8; 16], b_prefix: u8) -> bool { + let min_prefix = a_prefix.min(b_prefix); + let m = mask6(min_prefix); + (u128::from_be_bytes(a) & m) == (u128::from_be_bytes(b) & m) +} + +/// Whether an IPv6 subnet overlaps a reserved range (`::/128`, `::1/128`, +/// `fe80::/10` link-local, or `ff00::/8` multicast). +fn reserved_v6_subnet(net: [u8; 16], prefix: u8) -> Option<&'static str> { + const RESERVED: &[([u8; 16], u8, &str)] = &[ + ([0; 16], 128, "::/128 (unspecified)"), + ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], 128, "::1/128 (loopback)"), + ([0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 10, "fe80::/10 (link-local)"), + ([0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 8, "ff00::/8 (multicast)"), + ]; + RESERVED.iter().find_map(|&(rnet, rprefix, label)| cidrs6_overlap(net, prefix, rnet, rprefix).then_some(label)) +} + /// One IPv6 `IPAM.Config` entry. fn parse_ipam6(c: &serde_json::Value, subnet: &str) -> Result { let field = |k: &str| c[k].as_str().unwrap_or("").to_owned(); @@ -603,6 +644,9 @@ fn parse_ipam6(c: &serde_json::Value, subnet: &str) -> Result { if !(1..=126).contains(&prefix) { return Err(format!("invalid subnet {subnet}: Kiri supports IPv6 prefixes from /1 to /126")); } + if let Some(why) = reserved_v6_subnet(net, prefix) { + return Err(format!("invalid subnet {subnet}: overlaps reserved range {why}")); + } let inside = |ip: [u8; 16]| in_subnet6(ip, net, prefix); let ip_range = match field("IPRange") { r if r.is_empty() => None, @@ -686,6 +730,9 @@ pub fn parse_ipam_both(v: &serde_json::Value) -> Result<(Option, Option 30 || prefix < 8 { return Err(format!("invalid subnet {subnet}: Kiri supports prefixes from /8 to /30")); } + if let Some(why) = reserved_v4_subnet(net, prefix) { + return Err(format!("invalid subnet {subnet}: overlaps reserved range {why}")); + } let inside = |ip: [u8; 4]| in_subnet(ip, net, prefix); let ip_range = match field("IPRange") { r if r.is_empty() => None, @@ -1218,8 +1265,12 @@ fn host_addrs() -> Vec { while !p.is_null() { // SAFETY: `p` is non-null and an entry of the list getifaddrs returned. let Some(ifa) = (unsafe { p.as_ref() }) else { break }; - // SAFETY: ifa_addr is checked non-null before its family is read. - if !ifa.ifa_addr.is_null() && !ifa.ifa_netmask.is_null() && i32::from(unsafe { (*ifa.ifa_addr).sa_family }) == libc::AF_INET { + // SAFETY: ifa_addr, ifa_netmask, and ifa_name are checked non-null before use. + if !ifa.ifa_addr.is_null() + && !ifa.ifa_netmask.is_null() + && !ifa.ifa_name.is_null() + && i32::from(unsafe { (*ifa.ifa_addr).sa_family }) == libc::AF_INET + { // SAFETY: an AF_INET address and netmask are sockaddr_in. let a = unsafe { (*(ifa.ifa_addr as *const libc::sockaddr_in)).sin_addr.s_addr }.to_ne_bytes(); let m = unsafe { (*(ifa.ifa_netmask as *const libc::sockaddr_in)).sin_addr.s_addr }.to_ne_bytes(); @@ -1929,4 +1980,27 @@ mod tests { assert!(n.create("iso6-v4only", with(true, serde_json::json!({GATEWAY_MODE4_OPT: "isolated", GATEWAY_MODE6_OPT: "isolated"}))).unwrap().no_gateway4()); let _ = std::fs::remove_dir_all(dir); } + + #[test] + fn ipam_rejects_reserved_and_host_gateway_subnets() { + for bad in [ + "0.0.0.0/8", + "127.0.0.0/8", + "127.1.0.0/16", + "169.254.0.0/16", + "224.0.0.0/8", + "240.0.0.0/8", + "198.19.248.0/24", + "192.168.65.0/24", + "fe80::/64", + "ff00::/16", + "::/64", + ] { + let v = serde_json::json!({"Config": [{"Subnet": bad}]}); + assert!(parse_ipam_both(&v).is_err(), "subnet {bad} must be rejected"); + } + // Legitimate private IPv4/IPv6 subnets stay accepted. + let ok = serde_json::json!({"Config": [{"Subnet": "10.99.0.0/24"}, {"Subnet": "fd00:1234::/64"}]}); + assert!(parse_ipam_both(&ok).is_ok()); + } } diff --git a/crates/kiri/src/daemon/nfs.rs b/crates/kiri/src/daemon/nfs.rs index a5714699f..dab5404e8 100644 --- a/crates/kiri/src/daemon/nfs.rs +++ b/crates/kiri/src/daemon/nfs.rs @@ -72,8 +72,14 @@ pub fn start(engine: Arc) -> io::Result { if !allowed(&conn) { continue; } + let Some(permit) = acquire_nfs_conn() else { + continue; + }; + let _ = conn.set_read_timeout(Some(NFS_IO_TIMEOUT)); + let _ = conn.set_write_timeout(Some(NFS_IO_TIMEOUT)); let (engine, handles) = (engine.clone(), handles.clone()); let _ = std::thread::Builder::new().name("kiri-nfs-conn".into()).spawn(move || { + let _permit = permit; let _ = Server { engine: &engine, handles: &handles, listing: None }.serve(conn); }); } @@ -81,6 +87,27 @@ pub fn start(engine: Arc) -> io::Result { Ok(path) } +const MAX_NFS_CONNS: usize = 32; +const MAX_RPC_FRAGMENTS: usize = 64; +const NFS_IO_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60); + +static ACTIVE_NFS_CONNS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +struct NfsConnGuard; + +impl Drop for NfsConnGuard { + fn drop(&mut self) { + ACTIVE_NFS_CONNS.fetch_sub(1, std::sync::atomic::Ordering::AcqRel); + } +} + +fn acquire_nfs_conn() -> Option { + ACTIVE_NFS_CONNS + .try_update(std::sync::atomic::Ordering::AcqRel, std::sync::atomic::Ordering::Acquire, |n| (n < MAX_NFS_CONNS).then_some(n + 1)) + .ok() + .map(|_| NfsConnGuard) +} + /// Whether the peer is the Mac's NFS client, which connects as root, or this /// user. The folder already keeps other users out; this holds if it doesn't. fn allowed(conn: &UnixStream) -> bool { @@ -432,28 +459,45 @@ struct Server<'a> { listing: Option<([u8; 16], Vec)>, } +/// Reads one RFC 5531 record-marked RPC message, rejecting zero-length +/// non-final fragments and excessive fragment counts that would otherwise spin CPU. +fn read_record(conn: &mut impl Read, record: &mut Vec) -> io::Result<()> { + record.clear(); + let mut fragments = 0usize; + loop { + let mut mark = [0u8; 4]; + conn.read_exact(&mut mark)?; + let mark = u32::from_be_bytes(mark); + let last = mark & 0x8000_0000 != 0; + let len = (mark & 0x7fff_ffff) as usize; + if len == 0 && !last { + return Err(io::Error::new(io::ErrorKind::InvalidData, "empty non-final RPC fragment")); + } + fragments += 1; + if fragments > MAX_RPC_FRAGMENTS { + return Err(io::Error::new(io::ErrorKind::InvalidData, "too many RPC fragments")); + } + if record.len().saturating_add(len) > MAX_RECORD { + return Err(io::Error::new(io::ErrorKind::InvalidData, "RPC record too large")); + } + let at = record.len(); + record.resize(at + len, 0); + conn.read_exact(&mut record[at..])?; + if last { + return Ok(()); + } + } +} + impl Server<'_> { fn serve(mut self, mut conn: UnixStream) -> io::Result<()> { let mut record = Vec::new(); loop { - record.clear(); - // Record marking: fragments until one has the last bit set. - loop { - let mut mark = [0u8; 4]; - conn.read_exact(&mut mark)?; - let mark = u32::from_be_bytes(mark); - let len = (mark & 0x7fff_ffff) as usize; - if record.len() + len > MAX_RECORD { - return Err(io::Error::new(io::ErrorKind::InvalidData, "RPC record too large")); - } - let at = record.len(); - record.resize(at + len, 0); - conn.read_exact(&mut record[at..])?; - if mark & 0x8000_0000 != 0 { - break; - } - } + read_record(&mut conn, &mut record)?; let Some(reply) = self.call(&record) else { continue }; + if reply.len() >= 0x8000_0000 { + return Err(io::Error::new(io::ErrorKind::InvalidData, "RPC reply too large")); + } let mut framed = Vec::with_capacity(reply.len() + 4); framed.extend_from_slice(&(0x8000_0000 | reply.len() as u32).to_be_bytes()); framed.extend_from_slice(&reply); @@ -1082,4 +1126,24 @@ mod tests { assert_eq!(mounted_at(&d), None); std::fs::remove_dir_all(&d).unwrap(); } + + #[test] + fn read_record_rejects_empty_non_final_fragments_and_fragment_floods() { + // Zero-length non-final fragment must fail immediately instead of spinning forever. + let zeros = vec![0u8; 400]; + let mut buf = Vec::new(); + let err = read_record(&mut &zeros[..], &mut buf).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + + // Excessive 1-byte non-final fragments exceed MAX_RPC_FRAGMENTS. + let mut many = Vec::new(); + for _ in 0..=MAX_RPC_FRAGMENTS { + many.extend_from_slice(&1u32.to_be_bytes()); + many.push(b'a'); + } + many.extend_from_slice(&(0x8000_0000u32 | 1).to_be_bytes()); + many.push(b'z'); + let err = read_record(&mut &many[..], &mut buf).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + } } diff --git a/crates/kiri/src/daemon/ports.rs b/crates/kiri/src/daemon/ports.rs index f2e915554..a5965f9b3 100644 --- a/crates/kiri/src/daemon/ports.rs +++ b/crates/kiri/src/daemon/ports.rs @@ -500,7 +500,7 @@ pub struct Forwards { /// What was actually bound: (binding, host address, host port). pub bound: Vec<(Binding, String, u16)>, #[cfg(test)] - on_drop: Option>, + on_drop: Mutex>>, } #[cfg(test)] @@ -533,7 +533,7 @@ impl Forwards { loopback: None, host_port_53: None, bound, - on_drop: Some(Box::new(on_drop)), + on_drop: Mutex::new(Some(Box::new(on_drop))), } } } @@ -566,7 +566,7 @@ impl Drop for Forwards { let _ = t.join(); } #[cfg(test)] - if let Some(f) = self.on_drop.take() { + if let Some(f) = self.on_drop.lock().unwrap_or_else(|e| e.into_inner()).take() { f(); } } @@ -642,7 +642,7 @@ fn bind_socket(addr: SocketAddr, udp: bool) -> io::Result { bind_socket_on_if(addr, udp, false) } -fn bind_socket_on_if(addr: SocketAddr, udp: bool, bind_lo0: bool) -> io::Result { +pub(super) fn bind_socket_on_if(addr: SocketAddr, udp: bool, bind_lo0: bool) -> io::Result { let (family, ty) = (if addr.is_ipv6() { libc::AF_INET6 } else { libc::AF_INET }, if udp { libc::SOCK_DGRAM } else { libc::SOCK_STREAM }); // SAFETY: plain socket creation; owned at once. let fd = unsafe { libc::socket(family, ty, 0) }; @@ -1090,7 +1090,7 @@ pub fn start(vm: Arc, id: &str, bindings: &[Binding], target_ip: [u8; 4] host_port_53: None, bound: Vec::new(), #[cfg(test)] - on_drop: None, + on_drop: Mutex::new(None), }; // On a Linux host the daemon shares the kernel with the containers, so // the kernel can rewrite the packets (nftables DNAT) instead of two @@ -1666,6 +1666,55 @@ fn relayed_tcp(s: &TcpStream) -> io::Result<()> { set(libc::IPPROTO_TCP, libc::TCP_KEEPCNT, KEEPALIVE_PROBES) } +/// Dedicated concurrency pools decoupled from published-port `TCP_SESSIONS` so +/// container egress or host-bound traffic cannot starve host published ports, +/// and SSH-agent / host-bound relays cannot spawn unbounded host threads. +const MAX_HOST_BOUND_SESSIONS: usize = 256; +const MAX_EGRESS_SESSIONS: usize = 512; +const MAX_SSH_AGENT_SESSIONS: usize = 64; +const VSOCK_HEADER_TIMEOUT: Duration = Duration::from_secs(5); + +static HOST_BOUND_SESSIONS: AtomicUsize = AtomicUsize::new(0); +static EGRESS_SESSIONS: AtomicUsize = AtomicUsize::new(0); +static SSH_AGENT_SESSIONS: AtomicUsize = AtomicUsize::new(0); + +struct SlotPermit { + counter: &'static AtomicUsize, +} + +impl Drop for SlotPermit { + fn drop(&mut self) { + self.counter.fetch_sub(1, Ordering::AcqRel); + } +} + +fn try_acquire_slot(counter: &'static AtomicUsize, max: usize) -> Option { + counter + .try_update(Ordering::AcqRel, Ordering::Acquire, |n| (n < max).then_some(n + 1)) + .ok() + .map(|_| SlotPermit { counter }) +} + +/// Sets or clears `SO_RCVTIMEO` on `fd` (used to bound the initial 6-byte +/// vsock relay header read without imposing a read deadline on idle streams). +fn set_sock_rcvtimeo(fd: std::os::fd::RawFd, timeout: Option) -> io::Result<()> { + let tv = libc::timeval { + tv_sec: timeout.map_or(0, |d| d.as_secs()) as _, + tv_usec: 0, + }; + // SAFETY: `tv` is valid for the duration of the call on an owned socket. + let r = unsafe { + libc::setsockopt( + fd, + libc::SOL_SOCKET, + libc::SO_RCVTIMEO, + (&tv as *const libc::timeval).cast(), + std::mem::size_of::() as libc::socklen_t, + ) + }; + if r == 0 { Ok(()) } else { Err(io::Error::last_os_error()) } +} + /// The vsock end: no read deadline, so a quiet connection stays (#388). The /// client's end has keepalive; when it fails, the relay ends this one too. fn vsock_stall(fd: std::os::fd::RawFd) -> io::Result<()> { @@ -1687,15 +1736,23 @@ pub const HOST_BOUND_PORT: u32 = 1026; /// `ip[4] port[2]` (always 127.0.0.1 today), and we connect to the Mac's /// loopback at that port. pub fn serve_host_bound(stream: kiri_vmm::VsockStream) { + let Some(permit) = try_acquire_slot(&HOST_BOUND_SESSIONS, MAX_HOST_BOUND_SESSIONS) else { + return; + }; let _ = std::thread::Builder::new().name("kiri-host-bound".into()).spawn(move || { + let _permit = permit; let _ = host_bound(stream); }); } fn host_bound(stream: kiri_vmm::VsockStream) -> io::Result<()> { + vsock_stall(stream.fd.as_raw_fd())?; let mut from_guest = std::fs::File::from(stream.fd.try_clone()?); let mut header = [0u8; 6]; - from_guest.read_exact(&mut header)?; + let _ = set_sock_rcvtimeo(stream.fd.as_raw_fd(), Some(VSOCK_HEADER_TIMEOUT)); + let read_res = from_guest.read_exact(&mut header); + let _ = set_sock_rcvtimeo(stream.fd.as_raw_fd(), None); + read_res?; let ip = std::net::Ipv4Addr::new(header[0], header[1], header[2], header[3]); let port = u16::from_be_bytes([header[4], header[5]]); if !host_bound_allowed(ip, port, super::domains::routes) { @@ -1712,7 +1769,7 @@ fn host_bound(stream: kiri_vmm::VsockStream) -> io::Result<()> { // Refused or unreachable: dropping closes the container's connection, // which is what it would see from a real host too. let target = dial_loopback(port)?; - target.set_nodelay(true)?; + relayed_tcp(&target)?; let mut to_guest = std::fs::File::from(stream.fd.try_clone()?); let mut target_read = target.try_clone()?; let mut target_write = target; @@ -1845,7 +1902,7 @@ fn egress_target_allowed(ip: std::net::Ipv4Addr, port: u16) -> bool { /// routes (`utun*`, `ipsec*`, `ppp*`, #319) and NetworkExtension socket /// filters (#367, #616) carry the connection. pub fn serve_egress(stream: kiri_vmm::VsockStream) { - let Some(permit) = tcp_permit(IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)) else { + let Some(permit) = try_acquire_slot(&EGRESS_SESSIONS, MAX_EGRESS_SESSIONS) else { return; }; let _ = std::thread::Builder::new().name("kiri-egress".into()).spawn(move || { @@ -1858,7 +1915,10 @@ fn egress(stream: kiri_vmm::VsockStream) -> io::Result<()> { vsock_stall(stream.fd.as_raw_fd())?; let mut from_guest = std::fs::File::from(stream.fd.try_clone()?); let mut header = [0u8; 6]; - from_guest.read_exact(&mut header)?; + let _ = set_sock_rcvtimeo(stream.fd.as_raw_fd(), Some(VSOCK_HEADER_TIMEOUT)); + let read_res = from_guest.read_exact(&mut header); + let _ = set_sock_rcvtimeo(stream.fd.as_raw_fd(), None); + read_res?; let ip = std::net::Ipv4Addr::new(header[0], header[1], header[2], header[3]); let port = u16::from_be_bytes([header[4], header[5]]); if !egress_target_allowed(ip, port) { @@ -3095,10 +3155,38 @@ fn gather_ssh_auth_inputs(include_preferred: bool) -> SshAuthInputs { } } +/// Validates a macOS SSH agent socket candidate immediately before connecting: +/// canonicalizes it, verifies it is an owned Unix socket, ensures it never +/// resolves to Kiri's own daemon socket, and (for a stored `preferred` path) +/// rejects symlink swaps and re-verifies the SSH agent allowlist. +pub(crate) fn validate_ssh_agent_connect(path: &std::path::Path, is_preferred: bool) -> Option { + if is_preferred { + let sym = std::fs::symlink_metadata(path).ok()?; + if sym.file_type().is_symlink() { + return None; + } + } + let canon = std::fs::canonicalize(path).ok()?; + if !is_owned_unix_socket(&canon) || is_kiri_socket_path(&canon) { + return None; + } + if is_preferred && !(is_known_mac_ssh_agent_sock_path(&canon) || matches_default_ssh_auth_sock(&canon)) { + return None; + } + Some(canon) +} + fn ssh_auth_sock_candidates_for(include_preferred: bool) -> Vec { let inputs = gather_ssh_auth_inputs(include_preferred); if cfg!(target_os = "macos") { + let preferred = inputs.preferred.clone(); resolve_ssh_auth_sock_candidates(&inputs, is_owned_unix_socket) + .into_iter() + .filter_map(|p| { + let is_pref = preferred.as_deref().is_some_and(|pref| pref == p); + validate_ssh_agent_connect(&p, is_pref) + }) + .collect() } else { // On Linux the daemon may run as root while $SSH_AUTH_SOCK belongs // to a non-root user, so keep the existing env behavior. @@ -3182,27 +3270,35 @@ pub(crate) fn clear_preferred_ssh_auth_sock() { /// One container connection to the SSH agent, relayed to the Mac's agent. pub fn serve_ssh_agent(stream: kiri_vmm::VsockStream) { + let Some(permit) = try_acquire_slot(&SSH_AGENT_SESSIONS, MAX_SSH_AGENT_SESSIONS) else { + return; + }; let _ = std::thread::Builder::new().name("kiri-ssh-agent".into()).spawn(move || { + let _permit = permit; + let _ = vsock_stall(stream.fd.as_raw_fd()); let Some(agent) = ssh_auth_sock_candidates_for(true) .into_iter() .find_map(|path| std::os::unix::net::UnixStream::connect(path).ok()) else { return; }; + let _ = agent.set_write_timeout(Some(TCP_STALL)); let (Ok(mut agent_read), Ok(from_guest), Ok(to_guest)) = (agent.try_clone(), stream.fd.try_clone(), stream.fd.try_clone()) else { return; }; let mut from_guest = std::fs::File::from(from_guest); let mut to_guest = std::fs::File::from(to_guest); let mut agent_write = agent; - let down = std::thread::spawn(move || { + let down = std::thread::Builder::new().name("kiri-ssh-agent-down".into()).spawn(move || { let _ = copy(&mut agent_read, &mut to_guest); // SAFETY: half-closing a socket we own. unsafe { libc::shutdown(to_guest.as_raw_fd(), libc::SHUT_WR) }; }); let _ = copy(&mut from_guest, &mut agent_write); let _ = agent_write.shutdown(Shutdown::Write); - let _ = down.join(); + if let Ok(down) = down { + let _ = down.join(); + } drop(stream); }); } @@ -5078,4 +5174,55 @@ tcp4 0 0 *.53 *.* LISTEN 1 let sub = ActiveTunnel { name: "utun8".into(), ip: [100, 64, 1, 5], prefix: 10, peer: None, point_to_point: false }; assert_eq!(parse_macos_routes_with_tunnels(&[], |_| None, &[sub]), vec![([100, 64, 0, 0], 10)]); } + + #[test] + fn ssh_agent_connect_rejects_symlink_swap_and_kiri_socket() { + use std::os::unix::net::UnixListener; + let dir = std::env::temp_dir().join(format!("kiri-ssh-connect-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let fake_kiri_run = dir.join(".kiri").join("run"); + std::fs::create_dir_all(&fake_kiri_run).unwrap(); + let fake_kiri_sock = fake_kiri_run.join("docker.sock"); + let _kiri_listener = UnixListener::bind(&fake_kiri_sock).unwrap(); + + let other_sock = dir.join("other.sock"); + let _other_listener = UnixListener::bind(&other_sock).unwrap(); + + // Legitimate GPG SSH agent socket passes both preferred and non-preferred validation. + let gpg_sock = dir.join("S.gpg-agent.ssh"); + let gpg_listener = UnixListener::bind(&gpg_sock).unwrap(); + assert!(super::validate_ssh_agent_connect(&gpg_sock, true).is_some()); + assert!(super::validate_ssh_agent_connect(&gpg_sock, false).is_some()); + + // Replacing the stored preferred path with a symlink to another owned socket is rejected. + drop(gpg_listener); + std::fs::remove_file(&gpg_sock).unwrap(); + std::os::unix::fs::symlink(&other_sock, &gpg_sock).unwrap(); + assert!(super::validate_ssh_agent_connect(&gpg_sock, true).is_none()); + + // Replacing with a symlink to Kiri's own socket (or /var/run/docker.sock) is rejected + // for BOTH preferred and non-preferred (env/gpg) candidates. + std::fs::remove_file(&gpg_sock).unwrap(); + std::os::unix::fs::symlink(&fake_kiri_sock, &gpg_sock).unwrap(); + assert!(super::validate_ssh_agent_connect(&gpg_sock, true).is_none()); + let env_link = dir.join("env-agent.sock"); + std::os::unix::fs::symlink(&fake_kiri_sock, &env_link).unwrap(); + // Also check direct symlink to socket_path() if creatable, or at least non-preferred + // symlink to a known Kiri path. + assert!(super::validate_ssh_agent_connect(&fake_kiri_sock, true).is_none()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn egress_and_host_bound_permits_are_bounded_and_decoupled_from_published_ports() { + let mut egress_permits = Vec::new(); + for _ in 0..super::MAX_EGRESS_SESSIONS { + egress_permits.push(super::try_acquire_slot(&super::EGRESS_SESSIONS, super::MAX_EGRESS_SESSIONS).unwrap()); + } + assert!(super::try_acquire_slot(&super::EGRESS_SESSIONS, super::MAX_EGRESS_SESSIONS).is_none()); + // Published-port loopback permits must remain available even when egress is saturated. + assert!(super::tcp_permit(IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)).is_some()); + drop(egress_permits); + assert!(super::try_acquire_slot(&super::EGRESS_SESSIONS, super::MAX_EGRESS_SESSIONS).is_some()); + } } diff --git a/crates/kiri/src/daemon/proxy.rs b/crates/kiri/src/daemon/proxy.rs index 93a18caf4..e44ccbe5a 100644 --- a/crates/kiri/src/daemon/proxy.rs +++ b/crates/kiri/src/daemon/proxy.rs @@ -40,9 +40,7 @@ pub fn settings() -> Value { pub fn save(v: &Value) -> std::io::Result<()> { let path = path().ok_or_else(|| std::io::Error::other("HOME is not set"))?; - let tmp = path.with_extension("json.tmp"); - write_private(&tmp, v.to_string().as_bytes())?; - std::fs::rename(&tmp, &path)?; + write_private_atomic(&path, v.to_string().as_bytes())?; *CACHE.lock().unwrap_or_else(|e| e.into_inner()) = None; Ok(()) } @@ -225,23 +223,28 @@ fn redact_report(mut v: Value, strip_credentials: bool) -> Value { /// Writes a file only this user can read: proxy settings may carry a -/// `http://user:pass@host` credential. -fn write_private(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> { - #[cfg(unix)] - { - use std::io::Write; - use std::os::unix::fs::OpenOptionsExt; - let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(path)?; - f.write_all(bytes) - } - #[cfg(not(unix))] - { - std::fs::write(path, bytes) - } +/// `http://user:pass@host` credential. Uses `create_new(true)` + `0o600` + +/// atomic rename so a pre-existing temp file or symlink cannot weaken permissions. +fn write_private_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> { + super::write_atomic_mode(path, bytes, 0o600) } #[cfg(test)] mod tests { + #[test] + fn write_private_atomic_creates_0600_even_with_existing_permissive_file() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("kiri-proxy-priv-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let target = dir.join("proxy.json"); + std::fs::write(&target, b"old").unwrap(); + std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o644)).unwrap(); + super::write_private_atomic(&target, br#"{"http":"http://u:p@host:3128"}"#).unwrap(); + let mode = std::fs::symlink_metadata(&target).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600); + let _ = std::fs::remove_dir_all(&dir); + } #[test] fn a_proxy_is_shown_without_its_password() { let shown = |u: &str| super::without_password(u.into()); diff --git a/crates/kiri/src/daemon/seccomp.rs b/crates/kiri/src/daemon/seccomp.rs index 9f66dd6c7..530c9eb2f 100644 --- a/crates/kiri/src/daemon/seccomp.rs +++ b/crates/kiri/src/daemon/seccomp.rs @@ -81,7 +81,8 @@ //! boundary the guest keeps. Anything Kiri cannot do is an error that names //! it, never a fallback. -use std::collections::HashSet; +use std::collections::{HashSet, VecDeque}; +use std::sync::Mutex; use serde::Deserialize; use serde_json::Value; @@ -424,7 +425,7 @@ impl Rule { /// Compiles a profile for the guest's architecture and a container that /// keeps `caps` (one bit per capability, as the kernel numbers them). pub fn compile(json: &str, caps: u64) -> Result, String> { - compile_with(Arch::native(), json, caps, &guest_kernel) + compile_cached(Arch::native(), json, caps, &guest_kernel) } /// For the tests: the macOS VM's kernel. @@ -438,7 +439,95 @@ pub fn compile_for_kernel(arch: Arch, json: &str, caps: u64, kernel: (u32, u32)) compile_with(arch, json, caps, &|| Ok(kernel)) } +const MAX_SECCOMP_CACHE: usize = 64; +const MAX_CACHED_PROFILE_BYTES: usize = 256 << 10; + +struct CachedBpf { + arch: Arch, + caps: u64, + kernel: Option<(u32, u32)>, + json: Box, + prog: Vec, +} + +static BPF_CACHE: Mutex> = Mutex::new(VecDeque::new()); + /// `kernel` is asked only when a rule has a `minKernel`. +fn compile_cached(arch: Arch, json: &str, caps: u64, kernel: &dyn Fn() -> Result<(u32, u32), String>) -> Result, String> { + if json.len() <= MAX_CACHED_PROFILE_BYTES { + let mut cache = BPF_CACHE.lock().unwrap_or_else(|e| e.into_inner()); + let mut matched: Option = None; + for (idx, entry) in cache.iter().enumerate() { + if entry.arch == arch && entry.caps == caps && entry.json.len() == json.len() && entry.json.as_ref() == json { + match entry.kernel { + None => { + matched = Some(idx); + break; + } + Some(_) => { + drop(cache); + let cur_k = kernel()?; + cache = BPF_CACHE.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(pos) = cache.iter().position(|e| { + e.arch == arch + && e.caps == caps + && e.kernel == Some(cur_k) + && e.json.len() == json.len() + && e.json.as_ref() == json + }) { + matched = Some(pos); + } + break; + } + } + } + } + if let Some(idx) = matched { + let prog = cache[idx].prog.clone(); + if idx != 0 + && let Some(entry) = cache.remove(idx) + { + cache.push_front(entry); + } + return Ok(prog); + } + } + + let kernel_seen = std::cell::Cell::new(None); + let tracked_kernel = || -> Result<(u32, u32), String> { + if let Some(k) = kernel_seen.get() { + return Ok(k); + } + let k = kernel()?; + kernel_seen.set(Some(k)); + Ok(k) + }; + let prog = compile_with(arch, json, caps, &tracked_kernel)?; + if json.len() <= MAX_CACHED_PROFILE_BYTES { + let used_k = kernel_seen.get(); + let mut cache = BPF_CACHE.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(pos) = cache.iter().position(|e| { + e.arch == arch + && e.caps == caps + && e.kernel == used_k + && e.json.len() == json.len() + && e.json.as_ref() == json + }) { + cache.remove(pos); + } else if cache.len() >= MAX_SECCOMP_CACHE { + cache.pop_back(); + } + cache.push_front(CachedBpf { + arch, + caps, + kernel: used_k, + json: json.into(), + prog: prog.clone(), + }); + } + Ok(prog) +} + fn compile_with(arch: Arch, json: &str, caps: u64, kernel: &dyn Fn() -> Result<(u32, u32), String>) -> Result, String> { let profile: Profile = serde_json::from_str(json).map_err(|e| format!("invalid seccomp profile: {e}"))?; if profile.listener_path.as_deref().is_some_and(|p| !p.is_empty()) { @@ -1910,4 +1999,27 @@ mod spec_tests { assert_eq!(spec(&[DENY_MKDIR], 0, false).security_flags() & NO_SECCOMP, 0); assert_eq!(spec(&[], 0, false).security_flags() & NO_SECCOMP, 0); } + + #[test] + fn bpf_cache_distinguishes_profile_bytes_caps_kernel_and_stays_bounded() { + let p1 = r#"{"defaultAction":"SCMP_ACT_ERRNO","syscalls":[{"names":["read"],"action":"SCMP_ACT_ALLOW"}]}"#; + let p2 = r#"{"defaultAction":"SCMP_ACT_ERRNO","syscalls":[{"names":["stat"],"action":"SCMP_ACT_ALLOW"}]}"#; + assert_eq!(p1.len(), p2.len()); + let b1 = super::compile_cached(Arch::native(), p1, 0, &|| Ok((6, 18))).unwrap(); + let b1_again = super::compile_cached(Arch::native(), p1, 0, &|| Ok((6, 18))).unwrap(); + let b2 = super::compile_cached(Arch::native(), p2, 0, &|| Ok((6, 18))).unwrap(); + assert_eq!(b1, b1_again); + assert_ne!(b1, b2, "same-length profiles must not collide in cache"); + + let min_k = r#"{"defaultAction":"SCMP_ACT_ERRNO","syscalls":[{"names":["read"],"action":"SCMP_ACT_ALLOW","includes":{"minKernel":"6.0"}}]}"#; + let old_k = super::compile_cached(Arch::native(), min_k, 0, &|| Ok((5, 15))).unwrap(); + let new_k = super::compile_cached(Arch::native(), min_k, 0, &|| Ok((6, 18))).unwrap(); + assert_ne!(old_k, new_k, "minKernel profiles must distinguish kernel version"); + + for i in 0..(super::MAX_SECCOMP_CACHE + 16) { + let p = format!(r#"{{"defaultAction":"SCMP_ACT_ERRNO","defaultErrnoRet":{},"syscalls":[{{"names":["read"],"action":"SCMP_ACT_ALLOW"}}]}}"#, (i % 100) + 1); + let _ = super::compile_cached(Arch::native(), &p, i as u64, &|| Ok((6, 18))).unwrap(); + } + assert!(super::BPF_CACHE.lock().unwrap().len() <= super::MAX_SECCOMP_CACHE); + } } diff --git a/crates/kiri/src/daemon/storage.rs b/crates/kiri/src/daemon/storage.rs index c4e7c862b..c6b2c530b 100644 --- a/crates/kiri/src/daemon/storage.rs +++ b/crates/kiri/src/daemon/storage.rs @@ -445,10 +445,7 @@ fn read_disk_overhead(root: &Path) -> Option { #[cfg_attr(not(any(target_os = "macos", test)), allow(dead_code))] fn write_disk_overhead(root: &Path, bytes: u64) { let path = root.join(DISK_OVERHEAD_FILE); - let tmp = root.join("vm/disk-overhead.tmp"); - if std::fs::write(&tmp, format!("{bytes}\n")).is_ok() { - let _ = std::fs::rename(&tmp, &path); - } + let _ = super::write_atomic_mode(&path, format!("{bytes}\n").as_bytes(), 0o600); } /// Effective bytes in use inside `data.img`, combining occupied filesystem diff --git a/crates/kiri/src/daemon/time.rs b/crates/kiri/src/daemon/time.rs index addaa28dc..7aa0bd179 100644 --- a/crates/kiri/src/daemon/time.rs +++ b/crates/kiri/src/daemon/time.rs @@ -2,10 +2,104 @@ use std::time::{SystemTime, UNIX_EPOCH}; +/// Formats `YYYY-MM-DDTHH:MM:SS.` into `dst` (20 ASCII bytes) for years `0000..=9999`. +fn format_sec_prefix(secs: i64, dst: &mut [u8; 20]) -> bool { + let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400)); + let (y, m, day) = civil_from_days(days); + if !(0..=9999).contains(&y) { + return false; + } + let y = y as u32; + let m = m as u32; + let day = day as u32; + let h = (rem / 3600) as u32; + let mi = (rem % 3600 / 60) as u32; + let s = (rem % 60) as u32; + dst[0] = b'0' + (y / 1000) as u8; + dst[1] = b'0' + ((y / 100) % 10) as u8; + dst[2] = b'0' + ((y / 10) % 10) as u8; + dst[3] = b'0' + (y % 10) as u8; + dst[4] = b'-'; + dst[5] = b'0' + (m / 10) as u8; + dst[6] = b'0' + (m % 10) as u8; + dst[7] = b'-'; + dst[8] = b'0' + (day / 10) as u8; + dst[9] = b'0' + (day % 10) as u8; + dst[10] = b'T'; + dst[11] = b'0' + (h / 10) as u8; + dst[12] = b'0' + (h % 10) as u8; + dst[13] = b':'; + dst[14] = b'0' + (mi / 10) as u8; + dst[15] = b'0' + (mi % 10) as u8; + dst[16] = b':'; + dst[17] = b'0' + (s / 10) as u8; + dst[18] = b'0' + (s % 10) as u8; + dst[19] = b'.'; + true +} + +#[inline] +fn format_nanos_z(mut nanos: u32, dst: &mut [u8; 10]) { + dst[9] = b'Z'; + for i in (0..9).rev() { + dst[i] = b'0' + (nanos % 10) as u8; + nanos /= 10; + } +} + +/// 1-entry per-second cache for streaming RFC 3339 nanosecond timestamps +/// (`api::logs`), avoiding per-line `civil_from_days` and heap allocations. +pub struct Rfc3339Cache { + last_sec: i64, + valid: bool, + prefix: [u8; 20], +} + +impl Default for Rfc3339Cache { + fn default() -> Self { + Self::new() + } +} + +impl Rfc3339Cache { + pub fn new() -> Self { + Self { last_sec: i64::MIN, valid: false, prefix: [0u8; 20] } + } + + pub fn write_ns(&mut self, out: &mut Vec, ns: u64) { + let secs = (ns / 1_000_000_000) as i64; + let nanos = (ns % 1_000_000_000) as u32; + if !self.valid || self.last_sec != secs { + self.last_sec = secs; + self.valid = format_sec_prefix(secs, &mut self.prefix); + } + if self.valid { + let mut tail = [0u8; 10]; + format_nanos_z(nanos, &mut tail); + out.reserve(30); + out.extend_from_slice(&self.prefix); + out.extend_from_slice(&tail); + } else { + let s = rfc3339(UNIX_EPOCH + std::time::Duration::from_nanos(ns)); + out.extend_from_slice(s.as_bytes()); + } + } +} + /// `2026-10-24T09:41:07.123456789Z` pub fn rfc3339(t: SystemTime) -> String { let d = t.duration_since(UNIX_EPOCH).unwrap_or_default(); let secs = d.as_secs() as i64; + let mut prefix = [0u8; 20]; + if format_sec_prefix(secs, &mut prefix) { + let mut tail = [0u8; 10]; + format_nanos_z(d.subsec_nanos(), &mut tail); + let mut buf = [0u8; 30]; + buf[..20].copy_from_slice(&prefix); + buf[20..].copy_from_slice(&tail); + // SAFETY: `format_sec_prefix` and `format_nanos_z` write pure ASCII bytes. + return std::str::from_utf8(&buf).expect("ascii timestamp").to_owned(); + } let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400)); let (y, m, day) = civil_from_days(days); format!( diff --git a/crates/kiri/src/daemon/tls.rs b/crates/kiri/src/daemon/tls.rs index d35eab712..190bddd11 100644 --- a/crates/kiri/src/daemon/tls.rs +++ b/crates/kiri/src/daemon/tls.rs @@ -172,12 +172,79 @@ pub fn ours(host: &str) -> bool { }) } +/// Maximum cached multi-level leaf certificates before oldest-entry eviction. +const MAX_ISSUED_CERTS: usize = 512; +/// Burst capacity and per-second refill rate for dynamic multi-level cert +/// issuance so untrusted browser pages cannot DoS CPU with random subdomains. +const CERT_RATE_BURST: f64 = 32.0; +const CERT_RATE_PER_SEC: f64 = 1.0; + +struct IssuedCache { + certs: HashMap, i64)>, + order: std::collections::VecDeque, + tokens: f64, + last_refill: std::time::Instant, +} + +impl IssuedCache { + fn new() -> Self { + Self { + certs: HashMap::new(), + order: std::collections::VecDeque::new(), + tokens: CERT_RATE_BURST, + last_refill: std::time::Instant::now(), + } + } + + fn take_rate_token(&mut self) -> bool { + let now = std::time::Instant::now(); + let elapsed = now.saturating_duration_since(self.last_refill).as_secs_f64(); + self.tokens = (self.tokens + elapsed * CERT_RATE_PER_SEC).min(CERT_RATE_BURST); + self.last_refill = now; + if self.tokens >= 1.0 { + self.tokens -= 1.0; + true + } else { + false + } + } + + fn insert(&mut self, key: String, cert: Arc, not_after: i64) { + if !self.certs.contains_key(&key) { + while self.certs.len() >= MAX_ISSUED_CERTS { + if let Some(oldest) = self.order.pop_front() { + self.certs.remove(&oldest); + } else { + break; + } + } + self.order.push_back(key.clone()); + } + self.certs.insert(key, (cert, not_after)); + } +} + +/// Maps a validated container hostname to its leaf certificate key: single-level +/// names (`app.kiri.local`, `app.kiri.localhost`) share one cached wildcard cert +/// (`*.kiri.local` / `*.kiri.localhost`), preventing per-subdomain keygen DoS. +fn cert_key_for(host: &str) -> String { + let clean = host.trim_end_matches('.'); + for suffix in [".kiri.local", ".kiri.localhost"] { + if let Some(sub) = clean.strip_suffix(suffix) { + if !sub.contains('.') { + return format!("*{suffix}"); + } + } + } + clean.to_owned() +} + /// Certificates for container names, made on first use and kept while the /// daemon runs. pub struct Certs { ca: Mutex>, CertificateDer<'static>)>>, /// Per name: the certificate and the day (since the epoch) it expires. - issued: Mutex, i64)>>, + issued: Mutex, } /// Days since the epoch, the unit certificate dates are made in. @@ -193,7 +260,7 @@ impl std::fmt::Debug for Certs { impl Certs { pub fn new() -> Certs { - Certs { ca: Mutex::new(None), issued: Mutex::new(HashMap::new()) } + Certs { ca: Mutex::new(None), issued: Mutex::new(IssuedCache::new()) } } /// A certificate for `host` and the day it expires. @@ -232,20 +299,24 @@ impl ResolvesServerCert for Certs { if !ours(&host) { return None; } + let key = cert_key_for(&host); + let is_wildcard = key.starts_with("*."); // Reissue within 30 days of expiry: a daemon that runs for a year // would otherwise keep serving a certificate browsers reject. - if let Some((c, not_after)) = self.issued.lock().unwrap_or_else(|e| e.into_inner()).get(&host) { - if today() + 30 < *not_after { - return Some(c.clone()); + { + let mut cache = self.issued.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((c, not_after)) = cache.certs.get(&key) { + if today() + 30 < *not_after { + return Some(c.clone()); + } + } + if !is_wildcard && !cache.take_rate_token() { + return None; } } - let (cert, not_after) = self.issue(&host).ok()?; - let mut issued = self.issued.lock().unwrap_or_else(|e| e.into_inner()); - // Bound the cache: a client can ask for unlimited distinct SNI names. - if issued.len() >= 512 { - issued.clear(); - } - issued.insert(host, (cert.clone(), not_after)); + let (cert, not_after) = self.issue(&key).ok()?; + let mut cache = self.issued.lock().unwrap_or_else(|e| e.into_inner()); + cache.insert(key, cert.clone(), not_after); Some(cert) } } @@ -399,10 +470,22 @@ fn trust_for_websites(der: &[u8]) -> i32 { } else { let (keys, values) = ([k_policy, k_result], [policy, result]); let dict = CFDictionaryCreate(std::ptr::null(), keys.as_ptr(), values.as_ptr(), 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - let array = CFArrayCreate(std::ptr::null(), &dict, 1, &kCFTypeArrayCallBacks); - let status = SecTrustSettingsSetTrustSettings(cert, DOMAIN_USER, array); - CFRelease(array); - CFRelease(dict); + let array = if dict.is_null() { + std::ptr::null() + } else { + CFArrayCreate(std::ptr::null(), &dict, 1, &kCFTypeArrayCallBacks) + }; + let status = if array.is_null() { + -1 + } else { + SecTrustSettingsSetTrustSettings(cert, DOMAIN_USER, array) + }; + if !array.is_null() { + CFRelease(array); + } + if !dict.is_null() { + CFRelease(dict); + } status }; for r in made.into_iter().filter(|r| !r.is_null()) { @@ -547,4 +630,18 @@ mod tests { let _ = std::fs::remove_dir_all(&base); } + + #[test] + fn single_level_names_share_wildcard_and_cache_evicts_fifo_without_clearing() { + assert_eq!(super::cert_key_for("a.kiri.local"), "*.kiri.local"); + assert_eq!(super::cert_key_for("random-123.kiri.localhost."), "*.kiri.localhost"); + assert_eq!(super::cert_key_for("web.shop.kiri.localhost"), "web.shop.kiri.localhost"); + + // Multi-level rate bucket caps burst issuance to CERT_RATE_BURST. + let mut cache = super::IssuedCache::new(); + for _ in 0..32 { + assert!(cache.take_rate_token()); + } + assert!(!cache.take_rate_token()); + } } diff --git a/crates/kiri/src/daemon/volumes.rs b/crates/kiri/src/daemon/volumes.rs index d035bc9e9..bdebd8e79 100644 --- a/crates/kiri/src/daemon/volumes.rs +++ b/crates/kiri/src/daemon/volumes.rs @@ -58,8 +58,7 @@ impl Volumes { fn save(&self) { if let Ok(json) = serde_json::to_vec(&self.list) { - let tmp = self.path.with_extension("json.tmp"); - if let Err(e) = std::fs::write(&tmp, json).and_then(|()| std::fs::rename(&tmp, &self.path)) { + if let Err(e) = super::write_atomic_mode(&self.path, &json, 0o600) { crate::diag::error!("saving volumes failed", error = e); } } diff --git a/crates/kiri/src/diag/mod.rs b/crates/kiri/src/diag/mod.rs index 95a6d9224..686445d73 100644 --- a/crates/kiri/src/diag/mod.rs +++ b/crates/kiri/src/diag/mod.rs @@ -416,6 +416,21 @@ fn fd_path(fd: i32) -> Option { Some(PathBuf::from(format!("/proc/self/fd/{fd}"))) } +/// Tightens a regular-file stderr target (such as `~/.kiri/daemon.log`) to +/// owner-only `0o600` permissions so mirrored stderr lines are not world-readable. +fn tighten_stderr_file(fd: i32, file: &File) { + if file.metadata().is_ok_and(|m| m.is_file()) { + // SAFETY: `fd` is a valid regular-file descriptor owned by this module. + unsafe { libc::fchmod(fd, 0o600) }; + } +} + +/// Formats and redacts a captured stderr line before mirroring it to the +/// original stderr file (`~/.kiri/daemon.log`). +fn format_stderr_echo(time: &str, line: &str) -> String { + format!("{time} {}", redact::patterns(line)) +} + /// Sends fd 2 through a pipe: every line written to stderr (an /// `eprintln!`, a library's complaint, a child's output) lands in this /// part's log with a timestamp, and goes on to the original stderr with one. @@ -447,6 +462,7 @@ pub fn capture_stderr() { }; // SAFETY: `orig` is this module's; ManuallyDrop keeps it open. let file = ManuallyDrop::new(unsafe { File::from_raw_fd(orig) }); + tighten_stderr_file(orig, &file); if let Some((size, read)) = appended_file(orig, &file) { let _ = ECHO_READ.set(read); ECHO_SIZE.store(size as i64, Ordering::Relaxed); @@ -482,7 +498,7 @@ pub fn capture_stderr() { continue; } let time = now(); - echo(&format!("{time} {line}")); + echo(&format_stderr_echo(&time, line)); if enabled(Level::Info) { let _ = append(part(), &json_line(&time, Level::Info, part(), line, &[("src", "stderr".into())])); } @@ -802,4 +818,26 @@ mod tests { assert!(text.contains(&format!("Version: Kiri {}", env!("CARGO_PKG_VERSION")))); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn captured_stderr_echo_redacts_secrets_and_tightens_mode() { + use std::os::fd::AsRawFd; + use std::os::unix::fs::PermissionsExt; + + let line = format_stderr_echo( + "2026-11-27T00:00:00.000Z", + "proxy http://alice:s3cr3t@proxy.corp:3128 Authorization: Bearer tok_1234567890", + ); + assert!(!line.contains("s3cr3t"), "{line}"); + assert!(!line.contains("tok_1234567890"), "{line}"); + assert!(line.contains("[redacted]"), "{line}"); + + let dir = temp("stderr-mode"); + let path = dir.join("daemon.log"); + let file = std::fs::OpenOptions::new().create(true).append(true).open(&path).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + tighten_stderr_file(file.as_raw_fd(), &file); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/kiri/src/diag/redact.rs b/crates/kiri/src/diag/redact.rs index a3cde3e7a..2ef1969bc 100644 --- a/crates/kiri/src/diag/redact.rs +++ b/crates/kiri/src/diag/redact.rs @@ -26,14 +26,14 @@ impl Redactor { Redactor { homes, secrets: secrets.into_iter().filter(|s| s.len() >= 8).collect() } } - /// `$HOME` → `~`, and the patterns. + /// `$HOME` (or `%USERPROFILE%` on Windows) → `~`, and the patterns. pub fn home_only() -> Redactor { - Redactor::new(std::env::var("HOME").ok(), Vec::new()) + Redactor::new(user_home(), Vec::new()) } /// For a report: also the Kiri Cloud token, when signed in. pub fn for_user() -> Redactor { - Redactor::new(std::env::var("HOME").ok(), crate::share::read_config().token.into_iter().collect()) + Redactor::new(user_home(), crate::share::read_config().token.into_iter().collect()) } pub fn apply(&self, text: &str) -> String { @@ -70,13 +70,28 @@ fn is_word(b: u8) -> bool { b.is_ascii_alphanumeric() || b == b'_' } +fn user_home() -> Option { + #[cfg(windows)] + { + std::env::var("USERPROFILE") + .ok() + .filter(|s| !s.is_empty()) + .or_else(|| std::env::var("HOME").ok().filter(|s| !s.is_empty())) + } + #[cfg(not(windows))] + { + std::env::var("HOME").ok().filter(|s| !s.is_empty()) + } +} + /// A key whose value is secret: `token`, `access_token`, `PASSWORD`, -/// `client_secret`, `API-KEY`, `PGPASS`, docker's `auth`, `identitytoken`… +/// `client_secret`, `API-KEY`, `PGPASS`, docker's `auth`, `identitytoken`, +/// kubeconfig's `client-key-data`… fn sensitive(key: &str) -> bool { let k = key.trim_start_matches('-').to_ascii_lowercase().replace(['-', '.'], "_"); matches!(k.as_str(), "auth" | "authorization" | "pass" | "pgpass") || k.ends_with("_pass") - || ["token", "password", "passwd", "passphrase", "secret", "apikey", "api_key", "access_key", "private_key", "credential", "crashreporterkey", "cookie", "session"].iter().any(|w| k.contains(w)) + || ["token", "password", "passwd", "passphrase", "secret", "apikey", "api_key", "access_key", "private_key", "client_key", "credential", "crashreporterkey", "cookie", "session"].iter().any(|w| k.contains(w)) } /// The home folder as logs may write it. A Windows one (`C:\Users\Ada`) is @@ -775,4 +790,17 @@ mod tests { let report = "error: {\"token\":\"abcdefghijkl\n== Engine ==\nrunning: yes\r\nlast line"; assert_eq!(Redactor::new(None, Vec::new()).apply(report), "error: {\"token\":\"[redacted]\n== Engine ==\nrunning: yes\r\nlast line"); } + + #[test] + fn redacts_kubeconfig_client_key_data() { + let yaml = " user:\n client-certificate-data: Y2VydA==\n client-key-data: LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQ==\n"; + let out = patterns(yaml); + assert!(!out.contains("LS0tLS1CRUdJTi"), "{out}"); + assert!(out.contains("client-key-data: [redacted]"), "{out}"); + + let json = r#"{"user":{"client-key-data":"LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQ=="}}"#; + let out_json = patterns(json); + assert!(!out_json.contains("LS0tLS1CRUdJTi"), "{out_json}"); + assert!(out_json.contains(r#""client-key-data":"[redacted]""#), "{out_json}"); + } } diff --git a/crates/kiri/src/dockerctx.rs b/crates/kiri/src/dockerctx.rs index bd96d87cd..b78eeee1f 100644 --- a/crates/kiri/src/dockerctx.rs +++ b/crates/kiri/src/dockerctx.rs @@ -208,15 +208,42 @@ pub fn read_json(path: &Path) -> io::Result { } /// Writes JSON through a temporary file, so a crash never leaves half a config. +/// Creates missing parent directories with `0o700` and temp files with `0o600` +/// on Unix so `~/.docker/config.json` registry credentials stay owner-only. pub fn write_json(path: &Path, v: &Value) -> io::Result<()> { + use std::io::Write; static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + std::fs::DirBuilder::new().recursive(true).mode(0o700).create(dir)?; + } + #[cfg(not(unix))] std::fs::create_dir_all(dir)?; let file = path.file_name().and_then(|n| n.to_str()).unwrap_or("config.json"); - let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let tmp = dir.join(format!(".{file}.kiri-tmp-{}-{seq}", std::process::id())); let bytes = serde_json::to_vec_pretty(v).map_err(io::Error::other)?; - let res = std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, path)); + let mut attempt = 0u32; + let (tmp, mut f) = loop { + let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let candidate = dir.join(format!(".{file}.kiri-tmp-{}-{seq}", std::process::id())); + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + match opts.open(&candidate) { + Ok(f) => break (candidate, f), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists && attempt < 32 => attempt += 1, + Err(e) => return Err(e), + } + }; + let res = f.write_all(&bytes).and_then(|()| f.flush()).and_then(|()| { + drop(f); + std::fs::rename(&tmp, path) + }); if res.is_err() { let _ = std::fs::remove_file(&tmp); } @@ -910,4 +937,19 @@ mod tests { assert_eq!(sock_at(&link, &ours, &[]), Endpoint::Free); let _ = std::fs::remove_dir_all(&d); } + + #[cfg(unix)] + #[test] + fn write_json_enforces_0600_config_and_0700_new_dir() { + use std::os::unix::fs::PermissionsExt; + let root = scratch_home("mode-0600"); + let docker = root.join(".docker"); + let cfg = docker.join("config.json"); + write_json(&cfg, &json!({"auths": {"https://index.docker.io/v1/": {"auth": "c2VjcmV0"}}})).unwrap(); + assert_eq!(std::fs::metadata(&docker).unwrap().permissions().mode() & 0o777, 0o700); + assert_eq!(std::fs::metadata(&cfg).unwrap().permissions().mode() & 0o777, 0o600); + set_current(&cfg, "kiri").unwrap(); + assert_eq!(std::fs::metadata(&cfg).unwrap().permissions().mode() & 0o777, 0o600); + let _ = std::fs::remove_dir_all(&root); + } } diff --git a/crates/kiri/src/hostaccess.rs b/crates/kiri/src/hostaccess.rs index 01cbc08ad..c97c9ac3c 100644 --- a/crates/kiri/src/hostaccess.rs +++ b/crates/kiri/src/hostaccess.rs @@ -85,6 +85,62 @@ fn add_member_with(user: &str, group: &str, usermod: Option<&Path>, gpasswd: Opt Err(io::Error::other(usermod_err.unwrap_or_else(|| "neither usermod nor gpasswd found in system directories".into()))) } +fn uid_account_name(uid: u32) -> io::Result> { + use std::ffi::CStr; + let mut cap = 4096usize; + loop { + let mut pwd: libc::passwd = unsafe { std::mem::zeroed() }; + let mut buf = vec![0u8; cap]; + let mut result: *mut libc::passwd = std::ptr::null_mut(); + // SAFETY: `getpwuid_r` writes into `pwd` and `buf` (of length `cap`), + // setting `result` to `&mut pwd` on match or NULL if not found. + let rc = unsafe { libc::getpwuid_r(uid as libc::uid_t, &mut pwd, buf.as_mut_ptr().cast(), buf.len(), &mut result) }; + if rc == libc::ERANGE && cap < 65536 { + cap *= 2; + continue; + } + if rc != 0 { + return Err(io::Error::from_raw_os_error(rc)); + } + if result.is_null() || pwd.pw_name.is_null() { + return Ok(None); + } + // SAFETY: `pw_name` points to a NUL-terminated string inside `buf`. + let name = unsafe { CStr::from_ptr(pwd.pw_name) }.to_string_lossy().into_owned(); + return Ok(Some(name)); + } +} + +/// When invoked via Polkit (`PKEXEC_UID` present), requires the resolved target +/// account to match the invoking Polkit user so a cached `pkexec` grant cannot +/// add an arbitrary local account to the root-equivalent `kiri` group. +fn verify_pkexec_caller( + pkexec_uid: Option<&str>, + target_account: &str, + resolve_uid: impl Fn(u32) -> io::Result>, +) -> io::Result<()> { + let Some(raw_uid) = pkexec_uid else { + return Ok(()); + }; + let uid: u32 = raw_uid + .trim() + .parse() + .map_err(|_| io::Error::new(io::ErrorKind::PermissionDenied, "invalid PKEXEC_UID"))?; + let Some(caller) = resolve_uid(uid)? else { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("no account for PKEXEC_UID {uid}"), + )); + }; + if caller != target_account { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("pkexec caller (uid {uid}) cannot grant host access to {target_account}"), + )); + } + Ok(()) +} + #[allow(clippy::too_many_arguments)] fn run_with( user: &str, @@ -96,10 +152,40 @@ fn run_with( start_engine: impl Fn() -> io::Result<()>, grant_acl: impl Fn(&str) -> io::Result, mut emit: impl FnMut(&str), +) -> io::Result { + run_with_pkexec( + user, + group, + None, + resolve_account, + |_| Ok(None), + list_members, + create_group, + add_member, + start_engine, + grant_acl, + &mut emit, + ) +} + +#[allow(clippy::too_many_arguments)] +fn run_with_pkexec( + user: &str, + group: &str, + pkexec_uid: Option<&str>, + resolve_account: impl Fn(&str) -> io::Result>, + resolve_uid: impl Fn(u32) -> io::Result>, + list_members: impl Fn(&str) -> io::Result>, + create_group: impl Fn(&str) -> io::Result<()>, + add_member: impl Fn(&str, &str) -> io::Result<()>, + start_engine: impl Fn() -> io::Result<()>, + grant_acl: impl Fn(&str) -> io::Result, + emit: &mut impl FnMut(&str), ) -> io::Result { let Some(account) = resolve_account(user)? else { return Err(io::Error::other(format!("no account named {user}"))); }; + verify_pkexec_caller(pkexec_uid, &account, resolve_uid)?; match list_members(group) { Ok(_) => {} Err(e) if e.kind() == io::ErrorKind::NotFound => create_group(group)?, @@ -148,10 +234,14 @@ pub fn run(args: &[String]) -> io::Result { if unsafe { libc::geteuid() } != 0 { return Err(io::Error::other(format!("needs root: sudo kiri host-access {}{user}", if restart { "--restart " } else { "" }))); } - run_with( + let pkexec_uid = std::env::var("PKEXEC_UID").ok(); + let mut emit = |line: &str| println!("{line}"); + run_with_pkexec( user, GROUP, + pkexec_uid.as_deref(), crate::daemon::access::account_name, + uid_account_name, crate::daemon::access::members, |group| { let groupadd = find_tool("groupadd").ok_or_else(|| io::Error::other("groupadd not found in system directories"))?; @@ -160,7 +250,7 @@ pub fn run(args: &[String]) -> io::Result { |member, group| add_member_with(member, group, find_tool("usermod").as_deref(), find_tool("gpasswd").as_deref()), || engine(restart), |group| crate::daemon::access::grant(Path::new(SOCKET), group), - |line| println!("{line}"), + &mut emit, ) } @@ -358,4 +448,31 @@ mod tests { .to_string(); assert!(err.contains("KCanon349") && !err.contains("kcanon349@corp.example"), "got: {err}"); } + + #[test] + fn pkexec_caller_cannot_grant_access_to_different_account() { + let mut emit = |_: &str| {}; + let err = run_with_pkexec( + "bob", + "kiri", + Some("1000"), + |u| Ok(Some(u.to_owned())), + |uid| Ok((uid == 1000).then(|| "alice".to_owned())), + |_| panic!("must reject before querying group"), + |_| panic!("must reject before creating group"), + |_, _| panic!("must reject before adding member"), + || panic!("must reject before starting engine"), + |_| panic!("must reject before granting ACL"), + &mut emit, + ) + .unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::PermissionDenied); + + // Non-numeric PKEXEC_UID is also refused. + let err = verify_pkexec_caller(Some("not-a-uid"), "alice", |_| Ok(Some("alice".into()))).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::PermissionDenied); + + // Matching PKEXEC_UID succeeds. + verify_pkexec_caller(Some("1000"), "alice", |uid| Ok((uid == 1000).then(|| "alice".into()))).unwrap(); + } } diff --git a/crates/kiri/src/hostrelay.rs b/crates/kiri/src/hostrelay.rs index 2ccd5cc13..0825b3010 100644 --- a/crates/kiri/src/hostrelay.rs +++ b/crates/kiri/src/hostrelay.rs @@ -153,10 +153,13 @@ pub fn wsl_host_active() -> bool { /// before it is allocated. const CHUNK: usize = 64 * 1024; const MAX_FRAME: usize = 1 << 20; -/// Frames waiting for one connection's writer. When it is full the reader -/// waits, which slows the other connections too; a proxy relay has a few -/// connections that all keep reading, and nothing grows without bound. +/// Frames waiting for one connection's writer. Dispatched non-blockingly so a +/// stalled peer closes only its own connection rather than freezing the relay. const QUEUE: usize = 64; +/// Maximum concurrent connections multiplexed over one relay. +const MAX_CONNS: usize = 512; +/// Write timeout on relayed TCP sockets so a wedged peer cannot pin a writer thread forever. +const WRITE_TIMEOUT: Duration = Duration::from_secs(30); pub type Out = Arc>; @@ -222,18 +225,27 @@ impl Drop for CloseAll { } } +enum OpenOutcome { + Opened(Receiver), + Full, + Closed, +} + impl Conns { fn state(&self) -> std::sync::MutexGuard<'_, State> { self.0.lock().unwrap_or_else(PoisonError::into_inner) } /// A new connection: what arrives for it waits here until it is made. - fn open(&self, id: u32) -> Option> { + fn open(&self, id: u32) -> OpenOutcome { let (tx, rx) = sync_channel(QUEUE); let prev = { let mut s = self.state(); if s.closed { - return None; + return OpenOutcome::Closed; + } + if s.entries.len() >= MAX_CONNS && !s.entries.contains_key(&id) { + return OpenOutcome::Full; } s.entries.insert(id, Entry { tx, stream: None }) }; @@ -242,7 +254,7 @@ impl Conns { { let _ = stream.shutdown(Shutdown::Both); } - Some(rx) + OpenOutcome::Opened(rx) } fn close(&self, id: u32) -> bool { @@ -266,8 +278,9 @@ impl Conns { } } - /// A frame for one of the connections. - fn dispatch(&self, kind: u8, id: u32, data: Vec) { + /// A frame for one of the connections. Never blocks the multiplexer loop: + /// if a connection's bounded queue is full, only that stalled connection is closed. + fn dispatch(&self, out: &Out, kind: u8, id: u32, data: Vec) { let op = match kind { DATA => Op::Data(data), EOF => Op::Eof, @@ -277,18 +290,49 @@ impl Conns { } _ => return, }; - // Sent outside the lock: a full queue waits for its own writer only. let tx = self.state().entries.get(&id).map(|e| e.tx.clone()); if let Some(tx) = tx { - let _ = tx.send(op); + match tx.try_send(op) { + Ok(()) => {} + Err(std::sync::mpsc::TrySendError::Full(_)) => { + if self.close(id) { + let _ = send(out, CLOSE, id, &[]); + } + } + Err(std::sync::mpsc::TrySendError::Disconnected(_)) => { + self.close(id); + } + } } } } +fn enable_keepalive(stream: &TcpStream) { + #[cfg(unix)] + { + use std::os::fd::AsRawFd; + let on: libc::c_int = 1; + // SAFETY: SO_KEEPALIVE on a live TCP socket we own. + unsafe { + libc::setsockopt( + stream.as_raw_fd(), + libc::SOL_SOCKET, + libc::SO_KEEPALIVE, + (&raw const on).cast(), + std::mem::size_of::() as libc::socklen_t, + ); + } + } + #[cfg(not(unix))] + let _ = stream; +} + /// Joins `stream` to connection `id`: what it reads goes to the other end /// as DATA, then EOF; what arrives for it (`rx`) is written to it. fn attach(conns: &Arc, out: &Out, id: u32, rx: Receiver, stream: TcpStream) { let _ = stream.set_nodelay(true); + let _ = stream.set_write_timeout(Some(WRITE_TIMEOUT)); + enable_keepalive(&stream); let (Ok(reader), Ok(writer)) = (stream.try_clone(), stream.try_clone()) else { conns.close(id); let _ = send(out, CLOSE, id, &[]); @@ -321,57 +365,73 @@ fn attach(conns: &Arc, out: &Out, id: u32, rx: Receiver, stream: TcpS }; let done2 = done.clone(); let (c, o) = (conns.clone(), out.clone()); - std::thread::spawn(move || { - let mut writer = writer; - for op in rx { - match op { - Op::Data(d) => { - if writer.write_all(&d).is_err() { - let _ = writer.shutdown(Shutdown::Both); - c.close(id); - let _ = send(&o, CLOSE, id, &[]); - return; + if std::thread::Builder::new() + .name("kiri-relay-w".into()) + .spawn(move || { + let mut writer = writer; + for op in rx { + match op { + Op::Data(d) => { + if writer.write_all(&d).is_err() { + let _ = writer.shutdown(Shutdown::Both); + c.close(id); + let _ = send(&o, CLOSE, id, &[]); + return; + } + } + Op::Eof => { + let _ = writer.shutdown(Shutdown::Write); + break; } - } - Op::Eof => { - let _ = writer.shutdown(Shutdown::Write); - break; } } + done2(); + }) + .is_err() + { + if conns.close(id) { + let _ = send(out, CLOSE, id, &[]); } - done2(); - }); + return; + } let o = out.clone(); let c = conns.clone(); - std::thread::spawn(move || { - let mut reader = reader; - let mut buf = vec![0u8; CHUNK]; - loop { - match reader.read(&mut buf) { - Ok(0) => { - if send(&o, EOF, id, &[]).is_err() { - c.close(id); - } - break; - } - Ok(n) => { - if send(&o, DATA, id, &buf[..n]).is_err() { - c.close(id); + if std::thread::Builder::new() + .name("kiri-relay-r".into()) + .spawn(move || { + let mut reader = reader; + let mut buf = vec![0u8; CHUNK]; + loop { + match reader.read(&mut buf) { + Ok(0) => { + if send(&o, EOF, id, &[]).is_err() { + c.close(id); + } break; } - } - Err(e) if e.kind() == io::ErrorKind::Interrupted => {} - Err(_) => { - // Gone while the other end may still be sending: say so. - if c.close(id) { - let _ = send(&o, CLOSE, id, &[]); + Ok(n) => { + if send(&o, DATA, id, &buf[..n]).is_err() { + c.close(id); + break; + } + } + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + Err(_) => { + // Gone while the other end may still be sending: say so. + if c.close(id) { + let _ = send(&o, CLOSE, id, &[]); + } + break; } - break; } } - } - done(); - }); + done(); + }) + .is_err() + && conns.close(id) + { + let _ = send(out, CLOSE, id, &[]); + } } /// The WSL end (`kiri hostrelay`): listens as kiri-win asks and sends each @@ -424,7 +484,7 @@ pub fn listen_side(input: impl Read, out: &Out) -> io::Result<()> { let port: u16 = 0; send(out, LISTENING_HOST, 0, &port.to_be_bytes())?; } - _ => conns.dispatch(kind, id, data), + _ => conns.dispatch(out, kind, id, data), } } Ok(()) @@ -451,9 +511,16 @@ fn listen(target: u16, conns: &Arc, out: &Out, next: &Arc) -> } }; let id = next.fetch_add(1, Ordering::SeqCst); - let Some(rx) = conns.open(id) else { - let _ = s.shutdown(Shutdown::Both); - return; + let rx = match conns.open(id) { + OpenOutcome::Opened(rx) => rx, + OpenOutcome::Full => { + let _ = s.shutdown(Shutdown::Both); + continue; + } + OpenOutcome::Closed => { + let _ = s.shutdown(Shutdown::Both); + return; + } }; if send(&out, OPEN, id, &target.to_be_bytes()).is_err() { conns.close(id); @@ -628,9 +695,16 @@ fn start_host_gateway(addr: [u8; 4], conns: &Arc, out: &Out, next: &Arc rx, + OpenOutcome::Full => { + let _ = s.shutdown(Shutdown::Both); + continue; + } + OpenOutcome::Closed => { + let _ = s.shutdown(Shutdown::Both); + return; + } }; if send(&out, OPEN, id, &target.to_be_bytes()).is_err() { conns.close(id); @@ -1011,15 +1085,28 @@ pub fn dial_side_with_host( continue; }; // Data that arrives while it dials waits in the queue. - let Some(rx) = conns.open(id) else { continue }; - let (c, o) = (conns.clone(), out.clone()); - std::thread::spawn(move || match dial(target) { - Ok(s) => attach(&c, &o, id, rx, s), - Err(_) => { - c.close(id); - let _ = send(&o, CLOSE, id, &[]); + let rx = match conns.open(id) { + OpenOutcome::Opened(rx) => rx, + OpenOutcome::Full | OpenOutcome::Closed => { + let _ = send(out, CLOSE, id, &[]); + continue; } - }); + }; + let (c, o) = (conns.clone(), out.clone()); + if std::thread::Builder::new() + .name("kiri-relay-dial".into()) + .spawn(move || match dial(target) { + Ok(s) => attach(&c, &o, id, rx, s), + Err(_) => { + c.close(id); + let _ = send(&o, CLOSE, id, &[]); + } + }) + .is_err() + { + conns.close(id); + let _ = send(out, CLOSE, id, &[]); + } } LISTENING => { if let (Some(target), Some(local)) = (port_of(&data, 0), port_of(&data, 2)) { @@ -1031,7 +1118,7 @@ pub fn dial_side_with_host( listening_host(local); } } - _ => conns.dispatch(kind, id, data), + _ => conns.dispatch(out, kind, id, data), } } Ok(()) @@ -1301,7 +1388,7 @@ mod tests { let conns = Arc::new(Conns::default()); let (_out_rx, out_tx) = io::pipe().unwrap(); let out: Out = Arc::new(Mutex::new(out_tx)); - let rx = conns.open(1).unwrap(); + let OpenOutcome::Opened(rx) = conns.open(1) else { panic!("expected Opened") }; let client = TcpStream::connect(("127.0.0.1", port)).unwrap(); let (mut peer, _) = proxy.accept().unwrap(); attach(&conns, &out, 1, rx, client); @@ -1313,7 +1400,7 @@ mod tests { drop(tx); conns.close_all(); assert!(conns.state().entries.is_empty()); - assert!(conns.open(2).is_none()); + assert!(matches!(conns.open(2), OpenOutcome::Closed)); peer.set_read_timeout(Some(Duration::from_millis(500))).unwrap(); loop { match peer.read(&mut buf) { @@ -1356,7 +1443,7 @@ mod tests { let (out_rx, out_tx) = io::pipe().unwrap(); drop(out_rx); let out: Out = Arc::new(Mutex::new(out_tx)); - let rx = conns.open(1).unwrap(); + let OpenOutcome::Opened(rx) = conns.open(1) else { panic!("expected Opened") }; let client = TcpStream::connect(("127.0.0.1", port)).unwrap(); let (mut peer, _) = proxy.accept().unwrap(); attach(&conns, &out, 1, rx, client); @@ -1375,7 +1462,7 @@ mod tests { // 1. An in-flight connection opened before close_all() that reaches attach() after close_all(). let conns = Arc::new(Conns::default()); - let rx = conns.open(1).unwrap(); + let OpenOutcome::Opened(rx) = conns.open(1) else { panic!("expected Opened") }; conns.close_all(); let client = TcpStream::connect(("127.0.0.1", port)).unwrap(); let (mut peer, _) = proxy.accept().unwrap(); @@ -1569,6 +1656,60 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn stalled_connection_does_not_freeze_multiplexer_and_conn_cap_is_enforced() { + let conns = Arc::new(Conns::default()); + let buf: Arc>> = Arc::new(Mutex::new(Vec::new())); + struct SharedVec(Arc>>); + impl Write for SharedVec { + fn write(&mut self, data: &[u8]) -> io::Result { + self.0.lock().unwrap().extend_from_slice(data); + Ok(data.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + let out: Out = Arc::new(Mutex::new(SharedVec(buf.clone()))); + + let OpenOutcome::Opened(_rx1_stalled) = conns.open(1) else { + panic!("conn 1 should open"); + }; + let OpenOutcome::Opened(rx2_healthy) = conns.open(2) else { + panic!("conn 2 should open"); + }; + + // Flood conn 1 past QUEUE (64 frames) with nobody reading _rx1_stalled: + // dispatch MUST NOT block, must close conn 1 and emit a CLOSE frame for id 1. + for _ in 0..(QUEUE + 8) { + conns.dispatch(&out, DATA, 1, vec![0xaa; 16]); + } + // Conn 2 must still receive frames immediately. + conns.dispatch(&out, DATA, 2, b"ok".to_vec()); + match rx2_healthy.recv_timeout(Duration::from_secs(1)).unwrap() { + Op::Data(d) => assert_eq!(d, b"ok"), + Op::Eof => panic!("unexpected EOF on conn 2"), + } + // Verify CLOSE frame for conn 1 was emitted. + let wire = buf.lock().unwrap().clone(); + let mut cursor = io::Cursor::new(wire); + let (kind, id, data) = read_frame(&mut cursor).unwrap().unwrap(); + assert_eq!((kind, id, data.len()), (CLOSE, 1, 0)); + + // Verify MAX_CONNS cap rejects excess opens without closing existing ones. + let mut held = Vec::new(); + for id in 10..(10 + MAX_CONNS as u32) { + match conns.open(id) { + OpenOutcome::Opened(rx) => held.push(rx), + OpenOutcome::Full => break, + OpenOutcome::Closed => panic!("unexpected closed"), + } + } + assert!(matches!(conns.open(999_999), OpenOutcome::Full)); + conns.close_all(); + assert!(matches!(conns.open(1_000_000), OpenOutcome::Closed)); + } + #[cfg(target_os = "linux")] #[test] fn host_gateway_nft_batch_matches_bridges_output_and_guards_input() { diff --git a/crates/kiri/src/k8s.rs b/crates/kiri/src/k8s.rs index 300d4f89b..383677768 100644 --- a/crates/kiri/src/k8s.rs +++ b/crates/kiri/src/k8s.rs @@ -1043,9 +1043,7 @@ fn kubeconfig(use_context: bool, port: u16) -> io::Result { } .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("refused unsafe k3s kubeconfig: {e}")))?; let own = home()?.join(crate::flavor::STATE.get()).join("kubeconfig"); - std::fs::create_dir_all(own.parent().expect("has a parent"))?; - std::fs::write(&own, &ours)?; - std::fs::set_permissions(&own, std::os::unix::fs::PermissionsExt::from_mode(0o600))?; + crate::kubeconfig::write_private_atomic(&own, &ours)?; let Some(kube) = crate::kubeconfig::path() else { println!("kubeconfig: {} (HOME is not set, so not in ~/.kube/config)", own.display()); return Ok(false); diff --git a/crates/kiri/src/kubeconfig.rs b/crates/kiri/src/kubeconfig.rs index 7b778a075..d58ec3992 100644 --- a/crates/kiri/src/kubeconfig.rs +++ b/crates/kiri/src/kubeconfig.rs @@ -792,36 +792,59 @@ fn read(path: &Path) -> io::Result> { } } -/// The new text by a temporary file and a rename, 0600; the one before it -/// kept as `config.bak.kiri`. -fn write(path: &Path, before: Option<&str>, text: &str) -> io::Result<()> { +/// Atomically writes `text` to `path` via a unique sibling temp file created +/// with mode `0o600` on Unix (inside a `0o700` directory when newly created), +/// so kubeconfig private keys are never exposed world-readably even transiently +/// and pre-existing symlinks at `path` are replaced rather than followed. +pub(crate) fn write_private_atomic(path: &Path, text: &str) -> io::Result<()> { + use std::io::Write; static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + std::fs::DirBuilder::new().recursive(true).mode(0o700).create(dir)?; + } + #[cfg(not(unix))] std::fs::create_dir_all(dir)?; let file = path.file_name().and_then(|n| n.to_str()).unwrap_or("config"); - if let Some(before) = before { - let backup = dir.join(format!("{file}.bak.kiri")); - std::fs::write(&backup, before)?; - private(&backup)?; - } - let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let tmp = dir.join(format!(".{file}.kiri-{}-{seq}", std::process::id())); - let done = std::fs::write(&tmp, text).and_then(|()| private(&tmp)).and_then(|()| std::fs::rename(&tmp, path)); + let mut attempt = 0u32; + let (tmp, mut f) = loop { + let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let candidate = dir.join(format!(".{file}.kiri-{}-{seq}", std::process::id())); + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + match opts.open(&candidate) { + Ok(f) => break (candidate, f), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists && attempt < 32 => attempt += 1, + Err(e) => return Err(e), + } + }; + let done = f.write_all(text.as_bytes()).and_then(|()| f.flush()).and_then(|()| { + drop(f); + std::fs::rename(&tmp, path) + }); if done.is_err() { let _ = std::fs::remove_file(&tmp); } done } -#[cfg(unix)] -fn private(path: &Path) -> io::Result<()> { - std::fs::set_permissions(path, std::os::unix::fs::PermissionsExt::from_mode(0o600)) -} - -// %USERPROFILE% is the user's own already. -#[cfg(not(unix))] -fn private(_: &Path) -> io::Result<()> { - Ok(()) +/// The new text by a temporary file and a rename, 0600; the one before it +/// kept as `config.bak.kiri` (also written atomically with 0600). +fn write(path: &Path, before: Option<&str>, text: &str) -> io::Result<()> { + let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); + let file = path.file_name().and_then(|n| n.to_str()).unwrap_or("config"); + if let Some(before) = before { + let backup = dir.join(format!("{file}.bak.kiri")); + write_private_atomic(&backup, before)?; + } + write_private_atomic(path, text) } /// One top-level key and the lines under it (the first is the key's own); @@ -1385,4 +1408,32 @@ users: assert!(merge("apiVersion: v1\nclusters: []\n---\napiVersion: v1\n", &ours, "kiri", false).is_err()); } + + #[cfg(unix)] + #[test] + fn kubeconfig_and_backup_are_created_privately_without_following_backup_symlink() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("kiri-kubeconfig-sec-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let kube = dir.join(".kube"); + let path = kube.join("config"); + let backup = kube.join("config.bak.kiri"); + let canary = dir.join("outside.txt"); + let ours = from_k3s_named(K3S, "kiri", 6445).unwrap(); + + assert!(install(&path, &ours, "kiri", false).unwrap()); + assert_eq!(std::fs::metadata(&kube).unwrap().permissions().mode() & 0o777, 0o700); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + + // Pre-existing world-readable backup or symlink at config.bak.kiri must be atomically replaced with 0600. + std::fs::write(&canary, "untouched").unwrap(); + std::os::unix::fs::symlink(&canary, &backup).unwrap(); + std::fs::write(&path, MINE).unwrap(); + assert!(install(&path, &ours, "kiri", false).unwrap()); + assert_eq!(std::fs::read_to_string(&canary).unwrap(), "untouched"); + let meta = std::fs::symlink_metadata(&backup).unwrap(); + assert!(!meta.file_type().is_symlink()); + assert_eq!(meta.permissions().mode() & 0o777, 0o600); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/kiri/src/machine.rs b/crates/kiri/src/machine.rs index ec15973b3..6bc51c063 100644 --- a/crates/kiri/src/machine.rs +++ b/crates/kiri/src/machine.rs @@ -51,6 +51,21 @@ pub(crate) fn wants_help(args: &[String]) -> bool { args[..scan_end].iter().any(|a| matches!(a.as_str(), "-h" | "--help")) } +/// Validates a machine name (letters, digits, dashes; non-empty, no leading dash). +fn valid_machine_name(name: &str) -> bool { + !name.is_empty() && name.len() <= 63 && !name.starts_with('-') && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') +} + +fn require_machine_name(name: &str) -> io::Result<()> { + if name.is_empty() || name.starts_with('-') { + return Err(io::Error::other("name a machine")); + } + if !valid_machine_name(name) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "a machine name is letters, digits and dashes")); + } + Ok(()) +} + pub fn run(args: &[String]) -> io::Result<()> { if wants_help(args) { println!("{USAGE}"); @@ -63,7 +78,7 @@ pub fn run(args: &[String]) -> io::Result<()> { return Err(io::Error::other("kiri daemon is not running: open Kiri.app or run `kiri daemon`")); } let name = args.get(1).map(String::as_str).unwrap_or_default(); - let need_name = || if name.is_empty() || name.starts_with('-') { Err(io::Error::other("name a machine")) } else { Ok(()) }; + let need_name = || require_machine_name(name); match args.first().map(String::as_str) { Some("create") => { need_name()?; @@ -99,13 +114,49 @@ pub fn run(args: &[String]) -> io::Result<()> { /// The host's homes folder, mounted at the same path in every machine. const HOMES: &str = if cfg!(target_os = "macos") { "/Users" } else { "/home" }; +/// Strict POSIX username validation (`[a-z_][a-z0-9_-]*`, max 32 chars). +fn valid_posix_username(name: &str) -> bool { + let b = name.as_bytes(); + !b.is_empty() + && b.len() <= 32 + && (b[0].is_ascii_lowercase() || b[0] == b'_') + && b[1..].iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'_' || *c == b'-') +} + +fn pw_username(uid: u32) -> Option { + use std::ffi::CStr; + let mut pwd: libc::passwd = unsafe { std::mem::zeroed() }; + let mut buf = vec![0u8; 4096]; + let mut res: *mut libc::passwd = std::ptr::null_mut(); + // SAFETY: `getpwuid_r` writes into stack/heap buffers we own. + let rc = unsafe { libc::getpwuid_r(uid as libc::uid_t, &mut pwd, buf.as_mut_ptr().cast(), buf.len(), &mut res) }; + if rc != 0 || res.is_null() || pwd.pw_name.is_null() { + return None; + } + // SAFETY: `pw_name` points to a NUL-terminated string inside `buf`. + Some(unsafe { CStr::from_ptr(pwd.pw_name) }.to_string_lossy().into_owned()) +} + +fn resolve_username(uid: u32, env_user: Option<&str>, pw_user: Option<&str>) -> String { + if uid == 0 { + return "root".to_owned(); + } + env_user + .filter(|u| valid_posix_username(u)) + .or_else(|| pw_user.filter(|u| valid_posix_username(u))) + .unwrap_or("user") + .to_owned() +} + /// The host user's name, uid and gid. root is always `root`: under /// `wsl -u root` (Windows) USER is not set, and a made-up name with uid 0 /// was a user no machine had ("unknown user user"). fn user() -> (String, u32, u32) { // SAFETY: getuid/getgid cannot fail. let (uid, gid) = unsafe { (libc::getuid(), libc::getgid()) }; - let name = if uid == 0 { "root".to_owned() } else { std::env::var("USER").ok().filter(|u| !u.is_empty()).unwrap_or_else(|| "user".to_owned()) }; + let env_user = std::env::var("USER").ok(); + let pw_user = if uid == 0 { None } else { pw_username(uid) }; + let name = resolve_username(uid, env_user.as_deref(), pw_user.as_deref()); (name, uid, gid) } @@ -193,19 +244,24 @@ where } fn create_body_for(name: &str, image: &str, user: &str, uid: u32, gid: u32, systemd: bool) -> serde_json::Value { - let home = home(user); + let safe_user = resolve_username(uid, Some(user), None); + let home = home(&safe_user); // The host user, made once; every distro has one of these tools. An // image user that already has the uid (Ubuntu's `ubuntu` is 1000, the // first user's uid on most Linux hosts) is renamed to the host user. + // Username and home are passed as positional arguments ($1, $2) so no + // shell or sudoers metacharacter can ever break out of the init script. let init = format!( r#"set -e -if ! id -u {user} >/dev/null 2>&1; then - getent group {gid} >/dev/null 2>&1 || groupadd -g {gid} {user} 2>/dev/null || addgroup -g {gid} {user} 2>/dev/null || true +u="$1" +h="$2" +if ! id -u "$u" >/dev/null 2>&1; then + getent group {gid} >/dev/null 2>&1 || groupadd -g {gid} "$u" 2>/dev/null || addgroup -g {gid} "$u" 2>/dev/null || true g=$(getent group {gid} | cut -d: -f1) old=$(getent passwd {uid} | cut -d: -f1) - {{ [ -n "$old" ] && usermod -l {user} -d {home} "$old" 2>/dev/null; }} || useradd -o -M -u {uid} -g "${{g:-{gid}}}" -d {home} -s /bin/sh {user} 2>/dev/null || adduser -D -H -u {uid} -G "${{g:-{user}}}" -h {home} {user} 2>/dev/null || true + {{ [ -n "$old" ] && usermod -l "$u" -d "$h" "$old" 2>/dev/null; }} || useradd -o -M -u {uid} -g "${{g:-{gid}}}" -d "$h" -s /bin/sh "$u" 2>/dev/null || adduser -D -H -u {uid} -G "${{g:-$u}}" -h "$h" "$u" 2>/dev/null || true fi -mkdir -p /etc/sudoers.d && echo '{user} ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/kiri && chmod 440 /etc/sudoers.d/kiri +mkdir -p /etc/sudoers.d && printf '%s ALL=(ALL) NOPASSWD:ALL\n' "$u" > /etc/sudoers.d/kiri && chmod 440 /etc/sudoers.d/kiri # Slim images have no sudo: fetch it once, in the background. command -v sudo >/dev/null 2>&1 || (apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq sudo || apk add -q sudo || dnf -y -q install sudo || pacman -Sy --noconfirm sudo || zypper -n -q in sudo) >/dev/null 2>&1 & {tail}"#, @@ -218,7 +274,7 @@ command -v sudo >/dev/null 2>&1 || (apt-get update -qq && DEBIAN_FRONTEND=nonint ); let mut body = json!({ "Image": image, - "Cmd": ["/bin/sh", "-c", init], + "Cmd": ["/bin/sh", "-c", init, "kiri-machine-init", safe_user, home], "Hostname": name, "Labels": {LABEL: name}, "HostConfig": { @@ -253,19 +309,20 @@ where Exec: FnMut(&str, &[&str]) -> io::Result<(i64, String)>, OnPull: FnMut(&str), { - if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') || name.starts_with('-') { + if !valid_machine_name(name) { return Err(io::Error::other("a machine name is letters, digits and dashes")); } + let safe_user = resolve_username(uid, Some(user), None); let image = parse_machine_image(pick); ensure_machine_image_with(&image, &mut req, on_pull)?; - let body = create_body_for(name, &image.full, user, uid, gid, systemd); + let body = create_body_for(name, &image.full, &safe_user, uid, gid, systemd); ok(req("POST", &format!("/containers/create?name={}", container(name)), Some(&body)))?; ok(req("POST", &format!("/containers/{}/start", container(name)), None))?; // The user is made by the machine's own first command: wait for it, or // a `machine shell` straight after was "unknown user" (seen on Fedora). - let wait = format!("for i in $(seq 300); do id -u {user} >/dev/null 2>&1 && exit 0; sleep 0.1; done; exit 1"); - if exec(&container(name), &["sh", "-c", &wait])?.0 != 0 { - return Err(io::Error::other(format!("machine {name} is running, but the user {user} could not be added to it"))); + const WAIT_SCRIPT: &str = "for i in $(seq 300); do id -u \"$1\" >/dev/null 2>&1 && exit 0; sleep 0.1; done; exit 1"; + if exec(&container(name), &["sh", "-c", WAIT_SCRIPT, "kiri-wait", &safe_user])?.0 != 0 { + return Err(io::Error::other(format!("machine {name} is running, but the user {safe_user} could not be added to it"))); } Ok(image.full) } @@ -606,4 +663,25 @@ mod tests { assert_eq!(super::list_json(&rows), json!([{"name": "dev", "image": "ubuntu:24.04", "state": "running", "status": "Up 2 hours"}])); assert_eq!(super::list_json(&json!([])), json!([])); } + + #[test] + fn rejects_traversal_machine_names_and_sanitizes_user_env_into_positional_args() { + for bad in ["../other", "dev?force=1", "dev\r\nPOST /x", "dev/sub", "dev name", ""] { + assert!(super::require_machine_name(bad).is_err(), "should reject {bad:?}"); + } + assert!(super::require_machine_name("dev-box1").is_ok()); + + // Malicious $USER values are sanitized via POSIX rules and passed as positional args. + for bad_user in ["alice'; id #", "$(whoami)", "alice bob", "Alice", "0bad", "a\nb"] { + assert_eq!(super::resolve_username(1000, Some(bad_user), Some("fallback_u")), "fallback_u"); + let body = create_body_for("dev", "ubuntu:24.04", bad_user, 1000, 1000, false); + let cmd = body["Cmd"].as_array().unwrap(); + assert_eq!(cmd[0], "/bin/sh"); + assert_eq!(cmd[1], "-c"); + assert!(!cmd[2].as_str().unwrap().contains(bad_user), "init script must not interpolate raw USER"); + assert_eq!(cmd[3], "kiri-machine-init"); + assert_eq!(cmd[4], "user"); + assert_eq!(cmd[5], format!("{HOMES}/user")); + } + } } diff --git a/crates/kiri/src/main.rs b/crates/kiri/src/main.rs index ad50e2826..69073fb5e 100644 --- a/crates/kiri/src/main.rs +++ b/crates/kiri/src/main.rs @@ -47,6 +47,12 @@ mod daemon { } #[cfg(unix)] mod diag; +#[cfg(windows)] +mod diag { + #[path = "diag/redact.rs"] + #[allow(dead_code)] + pub mod redact; +} #[cfg(any(unix, windows))] mod docker; #[cfg(any(target_os = "macos", all(target_os = "linux", feature = "window"), windows, test))] diff --git a/crates/kiri/src/setup.rs b/crates/kiri/src/setup.rs index a4f4cf063..485e1b06c 100644 --- a/crates/kiri/src/setup.rs +++ b/crates/kiri/src/setup.rs @@ -252,6 +252,16 @@ pub fn run(args: &[String]) -> io::Result<()> { Ok(()) } +/// Validates a Kiri socket path before embedding it into a root shell script or +/// LaunchDaemon plist (rejects relative paths and ASCII control characters). +fn validate_socket_path(path: &Path) -> io::Result { + let s = path.to_str().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "socket path is not valid UTF-8"))?; + if !path.is_absolute() || s.is_empty() || s.bytes().any(|b| b < 0x20 || b == 0x7f) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("invalid KIRI_SOCKET path: {s:?}"))); + } + Ok(s.to_owned()) +} + /// Points macOS at Kiri for `*.kiri.local`. Writing /etc/resolver needs an /// administrator, so macOS asks for the password, once. pub fn domains() -> io::Result<()> { @@ -469,7 +479,8 @@ fn remove_docker_socket() -> io::Result<()> { } let mut command = format!("launchctl bootout system/{SOCKET_LABEL} 2>/dev/null; rm -f {SOCKET_DAEMON}"); if linked { - command.push_str(&format!("; [ \"$(readlink {DOCKER_SOCK})\" = {} ] && rm -f {DOCKER_SOCK}; true", sh_quote(&ours.to_string_lossy()))); + let ours_s = validate_socket_path(&ours)?; + command.push_str(&format!("; [ \"$(readlink {DOCKER_SOCK})\" = {} ] && rm -f {DOCKER_SOCK}; true", sh_quote(&ours_s))); } as_admin(&command, "Kiri wants to remove its /var/run/docker.sock.")?; println!("removed {DOCKER_SOCK}"); @@ -482,7 +493,7 @@ pub fn remove_domains() -> io::Result<()> { if !Path::new(resolver).exists() { return Ok(()); } - as_admin(&format!("rm -f {resolver}"), "Kiri wants to remove its *.kiri.local names.")?; + as_admin(&format!("rm -f {}", sh_quote(resolver)), "Kiri wants to remove its *.kiri.local names.")?; println!("removed *.kiri.local"); Ok(()) } @@ -1031,6 +1042,26 @@ pub fn start_at_login() -> bool { .unwrap_or(true) } +/// Ensures `~/.kiri/daemon.log` exists with owner-only `0o600` permissions +/// before launchd opens it for `StandardOutPath`/`StandardErrorPath`. +fn ensure_private_log(log: &Path) -> io::Result<()> { + use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt}; + if let Some(dir) = log.parent() { + std::fs::DirBuilder::new().recursive(true).mode(0o700).create(dir)?; + } + match std::fs::symlink_metadata(log) { + Ok(m) if m.file_type().is_file() => { + std::fs::set_permissions(log, std::fs::Permissions::from_mode(0o600))?; + } + Ok(_) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => { + let _ = std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(log); + } + Err(e) => return Err(e), + } + Ok(()) +} + /// Updates `RunAtLoad` in `path` (or writes a valid LaunchAgent plist when missing). pub(crate) fn set_start_at_login_at(path: &Path, exe: &Path, log: &Path, on: bool) -> io::Result<()> { if let Ok(xml) = std::fs::read_to_string(path) @@ -1041,9 +1072,7 @@ pub(crate) fn set_start_at_login_at(path: &Path, exe: &Path, log: &Path, on: boo if let Some(dir) = path.parent() { std::fs::create_dir_all(dir)?; } - if let Some(dir) = log.parent() { - std::fs::create_dir_all(dir)?; - } + ensure_private_log(log)?; std::fs::write(path, agent_plist_xml(exe, log, on)) } @@ -1075,9 +1104,7 @@ fn agent() -> io::Result { if let Some(dir) = path.parent() { std::fs::create_dir_all(dir)?; } - if let Some(dir) = log.parent() { - std::fs::create_dir_all(dir)?; - } + ensure_private_log(&log)?; std::fs::write(&path, plist)?; // Reload, so a new path to the binary takes effect. let _ = Command::new("/bin/launchctl").args(["bootout", &format!("gui/{}/{AGENT}", uid())]).stderr(std::process::Stdio::null()).status(); @@ -1627,4 +1654,20 @@ mod tests { assert!(res_cmd.contains("'/etc/resolver/kiri.local.new'") && res_cmd.contains("mv -f '/etc/resolver/kiri.local.new' '/etc/resolver/kiri.local'"), "{res_cmd}"); assert!(super::apple_script_source(&res_cmd, "prompt").is_ok()); } + + #[test] + fn socket_paths_are_validated_and_private_logs_are_owner_only() { + use std::os::unix::fs::PermissionsExt; + use std::path::Path; + assert!(super::validate_socket_path(Path::new("/Users/alice/.kiri/run/docker.sock")).is_ok()); + assert!(super::validate_socket_path(Path::new("relative/docker.sock")).is_err()); + assert!(super::validate_socket_path(Path::new("/tmp/bad\nsock")).is_err()); + + let d = scratch("priv-log"); + let log = d.join(".kiri/daemon.log"); + super::ensure_private_log(&log).unwrap(); + assert_eq!(std::fs::metadata(&log).unwrap().permissions().mode() & 0o777, 0o600); + assert_eq!(std::fs::metadata(log.parent().unwrap()).unwrap().permissions().mode() & 0o777, 0o700); + let _ = std::fs::remove_dir_all(&d); + } } diff --git a/crates/kiri/src/share.rs b/crates/kiri/src/share.rs index 009faf769..d59f3cff7 100644 --- a/crates/kiri/src/share.rs +++ b/crates/kiri/src/share.rs @@ -48,6 +48,12 @@ const DEFAULT_SERVER: &str = "edge.runkiri.com:443"; const IDLE: Duration = Duration::from_secs(90); const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); const LOCAL_CONNECT_TIMEOUT: Duration = Duration::from_secs(3); +/// Maximum size of an HTTP API response read from the remote Share edge. +const MAX_API_RESPONSE: u64 = 4 << 20; +/// Maximum concurrent visitor streams per Share tunnel session. +const MAX_STREAMS: usize = 256; +/// Maximum queued inbound frames per stream before resetting a non-draining peer. +const STREAM_QUEUE_CHUNKS: usize = 256; // From build.rs: the release's build key, if this is an official build. include!(concat!(env!("OUT_DIR"), "/share_build_key.rs")); @@ -490,8 +496,61 @@ fn dial(srv: &Server, alpn: &[u8]) -> io::Result<(TcpStream, rustls::ClientConne Ok((sock, conn)) } +/// Percent-encodes a single URI path segment or query value. +fn encode_uri_component(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for b in s.bytes() { + if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') { + out.push(b as char); + } else { + out.push_str(&format!("%{b:02X}")); + } + } + out +} + +/// Validates HTTP/1.1 request line and headers before sending to the Share edge. +fn validate_api_request(method: &str, path: &str, host: &str, token: Option<&str>) -> io::Result<()> { + if method.is_empty() || !method.bytes().all(|b| b.is_ascii_uppercase()) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid HTTP method")); + } + if !path.starts_with('/') || path.bytes().any(|b| b <= 0x20 || b == 0x7f) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid Share API path")); + } + let path_only = path.split('?').next().unwrap_or(path); + if path_only.split('/').any(|seg| seg == "..") { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "Share API path must not contain traversal segments")); + } + if host.is_empty() || host.bytes().any(|b| b <= 0x20 || b == 0x7f) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid Share server host")); + } + if let Some(t) = token + && t.bytes().any(|b| b < 0x20 || b == 0x7f) + { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid Share auth token")); + } + Ok(()) +} + +/// Reads an HTTP response up to `limit` bytes, failing cleanly if the remote +/// edge sends more than `limit` bytes. +fn read_bounded_response(r: impl Read, limit: u64) -> io::Result> { + let mut raw = Vec::new(); + match r.take(limit.saturating_add(1)).read_to_end(&mut raw) { + Ok(_) => {} + // Servers often close without TLS close_notify after `Connection: close`. + Err(e) if e.kind() == io::ErrorKind::UnexpectedEof && !raw.is_empty() => {} + Err(e) => return Err(e), + } + if raw.len() as u64 > limit { + return Err(io::Error::new(io::ErrorKind::InvalidData, "the Kiri Share server sent a response that is too large")); + } + Ok(raw) +} + /// One HTTPS request to the edge's API. Returns the status and JSON body. fn api(srv: &Server, method: &str, path: &str, body: Option<&Value>, token: Option<&str>) -> io::Result<(u16, Value)> { + validate_api_request(method, path, &srv.host, token)?; let (sock, conn) = dial(srv, b"http/1.1")?; sock.set_read_timeout(Some(Duration::from_secs(30)))?; let mut s = rustls::StreamOwned::new(conn, sock); @@ -505,13 +564,7 @@ fn api(srv: &Server, method: &str, path: &str, body: Option<&Value>, token: Opti payload.len() )?; s.flush()?; - let mut raw = Vec::new(); - match s.read_to_end(&mut raw) { - Ok(_) => {} - // Servers often close without TLS close_notify after `Connection: close`. - Err(e) if e.kind() == io::ErrorKind::UnexpectedEof && !raw.is_empty() => {} - Err(e) => return Err(e), - } + let raw = read_bounded_response(&mut s, MAX_API_RESPONSE)?; parse_http_response(&raw) } @@ -586,16 +639,52 @@ pub struct DeviceCode { device_code: String, } +/// Validates the remote `verification_uri` returned by `/v1/login/start`. +/// Requires `https://`, an allowlisted GitHub host (`github.com`), and rejects +/// control characters, whitespace, leading `-` flags, and shell metacharacters. +pub fn validate_verification_uri(uri: &str) -> io::Result { + if uri.is_empty() || uri.len() > 2048 || uri.starts_with('-') { + return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid verification_uri from Kiri Share server")); + } + if uri.bytes().any(|b| { + b <= 0x20 + || b >= 0x7f + || matches!( + b, + b'\\' | b'&' | b'|' | b'<' | b'>' | b'^' | b'%' | b'"' | b'\'' | b'`' | b';' | b'(' | b')' + ) + }) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "verification_uri contains unsafe characters")); + } + let rest = uri + .strip_prefix("https://") + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "verification_uri must use https://"))?; + let authority = rest.split(['/', '?', '#']).next().unwrap_or(""); + if authority.is_empty() || authority.contains('@') { + return Err(io::Error::new(io::ErrorKind::InvalidData, "verification_uri has an invalid authority")); + } + let host = match authority.split_once(':') { + Some((h, "443")) => h, + Some(_) => return Err(io::Error::new(io::ErrorKind::InvalidData, "verification_uri uses an unexpected port")), + None => authority, + }; + if !host.eq_ignore_ascii_case("github.com") { + return Err(io::Error::new(io::ErrorKind::InvalidData, "verification_uri host is not github.com")); + } + Ok(uri.to_owned()) +} + pub fn login_start() -> io::Result { let cfg = load()?; let (status, v) = api(&server(&cfg), "POST", "/v1/login/start", Some(&json!({})), None)?; let (Some(device_code), Some(user_code), Some(uri)) = (v["device_code"].as_str(), v["user_code"].as_str(), v["verification_uri"].as_str()) else { return Err(api_error(&v, status)); }; + let verification_uri = validate_verification_uri(uri)?; Ok(DeviceCode { device_code: device_code.to_owned(), user_code: user_code.to_owned(), - verification_uri: uri.to_owned(), + verification_uri, interval: Duration::from_secs(v["interval"].as_u64().unwrap_or(5).clamp(1, MAX_DEVICE_CODE_SECS)), expires: device_code_deadline(Instant::now(), v["expires_in"].as_u64().unwrap_or(900)), }) @@ -735,7 +824,11 @@ pub fn reserve(name: &str) -> io::Result { } pub fn release(name: &str) -> io::Result<()> { - let (status, v) = signed_in("DELETE", &format!("/v1/names/{}", name.to_ascii_lowercase()), None)?; + if name.is_empty() || name == "." || name == ".." { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid reserved name")); + } + let encoded = encode_uri_component(&name.to_ascii_lowercase()); + let (status, v) = signed_in("DELETE", &format!("/v1/names/{encoded}"), None)?; match status { 200 | 204 => Ok(()), 404 => Err(io::Error::other(format!("`{name}` isn't one of your reserved names"))), @@ -801,7 +894,11 @@ pub fn tunnels() -> io::Result { /// Closes one of the account's tunnels, wherever it runs. The edge tells /// the computer running it that it was stopped from this one. pub fn close_tunnel(name: &str) -> io::Result<()> { - let (status, v) = signed_in("DELETE", &format!("/v1/tunnels/{name}"), Some(&json!({ "host": host_name() })))?; + if name.is_empty() || name == "." || name == ".." { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid tunnel name")); + } + let encoded = encode_uri_component(name); + let (status, v) = signed_in("DELETE", &format!("/v1/tunnels/{encoded}"), Some(&json!({ "host": host_name() })))?; match status { 200 | 204 => Ok(()), 404 => Err(io::Error::other(format!("{name} isn't live any more"))), @@ -840,7 +937,7 @@ fn auto_reserve(name: &str) -> io::Result { { return Ok(AutoReserve::Full(limit)); } - let (status, v) = signed_in("GET", &format!("/v1/names/check?name={name}"), None)?; + let (status, v) = signed_in("GET", &format!("/v1/names/check?name={}", encode_uri_component(&name)), None)?; if status != 200 || v["available"].as_bool() != Some(true) { return Ok(AutoReserve::Unavailable); } @@ -967,12 +1064,25 @@ pub fn resolve_via(arg: &str, inspect: impl FnOnce(&str) -> io::Result io::Result { + if arg.is_empty() + || arg == "." + || arg == ".." + || arg.bytes().any(|b| b <= 0x20 || b == 0x7f || matches!(b, b'/' | b'\\' | b'?' | b'#')) + { + return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("invalid container name `{arg}`"))); + } + Ok(format!("/containers/{}/json", encode_uri_component(arg))) +} + #[cfg(unix)] fn container_target(arg: &str) -> io::Result { + let path = container_inspect_path(arg)?; if !client::alive() { return Err(io::Error::other(format!("`{arg}` isn't a port, and Kiri isn't running to look up a container by that name"))); } - let r = client::request("GET", &format!("/containers/{arg}/json"), None)?; + let r = client::request("GET", &path, None)?; if r.status == 404 { return Err(io::Error::other(format!("no port or container named `{arg}`"))); } @@ -1348,8 +1458,12 @@ fn write_all_tls(tls: &Mutex, sock: &TcpStream, mut by Ok(()) } +type StreamRx = mpsc::Receiver>>; + struct Stream { - to_local: mpsc::Sender>>, + to_local: mpsc::SyncSender>>, + inbound_queued: AtomicUsize, + eof: AtomicBool, credit: Mutex, cv: Condvar, reset: AtomicBool, @@ -1502,8 +1616,9 @@ impl Session { fn end_all(&self) { self.lanes.end(); for (_, s) in self.streams.lock().unwrap_or_else(PoisonError::into_inner).drain() { + s.eof.store(true, Ordering::Release); s.kill(); - let _ = s.to_local.send(None); + let _ = s.to_local.try_send(None); } } @@ -1530,11 +1645,16 @@ impl Session { Msg::Data { stream, data } => { let s = self.streams.lock().unwrap_or_else(PoisonError::into_inner).get(&stream).cloned(); if let Some(s) = s { - s.bytes_in.fetch_add(data.len() as u64, Ordering::Relaxed); - if s.to_local.send(Some(data.to_vec())).is_err() { + let max_win = (self.lanes.window() as usize).max(proto::INITIAL_WINDOW as usize); + let prev = s.inbound_queued.fetch_add(data.len(), Ordering::AcqRel); + let over_window = prev.checked_add(data.len()).is_none_or(|n| n > max_win); + if over_window || s.to_local.try_send(Some(data.to_vec())).is_err() { + s.inbound_queued.fetch_sub(data.len(), Ordering::AcqRel); self.streams.lock().unwrap_or_else(PoisonError::into_inner).remove(&stream); s.kill(); let _ = self.send(Msg::Reset { stream }); + } else { + s.bytes_in.fetch_add(data.len() as u64, Ordering::Relaxed); } } } @@ -1547,13 +1667,15 @@ impl Session { } Msg::Close { stream } => { if let Some(s) = self.streams.lock().unwrap_or_else(PoisonError::into_inner).get(&stream) { - let _ = s.to_local.send(None); + s.eof.store(true, Ordering::Release); + let _ = s.to_local.try_send(None); } } Msg::Reset { stream } => { if let Some(s) = self.streams.lock().unwrap_or_else(PoisonError::into_inner).remove(&stream) { + s.eof.store(true, Ordering::Release); s.kill(); - let _ = s.to_local.send(None); + let _ = s.to_local.try_send(None); } } Msg::Ping(v) => { @@ -1582,12 +1704,18 @@ impl Session { None } - /// A visitor connected: register the stream at once (data may follow - /// before the local connection is up), then connect on its own thread. - fn open(self: &Arc, id: u32) { - let (tx, rx) = mpsc::channel(); + /// Registers a new visitor stream if under `MAX_STREAMS` and `id` is not a + /// duplicate; returns `None` when rejected so the caller can emit `Msg::Reset`. + fn try_register_stream(&self, id: u32) -> Option<(Arc, StreamRx)> { + let mut streams = self.streams.lock().unwrap_or_else(PoisonError::into_inner); + if streams.len() >= MAX_STREAMS || streams.contains_key(&id) { + return None; + } + let (tx, rx) = mpsc::sync_channel(STREAM_QUEUE_CHUNKS); let stream = Arc::new(Stream { to_local: tx, + inbound_queued: AtomicUsize::new(0), + eof: AtomicBool::new(false), credit: Mutex::new(self.lanes.window()), cv: Condvar::new(), reset: AtomicBool::new(false), @@ -1597,7 +1725,17 @@ impl Session { request: Mutex::new(None), status: Mutex::new(0), }); - self.streams.lock().unwrap_or_else(PoisonError::into_inner).insert(id, stream.clone()); + streams.insert(id, stream.clone()); + Some((stream, rx)) + } + + /// A visitor connected: register the stream at once (data may follow + /// before the local connection is up), then connect on its own thread. + fn open(self: &Arc, id: u32) { + let Some((stream, rx)) = self.try_register_stream(id) else { + let _ = self.send(Msg::Reset { stream: id }); + return; + }; let sess = self.clone(); let spawned = std::thread::Builder::new().name("share-stream".into()).spawn(move || sess.carry(id, stream, rx)); if spawned.is_err() { @@ -1748,11 +1886,26 @@ impl Session { fn to_local(&self, id: u32, stream: Arc, rx: mpsc::Receiver>>, mut local: TcpStream) { let mut unacked = 0u32; let mut first = true; - while let Ok(msg) = rx.recv() { + loop { + let msg = match rx.try_recv() { + Ok(m) => m, + Err(mpsc::TryRecvError::Empty) => { + if stream.eof.load(Ordering::Acquire) { + let _ = local.shutdown(Shutdown::Write); + break; + } + match rx.recv() { + Ok(m) => m, + Err(_) => break, + } + } + Err(mpsc::TryRecvError::Disconnected) => break, + }; let Some(data) = msg else { let _ = local.shutdown(Shutdown::Write); break; }; + stream.inbound_queued.fetch_sub(data.len(), Ordering::AcqRel); if first { first = false; *stream.request.lock().unwrap_or_else(PoisonError::into_inner) = parse_request_line(&data); @@ -1985,34 +2138,70 @@ fn shorten(path: &str, max: usize) -> String { s } +/// Neutralizes C0 (`< 0x20`), DEL (`0x7f`), and C1 (`U+0080..=U+009F`) control +/// characters so untrusted Share visitor paths or edge notices cannot inject +/// ANSI/OSC escape sequences or overwrite terminal lines. +fn sanitize_terminal(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for ch in s.chars() { + if ch.is_control() { + out.push_str(&format!("\\x{:02x}", ch as u32)); + } else { + out.push(ch); + } + } + out +} + +fn format_request_line(p: &Paint, r: &Request) -> String { + let method = sanitize_terminal(&r.method); + let path = shorten(&sanitize_terminal(&r.path), 40); + format!( + " {} {:<7} {} {:<40} {:>7} {:>9}", + p.dim(&clock(r.at)), + p.bold(&method), + p.status(r.status), + path, + format!("{} ms", r.ms), + human_bytes(r.bytes_out), + ) +} + +fn format_notice_line(p: &Paint, n: &str) -> String { + format!(" {} {}", p.accent("!"), sanitize_terminal(n)) +} + /// Prints events the way `kiri share` shows them. fn printer(target: String) -> impl Fn(Event) + Send + Sync + 'static { let p = Paint::new(); let shown_url = Mutex::new(None::); let header_done = AtomicBool::new(false); + let safe_target = sanitize_terminal(&target); move |e| match e { Event::Connecting { server } => { if !header_done.swap(true, Ordering::Relaxed) { + let server = sanitize_terminal(&server); println!(); println!(" {} {}", p.accent(&p.bold("◆ Kiri Share")), p.dim(&format!("connecting to {server}…"))); } } Event::Live { url, rate, remaining, warning, domains } => { + let safe_url = sanitize_terminal(&url); let mut shown = shown_url.lock().unwrap_or_else(PoisonError::into_inner); - if shown.as_deref() == Some(url.as_str()) { + if shown.as_deref() == Some(safe_url.as_str()) { println!(" {} {}", p.accent("●"), p.dim("back online")); return; } let first = shown.is_none(); - *shown = Some(url.clone()); + *shown = Some(safe_url.clone()); if !first { - println!(" {} {} {}", p.accent("●"), p.dim("new address:"), p.bold(&url)); + println!(" {} {} {}", p.accent("●"), p.dim("new address:"), p.bold(&safe_url)); return; } - println!(" {} {:<9}{}", p.accent("●"), "linked", target); - println!(" {} {:<9}{}", p.accent("●"), "live", p.accent(&p.bold(&url))); + println!(" {} {:<9}{}", p.accent("●"), "linked", safe_target); + println!(" {} {:<9}{}", p.accent("●"), "live", p.accent(&p.bold(&safe_url))); for d in &domains { - println!(" {} {:<9}{}", p.accent("●"), "domain", p.accent(&p.bold(d))); + println!(" {} {:<9}{}", p.accent("●"), "domain", p.accent(&p.bold(&sanitize_terminal(d)))); } println!(" {:<9}{}", "", p.dim(&limits_line(rate, remaining, warning))); println!(); @@ -2020,23 +2209,16 @@ fn printer(target: String) -> impl Fn(Event) + Send + Sync + 'static { println!(); } Event::Request(r) => { - println!( - " {} {:<7} {} {:<40} {:>7} {:>9}", - p.dim(&clock(r.at)), - p.bold(&r.method), - p.status(r.status), - shorten(&r.path, 40), - format!("{} ms", r.ms), - human_bytes(r.bytes_out), - ); - } - Event::Notice(n) => println!(" {} {n}", p.accent("!")), + println!("{}", format_request_line(&p, &r)); + } + Event::Notice(n) => println!("{}", format_notice_line(&p, &n)), Event::Reconnecting { reason, delay } => { + let reason = sanitize_terminal(&reason); println!(" {} {} {}", p.dim("↻"), p.dim(&reason), p.dim(&format!("— reconnecting in {:.1}s", delay.as_secs_f32()))) } Event::Ended { reason, error } => { if error { - eprintln!(" {} {reason}", p.wrap("31", "✕")); + eprintln!(" {} {}", p.wrap("31", "✕"), sanitize_terminal(&reason)); } } } @@ -2163,25 +2345,62 @@ pub fn run(args: &[String]) -> io::Result<()> { } } +/// Opens a validated `https://github.com/...` URL in the user's browser without +/// invoking a shell (`ShellExecuteW` on Windows, `/usr/bin/open --` on macOS). +fn open_browser_url(uri: &str) { + let Ok(safe) = validate_verification_uri(uri) else { + return; + }; + #[cfg(target_os = "macos")] + { + let _ = std::process::Command::new("/usr/bin/open") + .args(["--", &safe]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status(); + } + #[cfg(windows)] + { + #[link(name = "shell32")] + unsafe extern "system" { + fn ShellExecuteW( + hwnd: *mut std::ffi::c_void, + lp_operation: *const u16, + lp_file: *const u16, + lp_parameters: *const u16, + lp_directory: *const u16, + n_show_cmd: i32, + ) -> isize; + } + let op: Vec = "open\0".encode_utf16().collect(); + let url_w: Vec = safe.encode_utf16().chain(std::iter::once(0)).collect(); + // SAFETY: NUL-terminated UTF-16 strings outlive the ShellExecuteW call; + // SW_SHOWNORMAL = 1; no shell (`cmd.exe`) is invoked. + unsafe { + ShellExecuteW(std::ptr::null_mut(), op.as_ptr(), url_w.as_ptr(), std::ptr::null(), std::ptr::null(), 1); + } + } + #[cfg(not(any(target_os = "macos", windows)))] + let _ = safe; +} + fn login_cli(args: &[String]) -> io::Result<()> { let p = Paint::new(); if let Some(i) = args.iter().position(|a| a == "--dev") { let login = args.get(i + 1).map_or("dev", String::as_str); let who = login_dev(login)?; - println!("Signed in to Kiri Share as {} (development edge).", p.bold(&who)); + println!("Signed in to Kiri Share as {} (development edge).", p.bold(&sanitize_terminal(&who))); return Ok(()); } let code = login_start()?; + let safe_uri = validate_verification_uri(&code.verification_uri)?; println!(); println!(" {} Sign in to Kiri Share with GitHub", p.accent(&p.bold("◆"))); - println!(" Open {} and enter", p.bold(&code.verification_uri)); + println!(" Open {} and enter", p.bold(&sanitize_terminal(&safe_uri))); println!(); - println!(" {}", p.accent(&p.bold(&code.user_code))); + println!(" {}", p.accent(&p.bold(&sanitize_terminal(&code.user_code)))); println!(); - #[cfg(target_os = "macos")] - let _ = std::process::Command::new("open").arg(&code.verification_uri).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).status(); - #[cfg(windows)] - let _ = std::process::Command::new("cmd").args(["/c", "start", "", &code.verification_uri]).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).status(); + open_browser_url(&safe_uri); println!(" {}", p.dim("Waiting for you to approve…")); let mut wait = code.interval; loop { @@ -2189,7 +2408,7 @@ fn login_cli(args: &[String]) -> io::Result<()> { match login_poll(&code)? { LoginPoll::Pending(next) => wait = next, LoginPoll::Done(who) => { - println!(" {} Signed in as {}.", p.accent("●"), p.bold(&who)); + println!(" {} Signed in as {}.", p.accent("●"), p.bold(&sanitize_terminal(&who))); return Ok(()); } } @@ -2651,4 +2870,128 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn validate_verification_uri_enforces_https_github_allowlist_and_blocks_shell_chars() { + assert_eq!( + validate_verification_uri("https://github.com/login/device").unwrap(), + "https://github.com/login/device" + ); + assert_eq!( + validate_verification_uri("https://github.com:443/login/device?user_code=ABCD-1234").unwrap(), + "https://github.com:443/login/device?user_code=ABCD-1234" + ); + for bad in [ + "", + "http://github.com/login/device", + "file:///Applications/Calculator.app", + "smb://evil.example/share", + "javascript:alert(1)", + "https://evil.com/login/device", + "https://github.com@evil.com/login/device", + "https://github.com:8443/login/device", + "-aCalculator", + "https://github.com/login/device&calc.exe", + "https://github.com/login/device|whoami", + "https://github.com/login/device^&calc", + "https://github.com/login/device%TEMP%", + "https://github.com/login/device\r\n", + "https://github.com/login/device with space", + "https://github.com/login/device\u{009b}2J", + ] { + assert!(validate_verification_uri(bad).is_err(), "should reject {bad:?}"); + } + } + + #[test] + fn api_request_validation_and_bounded_response_prevent_smuggling_and_oom() { + assert!(validate_api_request("GET", "/v1/whoami", "edge.runkiri.com", Some("ks_tok")).is_ok()); + for bad_path in [ + "v1/whoami", + "/v1/names/foo\r\nPOST /v1/evil HTTP/1.1", + "/v1/names/foo bar", + "/v1/names/../admin", + "/v1/names/foo\x00", + ] { + assert!(validate_api_request("GET", bad_path, "edge.runkiri.com", None).is_err(), "path: {bad_path:?}"); + } + assert!(validate_api_request("GET", "/v1/whoami", "edge.runkiri.com\r\nX-Evil: 1", None).is_err()); + assert!(validate_api_request("GET", "/v1/whoami", "edge.runkiri.com", Some("tok\r\nX-Evil: 1")).is_err()); + assert_eq!(encode_uri_component("a/b?c#d\r\n"), "a%2Fb%3Fc%23d%0D%0A"); + + #[cfg(unix)] + { + assert_eq!(container_inspect_path("my-app").unwrap(), "/containers/my-app/json"); + for bad in ["", ".", "..", "../kiri/stop", "a/b", "a?b=1", "a\r\nPOST /x"] { + assert!(container_inspect_path(bad).is_err(), "container: {bad:?}"); + } + } + + // Bounded response reader succeeds at exact limit and rejects limit + 1. + let ok = read_bounded_response(io::Cursor::new(vec![b'a'; 16]), 16).unwrap(); + assert_eq!(ok.len(), 16); + let err = read_bounded_response(io::Cursor::new(vec![b'a'; 17]), 16).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + } + + #[test] + fn terminal_output_sanitizes_ansi_osc_and_control_sequences() { + let p = Paint { on: false }; + let req = Request { + method: "GET\x1b[31m".into(), + path: "/ok\x1b]52;c;YQ==\x07\rspoof\u{009b}2J".into(), + status: 200, + ms: 5, + bytes_in: 10, + bytes_out: 20, + at: SystemTime::UNIX_EPOCH, + }; + let line = format_request_line(&p, &req); + assert!(!line.chars().any(char::is_control), "control char leaked in request line: {line:?}"); + assert!(line.contains("\\x1b"), "{line:?}"); + + let notice = format_notice_line(&p, "hello\x1b]0;pwned\x07\r\nfake"); + assert!(!notice.chars().any(char::is_control), "control char leaked in notice: {notice:?}"); + assert!(notice.contains("\\x1b") && notice.contains("\\x0d"), "{notice:?}"); + } + + #[test] + fn share_session_enforces_max_streams_and_rejects_duplicate_stream_ids() { + // Build a minimal Session backed by a dummy loopback socket to test stream cap & dedup. + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let accept = std::thread::spawn(move || listener.accept().unwrap().0); + let sock = TcpStream::connect(addr).unwrap(); + let _peer = accept.join().unwrap(); + let tls_cfg = tls_config(b"http/1.1").unwrap(); + let conn = rustls::ClientConnection::new(tls_cfg, ServerName::try_from("localhost").unwrap()).unwrap(); + let sess = Session { + tls: Mutex::new(conn), + sock, + streams: Mutex::new(HashMap::new()), + target: Target { addr: "127.0.0.1:1".into(), label: String::new(), display: "127.0.0.1:1".into() }, + on_event: Arc::new(|_| {}), + offline_notice: Mutex::new(None), + token: String::new(), + device: String::new(), + srv: Server { host: "localhost".into(), port: 443, dial: "127.0.0.1:443".into() }, + lanes: Lanes::default(), + }; + + let mut rxs = Vec::new(); + for id in 1..=(MAX_STREAMS as u32) { + let (_s, rx) = sess.try_register_stream(id).expect("under MAX_STREAMS"); + rxs.push(rx); + } + // Duplicate ID is rejected. + assert!(sess.try_register_stream(1).is_none()); + // Exceeding MAX_STREAMS is rejected. + assert!(sess.try_register_stream((MAX_STREAMS as u32) + 1).is_none()); + // Inbound window accounting caps per-stream queued bytes. + let s1 = sess.streams.lock().unwrap().get(&1).unwrap().clone(); + let max_win = proto::INITIAL_WINDOW as usize; + assert_eq!(s1.inbound_queued.fetch_add(max_win, Ordering::AcqRel), 0); + assert!(s1.inbound_queued.load(Ordering::Acquire) + 1 > max_win); + sess.end_all(); + } } diff --git a/crates/kiri/src/ui/assemble.rs b/crates/kiri/src/ui/assemble.rs index f5103f75c..90af2c421 100644 --- a/crates/kiri/src/ui/assemble.rs +++ b/crates/kiri/src/ui/assemble.rs @@ -17,31 +17,65 @@ //! them would add some 2 M units to every start, which is why the page //! carries only one. +use std::sync::OnceLock; + const ICONS_JS: &str = include_str!("icons.js"); /// The languages and the first start's language step, which both pages show. const LANGSTEP_JS: &str = include_str!("langstep.js"); +/// Non-boot UI panels (Settings, Builds/Scan, Diagnostics), loaded on demand via `loadpanels`. +const PANELS_JS: &str = include_str!("panels.js"); const XTERM_CSS: &str = include_str!("xterm/xterm.css"); /// xterm.js 6.0.0 and its fit, search and web-links add-ons (UMD builds, /// each defining a global), in the order they load. const XTERM_JS: [&str; 4] = [include_str!("xterm/xterm.js"), include_str!("xterm/addon-fit.js"), include_str!("xterm/addon-search.js"), include_str!("xterm/addon-web-links.js")]; +struct PageTemplate { + part0: String, + part1: String, + part2: String, + fixed_len: usize, +} + +impl PageTemplate { + fn build(index: &str) -> Self { + let stripped = strip_and_compact(index) + .replacen("/*ICONS*/", &compact_js(ICONS_JS), 1) + .replacen("/*LANGSTEP*/", &compact_js(LANGSTEP_JS), 1); + let (part0, rest) = match stripped.split_once("/*LANG*/") { + Some((a, b)) => (a.to_owned(), b), + None => (stripped, ""), + }; + let (part1, part2) = match rest.split_once("/*STRINGS*/{}") { + Some((a, b)) => (a.to_owned(), b.to_owned()), + None => (rest.to_owned(), String::new()), + }; + let fixed_len = part0.len() + part1.len() + part2.len(); + Self { part0, part1, part2, fixed_len } + } + + fn render(&self, lang: Option<&str>) -> String { + let boot = super::lang::boot_js(lang); + let strings = super::lang::strings_js_cached(super::lang::resolve(lang)); + let mut out = String::with_capacity(self.fixed_len + boot.len() + strings.len()); + out.push_str(&self.part0); + out.push_str(&boot); + out.push_str(&self.part1); + out.push_str(strings); + out.push_str(&self.part2); + out + } +} + /// `index` (index.html) with everything spliced in, `lang` (the `lang` -/// setting) picking its language. +/// setting) picking its language. xterm.js and its stylesheet are loaded +/// lazily on first terminal open via [`xterm_js`]. pub fn page(index: &str, lang: Option<&str>) -> String { - let mut js = String::with_capacity(XTERM_JS.iter().map(|s| s.len() + 1).sum()); - for part in XTERM_JS { - js.push_str(part); - // Each ends in a source-map comment: the next must start on a line of its own. - js.push('\n'); - } - let page = without_indent(&without_js_comment_lines(&without_css_comments(index))) - .replacen("/*ICONS*/", ICONS_JS, 1) - .replacen("/*LANGSTEP*/", LANGSTEP_JS, 1) - .replacen("/*XTERM_CSS*/", XTERM_CSS, 1) - .replacen("/*XTERM_JS*/", &js, 1) - .replacen("/*LANG*/", &super::lang::boot_js(lang), 1) - .replacen("/*STRINGS*/{}", &super::lang::strings_js(super::lang::resolve(lang)), 1); - with_script_hashes(page) + static CACHED: OnceLock<(usize, usize, PageTemplate)> = OnceLock::new(); + let key = (index.as_ptr() as usize, index.len()); + let (ptr, len, tpl) = CACHED.get_or_init(|| (key.0, key.1, PageTemplate::build(index))); + // Hashed after the words are in: they live in a script, so its hash + // changes with the language. + with_script_hashes(if (*ptr, *len) == key { tpl.render(lang) } else { PageTemplate::build(index).render(lang) }) } /// Where the page's Content-Security-Policy (its `` in index.html) @@ -84,6 +118,280 @@ fn base64(bytes: &[u8]) -> String { out } +/// Full static strip + compaction pass used by both [`page`] and `scripts/ui-test.py --strip`. +pub(crate) fn strip_and_compact(index: &str) -> String { + let base = without_indent(&without_js_comment_lines(&without_css_comments(index))); + compact_page(&base) +} + +/// Further compacts CSS and JS sections after comment/indent stripping, while +/// keeping HTML markup (`
`, `