rtci-dtls 0.3.0

Sans-I/O DTLS 1.2 and 1.3 (RFC 6347, RFC 9147) with DTLS-SRTP key export, for WebRTC
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//! Cryptographic primitives for DTLS.
//!
//! The record ciphers ([`crypto_gcm`], [`crypto_ccm`], [`crypto_chacha20`], [`crypto_cbc`]), plus
//! the certificate and signature handling the handshake needs. Which cipher is used is decided by
//! the negotiated cipher suite, so a caller normally reaches these only through
//! [`CipherSuite`](crate::cipher_suite::CipherSuite).
//!
//! Certificates here are usually self-signed: WebRTC authenticates a peer by comparing the
//! certificate fingerprint against the one signalled in SDP, not by validating a CA chain.
#[cfg(test)]
mod crypto_record_test;
#[cfg(test)]
mod crypto_test;

/// AES-CBC with a separate HMAC, for the older CBC suites.
pub mod crypto_cbc;
/// AES-CCM authenticated encryption.
pub mod crypto_ccm;
/// ChaCha20-Poly1305 authenticated encryption.
pub mod crypto_chacha20;
/// AES-GCM authenticated encryption.
pub mod crypto_gcm;
pub(crate) mod padding;

use crate::content::ContentType;
use std::convert::TryFrom;
use std::sync::Arc;

use der_parser::oid;
use der_parser::oid::Oid;

use rustls::client::danger::ServerCertVerifier;
use rustls::pki_types::{CertificateDer, ServerName};
use rustls::server::danger::ClientCertVerifier;

use crypto::{
    PublicKey, PublicKeyEncoding, RTCCrypto, SignatureScheme as CryptoSignatureScheme, SigningKey,
};
#[cfg(any(feature = "crypto-ring", feature = "crypto-aws-lc-rs"))]
use rcgen::{CertifiedKey, KeyPair, generate_simple_self_signed};

use crate::curve::named_curve::*;
use crate::record_layer::record_layer_header::*;
use crate::signature_hash_algorithm::{SignatureAlgorithm, SignatureHashAlgorithm};
use shared::error::*;

pub(crate) fn crypto_error(error: crypto::CryptoError) -> Error {
    Error::Crypto(error.to_string())
}

pub(crate) fn authentication_error(_: crypto::CryptoError) -> Error {
    Error::ErrInvalidMac
}

fn signature_verification_error(error: crypto::CryptoError) -> Error {
    match error {
        crypto::CryptoError::InvalidSignature => Error::ErrKeySignatureMismatch,
        crypto::CryptoError::UnsupportedAlgorithm(_) => Error::ErrKeySignatureVerifyUnimplemented,
        error => crypto_error(error),
    }
}

/// A X.509 certificate(s) used to authenticate a DTLS connection.
#[derive(Clone, PartialEq, Debug)]
pub struct Certificate {
    /// DER-encoded certificates.
    pub certificate: Vec<CertificateDer<'static>>,
    /// Private key.
    pub private_key: CryptoPrivateKey,
}

impl Certificate {
    #[cfg(any(feature = "crypto-ring", feature = "crypto-aws-lc-rs"))]
    /// Generates a self-signed certificate, importing its key into `provider`.
    pub fn generate_self_signed(
        subject_alt_names: impl Into<Vec<String>>,
        crypto: &dyn RTCCrypto,
    ) -> Result<Self> {
        let CertifiedKey { cert, signing_key } = generate_simple_self_signed(subject_alt_names)
            .map_err(|error| Error::Other(error.to_string()))?;
        Ok(Certificate {
            certificate: vec![cert.der().to_owned()],
            private_key: CryptoPrivateKey::from_key_pair(&signing_key, crypto)?,
        })
    }

    #[cfg(any(feature = "crypto-ring", feature = "crypto-aws-lc-rs"))]
    /// Generates a self-signed certificate with `alg`, importing its key into `provider`.
    pub fn generate_self_signed_with_alg(
        subject_alt_names: impl Into<Vec<String>>,
        alg: &'static rcgen::SignatureAlgorithm,
        crypto: &dyn RTCCrypto,
    ) -> Result<Self> {
        let params = rcgen::CertificateParams::new(subject_alt_names)
            .map_err(|error| Error::Other(error.to_string()))?;
        let key_pair =
            rcgen::KeyPair::generate_for(alg).map_err(|error| Error::Other(error.to_string()))?;
        let cert = params
            .self_signed(&key_pair)
            .map_err(|error| Error::Other(error.to_string()))?;

        Ok(Certificate {
            certificate: vec![cert.der().to_owned()],
            private_key: CryptoPrivateKey::from_key_pair(&key_pair, crypto)?,
        })
    }

