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
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
//! RFC 5246 7.4 (inherited by DTLS 1.2, RFC 6347 4.2) on the production connection: handshake
//! messages out of order, sent twice or left out, and the authentication checks of DTLS-SRTP.
//!
//! The cases come from two studies, read for their behaviours only: the 19 authentication tests
//! of Bach et al., "Analyzing the WebRTC Ecosystem and Breaking Authentication in DTLS-SRTP"
//! (USENIX Security 2026, section 4.2), and the state-machine bug patterns of Fiterău-Broştean
//! et al. (NDSS 2023, tables II and III). Each case runs a real client against a real server,
//! with one flight rewritten on its way by a man in the middle that works on whole handshake
//! messages: it can move, repeat, drop or add messages and renumber them, as a peer that broke
//! the rules would.

use super::conn_conformance_test::{
    builder, client, drain, feed, handshake_message, plaintext_record, provider, self_signed,
};
use super::*;
use crate::config::{ClientAuthType, ConfigBuilder, VerifyPeerCertificateFn};
use crate::crypto::Certificate;

const SERVER_HELLO: u8 = 2;
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;

const CHANGE_CIPHER_SPEC_RECORD: u8 = 20;
const HANDSHAKE_RECORD: u8 = 22;

const SRTP_LABEL: &str = "EXTRACTOR-dtls_srtp";

// ---------------------------------------------------------------------------------------------
// The man in the middle
// ---------------------------------------------------------------------------------------------

/// One record of a flight as the man in the middle sees it.
#[derive(Clone, Debug, PartialEq)]
enum Item {
    /// A plaintext (epoch 0) handshake message, unfragmented.
    Message { typ: u8, seq: u16, body: Vec<u8> },
    /// Any other record (ChangeCipherSpec, a protected record), passed on as it is.
    Record(Vec<u8>),
}

#[derive(Clone, Copy, Debug, PartialEq)]
enum Side {
    Client,
    Server,
}

fn items_of(datagrams: &[Vec<u8>]) -> Vec<Item> {
    let mut items = vec![];
    for datagram in datagrams {
        for record in unpack_datagram(datagram).expect("a datagram splits into records") {
            let epoch = u16::from_be_bytes([record[3], record[4]]);
            if record[0] != HANDSHAKE_RECORD || epoch != 0 {
                items.push(Item::Record(record));
                continue;
            }
            let mut rest = &record[RECORD_LAYER_HEADER_SIZE..];
            while !rest.is_empty() {
                let length = u32::from_be_bytes([0, rest[1], rest[2], rest[3]]) as usize;
                let offset = u32::from_be_bytes([0, rest[6], rest[7], rest[8]]) as usize;
                let fragment = u32::from_be_bytes([0, rest[9], rest[10], rest[11]]) as usize;
                assert!(
                    offset == 0 && fragment == length,
                    "the test flights are not fragmented"
                );
                items.push(Item::Message {
                    typ: rest[0],
                    seq: u16::from_be_bytes([rest[4], rest[5]]),
                    body: rest[12..12 + length].to_vec(),
                });
                rest = &rest[12 + length..];
            }
        }
    }
    items
}

/// One datagram per item. Plaintext records get record sequence numbers from `next`, in the
/// order the items are sent, as the sender would have numbered them.
fn encode(items: &[Item], next: &mut u64) -> Vec<Vec<u8>> {
    let mut datagrams = vec![];
    for item in items {
        match item {
            Item::Message { typ, seq, body } => {
                datagrams.push(plaintext_record(
                    HANDSHAKE_RECORD,
                    *next,
                    &handshake_message(*typ, *seq, body),
                ));
                *next += 1;
            }
            Item::Record(record) => {
                let mut record = record.clone();
                if record[3..5] == [0, 0] {
                    record[5..11].copy_from_slice(&next.to_be_bytes()[2..]);
                    *next += 1;
                }
                datagrams.push(record);
            }
        }
    }
    datagrams
}

fn index_of(items: &[Item], typ: u8) -> usize {
    items
        .iter()
        .position(|item| matches!(item, Item::Message { typ: t, .. } if *t == typ))
        .unwrap_or_else(|| panic!("the flight has a handshake message of type {typ}"))
}

fn seq_of(items: &[Item], typ: u8) -> u16 {
    match &items[index_of(items, typ)] {
        Item::Message { seq, .. } => *seq,
        Item::Record(_) => unreachable!(),
    }
}

fn has(items: &[Item], typ: u8) -> bool {
    items
        .iter()
        .any(|item| matches!(item, Item::Message { typ: t, .. } if *t == typ))
}

fn is_change_cipher_spec(item: &Item) -> bool {
    matches!(item, Item::Record(record) if record[0] == CHANGE_CIPHER_SPEC_RECORD)
}

fn is_protected(item: &Item) -> bool {
    matches!(item, Item::Record(record) if record[3..5] != [0, 0])
}

/// Sends message `a` under `b`'s sequence number and in its place, and `b` under `a`'s.
fn swap(items: &mut [Item], a: u8, b: u8) {
    let (ia, ib) = (index_of(items, a), index_of(items, b));
    let (sa, sb) = (seq_of(items, a), seq_of(items, b));
    if let Item::Message { seq, .. } = &mut items[ia] {
        *seq = sb;
    }
    if let Item::Message { seq, .. } = &mut items[ib] {
        *seq = sa;
    }
    items.swap(ia, ib);
}

/// Shifts the sequence number of every plaintext message from `from` on by `by`.
fn renumber_from(items: &mut [Item], from: usize, by: i32) {
    for item in &mut items[from..] {
        if let Item::Message { seq, .. } = item {
            *seq = (*seq as i32 + by) as u16;
        }
    }
}

/// Sends message `typ` a second time right after the first, under the next sequence number;
/// the messages after it move up one.
fn repeat(items: &mut Vec<Item>, typ: u8) {
    let at = index_of(items, typ);
    let mut copy = items[at].clone();
    if let Item::Message { seq, .. } = &mut copy {
        *seq += 1;
    }
    renumber_from(items, at + 1, 1);
    items.insert(at + 1, copy);
}

/// Leaves message `typ` out; the messages after it move down one, as a sender that never had
/// it would have numbered them.
fn omit(items: &mut Vec<Item>, typ: u8) {
    let at = index_of(items, typ);
    items.remove(at);
    renumber_from(items, at, -1);
}

/// Keeps the plaintext messages of the flight only: its ChangeCipherSpec and protected
/// Finished are dropped, so what the receiver makes of the messages does not depend on them.
fn messages_only(items: &mut Vec<Item>) {
    items.retain(|item| matches!(item, Item::Message { .. }));
}

