rtci-dtls 0.5.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
//! DTLS 1.3 0-RTT data (RFC 8446 sections 2.3, 4.2.10 and 8; RFC 9147 sections 5.6 and 6.1):
//! sent with the ClientHello under a ticket that allows it, taken by the server only where
//! it can tell the ClientHello is not a replay (the ticket used once, its age fresh), and
//! never after a HelloRetryRequest.

use super::conn::EPOCH_EARLY;
use super::handshake_test::*;
use super::messages::alert;
use crate::config::HandshakeConfig;
use crate::endpoint::{Endpoint, EndpointEvent};
use crate::session::{MemorySessionStore, SessionStore};
use bytes::BytesMut;
use shared::TransportProtocol;
use shared::error::Result;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};

const NAME: &str = "localhost";

fn store() -> Arc<MemorySessionStore> {
    Arc::new(MemorySessionStore::new())
}

fn client(store: &Arc<MemorySessionStore>) -> Result<Arc<HandshakeConfig>> {
    Ok(Arc::new(
        client_builder()
            .with_server_name(NAME.to_owned())
            .with_session_store(Some(store.clone()))
            .build(true, None)?,
    ))
}

/// A server that issues tickets allowing `max` bytes of 0-RTT data, without the cookie
/// exchange (or 0-RTT would never be taken: a HelloRetryRequest rules it out).
fn early_server(max: u32, cookie_exchange: bool) -> Result<Arc<HandshakeConfig>> {
    Ok(Arc::new(
        server_builder()
            .with_session_tickets(1)
            .with_max_early_data(max)
            .with_cookie_exchange(cookie_exchange)
            .build(false, None)?,
    ))
}

/// A pair whose client connects at `now` with `early` as 0-RTT data.
fn early_pair(
    client: Arc<HandshakeConfig>,
    server: Arc<HandshakeConfig>,
    now: Instant,
    early: &[u8],
) -> Result<Pair> {
    let mut pair = Pair {
        client: Endpoint::new(client_addr(), TransportProtocol::UDP, None),
        server: Endpoint::new(server_addr(), TransportProtocol::UDP, Some(server)),
        now,
        client_complete: false,
        server_complete: false,
        client_error: None,
        server_error: None,
        to_client: vec![],
        to_server: vec![],
    };
    pair.client
        .connect_with_early_data(now, server_addr(), client, None, early)?;
    Ok(pair)
}

fn early_data(events: &[EndpointEvent]) -> Vec<Vec<u8>> {
    events
        .iter()
        .filter_map(|event| match event {
            EndpointEvent::EarlyData(data) => Some(data.to_vec()),
            _ => None,
        })
        .collect()
}

fn accepted(pair: &Pair) -> (Option<bool>, Option<bool>) {
    (
        pair.client
            .get_connection_state(server_addr())
            .and_then(|state| state.early_data_accepted()),
        pair.server
            .get_connection_state(client_addr())
            .and_then(|state| state.early_data_accepted()),
    )
}

/// RFC 8446 section 2.3: with a ticket that allows it, the client's data goes with its
/// ClientHello, in epoch 1, and the server has it before the handshake is complete. The
/// handshake completes as a resumption; once a record of the client's epoch 3 arrives the
/// server keeps no epoch 1 keys (RFC 9147 section 5.6).
#[test]
fn early_data_arrives_with_the_client_hello() -> Result<()> {
    let store = store();
    let (client, server) = (client(&store)?, early_server(1024, false)?);
    let start = Instant::now();
    let _ = early_pair(client.clone(), server.clone(), start, &[])?.complete();
    assert_eq!(
        store.take(NAME).map(|session| session.max_early_data()),
        Some(1024)
    );
    let _ = early_pair(client.clone(), server.clone(), start, &[])?.complete();

    let mut pair = early_pair(
        client,
        server,
        start + Duration::from_secs(1),
        b"zero round trips",
    )?;
    let first = take(&mut pair.client);
    assert_eq!(first.len(), 2, "the ClientHello, then the 0-RTT record");
    assert_eq!(first[1][0] & 0x03, 1, "epoch 1");
    pair.deliver_to_server(first);
    assert!(!pair.server_complete);
    assert_eq!(early_data(&pair.to_server), [b"zero round trips".to_vec()]);
    assert!(pair.server_conn().has_read_epoch(EPOCH_EARLY));
    let mut pair = pair.complete();
    assert_eq!(accepted(&pair), (Some(true), Some(true)));
    assert!(pair.server_conn().resumed);
    // The client's first records of epoch 3 (its ACK) ended epoch 1.
    assert!(!pair.server_conn().has_read_epoch(EPOCH_EARLY));
    assert_eq!(pair.client_sends(b"1-rtt"), vec![b"1-rtt".to_vec()]);
    assert_eq!(
        early_data(&pair.to_server),
        Vec::<Vec<u8>>::new(),
        "not twice"
    );
    Ok(())
}

