Skip to main content

vault_core/
generators.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Cryptographic key and certificate generators.
4//!
5//! Every generator here takes an [`crate::entropy::Source`]. That is the whole
6//! reason this module changed in Phase 17: the CLI's secret and password
7//! generators used the default RNG while these two used an OS RNG, so there
8//! was no single seam an entropy source could attach to. There is one now, and
9//! the source reaches the key material rather than being applied to it
10//! afterwards — `rcgen` and `ssh-key` both generate their own keys, so bytes
11//! have to go *in*, not be mixed in after the fact.
12
13use crate::entropy::{EntropyRng, Source};
14use rcgen::{CertificateParams, DistinguishedName, DnType, KeyPair};
15use time::Duration;
16
17/// PKCS#8 v1 prefix for an Ed25519 private key: SEQUENCE, version 0,
18/// AlgorithmIdentifier 1.3.101.112, OCTET STRING wrapping the 32-byte seed.
19///
20/// Fixed because the structure is fixed — every Ed25519 PKCS#8 key differs only
21/// in its last 32 bytes. Building it here is what lets our entropy decide the
22/// certificate key, since `rcgen::KeyPair::generate` takes no RNG.
23const ED25519_PKCS8_PREFIX: [u8; 16] = [
24    0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20,
25];
26
27/// Generates a self-signed X.509 certificate and private key PEM pair.
28///
29/// Returns `{"cert_pem": "...", "key_pem": "..."}`.
30pub fn generate_certificate(
31    common_name: &str,
32    validity_days: u32,
33    source: &Source,
34) -> Result<serde_json::Value, String> {
35    let key_pair = if source.is_external() {
36        // Our bytes become the key. `KeyPair::generate()` would use ring's own
37        // RNG and quietly ignore the source the user selected.
38        let mut seed = [0u8; 32];
39        crate::entropy::fill(source, "cert-ed25519", &mut seed)?;
40        let mut der = Vec::with_capacity(48);
41        der.extend_from_slice(&ED25519_PKCS8_PREFIX);
42        der.extend_from_slice(&seed);
43        KeyPair::from_pkcs8_der_and_sign_algo(&der.into(), &rcgen::PKCS_ED25519)
44            .map_err(|e| e.to_string())?
45    } else {
46        KeyPair::generate().map_err(|e| e.to_string())?
47    };
48    let mut params =
49        CertificateParams::new(vec![common_name.to_string()]).map_err(|e| e.to_string())?;
50    let mut dn = DistinguishedName::new();
51    dn.push(DnType::CommonName, common_name);
52    params.distinguished_name = dn;
53    params.not_after =
54        time::OffsetDateTime::now_utc() + Duration::days(validity_days.max(1) as i64);
55    let cert = params.self_signed(&key_pair).map_err(|e| e.to_string())?;
56    Ok(serde_json::json!({
57        "cert_pem": cert.pem(),
58        "key_pem":  key_pair.serialize_pem(),
59        "entropy_source": source.label(),
60    }))
61}
62
63/// Generates an Ed25519 SSH key pair in OpenSSH format.
64///
65/// Returns `{"public_key": "...", "private_key": "..."}`.
66pub fn generate_ssh_keypair(comment: &str, source: &Source) -> Result<serde_json::Value, String> {
67    use ssh_key::{Algorithm, LineEnding, PrivateKey};
68
69    // Fail before generating rather than during: `RngCore::fill_bytes` cannot
70    // return an error, so a device that disappears mid-generation can only
71    // panic. Checking here turns the common case (device not plugged in) into a
72    // clean message.
73    if let crate::entropy::Availability::Missing(why) = source.availability() {
74        return Err(format!("Entropy source {source} is unavailable: {why}"));
75    }
76    let mut rng = EntropyRng::new(source.clone(), "ssh-ed25519");
77    let mut private_key =
78        PrivateKey::random(&mut rng, Algorithm::Ed25519).map_err(|e| e.to_string())?;
79    private_key.set_comment(comment);
80    let public_key_str = private_key
81        .public_key()
82        .to_openssh()
83        .map_err(|e| e.to_string())?;
84    let private_key_str = private_key
85        .to_openssh(LineEnding::LF)
86        .map_err(|e| e.to_string())?;
87    Ok(serde_json::json!({
88        "public_key":  public_key_str,
89        "private_key": private_key_str.to_string(),
90        "entropy_source": source.label(),
91    }))
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97
98    #[test]
99    fn a_cert_from_our_own_entropy_is_still_a_valid_cert() {
100        // The PKCS#8 wrapping is hand-built, so this asserts the bytes rcgen
101        // accepts are the bytes we produced — a wrong prefix would fail here
102        // rather than in the field.
103        let src = Source::File {
104            path: "/dev/urandom".into(),
105        };
106        if src.availability() != crate::entropy::Availability::Ready {
107            return;
108        }
109        let v = generate_certificate("example.test", 30, &src).expect("generate");
110        assert!(v["cert_pem"]
111            .as_str()
112            .unwrap()
113            .starts_with("-----BEGIN CERTIFICATE-----"));
114        assert!(v["key_pem"].as_str().unwrap().contains("PRIVATE KEY"));
115        assert_eq!(v["entropy_source"], "file:/dev/urandom");
116    }
117
118    #[test]
119    fn ssh_keys_differ_between_generations() {
120        let a = generate_ssh_keypair("a", &Source::Os).unwrap();
121        let b = generate_ssh_keypair("b", &Source::Os).unwrap();
122        assert_ne!(a["private_key"], b["private_key"]);
123    }
124
125    #[test]
126    fn an_unavailable_source_refuses_before_generating() {
127        let src = Source::File {
128            path: "/nonexistent/device".into(),
129        };
130        assert!(generate_ssh_keypair("x", &src).is_err());
131        assert!(generate_certificate("x.test", 30, &src).is_err());
132    }
133}