/// A record of `content_type` around `payload`, protected by `conn` in epoch 1 as its next
/// record: what the sender itself could have sent after its ChangeCipherSpec.
fn protected_by(conn: &mut DTLSConn, content_type: ContentType, payload: &[u8]) -> Vec<u8> {
    let sequence_number = conn.state.local_sequence_number[1];
    conn.state.local_sequence_number[1] += 1;
    let header = RecordLayerHeader {
        content_type,
        protocol_version: PROTOCOL_VERSION1_2,
        epoch: 1,
        sequence_number,
        content_len: payload.len() as u16,
    };
    let mut raw = vec![];
    header.marshal(&mut raw).unwrap();
    raw.extend_from_slice(payload);
    conn.state
        .cipher_suite
        .as_mut()
        .expect("the sender has its keys")
        .encrypt(&header, &raw)
        .unwrap()
}

/// A handshake between `client` and `server` in which the first flight of `side` that
/// `trigger` picks is passed through `edit` (which may use the sender's keys).
struct Run {
    client: DTLSConn,
    server: DTLSConn,
    client_err: Option<Error>,
    server_err: Option<Error>,
    /// What the client and the server sent, as delivered.
    from_client: Vec<Vec<u8>>,
    from_server: Vec<Vec<u8>>,
    /// The edited flight, as delivered.
    edited: Option<Vec<Item>>,
}

fn run(
    mut client: DTLSConn,
    mut server: DTLSConn,
    side: Side,
    trigger: impl Fn(&[Item]) -> bool,
    mut edit: impl FnMut(&mut Vec<Item>, &mut DTLSConn),
) -> Run {
    let now = Instant::now();
    let mut client_err = client.handshake(now).err();
    let mut server_err = None;
    let mut from_client = vec![];
    let mut from_server = vec![];
    let mut edited = None;
    // Once its flight is edited, a side's plaintext records are all renumbered, so its later
    // records are not taken for replays of the ones it sent before.
    let mut next_sequence = 100;
    for _ in 0..64 {
        let mut idle = true;
        for sender in [Side::Client, Side::Server] {
            let sent = match sender {
                Side::Client => drain(&mut client),
                Side::Server => drain(&mut server),
            };
            if sent.is_empty() {
                continue;
            }
            idle = false;
            let delivered = if sender == side && (edited.is_some() || trigger(&items_of(&sent))) {
                let mut items = items_of(&sent);
                if edited.is_none() {
                    match sender {
                        Side::Client => edit(&mut items, &mut client),
                        Side::Server => edit(&mut items, &mut server),
                    }
                    edited = Some(items.clone());
                }
                encode(&items, &mut next_sequence)
            } else {
                sent
            };
            let (receiver, err) = match sender {
                Side::Client => (&mut server, &mut server_err),
                Side::Server => (&mut client, &mut client_err),
            };
            for datagram in &delivered {
                if err.is_none()
                    && let Err(e) = feed(receiver, now, datagram)
                {
                    *err = Some(e);
                }
            }
            match sender {
                Side::Client => from_client.extend(delivered),
                Side::Server => from_server.extend(delivered),
            }
        }
        if idle {
            break;
        }
    }
    Run {
        client,
        server,
        client_err,
        server_err,
        from_client,
        from_server,
        edited,
    }
}

fn flight_with(typ: u8) -> impl Fn(&[Item]) -> bool {
    move |items| has(items, typ)
}

impl Run {
    fn conn(&self, side: Side) -> &DTLSConn {
        match side {
            Side::Client => &self.client,
            Side::Server => &self.server,
        }
    }

    fn err(&self, side: Side) -> Option<&Error> {
        match side {
            Side::Client => self.client_err.as_ref(),
            Side::Server => self.server_err.as_ref(),
        }
    }

    fn edited(&self) -> &[Item] {
        self.edited
            .as_deref()
            .expect("the flight to edit was sent and edited")
    }

    /// `side` refused the edited flight: it sent the fatal `alert` and failed with `error` (any
    /// error if `None`), did not complete, and holds no keys to export. (The other side may have
    /// completed: a server completes when it sends its last flight.)
    fn assert_refused(&self, side: Side, alert: AlertDescription, error: Option<Error>) {
        let conn = self.conn(side);
        assert!(conn.is_failed(), "{side:?} failed: {:?}", self.err(side));
        assert_eq!(
            conn.fatal_alerts().0,
            Some(alert as u8),
            "the fatal alert {side:?} sent ({:?})",
            self.err(side)
        );
        if let Some(error) = error {
            assert_eq!(self.err(side), Some(&error), "{side:?}'s error");
        }
        assert!(!conn.is_handshake_completed(), "{side:?} completed");
        assert!(
            conn.connection_state()
                .export_keying_material(SRTP_LABEL, &[], 30)
                .is_err(),
            "{side:?} exports no keys"
        );
    }

    /// `side` neither completed nor failed nor sent an alert: what it received is still being
    /// waited on, silently, and it exports no keys.
    fn assert_waiting(&self, side: Side) {
        let conn = self.conn(side);
        assert_eq!(self.err(side), None, "{side:?} has no error");
        assert!(!conn.is_failed(), "{side:?} did not fail");
        assert_eq!(conn.fatal_alerts(), (None, None), "no fatal alert");
        assert!(!conn.is_handshake_completed(), "{side:?} did not complete");
        if side == Side::Server {
            assert!(
                conn.connection_state()
                    .export_keying_material(SRTP_LABEL, &[], 30)
                    .is_err(),
                "the server exports no keys"
            );
        }
    }

    /// Both sides completed and export the same keys.
    fn assert_completed(&self) {
        assert_eq!(self.client_err, None);
        assert_eq!(self.server_err, None);
        assert!(self.client.is_handshake_completed(), "the client completed");
        assert!(self.server.is_handshake_completed(), "the server completed");
        let keys = |conn: &DTLSConn| {
            conn.connection_state()
                .export_keying_material(SRTP_LABEL, &[], 30)
                .expect("keys are exported")
                .as_ref()
                .to_vec()
        };
        assert_eq!(keys(&self.client), keys(&self.server), "the same keys");
    }
}

fn server_with(builder: ConfigBuilder, certificate: Certificate) -> DTLSConn {
    let config = builder
        .with_certificates(vec![certificate])
        .build(false, None)
        .expect("a server configuration");
    DTLSConn::new(Arc::new(config), false, None)
}

/// A server that requires a client certificate, as a WebRTC server does (RFC 8827 6.5).
fn requiring_server() -> DTLSConn {
    server_with(
        builder().with_client_auth(ClientAuthType::RequireAnyClientCert),
        self_signed(),
    )
}

