Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions crates/kiri/src/daemon/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 5 additions & 0 deletions crates/kiri/src/daemon/mirror.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u16> {
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<Engine>) {
Expand Down
54 changes: 53 additions & 1 deletion crates/kiri/src/daemon/ports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)?;
Expand All @@ -1722,6 +1729,33 @@ fn dial_loopback(port: u16) -> io::Result<TcpStream> {
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<bool> = 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.
Expand Down Expand Up @@ -3520,7 +3554,7 @@ pub fn listening<S: AsRef<str>>(lines: &[S], host_network: bool) -> (Vec<u16>, 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;

Expand All @@ -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]
Expand Down
5 changes: 4 additions & 1 deletion docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<name>` (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`,
Expand Down
10 changes: 10 additions & 0 deletions tests/e2e.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down