krab-agent 0.2.1

Lightweight kubelet for a real Kubernetes control plane (krab agent)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
use crate::client::Client;
use crate::yaml;
use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper::Request;
use hyper_util::rt::TokioIo;
use krab_controllers::util::{base64_decode, rand_u64, s};
use krab_tls::{b64, csr, der};
use ring::{digest, hmac};
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::crypto::ring::default_provider;
use rustls::{ClientConfig, DigitallySignedStruct, SignatureScheme};
use rustls_pki_types::pem::PemObject;
use rustls_pki_types::{CertificateDer, ServerName, UnixTime};
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::net::TcpStream;
use tokio_rustls::TlsConnector;

const CSR_PATH: &str = "/apis/certificates.k8s.io/v1/certificatesigningrequests";
const ROTATE_CHECK: Duration = Duration::from_secs(600);

pub struct JoinOpts {
    pub server: String,
    pub token: String,
    pub ca_hash: String,
    pub node_name: String,
    pub dir: PathBuf,
}

#[derive(Debug)]
struct Capture {
    chain: Arc<Mutex<Vec<Vec<u8>>>>,
}

impl ServerCertVerifier for Capture {
    fn verify_server_cert(
        &self,
        end_entity: &CertificateDer<'_>,
        intermediates: &[CertificateDer<'_>],
        _: &ServerName<'_>,
        _: &[u8],
        _: UnixTime,
    ) -> Result<ServerCertVerified, rustls::Error> {
        let mut c = self.chain.lock().unwrap_or_else(|e| e.into_inner());
        c.push(end_entity.as_ref().to_vec());
        c.extend(intermediates.iter().map(|i| i.as_ref().to_vec()));
        Ok(ServerCertVerified::assertion())
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        rustls::crypto::verify_tls12_signature(
            message,
            cert,
            dss,
            &default_provider().signature_verification_algorithms,
        )
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        rustls::crypto::verify_tls13_signature(
            message,
            cert,
            dss,
            &default_provider().signature_verification_algorithms,
        )
    }

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        default_provider()
            .signature_verification_algorithms
            .supported_schemes()
    }
}

pub fn parse_server(url: &str) -> Result<(String, u16), String> {
    let rest = url
        .strip_prefix("https://")
        .ok_or("--server must be an https:// URL")?
        .trim_end_matches('/');
    if rest.contains('/') {
        return Err("--server must not contain a path".into());
    }
    match rest.rsplit_once(':') {
        Some((h, p)) if !h.ends_with(']') || h.starts_with('[') => Ok((
            h.trim_matches(['[', ']']).to_string(),
            p.parse::<u16>().map_err(|_| "bad port in --server")?,
        )),
        _ => Ok((rest.to_string(), 443)),
    }
}

pub fn token_parts(token: &str) -> Result<(&str, &str), String> {
    let (id, secret) = token
        .split_once('.')
        .ok_or("bootstrap token must be ID.SECRET")?;
    let ok = |v: &str, n: usize| {
        v.len() == n
            && v.bytes()
                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
    };
    if ok(id, 6) && ok(secret, 16) {
        Ok((id, secret))
    } else {
        Err("bootstrap token must match [a-z0-9]{6}.[a-z0-9]{16}".into())
    }
}

pub fn parse_hash(h: &str) -> Result<String, String> {
    let hex = h
        .strip_prefix("sha256:")
        .ok_or("--ca-hash must start with sha256:")?;
    if hex.len() == 64 && hex.bytes().all(|b| b.is_ascii_hexdigit()) {
        Ok(hex.to_ascii_lowercase())
    } else {
        Err("--ca-hash must be sha256: followed by 64 hex digits".into())
    }
}

fn hex(b: &[u8]) -> String {
    b.iter().map(|x| format!("{x:02x}")).collect()
}

pub fn spki_hash(cert_der: &[u8]) -> Option<String> {
    let spki = der::spki(cert_der)?;
    Some(hex(digest::digest(&digest::SHA256, &spki).as_ref()))
}

fn url_encode(data: &[u8]) -> String {
    b64::encode_std(data)
        .trim_end_matches('=')
        .replace('+', "-")
        .replace('/', "_")
}

fn url_decode(s: &str) -> Option<Vec<u8>> {
    let mut t = s.replace('-', "+").replace('_', "/");
    while !t.len().is_multiple_of(4) {
        t.push('=');
    }
    base64_decode(&t)
}

pub fn verify_jws(secret: &str, payload: &str, jws: &str) -> bool {
    let Some((header, sig)) = jws.split_once("..") else {
        return false;
    };
    let Some(sig) = url_decode(sig) else {
        return false;
    };
    let input = format!("{header}.{}", url_encode(payload.as_bytes()));
    hmac::verify(
        &hmac::Key::new(hmac::HMAC_SHA256, secret.as_bytes()),
        input.as_bytes(),
        &sig,
    )
    .is_ok()
}

