use crate::client::Client;
use crate::watcher::{self, Msg};
use krab_controllers::util::{name, s};
use krab_runtime::native::net::Subnet;
use serde_json::{Value, json};
use std::collections::{BTreeMap, BTreeSet};
use std::io;
use std::path::PathBuf;
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::AsyncWriteExt;
use tokio::process::Command;
use tokio::sync::mpsc;
pub const PUBKEY: &str = "krab.io/wg-pubkey";
pub const ENDPOINT: &str = "krab.io/wg-endpoint";
#[derive(Clone)]
pub struct Opts {
pub cluster_subnet: Subnet,
pub local_subnet: Subnet,
pub iface: String,
pub port: u16,
pub endpoint: Option<String>,
pub dir: PathBuf,
pub node: String,
pub node_ip: String,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Peer {
pub key: String,
pub endpoint: String,
pub cidr: String,
}
pub(crate) async fn run_cmd(prog: &str, args: &[&str], stdin: Option<&[u8]>) -> io::Result<String> {
let mut cmd = Command::new(prog);
cmd.args(args)
.stdin(if stdin.is_some() {
Stdio::piped()
} else {
Stdio::null()
})
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = cmd
.spawn()
.map_err(|e| io::Error::new(e.kind(), format!("{prog}: {e}")))?;
if let (Some(data), Some(mut si)) = (stdin, child.stdin.take()) {
si.write_all(data).await?;
}
let out = child.wait_with_output().await?;
if !out.status.success() {
return Err(io::Error::other(format!(
"{prog} {}: {}",
args.join(" "),
String::from_utf8_lossy(&out.stderr).trim()
)));
}
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}
pub fn peers_from_nodes(nodes: &BTreeMap<String, Value>, me: &str, port: u16) -> Vec<Peer> {
let mut out: Vec<Peer> = Vec::new();
for (n, node) in nodes {
if n == me {
continue;
}
let key = s(
node,
&format!("/metadata/annotations/{}", PUBKEY.replace('/', "~1")),
);
let cidr = s(node, "/spec/podCIDR");
if key.is_empty() || cidr.is_empty() {
continue;
}
let endpoint = match s(
node,
&format!("/metadata/annotations/{}", ENDPOINT.replace('/', "~1")),
) {
"" => {
let ip = node["status"]["addresses"]
.as_array()
.into_iter()
.flatten()
.find(|a| a["type"] == "InternalIP")
.and_then(|a| a["address"].as_str())
.unwrap_or("");
if ip.is_empty() {
continue;
}
format!("{ip}:{port}")
}
e => e.to_string(),
};
if out.iter().any(|p| p.key == key || p.cidr == cidr) {
eprintln!(
"krab-agent: wireguard: node {n} repeats the key or pod CIDR of another node, ignoring it"
);
continue;
}
out.push(Peer {
key: key.to_string(),
endpoint,
cidr: cidr.to_string(),
});
}
out
}
pub fn apply_pins(
nodes: &mut BTreeMap<String, Value>,
pins: &mut BTreeMap<String, String>,
me: &str,
) -> bool {
let ptr = format!("/metadata/annotations/{}", PUBKEY.replace('/', "~1"));
let mut changed = false;
for (n, node) in nodes.iter_mut() {
if n == me {
continue;
}
let key = s(node, &ptr).to_string();
if key.is_empty() {
continue;
}
match pins.get(n) {
None => {
pins.insert(n.clone(), key);
changed = true;
}
Some(pinned) if *pinned != key => {
eprintln!(
"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)"
);
node["metadata"]["annotations"][PUBKEY] = json!(pinned);
}
Some(_) => {}
}
}
changed
}
fn load_pins(path: &std::path::Path) -> BTreeMap<String, String> {
std::fs::read(path)
.ok()
.and_then(|b| serde_json::from_slice(&b).ok())
.unwrap_or_default()
}
fn key_ok(k: &str) -> bool {
k.len() == 44
&& k.ends_with('=')
&& k.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'='))
}
fn endpoint_ok(e: &str) -> bool {
e.parse::<std::net::SocketAddr>().is_ok()
}
fn cidr_ok(c: &str) -> bool {
c.split_once('/').is_some_and(|(a, p)| {
a.parse::<std::net::Ipv4Addr>().is_ok() && p.parse::<u8>().is_ok_and(|p| p <= 32)
})
}
fn peer_cidr_ok(cidr: &str, cluster: Subnet, local: Subnet) -> bool {
Subnet::parse_pod(cidr).is_ok_and(|peer| {
peer.prefix >= cluster.prefix
&& cluster.contains(peer.base.into())
&& !local.overlaps(&peer)
})
}
pub async fn setup(o: &Opts) -> io::Result<String> {
let keyfile = o.dir.join("wg.key");
let key = match std::fs::read_to_string(&keyfile) {
Ok(k) if key_ok(k.trim()) => k.trim().to_string(),
_ => {
let k = run_cmd("wg", &["genkey"], None).await?.trim().to_string();
std::fs::create_dir_all(&o.dir)?;
crate::kubelet_api::write_private(&keyfile, k.as_bytes())?;
k
}
};
let public = run_cmd("wg", &["pubkey"], Some(key.as_bytes()))
.await?
.trim()
.to_string();
if run_cmd("ip", &["link", "show", &o.iface], None)
.await
.is_err()
{
run_cmd(
"ip",
&["link", "add", "dev", &o.iface, "type", "wireguard"],
None,
)
.await?;
}
run_cmd(
"wg",
&[
"set",
&o.iface,
"private-key",
"/dev/stdin",
"listen-port",
&o.port.to_string(),
],
Some(key.as_bytes()),
)
.await?;
run_cmd("ip", &["link", "set", &o.iface, "up"], None).await?;
Ok(public)
}
pub async fn teardown(iface: &str) {
let _ = run_cmd("ip", &["link", "del", iface], None).await;
}
async fn current(iface: &str) -> io::Result<(BTreeSet<String>, BTreeSet<String>)> {
let peers: BTreeSet<String> = run_cmd("wg", &["show", iface, "peers"], None)
.await?
.lines()
.map(str::to_string)
.collect();
let routes: BTreeSet<String> = run_cmd("ip", &["-4", "route", "show", "dev", iface], None)
.await?
.lines()
.filter_map(|l| l.split_whitespace().next())
.filter(|c| cidr_ok(c))
.map(str::to_string)
.collect();
Ok((peers, routes))
}
pub async fn reconcile(iface: &str, want: &[Peer]) -> io::Result<()> {
let (have_peers, have_routes) = current(iface).await?;
let want: Vec<&Peer> = want
.iter()
.filter(|p| key_ok(&p.key) && endpoint_ok(&p.endpoint) && cidr_ok(&p.cidr))
.collect();
for p in &want {
run_cmd(
"wg",
&[
"set",
iface,
"peer",
&p.key,
"endpoint",
&p.endpoint,
"allowed-ips",
&p.cidr,
"persistent-keepalive",
"25",
],
None,
)
.await?;
run_cmd("ip", &["route", "replace", &p.cidr, "dev", iface], None).await?;
}
let keys: BTreeSet<&str> = want.iter().map(|p| p.key.as_str()).collect();
for k in have_peers.iter().filter(|k| !keys.contains(k.as_str())) {
run_cmd("wg", &["set", iface, "peer", k, "remove"], None).await?;
}
let cidrs: BTreeSet<&str> = want.iter().map(|p| p.cidr.as_str()).collect();
for c in have_routes.iter().filter(|c| !cidrs.contains(c.as_str())) {
run_cmd("ip", &["route", "del", c, "dev", iface], None).await?;
}
Ok(())
}
pub async fn run(c: Arc<Client>, o: Opts) -> Result<(), String> {
let public = setup(&o).await.map_err(|e| format!("wireguard: {e}"))?;
let endpoint = o
.endpoint
.clone()
.unwrap_or_else(|| format!("{}:{}", o.node_ip, o.port));
let patch = json!({"metadata": {"annotations": {PUBKEY: public, ENDPOINT: endpoint}}});
loop {
match c
.patch(
&format!("/api/v1/nodes/{}", o.node),
"application/merge-patch+json",
&patch,
)
.await
{
Ok((200, _)) => break,
other => {
eprintln!("krab-agent: annotate node: {other:?}");
tokio::time::sleep(Duration::from_secs(3)).await;
}
}
}
let (tx, mut rx) = mpsc::channel(64);
tokio::spawn(watcher::run(c.clone(), "/api/v1/nodes".into(), tx));
let mut nodes: BTreeMap<String, Value> = BTreeMap::new();
let pins_path = o.dir.join("wg-pins.json");
let mut pins = load_pins(&pins_path);
let mut tick = tokio::time::interval(Duration::from_secs(30));
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
loop {
tokio::select! {
m = rx.recv() => {
match m {
Some(Msg::Reset(items)) => {
nodes = items.into_iter().map(|n| (name(&n).to_string(), n)).collect();
}
Some(Msg::Upsert(n)) => { nodes.insert(name(&n).to_string(), n); }
Some(Msg::Delete(n)) => { nodes.remove(name(&n)); pins.remove(name(&n)); }
None => return Ok(()),
}
tokio::time::sleep(Duration::from_millis(300)).await;
while let Ok(m) = rx.try_recv() {
match m {
Msg::Reset(items) => nodes = items.into_iter().map(|n| (name(&n).to_string(), n)).collect(),
Msg::Upsert(n) => { nodes.insert(name(&n).to_string(), n); }
Msg::Delete(n) => { nodes.remove(name(&n)); }
}
}
}
_ = tick.tick() => {}
}
if apply_pins(&mut nodes, &mut pins, &o.node)
&& let Ok(text) = serde_json::to_vec(&pins)
{
let _ = crate::kubelet_api::write_private(&pins_path, &text);
}
let mut peers = peers_from_nodes(&nodes, &o.node, o.port);
peers.retain(|p| peer_cidr_ok(&p.cidr, o.cluster_subnet, o.local_subnet));
if let Err(e) = reconcile(&o.iface, &peers).await {
eprintln!("krab-agent: wireguard: {e}");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const K: &str = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
fn node(n: &str, key: &str, cidr: &str, ip: &str, ep: Option<&str>) -> Value {
let mut a = json!({ PUBKEY: key });
if let Some(e) = ep {
a[ENDPOINT] = json!(e);
}
json!({"metadata": {"name": n, "annotations": a}, "spec": {"podCIDR": cidr},
"status": {"addresses": [{"type": "InternalIP", "address": ip}]}})
}
#[test]
fn selects_peers_with_key_and_cidr() {
let mut m = BTreeMap::new();
m.insert("me".into(), node("me", K, "10.42.0.0/24", "10.0.0.1", None));
m.insert("b".into(), node("b", K, "10.42.1.0/24", "10.0.0.2", None));
m.insert(
"c".into(),
node(
"c",
"BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=",
"10.42.2.0/24",
"10.0.0.3",
Some("1.2.3.4:5000"),
),
);
m.insert(
"k3s".into(),
json!({"metadata": {"name": "k3s"}, "spec": {"podCIDR": "10.42.3.0/24"}}),
);
m.insert(
"nocidr".into(),
json!({"metadata": {"name": "nocidr", "annotations": {PUBKEY: K}}}),
);
let p = peers_from_nodes(&m, "me", 51820);
assert_eq!(p.len(), 2);
assert_eq!(p[0].endpoint, "10.0.0.2:51820");
assert_eq!(p[1].endpoint, "1.2.3.4:5000");
}
#[test]
fn peer_routes_stay_in_the_cluster_and_avoid_the_local_subnet() {
let cluster = Subnet::parse("10.42.0.0/16").unwrap();
let local = Subnet::parse_pod("10.42.0.0/24").unwrap();
assert!(peer_cidr_ok("10.42.1.0/24", cluster, local));
for prefix in [
"0.0.0.0/0",
"10.0.0.0/8",
"10.43.0.0/24",
"10.42.0.0/16",
"10.42.0.128/25",
"10.42.1.1/24",
] {
assert!(!peer_cidr_ok(prefix, cluster, local), "{prefix}");
}
}
#[test]
fn duplicate_keys_and_cidrs_are_dropped() {
let mut m = BTreeMap::new();
m.insert("a".into(), node("a", K, "10.42.1.0/24", "10.0.0.2", None));
m.insert("b".into(), node("b", K, "10.42.2.0/24", "10.0.0.3", None));
let k2 = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=";
m.insert("c".into(), node("c", k2, "10.42.1.0/24", "10.0.0.4", None));
m.insert("d".into(), node("d", k2, "10.42.3.0/24", "10.0.0.5", None));
let p = peers_from_nodes(&m, "me", 51820);
assert_eq!(p.len(), 2);
assert_eq!(p[0].cidr, "10.42.1.0/24");
assert_eq!(p[1].cidr, "10.42.3.0/24");
}
#[test]
fn first_seen_key_is_pinned() {
let k2 = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=";
let mut m = BTreeMap::new();
m.insert("a".into(), node("a", K, "10.42.1.0/24", "10.0.0.2", None));
let mut pins = BTreeMap::new();
assert!(apply_pins(&mut m, &mut pins, "me"));
assert_eq!(pins["a"], K);
m.insert("a".into(), node("a", k2, "10.42.1.0/24", "10.0.0.2", None));
assert!(!apply_pins(&mut m, &mut pins, "me"));
assert_eq!(peers_from_nodes(&m, "me", 51820)[0].key, K);
assert!(!apply_pins(&mut m, &mut pins, "a"));
}
#[test]
fn validates_inputs() {
assert!(key_ok(K));
assert!(!key_ok("short"));
assert!(!key_ok(&K.replace('A', ";")));
assert!(endpoint_ok("10.0.0.2:51820"));
assert!(!endpoint_ok("host:1"));
assert!(cidr_ok("10.42.1.0/24"));
assert!(!cidr_ok("10.42.1.0/33"));
assert!(!cidr_ok("--evil/1"));
}
}