rtci-dtls 0.4.1

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
//! A forged ChangeCipherSpec (sec-9). The handshake's ChangeCipherSpec is sent under the cipher
//! state it changes from (RFC 5246 section 7.1): in DTLS 1.2 it is an epoch-0 record, and this
//! stack does not renegotiate, so no ChangeCipherSpec of a later epoch is ever the peer's. One
//! that claims a protected epoch has to authenticate like any other record of that epoch, and
//! one that does not is invalid and silently discarded (RFC 6347 sections 4.1.2.1 and 4.1.2.7):
//! no alert, no failure, no move of the replay window, no effect on the newest authenticated
//! record that RFC 9146 section 6 address migration compares against. The record ciphers used
//! to hand a ChangeCipherSpec back unopened, so one forged at the current epoch counted as
//! authenticated: with any body but `01` it drew a fatal decode_error and ended the association;
//! with `01` and the largest sequence number it pinned the newest authenticated record, so the
//! association could never follow its peer to a new address.
//!
//! Every DTLS 1.2 cipher family (AES-GCM, ChaCha20-Poly1305, AES-CCM, AES-CCM-8, AES-CBC), the
//! PSK suites, both roles, with and without connection ids, after a full and after a resumed
//! handshake, and during the handshake.

use crate::cipher_suite::CipherSuiteId;
use crate::config::{ConfigBuilder, DtlsVersion};
use crate::content::ContentType;
use crate::dtls13::handshake_test::{
    Pair, application_data, client_addr, client_builder, provider, server_addr, server_builder,
    take,
};
use crate::endpoint::Endpoint;
use crate::session::{MemorySessionCache, MemorySessionStore};
use bytes::BytesMut;
use shared::error::Result;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Instant;

const CERTIFICATE_SUITES: [CipherSuiteId; 5] = [
    CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256,
    CipherSuiteId::Tls_Ecdhe_Ecdsa_With_ChaCha20_Poly1305_Sha256,
    CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Ccm,
    CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Ccm_8,
    CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_256_Cbc_Sha,
];

const PSK_SUITES: [CipherSuiteId; 3] = [
    CipherSuiteId::Tls_Psk_With_Aes_128_Gcm_Sha256,
    CipherSuiteId::Tls_Psk_With_Aes_128_Ccm,
    CipherSuiteId::Tls_Psk_With_Aes_128_Ccm_8,
];

/// The largest DTLS record sequence number (48 bits).
const LAST_SEQUENCE_NUMBER: u64 = (1 << 48) - 1;

const TLS12_CID: u8 = 25;

fn psk(_identity_hint: &[u8]) -> Result<Vec<u8>> {
    Ok(vec![0xab, 0xcd, 0xef])
}

fn is_psk(suite: CipherSuiteId) -> bool {
    PSK_SUITES.contains(&suite)
}

/// A DTLS 1.2 client and server that offer only `suite`, with `connection_id` asked for on
/// both sides.
fn builders(suite: CipherSuiteId, connection_id: Option<usize>) -> (ConfigBuilder, ConfigBuilder) {
    let (client, server) = if is_psk(suite) {
        (
            client_builder()
                .with_psk(Some(Arc::new(psk)))
                .with_psk_identity_hint(Some(b"sec-9".to_vec())),
            ConfigBuilder::default()
                .with_crypto_provider(provider())
                .with_psk(Some(Arc::new(psk))),
        )
    } else {
        (client_builder(), server_builder())
    };
    let dtls12 = |builder: ConfigBuilder| {
        builder
            .with_protocol_versions(DtlsVersion::Dtls1_2, DtlsVersion::Dtls1_2)
            .with_cipher_suites(vec![suite])
            .with_connection_id(connection_id)
    };
    (dtls12(client), dtls12(server))
}

fn completed(suite: CipherSuiteId, connection_id: Option<usize>) -> Result<Pair> {
    let (client, server) = builders(suite, connection_id);
    Ok(Pair::new(client, server)?.complete())
}

