Skip to main content

krab_agent/
join.rs

1use crate::client::Client;
2use crate::yaml;
3use bytes::Bytes;
4use http_body_util::{BodyExt, Full};
5use hyper::Request;
6use hyper_util::rt::TokioIo;
7use krab_controllers::util::{base64_decode, rand_u64, s};
8use krab_tls::{b64, csr, der};
9use ring::{digest, hmac};
10use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
11use rustls::crypto::ring::default_provider;
12use rustls::{ClientConfig, DigitallySignedStruct, SignatureScheme};
13use rustls_pki_types::pem::PemObject;
14use rustls_pki_types::{CertificateDer, ServerName, UnixTime};
15use serde_json::{Value, json};
16use std::path::{Path, PathBuf};
17use std::sync::{Arc, Mutex};
18use std::time::Duration;
19use tokio::net::TcpStream;
20use tokio_rustls::TlsConnector;
21
22const CSR_PATH: &str = "/apis/certificates.k8s.io/v1/certificatesigningrequests";
23const ROTATE_CHECK: Duration = Duration::from_secs(600);
24
25pub struct JoinOpts {
26    pub server: String,
27    pub token: String,
28    pub ca_hash: String,
29    pub node_name: String,
30    pub dir: PathBuf,
31}
32
33#[derive(Debug)]
34struct Capture {
35    chain: Arc<Mutex<Vec<Vec<u8>>>>,
36}
37
38impl ServerCertVerifier for Capture {
39    fn verify_server_cert(
40        &self,
41        end_entity: &CertificateDer<'_>,
42        intermediates: &[CertificateDer<'_>],
43        _: &ServerName<'_>,
44        _: &[u8],
45        _: UnixTime,
46    ) -> Result<ServerCertVerified, rustls::Error> {
47        let mut c = self.chain.lock().unwrap_or_else(|e| e.into_inner());
48        c.push(end_entity.as_ref().to_vec());
49        c.extend(intermediates.iter().map(|i| i.as_ref().to_vec()));
50        Ok(ServerCertVerified::assertion())
51    }
52
53    fn verify_tls12_signature(
54        &self,
55        message: &[u8],
56        cert: &CertificateDer<'_>,
57        dss: &DigitallySignedStruct,
58    ) -> Result<HandshakeSignatureValid, rustls::Error> {
59        rustls::crypto::verify_tls12_signature(
60            message,
61            cert,
62            dss,
63            &default_provider().signature_verification_algorithms,
64        )
65    }
66
67    fn verify_tls13_signature(
68        &self,
69        message: &[u8],
70        cert: &CertificateDer<'_>,
71        dss: &DigitallySignedStruct,
72    ) -> Result<HandshakeSignatureValid, rustls::Error> {
73        rustls::crypto::verify_tls13_signature(
74            message,
75            cert,
76            dss,
77            &default_provider().signature_verification_algorithms,
78        )
79    }
80
81    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
82        default_provider()
83            .signature_verification_algorithms
84            .supported_schemes()
85    }
86}
87
88pub fn parse_server(url: &str) -> Result<(String, u16), String> {
89    let rest = url
90        .strip_prefix("https://")
91        .ok_or("--server must be an https:// URL")?
92        .trim_end_matches('/');
93    if rest.contains('/') {
94        return Err("--server must not contain a path".into());
95    }
96    match rest.rsplit_once(':') {
97        Some((h, p)) if !h.ends_with(']') || h.starts_with('[') => Ok((
98            h.trim_matches(['[', ']']).to_string(),
99            p.parse::<u16>().map_err(|_| "bad port in --server")?,
100        )),
101        _ => Ok((rest.to_string(), 443)),
102    }
103}
104
105pub fn token_parts(token: &str) -> Result<(&str, &str), String> {
106    let (id, secret) = token
107        .split_once('.')
108        .ok_or("bootstrap token must be ID.SECRET")?;
109    let ok = |v: &str, n: usize| {
110        v.len() == n
111            && v.bytes()
112                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
113    };
114    if ok(id, 6) && ok(secret, 16) {
115        Ok((id, secret))
116    } else {
117        Err("bootstrap token must match [a-z0-9]{6}.[a-z0-9]{16}".into())
118    }
119}
120
121pub fn parse_hash(h: &str) -> Result<String, String> {
122    let hex = h
123        .strip_prefix("sha256:")
124        .ok_or("--ca-hash must start with sha256:")?;
125    if hex.len() == 64 && hex.bytes().all(|b| b.is_ascii_hexdigit()) {
126        Ok(hex.to_ascii_lowercase())
127    } else {
128        Err("--ca-hash must be sha256: followed by 64 hex digits".into())
129    }
130}
131
132fn hex(b: &[u8]) -> String {
133    b.iter().map(|x| format!("{x:02x}")).collect()
134}
135
136pub fn spki_hash(cert_der: &[u8]) -> Option<String> {
137    let spki = der::spki(cert_der)?;
138    Some(hex(digest::digest(&digest::SHA256, &spki).as_ref()))
139}
140
141fn url_encode(data: &[u8]) -> String {
142    b64::encode_std(data)
143        .trim_end_matches('=')
144        .replace('+', "-")
145        .replace('/', "_")
146}
147
148fn url_decode(s: &str) -> Option<Vec<u8>> {
149    let mut t = s.replace('-', "+").replace('_', "/");
150    while !t.len().is_multiple_of(4) {
151        t.push('=');
152    }
153    base64_decode(&t)
154}
155
156pub fn verify_jws(secret: &str, payload: &str, jws: &str) -> bool {
157    let Some((header, sig)) = jws.split_once("..") else {
158        return false;
159    };
160    let Some(sig) = url_decode(sig) else {
161        return false;
162    };
163    let input = format!("{header}.{}", url_encode(payload.as_bytes()));
164    hmac::verify(
165        &hmac::Key::new(hmac::HMAC_SHA256, secret.as_bytes()),
166        input.as_bytes(),
167        &sig,
168    )
169    .is_ok()
170}
171
172fn pem_of(der: &[u8]) -> String {
173    let body = b64::encode_std(der);
174    let mut out = String::from("-----BEGIN CERTIFICATE-----\n");
175    for chunk in body.as_bytes().chunks(64) {
176        out.push_str(std::str::from_utf8(chunk).unwrap_or(""));
177        out.push('\n');
178    }
179    out.push_str("-----END CERTIFICATE-----\n");
180    out
181}
182
183async fn insecure_get(
184    host: &str,
185    port: u16,
186    path: &str,
187) -> Result<(u16, Bytes, Vec<Vec<u8>>), String> {
188    let chain = Arc::new(Mutex::new(Vec::new()));
189    let mut cfg = ClientConfig::builder_with_provider(Arc::new(default_provider()))
190        .with_safe_default_protocol_versions()
191        .map_err(|e| e.to_string())?
192        .dangerous()
193        .with_custom_certificate_verifier(Arc::new(Capture {
194            chain: chain.clone(),
195        }))
196        .with_no_client_auth();
197    cfg.alpn_protocols = vec![b"http/1.1".to_vec()];
198    let name = ServerName::try_from(host.to_string()).map_err(|e| e.to_string())?;
199    let tcp = tokio::time::timeout(Duration::from_secs(15), TcpStream::connect((host, port)))
200        .await
201        .map_err(|_| "connect timed out".to_string())?
202        .map_err(|e| e.to_string())?;
203    let tls = TlsConnector::from(Arc::new(cfg))
204        .connect(name, tcp)
205        .await
206        .map_err(|e| e.to_string())?;
207    let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(tls))
208        .await
209        .map_err(|e| e.to_string())?;
210    tokio::spawn(async move {
211        let _ = conn.await;
212    });
213    let req = Request::builder()
214        .uri(path)
215        .header("host", format!("{host}:{port}"))
216        .header("accept", "application/json")
217        .body(Full::new(Bytes::new()))
218        .map_err(|e| e.to_string())?;
219    let resp = sender.send_request(req).await.map_err(|e| e.to_string())?;
220    let status = resp.status().as_u16();
221    let body = resp
222        .into_body()
223        .collect()
224        .await
225        .map_err(|e| e.to_string())?
226        .to_bytes();
227    let c = chain.lock().unwrap_or_else(|e| e.into_inner()).clone();
228    Ok((status, body.slice(..body.len().min(1 << 20)), c))
229}
230
231fn pick_ca(pems: &[u8], want: &str) -> Option<String> {
232    CertificateDer::pem_slice_iter(pems)
233        .filter_map(Result::ok)
234        .find(|c| spki_hash(c.as_ref()).as_deref() == Some(want))
235        .map(|c| pem_of(c.as_ref()))
236}
237
238pub async fn discover(
239    host: &str,
240    port: u16,
241    token: &str,
242    want_hash: &str,
243) -> Result<String, String> {
244    let (id, secret) = token_parts(token)?;
245    let (code, body, chain) = insecure_get(
246        host,
247        port,
248        "/api/v1/namespaces/kube-public/configmaps/cluster-info",
249    )
250    .await?;
251    if code == 200 {
252        let cm: Value = serde_json::from_slice(&body).map_err(|e| e.to_string())?;
253        let kubeconfig = s(&cm, "/data/kubeconfig");
254        if kubeconfig.is_empty() {
255            return Err("cluster-info has no kubeconfig".into());
256        }
257        let jws = s(&cm, &format!("/data/jws-kubeconfig-{id}"));
258        if !jws.is_empty() && !verify_jws(secret, kubeconfig, jws) {
259            return Err("cluster-info signature does not match the bootstrap token".into());
260        }
261        let cfg = yaml::parse(kubeconfig);
262        let ca = cfg["clusters"][0]["cluster"]["certificate-authority-data"]
263            .as_str()
264            .and_then(base64_decode)
265            .ok_or("cluster-info has no certificate-authority-data")?;
266        return pick_ca(&ca, want_hash)
267            .ok_or_else(|| "no CA in cluster-info matches --ca-hash".to_string());
268    }
269    for der in &chain {
270        if spki_hash(der).as_deref() == Some(want_hash) {
271            return Ok(pem_of(der));
272        }
273    }
274    Err(format!(
275        "cluster-info unavailable (HTTP {code}) and no certificate in the server chain matches --ca-hash"
276    ))
277}
278
279fn write_private(path: &Path, data: &[u8]) -> Result<(), String> {
280    crate::kubelet_api::write_private(path, data).map_err(|e| format!("{}: {e}", path.display()))
281}
282
283fn kubeconfig_text(server: &str, ca: &str, user: &str) -> String {
284    format!(
285        "apiVersion: v1\nkind: Config\nclusters:\n- name: krab\n  cluster:\n    server: {server}\n    certificate-authority-data: {}\ncontexts:\n- name: krab\n  context:\n    cluster: krab\n    user: node\ncurrent-context: krab\nusers:\n- name: node\n  user:\n{user}",
286        b64::encode_std(ca.as_bytes())
287    )
288}
289
290pub async fn request_client_cert(c: &Client, node: &str) -> Result<(String, String), String> {
291    let req = csr::client_request(node).map_err(|e| e.to_string())?;
292    let name = format!("csr-krab-client-{node}-{:08x}", rand_u64() as u32);
293    let body = json!({
294        "apiVersion": "certificates.k8s.io/v1",
295        "kind": "CertificateSigningRequest",
296        "metadata": {"name": name},
297        "spec": {
298            "request": b64::encode_std(req.csr_pem.as_bytes()),
299            "signerName": "kubernetes.io/kube-apiserver-client-kubelet",
300            "usages": ["digital signature", "key encipherment", "client auth"]
301        }
302    });
303    let (code, out) = c.post(CSR_PATH, &body).await.map_err(|e| e.to_string())?;
304    if !matches!(code, 200 | 201) {
305        return Err(format!("create CSR: HTTP {code} {}", s(&out, "/message")));
306    }
307    let path = format!("{CSR_PATH}/{name}");
308    for _ in 0..100 {
309        tokio::time::sleep(Duration::from_secs(3)).await;
310        let Ok((200, csr)) = c.get(&path).await else {
311            continue;
312        };
313        let cert = s(&csr, "/status/certificate");
314        if !cert.is_empty() {
315            let pem = base64_decode(cert)
316                .and_then(|b| String::from_utf8(b).ok())
317                .ok_or("CSR certificate is not valid PEM")?;
318            return Ok((req.key_pem, pem));
319        }
320        let failed = csr["status"]["conditions"]
321            .as_array()
322            .into_iter()
323            .flatten()
324            .find(|x| matches!(s(x, "/type"), "Denied" | "Failed"));
325        if let Some(f) = failed {
326            return Err(format!("CSR {}: {}", s(f, "/type"), s(f, "/message")));
327        }
328    }
329    Err("CSR was not approved within 5 minutes".into())
330}
331
332fn install(dir: &Path, key: &str, cert: &str) -> Result<(), String> {
333    let pki = dir.join("pki");
334    std::fs::create_dir_all(&pki).map_err(|e| e.to_string())?;
335    write_private(&pki.join("client.key"), key.as_bytes())?;
336    write_private(&pki.join("client.crt"), cert.as_bytes())
337}
338
339fn write_final(dir: &Path, server: &str, ca: &str) -> Result<PathBuf, String> {
340    let pki = dir.join("pki");
341    let user = format!(
342        "    client-certificate: {}\n    client-key: {}\n",
343        pki.join("client.crt").display(),
344        pki.join("client.key").display()
345    );
346    let path = dir.join("kubeconfig");
347    write_private(&path, kubeconfig_text(server, ca, &user).as_bytes())?;
348    Ok(path)
349}
350
351fn cert_valid(dir: &Path, node: &str) -> bool {
352    let Ok(pem) = std::fs::read(dir.join("pki").join("client.crt")) else {
353        return false;
354    };
355    let Some(Ok(c)) = CertificateDer::pem_slice_iter(&pem).next() else {
356        return false;
357    };
358    let ok_subject =
359        der::subject_cn_o(c.as_ref()).is_some_and(|(cn, _)| cn == format!("system:node:{node}"));
360    ok_subject && der::validity(c.as_ref()).is_some_and(|(_, na)| na > now_secs())
361}
362
363fn now_secs() -> i64 {
364    std::time::SystemTime::now()
365        .duration_since(std::time::UNIX_EPOCH)
366        .map(|d| d.as_secs() as i64)
367        .unwrap_or(0)
368}
369
370pub fn existing(dir: &Path, node: &str) -> Option<PathBuf> {
371    let kubeconfig = dir.join("kubeconfig");
372    (kubeconfig.exists() && cert_valid(dir, node)).then_some(kubeconfig)
373}
374
375pub async fn join(o: &JoinOpts) -> Result<PathBuf, String> {
376    if let Some(kubeconfig) = existing(&o.dir, &o.node_name) {
377        return Ok(kubeconfig);
378    }
379    let (host, port) = parse_server(&o.server)?;
380    let want = parse_hash(&o.ca_hash)?;
381    token_parts(&o.token)?;
382    std::fs::create_dir_all(&o.dir).map_err(|e| e.to_string())?;
383    let ca = discover(&host, port, &o.token, &want).await?;
384    let token_file = o.dir.join("bootstrap-token");
385    write_private(&token_file, o.token.as_bytes())?;
386    let user = format!("    tokenFile: {}\n", token_file.display());
387    let boot = o.dir.join("bootstrap-kubeconfig");
388    write_private(&boot, kubeconfig_text(&o.server, &ca, &user).as_bytes())?;
389    let client = Client::from_kubeconfig(&boot)?;
390    let (key, cert) = request_client_cert(&client, &o.node_name).await?;
391    install(&o.dir, &key, &cert)?;
392    let path = write_final(&o.dir, &o.server, &ca)?;
393    let _ = std::fs::remove_file(&token_file);
394    let _ = std::fs::remove_file(&boot);
395    Ok(path)
396}
397
398pub fn rotation_wait(nb: i64, na: i64, now: i64) -> Option<Duration> {
399    let due = nb + (na - nb) * 8 / 10;
400    if now >= due {
401        None
402    } else {
403        Some(Duration::from_secs(
404            ((due - now) as u64 + 1).min(ROTATE_CHECK.as_secs()),
405        ))
406    }
407}
408
409pub async fn rotate_loop(kubeconfig: PathBuf, node: String, dir: PathBuf) {
410    loop {
411        let validity = std::fs::read(dir.join("pki").join("client.crt"))
412            .ok()
413            .and_then(|pem| {
414                CertificateDer::pem_slice_iter(&pem)
415                    .next()
416                    .and_then(Result::ok)
417                    .and_then(|c| der::validity(c.as_ref()))
418            });
419        if let Some((nb, na)) = validity
420            && let Some(wait) = rotation_wait(nb, na, now_secs())
421        {
422            tokio::time::sleep(wait).await;
423            continue;
424        }
425        if validity.is_some() {
426            match Client::from_kubeconfig(&kubeconfig) {
427                Ok(client) => match request_client_cert(&client, &node).await {
428                    Ok((key, cert)) => {
429                        let text = std::fs::read_to_string(&kubeconfig).unwrap_or_default();
430                        if install(&dir, &key, &cert).is_ok()
431                            && write_private(&kubeconfig, text.as_bytes()).is_ok()
432                        {
433                            eprintln!("krab-agent: client certificate rotated");
434                            continue;
435                        }
436                    }
437                    Err(e) => eprintln!("krab-agent: rotate: {e}"),
438                },
439                Err(e) => eprintln!("krab-agent: rotate: {e}"),
440            }
441        }
442        tokio::time::sleep(Duration::from_secs(60)).await;
443    }
444}
445
446#[cfg(test)]
447mod tests {
448    use super::*;
449
450    #[test]
451    fn parses_inputs() {
452        assert_eq!(
453            parse_server("https://10.0.0.1:6443").unwrap(),
454            ("10.0.0.1".into(), 6443)
455        );
456        assert_eq!(
457            parse_server("https://k8s.example.com").unwrap(),
458            ("k8s.example.com".into(), 443)
459        );
460        assert!(parse_server("http://x:1").is_err());
461        assert!(parse_server("https://x:1/path").is_err());
462        assert!(token_parts("abcdef.0123456789abcdef").is_ok());
463        assert!(token_parts("ABCDEF.0123456789abcdef").is_err());
464        assert!(token_parts("abcdef").is_err());
465        let h = format!("sha256:{}", "AB".repeat(32));
466        assert_eq!(parse_hash(&h).unwrap(), "ab".repeat(32));
467        assert!(parse_hash("sha256:zz").is_err());
468        assert!(parse_hash(&"ab".repeat(32)).is_err());
469    }
470
471    #[test]
472    fn rotation_waits_until_eighty_percent_of_lifetime() {
473        assert_eq!(rotation_wait(0, 1000, 0), Some(Duration::from_secs(600)));
474        assert_eq!(rotation_wait(0, 1000, 790), Some(Duration::from_secs(11)));
475        assert_eq!(rotation_wait(0, 1000, 800), None);
476        assert_eq!(rotation_wait(0, 1000, 5000), None);
477    }
478
479    #[test]
480    fn jws_roundtrip() {
481        let payload = "apiVersion: v1\nkind: Config\n";
482        let header = url_encode(br#"{"alg":"HS256","kid":"abcdef"}"#);
483        let key = hmac::Key::new(hmac::HMAC_SHA256, b"0123456789abcdef");
484        let sig = hmac::sign(
485            &key,
486            format!("{header}.{}", url_encode(payload.as_bytes())).as_bytes(),
487        );
488        let jws = format!("{header}..{}", url_encode(sig.as_ref()));
489        assert!(verify_jws("0123456789abcdef", payload, &jws));
490        assert!(!verify_jws("0123456789abcdee", payload, &jws));
491        assert!(!verify_jws("0123456789abcdef", "tampered", &jws));
492        assert!(!verify_jws("0123456789abcdef", payload, "garbage"));
493    }
494
495    #[test]
496    fn hashes_a_real_ca_and_picks_it() {
497        let d = tempfile::tempdir().unwrap();
498        let p = krab_tls::pki::ensure(d.path(), "n1", &[]).unwrap();
499        let ders = CertificateDer::pem_slice_iter(p.ca_cert_pem.as_bytes())
500            .collect::<Result<Vec<_>, _>>()
501            .unwrap();
502        let h = spki_hash(ders[0].as_ref()).unwrap();
503        assert_eq!(h.len(), 64);
504        let picked = pick_ca(p.ca_cert_pem.as_bytes(), &h).unwrap();
505        assert!(picked.starts_with("-----BEGIN CERTIFICATE-----"));
506        assert!(pick_ca(p.ca_cert_pem.as_bytes(), &"0".repeat(64)).is_none());
507        assert!(
508            kubeconfig_text("https://x:1", &picked, "    tokenFile: /t\n")
509                .contains("tokenFile: /t")
510        );
511    }
512}