    /// Parses a PEM certificate and imports its PKCS#8 key into `crypto`.
    pub fn from_pem(pem_str: &str, crypto: &dyn RTCCrypto) -> Result<Self> {
        let mut pems = pem::parse_many(pem_str).map_err(|e| Error::InvalidPEM(e.to_string()))?;
        if pems.len() < 2 {
            return Err(Error::InvalidPEM(format!(
                "expected at least two PEM blocks, got {}",
                pems.len()
            )));
        }
        if pems[0].tag() != "PRIVATE_KEY" {
            return Err(Error::InvalidPEM(format!(
                "invalid tag (expected: 'PRIVATE_KEY', got: '{}')",
                pems[0].tag()
            )));
        }

        let private_key_der = crypto::SecretVec::new(pems[0].contents().to_vec());

        let mut rustls_certs = Vec::new();
        for p in pems.drain(1..) {
            if p.tag() != "CERTIFICATE" {
                return Err(Error::InvalidPEM(format!(
                    "invalid tag (expected: 'CERTIFICATE', got: '{}')",
                    p.tag()
                )));
            }
            rustls_certs.push(CertificateDer::from(p.contents().to_vec()));
        }

        let schemes = [
            CryptoSignatureScheme::Ed25519,
            CryptoSignatureScheme::EcdsaP256Sha256,
            CryptoSignatureScheme::RsaPkcs1Sha256,
        ];
        let signing_key = schemes
            .into_iter()
            .filter(|scheme| crypto.supports(crypto::CryptoAlgorithm::SigningKeyImport(*scheme)))
            .find_map(|scheme| {
                crypto
                    .import_signing_key(scheme, private_key_der.as_ref())
                    .ok()
            })
            .ok_or_else(|| Error::InvalidPEM("can't decode PKCS#8 signing key".into()))?;

        Ok(Certificate::from_signing_key(rustls_certs, signing_key))
    }

    /// Serializes the certificate (including the private key) in PKCS#8 format in PEM.
    pub fn serialize_pem(&self) -> Result<String> {
        let private_key = self
            .private_key
            .signing_key
            .to_pkcs8_der()
            .map_err(crypto_error)?
            .ok_or_else(|| Error::Other("the certificate signing key is not exportable".into()))?;
        let mut data = vec![pem::Pem::new(
            "PRIVATE_KEY".to_string(),
            private_key.as_ref(),
        )];
        for rustls_cert in &self.certificate {
            data.push(pem::Pem::new(
                "CERTIFICATE".to_string(),
                rustls_cert.as_ref(),
            ));
        }
        Ok(pem::encode_many(&data))
    }

    /// Builds a certificate chain around an application-owned signing key, including HSM/KMS keys.
    pub fn from_signing_key(
        certificate: Vec<CertificateDer<'static>>,
        signing_key: Arc<dyn SigningKey>,
    ) -> Self {
        Self {
            certificate,
            private_key: CryptoPrivateKey::from_signing_key(signing_key),
        }
    }
}

pub(crate) fn value_key_message(
    client_random: &[u8],
    server_random: &[u8],
    public_key: &[u8],
    named_curve: NamedCurve,
) -> Vec<u8> {
    let mut server_ecdh_params = vec![0u8; 4];
    server_ecdh_params[0] = 3; // named curve
    server_ecdh_params[1..3].copy_from_slice(&(named_curve as u16).to_be_bytes());
    server_ecdh_params[3] = public_key.len() as u8;

    let mut plaintext = vec![];
    plaintext.extend_from_slice(client_random);
    plaintext.extend_from_slice(server_random);
    plaintext.extend_from_slice(&server_ecdh_params);
    plaintext.extend_from_slice(public_key);

    plaintext
}

/// Provider-neutral DTLS signing key.
#[derive(Clone)]
pub struct CryptoPrivateKey {
    /// Provider-owned signing key. It may be non-exportable.
    pub signing_key: Arc<dyn SigningKey>,
}

impl PartialEq for CryptoPrivateKey {
    fn eq(&self, other: &Self) -> bool {
        let left = self.signing_key.public_key();
        let right = other.signing_key.public_key();
        left.encoding == right.encoding && left.bytes == right.bytes
    }
}

