1use crate::client::Client;
2use crate::watcher::{self, Msg};
3use krab_controllers::util::{name, s};
4use krab_runtime::native::net::Subnet;
5use serde_json::{Value, json};
6use std::collections::{BTreeMap, BTreeSet};
7use std::io;
8use std::path::PathBuf;
9use std::process::Stdio;
10use std::sync::Arc;
11use std::time::Duration;
12use tokio::io::AsyncWriteExt;
13use tokio::process::Command;
14use tokio::sync::mpsc;
15
16pub const PUBKEY: &str = "krab.io/wg-pubkey";
17pub const ENDPOINT: &str = "krab.io/wg-endpoint";
18
19#[derive(Clone)]
20pub struct Opts {
21 pub cluster_subnet: Subnet,
22 pub local_subnet: Subnet,
23 pub iface: String,
24 pub port: u16,
25 pub endpoint: Option<String>,
26 pub dir: PathBuf,
27 pub node: String,
28 pub node_ip: String,
29}
30
31#[derive(Debug, PartialEq, Eq, Clone)]
32pub struct Peer {
33 pub key: String,
34 pub endpoint: String,
35 pub cidr: String,
36}
37
38pub(crate) async fn run_cmd(prog: &str, args: &[&str], stdin: Option<&[u8]>) -> io::Result<String> {
39 let mut cmd = Command::new(prog);
40 cmd.args(args)
41 .stdin(if stdin.is_some() {
42 Stdio::piped()
43 } else {
44 Stdio::null()
45 })
46 .stdout(Stdio::piped())
47 .stderr(Stdio::piped());
48 let mut child = cmd
49 .spawn()
50 .map_err(|e| io::Error::new(e.kind(), format!("{prog}: {e}")))?;
51 if let (Some(data), Some(mut si)) = (stdin, child.stdin.take()) {
52 si.write_all(data).await?;
53 }
54 let out = child.wait_with_output().await?;
55 if !out.status.success() {
56 return Err(io::Error::other(format!(
57 "{prog} {}: {}",
58 args.join(" "),
59 String::from_utf8_lossy(&out.stderr).trim()
60 )));
61 }
62 Ok(String::from_utf8_lossy(&out.stdout).into_owned())
63}
64
65pub fn peers_from_nodes(nodes: &BTreeMap<String, Value>, me: &str, port: u16) -> Vec<Peer> {
66 let mut out: Vec<Peer> = Vec::new();
67 for (n, node) in nodes {
68 if n == me {
69 continue;
70 }
71 let key = s(
72 node,
73 &format!("/metadata/annotations/{}", PUBKEY.replace('/', "~1")),
74 );
75 let cidr = s(node, "/spec/podCIDR");
76 if key.is_empty() || cidr.is_empty() {
77 continue;
78 }
79 let endpoint = match s(
80 node,
81 &format!("/metadata/annotations/{}", ENDPOINT.replace('/', "~1")),
82 ) {
83 "" => {
84 let ip = node["status"]["addresses"]
85 .as_array()
86 .into_iter()
87 .flatten()
88 .find(|a| a["type"] == "InternalIP")
89 .and_then(|a| a["address"].as_str())
90 .unwrap_or("");
91 if ip.is_empty() {
92 continue;
93 }
94 format!("{ip}:{port}")
95 }
96 e => e.to_string(),
97 };
98 if out.iter().any(|p| p.key == key || p.cidr == cidr) {
99 eprintln!(
100 "krab-agent: wireguard: node {n} repeats the key or pod CIDR of another node, ignoring it"
101 );
102 continue;
103 }
104 out.push(Peer {
105 key: key.to_string(),
106 endpoint,
107 cidr: cidr.to_string(),
108 });
109 }
110 out
111}
112
113pub fn apply_pins(
114 nodes: &mut BTreeMap<String, Value>,
115 pins: &mut BTreeMap<String, String>,
116 me: &str,
117) -> bool {
118 let ptr = format!("/metadata/annotations/{}", PUBKEY.replace('/', "~1"));
119 let mut changed = false;
120 for (n, node) in nodes.iter_mut() {
121 if n == me {
122 continue;
123 }
124 let key = s(node, &ptr).to_string();
125 if key.is_empty() {
126 continue;
127 }
128 match pins.get(n) {
129 None => {
130 pins.insert(n.clone(), key);
131 changed = true;
132 }
133 Some(pinned) if *pinned != key => {
134 eprintln!(
135 "krab-agent: wireguard: node {n} announced a different public key, keeping the pinned one (remove its entry from wg-pins.json to accept the new key)"
136 );
137 node["metadata"]["annotations"][PUBKEY] = json!(pinned);
138 }
139 Some(_) => {}
140 }
141 }
142 changed
143}
144
145fn load_pins(path: &std::path::Path) -> BTreeMap<String, String> {
146 std::fs::read(path)
147 .ok()
148 .and_then(|b| serde_json::from_slice(&b).ok())
149 .unwrap_or_default()
150}
151
152fn key_ok(k: &str) -> bool {
153 k.len() == 44
154 && k.ends_with('=')
155 && k.bytes()
156 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'='))
157}
158
159fn endpoint_ok(e: &str) -> bool {
160 e.parse::<std::net::SocketAddr>().is_ok()
161}
162
163fn cidr_ok(c: &str) -> bool {
164 c.split_once('/').is_some_and(|(a, p)| {
165 a.parse::<std::net::Ipv4Addr>().is_ok() && p.parse::<u8>().is_ok_and(|p| p <= 32)
166 })
167}
168
169fn peer_cidr_ok(cidr: &str, cluster: Subnet, local: Subnet) -> bool {
170 Subnet::parse_pod(cidr).is_ok_and(|peer| {
171 peer.prefix >= cluster.prefix
172 && cluster.contains(peer.base.into())
173 && !local.overlaps(&peer)
174 })
175}
176
177pub async fn setup(o: &Opts) -> io::Result<String> {
178 let keyfile = o.dir.join("wg.key");
179 let key = match std::fs::read_to_string(&keyfile) {
180 Ok(k) if key_ok(k.trim()) => k.trim().to_string(),
181 _ => {
182 let k = run_cmd("wg", &["genkey"], None).await?.trim().to_string();
183 std::fs::create_dir_all(&o.dir)?;
184 crate::kubelet_api::write_private(&keyfile, k.as_bytes())?;
185 k
186 }
187 };
188 let public = run_cmd("wg", &["pubkey"], Some(key.as_bytes()))
189 .await?
190 .trim()
191 .to_string();
192 if run_cmd("ip", &["link", "show", &o.iface], None)
193 .await
194 .is_err()
195 {
196 run_cmd(
197 "ip",
198 &["link", "add", "dev", &o.iface, "type", "wireguard"],
199 None,
200 )
201 .await?;
202 }
203 run_cmd(
204 "wg",
205 &[
206 "set",
207 &o.iface,
208 "private-key",
209 "/dev/stdin",
210 "listen-port",
211 &o.port.to_string(),
212 ],
213 Some(key.as_bytes()),
214 )
215 .await?;
216 run_cmd("ip", &["link", "set", &o.iface, "up"], None).await?;
217 Ok(public)
218}
219
220pub async fn teardown(iface: &str) {
221 let _ = run_cmd("ip", &["link", "del", iface], None).await;
222}
223
224async fn current(iface: &str) -> io::Result<(BTreeSet<String>, BTreeSet<String>)> {
225 let peers: BTreeSet<String> = run_cmd("wg", &["show", iface, "peers"], None)
226 .await?
227 .lines()
228 .map(str::to_string)
229 .collect();
230 let routes: BTreeSet<String> = run_cmd("ip", &["-4", "route", "show", "dev", iface], None)
231 .await?
232 .lines()
233 .filter_map(|l| l.split_whitespace().next())
234 .filter(|c| cidr_ok(c))
235 .map(str::to_string)
236 .collect();
237 Ok((peers, routes))
238}
239
240pub async fn reconcile(iface: &str, want: &[Peer]) -> io::Result<()> {
241 let (have_peers, have_routes) = current(iface).await?;
242 let want: Vec<&Peer> = want
243 .iter()
244 .filter(|p| key_ok(&p.key) && endpoint_ok(&p.endpoint) && cidr_ok(&p.cidr))
245 .collect();
246 for p in &want {
247 run_cmd(
248 "wg",
249 &[
250 "set",
251 iface,
252 "peer",
253 &p.key,
254 "endpoint",
255 &p.endpoint,
256 "allowed-ips",
257 &p.cidr,
258 "persistent-keepalive",
259 "25",
260 ],
261 None,
262 )
263 .await?;
264 run_cmd("ip", &["route", "replace", &p.cidr, "dev", iface], None).await?;
265 }
266 let keys: BTreeSet<&str> = want.iter().map(|p| p.key.as_str()).collect();
267 for k in have_peers.iter().filter(|k| !keys.contains(k.as_str())) {
268 run_cmd("wg", &["set", iface, "peer", k, "remove"], None).await?;
269 }
270 let cidrs: BTreeSet<&str> = want.iter().map(|p| p.cidr.as_str()).collect();
271 for c in have_routes.iter().filter(|c| !cidrs.contains(c.as_str())) {
272 run_cmd("ip", &["route", "del", c, "dev", iface], None).await?;
273 }
274 Ok(())
275}
276
277pub async fn run(c: Arc<Client>, o: Opts) -> Result<(), String> {
278 let public = setup(&o).await.map_err(|e| format!("wireguard: {e}"))?;
279 let endpoint = o
280 .endpoint
281 .clone()
282 .unwrap_or_else(|| format!("{}:{}", o.node_ip, o.port));
283 let patch = json!({"metadata": {"annotations": {PUBKEY: public, ENDPOINT: endpoint}}});
284 loop {
285 match c
286 .patch(
287 &format!("/api/v1/nodes/{}", o.node),
288 "application/merge-patch+json",
289 &patch,
290 )
291 .await
292 {
293 Ok((200, _)) => break,
294 other => {
295 eprintln!("krab-agent: annotate node: {other:?}");
296 tokio::time::sleep(Duration::from_secs(3)).await;
297 }
298 }
299 }
300 let (tx, mut rx) = mpsc::channel(64);
301 tokio::spawn(watcher::run(c.clone(), "/api/v1/nodes".into(), tx));
302 let mut nodes: BTreeMap<String, Value> = BTreeMap::new();
303 let pins_path = o.dir.join("wg-pins.json");
304 let mut pins = load_pins(&pins_path);
305 let mut tick = tokio::time::interval(Duration::from_secs(30));
306 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
307 loop {
308 tokio::select! {
309 m = rx.recv() => {
310 match m {
311 Some(Msg::Reset(items)) => {
312 nodes = items.into_iter().map(|n| (name(&n).to_string(), n)).collect();
313 }
314 Some(Msg::Upsert(n)) => { nodes.insert(name(&n).to_string(), n); }
315 Some(Msg::Delete(n)) => { nodes.remove(name(&n)); pins.remove(name(&n)); }
316 None => return Ok(()),
317 }
318 tokio::time::sleep(Duration::from_millis(300)).await;
319 while let Ok(m) = rx.try_recv() {
320 match m {
321 Msg::Reset(items) => nodes = items.into_iter().map(|n| (name(&n).to_string(), n)).collect(),
322 Msg::Upsert(n) => { nodes.insert(name(&n).to_string(), n); }
323 Msg::Delete(n) => { nodes.remove(name(&n)); }
324 }
325 }
326 }
327 _ = tick.tick() => {}
328 }
329 if apply_pins(&mut nodes, &mut pins, &o.node)
330 && let Ok(text) = serde_json::to_vec(&pins)
331 {
332 let _ = crate::kubelet_api::write_private(&pins_path, &text);
333 }
334 let mut peers = peers_from_nodes(&nodes, &o.node, o.port);
335 peers.retain(|p| peer_cidr_ok(&p.cidr, o.cluster_subnet, o.local_subnet));
336 if let Err(e) = reconcile(&o.iface, &peers).await {
337 eprintln!("krab-agent: wireguard: {e}");
338 }
339 }
340}
341
342#[cfg(test)]
343mod tests {
344 use super::*;
345
346 const K: &str = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
347
348 fn node(n: &str, key: &str, cidr: &str, ip: &str, ep: Option<&str>) -> Value {
349 let mut a = json!({ PUBKEY: key });
350 if let Some(e) = ep {
351 a[ENDPOINT] = json!(e);
352 }
353 json!({"metadata": {"name": n, "annotations": a}, "spec": {"podCIDR": cidr},
354 "status": {"addresses": [{"type": "InternalIP", "address": ip}]}})
355 }
356
357 #[test]
358 fn selects_peers_with_key_and_cidr() {
359 let mut m = BTreeMap::new();
360 m.insert("me".into(), node("me", K, "10.42.0.0/24", "10.0.0.1", None));
361 m.insert("b".into(), node("b", K, "10.42.1.0/24", "10.0.0.2", None));
362 m.insert(
363 "c".into(),
364 node(
365 "c",
366 "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=",
367 "10.42.2.0/24",
368 "10.0.0.3",
369 Some("1.2.3.4:5000"),
370 ),
371 );
372 m.insert(
373 "k3s".into(),
374 json!({"metadata": {"name": "k3s"}, "spec": {"podCIDR": "10.42.3.0/24"}}),
375 );
376 m.insert(
377 "nocidr".into(),
378 json!({"metadata": {"name": "nocidr", "annotations": {PUBKEY: K}}}),
379 );
380 let p = peers_from_nodes(&m, "me", 51820);
381 assert_eq!(p.len(), 2);
382 assert_eq!(p[0].endpoint, "10.0.0.2:51820");
383 assert_eq!(p[1].endpoint, "1.2.3.4:5000");
384 }
385
386 #[test]
387 fn peer_routes_stay_in_the_cluster_and_avoid_the_local_subnet() {
388 let cluster = Subnet::parse("10.42.0.0/16").unwrap();
389 let local = Subnet::parse_pod("10.42.0.0/24").unwrap();
390 assert!(peer_cidr_ok("10.42.1.0/24", cluster, local));
391 for prefix in [
392 "0.0.0.0/0",
393 "10.0.0.0/8",
394 "10.43.0.0/24",
395 "10.42.0.0/16",
396 "10.42.0.128/25",
397 "10.42.1.1/24",
398 ] {
399 assert!(!peer_cidr_ok(prefix, cluster, local), "{prefix}");
400 }
401 }
402
403 #[test]
404 fn duplicate_keys_and_cidrs_are_dropped() {
405 let mut m = BTreeMap::new();
406 m.insert("a".into(), node("a", K, "10.42.1.0/24", "10.0.0.2", None));
407 m.insert("b".into(), node("b", K, "10.42.2.0/24", "10.0.0.3", None));
408 let k2 = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=";
409 m.insert("c".into(), node("c", k2, "10.42.1.0/24", "10.0.0.4", None));
410 m.insert("d".into(), node("d", k2, "10.42.3.0/24", "10.0.0.5", None));
411 let p = peers_from_nodes(&m, "me", 51820);
412 assert_eq!(p.len(), 2);
413 assert_eq!(p[0].cidr, "10.42.1.0/24");
414 assert_eq!(p[1].cidr, "10.42.3.0/24");
415 }
416
417 #[test]
418 fn first_seen_key_is_pinned() {
419 let k2 = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=";
420 let mut m = BTreeMap::new();
421 m.insert("a".into(), node("a", K, "10.42.1.0/24", "10.0.0.2", None));
422 let mut pins = BTreeMap::new();
423 assert!(apply_pins(&mut m, &mut pins, "me"));
424 assert_eq!(pins["a"], K);
425 m.insert("a".into(), node("a", k2, "10.42.1.0/24", "10.0.0.2", None));
426 assert!(!apply_pins(&mut m, &mut pins, "me"));
427 assert_eq!(peers_from_nodes(&m, "me", 51820)[0].key, K);
428 assert!(!apply_pins(&mut m, &mut pins, "a"));
429 }
430
431 #[test]
432 fn validates_inputs() {
433 assert!(key_ok(K));
434 assert!(!key_ok("short"));
435 assert!(!key_ok(&K.replace('A', ";")));
436 assert!(endpoint_ok("10.0.0.2:51820"));
437 assert!(!endpoint_ok("host:1"));
438 assert!(cidr_ok("10.42.1.0/24"));
439 assert!(!cidr_ok("10.42.1.0/33"));
440 assert!(!cidr_ok("--evil/1"));
441 }
442}