1 #![allow(unused_imports)]
2 
3 use std::env;
4 use std::fs::File;
5 use std::io::prelude::*;
6 use std::io::{self, BufReader};
7 use std::iter;
8 use std::mem;
9 use std::net::UdpSocket;
10 use std::net::{SocketAddr, TcpListener, TcpStream};
11 use std::path::Path;
12 use std::process::{Child, ChildStdin, Command, Stdio};
13 use std::sync::atomic::{AtomicBool, Ordering};
14 use std::thread;
15 use std::time::Duration;
16 use tempdir::TempDir;
17 
18 use crate::dh::Dh;
19 use crate::error::ErrorStack;
20 use crate::hash::MessageDigest;
21 use crate::ocsp::{OcspResponse, OcspResponseStatus};
22 use crate::pkey::PKey;
23 use crate::srtp::SrtpProfileId;
24 use crate::ssl;
25 use crate::ssl::test::server::Server;
26 #[cfg(any(ossl110, ossl111, libressl261))]
27 use crate::ssl::SslVersion;
28 #[cfg(ossl111)]
29 use crate::ssl::{ClientHelloResponse, ExtensionContext};
30 use crate::ssl::{
31     Error, HandshakeError, MidHandshakeSslStream, ShutdownResult, ShutdownState, Ssl, SslAcceptor,
32     SslAcceptorBuilder, SslConnector, SslContext, SslContextBuilder, SslFiletype, SslMethod,
33     SslOptions, SslSessionCacheMode, SslStream, SslVerifyMode, StatusType,
34 };
35 #[cfg(ossl102)]
36 use crate::x509::store::X509StoreBuilder;
37 #[cfg(ossl102)]
38 use crate::x509::verify::X509CheckFlags;
39 use crate::x509::{X509Name, X509StoreContext, X509VerifyResult, X509};
40 
41 mod server;
42 
43 static ROOT_CERT: &[u8] = include_bytes!("../../../test/root-ca.pem");
44 static CERT: &[u8] = include_bytes!("../../../test/cert.pem");
45 static KEY: &[u8] = include_bytes!("../../../test/key.pem");
46 
47 #[test]
verify_untrusted()48 fn verify_untrusted() {
49     let mut server = Server::builder();
50     server.should_error();
51     let server = server.build();
52 
53     let mut client = server.client();
54     client.ctx().set_verify(SslVerifyMode::PEER);
55 
56     client.connect_err();
57 }
58 
59 #[test]
verify_trusted()60 fn verify_trusted() {
61     let server = Server::builder().build();
62 
63     let mut client = server.client();
64     client.ctx().set_ca_file("test/root-ca.pem").unwrap();
65 
66     client.connect();
67 }
68 
69 #[test]
70 #[cfg(ossl102)]
verify_trusted_with_set_cert()71 fn verify_trusted_with_set_cert() {
72     let server = Server::builder().build();
73 
74     let mut store = X509StoreBuilder::new().unwrap();
75     let x509 = X509::from_pem(ROOT_CERT).unwrap();
76     store.add_cert(x509).unwrap();
77 
78     let mut client = server.client();
79     client.ctx().set_verify(SslVerifyMode::PEER);
80     client.ctx().set_verify_cert_store(store.build()).unwrap();
81 
82     client.connect();
83 }
84 
85 #[test]
verify_untrusted_callback_override_ok()86 fn verify_untrusted_callback_override_ok() {
87     let server = Server::builder().build();
88 
89     let mut client = server.client();
90     client
91         .ctx()
92         .set_verify_callback(SslVerifyMode::PEER, |_, x509| {
93             assert!(x509.current_cert().is_some());
94             true
95         });
96 
97     client.connect();
98 }
99 
100 #[test]
verify_untrusted_callback_override_bad()101 fn verify_untrusted_callback_override_bad() {
102     let mut server = Server::builder();
103     server.should_error();
104     let server = server.build();
105 
106     let mut client = server.client();
107     client
108         .ctx()
109         .set_verify_callback(SslVerifyMode::PEER, |_, _| false);
110 
111     client.connect_err();
112 }
113 
114 #[test]
verify_trusted_callback_override_ok()115 fn verify_trusted_callback_override_ok() {
116     let server = Server::builder().build();
117 
118     let mut client = server.client();
119     client.ctx().set_ca_file("test/root-ca.pem").unwrap();
120     client
121         .ctx()
122         .set_verify_callback(SslVerifyMode::PEER, |_, x509| {
123             assert!(x509.current_cert().is_some());
124             true
125         });
126 
127     client.connect();
128 }
129 
130 #[test]
verify_trusted_callback_override_bad()131 fn verify_trusted_callback_override_bad() {
132     let mut server = Server::builder();
133     server.should_error();
134     let server = server.build();
135 
136     let mut client = server.client();
137     client.ctx().set_ca_file("test/root-ca.pem").unwrap();
138     client
139         .ctx()
140         .set_verify_callback(SslVerifyMode::PEER, |_, _| false);
141 
142     client.connect_err();
143 }
144 
145 #[test]
verify_callback_load_certs()146 fn verify_callback_load_certs() {
147     let server = Server::builder().build();
148 
149     let mut client = server.client();
150     client
151         .ctx()
152         .set_verify_callback(SslVerifyMode::PEER, |_, x509| {
153             assert!(x509.current_cert().is_some());
154             true
155         });
156 
157     client.connect();
158 }
159 
160 #[test]
verify_trusted_get_error_ok()161 fn verify_trusted_get_error_ok() {
162     let server = Server::builder().build();
163 
164     let mut client = server.client();
165     client.ctx().set_ca_file("test/root-ca.pem").unwrap();
166     client
167         .ctx()
168         .set_verify_callback(SslVerifyMode::PEER, |_, x509| {
169             assert_eq!(x509.error(), X509VerifyResult::OK);
170             true
171         });
172 
173     client.connect();
174 }
175 
176 #[test]
verify_trusted_get_error_err()177 fn verify_trusted_get_error_err() {
178     let mut server = Server::builder();
179     server.should_error();
180     let server = server.build();
181 
182     let mut client = server.client();
183     client
184         .ctx()
185         .set_verify_callback(SslVerifyMode::PEER, |_, x509| {
186             assert_ne!(x509.error(), X509VerifyResult::OK);
187             false
188         });
189 
190     client.connect_err();
191 }
192 
193 #[test]
verify_callback()194 fn verify_callback() {
195     static CALLED_BACK: AtomicBool = AtomicBool::new(false);
196 
197     let server = Server::builder().build();
198 
199     let mut client = server.client();
200     let expected = "59172d9313e84459bcff27f967e79e6e9217e584";
201     client
202         .ctx()
203         .set_verify_callback(SslVerifyMode::PEER, move |_, x509| {
204             CALLED_BACK.store(true, Ordering::SeqCst);
205             let cert = x509.current_cert().unwrap();
206             let digest = cert.digest(MessageDigest::sha1()).unwrap();
207             assert_eq!(hex::encode(&digest), expected);
208             true
209         });
210 
211     client.connect();
212     assert!(CALLED_BACK.load(Ordering::SeqCst));
213 }
214 
215 #[test]
ssl_verify_callback()216 fn ssl_verify_callback() {
217     static CALLED_BACK: AtomicBool = AtomicBool::new(false);
218 
219     let server = Server::builder().build();
220 
221     let mut client = server.client().build().builder();
222     let expected = "59172d9313e84459bcff27f967e79e6e9217e584";
223     client
224         .ssl()
225         .set_verify_callback(SslVerifyMode::PEER, move |_, x509| {
226             CALLED_BACK.store(true, Ordering::SeqCst);
227             let cert = x509.current_cert().unwrap();
228             let digest = cert.digest(MessageDigest::sha1()).unwrap();
229             assert_eq!(hex::encode(&digest), expected);
230             true
231         });
232 
233     client.connect();
234     assert!(CALLED_BACK.load(Ordering::SeqCst));
235 }
236 
237 #[test]
get_ctx_options()238 fn get_ctx_options() {
239     let ctx = SslContext::builder(SslMethod::tls()).unwrap();
240     ctx.options();
241 }
242 
243 #[test]
set_ctx_options()244 fn set_ctx_options() {
245     let mut ctx = SslContext::builder(SslMethod::tls()).unwrap();
246     let opts = ctx.set_options(SslOptions::NO_TICKET);
247     assert!(opts.contains(SslOptions::NO_TICKET));
248 }
249 
250 #[test]
clear_ctx_options()251 fn clear_ctx_options() {
252     let mut ctx = SslContext::builder(SslMethod::tls()).unwrap();
253     ctx.set_options(SslOptions::ALL);
254     let opts = ctx.clear_options(SslOptions::ALL);
255     assert!(!opts.contains(SslOptions::ALL));
256 }
257 
258 #[test]
zero_length_buffers()259 fn zero_length_buffers() {
260     let server = Server::builder().build();
261 
262     let mut s = server.client().connect();
263     assert_eq!(s.write(&[]).unwrap(), 0);
264     assert_eq!(s.read(&mut []).unwrap(), 0);
265 }
266 
267 #[test]
peer_certificate()268 fn peer_certificate() {
269     let server = Server::builder().build();
270 
271     let s = server.client().connect();
272     let cert = s.ssl().peer_certificate().unwrap();
273     let fingerprint = cert.digest(MessageDigest::sha1()).unwrap();
274     assert_eq!(
275         hex::encode(fingerprint),
276         "59172d9313e84459bcff27f967e79e6e9217e584"
277     );
278 }
279 
280 #[test]
pending()281 fn pending() {
282     let mut server = Server::builder();
283     server.io_cb(|mut s| s.write_all(&[0; 10]).unwrap());
284     let server = server.build();
285 
286     let mut s = server.client().connect();
287     s.read_exact(&mut [0]).unwrap();
288 
289     assert_eq!(s.ssl().pending(), 9);
290     assert_eq!(s.read(&mut [0; 10]).unwrap(), 9);
291 }
292 
293 #[test]
state()294 fn state() {
295     let server = Server::builder().build();
296 
297     let s = server.client().connect();
298     assert_eq!(s.ssl().state_string().trim(), "SSLOK");
299     assert_eq!(
300         s.ssl().state_string_long(),
301         "SSL negotiation finished successfully"
302     );
303 }
304 
305 /// Tests that when both the client as well as the server use SRTP and their
306 /// lists of supported protocols have an overlap -- with only ONE protocol
307 /// being valid for both.
308 #[test]
test_connect_with_srtp_ctx()309 fn test_connect_with_srtp_ctx() {
310     let listener = TcpListener::bind("127.0.0.1:0").unwrap();
311     let addr = listener.local_addr().unwrap();
312 
313     let guard = thread::spawn(move || {
314         let stream = listener.accept().unwrap().0;
315         let mut ctx = SslContext::builder(SslMethod::dtls()).unwrap();
316         ctx.set_tlsext_use_srtp("SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32")
317             .unwrap();
318         ctx.set_certificate_file(&Path::new("test/cert.pem"), SslFiletype::PEM)
319             .unwrap();
320         ctx.set_private_key_file(&Path::new("test/key.pem"), SslFiletype::PEM)
321             .unwrap();
322         let mut ssl = Ssl::new(&ctx.build()).unwrap();
323         ssl.set_mtu(1500).unwrap();
324         let mut stream = ssl.accept(stream).unwrap();
325 
326         let mut buf = [0; 60];
327         stream
328             .ssl()
329             .export_keying_material(&mut buf, "EXTRACTOR-dtls_srtp", None)
330             .unwrap();
331 
332         stream.write_all(&[0]).unwrap();
333 
334         buf
335     });
336 
337     let stream = TcpStream::connect(addr).unwrap();
338     let mut ctx = SslContext::builder(SslMethod::dtls()).unwrap();
339     ctx.set_tlsext_use_srtp("SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32")
340         .unwrap();
341     let mut ssl = Ssl::new(&ctx.build()).unwrap();
342     ssl.set_mtu(1500).unwrap();
343     let mut stream = ssl.connect(stream).unwrap();
344 
345     let mut buf = [1; 60];
346     {
347         let srtp_profile = stream.ssl().selected_srtp_profile().unwrap();
348         assert_eq!("SRTP_AES128_CM_SHA1_80", srtp_profile.name());
349         assert_eq!(SrtpProfileId::SRTP_AES128_CM_SHA1_80, srtp_profile.id());
350     }
351     stream
352         .ssl()
353         .export_keying_material(&mut buf, "EXTRACTOR-dtls_srtp", None)
354         .expect("extract");
355 
356     stream.read_exact(&mut [0]).unwrap();
357 
358     let buf2 = guard.join().unwrap();
359 
360     assert_eq!(buf[..], buf2[..]);
361 }
362 
363 /// Tests that when both the client as well as the server use SRTP and their
364 /// lists of supported protocols have an overlap -- with only ONE protocol
365 /// being valid for both.
366 #[test]
test_connect_with_srtp_ssl()367 fn test_connect_with_srtp_ssl() {
368     let listener = TcpListener::bind("127.0.0.1:0").unwrap();
369     let addr = listener.local_addr().unwrap();
370 
371     let guard = thread::spawn(move || {
372         let stream = listener.accept().unwrap().0;
373         let mut ctx = SslContext::builder(SslMethod::dtls()).unwrap();
374         ctx.set_certificate_file(&Path::new("test/cert.pem"), SslFiletype::PEM)
375             .unwrap();
376         ctx.set_private_key_file(&Path::new("test/key.pem"), SslFiletype::PEM)
377             .unwrap();
378         let mut ssl = Ssl::new(&ctx.build()).unwrap();
379         ssl.set_tlsext_use_srtp("SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32")
380             .unwrap();
381         let mut profilenames = String::new();
382         for profile in ssl.srtp_profiles().unwrap() {
383             if !profilenames.is_empty() {
384                 profilenames.push(':');
385             }
386             profilenames += profile.name();
387         }
388         assert_eq!(
389             "SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32",
390             profilenames
391         );
392         ssl.set_mtu(1500).unwrap();
393         let mut stream = ssl.accept(stream).unwrap();
394 
395         let mut buf = [0; 60];
396         stream
397             .ssl()
398             .export_keying_material(&mut buf, "EXTRACTOR-dtls_srtp", None)
399             .unwrap();
400 
401         stream.write_all(&[0]).unwrap();
402 
403         buf
404     });
405 
406     let stream = TcpStream::connect(addr).unwrap();
407     let ctx = SslContext::builder(SslMethod::dtls()).unwrap();
408     let mut ssl = Ssl::new(&ctx.build()).unwrap();
409     ssl.set_tlsext_use_srtp("SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32")
410         .unwrap();
411     ssl.set_mtu(1500).unwrap();
412     let mut stream = ssl.connect(stream).unwrap();
413 
414     let mut buf = [1; 60];
415     {
416         let srtp_profile = stream.ssl().selected_srtp_profile().unwrap();
417         assert_eq!("SRTP_AES128_CM_SHA1_80", srtp_profile.name());
418         assert_eq!(SrtpProfileId::SRTP_AES128_CM_SHA1_80, srtp_profile.id());
419     }
420     stream
421         .ssl()
422         .export_keying_material(&mut buf, "EXTRACTOR-dtls_srtp", None)
423         .expect("extract");
424 
425     stream.read_exact(&mut [0]).unwrap();
426 
427     let buf2 = guard.join().unwrap();
428 
429     assert_eq!(buf[..], buf2[..]);
430 }
431 
432 /// Tests that when the `SslStream` is created as a server stream, the protocols
433 /// are correctly advertised to the client.
434 #[test]
435 #[cfg(any(ossl102, libressl261))]
test_alpn_server_advertise_multiple()436 fn test_alpn_server_advertise_multiple() {
437     let mut server = Server::builder();
438     server.ctx().set_alpn_select_callback(|_, client| {
439         ssl::select_next_proto(b"\x08http/1.1\x08spdy/3.1", client).ok_or(ssl::AlpnError::NOACK)
440     });
441     let server = server.build();
442 
443     let mut client = server.client();
444     client.ctx().set_alpn_protos(b"\x08spdy/3.1").unwrap();
445     let s = client.connect();
446     assert_eq!(s.ssl().selected_alpn_protocol(), Some(&b"spdy/3.1"[..]));
447 }
448 
449 #[test]
450 #[cfg(any(ossl110))]
test_alpn_server_select_none_fatal()451 fn test_alpn_server_select_none_fatal() {
452     let mut server = Server::builder();
453     server.ctx().set_alpn_select_callback(|_, client| {
454         ssl::select_next_proto(b"\x08http/1.1\x08spdy/3.1", client)
455             .ok_or(ssl::AlpnError::ALERT_FATAL)
456     });
457     server.should_error();
458     let server = server.build();
459 
460     let mut client = server.client();
461     client.ctx().set_alpn_protos(b"\x06http/2").unwrap();
462     client.connect_err();
463 }
464 
465 #[test]
466 #[cfg(any(ossl102, libressl261))]
test_alpn_server_select_none()467 fn test_alpn_server_select_none() {
468     let mut server = Server::builder();
469     server.ctx().set_alpn_select_callback(|_, client| {
470         ssl::select_next_proto(b"\x08http/1.1\x08spdy/3.1", client).ok_or(ssl::AlpnError::NOACK)
471     });
472     let server = server.build();
473 
474     let mut client = server.client();
475     client.ctx().set_alpn_protos(b"\x06http/2").unwrap();
476     let s = client.connect();
477     assert_eq!(None, s.ssl().selected_alpn_protocol());
478 }
479 
480 #[test]
481 #[cfg(any(ossl102, libressl261))]
test_alpn_server_unilateral()482 fn test_alpn_server_unilateral() {
483     let server = Server::builder().build();
484 
485     let mut client = server.client();
486     client.ctx().set_alpn_protos(b"\x06http/2").unwrap();
487     let s = client.connect();
488     assert_eq!(None, s.ssl().selected_alpn_protocol());
489 }
490 
491 #[test]
492 #[should_panic(expected = "blammo")]
write_panic()493 fn write_panic() {
494     struct ExplodingStream(TcpStream);
495 
496     impl Read for ExplodingStream {
497         fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
498             self.0.read(buf)
499         }
500     }
501 
502     impl Write for ExplodingStream {
503         fn write(&mut self, _: &[u8]) -> io::Result<usize> {
504             panic!("blammo");
505         }
506 
507         fn flush(&mut self) -> io::Result<()> {
508             self.0.flush()
509         }
510     }
511 
512     let mut server = Server::builder();
513     server.should_error();
514     let server = server.build();
515 
516     let stream = ExplodingStream(server.connect_tcp());
517 
518     let ctx = SslContext::builder(SslMethod::tls()).unwrap();
519     let _ = Ssl::new(&ctx.build()).unwrap().connect(stream);
520 }
521 
522 #[test]
523 #[should_panic(expected = "blammo")]
read_panic()524 fn read_panic() {
525     struct ExplodingStream(TcpStream);
526 
527     impl Read for ExplodingStream {
528         fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
529             panic!("blammo");
530         }
531     }
532 
533     impl Write for ExplodingStream {
534         fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
535             self.0.write(buf)
536         }
537 
538         fn flush(&mut self) -> io::Result<()> {
539             self.0.flush()
540         }
541     }
542 
543     let mut server = Server::builder();
544     server.should_error();
545     let server = server.build();
546 
547     let stream = ExplodingStream(server.connect_tcp());
548 
549     let ctx = SslContext::builder(SslMethod::tls()).unwrap();
550     let _ = Ssl::new(&ctx.build()).unwrap().connect(stream);
551 }
552 
553 #[test]
554 #[cfg_attr(libressl321, ignore)]
555 #[should_panic(expected = "blammo")]
flush_panic()556 fn flush_panic() {
557     struct ExplodingStream(TcpStream);
558 
559     impl Read for ExplodingStream {
560         fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
561             self.0.read(buf)
562         }
563     }
564 
565     impl Write for ExplodingStream {
566         fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
567             self.0.write(buf)
568         }
569 
570         fn flush(&mut self) -> io::Result<()> {
571             panic!("blammo");
572         }
573     }
574 
575     let mut server = Server::builder();
576     server.should_error();
577     let server = server.build();
578 
579     let stream = ExplodingStream(server.connect_tcp());
580 
581     let ctx = SslContext::builder(SslMethod::tls()).unwrap();
582     let _ = Ssl::new(&ctx.build()).unwrap().connect(stream);
583 }
584 
585 #[test]
refcount_ssl_context()586 fn refcount_ssl_context() {
587     let mut ssl = {
588         let ctx = SslContext::builder(SslMethod::tls()).unwrap();
589         ssl::Ssl::new(&ctx.build()).unwrap()
590     };
591 
592     {
593         let new_ctx_a = SslContext::builder(SslMethod::tls()).unwrap().build();
594         let _new_ctx_b = ssl.set_ssl_context(&new_ctx_a);
595     }
596 }
597 
598 #[test]
599 #[cfg_attr(libressl250, ignore)]
600 #[cfg_attr(target_os = "windows", ignore)]
601 #[cfg_attr(all(target_os = "macos", feature = "vendored"), ignore)]
default_verify_paths()602 fn default_verify_paths() {
603     let mut ctx = SslContext::builder(SslMethod::tls()).unwrap();
604     ctx.set_default_verify_paths().unwrap();
605     ctx.set_verify(SslVerifyMode::PEER);
606     let ctx = ctx.build();
607     let s = match TcpStream::connect("google.com:443") {
608         Ok(s) => s,
609         Err(_) => return,
610     };
611     let mut ssl = Ssl::new(&ctx).unwrap();
612     ssl.set_hostname("google.com").unwrap();
613     let mut socket = ssl.connect(s).unwrap();
614 
615     socket.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap();
616     let mut result = vec![];
617     socket.read_to_end(&mut result).unwrap();
618 
619     println!("{}", String::from_utf8_lossy(&result));
620     assert!(result.starts_with(b"HTTP/1.0"));
621     assert!(result.ends_with(b"</HTML>\r\n") || result.ends_with(b"</html>"));
622 }
623 
624 #[test]
add_extra_chain_cert()625 fn add_extra_chain_cert() {
626     let cert = X509::from_pem(CERT).unwrap();
627     let mut ctx = SslContext::builder(SslMethod::tls()).unwrap();
628     ctx.add_extra_chain_cert(cert).unwrap();
629 }
630 
631 #[test]
632 #[cfg(ossl102)]
verify_valid_hostname()633 fn verify_valid_hostname() {
634     let server = Server::builder().build();
635 
636     let mut client = server.client();
637     client.ctx().set_ca_file("test/root-ca.pem").unwrap();
638     client.ctx().set_verify(SslVerifyMode::PEER);
639 
640     let mut client = client.build().builder();
641     client
642         .ssl()
643         .param_mut()
644         .set_hostflags(X509CheckFlags::NO_PARTIAL_WILDCARDS);
645     client.ssl().param_mut().set_host("foobar.com").unwrap();
646     client.connect();
647 }
648 
649 #[test]
650 #[cfg(ossl102)]
verify_invalid_hostname()651 fn verify_invalid_hostname() {
652     let mut server = Server::builder();
653     server.should_error();
654     let server = server.build();
655 
656     let mut client = server.client();
657     client.ctx().set_ca_file("test/root-ca.pem").unwrap();
658     client.ctx().set_verify(SslVerifyMode::PEER);
659 
660     let mut client = client.build().builder();
661     client
662         .ssl()
663         .param_mut()
664         .set_hostflags(X509CheckFlags::NO_PARTIAL_WILDCARDS);
665     client.ssl().param_mut().set_host("bogus.com").unwrap();
666     client.connect_err();
667 }
668 
669 #[test]
connector_valid_hostname()670 fn connector_valid_hostname() {
671     let server = Server::builder().build();
672 
673     let mut connector = SslConnector::builder(SslMethod::tls()).unwrap();
674     connector.set_ca_file("test/root-ca.pem").unwrap();
675 
676     let s = server.connect_tcp();
677     let mut s = connector.build().connect("foobar.com", s).unwrap();
678     s.read_exact(&mut [0]).unwrap();
679 }
680 
681 #[test]
connector_invalid_hostname()682 fn connector_invalid_hostname() {
683     let mut server = Server::builder();
684     server.should_error();
685     let server = server.build();
686 
687     let mut connector = SslConnector::builder(SslMethod::tls()).unwrap();
688     connector.set_ca_file("test/root-ca.pem").unwrap();
689 
690     let s = server.connect_tcp();
691     connector.build().connect("bogus.com", s).unwrap_err();
692 }
693 
694 #[test]
connector_invalid_no_hostname_verification()695 fn connector_invalid_no_hostname_verification() {
696     let server = Server::builder().build();
697 
698     let mut connector = SslConnector::builder(SslMethod::tls()).unwrap();
699     connector.set_ca_file("test/root-ca.pem").unwrap();
700 
701     let s = server.connect_tcp();
702     let mut s = connector
703         .build()
704         .configure()
705         .unwrap()
706         .verify_hostname(false)
707         .connect("bogus.com", s)
708         .unwrap();
709     s.read_exact(&mut [0]).unwrap();
710 }
711 
712 #[test]
connector_no_hostname_still_verifies()713 fn connector_no_hostname_still_verifies() {
714     let mut server = Server::builder();
715     server.should_error();
716     let server = server.build();
717 
718     let connector = SslConnector::builder(SslMethod::tls()).unwrap().build();
719 
720     let s = server.connect_tcp();
721     assert!(connector
722         .configure()
723         .unwrap()
724         .verify_hostname(false)
725         .connect("fizzbuzz.com", s)
726         .is_err());
727 }
728 
729 #[test]
connector_no_hostname_can_disable_verify()730 fn connector_no_hostname_can_disable_verify() {
731     let server = Server::builder().build();
732 
733     let mut connector = SslConnector::builder(SslMethod::tls()).unwrap();
734     connector.set_verify(SslVerifyMode::NONE);
735     let connector = connector.build();
736 
737     let s = server.connect_tcp();
738     let mut s = connector
739         .configure()
740         .unwrap()
741         .verify_hostname(false)
742         .connect("foobar.com", s)
743         .unwrap();
744     s.read_exact(&mut [0]).unwrap();
745 }
746 
test_mozilla_server(new: fn(SslMethod) -> Result<SslAcceptorBuilder, ErrorStack>)747 fn test_mozilla_server(new: fn(SslMethod) -> Result<SslAcceptorBuilder, ErrorStack>) {
748     let listener = TcpListener::bind("127.0.0.1:0").unwrap();
749     let port = listener.local_addr().unwrap().port();
750 
751     let t = thread::spawn(move || {
752         let key = PKey::private_key_from_pem(KEY).unwrap();
753         let cert = X509::from_pem(CERT).unwrap();
754         let mut acceptor = new(SslMethod::tls()).unwrap();
755         acceptor.set_private_key(&key).unwrap();
756         acceptor.set_certificate(&cert).unwrap();
757         let acceptor = acceptor.build();
758         let stream = listener.accept().unwrap().0;
759         let mut stream = acceptor.accept(stream).unwrap();
760 
761         stream.write_all(b"hello").unwrap();
762     });
763 
764     let mut connector = SslConnector::builder(SslMethod::tls()).unwrap();
765     connector.set_ca_file("test/root-ca.pem").unwrap();
766     let connector = connector.build();
767 
768     let stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
769     let mut stream = connector.connect("foobar.com", stream).unwrap();
770 
771     let mut buf = [0; 5];
772     stream.read_exact(&mut buf).unwrap();
773     assert_eq!(b"hello", &buf);
774 
775     t.join().unwrap();
776 }
777 
778 #[test]
connector_client_server_mozilla_intermediate()779 fn connector_client_server_mozilla_intermediate() {
780     test_mozilla_server(SslAcceptor::mozilla_intermediate);
781 }
782 
783 #[test]
connector_client_server_mozilla_modern()784 fn connector_client_server_mozilla_modern() {
785     test_mozilla_server(SslAcceptor::mozilla_modern);
786 }
787 
788 #[test]
connector_client_server_mozilla_intermediate_v5()789 fn connector_client_server_mozilla_intermediate_v5() {
790     test_mozilla_server(SslAcceptor::mozilla_intermediate_v5);
791 }
792 
793 #[test]
794 #[cfg(ossl111)]
connector_client_server_mozilla_modern_v5()795 fn connector_client_server_mozilla_modern_v5() {
796     test_mozilla_server(SslAcceptor::mozilla_modern_v5);
797 }
798 
799 #[test]
shutdown()800 fn shutdown() {
801     let mut server = Server::builder();
802     server.io_cb(|mut s| {
803         assert_eq!(s.read(&mut [0]).unwrap(), 0);
804         assert_eq!(s.shutdown().unwrap(), ShutdownResult::Received);
805     });
806     let server = server.build();
807 
808     let mut s = server.client().connect();
809 
810     assert_eq!(s.get_shutdown(), ShutdownState::empty());
811     assert_eq!(s.shutdown().unwrap(), ShutdownResult::Sent);
812     assert_eq!(s.get_shutdown(), ShutdownState::SENT);
813     assert_eq!(s.shutdown().unwrap(), ShutdownResult::Received);
814     assert_eq!(
815         s.get_shutdown(),
816         ShutdownState::SENT | ShutdownState::RECEIVED
817     );
818 }
819 
820 #[test]
client_ca_list()821 fn client_ca_list() {
822     let names = X509Name::load_client_ca_file("test/root-ca.pem").unwrap();
823     assert_eq!(names.len(), 1);
824 
825     let mut ctx = SslContext::builder(SslMethod::tls()).unwrap();
826     ctx.set_client_ca_list(names);
827 }
828 
829 #[test]
cert_store()830 fn cert_store() {
831     let server = Server::builder().build();
832 
833     let mut client = server.client();
834     let cert = X509::from_pem(ROOT_CERT).unwrap();
835     client.ctx().cert_store_mut().add_cert(cert).unwrap();
836     client.ctx().set_verify(SslVerifyMode::PEER);
837 
838     client.connect();
839 }
840 
841 #[test]
842 #[cfg_attr(libressl321, ignore)]
tmp_dh_callback()843 fn tmp_dh_callback() {
844     static CALLED_BACK: AtomicBool = AtomicBool::new(false);
845 
846     let mut server = Server::builder();
847     server.ctx().set_tmp_dh_callback(|_, _, _| {
848         CALLED_BACK.store(true, Ordering::SeqCst);
849         let dh = include_bytes!("../../../test/dhparams.pem");
850         Dh::params_from_pem(dh)
851     });
852 
853     let server = server.build();
854 
855     let mut client = server.client();
856     // TLS 1.3 has no DH suites, so make sure we don't pick that version
857     #[cfg(ossl111)]
858     client.ctx().set_options(super::SslOptions::NO_TLSV1_3);
859     client.ctx().set_cipher_list("EDH").unwrap();
860     client.connect();
861 
862     assert!(CALLED_BACK.load(Ordering::SeqCst));
863 }
864 
865 #[test]
866 #[cfg(all(ossl101, not(ossl110)))]
tmp_ecdh_callback()867 fn tmp_ecdh_callback() {
868     use crate::ec::EcKey;
869     use crate::nid::Nid;
870 
871     static CALLED_BACK: AtomicBool = AtomicBool::new(false);
872 
873     let mut server = Server::builder();
874     server.ctx().set_tmp_ecdh_callback(|_, _, _| {
875         CALLED_BACK.store(true, Ordering::SeqCst);
876         EcKey::from_curve_name(Nid::X9_62_PRIME256V1)
877     });
878 
879     let server = server.build();
880 
881     let mut client = server.client();
882     client.ctx().set_cipher_list("ECDH").unwrap();
883     client.connect();
884 
885     assert!(CALLED_BACK.load(Ordering::SeqCst));
886 }
887 
888 #[test]
889 #[cfg_attr(libressl321, ignore)]
tmp_dh_callback_ssl()890 fn tmp_dh_callback_ssl() {
891     static CALLED_BACK: AtomicBool = AtomicBool::new(false);
892 
893     let mut server = Server::builder();
894     server.ssl_cb(|ssl| {
895         ssl.set_tmp_dh_callback(|_, _, _| {
896             CALLED_BACK.store(true, Ordering::SeqCst);
897             let dh = include_bytes!("../../../test/dhparams.pem");
898             Dh::params_from_pem(dh)
899         });
900     });
901 
902     let server = server.build();
903 
904     let mut client = server.client();
905     // TLS 1.3 has no DH suites, so make sure we don't pick that version
906     #[cfg(ossl111)]
907     client.ctx().set_options(super::SslOptions::NO_TLSV1_3);
908     client.ctx().set_cipher_list("EDH").unwrap();
909     client.connect();
910 
911     assert!(CALLED_BACK.load(Ordering::SeqCst));
912 }
913 
914 #[test]
915 #[cfg(all(ossl101, not(ossl110)))]
tmp_ecdh_callback_ssl()916 fn tmp_ecdh_callback_ssl() {
917     use crate::ec::EcKey;
918     use crate::nid::Nid;
919 
920     static CALLED_BACK: AtomicBool = AtomicBool::new(false);
921 
922     let mut server = Server::builder();
923     server.ssl_cb(|ssl| {
924         ssl.set_tmp_ecdh_callback(|_, _, _| {
925             CALLED_BACK.store(true, Ordering::SeqCst);
926             EcKey::from_curve_name(Nid::X9_62_PRIME256V1)
927         });
928     });
929 
930     let server = server.build();
931 
932     let mut client = server.client();
933     client.ctx().set_cipher_list("ECDH").unwrap();
934     client.connect();
935 
936     assert!(CALLED_BACK.load(Ordering::SeqCst));
937 }
938 
939 #[test]
idle_session()940 fn idle_session() {
941     let ctx = SslContext::builder(SslMethod::tls()).unwrap().build();
942     let ssl = Ssl::new(&ctx).unwrap();
943     assert!(ssl.session().is_none());
944 }
945 
946 #[test]
947 #[cfg_attr(libressl321, ignore)]
active_session()948 fn active_session() {
949     let server = Server::builder().build();
950 
951     let s = server.client().connect();
952 
953     let session = s.ssl().session().unwrap();
954     let len = session.master_key_len();
955     let mut buf = vec![0; len - 1];
956     let copied = session.master_key(&mut buf);
957     assert_eq!(copied, buf.len());
958     let mut buf = vec![0; len + 1];
959     let copied = session.master_key(&mut buf);
960     assert_eq!(copied, len);
961 }
962 
963 #[test]
status_callbacks()964 fn status_callbacks() {
965     static CALLED_BACK_SERVER: AtomicBool = AtomicBool::new(false);
966     static CALLED_BACK_CLIENT: AtomicBool = AtomicBool::new(false);
967 
968     let mut server = Server::builder();
969     server
970         .ctx()
971         .set_status_callback(|ssl| {
972             CALLED_BACK_SERVER.store(true, Ordering::SeqCst);
973             let response = OcspResponse::create(OcspResponseStatus::UNAUTHORIZED, None).unwrap();
974             let response = response.to_der().unwrap();
975             ssl.set_ocsp_status(&response).unwrap();
976             Ok(true)
977         })
978         .unwrap();
979 
980     let server = server.build();
981 
982     let mut client = server.client();
983     client
984         .ctx()
985         .set_status_callback(|ssl| {
986             CALLED_BACK_CLIENT.store(true, Ordering::SeqCst);
987             let response = OcspResponse::from_der(ssl.ocsp_status().unwrap()).unwrap();
988             assert_eq!(response.status(), OcspResponseStatus::UNAUTHORIZED);
989             Ok(true)
990         })
991         .unwrap();
992 
993     let mut client = client.build().builder();
994     client.ssl().set_status_type(StatusType::OCSP).unwrap();
995 
996     client.connect();
997 
998     assert!(CALLED_BACK_SERVER.load(Ordering::SeqCst));
999     assert!(CALLED_BACK_CLIENT.load(Ordering::SeqCst));
1000 }
1001 
1002 #[test]
1003 #[cfg_attr(libressl321, ignore)]
new_session_callback()1004 fn new_session_callback() {
1005     static CALLED_BACK: AtomicBool = AtomicBool::new(false);
1006 
1007     let mut server = Server::builder();
1008     server.ctx().set_session_id_context(b"foo").unwrap();
1009 
1010     let server = server.build();
1011 
1012     let mut client = server.client();
1013 
1014     client
1015         .ctx()
1016         .set_session_cache_mode(SslSessionCacheMode::CLIENT | SslSessionCacheMode::NO_INTERNAL);
1017     client
1018         .ctx()
1019         .set_new_session_callback(|_, _| CALLED_BACK.store(true, Ordering::SeqCst));
1020 
1021     client.connect();
1022 
1023     assert!(CALLED_BACK.load(Ordering::SeqCst));
1024 }
1025 
1026 #[test]
1027 #[cfg_attr(libressl321, ignore)]
new_session_callback_swapped_ctx()1028 fn new_session_callback_swapped_ctx() {
1029     static CALLED_BACK: AtomicBool = AtomicBool::new(false);
1030 
1031     let mut server = Server::builder();
1032     server.ctx().set_session_id_context(b"foo").unwrap();
1033 
1034     let server = server.build();
1035 
1036     let mut client = server.client();
1037 
1038     client
1039         .ctx()
1040         .set_session_cache_mode(SslSessionCacheMode::CLIENT | SslSessionCacheMode::NO_INTERNAL);
1041     client
1042         .ctx()
1043         .set_new_session_callback(|_, _| CALLED_BACK.store(true, Ordering::SeqCst));
1044 
1045     let mut client = client.build().builder();
1046 
1047     let ctx = SslContextBuilder::new(SslMethod::tls()).unwrap().build();
1048     client.ssl().set_ssl_context(&ctx).unwrap();
1049 
1050     client.connect();
1051 
1052     assert!(CALLED_BACK.load(Ordering::SeqCst));
1053 }
1054 
1055 #[test]
keying_export()1056 fn keying_export() {
1057     let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1058     let addr = listener.local_addr().unwrap();
1059 
1060     let label = "EXPERIMENTAL test";
1061     let context = b"my context";
1062 
1063     let guard = thread::spawn(move || {
1064         let stream = listener.accept().unwrap().0;
1065         let mut ctx = SslContext::builder(SslMethod::tls()).unwrap();
1066         ctx.set_certificate_file(&Path::new("test/cert.pem"), SslFiletype::PEM)
1067             .unwrap();
1068         ctx.set_private_key_file(&Path::new("test/key.pem"), SslFiletype::PEM)
1069             .unwrap();
1070         let ssl = Ssl::new(&ctx.build()).unwrap();
1071         let mut stream = ssl.accept(stream).unwrap();
1072 
1073         let mut buf = [0; 32];
1074         stream
1075             .ssl()
1076             .export_keying_material(&mut buf, label, Some(context))
1077             .unwrap();
1078 
1079         stream.write_all(&[0]).unwrap();
1080 
1081         buf
1082     });
1083 
1084     let stream = TcpStream::connect(addr).unwrap();
1085     let ctx = SslContext::builder(SslMethod::tls()).unwrap();
1086     let ssl = Ssl::new(&ctx.build()).unwrap();
1087     let mut stream = ssl.connect(stream).unwrap();
1088 
1089     let mut buf = [1; 32];
1090     stream
1091         .ssl()
1092         .export_keying_material(&mut buf, label, Some(context))
1093         .unwrap();
1094 
1095     stream.read_exact(&mut [0]).unwrap();
1096 
1097     let buf2 = guard.join().unwrap();
1098 
1099     assert_eq!(buf, buf2);
1100 }
1101 
1102 #[test]
1103 #[cfg(any(ossl110, libressl261))]
no_version_overlap()1104 fn no_version_overlap() {
1105     let mut server = Server::builder();
1106     server.ctx().set_min_proto_version(None).unwrap();
1107     server
1108         .ctx()
1109         .set_max_proto_version(Some(SslVersion::TLS1_1))
1110         .unwrap();
1111     #[cfg(any(ossl110g, libressl270))]
1112     assert_eq!(server.ctx().max_proto_version(), Some(SslVersion::TLS1_1));
1113     server.should_error();
1114     let server = server.build();
1115 
1116     let mut client = server.client();
1117     client
1118         .ctx()
1119         .set_min_proto_version(Some(SslVersion::TLS1_2))
1120         .unwrap();
1121     #[cfg(ossl110g)]
1122     assert_eq!(client.ctx().min_proto_version(), Some(SslVersion::TLS1_2));
1123     client.ctx().set_max_proto_version(None).unwrap();
1124 
1125     client.connect_err();
1126 }
1127 
1128 #[test]
1129 #[cfg(ossl111)]
custom_extensions()1130 fn custom_extensions() {
1131     static FOUND_EXTENSION: AtomicBool = AtomicBool::new(false);
1132 
1133     let mut server = Server::builder();
1134     server
1135         .ctx()
1136         .add_custom_ext(
1137             12345,
1138             ExtensionContext::CLIENT_HELLO,
1139             |_, _, _| -> Result<Option<&'static [u8]>, _> { unreachable!() },
1140             |_, _, data, _| {
1141                 FOUND_EXTENSION.store(data == b"hello", Ordering::SeqCst);
1142                 Ok(())
1143             },
1144         )
1145         .unwrap();
1146 
1147     let server = server.build();
1148 
1149     let mut client = server.client();
1150     client
1151         .ctx()
1152         .add_custom_ext(
1153             12345,
1154             ssl::ExtensionContext::CLIENT_HELLO,
1155             |_, _, _| Ok(Some(b"hello")),
1156             |_, _, _, _| unreachable!(),
1157         )
1158         .unwrap();
1159 
1160     client.connect();
1161 
1162     assert!(FOUND_EXTENSION.load(Ordering::SeqCst));
1163 }
1164 
_check_kinds()1165 fn _check_kinds() {
1166     fn is_send<T: Send>() {}
1167     fn is_sync<T: Sync>() {}
1168 
1169     is_send::<SslStream<TcpStream>>();
1170     is_sync::<SslStream<TcpStream>>();
1171 }
1172 
1173 #[test]
1174 #[cfg(ossl111)]
stateless()1175 fn stateless() {
1176     use super::SslOptions;
1177 
1178     #[derive(Debug)]
1179     struct MemoryStream {
1180         incoming: io::Cursor<Vec<u8>>,
1181         outgoing: Vec<u8>,
1182     }
1183 
1184     impl MemoryStream {
1185         pub fn new() -> Self {
1186             Self {
1187                 incoming: io::Cursor::new(Vec::new()),
1188                 outgoing: Vec::new(),
1189             }
1190         }
1191 
1192         pub fn extend_incoming(&mut self, data: &[u8]) {
1193             self.incoming.get_mut().extend_from_slice(data);
1194         }
1195 
1196         pub fn take_outgoing(&mut self) -> Outgoing<'_> {
1197             Outgoing(&mut self.outgoing)
1198         }
1199     }
1200 
1201     impl Read for MemoryStream {
1202         fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1203             let n = self.incoming.read(buf)?;
1204             if self.incoming.position() == self.incoming.get_ref().len() as u64 {
1205                 self.incoming.set_position(0);
1206                 self.incoming.get_mut().clear();
1207             }
1208             if n == 0 {
1209                 return Err(io::Error::new(
1210                     io::ErrorKind::WouldBlock,
1211                     "no data available",
1212                 ));
1213             }
1214             Ok(n)
1215         }
1216     }
1217 
1218     impl Write for MemoryStream {
1219         fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1220             self.outgoing.write(buf)
1221         }
1222 
1223         fn flush(&mut self) -> io::Result<()> {
1224             Ok(())
1225         }
1226     }
1227 
1228     pub struct Outgoing<'a>(&'a mut Vec<u8>);
1229 
1230     impl<'a> Drop for Outgoing<'a> {
1231         fn drop(&mut self) {
1232             self.0.clear();
1233         }
1234     }
1235 
1236     impl<'a> ::std::ops::Deref for Outgoing<'a> {
1237         type Target = [u8];
1238         fn deref(&self) -> &[u8] {
1239             self.0
1240         }
1241     }
1242 
1243     impl<'a> AsRef<[u8]> for Outgoing<'a> {
1244         fn as_ref(&self) -> &[u8] {
1245             self.0
1246         }
1247     }
1248 
1249     fn send(from: &mut MemoryStream, to: &mut MemoryStream) {
1250         to.extend_incoming(&from.take_outgoing());
1251     }
1252 
1253     //
1254     // Setup
1255     //
1256 
1257     let mut client_ctx = SslContext::builder(SslMethod::tls()).unwrap();
1258     client_ctx.clear_options(SslOptions::ENABLE_MIDDLEBOX_COMPAT);
1259     let mut client_stream =
1260         SslStream::new(Ssl::new(&client_ctx.build()).unwrap(), MemoryStream::new()).unwrap();
1261 
1262     let mut server_ctx = SslContext::builder(SslMethod::tls()).unwrap();
1263     server_ctx
1264         .set_certificate_file(&Path::new("test/cert.pem"), SslFiletype::PEM)
1265         .unwrap();
1266     server_ctx
1267         .set_private_key_file(&Path::new("test/key.pem"), SslFiletype::PEM)
1268         .unwrap();
1269     const COOKIE: &[u8] = b"chocolate chip";
1270     server_ctx.set_stateless_cookie_generate_cb(|_tls, buf| {
1271         buf[0..COOKIE.len()].copy_from_slice(COOKIE);
1272         Ok(COOKIE.len())
1273     });
1274     server_ctx.set_stateless_cookie_verify_cb(|_tls, buf| buf == COOKIE);
1275     let mut server_stream =
1276         SslStream::new(Ssl::new(&server_ctx.build()).unwrap(), MemoryStream::new()).unwrap();
1277 
1278     //
1279     // Handshake
1280     //
1281 
1282     // Initial ClientHello
1283     client_stream.connect().unwrap_err();
1284     send(client_stream.get_mut(), server_stream.get_mut());
1285     // HelloRetryRequest
1286     assert!(!server_stream.stateless().unwrap());
1287     send(server_stream.get_mut(), client_stream.get_mut());
1288     // Second ClientHello
1289     client_stream.do_handshake().unwrap_err();
1290     send(client_stream.get_mut(), server_stream.get_mut());
1291     // OldServerHello
1292     assert!(server_stream.stateless().unwrap());
1293     server_stream.accept().unwrap_err();
1294     send(server_stream.get_mut(), client_stream.get_mut());
1295     // Finished
1296     client_stream.do_handshake().unwrap();
1297     send(client_stream.get_mut(), server_stream.get_mut());
1298     server_stream.do_handshake().unwrap();
1299 }
1300 
1301 #[cfg(not(osslconf = "OPENSSL_NO_PSK"))]
1302 #[test]
psk_ciphers()1303 fn psk_ciphers() {
1304     const CIPHER: &str = "PSK-AES128-CBC-SHA";
1305     const PSK: &[u8] = b"thisisaverysecurekey";
1306     const CLIENT_IDENT: &[u8] = b"thisisaclient";
1307     static CLIENT_CALLED: AtomicBool = AtomicBool::new(false);
1308     static SERVER_CALLED: AtomicBool = AtomicBool::new(false);
1309 
1310     let mut server = Server::builder();
1311     server.ctx().set_cipher_list(CIPHER).unwrap();
1312     server.ctx().set_psk_server_callback(|_, identity, psk| {
1313         assert!(identity.unwrap_or(&[]) == CLIENT_IDENT);
1314         psk[..PSK.len()].copy_from_slice(PSK);
1315         SERVER_CALLED.store(true, Ordering::SeqCst);
1316         Ok(PSK.len())
1317     });
1318 
1319     let server = server.build();
1320 
1321     let mut client = server.client();
1322     // This test relies on TLS 1.2 suites
1323     #[cfg(ossl111)]
1324     client.ctx().set_options(super::SslOptions::NO_TLSV1_3);
1325     client.ctx().set_cipher_list(CIPHER).unwrap();
1326     client
1327         .ctx()
1328         .set_psk_client_callback(move |_, _, identity, psk| {
1329             identity[..CLIENT_IDENT.len()].copy_from_slice(CLIENT_IDENT);
1330             identity[CLIENT_IDENT.len()] = 0;
1331             psk[..PSK.len()].copy_from_slice(PSK);
1332             CLIENT_CALLED.store(true, Ordering::SeqCst);
1333             Ok(PSK.len())
1334         });
1335 
1336     client.connect();
1337 
1338     assert!(CLIENT_CALLED.load(Ordering::SeqCst) && SERVER_CALLED.load(Ordering::SeqCst));
1339 }
1340 
1341 #[test]
sni_callback_swapped_ctx()1342 fn sni_callback_swapped_ctx() {
1343     static CALLED_BACK: AtomicBool = AtomicBool::new(false);
1344 
1345     let mut server = Server::builder();
1346 
1347     let mut ctx = SslContext::builder(SslMethod::tls()).unwrap();
1348     ctx.set_servername_callback(|_, _| {
1349         CALLED_BACK.store(true, Ordering::SeqCst);
1350         Ok(())
1351     });
1352 
1353     let keyed_ctx = mem::replace(server.ctx(), ctx).build();
1354     server.ssl_cb(move |ssl| ssl.set_ssl_context(&keyed_ctx).unwrap());
1355 
1356     let server = server.build();
1357 
1358     server.client().connect();
1359 
1360     assert!(CALLED_BACK.load(Ordering::SeqCst));
1361 }
1362 
1363 #[test]
1364 #[cfg(ossl111)]
client_hello()1365 fn client_hello() {
1366     static CALLED_BACK: AtomicBool = AtomicBool::new(false);
1367 
1368     let mut server = Server::builder();
1369     server.ctx().set_client_hello_callback(|ssl, _| {
1370         assert!(!ssl.client_hello_isv2());
1371         assert_eq!(ssl.client_hello_legacy_version(), Some(SslVersion::TLS1_2));
1372         assert!(ssl.client_hello_random().is_some());
1373         assert!(ssl.client_hello_session_id().is_some());
1374         assert!(ssl.client_hello_ciphers().is_some());
1375         assert!(ssl.client_hello_compression_methods().is_some());
1376 
1377         CALLED_BACK.store(true, Ordering::SeqCst);
1378         Ok(ClientHelloResponse::SUCCESS)
1379     });
1380 
1381     let server = server.build();
1382     server.client().connect();
1383 
1384     assert!(CALLED_BACK.load(Ordering::SeqCst));
1385 }
1386 
1387 #[test]
1388 #[cfg(ossl111)]
openssl_cipher_name()1389 fn openssl_cipher_name() {
1390     assert_eq!(
1391         super::cipher_name("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"),
1392         "ECDHE-RSA-AES256-SHA384",
1393     );
1394 
1395     assert_eq!(super::cipher_name("asdf"), "(NONE)");
1396 }
1397 
1398 #[test]
session_cache_size()1399 fn session_cache_size() {
1400     let mut ctx = SslContext::builder(SslMethod::tls()).unwrap();
1401     ctx.set_session_cache_size(1234);
1402     let ctx = ctx.build();
1403     assert_eq!(ctx.session_cache_size(), 1234);
1404 }
1405