Skip to main content

bitwarden_api_base/
client_certificate.rs

1//! TLS client certificates (mTLS) whose private key stays with the host application.
2//!
3//! The application supplies the certificate chain and a [`ClientCertSigner`] that signs the TLS
4//! handshake with a key held in the platform keystore. Only the chain and the signatures cross the
5//! FFI boundary.
6
7use std::sync::Arc;
8
9use rustls::{
10    SignatureAlgorithm, SignatureScheme,
11    client::ResolvesClientCert,
12    pki_types::CertificateDer,
13    sign::{CertifiedKey, Signer, SigningKey},
14};
15
16/// A TLS signature scheme a client certificate key can sign with.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
19pub enum TlsSigScheme {
20    /// RSASSA-PKCS1-v1_5 with SHA-256.
21    RsaPkcs1Sha256,
22    /// RSASSA-PKCS1-v1_5 with SHA-384.
23    RsaPkcs1Sha384,
24    /// RSASSA-PKCS1-v1_5 with SHA-512.
25    RsaPkcs1Sha512,
26    /// RSASSA-PSS with SHA-256, MGF1 with SHA-256, and a 32-byte salt.
27    RsaPssSha256,
28    /// RSASSA-PSS with SHA-384, MGF1 with SHA-384, and a 48-byte salt.
29    RsaPssSha384,
30    /// RSASSA-PSS with SHA-512, MGF1 with SHA-512, and a 64-byte salt.
31    RsaPssSha512,
32    /// ECDSA on P-256 with SHA-256.
33    EcdsaP256Sha256,
34    /// ECDSA on P-384 with SHA-384.
35    EcdsaP384Sha384,
36}
37
38/// The SDK's preference order, strongest first. The RSA order matches rustls' own RSA keys.
39const SCHEME_PREFERENCE: [TlsSigScheme; 8] = [
40    TlsSigScheme::EcdsaP384Sha384,
41    TlsSigScheme::EcdsaP256Sha256,
42    TlsSigScheme::RsaPssSha512,
43    TlsSigScheme::RsaPssSha384,
44    TlsSigScheme::RsaPssSha256,
45    TlsSigScheme::RsaPkcs1Sha512,
46    TlsSigScheme::RsaPkcs1Sha384,
47    TlsSigScheme::RsaPkcs1Sha256,
48];
49
50impl TlsSigScheme {
51    fn to_rustls(self) -> SignatureScheme {
52        match self {
53            Self::RsaPkcs1Sha256 => SignatureScheme::RSA_PKCS1_SHA256,
54            Self::RsaPkcs1Sha384 => SignatureScheme::RSA_PKCS1_SHA384,
55            Self::RsaPkcs1Sha512 => SignatureScheme::RSA_PKCS1_SHA512,
56            Self::RsaPssSha256 => SignatureScheme::RSA_PSS_SHA256,
57            Self::RsaPssSha384 => SignatureScheme::RSA_PSS_SHA384,
58            Self::RsaPssSha512 => SignatureScheme::RSA_PSS_SHA512,
59            Self::EcdsaP256Sha256 => SignatureScheme::ECDSA_NISTP256_SHA256,
60            Self::EcdsaP384Sha384 => SignatureScheme::ECDSA_NISTP384_SHA384,
61        }
62    }
63
64    /// Whether an RSA key with a modulus of `modulus_bits` can encode this scheme's signature, per
65    /// RFC 8017 sections 9.1.1 (PSS with a digest-length salt) and 9.2 (PKCS #1 v1.5, whose
66    /// SHA-2 `DigestInfo` prefix is 19 bytes).
67    fn fits_rsa_modulus(self, modulus_bits: usize) -> bool {
68        let (digest_len, pss) = match self {
69            Self::RsaPkcs1Sha256 => (32, false),
70            Self::RsaPkcs1Sha384 => (48, false),
71            Self::RsaPkcs1Sha512 => (64, false),
72            Self::RsaPssSha256 => (32, true),
73            Self::RsaPssSha384 => (48, true),
74            Self::RsaPssSha512 => (64, true),
75            Self::EcdsaP256Sha256 | Self::EcdsaP384Sha384 => return false,
76        };
77        if pss {
78            modulus_bits.saturating_sub(1).div_ceil(8) >= 2 * digest_len + 2
79        } else {
80            modulus_bits.div_ceil(8) >= 19 + digest_len + 11
81        }
82    }
83
84    fn algorithm(self) -> SignatureAlgorithm {
85        match self {
86            Self::EcdsaP256Sha256 | Self::EcdsaP384Sha384 => SignatureAlgorithm::ECDSA,
87            _ => SignatureAlgorithm::RSA,
88        }
89    }
90}
91
92/// Error returned by a [`ClientCertSigner`].
93#[derive(Debug, thiserror::Error)]
94#[cfg_attr(feature = "uniffi", derive(uniffi::Error))]
95pub enum ClientCertSignerError {
96    /// The platform could not produce the signature.
97    #[error("Client certificate signing failed: {reason}")]
98    SigningFailed {
99        /// Description of the failure. It reaches the SDK logs, so it must not contain secrets.
100        reason: String,
101    },
102    /// The foreign implementation raised an error it did not declare.
103    #[error("Unexpected client certificate signer error: {reason}")]
104    Unexpected {
105        /// Description of the failure.
106        reason: String,
107    },
108}
109
110#[cfg(feature = "uniffi")]
111impl From<uniffi::UnexpectedUniFFICallbackError> for ClientCertSignerError {
112    fn from(e: uniffi::UnexpectedUniFFICallbackError) -> Self {
113        Self::Unexpected { reason: e.reason }
114    }
115}
116
117/// Signs TLS handshakes with the private key of a client certificate, which never leaves the
118/// host application.
119///
120/// Both methods are called synchronously on the caller's thread: `schemes` inside
121/// [`ClientCertificate::new`], and `sign` inside [`ClientCertificate::validate`] and during the TLS
122/// handshake, on the thread that awaits the networked SDK call. Apps must not await networked SDK
123/// calls on the main thread, and implementations must be thread-safe and must not block on user
124/// interaction.
125#[cfg_attr(feature = "uniffi", uniffi::export(with_foreign))]
126pub trait ClientCertSigner: Send + Sync {
127    /// Signs `message` with `scheme`, which is always one of the schemes returned by
128    /// [`schemes`](Self::schemes).
129    ///
130    /// `message` is the raw data to sign, not a digest: hash it with the scheme's hash as part of
131    /// signing. The result must be an ASN.1 DER `ECDSA-Sig-Value` for ECDSA, an RSASSA-PKCS1-v1_5
132    /// signature for the PKCS#1 schemes, and an RSASSA-PSS signature with MGF1 over the same hash
133    /// and a salt as long as the digest for the PSS schemes.
134    fn sign(
135        &self,
136        scheme: TlsSigScheme,
137        message: Vec<u8>,
138    ) -> Result<Vec<u8>, ClientCertSignerError>;
139
140    /// Every scheme the key can sign with. The SDK calls this once, keeps those that fit the leaf's
141    /// key, and picks its preferred one among those the server accepts.
142    fn schemes(&self) -> Vec<TlsSigScheme>;
143}
144
145/// A client certificate chain and the signer for its private key.
146///
147/// It is presented to every host that requests client authentication on a connection the client
148/// opens. That includes an `https://` proxy and the target of a cross-host redirect, which is
149/// still followed.
150#[cfg_attr(feature = "uniffi", derive(uniffi::Object))]
151pub struct ClientCertificate {
152    key: Arc<DelegatedSigningKey>,
153    resolver: Arc<DelegatedResolver>,
154}
155
156#[cfg_attr(feature = "uniffi", uniffi::export)]
157impl ClientCertificate {
158    /// Creates a client certificate from its DER-encoded chain, leaf first, followed by any
159    /// intermediates, and the signer for the leaf's private key.
160    #[cfg_attr(feature = "uniffi", uniffi::constructor)]
161    pub fn new(chain: Vec<Vec<u8>>, signer: Arc<dyn ClientCertSigner>) -> Self {
162        let mut schemes = signer.schemes();
163        schemes.sort_by_key(|scheme| SCHEME_PREFERENCE.iter().position(|s| s == scheme));
164        schemes.dedup();
165        let chain: Vec<CertificateDer<'static>> =
166            chain.into_iter().map(CertificateDer::from).collect();
167        // An unparseable leaf keeps every scheme, and `validate` reports it.
168        if let Some(key_type) = chain.first().and_then(leaf_key_type) {
169            schemes.retain(|scheme| key_type.accepts(*scheme));
170        }
171
172        if schemes.is_empty() {
173            tracing::error!(
174                "mTLS: the client certificate signer advertised no signature schemes for the \
175                 leaf's key, so the client certificate will never be sent"
176            );
177        }
178
179        let key = Arc::new(DelegatedSigningKey { signer, schemes });
180        let certified_key = CertifiedKey::new(chain, key.clone());
181        Self {
182            key,
183            resolver: Arc::new(DelegatedResolver {
184                certified_key: Arc::new(certified_key),
185            }),
186        }
187    }
188}
189
190impl ClientCertificate {
191    pub(crate) fn resolver(&self) -> Arc<dyn ResolvesClientCert> {
192        self.resolver.clone()
193    }
194
195    /// Checks that the chain parses and that the signer's signature with every scheme it advertises
196    /// for the leaf's key verifies against that key.
197    pub fn validate(&self) -> Result<(), ClientCertificateError> {
198        let certificates = self
199            .resolver
200            .certified_key
201            .cert
202            .iter()
203            .enumerate()
204            .map(|(index, certificate)| {
205                webpki::EndEntityCert::try_from(certificate)
206                    .map_err(|_| ClientCertificateError::InvalidCertificate { index })
207            })
208            .collect::<Result<Vec<_>, _>>()?;
209        let leaf = certificates
210            .first()
211            .ok_or(ClientCertificateError::EmptyChain)?;
212        let key_type = LeafKeyType::from_spki(leaf.subject_public_key_info().as_ref())
213            .ok_or(ClientCertificateError::UnsupportedKey)?;
214        if self.key.schemes.is_empty() {
215            return Err(ClientCertificateError::NoCompatibleScheme);
216        }
217        for &scheme in &self.key.schemes {
218            let signature = self
219                .key
220                .signer
221                .sign(scheme, PROBE_MESSAGE.to_vec())
222                .map_err(|error| ClientCertificateError::SigningFailed {
223                    scheme,
224                    reason: error.to_string(),
225                })?;
226            if key_type.is_verifiable() && !verifies(leaf, scheme, &signature) {
227                return Err(ClientCertificateError::KeyMismatch { scheme });
228            }
229        }
230        Ok(())
231    }
232}
233
234/// Not a TLS handshake message, so a signature over it cannot stand in for one.
235const PROBE_MESSAGE: &[u8] = b"Bitwarden SDK client certificate check";
236
237fn verifies(leaf: &webpki::EndEntityCert<'_>, scheme: TlsSigScheme, signature: &[u8]) -> bool {
238    crate::client::crypto_provider()
239        .signature_verification_algorithms
240        .mapping
241        .iter()
242        .filter(|(mapped, _)| *mapped == scheme.to_rustls())
243        .flat_map(|(_, algorithms)| algorithms.iter())
244        .any(|algorithm| {
245            leaf.verify_signature(*algorithm, PROBE_MESSAGE, signature)
246                .is_ok()
247        })
248}
249
250fn leaf_key_type(leaf: &CertificateDer<'_>) -> Option<LeafKeyType> {
251    let leaf = webpki::EndEntityCert::try_from(leaf).ok()?;
252    LeafKeyType::from_spki(leaf.subject_public_key_info().as_ref())
253}
254
255/// Why [`ClientCertificate::validate`] rejected a certificate.
256#[derive(Debug, PartialEq, Eq, thiserror::Error)]
257pub enum ClientCertificateError {
258    /// The chain contains no certificates.
259    #[error("The certificate chain is empty")]
260    EmptyChain,
261    /// A certificate in the chain is not valid X.509 DER.
262    #[error("Certificate {index} in the chain is not a valid X.509 certificate")]
263    InvalidCertificate {
264        /// Position in the chain, where 0 is the leaf.
265        index: usize,
266    },
267    /// The leaf's key is neither RSA nor ECDSA on P-256 or P-384.
268    #[error("The leaf certificate's key is not RSA or ECDSA on P-256 or P-384")]
269    UnsupportedKey,
270    /// The signer advertises no scheme that matches the leaf's key.
271    #[error("The signer advertises no signature scheme for the leaf certificate's key")]
272    NoCompatibleScheme,
273    /// The signer failed to sign the test message.
274    #[error("The signer failed to sign with {scheme:?}: {reason}")]
275    SigningFailed {
276        /// The scheme the signature was requested with.
277        scheme: TlsSigScheme,
278        /// The signer's error.
279        reason: String,
280    },
281    /// The signer's signature does not verify with the leaf certificate's key.
282    #[error("The {scheme:?} signature does not match the leaf certificate's key")]
283    KeyMismatch {
284        /// The scheme the signature was made with.
285        scheme: TlsSigScheme,
286    },
287}
288
289/// The leaf key types the SDK can sign handshakes for.
290#[derive(Clone, Copy, Debug, PartialEq, Eq)]
291enum LeafKeyType {
292    Rsa { modulus_bits: usize },
293    EcdsaP256,
294    EcdsaP384,
295}
296
297impl LeafKeyType {
298    /// Reads the key type from the DER `AlgorithmIdentifier` at the start of an SPKI. DER encodes
299    /// each identifier as a single byte string, so comparing prefixes is exact.
300    fn from_spki(spki: &[u8]) -> Option<Self> {
301        // rsaEncryption, with or without the NULL parameters.
302        const RSA: &[u8] = &[
303            0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01,
304        ];
305        // id-ecPublicKey followed by the named curve.
306        const EC_P256: &[u8] = &[
307            0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48,
308            0xce, 0x3d, 0x03, 0x01, 0x07,
309        ];
310        const EC_P384: &[u8] = &[
311            0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04,
312            0x00, 0x22,
313        ];
314
315        let (content, _) = der_expect(spki, DER_SEQUENCE)?;
316        let (algorithm, rest) = der_expect(content, DER_SEQUENCE)?;
317        if algorithm.starts_with(RSA) {
318            let (public_key, _) = der_expect(rest, DER_BIT_STRING)?;
319            // The first byte counts the unused bits, which is 0 for every key encoding.
320            let modulus_bits = rsa_modulus_bits(public_key.strip_prefix(&[0])?)?;
321            Some(Self::Rsa { modulus_bits })
322        } else if algorithm == EC_P256 {
323            Some(Self::EcdsaP256)
324        } else if algorithm == EC_P384 {
325            Some(Self::EcdsaP384)
326        } else {
327            None
328        }
329    }
330
331    fn accepts(self, scheme: TlsSigScheme) -> bool {
332        match self {
333            Self::Rsa { modulus_bits } => scheme.fits_rsa_modulus(modulus_bits),
334            Self::EcdsaP256 => scheme == TlsSigScheme::EcdsaP256Sha256,
335            Self::EcdsaP384 => scheme == TlsSigScheme::EcdsaP384Sha384,
336        }
337    }
338
339    /// RSA keys outside 2048 to 8192 bits are only checked for a successful signature, since the
340    /// rustls providers reject them.
341    fn is_verifiable(self) -> bool {
342        match self {
343            Self::Rsa { modulus_bits } => (2048..=8192).contains(&modulus_bits),
344            Self::EcdsaP256 | Self::EcdsaP384 => true,
345        }
346    }
347}
348
349const DER_INTEGER: u8 = 0x02;
350const DER_BIT_STRING: u8 = 0x03;
351const DER_SEQUENCE: u8 = 0x30;
352
353/// Returns the bit length of the modulus of a DER `RSAPublicKey`.
354fn rsa_modulus_bits(public_key: &[u8]) -> Option<usize> {
355    let (key, _) = der_expect(public_key, DER_SEQUENCE)?;
356    let (modulus, _) = der_expect(key, DER_INTEGER)?;
357    let start = modulus.iter().position(|&byte| byte != 0)?;
358    let significant = &modulus[start..];
359    Some(significant.len() * 8 - significant[0].leading_zeros() as usize)
360}
361
362/// Splits the DER element at the start of `der` into its content and the bytes after it, if its
363/// tag is `tag`.
364fn der_expect(der: &[u8], tag: u8) -> Option<(&[u8], &[u8])> {
365    let (&actual, rest) = der.split_first()?;
366    let (&first, rest) = rest.split_first()?;
367    if actual != tag {
368        return None;
369    }
370    let (len, rest) = if first < 0x80 {
371        (usize::from(first), rest)
372    } else {
373        let count = usize::from(first & 0x7f);
374        if count == 0 || count > std::mem::size_of::<usize>() || rest.len() < count {
375            return None;
376        }
377        let (bytes, rest) = rest.split_at(count);
378        let len = bytes
379            .iter()
380            .fold(0usize, |len, &byte| (len << 8) | usize::from(byte));
381        (len, rest)
382    };
383    (len <= rest.len()).then(|| rest.split_at(len))
384}
385
386impl std::fmt::Debug for ClientCertificate {
387    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
388        f.debug_struct("ClientCertificate").finish_non_exhaustive()
389    }
390}
391
392/// Ignores the server's acceptable-issuer hints, since there is only one certificate to offer.
393#[derive(Debug)]
394struct DelegatedResolver {
395    certified_key: Arc<CertifiedKey>,
396}
397
398impl ResolvesClientCert for DelegatedResolver {
399    fn resolve(
400        &self,
401        _root_hint_subjects: &[&[u8]],
402        _sigschemes: &[SignatureScheme],
403    ) -> Option<Arc<CertifiedKey>> {
404        Some(self.certified_key.clone())
405    }
406
407    fn has_certs(&self) -> bool {
408        true
409    }
410}
411
412struct DelegatedSigningKey {
413    signer: Arc<dyn ClientCertSigner>,
414    /// The signer's schemes in the SDK's preference order.
415    schemes: Vec<TlsSigScheme>,
416}
417
418impl std::fmt::Debug for DelegatedSigningKey {
419    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
420        f.debug_struct("DelegatedSigningKey")
421            .field("schemes", &self.schemes)
422            .finish_non_exhaustive()
423    }
424}
425
426impl SigningKey for DelegatedSigningKey {
427    fn choose_scheme(&self, offered: &[SignatureScheme]) -> Option<Box<dyn Signer>> {
428        let chosen = self
429            .schemes
430            .iter()
431            .copied()
432            .find(|scheme| offered.contains(&scheme.to_rustls()));
433        match chosen {
434            Some(scheme) => Some(Box::new(DelegatedSigner {
435                signer: self.signer.clone(),
436                scheme,
437            })),
438            None => {
439                // The handshake continues without a certificate, and the server's rejection would
440                // otherwise be unexplained.
441                tracing::warn!(
442                    ours = ?self.schemes,
443                    server = ?offered,
444                    "mTLS: the server accepts none of the client certificate's signature \
445                     schemes, so no client certificate is sent"
446                );
447                None
448            }
449        }
450    }
451
452    fn algorithm(&self) -> SignatureAlgorithm {
453        self.schemes
454            .first()
455            .map_or(SignatureAlgorithm::Anonymous, |scheme| scheme.algorithm())
456    }
457}
458
459struct DelegatedSigner {
460    signer: Arc<dyn ClientCertSigner>,
461    scheme: TlsSigScheme,
462}
463
464impl std::fmt::Debug for DelegatedSigner {
465    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
466        f.debug_struct("DelegatedSigner")
467            .field("scheme", &self.scheme)
468            .finish_non_exhaustive()
469    }
470}
471
472impl Signer for DelegatedSigner {
473    fn sign(&self, message: &[u8]) -> Result<Vec<u8>, rustls::Error> {
474        self.signer
475            .sign(self.scheme, message.to_vec())
476            .map_err(|error| {
477                tracing::error!(scheme = ?self.scheme, "mTLS: {error}");
478                rustls::Error::General(error.to_string())
479            })
480    }
481
482    fn scheme(&self) -> SignatureScheme {
483        self.scheme.to_rustls()
484    }
485}
486
487#[cfg(test)]
488mod tests {
489    use std::sync::Mutex;
490
491    use super::*;
492
493    #[derive(Default)]
494    struct RecordingSigner {
495        schemes: Vec<TlsSigScheme>,
496        fail: bool,
497        calls: Mutex<Vec<(TlsSigScheme, Vec<u8>)>>,
498    }
499
500    impl ClientCertSigner for RecordingSigner {
501        fn sign(
502            &self,
503            scheme: TlsSigScheme,
504            message: Vec<u8>,
505        ) -> Result<Vec<u8>, ClientCertSignerError> {
506            self.calls
507                .lock()
508                .expect("lock should not be poisoned")
509                .push((scheme, message));
510            if self.fail {
511                Err(ClientCertSignerError::SigningFailed {
512                    reason: "key unavailable".to_owned(),
513                })
514            } else {
515                Ok(b"signature".to_vec())
516            }
517        }
518
519        fn schemes(&self) -> Vec<TlsSigScheme> {
520            self.schemes.clone()
521        }
522    }
523
524    fn signing_key(signer: &Arc<RecordingSigner>) -> Arc<dyn SigningKey> {
525        let certificate = ClientCertificate::new(vec![b"leaf".to_vec()], signer.clone());
526        let certified_key = certificate
527            .resolver()
528            .resolve(&[], &[])
529            .expect("resolver should always offer the certificate");
530        assert_eq!(
531            certified_key.cert,
532            vec![CertificateDer::from(b"leaf".to_vec())]
533        );
534        certified_key.key.clone()
535    }
536
537    const ALL_RSA: [TlsSigScheme; 6] = [
538        TlsSigScheme::RsaPkcs1Sha256,
539        TlsSigScheme::RsaPkcs1Sha384,
540        TlsSigScheme::RsaPkcs1Sha512,
541        TlsSigScheme::RsaPssSha256,
542        TlsSigScheme::RsaPssSha384,
543        TlsSigScheme::RsaPssSha512,
544    ];
545
546    #[test]
547    fn chooses_the_sdk_preferred_scheme_among_those_offered() {
548        let signer = Arc::new(RecordingSigner {
549            schemes: ALL_RSA.to_vec(),
550            ..Default::default()
551        });
552        let key = signing_key(&signer);
553
554        let offered = [
555            SignatureScheme::RSA_PKCS1_SHA256,
556            SignatureScheme::RSA_PSS_SHA256,
557            SignatureScheme::RSA_PSS_SHA384,
558        ];
559        let chosen = key.choose_scheme(&offered).expect("a scheme should match");
560
561        assert_eq!(chosen.scheme(), SignatureScheme::RSA_PSS_SHA384);
562        assert_eq!(key.algorithm(), SignatureAlgorithm::RSA);
563    }
564
565    #[test]
566    fn falls_back_to_pkcs1_when_the_server_offers_no_pss() {
567        let signer = Arc::new(RecordingSigner {
568            schemes: ALL_RSA.to_vec(),
569            ..Default::default()
570        });
571        let key = signing_key(&signer);
572
573        let chosen = key
574            .choose_scheme(&[SignatureScheme::RSA_PKCS1_SHA256, SignatureScheme::ED25519])
575            .expect("a scheme should match");
576
577        assert_eq!(chosen.scheme(), SignatureScheme::RSA_PKCS1_SHA256);
578    }
579
580    #[test]
581    fn returns_none_when_no_scheme_is_shared() {
582        let signer = Arc::new(RecordingSigner {
583            schemes: vec![TlsSigScheme::EcdsaP256Sha256],
584            ..Default::default()
585        });
586        let key = signing_key(&signer);
587
588        assert!(
589            key.choose_scheme(&[SignatureScheme::RSA_PSS_SHA256])
590                .is_none()
591        );
592        assert_eq!(key.algorithm(), SignatureAlgorithm::ECDSA);
593    }
594
595    #[test]
596    fn empty_schemes_never_match() {
597        let signer = Arc::new(RecordingSigner::default());
598        let key = signing_key(&signer);
599
600        assert!(
601            key.choose_scheme(&[SignatureScheme::RSA_PSS_SHA256])
602                .is_none()
603        );
604        assert_eq!(key.algorithm(), SignatureAlgorithm::Anonymous);
605    }
606
607    #[test]
608    fn signer_receives_the_negotiated_scheme_and_the_raw_message() {
609        let signer = Arc::new(RecordingSigner {
610            schemes: vec![TlsSigScheme::EcdsaP256Sha256],
611            ..Default::default()
612        });
613        let key = signing_key(&signer);
614        let chosen = key
615            .choose_scheme(&[SignatureScheme::ECDSA_NISTP256_SHA256])
616            .expect("a scheme should match");
617
618        let signature = chosen.sign(b"handshake").expect("signing should succeed");
619
620        assert_eq!(signature, b"signature");
621        assert_eq!(
622            *signer.calls.lock().expect("lock should not be poisoned"),
623            vec![(TlsSigScheme::EcdsaP256Sha256, b"handshake".to_vec())]
624        );
625    }
626
627    #[test]
628    fn signer_errors_become_rustls_errors() {
629        let signer = Arc::new(RecordingSigner {
630            schemes: vec![TlsSigScheme::EcdsaP256Sha256],
631            fail: true,
632            ..Default::default()
633        });
634        let key = signing_key(&signer);
635        let chosen = key
636            .choose_scheme(&[SignatureScheme::ECDSA_NISTP256_SHA256])
637            .expect("a scheme should match");
638
639        let error = chosen.sign(b"handshake").expect_err("signing should fail");
640
641        assert_eq!(
642            error,
643            rustls::Error::General("Client certificate signing failed: key unavailable".to_owned())
644        );
645    }
646
647    #[test]
648    fn rsa_schemes_fit_the_modulus_rfc_8017_requires() {
649        let fitting = |modulus_bits| {
650            ALL_RSA
651                .into_iter()
652                .filter(|scheme| scheme.fits_rsa_modulus(modulus_bits))
653                .collect::<Vec<_>>()
654        };
655
656        assert_eq!(fitting(2048), ALL_RSA);
657        assert_eq!(fitting(1034), ALL_RSA);
658        // PSS with SHA-512 needs a 130-byte encoded message, and a 1033-bit key encodes 129.
659        assert_eq!(
660            fitting(1033),
661            ALL_RSA
662                .into_iter()
663                .filter(|scheme| *scheme != TlsSigScheme::RsaPssSha512)
664                .collect::<Vec<_>>()
665        );
666        assert_eq!(fitting(512), vec![TlsSigScheme::RsaPkcs1Sha256]);
667        assert!(!TlsSigScheme::EcdsaP256Sha256.fits_rsa_modulus(4096));
668    }
669
670    #[test]
671    fn reads_the_rsa_modulus_length_without_the_sign_byte() {
672        // SEQUENCE { INTEGER 0x00 0x80 0x00 0x01, INTEGER 65537 }: a 24-bit modulus.
673        let key = [
674            0x30, 0x0b, 0x02, 0x04, 0x00, 0x80, 0x00, 0x01, 0x02, 0x03, 0x01, 0x00, 0x01,
675        ];
676        assert_eq!(rsa_modulus_bits(&key), Some(24));
677
678        // SEQUENCE { INTEGER 0x01 0xff, ... }: the top byte has 7 leading zero bits.
679        let key = [
680            0x30, 0x09, 0x02, 0x02, 0x01, 0xff, 0x02, 0x03, 0x01, 0x00, 0x01,
681        ];
682        assert_eq!(rsa_modulus_bits(&key), Some(9));
683
684        assert_eq!(rsa_modulus_bits(&[0x30, 0x03, 0x02, 0x01, 0x00]), None);
685    }
686
687    const P256_CERT: &str = include_str!("../tests/fixtures/client_certificate/p256.crt");
688    const P256_KEY: &str = include_str!("../tests/fixtures/client_certificate/p256.key");
689    const P256_OTHER_KEY: &str =
690        include_str!("../tests/fixtures/client_certificate/p256-other.key");
691    const P384_CERT: &str = include_str!("../tests/fixtures/client_certificate/p384.crt");
692    const P384_KEY: &str = include_str!("../tests/fixtures/client_certificate/p384.key");
693    const RSA_CERT: &str = include_str!("../tests/fixtures/client_certificate/rsa.crt");
694    const RSA_KEY: &str = include_str!("../tests/fixtures/client_certificate/rsa.key");
695    const ED25519_CERT: &str = include_str!("../tests/fixtures/client_certificate/ed25519.crt");
696
697    fn der(pem: &str) -> Vec<u8> {
698        use rustls::pki_types::pem::PemObject;
699
700        CertificateDer::from_pem_slice(pem.as_bytes())
701            .expect("fixture should be a PEM certificate")
702            .to_vec()
703    }
704
705    /// Advertises `schemes` and signs each of them with `key`.
706    struct KeySigner {
707        key: Arc<dyn SigningKey>,
708        schemes: Vec<TlsSigScheme>,
709    }
710
711    impl KeySigner {
712        fn new(key_pem: &str, schemes: &[TlsSigScheme]) -> Arc<Self> {
713            use rustls::pki_types::{PrivateKeyDer, pem::PemObject};
714
715            let key = PrivateKeyDer::from_pem_slice(key_pem.as_bytes())
716                .expect("fixture should be a PEM private key");
717            Arc::new(Self {
718                key: crate::client::crypto_provider()
719                    .key_provider
720                    .load_private_key(key)
721                    .expect("fixture key should load"),
722                schemes: schemes.to_vec(),
723            })
724        }
725    }
726
727    impl ClientCertSigner for KeySigner {
728        fn sign(
729            &self,
730            scheme: TlsSigScheme,
731            message: Vec<u8>,
732        ) -> Result<Vec<u8>, ClientCertSignerError> {
733            let signer = self
734                .key
735                .choose_scheme(&[scheme.to_rustls()])
736                .expect("fixture key should support the scheme");
737            Ok(signer.sign(&message).expect("signing should succeed"))
738        }
739
740        fn schemes(&self) -> Vec<TlsSigScheme> {
741            self.schemes.clone()
742        }
743    }
744
745    fn validate(
746        chain: Vec<Vec<u8>>,
747        signer: Arc<dyn ClientCertSigner>,
748    ) -> Result<(), ClientCertificateError> {
749        ClientCertificate::new(chain, signer).validate()
750    }
751
752    fn unusable_signer(schemes: &[TlsSigScheme]) -> Arc<RecordingSigner> {
753        Arc::new(RecordingSigner {
754            schemes: schemes.to_vec(),
755            fail: true,
756            ..Default::default()
757        })
758    }
759
760    #[test]
761    fn validate_accepts_keys_that_sign_every_advertised_scheme() {
762        validate(
763            vec![der(P256_CERT)],
764            KeySigner::new(P256_KEY, &[TlsSigScheme::EcdsaP256Sha256]),
765        )
766        .unwrap();
767        validate(
768            vec![der(P384_CERT)],
769            KeySigner::new(P384_KEY, &[TlsSigScheme::EcdsaP384Sha384]),
770        )
771        .unwrap();
772        validate(vec![der(RSA_CERT)], KeySigner::new(RSA_KEY, &ALL_RSA)).unwrap();
773        // The intermediate does not need to match the leaf's key type.
774        validate(
775            vec![der(P256_CERT), der(RSA_CERT)],
776            KeySigner::new(P256_KEY, &[TlsSigScheme::EcdsaP256Sha256]),
777        )
778        .unwrap();
779    }
780
781    #[test]
782    fn validate_rejects_a_scheme_the_signer_fails_to_sign() {
783        let error = validate(
784            vec![der(P256_CERT)],
785            unusable_signer(&[TlsSigScheme::EcdsaP256Sha256]),
786        )
787        .unwrap_err();
788
789        assert_eq!(
790            error,
791            ClientCertificateError::SigningFailed {
792                scheme: TlsSigScheme::EcdsaP256Sha256,
793                reason: "Client certificate signing failed: key unavailable".to_owned(),
794            }
795        );
796    }
797
798    #[test]
799    fn validate_rejects_a_signer_whose_key_does_not_match_the_leaf() {
800        let error = validate(
801            vec![der(P256_CERT)],
802            KeySigner::new(P256_OTHER_KEY, &[TlsSigScheme::EcdsaP256Sha256]),
803        )
804        .unwrap_err();
805
806        assert_eq!(
807            error,
808            ClientCertificateError::KeyMismatch {
809                scheme: TlsSigScheme::EcdsaP256Sha256,
810            }
811        );
812    }
813
814    #[test]
815    fn validate_rejects_an_empty_chain() {
816        let error = validate(vec![], unusable_signer(&[TlsSigScheme::EcdsaP256Sha256]));
817
818        assert_eq!(error, Err(ClientCertificateError::EmptyChain));
819    }
820
821    #[test]
822    fn validate_rejects_unparseable_certificates() {
823        let leaf = der(P256_CERT);
824        let mut trailing = leaf.clone();
825        trailing.push(0);
826
827        for (chain, index) in [
828            (vec![b"not a certificate".to_vec()], 0),
829            (vec![leaf[..leaf.len() - 1].to_vec()], 0),
830            (vec![trailing], 0),
831            (vec![leaf, b"not a certificate".to_vec()], 1),
832        ] {
833            let error = validate(chain, unusable_signer(&[TlsSigScheme::EcdsaP256Sha256]));
834
835            assert_eq!(
836                error,
837                Err(ClientCertificateError::InvalidCertificate { index })
838            );
839        }
840    }
841
842    #[test]
843    fn validate_rejects_schemes_for_another_key_type() {
844        for (certificate, schemes) in [
845            (P256_CERT, vec![TlsSigScheme::EcdsaP384Sha384]),
846            (P256_CERT, vec![TlsSigScheme::RsaPssSha256]),
847            (P256_CERT, vec![]),
848            (RSA_CERT, vec![TlsSigScheme::EcdsaP256Sha256]),
849        ] {
850            let error = validate(vec![der(certificate)], unusable_signer(&schemes));
851
852            assert_eq!(
853                error,
854                Err(ClientCertificateError::NoCompatibleScheme),
855                "{schemes:?}"
856            );
857        }
858    }
859
860    #[test]
861    fn validate_rejects_an_unsupported_key_type() {
862        let error = validate(
863            vec![der(ED25519_CERT)],
864            unusable_signer(&[TlsSigScheme::EcdsaP256Sha256]),
865        );
866
867        assert_eq!(error, Err(ClientCertificateError::UnsupportedKey));
868    }
869}