/// A ChangeCipherSpec record in the ordinary DTLS 1.2 format: content type 20, DTLS 1.2,
/// `epoch`, `sequence_number`, then `body` (a genuine one is the single byte 1).
fn change_cipher_spec(epoch: u16, sequence_number: u64, body: &[u8]) -> BytesMut {
    let mut record = vec![ContentType::ChangeCipherSpec as u8, 0xfe, 0xfd];
    record.extend_from_slice(&epoch.to_be_bytes());
    record.extend_from_slice(&sequence_number.to_be_bytes()[2..]);
    record.extend_from_slice(&(body.len() as u16).to_be_bytes());
    record.extend_from_slice(body);
    BytesMut::from(&record[..])
}

/// A `tls12_cid` record under `connection_id` (RFC 9146 section 4) whose protected part is
/// `body`: what anyone who saw the association's records can address to it.
fn tls12_cid_record(connection_id: &[u8], sequence_number: u64, body: &[u8]) -> BytesMut {
    let mut record = vec![TLS12_CID, 0xfe, 0xfd, 0x00, 0x01];
    record.extend_from_slice(&sequence_number.to_be_bytes()[2..]);
    record.extend_from_slice(connection_id);
    record.extend_from_slice(&(body.len() as u16).to_be_bytes());
    record.extend_from_slice(body);
    BytesMut::from(&record[..])
}

/// The forged ChangeCipherSpecs: every body (malformed `02`, the genuine `01`, empty, longer
/// than one byte with a valid or an invalid first byte) at the current epoch, the epoch before
/// (0), the next (2) and the last (65535), each with a fresh sequence number far ahead of the
/// genuine records; and the genuine body at the current epoch with the largest sequence number.
fn forgeries() -> Vec<(String, BytesMut)> {
    let bodies: [(&str, Vec<u8>); 5] = [
        ("malformed body 02", vec![0x02]),
        ("valid body 01", vec![0x01]),
        ("empty body", vec![]),
        ("48-byte body starting 01", vec![0x01; 48]),
        ("300-byte body of 02", vec![0x02; 300]),
    ];
    let mut forged = vec![];
    let mut sequence_number = 1_000_000;
    for epoch in [1u16, 0, 2, u16::MAX] {
        for (name, body) in &bodies {
            forged.push((
                format!("ChangeCipherSpec, epoch {epoch}, {name}"),
                change_cipher_spec(epoch, sequence_number, body),
            ));
            sequence_number += 1;
        }
    }
    forged.push((
        "ChangeCipherSpec, epoch 1, body 01, the largest sequence number".to_owned(),
        change_cipher_spec(1, LAST_SEQUENCE_NUMBER, &[0x01]),
    ));
    forged
}

/// The victim of a forgery and the peer it is associated with: the server (its peer is the
/// client), or the client.
struct Sides<'a> {
    now: Instant,
    victim: &'a mut Endpoint,
    victim_addr: SocketAddr,
    sender: &'a mut Endpoint,
    sender_addr: SocketAddr,
}

fn sides(pair: &mut Pair, into_server: bool) -> Sides<'_> {
    if into_server {
        Sides {
            now: pair.now,
            victim: &mut pair.server,
            victim_addr: server_addr(),
            sender: &mut pair.client,
            sender_addr: client_addr(),
        }
    } else {
        Sides {
            now: pair.now,
            victim: &mut pair.client,
            victim_addr: client_addr(),
            sender: &mut pair.server,
            sender_addr: server_addr(),
        }
    }
}

/// What a discarded record must leave as it was.
#[derive(Debug, PartialEq, Eq)]
struct Snapshot {
    newest_authenticated_record: Option<(u16, u64)>,
    authenticated_records: u64,
    remote_epoch: u16,
    failed: bool,
}

fn snapshot(endpoint: &mut Endpoint, peer: SocketAddr, what: &str) -> Snapshot {
    let conn = endpoint
        .connection_mut(&peer)
        .unwrap_or_else(|| panic!("{what}: the association is gone"));
    Snapshot {
        newest_authenticated_record: conn.newest_authenticated_record,
        authenticated_records: conn.authenticated_records,
        remote_epoch: conn.state.remote_epoch,
        failed: conn.is_failed(),
    }
}

