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
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
//! Malformed DTLS 1.2 handshake messages, one table over every message type: truncated
//! messages, length fields too long and too short, trailing bytes, empty vectors the
//! presentation language forbids (RFC 5246 4.3: `<floor..ceiling>`), oversize fields. Each is
//! framed as it arrives (12-byte header, `length` the body's) and parsed by
//! [`Handshake::unmarshal`], the parser the connection uses. The messages the cases start from
//! are first parsed whole, so a case fails for what was changed, not for a bad base message.
//!
//! What the connection does with a message that does not parse (RFC 6347 4.1.2.7: dropped in
//! the clear; decode_error when protected) is tested in `conn/handshake_order_test.rs`. Case
//! ideas from the TLS-Anvil `lengthfield` tests and BoGo `TrailingMessageData-*` (behaviours only).

use super::*;

const CLIENT_HELLO: u8 = 1;
const SERVER_HELLO: u8 = 2;
const HELLO_VERIFY_REQUEST: u8 = 3;
const NEW_SESSION_TICKET: u8 = 4;
const CERTIFICATE: u8 = 11;
const SERVER_KEY_EXCHANGE: u8 = 12;
const CERTIFICATE_REQUEST: u8 = 13;
const SERVER_HELLO_DONE: u8 = 14;
const CERTIFICATE_VERIFY: u8 = 15;
const CLIENT_KEY_EXCHANGE: u8 = 16;
const FINISHED: u8 = 20;

/// The outcome a case expects.
#[derive(Clone, Copy, Debug)]
enum Expect {
    /// Parsed.
    Ok,
    /// Ran out of bytes: a length field reaching past the message, or a message cut short.
    Truncated,
    /// A length that does not fit the message's form: trailing bytes, an empty vector where
    /// one is forbidden, a vector of pairs with an odd length, an oversize field.
    BadLength,
    /// Either of the two: the message's length does not match its fields (the parser checks
    /// the total, not which side is wrong).
    Malformed,
    /// This exact error.
    Is(fn() -> Error),
}

fn is_truncated(err: &Error) -> bool {
    match err {
        Error::ErrBufferTooSmall => true,
        Error::Io(io) => io.0.kind() == std::io::ErrorKind::UnexpectedEof,
        _ => false,
    }
}

fn check(name: &str, typ: u8, body: &[u8], expect: Expect) {
    let framed = framed(typ, body);
    let result = Handshake::unmarshal(&mut framed.as_slice());
    match (expect, &result) {
        (Expect::Ok, Ok(h)) => assert_eq!(h.handshake_header.handshake_type, typ.into(), "{name}"),
        (Expect::Truncated, Err(err)) => assert!(is_truncated(err), "{name}: {err:?}"),
        (Expect::BadLength, Err(err)) => {
            assert_eq!(err, &Error::ErrInvalidPacketLength, "{name}")
        }
        (Expect::Malformed, Err(err)) => assert!(
            is_truncated(err) || *err == Error::ErrInvalidPacketLength,
            "{name}: {err:?}"
        ),
        (Expect::Is(expected), Err(err)) => assert_eq!(err, &expected(), "{name}"),
        (expect, result) => panic!("{name}: expected {expect:?}, got {result:?}"),
    }
}

/// `body` with the 12-byte DTLS handshake header in front, unfragmented.
fn framed(typ: u8, body: &[u8]) -> Vec<u8> {
    framed_announcing(typ, body.len() as u32, body)
}

fn framed_announcing(typ: u8, length: u32, body: &[u8]) -> Vec<u8> {
    let length = length.to_be_bytes();
    let mut out = vec![typ];
    out.extend_from_slice(&length[1..]);
    out.extend_from_slice(&[0, 0, 0, 0, 0]);
    out.extend_from_slice(&length[1..]);
    out.extend_from_slice(body);
    out
}

fn cat(parts: &[&[u8]]) -> Vec<u8> {
    parts.concat()
}

const RANDOM: [u8; 32] = [0x5a; 32];

