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
use super::cipher_suite::*;
use super::client_certificate_type::ClientCertificateType;
use super::conn::*;
use super::curve::named_curve::*;
use super::extension::extension_use_srtp::SrtpProtectionProfile;
use super::handshake::handshake_random::*;
use super::prf::*;
use super::signature_hash_algorithm::SignatureHashAlgorithm;
use crypto::RTCCryptoProvider;
use crypto::SecretVec;
use rkyv::{Archive, Deserialize, Serialize};
use shared::error::*;
use std::io::{BufWriter, Cursor};
use std::sync::Arc;
use zeroize::Zeroize;

// State holds the dtls connection state and implements both encoding.BinaryMarshaler and encoding.BinaryUnmarshaler
/// The negotiated connection state: keys, sequence numbers, peer identity and the active
/// cipher suite.
pub struct State {
    pub(crate) crypto_provider: Arc<dyn RTCCryptoProvider>,
    pub(crate) local_epoch: u16,
    pub(crate) remote_epoch: u16,
    pub(crate) local_sequence_number: Vec<u64>, // uint48
    pub(crate) local_random: HandshakeRandom,
    pub(crate) remote_random: HandshakeRandom,
    /// Zeroized when replaced or dropped, like every secret here.
    pub(crate) master_secret: SecretVec,
    pub(crate) cipher_suite: Option<Box<dyn CipherSuite>>, // nil if a cipher_suite hasn't been chosen

    pub(crate) srtp_protection_profile: SrtpProtectionProfile, // Negotiated srtp_protection_profile
    /// The peer's certificate chain, DER-encoded.
    ///
    /// WebRTC checks its fingerprint against the one signalled in SDP.
    pub peer_certificates: Vec<Vec<u8>>,
    /// The PSK identity hint, for pre-shared-key handshakes.
    pub identity_hint: Vec<u8>,

    pub(crate) is_client: bool,

    pub(crate) pre_master_secret: SecretVec,
    pub(crate) extended_master_secret: bool,

