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")
);
}
}