/// ClientHello: version, random, session_id<0..32>, cookie<0..2^8-1>,
/// cipher_suites<2..2^16-2>, compression_methods<1..2^8-1>, no extensions block.
fn client_hello(session_id: &[u8], cookie_length: u8, rest: &[u8]) -> Vec<u8> {
    cat(&[
        &[0xfe, 0xfd],
        &RANDOM,
        &[session_id.len() as u8],
        session_id,
        &[cookie_length],
        rest,
    ])
}

const CLIENT_HELLO_TAIL: [u8; 6] = [0x00, 0x02, 0xc0, 0x2b, 0x01, 0x00];

/// ServerHello: version, random, session_id, cipher_suite, compression_method, then `tail`.
fn server_hello(session_id_length: u8, tail: &[u8]) -> Vec<u8> {
    cat(&[&[0xfe, 0xfd], &RANDOM, &[session_id_length], tail])
}

const SERVER_HELLO_TAIL: [u8; 3] = [0xc0, 0x2b, 0x00];

/// A stand-in for a DER certificate: the Certificate parser frames entries, it does not read
/// them.
const DER: [u8; 4] = [0x30, 0x02, 0x05, 0x00];

/// ECDHE ServerKeyExchange (RFC 8422 5.4): named_curve x25519, the point with `key_length`,
/// then ecdsa_secp256r1_sha256 and a signature of `signature_length` (4 bytes follow).
fn server_key_exchange(key_length: u8, signature_length: u16) -> Vec<u8> {
    cat(&[
        &[0x03, 0x00, 0x1d, key_length],
        &[0x42; 32],
        &[0x04, 0x03],
        &signature_length.to_be_bytes(),
        &[0x30, 0x01, 0x02, 0x03],
    ])
}

/// ECDHE ClientKeyExchange: point<1..2^8-1>, a 32-byte X25519 share.
fn client_key_exchange(length: u8) -> Vec<u8> {
    cat(&[&[length], &[0x11; 32]])
}

#[test]
fn malformed_handshake_messages_are_refused_by_the_parser() {
    use Expect::*;
    let cases: Vec<(&str, u8, Vec<u8>, Expect)> = vec![
        // ClientHello (RFC 5246 7.4.1.2)
        (
            "ClientHello",
            CLIENT_HELLO,
            client_hello(&[], 0, &CLIENT_HELLO_TAIL),
            Ok,
        ),
        (
            "ClientHello: session_id longer than 32",
            CLIENT_HELLO,
            client_hello(&[7; 33], 0, &CLIENT_HELLO_TAIL),
            BadLength,
        ),
        (
            "ClientHello: cookie length past the message",
            CLIENT_HELLO,
            client_hello(&[], 5, &CLIENT_HELLO_TAIL),
            Truncated,
        ),
        (
            "ClientHello: cipher_suites of odd length",
            CLIENT_HELLO,
            client_hello(&[], 0, &[0x00, 0x03, 0xc0, 0x2b, 0x00, 0x01, 0x00]),
            BadLength,
        ),
        (
            "ClientHello: cipher_suites length past the suites",
            CLIENT_HELLO,
            client_hello(&[], 0, &[0x00, 0x04, 0xc0, 0x2b, 0x01, 0x00]),
            Truncated,
        ),
        (
            "ClientHello: compression_methods count past the message",
            CLIENT_HELLO,
            client_hello(&[], 0, &[0x00, 0x02, 0xc0, 0x2b, 0x02, 0x00]),
            Truncated,
        ),
        (
            "ClientHello: one byte after the compression methods",
            CLIENT_HELLO,
            client_hello(&[], 0, &cat(&[&CLIENT_HELLO_TAIL, &[0x00]])),
            Malformed,
        ),
        // ServerHello (7.4.1.3)
        (
            "ServerHello",
            SERVER_HELLO,
            server_hello(0, &SERVER_HELLO_TAIL),
            Ok,
        ),
        (
            "ServerHello: cut before the compression method",
            SERVER_HELLO,
            server_hello(0, &SERVER_HELLO_TAIL[..2]),
            Truncated,
        ),
        (
            "ServerHello: session_id longer than 32",
            SERVER_HELLO,
            server_hello(33, &SERVER_HELLO_TAIL),
            BadLength,
        ),
        (
            "ServerHello: session_id length past the message",
            SERVER_HELLO,
            server_hello(5, &SERVER_HELLO_TAIL),
            Truncated,
        ),
        (
            "ServerHello: extensions length longer than the block",
            SERVER_HELLO,
            server_hello(
                0,
                &cat(&[&SERVER_HELLO_TAIL, &[0x00, 0x05, 0x00, 0x17, 0x00, 0x00]]),
            ),
            Is(|| Error::ErrLengthMismatch),
        ),
        (
            "ServerHello: extensions length shorter than the block",
            SERVER_HELLO,
            server_hello(
                0,
                &cat(&[&SERVER_HELLO_TAIL, &[0x00, 0x03, 0x00, 0x17, 0x00, 0x00]]),
            ),
            Is(|| Error::ErrLengthMismatch),
        ),
        (
            "ServerHello: extension data length past the block",
            SERVER_HELLO,
            server_hello(
                0,
                &cat(&[&SERVER_HELLO_TAIL, &[0x00, 0x04, 0x00, 0x17, 0x00, 0x01]]),
            ),
            Truncated,
        ),
        (
            "ServerHello: one byte where the extensions block starts",
            SERVER_HELLO,
            server_hello(0, &cat(&[&SERVER_HELLO_TAIL, &[0x00]])),
            Truncated,
        ),
        // HelloVerifyRequest (RFC 6347 4.2.1)
        (
            "HelloVerifyRequest",
            HELLO_VERIFY_REQUEST,
            vec![0xfe, 0xff, 0x02, 0xaa, 0xbb],
            Ok,
        ),
        (
            "HelloVerifyRequest: cut in the version",
            HELLO_VERIFY_REQUEST,
            vec![0xfe],
            Truncated,
        ),
        (
            "HelloVerifyRequest: cookie length past the message",
            HELLO_VERIFY_REQUEST,
            vec![0xfe, 0xff, 0x03, 0xaa, 0xbb],
            Truncated,
        ),
        (
            "HelloVerifyRequest: bytes after the cookie",
            HELLO_VERIFY_REQUEST,
            vec![0xfe, 0xff, 0x01, 0xaa, 0xbb],
            BadLength,
        ),
        // NewSessionTicket (RFC 5077 3.3)
        (
            "NewSessionTicket",
            NEW_SESSION_TICKET,
            vec![0, 0, 0, 0x3c, 0x00, 0x02, 0xaa, 0xbb],
            Ok,
        ),
        (
            "NewSessionTicket: ticket length past the message",
            NEW_SESSION_TICKET,
            vec![0, 0, 0, 0x3c, 0x00, 0x03, 0xaa, 0xbb],
            Truncated,
        ),
        (
            "NewSessionTicket: bytes after the ticket",
            NEW_SESSION_TICKET,
            vec![0, 0, 0, 0x3c, 0x00, 0x01, 0xaa, 0xbb],
            BadLength,
        ),
        // Certificate (RFC 5246 7.4.2, 7.4.6)
        (
            "Certificate",
            CERTIFICATE,
            cat(&[&[0, 0, 7, 0, 0, 4], &DER]),
            Ok,
        ),
        ("Certificate: empty list", CERTIFICATE, vec![0, 0, 0], Ok),
        (
            "Certificate: list length past the message",
            CERTIFICATE,
            cat(&[&[0, 0, 8, 0, 0, 4], &DER]),
            Truncated,
        ),
        (
            "Certificate: list length shorter than its entry",
            CERTIFICATE,
            cat(&[&[0, 0, 6, 0, 0, 4], &DER]),
            BadLength,
        ),
        (
            "Certificate: entry length past the list",
            CERTIFICATE,
            cat(&[&[0, 0, 7, 0, 0, 5], &DER]),
            BadLength,
        ),
        (
            "Certificate: entry length shorter than the entry",
            CERTIFICATE,
            cat(&[&[0, 0, 7, 0, 0, 3], &DER]),
            Truncated,
        ),
        (
            "Certificate: an empty entry",
            CERTIFICATE,
            vec![0, 0, 3, 0, 0, 0],
            BadLength,
        ),
        (
            "Certificate: a byte after the list",
            CERTIFICATE,
            cat(&[&[0, 0, 7, 0, 0, 4], &DER, &[0]]),
            BadLength,
        ),
        (
            "Certificate: cut in its entry",
            CERTIFICATE,
            cat(&[&[0, 0, 7, 0, 0, 4], &DER[..2]]),
            Truncated,
        ),
        // ServerKeyExchange (RFC 8422 5.4)
        (
            "ServerKeyExchange",
            SERVER_KEY_EXCHANGE,
            server_key_exchange(32, 4),
            Ok,
        ),
        (
            "ServerKeyExchange: cut after the named curve",
            SERVER_KEY_EXCHANGE,
            vec![0x03, 0x00, 0x1d],
            Truncated,
        ),
        (
            "ServerKeyExchange: an empty point",
            SERVER_KEY_EXCHANGE,
            cat(&[
                &[0x03, 0x00, 0x1d, 0x00, 0x04, 0x03, 0x00, 0x04],
                &[0x30, 1, 2, 3],
            ]),
            BadLength,
        ),
        (
            "ServerKeyExchange: point length past the point",
            SERVER_KEY_EXCHANGE,
            server_key_exchange(33, 4),
            Truncated,
        ),
        (
            "ServerKeyExchange: signature length past the message",
            SERVER_KEY_EXCHANGE,
            server_key_exchange(32, 5),
            Truncated,
        ),
        (
            "ServerKeyExchange: signature length shorter than the signature",
            SERVER_KEY_EXCHANGE,
            server_key_exchange(32, 3),
            BadLength,
        ),
        (
            "ServerKeyExchange: a byte after the signature",
            SERVER_KEY_EXCHANGE,
            cat(&[&server_key_exchange(32, 4), &[0]]),
            BadLength,
        ),
        // CertificateRequest (RFC 5246 7.4.4)
        (
            "CertificateRequest",
            CERTIFICATE_REQUEST,
            vec![0x01, 0x40, 0x00, 0x02, 0x04, 0x03, 0x00, 0x00],
            Ok,
        ),
        (
            "CertificateRequest: with certificate authorities",
            CERTIFICATE_REQUEST,
            vec![
                0x01, 0x40, 0x00, 0x02, 0x04, 0x03, 0x00, 0x04, 0x00, 0x02, 0xaa, 0xbb,
            ],
            Ok,
        ),
        (
            "CertificateRequest: no certificate types",
            CERTIFICATE_REQUEST,
            vec![0x00, 0x00, 0x02, 0x04, 0x03, 0x00, 0x00],
            BadLength,
        ),
        (
            "CertificateRequest: certificate types length past the types",
            CERTIFICATE_REQUEST,
            vec![0x05, 0x40, 0x00, 0x02, 0x04, 0x03, 0x00, 0x00],
            BadLength,
        ),
        (
            "CertificateRequest: no signature algorithms",
            CERTIFICATE_REQUEST,
            vec![0x01, 0x40, 0x00, 0x00, 0x00, 0x00],
            BadLength,
        ),
        (
            "CertificateRequest: signature algorithms of odd length",
            CERTIFICATE_REQUEST,
            vec![0x01, 0x40, 0x00, 0x03, 0x04, 0x03, 0x05, 0x00, 0x00],
            BadLength,
        ),
        (
            "CertificateRequest: signature algorithms length past the pairs",
            CERTIFICATE_REQUEST,
            vec![0x01, 0x40, 0x00, 0x04, 0x04, 0x03, 0x00, 0x00],
            Truncated,
        ),
        (
            "CertificateRequest: no certificate_authorities field",
            CERTIFICATE_REQUEST,
            vec![0x01, 0x40, 0x00, 0x02, 0x04, 0x03],
            Truncated,
        ),
        (
            "CertificateRequest: certificate_authorities length past the message",
            CERTIFICATE_REQUEST,
            vec![
                0x01, 0x40, 0x00, 0x02, 0x04, 0x03, 0x00, 0x05, 0x00, 0x02, 0xaa, 0xbb,
            ],
            Truncated,
        ),
        (
            "CertificateRequest: an empty distinguished name",
            CERTIFICATE_REQUEST,
            vec![0x01, 0x40, 0x00, 0x02, 0x04, 0x03, 0x00, 0x02, 0x00, 0x00],
            BadLength,
        ),
        (
            "CertificateRequest: a distinguished name past the list",
            CERTIFICATE_REQUEST,
            vec![
                0x01, 0x40, 0x00, 0x02, 0x04, 0x03, 0x00, 0x03, 0x00, 0x02, 0xaa,
            ],
            BadLength,
        ),
        (
            "CertificateRequest: a byte after the message",
            CERTIFICATE_REQUEST,
            vec![0x01, 0x40, 0x00, 0x02, 0x04, 0x03, 0x00, 0x00, 0x00],
            BadLength,
        ),
        // ServerHelloDone (7.4.5): an empty body
        ("ServerHelloDone", SERVER_HELLO_DONE, vec![], Ok),
        (
            "ServerHelloDone: a body",
            SERVER_HELLO_DONE,
            vec![0x00],
            BadLength,
        ),
        // CertificateVerify (7.4.8)
        (
            "CertificateVerify",
            CERTIFICATE_VERIFY,
            vec![0x04, 0x03, 0x00, 0x02, 0xaa, 0xbb],
            Ok,
        ),
        (
            "CertificateVerify: cut in the algorithm",
            CERTIFICATE_VERIFY,
            vec![0x04],
            Truncated,
        ),
        (
            "CertificateVerify: signature length past the message",
            CERTIFICATE_VERIFY,
            vec![0x04, 0x03, 0x00, 0x03, 0xaa, 0xbb],
            Truncated,
        ),
        (
            "CertificateVerify: signature length shorter than the signature",
            CERTIFICATE_VERIFY,
            vec![0x04, 0x03, 0x00, 0x01, 0xaa, 0xbb],
            BadLength,
        ),
        // ClientKeyExchange (7.4.7, RFC 8422 5.7)
        (
            "ClientKeyExchange",
            CLIENT_KEY_EXCHANGE,
            client_key_exchange(32),
            Ok,
        ),
        (
            "ClientKeyExchange: empty",
            CLIENT_KEY_EXCHANGE,
            vec![],
            Truncated,
        ),
        (
            "ClientKeyExchange: an empty point",
            CLIENT_KEY_EXCHANGE,
            vec![0x00],
            Truncated,
        ),
        (
            "ClientKeyExchange: point length past the point",
            CLIENT_KEY_EXCHANGE,
            client_key_exchange(33),
            Malformed,
        ),
        (
            "ClientKeyExchange: point length shorter than the point",
            CLIENT_KEY_EXCHANGE,
            client_key_exchange(31),
            Malformed,
        ),
        // Finished (7.4.9): verify_data[12]
        ("Finished", FINISHED, vec![0x0f; 12], Ok),
        (
            "Finished: verify_data of 11 bytes",
            FINISHED,
            vec![0x0f; 11],
            BadLength,
        ),
        (
            "Finished: verify_data of 13 bytes",
            FINISHED,
            vec![0x0f; 13],
            BadLength,
        ),
        ("Finished: empty", FINISHED, vec![], BadLength),
    ];
    let count = cases.len();
    for (name, typ, body, expect) in cases {
        check(name, typ, &body, expect);
    }
    assert_eq!(count, 65, "every case ran");
}

/// The handshake header itself: a body shorter than its `length`, a header cut short, and the
/// types this crate does not take (HelloRequest, which only a renegotiating server sends, and
/// an unassigned one).
#[test]
fn a_malformed_handshake_header_is_refused_by_the_parser() {
    let short = framed_announcing(SERVER_HELLO_DONE, 4, &[0, 0, 0]);
    assert!(
        is_truncated(&Handshake::unmarshal(&mut short.as_slice()).unwrap_err()),
        "a body shorter than its length"
    );
    let header = framed(SERVER_HELLO_DONE, &[]);
    for cut in 0..header.len() {
        let err = Handshake::unmarshal(&mut &header[..cut]).unwrap_err();
        assert!(is_truncated(&err), "a header cut to {cut} bytes: {err:?}");
    }
    assert!(Handshake::unmarshal(&mut header.as_slice()).is_ok());
    for typ in [0, 99] {
        let message = framed(typ, &[]);
        assert_eq!(
            Handshake::unmarshal(&mut message.as_slice()),
            Err(Error::ErrNotImplemented),
            "type {typ}"
        );
    }
}