    pub(crate) named_curve: NamedCurve,
    pub(crate) local_keypair: Option<NamedCurveKeypair>,
    pub(crate) cookie: Vec<u8>,
    pub(crate) handshake_send_sequence: isize,
    pub(crate) handshake_recv_sequence: isize,
    pub(crate) server_name: String,
    pub(crate) remote_requested_certificate: bool, // Did we get a CertificateRequest
    pub(crate) local_certificates_verify: Vec<u8>, // cache CertificateVerify
    pub(crate) local_verify_data: Vec<u8>,         // cached VerifyData
    pub(crate) local_key_signature: Vec<u8>,       // cached keySignature
    pub(crate) peer_certificates_verified: bool,
    /// The transcript and CertificateVerify signature whose check last passed, so that
    /// re-parsing the same flight does not verify the same signature again.
    pub(crate) verified_certificate_verify: Option<Vec<u8>>,
    /// Both ends signalled secure renegotiation in this handshake (RFC 5746 3.4, 3.6): the
    /// ClientHello carried an empty renegotiation_info or the signalling suite, and, for a
    /// client, the ServerHello answered with an empty renegotiation_info.
    pub(crate) secure_renegotiation: bool,
    /// The hash and signature pairs the peer accepts signatures under. For a server: the
    /// ClientHello's signature_algorithms, or the RFC 5246 7.4.1.4.1 defaults when it sent
    /// none. For a client: the CertificateRequest's supported_signature_algorithms.
    pub(crate) remote_signature_schemes: Vec<SignatureHashAlgorithm>,
    /// Client: the certificate types the CertificateRequest listed (RFC 5246 7.4.4).
    pub(crate) remote_certificate_types: Vec<ClientCertificateType>,
    /// Server: the ClientHello carried ec_point_formats, so the ServerHello may (RFC 8422 5.2).
    pub(crate) remote_offered_point_formats: bool,
    /// The application protocol ALPN selected (RFC 7301), once the server's hello (DTLS
    /// 1.2) or EncryptedExtensions (DTLS 1.3) has said: `None` without ALPN.
    pub(crate) application_protocol: Option<String>,
    /// RFC 9146, DTLS 1.2. The connection id this client put in its ClientHello, kept so
    /// that a repeated ClientHello carries the same one.
    pub(crate) connection_id_offer: Option<Vec<u8>>,
    /// The connection id the peer puts in the records it sends here, once the extension
    /// is negotiated (both hellos carried it). Empty: its records come without one.
    pub(crate) local_connection_id: Option<Vec<u8>>,
    /// The connection id this side puts in the records it sends, once negotiated. Empty:
    /// they go without one.
    pub(crate) remote_connection_id: Option<Vec<u8>>,
    /// Server: the pair chosen for the ServerKeyExchange signature, one the client listed and
    /// the certificate's key can produce (RFC 5246 7.4.3).
    pub(crate) local_signature_scheme: Option<SignatureHashAlgorithm>,
    /// The association failed and its secrets have been overwritten (RFC 5246 7.2.2).
    pub(crate) secrets_forgotten: bool,
    /// Server: the cookie of the ClientHello this association was made for has been verified
    /// by the endpoint, statelessly (RFC 6347 4.2.1), so the association itself keeps no
    /// cookie and takes that ClientHello as the one to negotiate from.
    pub(crate) cookie_verified_by_endpoint: bool,
    /// Client: the DTLS 1.3 part of the ClientHello (its key shares), until the server has
    /// chosen a version.
    pub(crate) tls13_offer: Option<crate::dtls13::hello::ClientOffer>,
    /// The association negotiated DTLS 1.3: its suite and exporter secret (RFC 8446
    /// section 7.5), once the handshake is complete.
    pub(crate) tls13: Option<(crate::dtls13::suite::Suite13, SecretVec)>,
    /// The version negotiated, once a ServerHello has settled it.
    pub(crate) negotiated_version: Option<crate::config::DtlsVersion>,
    /// The DTLS 1.3 handshake resumed a session, or used an external PSK, in place of
    /// certificates (RFC 8446 section 2.2).
    pub(crate) resumed: bool,
    /// The latest `now` the association was given: what a ClientHello dates its ticket's
    /// age by (the engine reads no clock).
    pub(crate) clock: Option<std::time::Instant>,
    /// DTLS 1.3 client: the 0-RTT data to send with the ClientHello, until it is offered.
    pub(crate) early_data: Vec<u8>,
    /// DTLS 1.3 client: the 0-RTT record, to go out after the ClientHello once.
    pub(crate) early_datagrams: Vec<bytes::BytesMut>,
    /// DTLS 1.3: whether 0-RTT data was accepted; `None` when none was offered.
    pub(crate) early_data_accepted: Option<bool>,
    /// DTLS 1.2: the session id of this handshake (RFC 5246 7.4.1.2, 7.4.1.3). A client's
    /// offer until the ServerHello, then the ServerHello's.
    pub(crate) session_id: Vec<u8>,
    /// DTLS 1.2 client: the session its ClientHello offers to resume.
    pub(crate) dtls12_offer: Option<crate::session::Dtls12Session>,
    /// DTLS 1.2 client: what its ClientHello's SessionTicket extension carries (RFC 5077
    /// section 3.2): a ticket, or nothing to ask for one. `None`: no extension.
    pub(crate) session_ticket_offer: Option<Vec<u8>>,
    /// DTLS 1.2: the session this abbreviated handshake resumes (RFC 5246 7.3).
    pub(crate) resuming: Option<crate::session::Dtls12Session>,
    /// DTLS 1.2: a NewSessionTicket comes in the server's last flight (RFC 5077 section 3.3:
    /// the ServerHello carried an empty SessionTicket extension).
    pub(crate) new_session_ticket: bool,
    /// DTLS 1.2 client: the ticket the server sent in this handshake, if not empty, with its
    /// lifetime hint in seconds (RFC 5077 section 3.3).
    pub(crate) received_ticket: Option<(Vec<u8>, u32)>,
    /// DTLS 1.2 server: the ticket it issued in this handshake (its id and when it expires),
    /// retired if the association fails (RFC 5246 7.2.2).
    pub(crate) issued_ticket: Option<([u8; 12], u64)>,
    /// DTLS 1.2 server: the NewSessionTicket of this handshake, once made.
    pub(crate) pending_ticket: Option<
        crate::handshake::handshake_message_new_session_ticket::HandshakeMessageNewSessionTicket,
    >,
    /// DTLS 1.2 client: the id the session of this association is stored under, to forget it
    /// if the association fails (RFC 5246 7.2.2).
    pub(crate) stored_session_id: Option<Vec<u8>>,
    //pub(crate) replay_detector: Vec<Box<dyn ReplayDetector>>,
}

