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
|
#![allow(unused_imports)]
use std::fs::File;
use std::io::prelude::*;
use std::io::{self, BufReader};
use std::iter;
use std::mem;
use std::net::{TcpStream, TcpListener, SocketAddr};
use std::path::Path;
use std::process::{Command, Child, Stdio, ChildStdin};
use std::thread;
use std::time::Duration;
use net2::TcpStreamExt;
use crypto::hash::Type::SHA256;
use ssl;
use ssl::SSL_VERIFY_PEER;
use ssl::SslMethod::Sslv23;
use ssl::SslMethod;
use ssl::error::NonblockingSslError;
use ssl::{SslContext, SslStream, VerifyCallback, NonblockingSslStream};
use x509::X509StoreContext;
use x509::X509FileType;
use x509::X509;
use crypto::pkey::PKey;
#[cfg(feature="dtlsv1")]
use std::net::UdpSocket;
#[cfg(feature="dtlsv1")]
use ssl::SslMethod::Dtlsv1;
#[cfg(feature="sslv2")]
use ssl::SslMethod::Sslv2;
#[cfg(feature="dtlsv1")]
use net2::UdpSocketExt;
mod select;
fn next_addr() -> SocketAddr {
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
static PORT: AtomicUsize = ATOMIC_USIZE_INIT;
let port = 15411 + PORT.fetch_add(1, Ordering::SeqCst);
format!("127.0.0.1:{}", port).parse().unwrap()
}
struct Server {
p: Child,
}
impl Server {
fn spawn(args: &[&str], input: Option<Box<FnMut(ChildStdin) + Send>>) -> (Server, SocketAddr) {
let addr = next_addr();
let mut child = Command::new("openssl")
.arg("s_server")
.arg("-accept")
.arg(addr.port().to_string())
.args(args)
.arg("-cert")
.arg("cert.pem")
.arg("-key")
.arg("key.pem")
.arg("-no_dhe")
.current_dir("test")
.stdout(Stdio::null())
.stderr(Stdio::null())
.stdin(Stdio::piped())
.spawn()
.unwrap();
let stdin = child.stdin.take().unwrap();
if let Some(mut input) = input {
thread::spawn(move || input(stdin));
}
(Server { p: child }, addr)
}
fn new_tcp(args: &[&str]) -> (Server, TcpStream) {
let (server, addr) = Server::spawn(args, None);
for _ in 0..20 {
match TcpStream::connect(&addr) {
Ok(s) => return (server, s),
Err(ref e) if e.kind() == io::ErrorKind::ConnectionRefused => {
thread::sleep(Duration::from_millis(100));
}
Err(e) => panic!("wut: {}", e),
}
}
panic!("server never came online");
}
fn new() -> (Server, TcpStream) {
Server::new_tcp(&["-www"])
}
#[cfg(any(feature = "alpn", feature = "npn"))]
fn new_alpn() -> (Server, TcpStream) {
Server::new_tcp(&["-www",
"-nextprotoneg",
"http/1.1,spdy/3.1",
"-alpn",
"http/1.1,spdy/3.1"])
}
#[cfg(feature = "dtlsv1")]
fn new_dtlsv1<I>(input: I) -> (Server, UdpConnected)
where I: IntoIterator<Item = &'static str>,
I::IntoIter: Send + 'static
{
let mut input = input.into_iter();
let (s, addr) = Server::spawn(&["-dtls1"],
Some(Box::new(move |mut io| {
for s in input.by_ref() {
if io.write_all(s.as_bytes()).is_err() {
break;
}
}
})));
// Need to wait for the UDP socket to get bound in our child process,
// but don't currently have a great way to do that so just wait for a
// bit.
thread::sleep(Duration::from_millis(100));
let socket = UdpSocket::bind(next_addr()).unwrap();
socket.connect(&addr).unwrap();
(s, UdpConnected(socket))
}
}
impl Drop for Server {
fn drop(&mut self) {
let _ = self.p.kill();
let _ = self.p.wait();
}
}
#[cfg(feature = "dtlsv1")]
struct UdpConnected(UdpSocket);
#[cfg(feature = "dtlsv1")]
impl Read for UdpConnected {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.0.recv_from(buf).map(|(s, _)| s)
}
}
#[cfg(feature = "dtlsv1")]
impl Write for UdpConnected {
#[cfg(unix)]
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
use std::os::unix::prelude::*;
use libc;
let n = unsafe {
libc::send(self.0.as_raw_fd(),
buf.as_ptr() as *const _,
buf.len() as libc::size_t,
0)
};
if n < 0 {
Err(io::Error::last_os_error())
} else {
Ok(n as usize)
}
}
#[cfg(windows)]
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
use std::os::windows::prelude::*;
use libc;
let n = unsafe {
libc::send(self.0.as_raw_socket(),
buf.as_ptr() as *const _,
buf.len() as libc::c_int,
0)
};
if n < 0 {
Err(io::Error::last_os_error())
} else {
Ok(n as usize)
}
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
macro_rules! run_test(
($module:ident, $blk:expr) => (
#[cfg(test)]
mod $module {
use std::io;
use std::io::prelude::*;
use std::path::Path;
use std::net::UdpSocket;
use std::net::TcpStream;
use ssl;
use ssl::SslMethod;
use ssl::{SslContext, Ssl, SslStream, VerifyCallback};
use ssl::SSL_VERIFY_PEER;
use crypto::hash::Type::SHA256;
use x509::X509StoreContext;
use serialize::hex::FromHex;
use super::Server;
#[test]
fn sslv23() {
let (_s, stream) = Server::new();
$blk(SslMethod::Sslv23, stream);
}
#[test]
#[cfg(feature="dtlsv1")]
fn dtlsv1() {
let (_s, stream) = Server::new_dtlsv1(Some("hello"));
$blk(SslMethod::Dtlsv1, stream);
}
}
);
);
run_test!(new_ctx, |method, _| {
SslContext::new(method).unwrap();
});
run_test!(new_sslstream, |method, stream| {
SslStream::connect_generic(&SslContext::new(method).unwrap(), stream).unwrap();
});
run_test!(get_ssl_method, |method, _| {
let ssl = Ssl::new(&SslContext::new(method).unwrap()).unwrap();
assert_eq!(ssl.get_ssl_method(), Some(method));
});
run_test!(verify_untrusted, |method, stream| {
let mut ctx = SslContext::new(method).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, None);
match SslStream::connect_generic(&ctx, stream) {
Ok(_) => panic!("expected failure"),
Err(err) => println!("error {:?}", err)
}
});
run_test!(verify_trusted, |method, stream| {
let mut ctx = SslContext::new(method).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, None);
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
Ok(_) => {}
Err(err) => panic!("Unexpected error {:?}", err)
}
match SslStream::connect_generic(&ctx, stream) {
Ok(_) => (),
Err(err) => panic!("Expected success, got {:?}", err)
}
});
run_test!(verify_untrusted_callback_override_ok, |method, stream| {
fn callback(_preverify_ok: bool, _x509_ctx: &X509StoreContext) -> bool {
true
}
let mut ctx = SslContext::new(method).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, Some(callback as VerifyCallback));
match SslStream::connect_generic(&ctx, stream) {
Ok(_) => (),
Err(err) => panic!("Expected success, got {:?}", err)
}
});
run_test!(verify_untrusted_callback_override_bad, |method, stream| {
fn callback(_preverify_ok: bool, _x509_ctx: &X509StoreContext) -> bool {
false
}
let mut ctx = SslContext::new(method).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, Some(callback as VerifyCallback));
assert!(SslStream::connect_generic(&ctx, stream).is_err());
});
run_test!(verify_trusted_callback_override_ok, |method, stream| {
fn callback(_preverify_ok: bool, _x509_ctx: &X509StoreContext) -> bool {
true
}
let mut ctx = SslContext::new(method).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, Some(callback as VerifyCallback));
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
Ok(_) => {}
Err(err) => panic!("Unexpected error {:?}", err)
}
match SslStream::connect_generic(&ctx, stream) {
Ok(_) => (),
Err(err) => panic!("Expected success, got {:?}", err)
}
});
run_test!(verify_trusted_callback_override_bad, |method, stream| {
fn callback(_preverify_ok: bool, _x509_ctx: &X509StoreContext) -> bool {
false
}
let mut ctx = SslContext::new(method).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, Some(callback as VerifyCallback));
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
Ok(_) => {}
Err(err) => panic!("Unexpected error {:?}", err)
}
assert!(SslStream::connect_generic(&ctx, stream).is_err());
});
run_test!(verify_callback_load_certs, |method, stream| {
fn callback(_preverify_ok: bool, x509_ctx: &X509StoreContext) -> bool {
assert!(x509_ctx.get_current_cert().is_some());
true
}
let mut ctx = SslContext::new(method).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, Some(callback as VerifyCallback));
assert!(SslStream::connect_generic(&ctx, stream).is_ok());
});
run_test!(verify_trusted_get_error_ok, |method, stream| {
fn callback(_preverify_ok: bool, x509_ctx: &X509StoreContext) -> bool {
assert!(x509_ctx.get_error().is_none());
true
}
let mut ctx = SslContext::new(method).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, Some(callback as VerifyCallback));
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
Ok(_) => {}
Err(err) => panic!("Unexpected error {:?}", err)
}
assert!(SslStream::connect_generic(&ctx, stream).is_ok());
});
run_test!(verify_trusted_get_error_err, |method, stream| {
fn callback(_preverify_ok: bool, x509_ctx: &X509StoreContext) -> bool {
assert!(x509_ctx.get_error().is_some());
false
}
let mut ctx = SslContext::new(method).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, Some(callback as VerifyCallback));
assert!(SslStream::connect_generic(&ctx, stream).is_err());
});
run_test!(verify_callback_data, |method, stream| {
fn callback(_preverify_ok: bool, x509_ctx: &X509StoreContext,
node_id: &Vec<u8>) -> bool {
let cert = x509_ctx.get_current_cert();
match cert {
None => false,
Some(cert) => {
let fingerprint = cert.fingerprint(SHA256).unwrap();
&fingerprint == node_id
}
}
}
let mut ctx = SslContext::new(method).unwrap();
// Node id was generated as SHA256 hash of certificate "test/cert.pem"
// in DER format.
// Command: openssl x509 -in test/cert.pem -outform DER | openssl dgst -sha256
// Please update if "test/cert.pem" will ever change
let node_hash_str = "db400bb62f1b1f29c3b8f323b8f7d9dea724fdcd67104ef549c772ae3749655b";
let node_id = node_hash_str.from_hex().unwrap();
ctx.set_verify_with_data(SSL_VERIFY_PEER, callback, node_id);
ctx.set_verify_depth(1);
match SslStream::connect_generic(&ctx, stream) {
Ok(_) => (),
Err(err) => panic!("Expected success, got {:?}", err)
}
});
// Make sure every write call translates to a write call to the underlying socket.
#[test]
fn test_write_hits_stream() {
let listener = TcpListener::bind(next_addr()).unwrap();
let addr = listener.local_addr().unwrap();
let guard = thread::spawn(move || {
let ctx = SslContext::new(Sslv23).unwrap();
let stream = TcpStream::connect(addr).unwrap();
let mut stream = SslStream::connect_generic(&ctx, stream).unwrap();
stream.write_all(b"hello").unwrap();
stream
});
let mut ctx = SslContext::new(Sslv23).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, None);
ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM).unwrap();
ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM).unwrap();
let stream = listener.accept().unwrap().0;
let mut stream = SslStream::accept(&ctx, stream).unwrap();
let mut buf = [0; 5];
assert_eq!(5, stream.read(&mut buf).unwrap());
assert_eq!(&b"hello"[..], &buf[..]);
guard.join().unwrap();
}
#[test]
fn test_set_certificate_and_private_key() {
let key_path = Path::new("test/key.pem");
let cert_path = Path::new("test/cert.pem");
let mut key_file = File::open(&key_path)
.ok()
.expect("Failed to open `test/key.pem`");
let mut cert_file = File::open(&cert_path)
.ok()
.expect("Failed to open `test/cert.pem`");
let key = PKey::private_key_from_pem(&mut key_file).unwrap();
let cert = X509::from_pem(&mut cert_file).unwrap();
let mut ctx = SslContext::new(Sslv23).unwrap();
ctx.set_private_key(&key).unwrap();
ctx.set_certificate(&cert).unwrap();
assert!(ctx.check_private_key().is_ok());
}
run_test!(get_ctx_options, |method, _| {
let mut ctx = SslContext::new(method).unwrap();
ctx.get_options();
});
run_test!(set_ctx_options, |method, _| {
let mut ctx = SslContext::new(method).unwrap();
let opts = ctx.set_options(ssl::SSL_OP_NO_TICKET);
assert!(opts.contains(ssl::SSL_OP_NO_TICKET));
});
run_test!(clear_ctx_options, |method, _| {
let mut ctx = SslContext::new(method).unwrap();
ctx.set_options(ssl::SSL_OP_ALL);
let opts = ctx.clear_options(ssl::SSL_OP_ALL);
assert!(!opts.contains(ssl::SSL_OP_ALL));
});
#[test]
fn test_write() {
let (_s, stream) = Server::new();
let mut stream = SslStream::connect_generic(&SslContext::new(Sslv23).unwrap(), stream).unwrap();
stream.write_all("hello".as_bytes()).unwrap();
stream.flush().unwrap();
stream.write_all(" there".as_bytes()).unwrap();
stream.flush().unwrap();
}
#[test]
fn test_write_direct() {
let (_s, stream) = Server::new();
let mut stream = SslStream::connect(&SslContext::new(Sslv23).unwrap(), stream).unwrap();
stream.write_all("hello".as_bytes()).unwrap();
stream.flush().unwrap();
stream.write_all(" there".as_bytes()).unwrap();
stream.flush().unwrap();
}
run_test!(get_peer_certificate, |method, stream| {
let stream = SslStream::connect_generic(&SslContext::new(method).unwrap(),
stream).unwrap();
let cert = stream.ssl().peer_certificate().unwrap();
let fingerprint = cert.fingerprint(SHA256).unwrap();
let node_hash_str = "db400bb62f1b1f29c3b8f323b8f7d9dea724fdcd67104ef549c772ae3749655b";
let node_id = node_hash_str.from_hex().unwrap();
assert_eq!(node_id, fingerprint)
});
#[test]
#[cfg(feature = "dtlsv1")]
fn test_write_dtlsv1() {
let (_s, stream) = Server::new_dtlsv1(iter::repeat("y\n"));
let mut stream = SslStream::connect_generic(&SslContext::new(Dtlsv1).unwrap(), stream).unwrap();
stream.write_all(b"hello").unwrap();
stream.flush().unwrap();
stream.write_all(b" there").unwrap();
stream.flush().unwrap();
}
#[test]
fn test_read() {
let (_s, tcp) = Server::new();
let mut stream = SslStream::connect_generic(&SslContext::new(Sslv23).unwrap(), tcp).unwrap();
stream.write_all("GET /\r\n\r\n".as_bytes()).unwrap();
stream.flush().unwrap();
io::copy(&mut stream, &mut io::sink()).ok().expect("read error");
}
#[test]
fn test_read_direct() {
let (_s, tcp) = Server::new();
let mut stream = SslStream::connect(&SslContext::new(Sslv23).unwrap(), tcp).unwrap();
stream.write_all("GET /\r\n\r\n".as_bytes()).unwrap();
stream.flush().unwrap();
io::copy(&mut stream, &mut io::sink()).ok().expect("read error");
}
#[test]
fn test_pending() {
let (_s, tcp) = Server::new();
let mut stream = SslStream::connect_generic(&SslContext::new(Sslv23).unwrap(), tcp).unwrap();
stream.write_all("GET /\r\n\r\n".as_bytes()).unwrap();
stream.flush().unwrap();
// wait for the response and read first byte...
let mut buf = [0u8; 16 * 1024];
stream.read(&mut buf[..1]).unwrap();
let pending = stream.ssl().pending();
let len = stream.read(&mut buf[1..]).unwrap();
assert_eq!(pending, len);
stream.read(&mut buf[..1]).unwrap();
let pending = stream.ssl().pending();
let len = stream.read(&mut buf[1..]).unwrap();
assert_eq!(pending, len);
}
#[test]
fn test_state() {
let (_s, tcp) = Server::new();
let stream = SslStream::connect_generic(&SslContext::new(Sslv23).unwrap(), tcp).unwrap();
assert_eq!(stream.ssl().state_string(), "SSLOK ");
assert_eq!(stream.ssl().state_string_long(),
"SSL negotiation finished successfully");
}
/// Tests that connecting with the client using ALPN, but the server not does not
/// break the existing connection behavior.
#[test]
#[cfg(feature = "alpn")]
fn test_connect_with_unilateral_alpn() {
let (_s, stream) = Server::new();
let mut ctx = SslContext::new(Sslv23).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, None);
ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]);
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
Ok(_) => {}
Err(err) => panic!("Unexpected error {:?}", err),
}
let stream = match SslStream::connect(&ctx, stream) {
Ok(stream) => stream,
Err(err) => panic!("Expected success, got {:?}", err),
};
// Since the socket to which we connected is not configured to use ALPN,
// there should be no selected protocol...
assert!(stream.ssl().selected_alpn_protocol().is_none());
}
/// Tests that connecting with the client using NPN, but the server not does not
/// break the existing connection behavior.
#[test]
#[cfg(feature = "npn")]
fn test_connect_with_unilateral_npn() {
let (_s, stream) = Server::new();
let mut ctx = SslContext::new(Sslv23).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, None);
ctx.set_npn_protocols(&[b"http/1.1", b"spdy/3.1"]);
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
Ok(_) => {}
Err(err) => panic!("Unexpected error {:?}", err),
}
let stream = match SslStream::connect_generic(&ctx, stream) {
Ok(stream) => stream,
Err(err) => panic!("Expected success, got {:?}", err),
};
// Since the socket to which we connected is not configured to use NPN,
// there should be no selected protocol...
assert!(stream.ssl().selected_npn_protocol().is_none());
}
/// Tests that when both the client as well as the server use ALPN and their
/// lists of supported protocols have an overlap, the correct protocol is chosen.
#[test]
#[cfg(feature = "alpn")]
fn test_connect_with_alpn_successful_multiple_matching() {
let (_s, stream) = Server::new_alpn();
let mut ctx = SslContext::new(Sslv23).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, None);
ctx.set_alpn_protocols(&[b"spdy/3.1", b"http/1.1"]);
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
Ok(_) => {}
Err(err) => panic!("Unexpected error {:?}", err),
}
let stream = match SslStream::connect(&ctx, stream) {
Ok(stream) => stream,
Err(err) => panic!("Expected success, got {:?}", err),
};
// The server prefers "http/1.1", so that is chosen, even though the client
// would prefer "spdy/3.1"
assert_eq!(b"http/1.1", stream.ssl().selected_alpn_protocol().unwrap());
}
/// Tests that when both the client as well as the server use NPN and their
/// lists of supported protocols have an overlap, the correct protocol is chosen.
#[test]
#[cfg(feature = "npn")]
fn test_connect_with_npn_successful_multiple_matching() {
let (_s, stream) = Server::new_alpn();
let mut ctx = SslContext::new(Sslv23).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, None);
ctx.set_npn_protocols(&[b"spdy/3.1", b"http/1.1"]);
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
Ok(_) => {}
Err(err) => panic!("Unexpected error {:?}", err),
}
let stream = match SslStream::connect_generic(&ctx, stream) {
Ok(stream) => stream,
Err(err) => panic!("Expected success, got {:?}", err),
};
// The server prefers "http/1.1", so that is chosen, even though the client
// would prefer "spdy/3.1"
assert_eq!(b"http/1.1", stream.ssl().selected_npn_protocol().unwrap());
}
/// Tests that when both the client as well as the server use ALPN and their
/// lists of supported protocols have an overlap -- with only ONE protocol
/// being valid for both.
#[test]
#[cfg(feature = "alpn")]
fn test_connect_with_alpn_successful_single_match() {
let (_s, stream) = Server::new_alpn();
let mut ctx = SslContext::new(Sslv23).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, None);
ctx.set_alpn_protocols(&[b"spdy/3.1"]);
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
Ok(_) => {}
Err(err) => panic!("Unexpected error {:?}", err),
}
let stream = match SslStream::connect(&ctx, stream) {
Ok(stream) => stream,
Err(err) => panic!("Expected success, got {:?}", err),
};
// The client now only supports one of the server's protocols, so that one
// is used.
assert_eq!(b"spdy/3.1", stream.ssl().selected_alpn_protocol().unwrap());
}
/// Tests that when both the client as well as the server use NPN and their
/// lists of supported protocols have an overlap -- with only ONE protocol
/// being valid for both.
#[test]
#[cfg(feature = "npn")]
fn test_connect_with_npn_successful_single_match() {
let (_s, stream) = Server::new_alpn();
let mut ctx = SslContext::new(Sslv23).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, None);
ctx.set_npn_protocols(&[b"spdy/3.1"]);
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
Ok(_) => {}
Err(err) => panic!("Unexpected error {:?}", err),
}
let stream = match SslStream::connect_generic(&ctx, stream) {
Ok(stream) => stream,
Err(err) => panic!("Expected success, got {:?}", err),
};
// The client now only supports one of the server's protocols, so that one
// is used.
assert_eq!(b"spdy/3.1", stream.ssl().selected_npn_protocol().unwrap());
}
/// Tests that when the `SslStream` is created as a server stream, the protocols
/// are correctly advertised to the client.
#[test]
#[cfg(feature = "npn")]
fn test_npn_server_advertise_multiple() {
let listener = TcpListener::bind(next_addr()).unwrap();
let localhost = listener.local_addr().unwrap();
// We create a different context instance for the server...
let listener_ctx = {
let mut ctx = SslContext::new(Sslv23).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, None);
ctx.set_npn_protocols(&[b"http/1.1", b"spdy/3.1"]);
assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM)
.is_ok());
ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM)
.unwrap();
ctx
};
// Have the listener wait on the connection in a different thread.
thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let _ = SslStream::accept(&listener_ctx, stream).unwrap();
});
let mut ctx = SslContext::new(Sslv23).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, None);
ctx.set_npn_protocols(&[b"spdy/3.1"]);
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
Ok(_) => {}
Err(err) => panic!("Unexpected error {:?}", err),
}
// Now connect to the socket and make sure the protocol negotiation works...
let stream = TcpStream::connect(localhost).unwrap();
let stream = match SslStream::connect_generic(&ctx, stream) {
Ok(stream) => stream,
Err(err) => panic!("Expected success, got {:?}", err),
};
// SPDY is selected since that's the only thing the client supports.
assert_eq!(b"spdy/3.1", stream.ssl().selected_npn_protocol().unwrap());
}
/// Tests that when the `SslStream` is created as a server stream, the protocols
/// are correctly advertised to the client.
#[test]
#[cfg(feature = "alpn")]
fn test_alpn_server_advertise_multiple() {
let listener = TcpListener::bind(next_addr()).unwrap();
let localhost = listener.local_addr().unwrap();
// We create a different context instance for the server...
let listener_ctx = {
let mut ctx = SslContext::new(Sslv23).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, None);
ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]);
assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM)
.is_ok());
ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM)
.unwrap();
ctx
};
// Have the listener wait on the connection in a different thread.
thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let _ = SslStream::accept(&listener_ctx, stream).unwrap();
});
let mut ctx = SslContext::new(Sslv23).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, None);
ctx.set_alpn_protocols(&[b"spdy/3.1"]);
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
Ok(_) => {}
Err(err) => panic!("Unexpected error {:?}", err),
}
// Now connect to the socket and make sure the protocol negotiation works...
let stream = TcpStream::connect(localhost).unwrap();
let stream = match SslStream::connect(&ctx, stream) {
Ok(stream) => stream,
Err(err) => panic!("Expected success, got {:?}", err),
};
// SPDY is selected since that's the only thing the client supports.
assert_eq!(b"spdy/3.1", stream.ssl().selected_alpn_protocol().unwrap());
}
/// Test that Servers supporting ALPN don't report a protocol when none of their protocols match
/// the client's reported protocol.
#[test]
#[cfg(feature = "alpn")]
fn test_alpn_server_select_none() {
let listener = TcpListener::bind(next_addr()).unwrap();
let localhost = listener.local_addr().unwrap();
// We create a different context instance for the server...
let listener_ctx = {
let mut ctx = SslContext::new(Sslv23).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, None);
ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]);
assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM)
.is_ok());
ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM)
.unwrap();
ctx
};
// Have the listener wait on the connection in a different thread.
thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let _ = SslStream::accept(&listener_ctx, stream).unwrap();
});
let mut ctx = SslContext::new(Sslv23).unwrap();
ctx.set_verify(SSL_VERIFY_PEER, None);
ctx.set_alpn_protocols(&[b"http/2"]);
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
Ok(_) => {}
Err(err) => panic!("Unexpected error {:?}", err),
}
// Now connect to the socket and make sure the protocol negotiation works...
let stream = TcpStream::connect(localhost).unwrap();
let stream = match SslStream::connect(&ctx, stream) {
Ok(stream) => stream,
Err(err) => panic!("Expected success, got {:?}", err),
};
// Since the protocols from the server and client don't overlap at all, no protocol is selected
assert_eq!(None, stream.ssl().selected_alpn_protocol());
}
#[cfg(feature="dtlsv1")]
#[cfg(test)]
mod dtlsv1 {
use serialize::hex::FromHex;
use std::net::TcpStream;
use std::thread;
use crypto::hash::Type::SHA256;
use ssl::SslMethod;
use ssl::SslMethod::Dtlsv1;
use ssl::{SslContext, SslStream, VerifyCallback};
use ssl::SSL_VERIFY_PEER;
use x509::X509StoreContext;
const PROTOCOL: SslMethod = Dtlsv1;
#[test]
fn test_new_ctx() {
SslContext::new(PROTOCOL).unwrap();
}
}
#[test]
#[cfg(feature = "dtlsv1")]
fn test_read_dtlsv1() {
let (_s, stream) = Server::new_dtlsv1(Some("hello"));
let mut stream = SslStream::connect_generic(&SslContext::new(Dtlsv1).unwrap(), stream).unwrap();
let mut buf = [0u8; 100];
assert!(stream.read(&mut buf).is_ok());
}
#[test]
#[cfg(feature = "sslv2")]
fn test_sslv2_connect_failure() {
let (_s, tcp) = Server::new_tcp(&["-no_ssl2", "-www"]);
SslStream::connect_generic(&SslContext::new(Sslv2).unwrap(), tcp)
.err()
.unwrap();
}
fn wait_io(stream: &NonblockingSslStream<TcpStream>, read: bool, timeout_ms: u32) -> bool {
unsafe {
let mut set: select::fd_set = mem::zeroed();
select::fd_set(&mut set, stream.get_ref());
let write = if read {
0 as *mut _
} else {
&mut set as *mut _
};
let read = if !read {
0 as *mut _
} else {
&mut set as *mut _
};
select::select(stream.get_ref(), read, write, 0 as *mut _, timeout_ms).unwrap()
}
}
#[test]
fn test_write_nonblocking() {
let (_s, stream) = Server::new();
stream.set_nonblocking(true).unwrap();
let cx = SslContext::new(Sslv23).unwrap();
let mut stream = NonblockingSslStream::connect(&cx, stream).unwrap();
let mut iterations = 0;
loop {
iterations += 1;
if iterations > 7 {
// Probably a safe assumption for the foreseeable future of
// openssl.
panic!("Too many read/write round trips in handshake!!");
}
let result = stream.write(b"hello");
match result {
Ok(_) => {
break;
}
Err(NonblockingSslError::WantRead) => {
assert!(wait_io(&stream, true, 1000));
}
Err(NonblockingSslError::WantWrite) => {
assert!(wait_io(&stream, false, 1000));
}
Err(other) => {
panic!("Unexpected SSL Error: {:?}", other);
}
}
}
// Second write should succeed immediately--plenty of space in kernel
// buffer, and handshake just completed.
stream.write(" there".as_bytes()).unwrap();
}
#[test]
fn test_read_nonblocking() {
let (_s, stream) = Server::new();
stream.set_nonblocking(true).unwrap();
let cx = SslContext::new(Sslv23).unwrap();
let mut stream = NonblockingSslStream::connect(&cx, stream).unwrap();
let mut iterations = 0;
loop {
iterations += 1;
if iterations > 7 {
// Probably a safe assumption for the foreseeable future of
// openssl.
panic!("Too many read/write round trips in handshake!!");
}
let result = stream.write(b"GET /\r\n\r\n");
match result {
Ok(n) => {
assert_eq!(n, 9);
break;
}
Err(NonblockingSslError::WantRead) => {
assert!(wait_io(&stream, true, 1000));
}
Err(NonblockingSslError::WantWrite) => {
assert!(wait_io(&stream, false, 1000));
}
Err(other) => {
panic!("Unexpected SSL Error: {:?}", other);
}
}
}
let mut input_buffer = [0u8; 1500];
let result = stream.read(&mut input_buffer);
let bytes_read = match result {
Ok(n) => {
// This branch is unlikely, but on an overloaded VM with
// unlucky context switching, the response could actually
// be in the receive buffer before we issue the read() syscall...
n
}
Err(NonblockingSslError::WantRead) => {
assert!(wait_io(&stream, true, 3000));
// Second read should return application data.
stream.read(&mut input_buffer).unwrap()
}
Err(other) => {
panic!("Unexpected SSL Error: {:?}", other);
}
};
assert!(bytes_read >= 5);
assert_eq!(&input_buffer[..5], b"HTTP/");
}
#[test]
fn broken_try_clone_doesnt_crash() {
let context = SslContext::new(SslMethod::Sslv23).unwrap();
let inner = TcpStream::connect("example.com:443").unwrap();
let stream1 = SslStream::connect(&context, inner).unwrap();
let _stream2 = stream1.try_clone().unwrap();
}
#[test]
#[should_panic(expected = "blammo")]
#[cfg(feature = "nightly")]
fn write_panic() {
struct ExplodingStream(TcpStream);
impl Read for ExplodingStream {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
}
impl Write for ExplodingStream {
fn write(&mut self, _: &[u8]) -> io::Result<usize> {
panic!("blammo");
}
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
}
let (_s, stream) = Server::new();
let stream = ExplodingStream(stream);
let ctx = SslContext::new(SslMethod::Sslv23).unwrap();
let _ = SslStream::connect(&ctx, stream);
}
#[test]
#[should_panic(expected = "blammo")]
#[cfg(feature = "nightly")]
fn read_panic() {
struct ExplodingStream(TcpStream);
impl Read for ExplodingStream {
fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
panic!("blammo");
}
}
impl Write for ExplodingStream {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
}
let (_s, stream) = Server::new();
let stream = ExplodingStream(stream);
let ctx = SslContext::new(SslMethod::Sslv23).unwrap();
let _ = SslStream::connect(&ctx, stream);
}
#[test]
#[should_panic(expected = "blammo")]
#[cfg(feature = "nightly")]
fn flush_panic() {
struct ExplodingStream(TcpStream);
impl Read for ExplodingStream {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
}
impl Write for ExplodingStream {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
panic!("blammo");
}
}
let (_s, stream) = Server::new();
let stream = ExplodingStream(stream);
let ctx = SslContext::new(SslMethod::Sslv23).unwrap();
let mut stream = SslStream::connect(&ctx, stream).unwrap();
let _ = stream.flush();
}
#[test]
fn refcount_ssl_context() {
let ssl = {
let ctx = SslContext::new(SslMethod::Sslv23).unwrap();
ssl::Ssl::new(&ctx).unwrap()
};
{
let new_ctx_a = SslContext::new(SslMethod::Sslv23).unwrap();
let _new_ctx_b = ssl.set_ssl_context(&new_ctx_a);
}
}
#[test]
fn default_verify_paths() {
let mut ctx = SslContext::new(SslMethod::Sslv23).unwrap();
ctx.set_default_verify_paths().unwrap();
ctx.set_verify(SSL_VERIFY_PEER, None);
let s = TcpStream::connect("google.com:443").unwrap();
let mut socket = SslStream::connect(&ctx, s).unwrap();
socket.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap();
let mut result = vec![];
socket.read_to_end(&mut result).unwrap();
println!("{}", String::from_utf8_lossy(&result));
assert!(result.starts_with(b"HTTP/1.0"));
assert!(result.ends_with(b"</HTML>\r\n") || result.ends_with(b"</html>"));
}
|