8 Commits
Author SHA1 Message Date
niklas 8ab77ec9dc fix(#8): ps skips corrupt meta, gc tolerates vanished refs, reject -p 0
One corrupt meta.json aborted `wsbx ps`; gc aborted on ENOENT when a concurrent
pull replaced a ref file; -p 0 could never work on the host side.
2026-10-22 19:55:48 +02:00
niklas b50e846b11 fix(#7): pin busybox by digest, kernel downloads use the filtered agent
busybox:musl was a mutable tag re-resolved daily for the binary that runs as
PID 1 in every VM. Kernel/GitHub downloads now go through the same
public-only resolver as registries.
2026-10-22 19:55:23 +02:00
niklas 56762648e3 fix(#6): connect/read timeouts on every HTTP agent
No ureq call had a timeout, so a silent registry hung pull forever. One
oci::agent() builder (30 s connect + per-read) now backs registry agents,
local ones included, and the kernel downloads.
2026-10-22 19:54:09 +02:00
niklas 2231e4efe1 fix(#5): write sandbox meta.json before creating the disk
Until meta existed the sandbox's image looked unreferenced, so a concurrent
`wsbx gc` deleted it mid-create; a crashed create was also invisible to ps and
refused by rm.
2026-10-22 19:53:03 +02:00
niklas 37c58cb5b2 fix(#4): decide 'local registry' by name, not by its DNS answer
A registry name resolving to loopback (e.g. *.127.0.0.1.nip.io) got the
unfiltered agent for the whole pull. Only localhost or a non-public IP literal
is local now; DNS-named registries always use the filtered resolver.
2026-10-22 19:52:32 +02:00
niklas 2f053b8a5b fix(#3): is_public() rejects IPv6 forms of private IPv4 targets
NAT64 (64:ff9b::/96) and 6to4 (2002::/16) now decode to the embedded IPv4 and
go through the V4 rules; documentation, Teredo and everything outside global
unicast 2000::/3 (incl. IPv4-compatible ::/96) is refused.
2026-10-22 19:52:32 +02:00
niklas fb6efa1558 fix(#2): make image ref-file names injective
ref_path() flattened / : @ to _, so evil_bar:v1 and evil/bar:v1 shared a ref
file and a poisoned one booted the wrong image with no network contact. Append
a hash of the exact reference; old-style ref files are ignored (re-resolved).
2026-10-22 19:52:32 +02:00
niklas 3879b4cc4d fix(#1): skip env entries whose key is not a shell identifier
Image Env (and -e) keys were interpolated unquoted into run.sh, which runs as
root: a hostile image could execute commands as guest root via the key.
2026-10-22 19:51:01 +02:00
7 changed files with 97 additions and 27 deletions
+6 -1
View File
@@ -68,8 +68,13 @@ The VM is the boundary. The guest (including a prompt-injected agent or a malici
- **vfkit arguments**: paths containing `,` `"` or control characters are refused (vfkit splits options on commas).
Workspaces overlapping `~/.wsbx` are refused.
- **Registry**: references are validated before any request, digest pins are enforced, and every blob/manifest is sha256-verified.
The tag cache is keyed by the exact reference (`a_b:t` and `a/b:t` never share an entry).
Auth realms must be https. For public registries, connections to loopback/private/link-local addresses are refused
(token realms and redirects included).
(token realms and redirects included, IPv6 forms like NAT64/6to4 too). A registry counts as local only by name:
`localhost` or a private IP literal (`192.168.1.5:5000`). LAN registries addressed by a DNS name are refused; use the IP.
All downloads (registries, kernel) time out after 30 s without progress (connect or any single read).
- **Guest base**: the static busybox (PID 1 in every VM) is pulled pinned by digest. The kernel comes from the Kata release
over the same public-addresses-only client and is sha256-checked against the release's published digest.
- **pi config**: allowlisted items only. Symlinks are followed only into `~/.pi/agent` or `~/.agents/skills`, with no cycles
and no special files, capped at 256 MB.
- **exec**: sessions run as root before dropping to the user, so the guest helper accepts them only from the host's vsock CID,
+5 -1
View File
@@ -13,13 +13,17 @@ const STUB_INIT: &str = "#!/.wsbx/busybox sh
echo 'wsbx: cannot mount host share'; exec /.wsbx/busybox sh
";
/// busybox:musl pinned by digest: this binary is PID 1 in every VM, so a moved tag must not change it.
/// Bump deliberately (index digest of `docker.io/library/busybox:musl`).
const BUSYBOX: &str = "busybox@sha256:ea2b9914a16a4ac1981994af97b318f7c7d4db76b580c56177f08bf76f4a0be8";
/// Static busybox from the official busybox image; runs PID 1 + helpers in the guest.
fn busybox(h: &Path) -> Result<PathBuf> {
let p = h.join("busybox");
if p.exists() {
return Ok(p);
}
let img = oci::pull(h, "busybox:musl", false)?;
let img = oci::pull(h, BUSYBOX, false)?;
let tmp = h.join("busybox.tmp");
fs::create_dir_all(&tmp)?;
let ok = Command::new("tar").arg("-xf").arg(&img.rootfs).arg("-C").arg(&tmp).arg("bin").status()?.success();
+3 -2
View File
@@ -34,7 +34,8 @@ pub fn kernel(h: &Path, update: bool, version: Option<String>) -> Result<PathBuf
Some(v) => format!("https://api.github.com/repos/{KATA_REPO}/releases/tags/{v}"),
None => format!("https://api.github.com/repos/{KATA_REPO}/releases/latest"),
};
let rel: Value = serde_json::from_reader(ureq::get(&api).call().with_context(|| format!("GET {api}"))?.into_reader())?;
let agent = oci::agent_for("api.github.com"); // public-only resolver, like registries (redirects to the CDN included)
let rel: Value = serde_json::from_reader(agent.get(&api).call().with_context(|| format!("GET {api}"))?.into_reader())?;
let tag = rel["tag_name"].as_str().ok_or_else(|| anyhow!("no tag in {api}"))?;
if k.exists() && installed.as_deref() == Some(tag) {
eprintln!("wsbx: kernel already at Kata {tag}");
@@ -62,7 +63,7 @@ pub fn kernel(h: &Path, update: bool, version: Option<String>) -> Result<PathBuf
.stdin(Stdio::piped())
.spawn()?;
let mut w = oci::HashWriter(tar.stdin.take().unwrap(), Sha256::new());
std::io::copy(&mut ureq::get(url).call()?.into_reader(), &mut w)?;
std::io::copy(&mut agent.get(url).call()?.into_reader(), &mut w)?;
let oci::HashWriter(stdin, hasher) = w;
drop(stdin);
if !tar.wait()?.success() {
+1 -1
View File
@@ -152,7 +152,7 @@ struct Opts {
#[arg(long)]
kernel: Option<PathBuf>,
/// Tunnel the host's localhost:PORT to localhost:PORT in the VM (vsock, no network exposure)
#[arg(short = 'p', long = "host-port")]
#[arg(short = 'p', long = "host-port", value_parser = clap::value_parser!(u16).range(1..))]
host_ports: Vec<u16>,
}
+60 -17
View File
@@ -6,7 +6,7 @@ use sha2::{Digest, Sha256};
use std::collections::HashSet;
use std::fs::{self, File};
use std::io::{BufReader, Read, Write};
use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
use std::net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs};
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
@@ -60,23 +60,40 @@ pub fn is_public(ip: IpAddr) -> bool {
|| o[0] == 0
|| (o[0] == 100 && o[1] & 0xc0 == 64)) // CGNAT 100.64/10
}
IpAddr::V6(v) => match v.to_ipv4_mapped() {
Some(v4) => is_public(v4.into()),
None => !(v.is_loopback() || v.is_unspecified() || v.is_multicast() || v.is_unique_local() || v.is_unicast_link_local()),
},
IpAddr::V6(v) => {
let v4 = |hi: u16, lo: u16| is_public(Ipv4Addr::from((hi as u32) << 16 | lo as u32).into());
match v.segments() {
[0, 0, 0, 0, 0, 0xffff, hi, lo] => v4(hi, lo), // IPv4-mapped
[0x64, 0xff9b, 0, 0, 0, 0, hi, lo] => v4(hi, lo), // NAT64 well-known prefix
[0x2002, hi, lo, ..] => v4(hi, lo), // 6to4
[0x2001, 0xdb8, ..] | [0x2001, 0, ..] => false, // documentation, Teredo
s => s[0] & 0xe000 == 0x2000, // global unicast 2000::/3 only
}
}
}
}
/// Every HTTP agent: a silent server (connect or any single read, TLS handshake included) fails after 30 s instead of hanging.
pub fn agent() -> ureq::AgentBuilder {
let t = std::time::Duration::from_secs(30);
ureq::AgentBuilder::new().timeout_connect(t).timeout_read(t)
}
/// Registry the user named as local: `localhost` or a non-public IP literal. Decided by name only --
/// a DNS name pointing at loopback (e.g. *.127.0.0.1.nip.io) is controlled by whoever owns the zone.
fn explicit_local(registry: &str) -> bool {
let host = registry.split_once(':').map_or(registry, |(h, _)| h);
host == "localhost" || host.parse().is_ok_and(|ip| !is_public(ip))
}
/// HTTP agent for a registry. Public registries get an agent that refuses to connect to non-public
/// addresses (covers token realms and blob redirects too); a registry that is itself local
/// (e.g. localhost:5000) was chosen explicitly by the user and keeps the default agent.
fn agent_for(registry: &str) -> ureq::Agent {
let addr = if registry.contains(':') { registry.to_string() } else { format!("{registry}:443") };
let local = addr.to_socket_addrs().map(|mut a| a.any(|a| !is_public(a.ip()))).unwrap_or(false);
if local {
return ureq::agent();
/// addresses (covers token realms and blob redirects too); an explicitly local registry
/// (e.g. localhost:5000, 192.168.1.5:5000) was chosen by the user and keeps the default agent.
pub fn agent_for(registry: &str) -> ureq::Agent {
if explicit_local(registry) {
return agent().build();
}
ureq::AgentBuilder::new()
agent()
.resolver(|addr: &str| -> std::io::Result<Vec<SocketAddr>> {
let ok: Vec<SocketAddr> = addr.to_socket_addrs()?.filter(|a| is_public(a.ip())).collect();
if ok.is_empty() {
@@ -199,8 +216,11 @@ pub fn pull(home: &Path, image: &str, refresh: bool) -> Result<Image> {
}
}
/// Flattened name for humans plus a hash of the exact reference, so `a_b:t` and `a/b:t` never share a ref file.
/// (Pre-hash ref files are simply ignored: the image is re-resolved and gc drops them.)
fn ref_path(home: &Path, image: &str) -> PathBuf {
home.join("images/refs").join(image.replace(['/', ':', '@'], "_"))
let h = hex::encode(Sha256::digest(image));
home.join("images/refs").join(format!("{}-{}", image.replace(['/', ':', '@'], "_"), &h[..16]))
}
fn image_dir(home: &Path, digest: &str) -> PathBuf {
@@ -224,7 +244,10 @@ pub fn gc(home: &Path, keep: &[String]) -> Result<u64> {
for e in fs::read_dir(home.join("images/refs"))?.flatten() {
match fs::read_to_string(e.path()) {
Ok(d) if keep.contains(&e.path()) => drop(live.insert(image_dir(home, d.trim()))),
_ => fs::remove_file(e.path())?,
_ => match fs::remove_file(e.path()) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()), // gone: a concurrent pull renamed it
_ => {}
},
}
}
let mut freed = 0;
@@ -467,14 +490,26 @@ mod tests {
#[test]
fn public_addresses() {
for ip in ["127.0.0.1", "10.1.2.3", "172.16.0.1", "192.168.64.1", "169.254.169.254", "100.64.0.1", "0.0.0.0", "::1", "fe80::1", "fd00::1", "::ffff:127.0.0.1"] {
for ip in ["127.0.0.1", "10.1.2.3", "172.16.0.1", "192.168.64.1", "169.254.169.254", "100.64.0.1", "0.0.0.0", "::1", "fe80::1", "fd00::1", "::ffff:127.0.0.1",
"64:ff9b::7f00:1", "64:ff9b::a00:1", "64:ff9b:1::1", "2002:7f00:1::1", "2002:c0a8:101::", "::7f00:1", "::a00:1",
"2001:db8::1", "2001::1", "ff02::1"] {
assert!(!is_public(ip.parse().unwrap()), "{ip} must be rejected");
}
for ip in ["8.8.8.8", "140.82.121.4", "2606:4700::6810:84e5"] {
for ip in ["8.8.8.8", "140.82.121.4", "2606:4700::6810:84e5", "64:ff9b::808:808", "2002:808:808::1", "::ffff:8.8.8.8"] {
assert!(is_public(ip.parse().unwrap()), "{ip} must be allowed");
}
}
#[test]
fn local_registries() {
for l in ["localhost:5000", "localhost", "127.0.0.1:5000", "192.168.1.5:5000"] {
assert!(explicit_local(l), "{l}");
}
for r in ["evil.127.0.0.1.nip.io:8443", "localhost.evil.com", "ghcr.io", "8.8.8.8:443", "registry-1.docker.io"] {
assert!(!explicit_local(r), "{r}");
}
}
#[test]
fn bad_refs() {
for bad in ["alpine@sha256:../../x", "../x", "a/../b", "alpine:../x", "Alpine", "a//b"] {
@@ -485,6 +520,14 @@ mod tests {
}
}
#[test]
fn ref_paths_distinct() {
let h = Path::new("/h");
assert_ne!(ref_path(h, "evil_bar:v1"), ref_path(h, "evil/bar:v1"));
assert_ne!(ref_path(h, "docker_sandbox-templates_claude-code"), ref_path(h, "docker/sandbox-templates:claude-code"));
assert_eq!(ref_path(h, "alpine"), ref_path(h, "alpine"));
}
#[test]
fn digests() {
assert!(check_digest(&format!("sha256:{}", "a".repeat(64))).is_ok());
+2 -2
View File
@@ -88,9 +88,9 @@ fn rows(h: &Path) -> Result<Vec<Row>> {
let Ok(rd) = fs::read_dir(h.join("sandboxes")) else { return Ok(vec![]) };
let mut rows = vec![];
for e in rd.flatten() {
let Ok(m) = fs::read(e.path().join("meta.json")) else { continue };
let Some(meta) = fs::read(e.path().join("meta.json")).ok().and_then(|m| serde_json::from_slice(&m).ok()) else { continue };
let running = lock_stopped(&e.path()).is_err();
rows.push(Row { name: e.file_name().to_string_lossy().into(), dir: e.path(), meta: serde_json::from_slice(&m)?, running });
rows.push(Row { name: e.file_name().to_string_lossy().into(), dir: e.path(), meta, running });
}
rows.sort_by(|a, b| a.name.cmp(&b.name));
Ok(rows)
+20 -3
View File
@@ -76,9 +76,10 @@ pub fn run(h: &Path, o: Opts, image: &str, cmd: Vec<String>, extra: &[String], g
}
if !disk.exists() {
eprintln!("wsbx: creating sandbox {name}");
create_disk(h, &disk, o.disk)?;
// meta first: it marks the image as in use for `wsbx gc` and makes a crashed create visible to ps/rm
meta = json!({"image": image, "digest": img.digest, "workspace": ws, "created": now(), "provisioned": false});
fs::write(&meta_path, serde_json::to_vec_pretty(&meta)?)?;
create_disk(h, &disk, o.disk)?;
}
// Build the guest-side run script (executed as root by init, then drops to the image user).
@@ -119,8 +120,9 @@ pub fn run(h: &Path, o: Opts, image: &str, cmd: Vec<String>, extra: &[String], g
}
}
for e in env {
if let Some((k, v)) = e.split_once('=') {
s += &format!("export {k}={}\n", sq(v));
match export(&e) {
Some(line) => s += &line,
None => eprintln!("wsbx: skipping env entry with invalid name: {e:?}"),
}
}
s += &format!("export WSBX_USER={}\n", sq(&user));
@@ -241,6 +243,13 @@ pub fn run(h: &Path, o: Opts, image: &str, cmd: Vec<String>, extra: &[String], g
}
}
/// `export K='v'` line; None unless K is a shell identifier (image Env is hostile and run.sh runs as root).
fn export(e: &str) -> Option<String> {
let (k, v) = e.split_once('=')?;
let ok = k.bytes().next().is_some_and(|b| b.is_ascii_alphabetic() || b == b'_') && k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_');
ok.then(|| format!("export {k}={}\n", sq(v)))
}
/// Small result file written by the guest; regular files only (no symlinks), size-capped.
fn guest_output(share: &Path, name: &str) -> Option<String> {
let p = share.join(name);
@@ -282,6 +291,14 @@ pub fn term_size() -> Option<(u16, u16)> {
mod tests {
use std::path::Path;
#[test]
fn env_keys() {
assert_eq!(super::export("_A1=x y").as_deref(), Some("export _A1='x y'\n"));
for bad in ["PWN$(id > /ws/pwn)=x", "=x", "1A=x", "A B=x", "A;id=x", "noequals"] {
assert!(super::export(bad).is_none(), "{bad}");
}
}
#[test]
fn vfkit_injection_rejected() {
assert!(super::vf(Path::new("/Users/me/repo")).is_ok());