impl std::fmt::Debug for CryptoPrivateKey {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let public_key = self.signing_key.public_key();
        formatter
            .debug_struct("CryptoPrivateKey")
            .field("public_key_encoding", &public_key.encoding)
            .field("public_key_len", &public_key.bytes.len())
            .finish()
    }
}

impl CryptoPrivateKey {
    /// Imports an rcgen key pair into an explicit provider.
    #[cfg(any(feature = "crypto-ring", feature = "crypto-aws-lc-rs"))]
    pub fn from_key_pair(key_pair: &KeyPair, crypto: &dyn RTCCrypto) -> Result<Self> {
        let serialized_der = crypto::SecretVec::new(key_pair.serialize_der());
        let scheme = if key_pair.is_compatible(&rcgen::PKCS_ED25519) {
            CryptoSignatureScheme::Ed25519
        } else if key_pair.is_compatible(&rcgen::PKCS_ECDSA_P256_SHA256) {
            CryptoSignatureScheme::EcdsaP256Sha256
        } else if key_pair.is_compatible(&rcgen::PKCS_RSA_SHA256) {
            CryptoSignatureScheme::RsaPkcs1Sha256
        } else {
            return Err(Error::Other("Unsupported key_pair".to_owned()));
        };
        let signing_key = crypto
            .import_signing_key(scheme, serialized_der.as_ref())
            .map_err(crypto_error)?;
        Ok(Self { signing_key })
    }

    /// Wraps a provider-neutral, potentially non-exportable signing key.
    pub fn from_signing_key(signing_key: Arc<dyn SigningKey>) -> Self {
        Self { signing_key }
    }
}

// If the client provided a "signature_algorithms" extension, then all
// certificates provided by the server MUST be signed by a
// hash/signature algorithm pair that appears in that extension
//
// https://tools.ietf.org/html/rfc5246#section-7.4.2
pub(crate) fn generate_key_signature(
    client_random: &[u8],
    server_random: &[u8],
    public_key: &[u8],
    named_curve: NamedCurve,
    algorithm: &SignatureHashAlgorithm,
    private_key: &CryptoPrivateKey,
) -> Result<Vec<u8>> {
    let msg = value_key_message(client_random, server_random, public_key, named_curve);
    private_key
        .signing_key
        .sign(algorithm.crypto_scheme()?, &msg)
        .map_err(crypto_error)
}

// add OID_ED25519 which is not defined in x509_parser
/// The X.509 algorithm OID for Ed25519.
pub const OID_ED25519: Oid<'static> = oid!(1.3.101.112);
/// The X.509 algorithm OID for ECDSA with a named curve.
pub const OID_ECDSA: Oid<'static> = oid!(1.2.840.10045.2.1);

/// The hash and signature pair `der`, an X.509 certificate, is signed with, as a TLS 1.2
/// SignatureAndHashAlgorithm. `None` for an algorithm with no such pair here (RSASSA-PSS, or
/// one this crate does not know), and for a certificate that does not parse.
fn certificate_signature_pair(der: &[u8]) -> Option<SignatureHashAlgorithm> {
    use crate::signature_hash_algorithm::HashAlgorithm;

    let (_, certificate) = x509_parser::parse_x509_certificate(der).ok()?;
    let (hash, signature) = match certificate
        .signature_algorithm
        .algorithm
        .to_id_string()
        .as_str()
    {
        "1.2.840.10045.4.1" => (HashAlgorithm::Sha1, SignatureAlgorithm::Ecdsa),
        "1.2.840.10045.4.3.2" => (HashAlgorithm::Sha256, SignatureAlgorithm::Ecdsa),
        "1.2.840.10045.4.3.3" => (HashAlgorithm::Sha384, SignatureAlgorithm::Ecdsa),
        "1.2.840.10045.4.3.4" => (HashAlgorithm::Sha512, SignatureAlgorithm::Ecdsa),
        "1.2.840.113549.1.1.5" => (HashAlgorithm::Sha1, SignatureAlgorithm::Rsa),
        "1.2.840.113549.1.1.11" => (HashAlgorithm::Sha256, SignatureAlgorithm::Rsa),
        "1.2.840.113549.1.1.12" => (HashAlgorithm::Sha384, SignatureAlgorithm::Rsa),
        "1.2.840.113549.1.1.13" => (HashAlgorithm::Sha512, SignatureAlgorithm::Rsa),
        "1.3.101.112" => (HashAlgorithm::Ed25519, SignatureAlgorithm::Ed25519),
        _ => return None,
    };
    Some(SignatureHashAlgorithm { hash, signature })
}

