1#![warn(missing_docs)]
80
81mod certs;
82#[cfg(target_os = "macos")]
83mod keychain;
84mod ktls;
85mod received;
86mod sys;
87mod user;
88#[cfg(windows)]
89mod winstore;
90
91pub use certs::Certificates;
92pub use ktls::{ktls_stats, ktls_support, Ktls, KtlsStats, KtlsSupport};
93pub use received::Received;
94pub use rustls_pki_types::CertificateDer;
97
98#[cfg(fuzzing)]
101#[doc(hidden)]
102pub mod fuzzing {
103 pub use crate::ktls::{check_handshake_messages, check_record_framing};
104}
105
106use std::cell::{Cell, RefCell, RefMut};
107use std::collections::HashSet;
108use std::ffi::OsStr;
109use std::future::{poll_fn, Future};
110use std::io;
111use std::mem;
112use std::net::Shutdown;
113use std::path::{Path, PathBuf};
114use std::sync::Arc;
115use std::task::{Poll, Waker};
116use std::time::Duration;
117
118use giong::error::Code;
119use giong::net::TcpStream;
120use giong::time::timeout;
121use rustls::client::ResolvesClientCert;
122use rustls::client::UnbufferedClientConnection;
123use rustls::pki_types::pem::PemObject;
124use rustls::pki_types::{PrivateKeyDer, ServerName};
125use rustls::server::UnbufferedServerConnection;
126use rustls::sign::CertifiedKey;
127use rustls::{ClientConfig, RootCertStore, ServerConfig, SignatureScheme};
128use user::User;
129
130#[cfg(feature = "unstable-rustls")]
136pub use rustls;
137
138fn coded(
139 code: Code,
140 message: impl Into<std::borrow::Cow<'static, str>>,
141 fix: &'static str,
142) -> io::Error {
143 giong::error::Error::new(code, message, fix).into()
144}
145
146fn file_too_short(offset: u64, len: u64, at: u64) -> io::Error {
149 let end = offset.saturating_add(len);
150 coded(
151 Code::FileTooShort,
152 format!(
153 "the file ended at byte {at}, {} bytes short of the {len} send_file was asked to send",
154 end - at
155 ),
156 "take the length from the open file (File::len), and replace a file that is being \
157 served by renaming a new one over it, not by rewriting it; the peer has fewer bytes \
158 than announced, so close the connection.",
159 )
160}
161
162pub(crate) fn bad_certificate_data(e: impl std::fmt::Display) -> io::Error {
164 coded(
165 Code::BadCertificateData,
166 e.to_string(),
167 "check that the file or data is PEM (\"-----BEGIN CERTIFICATE-----\") and holds \
168 at least one certificate.",
169 )
170}
171
172pub(crate) fn bad_key(e: impl std::fmt::Display) -> io::Error {
174 coded(
175 Code::BadCertificateData,
176 format!("cannot read the private key: {e}"),
177 "check that it is a PEM private key (\"-----BEGIN PRIVATE KEY-----\", or the RSA or \
178 EC forms).",
179 )
180}
181
182pub(crate) fn mismatched_key(e: rustls::Error) -> io::Error {
184 coded(
185 Code::BadCertificateData,
186 format!("the certificate and the private key cannot be used together: {e}"),
187 "check that the key belongs to the first certificate of the chain, and that its type \
188 (RSA, ECDSA, Ed25519) is supported.",
189 )
190}
191
192fn read_error(e: user::ReadError) -> io::Error {
195 match e {
196 user::ReadError::Tls(e) => tls_error(e),
197 user::ReadError::TooLarge => coded(
198 Code::TlsProtocol,
199 "the peer sent more TLS data than a record or a handshake message may hold \
200 before it could be processed",
201 "check that the other side speaks TLS on this port.",
202 ),
203 user::ReadError::EarlyData => coded(
204 Code::TlsProtocol,
205 "the client sent 0-RTT (early) data, which giong-tls does not accept",
206 "set max_early_data_size to 0 in the rustls ServerConfig given to \
207 TlsAcceptor::from_rustls: 0-RTT data can be replayed.",
208 ),
209 }
210}
211
212fn tls_error(e: rustls::Error) -> io::Error {
213 match e {
214 rustls::Error::InvalidCertificate(_) if e.to_string().contains("CaUsedAsEndEntity") => {
217 coded(
218 Code::TlsCertificate,
219 "the peer's certificate was rejected: it is marked as a certificate authority \
220 (basicConstraints CA:TRUE), and an authority's certificate cannot be the \
221 peer's own (CaUsedAsEndEntity)",
222 "issue the peer's certificate with CA:FALSE: a self-signed one made with \
223 `openssl req -x509` needs -addext \"basicConstraints=critical,CA:FALSE\"; or \
224 have the authority sign a separate certificate for the peer.",
225 )
226 }
227 rustls::Error::InvalidCertificate(_) => coded(
228 Code::TlsCertificate,
229 format!("the peer's certificate was rejected: {e}"),
230 "check the name you connect to, the certificate's expiry and its chain; a \
231 private authority has to be trusted with TlsConnector::with_root_pem.",
232 ),
233 e => coded(
234 Code::TlsProtocol,
235 format!("TLS error: {e}"),
236 "check that the other side speaks TLS on this port, and that both sides share a \
237 protocol version and cipher suite.",
238 ),
239 }
240}
241
242const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
244
245fn handshake_timed_out(limit: Duration) -> io::Error {
246 coded(
247 Code::TlsHandshakeTimeout,
248 format!("the TLS handshake did not finish within {limit:?}"),
249 "check that the other side speaks TLS on this port and is not overloaded, or raise \
250 handshake_timeout.",
251 )
252}
253
254fn handshake_eof() -> io::Error {
255 coded(
256 Code::TlsHandshakeEof,
257 "the peer closed the connection during the TLS handshake",
258 "check that the other side speaks TLS on this port, and whether it wants a client \
259 certificate or another server name.",
260 )
261}
262
263const WIRE_KEPT: usize = 16 * 1024;
268
269const SPARE_WIRES_KEPT: usize = 4;
272
273thread_local! {
274 static SPARE_WIRES: RefCell<Vec<Vec<u8>>> = const { RefCell::new(Vec::new()) };
278}
279
280const SEND_AT: usize = 64 * 1024;
283
284const ENCRYPT_AT: usize = 64 * 1024;
287
288#[cfg(test)]
289thread_local! {
290 static FLUSH_ROOM: Cell<usize> = const { Cell::new(usize::MAX) };
293}
294
295fn flush_room() -> usize {
298 #[cfg(test)]
299 return FLUSH_ROOM.with(Cell::get);
300 #[cfg(not(test))]
301 usize::MAX
302}
303
304fn sending_closed(code: Code) -> io::Error {
307 match code {
308 Code::TlsKeysExhausted => coded(
309 Code::TlsKeysExhausted,
310 "this connection has sent as many TLS records as its cipher allows under one key, \
311 and cannot change keys (TLS 1.2, or TLS 1.3 on a kernel older than 6.14); \
312 close_notify was sent",
313 "open a new connection. TLS 1.3 changes keys instead (in the process, and with \
314 kernel TLS on Linux 6.14 or newer).",
315 ),
316 _ => coded(
317 Code::TlsBroken,
318 "this TLS stream has been shut down or ended with an alert; nothing more can be sent",
319 "open a new connection.",
320 ),
321 }
322}
323
324fn broken() -> io::Error {
325 coded(
326 Code::TlsBroken,
327 "a TLS write failed or was cancelled; nothing more can be sent",
328 "open a new connection. A write cancelled half-way (a dropped future, a timeout) \
329 leaves a partial record or message behind, so the stream cannot go on.",
330 )
331}
332
333#[inline]
338fn no_buffers(e: &io::Error) -> bool {
339 cfg!(target_os = "macos") && e.raw_os_error() == Some(libc::ENOBUFS)
340}
341
342pub(crate) fn pem_certs(pem: &[u8]) -> io::Result<Vec<CertificateDer<'static>>> {
344 let certs = CertificateDer::pem_slice_iter(pem)
345 .collect::<Result<Vec<_>, _>>()
346 .map_err(bad_certificate_data)?;
347 if certs.is_empty() {
348 return Err(bad_certificate_data("no certificate found in the PEM data"));
349 }
350 Ok(certs)
351}
352
353pub(crate) fn provider() -> Arc<rustls::crypto::CryptoProvider> {
357 Arc::new(base_provider())
358}
359
360#[cfg(not(feature = "post-quantum"))]
361fn base_provider() -> rustls::crypto::CryptoProvider {
362 rustls::crypto::ring::default_provider()
363}
364
365#[cfg(feature = "post-quantum")]
366fn base_provider() -> rustls::crypto::CryptoProvider {
367 rustls::crypto::aws_lc_rs::default_provider()
368}
369
370fn provider_aes128_first() -> Arc<rustls::crypto::CryptoProvider> {
380 use rustls::CipherSuite as S;
381 let mut provider = base_provider();
382 provider.cipher_suites.sort_by_key(|suite| {
385 let rank = match suite.suite() {
386 S::TLS13_AES_128_GCM_SHA256
387 | S::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
388 | S::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 => 0,
389 S::TLS13_CHACHA20_POLY1305_SHA256
390 | S::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
391 | S::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 => 1,
392 _ => 2,
393 };
394 (
395 suite.version().version != rustls::ProtocolVersion::TLSv1_3,
396 rank,
397 )
398 });
399 Arc::new(provider)
400}
401
402fn prefers_chacha(hello: &[u8]) -> bool {
410 const SESSION_ID: usize = 5 + 4 + 2 + 32;
412 if hello.first() != Some(&22) || hello.get(5) != Some(&1) {
413 return false;
414 }
415 let Some(&id_len) = hello.get(SESSION_ID) else {
416 return false;
417 };
418 let at = SESSION_ID + 1 + usize::from(id_len);
419 let Some(len) = hello.get(at..at + 2) else {
420 return false;
421 };
422 let len = usize::from(u16::from_be_bytes([len[0], len[1]]));
423 let Some(suites) = hello.get(at + 2..at + 2 + len) else {
424 return false;
425 };
426 for suite in suites.chunks_exact(2) {
427 match [suite[0], suite[1]] {
428 [0x13, 0x01]
431 | [0x13, 0x02]
432 | [0xc0, 0x2b]
433 | [0xc0, 0x2f]
434 | [0xc0, 0x2c]
435 | [0xc0, 0x30] => return false,
436 [0x13, 0x03] | [0xcc, 0xa9] | [0xcc, 0xa8] => return true,
438 _ => {}
439 }
440 }
441 false
442}
443
444fn server_configs(
449 certificates: &Certificates,
450 verifier: Arc<dyn rustls::server::danger::ClientCertVerifier>,
451) -> io::Result<(ServerConfig, ServerConfig)> {
452 let mut config = ServerConfig::builder_with_provider(provider_aes128_first())
453 .with_safe_default_protocol_versions()
454 .map_err(tls_error)?
455 .with_client_cert_verifier(verifier)
456 .with_cert_resolver(certificates.resolver());
457 let chacha = config.clone();
458 config.ignore_client_order = true;
459 Ok((config, chacha))
460}
461
462#[derive(Clone)]
466pub struct TlsAcceptor {
467 config: Arc<ServerConfig>,
468 chacha: Option<Arc<ServerConfig>>,
473 handshake_timeout: Duration,
474 ktls: ktls::Plan,
475 certificates: Option<Certificates>,
479}
480
481impl TlsAcceptor {
482 #[cfg(feature = "unstable-rustls")]
490 pub fn from_rustls(config: Arc<ServerConfig>) -> Self {
491 Self::with_config(config)
492 }
493
494 fn with_config(config: Arc<ServerConfig>) -> Self {
495 Self {
496 config,
497 chacha: None,
498 handshake_timeout: HANDSHAKE_TIMEOUT,
499 ktls: ktls::Plan::Off,
500 certificates: None,
501 }
502 }
503
504 pub fn with_certificates(certificates: &Certificates) -> io::Result<Self> {
529 let verifier = rustls::server::WebPkiClientVerifier::no_client_auth();
530 let (config, chacha) = server_configs(certificates, verifier)?;
531 Ok(Self {
532 chacha: Some(Arc::new(chacha)),
533 certificates: Some(certificates.clone()),
534 ..Self::with_config(Arc::new(config))
535 })
536 }
537
538 pub fn require_client_cert(self, ca_pem: &[u8]) -> io::Result<Self> {
548 self.client_auth(ca_pem, true)
549 }
550
551 pub fn request_client_cert(self, ca_pem: &[u8]) -> io::Result<Self> {
558 self.client_auth(ca_pem, false)
559 }
560
561 fn client_auth(mut self, ca_pem: &[u8], required: bool) -> io::Result<Self> {
562 let Some(certificates) = &self.certificates else {
563 return Err(coded(
564 Code::TlsConfig,
565 "client certificates cannot be set on an acceptor made with from_rustls",
566 "set client authentication in the rustls configuration given to from_rustls \
567 (ServerConfig::builder().with_client_cert_verifier), or make the acceptor \
568 with with_certificates.",
569 ));
570 };
571 let mut roots = RootCertStore::empty();
572 for cert in pem_certs(ca_pem)? {
573 roots.add(cert).map_err(bad_certificate_data)?;
574 }
575 let builder = rustls::server::WebPkiClientVerifier::builder_with_provider(
576 Arc::new(roots),
577 self.config.crypto_provider().clone(),
578 );
579 let builder = if required {
580 builder
581 } else {
582 builder.allow_unauthenticated()
583 };
584 let verifier = builder.build().map_err(bad_certificate_data)?;
585 let (mut config, mut chacha) = server_configs(certificates, verifier)?;
586 for new in [&mut config, &mut chacha] {
588 new.alpn_protocols = self.config.alpn_protocols.clone();
589 new.enable_secret_extraction = self.config.enable_secret_extraction;
590 }
591 self.config = Arc::new(config);
592 self.chacha = Some(Arc::new(chacha));
593 Ok(self)
594 }
595
596 fn config_for(&self, hello: &[u8]) -> Arc<ServerConfig> {
599 match &self.chacha {
600 Some(chacha) if prefers_chacha(hello) => chacha.clone(),
601 _ => self.config.clone(),
602 }
603 }
604
605 fn change_config(&mut self, change: impl Fn(&mut ServerConfig)) {
607 change(Arc::make_mut(&mut self.config));
608 if let Some(chacha) = &mut self.chacha {
609 change(Arc::make_mut(chacha));
610 }
611 }
612
613 pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
621 let protocols: Vec<Vec<u8>> = protocols.iter().map(|p| p.to_vec()).collect();
622 self.change_config(|config| config.alpn_protocols = protocols.clone());
623 self
624 }
625
626 pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
629 self.handshake_timeout = timeout;
630 self
631 }
632
633 pub fn ktls(mut self, mode: Ktls) -> io::Result<Self> {
660 let early_data = self.config.max_early_data_size > 0;
661 self.ktls = ktls::Plan::new(mode, self.config.crypto_provider(), early_data)?;
662 let extract = self.ktls.tries();
664 if self.config.enable_secret_extraction != extract {
665 self.change_config(|config| config.enable_secret_extraction = extract);
666 }
667 Ok(self)
668 }
669
670 pub fn ktls_unavailable(&self) -> Option<&str> {
675 self.ktls.unavailable()
676 }
677
678 pub async fn accept(&self, tcp: TcpStream) -> io::Result<TlsStream> {
687 let tcp = match &self.ktls {
688 ktls::Plan::Off => tcp,
689 ktls::Plan::Try { required } => {
690 let start = ktls::Start::Server(self.config.clone(), self.chacha.clone());
691 match ktls::handshake(tcp, start, self.handshake_timeout).await? {
692 ktls::Outcome::Kernel(tls) => return Ok(*tls),
693 ktls::Outcome::Declined(_, e) if *required => return Err(e),
694 ktls::Outcome::Declined(tcp, _) => {
695 self.ktls.stayed();
696 tcp
697 }
698 }
699 }
700 ktls::Plan::Unavailable(_) => {
701 self.ktls.stayed();
702 tcp
703 }
704 };
705 let Some(_) = &self.chacha else {
706 let conn = UnbufferedServerConnection::new(self.config.clone())
707 .and_then(User::server)
708 .map_err(tls_error)?;
709 return TlsStream::new(tcp, conn)
710 .handshake(self.handshake_timeout, Duration::ZERO, None)
711 .await;
712 };
713 let started = std::time::Instant::now();
716 let first = match timeout(self.handshake_timeout, tcp.recv()).await {
717 Ok(first) => first?,
718 Err(_) => return Err(handshake_timed_out(self.handshake_timeout)),
719 };
720 if first.is_empty() {
721 return Err(handshake_eof());
722 }
723 let conn = UnbufferedServerConnection::new(self.config_for(&first))
724 .and_then(User::server)
725 .map_err(tls_error)?;
726 TlsStream::new(tcp, conn)
727 .handshake(self.handshake_timeout, started.elapsed(), Some(first))
728 .await
729 }
730}
731
732impl std::fmt::Debug for TlsAcceptor {
733 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
734 f.debug_struct("TlsAcceptor")
735 .field("handshake_timeout", &self.handshake_timeout)
736 .field("ktls", &self.ktls)
737 .finish_non_exhaustive()
738 }
739}
740
741#[derive(Clone)]
762pub struct TlsConnector {
763 config: Arc<ClientConfig>,
764 handshake_timeout: Duration,
765 ktls: ktls::Plan,
766}
767
768impl TlsConnector {
769 #[cfg(feature = "unstable-rustls")]
777 pub fn from_rustls(config: Arc<ClientConfig>) -> Self {
778 Self::with_config(config)
779 }
780
781 fn with_config(config: Arc<ClientConfig>) -> Self {
782 Self {
783 config,
784 handshake_timeout: HANDSHAKE_TIMEOUT,
785 ktls: ktls::Plan::Off,
786 }
787 }
788
789 fn from_roots(roots: RootCertStore) -> io::Result<Self> {
790 if roots.is_empty() {
791 return Err(coded(
792 Code::NoTrustedRoots,
793 "no trusted certificate authority given",
794 "pass at least one certificate, or use TlsConnector::with_system_roots.",
795 ));
796 }
797 let config = ClientConfig::builder_with_provider(provider())
798 .with_safe_default_protocol_versions()
799 .map_err(tls_error)?
800 .with_root_certificates(roots)
801 .with_no_client_auth();
802 Ok(Self::with_config(Arc::new(config)))
803 }
804
805 pub fn with_root_pem(pem: &[u8]) -> io::Result<Self> {
814 let mut roots = RootCertStore::empty();
815 for cert in pem_certs(pem)? {
816 roots.add(cert).map_err(bad_certificate_data)?;
817 }
818 Self::from_roots(roots)
819 }
820
821 pub fn with_root_pem_any_name(pem: &[u8]) -> io::Result<Self> {
833 let mut roots = RootCertStore::empty();
834 for cert in pem_certs(pem)? {
835 roots.add(cert).map_err(bad_certificate_data)?;
836 }
837 if roots.is_empty() {
838 return Err(coded(
839 Code::NoTrustedRoots,
840 "no trusted certificate authority given",
841 "pass at least one certificate authority in PEM form.",
842 ));
843 }
844 let provider = provider();
845 let webpki = rustls::client::WebPkiServerVerifier::builder_with_provider(
846 Arc::new(roots),
847 provider.clone(),
848 )
849 .build()
850 .map_err(bad_certificate_data)?;
851 let config = ClientConfig::builder_with_provider(provider)
852 .with_safe_default_protocol_versions()
853 .map_err(tls_error)?
854 .dangerous()
855 .with_custom_certificate_verifier(Arc::new(AnyName(webpki)))
856 .with_no_client_auth();
857 Ok(Self::with_config(Arc::new(config)))
858 }
859
860 pub fn with_system_roots() -> io::Result<Self> {
890 let file = std::env::var_os("SSL_CERT_FILE");
891 let dirs = std::env::var_os("SSL_CERT_DIR");
892 #[cfg(any(target_os = "macos", windows))]
893 if file.is_none() && dirs.is_none() {
894 #[cfg(target_os = "macos")]
895 let system = keychain::trusted_roots();
896 #[cfg(windows)]
897 let system = winstore::trusted_roots();
898 let mut roots = RootCertStore::empty();
899 roots.add_parsable_certificates(system);
900 if !roots.is_empty() {
901 return Self::from_roots(roots);
902 }
903 }
904 let roots = load_roots(
905 file.as_deref(),
906 dirs.as_deref(),
907 SYSTEM_CA_BUNDLES,
908 SYSTEM_CA_DIR,
909 )?;
910 Self::from_roots(roots)
911 }
912
913 #[cfg(feature = "webpki-roots")]
920 pub fn with_webpki_roots() -> Self {
921 let roots = RootCertStore {
922 roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
923 };
924 Self::from_roots(roots).expect("the webpki-roots crate provides roots")
925 }
926
927 pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
931 Arc::make_mut(&mut self.config).alpn_protocols =
932 protocols.iter().map(|p| p.to_vec()).collect();
933 self
934 }
935
936 pub fn client_auth(mut self, cert_chain: &[u8], private_key: &[u8]) -> io::Result<Self> {
939 let certs = pem_certs(cert_chain)?;
940 let key = PrivateKeyDer::from_pem_slice(private_key).map_err(bad_key)?;
941 let key = CertifiedKey::from_der(certs, key, self.config.crypto_provider())
942 .map_err(mismatched_key)?;
943 Arc::make_mut(&mut self.config).client_auth_cert_resolver =
944 Arc::new(ClientCert(Arc::new(key)));
945 Ok(self)
946 }
947
948 pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
951 self.handshake_timeout = timeout;
952 self
953 }
954
955 pub fn ktls(mut self, mode: Ktls) -> io::Result<Self> {
969 let early_data = self.config.enable_early_data;
970 self.ktls = ktls::Plan::new(mode, self.config.crypto_provider(), early_data)?;
971 let extract = self.ktls.tries();
972 if self.config.enable_secret_extraction != extract {
973 Arc::make_mut(&mut self.config).enable_secret_extraction = extract;
974 }
975 Ok(self)
976 }
977
978 pub fn ktls_unavailable(&self) -> Option<&str> {
981 self.ktls.unavailable()
982 }
983
984 pub async fn connect(&self, server_name: &str, tcp: TcpStream) -> io::Result<TlsStream> {
996 let name = parse_server_name(server_name)?;
997 let tcp = match &self.ktls {
998 ktls::Plan::Off => tcp,
999 ktls::Plan::Try { required } => {
1000 let start = ktls::Start::Client(self.config.clone(), name.clone());
1001 match ktls::handshake(tcp, start, self.handshake_timeout).await? {
1002 ktls::Outcome::Kernel(tls) => return Ok(*tls),
1003 ktls::Outcome::Declined(_, e) if *required => return Err(e),
1004 ktls::Outcome::Declined(tcp, _) => {
1005 self.ktls.stayed();
1006 tcp
1007 }
1008 }
1009 }
1010 ktls::Plan::Unavailable(_) => {
1011 self.ktls.stayed();
1012 tcp
1013 }
1014 };
1015 let conn = UnbufferedClientConnection::new(self.config.clone(), name)
1016 .and_then(User::client)
1017 .map_err(tls_error)?;
1018 TlsStream::new(tcp, conn)
1019 .handshake(self.handshake_timeout, Duration::ZERO, None)
1020 .await
1021 }
1022}
1023
1024impl std::fmt::Debug for TlsConnector {
1025 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1026 f.debug_struct("TlsConnector")
1027 .field("handshake_timeout", &self.handshake_timeout)
1028 .field("ktls", &self.ktls)
1029 .finish_non_exhaustive()
1030 }
1031}
1032
1033struct AnyName(Arc<rustls::client::WebPkiServerVerifier>);
1037
1038impl std::fmt::Debug for AnyName {
1039 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1040 f.write_str("AnyName")
1041 }
1042}
1043
1044impl rustls::client::danger::ServerCertVerifier for AnyName {
1045 fn verify_server_cert(
1046 &self,
1047 end_entity: &CertificateDer<'_>,
1048 intermediates: &[CertificateDer<'_>],
1049 server_name: &ServerName<'_>,
1050 ocsp_response: &[u8],
1051 now: rustls::pki_types::UnixTime,
1052 ) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
1053 use rustls::CertificateError;
1054 match self
1055 .0
1056 .verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)
1057 {
1058 Err(rustls::Error::InvalidCertificate(
1062 CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. },
1063 )) => Ok(rustls::client::danger::ServerCertVerified::assertion()),
1064 other => other,
1065 }
1066 }
1067
1068 fn verify_tls12_signature(
1069 &self,
1070 message: &[u8],
1071 cert: &CertificateDer<'_>,
1072 dss: &rustls::DigitallySignedStruct,
1073 ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
1074 self.0.verify_tls12_signature(message, cert, dss)
1075 }
1076
1077 fn verify_tls13_signature(
1078 &self,
1079 message: &[u8],
1080 cert: &CertificateDer<'_>,
1081 dss: &rustls::DigitallySignedStruct,
1082 ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
1083 self.0.verify_tls13_signature(message, cert, dss)
1084 }
1085
1086 fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
1087 self.0.supported_verify_schemes()
1088 }
1089}
1090
1091fn parse_server_name(name: &str) -> io::Result<ServerName<'static>> {
1093 let ipv6 = name
1094 .strip_prefix('[')
1095 .and_then(|n| n.strip_suffix(']'))
1096 .and_then(|n| n.parse::<std::net::Ipv6Addr>().ok());
1097 if let Some(ip) = ipv6 {
1098 return Ok(ServerName::IpAddress(std::net::IpAddr::V6(ip).into()));
1099 }
1100 ServerName::try_from(name.to_owned()).map_err(|_| {
1101 coded(
1102 Code::InvalidServerName,
1103 format!("{name:?} is neither a DNS name nor an IP address"),
1104 "pass the host name the certificate is for (\"example.com\"), or an IP address, \
1105 without a port or a scheme.",
1106 )
1107 })
1108}
1109
1110#[derive(Debug)]
1112struct ClientCert(Arc<CertifiedKey>);
1113
1114impl ResolvesClientCert for ClientCert {
1115 fn resolve(&self, _: &[&[u8]], _: &[SignatureScheme]) -> Option<Arc<CertifiedKey>> {
1116 Some(self.0.clone())
1117 }
1118
1119 fn has_certs(&self) -> bool {
1120 true
1121 }
1122}
1123
1124const SYSTEM_CA_BUNDLES: &[&str] = &[
1126 "/etc/ssl/certs/ca-certificates.crt",
1128 "/etc/pki/tls/certs/ca-bundle.crt",
1130 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
1131 "/etc/ssl/ca-bundle.pem",
1133 "/etc/ssl/cert.pem",
1135];
1136
1137const SYSTEM_CA_DIR: &str = "/etc/ssl/certs";
1139
1140fn load_roots(
1145 file: Option<&OsStr>,
1146 dirs: Option<&OsStr>,
1147 bundles: &[&str],
1148 dir: &str,
1149) -> io::Result<RootCertStore> {
1150 let mut roots = Roots {
1151 store: RootCertStore::empty(),
1152 seen: HashSet::new(),
1153 };
1154 if file.is_some() || dirs.is_some() {
1155 if let Some(file) = file {
1156 roots.add_file(Path::new(file)).map_err(|e| {
1157 io::Error::new(
1158 e.kind(),
1159 giong::error::Error::new(
1160 Code::BadCertificateData,
1161 format!("cannot read SSL_CERT_FILE {file:?}: {e}"),
1162 "point SSL_CERT_FILE at a readable PEM file of certificates, or unset \
1163 it to use the system's.",
1164 )
1165 .with_source(e),
1166 )
1167 })?;
1168 }
1169 for dir in dirs.map(std::env::split_paths).into_iter().flatten() {
1170 roots.add_dir(&dir);
1171 }
1172 } else if let Some(bundle) = bundles.iter().map(Path::new).find(|p| p.is_file()) {
1173 roots.add_file(bundle)?;
1174 } else {
1175 roots.add_dir(Path::new(dir));
1176 }
1177 if roots.store.is_empty() {
1178 return Err(coded(
1179 Code::NoTrustedRoots,
1180 "no trusted CA certificates found on this machine",
1181 "install the ca-certificates package, set SSL_CERT_FILE, or use \
1182 TlsConnector::with_webpki_roots (the webpki-roots feature of giong-tls).",
1183 ));
1184 }
1185 Ok(roots.store)
1186}
1187
1188struct Roots {
1189 store: RootCertStore,
1190 seen: HashSet<PathBuf>,
1193}
1194
1195impl Roots {
1196 fn add_file(&mut self, path: &Path) -> io::Result<()> {
1197 let real = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
1198 if !self.seen.insert(real) {
1199 return Ok(());
1200 }
1201 let pem = std::fs::read(path)?;
1202 let certs = CertificateDer::pem_slice_iter(&pem).filter_map(Result::ok);
1203 self.store.add_parsable_certificates(certs);
1204 Ok(())
1205 }
1206
1207 fn add_dir(&mut self, dir: &Path) {
1208 let Ok(entries) = std::fs::read_dir(dir) else {
1209 return;
1210 };
1211 let mut paths: Vec<PathBuf> = entries.filter_map(|e| Some(e.ok()?.path())).collect();
1212 paths.sort();
1213 for path in paths.iter().filter(|p| p.is_file()) {
1214 let _ = self.add_file(path);
1216 }
1217 }
1218}
1219
1220pub struct TlsStream {
1223 tcp: TcpStream,
1224 engine: RefCell<Engine>,
1226 plain: RefCell<Vec<u8>>,
1228 established: Cell<bool>,
1232 eof: Cell<bool>,
1234 close_notify: Cell<bool>,
1237 sending: Cell<bool>,
1241 broken: Cell<bool>,
1244 closed: Cell<Option<Code>>,
1248 failed: Cell<Option<io::Error>>,
1250 waiters: RefCell<Vec<Waker>>,
1252 unsent: RefCell<Vec<u8>>,
1256}
1257
1258#[allow(clippy::large_enum_variant)]
1262enum Engine {
1263 User(User),
1265 Kernel(ktls::Kernel),
1268}
1269
1270struct Sending<'a> {
1274 stream: &'a TlsStream,
1275 complete: bool,
1276}
1277
1278impl Sending<'_> {
1279 fn done(mut self) {
1281 self.complete = true;
1282 }
1283}
1284
1285impl Drop for Sending<'_> {
1286 fn drop(&mut self) {
1287 if !self.complete {
1288 self.stream.broken.set(true);
1289 }
1290 self.stream.sending.set(false);
1291 self.stream.wake_waiters();
1292 }
1293}
1294
1295impl TlsStream {
1296 fn new(tcp: TcpStream, conn: User) -> Self {
1297 Self::with_engine(tcp, Engine::User(conn), Vec::new(), false)
1298 }
1299
1300 fn kernel(tcp: TcpStream, kernel: ktls::Kernel, plain: Vec<u8>, peer_closed: bool) -> Self {
1304 Self::with_engine(tcp, Engine::Kernel(kernel), plain, peer_closed)
1305 }
1306
1307 fn with_engine(tcp: TcpStream, engine: Engine, plain: Vec<u8>, peer_closed: bool) -> Self {
1308 Self {
1309 tcp,
1310 engine: RefCell::new(engine),
1311 plain: RefCell::new(plain),
1312 established: Cell::new(false),
1313 eof: Cell::new(peer_closed),
1314 close_notify: Cell::new(peer_closed),
1315 sending: Cell::new(false),
1316 broken: Cell::new(false),
1317 closed: Cell::new(None),
1318 failed: Cell::new(None),
1319 waiters: RefCell::new(Vec::new()),
1320 unsent: RefCell::new(Vec::new()),
1321 }
1322 }
1323
1324 fn conn(&self) -> RefMut<'_, User> {
1327 RefMut::map(self.engine.borrow_mut(), |e| match e {
1328 Engine::User(c) => c,
1329 Engine::Kernel(_) => unreachable!("rustls' connection on a kernel TLS stream"),
1330 })
1331 }
1332
1333 pub fn is_ktls(&self) -> bool {
1337 matches!(*self.engine.borrow(), Engine::Kernel(_))
1338 }
1339
1340 async fn wait_for_sender(&self) {
1342 poll_fn(|cx| {
1343 if !self.sending.get() {
1344 return Poll::Ready(());
1345 }
1346 let mut waiters = self.waiters.borrow_mut();
1348 if !waiters.iter().any(|w| w.will_wake(cx.waker())) {
1349 waiters.push(cx.waker().clone());
1350 }
1351 Poll::Pending
1352 })
1353 .await;
1354 }
1355
1356 async fn lock_send(&self) -> Sending<'_> {
1359 while self.sending.get() {
1360 self.wait_for_sender().await;
1361 }
1362 self.sending.set(true);
1363 Sending {
1364 stream: self,
1365 complete: false,
1366 }
1367 }
1368
1369 async fn handshake(
1373 self,
1374 limit: Duration,
1375 spent: Duration,
1376 first: Option<giong::RecvBuf>,
1377 ) -> io::Result<Self> {
1378 let handshake = async {
1379 if let Some(first) = first {
1380 self.absorb(first).await?;
1381 }
1382 while self.conn().is_handshaking() {
1383 self.flush_tls().await?;
1384 if !self.conn().is_handshaking() {
1385 break;
1386 }
1387 if self.eof.get() {
1388 return Err(handshake_eof());
1389 }
1390 self.pump().await?;
1391 }
1392 if !self.hold_output() {
1393 self.flush_tls().await?;
1394 }
1395 self.established.set(true);
1396 Ok(())
1397 };
1398 match timeout(limit.saturating_sub(spent), handshake).await {
1399 Ok(Ok(())) => Ok(self),
1400 Ok(Err(e)) => Err(e),
1401 Err(_) => Err(handshake_timed_out(limit)),
1402 }
1403 }
1404
1405 fn wake_waiters(&self) {
1408 let waiters = mem::take(&mut *self.waiters.borrow_mut());
1409 for waker in waiters {
1410 waker.wake();
1411 }
1412 }
1413
1414 fn hold_output(&self) -> bool {
1428 if self.established.get() {
1429 return true;
1432 }
1433 let conn = self.conn();
1434 if conn.is_handshaking() {
1435 return false;
1436 }
1437 conn.is_server() && conn.protocol_version() == Some(rustls::ProtocolVersion::TLSv1_3)
1438 }
1439
1440 fn take_wire(&self) -> Vec<u8> {
1444 let mut wire = SPARE_WIRES.with(|spare| spare.borrow_mut().pop().unwrap_or_default());
1445 let mut unsent = self.unsent.borrow_mut();
1446 if unsent.capacity() > 0 {
1447 wire.extend_from_slice(&unsent);
1448 *unsent = Vec::new();
1450 }
1451 wire
1452 }
1453
1454 fn keep_wire(&self, mut wire: Vec<u8>) {
1458 if !wire.is_empty() && !self.broken.get() {
1459 self.unsent.borrow_mut().append(&mut wire);
1462 }
1463 if wire.capacity() <= WIRE_KEPT && wire.capacity() > 0 {
1464 wire.clear();
1465 SPARE_WIRES.with(|spare| {
1466 let mut spare = spare.borrow_mut();
1467 if spare.len() < SPARE_WIRES_KEPT {
1468 spare.push(wire);
1469 }
1470 });
1471 }
1472 }
1473
1474 fn cannot_send(&self) -> Option<io::Error> {
1477 if self.broken.get() {
1478 return Some(broken());
1479 }
1480 self.closed.get().map(sending_closed)
1481 }
1482
1483 async fn flush_tls(&self) -> io::Result<()> {
1487 loop {
1488 if !self.wants_send() {
1489 return Ok(());
1490 }
1491 if self.broken.get() {
1492 return Err(broken());
1493 }
1494 if self.sending.get() {
1495 self.wait_for_sender().await;
1498 continue;
1499 }
1500 let sending = self.lock_send().await;
1501 let mut wire = self.take_wire();
1502 let res = self.send_queued(&mut wire).await;
1503 self.keep_wire(wire);
1504 sending.done();
1505 res?;
1506 }
1507 }
1508
1509 async fn send_queued(&self, wire: &mut Vec<u8>) -> io::Result<()> {
1512 loop {
1513 self.conn().write_tls(wire);
1514 if wire.is_empty() {
1515 return Ok(());
1516 }
1517 self.send_wire(wire).await?;
1518 }
1519 }
1520
1521 fn wants_send(&self) -> bool {
1524 self.conn().wants_write() || !self.unsent.borrow().is_empty()
1525 }
1526
1527 fn flush_now(&self) -> io::Result<()> {
1539 if self.broken.get() {
1540 return Err(broken());
1541 }
1542 if self.sending.get() {
1543 return Ok(());
1544 }
1545 let mut unsent = self.unsent.borrow_mut();
1546 self.conn().write_tls(&mut unsent);
1547 loop {
1548 let len = unsent.len().min(flush_room());
1550 if len == 0 {
1551 return Ok(());
1552 }
1553 let fd = sys::AsRawFd::as_raw_fd(&self.tcp);
1554 let e = match sys::send_now(fd, &unsent[..len], false) {
1555 Ok(n) => {
1556 if n == unsent.len() {
1557 *unsent = Vec::new();
1559 } else {
1560 unsent.drain(..n);
1562 }
1563 return Ok(());
1564 }
1565 Err(e) => e,
1566 };
1567 match e.kind() {
1568 io::ErrorKind::Interrupted => {}
1569 io::ErrorKind::WouldBlock => return Ok(()),
1570 _ if no_buffers(&e) => return Ok(()),
1573 _ => {
1574 self.broken.set(true);
1575 *unsent = Vec::new();
1576 return Err(e);
1577 }
1578 }
1579 }
1580 }
1581
1582 #[allow(clippy::manual_async_fn)]
1586 fn send_wire<'a>(&'a self, wire: &'a mut Vec<u8>) -> impl Future<Output = io::Result<()>> + 'a {
1587 async move {
1588 let (res, mut sent) = self.tcp.write_all(mem::take(wire)).await;
1589 sent.clear();
1590 *wire = sent;
1591 if res.is_err() {
1592 self.broken.set(true);
1593 }
1594 res
1595 }
1596 }
1597
1598 #[allow(clippy::manual_async_fn)]
1610 fn send_plain<'a>(
1611 &'a self,
1612 wire: &'a mut Vec<u8>,
1613 data: &'a [u8],
1614 last: bool,
1615 ) -> impl Future<Output = io::Result<()>> + 'a {
1616 async move {
1617 let mut sent = 0;
1618 while sent < data.len() {
1619 let piece = &data[sent..data.len().min(sent + ENCRYPT_AT)];
1620 let (carried, refused) = {
1621 let mut conn = self.conn();
1622 conn.write_tls(wire);
1623 let carried = !wire.is_empty();
1624 let refused = match conn.encrypt(piece, wire) {
1625 Ok(_) => {
1626 sent += piece.len();
1627 false
1628 }
1629 Err(user::Refused::Exhausted) => {
1634 conn.write_tls(wire);
1635 true
1636 }
1637 Err(user::Refused::Closed) => {
1638 drop(conn);
1639 self.closed.set(Some(Code::TlsBroken));
1640 return Err(sending_closed(Code::TlsBroken));
1641 }
1642 Err(user::Refused::Tls(e)) => return Err(tls_error(e)),
1643 };
1644 (carried, refused)
1645 };
1646 let more = sent < data.len() || !last;
1647 if !wire.is_empty() && (carried || refused || !more || wire.len() >= SEND_AT) {
1648 self.send_wire(wire).await?;
1649 }
1650 if carried {
1651 self.wake_waiters();
1653 }
1654 if refused {
1655 self.closed.set(Some(Code::TlsKeysExhausted));
1656 return Err(sending_closed(Code::TlsKeysExhausted));
1657 }
1658 }
1659 Ok(())
1660 }
1661 }
1662
1663 #[allow(clippy::manual_async_fn)]
1667 fn write_in_process<'a>(
1668 &'a self,
1669 pieces: &'a [&'a [u8]],
1670 ) -> impl Future<Output = io::Result<()>> + 'a {
1671 async move {
1672 let sending = self.lock_send().await;
1673 if let Some(e) = self.cannot_send() {
1674 sending.done();
1675 return Err(e);
1676 }
1677 let mut wire = self.take_wire();
1678 let mut res = Ok(());
1679 for (i, piece) in pieces.iter().enumerate() {
1680 res = self
1681 .send_plain(&mut wire, piece, i + 1 == pieces.len())
1682 .await;
1683 if res.is_err() {
1684 break;
1685 }
1686 }
1687 if res.is_ok() && !wire.is_empty() {
1688 res = self.send_wire(&mut wire).await;
1690 }
1691 self.keep_wire(wire);
1692 sending.done();
1696 res
1697 }
1698 }
1699
1700 async fn pump(&self) -> io::Result<()> {
1704 let ready = if !self.broken.get() && self.wants_send() {
1707 poll_fn(|cx| Poll::Ready(self.tcp.poll_recv(cx))).await
1708 } else {
1709 Poll::Pending
1710 };
1711 let chunk = match ready {
1712 Poll::Ready(chunk) => chunk?,
1713 Poll::Pending => {
1714 if !self.broken.get() && self.wants_send() {
1715 let _ = self.flush_for_recv().await;
1719 }
1720 self.tcp.recv().await?
1722 }
1723 };
1724 self.absorb(chunk).await
1725 }
1726
1727 async fn absorb(&self, chunk: giong::RecvBuf) -> io::Result<()> {
1731 if chunk.is_empty() {
1732 self.eof.set(true);
1733 return Ok(());
1734 }
1735 let result = self.decrypt(chunk);
1736 if self.broken.get() || (result.is_ok() && self.hold_output()) {
1740 return result;
1741 }
1742 let flushed = self.flush_for_recv().await;
1743 result.and(flushed)
1744 }
1745
1746 fn decrypt(&self, chunk: giong::RecvBuf) -> io::Result<()> {
1749 if chunk.is_empty() {
1750 self.eof.set(true);
1751 return Ok(());
1752 }
1753 let mut conn = self.conn();
1754 let mut plain = self.plain.borrow_mut();
1755 let result = conn.read_tls(&chunk, &mut plain).map_err(read_error);
1757 if conn.peer_closed() {
1758 self.close_notify.set(true);
1759 self.eof.set(true);
1760 }
1761 result
1762 }
1763
1764 async fn pump_established(&self) -> io::Result<()> {
1771 debug_assert!(self.established.get());
1772 let ready = if !self.broken.get() && self.wants_send() {
1775 poll_fn(|cx| Poll::Ready(self.tcp.poll_recv(cx))).await
1776 } else {
1777 Poll::Pending
1778 };
1779 let chunk = match ready {
1780 Poll::Ready(chunk) => chunk?,
1781 Poll::Pending => {
1782 if !self.broken.get() && self.wants_send() {
1783 let _ = self.flush_now();
1785 }
1786 self.tcp.recv().await?
1788 }
1789 };
1790 let result = self.decrypt(chunk);
1791 if result.is_ok() || self.broken.get() {
1795 return result;
1796 }
1797 let flushed = self.flush_now();
1798 result.and(flushed)
1799 }
1800
1801 async fn flush_for_recv(&self) -> io::Result<()> {
1807 if self.established.get() {
1808 self.flush_now()
1809 } else {
1810 self.flush_tls().await
1811 }
1812 }
1813
1814 pub async fn recv(&self) -> io::Result<Received> {
1833 if self.is_ktls() {
1834 return self.kernel_recv().await.map(Received);
1835 }
1836 self.user_recv().await.map(Received)
1837 }
1838
1839 async fn user_recv(&self) -> io::Result<Vec<u8>> {
1840 loop {
1841 {
1842 let mut plain = self.plain.borrow_mut();
1843 if !plain.is_empty() {
1844 return Ok(mem::take(&mut *plain));
1845 }
1846 }
1847 if let Some(e) = self.failed.take() {
1848 return Err(e);
1849 }
1850 if self.eof.get() {
1851 return Ok(Vec::new());
1852 }
1853 if let Err(e) = self.pump_established().await {
1854 if self.plain.borrow().is_empty() {
1856 return Err(e);
1857 }
1858 self.failed.set(Some(e));
1859 }
1860 }
1861 }
1862
1863 pub async fn write_all<B>(&self, buf: B) -> (io::Result<()>, B)
1884 where
1885 B: giong::IoBuf + AsRef<[u8]>,
1886 {
1887 if self.is_ktls() {
1888 return self.kernel_write_all(buf).await;
1889 }
1890 let res = self.write_in_process(&[buf.as_ref()]).await;
1891 (res, buf)
1892 }
1893
1894 pub async fn write_all_vectored<B>(&self, bufs: Vec<B>) -> (io::Result<()>, Vec<B>)
1906 where
1907 B: giong::IoBuf + AsRef<[u8]>,
1908 {
1909 if self.is_ktls() {
1910 return self.kernel_write_all_vectored(bufs).await;
1911 }
1912 let pieces: Vec<&[u8]> = bufs.iter().map(AsRef::as_ref).collect();
1913 let res = self.write_in_process(&pieces).await;
1914 drop(pieces);
1915 (res, bufs)
1916 }
1917
1918 pub async fn send_file(&self, file: &giong::fs::File, offset: u64, len: u64) -> io::Result<()> {
1935 if offset
1936 .checked_add(len)
1937 .map_or(true, |end| end > i64::MAX as u64)
1938 {
1939 return Err(file_too_short(offset, len, offset));
1940 }
1941 if self.is_ktls() {
1942 return self.kernel_send_file(file, offset, len).await;
1943 }
1944 let sending = self.lock_send().await;
1945 if let Some(e) = self.cannot_send() {
1946 sending.done();
1947 return Err(e);
1948 }
1949 let mut wire = self.take_wire();
1950 let res = self
1951 .send_file_in_process(&mut wire, file, offset, len)
1952 .await;
1953 self.keep_wire(wire);
1954 sending.done();
1955 res
1956 }
1957
1958 async fn send_file_in_process(
1961 &self,
1962 wire: &mut Vec<u8>,
1963 file: &giong::fs::File,
1964 offset: u64,
1965 len: u64,
1966 ) -> io::Result<()> {
1967 const PIECE: u64 = 256 * 1024;
1968 let mut buf = Vec::with_capacity(len.min(PIECE) as usize);
1969 let (mut at, mut left) = (offset, len);
1970 while left > 0 {
1971 let (res, b) = file.read_at(buf, at).await;
1972 buf = b;
1973 let n = match res {
1974 Ok(0) => return Err(file_too_short(offset, len, at)),
1975 Ok(n) => (n as u64).min(left) as usize,
1976 Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
1977 Err(e) => return Err(e),
1978 };
1979 self.send_plain(wire, &buf[..n], true).await?;
1980 at += n as u64;
1981 left -= n as u64;
1982 }
1983 Ok(())
1984 }
1985
1986 async fn send_closing(&self, wire: &mut Vec<u8>) -> io::Result<()> {
1993 self.conn().write_tls(wire);
1994 match sys::send_now(sys::AsRawFd::as_raw_fd(&self.tcp), wire, true) {
1997 Ok(n) => {
1998 wire.drain(..n);
1999 }
2000 Err(e)
2003 if !matches!(
2004 e.kind(),
2005 io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted
2006 ) && !no_buffers(&e) =>
2007 {
2008 self.broken.set(true);
2009 wire.clear();
2010 return Err(e);
2011 }
2012 Err(_) => {}
2013 }
2014 if !wire.is_empty() {
2015 self.send_wire(wire).await?;
2016 }
2017 self.send_queued(wire).await
2018 }
2019
2020 pub async fn shutdown(&self) -> io::Result<()> {
2038 if self.is_ktls() {
2039 return self.kernel_shutdown().await;
2040 }
2041 let sending = self.lock_send().await;
2042 if self.cannot_send().is_none() {
2043 self.conn().send_close_notify();
2044 self.closed.set(Some(Code::TlsBroken));
2045 let mut wire = self.take_wire();
2046 let res = self.send_closing(&mut wire).await;
2047 self.keep_wire(wire);
2048 if let Err(e) = res {
2049 sending.done();
2051 let _ = self.tcp.shutdown(Shutdown::Write);
2052 return if self.peer_gone(&e) { Ok(()) } else { Err(e) };
2053 }
2054 }
2055 sending.done();
2056 self.tcp.shutdown(Shutdown::Write)
2057 }
2058
2059 fn peer_gone(&self, e: &io::Error) -> bool {
2062 matches!(
2063 e.kind(),
2064 io::ErrorKind::BrokenPipe | io::ErrorKind::ConnectionReset
2065 )
2066 }
2067
2068 pub fn received_close_notify(&self) -> bool {
2074 self.close_notify.get()
2075 }
2076
2077 pub fn alpn_protocol(&self) -> Option<Vec<u8>> {
2079 match &*self.engine.borrow() {
2080 Engine::User(c) => c.alpn_protocol().map(<[u8]>::to_vec),
2081 Engine::Kernel(k) => k.negotiated.alpn.clone(),
2082 }
2083 }
2084
2085 pub fn peer_certificates(&self) -> Option<Vec<CertificateDer<'static>>> {
2090 match &*self.engine.borrow() {
2091 Engine::User(c) => c.peer_certificates().map(<[_]>::to_vec),
2092 Engine::Kernel(k) => k.negotiated.peer_certificates.clone(),
2093 }
2094 }
2095
2096 pub fn resumed(&self) -> bool {
2099 match &*self.engine.borrow() {
2100 Engine::User(c) => c.handshake_kind() == Some(rustls::HandshakeKind::Resumed),
2101 Engine::Kernel(k) => k.negotiated.resumed,
2102 }
2103 }
2104
2105 pub fn tcp(&self) -> &TcpStream {
2112 &self.tcp
2113 }
2114}
2115
2116impl std::fmt::Debug for TlsStream {
2117 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2118 f.debug_struct("TlsStream")
2119 .field("tcp", &self.tcp)
2120 .field("ktls", &self.is_ktls())
2121 .finish_non_exhaustive()
2122 }
2123}
2124
2125#[cfg(test)]
2126mod tests {
2127 use super::*;
2128 use std::future::Future;
2129
2130 #[test]
2131 fn a_connector_without_trusted_authorities_is_refused() {
2132 let err = TlsConnector::from_roots(RootCertStore::empty()).unwrap_err();
2134 assert_eq!(err.kind(), io::ErrorKind::NotFound, "{err}");
2135 assert_eq!(
2136 giong::error::code(&err),
2137 Some(Code::NoTrustedRoots),
2138 "{err}"
2139 );
2140 }
2141
2142 fn authority(name: &str) -> (rcgen::Certificate, rcgen::KeyPair) {
2143 let key = rcgen::KeyPair::generate().unwrap();
2144 let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
2145 params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
2146 params
2147 .distinguished_name
2148 .push(rcgen::DnType::CommonName, name);
2149 (params.self_signed(&key).unwrap(), key)
2150 }
2151
2152 fn signed_by(
2153 ca: &rcgen::Certificate,
2154 ca_key: &rcgen::KeyPair,
2155 names: &[&str],
2156 expired: bool,
2157 ) -> CertificateDer<'static> {
2158 let key = rcgen::KeyPair::generate().unwrap();
2159 let names: Vec<String> = names.iter().map(|n| n.to_string()).collect();
2160 let mut params = rcgen::CertificateParams::new(names).unwrap();
2161 params.distinguished_name.push(
2163 rcgen::DnType::CommonName,
2164 "MySQL_Server_8.0.46_Auto_Generated_Server_Certificate",
2165 );
2166 if expired {
2167 params.not_before = rcgen::date_time_ymd(2020, 1, 1);
2168 params.not_after = rcgen::date_time_ymd(2021, 1, 1);
2169 }
2170 let cert = params.signed_by(&key, ca, ca_key).unwrap();
2171 CertificateDer::from(cert.der().to_vec())
2172 }
2173
2174 #[test]
2176 fn any_name_still_checks_the_chain() {
2177 use rustls::client::danger::ServerCertVerifier;
2178 use rustls::pki_types::UnixTime;
2179 use rustls::CertificateError;
2180
2181 let (ca, ca_key) = authority("ours");
2182 let mut roots = RootCertStore::empty();
2183 roots.add(CertificateDer::from(ca.der().to_vec())).unwrap();
2184 let webpki = rustls::client::WebPkiServerVerifier::builder_with_provider(
2185 Arc::new(roots),
2186 provider(),
2187 )
2188 .build()
2189 .unwrap();
2190 let verifier = AnyName(webpki);
2191 let name = ServerName::try_from("db.internal").unwrap();
2192 let check = |cert: &CertificateDer<'_>| {
2193 verifier.verify_server_cert(cert, &[], &name, &[], UnixTime::now())
2194 };
2195 for names in [&[][..], &["localhost"], &["db.internal"]] {
2197 check(&signed_by(&ca, &ca_key, names, false)).unwrap();
2198 }
2199 let e = check(&signed_by(&ca, &ca_key, &[], true)).unwrap_err();
2201 assert!(
2202 matches!(
2203 e,
2204 rustls::Error::InvalidCertificate(
2205 CertificateError::Expired | CertificateError::ExpiredContext { .. }
2206 )
2207 ),
2208 "{e:?}"
2209 );
2210 let (other, other_key) = authority("theirs");
2213 for cert in [
2214 signed_by(&other, &other_key, &["db.internal"], false),
2215 CertificateDer::from(other.der().to_vec()),
2216 ] {
2217 let e = check(&cert).unwrap_err();
2218 assert!(matches!(e, rustls::Error::InvalidCertificate(_)), "{e:?}");
2219 }
2220 assert!(check(&CertificateDer::from(ca.der().to_vec())).is_err());
2222 assert!(TlsConnector::with_root_pem_any_name(b"").is_err());
2224 assert!(TlsConnector::with_root_pem_any_name(
2225 b"-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n"
2226 )
2227 .is_err());
2228 assert!(TlsConnector::with_root_pem_any_name(ca.pem().as_bytes()).is_ok());
2229 }
2230
2231 fn client_hello(suites: &[u16], id_len: u8, keep: usize) -> Vec<u8> {
2234 let mut hello = vec![22, 3, 1, 0, 0, 1, 0, 0, 0, 3, 3];
2235 hello.extend_from_slice(&[7; 32]);
2236 hello.push(id_len);
2237 hello.extend(std::iter::repeat(9).take(id_len.into()));
2238 hello.extend_from_slice(&((suites.len() * 2) as u16).to_be_bytes());
2239 for suite in suites {
2240 hello.extend_from_slice(&suite.to_be_bytes());
2241 }
2242 hello.extend_from_slice(&[1, 0]); hello.truncate(keep);
2244 hello
2245 }
2246
2247 #[test]
2248 fn chacha20_first_clients_are_told_apart() {
2249 let all = usize::MAX;
2250 assert!(!prefers_chacha(&client_hello(
2252 &[0x1302, 0x1303, 0x1301],
2253 32,
2254 all
2255 )));
2256 assert!(!prefers_chacha(&client_hello(
2258 &[0x1301, 0x1302, 0x1303],
2259 0,
2260 all
2261 )));
2262 assert!(prefers_chacha(&client_hello(
2264 &[0x0a0a, 0x1303, 0x1301],
2265 32,
2266 all
2267 )));
2268 assert!(prefers_chacha(&client_hello(&[0xcca9, 0xc02b], 0, all)));
2270 assert!(!prefers_chacha(&client_hello(&[0xc02c, 0xcca9], 0, all)));
2271 assert!(!prefers_chacha(&client_hello(&[0x009c], 0, all)));
2273 let cut = client_hello(&[0x1303, 0x1301], 32, all).len() - 3;
2274 assert!(!prefers_chacha(&client_hello(&[0x1303, 0x1301], 32, cut)));
2275 assert!(!prefers_chacha(&client_hello(&[0x1303], 32, 40)));
2276 assert!(!prefers_chacha(&[]));
2277 let mut alert = client_hello(&[0x1303], 0, all);
2278 alert[0] = 21;
2279 assert!(!prefers_chacha(&alert));
2280 }
2281
2282 fn ca_pem(name: &str) -> String {
2283 let key = rcgen::KeyPair::generate().unwrap();
2284 let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
2285 params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
2286 params
2287 .distinguished_name
2288 .push(rcgen::DnType::CommonName, name);
2289 params.self_signed(&key).unwrap().pem()
2290 }
2291
2292 fn scratch(name: &str) -> PathBuf {
2294 let dir = std::env::temp_dir().join(format!("giong-tls-{}-{name}", std::process::id()));
2295 let _ = std::fs::remove_dir_all(&dir);
2296 std::fs::create_dir_all(&dir).unwrap();
2297 dir
2298 }
2299
2300 fn os(path: &Path) -> &OsStr {
2301 path.as_os_str()
2302 }
2303
2304 #[test]
2305 fn server_names_are_dns_names_or_ip_addresses() {
2306 let dns = |n: &str| matches!(parse_server_name(n), Ok(ServerName::DnsName(_)));
2307 let ip = |n: &str| matches!(parse_server_name(n), Ok(ServerName::IpAddress(_)));
2308 assert!(dns("example.com"));
2309 assert!(dns("db.prod.svc.cluster.local"));
2310 assert!(ip("10.0.0.1"));
2311 assert!(ip("::1"));
2312 assert!(ip("[::1]"));
2313 for bad in ["", "not a name", "[nope]", "[10.0.0.1]", "a..b"] {
2314 let err = parse_server_name(bad).unwrap_err();
2315 assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{bad:?}");
2316 }
2317 }
2318
2319 #[test]
2320 fn the_first_bundle_that_exists_is_read() {
2321 let dir = scratch("bundle");
2322 let bundle = dir.join("bundle.pem");
2323 let two = format!("{}{}", ca_pem("one"), ca_pem("two"));
2324 std::fs::write(&bundle, two).unwrap();
2325 let missing = dir.join("missing.pem");
2326 let bundles = [missing.to_str().unwrap(), bundle.to_str().unwrap()];
2327 let roots = load_roots(None, None, &bundles, "/nonexistent").unwrap();
2328 assert_eq!(roots.len(), 2);
2329 std::fs::remove_dir_all(dir).unwrap();
2330 }
2331
2332 #[test]
2333 fn ssl_cert_file_and_dir_replace_the_system_locations() {
2334 let dir = scratch("env");
2335 let file = dir.join("file.pem");
2336 std::fs::write(&file, ca_pem("from file")).unwrap();
2337 let certs = dir.join("certs");
2338 std::fs::create_dir(&certs).unwrap();
2339 std::fs::write(certs.join("a.pem"), ca_pem("a")).unwrap();
2340 std::fs::write(certs.join("b.pem"), ca_pem("b")).unwrap();
2341 std::fs::write(certs.join("README"), "not a certificate").unwrap();
2342 #[cfg(unix)]
2344 std::os::unix::fs::symlink(certs.join("a.pem"), certs.join("1a2b3c4d.0")).unwrap();
2345 let system = dir.join("system.pem");
2346 std::fs::write(&system, ca_pem("system")).unwrap();
2347 let bundles = [system.to_str().unwrap()];
2348
2349 let roots = load_roots(Some(os(&file)), None, &bundles, "/nonexistent").unwrap();
2350 assert_eq!(roots.len(), 1, "SSL_CERT_FILE only");
2351 let roots = load_roots(None, Some(os(&certs)), &bundles, "/nonexistent").unwrap();
2352 assert_eq!(roots.len(), 2, "SSL_CERT_DIR only, each file once");
2353 let both = std::env::join_paths([dir.join("nowhere"), certs.clone()]).unwrap();
2354 let roots = load_roots(Some(os(&file)), Some(&both), &bundles, "/nonexistent").unwrap();
2355 assert_eq!(roots.len(), 3, "both, with a missing directory in the list");
2356
2357 let err = load_roots(Some(os(&dir.join("gone.pem"))), None, &bundles, "").unwrap_err();
2358 assert_eq!(err.kind(), io::ErrorKind::NotFound);
2359 assert!(err.to_string().contains("SSL_CERT_FILE"), "{err}");
2360 std::fs::remove_dir_all(dir).unwrap();
2361 }
2362
2363 #[test]
2364 fn without_a_bundle_the_directory_is_read_and_nothing_is_an_error() {
2365 let dir = scratch("dir");
2366 std::fs::write(dir.join("only.crt"), ca_pem("only")).unwrap();
2367 let roots = load_roots(
2368 None,
2369 None,
2370 &["/nonexistent/bundle.crt"],
2371 dir.to_str().unwrap(),
2372 );
2373 assert_eq!(roots.unwrap().len(), 1);
2374
2375 let empty = scratch("empty");
2376 let err = load_roots(None, None, &[], empty.to_str().unwrap()).unwrap_err();
2377 assert_eq!(err.kind(), io::ErrorKind::NotFound);
2378 assert!(err.to_string().contains("webpki-roots"), "{err}");
2379 std::fs::remove_dir_all(dir).unwrap();
2380 std::fs::remove_dir_all(empty).unwrap();
2381 }
2382
2383 #[test]
2384 fn secrets_are_extractable_only_when_the_kernel_will_take_them() {
2385 let key = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
2386 let (cert, key) = (key.cert.pem(), key.key_pair.serialize_pem());
2387 for mode in [Ktls::Off, Ktls::Auto] {
2388 let acceptor = TlsAcceptor::with_certificates(
2389 &Certificates::from_pem(cert.as_bytes(), key.as_bytes()).unwrap(),
2390 )
2391 .unwrap()
2392 .ktls(mode)
2393 .unwrap();
2394 let tries = acceptor.ktls.tries();
2395 assert_eq!(acceptor.config.enable_secret_extraction, tries, "{mode:?}");
2396 let connector = TlsConnector::with_root_pem(cert.as_bytes())
2397 .unwrap()
2398 .ktls(mode)
2399 .unwrap();
2400 let tries = connector.ktls.tries();
2401 assert_eq!(connector.config.enable_secret_extraction, tries, "{mode:?}");
2402 }
2403 }
2404
2405 #[test]
2406 fn this_machines_roots_load() {
2407 TlsConnector::with_system_roots().unwrap();
2409 }
2410
2411 #[cfg(feature = "webpki-roots")]
2412 #[test]
2413 fn mozillas_roots_are_compiled_in() {
2414 TlsConnector::with_webpki_roots();
2415 }
2416
2417 #[test]
2418 fn records_a_receive_could_not_send_whole_go_out_first_and_in_order() {
2419 let key = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
2425 let cert = key.cert.pem();
2426 let acceptor = TlsAcceptor::with_certificates(
2427 &Certificates::from_pem(cert.as_bytes(), key.key_pair.serialize_pem().as_bytes())
2428 .unwrap(),
2429 )
2430 .unwrap();
2431 let connector = TlsConnector::with_root_pem(cert.as_bytes()).unwrap();
2432 giong::block_on(async move {
2433 let listener = giong::net::TcpListener::bind("127.0.0.1:0").unwrap();
2434 let addr = listener.local_addr().unwrap();
2435 let server = giong::spawn(async move {
2436 let tcp = listener.accept().await.unwrap();
2437 let tls = acceptor.accept(tcp).await.unwrap();
2438 assert!(tls.conn().wants_write(), "tickets wait for the first send");
2439 FLUSH_ROOM.set(1);
2440 let mut left = None;
2441 for _ in 0..5 {
2442 let mut recv = std::pin::pin!(tls.recv());
2443 let ready = poll_fn(|cx| Poll::Ready(recv.as_mut().poll(cx).is_ready())).await;
2444 assert!(!ready);
2445 let unsent = tls.unsent.borrow().len();
2446 assert!(
2447 left.map_or(unsent > 0, |l| unsent + 1 == l),
2448 "{left:?} {unsent}"
2449 );
2450 left = Some(unsent);
2451 }
2452 FLUSH_ROOM.set(usize::MAX);
2453 tls.write_all(&b"after the tickets"[..]).await.0.unwrap();
2454 assert_eq!(tls.unsent.borrow().capacity(), 0);
2457 tls.shutdown().await.unwrap();
2458 });
2459 let tcp = TcpStream::connect(addr).await.unwrap();
2460 let tls = connector.connect("localhost", tcp).await.unwrap();
2461 let mut got = Vec::new();
2462 loop {
2463 let data = tls.recv().await.unwrap();
2464 if data.is_empty() {
2465 break;
2466 }
2467 got.extend_from_slice(&data);
2468 }
2469 assert_eq!(got, b"after the tickets");
2470 assert!(tls.received_close_notify());
2471 server.await.unwrap();
2472 });
2473 }
2474
2475 #[test]
2476 fn a_receive_that_sent_what_was_owed_keeps_no_buffer_for_it() {
2477 let key = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
2481 let cert = key.cert.pem();
2482 let acceptor = TlsAcceptor::with_certificates(
2483 &Certificates::from_pem(cert.as_bytes(), key.key_pair.serialize_pem().as_bytes())
2484 .unwrap(),
2485 )
2486 .unwrap();
2487 let connector = TlsConnector::with_root_pem(cert.as_bytes()).unwrap();
2488 giong::block_on(async move {
2489 let listener = giong::net::TcpListener::bind("127.0.0.1:0").unwrap();
2490 let addr = listener.local_addr().unwrap();
2491 let server = giong::spawn(async move {
2492 let tcp = listener.accept().await.unwrap();
2493 let tls = acceptor.accept(tcp).await.unwrap();
2494 assert!(tls.conn().wants_write(), "tickets wait for the first send");
2495 let mut recv = std::pin::pin!(tls.recv());
2498 let ready = poll_fn(|cx| Poll::Ready(recv.as_mut().poll(cx).is_ready())).await;
2499 assert!(!ready);
2500 assert!(!tls.conn().wants_write());
2501 assert_eq!(tls.unsent.borrow().capacity(), 0);
2502 tls.shutdown().await.unwrap();
2503 });
2504 let tcp = TcpStream::connect(addr).await.unwrap();
2505 let tls = connector.connect("localhost", tcp).await.unwrap();
2506 assert!(tls.recv().await.unwrap().is_empty());
2507 assert!(tls.received_close_notify());
2508 server.await.unwrap();
2509 });
2510 }
2511
2512 #[test]
2513 fn a_connection_keeps_a_receive_buffer_only_while_it_holds_part_of_a_record() {
2514 let key = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
2517 let cert = key.cert.pem();
2518 let acceptor = TlsAcceptor::with_certificates(
2519 &Certificates::from_pem(cert.as_bytes(), key.key_pair.serialize_pem().as_bytes())
2520 .unwrap(),
2521 )
2522 .unwrap();
2523 let connector = TlsConnector::with_root_pem(cert.as_bytes()).unwrap();
2524 giong::block_on(async move {
2525 let listener = giong::net::TcpListener::bind("127.0.0.1:0").unwrap();
2526 let addr = listener.local_addr().unwrap();
2527 let server = giong::spawn(async move {
2528 let tcp = listener.accept().await.unwrap();
2529 let tls = acceptor.accept(tcp).await.unwrap();
2530 assert_eq!(&tls.recv().await.unwrap()[..], b"hello");
2531 assert_eq!(tls.conn().partial_capacity(), 0);
2532 tls.write_all(b"go".to_vec()).await.0.unwrap();
2533 let mut recv = std::pin::pin!(tls.recv());
2535 for _ in 0..400 {
2536 let ready = poll_fn(|cx| Poll::Ready(recv.as_mut().poll(cx).is_ready())).await;
2537 assert!(!ready);
2538 if tls.conn().partial_capacity() > 0 {
2539 break;
2540 }
2541 giong::time::sleep(Duration::from_millis(5)).await;
2542 }
2543 assert!(tls.conn().partial_capacity() > 0);
2544 });
2545 let tcp = TcpStream::connect(addr).await.unwrap();
2546 let tls = connector.connect("localhost", tcp).await.unwrap();
2547 tls.write_all(b"hello".to_vec()).await.0.unwrap();
2548 assert_eq!(&tls.recv().await.unwrap()[..], b"go");
2549 tls.tcp().write_all(vec![23u8, 3, 3]).await.0.unwrap();
2550 server.await.unwrap();
2551 });
2552 }
2553
2554 #[test]
2555 fn the_key_exchange_offers_post_quantum_first_with_the_feature() {
2556 let first = provider().kx_groups[0].name();
2557 let pq = rustls::NamedGroup::X25519MLKEM768;
2558 assert_eq!(first == pq, cfg!(feature = "post-quantum"), "{first:?}");
2559 assert_eq!(provider_aes128_first().kx_groups[0].name(), first);
2560 }
2561}