/// What [`State::marshal_binary`] writes. It holds the master secret, so it is zeroized when
/// dropped and has no `Debug`.
#[derive(Archive, Serialize, Deserialize, PartialEq)]
struct SerializedState {
    local_epoch: u16,
    remote_epoch: u16,
    local_random: [u8; HANDSHAKE_RANDOM_LENGTH],
    remote_random: [u8; HANDSHAKE_RANDOM_LENGTH],
    cipher_suite_id: u16,
    master_secret: Vec<u8>,
    sequence_number: u64,
    srtp_protection_profile: u16,
    peer_certificates: Vec<Vec<u8>>,
    identity_hint: Vec<u8>,
    is_client: bool,
    extended_master_secret: bool,
    /// RFC 9146: the connection ids negotiated, as `State` holds them.
    local_connection_id: Option<Vec<u8>>,
    remote_connection_id: Option<Vec<u8>>,
}

impl Drop for SerializedState {
    fn drop(&mut self) {
        self.master_secret.zeroize();
    }
}

/// An rkyv writer that only counts: the size of a serialized value, so that the buffer it is
/// then written to is allocated once at that size and never grows (a buffer that grew would
/// leave a copy of the master secret behind).
struct SerializedLength(usize);

impl rkyv::ser::Positional for SerializedLength {
    fn pos(&self) -> usize {
        self.0
    }
}

impl<E> rkyv::ser::Writer<E> for SerializedLength {
    fn write(&mut self, bytes: &[u8]) -> std::result::Result<(), E> {
        self.0 += bytes.len();
        Ok(())
    }
}

impl State {
    /// The connection id a protected record sent to the peer carries (RFC 9146): `None`
    /// unless the extension was negotiated and the peer asked for a non-empty one.
    pub(crate) fn send_connection_id(&self) -> Option<&[u8]> {
        self.local_connection_id.as_ref()?;
        self.remote_connection_id
            .as_deref()
            .filter(|connection_id| !connection_id.is_empty())
    }

    /// The connection id a protected record from the peer carries, likewise.
    pub(crate) fn receive_connection_id(&self) -> Option<&[u8]> {
        self.remote_connection_id.as_ref()?;
        self.local_connection_id
            .as_deref()
            .filter(|connection_id| !connection_id.is_empty())
    }

    /// Creates the initial handshake state for a connection.
    ///
    /// The crypto provider comes from the caller — `rtci-dtls` never resolves a default. This
    /// replaces the former `Default` impl, which resolved one implicitly only for `DTLSConn::new`
    /// to overwrite it a few lines later.
    pub fn new(crypto_provider: Arc<dyn RTCCryptoProvider>, is_client: bool) -> Self {
        State {
            crypto_provider,
            local_epoch: 0,
            remote_epoch: 0,
            local_sequence_number: vec![],
            local_random: HandshakeRandom::default(),
            remote_random: HandshakeRandom::default(),
            master_secret: SecretVec::new(vec![]),
            cipher_suite: None,

            srtp_protection_profile: SrtpProtectionProfile::Unsupported,
            peer_certificates: vec![],
            identity_hint: vec![],

            is_client,

            pre_master_secret: SecretVec::new(vec![]),
            extended_master_secret: false,

            named_curve: NamedCurve::Unsupported,
            local_keypair: None,
            cookie: vec![],
            handshake_send_sequence: 0,
            handshake_recv_sequence: 0,
            server_name: "".to_string(),
            remote_requested_certificate: false,
            local_certificates_verify: vec![],
            local_verify_data: vec![],
            local_key_signature: vec![],
            peer_certificates_verified: false,
            verified_certificate_verify: None,
            secure_renegotiation: false,
            remote_signature_schemes: vec![],
            remote_certificate_types: vec![],
            remote_offered_point_formats: false,
            application_protocol: None,
            connection_id_offer: None,
            local_connection_id: None,
            remote_connection_id: None,
            local_signature_scheme: None,
            secrets_forgotten: false,
            cookie_verified_by_endpoint: false,
            tls13_offer: None,
            tls13: None,
            negotiated_version: None,
            resumed: false,
            clock: None,
            early_data: vec![],
            early_datagrams: vec![],
            early_data_accepted: None,
            session_id: vec![],
            dtls12_offer: None,
            session_ticket_offer: None,
            resuming: None,
            new_session_ticket: false,
            received_ticket: None,
            issued_ticket: None,
            pending_ticket: None,
            stored_session_id: None,
        }
    }
}