fn certified_client(certificate: Certificate) -> DTLSConn {
    client(builder().with_certificates(vec![certificate]))
}

/// The WebRTC identity check (RFC 8122 5): the peer's end-entity certificate, the first of its
/// chain, must be `expected`, whatever else it looks like.
fn expecting(expected: &Certificate) -> VerifyPeerCertificateFn {
    let expected = expected.certificate[0].as_ref().to_vec();
    Arc::new(move |certificates: &[Vec<u8>], _| {
        if certificates.first() == Some(&expected) {
            Ok(())
        } else {
            Err(Error::ErrNoMatchingCertificateFingerprint)
        }
    })
}

fn certificate_for(name: &str) -> Certificate {
    Certificate::generate_self_signed(vec![name.to_owned()], provider().crypto())
        .expect("a self-signed certificate")
}

/// A chain of `first` then `second`, with the key of `key_of`.
fn chain(first: &Certificate, second: &Certificate, key_of: &Certificate) -> Certificate {
    Certificate {
        certificate: vec![first.certificate[0].clone(), second.certificate[0].clone()],
        private_key: key_of.private_key.clone(),
    }
}

/// A key-exchange message body with a byte of its public key, which starts at `key_at`,
/// changed: another share than the one the handshake signed.
fn with_other_key(body: &[u8], key_at: usize) -> Vec<u8> {
    let mut body = body.to_vec();
    body[key_at + 1] ^= 0x55;
    body
}

/// Where the public key starts in a ClientKeyExchange (after its one-byte length) and in an
/// ECDHE ServerKeyExchange (after curve type, named curve and length; RFC 8422 5.4).
const CLIENT_KEY_AT: usize = 1;
const SERVER_KEY_AT: usize = 4;

// ---------------------------------------------------------------------------------------------
// A second public key under the original sequence number (USENIX 2026 "Public Key Protected")
// ---------------------------------------------------------------------------------------------

/// A second ClientKeyExchange after the CertificateVerify, under the sequence number of the
/// first: the message sequence number is taken, so the copy is a repeat of a message already
/// received that is not byte for byte the same, and is dropped (RFC 6347 4.2.2). The share the
/// CertificateVerify signed is the one used: the handshake completes, both ends with the same
/// keys.
#[test]
fn a_second_client_key_exchange_under_the_first_ones_sequence_number_is_dropped() {
    let run = run(
        certified_client(self_signed()),
        requiring_server(),
        Side::Client,
        flight_with(CLIENT_KEY_EXCHANGE),
        |items, _| {
            let at = index_of(items, CLIENT_KEY_EXCHANGE);
            let Item::Message { typ, seq, body } = items[at].clone() else {
                unreachable!()
            };
            let after = index_of(items, CERTIFICATE_VERIFY) + 1;
            items.insert(
                after,
                Item::Message {
                    typ,
                    seq,
                    body: with_other_key(&body, CLIENT_KEY_AT),
                },
            );
        },
    );
    let edited = run.edited();
    assert!(index_of(edited, CERTIFICATE_VERIFY) < edited.len() - 1);
    assert_eq!(
        edited
            .iter()
            .filter(|item| matches!(item, Item::Message { typ, .. } if *typ == CLIENT_KEY_EXCHANGE))
            .count(),
        2,
        "two ClientKeyExchange messages were sent"
    );
    run.assert_completed();
}

/// The same for the server: a second ServerKeyExchange right after the first, under its
/// sequence number, is dropped, and the signed share is the one used.
#[test]
fn a_second_server_key_exchange_under_the_first_ones_sequence_number_is_dropped() {
    let run = run(
        client(builder()),
        server_with(builder(), self_signed()),
        Side::Server,
        flight_with(SERVER_KEY_EXCHANGE),
        |items, _| {
            let at = index_of(items, SERVER_KEY_EXCHANGE);
            let Item::Message { typ, seq, body } = items[at].clone() else {
                unreachable!()
            };
            items.insert(
                at + 1,
                Item::Message {
                    typ,
                    seq,
                    body: with_other_key(&body, SERVER_KEY_AT),
                },
            );
        },
    );
    assert_eq!(
        run.edited()
            .iter()
            .filter(|item| matches!(item, Item::Message { typ, .. } if *typ == SERVER_KEY_EXCHANGE))
            .count(),
        2,
        "two ServerKeyExchange messages were sent"
    );
    run.assert_completed();
}

// ---------------------------------------------------------------------------------------------
// ChangeCipherSpec (NDSS 2023 "Early ChangeCipherSpec", "Finished before ChangeCipherSpec")
// ---------------------------------------------------------------------------------------------

/// A ChangeCipherSpec that comes before the ClientKeyExchange (the network may reorder
/// records) is held until the keys it switches to exist, not acted on early: the epoch does
/// not change under keys that are not there yet. The handshake then completes, both ends with
/// the same keys.
#[test]
fn a_change_cipher_spec_before_the_client_key_exchange_is_held_until_the_keys_exist() {
    let run = run(
        client(builder()),
        server_with(builder(), self_signed()),
        Side::Client,
        flight_with(CLIENT_KEY_EXCHANGE),
        |items, _| {
            let ccs = items
                .iter()
                .position(is_change_cipher_spec)
                .expect("the flight has a ChangeCipherSpec");
            let item = items.remove(ccs);
            items.insert(0, item);
        },
    );
    let edited = run.edited();
    assert!(is_change_cipher_spec(&edited[0]));
    assert!(index_of(edited, CLIENT_KEY_EXCHANGE) > 0);
    run.assert_completed();
}

/// A Finished without the ChangeCipherSpec before it is never read: the record is of an epoch
/// the client has not announced, and is held. The server does not complete, fail or answer
/// (RFC 6347 4.1.2.7: what cannot be processed is dropped, the association preserved).
#[test]
fn a_finished_without_change_cipher_spec_is_never_taken() {
    let run = run(
        client(builder()),
        server_with(builder(), self_signed()),
        Side::Client,
        flight_with(CLIENT_KEY_EXCHANGE),
        |items, _| items.retain(|item| !is_change_cipher_spec(item)),
    );
    let edited = run.edited();
    assert!(!edited.iter().any(is_change_cipher_spec));
    assert!(edited.iter().any(is_protected), "the Finished was sent");
    run.assert_waiting(Side::Server);
    assert_eq!(run.server.state.remote_epoch, 0, "no epoch change");
}

// ---------------------------------------------------------------------------------------------
// Messages left out that are not yet shown missing
// ---------------------------------------------------------------------------------------------