/// Reads `forged` at `victim` from `peer` and checks it was discarded: no error, no event, no
/// datagram sent (no alert), the association still there and in the state it was in.
fn assert_discarded(
    now: Instant,
    victim: &mut Endpoint,
    peer: SocketAddr,
    forged: BytesMut,
    what: &str,
) {
    let before = snapshot(victim, peer, what);
    match victim.read(now, peer, None, forged) {
        Ok(events) => assert!(
            events.is_empty(),
            "{what}: reported as {} event(s)",
            events.len()
        ),
        Err(err) => panic!("{what}: the read failed: {err}"),
    }
    let answered = take(victim);
    assert!(
        answered.is_empty(),
        "{what}: answered with {} datagram(s), first bytes {:?}",
        answered.len(),
        answered
            .iter()
            .map(|d| d.first().copied())
            .collect::<Vec<_>>()
    );
    assert_eq!(
        snapshot(victim, peer, what),
        before,
        "{what}: changed the association"
    );
}

/// Injects `forged` into one side of a completed association, then checks the association
/// still carries data both ways, and that the replay window did not move: a genuine record
/// sent before one already read, still inside the window, is delivered after the forgeries.
fn inject_after_handshake(
    pair: &mut Pair,
    into_server: bool,
    forged: Vec<(String, BytesMut)>,
    label: &str,
) -> Result<()> {
    let role = if into_server { "server" } else { "client" };
    let s = sides(pair, into_server);
    s.sender.write(s.now, s.victim_addr, b"older")?;
    let older = take(s.sender);
    s.sender.write(s.now, s.victim_addr, b"newer")?;
    let newer = take(s.sender);
    let mut delivered = vec![];
    for datagram in newer {
        delivered.extend(s.victim.read(s.now, s.sender_addr, None, datagram)?);
    }
    assert_eq!(application_data(&delivered), vec![b"newer".to_vec()]);

    for (name, record) in forged {
        assert_discarded(
            s.now,
            s.victim,
            s.sender_addr,
            record,
            &format!("{label}, into the {role}: {name}"),
        );
    }

    let mut delivered = vec![];
    for datagram in older {
        delivered.extend(s.victim.read(s.now, s.sender_addr, None, datagram)?);
    }
    assert_eq!(
        application_data(&delivered),
        vec![b"older".to_vec()],
        "{label}, into the {role}: a record inside the replay window was refused after the \
         forgeries"
    );

    assert_eq!(
        pair.client_sends(b"up"),
        vec![b"up".to_vec()],
        "{label}, into the {role}"
    );
    assert_eq!(
        pair.server_sends(b"down"),
        vec![b"down".to_vec()],
        "{label}, into the {role}"
    );
    assert!(
        pair.client_error.is_none() && pair.server_error.is_none(),
        "{label}, into the {role}: {:?} {:?}",
        pair.client_error,
        pair.server_error
    );
    Ok(())
}

/// RFC 6347 4.1.2.7, RFC 5246 7.1: after the handshake a forged ChangeCipherSpec, at any
/// epoch and with any body, is discarded without an alert by either side, for every cipher
/// family and the PSK suites, and the association goes on.
#[test]
fn a_forged_change_cipher_spec_does_not_end_an_established_association() -> Result<()> {
    for suite in CERTIFICATE_SUITES.into_iter().chain(PSK_SUITES) {
        for into_server in [true, false] {
            let mut pair = completed(suite, None)?;
            inject_after_handshake(&mut pair, into_server, forgeries(), &format!("{suite}"))?;
        }
    }
    Ok(())
}