impl State {
    fn serialize(&self) -> Result<SerializedState> {
        // The serialized form is the DTLS 1.2 session (master secret and randoms). A DTLS
        // 1.3 association has neither, and its epochs and traffic secrets are not exported.
        if self.tls13.is_some() {
            return Err(Error::ErrUnsupportedProtocolVersion);
        }
        let mut local_rand = vec![];
        {
            let mut writer = BufWriter::<&mut Vec<u8>>::new(local_rand.as_mut());
            self.local_random.marshal(&mut writer)?;
        }
        let mut remote_rand = vec![];
        {
            let mut writer = BufWriter::<&mut Vec<u8>>::new(remote_rand.as_mut());
            self.remote_random.marshal(&mut writer)?;
        }

        let mut local_random = [0u8; HANDSHAKE_RANDOM_LENGTH];
        let mut remote_random = [0u8; HANDSHAKE_RANDOM_LENGTH];

        local_random.copy_from_slice(&local_rand);
        remote_random.copy_from_slice(&remote_rand);

        let local_epoch = self.local_epoch;
        let remote_epoch = self.remote_epoch;
        let sequence_number = self.local_sequence_number[local_epoch as usize];
        let cipher_suite_id = {
            match &self.cipher_suite {
                Some(cipher_suite) => cipher_suite.id() as u16,
                None => return Err(Error::ErrCipherSuiteUnset),
            }
        };

        Ok(SerializedState {
            local_epoch,
            remote_epoch,
            local_random,
            remote_random,
            cipher_suite_id,
            master_secret: self.master_secret.as_ref().to_vec(),
            sequence_number,
            srtp_protection_profile: self.srtp_protection_profile as u16,
            peer_certificates: self.peer_certificates.clone(),
            identity_hint: self.identity_hint.clone(),
            is_client: self.is_client,
            extended_master_secret: self.extended_master_secret,
            local_connection_id: self.local_connection_id.clone(),
            remote_connection_id: self.remote_connection_id.clone(),
        })
    }

    fn deserialize(&mut self, serialized: &SerializedState) -> Result<()> {
        // Set epoch values
        self.local_epoch = serialized.local_epoch;
        self.remote_epoch = serialized.remote_epoch;
        {
            while self.local_sequence_number.len() <= serialized.local_epoch as usize {
                self.local_sequence_number.push(0);
            }
            self.local_sequence_number[serialized.local_epoch as usize] =
                serialized.sequence_number;
        }

        // Set random values
        let mut reader = Cursor::new(&serialized.local_random);
        self.local_random = HandshakeRandom::unmarshal(&mut reader)?;

        let mut reader = Cursor::new(&serialized.remote_random);
        self.remote_random = HandshakeRandom::unmarshal(&mut reader)?;

        self.is_client = serialized.is_client;
        self.extended_master_secret = serialized.extended_master_secret;
        self.local_connection_id
            .clone_from(&serialized.local_connection_id);
        self.remote_connection_id
            .clone_from(&serialized.remote_connection_id);

        // Set master secret
        self.master_secret = SecretVec::new(serialized.master_secret.clone());

        // Set cipher suite
        self.cipher_suite = Some(cipher_suite_for_id(serialized.cipher_suite_id.into())?);

        self.srtp_protection_profile = serialized.srtp_protection_profile.into();

        // Set remote certificate
        self.peer_certificates
            .clone_from(&serialized.peer_certificates);
        self.identity_hint.clone_from(&serialized.identity_hint);

        Ok(())
    }

    /// Installs the negotiated keys into the cipher suite.
    ///
    /// # Errors
    ///
    /// Fails if the master secret or randoms are not yet available.
    pub fn init_cipher_suite(&mut self) -> Result<()> {
        if let Some(cipher_suite) = &mut self.cipher_suite {
            if cipher_suite.is_initialized() {
                return Ok(());
            }

            let mut local_random = vec![];
            {
                let mut writer = BufWriter::<&mut Vec<u8>>::new(local_random.as_mut());
                self.local_random.marshal(&mut writer)?;
            }
            let mut remote_random = vec![];
            {
                let mut writer = BufWriter::<&mut Vec<u8>>::new(remote_random.as_mut());
                self.remote_random.marshal(&mut writer)?;
            }

            if self.is_client {
                cipher_suite.init(
                    self.crypto_provider.clone(),
                    self.master_secret.as_ref(),
                    &local_random,
                    &remote_random,
                    true,
                )
            } else {
                cipher_suite.init(
                    self.crypto_provider.clone(),
                    self.master_secret.as_ref(),
                    &remote_random,
                    &local_random,
                    false,
                )
            }
        } else {
            Err(Error::ErrCipherSuiteUnset)
        }
    }