fn pem_of(der: &[u8]) -> String {
    let body = b64::encode_std(der);
    let mut out = String::from("-----BEGIN CERTIFICATE-----\n");
    for chunk in body.as_bytes().chunks(64) {
        out.push_str(std::str::from_utf8(chunk).unwrap_or(""));
        out.push('\n');
    }
    out.push_str("-----END CERTIFICATE-----\n");
    out
}

async fn insecure_get(
    host: &str,
    port: u16,
    path: &str,
) -> Result<(u16, Bytes, Vec<Vec<u8>>), String> {
    let chain = Arc::new(Mutex::new(Vec::new()));
    let mut cfg = ClientConfig::builder_with_provider(Arc::new(default_provider()))
        .with_safe_default_protocol_versions()
        .map_err(|e| e.to_string())?
        .dangerous()
        .with_custom_certificate_verifier(Arc::new(Capture {
            chain: chain.clone(),
        }))
        .with_no_client_auth();
    cfg.alpn_protocols = vec![b"http/1.1".to_vec()];
    let name = ServerName::try_from(host.to_string()).map_err(|e| e.to_string())?;
    let tcp = tokio::time::timeout(Duration::from_secs(15), TcpStream::connect((host, port)))
        .await
        .map_err(|_| "connect timed out".to_string())?
        .map_err(|e| e.to_string())?;
    let tls = TlsConnector::from(Arc::new(cfg))
        .connect(name, tcp)
        .await
        .map_err(|e| e.to_string())?;
    let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(tls))
        .await
        .map_err(|e| e.to_string())?;
    tokio::spawn(async move {
        let _ = conn.await;
    });
    let req = Request::builder()
        .uri(path)
        .header("host", format!("{host}:{port}"))
        .header("accept", "application/json")
        .body(Full::new(Bytes::new()))
        .map_err(|e| e.to_string())?;
    let resp = sender.send_request(req).await.map_err(|e| e.to_string())?;
    let status = resp.status().as_u16();
    let body = resp
        .into_body()
        .collect()
        .await
        .map_err(|e| e.to_string())?
        .to_bytes();
    let c = chain.lock().unwrap_or_else(|e| e.into_inner()).clone();
    Ok((status, body.slice(..body.len().min(1 << 20)), c))
}

fn pick_ca(pems: &[u8], want: &str) -> Option<String> {
    CertificateDer::pem_slice_iter(pems)
        .filter_map(Result::ok)
        .find(|c| spki_hash(c.as_ref()).as_deref() == Some(want))
        .map(|c| pem_of(c.as_ref()))
}

pub async fn discover(
    host: &str,
    port: u16,
    token: &str,
    want_hash: &str,
) -> Result<String, String> {
    let (id, secret) = token_parts(token)?;
    let (code, body, chain) = insecure_get(
        host,
        port,
        "/api/v1/namespaces/kube-public/configmaps/cluster-info",
    )
    .await?;
    if code == 200 {
        let cm: Value = serde_json::from_slice(&body).map_err(|e| e.to_string())?;
        let kubeconfig = s(&cm, "/data/kubeconfig");
        if kubeconfig.is_empty() {
            return Err("cluster-info has no kubeconfig".into());
        }
        let jws = s(&cm, &format!("/data/jws-kubeconfig-{id}"));
        if !jws.is_empty() && !verify_jws(secret, kubeconfig, jws) {
            return Err("cluster-info signature does not match the bootstrap token".into());
        }
        let cfg = yaml::parse(kubeconfig);
        let ca = cfg["clusters"][0]["cluster"]["certificate-authority-data"]
            .as_str()
            .and_then(base64_decode)
            .ok_or("cluster-info has no certificate-authority-data")?;
        return pick_ca(&ca, want_hash)
            .ok_or_else(|| "no CA in cluster-info matches --ca-hash".to_string());
    }
    for der in &chain {
        if spki_hash(der).as_deref() == Some(want_hash) {
            return Ok(pem_of(der));
        }
    }
    Err(format!(
        "cluster-info unavailable (HTTP {code}) and no certificate in the server chain matches --ca-hash"
    ))
}

fn write_private(path: &Path, data: &[u8]) -> Result<(), String> {
    crate::kubelet_api::write_private(path, data).map_err(|e| format!("{}: {e}", path.display()))
}

fn kubeconfig_text(server: &str, ca: &str, user: &str) -> String {
    format!(
        "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}",
        b64::encode_std(ca.as_bytes())
    )
}

