qtls 0.2.0

Connection-independent QUIC TLS 1.3 state machine for dquic
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
use std::{
    collections::VecDeque,
    fmt,
    sync::{Arc, Mutex},
};

use bytes::Bytes;
use rustls::{
    DigitallySignedStruct, DistinguishedName, SignatureScheme,
    client::{
        ResolvesClientCert, WebPkiServerVerifier,
        danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
    },
    pki_types::{CertificateDer, ServerName, UnixTime},
    server::{
        ClientHello, ResolvesServerCert, WebPkiClientVerifier,
        danger::{ClientCertVerified, ClientCertVerifier},
    },
    sign::CertifiedKey,
};
use x509_parser::{extensions::GeneralName, prelude::FromDer};

use crate::{
    BidirectionalKeys, CertificateError, Epoch, ExporterError, HandshakeNotComplete, LocalAuthority, OneRttKeyMaterial, PeerTlsError,
    RemoteAuthority, TlsAlert, TlsConfigError, TlsError, TlsInvariantError, TlsLimits, root::RootCertsSnapshot,
};

pub enum InstalledKeys {
    ZeroRtt(crate::DirectionalKeys),
    Handshake(BidirectionalKeys),
    OneRtt(OneRttKeyMaterial),
}

pub enum TlsEvent {
    WriteCrypto { epoch: Epoch, bytes: Bytes },
    InstallKeys(InstalledKeys),
    ClientHello { server_name: Option<Arc<str>>, transport_parameters: Bytes },
    ServerTransportParameters(Bytes),
    HandshakeComplete(HandshakeSummary),
    Alert(TlsAlert),
}

#[derive(Clone, Debug)]
pub struct HandshakeSummary {
    pub alpn: Option<Bytes>,
    pub local: Option<LocalAuthority>,
    pub remote: Option<RemoteAuthority>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum Role {
    Client,
    Server,
}

#[derive(Clone)]
pub(crate) struct PeerState {
    pub authorities: Arc<Mutex<AuthorityState>>,
}

impl PeerState {
    pub(crate) fn new() -> Self {
        Self { authorities: Arc::new(Mutex::new(AuthorityState::default())) }
    }
}

#[derive(Default)]
pub(crate) struct AuthorityState {
    pub local: Option<LocalAuthority>,
    pub remote: Option<RemoteAuthority>,
    pub resumed_local: Option<LocalAuthority>,
    pub resumed_remote: Option<RemoteAuthority>,
}

pub struct TlsHandshake {
    connection: rustls::quic::Connection,
    role: Role,
    peer: PeerState,
    limits: TlsLimits,
    events: VecDeque<TlsEvent>,
    input_epoch: Epoch,
    output_epoch: Epoch,
    received_bytes: usize,
    peer_parameters_emitted: bool,
    complete: bool,
    terminal: bool,
}

impl TlsHandshake {
    pub(crate) fn new(connection: rustls::quic::Connection, role: Role, peer: PeerState, limits: TlsLimits) -> Result<Self, TlsError> {
        let mut handshake = Self {
            connection,
            role,
            peer,
            limits,
            events: VecDeque::new(),
            input_epoch: Epoch::Initial,
            output_epoch: Epoch::Initial,
            received_bytes: 0,
            peer_parameters_emitted: false,
            complete: false,
            terminal: false,
        };
        handshake.drain_backend()?;
        Ok(handshake)
    }