    // marshal_binary is a binary.BinaryMarshaler.marshal_binary implementation
    /// Serializes the state, so a connection can be resumed or migrated.
    ///
    /// The bytes hold the session's master secret in the clear: protecting them (and erasing
    /// them) is the caller's responsibility. Nothing this function makes on the way is left
    /// in memory it frees.
    ///
    /// # Errors
    ///
    /// Fails if the state is incomplete.
    pub fn marshal_binary(&self) -> Result<Vec<u8>> {
        let serialized = self.serialize()?;

        let error = |err: rkyv::rancor::Error| Error::Other(err.to_string());
        let length = rkyv::api::high::to_bytes_in::<_, rkyv::rancor::Error>(
            &serialized,
            SerializedLength(0),
        )
        .map_err(error)?
        .0;
        rkyv::api::high::to_bytes_in::<_, rkyv::rancor::Error>(
            &serialized,
            Vec::with_capacity(length),
        )
        .map_err(error)
    }

    // unmarshal_binary is a binary.BinaryUnmarshaler.unmarshal_binary implementation
    /// Restores state previously produced by [`Self::marshal_binary`].
    ///
    /// `data` holds a master secret: erasing it afterwards is the caller's responsibility.
    ///
    /// # Errors
    ///
    /// Fails if `data` is truncated or malformed.
    pub fn unmarshal_binary(&mut self, data: &[u8]) -> Result<()> {
        let serialized: SerializedState =
            match rkyv::access::<ArchivedSerializedState, rkyv::rancor::Error>(data)
                .and_then(rkyv::deserialize)
            {
                Ok(dec) => dec,
                Err(err) => return Err(Error::Other(err.to_string())),
            };
        self.deserialize(&serialized)?;
        self.init_cipher_suite()?;

        Ok(())
    }

    /// Forgets the session's secrets: the master secret and the premaster secret are
    /// overwritten and dropped (RFC 5246 7.2.2 for a failed connection, 8.1 for the premaster
    /// secret once the master secret exists). Nothing can be exported or resumed afterwards.
    pub(crate) fn forget_secrets(&mut self) {
        self.secrets_forgotten = true;
        self.tls13_offer = None;
        // DTLS 1.2 sessions hold a master secret too (zeroed as they drop).
        self.dtls12_offer = None;
        self.resuming = None;
        if let Some((_, exporter_secret)) = &mut self.tls13 {
            *exporter_secret = SecretVec::new(vec![]);
        }
        self.forget_pre_master_secret();
        // Replacing a `SecretVec` zeroizes the one replaced.
        self.master_secret = SecretVec::new(vec![]);
    }

    /// Overwrites and drops the premaster secret.
    pub(crate) fn forget_pre_master_secret(&mut self) {
        self.pre_master_secret = SecretVec::new(vec![]);
    }

    /// The SRTP protection profile negotiated through `use_srtp`.
    pub fn srtp_protection_profile(&self) -> SrtpProtectionProfile {
        self.srtp_protection_profile
    }

    /// The application protocol Application-Layer Protocol Negotiation selected (RFC 7301;
    /// [`ConfigBuilder::with_alpn_protocols`](crate::config::ConfigBuilder::with_alpn_protocols)),
    /// once the handshake has settled it: `None` when either side used no ALPN. Not kept by
    /// [`marshal_binary`](Self::marshal_binary).
    pub fn application_protocol(&self) -> Option<&str> {
        self.application_protocol.as_deref()
    }

    /// The DTLS version the handshake negotiated, once it has: `None` before the ServerHello.
    /// [`DtlsVersion::protocol_version`](crate::config::DtlsVersion::protocol_version) gives
    /// the two bytes webrtc-stats reports as `tlsVersion` (`FEFD` for DTLS 1.2, `FEFC` for
    /// DTLS 1.3).
    pub fn negotiated_version(&self) -> Option<crate::config::DtlsVersion> {
        self.negotiated_version
    }

