//! Key pairs for the `key-pair` item type (docs/KEYS.md): Ed25519, ECDSA P-256 and RSA, written as an //! OpenSSH public line, SPKI PEM, PKCS#8 PEM and an OpenSSH private key. RustCrypto crates only; the //! randomness is the OS CSPRNG (`rand_core::OsRng`). use custos_vault::SecretString; use ed25519_dalek::pkcs8::spki::der::pem::LineEnding; use rand_core::OsRng; use ssh_key::private::{EcdsaKeypair, Ed25519Keypair, KeypairData, RsaKeypair}; use ssh_key::{HashAlg, PrivateKey}; #[derive(Debug, thiserror::Error)] pub enum KeyError { #[error("the key could not be generated or encoded")] Encode, #[error("not a valid key of this algorithm")] Invalid, #[error("the key is protected with a passphrase; remove it or import the key in the Custos app")] Encrypted, #[error("not a private key Custos can import (Ed25519, ECDSA P-256 or RSA 2048-4096 bits)")] Unsupported, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Algorithm { Ed25519, EcdsaP256, Rsa3072, Rsa4096, } impl Algorithm { pub const ALL: [Algorithm; 4] = [Algorithm::Ed25519, Algorithm::EcdsaP256, Algorithm::Rsa3072, Algorithm::Rsa4096]; /// The value of the item's `algorithm` field. pub fn name(self) -> &'static str { match self { Algorithm::Ed25519 => "ed25519", Algorithm::EcdsaP256 => "ecdsa-p256", Algorithm::Rsa3072 => "rsa-3072", Algorithm::Rsa4096 => "rsa-4096", } } pub fn from_name(s: &str) -> Option { Algorithm::ALL.into_iter().find(|a| a.name() == s) } } /// A generated key pair, ready to become a `key-pair` item. `Debug` never shows the private parts. #[derive(Clone, Debug)] pub struct KeyPair { pub algorithm: String, /// `ssh-ed25519 AAAA… comment`. pub public_openssh: String, /// SubjectPublicKeyInfo PEM. pub public_pem: String, /// PKCS#8 PEM, unencrypted (the vault is its encryption). pub private_pem: SecretString, /// OpenSSH private key, unencrypted. pub private_openssh: SecretString, /// `SHA256:…`, as `ssh-keygen -l` prints it. pub fingerprint: String, } fn enc(r: Result) -> Result { r.map_err(|_| KeyError::Encode) } /// A new key pair. RSA takes a few seconds (prime generation). pub fn generate(alg: Algorithm, comment: &str) -> Result { match alg { Algorithm::Ed25519 => from_ed25519(ed25519_dalek::SigningKey::generate(&mut OsRng), comment), Algorithm::EcdsaP256 => from_p256(p256::SecretKey::random(&mut OsRng), comment), Algorithm::Rsa3072 | Algorithm::Rsa4096 => { let bits = if alg == Algorithm::Rsa3072 { 3072 } else { 4096 }; from_rsa(enc(rsa::RsaPrivateKey::new(&mut OsRng, bits))?, comment) } } } /// An existing private key as a key pair (docs/KEYS.md, "Importing"): an OpenSSH private key, PKCS#8 /// (`BEGIN PRIVATE KEY`), PKCS#1 (`BEGIN RSA PRIVATE KEY`) or SEC1 (`BEGIN EC PRIVATE KEY`), unencrypted. /// The public parts and the fingerprint are derived from the private key, never taken from the input. /// An OpenSSH key keeps its own comment unless it has none. pub fn import(text: &str, comment: &str) -> Result { // Pasted or read from a Windows file: CRLF line ends. let text = text.replace(" ", " "); let text = text.trim(); let has = |label: &str| text.contains(&format!("-----BEGIN {label}-----")); if has("ENCRYPTED PRIVATE KEY") || text.contains("Proc-Type: 4,ENCRYPTED") { return Err(KeyError::Encrypted); } if has("OPENSSH PRIVATE KEY") { let key = PrivateKey::from_openssh(text).map_err(|_| KeyError::Invalid)?; if key.is_encrypted() { return Err(KeyError::Encrypted); } let comment = if key.comment().is_empty() { comment.to_owned() } else { key.comment().to_owned() }; return match key.key_data() { KeypairData::Ed25519(k) => from_ed25519(ed25519_dalek::SigningKey::from_bytes(&k.private.to_bytes()), &comment), KeypairData::Ecdsa(EcdsaKeypair::NistP256 { private, .. }) => { from_p256(p256::SecretKey::from_slice(private.as_slice()).map_err(|_| KeyError::Invalid)?, &comment) } KeypairData::Rsa(k) => from_rsa(rsa_from_openssh(k)?, &comment), KeypairData::Encrypted(_) => Err(KeyError::Encrypted), _ => Err(KeyError::Unsupported), }; } if has("PRIVATE KEY") { use ed25519_dalek::pkcs8::DecodePrivateKey; if let Ok(sk) = ed25519_dalek::SigningKey::from_pkcs8_pem(text) { return from_ed25519(sk, comment); } if let Ok(sk) = p256::SecretKey::from_pkcs8_pem(text) { return from_p256(sk, comment); } if let Ok(sk) = rsa::RsaPrivateKey::from_pkcs8_pem(text) { return from_rsa(sk, comment); } return Err(KeyError::Unsupported); } if has("RSA PRIVATE KEY") { use rsa::pkcs1::DecodeRsaPrivateKey; return from_rsa(rsa::RsaPrivateKey::from_pkcs1_pem(text).map_err(|_| KeyError::Invalid)?, comment); } if has("EC PRIVATE KEY") { return from_p256(p256::SecretKey::from_sec1_pem(text).map_err(|_| KeyError::Unsupported)?, comment); } Err(KeyError::Unsupported) } /// ssh-key 0.6.7's own `TryFrom<&RsaKeypair>` passes `p` twice instead of `p` and `q`, so the key is /// rebuilt from its components here. fn rsa_from_openssh(k: &RsaKeypair) -> Result { let n = |m: &ssh_key::Mpint| rsa::BigUint::try_from(m).map_err(|_| KeyError::Invalid); let sk = rsa::RsaPrivateKey::from_components(n(&k.public.n)?, n(&k.public.e)?, n(&k.private.d)?, vec![n(&k.private.p)?, n(&k.private.q)?]) .map_err(|_| KeyError::Invalid)?; sk.validate().map_err(|_| KeyError::Invalid)?; Ok(sk) } fn from_ed25519(sk: ed25519_dalek::SigningKey, comment: &str) -> Result { use ed25519_dalek::pkcs8::{EncodePrivateKey, EncodePublicKey}; let private_pem = enc(sk.to_pkcs8_pem(LineEnding::LF))?.to_string(); let public_pem = enc(sk.verifying_key().to_public_key_pem(LineEnding::LF))?; assemble("ed25519", KeypairData::Ed25519(Ed25519Keypair::from(&sk)), private_pem, public_pem, comment) } fn from_p256(sk: p256::SecretKey, comment: &str) -> Result { use p256::pkcs8::{EncodePrivateKey, EncodePublicKey}; let private_pem = enc(sk.to_pkcs8_pem(LineEnding::LF))?.to_string(); let public_pem = enc(sk.public_key().to_public_key_pem(LineEnding::LF))?; let public = sk.public_key(); let data = KeypairData::Ecdsa(EcdsaKeypair::NistP256 { private: sk.into(), public: public.into() }); assemble("ecdsa-p256", data, private_pem, public_pem, comment) } fn from_rsa(sk: rsa::RsaPrivateKey, comment: &str) -> Result { use rsa::pkcs8::{EncodePrivateKey, EncodePublicKey}; use rsa::traits::PublicKeyParts; let bits = sk.size() * 8; if !(2048..=4096).contains(&bits) { return Err(KeyError::Unsupported); } let private_pem = enc(sk.to_pkcs8_pem(LineEnding::LF))?.to_string(); let public_pem = enc(sk.to_public_key().to_public_key_pem(LineEnding::LF))?; assemble(&format!("rsa-{bits}"), KeypairData::Rsa(enc(RsaKeypair::try_from(sk))?), private_pem, public_pem, comment) } fn assemble(algorithm: &str, data: KeypairData, private_pem: String, public_pem: String, comment: &str) -> Result { let private = enc(PrivateKey::new(data, comment))?; let public = private.public_key(); Ok(KeyPair { algorithm: algorithm.into(), public_openssh: enc(public.to_openssh())?, public_pem, private_pem: SecretString::new(private_pem), private_openssh: SecretString::new(enc(private.to_openssh(ssh_key::LineEnding::LF))?.to_string()), fingerprint: public.fingerprint(HashAlg::Sha256).to_string(), }) } /// Whether a PKCS#8 private key and an SPKI public key belong together (tests, and a check before /// importing a key pair someone pasted). pub fn pem_matches(alg: Algorithm, private_pem: &str, public_pem: &str) -> Result { let derived = match alg { Algorithm::Ed25519 => { use ed25519_dalek::pkcs8::{DecodePrivateKey, EncodePublicKey}; let sk = ed25519_dalek::SigningKey::from_pkcs8_pem(private_pem).map_err(|_| KeyError::Invalid)?; enc(sk.verifying_key().to_public_key_pem(LineEnding::LF))? } Algorithm::EcdsaP256 => { use p256::pkcs8::{DecodePrivateKey, EncodePublicKey}; let sk = p256::SecretKey::from_pkcs8_pem(private_pem).map_err(|_| KeyError::Invalid)?; enc(sk.public_key().to_public_key_pem(LineEnding::LF))? } Algorithm::Rsa3072 | Algorithm::Rsa4096 => { use rsa::pkcs8::{DecodePrivateKey, EncodePublicKey}; let sk = rsa::RsaPrivateKey::from_pkcs8_pem(private_pem).map_err(|_| KeyError::Invalid)?; enc(sk.to_public_key().to_public_key_pem(LineEnding::LF))? } }; Ok(derived.trim() == public_pem.trim()) } /// An Ed25519 signature (64 bytes) of `message` with a PKCS#8 private key. pub fn sign_ed25519(private_pem: &str, message: &[u8]) -> Result, KeyError> { use ed25519_dalek::Signer; use ed25519_dalek::pkcs8::DecodePrivateKey; let sk = ed25519_dalek::SigningKey::from_pkcs8_pem(private_pem).map_err(|_| KeyError::Invalid)?; Ok(sk.sign(message).to_bytes().to_vec()) } /// Whether `signature` is a valid Ed25519 signature of `message` under an SPKI public key. pub fn verify_ed25519(public_pem: &str, message: &[u8], signature: &[u8]) -> Result { use ed25519_dalek::Verifier; use ed25519_dalek::pkcs8::DecodePublicKey; let vk = ed25519_dalek::VerifyingKey::from_public_key_pem(public_pem).map_err(|_| KeyError::Invalid)?; let sig = ed25519_dalek::Signature::from_slice(signature).map_err(|_| KeyError::Invalid)?; Ok(vk.verify(message, &sig).is_ok()) }