/// Whether the end-entity certificate of `chain` is an X.509 version 3 certificate. RFC 5246
/// section 7.4.6: "The certificate type MUST be X.509v3, unless explicitly negotiated
/// otherwise"; no other certificate type is negotiated here. A certificate that does not parse
/// is not one.
pub(crate) fn is_x509_v3(chain: &[CertificateDer<'static>]) -> bool {
    chain.first().is_some_and(|leaf| {
        x509_parser::parse_x509_certificate(leaf.as_ref()).is_ok_and(|(_, certificate)| {
            certificate.tbs_certificate.version == x509_parser::x509::X509Version::V3
        })
    })
}

/// Whether every certificate of `chain` is signed with a pair in `schemes`: RFC 5246 7.4.2
/// asks it of the certificates a server sends (against the client's signature_algorithms) and
/// 7.4.4 of the ones a client sends (against the CertificateRequest).
///
/// A certificate whose signature algorithm has no TLS 1.2 pair this crate knows (see
/// [`certificate_signature_pair`]) cannot be judged and is let through.
pub(crate) fn certificates_signed_within(
    chain: &[CertificateDer<'static>],
    schemes: &[SignatureHashAlgorithm],
) -> bool {
    chain.iter().all(|certificate| {
        certificate_signature_pair(certificate.as_ref()).is_none_or(|pair| schemes.contains(&pair))
    })
}

/// The smallest RSA key a peer may sign with (RFC 8446 appendix C.2; 4.2.3 for RSASSA-PSS).
pub(crate) const MIN_RSA_KEY_BITS: usize = 2048;
/// The largest RSA key a peer may sign with (RFC 8446 appendix C.2).
pub(crate) const MAX_RSA_KEY_BITS: usize = 8192;

fn verify_signature(
    crypto: &dyn crypto::RTCCrypto,
    message: &[u8],
    hash_algorithm: &SignatureHashAlgorithm,
    remote_key_signature: &[u8],
    raw_certificates: &[Vec<u8>],
    insecure_verification: bool,
) -> Result<()> {
    if raw_certificates.is_empty() {
        return Err(Error::ErrLengthMismatch);
    }

    let (_, certificate) = x509_parser::parse_x509_certificate(&raw_certificates[0])
        .map_err(|e| Error::Other(e.to_string()))?;

    let encoding = match hash_algorithm.signature {
        SignatureAlgorithm::Ed25519 => PublicKeyEncoding::Ed25519Raw,
        SignatureAlgorithm::Ecdsa => PublicKeyEncoding::EcUncompressedPoint,
        SignatureAlgorithm::Rsa
        | SignatureAlgorithm::RsaPssRsaeSha256
        | SignatureAlgorithm::RsaPssRsaeSha384
        | SignatureAlgorithm::RsaPssRsaeSha512 => PublicKeyEncoding::RsaPkcs1Der,
        SignatureAlgorithm::Unsupported => return Err(Error::ErrKeySignatureVerifyUnimplemented),
    };
    if hash_algorithm.signature.is_rsa()
        && remote_key_signature.len() < 256
        && !insecure_verification
    {
        return Err(Error::ErrKeySignatureMismatch);
    }
    // RFC 8446 appendix C.2: "Applications SHOULD also enforce minimum and maximum key
    // sizes." RSA keys from 2048 bits (below with `insecure_verification` only) to 8192 bits:
    // a larger one costs the verifier time for no security anyone needs. The EC and EdDSA
    // keys have the sizes of their curves, which the provider checks.
    if let Ok(x509_parser::public_key::PublicKey::RSA(rsa)) =
        certificate.tbs_certificate.subject_pki.parsed()
    {
        let bits = rsa.key_size();
        if bits > MAX_RSA_KEY_BITS || (bits < MIN_RSA_KEY_BITS && !insecure_verification) {
            return Err(Error::Other(format!(
                "an RSA key of {bits} bits, outside {MIN_RSA_KEY_BITS} to {MAX_RSA_KEY_BITS} \
                 (RFC 8446 appendix C.2)"
            )));
        }
    }
    let scheme = match (hash_algorithm.signature, hash_algorithm.hash) {
        (SignatureAlgorithm::Ecdsa, crate::signature_hash_algorithm::HashAlgorithm::Sha256) => {
            if certificate
                .tbs_certificate
                .subject_pki
                .subject_public_key
                .data
                .len()
                == 97
            {
                crypto::SignatureScheme::EcdsaP384Sha256
            } else {
                crypto::SignatureScheme::EcdsaP256Sha256
            }
        }
        _ => hash_algorithm.crypto_scheme()?,
    };

    let public_key = &certificate
        .tbs_certificate
        .subject_pki
        .subject_public_key
        .data;
    let verified = crypto.verify_signature(
        scheme,
        PublicKey {
            encoding,
            bytes: public_key,
        },
        message,
        remote_key_signature,
    );
    // RFC 5246 section 4.7: the DigestInfo of an RSASSA-PKCS1-v1_5 signature "MUST be NULL,
    // but implementations MUST accept both without parameters and with NULL parameters". The
    // providers verify the NULL form only; the form without parameters is checked by the
    // provider-independent RSA public operation of `rtci-crypto`.
    match (verified, crypto::rsa_pkcs1_hash(scheme)) {
        (Err(_), Some(hash)) if hash_algorithm.signature == SignatureAlgorithm::Rsa => {
            let digest = crypto.hash(hash, message).map_err(crypto_error)?;
            crypto::verify_rsa_pkcs1_without_digest_parameters(
                scheme,
                public_key,
                &digest,
                remote_key_signature,
            )
            .map_err(signature_verification_error)
        }
        (verified, _) => verified.map_err(signature_verification_error),
    }
}

pub(crate) fn verify_key_signature(
    crypto: &dyn crypto::RTCCrypto,
    message: &[u8],
    hash_algorithm: &SignatureHashAlgorithm,
    remote_key_signature: &[u8],
    raw_certificates: &[Vec<u8>],
    insecure_verification: bool,
) -> Result<()> {
    verify_signature(
        crypto,
        message,
        hash_algorithm,
        remote_key_signature,
        raw_certificates,
        insecure_verification,
    )
}

// If the server has sent a CertificateRequest message, the client MUST send the Certificate
// message.  The ClientKeyExchange message is now sent, and the content
// of that message will depend on the public key algorithm selected
// between the ClientHello and the ServerHello.  If the client has sent
// a certificate with signing ability, a digitally-signed
// CertificateVerify message is sent to explicitly verify possession of
// the private key in the certificate.
// https://tools.ietf.org/html/rfc5246#section-7.3
pub(crate) fn generate_certificate_verify(
    handshake_bodies: &[u8],
    algorithm: &SignatureHashAlgorithm,
    private_key: &CryptoPrivateKey,
) -> Result<Vec<u8>> {
    private_key
        .signing_key
        .sign(algorithm.crypto_scheme()?, handshake_bodies)
        .map_err(crypto_error)
}

pub(crate) fn verify_certificate_verify(
    crypto: &dyn crypto::RTCCrypto,
    handshake_bodies: &[u8],
    hash_algorithm: &SignatureHashAlgorithm,
    remote_key_signature: &[u8],
    raw_certificates: &[Vec<u8>],
    insecure_verification: bool,
) -> Result<()> {
    verify_signature(
        crypto,
        handshake_bodies,
        hash_algorithm,
        remote_key_signature,
        raw_certificates,
        insecure_verification,
    )
}

pub(crate) fn load_certs(raw_certificates: &[Vec<u8>]) -> Result<Vec<CertificateDer<'static>>> {
    if raw_certificates.is_empty() {
        return Err(Error::ErrLengthMismatch);
    }

    let mut certs = vec![];
    for raw_cert in raw_certificates {
        let cert = CertificateDer::from(raw_cert.to_vec());
        certs.push(cert);
    }

    Ok(certs)
}

pub(crate) fn verify_client_cert(
    raw_certificates: &[Vec<u8>],
    cert_verifier: &Arc<dyn ClientCertVerifier>,
) -> Result<Vec<CertificateDer<'static>>> {
    let chains = load_certs(raw_certificates)?;

    let (end_entity, intermediates) = chains
        .split_first()
        .ok_or(Error::ErrClientCertificateRequired)?;

    match cert_verifier.verify_client_cert(
        end_entity,
        intermediates,
        rustls::pki_types::UnixTime::now(),
    ) {
        Ok(_) => {}
        Err(err) => return Err(Error::Other(err.to_string())),
    };

    Ok(chains)
}