    /// Whether the handshake resumed a session rather than authenticating with certificates:
    /// a DTLS 1.3 one made with a pre-shared key, a ticket of an earlier session or an
    /// external PSK (RFC 8446 section 2.2), or a DTLS 1.2 abbreviated handshake (RFC 5246
    /// section 7.3, by session id or RFC 5077 ticket).
    pub fn resumed(&self) -> bool {
        self.resumed
    }

    /// DTLS 1.3 client and server: whether the 0-RTT data was accepted (RFC 8446 section
    /// 4.2.10), once the server's EncryptedExtensions has said; `None` when none was offered.
    /// Data that was not accepted was not delivered: the application may send it again.
    pub fn early_data_accepted(&self) -> Option<bool> {
        self.early_data_accepted
    }

    /// Whether this endpoint took the client role.
    pub fn is_client(&self) -> bool {
        self.is_client
    }

    /// The active cipher suite, once one has been negotiated.
    pub fn cipher_suite(&self) -> Option<&dyn CipherSuite> {
        self.cipher_suite.as_deref()
    }

    /// Whether the negotiated cipher suite authenticates with a pre-shared key.
    pub fn is_cipher_suite_psk(&self) -> bool {
        self.cipher_suite
            .as_ref()
            .is_some_and(|cipher_suite| cipher_suite.is_psk())
    }

    /// Exports `length` bytes of keying material from an established session, as defined in
    /// RFC 5705.
    ///
    /// # Errors
    ///
    /// Returns an error before the handshake completes, when the label is reserved by TLS,
    /// when the negotiated cipher suite is unavailable, and for DTLS 1.2 when `context` is
    /// non-empty or the session was established without the extended master secret: such a
    /// master secret is not bound to the handshake, and RFC 7627 5.4 forbids exporting from
    /// it.
    ///
    /// For DTLS 1.3 this is the exporter of RFC 8446 section 7.5, which always takes a
    /// context (the empty one by default): DTLS-SRTP keys are exported the same way from
    /// either version, with the label `EXTRACTOR-dtls_srtp` and no context.
    pub fn export_keying_material(
        &self,
        label: &str,
        context: &[u8],
        length: usize,
    ) -> Result<SecretVec> {
        if let Some((suite, exporter_secret)) = &self.tls13 {
            if self.secrets_forgotten || exporter_secret.is_empty() {
                return Err(Error::ErrConnClosed);
            }
            if INVALID_KEYING_LABELS.contains(&label) {
                return Err(Error::ReservedExportKeyingMaterial);
            }
            return crate::dtls13::key_schedule::export_keying_material(
                self.crypto_provider.crypto(),
                *suite,
                exporter_secret.as_ref(),
                label,
                context,
                length,
            );
        }
        if self.local_epoch == 0 {
            return Err(Error::HandshakeInProgress);
        } else if !context.is_empty() {
            return Err(Error::ContextUnsupported);
        } else if INVALID_KEYING_LABELS.contains(&label) {
            return Err(Error::ReservedExportKeyingMaterial);
        } else if !self.extended_master_secret {
            return Err(Error::ErrExportWithoutExtendedMasterSecret);
        } else if self.secrets_forgotten {
            // The association failed and its secrets were forgotten (RFC 5246 7.2.2).
            return Err(Error::ErrConnClosed);
        }

        let mut local_random = vec![];
        {
            let mut writer = BufWriter::<&mut Vec<u8>>::new(local_random.as_mut());
            self.local_random.marshal(&mut writer)?;
        }
        let mut remote_random = vec![];
        {
            let mut writer = BufWriter::<&mut Vec<u8>>::new(remote_random.as_mut());
            self.remote_random.marshal(&mut writer)?;
        }

        let mut seed = label.as_bytes().to_vec();
        if self.is_client {
            seed.extend_from_slice(&local_random);
            seed.extend_from_slice(&remote_random);
        } else {
            seed.extend_from_slice(&remote_random);
            seed.extend_from_slice(&local_random);
        }

        if let Some(cipher_suite) = &self.cipher_suite {
            let provider = self.crypto_provider.as_ref();
            prf_p_hash(
                provider.crypto(),
                self.master_secret.as_ref(),
                &seed,
                length,
                cipher_suite.hash_func(),
            )
            .map_err(|err| Error::Hash(err.to_string()))
        } else {
            Err(Error::CipherSuiteUnset)
        }
    }
}