    pub fn receive_crypto(&mut self, level: Epoch, contiguous: &[u8]) -> Result<(), TlsError> {
        if contiguous.is_empty() {
            return Ok(());
        }
        if self.terminal {
            return Err(TlsInvariantError::EventAfterTerminal.into());
        }
        if level != self.input_epoch {
            self.terminal = true;
            return Err(PeerTlsError::WrongCryptoLevel { expected: self.input_epoch, actual: level }.into());
        }
        let Some(received_bytes) = self.received_bytes.checked_add(contiguous.len()) else {
            self.terminal = true;
            return Err(PeerTlsError::ResourceLimit { resource: "handshake bytes", limit: self.limits.max_handshake_bytes }.into());
        };
        self.received_bytes = received_bytes;
        if self.received_bytes > self.limits.max_handshake_bytes {
            self.terminal = true;
            return Err(PeerTlsError::ResourceLimit { resource: "handshake bytes", limit: self.limits.max_handshake_bytes }.into());
        }

        if let Err(error) = self.connection.read_hs(contiguous) {
            self.terminal = true;
            if let Some(description) = self.connection.alert() {
                let alert = TlsAlert::new(description);
                self.events.push_back(TlsEvent::Alert(alert));
                return Err(TlsError::Alert(alert));
            }
            return Err(PeerTlsError::Protocol(error.to_string()).into());
        }

        if let Err(error) = self.emit_peer_parameters() {
            self.terminal = true;
            return Err(error);
        }
        if let Err(error) = self.drain_backend() {
            self.terminal = true;
            return Err(error);
        }
        if !self.connection.is_handshaking() {
            self.input_epoch = Epoch::Data;
        }
        if let Err(error) = self.emit_completion() {
            self.terminal = true;
            return Err(error);
        }
        Ok(())
    }

    pub fn next_event(&mut self) -> Option<TlsEvent> {
        self.events.pop_front()
    }

    pub fn is_complete(&self) -> bool {
        self.complete
    }

    pub fn finish(self) -> Result<EstablishedTls, HandshakeNotComplete> {
        if !self.complete {
            return Err(HandshakeNotComplete);
        }
        Ok(EstablishedTls { connection: self.connection, terminal: self.terminal })
    }

    fn emit_peer_parameters(&mut self) -> Result<(), TlsError> {
        if self.peer_parameters_emitted {
            return Ok(());
        }
        let Some(parameters) = self.connection.quic_transport_parameters() else {
            return Ok(());
        };
        let parameters = Bytes::copy_from_slice(parameters);
        match (&self.role, &self.connection) {
            (Role::Server, rustls::quic::Connection::Server(connection)) => {
                self.events.push_back(TlsEvent::ClientHello {
                    server_name: connection.server_name().map(Arc::from),
                    transport_parameters: parameters,
                });
            }
            (Role::Client, rustls::quic::Connection::Client(_)) => {
                self.events.push_back(TlsEvent::ServerTransportParameters(parameters));
            }
            _ => return Err(TlsInvariantError::Missing("matching TLS role").into()),
        }
        self.peer_parameters_emitted = true;
        Ok(())
    }

    fn drain_backend(&mut self) -> Result<(), TlsError> {
        loop {
            let mut output = Vec::new();
            let key_change = self.connection.write_hs(&mut output);
            if output.len() > self.limits.max_flight_bytes {
                return Err(PeerTlsError::ResourceLimit { resource: "output flight", limit: self.limits.max_flight_bytes }.into());
            }
            let output_is_empty = output.is_empty();
            if !output_is_empty {
                self.events.push_back(TlsEvent::WriteCrypto { epoch: self.output_epoch, bytes: output.into() });
            }

            match key_change {
                Some(rustls::quic::KeyChange::Handshake { keys }) => {
                    self.events.push_back(TlsEvent::InstallKeys(InstalledKeys::Handshake(keys.into())));
                    self.input_epoch = Epoch::Handshake;
                    self.output_epoch = Epoch::Handshake;
                }
                Some(rustls::quic::KeyChange::OneRtt { keys, next }) => {
                    self.events.push_back(TlsEvent::InstallKeys(InstalledKeys::OneRtt(OneRttKeyMaterial::new(keys, next))));
                    self.output_epoch = Epoch::Data;
                }
                None if output_is_empty => break,
                None => {}
            }
        }
        Ok(())
    }

    fn emit_completion(&mut self) -> Result<(), TlsError> {
        if self.complete || self.connection.is_handshaking() {
            return Ok(());
        }
        let authorities = self.peer.authorities.lock().map_err(|_| TlsInvariantError::Missing("authority state lock"))?;
        let resumed = self.handshake_kind() == Some(rustls::HandshakeKind::Resumed);
        let local = match (authorities.local.clone(), resumed) {
            (None, true) => authorities.resumed_local.clone(),
            (local, _) => local,
        };
        let remote = match (authorities.remote.clone(), resumed) {
            (None, true) => authorities.resumed_remote.clone(),
            (remote, _) => remote,
        };
        match self.role {
            Role::Client if remote.is_none() => {
                return Err(TlsInvariantError::Missing("verified server authority").into());
            }
            Role::Server if local.is_none() => {
                return Err(TlsInvariantError::Missing("selected server authority").into());
            }
            _ => {}
        }
        let summary = HandshakeSummary { alpn: self.connection.alpn_protocol().map(Bytes::copy_from_slice), local, remote };
        self.events.push_back(TlsEvent::HandshakeComplete(summary));
        self.complete = true;
        Ok(())
    }