/// RFC 8446 section 8.1: the ClientHello and its 0-RTT record, sent again (to this server
/// from another address, or to another server with the same configuration), get no 0-RTT:
/// the ticket has been used.
#[test]
fn a_replayed_client_hello_gets_no_early_data() -> Result<()> {
    let store = store();
    let (client, server) = (client(&store)?, early_server(1024, false)?);
    let now = Instant::now();
    let _ = early_pair(client.clone(), server.clone(), now, &[])?.complete();
    let mut pair = early_pair(client, server.clone(), now, b"transfer 100")?;
    let first = take(&mut pair.client);
    pair.deliver_to_server(first.clone());
    assert_eq!(early_data(&pair.to_server), [b"transfer 100".to_vec()]);

    let attacker: SocketAddr = "127.0.0.1:7777".parse().unwrap();
    let mut replayed = vec![];
    for datagram in first.clone() {
        replayed.extend(pair.server.read(now, attacker, None, datagram)?);
    }
    assert!(early_data(&replayed).is_empty(), "the same server");
    let mut other = Endpoint::new(server_addr(), TransportProtocol::UDP, Some(server));
    let mut replayed = vec![];
    for datagram in first {
        replayed.extend(other.read(now, attacker, None, datagram)?);
    }
    assert!(
        early_data(&replayed).is_empty(),
        "another server of the configuration"
    );
    Ok(())
}

/// RFC 8446 section 8 (7.5 of the audit): "The server MUST ensure that any instance of it
/// (be it a machine, a thread, or any other entity within the relevant serving
/// infrastructure) would accept 0-RTT for the same 0-RTT handshake at most once." The
/// instances that can open a ticket are the configurations holding its issuer's keys, which
/// are random and never leave the process; configurations given one issuer
/// (`with_session_ticket_issuer`) share its record of tickets used. The ClientHello and 0-RTT
/// record one of them took get no 0-RTT from another, nor from a third built from the same
/// issuer later.
#[test]
fn configurations_sharing_an_issuer_take_a_0rtt_handshake_once_between_them() -> Result<()> {
    let store = store();
    let client = client(&store)?;
    let issuer = crate::session::SessionTicketIssuer::new(
        provider().as_ref(),
        1,
        Duration::from_secs(3600),
    )?;
    let server = |issuer: &crate::session::SessionTicketIssuer| -> Result<Arc<HandshakeConfig>> {
        Ok(Arc::new(
            server_builder()
                .with_session_ticket_issuer(Some(issuer.clone()))
                .with_max_early_data(1024)
                .with_cookie_exchange(false)
                .build(false, None)?,
        ))
    };
    let (first, second) = (server(&issuer)?, server(&issuer)?);
    let now = Instant::now();
    let _ = early_pair(client.clone(), first.clone(), now, &[])?.complete();
    let mut pair = early_pair(client, first, now, b"transfer 100")?;
    let hello = take(&mut pair.client);
    pair.deliver_to_server(hello.clone());
    assert_eq!(early_data(&pair.to_server), [b"transfer 100".to_vec()]);

    let attacker: SocketAddr = "127.0.0.1:7777".parse().unwrap();
    for other in [second, server(&issuer)?] {
        let mut instance = Endpoint::new(server_addr(), TransportProtocol::UDP, Some(other));
        let mut replayed = vec![];
        for datagram in hello.clone() {
            replayed.extend(instance.read(now, attacker, None, datagram)?);
        }
        assert!(early_data(&replayed).is_empty(), "another instance");
    }
    Ok(())
}

