-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.rs
7424 lines (6519 loc) · 249 KB
/
api.rs
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
//! Assorted public API tests.
#![allow(clippy::duplicate_mod)]
use std::fmt::Debug;
use std::io::{self, IoSlice, Read, Write};
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::{fmt, mem};
use pki_types::{CertificateDer, IpAddr, ServerName, UnixTime};
use rustls::client::{verify_server_cert_signed_by_trust_anchor, ResolvesClientCert, Resumption};
use rustls::crypto::CryptoProvider;
use rustls::internal::msgs::base::Payload;
use rustls::internal::msgs::codec::Codec;
use rustls::internal::msgs::enums::{AlertLevel, Compression};
use rustls::internal::msgs::handshake::{
ClientExtension, ClientHelloPayload, HandshakeMessagePayload, HandshakePayload, Random,
ServerName as ServerNameExtensionItem, SessionId,
};
use rustls::internal::msgs::message::{Message, MessagePayload, PlainMessage};
use rustls::server::{ClientHello, ParsedCertificate, ResolvesServerCert};
#[cfg(feature = "aws_lc_rs")]
use rustls::{
client::{EchConfig, EchGreaseConfig, EchMode},
crypto::aws_lc_rs::hpke::ALL_SUPPORTED_SUITES,
internal::msgs::base::PayloadU16,
internal::msgs::handshake::{
EchConfigContents, EchConfigPayload, HpkeKeyConfig, HpkeSymmetricCipherSuite,
},
pki_types::{DnsName, EchConfigListBytes},
};
use rustls::{
sign, AlertDescription, CertificateError, CipherSuite, ClientConfig, ClientConnection,
ConnectionCommon, ConnectionTrafficSecrets, ContentType, DistinguishedName, Error,
HandshakeKind, HandshakeType, InconsistentKeys, InvalidMessage, KeyLog, NamedGroup,
PeerIncompatible, PeerMisbehaved, ProtocolVersion, ServerConfig, ServerConnection, SideData,
SignatureScheme, Stream, StreamOwned, SupportedCipherSuite,
};
use super::*;
mod common;
use common::*;
use provider::cipher_suite;
use provider::sign::RsaSigningKey;
use rustls::ProtocolVersion::TLSv1_2;
fn alpn_test_error(
server_protos: Vec<Vec<u8>>,
client_protos: Vec<Vec<u8>>,
agreed: Option<&[u8]>,
expected_error: Option<ErrorFromPeer>,
) {
let mut server_config = make_server_config(KeyType::Rsa2048);
server_config.alpn_protocols = server_protos;
let server_config = Arc::new(server_config);
for version in rustls::ALL_VERSIONS {
let mut client_config = make_client_config_with_versions(KeyType::Rsa2048, &[version]);
client_config
.alpn_protocols
.clone_from(&client_protos);
let (mut client, mut server) =
make_pair_for_arc_configs(&Arc::new(client_config), &server_config);
assert_eq!(client.alpn_protocol(), None);
assert_eq!(server.alpn_protocol(), None);
let error = do_handshake_until_error(&mut client, &mut server);
assert_eq!(client.alpn_protocol(), agreed);
assert_eq!(server.alpn_protocol(), agreed);
assert_eq!(error.err(), expected_error);
}
}
fn alpn_test(server_protos: Vec<Vec<u8>>, client_protos: Vec<Vec<u8>>, agreed: Option<&[u8]>) {
alpn_test_error(server_protos, client_protos, agreed, None)
}
#[test]
fn alpn() {
// no support
alpn_test(vec![], vec![], None);
// server support
alpn_test(vec![b"server-proto".to_vec()], vec![], None);
// client support
alpn_test(vec![], vec![b"client-proto".to_vec()], None);
// no overlap
alpn_test_error(
vec![b"server-proto".to_vec()],
vec![b"client-proto".to_vec()],
None,
Some(ErrorFromPeer::Server(Error::NoApplicationProtocol)),
);
// server chooses preference
alpn_test(
vec![b"server-proto".to_vec(), b"client-proto".to_vec()],
vec![b"client-proto".to_vec(), b"server-proto".to_vec()],
Some(b"server-proto"),
);
// case sensitive
alpn_test_error(
vec![b"PROTO".to_vec()],
vec![b"proto".to_vec()],
None,
Some(ErrorFromPeer::Server(Error::NoApplicationProtocol)),
);
}
fn version_test(
client_versions: &[&'static rustls::SupportedProtocolVersion],
server_versions: &[&'static rustls::SupportedProtocolVersion],
result: Option<ProtocolVersion>,
) {
let client_versions = if client_versions.is_empty() {
rustls::ALL_VERSIONS
} else {
client_versions
};
let server_versions = if server_versions.is_empty() {
rustls::ALL_VERSIONS
} else {
server_versions
};
let client_config = make_client_config_with_versions(KeyType::Rsa2048, client_versions);
let server_config = make_server_config_with_versions(KeyType::Rsa2048, server_versions);
println!(
"version {:?} {:?} -> {:?}",
client_versions, server_versions, result
);
let (mut client, mut server) = make_pair_for_configs(client_config, server_config);
assert_eq!(client.protocol_version(), None);
assert_eq!(server.protocol_version(), None);
if result.is_none() {
let err = do_handshake_until_error(&mut client, &mut server);
assert!(err.is_err());
} else {
do_handshake(&mut client, &mut server);
assert_eq!(client.protocol_version(), result);
assert_eq!(server.protocol_version(), result);
}
}
#[test]
fn versions() {
// default -> 1.3
version_test(&[], &[], Some(ProtocolVersion::TLSv1_3));
// client default, server 1.2 -> 1.2
#[cfg(feature = "tls12")]
version_test(
&[],
&[&rustls::version::TLS12],
Some(ProtocolVersion::TLSv1_2),
);
// client 1.2, server default -> 1.2
#[cfg(feature = "tls12")]
version_test(
&[&rustls::version::TLS12],
&[],
Some(ProtocolVersion::TLSv1_2),
);
// client 1.2, server 1.3 -> fail
#[cfg(feature = "tls12")]
version_test(&[&rustls::version::TLS12], &[&rustls::version::TLS13], None);
// client 1.3, server 1.2 -> fail
#[cfg(feature = "tls12")]
version_test(&[&rustls::version::TLS13], &[&rustls::version::TLS12], None);
// client 1.3, server 1.2+1.3 -> 1.3
#[cfg(feature = "tls12")]
version_test(
&[&rustls::version::TLS13],
&[&rustls::version::TLS12, &rustls::version::TLS13],
Some(ProtocolVersion::TLSv1_3),
);
// client 1.2+1.3, server 1.2 -> 1.2
#[cfg(feature = "tls12")]
version_test(
&[&rustls::version::TLS13, &rustls::version::TLS12],
&[&rustls::version::TLS12],
Some(ProtocolVersion::TLSv1_2),
);
}
fn check_read(reader: &mut dyn io::Read, bytes: &[u8]) {
let mut buf = vec![0u8; bytes.len() + 1];
assert_eq!(bytes.len(), reader.read(&mut buf).unwrap());
assert_eq!(bytes, &buf[..bytes.len()]);
}
fn check_read_err(reader: &mut dyn io::Read, err_kind: io::ErrorKind) {
let mut buf = vec![0u8; 1];
let err = reader.read(&mut buf).unwrap_err();
assert!(matches!(err, err if err.kind() == err_kind))
}
#[cfg(read_buf)]
fn check_read_buf(reader: &mut dyn io::Read, bytes: &[u8]) {
use core::io::BorrowedBuf;
use std::mem::MaybeUninit;
let mut buf = [MaybeUninit::<u8>::uninit(); 128];
let mut buf: BorrowedBuf<'_> = buf.as_mut_slice().into();
reader.read_buf(buf.unfilled()).unwrap();
assert_eq!(buf.filled(), bytes);
}
#[cfg(read_buf)]
fn check_read_buf_err(reader: &mut dyn io::Read, err_kind: io::ErrorKind) {
use core::io::BorrowedBuf;
use std::mem::MaybeUninit;
let mut buf = [MaybeUninit::<u8>::uninit(); 1];
let mut buf: BorrowedBuf<'_> = buf.as_mut_slice().into();
let err = reader
.read_buf(buf.unfilled())
.unwrap_err();
assert!(matches!(err, err if err.kind() == err_kind))
}
#[test]
fn config_builder_for_client_rejects_empty_kx_groups() {
assert_eq!(
ClientConfig::builder_with_provider(
CryptoProvider {
kx_groups: Vec::default(),
..provider::default_provider()
}
.into()
)
.with_safe_default_protocol_versions()
.err(),
Some(Error::General("no kx groups configured".into()))
);
}
#[test]
fn config_builder_for_client_rejects_empty_cipher_suites() {
assert_eq!(
ClientConfig::builder_with_provider(
CryptoProvider {
cipher_suites: Vec::default(),
..provider::default_provider()
}
.into()
)
.with_safe_default_protocol_versions()
.err(),
Some(Error::General("no usable cipher suites configured".into()))
);
}
#[cfg(feature = "tls12")]
#[test]
fn config_builder_for_client_rejects_incompatible_cipher_suites() {
assert_eq!(
ClientConfig::builder_with_provider(
CryptoProvider {
cipher_suites: vec![cipher_suite::TLS13_AES_256_GCM_SHA384],
..provider::default_provider()
}
.into()
)
.with_protocol_versions(&[&rustls::version::TLS12])
.err(),
Some(Error::General("no usable cipher suites configured".into()))
);
}
#[test]
fn config_builder_for_server_rejects_empty_kx_groups() {
assert_eq!(
ServerConfig::builder_with_provider(
CryptoProvider {
kx_groups: Vec::default(),
..provider::default_provider()
}
.into()
)
.with_safe_default_protocol_versions()
.err(),
Some(Error::General("no kx groups configured".into()))
);
}
#[test]
fn config_builder_for_server_rejects_empty_cipher_suites() {
assert_eq!(
ServerConfig::builder_with_provider(
CryptoProvider {
cipher_suites: Vec::default(),
..provider::default_provider()
}
.into()
)
.with_safe_default_protocol_versions()
.err(),
Some(Error::General("no usable cipher suites configured".into()))
);
}
#[cfg(feature = "tls12")]
#[test]
fn config_builder_for_server_rejects_incompatible_cipher_suites() {
assert_eq!(
ServerConfig::builder_with_provider(
CryptoProvider {
cipher_suites: vec![cipher_suite::TLS13_AES_256_GCM_SHA384],
..provider::default_provider()
}
.into()
)
.with_protocol_versions(&[&rustls::version::TLS12])
.err(),
Some(Error::General("no usable cipher suites configured".into()))
);
}
#[test]
fn config_builder_for_client_with_time() {
ClientConfig::builder_with_details(
provider::default_provider().into(),
Arc::new(rustls::time_provider::DefaultTimeProvider),
)
.with_safe_default_protocol_versions()
.unwrap();
}
#[test]
fn config_builder_for_server_with_time() {
ServerConfig::builder_with_details(
provider::default_provider().into(),
Arc::new(rustls::time_provider::DefaultTimeProvider),
)
.with_safe_default_protocol_versions()
.unwrap();
}
#[test]
fn buffered_client_data_sent() {
let server_config = Arc::new(make_server_config(KeyType::Rsa2048));
for version in rustls::ALL_VERSIONS {
let client_config = make_client_config_with_versions(KeyType::Rsa2048, &[version]);
let (mut client, mut server) =
make_pair_for_arc_configs(&Arc::new(client_config), &server_config);
assert_eq!(5, client.writer().write(b"hello").unwrap());
do_handshake(&mut client, &mut server);
transfer(&mut client, &mut server);
server.process_new_packets().unwrap();
check_read(&mut server.reader(), b"hello");
}
}
#[test]
fn buffered_server_data_sent() {
let server_config = Arc::new(make_server_config(KeyType::Rsa2048));
for version in rustls::ALL_VERSIONS {
let client_config = make_client_config_with_versions(KeyType::Rsa2048, &[version]);
let (mut client, mut server) =
make_pair_for_arc_configs(&Arc::new(client_config), &server_config);
assert_eq!(5, server.writer().write(b"hello").unwrap());
do_handshake(&mut client, &mut server);
transfer(&mut server, &mut client);
client.process_new_packets().unwrap();
check_read(&mut client.reader(), b"hello");
}
}
#[test]
fn buffered_both_data_sent() {
let server_config = Arc::new(make_server_config(KeyType::Rsa2048));
for version in rustls::ALL_VERSIONS {
let client_config = make_client_config_with_versions(KeyType::Rsa2048, &[version]);
let (mut client, mut server) =
make_pair_for_arc_configs(&Arc::new(client_config), &server_config);
assert_eq!(
12,
server
.writer()
.write(b"from-server!")
.unwrap()
);
assert_eq!(
12,
client
.writer()
.write(b"from-client!")
.unwrap()
);
do_handshake(&mut client, &mut server);
transfer(&mut server, &mut client);
client.process_new_packets().unwrap();
transfer(&mut client, &mut server);
server.process_new_packets().unwrap();
check_read(&mut client.reader(), b"from-server!");
check_read(&mut server.reader(), b"from-client!");
}
}
#[test]
fn client_can_get_server_cert() {
for kt in ALL_KEY_TYPES {
for version in rustls::ALL_VERSIONS {
let client_config = make_client_config_with_versions(*kt, &[version]);
let (mut client, mut server) =
make_pair_for_configs(client_config, make_server_config(*kt));
do_handshake(&mut client, &mut server);
let certs = client.peer_certificates();
assert_eq!(certs, Some(kt.get_chain().as_slice()));
}
}
}
#[test]
fn client_can_get_server_cert_after_resumption() {
for kt in ALL_KEY_TYPES {
let server_config = make_server_config(*kt);
for version in rustls::ALL_VERSIONS {
let client_config = make_client_config_with_versions(*kt, &[version]);
let (mut client, mut server) =
make_pair_for_configs(client_config.clone(), server_config.clone());
do_handshake(&mut client, &mut server);
let original_certs = client.peer_certificates();
let (mut client, mut server) =
make_pair_for_configs(client_config.clone(), server_config.clone());
do_handshake(&mut client, &mut server);
let resumed_certs = client.peer_certificates();
assert_eq!(original_certs, resumed_certs);
}
}
}
#[test]
fn server_can_get_client_cert() {
for kt in ALL_KEY_TYPES {
let server_config = Arc::new(make_server_config_with_mandatory_client_auth(*kt));
for version in rustls::ALL_VERSIONS {
let client_config = make_client_config_with_versions_with_auth(*kt, &[version]);
let (mut client, mut server) =
make_pair_for_arc_configs(&Arc::new(client_config), &server_config);
do_handshake(&mut client, &mut server);
let certs = server.peer_certificates();
assert_eq!(certs, Some(kt.get_client_chain().as_slice()));
}
}
}
#[test]
fn server_can_get_client_cert_after_resumption() {
for kt in ALL_KEY_TYPES {
let server_config = Arc::new(make_server_config_with_mandatory_client_auth(*kt));
for version in rustls::ALL_VERSIONS {
let client_config = make_client_config_with_versions_with_auth(*kt, &[version]);
let client_config = Arc::new(client_config);
let (mut client, mut server) =
make_pair_for_arc_configs(&client_config, &server_config);
do_handshake(&mut client, &mut server);
let original_certs = server.peer_certificates();
let (mut client, mut server) =
make_pair_for_arc_configs(&client_config, &server_config);
do_handshake(&mut client, &mut server);
let resumed_certs = server.peer_certificates();
assert_eq!(original_certs, resumed_certs);
}
}
}
#[test]
fn resumption_combinations() {
let expected_kx = match provider_is_fips() {
true => NamedGroup::secp256r1,
false => NamedGroup::X25519,
};
for kt in ALL_KEY_TYPES {
let server_config = make_server_config(*kt);
for version in rustls::ALL_VERSIONS {
let client_config = make_client_config_with_versions(*kt, &[version]);
let (mut client, mut server) =
make_pair_for_configs(client_config.clone(), server_config.clone());
do_handshake(&mut client, &mut server);
assert_eq!(client.handshake_kind(), Some(HandshakeKind::Full));
assert_eq!(server.handshake_kind(), Some(HandshakeKind::Full));
assert_eq!(
client
.negotiated_key_exchange_group()
.unwrap()
.name(),
expected_kx
);
assert_eq!(
server
.negotiated_key_exchange_group()
.unwrap()
.name(),
expected_kx
);
let (mut client, mut server) =
make_pair_for_configs(client_config.clone(), server_config.clone());
do_handshake(&mut client, &mut server);
assert_eq!(client.handshake_kind(), Some(HandshakeKind::Resumed));
assert_eq!(server.handshake_kind(), Some(HandshakeKind::Resumed));
if version.version == TLSv1_2 {
assert!(client
.negotiated_key_exchange_group()
.is_none());
} else {
assert_eq!(
client
.negotiated_key_exchange_group()
.unwrap()
.name(),
expected_kx
);
}
assert!(server
.negotiated_key_exchange_group()
.is_none());
}
}
}
#[test]
fn test_config_builders_debug() {
if !provider_is_ring() {
return;
}
let b = ServerConfig::builder_with_provider(
CryptoProvider {
cipher_suites: vec![cipher_suite::TLS13_CHACHA20_POLY1305_SHA256],
kx_groups: vec![provider::kx_group::X25519],
..provider::default_provider()
}
.into(),
);
let _ = format!("{:?}", b);
let b = server_config_builder_with_versions(&[&rustls::version::TLS13]);
let _ = format!("{:?}", b);
let b = b.with_no_client_auth();
let _ = format!("{:?}", b);
let b = ClientConfig::builder_with_provider(
CryptoProvider {
cipher_suites: vec![cipher_suite::TLS13_CHACHA20_POLY1305_SHA256],
kx_groups: vec![provider::kx_group::X25519],
..provider::default_provider()
}
.into(),
);
let _ = format!("{:?}", b);
let b = client_config_builder_with_versions(&[&rustls::version::TLS13]);
let _ = format!("{:?}", b);
}
/// Test that the server handles combination of `offer_client_auth()` returning true
/// and `client_auth_mandatory` returning `Some(false)`. This exercises both the
/// client's and server's ability to "recover" from the server asking for a client
/// certificate and not being given one.
#[test]
fn server_allow_any_anonymous_or_authenticated_client() {
let kt = KeyType::Rsa2048;
for client_cert_chain in [None, Some(kt.get_client_chain())] {
let client_auth_roots = get_client_root_store(kt);
let client_auth = webpki_client_verifier_builder(client_auth_roots.clone())
.allow_unauthenticated()
.build()
.unwrap();
let server_config = server_config_builder()
.with_client_cert_verifier(client_auth)
.with_single_cert(kt.get_chain(), kt.get_key())
.unwrap();
let server_config = Arc::new(server_config);
for version in rustls::ALL_VERSIONS {
let client_config = if client_cert_chain.is_some() {
make_client_config_with_versions_with_auth(kt, &[version])
} else {
make_client_config_with_versions(kt, &[version])
};
let (mut client, mut server) =
make_pair_for_arc_configs(&Arc::new(client_config), &server_config);
do_handshake(&mut client, &mut server);
let certs = server.peer_certificates();
assert_eq!(certs, client_cert_chain.as_deref());
}
}
}
fn check_read_and_close(reader: &mut dyn io::Read, expect: &[u8]) {
check_read(reader, expect);
assert!(matches!(reader.read(&mut [0u8; 5]), Ok(0)));
}
#[test]
fn server_close_notify() {
let kt = KeyType::Rsa2048;
let server_config = Arc::new(make_server_config_with_mandatory_client_auth(kt));
for version in rustls::ALL_VERSIONS {
let client_config = make_client_config_with_versions_with_auth(kt, &[version]);
let (mut client, mut server) =
make_pair_for_arc_configs(&Arc::new(client_config), &server_config);
do_handshake(&mut client, &mut server);
// check that alerts don't overtake appdata
assert_eq!(
12,
server
.writer()
.write(b"from-server!")
.unwrap()
);
assert_eq!(
12,
client
.writer()
.write(b"from-client!")
.unwrap()
);
server.send_close_notify();
transfer(&mut server, &mut client);
let io_state = client.process_new_packets().unwrap();
assert!(io_state.peer_has_closed());
check_read_and_close(&mut client.reader(), b"from-server!");
transfer(&mut client, &mut server);
server.process_new_packets().unwrap();
check_read(&mut server.reader(), b"from-client!");
}
}
#[test]
fn client_close_notify() {
let kt = KeyType::Rsa2048;
let server_config = Arc::new(make_server_config_with_mandatory_client_auth(kt));
for version in rustls::ALL_VERSIONS {
let client_config = make_client_config_with_versions_with_auth(kt, &[version]);
let (mut client, mut server) =
make_pair_for_arc_configs(&Arc::new(client_config), &server_config);
do_handshake(&mut client, &mut server);
// check that alerts don't overtake appdata
assert_eq!(
12,
server
.writer()
.write(b"from-server!")
.unwrap()
);
assert_eq!(
12,
client
.writer()
.write(b"from-client!")
.unwrap()
);
client.send_close_notify();
transfer(&mut client, &mut server);
let io_state = server.process_new_packets().unwrap();
assert!(io_state.peer_has_closed());
check_read_and_close(&mut server.reader(), b"from-client!");
transfer(&mut server, &mut client);
client.process_new_packets().unwrap();
check_read(&mut client.reader(), b"from-server!");
}
}
#[test]
fn server_closes_uncleanly() {
let kt = KeyType::Rsa2048;
let server_config = Arc::new(make_server_config(kt));
for version in rustls::ALL_VERSIONS {
let client_config = make_client_config_with_versions(kt, &[version]);
let (mut client, mut server) =
make_pair_for_arc_configs(&Arc::new(client_config), &server_config);
do_handshake(&mut client, &mut server);
// check that unclean EOF reporting does not overtake appdata
assert_eq!(
12,
server
.writer()
.write(b"from-server!")
.unwrap()
);
assert_eq!(
12,
client
.writer()
.write(b"from-client!")
.unwrap()
);
transfer(&mut server, &mut client);
transfer_eof(&mut client);
let io_state = client.process_new_packets().unwrap();
assert!(!io_state.peer_has_closed());
check_read(&mut client.reader(), b"from-server!");
check_read_err(
&mut client.reader() as &mut dyn io::Read,
io::ErrorKind::UnexpectedEof,
);
// may still transmit pending frames
transfer(&mut client, &mut server);
server.process_new_packets().unwrap();
check_read(&mut server.reader(), b"from-client!");
}
}
#[test]
fn client_closes_uncleanly() {
let kt = KeyType::Rsa2048;
let server_config = Arc::new(make_server_config(kt));
for version in rustls::ALL_VERSIONS {
let client_config = make_client_config_with_versions(kt, &[version]);
let (mut client, mut server) =
make_pair_for_arc_configs(&Arc::new(client_config), &server_config);
do_handshake(&mut client, &mut server);
// check that unclean EOF reporting does not overtake appdata
assert_eq!(
12,
server
.writer()
.write(b"from-server!")
.unwrap()
);
assert_eq!(
12,
client
.writer()
.write(b"from-client!")
.unwrap()
);
transfer(&mut client, &mut server);
transfer_eof(&mut server);
let io_state = server.process_new_packets().unwrap();
assert!(!io_state.peer_has_closed());
check_read(&mut server.reader(), b"from-client!");
check_read_err(
&mut server.reader() as &mut dyn io::Read,
io::ErrorKind::UnexpectedEof,
);
// may still transmit pending frames
transfer(&mut server, &mut client);
client.process_new_packets().unwrap();
check_read(&mut client.reader(), b"from-server!");
}
}
#[test]
fn test_tls13_valid_early_plaintext_alert() {
let (mut client, mut server) = make_pair(KeyType::Rsa2048);
// Perform the start of a TLS 1.3 handshake, sending a client hello to the server.
// The client will not have written a CCS or any encrypted messages to the server yet.
transfer(&mut client, &mut server);
server.process_new_packets().unwrap();
// Inject a plaintext alert from the client. The server should accept this since:
// * It hasn't decrypted any messages from the peer yet.
// * The message content type is Alert.
// * The payload size is indicative of a plaintext alert message.
// * The negotiated protocol version is TLS 1.3.
server
.read_tls(&mut io::Cursor::new(&build_alert(
AlertLevel::Fatal,
AlertDescription::UnknownCA,
&[],
)))
.unwrap();
// The server should process the plaintext alert without error.
assert_eq!(
server.process_new_packets(),
Err(Error::AlertReceived(AlertDescription::UnknownCA)),
);
}
#[test]
fn test_tls13_too_short_early_plaintext_alert() {
let (mut client, mut server) = make_pair(KeyType::Rsa2048);
// Perform the start of a TLS 1.3 handshake, sending a client hello to the server.
// The client will not have written a CCS or any encrypted messages to the server yet.
transfer(&mut client, &mut server);
server.process_new_packets().unwrap();
// Inject a plaintext alert from the client. The server should attempt to decrypt this message
// because the payload length is too large to be considered an early plaintext alert.
server
.read_tls(&mut io::Cursor::new(&build_alert(
AlertLevel::Fatal,
AlertDescription::UnknownCA,
&[0xff],
)))
.unwrap();
// The server should produce a decrypt error trying to decrypt the plaintext alert.
assert_eq!(server.process_new_packets(), Err(Error::DecryptError),);
}
#[test]
fn test_tls13_late_plaintext_alert() {
let (mut client, mut server) = make_pair(KeyType::Rsa2048);
// Complete a bi-directional TLS1.3 handshake. After this point no plaintext messages
// should occur.
do_handshake(&mut client, &mut server);
// Inject a plaintext alert from the client. The server should attempt to decrypt this message.
server
.read_tls(&mut io::Cursor::new(&build_alert(
AlertLevel::Fatal,
AlertDescription::UnknownCA,
&[],
)))
.unwrap();
// The server should produce a decrypt error, trying to decrypt a plaintext alert.
assert_eq!(server.process_new_packets(), Err(Error::DecryptError));
}
fn build_alert(level: AlertLevel, desc: AlertDescription, suffix: &[u8]) -> Vec<u8> {
let mut v = vec![ContentType::Alert.into()];
ProtocolVersion::TLSv1_2.encode(&mut v);
((2 + suffix.len()) as u16).encode(&mut v);
level.encode(&mut v);
desc.encode(&mut v);
v.extend_from_slice(suffix);
v
}
#[derive(Default, Debug)]
struct ServerCheckCertResolve {
expected_sni: Option<String>,
expected_sigalgs: Option<Vec<SignatureScheme>>,
expected_alpn: Option<Vec<Vec<u8>>>,
expected_cipher_suites: Option<Vec<CipherSuite>>,
}
impl ResolvesServerCert for ServerCheckCertResolve {
fn resolve(&self, client_hello: ClientHello) -> Option<Arc<sign::CertifiedKey>> {
if client_hello
.signature_schemes()
.is_empty()
{
panic!("no signature schemes shared by client");
}
if client_hello.cipher_suites().is_empty() {
panic!("no cipher suites shared by client");
}
if let Some(expected_sni) = &self.expected_sni {
let sni: &str = client_hello
.server_name()
.expect("sni unexpectedly absent");
assert_eq!(expected_sni, sni);
}
if let Some(expected_sigalgs) = &self.expected_sigalgs {
assert_eq!(
expected_sigalgs,
client_hello.signature_schemes(),
"unexpected signature schemes"
);
}
if let Some(expected_alpn) = &self.expected_alpn {
let alpn = client_hello
.alpn()
.expect("alpn unexpectedly absent")
.collect::<Vec<_>>();
assert_eq!(alpn.len(), expected_alpn.len());
for (got, wanted) in alpn.iter().zip(expected_alpn.iter()) {
assert_eq!(got, &wanted.as_slice());
}
}
if let Some(expected_cipher_suites) = &self.expected_cipher_suites {
assert_eq!(
expected_cipher_suites,
client_hello.cipher_suites(),
"unexpected cipher suites"
);
}
None
}
}
#[test]
fn server_cert_resolve_with_sni() {
for kt in ALL_KEY_TYPES {
let client_config = make_client_config(*kt);
let mut server_config = make_server_config(*kt);
server_config.cert_resolver = Arc::new(ServerCheckCertResolve {
expected_sni: Some("the-value-from-sni".into()),
..Default::default()
});
let mut client =
ClientConnection::new(Arc::new(client_config), server_name("the-value-from-sni"))
.unwrap();
let mut server = ServerConnection::new(Arc::new(server_config)).unwrap();
let err = do_handshake_until_error(&mut client, &mut server);
assert!(err.is_err());
}
}
#[test]
fn server_cert_resolve_with_alpn() {
for kt in ALL_KEY_TYPES {
let mut client_config = make_client_config(*kt);
client_config.alpn_protocols = vec!["foo".into(), "bar".into()];
let mut server_config = make_server_config(*kt);
server_config.cert_resolver = Arc::new(ServerCheckCertResolve {
expected_alpn: Some(vec![b"foo".to_vec(), b"bar".to_vec()]),
..Default::default()
});
let mut client =
ClientConnection::new(Arc::new(client_config), server_name("sni-value")).unwrap();
let mut server = ServerConnection::new(Arc::new(server_config)).unwrap();
let err = do_handshake_until_error(&mut client, &mut server);
assert!(err.is_err());
}
}
#[test]
fn client_trims_terminating_dot() {
for kt in ALL_KEY_TYPES {
let client_config = make_client_config(*kt);
let mut server_config = make_server_config(*kt);
server_config.cert_resolver = Arc::new(ServerCheckCertResolve {
expected_sni: Some("some-host.com".into()),
..Default::default()
});