/// A server flight without its ServerHelloDone is not complete: the client waits for the rest
/// (it may be lost and come again) and sends nothing of its next flight.
#[test]
fn a_server_flight_without_server_hello_done_is_waited_on() {
    let run = run(
        client(builder()),
        server_with(builder(), self_signed()),
        Side::Server,
        flight_with(SERVER_HELLO),
        |items, _| {
            let at = index_of(items, SERVER_HELLO_DONE);
            items.remove(at);
        },
    );
    assert!(!has(run.edited(), SERVER_HELLO_DONE));
    assert!(has(run.edited(), SERVER_KEY_EXCHANGE));
    run.assert_waiting(Side::Client);
    assert!(
        !has(&items_of(&run.from_client), CLIENT_KEY_EXCHANGE),
        "the client did not answer with its key exchange"
    );
}

/// A client that sends a certificate and leaves out the CertificateVerify (USENIX 2026 "No
/// Flow Bypass", NDSS 2023 "CertificateVerify-less Client Authentication"), its Finished in the
/// CertificateVerify's place: the server makes no keys from a key exchange whose certificate is
/// not proved (the client's flight may still be arriving), so it cannot read the Finished, and
/// never completes. Nothing is answered; the handshake deadline gives it up.
#[test]
fn a_client_certificate_without_certificate_verify_never_completes() {
    let deadline = Duration::from_secs(30);
    let server = server_with(
        builder()
            .with_client_auth(ClientAuthType::RequireAnyClientCert)
            .with_handshake_timeout(Some(deadline)),
        self_signed(),
    );
    let mut run = run(
        certified_client(self_signed()),
        server,
        Side::Client,
        flight_with(CLIENT_KEY_EXCHANGE),
        |items, client| {
            let at = index_of(items, CERTIFICATE_VERIFY);
            let seq = seq_of(items, CERTIFICATE_VERIFY);
            items.remove(at);
            items.retain(|item| !is_protected(item));
            let verify_data = client.state.local_verify_data.clone();
            let finished = handshake_message(FINISHED, seq, &verify_data);
            items.push(Item::Record(protected_by(
                client,
                ContentType::Handshake,
                &finished,
            )));
        },
    );
    let edited = run.edited();
    assert!(has(edited, CERTIFICATE) && has(edited, CLIENT_KEY_EXCHANGE));
    assert!(!has(edited, CERTIFICATE_VERIFY));
    assert!(edited.iter().any(is_protected), "a Finished was sent");
    assert!(!run.server.state.peer_certificates.is_empty());
    run.assert_waiting(Side::Server);

    let started = run.server.handshake_started.expect("the handshake started");
    assert_eq!(
        run.server.handle_timeout(started + deadline),
        Err(Error::ErrHandshakeTimeout)
    );
    assert!(run.server.is_failed());
    assert!(!run.server.is_handshake_completed());
}

/// The CertificateVerify sent after the ChangeCipherSpec, protected (NDSS 2023 "ChangeCipherSpec
/// before CertificateVerify"): until the certificate is proved the server makes no keys, so the
/// protected records stay unread and the server never completes, fails or answers.
#[test]
fn a_certificate_verify_after_change_cipher_spec_is_never_taken() {
    let run = run(
        certified_client(self_signed()),
        requiring_server(),
        Side::Client,
        flight_with(CLIENT_KEY_EXCHANGE),
        |items, client| {
            let at = index_of(items, CERTIFICATE_VERIFY);
            let Item::Message { typ, seq, body } = items.remove(at) else {
                unreachable!()
            };
            let ccs = items
                .iter()
                .position(is_change_cipher_spec)
                .expect("the flight has a ChangeCipherSpec");
            let protected = protected_by(
                client,
                ContentType::Handshake,
                &handshake_message(typ, seq, &body),
            );
            items.insert(ccs + 1, Item::Record(protected));
        },
    );
    let edited = run.edited();
    assert!(!has(edited, CERTIFICATE_VERIFY));
    let ccs = edited.iter().position(is_change_cipher_spec).unwrap();
    assert!(is_protected(&edited[ccs + 1]));
    run.assert_waiting(Side::Server);
}

// ---------------------------------------------------------------------------------------------
// Identity (USENIX 2026 "Performs Identity Check", "Signature Verified", "Incorrect Trust Store")
// ---------------------------------------------------------------------------------------------

/// A client that presents a certificate other than the one expected is refused with
/// bad_certificate (RFC 8122 6.2): an unrelated one, and a mimicry of the expected one (same
/// subject and issuer, another key). Nothing else makes a certificate acceptable: there is no
/// trust store in the decision.
#[test]
fn a_client_certificate_other_than_the_expected_one_is_refused() {
    let expected = self_signed();
    for presented in [
        certificate_for("attacker.example"),
        certificate_for("localhost"),
    ] {
        let server = server_with(
            builder()
                .with_client_auth(ClientAuthType::RequireAnyClientCert)
                .with_verify_peer_certificate(Some(expecting(&expected))),
            self_signed(),
        );
        assert_ne!(presented.certificate, expected.certificate);
        let run = run(
            certified_client(presented),
            server,
            Side::Client,
            |_| false,
            |_, _| {},
        );
        run.assert_refused(
            Side::Server,
            AlertDescription::BadCertificate,
            Some(Error::ErrNoMatchingCertificateFingerprint),
        );
    }
}

/// A client that presents the expected certificate alongside its own (USENIX 2026, the
/// mimicry variant): with the expected one first, the CertificateVerify, made with the
/// client's own key, does not verify under the end-entity key (decrypt_error); with its own
/// first, the identity check refuses it (bad_certificate).
#[test]
fn a_client_presenting_the_expected_certificate_with_its_own_is_refused() {
    let expected = self_signed();
    let own = certificate_for("localhost");
    let cases = [
        (chain(&expected, &own, &own), AlertDescription::DecryptError),
        (
            chain(&own, &expected, &own),
            AlertDescription::BadCertificate,
        ),
    ];
    for (presented, alert) in cases {
        let server = server_with(
            builder()
                .with_client_auth(ClientAuthType::RequireAnyClientCert)
                .with_verify_peer_certificate(Some(expecting(&expected))),
            self_signed(),
        );
        let run = run(
            certified_client(presented),
            server,
            Side::Client,
            |_| false,
            |_, _| {},
        );
        run.assert_refused(Side::Server, alert, None);
    }
}