/// RFC 9146 section 3: once connection ids are in use, a protected record without the id is
/// invalid; a ChangeCipherSpec is no exception. A forged `tls12_cid` record under the right id
/// fails authentication and is discarded too.
#[test]
fn with_connection_ids_a_forged_change_cipher_spec_does_not_end_the_association() -> Result<()> {
    for suite in CERTIFICATE_SUITES.into_iter().chain(PSK_SUITES) {
        for into_server in [true, false] {
            let mut pair = completed(suite, Some(4))?;
            let peer = if into_server {
                client_addr()
            } else {
                server_addr()
            };
            let victim = if into_server {
                &mut pair.server
            } else {
                &mut pair.client
            };
            let connection_id = victim
                .connection_mut(&peer)
                .and_then(|conn| conn.state.receive_connection_id().map(<[u8]>::to_vec))
                .expect("a connection id was negotiated");
            let mut forged = forgeries();
            for (n, body) in [vec![0x01], vec![0x02], vec![0x5a; 40]]
                .into_iter()
                .enumerate()
            {
                forged.push((
                    format!("tls12_cid record under the right id, {} bytes", body.len()),
                    tls12_cid_record(&connection_id, 2_000_000 + n as u64, &body),
                ));
            }
            inject_after_handshake(
                &mut pair,
                into_server,
                forged,
                &format!("{suite} with connection ids"),
            )?;
        }
    }
    Ok(())
}

/// RFC 9146 section 6: the association follows its peer to a new address for an authentic
/// record newer than any before. A forged ChangeCipherSpec with the largest sequence number
/// must not count as that newest record, or no genuine record would ever be newer.
#[test]
fn a_forged_change_cipher_spec_does_not_stop_connection_id_migration() -> Result<()> {
    let moved = SocketAddr::from(([127, 0, 0, 1], 7200));
    for suite in CERTIFICATE_SUITES.into_iter().chain(PSK_SUITES) {
        let (client, server) = builders(suite, Some(4));
        let mut pair = Pair::new(client, server.with_connection_id_migration(true))?.complete();
        for forged in [
            change_cipher_spec(1, LAST_SEQUENCE_NUMBER, &[0x01]),
            change_cipher_spec(1, LAST_SEQUENCE_NUMBER - 1, &[0x02]),
        ] {
            assert_discarded(
                pair.now,
                &mut pair.server,
                client_addr(),
                forged,
                &format!("{suite}: forged ChangeCipherSpec before migration"),
            );
        }
        pair.client
            .write(pair.now, server_addr(), b"from elsewhere")?;
        let datagram = take(&mut pair.client).remove(0);
        let events = pair.server.read(pair.now, moved, None, datagram)?;
        assert_eq!(
            application_data(&events),
            vec![b"from elsewhere".to_vec()],
            "{suite}"
        );
        assert!(
            pair.server.connection_mut(&moved).is_some(),
            "{suite}: the association did not follow its peer after a forged ChangeCipherSpec"
        );
        assert!(
            pair.server.connection_mut(&client_addr()).is_none(),
            "{suite}"
        );
    }
    Ok(())
}

/// The same after an abbreviated (resumed) handshake, where the server sends its
/// ChangeCipherSpec and Finished first.
#[test]
fn after_a_resumed_handshake_a_forged_change_cipher_spec_does_not_end_the_association() -> Result<()>
{
    for suite in [
        CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256,
        CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_256_Cbc_Sha,
    ] {
        for into_server in [true, false] {
            let store = Arc::new(MemorySessionStore::new());
            let cache = Arc::new(MemorySessionCache::default());
            let (client, server) = builders(suite, None);
            let client = Arc::new(
                client
                    .with_server_name("localhost".to_owned())
                    .with_session_store(Some(store))
                    .build(true, None)?,
            );
            let server = Arc::new(server.with_session_cache(Some(cache)).build(false, None)?);
            // A full handshake leaves a session to resume.
            Pair::with(client.clone(), server.clone())?.complete();
            let mut pair = Pair::with(client.clone(), server.clone())?.complete();
            assert!(
                pair.client
                    .connection_mut(&server_addr())
                    .is_some_and(|conn| conn.state.resumed),
                "{suite}: the second handshake resumed the session"
            );
            inject_after_handshake(
                &mut pair,
                into_server,
                forgeries(),
                &format!("{suite}, resumed"),
            )?;
        }
    }
    Ok(())
}

/// Alert records (content type 21) in `datagrams`, which carry no `tls12_cid` record.
fn alert_records(datagrams: &[BytesMut]) -> usize {
    let mut alerts = 0;
    for datagram in datagrams {
        let mut rest = &datagram[..];
        while rest.len() >= 13 {
            if rest[0] == ContentType::Alert as u8 {
                alerts += 1;
            }
            let length = usize::from(u16::from_be_bytes([rest[11], rest[12]]));
            rest = &rest[(13 + length).min(rest.len())..];
        }
    }
    alerts
}

