1#![warn(missing_docs)]
80
81mod certs;
82#[cfg(target_os = "macos")]
83mod keychain;
84mod ktls;
85
86#[cfg(target_os = "linux")]
89const NO_SIGNAL: libc::c_int = libc::MSG_NOSIGNAL;
90#[cfg(target_os = "macos")]
91const NO_SIGNAL: libc::c_int = 0;
92mod received;
93
94pub use certs::Certificates;
95pub use ktls::{ktls_stats, ktls_support, Ktls, KtlsStats, KtlsSupport};
96pub use received::Received;
97pub use rustls_pki_types::CertificateDer;
100
101#[cfg(fuzzing)]
104#[doc(hidden)]
105pub mod fuzzing {
106 pub use crate::ktls::{check_handshake_messages, check_record_framing};
107}
108
109use std::cell::{Cell, RefCell, RefMut};
110use std::collections::HashSet;
111use std::ffi::OsStr;
112use std::future::poll_fn;
113use std::io::{self, Read, Write};
114use std::mem;
115use std::net::Shutdown;
116use std::path::{Path, PathBuf};
117use std::sync::Arc;
118use std::task::{Poll, Waker};
119use std::time::Duration;
120
121use giong::error::Code;
122use giong::net::TcpStream;
123use giong::time::timeout;
124use rustls::client::ResolvesClientCert;
125use rustls::pki_types::pem::PemObject;
126use rustls::pki_types::{PrivateKeyDer, ServerName};
127use rustls::sign::CertifiedKey;
128use rustls::{
129 ClientConfig, ClientConnection, Connection, RootCertStore, ServerConfig, ServerConnection,
130 SignatureScheme,
131};
132
133#[cfg(feature = "unstable-rustls")]
139pub use rustls;
140
141fn coded(
142 code: Code,
143 message: impl Into<std::borrow::Cow<'static, str>>,
144 fix: &'static str,
145) -> io::Error {
146 giong::error::Error::new(code, message, fix).into()
147}
148
149fn file_too_short(offset: u64, len: u64, at: u64) -> io::Error {
152 let end = offset.saturating_add(len);
153 coded(
154 Code::FileTooShort,
155 format!(
156 "the file ended at byte {at}, {} bytes short of the {len} send_file was asked to send",
157 end - at
158 ),
159 "take the length from the open file (File::len), and replace a file that is being \
160 served by renaming a new one over it, not by rewriting it; the peer has fewer bytes \
161 than announced, so close the connection.",
162 )
163}
164
165pub(crate) fn bad_certificate_data(e: impl std::fmt::Display) -> io::Error {
167 coded(
168 Code::BadCertificateData,
169 e.to_string(),
170 "check that the file or data is PEM (\"-----BEGIN CERTIFICATE-----\") and holds \
171 at least one certificate.",
172 )
173}
174
175pub(crate) fn bad_key(e: impl std::fmt::Display) -> io::Error {
177 coded(
178 Code::BadCertificateData,
179 format!("cannot read the private key: {e}"),
180 "check that it is a PEM private key (\"-----BEGIN PRIVATE KEY-----\", or the RSA or \
181 EC forms).",
182 )
183}
184
185pub(crate) fn mismatched_key(e: rustls::Error) -> io::Error {
187 coded(
188 Code::BadCertificateData,
189 format!("the certificate and the private key cannot be used together: {e}"),
190 "check that the key belongs to the first certificate of the chain, and that its type \
191 (RSA, ECDSA, Ed25519) is supported.",
192 )
193}
194
195fn tls_error(e: rustls::Error) -> io::Error {
197 match e {
198 rustls::Error::InvalidCertificate(_) if e.to_string().contains("CaUsedAsEndEntity") => {
201 coded(
202 Code::TlsCertificate,
203 "the peer's certificate was rejected: it is marked as a certificate authority \
204 (basicConstraints CA:TRUE), and an authority's certificate cannot be the \
205 peer's own (CaUsedAsEndEntity)",
206 "issue the peer's certificate with CA:FALSE: a self-signed one made with \
207 `openssl req -x509` needs -addext \"basicConstraints=critical,CA:FALSE\"; or \
208 have the authority sign a separate certificate for the peer.",
209 )
210 }
211 rustls::Error::InvalidCertificate(_) => coded(
212 Code::TlsCertificate,
213 format!("the peer's certificate was rejected: {e}"),
214 "check the name you connect to, the certificate's expiry and its chain; a \
215 private authority has to be trusted with TlsConnector::with_root_pem.",
216 ),
217 e => coded(
218 Code::TlsProtocol,
219 format!("TLS error: {e}"),
220 "check that the other side speaks TLS on this port, and that both sides share a \
221 protocol version and cipher suite.",
222 ),
223 }
224}
225
226const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
228
229fn handshake_timed_out(limit: Duration) -> io::Error {
230 coded(
231 Code::TlsHandshakeTimeout,
232 format!("the TLS handshake did not finish within {limit:?}"),
233 "check that the other side speaks TLS on this port and is not overloaded, or raise \
234 handshake_timeout.",
235 )
236}
237
238fn handshake_eof() -> io::Error {
239 coded(
240 Code::TlsHandshakeEof,
241 "the peer closed the connection during the TLS handshake",
242 "check that the other side speaks TLS on this port, and whether it wants a client \
243 certificate or another server name.",
244 )
245}
246
247const WIRE_KEPT: usize = 16 * 1024;
252
253const SEND_AT: usize = 64 * 1024;
256
257#[cfg(test)]
258thread_local! {
259 static FLUSH_ROOM: Cell<usize> = const { Cell::new(usize::MAX) };
262}
263
264fn flush_room() -> usize {
267 #[cfg(test)]
268 return FLUSH_ROOM.with(Cell::get);
269 #[cfg(not(test))]
270 usize::MAX
271}
272
273fn has_application_data(records: &[u8]) -> bool {
277 let mut at = 0;
278 while let Some(header) = records.get(at..at + 5) {
279 if header[0] == 23 {
280 return true;
281 }
282 at += 5 + usize::from(u16::from_be_bytes([header[3], header[4]]));
283 }
284 false
285}
286
287fn sending_closed(code: Code) -> io::Error {
290 match code {
291 Code::TlsKeysExhausted => coded(
292 Code::TlsKeysExhausted,
293 "this connection has sent as many TLS records as its cipher allows under one key, \
294 and cannot change keys (TLS 1.2, or TLS 1.3 on a kernel older than 6.14); \
295 close_notify was sent",
296 "open a new connection. TLS 1.3 changes keys instead (in the process, and with \
297 kernel TLS on Linux 6.14 or newer).",
298 ),
299 _ => coded(
300 Code::TlsBroken,
301 "this TLS stream has been shut down or ended with an alert; nothing more can be sent",
302 "open a new connection.",
303 ),
304 }
305}
306
307fn broken() -> io::Error {
308 coded(
309 Code::TlsBroken,
310 "a TLS write failed or was cancelled; nothing more can be sent",
311 "open a new connection. A write cancelled half-way (a dropped future, a timeout) \
312 leaves a partial record or message behind, so the stream cannot go on.",
313 )
314}
315
316#[inline]
321fn no_buffers(e: &io::Error) -> bool {
322 cfg!(target_os = "macos") && e.raw_os_error() == Some(libc::ENOBUFS)
323}
324
325pub(crate) fn pem_certs(pem: &[u8]) -> io::Result<Vec<CertificateDer<'static>>> {
327 let certs = CertificateDer::pem_slice_iter(pem)
328 .collect::<Result<Vec<_>, _>>()
329 .map_err(bad_certificate_data)?;
330 if certs.is_empty() {
331 return Err(bad_certificate_data("no certificate found in the PEM data"));
332 }
333 Ok(certs)
334}
335
336pub(crate) fn provider() -> Arc<rustls::crypto::CryptoProvider> {
340 Arc::new(base_provider())
341}
342
343#[cfg(not(feature = "post-quantum"))]
344fn base_provider() -> rustls::crypto::CryptoProvider {
345 rustls::crypto::ring::default_provider()
346}
347
348#[cfg(feature = "post-quantum")]
349fn base_provider() -> rustls::crypto::CryptoProvider {
350 rustls::crypto::aws_lc_rs::default_provider()
351}
352
353fn provider_aes128_first() -> Arc<rustls::crypto::CryptoProvider> {
363 use rustls::CipherSuite as S;
364 let mut provider = base_provider();
365 provider.cipher_suites.sort_by_key(|suite| {
368 let rank = match suite.suite() {
369 S::TLS13_AES_128_GCM_SHA256
370 | S::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
371 | S::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 => 0,
372 S::TLS13_CHACHA20_POLY1305_SHA256
373 | S::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
374 | S::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 => 1,
375 _ => 2,
376 };
377 (
378 suite.version().version != rustls::ProtocolVersion::TLSv1_3,
379 rank,
380 )
381 });
382 Arc::new(provider)
383}
384
385fn prefers_chacha(hello: &[u8]) -> bool {
393 const SESSION_ID: usize = 5 + 4 + 2 + 32;
395 if hello.first() != Some(&22) || hello.get(5) != Some(&1) {
396 return false;
397 }
398 let Some(&id_len) = hello.get(SESSION_ID) else {
399 return false;
400 };
401 let at = SESSION_ID + 1 + usize::from(id_len);
402 let Some(len) = hello.get(at..at + 2) else {
403 return false;
404 };
405 let len = usize::from(u16::from_be_bytes([len[0], len[1]]));
406 let Some(suites) = hello.get(at + 2..at + 2 + len) else {
407 return false;
408 };
409 for suite in suites.chunks_exact(2) {
410 match [suite[0], suite[1]] {
411 [0x13, 0x01]
414 | [0x13, 0x02]
415 | [0xc0, 0x2b]
416 | [0xc0, 0x2f]
417 | [0xc0, 0x2c]
418 | [0xc0, 0x30] => return false,
419 [0x13, 0x03] | [0xcc, 0xa9] | [0xcc, 0xa8] => return true,
421 _ => {}
422 }
423 }
424 false
425}
426
427fn server_configs(
432 certificates: &Certificates,
433 verifier: Arc<dyn rustls::server::danger::ClientCertVerifier>,
434) -> io::Result<(ServerConfig, ServerConfig)> {
435 let mut config = ServerConfig::builder_with_provider(provider_aes128_first())
436 .with_safe_default_protocol_versions()
437 .map_err(tls_error)?
438 .with_client_cert_verifier(verifier)
439 .with_cert_resolver(certificates.resolver());
440 let chacha = config.clone();
441 config.ignore_client_order = true;
442 Ok((config, chacha))
443}
444
445#[derive(Clone)]
449pub struct TlsAcceptor {
450 config: Arc<ServerConfig>,
451 chacha: Option<Arc<ServerConfig>>,
456 handshake_timeout: Duration,
457 ktls: ktls::Plan,
458 certificates: Option<Certificates>,
462}
463
464impl TlsAcceptor {
465 #[cfg(feature = "unstable-rustls")]
473 pub fn from_rustls(config: Arc<ServerConfig>) -> Self {
474 Self::with_config(config)
475 }
476
477 fn with_config(config: Arc<ServerConfig>) -> Self {
478 Self {
479 config,
480 chacha: None,
481 handshake_timeout: HANDSHAKE_TIMEOUT,
482 ktls: ktls::Plan::Off,
483 certificates: None,
484 }
485 }
486
487 pub fn with_certificates(certificates: &Certificates) -> io::Result<Self> {
512 let verifier = rustls::server::WebPkiClientVerifier::no_client_auth();
513 let (config, chacha) = server_configs(certificates, verifier)?;
514 Ok(Self {
515 chacha: Some(Arc::new(chacha)),
516 certificates: Some(certificates.clone()),
517 ..Self::with_config(Arc::new(config))
518 })
519 }
520
521 pub fn require_client_cert(self, ca_pem: &[u8]) -> io::Result<Self> {
531 self.client_auth(ca_pem, true)
532 }
533
534 pub fn request_client_cert(self, ca_pem: &[u8]) -> io::Result<Self> {
541 self.client_auth(ca_pem, false)
542 }
543
544 fn client_auth(mut self, ca_pem: &[u8], required: bool) -> io::Result<Self> {
545 let Some(certificates) = &self.certificates else {
546 return Err(coded(
547 Code::TlsConfig,
548 "client certificates cannot be set on an acceptor made with from_rustls",
549 "set client authentication in the rustls configuration given to from_rustls \
550 (ServerConfig::builder().with_client_cert_verifier), or make the acceptor \
551 with with_certificates.",
552 ));
553 };
554 let mut roots = RootCertStore::empty();
555 for cert in pem_certs(ca_pem)? {
556 roots.add(cert).map_err(bad_certificate_data)?;
557 }
558 let builder = rustls::server::WebPkiClientVerifier::builder_with_provider(
559 Arc::new(roots),
560 self.config.crypto_provider().clone(),
561 );
562 let builder = if required {
563 builder
564 } else {
565 builder.allow_unauthenticated()
566 };
567 let verifier = builder.build().map_err(bad_certificate_data)?;
568 let (mut config, mut chacha) = server_configs(certificates, verifier)?;
569 for new in [&mut config, &mut chacha] {
571 new.alpn_protocols = self.config.alpn_protocols.clone();
572 new.enable_secret_extraction = self.config.enable_secret_extraction;
573 }
574 self.config = Arc::new(config);
575 self.chacha = Some(Arc::new(chacha));
576 Ok(self)
577 }
578
579 fn config_for(&self, hello: &[u8]) -> Arc<ServerConfig> {
582 match &self.chacha {
583 Some(chacha) if prefers_chacha(hello) => chacha.clone(),
584 _ => self.config.clone(),
585 }
586 }
587
588 fn change_config(&mut self, change: impl Fn(&mut ServerConfig)) {
590 change(Arc::make_mut(&mut self.config));
591 if let Some(chacha) = &mut self.chacha {
592 change(Arc::make_mut(chacha));
593 }
594 }
595
596 pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
604 let protocols: Vec<Vec<u8>> = protocols.iter().map(|p| p.to_vec()).collect();
605 self.change_config(|config| config.alpn_protocols = protocols.clone());
606 self
607 }
608
609 pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
612 self.handshake_timeout = timeout;
613 self
614 }
615
616 pub fn ktls(mut self, mode: Ktls) -> io::Result<Self> {
643 let early_data = self.config.max_early_data_size > 0;
644 self.ktls = ktls::Plan::new(mode, self.config.crypto_provider(), early_data)?;
645 let extract = self.ktls.tries();
647 if self.config.enable_secret_extraction != extract {
648 self.change_config(|config| config.enable_secret_extraction = extract);
649 }
650 Ok(self)
651 }
652
653 pub fn ktls_unavailable(&self) -> Option<&str> {
658 self.ktls.unavailable()
659 }
660
661 pub async fn accept(&self, tcp: TcpStream) -> io::Result<TlsStream> {
670 let tcp = match &self.ktls {
671 ktls::Plan::Off => tcp,
672 ktls::Plan::Try { required } => {
673 let start = ktls::Start::Server(self.config.clone(), self.chacha.clone());
674 match ktls::handshake(tcp, start, self.handshake_timeout).await? {
675 ktls::Outcome::Kernel(tls) => return Ok(*tls),
676 ktls::Outcome::Declined(_, e) if *required => return Err(e),
677 ktls::Outcome::Declined(tcp, _) => {
678 self.ktls.stayed();
679 tcp
680 }
681 }
682 }
683 ktls::Plan::Unavailable(_) => {
684 self.ktls.stayed();
685 tcp
686 }
687 };
688 let Some(_) = &self.chacha else {
689 let conn = ServerConnection::new(self.config.clone()).map_err(tls_error)?;
690 return TlsStream::new(tcp, conn.into())
691 .handshake(self.handshake_timeout, Duration::ZERO, None)
692 .await;
693 };
694 let started = std::time::Instant::now();
697 let first = match timeout(self.handshake_timeout, tcp.recv()).await {
698 Ok(first) => first?,
699 Err(_) => return Err(handshake_timed_out(self.handshake_timeout)),
700 };
701 if first.is_empty() {
702 return Err(handshake_eof());
703 }
704 let conn = ServerConnection::new(self.config_for(&first)).map_err(tls_error)?;
705 TlsStream::new(tcp, conn.into())
706 .handshake(self.handshake_timeout, started.elapsed(), Some(first))
707 .await
708 }
709}
710
711impl std::fmt::Debug for TlsAcceptor {
712 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
713 f.debug_struct("TlsAcceptor")
714 .field("handshake_timeout", &self.handshake_timeout)
715 .field("ktls", &self.ktls)
716 .finish_non_exhaustive()
717 }
718}
719
720#[derive(Clone)]
741pub struct TlsConnector {
742 config: Arc<ClientConfig>,
743 handshake_timeout: Duration,
744 ktls: ktls::Plan,
745}
746
747impl TlsConnector {
748 #[cfg(feature = "unstable-rustls")]
756 pub fn from_rustls(config: Arc<ClientConfig>) -> Self {
757 Self::with_config(config)
758 }
759
760 fn with_config(config: Arc<ClientConfig>) -> Self {
761 Self {
762 config,
763 handshake_timeout: HANDSHAKE_TIMEOUT,
764 ktls: ktls::Plan::Off,
765 }
766 }
767
768 fn from_roots(roots: RootCertStore) -> io::Result<Self> {
769 if roots.is_empty() {
770 return Err(coded(
771 Code::NoTrustedRoots,
772 "no trusted certificate authority given",
773 "pass at least one certificate, or use TlsConnector::with_system_roots.",
774 ));
775 }
776 let config = ClientConfig::builder_with_provider(provider())
777 .with_safe_default_protocol_versions()
778 .map_err(tls_error)?
779 .with_root_certificates(roots)
780 .with_no_client_auth();
781 Ok(Self::with_config(Arc::new(config)))
782 }
783
784 pub fn with_root_pem(pem: &[u8]) -> io::Result<Self> {
793 let mut roots = RootCertStore::empty();
794 for cert in pem_certs(pem)? {
795 roots.add(cert).map_err(bad_certificate_data)?;
796 }
797 Self::from_roots(roots)
798 }
799
800 pub fn with_root_pem_any_name(pem: &[u8]) -> io::Result<Self> {
812 let mut roots = RootCertStore::empty();
813 for cert in pem_certs(pem)? {
814 roots.add(cert).map_err(bad_certificate_data)?;
815 }
816 if roots.is_empty() {
817 return Err(coded(
818 Code::NoTrustedRoots,
819 "no trusted certificate authority given",
820 "pass at least one certificate authority in PEM form.",
821 ));
822 }
823 let provider = provider();
824 let webpki = rustls::client::WebPkiServerVerifier::builder_with_provider(
825 Arc::new(roots),
826 provider.clone(),
827 )
828 .build()
829 .map_err(bad_certificate_data)?;
830 let config = ClientConfig::builder_with_provider(provider)
831 .with_safe_default_protocol_versions()
832 .map_err(tls_error)?
833 .dangerous()
834 .with_custom_certificate_verifier(Arc::new(AnyName(webpki)))
835 .with_no_client_auth();
836 Ok(Self::with_config(Arc::new(config)))
837 }
838
839 pub fn with_system_roots() -> io::Result<Self> {
861 let file = std::env::var_os("SSL_CERT_FILE");
862 let dirs = std::env::var_os("SSL_CERT_DIR");
863 #[cfg(target_os = "macos")]
864 if file.is_none() && dirs.is_none() {
865 let mut roots = RootCertStore::empty();
866 roots.add_parsable_certificates(keychain::trusted_roots());
867 if !roots.is_empty() {
868 return Self::from_roots(roots);
869 }
870 }
871 let roots = load_roots(
872 file.as_deref(),
873 dirs.as_deref(),
874 SYSTEM_CA_BUNDLES,
875 SYSTEM_CA_DIR,
876 )?;
877 Self::from_roots(roots)
878 }
879
880 #[cfg(feature = "webpki-roots")]
887 pub fn with_webpki_roots() -> Self {
888 let roots = RootCertStore {
889 roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
890 };
891 Self::from_roots(roots).expect("the webpki-roots crate provides roots")
892 }
893
894 pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
898 Arc::make_mut(&mut self.config).alpn_protocols =
899 protocols.iter().map(|p| p.to_vec()).collect();
900 self
901 }
902
903 pub fn client_auth(mut self, cert_chain: &[u8], private_key: &[u8]) -> io::Result<Self> {
906 let certs = pem_certs(cert_chain)?;
907 let key = PrivateKeyDer::from_pem_slice(private_key).map_err(bad_key)?;
908 let key = CertifiedKey::from_der(certs, key, self.config.crypto_provider())
909 .map_err(mismatched_key)?;
910 Arc::make_mut(&mut self.config).client_auth_cert_resolver =
911 Arc::new(ClientCert(Arc::new(key)));
912 Ok(self)
913 }
914
915 pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
918 self.handshake_timeout = timeout;
919 self
920 }
921
922 pub fn ktls(mut self, mode: Ktls) -> io::Result<Self> {
936 let early_data = self.config.enable_early_data;
937 self.ktls = ktls::Plan::new(mode, self.config.crypto_provider(), early_data)?;
938 let extract = self.ktls.tries();
939 if self.config.enable_secret_extraction != extract {
940 Arc::make_mut(&mut self.config).enable_secret_extraction = extract;
941 }
942 Ok(self)
943 }
944
945 pub fn ktls_unavailable(&self) -> Option<&str> {
948 self.ktls.unavailable()
949 }
950
951 pub async fn connect(&self, server_name: &str, tcp: TcpStream) -> io::Result<TlsStream> {
963 let name = parse_server_name(server_name)?;
964 let tcp = match &self.ktls {
965 ktls::Plan::Off => tcp,
966 ktls::Plan::Try { required } => {
967 let start = ktls::Start::Client(self.config.clone(), name.clone());
968 match ktls::handshake(tcp, start, self.handshake_timeout).await? {
969 ktls::Outcome::Kernel(tls) => return Ok(*tls),
970 ktls::Outcome::Declined(_, e) if *required => return Err(e),
971 ktls::Outcome::Declined(tcp, _) => {
972 self.ktls.stayed();
973 tcp
974 }
975 }
976 }
977 ktls::Plan::Unavailable(_) => {
978 self.ktls.stayed();
979 tcp
980 }
981 };
982 let conn = ClientConnection::new(self.config.clone(), name).map_err(tls_error)?;
983 TlsStream::new(tcp, conn.into())
984 .handshake(self.handshake_timeout, Duration::ZERO, None)
985 .await
986 }
987}
988
989impl std::fmt::Debug for TlsConnector {
990 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
991 f.debug_struct("TlsConnector")
992 .field("handshake_timeout", &self.handshake_timeout)
993 .field("ktls", &self.ktls)
994 .finish_non_exhaustive()
995 }
996}
997
998struct AnyName(Arc<rustls::client::WebPkiServerVerifier>);
1002
1003impl std::fmt::Debug for AnyName {
1004 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1005 f.write_str("AnyName")
1006 }
1007}
1008
1009impl rustls::client::danger::ServerCertVerifier for AnyName {
1010 fn verify_server_cert(
1011 &self,
1012 end_entity: &CertificateDer<'_>,
1013 intermediates: &[CertificateDer<'_>],
1014 server_name: &ServerName<'_>,
1015 ocsp_response: &[u8],
1016 now: rustls::pki_types::UnixTime,
1017 ) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
1018 use rustls::CertificateError;
1019 match self
1020 .0
1021 .verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)
1022 {
1023 Err(rustls::Error::InvalidCertificate(
1027 CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. },
1028 )) => Ok(rustls::client::danger::ServerCertVerified::assertion()),
1029 other => other,
1030 }
1031 }
1032
1033 fn verify_tls12_signature(
1034 &self,
1035 message: &[u8],
1036 cert: &CertificateDer<'_>,
1037 dss: &rustls::DigitallySignedStruct,
1038 ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
1039 self.0.verify_tls12_signature(message, cert, dss)
1040 }
1041
1042 fn verify_tls13_signature(
1043 &self,
1044 message: &[u8],
1045 cert: &CertificateDer<'_>,
1046 dss: &rustls::DigitallySignedStruct,
1047 ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
1048 self.0.verify_tls13_signature(message, cert, dss)
1049 }
1050
1051 fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
1052 self.0.supported_verify_schemes()
1053 }
1054}
1055
1056fn parse_server_name(name: &str) -> io::Result<ServerName<'static>> {
1058 let ipv6 = name
1059 .strip_prefix('[')
1060 .and_then(|n| n.strip_suffix(']'))
1061 .and_then(|n| n.parse::<std::net::Ipv6Addr>().ok());
1062 if let Some(ip) = ipv6 {
1063 return Ok(ServerName::IpAddress(std::net::IpAddr::V6(ip).into()));
1064 }
1065 ServerName::try_from(name.to_owned()).map_err(|_| {
1066 coded(
1067 Code::InvalidServerName,
1068 format!("{name:?} is neither a DNS name nor an IP address"),
1069 "pass the host name the certificate is for (\"example.com\"), or an IP address, \
1070 without a port or a scheme.",
1071 )
1072 })
1073}
1074
1075#[derive(Debug)]
1077struct ClientCert(Arc<CertifiedKey>);
1078
1079impl ResolvesClientCert for ClientCert {
1080 fn resolve(&self, _: &[&[u8]], _: &[SignatureScheme]) -> Option<Arc<CertifiedKey>> {
1081 Some(self.0.clone())
1082 }
1083
1084 fn has_certs(&self) -> bool {
1085 true
1086 }
1087}
1088
1089const SYSTEM_CA_BUNDLES: &[&str] = &[
1091 "/etc/ssl/certs/ca-certificates.crt",
1093 "/etc/pki/tls/certs/ca-bundle.crt",
1095 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
1096 "/etc/ssl/ca-bundle.pem",
1098 "/etc/ssl/cert.pem",
1100];
1101
1102const SYSTEM_CA_DIR: &str = "/etc/ssl/certs";
1104
1105fn load_roots(
1110 file: Option<&OsStr>,
1111 dirs: Option<&OsStr>,
1112 bundles: &[&str],
1113 dir: &str,
1114) -> io::Result<RootCertStore> {
1115 let mut roots = Roots {
1116 store: RootCertStore::empty(),
1117 seen: HashSet::new(),
1118 };
1119 if file.is_some() || dirs.is_some() {
1120 if let Some(file) = file {
1121 roots.add_file(Path::new(file)).map_err(|e| {
1122 io::Error::new(
1123 e.kind(),
1124 giong::error::Error::new(
1125 Code::BadCertificateData,
1126 format!("cannot read SSL_CERT_FILE {file:?}: {e}"),
1127 "point SSL_CERT_FILE at a readable PEM file of certificates, or unset \
1128 it to use the system's.",
1129 )
1130 .with_source(e),
1131 )
1132 })?;
1133 }
1134 for dir in dirs.map(std::env::split_paths).into_iter().flatten() {
1135 roots.add_dir(&dir);
1136 }
1137 } else if let Some(bundle) = bundles.iter().map(Path::new).find(|p| p.is_file()) {
1138 roots.add_file(bundle)?;
1139 } else {
1140 roots.add_dir(Path::new(dir));
1141 }
1142 if roots.store.is_empty() {
1143 return Err(coded(
1144 Code::NoTrustedRoots,
1145 "no trusted CA certificates found on this machine",
1146 "install the ca-certificates package, set SSL_CERT_FILE, or use \
1147 TlsConnector::with_webpki_roots (the webpki-roots feature of giong-tls).",
1148 ));
1149 }
1150 Ok(roots.store)
1151}
1152
1153struct Roots {
1154 store: RootCertStore,
1155 seen: HashSet<PathBuf>,
1158}
1159
1160impl Roots {
1161 fn add_file(&mut self, path: &Path) -> io::Result<()> {
1162 let real = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
1163 if !self.seen.insert(real) {
1164 return Ok(());
1165 }
1166 let pem = std::fs::read(path)?;
1167 let certs = CertificateDer::pem_slice_iter(&pem).filter_map(Result::ok);
1168 self.store.add_parsable_certificates(certs);
1169 Ok(())
1170 }
1171
1172 fn add_dir(&mut self, dir: &Path) {
1173 let Ok(entries) = std::fs::read_dir(dir) else {
1174 return;
1175 };
1176 let mut paths: Vec<PathBuf> = entries.filter_map(|e| Some(e.ok()?.path())).collect();
1177 paths.sort();
1178 for path in paths.iter().filter(|p| p.is_file()) {
1179 let _ = self.add_file(path);
1181 }
1182 }
1183}
1184
1185pub struct TlsStream {
1188 tcp: TcpStream,
1189 engine: RefCell<Engine>,
1191 plain: RefCell<Vec<u8>>,
1193 wire: RefCell<Vec<u8>>,
1196 established: Cell<bool>,
1200 eof: Cell<bool>,
1202 close_notify: Cell<bool>,
1205 sending: Cell<bool>,
1209 broken: Cell<bool>,
1212 closed: Cell<Option<Code>>,
1216 failed: Cell<Option<io::Error>>,
1218 waiters: RefCell<Vec<Waker>>,
1220 unsent: RefCell<Vec<u8>>,
1224}
1225
1226#[allow(clippy::large_enum_variant)]
1230enum Engine {
1231 User(Connection),
1233 Kernel(ktls::Kernel),
1236}
1237
1238struct Sending<'a> {
1242 stream: &'a TlsStream,
1243 complete: bool,
1244}
1245
1246impl Sending<'_> {
1247 fn done(mut self) {
1249 self.complete = true;
1250 }
1251}
1252
1253impl Drop for Sending<'_> {
1254 fn drop(&mut self) {
1255 if !self.complete {
1256 self.stream.broken.set(true);
1257 }
1258 self.stream.sending.set(false);
1259 self.stream.wake_waiters();
1260 }
1261}
1262
1263impl TlsStream {
1264 fn new(tcp: TcpStream, conn: Connection) -> Self {
1265 Self::with_engine(tcp, Engine::User(conn), Vec::new(), false)
1266 }
1267
1268 fn kernel(tcp: TcpStream, kernel: ktls::Kernel, plain: Vec<u8>, peer_closed: bool) -> Self {
1272 Self::with_engine(tcp, Engine::Kernel(kernel), plain, peer_closed)
1273 }
1274
1275 fn with_engine(tcp: TcpStream, engine: Engine, plain: Vec<u8>, peer_closed: bool) -> Self {
1276 Self {
1277 tcp,
1278 engine: RefCell::new(engine),
1279 plain: RefCell::new(plain),
1280 wire: RefCell::new(Vec::new()),
1281 established: Cell::new(false),
1282 eof: Cell::new(peer_closed),
1283 close_notify: Cell::new(peer_closed),
1284 sending: Cell::new(false),
1285 broken: Cell::new(false),
1286 closed: Cell::new(None),
1287 failed: Cell::new(None),
1288 waiters: RefCell::new(Vec::new()),
1289 unsent: RefCell::new(Vec::new()),
1290 }
1291 }
1292
1293 fn conn(&self) -> RefMut<'_, Connection> {
1296 RefMut::map(self.engine.borrow_mut(), |e| match e {
1297 Engine::User(c) => c,
1298 Engine::Kernel(_) => unreachable!("rustls' connection on a kernel TLS stream"),
1299 })
1300 }
1301
1302 pub fn is_ktls(&self) -> bool {
1306 matches!(*self.engine.borrow(), Engine::Kernel(_))
1307 }
1308
1309 async fn wait_for_sender(&self) {
1311 poll_fn(|cx| {
1312 if !self.sending.get() {
1313 return Poll::Ready(());
1314 }
1315 let mut waiters = self.waiters.borrow_mut();
1317 if !waiters.iter().any(|w| w.will_wake(cx.waker())) {
1318 waiters.push(cx.waker().clone());
1319 }
1320 Poll::Pending
1321 })
1322 .await;
1323 }
1324
1325 async fn lock_send(&self) -> Sending<'_> {
1328 while self.sending.get() {
1329 self.wait_for_sender().await;
1330 }
1331 self.sending.set(true);
1332 Sending {
1333 stream: self,
1334 complete: false,
1335 }
1336 }
1337
1338 async fn handshake(
1342 self,
1343 limit: Duration,
1344 spent: Duration,
1345 first: Option<giong::RecvBuf>,
1346 ) -> io::Result<Self> {
1347 let handshake = async {
1348 if let Some(first) = first {
1349 self.absorb(first).await?;
1350 }
1351 while self.conn().is_handshaking() {
1352 self.flush_tls().await?;
1353 if !self.conn().is_handshaking() {
1354 break;
1355 }
1356 if self.eof.get() {
1357 return Err(handshake_eof());
1358 }
1359 self.pump().await?;
1360 }
1361 if !self.hold_output() {
1362 self.flush_tls().await?;
1363 }
1364 self.established.set(true);
1365 Ok(())
1366 };
1367 match timeout(limit.saturating_sub(spent), handshake).await {
1368 Ok(Ok(())) => Ok(self),
1369 Ok(Err(e)) => Err(e),
1370 Err(_) => Err(handshake_timed_out(limit)),
1371 }
1372 }
1373
1374 fn wake_waiters(&self) {
1377 let waiters = mem::take(&mut *self.waiters.borrow_mut());
1378 for waker in waiters {
1379 waker.wake();
1380 }
1381 }
1382
1383 fn hold_output(&self) -> bool {
1397 if self.established.get() {
1398 return true;
1401 }
1402 let conn = self.conn();
1403 if conn.is_handshaking() {
1404 return false;
1405 }
1406 (matches!(*conn, Connection::Server(_))
1407 && conn.protocol_version() == Some(rustls::ProtocolVersion::TLSv1_3))
1408 }
1409
1410 fn take_wire(&self) -> Vec<u8> {
1414 let mut wire = mem::take(&mut *self.wire.borrow_mut());
1415 let mut unsent = self.unsent.borrow_mut();
1416 if unsent.capacity() > 0 {
1417 wire.extend_from_slice(&unsent);
1418 *unsent = Vec::new();
1420 }
1421 wire
1422 }
1423
1424 fn keep_wire(&self, mut wire: Vec<u8>) {
1428 if !wire.is_empty() && !self.broken.get() {
1429 self.unsent.borrow_mut().append(&mut wire);
1432 }
1433 if wire.capacity() <= WIRE_KEPT {
1434 wire.clear();
1435 *self.wire.borrow_mut() = wire;
1436 }
1437 }
1438
1439 fn cannot_send(&self) -> Option<io::Error> {
1442 if self.broken.get() {
1443 return Some(broken());
1444 }
1445 self.closed.get().map(sending_closed)
1446 }
1447
1448 async fn flush_tls(&self) -> io::Result<()> {
1452 loop {
1453 if !self.wants_send() {
1454 return Ok(());
1455 }
1456 if self.broken.get() {
1457 return Err(broken());
1458 }
1459 if self.sending.get() {
1460 self.wait_for_sender().await;
1463 continue;
1464 }
1465 let sending = self.lock_send().await;
1466 let mut wire = self.take_wire();
1467 let res = self.send_queued(&mut wire).await;
1468 self.keep_wire(wire);
1469 sending.done();
1470 res?;
1471 }
1472 }
1473
1474 async fn send_queued(&self, wire: &mut Vec<u8>) -> io::Result<()> {
1477 loop {
1478 {
1479 let mut conn = self.conn();
1480 while conn.wants_write() {
1481 conn.write_tls(wire)?;
1482 }
1483 }
1484 if wire.is_empty() {
1485 return Ok(());
1486 }
1487 self.send_wire(wire).await?;
1488 }
1489 }
1490
1491 fn wants_send(&self) -> bool {
1494 self.conn().wants_write() || !self.unsent.borrow().is_empty()
1495 }
1496
1497 fn flush_now(&self) -> io::Result<()> {
1509 if self.broken.get() {
1510 return Err(broken());
1511 }
1512 if self.sending.get() {
1513 return Ok(());
1514 }
1515 let mut unsent = self.unsent.borrow_mut();
1516 {
1517 let mut conn = self.conn();
1518 while conn.wants_write() {
1519 conn.write_tls(&mut *unsent)?;
1520 }
1521 }
1522 loop {
1523 let len = unsent.len().min(flush_room());
1525 if len == 0 {
1526 return Ok(());
1527 }
1528 let n = unsafe {
1530 libc::send(
1531 std::os::fd::AsRawFd::as_raw_fd(&self.tcp),
1532 unsent.as_ptr().cast(),
1533 len,
1534 libc::MSG_DONTWAIT | NO_SIGNAL,
1535 )
1536 };
1537 if n >= 0 {
1538 if n as usize == unsent.len() {
1539 *unsent = Vec::new();
1541 } else {
1542 unsent.drain(..n as usize);
1544 }
1545 return Ok(());
1546 }
1547 let e = io::Error::last_os_error();
1548 match e.kind() {
1549 io::ErrorKind::Interrupted => {}
1550 io::ErrorKind::WouldBlock => return Ok(()),
1551 _ if no_buffers(&e) => return Ok(()),
1554 _ => {
1555 self.broken.set(true);
1556 *unsent = Vec::new();
1557 return Err(e);
1558 }
1559 }
1560 }
1561 }
1562
1563 async fn send_wire(&self, wire: &mut Vec<u8>) -> io::Result<()> {
1567 let (res, mut sent) = self.tcp.write_all(mem::take(wire)).await;
1568 sent.clear();
1569 *wire = sent;
1570 if res.is_err() {
1571 self.broken.set(true);
1572 }
1573 res
1574 }
1575
1576 async fn send_plain(&self, wire: &mut Vec<u8>, data: &[u8], last: bool) -> io::Result<()> {
1588 let mut sent = 0;
1589 while sent < data.len() {
1590 let (carried, refused) = {
1591 let mut conn = self.conn();
1592 while conn.wants_write() {
1593 conn.write_tls(wire)?;
1594 }
1595 let carried = !wire.is_empty();
1596 let start = wire.len();
1597 let n = conn.writer().write(&data[sent..])?;
1598 while conn.wants_write() {
1599 conn.write_tls(wire)?;
1600 }
1601 sent += n;
1602 (carried, n > 0 && !has_application_data(&wire[start..]))
1607 };
1608 let more = sent < data.len() || !last;
1609 if !wire.is_empty() && (carried || refused || !more || wire.len() >= SEND_AT) {
1610 self.send_wire(wire).await?;
1611 }
1612 if carried {
1613 self.wake_waiters();
1615 }
1616 if refused {
1617 self.closed.set(Some(Code::TlsKeysExhausted));
1618 return Err(sending_closed(Code::TlsKeysExhausted));
1619 }
1620 }
1621 Ok(())
1622 }
1623
1624 async fn write_in_process(&self, pieces: &[&[u8]]) -> io::Result<()> {
1628 let sending = self.lock_send().await;
1629 if let Some(e) = self.cannot_send() {
1630 sending.done();
1631 return Err(e);
1632 }
1633 let mut wire = self.take_wire();
1634 let mut res = Ok(());
1635 for (i, piece) in pieces.iter().enumerate() {
1636 res = self
1637 .send_plain(&mut wire, piece, i + 1 == pieces.len())
1638 .await;
1639 if res.is_err() {
1640 break;
1641 }
1642 }
1643 if res.is_ok() && !wire.is_empty() {
1644 res = self.send_wire(&mut wire).await;
1646 }
1647 self.keep_wire(wire);
1648 sending.done();
1652 res
1653 }
1654
1655 async fn pump(&self) -> io::Result<()> {
1658 let ready = if !self.broken.get() && self.wants_send() {
1661 poll_fn(|cx| Poll::Ready(self.tcp.poll_recv(cx))).await
1662 } else {
1663 Poll::Pending
1664 };
1665 let chunk = match ready {
1666 Poll::Ready(chunk) => chunk?,
1667 Poll::Pending => {
1668 if !self.broken.get() && self.wants_send() {
1669 let _ = self.flush_for_recv().await;
1673 }
1674 self.tcp.recv().await?
1676 }
1677 };
1678 self.absorb(chunk).await
1679 }
1680
1681 async fn absorb(&self, chunk: giong::RecvBuf) -> io::Result<()> {
1685 if chunk.is_empty() {
1686 self.eof.set(true);
1687 return Ok(());
1688 }
1689 let result = {
1690 let mut conn = self.conn();
1691 let mut plain = self.plain.borrow_mut();
1692 let mut input = &chunk[..];
1693 let mut result = Ok(());
1694 while !input.is_empty() {
1695 match conn.read_tls(&mut input) {
1698 Ok(0) => {
1699 result = Err(coded(
1700 Code::TlsProtocol,
1701 "rustls accepted no more TLS data",
1702 "this is a bug in giong-tls; please report it at \
1703 https://github.com/giong-run/Giong/issues.",
1704 ));
1705 break;
1706 }
1707 Ok(_) => {}
1708 Err(e) => {
1709 result = Err(e);
1710 break;
1711 }
1712 }
1713 match conn.process_new_packets() {
1714 Ok(state) => {
1715 let n = state.plaintext_bytes_to_read();
1716 if n > 0 {
1717 let at = plain.len();
1718 plain.resize(at + n, 0);
1719 if let Err(e) = conn.reader().read_exact(&mut plain[at..]) {
1720 plain.truncate(at);
1721 result = Err(e);
1722 break;
1723 }
1724 }
1725 if state.peer_has_closed() {
1726 self.close_notify.set(true);
1727 self.eof.set(true);
1728 break;
1729 }
1730 }
1731 Err(e) => {
1732 result = Err(tls_error(e));
1733 break;
1734 }
1735 }
1736 }
1737 result
1738 };
1739 drop(chunk);
1740 if self.broken.get() || (result.is_ok() && self.hold_output()) {
1744 return result;
1745 }
1746 let flushed = self.flush_for_recv().await;
1747 result.and(flushed)
1748 }
1749
1750 async fn flush_for_recv(&self) -> io::Result<()> {
1756 if self.established.get() {
1757 self.flush_now()
1758 } else {
1759 self.flush_tls().await
1760 }
1761 }
1762
1763 pub async fn recv(&self) -> io::Result<Received> {
1782 if self.is_ktls() {
1783 return self.kernel_recv().await.map(Received);
1784 }
1785 self.user_recv().await.map(Received)
1786 }
1787
1788 async fn user_recv(&self) -> io::Result<Vec<u8>> {
1789 loop {
1790 {
1791 let mut plain = self.plain.borrow_mut();
1792 if !plain.is_empty() {
1793 return Ok(mem::take(&mut *plain));
1794 }
1795 }
1796 if let Some(e) = self.failed.take() {
1797 return Err(e);
1798 }
1799 if self.eof.get() {
1800 return Ok(Vec::new());
1801 }
1802 if let Err(e) = self.pump().await {
1803 if self.plain.borrow().is_empty() {
1805 return Err(e);
1806 }
1807 self.failed.set(Some(e));
1808 }
1809 }
1810 }
1811
1812 pub async fn write_all<B>(&self, buf: B) -> (io::Result<()>, B)
1833 where
1834 B: giong::IoBuf + AsRef<[u8]>,
1835 {
1836 if self.is_ktls() {
1837 return self.kernel_write_all(buf).await;
1838 }
1839 let res = self.write_in_process(&[buf.as_ref()]).await;
1840 (res, buf)
1841 }
1842
1843 pub async fn write_all_vectored<B>(&self, bufs: Vec<B>) -> (io::Result<()>, Vec<B>)
1855 where
1856 B: giong::IoBuf + AsRef<[u8]>,
1857 {
1858 if self.is_ktls() {
1859 return self.kernel_write_all_vectored(bufs).await;
1860 }
1861 let pieces: Vec<&[u8]> = bufs.iter().map(AsRef::as_ref).collect();
1862 let res = self.write_in_process(&pieces).await;
1863 drop(pieces);
1864 (res, bufs)
1865 }
1866
1867 pub async fn send_file(&self, file: &giong::fs::File, offset: u64, len: u64) -> io::Result<()> {
1884 if offset
1885 .checked_add(len)
1886 .map_or(true, |end| end > i64::MAX as u64)
1887 {
1888 return Err(file_too_short(offset, len, offset));
1889 }
1890 if self.is_ktls() {
1891 return self.kernel_send_file(file, offset, len).await;
1892 }
1893 let sending = self.lock_send().await;
1894 if let Some(e) = self.cannot_send() {
1895 sending.done();
1896 return Err(e);
1897 }
1898 let mut wire = self.take_wire();
1899 let res = self
1900 .send_file_in_process(&mut wire, file, offset, len)
1901 .await;
1902 self.keep_wire(wire);
1903 sending.done();
1904 res
1905 }
1906
1907 async fn send_file_in_process(
1910 &self,
1911 wire: &mut Vec<u8>,
1912 file: &giong::fs::File,
1913 offset: u64,
1914 len: u64,
1915 ) -> io::Result<()> {
1916 const PIECE: u64 = 256 * 1024;
1917 let mut buf = Vec::with_capacity(len.min(PIECE) as usize);
1918 let (mut at, mut left) = (offset, len);
1919 while left > 0 {
1920 let (res, b) = file.read_at(buf, at).await;
1921 buf = b;
1922 let n = match res {
1923 Ok(0) => return Err(file_too_short(offset, len, at)),
1924 Ok(n) => (n as u64).min(left) as usize,
1925 Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
1926 Err(e) => return Err(e),
1927 };
1928 self.send_plain(wire, &buf[..n], true).await?;
1929 at += n as u64;
1930 left -= n as u64;
1931 }
1932 Ok(())
1933 }
1934
1935 async fn send_closing(&self, wire: &mut Vec<u8>) -> io::Result<()> {
1942 {
1943 let mut conn = self.conn();
1944 while conn.wants_write() {
1945 conn.write_tls(wire)?;
1946 }
1947 }
1948 #[cfg(target_os = "linux")]
1952 const FLAGS: libc::c_int = libc::MSG_MORE | libc::MSG_DONTWAIT | libc::MSG_NOSIGNAL;
1953 #[cfg(target_os = "macos")]
1954 const FLAGS: libc::c_int = libc::MSG_DONTWAIT;
1955 let n = unsafe {
1957 libc::send(
1958 std::os::fd::AsRawFd::as_raw_fd(&self.tcp),
1959 wire.as_ptr().cast(),
1960 wire.len(),
1961 FLAGS,
1962 )
1963 };
1964 if n >= 0 {
1965 wire.drain(..n as usize);
1966 } else {
1967 let e = io::Error::last_os_error();
1968 if !matches!(
1971 e.kind(),
1972 io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted
1973 ) && !no_buffers(&e)
1974 {
1975 self.broken.set(true);
1976 wire.clear();
1977 return Err(e);
1978 }
1979 }
1980 if !wire.is_empty() {
1981 self.send_wire(wire).await?;
1982 }
1983 self.send_queued(wire).await
1984 }
1985
1986 pub async fn shutdown(&self) -> io::Result<()> {
2004 if self.is_ktls() {
2005 return self.kernel_shutdown().await;
2006 }
2007 let sending = self.lock_send().await;
2008 if self.cannot_send().is_none() {
2009 self.conn().send_close_notify();
2010 self.closed.set(Some(Code::TlsBroken));
2011 let mut wire = self.take_wire();
2012 let res = self.send_closing(&mut wire).await;
2013 self.keep_wire(wire);
2014 if let Err(e) = res {
2015 sending.done();
2017 let _ = self.tcp.shutdown(Shutdown::Write);
2018 return if self.peer_gone(&e) { Ok(()) } else { Err(e) };
2019 }
2020 }
2021 sending.done();
2022 self.tcp.shutdown(Shutdown::Write)
2023 }
2024
2025 fn peer_gone(&self, e: &io::Error) -> bool {
2028 matches!(
2029 e.kind(),
2030 io::ErrorKind::BrokenPipe | io::ErrorKind::ConnectionReset
2031 )
2032 }
2033
2034 pub fn received_close_notify(&self) -> bool {
2040 self.close_notify.get()
2041 }
2042
2043 pub fn alpn_protocol(&self) -> Option<Vec<u8>> {
2045 match &*self.engine.borrow() {
2046 Engine::User(c) => c.alpn_protocol().map(<[u8]>::to_vec),
2047 Engine::Kernel(k) => k.negotiated.alpn.clone(),
2048 }
2049 }
2050
2051 pub fn peer_certificates(&self) -> Option<Vec<CertificateDer<'static>>> {
2056 match &*self.engine.borrow() {
2057 Engine::User(c) => c.peer_certificates().map(<[_]>::to_vec),
2058 Engine::Kernel(k) => k.negotiated.peer_certificates.clone(),
2059 }
2060 }
2061
2062 pub fn resumed(&self) -> bool {
2065 match &*self.engine.borrow() {
2066 Engine::User(c) => c.handshake_kind() == Some(rustls::HandshakeKind::Resumed),
2067 Engine::Kernel(k) => k.negotiated.resumed,
2068 }
2069 }
2070
2071 pub fn tcp(&self) -> &TcpStream {
2078 &self.tcp
2079 }
2080}
2081
2082impl std::fmt::Debug for TlsStream {
2083 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2084 f.debug_struct("TlsStream")
2085 .field("tcp", &self.tcp)
2086 .field("ktls", &self.is_ktls())
2087 .finish_non_exhaustive()
2088 }
2089}
2090
2091#[cfg(test)]
2092mod tests {
2093 use super::*;
2094 use std::future::Future;
2095
2096 #[test]
2097 fn a_connector_without_trusted_authorities_is_refused() {
2098 let err = TlsConnector::from_roots(RootCertStore::empty()).unwrap_err();
2100 assert_eq!(err.kind(), io::ErrorKind::NotFound, "{err}");
2101 assert_eq!(
2102 giong::error::code(&err),
2103 Some(Code::NoTrustedRoots),
2104 "{err}"
2105 );
2106 }
2107
2108 fn authority(name: &str) -> (rcgen::Certificate, rcgen::KeyPair) {
2109 let key = rcgen::KeyPair::generate().unwrap();
2110 let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
2111 params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
2112 params
2113 .distinguished_name
2114 .push(rcgen::DnType::CommonName, name);
2115 (params.self_signed(&key).unwrap(), key)
2116 }
2117
2118 fn signed_by(
2119 ca: &rcgen::Certificate,
2120 ca_key: &rcgen::KeyPair,
2121 names: &[&str],
2122 expired: bool,
2123 ) -> CertificateDer<'static> {
2124 let key = rcgen::KeyPair::generate().unwrap();
2125 let names: Vec<String> = names.iter().map(|n| n.to_string()).collect();
2126 let mut params = rcgen::CertificateParams::new(names).unwrap();
2127 params.distinguished_name.push(
2129 rcgen::DnType::CommonName,
2130 "MySQL_Server_8.0.46_Auto_Generated_Server_Certificate",
2131 );
2132 if expired {
2133 params.not_before = rcgen::date_time_ymd(2020, 1, 1);
2134 params.not_after = rcgen::date_time_ymd(2021, 1, 1);
2135 }
2136 let cert = params.signed_by(&key, ca, ca_key).unwrap();
2137 CertificateDer::from(cert.der().to_vec())
2138 }
2139
2140 #[test]
2142 fn any_name_still_checks_the_chain() {
2143 use rustls::client::danger::ServerCertVerifier;
2144 use rustls::pki_types::UnixTime;
2145 use rustls::CertificateError;
2146
2147 let (ca, ca_key) = authority("ours");
2148 let mut roots = RootCertStore::empty();
2149 roots.add(CertificateDer::from(ca.der().to_vec())).unwrap();
2150 let webpki = rustls::client::WebPkiServerVerifier::builder_with_provider(
2151 Arc::new(roots),
2152 provider(),
2153 )
2154 .build()
2155 .unwrap();
2156 let verifier = AnyName(webpki);
2157 let name = ServerName::try_from("db.internal").unwrap();
2158 let check = |cert: &CertificateDer<'_>| {
2159 verifier.verify_server_cert(cert, &[], &name, &[], UnixTime::now())
2160 };
2161 for names in [&[][..], &["localhost"], &["db.internal"]] {
2163 check(&signed_by(&ca, &ca_key, names, false)).unwrap();
2164 }
2165 let e = check(&signed_by(&ca, &ca_key, &[], true)).unwrap_err();
2167 assert!(
2168 matches!(
2169 e,
2170 rustls::Error::InvalidCertificate(
2171 CertificateError::Expired | CertificateError::ExpiredContext { .. }
2172 )
2173 ),
2174 "{e:?}"
2175 );
2176 let (other, other_key) = authority("theirs");
2179 for cert in [
2180 signed_by(&other, &other_key, &["db.internal"], false),
2181 CertificateDer::from(other.der().to_vec()),
2182 ] {
2183 let e = check(&cert).unwrap_err();
2184 assert!(matches!(e, rustls::Error::InvalidCertificate(_)), "{e:?}");
2185 }
2186 assert!(check(&CertificateDer::from(ca.der().to_vec())).is_err());
2188 assert!(TlsConnector::with_root_pem_any_name(b"").is_err());
2190 assert!(TlsConnector::with_root_pem_any_name(
2191 b"-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n"
2192 )
2193 .is_err());
2194 assert!(TlsConnector::with_root_pem_any_name(ca.pem().as_bytes()).is_ok());
2195 }
2196
2197 fn client_hello(suites: &[u16], id_len: u8, keep: usize) -> Vec<u8> {
2200 let mut hello = vec![22, 3, 1, 0, 0, 1, 0, 0, 0, 3, 3];
2201 hello.extend_from_slice(&[7; 32]);
2202 hello.push(id_len);
2203 hello.extend(std::iter::repeat(9).take(id_len.into()));
2204 hello.extend_from_slice(&((suites.len() * 2) as u16).to_be_bytes());
2205 for suite in suites {
2206 hello.extend_from_slice(&suite.to_be_bytes());
2207 }
2208 hello.extend_from_slice(&[1, 0]); hello.truncate(keep);
2210 hello
2211 }
2212
2213 #[test]
2214 fn chacha20_first_clients_are_told_apart() {
2215 let all = usize::MAX;
2216 assert!(!prefers_chacha(&client_hello(
2218 &[0x1302, 0x1303, 0x1301],
2219 32,
2220 all
2221 )));
2222 assert!(!prefers_chacha(&client_hello(
2224 &[0x1301, 0x1302, 0x1303],
2225 0,
2226 all
2227 )));
2228 assert!(prefers_chacha(&client_hello(
2230 &[0x0a0a, 0x1303, 0x1301],
2231 32,
2232 all
2233 )));
2234 assert!(prefers_chacha(&client_hello(&[0xcca9, 0xc02b], 0, all)));
2236 assert!(!prefers_chacha(&client_hello(&[0xc02c, 0xcca9], 0, all)));
2237 assert!(!prefers_chacha(&client_hello(&[0x009c], 0, all)));
2239 let cut = client_hello(&[0x1303, 0x1301], 32, all).len() - 3;
2240 assert!(!prefers_chacha(&client_hello(&[0x1303, 0x1301], 32, cut)));
2241 assert!(!prefers_chacha(&client_hello(&[0x1303], 32, 40)));
2242 assert!(!prefers_chacha(&[]));
2243 let mut alert = client_hello(&[0x1303], 0, all);
2244 alert[0] = 21;
2245 assert!(!prefers_chacha(&alert));
2246 }
2247
2248 fn ca_pem(name: &str) -> String {
2249 let key = rcgen::KeyPair::generate().unwrap();
2250 let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
2251 params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
2252 params
2253 .distinguished_name
2254 .push(rcgen::DnType::CommonName, name);
2255 params.self_signed(&key).unwrap().pem()
2256 }
2257
2258 fn scratch(name: &str) -> PathBuf {
2260 let dir = std::env::temp_dir().join(format!("giong-tls-{}-{name}", std::process::id()));
2261 let _ = std::fs::remove_dir_all(&dir);
2262 std::fs::create_dir_all(&dir).unwrap();
2263 dir
2264 }
2265
2266 fn os(path: &Path) -> &OsStr {
2267 path.as_os_str()
2268 }
2269
2270 #[test]
2271 fn server_names_are_dns_names_or_ip_addresses() {
2272 let dns = |n: &str| matches!(parse_server_name(n), Ok(ServerName::DnsName(_)));
2273 let ip = |n: &str| matches!(parse_server_name(n), Ok(ServerName::IpAddress(_)));
2274 assert!(dns("example.com"));
2275 assert!(dns("db.prod.svc.cluster.local"));
2276 assert!(ip("10.0.0.1"));
2277 assert!(ip("::1"));
2278 assert!(ip("[::1]"));
2279 for bad in ["", "not a name", "[nope]", "[10.0.0.1]", "a..b"] {
2280 let err = parse_server_name(bad).unwrap_err();
2281 assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{bad:?}");
2282 }
2283 }
2284
2285 #[test]
2286 fn the_first_bundle_that_exists_is_read() {
2287 let dir = scratch("bundle");
2288 let bundle = dir.join("bundle.pem");
2289 let two = format!("{}{}", ca_pem("one"), ca_pem("two"));
2290 std::fs::write(&bundle, two).unwrap();
2291 let missing = dir.join("missing.pem");
2292 let bundles = [missing.to_str().unwrap(), bundle.to_str().unwrap()];
2293 let roots = load_roots(None, None, &bundles, "/nonexistent").unwrap();
2294 assert_eq!(roots.len(), 2);
2295 std::fs::remove_dir_all(dir).unwrap();
2296 }
2297
2298 #[test]
2299 fn ssl_cert_file_and_dir_replace_the_system_locations() {
2300 let dir = scratch("env");
2301 let file = dir.join("file.pem");
2302 std::fs::write(&file, ca_pem("from file")).unwrap();
2303 let certs = dir.join("certs");
2304 std::fs::create_dir(&certs).unwrap();
2305 std::fs::write(certs.join("a.pem"), ca_pem("a")).unwrap();
2306 std::fs::write(certs.join("b.pem"), ca_pem("b")).unwrap();
2307 std::fs::write(certs.join("README"), "not a certificate").unwrap();
2308 std::os::unix::fs::symlink(certs.join("a.pem"), certs.join("1a2b3c4d.0")).unwrap();
2310 let system = dir.join("system.pem");
2311 std::fs::write(&system, ca_pem("system")).unwrap();
2312 let bundles = [system.to_str().unwrap()];
2313
2314 let roots = load_roots(Some(os(&file)), None, &bundles, "/nonexistent").unwrap();
2315 assert_eq!(roots.len(), 1, "SSL_CERT_FILE only");
2316 let roots = load_roots(None, Some(os(&certs)), &bundles, "/nonexistent").unwrap();
2317 assert_eq!(roots.len(), 2, "SSL_CERT_DIR only, each file once");
2318 let both = std::env::join_paths([dir.join("nowhere"), certs.clone()]).unwrap();
2319 let roots = load_roots(Some(os(&file)), Some(&both), &bundles, "/nonexistent").unwrap();
2320 assert_eq!(roots.len(), 3, "both, with a missing directory in the list");
2321
2322 let err = load_roots(Some(os(&dir.join("gone.pem"))), None, &bundles, "").unwrap_err();
2323 assert_eq!(err.kind(), io::ErrorKind::NotFound);
2324 assert!(err.to_string().contains("SSL_CERT_FILE"), "{err}");
2325 std::fs::remove_dir_all(dir).unwrap();
2326 }
2327
2328 #[test]
2329 fn without_a_bundle_the_directory_is_read_and_nothing_is_an_error() {
2330 let dir = scratch("dir");
2331 std::fs::write(dir.join("only.crt"), ca_pem("only")).unwrap();
2332 let roots = load_roots(
2333 None,
2334 None,
2335 &["/nonexistent/bundle.crt"],
2336 dir.to_str().unwrap(),
2337 );
2338 assert_eq!(roots.unwrap().len(), 1);
2339
2340 let empty = scratch("empty");
2341 let err = load_roots(None, None, &[], empty.to_str().unwrap()).unwrap_err();
2342 assert_eq!(err.kind(), io::ErrorKind::NotFound);
2343 assert!(err.to_string().contains("webpki-roots"), "{err}");
2344 std::fs::remove_dir_all(dir).unwrap();
2345 std::fs::remove_dir_all(empty).unwrap();
2346 }
2347
2348 #[test]
2349 fn records_are_scanned_for_application_data() {
2350 let record = |typ: u8, len: u16| {
2352 let mut r = vec![typ, 3, 3];
2353 r.extend_from_slice(&len.to_be_bytes());
2354 r.resize(5 + len as usize, 0xAA);
2355 r
2356 };
2357 assert!(!has_application_data(&[]));
2358 assert!(!has_application_data(&record(21, 26)));
2359 assert!(has_application_data(&record(23, 0)));
2360 let mut alert_then_data = record(21, 26);
2361 alert_then_data.extend(record(23, 300));
2362 assert!(has_application_data(&alert_then_data));
2363 let mut alert = record(21, 26);
2365 alert[5] = 23;
2366 assert!(!has_application_data(&alert));
2367 }
2368
2369 #[test]
2370 fn secrets_are_extractable_only_when_the_kernel_will_take_them() {
2371 let key = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
2372 let (cert, key) = (key.cert.pem(), key.key_pair.serialize_pem());
2373 for mode in [Ktls::Off, Ktls::Auto] {
2374 let acceptor = TlsAcceptor::with_certificates(
2375 &Certificates::from_pem(cert.as_bytes(), key.as_bytes()).unwrap(),
2376 )
2377 .unwrap()
2378 .ktls(mode)
2379 .unwrap();
2380 let tries = acceptor.ktls.tries();
2381 assert_eq!(acceptor.config.enable_secret_extraction, tries, "{mode:?}");
2382 let connector = TlsConnector::with_root_pem(cert.as_bytes())
2383 .unwrap()
2384 .ktls(mode)
2385 .unwrap();
2386 let tries = connector.ktls.tries();
2387 assert_eq!(connector.config.enable_secret_extraction, tries, "{mode:?}");
2388 }
2389 }
2390
2391 #[test]
2392 fn this_machines_roots_load() {
2393 TlsConnector::with_system_roots().unwrap();
2395 }
2396
2397 #[cfg(feature = "webpki-roots")]
2398 #[test]
2399 fn mozillas_roots_are_compiled_in() {
2400 TlsConnector::with_webpki_roots();
2401 }
2402
2403 #[test]
2404 fn records_a_receive_could_not_send_whole_go_out_first_and_in_order() {
2405 let key = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
2411 let cert = key.cert.pem();
2412 let acceptor = TlsAcceptor::with_certificates(
2413 &Certificates::from_pem(cert.as_bytes(), key.key_pair.serialize_pem().as_bytes())
2414 .unwrap(),
2415 )
2416 .unwrap();
2417 let connector = TlsConnector::with_root_pem(cert.as_bytes()).unwrap();
2418 giong::block_on(async move {
2419 let listener = giong::net::TcpListener::bind("127.0.0.1:0").unwrap();
2420 let addr = listener.local_addr().unwrap();
2421 let server = giong::spawn(async move {
2422 let tcp = listener.accept().await.unwrap();
2423 let tls = acceptor.accept(tcp).await.unwrap();
2424 assert!(tls.conn().wants_write(), "tickets wait for the first send");
2425 FLUSH_ROOM.set(1);
2426 let mut left = None;
2427 for _ in 0..5 {
2428 let mut recv = std::pin::pin!(tls.recv());
2429 let ready = poll_fn(|cx| Poll::Ready(recv.as_mut().poll(cx).is_ready())).await;
2430 assert!(!ready);
2431 let unsent = tls.unsent.borrow().len();
2432 assert!(
2433 left.map_or(unsent > 0, |l| unsent + 1 == l),
2434 "{left:?} {unsent}"
2435 );
2436 left = Some(unsent);
2437 }
2438 FLUSH_ROOM.set(usize::MAX);
2439 tls.write_all(&b"after the tickets"[..]).await.0.unwrap();
2440 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 let mut got = Vec::new();
2448 loop {
2449 let data = tls.recv().await.unwrap();
2450 if data.is_empty() {
2451 break;
2452 }
2453 got.extend_from_slice(&data);
2454 }
2455 assert_eq!(got, b"after the tickets");
2456 assert!(tls.received_close_notify());
2457 server.await.unwrap();
2458 });
2459 }
2460
2461 #[test]
2462 fn a_receive_that_sent_what_was_owed_keeps_no_buffer_for_it() {
2463 let key = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
2467 let cert = key.cert.pem();
2468 let acceptor = TlsAcceptor::with_certificates(
2469 &Certificates::from_pem(cert.as_bytes(), key.key_pair.serialize_pem().as_bytes())
2470 .unwrap(),
2471 )
2472 .unwrap();
2473 let connector = TlsConnector::with_root_pem(cert.as_bytes()).unwrap();
2474 giong::block_on(async move {
2475 let listener = giong::net::TcpListener::bind("127.0.0.1:0").unwrap();
2476 let addr = listener.local_addr().unwrap();
2477 let server = giong::spawn(async move {
2478 let tcp = listener.accept().await.unwrap();
2479 let tls = acceptor.accept(tcp).await.unwrap();
2480 assert!(tls.conn().wants_write(), "tickets wait for the first send");
2481 let mut recv = std::pin::pin!(tls.recv());
2484 let ready = poll_fn(|cx| Poll::Ready(recv.as_mut().poll(cx).is_ready())).await;
2485 assert!(!ready);
2486 assert!(!tls.conn().wants_write());
2487 assert_eq!(tls.unsent.borrow().capacity(), 0);
2488 tls.shutdown().await.unwrap();
2489 });
2490 let tcp = TcpStream::connect(addr).await.unwrap();
2491 let tls = connector.connect("localhost", tcp).await.unwrap();
2492 assert!(tls.recv().await.unwrap().is_empty());
2493 assert!(tls.received_close_notify());
2494 server.await.unwrap();
2495 });
2496 }
2497
2498 #[test]
2499 fn the_key_exchange_offers_post_quantum_first_with_the_feature() {
2500 let first = provider().kx_groups[0].name();
2501 let pq = rustls::NamedGroup::X25519MLKEM768;
2502 assert_eq!(first == pq, cfg!(feature = "post-quantum"), "{first:?}");
2503 assert_eq!(provider_aes128_first().kx_groups[0].name(), first);
2504 }
2505}