/// RFC 8446 section 4.2.10: a ClientHello after a HelloRetryRequest has no early_data, so
/// with the cookie exchange the 0-RTT data is not taken, and the resumption goes on.
#[test]
fn after_a_hello_retry_request_there_is_no_early_data() -> Result<()> {
    let store = store();
    let (client, server) = (client(&store)?, early_server(1024, true)?);
    let now = Instant::now();
    let _ = early_pair(client.clone(), server.clone(), now, &[])?.complete();
    let mut pair = early_pair(client, server, now, b"too early")?.complete();
    assert!(early_data(&pair.to_server).is_empty());
    assert_eq!(accepted(&pair), (Some(false), None));
    assert!(pair.server_conn().resumed);
    not_resent(&mut pair, b"too early");
    Ok(())
}

/// RFC 8446 section 4.2.2: a server that sends a HelloRetryRequest statelessly may receive
/// the client's 0-RTT records afterwards, and "Servers operating statelessly MUST ignore these
/// records." With the cookie exchange this server keeps nothing for the client until a
/// ClientHello carries its cookie: the 0-RTT record that follows the first ClientHello is
/// read without an error, makes no association, raises no event and draws nothing; the
/// ClientHello alone is answered (with the HelloRetryRequest).
#[test]
fn a_stateless_server_ignores_0rtt_records() -> Result<()> {
    let store = store();
    let (client, server) = (client(&store)?, early_server(1024, true)?);
    let now = Instant::now();
    let _ = early_pair(client.clone(), server.clone(), now, &[])?.complete();
    let mut pair = early_pair(client, server, now, b"too early")?;
    let first = take(&mut pair.client);
    assert_eq!(first.len(), 2, "the ClientHello, then the 0-RTT record");
    let mut stateless = Endpoint::new(
        server_addr(),
        TransportProtocol::UDP,
        Some(early_server(1024, true)?),
    );
    let hello = stateless.read(now, client_addr(), None, first[0].clone())?;
    let answer = take(&mut stateless);
    assert_eq!(answer.len(), 1, "the HelloRetryRequest");
    assert!(hello.is_empty());
    assert!(stateless.get_connection_state(client_addr()).is_none());
    let early = stateless.read(now, client_addr(), None, first[1].clone())?;
    assert!(early.is_empty(), "no event: {}", early.len());
    assert!(take(&mut stateless).is_empty(), "nothing is sent for it");
    assert!(stateless.get_connection_state(client_addr()).is_none());
    assert!(!stateless.is_connection_failed(&client_addr()));
    Ok(())
}

/// A ticket that allows no 0-RTT data (the server takes none) is not offered any: the
/// ClientHello goes alone.
#[test]
fn without_max_early_data_none_is_offered() -> Result<()> {
    let store = store();
    let (client, server) = (client(&store)?, early_server(0, false)?);
    let now = Instant::now();
    let _ = early_pair(client.clone(), server.clone(), now, &[])?.complete();
    let mut pair = early_pair(client, server, now, b"nothing")?;
    assert_eq!(take(&mut pair.client).len(), 1);
    Ok(())
}

/// RFC 8446 section 8.3: a ticket age that does not agree with the server's view, by more
/// than the window, rules 0-RTT out; the handshake goes on (section 4.2.10) and resumes.
#[test]
fn a_ticket_age_out_of_the_window_rules_out_early_data() -> Result<()> {
    let store = store();
    let (client, server) = (client(&store)?, early_server(1024, false)?);
    let now = Instant::now();
    let _ = early_pair(client.clone(), server.clone(), now, &[])?.complete();
    let mut session = store.take(NAME).expect("a ticket");
    session.age_add = session.age_add.wrapping_add(20_000);
    store.put(NAME, session);
    let mut pair = early_pair(client, server, now, b"stale")?.complete();
    assert!(early_data(&pair.to_server).is_empty());
    assert_eq!(accepted(&pair), (Some(false), Some(false)));
    assert!(pair.server_conn().resumed);
    not_resent(&mut pair, b"stale");
    Ok(())
}