/// The client checks the server's identity the same way: a certificate other than the
/// expected one, unrelated or a mimicry, is refused with bad_certificate.
#[test]
fn a_server_certificate_other_than_the_expected_one_is_refused() {
    let expected = self_signed();
    for presented in [
        certificate_for("attacker.example"),
        certificate_for("localhost"),
    ] {
        let client = client(builder().with_verify_peer_certificate(Some(expecting(&expected))));
        let run = run(
            client,
            server_with(builder(), presented),
            Side::Server,
            |_| false,
            |_, _| {},
        );
        run.assert_refused(
            Side::Client,
            AlertDescription::BadCertificate,
            Some(Error::ErrNoMatchingCertificateFingerprint),
        );
    }
}

/// A server that presents the expected certificate alongside its own: with the expected one
/// first, its ServerKeyExchange, signed with its own key, does not verify (decrypt_error);
/// with its own first, the identity check refuses it (bad_certificate).
#[test]
fn a_server_presenting_the_expected_certificate_with_its_own_is_refused() {
    let expected = self_signed();
    let own = certificate_for("localhost");
    let cases = [
        (chain(&expected, &own, &own), AlertDescription::DecryptError),
        (
            chain(&own, &expected, &own),
            AlertDescription::BadCertificate,
        ),
    ];
    for (presented, alert) in cases {
        let client = client(builder().with_verify_peer_certificate(Some(expecting(&expected))));
        let run = run(
            client,
            server_with(builder(), presented),
            Side::Server,
            |_| false,
            |_, _| {},
        );
        run.assert_refused(Side::Client, alert, None);
    }
}

// ---------------------------------------------------------------------------------------------
// Messages out of order, repeated or left out (RFC 5246 7.4: a fatal error, unexpected_message)
// ---------------------------------------------------------------------------------------------

/// A server flight edited by `edit`, which the client must refuse as out of order.
fn client_refuses(
    server: DTLSConn,
    client: DTLSConn,
    edit: impl FnMut(&mut Vec<Item>, &mut DTLSConn),
) -> Run {
    let run = run(
        client,
        server,
        Side::Server,
        flight_with(SERVER_HELLO),
        edit,
    );
    run.assert_refused(
        Side::Client,
        AlertDescription::UnexpectedMessage,
        Some(Error::ErrHandshakeMessageOutOfOrder),
    );
    run
}

/// A client flight edited by `edit`, which the server must refuse as out of order.
fn server_refuses(
    client: DTLSConn,
    server: DTLSConn,
    edit: impl FnMut(&mut Vec<Item>, &mut DTLSConn),
) -> Run {
    let run = run(
        client,
        server,
        Side::Client,
        flight_with(CLIENT_KEY_EXCHANGE),
        edit,
    );
    run.assert_refused(
        Side::Server,
        AlertDescription::UnexpectedMessage,
        Some(Error::ErrHandshakeMessageOutOfOrder),
    );
    run
}

/// The plaintext messages of `items`, in the order sent, as (type, sequence number).
fn order_of(items: &[Item]) -> Vec<(u8, u16)> {
    items
        .iter()
        .filter_map(|item| match item {
            Item::Message { typ, seq, .. } => Some((*typ, *seq)),
            Item::Record(_) => None,
        })
        .collect()
}

/// Checks the edited flight's messages are `expected`, by type, with consecutive sequence
/// numbers from the first: the edit made the flight it is meant to.
fn assert_sent(items: &[Item], expected: &[u8]) {
    let order = order_of(items);
    let first = order.first().expect("the flight has messages").1;
    let wanted: Vec<(u8, u16)> = expected
        .iter()
        .enumerate()
        .map(|(i, typ)| (*typ, first + i as u16))
        .collect();
    assert_eq!(order, wanted, "the edited flight");
}

/// NDSS 2023 "ClientKeyExchange before Certificate": the client sends its key exchange first.
#[test]
fn a_client_key_exchange_before_the_certificate_is_an_unexpected_message() {
    let run = server_refuses(
        certified_client(self_signed()),
        requiring_server(),
        |items, _| swap(items, CERTIFICATE, CLIENT_KEY_EXCHANGE),
    );
    assert_sent(
        run.edited(),
        &[CLIENT_KEY_EXCHANGE, CERTIFICATE, CERTIFICATE_VERIFY],
    );
}

/// NDSS 2023 "Unauthenticated ClientKeyExchange": the CertificateVerify before the key
/// exchange it should sign.
#[test]
fn a_certificate_verify_before_the_client_key_exchange_is_an_unexpected_message() {
    let run = server_refuses(
        certified_client(self_signed()),
        requiring_server(),
        |items, _| swap(items, CLIENT_KEY_EXCHANGE, CERTIFICATE_VERIFY),
    );
    assert_sent(
        run.edited(),
        &[CERTIFICATE, CERTIFICATE_VERIFY, CLIENT_KEY_EXCHANGE],
    );
}

/// The ServerKeyExchange before the server's Certificate.
#[test]
fn a_server_key_exchange_before_the_server_certificate_is_an_unexpected_message() {
    let run = client_refuses(
        server_with(builder(), self_signed()),
        client(builder()),
        |items, _| swap(items, CERTIFICATE, SERVER_KEY_EXCHANGE),
    );
    assert_sent(
        run.edited(),
        &[
            SERVER_HELLO,
            SERVER_KEY_EXCHANGE,
            CERTIFICATE,
            SERVER_HELLO_DONE,
        ],
    );
}

/// NDSS 2023 "CertificateRequest before Certificate".
#[test]
fn a_certificate_request_before_the_server_certificate_is_an_unexpected_message() {
    let run = client_refuses(
        requiring_server(),
        certified_client(self_signed()),
        |items, _| swap(items, CERTIFICATE, CERTIFICATE_REQUEST),
    );
    assert_sent(
        run.edited(),
        &[
            SERVER_HELLO,
            CERTIFICATE_REQUEST,
            SERVER_KEY_EXCHANGE,
            CERTIFICATE,
            SERVER_HELLO_DONE,
        ],
    );
}

/// The ServerHelloDone before the ServerKeyExchange.
#[test]
fn a_server_hello_done_before_the_server_key_exchange_is_an_unexpected_message() {
    let run = client_refuses(
        server_with(builder(), self_signed()),
        client(builder()),
        |items, _| swap(items, SERVER_KEY_EXCHANGE, SERVER_HELLO_DONE),
    );
    assert_sent(
        run.edited(),
        &[
            SERVER_HELLO,
            CERTIFICATE,
            SERVER_HELLO_DONE,
            SERVER_KEY_EXCHANGE,
        ],
    );
}

