diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 87e58e6a6..047f1384a 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -2134,6 +2134,9 @@ impl Engine { })?); // host.docker.internal: the guest dials back for each connection. vm.listen(super::ports::HOST_BOUND_PORT, Box::new(super::ports::serve_host_bound))?; + if !super::ports::host_loopback() { + crate::diag::info!("containers don't reach this Mac's loopback through host.docker.internal (KIRI_HOST_LOOPBACK=off)"); + } // Outbound container TCP to VPN tunnel routes or under host egress. vm.listen(kiri_proto::EGRESS_TCP_PORT, Box::new(super::ports::serve_egress))?; // SSH agent forwarding, for containers that mount /run/host-services/ssh-auth.sock. diff --git a/crates/kiri/src/daemon/mirror.rs b/crates/kiri/src/daemon/mirror.rs index cf5c7a057..41acb1876 100644 --- a/crates/kiri/src/daemon/mirror.rs +++ b/crates/kiri/src/daemon/mirror.rs @@ -77,6 +77,11 @@ fn save_token(path: &std::path::Path, token: &str) -> io::Result<()> { std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(path)?.write_all(token.as_bytes()) } +/// The port the mirror listens on, on this computer's loopback, once it does. +pub fn port() -> Option { + LISTENING.get().copied().flatten().map(|l| l.port) +} + /// Starts the server (at the daemon's start: a listening socket costs /// nothing while no build asks). pub fn start(engine: &Arc) { diff --git a/crates/kiri/src/daemon/ports.rs b/crates/kiri/src/daemon/ports.rs index a747061f3..178d7a182 100644 --- a/crates/kiri/src/daemon/ports.rs +++ b/crates/kiri/src/daemon/ports.rs @@ -1698,6 +1698,13 @@ fn host_bound(stream: kiri_vmm::VsockStream) -> io::Result<()> { crate::diag::warn!("refused a host-bound connection; only 127.0.0.1 is relayed, and never to a container-domain router", to = format!("{ip}:{port}")); return Err(io::Error::new(io::ErrorKind::PermissionDenied, "not relayed")); } + if !loopback_relayed(host_loopback(), port, |p| super::mirror::port() == Some(p)) { + // Once a daemon: a CI job probing host.docker.internal would fill the log. + if !LOOPBACK_REFUSAL_LOGGED.swap(true, std::sync::atomic::Ordering::Relaxed) { + crate::diag::info!("refused a container's connection to this Mac's loopback: KIRI_HOST_LOOPBACK is off (logged once)", port = port); + } + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "host loopback is off")); + } // 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)?; @@ -1722,6 +1729,33 @@ fn dial_loopback(port: u16) -> io::Result { TcpStream::connect((std::net::Ipv4Addr::LOCALHOST, port)).or_else(|e| TcpStream::connect((std::net::Ipv6Addr::LOCALHOST, port)).map_err(|_| e)) } +/// Whether containers reach this Mac's loopback through `host.docker.internal` +/// (`host.kiri.internal`, `host-gateway`). On by default, as with Docker +/// Desktop and OrbStack (#258). `KIRI_HOST_LOOPBACK=off` (or `0`, `false`, +/// `no`) in the daemon's environment turns it off, for workloads that must +/// not reach the services listening on 127.0.0.1 and ::1, such as CI jobs +/// (#995): pf can't stop the engine's own connections there, since macOS +/// skips lo0 while a VM runs. Read once, when the daemon starts. +pub fn host_loopback() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| host_loopback_from(std::env::var("KIRI_HOST_LOOPBACK").ok().as_deref())) +} + +/// `KIRI_HOST_LOOPBACK`'s value: only an explicit off turns it off, so a +/// typo leaves Kiri as it was. +fn host_loopback_from(v: Option<&str>) -> bool { + !v.map(str::trim).is_some_and(|v| ["off", "0", "false", "no"].iter().any(|o| v.eq_ignore_ascii_case(o))) +} + +static LOOPBACK_REFUSAL_LOGGED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Whether a host-bound connection to `port` is relayed to the Mac's +/// loopback. With it off, only Kiri's own server there is: the image +/// mirror builds pull through (token-checked, and the engine's own). +fn loopback_relayed(on: bool, port: u16, kiris_own: impl Fn(u16) -> bool) -> bool { + on || kiris_own(port) +} + /// The guest's relay only ever asks for the Mac's loopback; anything else is /// a guest process speaking the protocol itself. A router's port is refused /// too: it serves this Mac, and would take a container to any container. @@ -3520,7 +3554,7 @@ pub fn listening>(lines: &[S], host_network: bool) -> (Vec, V #[cfg(test)] mod tests { - use super::{MAX_PEER_SESSIONS, MAX_REMOTE_SESSIONS, MAX_TCP_SESSIONS, NAT_PORTS, REMOTE_SESSIONS, TCP_SESSIONS, dial_loopback, host_bound_allowed, kernel_forwards, kernel_host_ip, listening, nat_port, relays_too, tcp_permit}; + use super::{MAX_PEER_SESSIONS, MAX_REMOTE_SESSIONS, MAX_TCP_SESSIONS, NAT_PORTS, REMOTE_SESSIONS, TCP_SESSIONS, dial_loopback, host_bound_allowed, host_loopback_from, kernel_forwards, kernel_host_ip, listening, loopback_relayed, nat_port, relays_too, tcp_permit}; use std::net::IpAddr; use std::sync::atomic::Ordering; @@ -3537,6 +3571,24 @@ mod tests { assert!(!host_bound_allowed(std::net::Ipv4Addr::new(10, 0, 0, 1), 5432, router), "loopback only"); } + /// `KIRI_HOST_LOOPBACK=off` keeps containers away from the Mac's + /// loopback (#995), all but the engine's own image mirror, which builds + /// pull through. Unset, or anything but an off, leaves it as it was. + #[test] + fn host_loopback_off_refuses_all_but_the_mirror() { + for off in ["off", "OFF", " 0 ", "false", "no"] { + assert!(!host_loopback_from(Some(off)), "{off:?}"); + } + for on in [None, Some(""), Some("on"), Some("1"), Some("yes"), Some("of")] { + assert!(host_loopback_from(on), "{on:?}"); + } + let mirror = |p: u16| p == 5050; + assert!(loopback_relayed(true, 5432, mirror), "on: every port"); + assert!(!loopback_relayed(false, 5432, mirror), "off: a Mac service is refused"); + assert!(loopback_relayed(false, 5050, mirror), "off: Kiri's own mirror still answers builds"); + assert!(!loopback_relayed(false, 5050, |_| false), "off, with no mirror: nothing"); + } + /// A Mac server on `::1` only (Node's `localhost`) is reached; one on /// both loopbacks is reached on 127.0.0.1, as before (#258). #[test] diff --git a/docs/features.md b/docs/features.md index 4b362884e..e729e1bbc 100644 --- a/docs/features.md +++ b/docs/features.md @@ -27,7 +27,10 @@ Apple silicon and Intel Macs (macOS 14+), Windows 10 and 11 (x86-64 and Arm, thr with `--network none`; to leave its first network a running container is stopped first), `--network host|none`, `-p`/`-P` (TCP and UDP) on all interfaces (as Docker does; `-p 127.0.0.1:8080:80` - keeps a port local), `--add-host`, `host.docker.internal`, + keeps a port local), `--add-host`, `host.docker.internal` (on a Mac it + reaches the Mac's own 127.0.0.1 and ::1; for untrusted workloads such as + CI jobs, `KIRI_HOST_LOOPBACK=off` in the daemon's environment turns that + off, and only Kiri's build mirror stays reachable there), `--network container:` (Compose `network_mode: service:x`; as with Docker, if that container restarts, the ones sharing its network keep the old, now empty namespace until they are restarted too), IPAM (`--subnet`, diff --git a/tests/e2e.sh b/tests/e2e.sh index e488b0e2c..a6343db31 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -957,9 +957,19 @@ python3 -m http.server 18999 --bind $HTTP_BIND --directory "$HTTP_DIR" >/dev/nul HTTP_PID=$! [ "$SYS" = mac ] || { python3 -m http.server 18998 --bind 127.0.0.1 --directory "$HTTP_DIR" >/dev/null 2>&1 & HTTP_LO_PID=$!; } sleep 0.7 +# A daemon started with KIRI_HOST_LOOPBACK=off (#995): containers don't +# reach the Mac's loopback, though the name still resolves. Run the suite +# with the same variable set to check it: `KIRI_HOST_LOOPBACK=off kiri +# daemon`, then `KIRI_HOST_LOOPBACK=off tests/e2e.sh`. +if [ "$SYS" = mac ] && [ "${KIRI_HOST_LOOPBACK:-}" = off ]; then + t host-loopback-off "refused 198.19.248.254" $D run --rm alpine sh -c 'r=refused; wget -qO- -T 5 http://host.docker.internal:18999/ >/dev/null 2>&1 && r=reached; echo "$r $(getent hosts host.docker.internal | cut -d" " -f1)"' + t host-loopback-off-gateway "refused" $D run --rm --add-host mac:host-gateway alpine sh -c 'wget -qO- -T 5 http://mac:18999/ >/dev/null 2>&1 && echo reached || echo refused' + t host-loopback-off-hostnet "refused" $D run --rm --network host alpine sh -c 'wget -qO- -T 5 http://host.docker.internal:18999/ >/dev/null 2>&1 && echo reached || echo refused' +else t host-internal "Directory listing" $D run --rm alpine wget -qO- http://host.docker.internal:18999/ t host-gateway "Directory listing" $D run --rm --add-host mac:host-gateway alpine wget -qO- http://mac:18999/ t host-internal-hostnet "Directory listing" $D run --rm --network host alpine wget -qO- http://host.docker.internal:18999/ +fi # A port published on 127.0.0.1 or on every address is in the host's own # network, as Docker binds it: a --network host container reaches it at # 127.0.0.1 and localhost (::1 first in musl) (#732; a host-network