Skip to main content

alien_signing/
key.rs

1//! ECDSA P-256 keys in the text forms statements and signer lists carry.
2//!
3//! A public key travels as `ecdsa-p256:<base64 DER SubjectPublicKeyInfo>` and a
4//! signature as base64 DER ECDSA over the SHA-256 of the signed bytes. Those
5//! are the forms cloud key services, Secure Enclave, TPMs and PIV tokens
6//! produce, so a key can live in any of them.
7
8use std::fmt;
9
10use alien_error::AlienError;
11use base64::engine::general_purpose::STANDARD;
12use base64::Engine as _;
13use p256::ecdsa::signature::{Signer as _, Verifier as _};
14use p256::ecdsa::{DerSignature, SigningKey, VerifyingKey};
15use p256::pkcs8::{
16    DecodePrivateKey, DecodePublicKey, EncodePrivateKey, EncodePublicKey, LineEnding,
17};
18use sha2::{Digest, Sha256};
19
20use crate::error::{ErrorData, Result};
21
22/// Prefix of a public key in text form.
23pub const PUBLIC_KEY_PREFIX: &str = "ecdsa-p256:";
24
25/// A P-256 public key that parsed, so it is a valid point on the curve.
26#[derive(Clone, PartialEq, Eq)]
27pub struct PublicKey {
28    key: VerifyingKey,
29    text: String,
30}
31
32impl fmt::Debug for PublicKey {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        f.write_str(&self.text)
35    }
36}
37
38impl PublicKey {
39    /// Parse `ecdsa-p256:<base64 DER SPKI>`. The point decoder rejects points
40    /// that are not on the curve and the identity, so an invalid-curve or
41    /// low-order key can't enter a signer list.
42    pub fn parse(text: &str) -> Result<Self> {
43        let encoded = text.strip_prefix(PUBLIC_KEY_PREFIX).ok_or_else(|| {
44            key_invalid(format!("the key does not start with '{PUBLIC_KEY_PREFIX}'"))
45        })?;
46        let der = STANDARD
47            .decode(encoded)
48            .map_err(|_| key_invalid("the key is not valid base64"))?;
49        let key = VerifyingKey::from_public_key_der(&der)
50            .map_err(|_| key_invalid("the key is not a DER P-256 SubjectPublicKeyInfo"))?;
51        Ok(Self::from_verifying_key(key))
52    }
53
54    fn from_verifying_key(key: VerifyingKey) -> Self {
55        let der = key
56            .to_public_key_der()
57            .expect("a valid P-256 public key always encodes");
58        let text = format!("{PUBLIC_KEY_PREFIX}{}", STANDARD.encode(der.as_bytes()));
59        Self { key, text }
60    }
61
62    /// The key in text form. Parsing re-encodes, so two spellings of one key
63    /// give the same text.
64    pub fn as_str(&self) -> &str {
65        &self.text
66    }
67
68    /// `SHA256:<hex>` of the DER SubjectPublicKeyInfo, for display.
69    pub fn fingerprint(&self) -> String {
70        let der = self
71            .key
72            .to_public_key_der()
73            .expect("a valid P-256 public key always encodes");
74        format!("SHA256:{}", hex::encode(Sha256::digest(der.as_bytes())))
75    }
76
77    /// Whether `signature` (base64 DER) is this key's signature over `message`.
78    pub fn verify(&self, message: &[u8], signature: &str) -> Result<()> {
79        let der = STANDARD
80            .decode(signature)
81            .map_err(|_| signature_invalid("the signature is not valid base64"))?;
82        let signature = DerSignature::try_from(der.as_slice())
83            .map_err(|_| signature_invalid("the signature is not DER ECDSA"))?;
84        self.key
85            .verify(message, &signature)
86            .map_err(|_| signature_invalid("the signature does not match the signed bytes"))
87    }
88}
89
90/// A private key held in memory: the CI key, or the recovery key while it
91/// signs. Device keys never take this form; they stay in secure hardware.
92pub struct SecretKey(SigningKey);
93
94impl fmt::Debug for SecretKey {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        f.debug_tuple("SecretKey")
97            .field(&self.public_key())
98            .finish()
99    }
100}
101
102impl SecretKey {
103    /// A new random key from the operating system's generator.
104    pub fn generate() -> Result<Self> {
105        // Random bytes are a valid scalar except with negligible probability.
106        loop {
107            let mut secret = [0u8; 32];
108            getrandom::fill(&mut secret).map_err(|error| {
109                key_invalid(format!("the system random source failed: {error}"))
110            })?;
111            if let Ok(key) = Self::from_secret_bytes(&secret) {
112                return Ok(key);
113            }
114        }
115    }
116
117    /// The key for 32 secret bytes, which must be a valid P-256 scalar.
118    pub fn from_secret_bytes(bytes: &[u8; 32]) -> Result<Self> {
119        SigningKey::from_slice(bytes)
120            .map(Self)
121            .map_err(|_| key_invalid("the secret bytes are not a valid P-256 scalar"))
122    }
123
124    /// Read a PKCS#8 PEM private key.
125    pub fn from_pkcs8_pem(pem: &str) -> Result<Self> {
126        SigningKey::from_pkcs8_pem(pem.trim())
127            .map(Self)
128            .map_err(|_| key_invalid("the text is not a PKCS#8 PEM ECDSA P-256 private key"))
129    }
130
131    /// The key as PKCS#8 PEM.
132    pub fn to_pkcs8_pem(&self) -> Result<String> {
133        self.0
134            .to_pkcs8_pem(LineEnding::LF)
135            .map(|pem| pem.as_str().to_string())
136            .map_err(|_| key_invalid("the key could not be encoded"))
137    }
138
139    /// The public half.
140    pub fn public_key(&self) -> PublicKey {
141        PublicKey::from_verifying_key(*self.0.verifying_key())
142    }
143
144    /// Base64 DER signature over `message`.
145    pub fn sign(&self, message: &[u8]) -> String {
146        let signature: DerSignature = self.0.sign(message);
147        STANDARD.encode(signature.as_bytes())
148    }
149}
150
151fn key_invalid(reason: impl Into<String>) -> AlienError<ErrorData> {
152    AlienError::new(ErrorData::KeyInvalid {
153        reason: reason.into(),
154    })
155}
156
157fn signature_invalid(reason: &str) -> AlienError<ErrorData> {
158    AlienError::new(ErrorData::SignatureRefused {
159        signer: String::new(),
160        reason: reason.to_string(),
161    })
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    #[test]
169    fn a_signature_verifies_only_for_its_key_and_message() {
170        let key = SecretKey::generate().unwrap();
171        let other = SecretKey::generate().unwrap();
172        let signature = key.sign(b"hello");
173        key.public_key().verify(b"hello", &signature).unwrap();
174        key.public_key()
175            .verify(b"hellp", &signature)
176            .expect_err("changed message");
177        other
178            .public_key()
179            .verify(b"hello", &signature)
180            .expect_err("other key");
181    }
182
183    #[test]
184    fn public_keys_round_trip_through_text_and_pem() {
185        let key = SecretKey::generate().unwrap();
186        let text = key.public_key().as_str().to_string();
187        assert_eq!(PublicKey::parse(&text).unwrap(), key.public_key());
188        let restored = SecretKey::from_pkcs8_pem(&key.to_pkcs8_pem().unwrap()).unwrap();
189        assert_eq!(restored.public_key(), key.public_key());
190    }
191
192    #[test]
193    fn points_off_the_curve_are_refused() {
194        let key = SecretKey::generate().unwrap();
195        let der = STANDARD
196            .decode(
197                key.public_key()
198                    .as_str()
199                    .strip_prefix(PUBLIC_KEY_PREFIX)
200                    .unwrap(),
201            )
202            .unwrap();
203        // The uncompressed point is the last 64 bytes; change one byte of y.
204        let mut off_curve = der.clone();
205        let last = off_curve.len() - 1;
206        off_curve[last] ^= 0x01;
207        let text = format!("{PUBLIC_KEY_PREFIX}{}", STANDARD.encode(&off_curve));
208        let error = PublicKey::parse(&text).expect_err("off-curve point");
209        assert_eq!(error.code, "SIGNING_KEY_INVALID");
210
211        PublicKey::parse("ed25519:AAAA").expect_err("other algorithm");
212    }
213}