rustls/crypto/signer.rs
1use alloc::boxed::Box;
2use alloc::sync::Arc;
3use alloc::vec::Vec;
4use core::fmt::Debug;
5
6use pki_types::{AlgorithmIdentifier, CertificateDer, SubjectPublicKeyInfoDer};
7
8use crate::enums::{SignatureAlgorithm, SignatureScheme};
9use crate::error::{Error, InconsistentKeys};
10use crate::server::ParsedCertificate;
11use crate::x509;
12
13/// An abstract signing key.
14///
15/// This interface is used by rustls to use a private signing key
16/// for authentication. This includes server and client authentication.
17///
18/// Objects of this type are always used within Rustls as
19/// `Arc<dyn SigningKey>`. There are no concrete public structs in Rustls
20/// that implement this trait.
21///
22/// There are two main ways to get a signing key:
23///
24/// - [`KeyProvider::load_private_key()`], or
25/// - some other method outside of the `KeyProvider` extension trait,
26/// for instance:
27/// - [`crypto::ring::sign::any_ecdsa_type()`]
28/// - [`crypto::ring::sign::any_eddsa_type()`]
29/// - [`crypto::ring::sign::any_supported_type()`]
30/// - [`crypto::aws_lc_rs::sign::any_ecdsa_type()`]
31/// - [`crypto::aws_lc_rs::sign::any_eddsa_type()`]
32/// - [`crypto::aws_lc_rs::sign::any_supported_type()`]
33///
34/// The `KeyProvider` method `load_private_key()` is called under the hood by
35/// [`ConfigBuilder::with_single_cert()`],
36/// [`ConfigBuilder::with_client_auth_cert()`], and
37/// [`ConfigBuilder::with_single_cert_with_ocsp()`].
38///
39/// A signing key created outside of the `KeyProvider` extension trait can be used
40/// to create a [`CertifiedKey`], which in turn can be used to create a
41/// [`ResolvesServerCertUsingSni`]. Alternately, a `CertifiedKey` can be returned from a
42/// custom implementation of the [`ResolvesServerCert`] or [`ResolvesClientCert`] traits.
43///
44/// [`KeyProvider::load_private_key()`]: crate::crypto::KeyProvider::load_private_key
45/// [`ConfigBuilder::with_single_cert()`]: crate::ConfigBuilder::with_single_cert
46/// [`ConfigBuilder::with_single_cert_with_ocsp()`]: crate::ConfigBuilder::with_single_cert_with_ocsp
47/// [`ConfigBuilder::with_client_auth_cert()`]: crate::ConfigBuilder::with_client_auth_cert
48/// [`crypto::ring::sign::any_ecdsa_type()`]: crate::crypto::ring::sign::any_ecdsa_type
49/// [`crypto::ring::sign::any_eddsa_type()`]: crate::crypto::ring::sign::any_eddsa_type
50/// [`crypto::ring::sign::any_supported_type()`]: crate::crypto::ring::sign::any_supported_type
51/// [`crypto::aws_lc_rs::sign::any_ecdsa_type()`]: crate::crypto::aws_lc_rs::sign::any_ecdsa_type
52/// [`crypto::aws_lc_rs::sign::any_eddsa_type()`]: crate::crypto::aws_lc_rs::sign::any_eddsa_type
53/// [`crypto::aws_lc_rs::sign::any_supported_type()`]: crate::crypto::aws_lc_rs::sign::any_supported_type
54/// [`ResolvesServerCertUsingSni`]: crate::server::ResolvesServerCertUsingSni
55/// [`ResolvesServerCert`]: crate::server::ResolvesServerCert
56/// [`ResolvesClientCert`]: crate::client::ResolvesClientCert
57pub trait SigningKey: Debug + Send + Sync {
58 /// Choose a `SignatureScheme` from those offered.
59 ///
60 /// Expresses the choice by returning something that implements `Signer`,
61 /// using the chosen scheme.
62 fn choose_scheme(&self, offered: &[SignatureScheme]) -> Option<Box<dyn Signer>>;
63
64 /// Get the RFC 5280-compliant SubjectPublicKeyInfo (SPKI) of this [`SigningKey`] if available.
65 fn public_key(&self) -> Option<SubjectPublicKeyInfoDer<'_>> {
66 // Opt-out by default
67 None
68 }
69
70 /// What kind of key we have.
71 fn algorithm(&self) -> SignatureAlgorithm;
72}
73
74/// A thing that can sign a message.
75pub trait Signer: Debug + Send + Sync {
76 /// Signs `message` using the selected scheme.
77 ///
78 /// `message` is not hashed; the implementer must hash it using the hash function
79 /// implicit in [`Self::scheme()`].
80 ///
81 /// The returned signature format is also defined by [`Self::scheme()`].
82 fn sign(&self, message: &[u8]) -> Result<Vec<u8>, Error>;
83
84 /// Reveals which scheme will be used when you call [`Self::sign()`].
85 fn scheme(&self) -> SignatureScheme;
86}
87
88/// A packaged-together certificate chain, matching `SigningKey` and
89/// optional stapled OCSP response.
90#[derive(Clone, Debug)]
91pub struct CertifiedKey {
92 /// The certificate chain.
93 pub cert: Vec<CertificateDer<'static>>,
94
95 /// The certified key.
96 pub key: Arc<dyn SigningKey>,
97
98 /// An optional OCSP response from the certificate issuer,
99 /// attesting to its continued validity.
100 pub ocsp: Option<Vec<u8>>,
101}
102
103impl CertifiedKey {
104 /// Make a new CertifiedKey, with the given chain and key.
105 ///
106 /// The cert chain must not be empty. The first certificate in the chain
107 /// must be the end-entity certificate.
108 pub fn new(cert: Vec<CertificateDer<'static>>, key: Arc<dyn SigningKey>) -> Self {
109 Self {
110 cert,
111 key,
112 ocsp: None,
113 }
114 }
115
116 /// Verify the consistency of this [`CertifiedKey`]'s public and private keys.
117 /// This is done by performing a comparison of SubjectPublicKeyInfo bytes.
118 pub fn keys_match(&self) -> Result<(), Error> {
119 let key_spki = match self.key.public_key() {
120 Some(key) => key,
121 None => return Err(InconsistentKeys::Unknown.into()),
122 };
123
124 let cert = ParsedCertificate::try_from(self.end_entity_cert()?)?;
125 match key_spki == cert.subject_public_key_info() {
126 true => Ok(()),
127 false => Err(InconsistentKeys::KeyMismatch.into()),
128 }
129 }
130
131 /// The end-entity certificate.
132 pub fn end_entity_cert(&self) -> Result<&CertificateDer<'_>, Error> {
133 self.cert
134 .first()
135 .ok_or(Error::NoCertificatesPresented)
136 }
137}
138
139#[cfg_attr(not(any(feature = "aws_lc_rs", feature = "ring")), allow(dead_code))]
140pub(crate) fn public_key_to_spki(
141 alg_id: &AlgorithmIdentifier,
142 public_key: impl AsRef<[u8]>,
143) -> SubjectPublicKeyInfoDer<'static> {
144 // SubjectPublicKeyInfo ::= SEQUENCE {
145 // algorithm AlgorithmIdentifier,
146 // subjectPublicKey BIT STRING }
147 //
148 // AlgorithmIdentifier ::= SEQUENCE {
149 // algorithm OBJECT IDENTIFIER,
150 // parameters ANY DEFINED BY algorithm OPTIONAL }
151 //
152 // note that the `pki_types::AlgorithmIdentifier` type is the
153 // concatenation of `algorithm` and `parameters`, but misses the
154 // outer `Sequence`.
155
156 let mut spki_inner = x509::wrap_in_sequence(alg_id.as_ref());
157 spki_inner.extend(&x509::wrap_in_bit_string(public_key.as_ref()));
158
159 let spki = x509::wrap_in_sequence(&spki_inner);
160
161 SubjectPublicKeyInfoDer::from(spki)
162}