[keys] Key pairs and API keys: custos-keys (Ed25519, ECDSA P-256, RSA), secret_key, api_key; threat model; v0.4.0

This commit is contained in:
2026-11-02 15:49:07 +01:00
parent 12783c9b92
commit 3f3cd26590
8 changed files with 914 additions and 48 deletions
+142
View File
@@ -0,0 +1,142 @@
//! 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,
}
#[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<Self> {
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<T, E>(r: Result<T, E>) -> Result<T, KeyError> {
r.map_err(|_| KeyError::Encode)
}
/// A new key pair. RSA takes a few seconds (prime generation).
pub fn generate(alg: Algorithm, comment: &str) -> Result<KeyPair, KeyError> {
let (data, private_pem, public_pem) = match alg {
Algorithm::Ed25519 => {
use ed25519_dalek::pkcs8::{EncodePrivateKey, EncodePublicKey};
let sk = ed25519_dalek::SigningKey::generate(&mut OsRng);
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))?;
(KeypairData::Ed25519(Ed25519Keypair::from(&sk)), private_pem, public_pem)
}
Algorithm::EcdsaP256 => {
use p256::pkcs8::{EncodePrivateKey, EncodePublicKey};
let sk = p256::SecretKey::random(&mut OsRng);
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();
(KeypairData::Ecdsa(EcdsaKeypair::NistP256 { private: sk.into(), public: public.into() }), private_pem, public_pem)
}
Algorithm::Rsa3072 | Algorithm::Rsa4096 => {
use rsa::pkcs8::{EncodePrivateKey, EncodePublicKey};
let bits = if alg == Algorithm::Rsa3072 { 3072 } else { 4096 };
let sk = enc(rsa::RsaPrivateKey::new(&mut OsRng, bits))?;
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))?;
(KeypairData::Rsa(enc(RsaKeypair::try_from(sk))?), private_pem, public_pem)
}
};
let private = enc(PrivateKey::new(data, comment))?;
let public = private.public_key();
Ok(KeyPair {
algorithm: alg.name().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<bool, KeyError> {
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<Vec<u8>, 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<bool, KeyError> {
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())
}