feat(fence): CELLD_FENCE_DNAT and CELLD_FENCE_ALLOW exceptions
DNAT'd connections carry netavark's 0x1000 mark, so Podman's isolation lets them through.
Jason Schwarzenberger authored 1 parent 6db89b9commit 051fe80ff4d5f5cb4e14883236fbdf90ea147491Browse files
2 files changed+191−11
modifiedHOMEFLARE.md+1−0View file
| @@ -29,6 +29,7 @@ | ||
| 29 | 29 | | `send_email` binding (Email Sending) | Diffinery sends sign-up codes, invitations and notifications with `env.EMAIL.send({ from, to, subject, html, text })`. The binding checks the message and the binding's `allowed_sender_addresses` / `destination_address` / `allowed_destination_addresses`, then posts it in the REST API's shape (`{address, name}`, `reply_to`, base64 attachments) to `CELLD_EMAIL_URL/send` with `CELLD_EMAIL_TOKEN` as a bearer. Homeflare relays it to Cloudflare's Email Sending API. The result is `{ messageId, delivered, queued, permanent_bounces, suppressed_recipients }`; API errors become the binding's `E_*` codes. The legacy raw `EmailMessage` isn't supported (celld has no `cloudflare:email`). | |
| 30 | 30 | | Container images in parts | `celld deploy` read the whole `docker save` output into memory and wrote it in one `PUT`, which has to finish within the bucket client's 30 s; Diffinery's multi-GB runner image timed out against RustFS, failing every redeploy. The save now streams into a multipart upload of 16 MiB parts (`Bucket::put_large`), completed only once the save exits successfully. A node loading the image downloads it in 16 MiB ranges to a temporary file (`Bucket::get_large`) and streams that to the engine's `images/load` (`Docker::post_file`). Test: `CELLD_TEST_S3_ENDPOINT=... cargo test -p celld --lib large_object_round_trip -- --ignored` against any S3 (moto_server works). | |
| 31 | 31 | | Fence in another network namespace (`CELLD_FENCE_NETNS`) | Under rootless Podman the fence's `--network host` container can't load nftables rules (`netlink: Operation not permitted`), and the container bridges aren't in the host's namespace anyway: they're in Podman's rootless-netns, which the user owns. With `CELLD_FENCE_NETNS=<path>` the fence joins that namespace (`ns:<path>`) and loads `FENCE_RULES_NETNS`: as `FENCE_RULES`, plus `ct state established,related accept` in forward (the node is another container there, so its replies are forwarded) and port 53 to the bridge gateways (aardvark-dns). Unset keeps upstream's behaviour. | |
| 32 | +| Fence exceptions (`CELLD_FENCE_DNAT`, `CELLD_FENCE_ALLOW`) | A container reaching one of the node's own Workers on Cloudflare goes over the Internet. On Homeflare the Worker's hostname resolves to the LAN, which the fence refuses (Diffinery's import agent couldn't report back). `CELLD_FENCE_DNAT=HOST:PORT=HOST:PORT[,...]` rewrites the bridges' new TCP connections to the first endpoint into the second (a nat prerouting chain at -110, ahead of the engine's port forwarding, since a connection is translated once). The rewrite also sets connection mark `0x1000`: Podman (netavark) isolates its networks from one another and drops forwarding from celld's bridge to the edge's network, but accepts connections with that mark ahead of its isolation, as it does for its own port forwarding; the mark stays with the connection, so replies pass. `CELLD_FENCE_ALLOW=HOST:PORT[,...]` accepts the bridges' connections to those endpoints inside the fence's input and forward chains, ahead of the rejects (an accept in a chain of its own wouldn't stop them). A host may be a name; it's resolved to IPv4 each time a container starts, and the fence is installed again when its rules change. Only addresses and numbers reach the rules. Test: `cargo test -p celld --lib fence_rule_tests`. | | |
| 32 | 33 | | `homeflare:` line in `celld --version` | Lists what this build adds (`HOMEFLARE_FEATURES` in `lib.rs`), so Homeflare sends a config key only to a celld that accepts it. Add a feature there with each patch. | |
| 33 | 34 | |
| 34 | 35 | ## Building |
modifiedcrates/celld/container.rs+190−11View file
| @@ -149,13 +149,16 @@ | ||
| 149 | 149 | chain input { |
| 150 | 150 | type filter hook input priority -10; policy accept; |
| 151 | 151 | iifname { "celld0", "celld1" } ct state established,related accept |
| 152 | + #ALLOW | |
| 152 | 153 | iifname { "celld0", "celld1" } reject |
| 153 | 154 | } |
| 154 | 155 | chain forward { |
| 155 | 156 | type filter hook forward priority -10; policy accept; |
| 157 | + #ALLOW | |
| 156 | 158 | iifname { "celld0", "celld1" } ip daddr { 169.254.0.0/16, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10 } reject |
| 157 | 159 | iifname { "celld0", "celld1" } ip6 daddr { fe80::/10, fc00::/7 } reject |
| 158 | 160 | } |
| 161 | +#CHAINS | |
| 159 | 162 | } |
| 160 | 163 | "#; |
| 161 | 164 | |
| @@ -178,17 +181,116 @@ | ||
| 178 | 181 | type filter hook input priority -10; policy accept; |
| 179 | 182 | iifname { "celld0", "celld1" } ct state established,related accept |
| 180 | 183 | iifname { "celld0", "celld1" } meta l4proto { udp, tcp } th dport 53 accept |
| 184 | + #ALLOW | |
| 181 | 185 | iifname { "celld0", "celld1" } reject |
| 182 | 186 | } |
| 183 | 187 | chain forward { |
| 184 | 188 | type filter hook forward priority -10; policy accept; |
| 185 | 189 | iifname { "celld0", "celld1" } ct state established,related accept |
| 190 | + #ALLOW | |
| 186 | 191 | iifname { "celld0", "celld1" } ip daddr { 169.254.0.0/16, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10 } reject |
| 187 | 192 | iifname { "celld0", "celld1" } ip6 daddr { fe80::/10, fc00::/7 } reject |
| 188 | 193 | } |
| 194 | +#CHAINS | |
| 189 | 195 | } |
| 190 | 196 | "#; |
| 191 | 197 | |
| 198 | +/// homeflare: the connection mark a `CELLD_FENCE_DNAT` rewrite sets. Podman | |
| 199 | +/// (netavark) isolates its networks from one another, and the redirected | |
| 200 | +/// connection crosses from celld's bridge to the edge's network; netavark | |
| 201 | +/// accepts connections carrying this mark ahead of its isolation rules, as | |
| 202 | +/// it does for its own port forwarding (its "hostport" mark). The mark stays | |
| 203 | +/// with the connection, so the replies pass too. Another engine ignores it. | |
| 204 | +const FENCE_DNAT_MARK: u32 = 0x1000; | |
| 205 | + | |
| 206 | +/// homeflare: an IPv4 address and TCP port from a fence setting. The host | |
| 207 | +/// may be a name (Homeflare's edge container, whose address can change when | |
| 208 | +/// it restarts), resolved to IPv4 each time the rules are rendered; either | |
| 209 | +/// way only an address and a number reach the nftables rules. | |
| 210 | +async fn fence_endpoint(text: &str) -> anyhow::Result<(std::net::Ipv4Addr, u16)> { | |
| 211 | + let (host, port) = text | |
| 212 | + .trim() | |
| 213 | + .rsplit_once(':') | |
| 214 | + .ok_or_else(|| anyhow!("{text:?} is not HOST:PORT"))?; | |
| 215 | + let port: u16 = port.parse().with_context(|| format!("{text:?}: port"))?; | |
| 216 | + anyhow::ensure!(port != 0, "{text:?}: port 0"); | |
| 217 | + if let Ok(ip) = host.parse::<std::net::Ipv4Addr>() { | |
| 218 | + return Ok((ip, port)); | |
| 219 | + } | |
| 220 | + anyhow::ensure!( | |
| 221 | + !host.is_empty() | |
| 222 | + && host.len() <= 253 | |
| 223 | + && host | |
| 224 | + .chars() | |
| 225 | + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.'), | |
| 226 | + "{text:?}: not an IPv4 address or a hostname" | |
| 227 | + ); | |
| 228 | + let ip = tokio::net::lookup_host((host, port)) | |
| 229 | + .await | |
| 230 | + .with_context(|| format!("{text:?}: resolve {host}"))? | |
| 231 | + .find_map(|addr| match addr.ip() { | |
| 232 | + std::net::IpAddr::V4(ip) => Some(ip), | |
| 233 | + std::net::IpAddr::V6(_) => None, | |
| 234 | + }) | |
| 235 | + .ok_or_else(|| anyhow!("{text:?}: {host} has no IPv4 address"))?; | |
| 236 | + Ok((ip, port)) | |
| 237 | +} | |
| 238 | + | |
| 239 | +/// homeflare: exceptions to the fence, for a node that serves its own | |
| 240 | +/// Workers on a private address (Homeflare's edge on the LAN). On Cloudflare | |
| 241 | +/// a container reaches a Worker over the Internet; here the Worker's | |
| 242 | +/// hostname resolves to the LAN, which the fence refuses. Homeflare runs a | |
| 243 | +/// listener that serves Worker hostnames only and asks the fence to send the | |
| 244 | +/// containers there: | |
| 245 | +/// | |
| 246 | +/// - `CELLD_FENCE_DNAT=IP:PORT=IP:PORT[,...]` rewrites new TCP connections | |
| 247 | +/// from the bridges to the first endpoint into the second (prerouting, | |
| 248 | +/// before the engine's own port forwarding); | |
| 249 | +/// - `CELLD_FENCE_ALLOW=IP:PORT[,...]` lets new TCP connections from the | |
| 250 | +/// bridges reach those endpoints, ahead of the rejects. | |
| 251 | +/// | |
| 252 | +/// Everything else stays fenced. Returns the rules to add to the table. | |
| 253 | +async fn fence_rules(base: &str) -> anyhow::Result<String> { | |
| 254 | + let list = |name: &str| -> Vec<String> { | |
| 255 | + std::env::var(name) | |
| 256 | + .unwrap_or_default() | |
| 257 | + .split(',') | |
| 258 | + .map(str::trim) | |
| 259 | + .filter(|s| !s.is_empty()) | |
| 260 | + .map(str::to_string) | |
| 261 | + .collect() | |
| 262 | + }; | |
| 263 | + let bridges = format!("{{ \"{OPEN_BRIDGE}\", \"{INTERNAL_BRIDGE}\" }}"); | |
| 264 | + // An accept ends only its own chain, so the exceptions go inside the | |
| 265 | + // fence's chains, ahead of the rejects (a reject anywhere is final). | |
| 266 | + let mut allow = String::new(); | |
| 267 | + for entry in list("CELLD_FENCE_ALLOW") { | |
| 268 | + let (ip, port) = fence_endpoint(&entry).await.context("CELLD_FENCE_ALLOW")?; | |
| 269 | + allow.push_str(&format!( | |
| 270 | + "iifname {bridges} ip daddr {ip} tcp dport {port} accept\n " | |
| 271 | + )); | |
| 272 | + } | |
| 273 | + let mut dnat = String::new(); | |
| 274 | + for entry in list("CELLD_FENCE_DNAT") { | |
| 275 | + let (from, to) = entry | |
| 276 | + .split_once('=') | |
| 277 | + .ok_or_else(|| anyhow!("CELLD_FENCE_DNAT: {entry:?} is not IP:PORT=IP:PORT"))?; | |
| 278 | + let (from_ip, from_port) = fence_endpoint(from).await.context("CELLD_FENCE_DNAT")?; | |
| 279 | + let (to_ip, to_port) = fence_endpoint(to).await.context("CELLD_FENCE_DNAT")?; | |
| 280 | + dnat.push_str(&format!( | |
| 281 | + " iifname {bridges} ip daddr {from_ip} tcp dport {from_port} ct mark set ct mark | {FENCE_DNAT_MARK:#010x} dnat ip to {to_ip}:{to_port}\n" | |
| 282 | + )); | |
| 283 | + } | |
| 284 | + let chains = if dnat.is_empty() { | |
| 285 | + String::new() | |
| 286 | + } else { | |
| 287 | + format!(" chain prerouting {{\n type nat hook prerouting priority -110; policy accept;\n{dnat} }}\n") | |
| 288 | + }; | |
| 289 | + Ok(base | |
| 290 | + .replace("#ALLOW\n ", &allow) | |
| 291 | + .replace("#CHAINS\n", &chains)) | |
| 292 | +} | |
| 293 | + | |
| 192 | 294 | /// homeflare: the network namespace the fence joins instead of the host's, |
| 193 | 295 | /// as the engine names it (`ns:<path>`): a rootless Podman's rootless-netns, |
| 194 | 296 | /// `$XDG_RUNTIME_DIR/containers/networks/rootless-netns/rootless-netns`. |
| @@ -341,7 +443,10 @@ | ||
| 341 | 443 | cells: Mutex<HashMap<String, Arc<CellContainer>>>, |
| 342 | 444 | networks: tokio::sync::Mutex<Option<(String, String)>>, |
| 343 | 445 | /// Whether this process has installed the fence on the node's bridges. |
| 344 | - fenced: tokio::sync::Mutex<bool>, | |
| 446 | + /// The rules this process installed on the node's bridges, if any. A | |
| 447 | + /// change (homeflare: a fence exception's host resolving elsewhere) | |
| 448 | + /// installs them again. | |
| 449 | + fenced: tokio::sync::Mutex<Option<String>>, | |
| 345 | 450 | } |
| 346 | 451 | |
| 347 | 452 | /// What the runtime told this module about the node: set once at start. |
| @@ -547,7 +652,7 @@ | ||
| 547 | 652 | images: Mutex::new(HashMap::new()), |
| 548 | 653 | cells: Mutex::new(HashMap::new()), |
| 549 | 654 | networks: tokio::sync::Mutex::new(None), |
| 550 | - fenced: tokio::sync::Mutex::new(false), | |
| 655 | + fenced: tokio::sync::Mutex::new(None), | |
| 551 | 656 | }; |
| 552 | 657 | engine.reap().await?; |
| 553 | 658 | Ok(engine) |
| @@ -724,15 +829,23 @@ | ||
| 724 | 829 | Ok(names) |
| 725 | 830 | } |
| 726 | 831 | |
| 727 | - /// Install the fence on the node's bridges, once per process. Every | |
| 728 | - /// container start waits on this and fails when it fails: a node that | |
| 832 | + /// Install the fence on the node's bridges, once per process, and again | |
| 833 | + /// when its rules change (homeflare: a fence exception's host resolving | |
| 834 | + /// to a new address). Every container start waits on this and fails | |
| 835 | + /// when it fails: a node that | |
| 729 | 836 | /// cannot fence its bridges runs no container, because an unfenced |
| 730 | 837 | /// container can reach the node's internal listener and the cloud's |
| 731 | 838 | /// metadata service. The rules live in the kernel and outlive this |
| 732 | 839 | /// process; a restart re-applies them, which is idempotent. |
| 733 | 840 | pub async fn ensure_fence(&self) -> anyhow::Result<()> { |
| 734 | 841 | let mut fenced = self.fenced.lock().await; |
| 735 | - if *fenced { | |
| 842 | + let netns = fence_netns(); | |
| 843 | + let (rules, network_mode) = match &netns { | |
| 844 | + Some(path) => (FENCE_RULES_NETNS, format!("ns:{path}")), | |
| 845 | + None => (FENCE_RULES, "host".to_string()), | |
| 846 | + }; | |
| 847 | + let rules = fence_rules(rules).await?; | |
| 848 | + if fenced.as_deref() == Some(rules.as_str()) { | |
| 736 | 849 | return Ok(()); |
| 737 | 850 | } |
| 738 | 851 | let image = FENCE_IMAGE.read().unwrap().clone().ok_or_else(|| { |
| @@ -743,11 +856,6 @@ | ||
| 743 | 856 | })?; |
| 744 | 857 | self.ensure_image(&image).await?; |
| 745 | 858 | self.networks().await?; |
| 746 | - let netns = fence_netns(); | |
| 747 | - let (rules, network_mode) = match &netns { | |
| 748 | - Some(path) => (FENCE_RULES_NETNS, format!("ns:{path}")), | |
| 749 | - None => (FENCE_RULES, "host".to_string()), | |
| 750 | - }; | |
| 751 | 859 | let body = json!({ |
| 752 | 860 | "Image": image, |
| 753 | 861 | "Env": [format!("CELLD_NFT={rules}")], |
| @@ -814,7 +922,7 @@ | ||
| 814 | 922 | netns = netns.as_deref().unwrap_or("host"), |
| 815 | 923 | "containers can reach the Internet and nothing of the node's own" |
| 816 | 924 | ); |
| 817 | - *fenced = true; | |
| 925 | + *fenced = Some(rules); | |
| 818 | 926 | Ok(()) |
| 819 | 927 | } |
| 820 | 928 | |
| @@ -1644,3 +1752,74 @@ | ||
| 1644 | 1752 | let digest = sha2::Sha256::digest(format!("{node}\n{scope}").as_bytes()); |
| 1645 | 1753 | format!("celld-{:x}", digest)[..30].to_string() |
| 1646 | 1754 | } |
| 1755 | + | |
| 1756 | +#[cfg(test)] | |
| 1757 | +mod fence_rule_tests { | |
| 1758 | + use super::*; | |
| 1759 | + | |
| 1760 | + #[test] | |
| 1761 | + #[allow(clippy::disallowed_methods)] | |
| 1762 | + fn exceptions_go_inside_the_fence_chains() { | |
| 1763 | + // SAFETY: tests in this module run in one thread; nothing else reads these. | |
| 1764 | + unsafe { | |
| 1765 | + std::env::remove_var("CELLD_FENCE_ALLOW"); | |
| 1766 | + std::env::remove_var("CELLD_FENCE_DNAT"); | |
| 1767 | + } | |
| 1768 | + let rt = tokio::runtime::Builder::new_current_thread() | |
| 1769 | + .enable_all() | |
| 1770 | + .build() | |
| 1771 | + .unwrap(); | |
| 1772 | + let render = |base| rt.block_on(fence_rules(base)); | |
| 1773 | + let plain = render(FENCE_RULES_NETNS).unwrap(); | |
| 1774 | + assert!( | |
| 1775 | + !plain.contains("#ALLOW") | |
| 1776 | + && !plain.contains("#CHAINS") | |
| 1777 | + && !plain.contains("prerouting") | |
| 1778 | + ); | |
| 1779 | + assert_eq!( | |
| 1780 | + plain.matches("reject").count(), | |
| 1781 | + FENCE_RULES_NETNS.matches("reject").count() | |
| 1782 | + ); | |
| 1783 | + let upstream = render(FENCE_RULES).unwrap(); | |
| 1784 | + assert!(!upstream.contains('#')); | |
| 1785 | + | |
| 1786 | + unsafe { | |
| 1787 | + std::env::set_var("CELLD_FENCE_ALLOW", "192.168.50.189:8444"); | |
| 1788 | + std::env::set_var("CELLD_FENCE_DNAT", "192.168.50.189:443=192.168.50.189:8444"); | |
| 1789 | + } | |
| 1790 | + let rules = render(FENCE_RULES_NETNS).unwrap(); | |
| 1791 | + let accept = | |
| 1792 | + r#"iifname { "celld0", "celld1" } ip daddr 192.168.50.189 tcp dport 8444 accept"#; | |
| 1793 | + assert_eq!(rules.matches(accept).count(), 2, "{rules}"); | |
| 1794 | + // Each accept comes before its chain's first reject. | |
| 1795 | + for chain in ["chain input", "chain forward"] { | |
| 1796 | + let body = &rules[rules.find(chain).unwrap()..]; | |
| 1797 | + let body = &body[..body.find(" }").unwrap()]; | |
| 1798 | + assert!( | |
| 1799 | + body.find(accept).unwrap() < body.find("reject").unwrap(), | |
| 1800 | + "{body}" | |
| 1801 | + ); | |
| 1802 | + } | |
| 1803 | + assert!(rules.contains("type nat hook prerouting priority -110")); | |
| 1804 | + assert!( | |
| 1805 | + rules.contains("ip daddr 192.168.50.189 tcp dport 443 ct mark set ct mark | 0x00001000 dnat ip to 192.168.50.189:8444") | |
| 1806 | + ); | |
| 1807 | + | |
| 1808 | + unsafe { | |
| 1809 | + std::env::set_var( | |
| 1810 | + "CELLD_FENCE_ALLOW", | |
| 1811 | + "192.168.50.189:8444; nft flush ruleset", | |
| 1812 | + ) | |
| 1813 | + }; | |
| 1814 | + assert!(render(FENCE_RULES_NETNS).is_err()); | |
| 1815 | + // A hostname target resolves to its IPv4 address. | |
| 1816 | + unsafe { std::env::set_var("CELLD_FENCE_ALLOW", "localhost:8444") }; | |
| 1817 | + assert!(render(FENCE_RULES_NETNS) | |
| 1818 | + .unwrap() | |
| 1819 | + .contains("ip daddr 127.0.0.1 tcp dport 8444 accept")); | |
| 1820 | + unsafe { | |
| 1821 | + std::env::remove_var("CELLD_FENCE_ALLOW"); | |
| 1822 | + std::env::remove_var("CELLD_FENCE_DNAT"); | |
| 1823 | + } | |
| 1824 | + } | |
| 1825 | +} |