    fn handshake_kind(&self) -> Option<rustls::HandshakeKind> {
        match &self.connection {
            rustls::quic::Connection::Client(connection) => connection.handshake_kind(),
            rustls::quic::Connection::Server(connection) => connection.handshake_kind(),
        }
    }
}

pub struct EstablishedTls {
    connection: rustls::quic::Connection,
    terminal: bool,
}

impl EstablishedTls {
    pub fn receive_post_handshake(&mut self, contiguous_one_rtt_crypto: &[u8]) -> Result<(), TlsError> {
        if contiguous_one_rtt_crypto.is_empty() {
            return Ok(());
        }
        if self.terminal {
            return Err(TlsInvariantError::EventAfterTerminal.into());
        }
        if let Err(error) = self.connection.read_hs(contiguous_one_rtt_crypto) {
            self.terminal = true;
            if let Some(description) = self.connection.alert() {
                return Err(TlsError::Alert(TlsAlert::new(description)));
            }
            return Err(PeerTlsError::Protocol(error.to_string()).into());
        }
        let mut unexpected_output = Vec::new();
        if self.connection.write_hs(&mut unexpected_output).is_some() || !unexpected_output.is_empty() {
            return Err(TlsInvariantError::Missing("post-handshake output sink").into());
        }
        Ok(())
    }

    pub fn export_keying_material(&self, output: &mut [u8], label: &[u8], context: Option<&[u8]>) -> Result<(), ExporterError> {
        self.connection.export_keying_material(output, label, context).map(|_| ()).map_err(|_| ExporterError::Failed)
    }
}

pub(crate) fn map_rustls_error(error: rustls::Error) -> TlsError {
    PeerTlsError::Protocol(error.to_string()).into()
}

pub(crate) struct FixedServerCert {
    authority: LocalAuthority,
    peer: PeerState,
    limits: TlsLimits,
}

impl FixedServerCert {
    pub fn new(authority: LocalAuthority, peer: PeerState, limits: TlsLimits) -> Self {
        Self { authority, peer, limits }
    }
}

impl fmt::Debug for FixedServerCert {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.debug_struct("FixedServerCert").finish_non_exhaustive()
    }
}

impl ResolvesServerCert for FixedServerCert {
    fn resolve(&self, _: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
        if !authority_within_limits(&self.authority, self.limits) {
            return None;
        }
        let certified_key = self.authority.certified_key();
        self.peer.authorities.lock().ok()?.local = Some(self.authority.clone());
        Some(certified_key)
    }
}

pub(crate) struct OptionalClientCert {
    authority: Option<LocalAuthority>,
    peer: PeerState,
    limits: TlsLimits,
}

impl OptionalClientCert {
    pub fn new(authority: Option<LocalAuthority>, peer: PeerState, limits: TlsLimits) -> Self {
        Self { authority, peer, limits }
    }

    pub(crate) fn rebind(&self, expected: &crate::resumption::AuthorityProjection) -> Option<LocalAuthority> {
        let authority = self.authority.as_ref()?;
        if !authority_within_limits(authority, self.limits) || !expected.matches(authority) {
            return None;
        }
        Some(authority.clone())
    }
}

impl fmt::Debug for OptionalClientCert {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.debug_struct("OptionalClientCert").finish_non_exhaustive()
    }
}

impl ResolvesClientCert for OptionalClientCert {
    fn resolve(&self, _: &[&[u8]], _: &[SignatureScheme]) -> Option<Arc<CertifiedKey>> {
        let authority = self.authority.as_ref()?;
        if !authority_within_limits(authority, self.limits) {
            return None;
        }
        let certified_key = authority.certified_key();
        self.peer.authorities.lock().ok()?.local = Some(authority.clone());
        Some(certified_key)
    }