pub async fn request_client_cert(c: &Client, node: &str) -> Result<(String, String), String> {
    let req = csr::client_request(node).map_err(|e| e.to_string())?;
    let name = format!("csr-krab-client-{node}-{:08x}", rand_u64() as u32);
    let body = json!({
        "apiVersion": "certificates.k8s.io/v1",
        "kind": "CertificateSigningRequest",
        "metadata": {"name": name},
        "spec": {
            "request": b64::encode_std(req.csr_pem.as_bytes()),
            "signerName": "kubernetes.io/kube-apiserver-client-kubelet",
            "usages": ["digital signature", "key encipherment", "client auth"]
        }
    });
    let (code, out) = c.post(CSR_PATH, &body).await.map_err(|e| e.to_string())?;
    if !matches!(code, 200 | 201) {
        return Err(format!("create CSR: HTTP {code} {}", s(&out, "/message")));
    }
    let path = format!("{CSR_PATH}/{name}");
    for _ in 0..100 {
        tokio::time::sleep(Duration::from_secs(3)).await;
        let Ok((200, csr)) = c.get(&path).await else {
            continue;
        };
        let cert = s(&csr, "/status/certificate");
        if !cert.is_empty() {
            let pem = base64_decode(cert)
                .and_then(|b| String::from_utf8(b).ok())
                .ok_or("CSR certificate is not valid PEM")?;
            return Ok((req.key_pem, pem));
        }
        let failed = csr["status"]["conditions"]
            .as_array()
            .into_iter()
            .flatten()
            .find(|x| matches!(s(x, "/type"), "Denied" | "Failed"));
        if let Some(f) = failed {
            return Err(format!("CSR {}: {}", s(f, "/type"), s(f, "/message")));
        }
    }
    Err("CSR was not approved within 5 minutes".into())
}

fn install(dir: &Path, key: &str, cert: &str) -> Result<(), String> {
    let pki = dir.join("pki");
    std::fs::create_dir_all(&pki).map_err(|e| e.to_string())?;
    write_private(&pki.join("client.key"), key.as_bytes())?;
    write_private(&pki.join("client.crt"), cert.as_bytes())
}

fn write_final(dir: &Path, server: &str, ca: &str) -> Result<PathBuf, String> {
    let pki = dir.join("pki");
    let user = format!(
        "    client-certificate: {}\n    client-key: {}\n",
        pki.join("client.crt").display(),
        pki.join("client.key").display()
    );
    let path = dir.join("kubeconfig");
    write_private(&path, kubeconfig_text(server, ca, &user).as_bytes())?;
    Ok(path)
}

fn cert_valid(dir: &Path, node: &str) -> bool {
    let Ok(pem) = std::fs::read(dir.join("pki").join("client.crt")) else {
        return false;
    };
    let Some(Ok(c)) = CertificateDer::pem_slice_iter(&pem).next() else {
        return false;
    };
    let ok_subject =
        der::subject_cn_o(c.as_ref()).is_some_and(|(cn, _)| cn == format!("system:node:{node}"));
    ok_subject && der::validity(c.as_ref()).is_some_and(|(_, na)| na > now_secs())
}

fn now_secs() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

pub fn existing(dir: &Path, node: &str) -> Option<PathBuf> {
    let kubeconfig = dir.join("kubeconfig");
    (kubeconfig.exists() && cert_valid(dir, node)).then_some(kubeconfig)
}

pub async fn join(o: &JoinOpts) -> Result<PathBuf, String> {
    if let Some(kubeconfig) = existing(&o.dir, &o.node_name) {
        return Ok(kubeconfig);
    }
    let (host, port) = parse_server(&o.server)?;
    let want = parse_hash(&o.ca_hash)?;
    token_parts(&o.token)?;
    std::fs::create_dir_all(&o.dir).map_err(|e| e.to_string())?;
    let ca = discover(&host, port, &o.token, &want).await?;
    let token_file = o.dir.join("bootstrap-token");
    write_private(&token_file, o.token.as_bytes())?;
    let user = format!("    tokenFile: {}\n", token_file.display());
    let boot = o.dir.join("bootstrap-kubeconfig");
    write_private(&boot, kubeconfig_text(&o.server, &ca, &user).as_bytes())?;
    let client = Client::from_kubeconfig(&boot)?;
    let (key, cert) = request_client_cert(&client, &o.node_name).await?;
    install(&o.dir, &key, &cert)?;
    let path = write_final(&o.dir, &o.server, &ca)?;
    let _ = std::fs::remove_file(&token_file);
    let _ = std::fs::remove_file(&boot);
    Ok(path)
}