/// NDSS 2023 "Multiple Certificate" (server side): the client's Certificate twice.
#[test]
fn a_repeated_client_certificate_is_an_unexpected_message() {
    let run = server_refuses(
        certified_client(self_signed()),
        requiring_server(),
        |items, _| {
            repeat(items, CERTIFICATE);
            messages_only(items);
        },
    );
    assert_sent(
        run.edited(),
        &[
            CERTIFICATE,
            CERTIFICATE,
            CLIENT_KEY_EXCHANGE,
            CERTIFICATE_VERIFY,
        ],
    );
}

/// TLS-Anvil `secondClientKeyExchange`: the ClientKeyExchange twice.
#[test]
fn a_repeated_client_key_exchange_is_an_unexpected_message() {
    let run = server_refuses(
        client(builder()),
        server_with(builder(), self_signed()),
        |items, _| {
            repeat(items, CLIENT_KEY_EXCHANGE);
            messages_only(items);
        },
    );
    assert_sent(run.edited(), &[CLIENT_KEY_EXCHANGE, CLIENT_KEY_EXCHANGE]);
}

/// The CertificateVerify twice.
#[test]
fn a_repeated_certificate_verify_is_an_unexpected_message() {
    let run = server_refuses(
        certified_client(self_signed()),
        requiring_server(),
        |items, _| {
            repeat(items, CERTIFICATE_VERIFY);
            messages_only(items);
        },
    );
    assert_sent(
        run.edited(),
        &[
            CERTIFICATE,
            CLIENT_KEY_EXCHANGE,
            CERTIFICATE_VERIFY,
            CERTIFICATE_VERIFY,
        ],
    );
}

/// NDSS 2023 "Multiple Certificate" (client side): the server's Certificate twice.
#[test]
fn a_repeated_server_certificate_is_an_unexpected_message() {
    let run = client_refuses(
        server_with(builder(), self_signed()),
        client(builder()),
        |items, _| repeat(items, CERTIFICATE),
    );
    assert_sent(
        run.edited(),
        &[
            SERVER_HELLO,
            CERTIFICATE,
            CERTIFICATE,
            SERVER_KEY_EXCHANGE,
            SERVER_HELLO_DONE,
        ],
    );
}

/// NDSS 2023 "Multiple CertificateRequest".
#[test]
fn a_repeated_certificate_request_is_an_unexpected_message() {
    let run = client_refuses(
        requiring_server(),
        certified_client(self_signed()),
        |items, _| repeat(items, CERTIFICATE_REQUEST),
    );
    assert_sent(
        run.edited(),
        &[
            SERVER_HELLO,
            CERTIFICATE,
            SERVER_KEY_EXCHANGE,
            CERTIFICATE_REQUEST,
            CERTIFICATE_REQUEST,
            SERVER_HELLO_DONE,
        ],
    );
}

/// USENIX 2026 "Public Key Protected" (server key, next sequence number) and NDSS 2023
/// "Multiple ServerKeyExchange": a second ServerKeyExchange with another share after the
/// first, under the next sequence number. The client never reaches the point of using it.
#[test]
fn a_second_server_key_exchange_under_the_next_sequence_number_is_an_unexpected_message() {
    let run = client_refuses(
        server_with(builder(), self_signed()),
        client(builder()),
        |items, _| {
            repeat(items, SERVER_KEY_EXCHANGE);
            let at = index_of(items, SERVER_KEY_EXCHANGE) + 1;
            if let Item::Message { body, .. } = &mut items[at] {
                *body = with_other_key(body, SERVER_KEY_AT);
            }
        },
    );
    assert_sent(
        run.edited(),
        &[
            SERVER_HELLO,
            CERTIFICATE,
            SERVER_KEY_EXCHANGE,
            SERVER_KEY_EXCHANGE,
            SERVER_HELLO_DONE,
        ],
    );
}

/// USENIX 2026 "Public Key Protected" (client key, next sequence number): a second
/// ClientKeyExchange with another share after the CertificateVerify, under the next sequence
/// number. The server never computes a secret from it.
#[test]
fn a_second_client_key_exchange_after_the_certificate_verify_is_an_unexpected_message() {
    let run = server_refuses(
        certified_client(self_signed()),
        requiring_server(),
        |items, _| {
            messages_only(items);
            let at = index_of(items, CLIENT_KEY_EXCHANGE);
            let Item::Message { typ, body, .. } = items[at].clone() else {
                unreachable!()
            };
            let seq = seq_of(items, CERTIFICATE_VERIFY) + 1;
            items.push(Item::Message {
                typ,
                seq,
                body: with_other_key(&body, CLIENT_KEY_AT),
            });
        },
    );
    assert_sent(
        run.edited(),
        &[
            CERTIFICATE,
            CLIENT_KEY_EXCHANGE,
            CERTIFICATE_VERIFY,
            CLIENT_KEY_EXCHANGE,
        ],
    );
}

/// The ClientKeyExchange left out: a CertificateVerify where the key exchange must be.
#[test]
fn a_client_flight_without_client_key_exchange_is_an_unexpected_message() {
    let run = server_refuses(
        certified_client(self_signed()),
        requiring_server(),
        |items, _| {
            omit(items, CLIENT_KEY_EXCHANGE);
            messages_only(items);
        },
    );
    assert_sent(run.edited(), &[CERTIFICATE, CERTIFICATE_VERIFY]);
}

/// The ServerKeyExchange left out: an ECDHE suite needs it (RFC 8422 5.4), and the
/// ServerHelloDone is where it must be.
#[test]
fn a_server_flight_without_server_key_exchange_is_an_unexpected_message() {
    let run = client_refuses(
        server_with(builder(), self_signed()),
        client(builder()),
        |items, _| omit(items, SERVER_KEY_EXCHANGE),
    );
    assert_sent(
        run.edited(),
        &[SERVER_HELLO, CERTIFICATE, SERVER_HELLO_DONE],
    );
}

/// NDSS 2023 "ServerHello Flight Restart" (and "Switching Cipher Suite"): after its flight the
/// server starts again with a ServerHello, under the sequence number its Finished should have.
/// The client, waiting for that Finished, refuses it.
#[test]
fn a_server_hello_after_the_server_flight_is_an_unexpected_message() {
    let run = run(
        client(builder()),
        server_with(builder(), self_signed()),
        Side::Server,
        |items| items.iter().any(is_change_cipher_spec),
        |items, server| {
            let server_hello = server.cache.pull_and_merge(&[HandshakeCachePullRule {
                typ: HandshakeType::ServerHello,
                epoch: 0,
                is_client: false,
                optional: false,
            }]);
            assert!(server_hello.len() > HANDSHAKE_HEADER_LENGTH);
            let seq = (server.state.handshake_send_sequence - 1) as u16;
            items.insert(
                0,
                Item::Message {
                    typ: SERVER_HELLO,
                    seq,
                    body: server_hello[HANDSHAKE_HEADER_LENGTH..].to_vec(),
                },
            );
        },
    );
    let edited = run.edited();
    assert!(matches!(
        &edited[0],
        Item::Message {
            typ: SERVER_HELLO,
            ..
        }
    ));
    assert!(
        edited.iter().any(is_protected),
        "the server's Finished follows"
    );
    run.assert_refused(
        Side::Client,
        AlertDescription::UnexpectedMessage,
        Some(Error::ErrHandshakeMessageOutOfOrder),
    );
}

// ---------------------------------------------------------------------------------------------
// Certificate messages required, and not asked for (RFC 5246 7.4.2, 7.4.6)
// ---------------------------------------------------------------------------------------------

/// A Certificate message body carrying `certificate`'s chain.
fn certificate_body(certificate: &Certificate) -> Vec<u8> {
    let mut entries = vec![];
    for der in &certificate.certificate {
        entries.extend_from_slice(&(der.as_ref().len() as u32).to_be_bytes()[1..]);
        entries.extend_from_slice(der.as_ref());
    }
    let mut body = (entries.len() as u32).to_be_bytes()[1..].to_vec();
    body.extend_from_slice(&entries);
    body
}

/// The server's Certificate left out (NDSS 2023's client-side "Certificate-less" patterns):
/// every suite but PSK authenticates the server with it, so the ServerKeyExchange in its place
/// is out of order. (Before, the client went on and failed only when the ServerKeyExchange
/// signature could not be checked: decrypt_error.)
#[test]
fn a_server_flight_without_certificate_is_an_unexpected_message() {
    let run = client_refuses(
        server_with(builder(), self_signed()),
        client(builder()),
        |items, _| omit(items, CERTIFICATE),
    );
    assert_sent(
        run.edited(),
        &[SERVER_HELLO, SERVER_KEY_EXCHANGE, SERVER_HELLO_DONE],
    );
}

/// USENIX 2026 "No Flow Bypass" (Certificate left out) and NDSS 2023 "Certificate-less Client
/// Authentication": asked for a certificate, the client leaves the Certificate message out
/// (rather than sending an empty one) and goes on with its key exchange and CertificateVerify.
#[test]
fn a_client_flight_without_the_requested_certificate_is_an_unexpected_message() {
    let run = server_refuses(
        certified_client(self_signed()),
        requiring_server(),
        |items, _| {
            omit(items, CERTIFICATE);
            messages_only(items);
        },
    );
    assert_sent(run.edited(), &[CLIENT_KEY_EXCHANGE, CERTIFICATE_VERIFY]);
}

/// USENIX 2026 "No Flow Bypass" (neither Certificate nor CertificateVerify): asked for a
/// certificate, the client sends its key exchange, ChangeCipherSpec and Finished only.
#[test]
fn a_client_flight_without_certificate_and_certificate_verify_is_an_unexpected_message() {
    let run = server_refuses(
        certified_client(self_signed()),
        requiring_server(),
        |items, _| {
            omit(items, CERTIFICATE);
            let at = index_of(items, CERTIFICATE_VERIFY);
            items.remove(at);
        },
    );
    let edited = run.edited();
    assert_sent(edited, &[CLIENT_KEY_EXCHANGE]);
    assert!(edited.iter().any(is_protected), "the Finished was sent");
}

/// NDSS 2023 "Unrequested Certificate": a client certificate the server did not ask for (it
/// sent no CertificateRequest) is out of place (RFC 5246 7.4.6: "only sent if the server
/// requests a certificate").
#[test]
fn an_unrequested_client_certificate_is_an_unexpected_message() {
    let run = server_refuses(
        client(builder()),
        server_with(builder(), self_signed()),
        |items, _| {
            messages_only(items);
            let at = index_of(items, CLIENT_KEY_EXCHANGE);
            let seq = seq_of(items, CLIENT_KEY_EXCHANGE);
            renumber_from(items, at, 1);
            items.insert(
                at,
                Item::Message {
                    typ: CERTIFICATE,
                    seq,
                    body: certificate_body(&self_signed()),
                },
            );
        },
    );
    assert_sent(run.edited(), &[CERTIFICATE, CLIENT_KEY_EXCHANGE]);
    assert!(
        !has(&items_of(&run.from_server), CERTIFICATE_REQUEST),
        "the server asked for no certificate"
    );
}

// ---------------------------------------------------------------------------------------------
// Malformed messages at the connection (RFC 6347 4.1.2.7, RFC 5246 7.2.2)
// ---------------------------------------------------------------------------------------------

const HELLO_VERIFY_REQUEST: u8 = 3;

fn with_a_byte_more(body: &[u8]) -> Vec<u8> {
    [body, &[0]].concat()
}

fn with_a_byte_less(body: &[u8]) -> Vec<u8> {
    body[..body.len() - 1].to_vec()
}

/// Sends, ahead of message `typ`, a copy changed by `change` under the same sequence number.
fn malformed_copy_first(
    typ: u8,
    change: fn(&[u8]) -> Vec<u8>,
) -> impl FnMut(&mut Vec<Item>, &mut DTLSConn) {
    move |items, _| {
        let at = index_of(items, typ);
        let Item::Message { typ, seq, body } = items[at].clone() else {
            unreachable!()
        };
        items.insert(
            at,
            Item::Message {
                typ,
                seq,
                body: change(&body),
            },
        );
    }
}

/// The edited flight carries message `typ` twice under one sequence number, the first copy
/// not the second.
fn assert_copy_sent(items: &[Item], typ: u8) {
    let copies: Vec<&Item> = items
        .iter()
        .filter(|item| matches!(item, Item::Message { typ: t, .. } if *t == typ))
        .collect();
    match copies.as_slice() {
        [
            Item::Message {
                seq: a,
                body: first,
                ..
            },
            Item::Message {
                seq: b,
                body: second,
                ..
            },
        ] => {
            assert_eq!(a, b, "one sequence number");
            assert_ne!(first, second, "the first copy is changed");
        }
        other => panic!("two copies of type {typ} were sent: {other:?}"),
    }
}