    fn has_certs(&self) -> bool {
        self.authority.is_some()
    }
}

fn authority_within_limits(authority: &LocalAuthority, limits: TlsLimits) -> bool {
    authority.certificates().len() <= limits.max_certificates
        && authority.certificates().iter().map(|certificate| certificate.as_ref().len()).sum::<usize>()
            <= limits.max_certificate_chain_bytes
        && authority.ocsp().len() <= limits.max_ocsp_bytes
}

pub(crate) struct ServerVerifier {
    inner: Arc<dyn ServerCertVerifier>,
    roots: RootCertsSnapshot,
    algorithms: rustls::crypto::WebPkiSupportedAlgorithms,
    peer: PeerState,
    limits: TlsLimits,
}

impl ServerVerifier {
    pub fn new(
        roots: RootCertsSnapshot,
        provider: Arc<rustls::crypto::CryptoProvider>,
        peer: PeerState,
        limits: TlsLimits,
    ) -> Result<Self, TlsConfigError> {
        let algorithms = provider.signature_verification_algorithms;
        let inner = WebPkiServerVerifier::builder_with_provider(roots.store.clone(), provider)
            .build()
            .map_err(|error| TlsConfigError::Invalid(error.to_string()))?;
        Ok(Self { inner, roots, algorithms, peer, limits })
    }
}

impl fmt::Debug for ServerVerifier {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.debug_struct("ServerVerifier").finish_non_exhaustive()
    }
}

impl ServerCertVerifier for ServerVerifier {
    fn verify_server_cert(
        &self,
        end_entity: &CertificateDer<'_>,
        intermediates: &[CertificateDer<'_>],
        server_name: &ServerName<'_>,
        ocsp_response: &[u8],
        now: UnixTime,
    ) -> Result<ServerCertVerified, rustls::Error> {
        let certificates = chain(end_entity, intermediates);
        validate_peer_limits(&certificates, ocsp_response, self.limits)?;
        self.inner.verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)?;
        // A configured DDNS fallback must pass the same mandatory OCSP checks
        // as a peer staple.
        let fetched_ocsp =
            if ocsp_response.is_empty() && matches!(server_name, ServerName::DnsName(name) if name.as_ref() == "ddns.genmeta.net") {
                std::env::var_os("DQUIC_DDNS_OCSP_FILE")
                    .map(|path| {
                        use std::io::Read as _;
                        let mut response = Vec::new();
                        std::fs::File::open(path)
                            .and_then(|file| file.take(self.limits.max_ocsp_bytes as u64 + 1).read_to_end(&mut response))
                            .map_err(|_| rustls::Error::InvalidCertificate(CertificateError::InvalidOcspResponse))?;
                        validate_peer_limits(&certificates, &response, self.limits)?;
                        Ok::<_, rustls::Error>(response)
                    })
                    .transpose()?
            } else {
                None
            };
        crate::ocsp::verify(
            fetched_ocsp.as_deref().unwrap_or(ocsp_response),
            end_entity,
            intermediates,
            &self.roots,
            now,
            self.algorithms,
        )?;
        let name: Arc<str> = match server_name {
            ServerName::DnsName(name) => Arc::from(name.as_ref()),
            _ => return Err(CertificateError::NotValidForName.into()),
        };
        let authority =
            RemoteAuthority::new(name, &certificates).map_err(|_| rustls::Error::InvalidCertificate(CertificateError::BadEncoding))?;
        self.peer.authorities.lock().map_err(|_| rustls::Error::General("verified authority lock poisoned".into()))?.remote =
            Some(authority);
        Ok(ServerCertVerified::assertion())
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        certificate: &CertificateDer<'_>,
        signature: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls12_signature(message, certificate, signature)
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        certificate: &CertificateDer<'_>,
        signature: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls13_signature(message, certificate, signature)
    }

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        self.inner.supported_verify_schemes()
    }
}

pub(crate) struct ClientVerifier {
    inner: Arc<dyn ClientCertVerifier>,
    roots: RootCertsSnapshot,
    algorithms: rustls::crypto::WebPkiSupportedAlgorithms,
    peer: PeerState,
    limits: TlsLimits,
}