pub fn rotation_wait(nb: i64, na: i64, now: i64) -> Option<Duration> {
    let due = nb + (na - nb) * 8 / 10;
    if now >= due {
        None
    } else {
        Some(Duration::from_secs(
            ((due - now) as u64 + 1).min(ROTATE_CHECK.as_secs()),
        ))
    }
}

pub async fn rotate_loop(kubeconfig: PathBuf, node: String, dir: PathBuf) {
    loop {
        let validity = std::fs::read(dir.join("pki").join("client.crt"))
            .ok()
            .and_then(|pem| {
                CertificateDer::pem_slice_iter(&pem)
                    .next()
                    .and_then(Result::ok)
                    .and_then(|c| der::validity(c.as_ref()))
            });
        if let Some((nb, na)) = validity
            && let Some(wait) = rotation_wait(nb, na, now_secs())
        {
            tokio::time::sleep(wait).await;
            continue;
        }
        if validity.is_some() {
            match Client::from_kubeconfig(&kubeconfig) {
                Ok(client) => match request_client_cert(&client, &node).await {
                    Ok((key, cert)) => {
                        let text = std::fs::read_to_string(&kubeconfig).unwrap_or_default();
                        if install(&dir, &key, &cert).is_ok()
                            && write_private(&kubeconfig, text.as_bytes()).is_ok()
                        {
                            eprintln!("krab-agent: client certificate rotated");
                            continue;
                        }
                    }
                    Err(e) => eprintln!("krab-agent: rotate: {e}"),
                },
                Err(e) => eprintln!("krab-agent: rotate: {e}"),
            }
        }
        tokio::time::sleep(Duration::from_secs(60)).await;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_inputs() {
        assert_eq!(
            parse_server("https://10.0.0.1:6443").unwrap(),
            ("10.0.0.1".into(), 6443)
        );
        assert_eq!(
            parse_server("https://k8s.example.com").unwrap(),
            ("k8s.example.com".into(), 443)
        );
        assert!(parse_server("http://x:1").is_err());
        assert!(parse_server("https://x:1/path").is_err());
        assert!(token_parts("abcdef.0123456789abcdef").is_ok());
        assert!(token_parts("ABCDEF.0123456789abcdef").is_err());
        assert!(token_parts("abcdef").is_err());
        let h = format!("sha256:{}", "AB".repeat(32));
        assert_eq!(parse_hash(&h).unwrap(), "ab".repeat(32));
        assert!(parse_hash("sha256:zz").is_err());
        assert!(parse_hash(&"ab".repeat(32)).is_err());
    }

    #[test]
    fn rotation_waits_until_eighty_percent_of_lifetime() {
        assert_eq!(rotation_wait(0, 1000, 0), Some(Duration::from_secs(600)));
        assert_eq!(rotation_wait(0, 1000, 790), Some(Duration::from_secs(11)));
        assert_eq!(rotation_wait(0, 1000, 800), None);
        assert_eq!(rotation_wait(0, 1000, 5000), None);
    }

    #[test]
    fn jws_roundtrip() {
        let payload = "apiVersion: v1\nkind: Config\n";
        let header = url_encode(br#"{"alg":"HS256","kid":"abcdef"}"#);
        let key = hmac::Key::new(hmac::HMAC_SHA256, b"0123456789abcdef");
        let sig = hmac::sign(
            &key,
            format!("{header}.{}", url_encode(payload.as_bytes())).as_bytes(),
        );
        let jws = format!("{header}..{}", url_encode(sig.as_ref()));
        assert!(verify_jws("0123456789abcdef", payload, &jws));
        assert!(!verify_jws("0123456789abcdee", payload, &jws));
        assert!(!verify_jws("0123456789abcdef", "tampered", &jws));
        assert!(!verify_jws("0123456789abcdef", payload, "garbage"));
    }

    #[test]
    fn hashes_a_real_ca_and_picks_it() {
        let d = tempfile::tempdir().unwrap();
        let p = krab_tls::pki::ensure(d.path(), "n1", &[]).unwrap();
        let ders = CertificateDer::pem_slice_iter(p.ca_cert_pem.as_bytes())
            .collect::<Result<Vec<_>, _>>()
            .unwrap();
        let h = spki_hash(ders[0].as_ref()).unwrap();
        assert_eq!(h.len(), 64);
        let picked = pick_ca(p.ca_cert_pem.as_bytes(), &h).unwrap();
        assert!(picked.starts_with("-----BEGIN CERTIFICATE-----"));
        assert!(pick_ca(p.ca_cert_pem.as_bytes(), &"0".repeat(64)).is_none());
        assert!(
            kubeconfig_text("https://x:1", &picked, "    tokenFile: /t\n")
                .contains("tokenFile: /t")
        );
    }
}