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
5 changes: 3 additions & 2 deletions crates/kiri-init/src/linux/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -782,15 +782,16 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap<libc::pid_t, Pr
let is_user = n.bridge != "kiri0";
let attached = net::attach(&mut bridges, n.bridge, &host_if, pid, num, n.ip, n.prefix, n.gateway, mac, v6, plug).and_then(|()| {
if !is_user {
if !plug.no_ipv4 && dns.relay {
if plug.bridge_has_ipv4() && dns.relay {
dns.serve_or_warn(n.bridge, n.gateway);
}
return Ok(());
}
// A gateway that won't take the listener doesn't
// stop the connect: names answer at 127.0.0.11 in
// the container (dns.rs `serve_or_warn`, #477).
if !plug.no_ipv4 {
// No address on an isolated network's bridge (#1001).
if plug.bridge_has_ipv4() {
dns.serve_or_warn(n.bridge, n.gateway);
}
let res = std::fs::File::open(format!("/proc/{pid}/ns/net")).and_then(|ns| dns.serve_in(&ns, pid, n.bridge));
Expand Down
3 changes: 2 additions & 1 deletion crates/kiri-init/src/linux/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -868,7 +868,8 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result<P
// and its containers no A records.
// A gateway that won't take the listener doesn't stop the start
// (dns.rs `serve_or_warn`, #477).
let gateway = (!plug.no_ipv4 && net.dns.serve_or_warn(spec.net.bridge, spec.net.gateway)).then_some(spec.net.gateway);
// An isolated one's has none either (#1001).
let gateway = (plug.bridge_has_ipv4() && net.dns.serve_or_warn(spec.net.bridge, spec.net.gateway)).then_some(spec.net.gateway);
// 127.0.0.11 in the container, when it is the resolver. Not when
// the gateway is (the default bridge in the VM, or on a host
// whose resolver is one of its own addresses): the listener would
Expand Down
39 changes: 31 additions & 8 deletions crates/kiri-init/src/linux/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,12 +139,22 @@ pub struct Plug {
pub internal: bool,
/// IPv6-only: no IPv4 address on the container or the bridge.
pub no_ipv4: bool,
/// `gateway_mode_ipv4=isolated` (#1001): no IPv4 address on the bridge,
/// so the host isn't on the network; the container keeps its own.
pub no_gateway4: bool,
}

impl Plug {
pub fn from_opts(opts: kiri_proto::StrList<'_>) -> 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
}
}

Expand All @@ -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<Ip6>, plug: Plug) -> Option<Uplink> {
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 })
}
Expand Down Expand Up @@ -1408,9 +1418,9 @@ fn attach_with_ns(
v6: Option<Ip6>,
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,
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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)];
Expand All @@ -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()));

Expand Down
5 changes: 5 additions & 0 deletions crates/kiri-proto/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions crates/kiri/src/daemon/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down Expand Up @@ -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);
Expand Down
100 changes: 100 additions & 0 deletions crates/kiri/src/daemon/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,67 @@ fn checked_options(options: serde_json::Value) -> Result<serde_json::Value, Stri
Ok(serde_json::Value::Object(map))
}

/// `--opt com.docker.network.bridge.gateway_mode_ipv4=isolated` (Docker
/// 28): the bridge gets no IPv4 address, so the host has none on an
/// internal network for its containers to reach (#1001).
pub const GATEWAY_MODE4_OPT: &str = "com.docker.network.bridge.gateway_mode_ipv4";
/// `gateway_mode_ipv4`'s IPv6 counterpart.
pub const GATEWAY_MODE6_OPT: &str = "com.docker.network.bridge.gateway_mode_ipv6";
/// `--opt com.docker.network.bridge.inhibit_ipv4=true`: on an internal
/// network the same as `gateway_mode_ipv4=isolated`, as in Docker.
pub const INHIBIT_IPV4_OPT: &str = "com.docker.network.bridge.inhibit_ipv4";

/// An option's value as Docker reads it: a string (`--opt` gives only those).
fn opt_str<'a>(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<bool> {
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 {
Expand Down Expand Up @@ -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());
}
Expand Down Expand Up @@ -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.
Expand Down
6 changes: 5 additions & 1 deletion docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 22 additions & 0 deletions tests/e2e.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading