Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_net/tests/tls_handshake.rs

7.9 KiB, 3 runs

created by r1870400018:65933, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1#![cfg(feature = "async")]
2//! Whose fault a failed server-side TLS handshake is.
3//!
4//! A public listener is probed all day by scanners, old clients and clients that hang up, and
5//! every one of those ends a handshake in an error. A caller that logs each at `ERROR` buries the
6//! faults that are the server's own, so `BoundedTlsAcceptor` says which kind it was:
7//! `Handshake::PeerFailed` for a peer that offered nothing acceptable, spoke nonsense or hung up,
8//! `Handshake::Failed` for anything that may be ours -- a certificate that cannot be served, or a
9//! client rejecting the one it was given. When in doubt the answer is `Failed`.
10
11use oxedyne_fe2o3_core::prelude::*;
12use oxedyne_fe2o3_net::tls::{
13 ensure_crypto_provider,
14 BoundedTlsAcceptor,
15 Handshake,
16};
17
18use std::{
19 future::Future,
20 sync::Arc,
21 time::Duration,
22};
23
24use tokio::{
25 io::AsyncWriteExt,
26 net::{
27 TcpListener,
28 TcpStream,
29 },
30};
31use tokio_rustls::{
32 rustls::{
33 client::ClientConfig,
34 pki_types::{
35 CertificateDer,
36 PrivateKeyDer,
37 PrivatePkcs8KeyDer,
38 ServerName,
39 },
40 server::{
41 ClientHello,
42 ResolvesServerCert,
43 ServerConfig,
44 },
45 sign::CertifiedKey,
46 version,
47 RootCertStore,
48 },
49 TlsAcceptor,
50 TlsConnector,
51};
52
53
54const HOST: &str = "scan.test.local";
55const WAIT: Duration = Duration::from_secs(5);
56
57/// A certificate for [`HOST`] and the key that goes with it.
58fn identity() -> Outcome<(CertificateDer<'static>, PrivateKeyDer<'static>)> {
59 let cert = res!(rcgen::generate_simple_self_signed(vec![HOST.to_string()]), Init);
60 let der = res!(cert.serialize_der(), Init);
61 let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(cert.serialize_private_key_der()));
62 Ok((CertificateDer::from(der), key))
63}
64
65/// A server that holds a certificate and key and is willing to speak TLS 1.2 and 1.3, offering
66/// `http/1.1` the way Steel does.
67fn server_tls() -> Outcome<ServerConfig> {
68 ensure_crypto_provider();
69 let (der, key) = res!(identity());
70 let mut cfg = res!(ServerConfig::builder()
71 .with_no_client_auth()
72 .with_single_cert(vec![der], key), Init);
73 cfg.alpn_protocols.push(b"http/1.1".to_vec());
74 Ok(cfg)
75}
76
77/// A client with an empty root store, which trusts no certificate a server could show it.
78fn client_tls_trusting_nothing() -> ClientConfig {
79 // Built before `server_tls` installs the provider, so it must not rely on test order.
80 ensure_crypto_provider();
81 ClientConfig::builder()
82 .with_root_certificates(RootCertStore::empty())
83 .with_no_client_auth()
84}
85
86/// Which arm a handshake took, as a word an assertion can show.
87fn kind<IO>(h: &Handshake<IO>) -> &'static str {
88 match h {
89 Handshake::Ok(_) => "ok",
90 Handshake::TimedOut => "timed out",
91 Handshake::PeerFailed(_) => "peer failed",
92 Handshake::Failed(_) => "failed",
93 }
94}
95
96/// Runs one server-side handshake on loopback against whatever `client` does with its end of the
97/// connection, and returns what the acceptor made of it.
98async fn serve<F, Fut>(server: ServerConfig, client: F) -> Outcome<Handshake<TcpStream>>
99where
100 F: FnOnce(TcpStream) -> Fut + Send + 'static,
101 Fut: Future<Output = ()> + Send + 'static,
102{
103 let listener = res!(TcpListener::bind("127.0.0.1:0").await, IO, Network);
104 let addr = res!(listener.local_addr(), IO, Network);
105 let peer = tokio::spawn(async move {
106 if let Ok(s) = TcpStream::connect(addr).await {
107 client(s).await;
108 }
109 });
110 let (stream, _) = res!(listener.accept().await, IO, Network);
111 let acceptor = BoundedTlsAcceptor::new(TlsAcceptor::from(Arc::new(server)), 0, Some(WAIT));
112 let h = acceptor.accept(stream).await;
113 let _ = peer.await;
114 Ok(h)
115}
116
117/// A client that completes the handshake as far as it can with `cfg`, then lets go.
118async fn connect_with(cfg: ClientConfig, s: TcpStream) {
119 let name = match ServerName::try_from(HOST) {
120 Ok(n) => n,
121 Err(_) => return,
122 };
123 let _ = TlsConnector::from(Arc::new(cfg)).connect(name, s).await;
124}
125
126/// A server that has no certificate for anybody, as when none loaded at start.
127#[derive(Debug)]
128struct NoCert;
129
130impl ResolvesServerCert for NoCert {
131 fn resolve(&self, _hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
132 None
133 }
134}
135
136#[tokio::test]
137async fn test_a_client_that_trusts_the_server_completes_the_handshake() -> Outcome<()> {
138 // The client's one root is the server's own certificate, so nothing about it can be refused.
139 ensure_crypto_provider();
140 let (der, key) = res!(identity());
141 let mut srv = res!(ServerConfig::builder()
142 .with_no_client_auth()
143 .with_single_cert(vec![der.clone()], key), Init);
144 srv.alpn_protocols.push(b"http/1.1".to_vec());
145 let mut roots = RootCertStore::empty();
146 res!(roots.add(der), Init);
147 let mut cli = ClientConfig::builder().with_root_certificates(roots).with_no_client_auth();
148 cli.alpn_protocols.push(b"http/1.1".to_vec());
149 let h = res!(serve(srv, move |s| connect_with(cli, s)).await);
150 assert_eq!(kind(&h), "ok");
151 Ok(())
152}
153
154#[tokio::test]
155async fn test_a_client_with_no_application_protocol_in_common_is_the_peers_fault() -> Outcome<()> {
156 let mut cli = client_tls_trusting_nothing();
157 cli.alpn_protocols.push(b"h2".to_vec());
158 let h = res!(serve(res!(server_tls()), move |s| connect_with(cli, s)).await);
159 assert_eq!(kind(&h), "peer failed", "an ALPN offer the server cannot meet");
160 Ok(())
161}
162
163#[tokio::test]
164async fn test_a_client_offering_no_protocol_version_we_serve_is_the_peers_fault() -> Outcome<()> {
165 ensure_crypto_provider();
166 // A server that will only speak TLS 1.3 and a client that will only speak TLS 1.2.
167 let (der, key) = res!(identity());
168 let srv = res!(ServerConfig::builder_with_protocol_versions(&[&version::TLS13])
169 .with_no_client_auth()
170 .with_single_cert(vec![der], key), Init);
171 let cli = ClientConfig::builder_with_protocol_versions(&[&version::TLS12])
172 .with_root_certificates(RootCertStore::empty())
173 .with_no_client_auth();
174 let h = res!(serve(srv, move |s| connect_with(cli, s)).await);
175 assert_eq!(kind(&h), "peer failed", "a version the server does not offer");
176 Ok(())
177}
178
179#[tokio::test]
180async fn test_a_client_that_hangs_up_before_it_speaks_is_the_peers_fault() -> Outcome<()> {
181 let h = res!(serve(res!(server_tls()), |s| async move { drop(s); }).await);
182 assert_eq!(kind(&h), "peer failed", "a connection closed with no ClientHello");
183 Ok(())
184}
185
186#[tokio::test]
187async fn test_a_client_that_speaks_plain_http_to_a_tls_port_is_the_peers_fault() -> Outcome<()> {
188 let h = res!(serve(res!(server_tls()), |mut s| async move {
189 let _ = s.write_all(b"\x16\x03\x01\x00\x05GET /\r\n\r\n").await;
190 let _ = s.flush().await;
191 }).await);
192 assert_eq!(kind(&h), "peer failed", "nonsense after a TLS record header");
193 Ok(())
194}
195
196#[tokio::test]
197async fn test_a_server_with_no_certificate_to_serve_is_not_blamed_on_the_client() -> Outcome<()> {
198 ensure_crypto_provider();
199 let srv = ServerConfig::builder()
200 .with_no_client_auth()
201 .with_cert_resolver(Arc::new(NoCert));
202 let cli = client_tls_trusting_nothing();
203 let h = res!(serve(srv, move |s| connect_with(cli, s)).await);
204 assert_eq!(kind(&h), "failed", "a fault of the server's own must stay a fault");
205 Ok(())
206}
207
208#[tokio::test]
209async fn test_a_client_that_rejects_the_certificate_is_not_blamed_on_the_client() -> Outcome<()> {
210 // The client's alert says our certificate is unacceptable, which is how an expired or
211 // mismatched certificate shows up here, so it is not written off as a scanner.
212 let cli = client_tls_trusting_nothing();
213 let h = res!(serve(res!(server_tls()), move |s| connect_with(cli, s)).await);
214 assert_eq!(kind(&h), "failed", "a client's alert against the server's certificate");
215 Ok(())
216}