diff --git a/docs/4-implementation/networking/network.md b/docs/4-implementation/networking/network.md index 2fab0bc59..198aaf934 100644 --- a/docs/4-implementation/networking/network.md +++ b/docs/4-implementation/networking/network.md @@ -748,6 +748,15 @@ also refuses the flow. (`/var/lib/hive-squid/ssh-connections`), and `hive-egress-pin` fills the set from the file like `direct_mac`, when the file changes and on its timer. The set is empty while the file is missing or empty. +- **The swarm's own endpoints.** The same file carries a `* ` + line for each address and port an agent needs on the swarm itself and that + does not sit on the bridge: the secret store, the log and metrics stores and + the queue (`HIVE_AGENT_BAO_ADDR`, `HIVE_AGENT_LOGS_QUERY_URL`, + `HIVE_AGENT_METRICS_URL` and `HIVE_AGENT_NATS_URL` in the environment of + `hive-c0re`). `hive-egress-pin` expands a `*` line to every agent's MAC, so + `reject` does not stop an agent from reaching them when they run on another + host. The forge and matrix gateways need no line: the hive's resolver answers + their names with the bridge address, which the forward chain never sees. - **What `reject` refuses.** Everything from the bridge to the uplink that the chain didn't exempt or allow, whether a flow is new or not: TCP on any port but the 80 and 443 that squid takes, UDP (DNS to an outside resolver, QUIC diff --git a/docs/4-implementation/swarm/ssh-ca.md b/docs/4-implementation/swarm/ssh-ca.md index 1498236f5..ac9ee30c5 100644 --- a/docs/4-implementation/swarm/ssh-ca.md +++ b/docs/4-implementation/swarm/ssh-ca.md @@ -177,7 +177,9 @@ the agents it has: bridge subnet (`HIVE_NETWORK_SUBNET`) with one warning per host, because a flow to the bridge never reaches the forward chain. It writes ` ` lines to `egress.connectionsFile`, beside squid's - users file. + users file. It adds a `* ` line for each endpoint of the swarm + itself that agents use (store, queue, logs and metrics), resolved the same + way, which `egress-pin` allows to every agent. 2. `hive-priv egress-pin` maps each agent to the MAC of its port and fills the `agent_allow` set of the `inet hive_egress` table, in the same transaction as `direct_mac`. `hive-egress-connections.path` runs a pass when the file diff --git a/hive-c0re/src/workers/egress_connections.rs b/hive-c0re/src/workers/egress_connections.rs index 955c85172..5718c6377 100644 --- a/hive-c0re/src/workers/egress_connections.rs +++ b/hive-c0re/src/workers/egress_connections.rs @@ -10,6 +10,10 @@ //! MAC of the agent's port, which only hive-priv can tell. IPv6 answers are //! left out: the agent bridge has no IPv6 addressing. //! +//! The swarm's own endpoints (store, queue, logs, metrics: [`ENDPOINT_ENVS`]) +//! render as `* `, `*` standing for every agent. An older +//! `hive-priv` skips such a line. +//! //! A host name is resolved by the system resolver, so it means what it means //! to the host's other services; an IPv4 literal is taken as it is. Every //! address a name resolves to is allowed, as the agent may use any of them. @@ -62,6 +66,52 @@ pub const ENV_FILE: &str = "HIVE_EGRESS_CONNECTIONS_FILE"; /// (`10.42.0.1/24`); `nix/host-modules/hive-network.nix` sets it for the daemon. const ENV_SUBNET: &str = "HIVE_NETWORK_SUBNET"; +/// The agent column of a line for every agent. +const ALL_AGENTS: &str = "*"; + +/// The environment variables holding the URLs of the swarm endpoints every +/// agent uses, as the agents are configured with them +/// (`nix/host-modules/hive-c0re/environment.nix`): the secret store, the logs +/// query, the metrics query and the swarm queue. +const ENDPOINT_ENVS: [&str; 4] = [ + "HIVE_AGENT_BAO_ADDR", + "HIVE_AGENT_LOGS_QUERY_URL", + "HIVE_AGENT_METRICS_URL", + "HIVE_AGENT_NATS_URL", +]; + +/// The host and TCP port of a URL: its port, or the scheme's own when it names +/// none (443 for `https`, 80 for `http`, 4222 for `tls` and `nats`). `None` for +/// any other scheme, an IPv6 literal (the bridge has no IPv6) and an empty host. +fn endpoint_of(url: &str) -> Option<(String, u16)> { + let (scheme, rest) = url.split_once("://")?; + let default = match scheme { + "https" => 443, + "http" => 80, + "tls" | "nats" => 4222, + _ => return None, + }; + let authority = rest.split(['/', '?', '#']).next()?; + let authority = authority.rsplit_once('@').map_or(authority, |(_, a)| a); + if authority.starts_with('[') { + return None; + } + let (host, port) = match authority.split_once(':') { + Some((host, port)) => (host, port.parse().ok().filter(|p| *p != 0)?), + None => (authority, default), + }; + (!host.is_empty()).then(|| (host.to_owned(), port)) +} + +/// The endpoints [`ENDPOINT_ENVS`] name in this process's environment. +fn endpoints_from_env() -> BTreeSet<(String, u16)> { + ENDPOINT_ENVS + .iter() + .filter_map(|name| std::env::var(name).ok()) + .filter_map(|url| endpoint_of(&url)) + .collect() +} + /// An IPv4 subnet. #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct Subnet { @@ -94,9 +144,17 @@ struct Target { port: u16, } -/// The connections of every agent whose `ssh` switch is on. -fn targets(perms: &permissions::Stored) -> BTreeSet { - let mut out = BTreeSet::new(); +/// The connections of every agent whose `ssh` switch is on, and the +/// `endpoints` every agent may reach. +fn targets(perms: &permissions::Stored, endpoints: &BTreeSet<(String, u16)>) -> BTreeSet { + let mut out: BTreeSet = endpoints + .iter() + .map(|(host, port)| Target { + agent: ALL_AGENTS.to_owned(), + host: host.clone(), + port: *port, + }) + .collect(); for (agent, record) in perms { if record.ssh != Some(true) || hive_types::Ident::parse(agent).is_err() { continue; @@ -264,6 +322,7 @@ fn render(targets: &BTreeSet, answers: &Answers) -> String { /// if it changed. async fn pass_with( perms: &permissions::Stored, + endpoints: &BTreeSet<(String, u16)>, answers: &mut Answers, file: &Path, now: Instant, @@ -274,7 +333,7 @@ where F: Fn(String) -> Fut, Fut: Future>>, { - let wanted = targets(perms); + let wanted = targets(perms, endpoints); let hosts: BTreeSet<&str> = wanted.iter().map(|t| t.host.as_str()).collect(); answers.refresh(&hosts, now, bridge, resolve).await; let text = render(&wanted, answers); @@ -315,6 +374,7 @@ pub fn spawn(mut shutdown: tokio::sync::watch::Receiver) { "egress connections: {ENV_SUBNET} is unset or invalid, so the bridge subnet is not excluded" ); } + let endpoints = endpoints_from_env(); tokio::spawn(async move { let mut health = SweepHealth::new("egress_connections_render", "warn", FAILURES_BEFORE_WARNING); @@ -324,6 +384,7 @@ pub fn spawn(mut shutdown: tokio::sync::watch::Receiver) { Ok(perms) => { pass_with( &perms, + &endpoints, &mut answers, &file, Instant::now(), @@ -435,6 +496,7 @@ mod tests { dns: Dns, start: Instant, bridge: Option, + endpoints: BTreeSet<(String, u16)>, } impl Rig { @@ -445,6 +507,7 @@ mod tests { dns: Dns::default(), start: Instant::now(), bridge: None, + endpoints: BTreeSet::new(), }; // The empty file `systemd-tmpfiles` creates before c0re starts. std::fs::write(rig.file(), "").expect("write"); @@ -457,6 +520,7 @@ mod tests { let (file, now) = (self.file(), self.start + after); pass_with( perms, + &self.endpoints, &mut self.answers, &file, now, @@ -472,6 +536,62 @@ mod tests { const T0: Duration = Duration::ZERO; + #[test] + fn an_endpoint_is_the_host_and_port_of_a_url() { + let e = |u: &str| endpoint_of(u); + let some = |h: &str, p: u16| Some((h.to_owned(), p)); + assert_eq!(e("https://bao.t.local:8200"), some("bao.t.local", 8200)); + assert_eq!( + e("https://logs.t.local/select/logsql/query"), + some("logs.t.local", 443) + ); + assert_eq!(e("http://metrics.t.local"), some("metrics.t.local", 80)); + assert_eq!(e("tls://nats.t.local:4222"), some("nats.t.local", 4222)); + assert_eq!(e("nats://nats.t.local"), some("nats.t.local", 4222)); + assert_eq!(e("https://u:p@10.0.0.1:8443/x?y#z"), some("10.0.0.1", 8443)); + for bad in [ + "bao.t.local:8200", + "ftp://x/", + "https://", + "https://[::1]:8200", + "https://x:0", + "https://x:nope", + ] { + assert_eq!(e(bad), None, "{bad}"); + } + } + + #[tokio::test] + async fn the_endpoints_of_the_swarm_are_allowed_to_every_agent() { + let mut rig = Rig::new(); + rig.dns.set("bao.t.local", &["10.77.0.1"]); + rig.dns.set("logs.t.local", &["10.77.0.2", "fd00::2"]); + rig.endpoints = BTreeSet::from([ + ("bao.t.local".to_owned(), 8200), + ("logs.t.local".to_owned(), 443), + ]); + rig.pass(&permissions::Stored::new(), T0) + .await + .expect("renders"); + assert_eq!(rig.text(), "* 10.77.0.1 8200\n* 10.77.0.2 443\n"); + } + + #[tokio::test] + async fn an_endpoint_that_does_not_resolve_keeps_its_last_answer_and_the_ssh_lines_stay() { + let mut rig = Rig::new(); + rig.dns.set("bao.t.local", &["10.77.0.1"]); + rig.dns.set("muede-pc2", &["192.168.23.232"]); + rig.endpoints = BTreeSet::from([("bao.t.local".to_owned(), 8200)]); + let perms = permissions::Stored::from([("atlas".to_owned(), pc2("true"))]); + rig.pass(&perms, T0).await.expect("renders"); + assert_eq!(rig.text(), "* 10.77.0.1 8200\natlas 192.168.23.232 2222\n"); + rig.dns.fail("bao.t.local"); + rig.pass(&perms, RESOLVE_EVERY + Duration::from_secs(1)) + .await + .expect("renders"); + assert_eq!(rig.text(), "* 10.77.0.1 8200\natlas 192.168.23.232 2222\n"); + } + #[tokio::test] async fn a_name_is_allowed_at_every_address_it_resolves_to() { let mut rig = Rig::new(); diff --git a/hive-priv/src/egress.rs b/hive-priv/src/egress.rs index 0c8092efa..8b8d6cc11 100644 --- a/hive-priv/src/egress.rs +++ b/hive-priv/src/egress.rs @@ -330,7 +330,12 @@ pub(crate) fn direct_macs(pins: &[Pin], unrestricted: &[String]) -> Vec { macs } -/// One connection an agent may open: its name, the address and the TCP port. +/// The agent column of a connection every agent may open: the swarm's own +/// endpoints (the secret store, the logs and metrics queries). +const ALL_AGENTS: &str = "*"; + +/// One connection an agent may open: its name (or [`ALL_AGENTS`]), the address +/// and the TCP port. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Connection { pub(crate) agent: String, @@ -338,8 +343,9 @@ pub(crate) struct Connection { pub(crate) port: u16, } -/// The connections in `text`, one ` ` per line. A line of -/// another shape, a port 0 or a name that is no identifier is skipped. +/// The connections in `text`, one ` ` per line, where the +/// agent is an identifier or `*`. A line of another shape or a port 0 is +/// skipped. pub(crate) fn parse_connections(text: &str) -> Vec { text.lines() .filter_map(|line| { @@ -348,7 +354,9 @@ pub(crate) fn parse_connections(text: &str) -> Vec { if cols.next().is_some() { return None; } - hive_types::Ident::parse(agent).ok()?; + if agent != ALL_AGENTS { + hive_types::Ident::parse(agent).ok()?; + } Some(Connection { agent: agent.to_owned(), ip: ip.parse().ok()?, @@ -359,13 +367,15 @@ pub(crate) fn parse_connections(text: &str) -> Vec { } /// The `agent_allow` elements of `connections`: for each, one per MAC bound to -/// a port of the agent's container (`h-`). An agent with no binding has -/// none, so nothing is allowed for it until its port is bound. +/// a port of the agent's container (`h-`), or of every agent's for a +/// connection of [`ALL_AGENTS`]. An agent with no binding has none, so nothing +/// is allowed for it until its port is bound. pub(crate) fn connection_elements(pins: &[Pin], connections: &[Connection]) -> String { let mut rows: Vec<(Mac, std::net::Ipv4Addr, u16)> = Vec::new(); for c in connections { for p in pins { - if p.machine.strip_prefix(AGENT_PREFIX) == Some(c.agent.as_str()) { + let agent = p.machine.strip_prefix(AGENT_PREFIX); + if agent.is_some_and(|a| c.agent == ALL_AGENTS || a == c.agent) { rows.push((p.mac, c.ip, c.port)); } } @@ -1521,6 +1531,38 @@ mod tests { ); } + /// A `*` connection is allowed from the MAC of every agent's port and from + /// no service container; the same address of an agent's own line collapses + /// with it. + #[test] + fn a_connection_of_every_agent_is_allowed_from_every_agents_mac_only() { + let pins = [ + pin("vb-h-atlas", 10, 1, "h-atlas"), + pin("vb-h-argus", 11, 2, "h-argus"), + pin("vb-matrix", 12, 3, "swarm-nats"), + ]; + let script = connection_elements( + &pins, + &[ + conn("*", "10.77.0.1", 8200), + conn("atlas", "10.77.0.1", 8200), + ], + ); + assert_eq!( + script, + "add element inet hive_egress agent_allow { 02:00:00:00:00:01 . 10.77.0.1 . 8200 }\n\ + add element inet hive_egress agent_allow { 02:00:00:00:00:02 . 10.77.0.1 . 8200 }\n" + ); + } + + #[test] + fn a_star_line_is_parsed_and_other_odd_names_are_still_skipped() { + assert_eq!( + parse_connections("* 10.77.0.1 8200\n*x 10.0.0.1 22\n** 10.0.0.2 22\n"), + [conn("*", "10.77.0.1", 8200)] + ); + } + #[test] fn a_connection_of_an_unbound_agent_adds_nothing_and_duplicates_collapse() { let pins = [pin("vb-h-atlas", 10, 1, "h-atlas")]; diff --git a/nix/host-modules/hive-egress.nix b/nix/host-modules/hive-egress.nix index bfb980233..62811e92f 100644 --- a/nix/host-modules/hive-egress.nix +++ b/nix/host-modules/hive-egress.nix @@ -381,7 +381,10 @@ in The file hive-c0re renders with the SSH connections each agent may open, one ` ` per line: the addresses behind the `host` of each connection in the permissions record of an agent whose `ssh` switch - is on. `hive-priv egress-pin` turns each line into elements of the + is on. A `*` line instead of an agent name allows the address and port to + every agent: hive-c0re writes one for the secret store, the queue, the + logs and the metrics endpoint of the swarm, so that `reject` does not cut + agents off from them. `hive-priv egress-pin` turns each line into elements of the `agent_allow` set of the `inet hive_egress` table, keyed by the MAC of the agent's port, and the forward chain accepts TCP to an address and port in it before it logs or refuses. The file is read when a port is diff --git a/nix/module-eval/core-toggle.nix b/nix/module-eval/core-toggle.nix index 53e2f50eb..8a47f6557 100644 --- a/nix/module-eval/core-toggle.nix +++ b/nix/module-eval/core-toggle.nix @@ -616,6 +616,22 @@ let name = "a hive with no store identity forwards no store address to its agents"; ok = !(bare.systemd.services.hive-c0re.environment ? HIVE_AGENT_BAO_ADDR); } + { + # hive-c0re's egress worker reads these three names and lets every agent + # open a connection to each address (`egress_connections.rs`, + # `ENDPOINT_ENVS`). The names are spelled in both places, so this is the + # nix half of that agreement, with the file's own variable as the + # presence control that the worker runs on this host at all. + name = "the environment of a hive that runs the egress worker names the store, logs and metrics endpoints its agents use"; + ok = + let + e = allLocal.systemd.services.hive-c0re.environment; + in + e ? HIVE_EGRESS_CONNECTIONS_FILE + && lib.hasPrefix "https://" e.HIVE_AGENT_BAO_ADDR + && lib.hasSuffix "/select/logsql/query" e.HIVE_AGENT_LOGS_QUERY_URL + && lib.hasPrefix "https://" e.HIVE_AGENT_METRICS_URL; + } { # The gateway's per-name issuer choice. If this ever collapses to a # constant, every swarm-service vhost serves a certificate its CA