type Change = (&'static str, fn(&[u8]) -> Vec<u8>);

const CHANGES: [Change; 2] = [
    ("a byte more", with_a_byte_more),
    ("a byte less", with_a_byte_less),
];

/// RFC 6347 4.1.2.7: a plaintext handshake message that does not parse (a byte more or less
/// than its fields say) is dropped without an alert, and without taking the place of the
/// genuine message under the same sequence number: the handshake completes. Anyone can send a
/// plaintext record from the peer's address, so answering it would let them end the handshake.
/// The client's side: every message of the server's flights.
#[test]
fn a_malformed_server_message_in_the_clear_is_dropped_and_the_genuine_one_taken() {
    let cases = [
        HELLO_VERIFY_REQUEST,
        SERVER_HELLO,
        CERTIFICATE,
        SERVER_KEY_EXCHANGE,
        CERTIFICATE_REQUEST,
        SERVER_HELLO_DONE,
    ];
    let mut ran = 0;
    for typ in cases {
        for (name, change) in CHANGES {
            if typ == SERVER_HELLO_DONE && name == "a byte less" {
                continue; // an empty body has no byte to take
            }
            let run = run(
                certified_client(self_signed()),
                requiring_server(),
                Side::Server,
                flight_with(typ),
                malformed_copy_first(typ, change),
            );
            assert_copy_sent(run.edited(), typ);
            assert!(
                run.client.is_handshake_completed() && run.server.is_handshake_completed(),
                "type {typ}, {name}: client {:?}, server {:?}",
                run.client_err,
                run.server_err
            );
            run.assert_completed();
            ran += 1;
        }
    }
    assert_eq!(ran, 11);
}

/// The server's side: every message of the client's last flight in the clear.
#[test]
fn a_malformed_client_message_in_the_clear_is_dropped_and_the_genuine_one_taken() {
    let mut ran = 0;
    for typ in [CERTIFICATE, CLIENT_KEY_EXCHANGE, CERTIFICATE_VERIFY] {
        for (name, change) in CHANGES {
            let run = run(
                certified_client(self_signed()),
                requiring_server(),
                Side::Client,
                flight_with(CLIENT_KEY_EXCHANGE),
                malformed_copy_first(typ, change),
            );
            assert_copy_sent(run.edited(), typ);
            assert!(
                run.client.is_handshake_completed() && run.server.is_handshake_completed(),
                "type {typ}, {name}: client {:?}, server {:?}",
                run.client_err,
                run.server_err
            );
            run.assert_completed();
            ran += 1;
        }
    }
    assert_eq!(ran, 6);
}

/// RFC 5246 7.4.9, 7.2.2: a Finished whose verify_data is not 12 bytes long cannot be decoded.
/// It is protected, so it is the peer's: decode_error, from the server for the client's
/// Finished and from the client for the server's. (Before, it was taken and compared, and
/// refused as a Finished that does not verify: decrypt_error.)
#[test]
fn a_finished_of_the_wrong_length_is_a_decode_error() {
    for length in [11, 13, 0] {
        for side in [Side::Client, Side::Server] {
            let run = run(
                client(builder()),
                server_with(builder(), self_signed()),
                side,
                |items| items.iter().any(is_change_cipher_spec),
                |items, sender| {
                    let before = items.len();
                    items.retain(|item| !is_protected(item));
                    assert_eq!(items.len(), before - 1, "one protected Finished");
                    let seq = (sender.state.handshake_send_sequence - 1) as u16;
                    let mut verify_data = sender.state.local_verify_data.clone();
                    assert_eq!(verify_data.len(), 12);
                    verify_data.resize(length, 0x5a);
                    let finished = handshake_message(FINISHED, seq, &verify_data);
                    let record = protected_by(sender, ContentType::Handshake, &finished);
                    items.push(Item::Record(record));
                },
            );
            let refuser = match side {
                Side::Client => Side::Server,
                Side::Server => Side::Client,
            };
            let conn = run.conn(refuser);
            assert!(run.edited.is_some(), "{side:?}'s last flight was edited");
            assert!(
                conn.is_failed(),
                "{length} bytes from {side:?}: {:?}",
                run.err(refuser)
            );
            assert_eq!(
                conn.fatal_alerts().0,
                Some(AlertDescription::DecodeError as u8),
                "{length} bytes from {side:?}: {:?}",
                run.err(refuser)
            );
            assert!(!conn.is_handshake_completed());
            assert!(
                conn.connection_state()
                    .export_keying_material(SRTP_LABEL, &[], 30)
                    .is_err()
            );
        }
    }
}

// ---------------------------------------------------------------------------------------------
// PSK flights (RFC 4279 2): no Certificate, a ServerKeyExchange only with a hint
// ---------------------------------------------------------------------------------------------

fn psk_builder(hint: Option<Vec<u8>>) -> ConfigBuilder {
    ConfigBuilder::default()
        .with_crypto_provider(provider())
        .with_psk(Some(Arc::new(|_hint: &[u8]| Ok(vec![0xab, 0xc1, 0x23]))))
        .with_psk_identity_hint(hint)
        .with_cipher_suites(vec![
            crate::cipher_suite::CipherSuiteId::Tls_Psk_With_Aes_128_Ccm_8,
        ])
}

/// A PSK handshake needs no Certificate either way, and a ServerKeyExchange only when the
/// server gives an identity hint (RFC 4279 2): without one, with an empty one and with one,
/// the handshake completes. The hint goes as `psk_identity_hint<0..2^16-1>`, an empty one as
/// `00 00` (it used to go as an ECDHE ServerKeyExchange with every field zero, which a client
/// that parses ECPoint<1..2^8-1> drops).
#[test]
fn psk_flights_carry_no_certificate_and_a_server_key_exchange_only_with_a_hint() {
    for hint in [None, Some(vec![]), Some(b"hint".to_vec())] {
        let server = DTLSConn::new(
            Arc::new(
                psk_builder(hint.clone())
                    .build(false, None)
                    .expect("a PSK server configuration"),
            ),
            false,
            None,
        );
        let run = run(
            client(psk_builder(Some(b"client identity".to_vec()))),
            server,
            Side::Server,
            |_| false,
            |_, _| {},
        );
        assert_eq!(run.client_err, None, "hint {hint:?}");
        assert_eq!(run.server_err, None, "hint {hint:?}");
        assert!(run.client.is_handshake_completed(), "hint {hint:?}");
        assert!(run.server.is_handshake_completed(), "hint {hint:?}");
        let server_messages = items_of(&run.from_server);
        let client_messages = items_of(&run.from_client);
        assert!(!has(&server_messages, CERTIFICATE), "hint {hint:?}");
        assert!(!has(&client_messages, CERTIFICATE), "hint {hint:?}");
        let server_key_exchange = server_messages.iter().find_map(|item| match item {
            Item::Message {
                typ: SERVER_KEY_EXCHANGE,
                body,
                ..
            } => Some(body.clone()),
            _ => None,
        });
        let expected = hint.map(|hint| {
            let mut body = (hint.len() as u16).to_be_bytes().to_vec();
            body.extend_from_slice(&hint);
            body
        });
        assert_eq!(server_key_exchange, expected);
    }
}