/// RFC 8446 section 4.2.10: "A TLS implementation MUST NOT automatically resend early data
/// unless the negotiated connection selects the same ALPN protocol." This one never resends
/// it: 0-RTT data the server did not take does not reach it as application data, neither
/// during the handshake nor once the client writes again.
fn not_resent(pair: &mut Pair, early: &[u8]) {
    assert!(
        application_data(&pair.to_server)
            .iter()
            .all(|data| data != early),
        "the rejected early data was sent again"
    );
    assert_eq!(pair.client_sends(b"after"), vec![b"after".to_vec()]);
}

/// RFC 8446 section 4.6.1: more 0-RTT data than the ticket allows ends the handshake with
/// unexpected_message.
#[test]
fn more_early_data_than_allowed_is_an_unexpected_message() -> Result<()> {
    let store = store();
    let (client, server) = (client(&store)?, early_server(16, false)?);
    let now = Instant::now();
    let _ = early_pair(client.clone(), server.clone(), now, &[])?.complete();
    let mut session = store.take(NAME).expect("a ticket");
    session.max_early_data = 1024;
    store.put(NAME, session);
    let mut pair = early_pair(client, server, now, &[7; 100])?;
    let first = take(&mut pair.client);
    pair.deliver_to_server(first);
    assert!(early_data(&pair.to_server).is_empty());
    assert!(pair.server.is_connection_failed(&client_addr()));
    let _ = alert::UNEXPECTED_MESSAGE;
    Ok(())
}

/// RFC 8446 section 4.2.11: early_data in EncryptedExtensions with a selected_identity
/// other than 0 is an illegal_parameter ("If any other value is returned, the client MUST
/// abort the handshake with an "illegal_parameter" alert"): the client fails with that
/// alert sent, and none received.
#[test]
fn accepted_early_data_with_another_identity_is_an_illegal_parameter() -> Result<()> {
    let store = store();
    let (client, server) = (client(&store)?, early_server(1024, false)?);
    let now = Instant::now();
    let _ = early_pair(client.clone(), server.clone(), now, &[])?.complete();
    let mut pair = early_pair(client, server, now, b"x")?;
    let first = take(&mut pair.client);
    pair.deliver_to_server(first);
    let flight = take(&mut pair.server);
    // The ServerHello alone first, then the client is made to believe it selected another.
    let split = 13 + u16::from_be_bytes([flight[0][11], flight[0][12]]) as usize;
    pair.deliver_to_client(vec![BytesMut::from(&flight[0][..split])]);
    pair.client_conn().psk_index = Some(1);
    pair.deliver_to_client(vec![BytesMut::from(&flight[0][split..])]);
    assert!(pair.client.is_connection_failed(&server_addr()));
    assert!(!pair.client_complete);
    assert_eq!(
        pair.client.connection_fatal_alerts(&server_addr()),
        Some((Some(alert::ILLEGAL_PARAMETER), None))
    );
    Ok(())
}

/// A server of DTLS 1.2 only, which never takes 0-RTT data.
fn dtls12_server() -> Result<Arc<HandshakeConfig>> {
    use crate::config::DtlsVersion::Dtls1_2;
    Ok(Arc::new(
        server_builder()
            .with_protocol_versions(Dtls1_2, Dtls1_2)
            .with_cookie_exchange(false)
            .build(false, None)?,
    ))
}