pub(crate) fn verify_server_cert(
    raw_certificates: &[Vec<u8>],
    cert_verifier: &Arc<dyn ServerCertVerifier>,
    server_name: &str,
) -> Result<Vec<CertificateDer<'static>>> {
    let chains = load_certs(raw_certificates)?;
    let server_name = match ServerName::try_from(server_name) {
        Ok(server_name) => server_name,
        Err(err) => return Err(Error::Other(err.to_string())),
    };

    let (end_entity, intermediates) = chains
        .split_first()
        .ok_or(Error::ErrServerMustHaveCertificate)?;
    match cert_verifier.verify_server_cert(
        end_entity,
        intermediates,
        &server_name,
        &[],
        rustls::pki_types::UnixTime::now(),
    ) {
        Ok(_) => {}
        Err(err) => return Err(Error::Other(err.to_string())),
    };

    Ok(chains)
}

/// The explicit nonce an AES-GCM or AES-CCM record carries: its epoch and sequence number, the
/// eight bytes of the record header between the version and the length. A record's epoch and
/// sequence number never repeat under one key (a key belongs to one epoch and one direction, and
/// the sequence number may not wrap, RFC 6347 4.1), so neither does the nonce, as RFC 5288
/// section 3 requires; RFC 6655 section 3 and RFC 9325 recommend exactly this construction. A
/// random 64-bit value would be expected to repeat after about 2^32 records under one key.
pub(crate) fn record_explicit_nonce(h: &RecordLayerHeader) -> [u8; 8] {
    let mut nonce = [0u8; 8];
    nonce[..2].copy_from_slice(&h.epoch.to_be_bytes());
    nonce[2..].copy_from_slice(&h.sequence_number.to_be_bytes()[2..]);
    nonce
}

