From e4d026b6dfe8c6c10a58f064b26c85f2339002a3 Mon Sep 17 00:00:00 2001 From: Masih Moloodian Date: Sat, 28 Nov 2026 12:14:31 +0400 Subject: [PATCH] Networks: gateway_mode_ipv4=isolated leaves the host off an internal network An internal network's bridge still had the gateway address, so its containers reached every service listening on all of the host's addresses through it (#1001): a database, a dev server, an admin endpoint. Docker 28 closes that path with `-o com.docker.network.bridge.gateway_mode_ipv4=isolated` on an internal network, and `inhibit_ipv4=true` does the same there. Kiri accepted both and did nothing with them. - With either on an internal network, the bridge gets no IPv4 address, so the host has none on the network. Containers keep their own addresses and reach each other, by name too: with nothing listening on the gateway, they ask Kiri's resolver at 127.0.0.11 in their own network. The same holds for a container that joins with `network connect`, on a Linux host and in the Mac's VM. - The gateway options are checked as Docker checks them: a known mode (`nat`, `nat-unprotected`, `routed`, `isolated`), a boolean `inhibit_ipv4`, and `isolated` only on an internal network, with Docker's messages. The modes other than `isolated` work as before. - `gateway_mode_ipv6=isolated` on a network with IPv6 is refused for now, rather than accepted with the bridge's IPv6 address left in place. Fixes #1001 --- crates/kiri-init/src/linux/agent.rs | 5 +- crates/kiri-init/src/linux/container.rs | 3 +- crates/kiri-init/src/linux/net.rs | 39 +++++++-- crates/kiri-proto/src/lib.rs | 5 ++ crates/kiri/src/daemon/engine.rs | 6 ++ crates/kiri/src/daemon/network.rs | 100 ++++++++++++++++++++++++ docs/features.md | 6 +- tests/e2e.sh | 22 ++++++ tests/linux-host.sh | 9 +++ 9 files changed, 183 insertions(+), 12 deletions(-) diff --git a/crates/kiri-init/src/linux/agent.rs b/crates/kiri-init/src/linux/agent.rs index 413478b05..4acd7e93b 100644 --- a/crates/kiri-init/src/linux/agent.rs +++ b/crates/kiri-init/src/linux/agent.rs @@ -782,7 +782,7 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap, paths: &Paths, net: NetCtx<'_>) -> io::Result

) -> Plug { use kiri_proto::net_opts as k; - Plug { internal: k::values(opts, k::INTERNAL).next().is_some(), no_ipv4: k::values(opts, k::NO_IPV4).next().is_some() } + let has = |key| k::values(opts, key).next().is_some(); + Plug { internal: has(k::INTERNAL), no_ipv4: has(k::NO_IPV4), no_gateway4: has(k::NO_GATEWAY4) } + } + + /// Whether the bridge has an IPv4 address: Kiri's resolver can listen + /// there, and the network offers an IPv4 gateway. + pub fn bridge_has_ipv4(self) -> bool { + !self.no_ipv4 && !self.no_gateway4 } } @@ -165,7 +175,7 @@ pub struct Uplink { impl Uplink { /// None for an internal network, which never gives a default route. pub fn of(veth: &str, ifname: &str, gateway: [u8; 4], v6: Option, plug: Plug) -> Option { - let v4 = (!plug.internal && !plug.no_ipv4).then_some(gateway); + let v4 = (!plug.internal && plug.bridge_has_ipv4()).then_some(gateway); let v6 = v6.filter(|_| !plug.internal).map(|v| v.gateway); (v4.is_some() || v6.is_some()).then(|| Uplink { veth: veth.to_owned(), ifname: ifname.to_owned(), v4, v6 }) } @@ -1408,9 +1418,9 @@ fn attach_with_ns( v6: Option, plug: Plug, ) -> io::Result<()> { - let Plug { internal, no_ipv4 } = plug; + let Plug { internal, no_ipv4, .. } = plug; let mac = Some(mac.unwrap_or_else(|| mac_for(ip))); - let bridge_index = bridges.ensure(bridge, (!no_ipv4).then_some(gateway), prefix, v6)?; + let bridge_index = bridges.ensure(bridge, plug.bridge_has_ipv4().then_some(gateway), prefix, v6)?; let opened_ns; let netns = match netns_fd { Some(f) => f, @@ -1457,7 +1467,7 @@ fn attach_with_ns( } netlink::set_up(&mut inner, index)?; } - if !internal && !no_ipv4 { + if !internal && plug.bridge_has_ipv4() { netlink::add_default_route(&mut inner, index, gateway)?; } if let Some(v) = v6.filter(|_| !internal) { @@ -1581,13 +1591,26 @@ mod tests { #[test] fn internal_networks_are_no_uplink() { let v6 = Some(Ip6 { ip: [0xfd; 16], prefix: 64, gateway: [0xfd; 16] }); - assert_eq!(Uplink::of("kv1", "eth0", [10, 0, 0, 1], v6, Plug { internal: true, no_ipv4: false }), None); + assert_eq!(Uplink::of("kv1", "eth0", [10, 0, 0, 1], v6, Plug { internal: true, ..Plug::default() }), None); let u = Uplink::of("kv1", "eth1", [10, 0, 0, 1], None, Plug::default()).unwrap(); assert_eq!((u.ifname.as_str(), u.v4, u.v6), ("eth1", Some([10, 0, 0, 1]), None)); - let u = Uplink::of("kv1", "eth1", [10, 0, 0, 1], v6, Plug { internal: false, no_ipv4: true }).unwrap(); + let u = Uplink::of("kv1", "eth1", [10, 0, 0, 1], v6, Plug { no_ipv4: true, ..Plug::default() }).unwrap(); assert_eq!((u.v4, u.v6), (None, Some([0xfd; 16]))); } + /// An isolated network's bridge has no IPv4 address (#1001): no gateway + /// to route by or serve DNS on, though the container keeps its own. + #[test] + fn an_isolated_bridge_has_no_ipv4_gateway() { + let iso = Plug { internal: true, no_gateway4: true, ..Plug::default() }; + assert!(!iso.bridge_has_ipv4()); + assert!(!Plug { no_ipv4: true, ..Plug::default() }.bridge_has_ipv4()); + assert!(Plug { internal: true, ..Plug::default() }.bridge_has_ipv4(), "a plain internal network keeps its gateway"); + assert_eq!(Uplink::of("kv1", "eth0", [10, 0, 0, 1], None, iso), None); + let u = Uplink::of("kv1", "eth1", [10, 0, 0, 1], None, Plug { no_gateway4: true, ..Plug::default() }); + assert_eq!(u.and_then(|u| u.v4), None, "never an IPv4 default route by a gateway that isn't there"); + } + #[test] fn the_first_uplink_with_each_family_holds_its_default_route() { let ups = [up("a", false, true), up("b", true, false), up("c", true, true)]; @@ -1604,7 +1627,7 @@ mod tests { let mut ups = Vec::new(); ups.extend(Uplink::of("kva0", "eth0", gw_a, None, Plug::default())); // An internal network attached in between produces no uplink. - ups.extend(Uplink::of("kxi1", "eth1", [10, 98, 9, 1], None, Plug { internal: true, no_ipv4: false })); + ups.extend(Uplink::of("kxi1", "eth1", [10, 98, 9, 1], None, Plug { internal: true, ..Plug::default() })); ups.extend(Uplink::of("kxz2", "eth2", gw_zeta, None, Plug::default())); ups.extend(Uplink::of("kxb3", "eth3", gw_beta, None, Plug::default())); diff --git a/crates/kiri-proto/src/lib.rs b/crates/kiri-proto/src/lib.rs index c49234412..fa2a9c8e2 100644 --- a/crates/kiri-proto/src/lib.rs +++ b/crates/kiri-proto/src/lib.rs @@ -561,6 +561,11 @@ pub mod net_opts { /// only the name the guest keeps it by: neither it nor the bridge gets /// one, and DNS has no A record for it. pub const NO_IPV4: &str = "noipv4"; + /// `nogw4=1`: the bridge has no IPv4 address (`gateway_mode_ipv4=isolated` + /// on an internal network), so the host isn't on the network. The + /// container keeps its own address; it has no default route anyway, and + /// asks Kiri's resolver at 127.0.0.11, as nothing listens on the gateway. + pub const NO_GATEWAY4: &str = "nogw4"; /// `dnsbridge=kiri3`, one per network: a user network the container /// joins once it runs (`NetAttach`). Its embedded DNS answers that /// network's names from the start, as Docker's does with every network diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 87e58e6a6..c6d5b3ab2 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -4285,6 +4285,9 @@ impl Engine { if n.no_ipv4 { net6_opts.push(format!("{}=1", kiri_proto::net_opts::NO_IPV4)); } + if n.no_gateway4() { + net6_opts.push(format!("{}=1", kiri_proto::net_opts::NO_GATEWAY4)); + } net6_opts.push(format!("{}={}", kiri_proto::net_opts::NETWORK, n.name)); } Err(e) => { @@ -5292,6 +5295,9 @@ impl Engine { if net.no_ipv4 { opts.push(format!("{}=1", kiri_proto::net_opts::NO_IPV4)); } + if net.no_gateway4() { + opts.push(format!("{}=1", kiri_proto::net_opts::NO_GATEWAY4)); + } opts.push(format!("{}={}", kiri_proto::net_opts::NETWORK, net.name)); if let Err(e) = vm.net_attach(id, n, &net.bridge, ip, net.prefix, net.gateway, &names, &opts) { self.release_attached_ips(&net.name, Some(ip), ip6); diff --git a/crates/kiri/src/daemon/network.rs b/crates/kiri/src/daemon/network.rs index 216666d01..1b56bb90b 100644 --- a/crates/kiri/src/daemon/network.rs +++ b/crates/kiri/src/daemon/network.rs @@ -389,6 +389,67 @@ fn checked_options(options: serde_json::Value) -> Result(options: &'a serde_json::Value, key: &str) -> Option<&'a str> { + options.get(key).map(|v| v.as_str().unwrap_or("?")) +} + +/// Go's `strconv.ParseBool`, which Docker reads `inhibit_ipv4` with. +fn go_bool(v: &str) -> Option { + match v { + "1" | "t" | "T" | "true" | "TRUE" | "True" => Some(true), + "0" | "f" | "F" | "false" | "FALSE" | "False" => Some(false), + _ => None, + } +} + +/// The gateway options, checked as Docker's bridge driver checks them: +/// a known mode, a boolean `inhibit_ipv4`, and `isolated` only on an +/// internal network. Kiri gives every other mode the default (`nat`), as +/// before. An isolated IPv6 gateway isn't done yet, so a network with IPv6 +/// is refused it rather than given one anyway. +fn checked_gateway_options(options: &serde_json::Value, internal: bool, ipv6: bool) -> Result<(), String> { + let mut isolated = [false; 2]; + for (i, key) in [GATEWAY_MODE4_OPT, GATEWAY_MODE6_OPT].into_iter().enumerate() { + match opt_str(options, key) { + None | Some("" | "nat" | "nat-unprotected" | "routed") => {} + Some("isolated") => isolated[i] = true, + Some(v) => return Err(format!("failed to parse {key} value: {v} (unknown gateway mode {v})")), + } + } + if let Some(v) = opt_str(options, INHIBIT_IPV4_OPT) + && go_bool(v).is_none() + { + return Err(format!("failed to parse {INHIBIT_IPV4_OPT} value: {v} (strconv.ParseBool: parsing {v:?}: invalid syntax)")); + } + if isolated.contains(&true) && !internal { + return Err("gateway mode 'isolated' can only be used for an internal network".into()); + } + if isolated[1] && ipv6 { + return Err(format!("Kiri does not support {GATEWAY_MODE6_OPT}=isolated yet: the bridge would still have its IPv6 address. Leave it out, or use an IPv4-only internal network with {GATEWAY_MODE4_OPT}=isolated")); + } + Ok(()) +} + +impl Network { + /// Whether the bridge has no IPv4 address (`gateway_mode_ipv4=isolated`, + /// or `inhibit_ipv4` on an internal network): the host is not on the + /// network, and its containers ask Kiri's resolver at 127.0.0.11. + pub fn no_gateway4(&self) -> bool { + self.internal && (opt_str(&self.options, GATEWAY_MODE4_OPT) == Some("isolated") || opt_str(&self.options, INHIBIT_IPV4_OPT).and_then(go_bool) == Some(true)) + } +} + /// A network's options as inspect shows them: a bridge name that is not the /// bridge's own (kept by a Kiri that did not refuse it) is left out. pub fn shown_options(n: &Network) -> serde_json::Value { @@ -728,6 +789,7 @@ impl Networks { return Err("invalid network config: IPv4 or IPv6 must be enabled".into()); } let options = checked_options(s.options.clone())?; + checked_gateway_options(&options, s.internal, s.ipv6)?; if s.no_ipv4 && s.ipam.is_some() { return Err("invalid network config: an IPv4 subnet was given, but IPv4 is disabled (--ipv4=false)".into()); } @@ -1359,6 +1421,44 @@ mod tests { let _ = std::fs::remove_dir_all(dir); } + /// `gateway_mode_ipv4=isolated` (and `inhibit_ipv4` on an internal + /// network) leaves the host off the network (#1001), with Docker's own + /// checks: `isolated` only on an internal network, a known mode, a + /// boolean. The other modes are kept as before. + #[test] + fn an_isolated_gateway_is_for_internal_networks_only() { + let (mut n, dir) = nets(); + let with = |internal: bool, opts: serde_json::Value| Settings { internal, options: opts, ..Default::default() }; + let iso = n.create("iso", with(true, serde_json::json!({GATEWAY_MODE4_OPT: "isolated"}))).unwrap(); + assert!(iso.no_gateway4()); + assert!(n.create("inhibit", with(true, serde_json::json!({INHIBIT_IPV4_OPT: "true"}))).unwrap().no_gateway4()); + assert!(!n.create("inhibit-off", with(true, serde_json::json!({INHIBIT_IPV4_OPT: "false"}))).unwrap().no_gateway4()); + assert!(!n.create("plain-internal", with(true, serde_json::json!({}))).unwrap().no_gateway4()); + // Outside an internal network inhibit_ipv4 is kept, as before: Docker + // leaves such a bridge to be set up by hand, which Kiri doesn't do. + assert!(!n.create("inhibit-outside", with(false, serde_json::json!({INHIBIT_IPV4_OPT: "true"}))).unwrap().no_gateway4()); + for mode in ["nat", "nat-unprotected", "routed"] { + let made = n.create(&format!("m-{mode}"), with(false, serde_json::json!({GATEWAY_MODE4_OPT: mode}))).unwrap(); + assert!(!made.no_gateway4() && made.options[GATEWAY_MODE4_OPT] == mode, "{mode}"); + } + let refused = [ + (with(false, serde_json::json!({GATEWAY_MODE4_OPT: "isolated"})), "gateway mode 'isolated' can only be used for an internal network".to_owned()), + (with(false, serde_json::json!({GATEWAY_MODE6_OPT: "isolated"})), "gateway mode 'isolated' can only be used for an internal network".to_owned()), + (with(true, serde_json::json!({GATEWAY_MODE4_OPT: "closed"})), format!("failed to parse {GATEWAY_MODE4_OPT} value: closed (unknown gateway mode closed)")), + (with(true, serde_json::json!({INHIBIT_IPV4_OPT: "yes"})), format!("failed to parse {INHIBIT_IPV4_OPT} value: yes (strconv.ParseBool: parsing \"yes\": invalid syntax)")), + ]; + for (i, (settings, want)) in refused.into_iter().enumerate() { + assert_eq!(n.create(&format!("bad{i}"), settings).unwrap_err(), want); + assert!(n.find(&format!("bad{i}")).is_none(), "nothing made"); + } + // An isolated IPv6 gateway isn't done: refused on a network with IPv6, + // and nothing to do on one without. + let e = n.create("iso6", Settings { internal: true, options: serde_json::json!({GATEWAY_MODE6_OPT: "isolated"}), ..v6(None) }).unwrap_err(); + assert!(e.starts_with("Kiri does not support com.docker.network.bridge.gateway_mode_ipv6=isolated yet"), "{e}"); + 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); + } + /// A bridge name of the user's own is refused: Kiri's firewall knows /// its bridges by their `kiri` prefix. An empty one is Docker's unset; /// one kept by an older Kiri is not shown in inspect. diff --git a/docs/features.md b/docs/features.md index 4b362884e..dbb0eee18 100644 --- a/docs/features.md +++ b/docs/features.md @@ -21,7 +21,11 @@ Apple silicon and Intel Macs (macOS 14+), Windows 10 and 11 (x86-64 and Arm, thr privileged and unconfined containers keep the host boundary: no vsock sockets (the way to the Mac) and no io_uring - **Networking**: a default bridge, user networks with DNS by name and - alias, `network connect`/`disconnect` (as with Docker, a container can + alias, `--internal` networks (with + `-o com.docker.network.bridge.gateway_mode_ipv4=isolated`, or + `inhibit_ipv4=true`, the bridge has no IPv4 address, so the host isn't on + the network for its containers to reach; the IPv6 counterpart is refused + for now), `network connect`/`disconnect` (as with Docker, a container can leave any of its networks, its first one too: another of its networks then gives its default route, and with none left it has no network, as with `--network none`; to leave its first network a running container is diff --git a/tests/e2e.sh b/tests/e2e.sh index e488b0e2c..57e697233 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -773,6 +773,28 @@ t internal-no-default "none" $D run --rm --network intnet alpine sh -c 'ip route # An IPv4-only network: IPv6 is off on eth0 (no link-local), lo keeps ::1. t v4-net-no-inet6 "none" $D run --rm --network intnet alpine sh -c 'ip -6 addr show eth0 | grep -q inet6 && echo some || echo none' $D rm -f intweb >/dev/null; $D network rm intnet >/dev/null +# gateway_mode_ipv4=isolated (#1001): an internal network whose bridge has +# no IPv4 address, so the host isn't on it. A plain internal network's +# containers reach a server on every host address through the gateway; an +# isolated one's don't, while its containers still find each other by name +# (Kiri's resolver answers at 127.0.0.11 in each). +$D rm -f isohost isoweb >/dev/null 2>&1; $D network rm isonet plainint >/dev/null 2>&1 +$D network create --internal plainint >/dev/null +$D network create --internal -o com.docker.network.bridge.gateway_mode_ipv4=isolated isonet >/dev/null +$D run -d --name isohost --network host busybox:1.36 httpd -f -p 18997 -h /tmp >/dev/null +$D run -d --name isoweb --network isonet nginx:alpine >/dev/null +nginx_up isoweb +gw_of() { $D network inspect "$1" -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}'; } +t isolated-plain-internal-reaches-host "reached" $D run --rm --network plainint alpine sh -c "nc -z -w 3 $(gw_of plainint) 18997 && echo reached || echo unreached" +t isolated-host-unreached "unreached" $D run --rm --network isonet alpine sh -c "nc -z -w 3 $(gw_of isonet) 18997 && echo reached || echo unreached" +t isolated-names "Welcome to nginx" $D run --rm --network isonet alpine wget -qO- -T 5 http://isoweb +t isolated-resolver "nameserver 127.0.0.11" $D run --rm --network isonet alpine grep nameserver /etc/resolv.conf +t isolated-option-shown "isolated" $D network inspect isonet -f '{{index .Options "com.docker.network.bridge.gateway_mode_ipv4"}}' +# The same through a connect, the network a running container joins. +t isolated-connect-unreached "unreached" bash -c "$D rm -f isoconn >/dev/null 2>&1; $D run -d --name isoconn --network plainint alpine sleep 60 >/dev/null && $D network connect isonet isoconn && $D exec isoconn sh -c 'nc -z -w 3 $(gw_of isonet) 18997 && echo reached || echo unreached'; $D rm -f isoconn >/dev/null" +# Only for an internal network, as in Docker. +t isolated-needs-internal "gateway mode 'isolated' can only be used for an internal network" $D network create -o com.docker.network.bridge.gateway_mode_ipv4=isolated isoext +$D rm -f isohost isoweb >/dev/null; $D network rm isonet plainint >/dev/null section "networking options" # IPAM: a chosen subnet, gateway, range and reserved address. diff --git a/tests/linux-host.sh b/tests/linux-host.sh index 5b734a3ed..ee1b9e0f3 100755 --- a/tests/linux-host.sh +++ b/tests/linux-host.sh @@ -194,6 +194,15 @@ t disconnect-hands-ipv6-default-on "default via fd00:193:2::1 dev eth2" "docker # An IPv6 IPAM subnet without --ipv6 is ignored, as Docker does (#433): # both with an IPv4 subnet (mailcow-dockerized) and with only an IPv6 subnet. t network-ipv6-subnet-ignored-when-disabled "false 1 10.234.0.0/24 false 1 v4" "docker network create --subnet 10.234.0.0/24 --subnet fd4d:6169:6c63:6f77::/64 lh6off >/dev/null && a=\$(docker network inspect lh6off -f '{{.EnableIPv6}} {{len .IPAM.Config}} {{(index .IPAM.Config 0).Subnet}}') && docker network create --subnet fd4d:6169:6c63:6f77::/64 lh6off-auto >/dev/null && b=\$(docker network inspect lh6off-auto -f '{{.EnableIPv6}} {{len .IPAM.Config}}') && s=\$(docker network inspect lh6off-auto -f '{{(index .IPAM.Config 0).Subnet}}') && case \"\$s\" in *.*/*) v=v4;; *) v=bad:\$s;; esac && echo \"\$a \$b \$v\"; docker network rm lh6off lh6off-auto >/dev/null 2>&1" +# gateway_mode_ipv4=isolated (#1001): the host has no address on an +# internal network's bridge, so a service on every host address isn't +# reached through the gateway; without it, it is. Names still resolve. +t isolated-setup "up" "docker network create --internal lh-plain >/dev/null && docker network create --internal -o com.docker.network.bridge.gateway_mode_ipv4=isolated lh-iso >/dev/null && docker run -d --name lh-isohost --network host alpine nc -lk -p 18997 -e true >/dev/null && docker run -d --name lh-isoweb --network lh-iso nginx:alpine >/dev/null && echo up" +t isolated-plain-reaches-host "reached" "gw=\$(docker network inspect lh-plain -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}') && docker run --rm --network lh-plain alpine sh -c \"nc -z -w 3 \$gw 18997 && echo reached || echo unreached\"" +t isolated-host-unreached "unreached" "gw=\$(docker network inspect lh-iso -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}') && docker run --rm --network lh-iso alpine sh -c \"nc -z -w 3 \$gw 18997 && echo reached || echo unreached\"" +t isolated-bridge-no-ipv4 "none" "gw=\$(docker network inspect lh-iso -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}'); ip -4 -o addr | grep -q \" \$gw/\" && echo \"\$gw is on the host\" || echo none" +t isolated-names "Welcome to nginx" "for i in \$(seq 30); do docker run --rm --network lh-iso alpine wget -qO- -T 3 http://lh-isoweb 2>/dev/null && break; sleep 0.3; done" +t isolated-cleanup "gone" "docker rm -f lh-isohost lh-isoweb >/dev/null; docker network rm lh-plain lh-iso >/dev/null && echo gone" # A build's --add-host host-gateway is the bridge gateway, as for docker run (not the Mac VM's 198.19.248.254). t build-host-gateway "GW-OK" "gw=\$(docker network inspect bridge --format '{{(index .IPAM.Config 0).Gateway}}'); mkdir -p /bhg && printf 'FROM $KIRI_REG/alpine:3.21\\nRUN grep -w hgw /etc/hosts\\n' > /bhg/Dockerfile && DOCKER_BUILDKIT=0 docker build --no-cache --add-host hgw:host-gateway /bhg 2>&1 | grep -q \"\$gw\" && echo GW-OK" # A privileged container must not touch the host's /dev. The kernel has one