impl ClientVerifier {
    pub fn new(
        roots: RootCertsSnapshot,
        provider: Arc<rustls::crypto::CryptoProvider>,
        peer: PeerState,
        limits: TlsLimits,
    ) -> Result<Self, TlsConfigError> {
        let algorithms = provider.signature_verification_algorithms;
        let inner = WebPkiClientVerifier::builder_with_provider(roots.store.clone(), provider)
            .build()
            .map_err(|error| TlsConfigError::Invalid(error.to_string()))?;
        Ok(Self { inner, roots, algorithms, peer, limits })
    }
}

impl fmt::Debug for ClientVerifier {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.debug_struct("ClientVerifier").finish_non_exhaustive()
    }
}

impl ClientCertVerifier for ClientVerifier {
    fn offer_client_auth(&self) -> bool {
        true
    }

    fn client_auth_mandatory(&self) -> bool {
        false
    }

    fn request_client_ocsp(&self) -> bool {
        true
    }

    fn root_hint_subjects(&self) -> &[DistinguishedName] {
        self.inner.root_hint_subjects()
    }

    fn verify_client_cert(
        &self,
        end_entity: &CertificateDer<'_>,
        intermediates: &[CertificateDer<'_>],
        now: UnixTime,
    ) -> Result<ClientCertVerified, rustls::Error> {
        self.verify_client_cert_with_ocsp(end_entity, intermediates, &[], now)
    }

    fn verify_client_cert_with_ocsp(
        &self,
        end_entity: &CertificateDer<'_>,
        intermediates: &[CertificateDer<'_>],
        ocsp_response: &[u8],
        now: UnixTime,
    ) -> Result<ClientCertVerified, rustls::Error> {
        let certificates = chain(end_entity, intermediates);
        validate_peer_limits(&certificates, ocsp_response, self.limits)?;
        self.inner.verify_client_cert_with_ocsp(end_entity, intermediates, ocsp_response, now)?;
        crate::ocsp::verify(ocsp_response, end_entity, intermediates, &self.roots, now, self.algorithms)?;
        let name = certificate_name(end_entity)?;
        let authority =
            RemoteAuthority::new(name, &certificates).map_err(|_| rustls::Error::InvalidCertificate(CertificateError::BadEncoding))?;
        self.peer.authorities.lock().map_err(|_| rustls::Error::General("verified authority lock poisoned".into()))?.remote =
            Some(authority);
        Ok(ClientCertVerified::assertion())
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        certificate: &CertificateDer<'_>,
        signature: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls12_signature(message, certificate, signature)
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        certificate: &CertificateDer<'_>,
        signature: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls13_signature(message, certificate, signature)
    }

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        self.inner.supported_verify_schemes()
    }
}

fn chain<'a>(end_entity: &CertificateDer<'a>, intermediates: &[CertificateDer<'a>]) -> Vec<CertificateDer<'a>> {
    std::iter::once(end_entity.clone()).chain(intermediates.iter().cloned()).collect()
}

fn certificate_name(certificate: &CertificateDer<'_>) -> Result<Arc<str>, rustls::Error> {
    let (_, certificate) =
        x509_parser::certificate::X509Certificate::from_der(certificate.as_ref()).map_err(|_| CertificateError::BadEncoding)?;
    let name = certificate
        .subject_alternative_name()
        .map_err(|_| CertificateError::BadEncoding)?
        .into_iter()
        .flat_map(|extension| extension.value.general_names.iter())
        .find_map(|name| match name {
            GeneralName::DNSName(name) => Some(*name),
            _ => None,
        })
        .ok_or(CertificateError::NotValidForName)?;
    rustls::pki_types::DnsName::try_from(name.to_owned()).map_err(|_| CertificateError::NotValidForName)?;
    Ok(Arc::from(name))
}

fn validate_peer_limits(certificates: &[CertificateDer<'_>], ocsp: &[u8], limits: TlsLimits) -> Result<(), rustls::Error> {
    if certificates.len() > limits.max_certificates
        || certificates.iter().map(|certificate| certificate.as_ref().len()).sum::<usize>() > limits.max_certificate_chain_bytes
    {
        return Err(CertificateError::BadEncoding.into());
    }
    if ocsp.len() > limits.max_ocsp_bytes {
        return Err(CertificateError::InvalidOcspResponse.into());
    }
    Ok(())
}