Skip to main content

libtea_client/signature/
keys.rs

1//! `KeyVerifier`: raw detached signatures checked against caller-supplied
2//! public keys (feature `signature-keys`, using `ring`).
3
4use std::fmt;
5
6use base64::Engine;
7use ring::signature::{
8    UnparsedPublicKey, ECDSA_P256_SHA256_ASN1, ECDSA_P256_SHA256_FIXED, ED25519,
9};
10use thiserror::Error;
11
12use super::{
13    detect_signature_format, SignatureFormat, SignatureVerification, SignatureVerifier,
14    SignatureVerifyOutcome, SignedContent, VerifyRequest,
15};
16
17/// DER `SubjectPublicKeyInfo` header of an Ed25519 key (RFC 8410), followed
18/// by the 32 key bytes.
19const ED25519_SPKI_PREFIX: [u8; 12] = [
20    0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,
21];
22
23/// DER `SubjectPublicKeyInfo` header of a P-256 key (RFC 5480,
24/// `id-ecPublicKey` with `prime256v1`), followed by the 65-byte uncompressed
25/// point.
26const P256_SPKI_PREFIX: [u8; 26] = [
27    0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a,
28    0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00,
29];
30
31const PEM_BEGIN: &str = "-----BEGIN PUBLIC KEY-----";
32const PEM_END: &str = "-----END PUBLIC KEY-----";
33
34/// Key files longer than this are rejected before parsing.
35const MAX_KEY_BYTES: usize = 4096;
36
37/// The signature algorithm of a [`PublicKey`].
38///
39/// **Experimental:** may change in a 0.x minor release.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41#[non_exhaustive]
42pub enum KeyAlgorithm {
43    /// Ed25519 (RFC 8032) over the content bytes. The signature is the
44    /// 64-byte value, as `openssl pkeyutl -sign -rawin` writes it.
45    Ed25519,
46    /// ECDSA with P-256 and SHA-256 over the content bytes. The signature is
47    /// DER-encoded, as `openssl dgst -sha256 -sign` writes it, or the 64-byte
48    /// `r || s` form.
49    EcdsaP256Sha256,
50}
51
52impl KeyAlgorithm {
53    /// A stable lowercase name: `ed25519` or `ecdsa-p256-sha256`.
54    #[must_use]
55    pub fn as_str(self) -> &'static str {
56        match self {
57            Self::Ed25519 => "ed25519",
58            Self::EcdsaP256Sha256 => "ecdsa-p256-sha256",
59        }
60    }
61}
62
63impl fmt::Display for KeyAlgorithm {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        f.write_str(self.as_str())
66    }
67}
68
69/// Why bytes are not a public key this verifier accepts.
70///
71/// **Experimental:** may change in a 0.x minor release.
72#[derive(Debug, Clone, PartialEq, Eq, Error)]
73#[non_exhaustive]
74pub enum KeyError {
75    /// Longer than 4096 bytes.
76    #[error("public key is longer than 4096 bytes")]
77    TooLong,
78    /// A `PUBLIC KEY` PEM block whose body is not Base64.
79    #[error("public key PEM body is not Base64")]
80    Pem,
81    /// Not one of the accepted encodings of an Ed25519 or P-256 key.
82    #[error(
83        "not an Ed25519 or P-256 public key (accepted: PEM or DER SubjectPublicKeyInfo, \
84         raw 32-byte Ed25519, raw 65-byte uncompressed P-256 point)"
85    )]
86    Unrecognized,
87}
88
89/// A public key the caller trusts.
90///
91/// **Experimental:** may change in a 0.x minor release.
92///
93/// Accepted encodings, recognised by exact length and fixed header bytes
94/// rather than by a general ASN.1 parser:
95///
96/// - a PEM `PUBLIC KEY` block (as `openssl pkey -pubout` writes it) holding
97///   one of the DER forms below;
98/// - DER `SubjectPublicKeyInfo` of an Ed25519 key (44 bytes) or a P-256 key
99///   with an uncompressed point (91 bytes);
100/// - the raw 32-byte Ed25519 key, or the raw 65-byte uncompressed P-256 point.
101///
102/// [`Self::fingerprint`] is the SHA-256 of the DER `SubjectPublicKeyInfo`,
103/// the same value as `openssl pkey -pubin -outform DER | sha256sum`.
104#[derive(Clone, PartialEq, Eq, Hash)]
105pub struct PublicKey {
106    algorithm: KeyAlgorithm,
107    key: Vec<u8>,
108    fingerprint: String,
109}
110
111impl fmt::Debug for PublicKey {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        f.debug_struct("PublicKey")
114            .field("algorithm", &self.algorithm)
115            .field("fingerprint", &self.fingerprint)
116            .finish_non_exhaustive()
117    }
118}
119
120impl PublicKey {
121    /// Parse a public key in one of the accepted encodings.
122    ///
123    /// ```
124    /// use libtea_client::signature::{KeyAlgorithm, PublicKey};
125    ///
126    /// let key = PublicKey::parse(&[7; 32]).unwrap();
127    /// assert_eq!(key.algorithm(), KeyAlgorithm::Ed25519);
128    /// assert!(key.fingerprint().starts_with("sha256:"));
129    /// assert!(PublicKey::parse(b"not a key").is_err());
130    /// ```
131    ///
132    /// # Errors
133    ///
134    /// [`KeyError`] when the bytes are not an accepted encoding. A P-256 point
135    /// that is not on the curve is not detected here; no signature verifies
136    /// under it.
137    pub fn parse(bytes: &[u8]) -> Result<Self, KeyError> {
138        if bytes.len() > MAX_KEY_BYTES {
139            return Err(KeyError::TooLong);
140        }
141        if let Some(der) = pem_body(bytes)? {
142            return Self::from_der(&der);
143        }
144        match bytes.len() {
145            32 => Ok(Self::new(KeyAlgorithm::Ed25519, bytes)),
146            65 if bytes[0] == 0x04 => Ok(Self::new(KeyAlgorithm::EcdsaP256Sha256, bytes)),
147            _ => Self::from_der(bytes),
148        }
149    }
150
151    fn from_der(der: &[u8]) -> Result<Self, KeyError> {
152        if let Some(key) = der.strip_prefix(&ED25519_SPKI_PREFIX) {
153            if key.len() == 32 {
154                return Ok(Self::new(KeyAlgorithm::Ed25519, key));
155            }
156        }
157        if let Some(point) = der.strip_prefix(&P256_SPKI_PREFIX) {
158            if point.len() == 65 && point[0] == 0x04 {
159                return Ok(Self::new(KeyAlgorithm::EcdsaP256Sha256, point));
160            }
161        }
162        Err(KeyError::Unrecognized)
163    }
164
165    fn new(algorithm: KeyAlgorithm, key: &[u8]) -> Self {
166        let prefix: &[u8] = match algorithm {
167            KeyAlgorithm::Ed25519 => &ED25519_SPKI_PREFIX,
168            KeyAlgorithm::EcdsaP256Sha256 => &P256_SPKI_PREFIX,
169        };
170        let mut der = prefix.to_vec();
171        der.extend_from_slice(key);
172        let digest = ring::digest::digest(&ring::digest::SHA256, &der);
173        let hex: String = digest.as_ref().iter().map(|b| format!("{b:02x}")).collect();
174        Self {
175            algorithm,
176            key: key.to_vec(),
177            fingerprint: format!("sha256:{hex}"),
178        }
179    }
180
181    /// The algorithm.
182    #[must_use]
183    pub fn algorithm(&self) -> KeyAlgorithm {
184        self.algorithm
185    }
186
187    /// `sha256:` and the lowercase hex SHA-256 of the DER `SubjectPublicKeyInfo`.
188    #[must_use]
189    pub fn fingerprint(&self) -> &str {
190        &self.fingerprint
191    }
192
193    fn verifies(&self, message: &[u8], signature: &[u8]) -> bool {
194        match self.algorithm {
195            KeyAlgorithm::Ed25519 => UnparsedPublicKey::new(&ED25519, &self.key)
196                .verify(message, signature)
197                .is_ok(),
198            KeyAlgorithm::EcdsaP256Sha256 => {
199                let fixed = signature.len() == 64
200                    && UnparsedPublicKey::new(&ECDSA_P256_SHA256_FIXED, &self.key)
201                        .verify(message, signature)
202                        .is_ok();
203                fixed
204                    || UnparsedPublicKey::new(&ECDSA_P256_SHA256_ASN1, &self.key)
205                        .verify(message, signature)
206                        .is_ok()
207            }
208        }
209    }
210}
211
212/// The DER inside a `PUBLIC KEY` PEM block, or `None` when the bytes are not
213/// PEM.
214fn pem_body(bytes: &[u8]) -> Result<Option<Vec<u8>>, KeyError> {
215    let Ok(text) = std::str::from_utf8(bytes) else {
216        return Ok(None);
217    };
218    let text = text.trim();
219    let Some(rest) = text.strip_prefix(PEM_BEGIN) else {
220        return Ok(None);
221    };
222    let body = rest.strip_suffix(PEM_END).ok_or(KeyError::Pem)?;
223    let joined: String = body.split_whitespace().collect();
224    base64::engine::general_purpose::STANDARD
225        .decode(joined)
226        .map(Some)
227        .map_err(|_| KeyError::Pem)
228}
229
230/// A [`super::SignatureVerifier`] for raw detached signatures over the decoded
231/// artifact bytes, under public keys the caller supplies.
232///
233/// **Experimental:** may change in a 0.x minor release.
234///
235/// It trusts exactly the keys it is given, fetches none, and returns:
236///
237/// - [`SignatureVerifyOutcome::MissingSignature`] for empty signature bytes;
238/// - [`SignatureVerifyOutcome::NoTrustAnchor`] when it has no keys;
239/// - [`SignatureVerifyOutcome::ContentUnavailable`] when a
240///   [`SignedContent::File`] cannot be read;
241/// - [`SignatureVerifyOutcome::Verified`] when the signature verifies under one
242///   of the keys, with that key's algorithm and fingerprint in
243///   [`SignatureVerification::policy`];
244/// - otherwise [`SignatureVerifyOutcome::Unsupported`] when the bytes look like
245///   a signature container it does not check (OpenPGP, CMS, a Sigstore
246///   bundle, or more than 1 MiB), and [`SignatureVerifyOutcome::Invalid`] for
247///   anything else.
248///
249/// A raw signature is tried under every key before its format is looked at,
250/// so bytes that happen to resemble a container still verify.
251///
252/// ```
253/// use libtea_client::signature::{
254///     KeyVerifier, PublicKey, SignatureVerifier, SignatureVerifyOutcome, SignedContent,
255///     VerifyRequest,
256/// };
257///
258/// let verifier = KeyVerifier::new(vec![PublicKey::parse(&[7; 32]).unwrap()]);
259/// let request = VerifyRequest::new(SignedContent::Bytes(b"artifact"), &[0; 64]);
260/// assert_eq!(verifier.verify(&request).outcome, SignatureVerifyOutcome::Invalid);
261/// assert_eq!(
262///     KeyVerifier::new(vec![]).verify(&request).outcome,
263///     SignatureVerifyOutcome::NoTrustAnchor
264/// );
265/// ```
266#[derive(Debug, Clone, PartialEq, Eq)]
267pub struct KeyVerifier {
268    keys: Vec<PublicKey>,
269}
270
271impl KeyVerifier {
272    /// A verifier that trusts exactly `keys`.
273    #[must_use]
274    pub fn new(keys: Vec<PublicKey>) -> Self {
275        Self { keys }
276    }
277
278    /// The trusted keys.
279    #[must_use]
280    pub fn keys(&self) -> &[PublicKey] {
281        &self.keys
282    }
283
284    fn policy(&self) -> String {
285        let fingerprints: Vec<_> = self.keys.iter().map(PublicKey::fingerprint).collect();
286        format!(
287            "caller keys ({}): {}",
288            self.keys.len(),
289            fingerprints.join(", ")
290        )
291    }
292}
293
294impl SignatureVerifier for KeyVerifier {
295    fn verify(&self, request: &VerifyRequest<'_>) -> SignatureVerification {
296        if request.signature.is_empty() {
297            return SignatureVerification::new(
298                SignatureVerifyOutcome::MissingSignature,
299                self.policy(),
300            );
301        }
302        if self.keys.is_empty() {
303            return SignatureVerification::new(
304                SignatureVerifyOutcome::NoTrustAnchor,
305                "caller keys (0)",
306            );
307        }
308        let read;
309        let message: &[u8] = match request.content {
310            SignedContent::Bytes(bytes) => bytes,
311            SignedContent::File(path) => match std::fs::read(path) {
312                Ok(bytes) => {
313                    read = bytes;
314                    &read
315                }
316                Err(error) => {
317                    return SignatureVerification::new(
318                        SignatureVerifyOutcome::ContentUnavailable,
319                        self.policy(),
320                    )
321                    .with_detail(format!("cannot read {}: {error}", path.display()));
322                }
323            },
324        };
325        if let Some(key) = self
326            .keys
327            .iter()
328            .find(|key| key.verifies(message, request.signature))
329        {
330            return SignatureVerification::new(
331                SignatureVerifyOutcome::Verified,
332                format!("caller key {} {}", key.algorithm(), key.fingerprint()),
333            );
334        }
335        let format = detect_signature_format(request.signature);
336        match format {
337            SignatureFormat::OpenPgpArmored
338            | SignatureFormat::OpenPgpBinary
339            | SignatureFormat::Cms
340            | SignatureFormat::SigstoreBundle
341            | SignatureFormat::TooLarge => {
342                SignatureVerification::new(SignatureVerifyOutcome::Unsupported, self.policy())
343                    .with_detail(format!(
344                    "signature looks like {}, which this verifier does not check; it checks raw \
345                         Ed25519 and ECDSA P-256 signatures",
346                    format.as_str()
347                ))
348            }
349            _ => SignatureVerification::new(SignatureVerifyOutcome::Invalid, self.policy())
350                .with_detail("the signature does not verify under any of the keys"),
351        }
352    }
353}
354
355#[cfg(test)]
356mod tests {
357    use ring::rand::SystemRandom;
358    use ring::signature::{EcdsaKeyPair, Ed25519KeyPair, KeyPair, ECDSA_P256_SHA256_ASN1_SIGNING};
359
360    use super::*;
361
362    fn ed25519() -> Ed25519KeyPair {
363        let rng = SystemRandom::new();
364        let pkcs8 = Ed25519KeyPair::generate_pkcs8(&rng).unwrap();
365        Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).unwrap()
366    }
367
368    fn p256() -> EcdsaKeyPair {
369        let rng = SystemRandom::new();
370        let pkcs8 = EcdsaKeyPair::generate_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, &rng).unwrap();
371        EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, pkcs8.as_ref(), &rng).unwrap()
372    }
373
374    fn check(verifier: &KeyVerifier, message: &[u8], signature: &[u8]) -> SignatureVerification {
375        verifier.verify(&VerifyRequest::new(
376            SignedContent::Bytes(message),
377            signature,
378        ))
379    }
380
381    #[test]
382    fn ed25519_signatures_verify_only_for_their_content_and_key() {
383        let pair = ed25519();
384        let key = PublicKey::parse(pair.public_key().as_ref()).unwrap();
385        assert_eq!(key.algorithm(), KeyAlgorithm::Ed25519);
386        let signature = pair.sign(b"artifact");
387        let verifier = KeyVerifier::new(vec![key.clone()]);
388        let result = check(&verifier, b"artifact", signature.as_ref());
389        assert_eq!(result.outcome, SignatureVerifyOutcome::Verified);
390        assert_eq!(
391            result.policy,
392            format!("caller key ed25519 {}", key.fingerprint())
393        );
394        assert_eq!(
395            check(&verifier, b"artifacT", signature.as_ref()).outcome,
396            SignatureVerifyOutcome::Invalid
397        );
398        let other = KeyVerifier::new(vec![
399            PublicKey::parse(ed25519().public_key().as_ref()).unwrap()
400        ]);
401        assert_eq!(
402            check(&other, b"artifact", signature.as_ref()).outcome,
403            SignatureVerifyOutcome::Invalid
404        );
405    }
406
407    #[test]
408    fn p256_signatures_verify_in_der_and_fixed_form() {
409        let rng = SystemRandom::new();
410        let pair = p256();
411        let key = PublicKey::parse(pair.public_key().as_ref()).unwrap();
412        assert_eq!(key.algorithm(), KeyAlgorithm::EcdsaP256Sha256);
413        let der = pair.sign(&rng, b"artifact").unwrap();
414        let verifier = KeyVerifier::new(vec![key]);
415        assert_eq!(
416            check(&verifier, b"artifact", der.as_ref()).outcome,
417            SignatureVerifyOutcome::Verified
418        );
419        let fixed_pair = {
420            let pkcs8 = EcdsaKeyPair::generate_pkcs8(
421                &ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING,
422                &rng,
423            )
424            .unwrap();
425            EcdsaKeyPair::from_pkcs8(
426                &ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING,
427                pkcs8.as_ref(),
428                &rng,
429            )
430            .unwrap()
431        };
432        let fixed = fixed_pair.sign(&rng, b"artifact").unwrap();
433        assert_eq!(fixed.as_ref().len(), 64);
434        let verifier = KeyVerifier::new(vec![
435            PublicKey::parse(fixed_pair.public_key().as_ref()).unwrap()
436        ]);
437        assert_eq!(
438            check(&verifier, b"artifact", fixed.as_ref()).outcome,
439            SignatureVerifyOutcome::Verified
440        );
441        assert_eq!(
442            check(&verifier, b"other", fixed.as_ref()).outcome,
443            SignatureVerifyOutcome::Invalid
444        );
445    }
446
447    #[test]
448    fn any_of_several_keys_may_verify() {
449        let pair = ed25519();
450        let keys = vec![
451            PublicKey::parse(p256().public_key().as_ref()).unwrap(),
452            PublicKey::parse(pair.public_key().as_ref()).unwrap(),
453        ];
454        let verifier = KeyVerifier::new(keys);
455        let result = check(&verifier, b"artifact", pair.sign(b"artifact").as_ref());
456        assert_eq!(result.outcome, SignatureVerifyOutcome::Verified);
457        assert!(result.policy.starts_with("caller key ed25519 sha256:"));
458    }
459
460    #[test]
461    fn outcomes_other_than_verified() {
462        let verifier = KeyVerifier::new(vec![
463            PublicKey::parse(ed25519().public_key().as_ref()).unwrap()
464        ]);
465        assert_eq!(
466            check(&verifier, b"artifact", b"").outcome,
467            SignatureVerifyOutcome::MissingSignature
468        );
469        assert_eq!(
470            check(&KeyVerifier::new(vec![]), b"artifact", b"x").outcome,
471            SignatureVerifyOutcome::NoTrustAnchor
472        );
473        let armored = b"-----BEGIN PGP SIGNATURE-----\n\nabc\n-----END PGP SIGNATURE-----\n";
474        let result = check(&verifier, b"artifact", armored);
475        assert_eq!(result.outcome, SignatureVerifyOutcome::Unsupported);
476        assert!(result.detail.unwrap().contains("openpgp"));
477        assert_eq!(
478            check(&verifier, b"artifact", &vec![0; 2 << 20]).outcome,
479            SignatureVerifyOutcome::Unsupported
480        );
481        assert_eq!(
482            check(&verifier, b"artifact", &[1; 64]).outcome,
483            SignatureVerifyOutcome::Invalid
484        );
485        let missing = std::path::Path::new("/nonexistent/libtea/artifact");
486        let result = verifier.verify(&VerifyRequest::new(SignedContent::File(missing), &[1; 64]));
487        assert_eq!(result.outcome, SignatureVerifyOutcome::ContentUnavailable);
488    }
489
490    #[test]
491    fn key_encodings() {
492        let pair = ed25519();
493        let raw = pair.public_key().as_ref();
494        let mut der = ED25519_SPKI_PREFIX.to_vec();
495        der.extend_from_slice(raw);
496        let pem = format!(
497            "{PEM_BEGIN}\n{}\n{PEM_END}\n",
498            base64::engine::general_purpose::STANDARD.encode(&der)
499        );
500        let from_raw = PublicKey::parse(raw).unwrap();
501        assert_eq!(PublicKey::parse(&der).unwrap(), from_raw);
502        assert_eq!(PublicKey::parse(pem.as_bytes()).unwrap(), from_raw);
503        for bad in [
504            &b""[..],
505            &[0u8; 31],
506            &[0u8; 33],
507            &[0x05; 65],
508            &der[..43],
509            &[der.as_slice(), &[0]].concat(),
510        ] {
511            assert_eq!(
512                PublicKey::parse(bad),
513                Err(KeyError::Unrecognized),
514                "{bad:?}"
515            );
516        }
517        assert_eq!(
518            PublicKey::parse(format!("{PEM_BEGIN}\n!!\n{PEM_END}").as_bytes()),
519            Err(KeyError::Pem)
520        );
521        assert_eq!(
522            PublicKey::parse(format!("{PEM_BEGIN}\nAAAA\n").as_bytes()),
523            Err(KeyError::Pem)
524        );
525        assert_eq!(PublicKey::parse(&[0; 4097]), Err(KeyError::TooLong));
526        // The Debug output names the key, not its bytes.
527        assert!(!format!("{from_raw:?}").contains("key:"));
528    }
529}