1#![warn(missing_docs)]
80
81mod ktls;
82mod received;
83
84pub use ktls::{ktls_stats, ktls_support, Ktls, KtlsStats, KtlsSupport};
85pub use received::Received;
86
87#[cfg(fuzzing)]
90#[doc(hidden)]
91pub mod fuzzing {
92 pub use crate::ktls::{check_handshake_messages, check_record_framing};
93}
94
95use std::cell::{Cell, RefCell, RefMut};
96use std::collections::HashSet;
97use std::ffi::OsStr;
98use std::future::poll_fn;
99use std::io::{self, Read, Write};
100use std::mem;
101use std::net::Shutdown;
102use std::path::{Path, PathBuf};
103use std::sync::Arc;
104use std::task::{Poll, Waker};
105use std::time::Duration;
106
107use giong::error::Code;
108use giong::net::TcpStream;
109use giong::time::timeout;
110use rustls::client::ResolvesClientCert;
111use rustls::pki_types::pem::PemObject;
112use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName};
113use rustls::sign::CertifiedKey;
114use rustls::{
115 ClientConfig, ClientConnection, Connection, RootCertStore, ServerConfig, ServerConnection,
116 SignatureScheme,
117};
118
119pub use rustls;
120
121fn coded(
122 code: Code,
123 message: impl Into<std::borrow::Cow<'static, str>>,
124 fix: &'static str,
125) -> io::Error {
126 giong::error::Error::new(code, message, fix).into()
127}
128
129fn file_too_short(offset: u64, len: u64, at: u64) -> io::Error {
132 let end = offset.saturating_add(len);
133 coded(
134 Code::FileTooShort,
135 format!(
136 "the file ended at byte {at}, {} bytes short of the {len} send_file was asked to send",
137 end - at
138 ),
139 "take the length from the open file (File::len), and replace a file that is being \
140 served by renaming a new one over it, not by rewriting it; the peer has fewer bytes \
141 than announced, so close the connection.",
142 )
143}
144
145fn bad_certificate_data(e: impl std::fmt::Display) -> io::Error {
147 coded(
148 Code::BadCertificateData,
149 e.to_string(),
150 "check that the file or data is PEM (\"-----BEGIN CERTIFICATE-----\") and holds \
151 at least one certificate.",
152 )
153}
154
155fn bad_key(e: impl std::fmt::Display) -> io::Error {
157 coded(
158 Code::BadCertificateData,
159 format!("cannot read the private key: {e}"),
160 "check that it is a PEM private key (\"-----BEGIN PRIVATE KEY-----\", or the RSA or \
161 EC forms).",
162 )
163}
164
165fn mismatched_key(e: rustls::Error) -> io::Error {
167 coded(
168 Code::BadCertificateData,
169 format!("the certificate and the private key cannot be used together: {e}"),
170 "check that the key belongs to the first certificate of the chain, and that its type \
171 (RSA, ECDSA, Ed25519) is supported.",
172 )
173}
174
175fn tls_error(e: rustls::Error) -> io::Error {
177 match e {
178 rustls::Error::InvalidCertificate(_) if e.to_string().contains("CaUsedAsEndEntity") => {
181 coded(
182 Code::TlsCertificate,
183 "the peer's certificate was rejected: it is marked as a certificate authority \
184 (basicConstraints CA:TRUE), and an authority's certificate cannot be the \
185 peer's own (CaUsedAsEndEntity)",
186 "issue the peer's certificate with CA:FALSE: a self-signed one made with \
187 `openssl req -x509` needs -addext \"basicConstraints=critical,CA:FALSE\"; or \
188 have the authority sign a separate certificate for the peer.",
189 )
190 }
191 rustls::Error::InvalidCertificate(_) => coded(
192 Code::TlsCertificate,
193 format!("the peer's certificate was rejected: {e}"),
194 "check the name you connect to, the certificate's expiry and its chain; a \
195 private authority has to be trusted with TlsConnector::with_roots.",
196 ),
197 e => coded(
198 Code::TlsProtocol,
199 format!("TLS error: {e}"),
200 "check that the other side speaks TLS on this port, and that both sides share a \
201 protocol version and cipher suite.",
202 ),
203 }
204}
205
206const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
208
209fn handshake_timed_out(limit: Duration) -> io::Error {
210 coded(
211 Code::TlsHandshakeTimeout,
212 format!("the TLS handshake did not finish within {limit:?}"),
213 "check that the other side speaks TLS on this port and is not overloaded, or raise \
214 handshake_timeout.",
215 )
216}
217
218fn handshake_eof() -> io::Error {
219 coded(
220 Code::TlsHandshakeEof,
221 "the peer closed the connection during the TLS handshake",
222 "check that the other side speaks TLS on this port, and whether it wants a client \
223 certificate or another server name.",
224 )
225}
226
227const WIRE_KEPT: usize = 16 * 1024;
232
233fn has_application_data(records: &[u8]) -> bool {
237 let mut at = 0;
238 while let Some(header) = records.get(at..at + 5) {
239 if header[0] == 23 {
240 return true;
241 }
242 at += 5 + usize::from(u16::from_be_bytes([header[3], header[4]]));
243 }
244 false
245}
246
247fn sending_closed(code: Code) -> io::Error {
250 match code {
251 Code::TlsKeysExhausted => coded(
252 Code::TlsKeysExhausted,
253 "this connection has sent as many TLS records as its cipher allows under one key, \
254 and cannot change keys (TLS 1.2, or TLS 1.3 on a kernel older than 6.14); \
255 close_notify was sent",
256 "open a new connection. TLS 1.3 changes keys instead (in the process, and with \
257 kernel TLS on Linux 6.14 or newer).",
258 ),
259 _ => coded(
260 Code::TlsBroken,
261 "this TLS stream has been shut down or ended with an alert; nothing more can be sent",
262 "open a new connection.",
263 ),
264 }
265}
266
267fn broken() -> io::Error {
268 coded(
269 Code::TlsBroken,
270 "a TLS write failed or was cancelled; nothing more can be sent",
271 "open a new connection. A write cancelled half-way (a dropped future, a timeout) \
272 leaves a partial record or message behind, so the stream cannot go on.",
273 )
274}
275
276fn pem_certs(pem: &[u8]) -> io::Result<Vec<CertificateDer<'static>>> {
278 let certs = CertificateDer::pem_slice_iter(pem)
279 .collect::<Result<Vec<_>, _>>()
280 .map_err(bad_certificate_data)?;
281 if certs.is_empty() {
282 return Err(bad_certificate_data("no certificate found in the PEM data"));
283 }
284 Ok(certs)
285}
286
287fn ring() -> Arc<rustls::crypto::CryptoProvider> {
288 Arc::new(rustls::crypto::ring::default_provider())
289}
290
291#[derive(Clone)]
295pub struct TlsAcceptor {
296 config: Arc<ServerConfig>,
297 handshake_timeout: Duration,
298 ktls: ktls::Plan,
299}
300
301impl TlsAcceptor {
302 pub fn new(config: Arc<ServerConfig>) -> Self {
304 Self {
305 config,
306 handshake_timeout: HANDSHAKE_TIMEOUT,
307 ktls: ktls::Plan::Off,
308 }
309 }
310
311 pub fn from_pem(cert_chain: &[u8], private_key: &[u8]) -> io::Result<Self> {
316 let certs = pem_certs(cert_chain)?;
317 let key = PrivateKeyDer::from_pem_slice(private_key).map_err(bad_key)?;
318 let config = ServerConfig::builder_with_provider(ring())
319 .with_safe_default_protocol_versions()
320 .map_err(tls_error)?
321 .with_no_client_auth()
322 .with_single_cert(certs, key)
323 .map_err(mismatched_key)?;
324 Ok(Self::new(Arc::new(config)))
325 }
326
327 pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
335 Arc::make_mut(&mut self.config).alpn_protocols =
336 protocols.iter().map(|p| p.to_vec()).collect();
337 self
338 }
339
340 pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
343 self.handshake_timeout = timeout;
344 self
345 }
346
347 pub fn ktls(mut self, mode: Ktls) -> io::Result<Self> {
373 let early_data = self.config.max_early_data_size > 0;
374 self.ktls = ktls::Plan::new(mode, self.config.crypto_provider(), early_data)?;
375 let extract = self.ktls.tries();
377 if self.config.enable_secret_extraction != extract {
378 Arc::make_mut(&mut self.config).enable_secret_extraction = extract;
379 }
380 Ok(self)
381 }
382
383 pub fn ktls_unavailable(&self) -> Option<&str> {
388 self.ktls.unavailable()
389 }
390
391 pub async fn accept(&self, tcp: TcpStream) -> io::Result<TlsStream> {
397 let tcp = match &self.ktls {
398 ktls::Plan::Off => tcp,
399 ktls::Plan::Try { required } => {
400 let start = ktls::Start::Server(self.config.clone());
401 match ktls::handshake(tcp, start, self.handshake_timeout).await? {
402 ktls::Outcome::Kernel(tls) => return Ok(*tls),
403 ktls::Outcome::Declined(_, e) if *required => return Err(e),
404 ktls::Outcome::Declined(tcp, _) => {
405 self.ktls.stayed();
406 tcp
407 }
408 }
409 }
410 ktls::Plan::Unavailable(_) => {
411 self.ktls.stayed();
412 tcp
413 }
414 };
415 let conn = ServerConnection::new(self.config.clone()).map_err(tls_error)?;
416 TlsStream::new(tcp, conn.into())
417 .handshake(self.handshake_timeout)
418 .await
419 }
420}
421
422impl std::fmt::Debug for TlsAcceptor {
423 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
424 f.debug_struct("TlsAcceptor")
425 .field("handshake_timeout", &self.handshake_timeout)
426 .field("ktls", &self.ktls)
427 .finish_non_exhaustive()
428 }
429}
430
431#[derive(Clone)]
452pub struct TlsConnector {
453 config: Arc<ClientConfig>,
454 handshake_timeout: Duration,
455 ktls: ktls::Plan,
456}
457
458impl TlsConnector {
459 pub fn new(config: Arc<ClientConfig>) -> Self {
461 Self {
462 config,
463 handshake_timeout: HANDSHAKE_TIMEOUT,
464 ktls: ktls::Plan::Off,
465 }
466 }
467
468 pub fn with_roots(roots: RootCertStore) -> io::Result<Self> {
471 if roots.is_empty() {
472 return Err(coded(
473 Code::NoTrustedRoots,
474 "no trusted certificate authority given",
475 "pass at least one certificate, or use TlsConnector::with_system_roots.",
476 ));
477 }
478 let config = ClientConfig::builder_with_provider(ring())
479 .with_safe_default_protocol_versions()
480 .map_err(tls_error)?
481 .with_root_certificates(roots)
482 .with_no_client_auth();
483 Ok(Self::new(Arc::new(config)))
484 }
485
486 pub fn with_root_pem(pem: &[u8]) -> io::Result<Self> {
495 let mut roots = RootCertStore::empty();
496 for cert in pem_certs(pem)? {
497 roots.add(cert).map_err(bad_certificate_data)?;
498 }
499 Self::with_roots(roots)
500 }
501
502 pub fn with_system_roots() -> io::Result<Self> {
518 let file = std::env::var_os("SSL_CERT_FILE");
519 let dirs = std::env::var_os("SSL_CERT_DIR");
520 let roots = load_roots(
521 file.as_deref(),
522 dirs.as_deref(),
523 SYSTEM_CA_BUNDLES,
524 SYSTEM_CA_DIR,
525 )?;
526 Self::with_roots(roots)
527 }
528
529 #[cfg(feature = "webpki-roots")]
536 pub fn with_webpki_roots() -> Self {
537 let roots = RootCertStore {
538 roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
539 };
540 Self::with_roots(roots).expect("the webpki-roots crate provides roots")
541 }
542
543 pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
547 Arc::make_mut(&mut self.config).alpn_protocols =
548 protocols.iter().map(|p| p.to_vec()).collect();
549 self
550 }
551
552 pub fn client_auth(mut self, cert_chain: &[u8], private_key: &[u8]) -> io::Result<Self> {
555 let certs = pem_certs(cert_chain)?;
556 let key = PrivateKeyDer::from_pem_slice(private_key).map_err(bad_key)?;
557 let key = CertifiedKey::from_der(certs, key, self.config.crypto_provider())
558 .map_err(mismatched_key)?;
559 Arc::make_mut(&mut self.config).client_auth_cert_resolver =
560 Arc::new(ClientCert(Arc::new(key)));
561 Ok(self)
562 }
563
564 pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
567 self.handshake_timeout = timeout;
568 self
569 }
570
571 pub fn ktls(mut self, mode: Ktls) -> io::Result<Self> {
585 let early_data = self.config.enable_early_data;
586 self.ktls = ktls::Plan::new(mode, self.config.crypto_provider(), early_data)?;
587 let extract = self.ktls.tries();
588 if self.config.enable_secret_extraction != extract {
589 Arc::make_mut(&mut self.config).enable_secret_extraction = extract;
590 }
591 Ok(self)
592 }
593
594 pub fn ktls_unavailable(&self) -> Option<&str> {
597 self.ktls.unavailable()
598 }
599
600 pub async fn connect(&self, server_name: &str, tcp: TcpStream) -> io::Result<TlsStream> {
609 let name = parse_server_name(server_name)?;
610 let tcp = match &self.ktls {
611 ktls::Plan::Off => tcp,
612 ktls::Plan::Try { required } => {
613 let start = ktls::Start::Client(self.config.clone(), name.clone());
614 match ktls::handshake(tcp, start, self.handshake_timeout).await? {
615 ktls::Outcome::Kernel(tls) => return Ok(*tls),
616 ktls::Outcome::Declined(_, e) if *required => return Err(e),
617 ktls::Outcome::Declined(tcp, _) => {
618 self.ktls.stayed();
619 tcp
620 }
621 }
622 }
623 ktls::Plan::Unavailable(_) => {
624 self.ktls.stayed();
625 tcp
626 }
627 };
628 let conn = ClientConnection::new(self.config.clone(), name).map_err(tls_error)?;
629 TlsStream::new(tcp, conn.into())
630 .handshake(self.handshake_timeout)
631 .await
632 }
633}
634
635impl std::fmt::Debug for TlsConnector {
636 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
637 f.debug_struct("TlsConnector")
638 .field("handshake_timeout", &self.handshake_timeout)
639 .field("ktls", &self.ktls)
640 .finish_non_exhaustive()
641 }
642}
643
644fn parse_server_name(name: &str) -> io::Result<ServerName<'static>> {
646 let ipv6 = name
647 .strip_prefix('[')
648 .and_then(|n| n.strip_suffix(']'))
649 .and_then(|n| n.parse::<std::net::Ipv6Addr>().ok());
650 if let Some(ip) = ipv6 {
651 return Ok(ServerName::IpAddress(std::net::IpAddr::V6(ip).into()));
652 }
653 ServerName::try_from(name.to_owned()).map_err(|_| {
654 coded(
655 Code::InvalidServerName,
656 format!("{name:?} is neither a DNS name nor an IP address"),
657 "pass the host name the certificate is for (\"example.com\"), or an IP address, \
658 without a port or a scheme.",
659 )
660 })
661}
662
663#[derive(Debug)]
665struct ClientCert(Arc<CertifiedKey>);
666
667impl ResolvesClientCert for ClientCert {
668 fn resolve(&self, _: &[&[u8]], _: &[SignatureScheme]) -> Option<Arc<CertifiedKey>> {
669 Some(self.0.clone())
670 }
671
672 fn has_certs(&self) -> bool {
673 true
674 }
675}
676
677const SYSTEM_CA_BUNDLES: &[&str] = &[
679 "/etc/ssl/certs/ca-certificates.crt",
681 "/etc/pki/tls/certs/ca-bundle.crt",
683 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
684 "/etc/ssl/ca-bundle.pem",
686 "/etc/ssl/cert.pem",
688];
689
690const SYSTEM_CA_DIR: &str = "/etc/ssl/certs";
692
693fn load_roots(
698 file: Option<&OsStr>,
699 dirs: Option<&OsStr>,
700 bundles: &[&str],
701 dir: &str,
702) -> io::Result<RootCertStore> {
703 let mut roots = Roots {
704 store: RootCertStore::empty(),
705 seen: HashSet::new(),
706 };
707 if file.is_some() || dirs.is_some() {
708 if let Some(file) = file {
709 roots.add_file(Path::new(file)).map_err(|e| {
710 io::Error::new(
711 e.kind(),
712 giong::error::Error::new(
713 Code::BadCertificateData,
714 format!("cannot read SSL_CERT_FILE {file:?}: {e}"),
715 "point SSL_CERT_FILE at a readable PEM file of certificates, or unset \
716 it to use the system's.",
717 )
718 .with_source(e),
719 )
720 })?;
721 }
722 for dir in dirs.map(std::env::split_paths).into_iter().flatten() {
723 roots.add_dir(&dir);
724 }
725 } else if let Some(bundle) = bundles.iter().map(Path::new).find(|p| p.is_file()) {
726 roots.add_file(bundle)?;
727 } else {
728 roots.add_dir(Path::new(dir));
729 }
730 if roots.store.is_empty() {
731 return Err(coded(
732 Code::NoTrustedRoots,
733 "no trusted CA certificates found on this machine",
734 "install the ca-certificates package, set SSL_CERT_FILE, or use \
735 TlsConnector::with_webpki_roots (the webpki-roots feature of giong-tls).",
736 ));
737 }
738 Ok(roots.store)
739}
740
741struct Roots {
742 store: RootCertStore,
743 seen: HashSet<PathBuf>,
746}
747
748impl Roots {
749 fn add_file(&mut self, path: &Path) -> io::Result<()> {
750 let real = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
751 if !self.seen.insert(real) {
752 return Ok(());
753 }
754 let pem = std::fs::read(path)?;
755 let certs = CertificateDer::pem_slice_iter(&pem).filter_map(Result::ok);
756 self.store.add_parsable_certificates(certs);
757 Ok(())
758 }
759
760 fn add_dir(&mut self, dir: &Path) {
761 let Ok(entries) = std::fs::read_dir(dir) else {
762 return;
763 };
764 let mut paths: Vec<PathBuf> = entries.filter_map(|e| Some(e.ok()?.path())).collect();
765 paths.sort();
766 for path in paths.iter().filter(|p| p.is_file()) {
767 let _ = self.add_file(path);
769 }
770 }
771}
772
773pub struct TlsStream {
776 tcp: TcpStream,
777 engine: RefCell<Engine>,
779 plain: RefCell<Vec<u8>>,
781 wire: RefCell<Vec<u8>>,
784 eof: Cell<bool>,
786 close_notify: Cell<bool>,
789 sending: Cell<bool>,
793 broken: Cell<bool>,
796 closed: Cell<Option<Code>>,
800 failed: Cell<Option<io::Error>>,
802 waiters: RefCell<Vec<Waker>>,
804}
805
806#[allow(clippy::large_enum_variant)]
810enum Engine {
811 User(Connection),
813 Kernel(ktls::Kernel),
816}
817
818struct Sending<'a> {
822 stream: &'a TlsStream,
823 complete: bool,
824}
825
826impl Sending<'_> {
827 fn done(mut self) {
829 self.complete = true;
830 }
831}
832
833impl Drop for Sending<'_> {
834 fn drop(&mut self) {
835 if !self.complete {
836 self.stream.broken.set(true);
837 }
838 self.stream.sending.set(false);
839 self.stream.wake_waiters();
840 }
841}
842
843impl TlsStream {
844 fn new(tcp: TcpStream, conn: Connection) -> Self {
845 Self::with_engine(tcp, Engine::User(conn), Vec::new(), false)
846 }
847
848 fn kernel(tcp: TcpStream, kernel: ktls::Kernel, plain: Vec<u8>, peer_closed: bool) -> Self {
852 Self::with_engine(tcp, Engine::Kernel(kernel), plain, peer_closed)
853 }
854
855 fn with_engine(tcp: TcpStream, engine: Engine, plain: Vec<u8>, peer_closed: bool) -> Self {
856 Self {
857 tcp,
858 engine: RefCell::new(engine),
859 plain: RefCell::new(plain),
860 wire: RefCell::new(Vec::new()),
861 eof: Cell::new(peer_closed),
862 close_notify: Cell::new(peer_closed),
863 sending: Cell::new(false),
864 broken: Cell::new(false),
865 closed: Cell::new(None),
866 failed: Cell::new(None),
867 waiters: RefCell::new(Vec::new()),
868 }
869 }
870
871 fn conn(&self) -> RefMut<'_, Connection> {
874 RefMut::map(self.engine.borrow_mut(), |e| match e {
875 Engine::User(c) => c,
876 Engine::Kernel(_) => unreachable!("rustls' connection on a kernel TLS stream"),
877 })
878 }
879
880 pub fn is_ktls(&self) -> bool {
884 matches!(*self.engine.borrow(), Engine::Kernel(_))
885 }
886
887 async fn wait_for_sender(&self) {
889 poll_fn(|cx| {
890 if !self.sending.get() {
891 return Poll::Ready(());
892 }
893 let mut waiters = self.waiters.borrow_mut();
895 if !waiters.iter().any(|w| w.will_wake(cx.waker())) {
896 waiters.push(cx.waker().clone());
897 }
898 Poll::Pending
899 })
900 .await;
901 }
902
903 async fn lock_send(&self) -> Sending<'_> {
906 while self.sending.get() {
907 self.wait_for_sender().await;
908 }
909 self.sending.set(true);
910 Sending {
911 stream: self,
912 complete: false,
913 }
914 }
915
916 async fn handshake(self, limit: Duration) -> io::Result<Self> {
918 let handshake = async {
919 while self.conn().is_handshaking() {
920 self.flush_tls().await?;
921 if !self.conn().is_handshaking() {
922 break;
923 }
924 if self.eof.get() {
925 return Err(handshake_eof());
926 }
927 self.pump().await?;
928 }
929 self.flush_tls().await
930 };
931 match timeout(limit, handshake).await {
932 Ok(Ok(())) => Ok(self),
933 Ok(Err(e)) => Err(e),
934 Err(_) => Err(handshake_timed_out(limit)),
935 }
936 }
937
938 fn wake_waiters(&self) {
941 let waiters = mem::take(&mut *self.waiters.borrow_mut());
942 for waker in waiters {
943 waker.wake();
944 }
945 }
946
947 fn take_wire(&self) -> Vec<u8> {
949 mem::take(&mut *self.wire.borrow_mut())
950 }
951
952 fn keep_wire(&self, mut wire: Vec<u8>) {
956 if wire.capacity() <= WIRE_KEPT {
957 wire.clear();
958 *self.wire.borrow_mut() = wire;
959 }
960 }
961
962 fn cannot_send(&self) -> Option<io::Error> {
965 if self.broken.get() {
966 return Some(broken());
967 }
968 self.closed.get().map(sending_closed)
969 }
970
971 async fn flush_tls(&self) -> io::Result<()> {
975 loop {
976 if !self.conn().wants_write() {
977 return Ok(());
978 }
979 if self.broken.get() {
980 return Err(broken());
981 }
982 if self.sending.get() {
983 self.wait_for_sender().await;
986 continue;
987 }
988 let sending = self.lock_send().await;
989 let mut wire = self.take_wire();
990 let res = self.send_queued(&mut wire).await;
991 self.keep_wire(wire);
992 sending.done();
993 res?;
994 }
995 }
996
997 async fn send_queued(&self, wire: &mut Vec<u8>) -> io::Result<()> {
1000 loop {
1001 {
1002 let mut conn = self.conn();
1003 if !conn.wants_write() {
1004 return Ok(());
1005 }
1006 while conn.wants_write() {
1007 conn.write_tls(wire)?;
1008 }
1009 }
1010 self.send_wire(wire).await?;
1011 }
1012 }
1013
1014 async fn send_wire(&self, wire: &mut Vec<u8>) -> io::Result<()> {
1018 let (res, mut sent) = self.tcp.write_all(mem::take(wire)).await;
1019 sent.clear();
1020 *wire = sent;
1021 if res.is_err() {
1022 self.broken.set(true);
1023 }
1024 res
1025 }
1026
1027 async fn send_plain(&self, wire: &mut Vec<u8>, data: &[u8]) -> io::Result<()> {
1033 let mut sent = 0;
1034 while sent < data.len() {
1035 let (carried, refused) = {
1036 let mut conn = self.conn();
1037 while conn.wants_write() {
1038 conn.write_tls(wire)?;
1039 }
1040 let carried = !wire.is_empty();
1041 let start = wire.len();
1042 let n = conn.writer().write(&data[sent..])?;
1043 while conn.wants_write() {
1044 conn.write_tls(wire)?;
1045 }
1046 sent += n;
1047 (carried, n > 0 && !has_application_data(&wire[start..]))
1052 };
1053 if !wire.is_empty() {
1054 self.send_wire(wire).await?;
1055 }
1056 if carried {
1057 self.wake_waiters();
1059 }
1060 if refused {
1061 self.closed.set(Some(Code::TlsKeysExhausted));
1062 return Err(sending_closed(Code::TlsKeysExhausted));
1063 }
1064 }
1065 Ok(())
1066 }
1067
1068 async fn write_in_process(&self, pieces: &[&[u8]]) -> io::Result<()> {
1072 let sending = self.lock_send().await;
1073 if let Some(e) = self.cannot_send() {
1074 sending.done();
1075 return Err(e);
1076 }
1077 let mut wire = self.take_wire();
1078 let mut res = Ok(());
1079 for piece in pieces {
1080 res = self.send_plain(&mut wire, piece).await;
1081 if res.is_err() {
1082 break;
1083 }
1084 }
1085 self.keep_wire(wire);
1086 sending.done();
1090 res
1091 }
1092
1093 async fn pump(&self) -> io::Result<()> {
1096 let chunk = self.tcp.recv().await?;
1098 if chunk.is_empty() {
1099 self.eof.set(true);
1100 return Ok(());
1101 }
1102 let result = {
1103 let mut conn = self.conn();
1104 let mut plain = self.plain.borrow_mut();
1105 let mut input = &chunk[..];
1106 let mut result = Ok(());
1107 while !input.is_empty() {
1108 match conn.read_tls(&mut input) {
1111 Ok(0) => {
1112 result = Err(coded(
1113 Code::TlsProtocol,
1114 "rustls accepted no more TLS data",
1115 "this is a bug in giong-tls; please report it at \
1116 https://github.com/giong-run/Giong/issues.",
1117 ));
1118 break;
1119 }
1120 Ok(_) => {}
1121 Err(e) => {
1122 result = Err(e);
1123 break;
1124 }
1125 }
1126 match conn.process_new_packets() {
1127 Ok(state) => {
1128 let n = state.plaintext_bytes_to_read();
1129 if n > 0 {
1130 let at = plain.len();
1131 plain.resize(at + n, 0);
1132 if let Err(e) = conn.reader().read_exact(&mut plain[at..]) {
1133 plain.truncate(at);
1134 result = Err(e);
1135 break;
1136 }
1137 }
1138 if state.peer_has_closed() {
1139 self.close_notify.set(true);
1140 self.eof.set(true);
1141 break;
1142 }
1143 }
1144 Err(e) => {
1145 result = Err(tls_error(e));
1146 break;
1147 }
1148 }
1149 }
1150 result
1151 };
1152 drop(chunk);
1153 if self.broken.get() {
1157 return result;
1158 }
1159 let flushed = self.flush_tls().await;
1160 result.and(flushed)
1161 }
1162
1163 pub async fn recv(&self) -> io::Result<Received> {
1181 if self.is_ktls() {
1182 return self.kernel_recv().await.map(Received);
1183 }
1184 self.user_recv().await.map(Received)
1185 }
1186
1187 async fn user_recv(&self) -> io::Result<Vec<u8>> {
1188 loop {
1189 {
1190 let mut plain = self.plain.borrow_mut();
1191 if !plain.is_empty() {
1192 return Ok(mem::take(&mut *plain));
1193 }
1194 }
1195 if let Some(e) = self.failed.take() {
1196 return Err(e);
1197 }
1198 if self.eof.get() {
1199 return Ok(Vec::new());
1200 }
1201 if let Err(e) = self.pump().await {
1202 if self.plain.borrow().is_empty() {
1204 return Err(e);
1205 }
1206 self.failed.set(Some(e));
1207 }
1208 }
1209 }
1210
1211 pub async fn write_all<B>(&self, buf: B) -> (io::Result<()>, B)
1232 where
1233 B: giong::IoBuf + AsRef<[u8]>,
1234 {
1235 if self.is_ktls() {
1236 return self.kernel_write_all(buf).await;
1237 }
1238 let res = self.write_in_process(&[buf.as_ref()]).await;
1239 (res, buf)
1240 }
1241
1242 pub async fn write_all_vectored<B>(&self, bufs: Vec<B>) -> (io::Result<()>, Vec<B>)
1254 where
1255 B: giong::IoBuf + AsRef<[u8]>,
1256 {
1257 if self.is_ktls() {
1258 return self.kernel_write_all_vectored(bufs).await;
1259 }
1260 let pieces: Vec<&[u8]> = bufs.iter().map(AsRef::as_ref).collect();
1261 let res = self.write_in_process(&pieces).await;
1262 drop(pieces);
1263 (res, bufs)
1264 }
1265
1266 pub async fn send_file(&self, file: &giong::fs::File, offset: u64, len: u64) -> io::Result<()> {
1283 if offset
1284 .checked_add(len)
1285 .map_or(true, |end| end > i64::MAX as u64)
1286 {
1287 return Err(file_too_short(offset, len, offset));
1288 }
1289 if self.is_ktls() {
1290 return self.kernel_send_file(file, offset, len).await;
1291 }
1292 let sending = self.lock_send().await;
1293 if let Some(e) = self.cannot_send() {
1294 sending.done();
1295 return Err(e);
1296 }
1297 let mut wire = self.take_wire();
1298 let res = self
1299 .send_file_in_process(&mut wire, file, offset, len)
1300 .await;
1301 self.keep_wire(wire);
1302 sending.done();
1303 res
1304 }
1305
1306 async fn send_file_in_process(
1309 &self,
1310 wire: &mut Vec<u8>,
1311 file: &giong::fs::File,
1312 offset: u64,
1313 len: u64,
1314 ) -> io::Result<()> {
1315 const PIECE: u64 = 256 * 1024;
1316 let mut buf = Vec::with_capacity(len.min(PIECE) as usize);
1317 let (mut at, mut left) = (offset, len);
1318 while left > 0 {
1319 let (res, b) = file.read_at(buf, at).await;
1320 buf = b;
1321 let n = match res {
1322 Ok(0) => return Err(file_too_short(offset, len, at)),
1323 Ok(n) => (n as u64).min(left) as usize,
1324 Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
1325 Err(e) => return Err(e),
1326 };
1327 self.send_plain(wire, &buf[..n]).await?;
1328 at += n as u64;
1329 left -= n as u64;
1330 }
1331 Ok(())
1332 }
1333
1334 pub async fn shutdown(&self) -> io::Result<()> {
1341 if self.is_ktls() {
1342 return self.kernel_shutdown().await;
1343 }
1344 let sending = self.lock_send().await;
1345 if self.cannot_send().is_none() {
1346 self.conn().send_close_notify();
1347 self.closed.set(Some(Code::TlsBroken));
1348 let mut wire = self.take_wire();
1349 let res = self.send_queued(&mut wire).await;
1350 self.keep_wire(wire);
1351 if let Err(e) = res {
1352 sending.done();
1354 let _ = self.tcp.shutdown(Shutdown::Write);
1355 return Err(e);
1356 }
1357 }
1358 sending.done();
1359 self.tcp.shutdown(Shutdown::Write)
1360 }
1361
1362 pub fn received_close_notify(&self) -> bool {
1368 self.close_notify.get()
1369 }
1370
1371 pub fn alpn_protocol(&self) -> Option<Vec<u8>> {
1373 match &*self.engine.borrow() {
1374 Engine::User(c) => c.alpn_protocol().map(<[u8]>::to_vec),
1375 Engine::Kernel(k) => k.negotiated.alpn.clone(),
1376 }
1377 }
1378
1379 pub fn peer_certificates(&self) -> Option<Vec<CertificateDer<'static>>> {
1384 match &*self.engine.borrow() {
1385 Engine::User(c) => c.peer_certificates().map(<[_]>::to_vec),
1386 Engine::Kernel(k) => k.negotiated.peer_certificates.clone(),
1387 }
1388 }
1389
1390 pub fn resumed(&self) -> bool {
1393 match &*self.engine.borrow() {
1394 Engine::User(c) => c.handshake_kind() == Some(rustls::HandshakeKind::Resumed),
1395 Engine::Kernel(k) => k.negotiated.resumed,
1396 }
1397 }
1398
1399 pub fn tcp(&self) -> &TcpStream {
1406 &self.tcp
1407 }
1408}
1409
1410impl std::fmt::Debug for TlsStream {
1411 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1412 f.debug_struct("TlsStream")
1413 .field("tcp", &self.tcp)
1414 .field("ktls", &self.is_ktls())
1415 .finish_non_exhaustive()
1416 }
1417}
1418
1419#[cfg(test)]
1420mod tests {
1421 use super::*;
1422
1423 fn ca_pem(name: &str) -> String {
1424 let key = rcgen::KeyPair::generate().unwrap();
1425 let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
1426 params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
1427 params
1428 .distinguished_name
1429 .push(rcgen::DnType::CommonName, name);
1430 params.self_signed(&key).unwrap().pem()
1431 }
1432
1433 fn scratch(name: &str) -> PathBuf {
1435 let dir = std::env::temp_dir().join(format!("giong-tls-{}-{name}", std::process::id()));
1436 let _ = std::fs::remove_dir_all(&dir);
1437 std::fs::create_dir_all(&dir).unwrap();
1438 dir
1439 }
1440
1441 fn os(path: &Path) -> &OsStr {
1442 path.as_os_str()
1443 }
1444
1445 #[test]
1446 fn server_names_are_dns_names_or_ip_addresses() {
1447 let dns = |n: &str| matches!(parse_server_name(n), Ok(ServerName::DnsName(_)));
1448 let ip = |n: &str| matches!(parse_server_name(n), Ok(ServerName::IpAddress(_)));
1449 assert!(dns("example.com"));
1450 assert!(dns("db.prod.svc.cluster.local"));
1451 assert!(ip("10.0.0.1"));
1452 assert!(ip("::1"));
1453 assert!(ip("[::1]"));
1454 for bad in ["", "not a name", "[nope]", "[10.0.0.1]", "a..b"] {
1455 let err = parse_server_name(bad).unwrap_err();
1456 assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{bad:?}");
1457 }
1458 }
1459
1460 #[test]
1461 fn the_first_bundle_that_exists_is_read() {
1462 let dir = scratch("bundle");
1463 let bundle = dir.join("bundle.pem");
1464 let two = format!("{}{}", ca_pem("one"), ca_pem("two"));
1465 std::fs::write(&bundle, two).unwrap();
1466 let missing = dir.join("missing.pem");
1467 let bundles = [missing.to_str().unwrap(), bundle.to_str().unwrap()];
1468 let roots = load_roots(None, None, &bundles, "/nonexistent").unwrap();
1469 assert_eq!(roots.len(), 2);
1470 std::fs::remove_dir_all(dir).unwrap();
1471 }
1472
1473 #[test]
1474 fn ssl_cert_file_and_dir_replace_the_system_locations() {
1475 let dir = scratch("env");
1476 let file = dir.join("file.pem");
1477 std::fs::write(&file, ca_pem("from file")).unwrap();
1478 let certs = dir.join("certs");
1479 std::fs::create_dir(&certs).unwrap();
1480 std::fs::write(certs.join("a.pem"), ca_pem("a")).unwrap();
1481 std::fs::write(certs.join("b.pem"), ca_pem("b")).unwrap();
1482 std::fs::write(certs.join("README"), "not a certificate").unwrap();
1483 std::os::unix::fs::symlink(certs.join("a.pem"), certs.join("1a2b3c4d.0")).unwrap();
1485 let system = dir.join("system.pem");
1486 std::fs::write(&system, ca_pem("system")).unwrap();
1487 let bundles = [system.to_str().unwrap()];
1488
1489 let roots = load_roots(Some(os(&file)), None, &bundles, "/nonexistent").unwrap();
1490 assert_eq!(roots.len(), 1, "SSL_CERT_FILE only");
1491 let roots = load_roots(None, Some(os(&certs)), &bundles, "/nonexistent").unwrap();
1492 assert_eq!(roots.len(), 2, "SSL_CERT_DIR only, each file once");
1493 let both = std::env::join_paths([dir.join("nowhere"), certs.clone()]).unwrap();
1494 let roots = load_roots(Some(os(&file)), Some(&both), &bundles, "/nonexistent").unwrap();
1495 assert_eq!(roots.len(), 3, "both, with a missing directory in the list");
1496
1497 let err = load_roots(Some(os(&dir.join("gone.pem"))), None, &bundles, "").unwrap_err();
1498 assert_eq!(err.kind(), io::ErrorKind::NotFound);
1499 assert!(err.to_string().contains("SSL_CERT_FILE"), "{err}");
1500 std::fs::remove_dir_all(dir).unwrap();
1501 }
1502
1503 #[test]
1504 fn without_a_bundle_the_directory_is_read_and_nothing_is_an_error() {
1505 let dir = scratch("dir");
1506 std::fs::write(dir.join("only.crt"), ca_pem("only")).unwrap();
1507 let roots = load_roots(
1508 None,
1509 None,
1510 &["/nonexistent/bundle.crt"],
1511 dir.to_str().unwrap(),
1512 );
1513 assert_eq!(roots.unwrap().len(), 1);
1514
1515 let empty = scratch("empty");
1516 let err = load_roots(None, None, &[], empty.to_str().unwrap()).unwrap_err();
1517 assert_eq!(err.kind(), io::ErrorKind::NotFound);
1518 assert!(err.to_string().contains("webpki-roots"), "{err}");
1519 std::fs::remove_dir_all(dir).unwrap();
1520 std::fs::remove_dir_all(empty).unwrap();
1521 }
1522
1523 #[test]
1524 fn records_are_scanned_for_application_data() {
1525 let record = |typ: u8, len: u16| {
1527 let mut r = vec![typ, 3, 3];
1528 r.extend_from_slice(&len.to_be_bytes());
1529 r.resize(5 + len as usize, 0xAA);
1530 r
1531 };
1532 assert!(!has_application_data(&[]));
1533 assert!(!has_application_data(&record(21, 26)));
1534 assert!(has_application_data(&record(23, 0)));
1535 let mut alert_then_data = record(21, 26);
1536 alert_then_data.extend(record(23, 300));
1537 assert!(has_application_data(&alert_then_data));
1538 let mut alert = record(21, 26);
1540 alert[5] = 23;
1541 assert!(!has_application_data(&alert));
1542 }
1543
1544 #[test]
1545 fn secrets_are_extractable_only_when_the_kernel_will_take_them() {
1546 let key = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
1547 let (cert, key) = (key.cert.pem(), key.key_pair.serialize_pem());
1548 for mode in [Ktls::Off, Ktls::Auto] {
1549 let acceptor = TlsAcceptor::from_pem(cert.as_bytes(), key.as_bytes())
1550 .unwrap()
1551 .ktls(mode)
1552 .unwrap();
1553 let tries = acceptor.ktls.tries();
1554 assert_eq!(acceptor.config.enable_secret_extraction, tries, "{mode:?}");
1555 let connector = TlsConnector::with_root_pem(cert.as_bytes())
1556 .unwrap()
1557 .ktls(mode)
1558 .unwrap();
1559 let tries = connector.ktls.tries();
1560 assert_eq!(connector.config.enable_secret_extraction, tries, "{mode:?}");
1561 }
1562 }
1563
1564 #[test]
1565 fn this_machines_roots_load() {
1566 TlsConnector::with_system_roots().unwrap();
1568 }
1569
1570 #[cfg(feature = "webpki-roots")]
1571 #[test]
1572 fn mozillas_roots_are_compiled_in() {
1573 TlsConnector::with_webpki_roots();
1574 }
1575}