/// The handshake-time forgeries: a malformed ChangeCipherSpec in epoch 0 (unauthenticated in
/// any case), and ChangeCipherSpecs that claim epoch 1 or 2 (held until the keys exist, then
/// opened, and failing).
fn handshake_forgeries() -> Vec<(String, BytesMut)> {
    let mut forged = vec![];
    for (n, (epoch, body)) in [
        (0u16, vec![0x02]),
        (0, vec![]),
        (0, vec![0x02; 300]),
        (1, vec![0x02]),
        (1, vec![0x01]),
        (1, vec![]),
        (1, vec![0x02; 300]),
        (2, vec![0x02]),
    ]
    .into_iter()
    .enumerate()
    {
        forged.push((
            format!("ChangeCipherSpec, epoch {epoch}, {} byte(s)", body.len()),
            change_cipher_spec(epoch, 500 + n as u64, &body),
        ));
    }
    forged
}

/// Reads each handshake-time forgery at `victim` and checks it drew nothing and failed
/// nothing.
fn inject_during_handshake(now: Instant, victim: &mut Endpoint, peer: SocketAddr, label: &str) {
    for (name, forged) in handshake_forgeries() {
        if let Err(err) = victim.read(now, peer, None, forged) {
            panic!("{label}: {name}: the read failed: {err}");
        }
        let answered = take(victim);
        assert_eq!(
            alert_records(&answered),
            0,
            "{label}: {name} was answered with an alert"
        );
        assert!(
            victim
                .connection_mut(&peer)
                .is_some_and(|conn| !conn.is_failed()),
            "{label}: {name} failed the handshake"
        );
    }
}

/// RFC 6347 4.1.2.7: during the handshake a malformed ChangeCipherSpec in epoch 0 is
/// discarded without an alert, and one that claims a protected epoch, held until the keys
/// exist, fails authentication and is discarded too; the handshake completes and carries data.
/// At the client (before the server's ChangeCipherSpec and Finished) and at the server
/// (before the client's key exchange, ChangeCipherSpec and Finished), every cipher family.
#[test]
fn a_forged_change_cipher_spec_during_the_handshake_is_discarded() -> Result<()> {
    for suite in CERTIFICATE_SUITES {
        for into_server in [true, false] {
            let (client, server) = builders(suite, None);
            let mut pair = Pair::new(client, server.with_cookie_exchange(false))?;
            // ClientHello up, the server's first flight down.
            pair.round();
            let client_final = take(&mut pair.client);
            if into_server {
                let now = pair.now;
                inject_during_handshake(now, &mut pair.server, client_addr(), &format!("{suite}"));
            }
            pair.deliver_to_server(client_final);
            let server_final = take(&mut pair.server);
            assert_eq!(
                alert_records(&server_final),
                0,
                "{suite}: the server answered with an alert"
            );
            if !into_server {
                let now = pair.now;
                inject_during_handshake(now, &mut pair.client, server_addr(), &format!("{suite}"));
            }
            pair.deliver_to_client(server_final);
            pair.run();
            assert!(
                pair.client_complete && pair.server_complete,
                "{suite}, into the {}: the handshake did not complete ({:?} {:?})",
                if into_server { "server" } else { "client" },
                pair.client_error,
                pair.server_error
            );
            assert_eq!(pair.client_sends(b"up"), vec![b"up".to_vec()], "{suite}");
            assert_eq!(
                pair.server_sends(b"down"),
                vec![b"down".to_vec()],
                "{suite}"
            );
            for (endpoint, peer) in [
                (&mut pair.client, server_addr()),
                (&mut pair.server, client_addr()),
            ] {
                assert!(
                    endpoint
                        .connection_mut(&peer)
                        .is_some_and(|conn| !conn.is_failed()),
                    "{suite}: an association failed after the handshake-time forgeries"
                );
            }
        }
    }
    Ok(())
}