Skip to main content

coqui_peer_tls/
identity.rs

1use core::fmt;
2#[cfg(feature = "generate")]
3use core::time::Duration;
4use std::fs;
5use std::io;
6use std::path::Path;
7#[cfg(feature = "generate")]
8use std::time::{SystemTime, UNIX_EPOCH};
9
10use rustls::ServerConfig;
11use rustls::pki_types::pem::PemObject;
12use rustls::pki_types::{CertificateDer, PrivateKeyDer};
13
14use crate::error::PeerError;
15use alloc::sync::Arc;
16use coqui_peer::PeerId;
17use coqui_peer::file::{self, Access};
18use coqui_peer::pem;
19
20/// A verified peer: the certificate the other side proved it holds the key of.
21///
22/// Returned by [`dial`](crate::dial) and [`accept`](crate::accept) after the handshake.
23#[derive(Clone, PartialEq, Eq)]
24pub struct PeerIdentity {
25    /// The certificate's fingerprint.
26    pub fingerprint: PeerId,
27    /// The certificate, DER encoded; with a raw public key (see
28    /// [`CertificateType`](crate::CertificateType)), the `SubjectPublicKeyInfo`, DER encoded.
29    pub certificate: Vec<u8>,
30}
31
32impl PeerIdentity {
33    /// Whether this peer authenticated with a raw public key (RFC 7250), so
34    /// [`certificate`](Self::certificate) holds its `SubjectPublicKeyInfo`, and its
35    /// [`fingerprint`](Self::fingerprint) is the id of that.
36    pub fn is_raw_public_key(&self) -> bool {
37        crate::x509::is_public_key_info(&self.certificate)
38    }
39}
40
41impl fmt::Debug for PeerIdentity {
42    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
43        formatter
44            .debug_tuple("PeerIdentity")
45            .field(&self.fingerprint)
46            .finish()
47    }
48}
49
50/// This side's certificate and its private key, with the intermediates that issued the
51/// certificate when it has any.
52///
53/// A peer identity is one self-issued certificate ([`from_pem`](Identity::from_pem)). A server
54/// a browser reaches under web PKI presents a CA-issued certificate with its intermediates
55/// ([`from_pem_chain`](Identity::from_pem_chain)). The fingerprint is always the leaf
56/// certificate's.
57///
58/// On disk it is one PEM file: the certificate block, then a PKCS#8 `PRIVATE KEY` block.
59pub struct Identity {
60    fingerprint: PeerId,
61    certificate: CertificateDer<'static>,
62    public_key: Vec<u8>,
63    intermediates: Vec<CertificateDer<'static>>,
64    key: PrivateKeyDer<'static>,
65}
66
67impl fmt::Debug for Identity {
68    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
69        formatter
70            .debug_tuple("Identity")
71            .field(&self.fingerprint)
72            .finish()
73    }
74}
75
76impl Clone for Identity {
77    fn clone(&self) -> Self {
78        Self {
79            fingerprint: self.fingerprint,
80            certificate: self.certificate.clone(),
81            public_key: self.public_key.clone(),
82            intermediates: self.intermediates.clone(),
83            key: self.key.clone_key(),
84        }
85    }
86}
87
88impl Identity {
89    /// Reads one certificate and its matching private key from PEM text.
90    ///
91    /// # Errors
92    ///
93    /// [`PeerError::Certificate`] when either is missing, malformed or not a pair, or when more
94    /// than one certificate is present.
95    pub fn from_pem(text: &str) -> Result<Self, PeerError> {
96        // A chain is refused: an identity is one self-issued certificate.
97        if CertificateDer::pem_slice_iter(text.as_bytes()).count() != 1 {
98            return Err(PeerError::Certificate);
99        }
100        Self::from_pem_chain(text)
101    }
102
103    /// Reads a certificate, the intermediates that issued it and the leaf's private key from
104    /// PEM text: the leaf certificate first, then each issuer in order up to (not necessarily
105    /// including) the root, and one private key in any block position.
106    ///
107    /// A configuration built from it presents the whole chain. The fingerprint is the leaf's.
108    /// A peer that pins this identity refuses the chain unless its policy sets
109    /// [`allow_chain_when_pinned`](crate::Policy::allow_chain_when_pinned). One certificate
110    /// alone gives the same identity as [`from_pem`](Identity::from_pem).
111    ///
112    /// # Errors
113    ///
114    /// [`PeerError::Certificate`] when there is no certificate or no key, either is malformed,
115    /// or the key is not the first certificate's.
116    pub fn from_pem_chain(text: &str) -> Result<Self, PeerError> {
117        let mut certificates = CertificateDer::pem_slice_iter(text.as_bytes())
118            .collect::<Result<Vec<_>, _>>()
119            .map_err(|_| PeerError::Certificate)?;
120        if certificates.is_empty() {
121            return Err(PeerError::Certificate);
122        }
123        let key =
124            PrivateKeyDer::from_pem_slice(text.as_bytes()).map_err(|_| PeerError::Certificate)?;
125        // rustls refuses a key whose public key is not the first certificate's. A key ring
126        // cannot load (ML-DSA) is checked by aws-lc-rs when this build has it.
127        let matches = |provider: rustls::crypto::CryptoProvider| {
128            ServerConfig::builder_with_provider(Arc::new(provider))
129                .with_protocol_versions(&[&rustls::version::TLS13])
130                .is_ok_and(|builder| {
131                    builder
132                        .with_no_client_auth()
133                        .with_single_cert(certificates.clone(), key.clone_key())
134                        .is_ok()
135                })
136        };
137        let loaded = matches(rustls::crypto::ring::default_provider());
138        #[cfg(feature = "aws-lc")]
139        let loaded = loaded || matches(rustls::crypto::aws_lc_rs::default_provider());
140        if !loaded {
141            return Err(PeerError::Certificate);
142        }
143        let certificate = certificates.remove(0);
144        let public_key = crate::x509::subject_public_key_info(certificate.as_ref())
145            .map_err(|_| PeerError::Certificate)?
146            .to_vec();
147        Ok(Self {
148            fingerprint: PeerId::of(certificate.as_ref()),
149            certificate,
150            public_key,
151            intermediates: certificates,
152            key,
153        })
154    }
155
156    /// The identity as PEM text: the certificate, its intermediates in order, then the PKCS#8
157    /// private key. Text with intermediates reads back with
158    /// [`from_pem_chain`](Identity::from_pem_chain) only.
159    ///
160    /// # Errors
161    ///
162    /// [`PeerError::Certificate`] when the key is not PKCS#8.
163    pub fn to_pem(&self) -> Result<String, PeerError> {
164        let PrivateKeyDer::Pkcs8(key) = &self.key else {
165            return Err(PeerError::Certificate);
166        };
167        let mut pem = pem::encode("CERTIFICATE", self.certificate.as_ref());
168        for intermediate in &self.intermediates {
169            pem.push_str(&pem::encode("CERTIFICATE", intermediate.as_ref()));
170        }
171        pem.push_str(&pem::encode("PRIVATE KEY", key.secret_pkcs8_der()));
172        Ok(pem)
173    }
174
175    /// Reads the identity file at `path`; `None` when it is absent. The file holds the
176    /// certificate, the intermediates that issued it, if any, and its key, as
177    /// [`from_pem_chain`](Identity::from_pem_chain) reads them: what
178    /// [`write_new`](Identity::write_new) writes for any identity.
179    ///
180    /// # Errors
181    ///
182    /// [`PeerError::Io`] when it cannot be read, [`PeerError::Certificate`] when invalid.
183    pub fn read(path: &Path) -> Result<Option<Self>, PeerError> {
184        match fs::read_to_string(path) {
185            Ok(text) => Self::from_pem_chain(&text).map(Some),
186            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
187            Err(error) => Err(PeerError::Io(error)),
188        }
189    }
190
191    /// Writes the identity file without replacing an existing one, readable by its owner
192    /// alone (`0600` on Unix). Parent directories are created.
193    ///
194    /// # Errors
195    ///
196    /// [`PeerError::Io`] with kind `AlreadyExists` when `path` exists.
197    pub fn write_new(&self, path: &Path) -> Result<(), PeerError> {
198        path.parent().ok_or(PeerError::Path)?;
199        let pem = self.to_pem()?;
200        file::write_new(path, pem.as_bytes(), Access::OwnerOnly).map_err(PeerError::Io)
201    }
202
203    /// The certificate's fingerprint: what a peer pins.
204    pub fn fingerprint(&self) -> PeerId {
205        self.fingerprint
206    }
207
208    /// The certificate, DER encoded.
209    pub fn certificate_der(&self) -> &[u8] {
210        self.certificate.as_ref()
211    }
212
213    /// The certificate's `SubjectPublicKeyInfo`, DER encoded: what this side sends when the
214    /// policy's [`certificate`](crate::Policy::certificate) is
215    /// [`RawPublicKey`](crate::CertificateType::RawPublicKey).
216    pub fn public_key_der(&self) -> &[u8] {
217        &self.public_key
218    }
219
220    /// The id of the [`public_key_der`](Self::public_key_der) (SHA-256): what a peer pins when
221    /// it authenticates this side by its raw public key.
222    pub fn public_key_fingerprint(&self) -> PeerId {
223        PeerId::of(&self.public_key)
224    }
225
226    /// This identity as a remote peer sees it after a raw-public-key handshake.
227    pub fn raw_peer_identity(&self) -> PeerIdentity {
228        PeerIdentity {
229            fingerprint: self.public_key_fingerprint(),
230            certificate: self.public_key.clone(),
231        }
232    }
233
234    /// The key as a raw-public-key resolver presents it: the `SubjectPublicKeyInfo` in place of
235    /// a certificate, with the private key loaded by `provider`.
236    ///
237    /// # Errors
238    ///
239    /// [`PeerError::Certificate`] when `provider` cannot load the key, or loads one whose public
240    /// key is not the certificate's.
241    pub(crate) fn raw_public_key(
242        &self,
243        provider: &rustls::crypto::CryptoProvider,
244    ) -> Result<Arc<rustls::sign::CertifiedKey>, PeerError> {
245        let key = provider
246            .key_provider
247            .load_private_key(self.key.clone_key())
248            .map_err(|_| PeerError::Certificate)?;
249        if key
250            .public_key()
251            .is_some_and(|public| public.as_ref() != self.public_key.as_slice())
252        {
253            return Err(PeerError::Certificate);
254        }
255        Ok(Arc::new(rustls::sign::CertifiedKey::new(
256            vec![CertificateDer::from(self.public_key.clone())],
257            key,
258        )))
259    }
260
261    /// The intermediates presented after the certificate, DER encoded, in order; none for an
262    /// identity read by [`from_pem`](Identity::from_pem) or generated.
263    pub fn intermediates_der(&self) -> impl ExactSizeIterator<Item = &[u8]> {
264        self.intermediates.iter().map(AsRef::as_ref)
265    }
266
267    /// This identity as the value a remote peer sees after a handshake.
268    pub fn peer_identity(&self) -> PeerIdentity {
269        PeerIdentity {
270            fingerprint: self.fingerprint,
271            certificate: self.certificate.as_ref().to_vec(),
272        }
273    }
274
275    /// The certificate followed by its intermediates, as a configuration presents them: for a
276    /// host that builds a rustls or quinn configuration of its own.
277    pub fn certificate_chain(&self) -> Vec<CertificateDer<'static>> {
278        let mut chain = Vec::with_capacity(1 + self.intermediates.len());
279        chain.push(self.certificate.clone());
280        chain.extend(self.intermediates.iter().cloned());
281        chain
282    }
283
284    /// A copy of the private key, DER encoded, for a host that builds a rustls or quinn
285    /// configuration of its own. It is the secret of this identity: keep it in memory only.
286    /// Its `Debug` shows no key material.
287    pub fn private_key_der(&self) -> PrivateKeyDer<'static> {
288        self.key.clone_key()
289    }
290}
291
292/// Generates a self-signed ECDSA P-256 identity without writing it: [`Identity::builder`], the
293/// validity, then [`generate`](Self::generate).
294///
295/// With nothing set the certificate is valid for rcgen's default period (decades), as
296/// [`Identity::generate`] makes it. Every generated certificate has the common name
297/// `coqui-peer`, a DNS subjectAltName [`SERVER_NAME`](crate::SERVER_NAME), a
298/// subjectKeyIdentifier and basicConstraints `CA:FALSE`. Peers pin it by fingerprint, so the
299/// name is not checked. Times are whole seconds: both are truncated.
300///
301/// The end of the validity is one setting: [`not_after`](Self::not_after) and
302/// [`valid_for`](Self::valid_for) each set it, and the last one called wins.
303///
304/// For WebTransport's `serverCertificateHashes`, which accepts only a certificate whose whole
305/// validity period is at most 14 days, use `valid_for(Duration::from_secs(14 * 86_400))` at most
306/// and replace the identity before it expires; a peer whose clock runs behind sees it as not yet
307/// valid, so an earlier `not_before`, within the same 14 days, covers that.
308///
309/// The key algorithm is [`key_algorithm`](Self::key_algorithm); the default is ECDSA P-256.
310#[cfg(feature = "generate")]
311#[derive(Debug, Clone, Default)]
312#[must_use]
313pub struct IdentityBuilder {
314    not_before: Option<SystemTime>,
315    end: Option<End>,
316    algorithm: KeyAlgorithm,
317}
318
319/// The key algorithm of a generated identity, chosen with
320/// [`IdentityBuilder::key_algorithm`].
321///
322/// P-256 is the default: it is what [`Identity::generate`] and
323/// [`Identity::open_or_create`] make. The CNSA profiles need more: `cnsa-1.0` P-384,
324/// `cnsa-2.0` ML-DSA-87.
325#[cfg(feature = "generate")]
326#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
327#[non_exhaustive]
328pub enum KeyAlgorithm {
329    /// ECDSA over P-256 with SHA-256.
330    #[default]
331    P256,
332    /// ECDSA over P-384 with SHA-384.
333    P384,
334    /// ML-DSA-87 (FIPS 204). Only with the `aws-lc` feature; a peer uses it with
335    /// [`Crypto::AwsLc`](crate::Crypto::AwsLc), as ring has no ML-DSA.
336    #[cfg(feature = "aws-lc")]
337    MlDsa87,
338}
339
340#[cfg(feature = "generate")]
341impl KeyAlgorithm {
342    fn signature(self) -> &'static rcgen::SignatureAlgorithm {
343        match self {
344            Self::P256 => &rcgen::PKCS_ECDSA_P256_SHA256,
345            Self::P384 => &rcgen::PKCS_ECDSA_P384_SHA384,
346            #[cfg(feature = "aws-lc")]
347            Self::MlDsa87 => &rcgen::PKCS_ML_DSA_87,
348        }
349    }
350}
351
352/// Where the validity ends.
353#[cfg(feature = "generate")]
354#[derive(Debug, Clone, Copy)]
355enum End {
356    At(SystemTime),
357    After(Duration),
358}
359
360#[cfg(feature = "generate")]
361impl IdentityBuilder {
362    /// The first instant the certificate is valid. Default rcgen's.
363    pub fn not_before(mut self, at: SystemTime) -> Self {
364        self.not_before = Some(at);
365        self
366    }
367
368    /// The last instant the certificate is valid. Replaces [`valid_for`](Self::valid_for).
369    pub fn not_after(mut self, at: SystemTime) -> Self {
370        self.end = Some(End::At(at));
371        self
372    }
373
374    /// How long the certificate is valid from `not_before`, from now when that is not set.
375    /// Replaces [`not_after`](Self::not_after).
376    pub fn valid_for(mut self, validity: Duration) -> Self {
377        self.end = Some(End::After(validity));
378        self
379    }
380
381    /// The key algorithm. Default [`KeyAlgorithm::P256`].
382    pub fn key_algorithm(mut self, algorithm: KeyAlgorithm) -> Self {
383        self.algorithm = algorithm;
384        self
385    }
386
387    /// Generates the identity.
388    ///
389    /// # Errors
390    ///
391    /// [`PeerError::Certificate`] when `valid_for` is under one second, when `not_after` is not
392    /// at least one second after `not_before`, when either is before 1970 or out of range, or
393    /// when key generation fails.
394    pub fn generate(self) -> Result<Identity, PeerError> {
395        let seconds = |at: SystemTime| -> Result<time::OffsetDateTime, PeerError> {
396            let since = at
397                .duration_since(UNIX_EPOCH)
398                .map_err(|_| PeerError::Certificate)?;
399            let since = i64::try_from(since.as_secs()).map_err(|_| PeerError::Certificate)?;
400            time::OffsetDateTime::from_unix_timestamp(since).map_err(|_| PeerError::Certificate)
401        };
402        let (not_before, not_after) = match self.end {
403            Some(End::After(validity)) => {
404                if validity < Duration::from_secs(1) {
405                    return Err(PeerError::Certificate);
406                }
407                let start = self.not_before.unwrap_or_else(SystemTime::now);
408                let end = start.checked_add(validity).ok_or(PeerError::Certificate)?;
409                (Some(start), Some(end))
410            }
411            Some(End::At(end)) => (self.not_before, Some(end)),
412            None => (self.not_before, None),
413        };
414        let mut parameters = Identity::parameters()?;
415        if let Some(at) = not_before {
416            parameters.not_before = seconds(at)?;
417        }
418        if let Some(at) = not_after {
419            parameters.not_after = seconds(at)?;
420        }
421        if not_before.is_some()
422            && not_after.is_some()
423            && parameters.not_after <= parameters.not_before
424        {
425            return Err(PeerError::Certificate);
426        }
427        Identity::generate_from(parameters, self.algorithm)
428    }
429}
430
431#[cfg(feature = "generate")]
432impl Identity {
433    /// Creates a self-signed ECDSA P-256 identity without writing it, valid for rcgen's
434    /// default period (decades).
435    ///
436    /// Every generated certificate has the common name `coqui-peer`, a DNS subjectAltName
437    /// [`SERVER_NAME`](crate::SERVER_NAME), a subjectKeyIdentifier and basicConstraints
438    /// `CA:FALSE`. Peers pin it by fingerprint, so the name is not checked.
439    ///
440    /// # Errors
441    ///
442    /// [`PeerError::Certificate`] when key generation fails.
443    pub fn generate() -> Result<Self, PeerError> {
444        Self::generate_from(Self::parameters()?, KeyAlgorithm::default())
445    }
446
447    /// A builder for a self-signed identity with a validity window of your own; see
448    /// [`IdentityBuilder`]. [`generate`](Identity::generate) is the same with the defaults.
449    pub fn builder() -> IdentityBuilder {
450        IdentityBuilder::default()
451    }
452
453    /// rcgen writes the subjectKeyIdentifier only beside basicConstraints, hence
454    /// `ExplicitNoCa`. Chrome's `serverCertificateHashes` verifier refuses a certificate
455    /// with no extensions.
456    fn parameters() -> Result<rcgen::CertificateParams, PeerError> {
457        let mut parameters = rcgen::CertificateParams::new(vec![crate::SERVER_NAME.to_owned()])
458            .map_err(|_| PeerError::Certificate)?;
459        parameters
460            .distinguished_name
461            .push(rcgen::DnType::CommonName, "coqui-peer");
462        parameters.is_ca = rcgen::IsCa::ExplicitNoCa;
463        Ok(parameters)
464    }
465
466    fn generate_from(
467        parameters: rcgen::CertificateParams,
468        algorithm: KeyAlgorithm,
469    ) -> Result<Self, PeerError> {
470        let key = rcgen::KeyPair::generate_for(algorithm.signature())
471            .map_err(|_| PeerError::Certificate)?;
472        let certificate = parameters
473            .self_signed(&key)
474            .map_err(|_| PeerError::Certificate)?;
475        Self::from_pem(&format!("{}{}", certificate.pem(), key.serialize_pem()))
476    }
477
478    /// Reads the identity file at `path`, creating and writing a new identity when absent.
479    /// Two processes racing to create it end with the same identity.
480    ///
481    /// # Errors
482    ///
483    /// As [`read`](Identity::read) and [`write_new`](Identity::write_new).
484    pub fn open_or_create(path: &Path) -> Result<Self, PeerError> {
485        if let Some(identity) = Self::read(path)? {
486            return Ok(identity);
487        }
488        let identity = Self::generate()?;
489        match identity.write_new(path) {
490            Ok(()) => Ok(identity),
491            Err(PeerError::Io(error)) if error.kind() == io::ErrorKind::AlreadyExists => {
492                Self::read(path)?.ok_or(PeerError::Certificate)
493            }
494            Err(error) => Err(error),
495        }
496    }
497}
498
499/// Encodes DER as a PEM block with 64-character lines and LF line endings.
500#[cfg(all(test, feature = "generate"))]
501mod tests {
502    use super::*;
503
504    const DAY: u64 = 86_400;
505
506    fn window(identity: &Identity) -> (i64, i64) {
507        crate::x509::validity(identity.certificate_der()).unwrap()
508    }
509
510    #[test]
511    fn a_short_lived_identity_has_the_requested_window() {
512        let before = SystemTime::now()
513            .duration_since(UNIX_EPOCH)
514            .unwrap()
515            .as_secs();
516        let identity = Identity::builder()
517            .valid_for(Duration::from_secs(14 * DAY))
518            .generate()
519            .unwrap();
520        let after = SystemTime::now()
521            .duration_since(UNIX_EPOCH)
522            .unwrap()
523            .as_secs();
524        let (not_before, not_after) = window(&identity);
525        let not_before = u64::try_from(not_before).unwrap();
526        assert!((before..=after).contains(&not_before));
527        assert_eq!(u64::try_from(not_after).unwrap() - not_before, 14 * DAY);
528        assert_eq!(identity.intermediates_der().len(), 0);
529    }
530
531    #[test]
532    fn an_explicit_window_is_kept_to_the_second() {
533        let start = UNIX_EPOCH + Duration::from_secs(1_800_000_000) + Duration::from_millis(700);
534        let end = start + Duration::from_secs(3 * DAY);
535        let identity = Identity::builder()
536            .not_before(start)
537            .not_after(end)
538            .generate()
539            .unwrap();
540        assert_eq!(
541            window(&identity),
542            (1_800_000_000, 1_800_000_000 + 3 * 86_400)
543        );
544    }
545
546    /// Chrome's `serverCertificateHashes` verifier refuses a certificate with no extensions.
547    #[test]
548    fn generated_identities_carry_a_server_name_and_a_key_identifier() {
549        use x509_parser::extensions::{GeneralName, ParsedExtension};
550
551        let start = SystemTime::now();
552        for identity in [
553            Identity::generate().unwrap(),
554            Identity::builder()
555                .valid_for(Duration::from_secs(14 * DAY))
556                .generate()
557                .unwrap(),
558            Identity::builder()
559                .not_before(start)
560                .not_after(start + Duration::from_secs(DAY))
561                .generate()
562                .unwrap(),
563        ] {
564            let (_, certificate) =
565                x509_parser::parse_x509_certificate(identity.certificate_der()).unwrap();
566            let names: Vec<_> = certificate
567                .subject_alternative_name()
568                .unwrap()
569                .expect("a subjectAltName")
570                .value
571                .general_names
572                .clone();
573            assert_eq!(names, vec![GeneralName::DNSName(crate::SERVER_NAME)]);
574            let key_identifier = certificate
575                .extensions()
576                .iter()
577                .find_map(|extension| match extension.parsed_extension() {
578                    ParsedExtension::SubjectKeyIdentifier(id) => Some(id.0.to_vec()),
579                    _ => None,
580                })
581                .expect("a subjectKeyIdentifier");
582            assert!(!key_identifier.is_empty());
583            let constraints = certificate.basic_constraints().unwrap().unwrap();
584            assert!(!constraints.value.ca);
585            // The fingerprint names the certificate as made, extensions included.
586            assert_eq!(
587                identity.fingerprint(),
588                PeerId::of(identity.certificate_der())
589            );
590        }
591    }
592
593    #[test]
594    fn an_empty_or_inverted_window_is_refused() {
595        assert!(matches!(
596            Identity::builder().valid_for(Duration::ZERO).generate(),
597            Err(PeerError::Certificate)
598        ));
599        assert!(matches!(
600            Identity::builder()
601                .valid_for(Duration::from_millis(999))
602                .generate(),
603            Err(PeerError::Certificate)
604        ));
605        let now = SystemTime::now();
606        assert!(matches!(
607            Identity::builder()
608                .not_before(now)
609                .not_after(now - Duration::from_secs(60))
610                .generate(),
611            Err(PeerError::Certificate)
612        ));
613    }
614}