/// The additional data of an AEAD record, and the pseudo-header a MAC covers in front of
/// the content: RFC 5246 6.2.3.3 / 6.2.3.1 for an ordinary record, and RFC 9146 section 5
/// for a `tls12_cid` record, whose connection id `cid` is given (the header then has the
/// content type `tls12_cid`, and `payload_len` is the length of the DTLSInnerPlaintext).
///
/// ```text
/// seq_num_placeholder (8 x 0xff) || tls12_cid || cid_length || tls12_cid || version
///     || epoch || sequence_number || cid || length_of_DTLSInnerPlaintext
/// ```
pub(crate) fn record_additional_data(
    h: &RecordLayerHeader,
    payload_len: usize,
    cid: Option<&[u8]>,
) -> Vec<u8> {
    let Some(cid) = cid else {
        return generate_aead_additional_data(h, payload_len).to_vec();
    };
    let mut data = Vec::with_capacity(23 + cid.len());
    data.extend_from_slice(&[0xff; 8]);
    data.push(ContentType::Tls12Cid as u8);
    data.push(cid.len() as u8);
    data.push(ContentType::Tls12Cid as u8);
    data.push(h.protocol_version.major);
    data.push(h.protocol_version.minor);
    data.extend_from_slice(&h.epoch.to_be_bytes());
    data.extend_from_slice(&h.sequence_number.to_be_bytes()[2..]);
    data.extend_from_slice(cid);
    data.extend_from_slice(&(payload_len as u16).to_be_bytes());
    data
}

pub(crate) fn generate_aead_additional_data(h: &RecordLayerHeader, payload_len: usize) -> [u8; 13] {
    let mut additional_data = [0u8; 13];
    // SequenceNumber MUST be set first
    // we only want uint48, clobbering an extra 2 (using uint64, rust doesn't have uint48)
    additional_data[..8].copy_from_slice(&h.sequence_number.to_be_bytes());
    additional_data[..2].copy_from_slice(&h.epoch.to_be_bytes());
    additional_data[8] = h.content_type as u8;
    additional_data[9] = h.protocol_version.major;
    additional_data[10] = h.protocol_version.minor;
    additional_data[11..].copy_from_slice(&(payload_len as u16).to_be_bytes());

    additional_data
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_certificate_serialize_pem_and_from_pem() -> Result<()> {
        let provider = crypto::default_provider().map_err(crypto_error)?;
        let cert =
            Certificate::generate_self_signed(vec!["webrtc.rs".to_owned()], provider.crypto())?;

        let pem = cert.serialize_pem()?;
        let loaded_cert = Certificate::from_pem(&pem, provider.crypto())?;

        assert_eq!(loaded_cert, cert);

        Ok(())
    }
}