1#![warn(missing_docs)]
80
81mod certs;
82mod ktls;
83mod received;
84
85pub use certs::Certificates;
86pub use ktls::{ktls_stats, ktls_support, Ktls, KtlsStats, KtlsSupport};
87pub use received::Received;
88pub use rustls_pki_types::CertificateDer;
91
92#[cfg(fuzzing)]
95#[doc(hidden)]
96pub mod fuzzing {
97 pub use crate::ktls::{check_handshake_messages, check_record_framing};
98}
99
100use std::cell::{Cell, RefCell, RefMut};
101use std::collections::HashSet;
102use std::ffi::OsStr;
103use std::future::poll_fn;
104use std::io::{self, Read, Write};
105use std::mem;
106use std::net::Shutdown;
107use std::path::{Path, PathBuf};
108use std::sync::Arc;
109use std::task::{Poll, Waker};
110use std::time::Duration;
111
112use giong::error::Code;
113use giong::net::TcpStream;
114use giong::time::timeout;
115use rustls::client::ResolvesClientCert;
116use rustls::pki_types::pem::PemObject;
117use rustls::pki_types::{PrivateKeyDer, ServerName};
118use rustls::sign::CertifiedKey;
119use rustls::{
120 ClientConfig, ClientConnection, Connection, RootCertStore, ServerConfig, ServerConnection,
121 SignatureScheme,
122};
123
124#[cfg(feature = "unstable-rustls")]
130pub use rustls;
131
132fn coded(
133 code: Code,
134 message: impl Into<std::borrow::Cow<'static, str>>,
135 fix: &'static str,
136) -> io::Error {
137 giong::error::Error::new(code, message, fix).into()
138}
139
140fn file_too_short(offset: u64, len: u64, at: u64) -> io::Error {
143 let end = offset.saturating_add(len);
144 coded(
145 Code::FileTooShort,
146 format!(
147 "the file ended at byte {at}, {} bytes short of the {len} send_file was asked to send",
148 end - at
149 ),
150 "take the length from the open file (File::len), and replace a file that is being \
151 served by renaming a new one over it, not by rewriting it; the peer has fewer bytes \
152 than announced, so close the connection.",
153 )
154}
155
156pub(crate) fn bad_certificate_data(e: impl std::fmt::Display) -> io::Error {
158 coded(
159 Code::BadCertificateData,
160 e.to_string(),
161 "check that the file or data is PEM (\"-----BEGIN CERTIFICATE-----\") and holds \
162 at least one certificate.",
163 )
164}
165
166pub(crate) fn bad_key(e: impl std::fmt::Display) -> io::Error {
168 coded(
169 Code::BadCertificateData,
170 format!("cannot read the private key: {e}"),
171 "check that it is a PEM private key (\"-----BEGIN PRIVATE KEY-----\", or the RSA or \
172 EC forms).",
173 )
174}
175
176pub(crate) fn mismatched_key(e: rustls::Error) -> io::Error {
178 coded(
179 Code::BadCertificateData,
180 format!("the certificate and the private key cannot be used together: {e}"),
181 "check that the key belongs to the first certificate of the chain, and that its type \
182 (RSA, ECDSA, Ed25519) is supported.",
183 )
184}
185
186fn tls_error(e: rustls::Error) -> io::Error {
188 match e {
189 rustls::Error::InvalidCertificate(_) if e.to_string().contains("CaUsedAsEndEntity") => {
192 coded(
193 Code::TlsCertificate,
194 "the peer's certificate was rejected: it is marked as a certificate authority \
195 (basicConstraints CA:TRUE), and an authority's certificate cannot be the \
196 peer's own (CaUsedAsEndEntity)",
197 "issue the peer's certificate with CA:FALSE: a self-signed one made with \
198 `openssl req -x509` needs -addext \"basicConstraints=critical,CA:FALSE\"; or \
199 have the authority sign a separate certificate for the peer.",
200 )
201 }
202 rustls::Error::InvalidCertificate(_) => coded(
203 Code::TlsCertificate,
204 format!("the peer's certificate was rejected: {e}"),
205 "check the name you connect to, the certificate's expiry and its chain; a \
206 private authority has to be trusted with TlsConnector::with_root_pem.",
207 ),
208 e => coded(
209 Code::TlsProtocol,
210 format!("TLS error: {e}"),
211 "check that the other side speaks TLS on this port, and that both sides share a \
212 protocol version and cipher suite.",
213 ),
214 }
215}
216
217const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
219
220fn handshake_timed_out(limit: Duration) -> io::Error {
221 coded(
222 Code::TlsHandshakeTimeout,
223 format!("the TLS handshake did not finish within {limit:?}"),
224 "check that the other side speaks TLS on this port and is not overloaded, or raise \
225 handshake_timeout.",
226 )
227}
228
229fn handshake_eof() -> io::Error {
230 coded(
231 Code::TlsHandshakeEof,
232 "the peer closed the connection during the TLS handshake",
233 "check that the other side speaks TLS on this port, and whether it wants a client \
234 certificate or another server name.",
235 )
236}
237
238const WIRE_KEPT: usize = 16 * 1024;
243
244const SEND_AT: usize = 64 * 1024;
247
248#[cfg(test)]
249thread_local! {
250 static FLUSH_ROOM: Cell<usize> = const { Cell::new(usize::MAX) };
253}
254
255fn flush_room() -> usize {
258 #[cfg(test)]
259 return FLUSH_ROOM.with(Cell::get);
260 #[cfg(not(test))]
261 usize::MAX
262}
263
264fn has_application_data(records: &[u8]) -> bool {
268 let mut at = 0;
269 while let Some(header) = records.get(at..at + 5) {
270 if header[0] == 23 {
271 return true;
272 }
273 at += 5 + usize::from(u16::from_be_bytes([header[3], header[4]]));
274 }
275 false
276}
277
278fn sending_closed(code: Code) -> io::Error {
281 match code {
282 Code::TlsKeysExhausted => coded(
283 Code::TlsKeysExhausted,
284 "this connection has sent as many TLS records as its cipher allows under one key, \
285 and cannot change keys (TLS 1.2, or TLS 1.3 on a kernel older than 6.14); \
286 close_notify was sent",
287 "open a new connection. TLS 1.3 changes keys instead (in the process, and with \
288 kernel TLS on Linux 6.14 or newer).",
289 ),
290 _ => coded(
291 Code::TlsBroken,
292 "this TLS stream has been shut down or ended with an alert; nothing more can be sent",
293 "open a new connection.",
294 ),
295 }
296}
297
298fn broken() -> io::Error {
299 coded(
300 Code::TlsBroken,
301 "a TLS write failed or was cancelled; nothing more can be sent",
302 "open a new connection. A write cancelled half-way (a dropped future, a timeout) \
303 leaves a partial record or message behind, so the stream cannot go on.",
304 )
305}
306
307pub(crate) fn pem_certs(pem: &[u8]) -> io::Result<Vec<CertificateDer<'static>>> {
309 let certs = CertificateDer::pem_slice_iter(pem)
310 .collect::<Result<Vec<_>, _>>()
311 .map_err(bad_certificate_data)?;
312 if certs.is_empty() {
313 return Err(bad_certificate_data("no certificate found in the PEM data"));
314 }
315 Ok(certs)
316}
317
318pub(crate) fn provider() -> Arc<rustls::crypto::CryptoProvider> {
322 Arc::new(base_provider())
323}
324
325#[cfg(not(feature = "post-quantum"))]
326fn base_provider() -> rustls::crypto::CryptoProvider {
327 rustls::crypto::ring::default_provider()
328}
329
330#[cfg(feature = "post-quantum")]
331fn base_provider() -> rustls::crypto::CryptoProvider {
332 rustls::crypto::aws_lc_rs::default_provider()
333}
334
335fn provider_aes128_first() -> Arc<rustls::crypto::CryptoProvider> {
345 use rustls::CipherSuite as S;
346 let mut provider = base_provider();
347 provider.cipher_suites.sort_by_key(|suite| {
350 let rank = match suite.suite() {
351 S::TLS13_AES_128_GCM_SHA256
352 | S::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
353 | S::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 => 0,
354 S::TLS13_CHACHA20_POLY1305_SHA256
355 | S::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
356 | S::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 => 1,
357 _ => 2,
358 };
359 (
360 suite.version().version != rustls::ProtocolVersion::TLSv1_3,
361 rank,
362 )
363 });
364 Arc::new(provider)
365}
366
367fn prefers_chacha(hello: &[u8]) -> bool {
375 const SESSION_ID: usize = 5 + 4 + 2 + 32;
377 if hello.first() != Some(&22) || hello.get(5) != Some(&1) {
378 return false;
379 }
380 let Some(&id_len) = hello.get(SESSION_ID) else {
381 return false;
382 };
383 let at = SESSION_ID + 1 + usize::from(id_len);
384 let Some(len) = hello.get(at..at + 2) else {
385 return false;
386 };
387 let len = usize::from(u16::from_be_bytes([len[0], len[1]]));
388 let Some(suites) = hello.get(at + 2..at + 2 + len) else {
389 return false;
390 };
391 for suite in suites.chunks_exact(2) {
392 match [suite[0], suite[1]] {
393 [0x13, 0x01]
396 | [0x13, 0x02]
397 | [0xc0, 0x2b]
398 | [0xc0, 0x2f]
399 | [0xc0, 0x2c]
400 | [0xc0, 0x30] => return false,
401 [0x13, 0x03] | [0xcc, 0xa9] | [0xcc, 0xa8] => return true,
403 _ => {}
404 }
405 }
406 false
407}
408
409fn server_configs(
414 certificates: &Certificates,
415 verifier: Arc<dyn rustls::server::danger::ClientCertVerifier>,
416) -> io::Result<(ServerConfig, ServerConfig)> {
417 let mut config = ServerConfig::builder_with_provider(provider_aes128_first())
418 .with_safe_default_protocol_versions()
419 .map_err(tls_error)?
420 .with_client_cert_verifier(verifier)
421 .with_cert_resolver(certificates.resolver());
422 let chacha = config.clone();
423 config.ignore_client_order = true;
424 Ok((config, chacha))
425}
426
427#[derive(Clone)]
431pub struct TlsAcceptor {
432 config: Arc<ServerConfig>,
433 chacha: Option<Arc<ServerConfig>>,
438 handshake_timeout: Duration,
439 ktls: ktls::Plan,
440 certificates: Option<Certificates>,
444}
445
446impl TlsAcceptor {
447 #[cfg(feature = "unstable-rustls")]
455 pub fn from_rustls(config: Arc<ServerConfig>) -> Self {
456 Self::with_config(config)
457 }
458
459 fn with_config(config: Arc<ServerConfig>) -> Self {
460 Self {
461 config,
462 chacha: None,
463 handshake_timeout: HANDSHAKE_TIMEOUT,
464 ktls: ktls::Plan::Off,
465 certificates: None,
466 }
467 }
468
469 pub fn with_certificates(certificates: &Certificates) -> io::Result<Self> {
494 let verifier = rustls::server::WebPkiClientVerifier::no_client_auth();
495 let (config, chacha) = server_configs(certificates, verifier)?;
496 Ok(Self {
497 chacha: Some(Arc::new(chacha)),
498 certificates: Some(certificates.clone()),
499 ..Self::with_config(Arc::new(config))
500 })
501 }
502
503 pub fn require_client_cert(self, ca_pem: &[u8]) -> io::Result<Self> {
513 self.client_auth(ca_pem, true)
514 }
515
516 pub fn request_client_cert(self, ca_pem: &[u8]) -> io::Result<Self> {
523 self.client_auth(ca_pem, false)
524 }
525
526 fn client_auth(mut self, ca_pem: &[u8], required: bool) -> io::Result<Self> {
527 let Some(certificates) = &self.certificates else {
528 return Err(coded(
529 Code::TlsConfig,
530 "client certificates cannot be set on an acceptor made with from_rustls",
531 "set client authentication in the rustls configuration given to from_rustls \
532 (ServerConfig::builder().with_client_cert_verifier), or make the acceptor \
533 with with_certificates.",
534 ));
535 };
536 let mut roots = RootCertStore::empty();
537 for cert in pem_certs(ca_pem)? {
538 roots.add(cert).map_err(bad_certificate_data)?;
539 }
540 let builder = rustls::server::WebPkiClientVerifier::builder_with_provider(
541 Arc::new(roots),
542 self.config.crypto_provider().clone(),
543 );
544 let builder = if required {
545 builder
546 } else {
547 builder.allow_unauthenticated()
548 };
549 let verifier = builder.build().map_err(bad_certificate_data)?;
550 let (mut config, mut chacha) = server_configs(certificates, verifier)?;
551 for new in [&mut config, &mut chacha] {
553 new.alpn_protocols = self.config.alpn_protocols.clone();
554 new.enable_secret_extraction = self.config.enable_secret_extraction;
555 }
556 self.config = Arc::new(config);
557 self.chacha = Some(Arc::new(chacha));
558 Ok(self)
559 }
560
561 fn config_for(&self, hello: &[u8]) -> Arc<ServerConfig> {
564 match &self.chacha {
565 Some(chacha) if prefers_chacha(hello) => chacha.clone(),
566 _ => self.config.clone(),
567 }
568 }
569
570 fn change_config(&mut self, change: impl Fn(&mut ServerConfig)) {
572 change(Arc::make_mut(&mut self.config));
573 if let Some(chacha) = &mut self.chacha {
574 change(Arc::make_mut(chacha));
575 }
576 }
577
578 pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
586 let protocols: Vec<Vec<u8>> = protocols.iter().map(|p| p.to_vec()).collect();
587 self.change_config(|config| config.alpn_protocols = protocols.clone());
588 self
589 }
590
591 pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
594 self.handshake_timeout = timeout;
595 self
596 }
597
598 pub fn ktls(mut self, mode: Ktls) -> io::Result<Self> {
625 let early_data = self.config.max_early_data_size > 0;
626 self.ktls = ktls::Plan::new(mode, self.config.crypto_provider(), early_data)?;
627 let extract = self.ktls.tries();
629 if self.config.enable_secret_extraction != extract {
630 self.change_config(|config| config.enable_secret_extraction = extract);
631 }
632 Ok(self)
633 }
634
635 pub fn ktls_unavailable(&self) -> Option<&str> {
640 self.ktls.unavailable()
641 }
642
643 pub async fn accept(&self, tcp: TcpStream) -> io::Result<TlsStream> {
652 let tcp = match &self.ktls {
653 ktls::Plan::Off => tcp,
654 ktls::Plan::Try { required } => {
655 let start = ktls::Start::Server(self.config.clone(), self.chacha.clone());
656 match ktls::handshake(tcp, start, self.handshake_timeout).await? {
657 ktls::Outcome::Kernel(tls) => return Ok(*tls),
658 ktls::Outcome::Declined(_, e) if *required => return Err(e),
659 ktls::Outcome::Declined(tcp, _) => {
660 self.ktls.stayed();
661 tcp
662 }
663 }
664 }
665 ktls::Plan::Unavailable(_) => {
666 self.ktls.stayed();
667 tcp
668 }
669 };
670 let Some(_) = &self.chacha else {
671 let conn = ServerConnection::new(self.config.clone()).map_err(tls_error)?;
672 return TlsStream::new(tcp, conn.into())
673 .handshake(self.handshake_timeout, Duration::ZERO, None)
674 .await;
675 };
676 let started = std::time::Instant::now();
679 let first = match timeout(self.handshake_timeout, tcp.recv()).await {
680 Ok(first) => first?,
681 Err(_) => return Err(handshake_timed_out(self.handshake_timeout)),
682 };
683 if first.is_empty() {
684 return Err(handshake_eof());
685 }
686 let conn = ServerConnection::new(self.config_for(&first)).map_err(tls_error)?;
687 TlsStream::new(tcp, conn.into())
688 .handshake(self.handshake_timeout, started.elapsed(), Some(first))
689 .await
690 }
691}
692
693impl std::fmt::Debug for TlsAcceptor {
694 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
695 f.debug_struct("TlsAcceptor")
696 .field("handshake_timeout", &self.handshake_timeout)
697 .field("ktls", &self.ktls)
698 .finish_non_exhaustive()
699 }
700}
701
702#[derive(Clone)]
723pub struct TlsConnector {
724 config: Arc<ClientConfig>,
725 handshake_timeout: Duration,
726 ktls: ktls::Plan,
727}
728
729impl TlsConnector {
730 #[cfg(feature = "unstable-rustls")]
738 pub fn from_rustls(config: Arc<ClientConfig>) -> Self {
739 Self::with_config(config)
740 }
741
742 fn with_config(config: Arc<ClientConfig>) -> Self {
743 Self {
744 config,
745 handshake_timeout: HANDSHAKE_TIMEOUT,
746 ktls: ktls::Plan::Off,
747 }
748 }
749
750 fn from_roots(roots: RootCertStore) -> io::Result<Self> {
751 if roots.is_empty() {
752 return Err(coded(
753 Code::NoTrustedRoots,
754 "no trusted certificate authority given",
755 "pass at least one certificate, or use TlsConnector::with_system_roots.",
756 ));
757 }
758 let config = ClientConfig::builder_with_provider(provider())
759 .with_safe_default_protocol_versions()
760 .map_err(tls_error)?
761 .with_root_certificates(roots)
762 .with_no_client_auth();
763 Ok(Self::with_config(Arc::new(config)))
764 }
765
766 pub fn with_root_pem(pem: &[u8]) -> io::Result<Self> {
775 let mut roots = RootCertStore::empty();
776 for cert in pem_certs(pem)? {
777 roots.add(cert).map_err(bad_certificate_data)?;
778 }
779 Self::from_roots(roots)
780 }
781
782 pub fn with_root_pem_any_name(pem: &[u8]) -> io::Result<Self> {
794 let mut roots = RootCertStore::empty();
795 for cert in pem_certs(pem)? {
796 roots.add(cert).map_err(bad_certificate_data)?;
797 }
798 if roots.is_empty() {
799 return Err(coded(
800 Code::NoTrustedRoots,
801 "no trusted certificate authority given",
802 "pass at least one certificate authority in PEM form.",
803 ));
804 }
805 let provider = provider();
806 let webpki = rustls::client::WebPkiServerVerifier::builder_with_provider(
807 Arc::new(roots),
808 provider.clone(),
809 )
810 .build()
811 .map_err(bad_certificate_data)?;
812 let config = ClientConfig::builder_with_provider(provider)
813 .with_safe_default_protocol_versions()
814 .map_err(tls_error)?
815 .dangerous()
816 .with_custom_certificate_verifier(Arc::new(AnyName(webpki)))
817 .with_no_client_auth();
818 Ok(Self::with_config(Arc::new(config)))
819 }
820
821 pub fn with_system_roots() -> io::Result<Self> {
837 let file = std::env::var_os("SSL_CERT_FILE");
838 let dirs = std::env::var_os("SSL_CERT_DIR");
839 let roots = load_roots(
840 file.as_deref(),
841 dirs.as_deref(),
842 SYSTEM_CA_BUNDLES,
843 SYSTEM_CA_DIR,
844 )?;
845 Self::from_roots(roots)
846 }
847
848 #[cfg(feature = "webpki-roots")]
855 pub fn with_webpki_roots() -> Self {
856 let roots = RootCertStore {
857 roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
858 };
859 Self::from_roots(roots).expect("the webpki-roots crate provides roots")
860 }
861
862 pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
866 Arc::make_mut(&mut self.config).alpn_protocols =
867 protocols.iter().map(|p| p.to_vec()).collect();
868 self
869 }
870
871 pub fn client_auth(mut self, cert_chain: &[u8], private_key: &[u8]) -> io::Result<Self> {
874 let certs = pem_certs(cert_chain)?;
875 let key = PrivateKeyDer::from_pem_slice(private_key).map_err(bad_key)?;
876 let key = CertifiedKey::from_der(certs, key, self.config.crypto_provider())
877 .map_err(mismatched_key)?;
878 Arc::make_mut(&mut self.config).client_auth_cert_resolver =
879 Arc::new(ClientCert(Arc::new(key)));
880 Ok(self)
881 }
882
883 pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
886 self.handshake_timeout = timeout;
887 self
888 }
889
890 pub fn ktls(mut self, mode: Ktls) -> io::Result<Self> {
904 let early_data = self.config.enable_early_data;
905 self.ktls = ktls::Plan::new(mode, self.config.crypto_provider(), early_data)?;
906 let extract = self.ktls.tries();
907 if self.config.enable_secret_extraction != extract {
908 Arc::make_mut(&mut self.config).enable_secret_extraction = extract;
909 }
910 Ok(self)
911 }
912
913 pub fn ktls_unavailable(&self) -> Option<&str> {
916 self.ktls.unavailable()
917 }
918
919 pub async fn connect(&self, server_name: &str, tcp: TcpStream) -> io::Result<TlsStream> {
931 let name = parse_server_name(server_name)?;
932 let tcp = match &self.ktls {
933 ktls::Plan::Off => tcp,
934 ktls::Plan::Try { required } => {
935 let start = ktls::Start::Client(self.config.clone(), name.clone());
936 match ktls::handshake(tcp, start, self.handshake_timeout).await? {
937 ktls::Outcome::Kernel(tls) => return Ok(*tls),
938 ktls::Outcome::Declined(_, e) if *required => return Err(e),
939 ktls::Outcome::Declined(tcp, _) => {
940 self.ktls.stayed();
941 tcp
942 }
943 }
944 }
945 ktls::Plan::Unavailable(_) => {
946 self.ktls.stayed();
947 tcp
948 }
949 };
950 let conn = ClientConnection::new(self.config.clone(), name).map_err(tls_error)?;
951 TlsStream::new(tcp, conn.into())
952 .handshake(self.handshake_timeout, Duration::ZERO, None)
953 .await
954 }
955}
956
957impl std::fmt::Debug for TlsConnector {
958 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
959 f.debug_struct("TlsConnector")
960 .field("handshake_timeout", &self.handshake_timeout)
961 .field("ktls", &self.ktls)
962 .finish_non_exhaustive()
963 }
964}
965
966struct AnyName(Arc<rustls::client::WebPkiServerVerifier>);
970
971impl std::fmt::Debug for AnyName {
972 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
973 f.write_str("AnyName")
974 }
975}
976
977impl rustls::client::danger::ServerCertVerifier for AnyName {
978 fn verify_server_cert(
979 &self,
980 end_entity: &CertificateDer<'_>,
981 intermediates: &[CertificateDer<'_>],
982 server_name: &ServerName<'_>,
983 ocsp_response: &[u8],
984 now: rustls::pki_types::UnixTime,
985 ) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
986 use rustls::CertificateError;
987 match self
988 .0
989 .verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)
990 {
991 Err(rustls::Error::InvalidCertificate(
995 CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. },
996 )) => Ok(rustls::client::danger::ServerCertVerified::assertion()),
997 other => other,
998 }
999 }
1000
1001 fn verify_tls12_signature(
1002 &self,
1003 message: &[u8],
1004 cert: &CertificateDer<'_>,
1005 dss: &rustls::DigitallySignedStruct,
1006 ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
1007 self.0.verify_tls12_signature(message, cert, dss)
1008 }
1009
1010 fn verify_tls13_signature(
1011 &self,
1012 message: &[u8],
1013 cert: &CertificateDer<'_>,
1014 dss: &rustls::DigitallySignedStruct,
1015 ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
1016 self.0.verify_tls13_signature(message, cert, dss)
1017 }
1018
1019 fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
1020 self.0.supported_verify_schemes()
1021 }
1022}
1023
1024fn parse_server_name(name: &str) -> io::Result<ServerName<'static>> {
1026 let ipv6 = name
1027 .strip_prefix('[')
1028 .and_then(|n| n.strip_suffix(']'))
1029 .and_then(|n| n.parse::<std::net::Ipv6Addr>().ok());
1030 if let Some(ip) = ipv6 {
1031 return Ok(ServerName::IpAddress(std::net::IpAddr::V6(ip).into()));
1032 }
1033 ServerName::try_from(name.to_owned()).map_err(|_| {
1034 coded(
1035 Code::InvalidServerName,
1036 format!("{name:?} is neither a DNS name nor an IP address"),
1037 "pass the host name the certificate is for (\"example.com\"), or an IP address, \
1038 without a port or a scheme.",
1039 )
1040 })
1041}
1042
1043#[derive(Debug)]
1045struct ClientCert(Arc<CertifiedKey>);
1046
1047impl ResolvesClientCert for ClientCert {
1048 fn resolve(&self, _: &[&[u8]], _: &[SignatureScheme]) -> Option<Arc<CertifiedKey>> {
1049 Some(self.0.clone())
1050 }
1051
1052 fn has_certs(&self) -> bool {
1053 true
1054 }
1055}
1056
1057const SYSTEM_CA_BUNDLES: &[&str] = &[
1059 "/etc/ssl/certs/ca-certificates.crt",
1061 "/etc/pki/tls/certs/ca-bundle.crt",
1063 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
1064 "/etc/ssl/ca-bundle.pem",
1066 "/etc/ssl/cert.pem",
1068];
1069
1070const SYSTEM_CA_DIR: &str = "/etc/ssl/certs";
1072
1073fn load_roots(
1078 file: Option<&OsStr>,
1079 dirs: Option<&OsStr>,
1080 bundles: &[&str],
1081 dir: &str,
1082) -> io::Result<RootCertStore> {
1083 let mut roots = Roots {
1084 store: RootCertStore::empty(),
1085 seen: HashSet::new(),
1086 };
1087 if file.is_some() || dirs.is_some() {
1088 if let Some(file) = file {
1089 roots.add_file(Path::new(file)).map_err(|e| {
1090 io::Error::new(
1091 e.kind(),
1092 giong::error::Error::new(
1093 Code::BadCertificateData,
1094 format!("cannot read SSL_CERT_FILE {file:?}: {e}"),
1095 "point SSL_CERT_FILE at a readable PEM file of certificates, or unset \
1096 it to use the system's.",
1097 )
1098 .with_source(e),
1099 )
1100 })?;
1101 }
1102 for dir in dirs.map(std::env::split_paths).into_iter().flatten() {
1103 roots.add_dir(&dir);
1104 }
1105 } else if let Some(bundle) = bundles.iter().map(Path::new).find(|p| p.is_file()) {
1106 roots.add_file(bundle)?;
1107 } else {
1108 roots.add_dir(Path::new(dir));
1109 }
1110 if roots.store.is_empty() {
1111 return Err(coded(
1112 Code::NoTrustedRoots,
1113 "no trusted CA certificates found on this machine",
1114 "install the ca-certificates package, set SSL_CERT_FILE, or use \
1115 TlsConnector::with_webpki_roots (the webpki-roots feature of giong-tls).",
1116 ));
1117 }
1118 Ok(roots.store)
1119}
1120
1121struct Roots {
1122 store: RootCertStore,
1123 seen: HashSet<PathBuf>,
1126}
1127
1128impl Roots {
1129 fn add_file(&mut self, path: &Path) -> io::Result<()> {
1130 let real = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
1131 if !self.seen.insert(real) {
1132 return Ok(());
1133 }
1134 let pem = std::fs::read(path)?;
1135 let certs = CertificateDer::pem_slice_iter(&pem).filter_map(Result::ok);
1136 self.store.add_parsable_certificates(certs);
1137 Ok(())
1138 }
1139
1140 fn add_dir(&mut self, dir: &Path) {
1141 let Ok(entries) = std::fs::read_dir(dir) else {
1142 return;
1143 };
1144 let mut paths: Vec<PathBuf> = entries.filter_map(|e| Some(e.ok()?.path())).collect();
1145 paths.sort();
1146 for path in paths.iter().filter(|p| p.is_file()) {
1147 let _ = self.add_file(path);
1149 }
1150 }
1151}
1152
1153pub struct TlsStream {
1156 tcp: TcpStream,
1157 engine: RefCell<Engine>,
1159 plain: RefCell<Vec<u8>>,
1161 wire: RefCell<Vec<u8>>,
1164 established: Cell<bool>,
1168 eof: Cell<bool>,
1170 close_notify: Cell<bool>,
1173 sending: Cell<bool>,
1177 broken: Cell<bool>,
1180 closed: Cell<Option<Code>>,
1184 failed: Cell<Option<io::Error>>,
1186 waiters: RefCell<Vec<Waker>>,
1188 unsent: RefCell<Vec<u8>>,
1192}
1193
1194#[allow(clippy::large_enum_variant)]
1198enum Engine {
1199 User(Connection),
1201 Kernel(ktls::Kernel),
1204}
1205
1206struct Sending<'a> {
1210 stream: &'a TlsStream,
1211 complete: bool,
1212}
1213
1214impl Sending<'_> {
1215 fn done(mut self) {
1217 self.complete = true;
1218 }
1219}
1220
1221impl Drop for Sending<'_> {
1222 fn drop(&mut self) {
1223 if !self.complete {
1224 self.stream.broken.set(true);
1225 }
1226 self.stream.sending.set(false);
1227 self.stream.wake_waiters();
1228 }
1229}
1230
1231impl TlsStream {
1232 fn new(tcp: TcpStream, conn: Connection) -> Self {
1233 Self::with_engine(tcp, Engine::User(conn), Vec::new(), false)
1234 }
1235
1236 fn kernel(tcp: TcpStream, kernel: ktls::Kernel, plain: Vec<u8>, peer_closed: bool) -> Self {
1240 Self::with_engine(tcp, Engine::Kernel(kernel), plain, peer_closed)
1241 }
1242
1243 fn with_engine(tcp: TcpStream, engine: Engine, plain: Vec<u8>, peer_closed: bool) -> Self {
1244 Self {
1245 tcp,
1246 engine: RefCell::new(engine),
1247 plain: RefCell::new(plain),
1248 wire: RefCell::new(Vec::new()),
1249 established: Cell::new(false),
1250 eof: Cell::new(peer_closed),
1251 close_notify: Cell::new(peer_closed),
1252 sending: Cell::new(false),
1253 broken: Cell::new(false),
1254 closed: Cell::new(None),
1255 failed: Cell::new(None),
1256 waiters: RefCell::new(Vec::new()),
1257 unsent: RefCell::new(Vec::new()),
1258 }
1259 }
1260
1261 fn conn(&self) -> RefMut<'_, Connection> {
1264 RefMut::map(self.engine.borrow_mut(), |e| match e {
1265 Engine::User(c) => c,
1266 Engine::Kernel(_) => unreachable!("rustls' connection on a kernel TLS stream"),
1267 })
1268 }
1269
1270 pub fn is_ktls(&self) -> bool {
1274 matches!(*self.engine.borrow(), Engine::Kernel(_))
1275 }
1276
1277 async fn wait_for_sender(&self) {
1279 poll_fn(|cx| {
1280 if !self.sending.get() {
1281 return Poll::Ready(());
1282 }
1283 let mut waiters = self.waiters.borrow_mut();
1285 if !waiters.iter().any(|w| w.will_wake(cx.waker())) {
1286 waiters.push(cx.waker().clone());
1287 }
1288 Poll::Pending
1289 })
1290 .await;
1291 }
1292
1293 async fn lock_send(&self) -> Sending<'_> {
1296 while self.sending.get() {
1297 self.wait_for_sender().await;
1298 }
1299 self.sending.set(true);
1300 Sending {
1301 stream: self,
1302 complete: false,
1303 }
1304 }
1305
1306 async fn handshake(
1310 self,
1311 limit: Duration,
1312 spent: Duration,
1313 first: Option<giong::RecvBuf>,
1314 ) -> io::Result<Self> {
1315 let handshake = async {
1316 if let Some(first) = first {
1317 self.absorb(first).await?;
1318 }
1319 while self.conn().is_handshaking() {
1320 self.flush_tls().await?;
1321 if !self.conn().is_handshaking() {
1322 break;
1323 }
1324 if self.eof.get() {
1325 return Err(handshake_eof());
1326 }
1327 self.pump().await?;
1328 }
1329 if !self.hold_output() {
1330 self.flush_tls().await?;
1331 }
1332 self.established.set(true);
1333 Ok(())
1334 };
1335 match timeout(limit.saturating_sub(spent), handshake).await {
1336 Ok(Ok(())) => Ok(self),
1337 Ok(Err(e)) => Err(e),
1338 Err(_) => Err(handshake_timed_out(limit)),
1339 }
1340 }
1341
1342 fn wake_waiters(&self) {
1345 let waiters = mem::take(&mut *self.waiters.borrow_mut());
1346 for waker in waiters {
1347 waker.wake();
1348 }
1349 }
1350
1351 fn hold_output(&self) -> bool {
1365 if self.established.get() {
1366 return true;
1369 }
1370 let conn = self.conn();
1371 if conn.is_handshaking() {
1372 return false;
1373 }
1374 (matches!(*conn, Connection::Server(_))
1375 && conn.protocol_version() == Some(rustls::ProtocolVersion::TLSv1_3))
1376 }
1377
1378 fn take_wire(&self) -> Vec<u8> {
1382 let mut wire = mem::take(&mut *self.wire.borrow_mut());
1383 let mut unsent = self.unsent.borrow_mut();
1384 if unsent.capacity() > 0 {
1385 wire.extend_from_slice(&unsent);
1386 *unsent = Vec::new();
1388 }
1389 wire
1390 }
1391
1392 fn keep_wire(&self, mut wire: Vec<u8>) {
1396 if !wire.is_empty() && !self.broken.get() {
1397 self.unsent.borrow_mut().append(&mut wire);
1400 }
1401 if wire.capacity() <= WIRE_KEPT {
1402 wire.clear();
1403 *self.wire.borrow_mut() = wire;
1404 }
1405 }
1406
1407 fn cannot_send(&self) -> Option<io::Error> {
1410 if self.broken.get() {
1411 return Some(broken());
1412 }
1413 self.closed.get().map(sending_closed)
1414 }
1415
1416 async fn flush_tls(&self) -> io::Result<()> {
1420 loop {
1421 if !self.wants_send() {
1422 return Ok(());
1423 }
1424 if self.broken.get() {
1425 return Err(broken());
1426 }
1427 if self.sending.get() {
1428 self.wait_for_sender().await;
1431 continue;
1432 }
1433 let sending = self.lock_send().await;
1434 let mut wire = self.take_wire();
1435 let res = self.send_queued(&mut wire).await;
1436 self.keep_wire(wire);
1437 sending.done();
1438 res?;
1439 }
1440 }
1441
1442 async fn send_queued(&self, wire: &mut Vec<u8>) -> io::Result<()> {
1445 loop {
1446 {
1447 let mut conn = self.conn();
1448 while conn.wants_write() {
1449 conn.write_tls(wire)?;
1450 }
1451 }
1452 if wire.is_empty() {
1453 return Ok(());
1454 }
1455 self.send_wire(wire).await?;
1456 }
1457 }
1458
1459 fn wants_send(&self) -> bool {
1462 self.conn().wants_write() || !self.unsent.borrow().is_empty()
1463 }
1464
1465 fn flush_now(&self) -> io::Result<()> {
1477 if self.broken.get() {
1478 return Err(broken());
1479 }
1480 if self.sending.get() {
1481 return Ok(());
1482 }
1483 let mut unsent = self.unsent.borrow_mut();
1484 {
1485 let mut conn = self.conn();
1486 while conn.wants_write() {
1487 conn.write_tls(&mut *unsent)?;
1488 }
1489 }
1490 loop {
1491 let len = unsent.len().min(flush_room());
1493 if len == 0 {
1494 return Ok(());
1495 }
1496 let n = unsafe {
1498 libc::send(
1499 std::os::fd::AsRawFd::as_raw_fd(&self.tcp),
1500 unsent.as_ptr().cast(),
1501 len,
1502 libc::MSG_DONTWAIT | libc::MSG_NOSIGNAL,
1503 )
1504 };
1505 if n >= 0 {
1506 if n as usize == unsent.len() {
1507 *unsent = Vec::new();
1509 } else {
1510 unsent.drain(..n as usize);
1512 }
1513 return Ok(());
1514 }
1515 let e = io::Error::last_os_error();
1516 match e.kind() {
1517 io::ErrorKind::Interrupted => {}
1518 io::ErrorKind::WouldBlock => return Ok(()),
1519 _ => {
1520 self.broken.set(true);
1521 *unsent = Vec::new();
1522 return Err(e);
1523 }
1524 }
1525 }
1526 }
1527
1528 async fn send_wire(&self, wire: &mut Vec<u8>) -> io::Result<()> {
1532 let (res, mut sent) = self.tcp.write_all(mem::take(wire)).await;
1533 sent.clear();
1534 *wire = sent;
1535 if res.is_err() {
1536 self.broken.set(true);
1537 }
1538 res
1539 }
1540
1541 async fn send_plain(&self, wire: &mut Vec<u8>, data: &[u8], last: bool) -> io::Result<()> {
1553 let mut sent = 0;
1554 while sent < data.len() {
1555 let (carried, refused) = {
1556 let mut conn = self.conn();
1557 while conn.wants_write() {
1558 conn.write_tls(wire)?;
1559 }
1560 let carried = !wire.is_empty();
1561 let start = wire.len();
1562 let n = conn.writer().write(&data[sent..])?;
1563 while conn.wants_write() {
1564 conn.write_tls(wire)?;
1565 }
1566 sent += n;
1567 (carried, n > 0 && !has_application_data(&wire[start..]))
1572 };
1573 let more = sent < data.len() || !last;
1574 if !wire.is_empty() && (carried || refused || !more || wire.len() >= SEND_AT) {
1575 self.send_wire(wire).await?;
1576 }
1577 if carried {
1578 self.wake_waiters();
1580 }
1581 if refused {
1582 self.closed.set(Some(Code::TlsKeysExhausted));
1583 return Err(sending_closed(Code::TlsKeysExhausted));
1584 }
1585 }
1586 Ok(())
1587 }
1588
1589 async fn write_in_process(&self, pieces: &[&[u8]]) -> io::Result<()> {
1593 let sending = self.lock_send().await;
1594 if let Some(e) = self.cannot_send() {
1595 sending.done();
1596 return Err(e);
1597 }
1598 let mut wire = self.take_wire();
1599 let mut res = Ok(());
1600 for (i, piece) in pieces.iter().enumerate() {
1601 res = self
1602 .send_plain(&mut wire, piece, i + 1 == pieces.len())
1603 .await;
1604 if res.is_err() {
1605 break;
1606 }
1607 }
1608 if res.is_ok() && !wire.is_empty() {
1609 res = self.send_wire(&mut wire).await;
1611 }
1612 self.keep_wire(wire);
1613 sending.done();
1617 res
1618 }
1619
1620 async fn pump(&self) -> io::Result<()> {
1623 let ready = if !self.broken.get() && self.wants_send() {
1626 poll_fn(|cx| Poll::Ready(self.tcp.poll_recv(cx))).await
1627 } else {
1628 Poll::Pending
1629 };
1630 let chunk = match ready {
1631 Poll::Ready(chunk) => chunk?,
1632 Poll::Pending => {
1633 if !self.broken.get() && self.wants_send() {
1634 let _ = self.flush_for_recv().await;
1638 }
1639 self.tcp.recv().await?
1641 }
1642 };
1643 self.absorb(chunk).await
1644 }
1645
1646 async fn absorb(&self, chunk: giong::RecvBuf) -> io::Result<()> {
1650 if chunk.is_empty() {
1651 self.eof.set(true);
1652 return Ok(());
1653 }
1654 let result = {
1655 let mut conn = self.conn();
1656 let mut plain = self.plain.borrow_mut();
1657 let mut input = &chunk[..];
1658 let mut result = Ok(());
1659 while !input.is_empty() {
1660 match conn.read_tls(&mut input) {
1663 Ok(0) => {
1664 result = Err(coded(
1665 Code::TlsProtocol,
1666 "rustls accepted no more TLS data",
1667 "this is a bug in giong-tls; please report it at \
1668 https://github.com/giong-run/Giong/issues.",
1669 ));
1670 break;
1671 }
1672 Ok(_) => {}
1673 Err(e) => {
1674 result = Err(e);
1675 break;
1676 }
1677 }
1678 match conn.process_new_packets() {
1679 Ok(state) => {
1680 let n = state.plaintext_bytes_to_read();
1681 if n > 0 {
1682 let at = plain.len();
1683 plain.resize(at + n, 0);
1684 if let Err(e) = conn.reader().read_exact(&mut plain[at..]) {
1685 plain.truncate(at);
1686 result = Err(e);
1687 break;
1688 }
1689 }
1690 if state.peer_has_closed() {
1691 self.close_notify.set(true);
1692 self.eof.set(true);
1693 break;
1694 }
1695 }
1696 Err(e) => {
1697 result = Err(tls_error(e));
1698 break;
1699 }
1700 }
1701 }
1702 result
1703 };
1704 drop(chunk);
1705 if self.broken.get() || (result.is_ok() && self.hold_output()) {
1709 return result;
1710 }
1711 let flushed = self.flush_for_recv().await;
1712 result.and(flushed)
1713 }
1714
1715 async fn flush_for_recv(&self) -> io::Result<()> {
1721 if self.established.get() {
1722 self.flush_now()
1723 } else {
1724 self.flush_tls().await
1725 }
1726 }
1727
1728 pub async fn recv(&self) -> io::Result<Received> {
1747 if self.is_ktls() {
1748 return self.kernel_recv().await.map(Received);
1749 }
1750 self.user_recv().await.map(Received)
1751 }
1752
1753 async fn user_recv(&self) -> io::Result<Vec<u8>> {
1754 loop {
1755 {
1756 let mut plain = self.plain.borrow_mut();
1757 if !plain.is_empty() {
1758 return Ok(mem::take(&mut *plain));
1759 }
1760 }
1761 if let Some(e) = self.failed.take() {
1762 return Err(e);
1763 }
1764 if self.eof.get() {
1765 return Ok(Vec::new());
1766 }
1767 if let Err(e) = self.pump().await {
1768 if self.plain.borrow().is_empty() {
1770 return Err(e);
1771 }
1772 self.failed.set(Some(e));
1773 }
1774 }
1775 }
1776
1777 pub async fn write_all<B>(&self, buf: B) -> (io::Result<()>, B)
1798 where
1799 B: giong::IoBuf + AsRef<[u8]>,
1800 {
1801 if self.is_ktls() {
1802 return self.kernel_write_all(buf).await;
1803 }
1804 let res = self.write_in_process(&[buf.as_ref()]).await;
1805 (res, buf)
1806 }
1807
1808 pub async fn write_all_vectored<B>(&self, bufs: Vec<B>) -> (io::Result<()>, Vec<B>)
1820 where
1821 B: giong::IoBuf + AsRef<[u8]>,
1822 {
1823 if self.is_ktls() {
1824 return self.kernel_write_all_vectored(bufs).await;
1825 }
1826 let pieces: Vec<&[u8]> = bufs.iter().map(AsRef::as_ref).collect();
1827 let res = self.write_in_process(&pieces).await;
1828 drop(pieces);
1829 (res, bufs)
1830 }
1831
1832 pub async fn send_file(&self, file: &giong::fs::File, offset: u64, len: u64) -> io::Result<()> {
1849 if offset
1850 .checked_add(len)
1851 .map_or(true, |end| end > i64::MAX as u64)
1852 {
1853 return Err(file_too_short(offset, len, offset));
1854 }
1855 if self.is_ktls() {
1856 return self.kernel_send_file(file, offset, len).await;
1857 }
1858 let sending = self.lock_send().await;
1859 if let Some(e) = self.cannot_send() {
1860 sending.done();
1861 return Err(e);
1862 }
1863 let mut wire = self.take_wire();
1864 let res = self
1865 .send_file_in_process(&mut wire, file, offset, len)
1866 .await;
1867 self.keep_wire(wire);
1868 sending.done();
1869 res
1870 }
1871
1872 async fn send_file_in_process(
1875 &self,
1876 wire: &mut Vec<u8>,
1877 file: &giong::fs::File,
1878 offset: u64,
1879 len: u64,
1880 ) -> io::Result<()> {
1881 const PIECE: u64 = 256 * 1024;
1882 let mut buf = Vec::with_capacity(len.min(PIECE) as usize);
1883 let (mut at, mut left) = (offset, len);
1884 while left > 0 {
1885 let (res, b) = file.read_at(buf, at).await;
1886 buf = b;
1887 let n = match res {
1888 Ok(0) => return Err(file_too_short(offset, len, at)),
1889 Ok(n) => (n as u64).min(left) as usize,
1890 Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
1891 Err(e) => return Err(e),
1892 };
1893 self.send_plain(wire, &buf[..n], true).await?;
1894 at += n as u64;
1895 left -= n as u64;
1896 }
1897 Ok(())
1898 }
1899
1900 async fn send_closing(&self, wire: &mut Vec<u8>) -> io::Result<()> {
1907 {
1908 let mut conn = self.conn();
1909 while conn.wants_write() {
1910 conn.write_tls(wire)?;
1911 }
1912 }
1913 let n = unsafe {
1915 libc::send(
1916 std::os::fd::AsRawFd::as_raw_fd(&self.tcp),
1917 wire.as_ptr().cast(),
1918 wire.len(),
1919 libc::MSG_MORE | libc::MSG_DONTWAIT | libc::MSG_NOSIGNAL,
1920 )
1921 };
1922 if n >= 0 {
1923 wire.drain(..n as usize);
1924 } else {
1925 let e = io::Error::last_os_error();
1926 if !matches!(
1927 e.kind(),
1928 io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted
1929 ) {
1930 self.broken.set(true);
1931 wire.clear();
1932 return Err(e);
1933 }
1934 }
1935 if !wire.is_empty() {
1936 self.send_wire(wire).await?;
1937 }
1938 self.send_queued(wire).await
1939 }
1940
1941 pub async fn shutdown(&self) -> io::Result<()> {
1959 if self.is_ktls() {
1960 return self.kernel_shutdown().await;
1961 }
1962 let sending = self.lock_send().await;
1963 if self.cannot_send().is_none() {
1964 self.conn().send_close_notify();
1965 self.closed.set(Some(Code::TlsBroken));
1966 let mut wire = self.take_wire();
1967 let res = self.send_closing(&mut wire).await;
1968 self.keep_wire(wire);
1969 if let Err(e) = res {
1970 sending.done();
1972 let _ = self.tcp.shutdown(Shutdown::Write);
1973 return if self.peer_gone(&e) { Ok(()) } else { Err(e) };
1974 }
1975 }
1976 sending.done();
1977 self.tcp.shutdown(Shutdown::Write)
1978 }
1979
1980 fn peer_gone(&self, e: &io::Error) -> bool {
1983 matches!(
1984 e.kind(),
1985 io::ErrorKind::BrokenPipe | io::ErrorKind::ConnectionReset
1986 )
1987 }
1988
1989 pub fn received_close_notify(&self) -> bool {
1995 self.close_notify.get()
1996 }
1997
1998 pub fn alpn_protocol(&self) -> Option<Vec<u8>> {
2000 match &*self.engine.borrow() {
2001 Engine::User(c) => c.alpn_protocol().map(<[u8]>::to_vec),
2002 Engine::Kernel(k) => k.negotiated.alpn.clone(),
2003 }
2004 }
2005
2006 pub fn peer_certificates(&self) -> Option<Vec<CertificateDer<'static>>> {
2011 match &*self.engine.borrow() {
2012 Engine::User(c) => c.peer_certificates().map(<[_]>::to_vec),
2013 Engine::Kernel(k) => k.negotiated.peer_certificates.clone(),
2014 }
2015 }
2016
2017 pub fn resumed(&self) -> bool {
2020 match &*self.engine.borrow() {
2021 Engine::User(c) => c.handshake_kind() == Some(rustls::HandshakeKind::Resumed),
2022 Engine::Kernel(k) => k.negotiated.resumed,
2023 }
2024 }
2025
2026 pub fn tcp(&self) -> &TcpStream {
2033 &self.tcp
2034 }
2035}
2036
2037impl std::fmt::Debug for TlsStream {
2038 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2039 f.debug_struct("TlsStream")
2040 .field("tcp", &self.tcp)
2041 .field("ktls", &self.is_ktls())
2042 .finish_non_exhaustive()
2043 }
2044}
2045
2046#[cfg(test)]
2047mod tests {
2048 use super::*;
2049 use std::future::Future;
2050
2051 #[test]
2052 fn a_connector_without_trusted_authorities_is_refused() {
2053 let err = TlsConnector::from_roots(RootCertStore::empty()).unwrap_err();
2055 assert_eq!(err.kind(), io::ErrorKind::NotFound, "{err}");
2056 assert_eq!(
2057 giong::error::code(&err),
2058 Some(Code::NoTrustedRoots),
2059 "{err}"
2060 );
2061 }
2062
2063 fn authority(name: &str) -> (rcgen::Certificate, rcgen::KeyPair) {
2064 let key = rcgen::KeyPair::generate().unwrap();
2065 let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
2066 params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
2067 params
2068 .distinguished_name
2069 .push(rcgen::DnType::CommonName, name);
2070 (params.self_signed(&key).unwrap(), key)
2071 }
2072
2073 fn signed_by(
2074 ca: &rcgen::Certificate,
2075 ca_key: &rcgen::KeyPair,
2076 names: &[&str],
2077 expired: bool,
2078 ) -> CertificateDer<'static> {
2079 let key = rcgen::KeyPair::generate().unwrap();
2080 let names: Vec<String> = names.iter().map(|n| n.to_string()).collect();
2081 let mut params = rcgen::CertificateParams::new(names).unwrap();
2082 params.distinguished_name.push(
2084 rcgen::DnType::CommonName,
2085 "MySQL_Server_8.0.46_Auto_Generated_Server_Certificate",
2086 );
2087 if expired {
2088 params.not_before = rcgen::date_time_ymd(2020, 1, 1);
2089 params.not_after = rcgen::date_time_ymd(2021, 1, 1);
2090 }
2091 let cert = params.signed_by(&key, ca, ca_key).unwrap();
2092 CertificateDer::from(cert.der().to_vec())
2093 }
2094
2095 #[test]
2097 fn any_name_still_checks_the_chain() {
2098 use rustls::client::danger::ServerCertVerifier;
2099 use rustls::pki_types::UnixTime;
2100 use rustls::CertificateError;
2101
2102 let (ca, ca_key) = authority("ours");
2103 let mut roots = RootCertStore::empty();
2104 roots.add(CertificateDer::from(ca.der().to_vec())).unwrap();
2105 let webpki = rustls::client::WebPkiServerVerifier::builder_with_provider(
2106 Arc::new(roots),
2107 provider(),
2108 )
2109 .build()
2110 .unwrap();
2111 let verifier = AnyName(webpki);
2112 let name = ServerName::try_from("db.internal").unwrap();
2113 let check = |cert: &CertificateDer<'_>| {
2114 verifier.verify_server_cert(cert, &[], &name, &[], UnixTime::now())
2115 };
2116 for names in [&[][..], &["localhost"], &["db.internal"]] {
2118 check(&signed_by(&ca, &ca_key, names, false)).unwrap();
2119 }
2120 let e = check(&signed_by(&ca, &ca_key, &[], true)).unwrap_err();
2122 assert!(
2123 matches!(
2124 e,
2125 rustls::Error::InvalidCertificate(
2126 CertificateError::Expired | CertificateError::ExpiredContext { .. }
2127 )
2128 ),
2129 "{e:?}"
2130 );
2131 let (other, other_key) = authority("theirs");
2134 for cert in [
2135 signed_by(&other, &other_key, &["db.internal"], false),
2136 CertificateDer::from(other.der().to_vec()),
2137 ] {
2138 let e = check(&cert).unwrap_err();
2139 assert!(matches!(e, rustls::Error::InvalidCertificate(_)), "{e:?}");
2140 }
2141 assert!(check(&CertificateDer::from(ca.der().to_vec())).is_err());
2143 assert!(TlsConnector::with_root_pem_any_name(b"").is_err());
2145 assert!(TlsConnector::with_root_pem_any_name(
2146 b"-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n"
2147 )
2148 .is_err());
2149 assert!(TlsConnector::with_root_pem_any_name(ca.pem().as_bytes()).is_ok());
2150 }
2151
2152 fn client_hello(suites: &[u16], id_len: u8, keep: usize) -> Vec<u8> {
2155 let mut hello = vec![22, 3, 1, 0, 0, 1, 0, 0, 0, 3, 3];
2156 hello.extend_from_slice(&[7; 32]);
2157 hello.push(id_len);
2158 hello.extend(std::iter::repeat(9).take(id_len.into()));
2159 hello.extend_from_slice(&((suites.len() * 2) as u16).to_be_bytes());
2160 for suite in suites {
2161 hello.extend_from_slice(&suite.to_be_bytes());
2162 }
2163 hello.extend_from_slice(&[1, 0]); hello.truncate(keep);
2165 hello
2166 }
2167
2168 #[test]
2169 fn chacha20_first_clients_are_told_apart() {
2170 let all = usize::MAX;
2171 assert!(!prefers_chacha(&client_hello(
2173 &[0x1302, 0x1303, 0x1301],
2174 32,
2175 all
2176 )));
2177 assert!(!prefers_chacha(&client_hello(
2179 &[0x1301, 0x1302, 0x1303],
2180 0,
2181 all
2182 )));
2183 assert!(prefers_chacha(&client_hello(
2185 &[0x0a0a, 0x1303, 0x1301],
2186 32,
2187 all
2188 )));
2189 assert!(prefers_chacha(&client_hello(&[0xcca9, 0xc02b], 0, all)));
2191 assert!(!prefers_chacha(&client_hello(&[0xc02c, 0xcca9], 0, all)));
2192 assert!(!prefers_chacha(&client_hello(&[0x009c], 0, all)));
2194 let cut = client_hello(&[0x1303, 0x1301], 32, all).len() - 3;
2195 assert!(!prefers_chacha(&client_hello(&[0x1303, 0x1301], 32, cut)));
2196 assert!(!prefers_chacha(&client_hello(&[0x1303], 32, 40)));
2197 assert!(!prefers_chacha(&[]));
2198 let mut alert = client_hello(&[0x1303], 0, all);
2199 alert[0] = 21;
2200 assert!(!prefers_chacha(&alert));
2201 }
2202
2203 fn ca_pem(name: &str) -> String {
2204 let key = rcgen::KeyPair::generate().unwrap();
2205 let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
2206 params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
2207 params
2208 .distinguished_name
2209 .push(rcgen::DnType::CommonName, name);
2210 params.self_signed(&key).unwrap().pem()
2211 }
2212
2213 fn scratch(name: &str) -> PathBuf {
2215 let dir = std::env::temp_dir().join(format!("giong-tls-{}-{name}", std::process::id()));
2216 let _ = std::fs::remove_dir_all(&dir);
2217 std::fs::create_dir_all(&dir).unwrap();
2218 dir
2219 }
2220
2221 fn os(path: &Path) -> &OsStr {
2222 path.as_os_str()
2223 }
2224
2225 #[test]
2226 fn server_names_are_dns_names_or_ip_addresses() {
2227 let dns = |n: &str| matches!(parse_server_name(n), Ok(ServerName::DnsName(_)));
2228 let ip = |n: &str| matches!(parse_server_name(n), Ok(ServerName::IpAddress(_)));
2229 assert!(dns("example.com"));
2230 assert!(dns("db.prod.svc.cluster.local"));
2231 assert!(ip("10.0.0.1"));
2232 assert!(ip("::1"));
2233 assert!(ip("[::1]"));
2234 for bad in ["", "not a name", "[nope]", "[10.0.0.1]", "a..b"] {
2235 let err = parse_server_name(bad).unwrap_err();
2236 assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{bad:?}");
2237 }
2238 }
2239
2240 #[test]
2241 fn the_first_bundle_that_exists_is_read() {
2242 let dir = scratch("bundle");
2243 let bundle = dir.join("bundle.pem");
2244 let two = format!("{}{}", ca_pem("one"), ca_pem("two"));
2245 std::fs::write(&bundle, two).unwrap();
2246 let missing = dir.join("missing.pem");
2247 let bundles = [missing.to_str().unwrap(), bundle.to_str().unwrap()];
2248 let roots = load_roots(None, None, &bundles, "/nonexistent").unwrap();
2249 assert_eq!(roots.len(), 2);
2250 std::fs::remove_dir_all(dir).unwrap();
2251 }
2252
2253 #[test]
2254 fn ssl_cert_file_and_dir_replace_the_system_locations() {
2255 let dir = scratch("env");
2256 let file = dir.join("file.pem");
2257 std::fs::write(&file, ca_pem("from file")).unwrap();
2258 let certs = dir.join("certs");
2259 std::fs::create_dir(&certs).unwrap();
2260 std::fs::write(certs.join("a.pem"), ca_pem("a")).unwrap();
2261 std::fs::write(certs.join("b.pem"), ca_pem("b")).unwrap();
2262 std::fs::write(certs.join("README"), "not a certificate").unwrap();
2263 std::os::unix::fs::symlink(certs.join("a.pem"), certs.join("1a2b3c4d.0")).unwrap();
2265 let system = dir.join("system.pem");
2266 std::fs::write(&system, ca_pem("system")).unwrap();
2267 let bundles = [system.to_str().unwrap()];
2268
2269 let roots = load_roots(Some(os(&file)), None, &bundles, "/nonexistent").unwrap();
2270 assert_eq!(roots.len(), 1, "SSL_CERT_FILE only");
2271 let roots = load_roots(None, Some(os(&certs)), &bundles, "/nonexistent").unwrap();
2272 assert_eq!(roots.len(), 2, "SSL_CERT_DIR only, each file once");
2273 let both = std::env::join_paths([dir.join("nowhere"), certs.clone()]).unwrap();
2274 let roots = load_roots(Some(os(&file)), Some(&both), &bundles, "/nonexistent").unwrap();
2275 assert_eq!(roots.len(), 3, "both, with a missing directory in the list");
2276
2277 let err = load_roots(Some(os(&dir.join("gone.pem"))), None, &bundles, "").unwrap_err();
2278 assert_eq!(err.kind(), io::ErrorKind::NotFound);
2279 assert!(err.to_string().contains("SSL_CERT_FILE"), "{err}");
2280 std::fs::remove_dir_all(dir).unwrap();
2281 }
2282
2283 #[test]
2284 fn without_a_bundle_the_directory_is_read_and_nothing_is_an_error() {
2285 let dir = scratch("dir");
2286 std::fs::write(dir.join("only.crt"), ca_pem("only")).unwrap();
2287 let roots = load_roots(
2288 None,
2289 None,
2290 &["/nonexistent/bundle.crt"],
2291 dir.to_str().unwrap(),
2292 );
2293 assert_eq!(roots.unwrap().len(), 1);
2294
2295 let empty = scratch("empty");
2296 let err = load_roots(None, None, &[], empty.to_str().unwrap()).unwrap_err();
2297 assert_eq!(err.kind(), io::ErrorKind::NotFound);
2298 assert!(err.to_string().contains("webpki-roots"), "{err}");
2299 std::fs::remove_dir_all(dir).unwrap();
2300 std::fs::remove_dir_all(empty).unwrap();
2301 }
2302
2303 #[test]
2304 fn records_are_scanned_for_application_data() {
2305 let record = |typ: u8, len: u16| {
2307 let mut r = vec![typ, 3, 3];
2308 r.extend_from_slice(&len.to_be_bytes());
2309 r.resize(5 + len as usize, 0xAA);
2310 r
2311 };
2312 assert!(!has_application_data(&[]));
2313 assert!(!has_application_data(&record(21, 26)));
2314 assert!(has_application_data(&record(23, 0)));
2315 let mut alert_then_data = record(21, 26);
2316 alert_then_data.extend(record(23, 300));
2317 assert!(has_application_data(&alert_then_data));
2318 let mut alert = record(21, 26);
2320 alert[5] = 23;
2321 assert!(!has_application_data(&alert));
2322 }
2323
2324 #[test]
2325 fn secrets_are_extractable_only_when_the_kernel_will_take_them() {
2326 let key = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
2327 let (cert, key) = (key.cert.pem(), key.key_pair.serialize_pem());
2328 for mode in [Ktls::Off, Ktls::Auto] {
2329 let acceptor = TlsAcceptor::with_certificates(
2330 &Certificates::from_pem(cert.as_bytes(), key.as_bytes()).unwrap(),
2331 )
2332 .unwrap()
2333 .ktls(mode)
2334 .unwrap();
2335 let tries = acceptor.ktls.tries();
2336 assert_eq!(acceptor.config.enable_secret_extraction, tries, "{mode:?}");
2337 let connector = TlsConnector::with_root_pem(cert.as_bytes())
2338 .unwrap()
2339 .ktls(mode)
2340 .unwrap();
2341 let tries = connector.ktls.tries();
2342 assert_eq!(connector.config.enable_secret_extraction, tries, "{mode:?}");
2343 }
2344 }
2345
2346 #[test]
2347 fn this_machines_roots_load() {
2348 TlsConnector::with_system_roots().unwrap();
2350 }
2351
2352 #[cfg(feature = "webpki-roots")]
2353 #[test]
2354 fn mozillas_roots_are_compiled_in() {
2355 TlsConnector::with_webpki_roots();
2356 }
2357
2358 #[test]
2359 fn records_a_receive_could_not_send_whole_go_out_first_and_in_order() {
2360 let key = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
2366 let cert = key.cert.pem();
2367 let acceptor = TlsAcceptor::with_certificates(
2368 &Certificates::from_pem(cert.as_bytes(), key.key_pair.serialize_pem().as_bytes())
2369 .unwrap(),
2370 )
2371 .unwrap();
2372 let connector = TlsConnector::with_root_pem(cert.as_bytes()).unwrap();
2373 giong::block_on(async move {
2374 let listener = giong::net::TcpListener::bind("127.0.0.1:0").unwrap();
2375 let addr = listener.local_addr().unwrap();
2376 let server = giong::spawn(async move {
2377 let tcp = listener.accept().await.unwrap();
2378 let tls = acceptor.accept(tcp).await.unwrap();
2379 assert!(tls.conn().wants_write(), "tickets wait for the first send");
2380 FLUSH_ROOM.set(1);
2381 let mut left = None;
2382 for _ in 0..5 {
2383 let mut recv = std::pin::pin!(tls.recv());
2384 let ready = poll_fn(|cx| Poll::Ready(recv.as_mut().poll(cx).is_ready())).await;
2385 assert!(!ready);
2386 let unsent = tls.unsent.borrow().len();
2387 assert!(
2388 left.map_or(unsent > 0, |l| unsent + 1 == l),
2389 "{left:?} {unsent}"
2390 );
2391 left = Some(unsent);
2392 }
2393 FLUSH_ROOM.set(usize::MAX);
2394 tls.write_all(&b"after the tickets"[..]).await.0.unwrap();
2395 assert_eq!(tls.unsent.borrow().capacity(), 0);
2398 tls.shutdown().await.unwrap();
2399 });
2400 let tcp = TcpStream::connect(addr).await.unwrap();
2401 let tls = connector.connect("localhost", tcp).await.unwrap();
2402 let mut got = Vec::new();
2403 loop {
2404 let data = tls.recv().await.unwrap();
2405 if data.is_empty() {
2406 break;
2407 }
2408 got.extend_from_slice(&data);
2409 }
2410 assert_eq!(got, b"after the tickets");
2411 assert!(tls.received_close_notify());
2412 server.await.unwrap();
2413 });
2414 }
2415
2416 #[test]
2417 fn a_receive_that_sent_what_was_owed_keeps_no_buffer_for_it() {
2418 let key = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
2422 let cert = key.cert.pem();
2423 let acceptor = TlsAcceptor::with_certificates(
2424 &Certificates::from_pem(cert.as_bytes(), key.key_pair.serialize_pem().as_bytes())
2425 .unwrap(),
2426 )
2427 .unwrap();
2428 let connector = TlsConnector::with_root_pem(cert.as_bytes()).unwrap();
2429 giong::block_on(async move {
2430 let listener = giong::net::TcpListener::bind("127.0.0.1:0").unwrap();
2431 let addr = listener.local_addr().unwrap();
2432 let server = giong::spawn(async move {
2433 let tcp = listener.accept().await.unwrap();
2434 let tls = acceptor.accept(tcp).await.unwrap();
2435 assert!(tls.conn().wants_write(), "tickets wait for the first send");
2436 let mut recv = std::pin::pin!(tls.recv());
2439 let ready = poll_fn(|cx| Poll::Ready(recv.as_mut().poll(cx).is_ready())).await;
2440 assert!(!ready);
2441 assert!(!tls.conn().wants_write());
2442 assert_eq!(tls.unsent.borrow().capacity(), 0);
2443 tls.shutdown().await.unwrap();
2444 });
2445 let tcp = TcpStream::connect(addr).await.unwrap();
2446 let tls = connector.connect("localhost", tcp).await.unwrap();
2447 assert!(tls.recv().await.unwrap().is_empty());
2448 assert!(tls.received_close_notify());
2449 server.await.unwrap();
2450 });
2451 }
2452
2453 #[test]
2454 fn the_key_exchange_offers_post_quantum_first_with_the_feature() {
2455 let first = provider().kx_groups[0].name();
2456 let pq = rustls::NamedGroup::X25519MLKEM768;
2457 assert_eq!(first == pq, cfg!(feature = "post-quantum"), "{first:?}");
2458 assert_eq!(provider_aes128_first().kx_groups[0].name(), first);
2459 }
2460}