1#![warn(missing_docs)]
80
81mod certs;
82#[cfg(target_os = "macos")]
83mod keychain;
84mod ktls;
85mod received;
86mod sys;
87#[cfg(windows)]
88mod winstore;
89
90pub use certs::Certificates;
91pub use ktls::{ktls_stats, ktls_support, Ktls, KtlsStats, KtlsSupport};
92pub use received::Received;
93pub use rustls_pki_types::CertificateDer;
96
97#[cfg(fuzzing)]
100#[doc(hidden)]
101pub mod fuzzing {
102 pub use crate::ktls::{check_handshake_messages, check_record_framing};
103}
104
105use std::cell::{Cell, RefCell, RefMut};
106use std::collections::HashSet;
107use std::ffi::OsStr;
108use std::future::poll_fn;
109use std::io::{self, Read, Write};
110use std::mem;
111use std::net::Shutdown;
112use std::path::{Path, PathBuf};
113use std::sync::Arc;
114use std::task::{Poll, Waker};
115use std::time::Duration;
116
117use giong::error::Code;
118use giong::net::TcpStream;
119use giong::time::timeout;
120use rustls::client::ResolvesClientCert;
121use rustls::pki_types::pem::PemObject;
122use rustls::pki_types::{PrivateKeyDer, ServerName};
123use rustls::sign::CertifiedKey;
124use rustls::{
125 ClientConfig, ClientConnection, Connection, RootCertStore, ServerConfig, ServerConnection,
126 SignatureScheme,
127};
128
129#[cfg(feature = "unstable-rustls")]
135pub use rustls;
136
137fn coded(
138 code: Code,
139 message: impl Into<std::borrow::Cow<'static, str>>,
140 fix: &'static str,
141) -> io::Error {
142 giong::error::Error::new(code, message, fix).into()
143}
144
145fn file_too_short(offset: u64, len: u64, at: u64) -> io::Error {
148 let end = offset.saturating_add(len);
149 coded(
150 Code::FileTooShort,
151 format!(
152 "the file ended at byte {at}, {} bytes short of the {len} send_file was asked to send",
153 end - at
154 ),
155 "take the length from the open file (File::len), and replace a file that is being \
156 served by renaming a new one over it, not by rewriting it; the peer has fewer bytes \
157 than announced, so close the connection.",
158 )
159}
160
161pub(crate) fn bad_certificate_data(e: impl std::fmt::Display) -> io::Error {
163 coded(
164 Code::BadCertificateData,
165 e.to_string(),
166 "check that the file or data is PEM (\"-----BEGIN CERTIFICATE-----\") and holds \
167 at least one certificate.",
168 )
169}
170
171pub(crate) fn bad_key(e: impl std::fmt::Display) -> io::Error {
173 coded(
174 Code::BadCertificateData,
175 format!("cannot read the private key: {e}"),
176 "check that it is a PEM private key (\"-----BEGIN PRIVATE KEY-----\", or the RSA or \
177 EC forms).",
178 )
179}
180
181pub(crate) fn mismatched_key(e: rustls::Error) -> io::Error {
183 coded(
184 Code::BadCertificateData,
185 format!("the certificate and the private key cannot be used together: {e}"),
186 "check that the key belongs to the first certificate of the chain, and that its type \
187 (RSA, ECDSA, Ed25519) is supported.",
188 )
189}
190
191fn tls_error(e: rustls::Error) -> io::Error {
193 match e {
194 rustls::Error::InvalidCertificate(_) if e.to_string().contains("CaUsedAsEndEntity") => {
197 coded(
198 Code::TlsCertificate,
199 "the peer's certificate was rejected: it is marked as a certificate authority \
200 (basicConstraints CA:TRUE), and an authority's certificate cannot be the \
201 peer's own (CaUsedAsEndEntity)",
202 "issue the peer's certificate with CA:FALSE: a self-signed one made with \
203 `openssl req -x509` needs -addext \"basicConstraints=critical,CA:FALSE\"; or \
204 have the authority sign a separate certificate for the peer.",
205 )
206 }
207 rustls::Error::InvalidCertificate(_) => coded(
208 Code::TlsCertificate,
209 format!("the peer's certificate was rejected: {e}"),
210 "check the name you connect to, the certificate's expiry and its chain; a \
211 private authority has to be trusted with TlsConnector::with_root_pem.",
212 ),
213 e => coded(
214 Code::TlsProtocol,
215 format!("TLS error: {e}"),
216 "check that the other side speaks TLS on this port, and that both sides share a \
217 protocol version and cipher suite.",
218 ),
219 }
220}
221
222const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
224
225fn handshake_timed_out(limit: Duration) -> io::Error {
226 coded(
227 Code::TlsHandshakeTimeout,
228 format!("the TLS handshake did not finish within {limit:?}"),
229 "check that the other side speaks TLS on this port and is not overloaded, or raise \
230 handshake_timeout.",
231 )
232}
233
234fn handshake_eof() -> io::Error {
235 coded(
236 Code::TlsHandshakeEof,
237 "the peer closed the connection during the TLS handshake",
238 "check that the other side speaks TLS on this port, and whether it wants a client \
239 certificate or another server name.",
240 )
241}
242
243const WIRE_KEPT: usize = 16 * 1024;
248
249const SEND_AT: usize = 64 * 1024;
252
253#[cfg(test)]
254thread_local! {
255 static FLUSH_ROOM: Cell<usize> = const { Cell::new(usize::MAX) };
258}
259
260fn flush_room() -> usize {
263 #[cfg(test)]
264 return FLUSH_ROOM.with(Cell::get);
265 #[cfg(not(test))]
266 usize::MAX
267}
268
269fn has_application_data(records: &[u8]) -> bool {
273 let mut at = 0;
274 while let Some(header) = records.get(at..at + 5) {
275 if header[0] == 23 {
276 return true;
277 }
278 at += 5 + usize::from(u16::from_be_bytes([header[3], header[4]]));
279 }
280 false
281}
282
283fn sending_closed(code: Code) -> io::Error {
286 match code {
287 Code::TlsKeysExhausted => coded(
288 Code::TlsKeysExhausted,
289 "this connection has sent as many TLS records as its cipher allows under one key, \
290 and cannot change keys (TLS 1.2, or TLS 1.3 on a kernel older than 6.14); \
291 close_notify was sent",
292 "open a new connection. TLS 1.3 changes keys instead (in the process, and with \
293 kernel TLS on Linux 6.14 or newer).",
294 ),
295 _ => coded(
296 Code::TlsBroken,
297 "this TLS stream has been shut down or ended with an alert; nothing more can be sent",
298 "open a new connection.",
299 ),
300 }
301}
302
303fn broken() -> io::Error {
304 coded(
305 Code::TlsBroken,
306 "a TLS write failed or was cancelled; nothing more can be sent",
307 "open a new connection. A write cancelled half-way (a dropped future, a timeout) \
308 leaves a partial record or message behind, so the stream cannot go on.",
309 )
310}
311
312#[inline]
317fn no_buffers(e: &io::Error) -> bool {
318 cfg!(target_os = "macos") && e.raw_os_error() == Some(libc::ENOBUFS)
319}
320
321pub(crate) fn pem_certs(pem: &[u8]) -> io::Result<Vec<CertificateDer<'static>>> {
323 let certs = CertificateDer::pem_slice_iter(pem)
324 .collect::<Result<Vec<_>, _>>()
325 .map_err(bad_certificate_data)?;
326 if certs.is_empty() {
327 return Err(bad_certificate_data("no certificate found in the PEM data"));
328 }
329 Ok(certs)
330}
331
332pub(crate) fn provider() -> Arc<rustls::crypto::CryptoProvider> {
336 Arc::new(base_provider())
337}
338
339#[cfg(not(feature = "post-quantum"))]
340fn base_provider() -> rustls::crypto::CryptoProvider {
341 rustls::crypto::ring::default_provider()
342}
343
344#[cfg(feature = "post-quantum")]
345fn base_provider() -> rustls::crypto::CryptoProvider {
346 rustls::crypto::aws_lc_rs::default_provider()
347}
348
349fn provider_aes128_first() -> Arc<rustls::crypto::CryptoProvider> {
359 use rustls::CipherSuite as S;
360 let mut provider = base_provider();
361 provider.cipher_suites.sort_by_key(|suite| {
364 let rank = match suite.suite() {
365 S::TLS13_AES_128_GCM_SHA256
366 | S::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
367 | S::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 => 0,
368 S::TLS13_CHACHA20_POLY1305_SHA256
369 | S::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
370 | S::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 => 1,
371 _ => 2,
372 };
373 (
374 suite.version().version != rustls::ProtocolVersion::TLSv1_3,
375 rank,
376 )
377 });
378 Arc::new(provider)
379}
380
381fn prefers_chacha(hello: &[u8]) -> bool {
389 const SESSION_ID: usize = 5 + 4 + 2 + 32;
391 if hello.first() != Some(&22) || hello.get(5) != Some(&1) {
392 return false;
393 }
394 let Some(&id_len) = hello.get(SESSION_ID) else {
395 return false;
396 };
397 let at = SESSION_ID + 1 + usize::from(id_len);
398 let Some(len) = hello.get(at..at + 2) else {
399 return false;
400 };
401 let len = usize::from(u16::from_be_bytes([len[0], len[1]]));
402 let Some(suites) = hello.get(at + 2..at + 2 + len) else {
403 return false;
404 };
405 for suite in suites.chunks_exact(2) {
406 match [suite[0], suite[1]] {
407 [0x13, 0x01]
410 | [0x13, 0x02]
411 | [0xc0, 0x2b]
412 | [0xc0, 0x2f]
413 | [0xc0, 0x2c]
414 | [0xc0, 0x30] => return false,
415 [0x13, 0x03] | [0xcc, 0xa9] | [0xcc, 0xa8] => return true,
417 _ => {}
418 }
419 }
420 false
421}
422
423fn server_configs(
428 certificates: &Certificates,
429 verifier: Arc<dyn rustls::server::danger::ClientCertVerifier>,
430) -> io::Result<(ServerConfig, ServerConfig)> {
431 let mut config = ServerConfig::builder_with_provider(provider_aes128_first())
432 .with_safe_default_protocol_versions()
433 .map_err(tls_error)?
434 .with_client_cert_verifier(verifier)
435 .with_cert_resolver(certificates.resolver());
436 let chacha = config.clone();
437 config.ignore_client_order = true;
438 Ok((config, chacha))
439}
440
441#[derive(Clone)]
445pub struct TlsAcceptor {
446 config: Arc<ServerConfig>,
447 chacha: Option<Arc<ServerConfig>>,
452 handshake_timeout: Duration,
453 ktls: ktls::Plan,
454 certificates: Option<Certificates>,
458}
459
460impl TlsAcceptor {
461 #[cfg(feature = "unstable-rustls")]
469 pub fn from_rustls(config: Arc<ServerConfig>) -> Self {
470 Self::with_config(config)
471 }
472
473 fn with_config(config: Arc<ServerConfig>) -> Self {
474 Self {
475 config,
476 chacha: None,
477 handshake_timeout: HANDSHAKE_TIMEOUT,
478 ktls: ktls::Plan::Off,
479 certificates: None,
480 }
481 }
482
483 pub fn with_certificates(certificates: &Certificates) -> io::Result<Self> {
508 let verifier = rustls::server::WebPkiClientVerifier::no_client_auth();
509 let (config, chacha) = server_configs(certificates, verifier)?;
510 Ok(Self {
511 chacha: Some(Arc::new(chacha)),
512 certificates: Some(certificates.clone()),
513 ..Self::with_config(Arc::new(config))
514 })
515 }
516
517 pub fn require_client_cert(self, ca_pem: &[u8]) -> io::Result<Self> {
527 self.client_auth(ca_pem, true)
528 }
529
530 pub fn request_client_cert(self, ca_pem: &[u8]) -> io::Result<Self> {
537 self.client_auth(ca_pem, false)
538 }
539
540 fn client_auth(mut self, ca_pem: &[u8], required: bool) -> io::Result<Self> {
541 let Some(certificates) = &self.certificates else {
542 return Err(coded(
543 Code::TlsConfig,
544 "client certificates cannot be set on an acceptor made with from_rustls",
545 "set client authentication in the rustls configuration given to from_rustls \
546 (ServerConfig::builder().with_client_cert_verifier), or make the acceptor \
547 with with_certificates.",
548 ));
549 };
550 let mut roots = RootCertStore::empty();
551 for cert in pem_certs(ca_pem)? {
552 roots.add(cert).map_err(bad_certificate_data)?;
553 }
554 let builder = rustls::server::WebPkiClientVerifier::builder_with_provider(
555 Arc::new(roots),
556 self.config.crypto_provider().clone(),
557 );
558 let builder = if required {
559 builder
560 } else {
561 builder.allow_unauthenticated()
562 };
563 let verifier = builder.build().map_err(bad_certificate_data)?;
564 let (mut config, mut chacha) = server_configs(certificates, verifier)?;
565 for new in [&mut config, &mut chacha] {
567 new.alpn_protocols = self.config.alpn_protocols.clone();
568 new.enable_secret_extraction = self.config.enable_secret_extraction;
569 }
570 self.config = Arc::new(config);
571 self.chacha = Some(Arc::new(chacha));
572 Ok(self)
573 }
574
575 fn config_for(&self, hello: &[u8]) -> Arc<ServerConfig> {
578 match &self.chacha {
579 Some(chacha) if prefers_chacha(hello) => chacha.clone(),
580 _ => self.config.clone(),
581 }
582 }
583
584 fn change_config(&mut self, change: impl Fn(&mut ServerConfig)) {
586 change(Arc::make_mut(&mut self.config));
587 if let Some(chacha) = &mut self.chacha {
588 change(Arc::make_mut(chacha));
589 }
590 }
591
592 pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
600 let protocols: Vec<Vec<u8>> = protocols.iter().map(|p| p.to_vec()).collect();
601 self.change_config(|config| config.alpn_protocols = protocols.clone());
602 self
603 }
604
605 pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
608 self.handshake_timeout = timeout;
609 self
610 }
611
612 pub fn ktls(mut self, mode: Ktls) -> io::Result<Self> {
639 let early_data = self.config.max_early_data_size > 0;
640 self.ktls = ktls::Plan::new(mode, self.config.crypto_provider(), early_data)?;
641 let extract = self.ktls.tries();
643 if self.config.enable_secret_extraction != extract {
644 self.change_config(|config| config.enable_secret_extraction = extract);
645 }
646 Ok(self)
647 }
648
649 pub fn ktls_unavailable(&self) -> Option<&str> {
654 self.ktls.unavailable()
655 }
656
657 pub async fn accept(&self, tcp: TcpStream) -> io::Result<TlsStream> {
666 let tcp = match &self.ktls {
667 ktls::Plan::Off => tcp,
668 ktls::Plan::Try { required } => {
669 let start = ktls::Start::Server(self.config.clone(), self.chacha.clone());
670 match ktls::handshake(tcp, start, self.handshake_timeout).await? {
671 ktls::Outcome::Kernel(tls) => return Ok(*tls),
672 ktls::Outcome::Declined(_, e) if *required => return Err(e),
673 ktls::Outcome::Declined(tcp, _) => {
674 self.ktls.stayed();
675 tcp
676 }
677 }
678 }
679 ktls::Plan::Unavailable(_) => {
680 self.ktls.stayed();
681 tcp
682 }
683 };
684 let Some(_) = &self.chacha else {
685 let conn = ServerConnection::new(self.config.clone()).map_err(tls_error)?;
686 return TlsStream::new(tcp, conn.into())
687 .handshake(self.handshake_timeout, Duration::ZERO, None)
688 .await;
689 };
690 let started = std::time::Instant::now();
693 let first = match timeout(self.handshake_timeout, tcp.recv()).await {
694 Ok(first) => first?,
695 Err(_) => return Err(handshake_timed_out(self.handshake_timeout)),
696 };
697 if first.is_empty() {
698 return Err(handshake_eof());
699 }
700 let conn = ServerConnection::new(self.config_for(&first)).map_err(tls_error)?;
701 TlsStream::new(tcp, conn.into())
702 .handshake(self.handshake_timeout, started.elapsed(), Some(first))
703 .await
704 }
705}
706
707impl std::fmt::Debug for TlsAcceptor {
708 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
709 f.debug_struct("TlsAcceptor")
710 .field("handshake_timeout", &self.handshake_timeout)
711 .field("ktls", &self.ktls)
712 .finish_non_exhaustive()
713 }
714}
715
716#[derive(Clone)]
737pub struct TlsConnector {
738 config: Arc<ClientConfig>,
739 handshake_timeout: Duration,
740 ktls: ktls::Plan,
741}
742
743impl TlsConnector {
744 #[cfg(feature = "unstable-rustls")]
752 pub fn from_rustls(config: Arc<ClientConfig>) -> Self {
753 Self::with_config(config)
754 }
755
756 fn with_config(config: Arc<ClientConfig>) -> Self {
757 Self {
758 config,
759 handshake_timeout: HANDSHAKE_TIMEOUT,
760 ktls: ktls::Plan::Off,
761 }
762 }
763
764 fn from_roots(roots: RootCertStore) -> io::Result<Self> {
765 if roots.is_empty() {
766 return Err(coded(
767 Code::NoTrustedRoots,
768 "no trusted certificate authority given",
769 "pass at least one certificate, or use TlsConnector::with_system_roots.",
770 ));
771 }
772 let config = ClientConfig::builder_with_provider(provider())
773 .with_safe_default_protocol_versions()
774 .map_err(tls_error)?
775 .with_root_certificates(roots)
776 .with_no_client_auth();
777 Ok(Self::with_config(Arc::new(config)))
778 }
779
780 pub fn with_root_pem(pem: &[u8]) -> io::Result<Self> {
789 let mut roots = RootCertStore::empty();
790 for cert in pem_certs(pem)? {
791 roots.add(cert).map_err(bad_certificate_data)?;
792 }
793 Self::from_roots(roots)
794 }
795
796 pub fn with_root_pem_any_name(pem: &[u8]) -> io::Result<Self> {
808 let mut roots = RootCertStore::empty();
809 for cert in pem_certs(pem)? {
810 roots.add(cert).map_err(bad_certificate_data)?;
811 }
812 if roots.is_empty() {
813 return Err(coded(
814 Code::NoTrustedRoots,
815 "no trusted certificate authority given",
816 "pass at least one certificate authority in PEM form.",
817 ));
818 }
819 let provider = provider();
820 let webpki = rustls::client::WebPkiServerVerifier::builder_with_provider(
821 Arc::new(roots),
822 provider.clone(),
823 )
824 .build()
825 .map_err(bad_certificate_data)?;
826 let config = ClientConfig::builder_with_provider(provider)
827 .with_safe_default_protocol_versions()
828 .map_err(tls_error)?
829 .dangerous()
830 .with_custom_certificate_verifier(Arc::new(AnyName(webpki)))
831 .with_no_client_auth();
832 Ok(Self::with_config(Arc::new(config)))
833 }
834
835 pub fn with_system_roots() -> io::Result<Self> {
865 let file = std::env::var_os("SSL_CERT_FILE");
866 let dirs = std::env::var_os("SSL_CERT_DIR");
867 #[cfg(any(target_os = "macos", windows))]
868 if file.is_none() && dirs.is_none() {
869 #[cfg(target_os = "macos")]
870 let system = keychain::trusted_roots();
871 #[cfg(windows)]
872 let system = winstore::trusted_roots();
873 let mut roots = RootCertStore::empty();
874 roots.add_parsable_certificates(system);
875 if !roots.is_empty() {
876 return Self::from_roots(roots);
877 }
878 }
879 let roots = load_roots(
880 file.as_deref(),
881 dirs.as_deref(),
882 SYSTEM_CA_BUNDLES,
883 SYSTEM_CA_DIR,
884 )?;
885 Self::from_roots(roots)
886 }
887
888 #[cfg(feature = "webpki-roots")]
895 pub fn with_webpki_roots() -> Self {
896 let roots = RootCertStore {
897 roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
898 };
899 Self::from_roots(roots).expect("the webpki-roots crate provides roots")
900 }
901
902 pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
906 Arc::make_mut(&mut self.config).alpn_protocols =
907 protocols.iter().map(|p| p.to_vec()).collect();
908 self
909 }
910
911 pub fn client_auth(mut self, cert_chain: &[u8], private_key: &[u8]) -> io::Result<Self> {
914 let certs = pem_certs(cert_chain)?;
915 let key = PrivateKeyDer::from_pem_slice(private_key).map_err(bad_key)?;
916 let key = CertifiedKey::from_der(certs, key, self.config.crypto_provider())
917 .map_err(mismatched_key)?;
918 Arc::make_mut(&mut self.config).client_auth_cert_resolver =
919 Arc::new(ClientCert(Arc::new(key)));
920 Ok(self)
921 }
922
923 pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
926 self.handshake_timeout = timeout;
927 self
928 }
929
930 pub fn ktls(mut self, mode: Ktls) -> io::Result<Self> {
944 let early_data = self.config.enable_early_data;
945 self.ktls = ktls::Plan::new(mode, self.config.crypto_provider(), early_data)?;
946 let extract = self.ktls.tries();
947 if self.config.enable_secret_extraction != extract {
948 Arc::make_mut(&mut self.config).enable_secret_extraction = extract;
949 }
950 Ok(self)
951 }
952
953 pub fn ktls_unavailable(&self) -> Option<&str> {
956 self.ktls.unavailable()
957 }
958
959 pub async fn connect(&self, server_name: &str, tcp: TcpStream) -> io::Result<TlsStream> {
971 let name = parse_server_name(server_name)?;
972 let tcp = match &self.ktls {
973 ktls::Plan::Off => tcp,
974 ktls::Plan::Try { required } => {
975 let start = ktls::Start::Client(self.config.clone(), name.clone());
976 match ktls::handshake(tcp, start, self.handshake_timeout).await? {
977 ktls::Outcome::Kernel(tls) => return Ok(*tls),
978 ktls::Outcome::Declined(_, e) if *required => return Err(e),
979 ktls::Outcome::Declined(tcp, _) => {
980 self.ktls.stayed();
981 tcp
982 }
983 }
984 }
985 ktls::Plan::Unavailable(_) => {
986 self.ktls.stayed();
987 tcp
988 }
989 };
990 let conn = ClientConnection::new(self.config.clone(), name).map_err(tls_error)?;
991 TlsStream::new(tcp, conn.into())
992 .handshake(self.handshake_timeout, Duration::ZERO, None)
993 .await
994 }
995}
996
997impl std::fmt::Debug for TlsConnector {
998 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
999 f.debug_struct("TlsConnector")
1000 .field("handshake_timeout", &self.handshake_timeout)
1001 .field("ktls", &self.ktls)
1002 .finish_non_exhaustive()
1003 }
1004}
1005
1006struct AnyName(Arc<rustls::client::WebPkiServerVerifier>);
1010
1011impl std::fmt::Debug for AnyName {
1012 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1013 f.write_str("AnyName")
1014 }
1015}
1016
1017impl rustls::client::danger::ServerCertVerifier for AnyName {
1018 fn verify_server_cert(
1019 &self,
1020 end_entity: &CertificateDer<'_>,
1021 intermediates: &[CertificateDer<'_>],
1022 server_name: &ServerName<'_>,
1023 ocsp_response: &[u8],
1024 now: rustls::pki_types::UnixTime,
1025 ) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
1026 use rustls::CertificateError;
1027 match self
1028 .0
1029 .verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)
1030 {
1031 Err(rustls::Error::InvalidCertificate(
1035 CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. },
1036 )) => Ok(rustls::client::danger::ServerCertVerified::assertion()),
1037 other => other,
1038 }
1039 }
1040
1041 fn verify_tls12_signature(
1042 &self,
1043 message: &[u8],
1044 cert: &CertificateDer<'_>,
1045 dss: &rustls::DigitallySignedStruct,
1046 ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
1047 self.0.verify_tls12_signature(message, cert, dss)
1048 }
1049
1050 fn verify_tls13_signature(
1051 &self,
1052 message: &[u8],
1053 cert: &CertificateDer<'_>,
1054 dss: &rustls::DigitallySignedStruct,
1055 ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
1056 self.0.verify_tls13_signature(message, cert, dss)
1057 }
1058
1059 fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
1060 self.0.supported_verify_schemes()
1061 }
1062}
1063
1064fn parse_server_name(name: &str) -> io::Result<ServerName<'static>> {
1066 let ipv6 = name
1067 .strip_prefix('[')
1068 .and_then(|n| n.strip_suffix(']'))
1069 .and_then(|n| n.parse::<std::net::Ipv6Addr>().ok());
1070 if let Some(ip) = ipv6 {
1071 return Ok(ServerName::IpAddress(std::net::IpAddr::V6(ip).into()));
1072 }
1073 ServerName::try_from(name.to_owned()).map_err(|_| {
1074 coded(
1075 Code::InvalidServerName,
1076 format!("{name:?} is neither a DNS name nor an IP address"),
1077 "pass the host name the certificate is for (\"example.com\"), or an IP address, \
1078 without a port or a scheme.",
1079 )
1080 })
1081}
1082
1083#[derive(Debug)]
1085struct ClientCert(Arc<CertifiedKey>);
1086
1087impl ResolvesClientCert for ClientCert {
1088 fn resolve(&self, _: &[&[u8]], _: &[SignatureScheme]) -> Option<Arc<CertifiedKey>> {
1089 Some(self.0.clone())
1090 }
1091
1092 fn has_certs(&self) -> bool {
1093 true
1094 }
1095}
1096
1097const SYSTEM_CA_BUNDLES: &[&str] = &[
1099 "/etc/ssl/certs/ca-certificates.crt",
1101 "/etc/pki/tls/certs/ca-bundle.crt",
1103 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
1104 "/etc/ssl/ca-bundle.pem",
1106 "/etc/ssl/cert.pem",
1108];
1109
1110const SYSTEM_CA_DIR: &str = "/etc/ssl/certs";
1112
1113fn load_roots(
1118 file: Option<&OsStr>,
1119 dirs: Option<&OsStr>,
1120 bundles: &[&str],
1121 dir: &str,
1122) -> io::Result<RootCertStore> {
1123 let mut roots = Roots {
1124 store: RootCertStore::empty(),
1125 seen: HashSet::new(),
1126 };
1127 if file.is_some() || dirs.is_some() {
1128 if let Some(file) = file {
1129 roots.add_file(Path::new(file)).map_err(|e| {
1130 io::Error::new(
1131 e.kind(),
1132 giong::error::Error::new(
1133 Code::BadCertificateData,
1134 format!("cannot read SSL_CERT_FILE {file:?}: {e}"),
1135 "point SSL_CERT_FILE at a readable PEM file of certificates, or unset \
1136 it to use the system's.",
1137 )
1138 .with_source(e),
1139 )
1140 })?;
1141 }
1142 for dir in dirs.map(std::env::split_paths).into_iter().flatten() {
1143 roots.add_dir(&dir);
1144 }
1145 } else if let Some(bundle) = bundles.iter().map(Path::new).find(|p| p.is_file()) {
1146 roots.add_file(bundle)?;
1147 } else {
1148 roots.add_dir(Path::new(dir));
1149 }
1150 if roots.store.is_empty() {
1151 return Err(coded(
1152 Code::NoTrustedRoots,
1153 "no trusted CA certificates found on this machine",
1154 "install the ca-certificates package, set SSL_CERT_FILE, or use \
1155 TlsConnector::with_webpki_roots (the webpki-roots feature of giong-tls).",
1156 ));
1157 }
1158 Ok(roots.store)
1159}
1160
1161struct Roots {
1162 store: RootCertStore,
1163 seen: HashSet<PathBuf>,
1166}
1167
1168impl Roots {
1169 fn add_file(&mut self, path: &Path) -> io::Result<()> {
1170 let real = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
1171 if !self.seen.insert(real) {
1172 return Ok(());
1173 }
1174 let pem = std::fs::read(path)?;
1175 let certs = CertificateDer::pem_slice_iter(&pem).filter_map(Result::ok);
1176 self.store.add_parsable_certificates(certs);
1177 Ok(())
1178 }
1179
1180 fn add_dir(&mut self, dir: &Path) {
1181 let Ok(entries) = std::fs::read_dir(dir) else {
1182 return;
1183 };
1184 let mut paths: Vec<PathBuf> = entries.filter_map(|e| Some(e.ok()?.path())).collect();
1185 paths.sort();
1186 for path in paths.iter().filter(|p| p.is_file()) {
1187 let _ = self.add_file(path);
1189 }
1190 }
1191}
1192
1193pub struct TlsStream {
1196 tcp: TcpStream,
1197 engine: RefCell<Engine>,
1199 plain: RefCell<Vec<u8>>,
1201 wire: RefCell<Vec<u8>>,
1204 established: Cell<bool>,
1208 eof: Cell<bool>,
1210 close_notify: Cell<bool>,
1213 sending: Cell<bool>,
1217 broken: Cell<bool>,
1220 closed: Cell<Option<Code>>,
1224 failed: Cell<Option<io::Error>>,
1226 waiters: RefCell<Vec<Waker>>,
1228 unsent: RefCell<Vec<u8>>,
1232}
1233
1234#[allow(clippy::large_enum_variant)]
1238enum Engine {
1239 User(Connection),
1241 Kernel(ktls::Kernel),
1244}
1245
1246struct Sending<'a> {
1250 stream: &'a TlsStream,
1251 complete: bool,
1252}
1253
1254impl Sending<'_> {
1255 fn done(mut self) {
1257 self.complete = true;
1258 }
1259}
1260
1261impl Drop for Sending<'_> {
1262 fn drop(&mut self) {
1263 if !self.complete {
1264 self.stream.broken.set(true);
1265 }
1266 self.stream.sending.set(false);
1267 self.stream.wake_waiters();
1268 }
1269}
1270
1271impl TlsStream {
1272 fn new(tcp: TcpStream, conn: Connection) -> Self {
1273 Self::with_engine(tcp, Engine::User(conn), Vec::new(), false)
1274 }
1275
1276 fn kernel(tcp: TcpStream, kernel: ktls::Kernel, plain: Vec<u8>, peer_closed: bool) -> Self {
1280 Self::with_engine(tcp, Engine::Kernel(kernel), plain, peer_closed)
1281 }
1282
1283 fn with_engine(tcp: TcpStream, engine: Engine, plain: Vec<u8>, peer_closed: bool) -> Self {
1284 Self {
1285 tcp,
1286 engine: RefCell::new(engine),
1287 plain: RefCell::new(plain),
1288 wire: RefCell::new(Vec::new()),
1289 established: Cell::new(false),
1290 eof: Cell::new(peer_closed),
1291 close_notify: Cell::new(peer_closed),
1292 sending: Cell::new(false),
1293 broken: Cell::new(false),
1294 closed: Cell::new(None),
1295 failed: Cell::new(None),
1296 waiters: RefCell::new(Vec::new()),
1297 unsent: RefCell::new(Vec::new()),
1298 }
1299 }
1300
1301 fn conn(&self) -> RefMut<'_, Connection> {
1304 RefMut::map(self.engine.borrow_mut(), |e| match e {
1305 Engine::User(c) => c,
1306 Engine::Kernel(_) => unreachable!("rustls' connection on a kernel TLS stream"),
1307 })
1308 }
1309
1310 pub fn is_ktls(&self) -> bool {
1314 matches!(*self.engine.borrow(), Engine::Kernel(_))
1315 }
1316
1317 async fn wait_for_sender(&self) {
1319 poll_fn(|cx| {
1320 if !self.sending.get() {
1321 return Poll::Ready(());
1322 }
1323 let mut waiters = self.waiters.borrow_mut();
1325 if !waiters.iter().any(|w| w.will_wake(cx.waker())) {
1326 waiters.push(cx.waker().clone());
1327 }
1328 Poll::Pending
1329 })
1330 .await;
1331 }
1332
1333 async fn lock_send(&self) -> Sending<'_> {
1336 while self.sending.get() {
1337 self.wait_for_sender().await;
1338 }
1339 self.sending.set(true);
1340 Sending {
1341 stream: self,
1342 complete: false,
1343 }
1344 }
1345
1346 async fn handshake(
1350 self,
1351 limit: Duration,
1352 spent: Duration,
1353 first: Option<giong::RecvBuf>,
1354 ) -> io::Result<Self> {
1355 let handshake = async {
1356 if let Some(first) = first {
1357 self.absorb(first).await?;
1358 }
1359 while self.conn().is_handshaking() {
1360 self.flush_tls().await?;
1361 if !self.conn().is_handshaking() {
1362 break;
1363 }
1364 if self.eof.get() {
1365 return Err(handshake_eof());
1366 }
1367 self.pump().await?;
1368 }
1369 if !self.hold_output() {
1370 self.flush_tls().await?;
1371 }
1372 self.established.set(true);
1373 Ok(())
1374 };
1375 match timeout(limit.saturating_sub(spent), handshake).await {
1376 Ok(Ok(())) => Ok(self),
1377 Ok(Err(e)) => Err(e),
1378 Err(_) => Err(handshake_timed_out(limit)),
1379 }
1380 }
1381
1382 fn wake_waiters(&self) {
1385 let waiters = mem::take(&mut *self.waiters.borrow_mut());
1386 for waker in waiters {
1387 waker.wake();
1388 }
1389 }
1390
1391 fn hold_output(&self) -> bool {
1405 if self.established.get() {
1406 return true;
1409 }
1410 let conn = self.conn();
1411 if conn.is_handshaking() {
1412 return false;
1413 }
1414 (matches!(*conn, Connection::Server(_))
1415 && conn.protocol_version() == Some(rustls::ProtocolVersion::TLSv1_3))
1416 }
1417
1418 fn take_wire(&self) -> Vec<u8> {
1422 let mut wire = mem::take(&mut *self.wire.borrow_mut());
1423 let mut unsent = self.unsent.borrow_mut();
1424 if unsent.capacity() > 0 {
1425 wire.extend_from_slice(&unsent);
1426 *unsent = Vec::new();
1428 }
1429 wire
1430 }
1431
1432 fn keep_wire(&self, mut wire: Vec<u8>) {
1436 if !wire.is_empty() && !self.broken.get() {
1437 self.unsent.borrow_mut().append(&mut wire);
1440 }
1441 if wire.capacity() <= WIRE_KEPT {
1442 wire.clear();
1443 *self.wire.borrow_mut() = wire;
1444 }
1445 }
1446
1447 fn cannot_send(&self) -> Option<io::Error> {
1450 if self.broken.get() {
1451 return Some(broken());
1452 }
1453 self.closed.get().map(sending_closed)
1454 }
1455
1456 async fn flush_tls(&self) -> io::Result<()> {
1460 loop {
1461 if !self.wants_send() {
1462 return Ok(());
1463 }
1464 if self.broken.get() {
1465 return Err(broken());
1466 }
1467 if self.sending.get() {
1468 self.wait_for_sender().await;
1471 continue;
1472 }
1473 let sending = self.lock_send().await;
1474 let mut wire = self.take_wire();
1475 let res = self.send_queued(&mut wire).await;
1476 self.keep_wire(wire);
1477 sending.done();
1478 res?;
1479 }
1480 }
1481
1482 async fn send_queued(&self, wire: &mut Vec<u8>) -> io::Result<()> {
1485 loop {
1486 {
1487 let mut conn = self.conn();
1488 while conn.wants_write() {
1489 conn.write_tls(wire)?;
1490 }
1491 }
1492 if wire.is_empty() {
1493 return Ok(());
1494 }
1495 self.send_wire(wire).await?;
1496 }
1497 }
1498
1499 fn wants_send(&self) -> bool {
1502 self.conn().wants_write() || !self.unsent.borrow().is_empty()
1503 }
1504
1505 fn flush_now(&self) -> io::Result<()> {
1517 if self.broken.get() {
1518 return Err(broken());
1519 }
1520 if self.sending.get() {
1521 return Ok(());
1522 }
1523 let mut unsent = self.unsent.borrow_mut();
1524 {
1525 let mut conn = self.conn();
1526 while conn.wants_write() {
1527 conn.write_tls(&mut *unsent)?;
1528 }
1529 }
1530 loop {
1531 let len = unsent.len().min(flush_room());
1533 if len == 0 {
1534 return Ok(());
1535 }
1536 let fd = sys::AsRawFd::as_raw_fd(&self.tcp);
1537 let e = match sys::send_now(fd, &unsent[..len], false) {
1538 Ok(n) => {
1539 if n == unsent.len() {
1540 *unsent = Vec::new();
1542 } else {
1543 unsent.drain(..n);
1545 }
1546 return Ok(());
1547 }
1548 Err(e) => e,
1549 };
1550 match e.kind() {
1551 io::ErrorKind::Interrupted => {}
1552 io::ErrorKind::WouldBlock => return Ok(()),
1553 _ if no_buffers(&e) => return Ok(()),
1556 _ => {
1557 self.broken.set(true);
1558 *unsent = Vec::new();
1559 return Err(e);
1560 }
1561 }
1562 }
1563 }
1564
1565 async fn send_wire(&self, wire: &mut Vec<u8>) -> io::Result<()> {
1569 let (res, mut sent) = self.tcp.write_all(mem::take(wire)).await;
1570 sent.clear();
1571 *wire = sent;
1572 if res.is_err() {
1573 self.broken.set(true);
1574 }
1575 res
1576 }
1577
1578 async fn send_plain(&self, wire: &mut Vec<u8>, data: &[u8], last: bool) -> io::Result<()> {
1590 let mut sent = 0;
1591 while sent < data.len() {
1592 let (carried, refused) = {
1593 let mut conn = self.conn();
1594 while conn.wants_write() {
1595 conn.write_tls(wire)?;
1596 }
1597 let carried = !wire.is_empty();
1598 let start = wire.len();
1599 let n = conn.writer().write(&data[sent..])?;
1600 while conn.wants_write() {
1601 conn.write_tls(wire)?;
1602 }
1603 sent += n;
1604 (carried, n > 0 && !has_application_data(&wire[start..]))
1609 };
1610 let more = sent < data.len() || !last;
1611 if !wire.is_empty() && (carried || refused || !more || wire.len() >= SEND_AT) {
1612 self.send_wire(wire).await?;
1613 }
1614 if carried {
1615 self.wake_waiters();
1617 }
1618 if refused {
1619 self.closed.set(Some(Code::TlsKeysExhausted));
1620 return Err(sending_closed(Code::TlsKeysExhausted));
1621 }
1622 }
1623 Ok(())
1624 }
1625
1626 async fn write_in_process(&self, pieces: &[&[u8]]) -> io::Result<()> {
1630 let sending = self.lock_send().await;
1631 if let Some(e) = self.cannot_send() {
1632 sending.done();
1633 return Err(e);
1634 }
1635 let mut wire = self.take_wire();
1636 let mut res = Ok(());
1637 for (i, piece) in pieces.iter().enumerate() {
1638 res = self
1639 .send_plain(&mut wire, piece, i + 1 == pieces.len())
1640 .await;
1641 if res.is_err() {
1642 break;
1643 }
1644 }
1645 if res.is_ok() && !wire.is_empty() {
1646 res = self.send_wire(&mut wire).await;
1648 }
1649 self.keep_wire(wire);
1650 sending.done();
1654 res
1655 }
1656
1657 async fn pump(&self) -> io::Result<()> {
1660 let ready = if !self.broken.get() && self.wants_send() {
1663 poll_fn(|cx| Poll::Ready(self.tcp.poll_recv(cx))).await
1664 } else {
1665 Poll::Pending
1666 };
1667 let chunk = match ready {
1668 Poll::Ready(chunk) => chunk?,
1669 Poll::Pending => {
1670 if !self.broken.get() && self.wants_send() {
1671 let _ = self.flush_for_recv().await;
1675 }
1676 self.tcp.recv().await?
1678 }
1679 };
1680 self.absorb(chunk).await
1681 }
1682
1683 async fn absorb(&self, chunk: giong::RecvBuf) -> io::Result<()> {
1687 if chunk.is_empty() {
1688 self.eof.set(true);
1689 return Ok(());
1690 }
1691 let result = {
1692 let mut conn = self.conn();
1693 let mut plain = self.plain.borrow_mut();
1694 let mut input = &chunk[..];
1695 let mut result = Ok(());
1696 while !input.is_empty() {
1697 match conn.read_tls(&mut input) {
1700 Ok(0) => {
1701 result = Err(coded(
1702 Code::TlsProtocol,
1703 "rustls accepted no more TLS data",
1704 "this is a bug in giong-tls; please report it at \
1705 https://github.com/giong-run/Giong/issues.",
1706 ));
1707 break;
1708 }
1709 Ok(_) => {}
1710 Err(e) => {
1711 result = Err(e);
1712 break;
1713 }
1714 }
1715 match conn.process_new_packets() {
1716 Ok(state) => {
1717 let n = state.plaintext_bytes_to_read();
1718 if n > 0 {
1719 let at = plain.len();
1720 plain.resize(at + n, 0);
1721 if let Err(e) = conn.reader().read_exact(&mut plain[at..]) {
1722 plain.truncate(at);
1723 result = Err(e);
1724 break;
1725 }
1726 }
1727 if state.peer_has_closed() {
1728 self.close_notify.set(true);
1729 self.eof.set(true);
1730 break;
1731 }
1732 }
1733 Err(e) => {
1734 result = Err(tls_error(e));
1735 break;
1736 }
1737 }
1738 }
1739 result
1740 };
1741 drop(chunk);
1742 if self.broken.get() || (result.is_ok() && self.hold_output()) {
1746 return result;
1747 }
1748 let flushed = self.flush_for_recv().await;
1749 result.and(flushed)
1750 }
1751
1752 async fn flush_for_recv(&self) -> io::Result<()> {
1758 if self.established.get() {
1759 self.flush_now()
1760 } else {
1761 self.flush_tls().await
1762 }
1763 }
1764
1765 pub async fn recv(&self) -> io::Result<Received> {
1784 if self.is_ktls() {
1785 return self.kernel_recv().await.map(Received);
1786 }
1787 self.user_recv().await.map(Received)
1788 }
1789
1790 async fn user_recv(&self) -> io::Result<Vec<u8>> {
1791 loop {
1792 {
1793 let mut plain = self.plain.borrow_mut();
1794 if !plain.is_empty() {
1795 return Ok(mem::take(&mut *plain));
1796 }
1797 }
1798 if let Some(e) = self.failed.take() {
1799 return Err(e);
1800 }
1801 if self.eof.get() {
1802 return Ok(Vec::new());
1803 }
1804 if let Err(e) = self.pump().await {
1805 if self.plain.borrow().is_empty() {
1807 return Err(e);
1808 }
1809 self.failed.set(Some(e));
1810 }
1811 }
1812 }
1813
1814 pub async fn write_all<B>(&self, buf: B) -> (io::Result<()>, B)
1835 where
1836 B: giong::IoBuf + AsRef<[u8]>,
1837 {
1838 if self.is_ktls() {
1839 return self.kernel_write_all(buf).await;
1840 }
1841 let res = self.write_in_process(&[buf.as_ref()]).await;
1842 (res, buf)
1843 }
1844
1845 pub async fn write_all_vectored<B>(&self, bufs: Vec<B>) -> (io::Result<()>, Vec<B>)
1857 where
1858 B: giong::IoBuf + AsRef<[u8]>,
1859 {
1860 if self.is_ktls() {
1861 return self.kernel_write_all_vectored(bufs).await;
1862 }
1863 let pieces: Vec<&[u8]> = bufs.iter().map(AsRef::as_ref).collect();
1864 let res = self.write_in_process(&pieces).await;
1865 drop(pieces);
1866 (res, bufs)
1867 }
1868
1869 pub async fn send_file(&self, file: &giong::fs::File, offset: u64, len: u64) -> io::Result<()> {
1886 if offset
1887 .checked_add(len)
1888 .map_or(true, |end| end > i64::MAX as u64)
1889 {
1890 return Err(file_too_short(offset, len, offset));
1891 }
1892 if self.is_ktls() {
1893 return self.kernel_send_file(file, offset, len).await;
1894 }
1895 let sending = self.lock_send().await;
1896 if let Some(e) = self.cannot_send() {
1897 sending.done();
1898 return Err(e);
1899 }
1900 let mut wire = self.take_wire();
1901 let res = self
1902 .send_file_in_process(&mut wire, file, offset, len)
1903 .await;
1904 self.keep_wire(wire);
1905 sending.done();
1906 res
1907 }
1908
1909 async fn send_file_in_process(
1912 &self,
1913 wire: &mut Vec<u8>,
1914 file: &giong::fs::File,
1915 offset: u64,
1916 len: u64,
1917 ) -> io::Result<()> {
1918 const PIECE: u64 = 256 * 1024;
1919 let mut buf = Vec::with_capacity(len.min(PIECE) as usize);
1920 let (mut at, mut left) = (offset, len);
1921 while left > 0 {
1922 let (res, b) = file.read_at(buf, at).await;
1923 buf = b;
1924 let n = match res {
1925 Ok(0) => return Err(file_too_short(offset, len, at)),
1926 Ok(n) => (n as u64).min(left) as usize,
1927 Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
1928 Err(e) => return Err(e),
1929 };
1930 self.send_plain(wire, &buf[..n], true).await?;
1931 at += n as u64;
1932 left -= n as u64;
1933 }
1934 Ok(())
1935 }
1936
1937 async fn send_closing(&self, wire: &mut Vec<u8>) -> io::Result<()> {
1944 {
1945 let mut conn = self.conn();
1946 while conn.wants_write() {
1947 conn.write_tls(wire)?;
1948 }
1949 }
1950 match sys::send_now(sys::AsRawFd::as_raw_fd(&self.tcp), wire, true) {
1953 Ok(n) => {
1954 wire.drain(..n);
1955 }
1956 Err(e)
1959 if !matches!(
1960 e.kind(),
1961 io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted
1962 ) && !no_buffers(&e) =>
1963 {
1964 self.broken.set(true);
1965 wire.clear();
1966 return Err(e);
1967 }
1968 Err(_) => {}
1969 }
1970 if !wire.is_empty() {
1971 self.send_wire(wire).await?;
1972 }
1973 self.send_queued(wire).await
1974 }
1975
1976 pub async fn shutdown(&self) -> io::Result<()> {
1994 if self.is_ktls() {
1995 return self.kernel_shutdown().await;
1996 }
1997 let sending = self.lock_send().await;
1998 if self.cannot_send().is_none() {
1999 self.conn().send_close_notify();
2000 self.closed.set(Some(Code::TlsBroken));
2001 let mut wire = self.take_wire();
2002 let res = self.send_closing(&mut wire).await;
2003 self.keep_wire(wire);
2004 if let Err(e) = res {
2005 sending.done();
2007 let _ = self.tcp.shutdown(Shutdown::Write);
2008 return if self.peer_gone(&e) { Ok(()) } else { Err(e) };
2009 }
2010 }
2011 sending.done();
2012 self.tcp.shutdown(Shutdown::Write)
2013 }
2014
2015 fn peer_gone(&self, e: &io::Error) -> bool {
2018 matches!(
2019 e.kind(),
2020 io::ErrorKind::BrokenPipe | io::ErrorKind::ConnectionReset
2021 )
2022 }
2023
2024 pub fn received_close_notify(&self) -> bool {
2030 self.close_notify.get()
2031 }
2032
2033 pub fn alpn_protocol(&self) -> Option<Vec<u8>> {
2035 match &*self.engine.borrow() {
2036 Engine::User(c) => c.alpn_protocol().map(<[u8]>::to_vec),
2037 Engine::Kernel(k) => k.negotiated.alpn.clone(),
2038 }
2039 }
2040
2041 pub fn peer_certificates(&self) -> Option<Vec<CertificateDer<'static>>> {
2046 match &*self.engine.borrow() {
2047 Engine::User(c) => c.peer_certificates().map(<[_]>::to_vec),
2048 Engine::Kernel(k) => k.negotiated.peer_certificates.clone(),
2049 }
2050 }
2051
2052 pub fn resumed(&self) -> bool {
2055 match &*self.engine.borrow() {
2056 Engine::User(c) => c.handshake_kind() == Some(rustls::HandshakeKind::Resumed),
2057 Engine::Kernel(k) => k.negotiated.resumed,
2058 }
2059 }
2060
2061 pub fn tcp(&self) -> &TcpStream {
2068 &self.tcp
2069 }
2070}
2071
2072impl std::fmt::Debug for TlsStream {
2073 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2074 f.debug_struct("TlsStream")
2075 .field("tcp", &self.tcp)
2076 .field("ktls", &self.is_ktls())
2077 .finish_non_exhaustive()
2078 }
2079}
2080
2081#[cfg(test)]
2082mod tests {
2083 use super::*;
2084 use std::future::Future;
2085
2086 #[test]
2087 fn a_connector_without_trusted_authorities_is_refused() {
2088 let err = TlsConnector::from_roots(RootCertStore::empty()).unwrap_err();
2090 assert_eq!(err.kind(), io::ErrorKind::NotFound, "{err}");
2091 assert_eq!(
2092 giong::error::code(&err),
2093 Some(Code::NoTrustedRoots),
2094 "{err}"
2095 );
2096 }
2097
2098 fn authority(name: &str) -> (rcgen::Certificate, rcgen::KeyPair) {
2099 let key = rcgen::KeyPair::generate().unwrap();
2100 let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
2101 params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
2102 params
2103 .distinguished_name
2104 .push(rcgen::DnType::CommonName, name);
2105 (params.self_signed(&key).unwrap(), key)
2106 }
2107
2108 fn signed_by(
2109 ca: &rcgen::Certificate,
2110 ca_key: &rcgen::KeyPair,
2111 names: &[&str],
2112 expired: bool,
2113 ) -> CertificateDer<'static> {
2114 let key = rcgen::KeyPair::generate().unwrap();
2115 let names: Vec<String> = names.iter().map(|n| n.to_string()).collect();
2116 let mut params = rcgen::CertificateParams::new(names).unwrap();
2117 params.distinguished_name.push(
2119 rcgen::DnType::CommonName,
2120 "MySQL_Server_8.0.46_Auto_Generated_Server_Certificate",
2121 );
2122 if expired {
2123 params.not_before = rcgen::date_time_ymd(2020, 1, 1);
2124 params.not_after = rcgen::date_time_ymd(2021, 1, 1);
2125 }
2126 let cert = params.signed_by(&key, ca, ca_key).unwrap();
2127 CertificateDer::from(cert.der().to_vec())
2128 }
2129
2130 #[test]
2132 fn any_name_still_checks_the_chain() {
2133 use rustls::client::danger::ServerCertVerifier;
2134 use rustls::pki_types::UnixTime;
2135 use rustls::CertificateError;
2136
2137 let (ca, ca_key) = authority("ours");
2138 let mut roots = RootCertStore::empty();
2139 roots.add(CertificateDer::from(ca.der().to_vec())).unwrap();
2140 let webpki = rustls::client::WebPkiServerVerifier::builder_with_provider(
2141 Arc::new(roots),
2142 provider(),
2143 )
2144 .build()
2145 .unwrap();
2146 let verifier = AnyName(webpki);
2147 let name = ServerName::try_from("db.internal").unwrap();
2148 let check = |cert: &CertificateDer<'_>| {
2149 verifier.verify_server_cert(cert, &[], &name, &[], UnixTime::now())
2150 };
2151 for names in [&[][..], &["localhost"], &["db.internal"]] {
2153 check(&signed_by(&ca, &ca_key, names, false)).unwrap();
2154 }
2155 let e = check(&signed_by(&ca, &ca_key, &[], true)).unwrap_err();
2157 assert!(
2158 matches!(
2159 e,
2160 rustls::Error::InvalidCertificate(
2161 CertificateError::Expired | CertificateError::ExpiredContext { .. }
2162 )
2163 ),
2164 "{e:?}"
2165 );
2166 let (other, other_key) = authority("theirs");
2169 for cert in [
2170 signed_by(&other, &other_key, &["db.internal"], false),
2171 CertificateDer::from(other.der().to_vec()),
2172 ] {
2173 let e = check(&cert).unwrap_err();
2174 assert!(matches!(e, rustls::Error::InvalidCertificate(_)), "{e:?}");
2175 }
2176 assert!(check(&CertificateDer::from(ca.der().to_vec())).is_err());
2178 assert!(TlsConnector::with_root_pem_any_name(b"").is_err());
2180 assert!(TlsConnector::with_root_pem_any_name(
2181 b"-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n"
2182 )
2183 .is_err());
2184 assert!(TlsConnector::with_root_pem_any_name(ca.pem().as_bytes()).is_ok());
2185 }
2186
2187 fn client_hello(suites: &[u16], id_len: u8, keep: usize) -> Vec<u8> {
2190 let mut hello = vec![22, 3, 1, 0, 0, 1, 0, 0, 0, 3, 3];
2191 hello.extend_from_slice(&[7; 32]);
2192 hello.push(id_len);
2193 hello.extend(std::iter::repeat(9).take(id_len.into()));
2194 hello.extend_from_slice(&((suites.len() * 2) as u16).to_be_bytes());
2195 for suite in suites {
2196 hello.extend_from_slice(&suite.to_be_bytes());
2197 }
2198 hello.extend_from_slice(&[1, 0]); hello.truncate(keep);
2200 hello
2201 }
2202
2203 #[test]
2204 fn chacha20_first_clients_are_told_apart() {
2205 let all = usize::MAX;
2206 assert!(!prefers_chacha(&client_hello(
2208 &[0x1302, 0x1303, 0x1301],
2209 32,
2210 all
2211 )));
2212 assert!(!prefers_chacha(&client_hello(
2214 &[0x1301, 0x1302, 0x1303],
2215 0,
2216 all
2217 )));
2218 assert!(prefers_chacha(&client_hello(
2220 &[0x0a0a, 0x1303, 0x1301],
2221 32,
2222 all
2223 )));
2224 assert!(prefers_chacha(&client_hello(&[0xcca9, 0xc02b], 0, all)));
2226 assert!(!prefers_chacha(&client_hello(&[0xc02c, 0xcca9], 0, all)));
2227 assert!(!prefers_chacha(&client_hello(&[0x009c], 0, all)));
2229 let cut = client_hello(&[0x1303, 0x1301], 32, all).len() - 3;
2230 assert!(!prefers_chacha(&client_hello(&[0x1303, 0x1301], 32, cut)));
2231 assert!(!prefers_chacha(&client_hello(&[0x1303], 32, 40)));
2232 assert!(!prefers_chacha(&[]));
2233 let mut alert = client_hello(&[0x1303], 0, all);
2234 alert[0] = 21;
2235 assert!(!prefers_chacha(&alert));
2236 }
2237
2238 fn ca_pem(name: &str) -> String {
2239 let key = rcgen::KeyPair::generate().unwrap();
2240 let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
2241 params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
2242 params
2243 .distinguished_name
2244 .push(rcgen::DnType::CommonName, name);
2245 params.self_signed(&key).unwrap().pem()
2246 }
2247
2248 fn scratch(name: &str) -> PathBuf {
2250 let dir = std::env::temp_dir().join(format!("giong-tls-{}-{name}", std::process::id()));
2251 let _ = std::fs::remove_dir_all(&dir);
2252 std::fs::create_dir_all(&dir).unwrap();
2253 dir
2254 }
2255
2256 fn os(path: &Path) -> &OsStr {
2257 path.as_os_str()
2258 }
2259
2260 #[test]
2261 fn server_names_are_dns_names_or_ip_addresses() {
2262 let dns = |n: &str| matches!(parse_server_name(n), Ok(ServerName::DnsName(_)));
2263 let ip = |n: &str| matches!(parse_server_name(n), Ok(ServerName::IpAddress(_)));
2264 assert!(dns("example.com"));
2265 assert!(dns("db.prod.svc.cluster.local"));
2266 assert!(ip("10.0.0.1"));
2267 assert!(ip("::1"));
2268 assert!(ip("[::1]"));
2269 for bad in ["", "not a name", "[nope]", "[10.0.0.1]", "a..b"] {
2270 let err = parse_server_name(bad).unwrap_err();
2271 assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{bad:?}");
2272 }
2273 }
2274
2275 #[test]
2276 fn the_first_bundle_that_exists_is_read() {
2277 let dir = scratch("bundle");
2278 let bundle = dir.join("bundle.pem");
2279 let two = format!("{}{}", ca_pem("one"), ca_pem("two"));
2280 std::fs::write(&bundle, two).unwrap();
2281 let missing = dir.join("missing.pem");
2282 let bundles = [missing.to_str().unwrap(), bundle.to_str().unwrap()];
2283 let roots = load_roots(None, None, &bundles, "/nonexistent").unwrap();
2284 assert_eq!(roots.len(), 2);
2285 std::fs::remove_dir_all(dir).unwrap();
2286 }
2287
2288 #[test]
2289 fn ssl_cert_file_and_dir_replace_the_system_locations() {
2290 let dir = scratch("env");
2291 let file = dir.join("file.pem");
2292 std::fs::write(&file, ca_pem("from file")).unwrap();
2293 let certs = dir.join("certs");
2294 std::fs::create_dir(&certs).unwrap();
2295 std::fs::write(certs.join("a.pem"), ca_pem("a")).unwrap();
2296 std::fs::write(certs.join("b.pem"), ca_pem("b")).unwrap();
2297 std::fs::write(certs.join("README"), "not a certificate").unwrap();
2298 #[cfg(unix)]
2300 std::os::unix::fs::symlink(certs.join("a.pem"), certs.join("1a2b3c4d.0")).unwrap();
2301 let system = dir.join("system.pem");
2302 std::fs::write(&system, ca_pem("system")).unwrap();
2303 let bundles = [system.to_str().unwrap()];
2304
2305 let roots = load_roots(Some(os(&file)), None, &bundles, "/nonexistent").unwrap();
2306 assert_eq!(roots.len(), 1, "SSL_CERT_FILE only");
2307 let roots = load_roots(None, Some(os(&certs)), &bundles, "/nonexistent").unwrap();
2308 assert_eq!(roots.len(), 2, "SSL_CERT_DIR only, each file once");
2309 let both = std::env::join_paths([dir.join("nowhere"), certs.clone()]).unwrap();
2310 let roots = load_roots(Some(os(&file)), Some(&both), &bundles, "/nonexistent").unwrap();
2311 assert_eq!(roots.len(), 3, "both, with a missing directory in the list");
2312
2313 let err = load_roots(Some(os(&dir.join("gone.pem"))), None, &bundles, "").unwrap_err();
2314 assert_eq!(err.kind(), io::ErrorKind::NotFound);
2315 assert!(err.to_string().contains("SSL_CERT_FILE"), "{err}");
2316 std::fs::remove_dir_all(dir).unwrap();
2317 }
2318
2319 #[test]
2320 fn without_a_bundle_the_directory_is_read_and_nothing_is_an_error() {
2321 let dir = scratch("dir");
2322 std::fs::write(dir.join("only.crt"), ca_pem("only")).unwrap();
2323 let roots = load_roots(
2324 None,
2325 None,
2326 &["/nonexistent/bundle.crt"],
2327 dir.to_str().unwrap(),
2328 );
2329 assert_eq!(roots.unwrap().len(), 1);
2330
2331 let empty = scratch("empty");
2332 let err = load_roots(None, None, &[], empty.to_str().unwrap()).unwrap_err();
2333 assert_eq!(err.kind(), io::ErrorKind::NotFound);
2334 assert!(err.to_string().contains("webpki-roots"), "{err}");
2335 std::fs::remove_dir_all(dir).unwrap();
2336 std::fs::remove_dir_all(empty).unwrap();
2337 }
2338
2339 #[test]
2340 fn records_are_scanned_for_application_data() {
2341 let record = |typ: u8, len: u16| {
2343 let mut r = vec![typ, 3, 3];
2344 r.extend_from_slice(&len.to_be_bytes());
2345 r.resize(5 + len as usize, 0xAA);
2346 r
2347 };
2348 assert!(!has_application_data(&[]));
2349 assert!(!has_application_data(&record(21, 26)));
2350 assert!(has_application_data(&record(23, 0)));
2351 let mut alert_then_data = record(21, 26);
2352 alert_then_data.extend(record(23, 300));
2353 assert!(has_application_data(&alert_then_data));
2354 let mut alert = record(21, 26);
2356 alert[5] = 23;
2357 assert!(!has_application_data(&alert));
2358 }
2359
2360 #[test]
2361 fn secrets_are_extractable_only_when_the_kernel_will_take_them() {
2362 let key = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
2363 let (cert, key) = (key.cert.pem(), key.key_pair.serialize_pem());
2364 for mode in [Ktls::Off, Ktls::Auto] {
2365 let acceptor = TlsAcceptor::with_certificates(
2366 &Certificates::from_pem(cert.as_bytes(), key.as_bytes()).unwrap(),
2367 )
2368 .unwrap()
2369 .ktls(mode)
2370 .unwrap();
2371 let tries = acceptor.ktls.tries();
2372 assert_eq!(acceptor.config.enable_secret_extraction, tries, "{mode:?}");
2373 let connector = TlsConnector::with_root_pem(cert.as_bytes())
2374 .unwrap()
2375 .ktls(mode)
2376 .unwrap();
2377 let tries = connector.ktls.tries();
2378 assert_eq!(connector.config.enable_secret_extraction, tries, "{mode:?}");
2379 }
2380 }
2381
2382 #[test]
2383 fn this_machines_roots_load() {
2384 TlsConnector::with_system_roots().unwrap();
2386 }
2387
2388 #[cfg(feature = "webpki-roots")]
2389 #[test]
2390 fn mozillas_roots_are_compiled_in() {
2391 TlsConnector::with_webpki_roots();
2392 }
2393
2394 #[test]
2395 fn records_a_receive_could_not_send_whole_go_out_first_and_in_order() {
2396 let key = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
2402 let cert = key.cert.pem();
2403 let acceptor = TlsAcceptor::with_certificates(
2404 &Certificates::from_pem(cert.as_bytes(), key.key_pair.serialize_pem().as_bytes())
2405 .unwrap(),
2406 )
2407 .unwrap();
2408 let connector = TlsConnector::with_root_pem(cert.as_bytes()).unwrap();
2409 giong::block_on(async move {
2410 let listener = giong::net::TcpListener::bind("127.0.0.1:0").unwrap();
2411 let addr = listener.local_addr().unwrap();
2412 let server = giong::spawn(async move {
2413 let tcp = listener.accept().await.unwrap();
2414 let tls = acceptor.accept(tcp).await.unwrap();
2415 assert!(tls.conn().wants_write(), "tickets wait for the first send");
2416 FLUSH_ROOM.set(1);
2417 let mut left = None;
2418 for _ in 0..5 {
2419 let mut recv = std::pin::pin!(tls.recv());
2420 let ready = poll_fn(|cx| Poll::Ready(recv.as_mut().poll(cx).is_ready())).await;
2421 assert!(!ready);
2422 let unsent = tls.unsent.borrow().len();
2423 assert!(
2424 left.map_or(unsent > 0, |l| unsent + 1 == l),
2425 "{left:?} {unsent}"
2426 );
2427 left = Some(unsent);
2428 }
2429 FLUSH_ROOM.set(usize::MAX);
2430 tls.write_all(&b"after the tickets"[..]).await.0.unwrap();
2431 assert_eq!(tls.unsent.borrow().capacity(), 0);
2434 tls.shutdown().await.unwrap();
2435 });
2436 let tcp = TcpStream::connect(addr).await.unwrap();
2437 let tls = connector.connect("localhost", tcp).await.unwrap();
2438 let mut got = Vec::new();
2439 loop {
2440 let data = tls.recv().await.unwrap();
2441 if data.is_empty() {
2442 break;
2443 }
2444 got.extend_from_slice(&data);
2445 }
2446 assert_eq!(got, b"after the tickets");
2447 assert!(tls.received_close_notify());
2448 server.await.unwrap();
2449 });
2450 }
2451
2452 #[test]
2453 fn a_receive_that_sent_what_was_owed_keeps_no_buffer_for_it() {
2454 let key = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
2458 let cert = key.cert.pem();
2459 let acceptor = TlsAcceptor::with_certificates(
2460 &Certificates::from_pem(cert.as_bytes(), key.key_pair.serialize_pem().as_bytes())
2461 .unwrap(),
2462 )
2463 .unwrap();
2464 let connector = TlsConnector::with_root_pem(cert.as_bytes()).unwrap();
2465 giong::block_on(async move {
2466 let listener = giong::net::TcpListener::bind("127.0.0.1:0").unwrap();
2467 let addr = listener.local_addr().unwrap();
2468 let server = giong::spawn(async move {
2469 let tcp = listener.accept().await.unwrap();
2470 let tls = acceptor.accept(tcp).await.unwrap();
2471 assert!(tls.conn().wants_write(), "tickets wait for the first send");
2472 let mut recv = std::pin::pin!(tls.recv());
2475 let ready = poll_fn(|cx| Poll::Ready(recv.as_mut().poll(cx).is_ready())).await;
2476 assert!(!ready);
2477 assert!(!tls.conn().wants_write());
2478 assert_eq!(tls.unsent.borrow().capacity(), 0);
2479 tls.shutdown().await.unwrap();
2480 });
2481 let tcp = TcpStream::connect(addr).await.unwrap();
2482 let tls = connector.connect("localhost", tcp).await.unwrap();
2483 assert!(tls.recv().await.unwrap().is_empty());
2484 assert!(tls.received_close_notify());
2485 server.await.unwrap();
2486 });
2487 }
2488
2489 #[test]
2490 fn the_key_exchange_offers_post_quantum_first_with_the_feature() {
2491 let first = provider().kx_groups[0].name();
2492 let pq = rustls::NamedGroup::X25519MLKEM768;
2493 assert_eq!(first == pq, cfg!(feature = "post-quantum"), "{first:?}");
2494 assert_eq!(provider_aes128_first().kx_groups[0].name(), first);
2495 }
2496}