1#![warn(missing_docs)]
80
81mod ktls;
82
83pub use ktls::{ktls_stats, ktls_support, Ktls, KtlsStats, KtlsSupport};
84
85#[cfg(fuzzing)]
88#[doc(hidden)]
89pub mod fuzzing {
90 pub use crate::ktls::{check_handshake_messages, check_record_framing};
91}
92
93use std::cell::{Cell, RefCell, RefMut};
94use std::collections::HashSet;
95use std::ffi::OsStr;
96use std::future::poll_fn;
97use std::io::{self, Read, Write};
98use std::mem;
99use std::net::Shutdown;
100use std::path::{Path, PathBuf};
101use std::sync::Arc;
102use std::task::{Poll, Waker};
103use std::time::Duration;
104
105use giong::error::Code;
106use giong::net::TcpStream;
107use giong::time::timeout;
108use rustls::client::ResolvesClientCert;
109use rustls::pki_types::pem::PemObject;
110use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName};
111use rustls::sign::CertifiedKey;
112use rustls::{
113 ClientConfig, ClientConnection, Connection, RootCertStore, ServerConfig, ServerConnection,
114 SignatureScheme,
115};
116
117pub use rustls;
118
119fn coded(
120 code: Code,
121 message: impl Into<std::borrow::Cow<'static, str>>,
122 fix: &'static str,
123) -> io::Error {
124 giong::error::Error::new(code, message, fix).into()
125}
126
127fn file_too_short(offset: u64, len: u64, at: u64) -> io::Error {
130 let end = offset.saturating_add(len);
131 coded(
132 Code::FileTooShort,
133 format!(
134 "the file ended at byte {at}, {} bytes short of the {len} send_file was asked to send",
135 end - at
136 ),
137 "take the length from the open file (File::len), and replace a file that is being \
138 served by renaming a new one over it, not by rewriting it; the peer has fewer bytes \
139 than announced, so close the connection.",
140 )
141}
142
143fn bad_certificate_data(e: impl std::fmt::Display) -> io::Error {
145 coded(
146 Code::BadCertificateData,
147 e.to_string(),
148 "check that the file or data is PEM (\"-----BEGIN CERTIFICATE-----\") and holds \
149 at least one certificate.",
150 )
151}
152
153fn bad_key(e: impl std::fmt::Display) -> io::Error {
155 coded(
156 Code::BadCertificateData,
157 format!("cannot read the private key: {e}"),
158 "check that it is a PEM private key (\"-----BEGIN PRIVATE KEY-----\", or the RSA or \
159 EC forms).",
160 )
161}
162
163fn mismatched_key(e: rustls::Error) -> io::Error {
165 coded(
166 Code::BadCertificateData,
167 format!("the certificate and the private key cannot be used together: {e}"),
168 "check that the key belongs to the first certificate of the chain, and that its type \
169 (RSA, ECDSA, Ed25519) is supported.",
170 )
171}
172
173fn tls_error(e: rustls::Error) -> io::Error {
175 match e {
176 rustls::Error::InvalidCertificate(_) => coded(
177 Code::TlsCertificate,
178 format!("the peer's certificate was rejected: {e}"),
179 "check the name you connect to, the certificate's expiry and its chain; a \
180 private authority has to be trusted with TlsConnector::with_roots.",
181 ),
182 e => coded(
183 Code::TlsProtocol,
184 format!("TLS error: {e}"),
185 "check that the other side speaks TLS on this port, and that both sides share a \
186 protocol version and cipher suite.",
187 ),
188 }
189}
190
191const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
193
194fn handshake_timed_out(limit: Duration) -> io::Error {
195 coded(
196 Code::TlsHandshakeTimeout,
197 format!("the TLS handshake did not finish within {limit:?}"),
198 "check that the other side speaks TLS on this port and is not overloaded, or raise \
199 handshake_timeout.",
200 )
201}
202
203fn handshake_eof() -> io::Error {
204 coded(
205 Code::TlsHandshakeEof,
206 "the peer closed the connection during the TLS handshake",
207 "check that the other side speaks TLS on this port, and whether it wants a client \
208 certificate or another server name.",
209 )
210}
211
212const WIRE_KEPT: usize = 16 * 1024;
217
218fn has_application_data(records: &[u8]) -> bool {
222 let mut at = 0;
223 while let Some(header) = records.get(at..at + 5) {
224 if header[0] == 23 {
225 return true;
226 }
227 at += 5 + usize::from(u16::from_be_bytes([header[3], header[4]]));
228 }
229 false
230}
231
232fn sending_closed(code: Code) -> io::Error {
235 match code {
236 Code::TlsKeysExhausted => coded(
237 Code::TlsKeysExhausted,
238 "this connection has sent as many TLS records as its cipher allows under one key, \
239 and cannot change keys (TLS 1.2, or TLS 1.3 on a kernel older than 6.14); \
240 close_notify was sent",
241 "open a new connection. TLS 1.3 changes keys instead (in the process, and with \
242 kernel TLS on Linux 6.14 or newer).",
243 ),
244 _ => coded(
245 Code::TlsBroken,
246 "this TLS stream has been shut down or ended with an alert; nothing more can be sent",
247 "open a new connection.",
248 ),
249 }
250}
251
252fn broken() -> io::Error {
253 coded(
254 Code::TlsBroken,
255 "a TLS write failed or was cancelled; nothing more can be sent",
256 "open a new connection. A write cancelled half-way (a dropped future, a timeout) \
257 leaves a partial record or message behind, so the stream cannot go on.",
258 )
259}
260
261fn pem_certs(pem: &[u8]) -> io::Result<Vec<CertificateDer<'static>>> {
263 let certs = CertificateDer::pem_slice_iter(pem)
264 .collect::<Result<Vec<_>, _>>()
265 .map_err(bad_certificate_data)?;
266 if certs.is_empty() {
267 return Err(bad_certificate_data("no certificate found in the PEM data"));
268 }
269 Ok(certs)
270}
271
272fn ring() -> Arc<rustls::crypto::CryptoProvider> {
273 Arc::new(rustls::crypto::ring::default_provider())
274}
275
276#[derive(Clone)]
280pub struct TlsAcceptor {
281 config: Arc<ServerConfig>,
282 handshake_timeout: Duration,
283 ktls: ktls::Plan,
284}
285
286impl TlsAcceptor {
287 pub fn new(config: Arc<ServerConfig>) -> Self {
289 Self {
290 config,
291 handshake_timeout: HANDSHAKE_TIMEOUT,
292 ktls: ktls::Plan::Off,
293 }
294 }
295
296 pub fn from_pem(cert_chain: &[u8], private_key: &[u8]) -> io::Result<Self> {
301 let certs = pem_certs(cert_chain)?;
302 let key = PrivateKeyDer::from_pem_slice(private_key).map_err(bad_key)?;
303 let config = ServerConfig::builder_with_provider(ring())
304 .with_safe_default_protocol_versions()
305 .map_err(tls_error)?
306 .with_no_client_auth()
307 .with_single_cert(certs, key)
308 .map_err(mismatched_key)?;
309 Ok(Self::new(Arc::new(config)))
310 }
311
312 pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
320 Arc::make_mut(&mut self.config).alpn_protocols =
321 protocols.iter().map(|p| p.to_vec()).collect();
322 self
323 }
324
325 pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
328 self.handshake_timeout = timeout;
329 self
330 }
331
332 pub fn ktls(mut self, mode: Ktls) -> io::Result<Self> {
358 let early_data = self.config.max_early_data_size > 0;
359 self.ktls = ktls::Plan::new(mode, self.config.crypto_provider(), early_data)?;
360 let extract = self.ktls.tries();
362 if self.config.enable_secret_extraction != extract {
363 Arc::make_mut(&mut self.config).enable_secret_extraction = extract;
364 }
365 Ok(self)
366 }
367
368 pub fn ktls_unavailable(&self) -> Option<&str> {
373 self.ktls.unavailable()
374 }
375
376 pub async fn accept(&self, tcp: TcpStream) -> io::Result<TlsStream> {
382 let tcp = match &self.ktls {
383 ktls::Plan::Off => tcp,
384 ktls::Plan::Try { required } => {
385 let start = ktls::Start::Server(self.config.clone());
386 match ktls::handshake(tcp, start, self.handshake_timeout).await? {
387 ktls::Outcome::Kernel(tls) => return Ok(*tls),
388 ktls::Outcome::Declined(_, e) if *required => return Err(e),
389 ktls::Outcome::Declined(tcp, _) => {
390 self.ktls.stayed();
391 tcp
392 }
393 }
394 }
395 ktls::Plan::Unavailable(_) => {
396 self.ktls.stayed();
397 tcp
398 }
399 };
400 let conn = ServerConnection::new(self.config.clone()).map_err(tls_error)?;
401 TlsStream::new(tcp, conn.into())
402 .handshake(self.handshake_timeout)
403 .await
404 }
405}
406
407impl std::fmt::Debug for TlsAcceptor {
408 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
409 f.debug_struct("TlsAcceptor")
410 .field("handshake_timeout", &self.handshake_timeout)
411 .field("ktls", &self.ktls)
412 .finish_non_exhaustive()
413 }
414}
415
416#[derive(Clone)]
437pub struct TlsConnector {
438 config: Arc<ClientConfig>,
439 handshake_timeout: Duration,
440 ktls: ktls::Plan,
441}
442
443impl TlsConnector {
444 pub fn new(config: Arc<ClientConfig>) -> Self {
446 Self {
447 config,
448 handshake_timeout: HANDSHAKE_TIMEOUT,
449 ktls: ktls::Plan::Off,
450 }
451 }
452
453 pub fn with_roots(roots: RootCertStore) -> io::Result<Self> {
456 if roots.is_empty() {
457 return Err(coded(
458 Code::NoTrustedRoots,
459 "no trusted certificate authority given",
460 "pass at least one certificate, or use TlsConnector::with_system_roots.",
461 ));
462 }
463 let config = ClientConfig::builder_with_provider(ring())
464 .with_safe_default_protocol_versions()
465 .map_err(tls_error)?
466 .with_root_certificates(roots)
467 .with_no_client_auth();
468 Ok(Self::new(Arc::new(config)))
469 }
470
471 pub fn with_root_pem(pem: &[u8]) -> io::Result<Self> {
474 let mut roots = RootCertStore::empty();
475 for cert in pem_certs(pem)? {
476 roots.add(cert).map_err(bad_certificate_data)?;
477 }
478 Self::with_roots(roots)
479 }
480
481 pub fn with_system_roots() -> io::Result<Self> {
497 let file = std::env::var_os("SSL_CERT_FILE");
498 let dirs = std::env::var_os("SSL_CERT_DIR");
499 let roots = load_roots(
500 file.as_deref(),
501 dirs.as_deref(),
502 SYSTEM_CA_BUNDLES,
503 SYSTEM_CA_DIR,
504 )?;
505 Self::with_roots(roots)
506 }
507
508 #[cfg(feature = "webpki-roots")]
515 pub fn with_webpki_roots() -> Self {
516 let roots = RootCertStore {
517 roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
518 };
519 Self::with_roots(roots).expect("the webpki-roots crate provides roots")
520 }
521
522 pub fn alpn(mut self, protocols: &[&[u8]]) -> Self {
526 Arc::make_mut(&mut self.config).alpn_protocols =
527 protocols.iter().map(|p| p.to_vec()).collect();
528 self
529 }
530
531 pub fn client_auth(mut self, cert_chain: &[u8], private_key: &[u8]) -> io::Result<Self> {
534 let certs = pem_certs(cert_chain)?;
535 let key = PrivateKeyDer::from_pem_slice(private_key).map_err(bad_key)?;
536 let key = CertifiedKey::from_der(certs, key, self.config.crypto_provider())
537 .map_err(mismatched_key)?;
538 Arc::make_mut(&mut self.config).client_auth_cert_resolver =
539 Arc::new(ClientCert(Arc::new(key)));
540 Ok(self)
541 }
542
543 pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
546 self.handshake_timeout = timeout;
547 self
548 }
549
550 pub fn ktls(mut self, mode: Ktls) -> io::Result<Self> {
564 let early_data = self.config.enable_early_data;
565 self.ktls = ktls::Plan::new(mode, self.config.crypto_provider(), early_data)?;
566 let extract = self.ktls.tries();
567 if self.config.enable_secret_extraction != extract {
568 Arc::make_mut(&mut self.config).enable_secret_extraction = extract;
569 }
570 Ok(self)
571 }
572
573 pub fn ktls_unavailable(&self) -> Option<&str> {
576 self.ktls.unavailable()
577 }
578
579 pub async fn connect(&self, server_name: &str, tcp: TcpStream) -> io::Result<TlsStream> {
588 let name = parse_server_name(server_name)?;
589 let tcp = match &self.ktls {
590 ktls::Plan::Off => tcp,
591 ktls::Plan::Try { required } => {
592 let start = ktls::Start::Client(self.config.clone(), name.clone());
593 match ktls::handshake(tcp, start, self.handshake_timeout).await? {
594 ktls::Outcome::Kernel(tls) => return Ok(*tls),
595 ktls::Outcome::Declined(_, e) if *required => return Err(e),
596 ktls::Outcome::Declined(tcp, _) => {
597 self.ktls.stayed();
598 tcp
599 }
600 }
601 }
602 ktls::Plan::Unavailable(_) => {
603 self.ktls.stayed();
604 tcp
605 }
606 };
607 let conn = ClientConnection::new(self.config.clone(), name).map_err(tls_error)?;
608 TlsStream::new(tcp, conn.into())
609 .handshake(self.handshake_timeout)
610 .await
611 }
612}
613
614impl std::fmt::Debug for TlsConnector {
615 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
616 f.debug_struct("TlsConnector")
617 .field("handshake_timeout", &self.handshake_timeout)
618 .field("ktls", &self.ktls)
619 .finish_non_exhaustive()
620 }
621}
622
623fn parse_server_name(name: &str) -> io::Result<ServerName<'static>> {
625 let ipv6 = name
626 .strip_prefix('[')
627 .and_then(|n| n.strip_suffix(']'))
628 .and_then(|n| n.parse::<std::net::Ipv6Addr>().ok());
629 if let Some(ip) = ipv6 {
630 return Ok(ServerName::IpAddress(std::net::IpAddr::V6(ip).into()));
631 }
632 ServerName::try_from(name.to_owned()).map_err(|_| {
633 coded(
634 Code::InvalidServerName,
635 format!("{name:?} is neither a DNS name nor an IP address"),
636 "pass the host name the certificate is for (\"example.com\"), or an IP address, \
637 without a port or a scheme.",
638 )
639 })
640}
641
642#[derive(Debug)]
644struct ClientCert(Arc<CertifiedKey>);
645
646impl ResolvesClientCert for ClientCert {
647 fn resolve(&self, _: &[&[u8]], _: &[SignatureScheme]) -> Option<Arc<CertifiedKey>> {
648 Some(self.0.clone())
649 }
650
651 fn has_certs(&self) -> bool {
652 true
653 }
654}
655
656const SYSTEM_CA_BUNDLES: &[&str] = &[
658 "/etc/ssl/certs/ca-certificates.crt",
660 "/etc/pki/tls/certs/ca-bundle.crt",
662 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
663 "/etc/ssl/ca-bundle.pem",
665 "/etc/ssl/cert.pem",
667];
668
669const SYSTEM_CA_DIR: &str = "/etc/ssl/certs";
671
672fn load_roots(
677 file: Option<&OsStr>,
678 dirs: Option<&OsStr>,
679 bundles: &[&str],
680 dir: &str,
681) -> io::Result<RootCertStore> {
682 let mut roots = Roots {
683 store: RootCertStore::empty(),
684 seen: HashSet::new(),
685 };
686 if file.is_some() || dirs.is_some() {
687 if let Some(file) = file {
688 roots.add_file(Path::new(file)).map_err(|e| {
689 io::Error::new(
690 e.kind(),
691 giong::error::Error::new(
692 Code::BadCertificateData,
693 format!("cannot read SSL_CERT_FILE {file:?}: {e}"),
694 "point SSL_CERT_FILE at a readable PEM file of certificates, or unset \
695 it to use the system's.",
696 )
697 .with_source(e),
698 )
699 })?;
700 }
701 for dir in dirs.map(std::env::split_paths).into_iter().flatten() {
702 roots.add_dir(&dir);
703 }
704 } else if let Some(bundle) = bundles.iter().map(Path::new).find(|p| p.is_file()) {
705 roots.add_file(bundle)?;
706 } else {
707 roots.add_dir(Path::new(dir));
708 }
709 if roots.store.is_empty() {
710 return Err(coded(
711 Code::NoTrustedRoots,
712 "no trusted CA certificates found on this machine",
713 "install the ca-certificates package, set SSL_CERT_FILE, or use \
714 TlsConnector::with_webpki_roots (the webpki-roots feature of giong-tls).",
715 ));
716 }
717 Ok(roots.store)
718}
719
720struct Roots {
721 store: RootCertStore,
722 seen: HashSet<PathBuf>,
725}
726
727impl Roots {
728 fn add_file(&mut self, path: &Path) -> io::Result<()> {
729 let real = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
730 if !self.seen.insert(real) {
731 return Ok(());
732 }
733 let pem = std::fs::read(path)?;
734 let certs = CertificateDer::pem_slice_iter(&pem).filter_map(Result::ok);
735 self.store.add_parsable_certificates(certs);
736 Ok(())
737 }
738
739 fn add_dir(&mut self, dir: &Path) {
740 let Ok(entries) = std::fs::read_dir(dir) else {
741 return;
742 };
743 let mut paths: Vec<PathBuf> = entries.filter_map(|e| Some(e.ok()?.path())).collect();
744 paths.sort();
745 for path in paths.iter().filter(|p| p.is_file()) {
746 let _ = self.add_file(path);
748 }
749 }
750}
751
752pub struct TlsStream {
755 tcp: TcpStream,
756 engine: RefCell<Engine>,
758 plain: RefCell<Vec<u8>>,
760 wire: RefCell<Vec<u8>>,
763 eof: Cell<bool>,
765 close_notify: Cell<bool>,
768 sending: Cell<bool>,
772 broken: Cell<bool>,
775 closed: Cell<Option<Code>>,
779 failed: Cell<Option<io::Error>>,
781 waiters: RefCell<Vec<Waker>>,
783}
784
785#[allow(clippy::large_enum_variant)]
789enum Engine {
790 User(Connection),
792 Kernel(ktls::Kernel),
795}
796
797struct Sending<'a> {
801 stream: &'a TlsStream,
802 complete: bool,
803}
804
805impl Sending<'_> {
806 fn done(mut self) {
808 self.complete = true;
809 }
810}
811
812impl Drop for Sending<'_> {
813 fn drop(&mut self) {
814 if !self.complete {
815 self.stream.broken.set(true);
816 }
817 self.stream.sending.set(false);
818 self.stream.wake_waiters();
819 }
820}
821
822impl TlsStream {
823 fn new(tcp: TcpStream, conn: Connection) -> Self {
824 Self::with_engine(tcp, Engine::User(conn), Vec::new(), false)
825 }
826
827 fn kernel(tcp: TcpStream, kernel: ktls::Kernel, plain: Vec<u8>, peer_closed: bool) -> Self {
831 Self::with_engine(tcp, Engine::Kernel(kernel), plain, peer_closed)
832 }
833
834 fn with_engine(tcp: TcpStream, engine: Engine, plain: Vec<u8>, peer_closed: bool) -> Self {
835 Self {
836 tcp,
837 engine: RefCell::new(engine),
838 plain: RefCell::new(plain),
839 wire: RefCell::new(Vec::new()),
840 eof: Cell::new(peer_closed),
841 close_notify: Cell::new(peer_closed),
842 sending: Cell::new(false),
843 broken: Cell::new(false),
844 closed: Cell::new(None),
845 failed: Cell::new(None),
846 waiters: RefCell::new(Vec::new()),
847 }
848 }
849
850 fn conn(&self) -> RefMut<'_, Connection> {
853 RefMut::map(self.engine.borrow_mut(), |e| match e {
854 Engine::User(c) => c,
855 Engine::Kernel(_) => unreachable!("rustls' connection on a kernel TLS stream"),
856 })
857 }
858
859 pub fn is_ktls(&self) -> bool {
863 matches!(*self.engine.borrow(), Engine::Kernel(_))
864 }
865
866 async fn wait_for_sender(&self) {
868 poll_fn(|cx| {
869 if !self.sending.get() {
870 return Poll::Ready(());
871 }
872 let mut waiters = self.waiters.borrow_mut();
874 if !waiters.iter().any(|w| w.will_wake(cx.waker())) {
875 waiters.push(cx.waker().clone());
876 }
877 Poll::Pending
878 })
879 .await;
880 }
881
882 async fn lock_send(&self) -> Sending<'_> {
885 while self.sending.get() {
886 self.wait_for_sender().await;
887 }
888 self.sending.set(true);
889 Sending {
890 stream: self,
891 complete: false,
892 }
893 }
894
895 async fn handshake(self, limit: Duration) -> io::Result<Self> {
897 let handshake = async {
898 while self.conn().is_handshaking() {
899 self.flush_tls().await?;
900 if !self.conn().is_handshaking() {
901 break;
902 }
903 if self.eof.get() {
904 return Err(handshake_eof());
905 }
906 self.pump().await?;
907 }
908 self.flush_tls().await
909 };
910 match timeout(limit, handshake).await {
911 Ok(Ok(())) => Ok(self),
912 Ok(Err(e)) => Err(e),
913 Err(_) => Err(handshake_timed_out(limit)),
914 }
915 }
916
917 fn wake_waiters(&self) {
920 let waiters = mem::take(&mut *self.waiters.borrow_mut());
921 for waker in waiters {
922 waker.wake();
923 }
924 }
925
926 fn take_wire(&self) -> Vec<u8> {
928 mem::take(&mut *self.wire.borrow_mut())
929 }
930
931 fn keep_wire(&self, mut wire: Vec<u8>) {
935 if wire.capacity() <= WIRE_KEPT {
936 wire.clear();
937 *self.wire.borrow_mut() = wire;
938 }
939 }
940
941 fn cannot_send(&self) -> Option<io::Error> {
944 if self.broken.get() {
945 return Some(broken());
946 }
947 self.closed.get().map(sending_closed)
948 }
949
950 async fn flush_tls(&self) -> io::Result<()> {
954 loop {
955 if !self.conn().wants_write() {
956 return Ok(());
957 }
958 if self.broken.get() {
959 return Err(broken());
960 }
961 if self.sending.get() {
962 self.wait_for_sender().await;
965 continue;
966 }
967 let sending = self.lock_send().await;
968 let mut wire = self.take_wire();
969 let res = self.send_queued(&mut wire).await;
970 self.keep_wire(wire);
971 sending.done();
972 res?;
973 }
974 }
975
976 async fn send_queued(&self, wire: &mut Vec<u8>) -> io::Result<()> {
979 loop {
980 {
981 let mut conn = self.conn();
982 if !conn.wants_write() {
983 return Ok(());
984 }
985 while conn.wants_write() {
986 conn.write_tls(wire)?;
987 }
988 }
989 self.send_wire(wire).await?;
990 }
991 }
992
993 async fn send_wire(&self, wire: &mut Vec<u8>) -> io::Result<()> {
997 let (res, mut sent) = self.tcp.write_all(mem::take(wire)).await;
998 sent.clear();
999 *wire = sent;
1000 if res.is_err() {
1001 self.broken.set(true);
1002 }
1003 res
1004 }
1005
1006 async fn send_plain(&self, wire: &mut Vec<u8>, data: &[u8]) -> io::Result<()> {
1012 let mut sent = 0;
1013 while sent < data.len() {
1014 let (carried, refused) = {
1015 let mut conn = self.conn();
1016 while conn.wants_write() {
1017 conn.write_tls(wire)?;
1018 }
1019 let carried = !wire.is_empty();
1020 let start = wire.len();
1021 let n = conn.writer().write(&data[sent..])?;
1022 while conn.wants_write() {
1023 conn.write_tls(wire)?;
1024 }
1025 sent += n;
1026 (carried, n > 0 && !has_application_data(&wire[start..]))
1031 };
1032 if !wire.is_empty() {
1033 self.send_wire(wire).await?;
1034 }
1035 if carried {
1036 self.wake_waiters();
1038 }
1039 if refused {
1040 self.closed.set(Some(Code::TlsKeysExhausted));
1041 return Err(sending_closed(Code::TlsKeysExhausted));
1042 }
1043 }
1044 Ok(())
1045 }
1046
1047 async fn write_in_process(&self, pieces: &[&[u8]]) -> io::Result<()> {
1051 let sending = self.lock_send().await;
1052 if let Some(e) = self.cannot_send() {
1053 sending.done();
1054 return Err(e);
1055 }
1056 let mut wire = self.take_wire();
1057 let mut res = Ok(());
1058 for piece in pieces {
1059 res = self.send_plain(&mut wire, piece).await;
1060 if res.is_err() {
1061 break;
1062 }
1063 }
1064 self.keep_wire(wire);
1065 sending.done();
1069 res
1070 }
1071
1072 async fn pump(&self) -> io::Result<()> {
1075 let chunk = self.tcp.recv().await?;
1077 if chunk.is_empty() {
1078 self.eof.set(true);
1079 return Ok(());
1080 }
1081 let result = {
1082 let mut conn = self.conn();
1083 let mut plain = self.plain.borrow_mut();
1084 let mut input = &chunk[..];
1085 let mut result = Ok(());
1086 while !input.is_empty() {
1087 match conn.read_tls(&mut input) {
1090 Ok(0) => {
1091 result = Err(coded(
1092 Code::TlsProtocol,
1093 "rustls accepted no more TLS data",
1094 "this is a bug in giong-tls; please report it at \
1095 https://github.com/giong-run/Giong/issues.",
1096 ));
1097 break;
1098 }
1099 Ok(_) => {}
1100 Err(e) => {
1101 result = Err(e);
1102 break;
1103 }
1104 }
1105 match conn.process_new_packets() {
1106 Ok(state) => {
1107 let n = state.plaintext_bytes_to_read();
1108 if n > 0 {
1109 let at = plain.len();
1110 plain.resize(at + n, 0);
1111 if let Err(e) = conn.reader().read_exact(&mut plain[at..]) {
1112 plain.truncate(at);
1113 result = Err(e);
1114 break;
1115 }
1116 }
1117 if state.peer_has_closed() {
1118 self.close_notify.set(true);
1119 self.eof.set(true);
1120 break;
1121 }
1122 }
1123 Err(e) => {
1124 result = Err(tls_error(e));
1125 break;
1126 }
1127 }
1128 }
1129 result
1130 };
1131 drop(chunk);
1132 if self.broken.get() {
1136 return result;
1137 }
1138 let flushed = self.flush_tls().await;
1139 result.and(flushed)
1140 }
1141
1142 pub async fn recv(&self) -> io::Result<Vec<u8>> {
1160 if self.is_ktls() {
1161 return self.kernel_recv().await;
1162 }
1163 loop {
1164 {
1165 let mut plain = self.plain.borrow_mut();
1166 if !plain.is_empty() {
1167 return Ok(mem::take(&mut *plain));
1168 }
1169 }
1170 if let Some(e) = self.failed.take() {
1171 return Err(e);
1172 }
1173 if self.eof.get() {
1174 return Ok(Vec::new());
1175 }
1176 if let Err(e) = self.pump().await {
1177 if self.plain.borrow().is_empty() {
1179 return Err(e);
1180 }
1181 self.failed.set(Some(e));
1182 }
1183 }
1184 }
1185
1186 pub async fn write_all<B>(&self, buf: B) -> (io::Result<()>, B)
1207 where
1208 B: giong::IoBuf + AsRef<[u8]>,
1209 {
1210 if self.is_ktls() {
1211 return self.kernel_write_all(buf).await;
1212 }
1213 let res = self.write_in_process(&[buf.as_ref()]).await;
1214 (res, buf)
1215 }
1216
1217 pub async fn write_all_vectored<B>(&self, bufs: Vec<B>) -> (io::Result<()>, Vec<B>)
1229 where
1230 B: giong::IoBuf + AsRef<[u8]>,
1231 {
1232 if self.is_ktls() {
1233 return self.kernel_write_all_vectored(bufs).await;
1234 }
1235 let pieces: Vec<&[u8]> = bufs.iter().map(AsRef::as_ref).collect();
1236 let res = self.write_in_process(&pieces).await;
1237 drop(pieces);
1238 (res, bufs)
1239 }
1240
1241 pub async fn send_file(&self, file: &giong::fs::File, offset: u64, len: u64) -> io::Result<()> {
1258 if offset
1259 .checked_add(len)
1260 .map_or(true, |end| end > i64::MAX as u64)
1261 {
1262 return Err(file_too_short(offset, len, offset));
1263 }
1264 if self.is_ktls() {
1265 return self.kernel_send_file(file, offset, len).await;
1266 }
1267 let sending = self.lock_send().await;
1268 if let Some(e) = self.cannot_send() {
1269 sending.done();
1270 return Err(e);
1271 }
1272 let mut wire = self.take_wire();
1273 let res = self
1274 .send_file_in_process(&mut wire, file, offset, len)
1275 .await;
1276 self.keep_wire(wire);
1277 sending.done();
1278 res
1279 }
1280
1281 async fn send_file_in_process(
1284 &self,
1285 wire: &mut Vec<u8>,
1286 file: &giong::fs::File,
1287 offset: u64,
1288 len: u64,
1289 ) -> io::Result<()> {
1290 const PIECE: u64 = 256 * 1024;
1291 let mut buf = Vec::with_capacity(len.min(PIECE) as usize);
1292 let (mut at, mut left) = (offset, len);
1293 while left > 0 {
1294 let (res, b) = file.read_at(buf, at).await;
1295 buf = b;
1296 let n = match res {
1297 Ok(0) => return Err(file_too_short(offset, len, at)),
1298 Ok(n) => (n as u64).min(left) as usize,
1299 Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
1300 Err(e) => return Err(e),
1301 };
1302 self.send_plain(wire, &buf[..n]).await?;
1303 at += n as u64;
1304 left -= n as u64;
1305 }
1306 Ok(())
1307 }
1308
1309 pub async fn shutdown(&self) -> io::Result<()> {
1316 if self.is_ktls() {
1317 return self.kernel_shutdown().await;
1318 }
1319 let sending = self.lock_send().await;
1320 if self.cannot_send().is_none() {
1321 self.conn().send_close_notify();
1322 self.closed.set(Some(Code::TlsBroken));
1323 let mut wire = self.take_wire();
1324 let res = self.send_queued(&mut wire).await;
1325 self.keep_wire(wire);
1326 if let Err(e) = res {
1327 sending.done();
1329 let _ = self.tcp.shutdown(Shutdown::Write);
1330 return Err(e);
1331 }
1332 }
1333 sending.done();
1334 self.tcp.shutdown(Shutdown::Write)
1335 }
1336
1337 pub fn received_close_notify(&self) -> bool {
1343 self.close_notify.get()
1344 }
1345
1346 pub fn alpn_protocol(&self) -> Option<Vec<u8>> {
1348 match &*self.engine.borrow() {
1349 Engine::User(c) => c.alpn_protocol().map(<[u8]>::to_vec),
1350 Engine::Kernel(k) => k.negotiated.alpn.clone(),
1351 }
1352 }
1353
1354 pub fn peer_certificates(&self) -> Option<Vec<CertificateDer<'static>>> {
1359 match &*self.engine.borrow() {
1360 Engine::User(c) => c.peer_certificates().map(<[_]>::to_vec),
1361 Engine::Kernel(k) => k.negotiated.peer_certificates.clone(),
1362 }
1363 }
1364
1365 pub fn resumed(&self) -> bool {
1368 match &*self.engine.borrow() {
1369 Engine::User(c) => c.handshake_kind() == Some(rustls::HandshakeKind::Resumed),
1370 Engine::Kernel(k) => k.negotiated.resumed,
1371 }
1372 }
1373
1374 pub fn tcp(&self) -> &TcpStream {
1381 &self.tcp
1382 }
1383}
1384
1385impl std::fmt::Debug for TlsStream {
1386 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1387 f.debug_struct("TlsStream")
1388 .field("tcp", &self.tcp)
1389 .field("ktls", &self.is_ktls())
1390 .finish_non_exhaustive()
1391 }
1392}
1393
1394#[cfg(test)]
1395mod tests {
1396 use super::*;
1397
1398 fn ca_pem(name: &str) -> String {
1399 let key = rcgen::KeyPair::generate().unwrap();
1400 let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
1401 params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
1402 params
1403 .distinguished_name
1404 .push(rcgen::DnType::CommonName, name);
1405 params.self_signed(&key).unwrap().pem()
1406 }
1407
1408 fn scratch(name: &str) -> PathBuf {
1410 let dir = std::env::temp_dir().join(format!("giong-tls-{}-{name}", std::process::id()));
1411 let _ = std::fs::remove_dir_all(&dir);
1412 std::fs::create_dir_all(&dir).unwrap();
1413 dir
1414 }
1415
1416 fn os(path: &Path) -> &OsStr {
1417 path.as_os_str()
1418 }
1419
1420 #[test]
1421 fn server_names_are_dns_names_or_ip_addresses() {
1422 let dns = |n: &str| matches!(parse_server_name(n), Ok(ServerName::DnsName(_)));
1423 let ip = |n: &str| matches!(parse_server_name(n), Ok(ServerName::IpAddress(_)));
1424 assert!(dns("example.com"));
1425 assert!(dns("db.prod.svc.cluster.local"));
1426 assert!(ip("10.0.0.1"));
1427 assert!(ip("::1"));
1428 assert!(ip("[::1]"));
1429 for bad in ["", "not a name", "[nope]", "[10.0.0.1]", "a..b"] {
1430 let err = parse_server_name(bad).unwrap_err();
1431 assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{bad:?}");
1432 }
1433 }
1434
1435 #[test]
1436 fn the_first_bundle_that_exists_is_read() {
1437 let dir = scratch("bundle");
1438 let bundle = dir.join("bundle.pem");
1439 let two = format!("{}{}", ca_pem("one"), ca_pem("two"));
1440 std::fs::write(&bundle, two).unwrap();
1441 let missing = dir.join("missing.pem");
1442 let bundles = [missing.to_str().unwrap(), bundle.to_str().unwrap()];
1443 let roots = load_roots(None, None, &bundles, "/nonexistent").unwrap();
1444 assert_eq!(roots.len(), 2);
1445 std::fs::remove_dir_all(dir).unwrap();
1446 }
1447
1448 #[test]
1449 fn ssl_cert_file_and_dir_replace_the_system_locations() {
1450 let dir = scratch("env");
1451 let file = dir.join("file.pem");
1452 std::fs::write(&file, ca_pem("from file")).unwrap();
1453 let certs = dir.join("certs");
1454 std::fs::create_dir(&certs).unwrap();
1455 std::fs::write(certs.join("a.pem"), ca_pem("a")).unwrap();
1456 std::fs::write(certs.join("b.pem"), ca_pem("b")).unwrap();
1457 std::fs::write(certs.join("README"), "not a certificate").unwrap();
1458 std::os::unix::fs::symlink(certs.join("a.pem"), certs.join("1a2b3c4d.0")).unwrap();
1460 let system = dir.join("system.pem");
1461 std::fs::write(&system, ca_pem("system")).unwrap();
1462 let bundles = [system.to_str().unwrap()];
1463
1464 let roots = load_roots(Some(os(&file)), None, &bundles, "/nonexistent").unwrap();
1465 assert_eq!(roots.len(), 1, "SSL_CERT_FILE only");
1466 let roots = load_roots(None, Some(os(&certs)), &bundles, "/nonexistent").unwrap();
1467 assert_eq!(roots.len(), 2, "SSL_CERT_DIR only, each file once");
1468 let both = std::env::join_paths([dir.join("nowhere"), certs.clone()]).unwrap();
1469 let roots = load_roots(Some(os(&file)), Some(&both), &bundles, "/nonexistent").unwrap();
1470 assert_eq!(roots.len(), 3, "both, with a missing directory in the list");
1471
1472 let err = load_roots(Some(os(&dir.join("gone.pem"))), None, &bundles, "").unwrap_err();
1473 assert_eq!(err.kind(), io::ErrorKind::NotFound);
1474 assert!(err.to_string().contains("SSL_CERT_FILE"), "{err}");
1475 std::fs::remove_dir_all(dir).unwrap();
1476 }
1477
1478 #[test]
1479 fn without_a_bundle_the_directory_is_read_and_nothing_is_an_error() {
1480 let dir = scratch("dir");
1481 std::fs::write(dir.join("only.crt"), ca_pem("only")).unwrap();
1482 let roots = load_roots(
1483 None,
1484 None,
1485 &["/nonexistent/bundle.crt"],
1486 dir.to_str().unwrap(),
1487 );
1488 assert_eq!(roots.unwrap().len(), 1);
1489
1490 let empty = scratch("empty");
1491 let err = load_roots(None, None, &[], empty.to_str().unwrap()).unwrap_err();
1492 assert_eq!(err.kind(), io::ErrorKind::NotFound);
1493 assert!(err.to_string().contains("webpki-roots"), "{err}");
1494 std::fs::remove_dir_all(dir).unwrap();
1495 std::fs::remove_dir_all(empty).unwrap();
1496 }
1497
1498 #[test]
1499 fn records_are_scanned_for_application_data() {
1500 let record = |typ: u8, len: u16| {
1502 let mut r = vec![typ, 3, 3];
1503 r.extend_from_slice(&len.to_be_bytes());
1504 r.resize(5 + len as usize, 0xAA);
1505 r
1506 };
1507 assert!(!has_application_data(&[]));
1508 assert!(!has_application_data(&record(21, 26)));
1509 assert!(has_application_data(&record(23, 0)));
1510 let mut alert_then_data = record(21, 26);
1511 alert_then_data.extend(record(23, 300));
1512 assert!(has_application_data(&alert_then_data));
1513 let mut alert = record(21, 26);
1515 alert[5] = 23;
1516 assert!(!has_application_data(&alert));
1517 }
1518
1519 #[test]
1520 fn secrets_are_extractable_only_when_the_kernel_will_take_them() {
1521 let key = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
1522 let (cert, key) = (key.cert.pem(), key.key_pair.serialize_pem());
1523 for mode in [Ktls::Off, Ktls::Auto] {
1524 let acceptor = TlsAcceptor::from_pem(cert.as_bytes(), key.as_bytes())
1525 .unwrap()
1526 .ktls(mode)
1527 .unwrap();
1528 let tries = acceptor.ktls.tries();
1529 assert_eq!(acceptor.config.enable_secret_extraction, tries, "{mode:?}");
1530 let connector = TlsConnector::with_root_pem(cert.as_bytes())
1531 .unwrap()
1532 .ktls(mode)
1533 .unwrap();
1534 let tries = connector.ktls.tries();
1535 assert_eq!(connector.config.enable_secret_extraction, tries, "{mode:?}");
1536 }
1537 }
1538
1539 #[test]
1540 fn this_machines_roots_load() {
1541 TlsConnector::with_system_roots().unwrap();
1543 }
1544
1545 #[cfg(feature = "webpki-roots")]
1546 #[test]
1547 fn mozillas_roots_are_compiled_in() {
1548 TlsConnector::with_webpki_roots();
1549 }
1550}