/// RFC 8446 appendix D.2: "A client that attempts to send 0-RTT data MUST fail a connection
/// if it receives a ServerHello with TLS 1.2 or older." A client holding a DTLS 1.3 ticket
/// that allows 0-RTT sends its data with the ClientHello; a DTLS 1.2 ServerHello ends the
/// association with protocol_version. The same client without 0-RTT data goes on in DTLS 1.2
/// with the same server, so it is the 0-RTT data that fails it.
#[test]
fn a_client_that_sent_early_data_fails_on_a_dtls_1_2_server_hello() -> Result<()> {
    use crate::config::DtlsVersion;
    let store = store();
    let client = client(&store)?;
    let now = Instant::now();
    let _ = early_pair(client.clone(), early_server(1024, false)?, now, &[])?.complete();

    let mut pair = early_pair(client.clone(), dtls12_server()?, now, b"too early")?;
    let first = take(&mut pair.client);
    assert_eq!(first.len(), 2, "the ClientHello, then the 0-RTT record");
    pair.deliver_to_server(first);
    let flight = take(&mut pair.server);
    assert!(!flight.is_empty(), "the DTLS 1.2 server answers");
    pair.deliver_to_client(flight);
    assert!(pair.client.is_connection_failed(&server_addr()));
    assert!(!pair.client_complete);
    assert_eq!(
        pair.client.connection_fatal_alerts(&server_addr()),
        Some((Some(alert::PROTOCOL_VERSION), None))
    );

    // Control: a fresh ticket, no 0-RTT data, the same DTLS 1.2 server.
    let _ = early_pair(client.clone(), early_server(1024, false)?, now, &[])?.complete();
    let mut pair = early_pair(client, dtls12_server()?, now, &[])?;
    assert_eq!(take_and_count(&mut pair), 1, "the ClientHello alone");
    pair.run();
    assert!(pair.client_complete && pair.server_complete);
    assert_eq!(
        pair.versions(),
        (Some(DtlsVersion::Dtls1_2), Some(DtlsVersion::Dtls1_2))
    );
    Ok(())
}

/// Delivers what the client has queued to the server and says how many datagrams it was.
fn take_and_count(pair: &mut Pair) -> usize {
    let first = take(&mut pair.client);
    let count = first.len();
    pair.deliver_to_server(first);
    count
}

/// RFC 8446 appendix D.1: "0-RTT data ... SHOULD NOT be sent absent knowledge that the
/// server supports TLS 1.3." Only a DTLS 1.3 ticket that allows it is that knowledge: a client
/// that holds only a DTLS 1.2 session (and has never seen the server speak DTLS 1.3) sends its
/// ClientHello alone, even when the application hands it 0-RTT data.
#[test]
fn no_early_data_is_sent_without_a_dtls_1_3_ticket() -> Result<()> {
    let store = store();
    let client = client(&store)?;
    let now = Instant::now();
    let dtls12_resuming = Arc::new(
        server_builder()
            .with_protocol_versions(
                crate::config::DtlsVersion::Dtls1_2,
                crate::config::DtlsVersion::Dtls1_2,
            )
            .with_cookie_exchange(false)
            .with_dtls12_resumption(true)
            .with_session_tickets(1)
            .build(false, None)?,
    );
    let _ = early_pair(client.clone(), dtls12_resuming.clone(), now, &[])?.complete();
    let session = store
        .take_dtls12(NAME)
        .expect("a DTLS 1.2 session is cached");
    store.put_dtls12(NAME, session);
    assert!(store.take(NAME).is_none(), "and no DTLS 1.3 ticket");
    let mut pair = early_pair(client, dtls12_resuming, now, b"nothing yet")?;
    assert_eq!(take(&mut pair.client).len(), 1, "the ClientHello alone");
    Ok(())
}

/// RFC 8446 section 4.2.10: 0-RTT is taken only with the cipher suite of the handshake that
/// made the ticket. A client that now prefers another suite of the same hash resumes, without
/// 0-RTT.
#[test]
fn early_data_needs_the_suite_of_the_ticket() -> Result<()> {
    use crate::cipher_suite::CipherSuiteId;
    let store = store();
    let server = early_server(1024, false)?;
    let now = Instant::now();
    let _ = early_pair(client(&store)?, server.clone(), now, &[])?.complete();
    let chacha_first = Arc::new(
        client_builder()
            .with_server_name(NAME.to_owned())
            .with_session_store(Some(store.clone()))
            .with_cipher_suites(vec![
                CipherSuiteId::Tls_ChaCha20_Poly1305_Sha256,
                CipherSuiteId::Tls_Aes_128_Gcm_Sha256,
            ])
            .build(true, None)?,
    );
    let mut pair = early_pair(chacha_first, server, now, b"other suite")?.complete();
    assert_eq!(
        pair.server_conn().suite.map(|suite| suite.id),
        Some(CipherSuiteId::Tls_ChaCha20_Poly1305_Sha256)
    );
    assert!(pair.server_conn().resumed);
    assert!(early_data(&pair.to_server).is_empty());
    assert_eq!(accepted(&pair), (Some(false), Some(false)));
    Ok(())
}