[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:
@@ -11,6 +11,7 @@ custos-vault = { path = "../custos-vault" }
|
||||
rand.workspace = true
|
||||
zeroize.workspace = true
|
||||
unicode-normalization.workspace = true
|
||||
data-encoding.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
regex = "1"
|
||||
|
||||
@@ -514,3 +514,83 @@ pub fn pin(length: u8) -> Generated {
|
||||
let value: String = (0..len).map(|_| digit()).collect();
|
||||
Generated { value: SecretString::new(value), entropy_bits: len as f64 * 10f64.log2() }
|
||||
}
|
||||
|
||||
// ---------- keys and API keys (docs/KEYS.md) ----------
|
||||
|
||||
/// How a secret key is written out.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum KeyEncoding {
|
||||
/// Lowercase hex.
|
||||
Hex,
|
||||
/// Base64url without padding.
|
||||
Base64Url,
|
||||
/// Standard base64 with padding.
|
||||
Base64,
|
||||
}
|
||||
|
||||
/// `bytes` random bytes (16..=128), encoded: symmetric keys, HMAC and JWT secrets.
|
||||
pub fn secret_key(bytes: usize, encoding: KeyEncoding) -> Result<Generated, GenError> {
|
||||
if !(16..=128).contains(&bytes) {
|
||||
return Err(GenError("a secret key is 16 to 128 bytes".into()));
|
||||
}
|
||||
let mut raw = zeroize::Zeroizing::new(vec![0u8; bytes]);
|
||||
rand::Rng::fill_bytes(&mut rng(), &mut raw);
|
||||
let value = match encoding {
|
||||
KeyEncoding::Hex => data_encoding::HEXLOWER.encode(&raw),
|
||||
KeyEncoding::Base64Url => data_encoding::BASE64URL_NOPAD.encode(&raw),
|
||||
KeyEncoding::Base64 => data_encoding::BASE64.encode(&raw),
|
||||
};
|
||||
Ok(Generated { value: SecretString::new(value), entropy_bits: 8.0 * bytes as f64 })
|
||||
}
|
||||
|
||||
const BASE62: &[u8; 62] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
||||
const API_KEY_RANDOM: usize = 32;
|
||||
|
||||
/// CRC-32 (IEEE 802.3, reflected, as zlib computes it): the API key checksum. Not a security feature.
|
||||
fn crc32(data: &[u8]) -> u32 {
|
||||
let mut crc = !0u32;
|
||||
for &b in data {
|
||||
crc ^= b as u32;
|
||||
for _ in 0..8 {
|
||||
crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 };
|
||||
}
|
||||
}
|
||||
!crc
|
||||
}
|
||||
|
||||
fn checksum6(body: &str) -> String {
|
||||
let mut n = crc32(body.as_bytes()) as u64;
|
||||
let mut out = [b'0'; 6];
|
||||
for c in out.iter_mut().rev() {
|
||||
*c = BASE62[(n % 62) as usize];
|
||||
n /= 62;
|
||||
}
|
||||
String::from_utf8(out.to_vec()).expect("base62 is ASCII")
|
||||
}
|
||||
|
||||
/// `<prefix>_` + 32 uniform base62 characters (190.5 bits) + a 6-character CRC-32 checksum.
|
||||
/// The prefix is empty, or a lowercase letter and up to 15 lowercase letters or digits.
|
||||
pub fn api_key(prefix: &str) -> Result<Generated, GenError> {
|
||||
let ok = prefix.is_empty()
|
||||
|| (prefix.len() <= 16
|
||||
&& prefix.starts_with(|c: char| c.is_ascii_lowercase())
|
||||
&& prefix.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()));
|
||||
if !ok {
|
||||
return Err(GenError("the prefix is a lowercase letter and up to 15 lowercase letters or digits".into()));
|
||||
}
|
||||
let mut body = if prefix.is_empty() { String::new() } else { format!("{prefix}_") };
|
||||
for _ in 0..API_KEY_RANDOM {
|
||||
body.push(BASE62[rng().random_range(0..62)] as char);
|
||||
}
|
||||
let sum = checksum6(&body);
|
||||
body.push_str(&sum);
|
||||
Ok(Generated { value: SecretString::new(body), entropy_bits: API_KEY_RANDOM as f64 * 62f64.log2() })
|
||||
}
|
||||
|
||||
/// Whether an API key's last 6 characters are the checksum of the rest (a typo, or not one of ours).
|
||||
pub fn api_key_checksum_ok(key: &str) -> bool {
|
||||
key.len() > 6 && key.is_char_boundary(key.len() - 6) && {
|
||||
let (body, sum) = key.split_at(key.len() - 6);
|
||||
checksum6(body) == sum
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "custos-keys"
|
||||
description = "Custos key pairs: Ed25519, ECDSA P-256 and RSA, as OpenSSH and PKCS#8 PEM (docs/KEYS.md)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
custos-vault = { path = "../custos-vault" }
|
||||
thiserror.workspace = true
|
||||
# RustCrypto's SSH key formats and the key types they build on (rand_core 0.6 generation API).
|
||||
ssh-key = { version = "0.6", default-features = false, features = ["std", "ed25519", "p256", "rsa", "rand_core"] }
|
||||
ed25519-dalek = { version = "2", features = ["pkcs8", "pem", "rand_core"] }
|
||||
p256 = { version = "0.13", features = ["ecdsa", "pkcs8", "pem"] }
|
||||
rsa = { version = "0.9", features = ["pem"] }
|
||||
rand_core = { version = "0.6", features = ["getrandom"] }
|
||||
@@ -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())
|
||||
}
|
||||
Reference in New Issue
Block a user