//! TLS for compiled programs (`std/tls`, ADR 0038): clients and servers, //! rustls with the ring provider, over the non-blocking sockets of //! `net.rs`. //! //! **Security review needed before production use** (ADR 0038 lists what //! to check). What this module promises: //! - a server's certificate and host name are always verified, against //! Mozilla's roots (webpki-roots) and the CAs the program adds, unless the //! program asked for `insecure_skip_verification`, which warns on stderr; //! - a server given client authorities refuses every client without a //! certificate they signed (mutual TLS); there is no way to skip that; //! - TLS 1.2 at least, 1.3 preferred; no 0-RTT, no key log; //! - an end of the connection without TLS's `close_notify` is `Truncated`, //! never a clean end of the stream; //! - keys are read from files, by path; neither keys nor their contents //! appear in error messages. //! //! **Sockets:** a TLS stream takes a TCP connection's socket and reactor //! token (`net::upgrade`), so it waits on the socket like `net.rs` does. //! The connection keeps it only to shut it down: another actor can stop a //! handshake that hangs by closing the TCP connection. Both sides share //! this: a stream is a `rustls::Connection`, client or server. //! //! **Configurations** are built from plain Rust values (`ClientOptions`, //! `ServerOptions`), so the distribution transport (ADR 0072) can make //! the same mutual-TLS configurations without going through Louise, and //! check a peer's name with `has_name`. //! //! **Threads:** a stream may be used from any actor (one at a time is the //! sensible use). Its state is behind a mutex, never held while the actor //! waits. //! //! Errors are `(code, message)` pairs, which `std/tls` turns into its //! `TlsError` (codes below). #[cfg(feature = "tls")] use crate::abi::UNIT; use crate::abi::{Ctx, Value, int}; use crate::values::{cell, string}; /// The error codes `std/tls` maps to `TlsError`'s constructors. #[cfg_attr(not(feature = "tls"), allow(dead_code))] mod code { pub const IO: i64 = 0; pub const UNTRUSTED_ISSUER: i64 = 1; pub const EXPIRED: i64 = 2; pub const NOT_YET_VALID: i64 = 3; pub const WRONG_HOST_NAME: i64 = 4; pub const BAD_CERTIFICATE: i64 = 5; pub const PROTOCOL_VERSION: i64 = 6; pub const HANDSHAKE_FAILURE: i64 = 7; pub const TRUNCATED: i64 = 8; pub const INVALID_CONFIG: i64 = 9; } /// `Error((code, message))`. fn failure(ctx: *mut Ctx, code: i64, message: &str) -> Value { let pair = cell(ctx, 0, &[int(code), string(ctx, message)]); cell(ctx, 1, &[pair]) } /// `Ok(v)`. #[cfg_attr(not(feature = "tls"), allow(dead_code))] fn success(ctx: *mut Ctx, v: Value) -> Value { cell(ctx, 0, &[v]) } #[cfg(feature = "tls")] pub use enabled::*; #[cfg(not(feature = "tls"))] pub use disabled::*; #[cfg(not(feature = "tls"))] mod disabled { use super::*; const NOT_BUILT: &str = "TLS support not built in (louise_rt's `tls` feature)"; /// # Safety /// As the enabled version. #[unsafe(no_mangle)] #[allow(clippy::too_many_arguments)] pub unsafe extern "C" fn tl_tls_config( ctx: *mut Ctx, _default_roots: Value, _ca_pems: Value, _ca_files: Value, _alpn: Value, _tls13_only: Value, _insecure: Value, _cert_file: Value, _key_file: Value, ) -> Value { failure(ctx, code::INVALID_CONFIG, NOT_BUILT) } /// # Safety /// As the enabled version. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_tls_server_config( ctx: *mut Ctx, _cert_file: Value, _key_file: Value, _client_ca_pems: Value, _client_ca_files: Value, _alpn: Value, _tls13_only: Value, ) -> Value { failure(ctx, code::INVALID_CONFIG, NOT_BUILT) } /// # Safety /// As the enabled version. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_tls_connect( ctx: *mut Ctx, _conn: Value, _host: Value, _config: Value, ) -> Value { failure(ctx, code::INVALID_CONFIG, NOT_BUILT) } /// # Safety /// As the enabled version. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_tls_accept(ctx: *mut Ctx, _conn: Value, _config: Value) -> Value { failure(ctx, code::INVALID_CONFIG, NOT_BUILT) } macro_rules! unreachable_stream { ($($name:ident($($arg:ident),*)),*) => {$( /// # Safety /// Never called: no TLS stream exists without the feature. #[unsafe(no_mangle)] pub unsafe extern "C" fn $name(ctx: *mut Ctx, $($arg: Value),*) -> Value { $(let _ = $arg;)* failure(ctx, code::INVALID_CONFIG, NOT_BUILT) } )*}; } unreachable_stream!( tl_tls_read(tls, max), tl_tls_write(tls, data), tl_tls_write_string(tls, s), tl_tls_close(tls), tl_tls_alpn(tls), tl_tls_version(tls), tl_tls_peer_names(tls) ); } #[cfg(feature = "tls")] mod enabled { use std::io::{ErrorKind, Read, Write}; use std::sync::{Arc, Mutex, MutexGuard}; use mio::Token; use mio::net::TcpStream; use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; use rustls::pki_types::pem::PemObject; use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime}; use rustls::server::danger::{ClientCertVerified, ClientCertVerifier}; use rustls::server::{NoServerSessionStorage, WebPkiClientVerifier}; use rustls::{ AlertDescription, CertificateError, ClientConfig, ClientConnection, Connection, DigitallySignedStruct, RootCertStore, ServerConfig, ServerConnection, SignatureScheme, SupportedProtocolVersion, }; use super::*; use crate::heap::drop_value; use crate::int::saturating; use crate::net::{io_events, upgrade, wait_for}; use crate::resource::{tl_resource_get, tl_resource_new}; use crate::sock::NoSigPipe; use crate::values::{bytes_from, bytes_of, list, list_items, text}; // ---- configurations ------------------------------------------------- /// Trusted authorities: Mozilla's roots, PEM texts, PEM files. #[derive(Default)] pub(crate) struct Authorities { pub(crate) default_roots: bool, pub(crate) pems: Vec, pub(crate) files: Vec, } /// A certificate chain and its private key, PEM files: the key is read /// by path only, and never quoted. pub(crate) struct Identity { pub(crate) cert_file: String, pub(crate) key_file: String, } /// What a client configuration is made of (`std/tls`'s `Options`). pub(crate) struct ClientOptions { pub(crate) authorities: Authorities, /// A client certificate, for servers that ask for one. pub(crate) identity: Option, pub(crate) alpn: Vec>, pub(crate) tls13_only: bool, /// `insecure_skip_verification`: any server certificate. pub(crate) insecure: bool, } /// What a server configuration is made of (`std/tls`'s /// `ServerOptions`). pub(crate) struct ServerOptions { pub(crate) identity: Identity, /// Mutual TLS: every client must present a certificate from these, /// or the handshake fails. `None`: no client certificate asked for. pub(crate) client_authorities: Option, pub(crate) alpn: Vec>, pub(crate) tls13_only: bool, /// Distribution's transport (ADR 0072), whose clients are nodes: /// no session resumption, so every connection verifies the chain /// and its dates; no root hints; client chains of a node's length /// ([`PeerChains`]). pub(crate) peers: bool, } /// A client configuration, as a `TlsConfig` resource holds it. struct Client { config: Arc, /// The server's certificate is verified (not `insecure`): its names /// may be given out (`peer_names`). verified: bool, } unsafe extern "C" fn finalize_config(p: *mut std::ffi::c_void) { // SAFETY: made by `tl_tls_config`, finalized once. drop(unsafe { Box::from_raw(p.cast::()) }); } unsafe extern "C" fn finalize_server_config(p: *mut std::ffi::c_void) { // SAFETY: made by `tl_tls_server_config`, finalized once. drop(unsafe { Box::from_raw(p.cast::>()) }); } /// `config(...)`: a client configuration, from `std/tls`'s `Options`. /// Reads the CA and key files (a `blocking` extern: on the pool). /// /// # Safety /// The arguments must be live values of the types `std/tls` declares. #[unsafe(no_mangle)] #[allow(clippy::too_many_arguments)] pub unsafe extern "C" fn tl_tls_config( ctx: *mut Ctx, default_roots: Value, ca_pems: Value, ca_files: Value, alpn: Value, tls13_only: Value, insecure: Value, cert_file: Value, key_file: Value, ) -> Value { // SAFETY: caller guarantees the types. let options = unsafe { identity(text(cert_file), text(key_file)).map(|identity| ClientOptions { authorities: Authorities { default_roots: truthy(default_roots), pems: strings(ca_pems), files: strings(ca_files), }, identity, alpn: protocols(alpn), tls13_only: truthy(tls13_only), insecure: truthy(insecure), }) }; let verified = options.as_ref().is_ok_and(|o| !o.insecure); match options.and_then(client_config) { Ok(config) => { let boxed = Box::into_raw(Box::new(Client { config, verified })); let r = tl_resource_new(ctx, boxed.cast(), Some(finalize_config), true); success(ctx, r) } Err(message) => failure(ctx, code::INVALID_CONFIG, &message), } } /// `server_config(...)`: a server configuration, from `std/tls`'s /// `ServerOptions`. Reads the certificate, key and CA files (a /// `blocking` extern: on the pool). /// /// # Safety /// The arguments must be live values of the types `std/tls` declares. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_tls_server_config( ctx: *mut Ctx, cert_file: Value, key_file: Value, client_ca_pems: Value, client_ca_files: Value, alpn: Value, tls13_only: Value, ) -> Value { // SAFETY: caller guarantees the types. let options = unsafe { let (pems, files) = (strings(client_ca_pems), strings(client_ca_files)); ServerOptions { identity: Identity { cert_file: text(cert_file).to_owned(), key_file: text(key_file).to_owned(), }, client_authorities: (!pems.is_empty() || !files.is_empty()).then_some( Authorities { default_roots: false, pems, files, }, ), alpn: protocols(alpn), tls13_only: truthy(tls13_only), peers: false, } }; match server_config(options) { Ok(config) => { let boxed = Box::into_raw(Box::new(config)); let r = tl_resource_new(ctx, boxed.cast(), Some(finalize_server_config), true); success(ctx, r) } Err(message) => failure(ctx, code::INVALID_CONFIG, &message), } } fn truthy(b: Value) -> bool { b == int(1) } /// # Safety /// `l` must be a live `List`. unsafe fn strings(l: Value) -> Vec { // SAFETY: caller guarantees a list of strings. unsafe { list_items(l).map(|s| text(s).to_owned()).collect() } } /// # Safety /// `l` must be a live `List`. unsafe fn protocols(l: Value) -> Vec> { // SAFETY: caller guarantees a list of strings. unsafe { list_items(l).map(|s| text(s).as_bytes().to_vec()).collect() } } /// A client certificate from `std/tls`'s two paths: both or neither. fn identity(cert_file: &str, key_file: &str) -> Result, String> { match (cert_file.is_empty(), key_file.is_empty()) { (true, true) => Ok(None), (false, false) => Ok(Some(Identity { cert_file: cert_file.to_owned(), key_file: key_file.to_owned(), })), _ => Err("a client certificate needs both its certificate and key files".into()), } } /// A client configuration. Fails rather than make one that can't /// verify anything. pub(crate) fn client_config(o: ClientOptions) -> Result, String> { let roots = root_store(&o.authorities)?; if roots.is_empty() && !o.insecure { return Err("no trusted roots: add a CA, or keep the default roots".into()); } let provider = Arc::new(rustls::crypto::ring::default_provider()); let builder = ClientConfig::builder_with_provider(provider.clone()) .with_protocol_versions(versions(o.tls13_only)) .map_err(|e| e.to_string())?; let builder = if o.insecure { eprintln!( "louise: warning: a TLS configuration skips certificate verification (`tls.insecure_skip_verification`): connections are not authenticated" ); builder .dangerous() .with_custom_certificate_verifier(Arc::new(NoVerification(provider))) } else { builder.with_root_certificates(roots) }; let mut config = match &o.identity { None => builder.with_no_client_auth(), Some(identity) => { let (certs, key) = load_identity(identity, "client")?; builder .with_client_auth_cert(certs, key) .map_err(|e| format!("client certificate: {e}"))? } }; config.alpn_protocols = o.alpn; // The defaults, stated: no early data, no key log. config.enable_early_data = false; Ok(Arc::new(config)) } /// A server configuration. With client authorities, a client without /// a certificate they signed is refused: required, never optional. pub(crate) fn server_config(o: ServerOptions) -> Result, String> { let (certs, key) = load_identity(&o.identity, "server")?; let provider = Arc::new(rustls::crypto::ring::default_provider()); let builder = ServerConfig::builder_with_provider(provider.clone()) .with_protocol_versions(versions(o.tls13_only)) .map_err(|e| e.to_string())?; let builder = match &o.client_authorities { None => builder.with_no_client_auth(), Some(authorities) => { let roots = root_store(authorities)?; // No revocation lists (ADR 0038), and no // `allow_unauthenticated`. let mut verifier = WebPkiClientVerifier::builder_with_provider(Arc::new(roots), provider); if o.peers { verifier = verifier.clear_root_hint_subjects(); } let verifier = verifier .build() .map_err(|e| format!("client authorities: {e}"))?; if o.peers { builder.with_client_cert_verifier(Arc::new(PeerChains(verifier))) } else { builder.with_client_cert_verifier(verifier) } } }; let mut config = builder .with_single_cert(certs, key) .map_err(|e| format!("server certificate: {e}"))?; config.alpn_protocols = o.alpn; // The defaults, stated: no early data, no key log. config.max_early_data_size = 0; if o.peers { config.session_storage = Arc::new(NoServerSessionStorage {}); config.send_tls13_tickets = 0; } Ok(Arc::new(config)) } /// The most certificates a node's client chain holds besides its own: /// a cluster's intermediate authorities. pub(crate) const PEER_INTERMEDIATES: usize = 3; /// The most bytes a node's client chain takes. pub(crate) const PEER_CHAIN_BYTES: usize = 16 << 10; /// A client verifier that refuses a chain longer or larger than a /// node's ([`PEER_INTERMEDIATES`], [`PEER_CHAIN_BYTES`]) before webpki /// builds paths through it: a client presenting a hundred certificates /// of the authority's name made path building cost 65 times a real /// handshake, on distribution's one transport thread. #[derive(Debug)] struct PeerChains(Arc); impl ClientCertVerifier for PeerChains { fn offer_client_auth(&self) -> bool { self.0.offer_client_auth() } fn client_auth_mandatory(&self) -> bool { self.0.client_auth_mandatory() } fn root_hint_subjects(&self) -> &[rustls::DistinguishedName] { self.0.root_hint_subjects() } fn verify_client_cert( &self, end_entity: &CertificateDer<'_>, intermediates: &[CertificateDer<'_>], now: UnixTime, ) -> Result { let bytes = intermediates.iter().map(|c| c.len()).sum::() + end_entity.len(); if intermediates.len() > PEER_INTERMEDIATES || bytes > PEER_CHAIN_BYTES { return Err(rustls::Error::InvalidCertificate( CertificateError::ApplicationVerificationFailure, )); } self.0.verify_client_cert(end_entity, intermediates, now) } fn verify_tls12_signature( &self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct, ) -> Result { self.0.verify_tls12_signature(message, cert, dss) } fn verify_tls13_signature( &self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct, ) -> Result { self.0.verify_tls13_signature(message, cert, dss) } fn supported_verify_schemes(&self) -> Vec { self.0.supported_verify_schemes() } } fn versions(tls13_only: bool) -> &'static [&'static SupportedProtocolVersion] { const ONLY_13: &[&SupportedProtocolVersion] = &[&rustls::version::TLS13]; const BOTH: &[&SupportedProtocolVersion] = &[&rustls::version::TLS13, &rustls::version::TLS12]; if tls13_only { ONLY_13 } else { BOTH } } fn root_store(a: &Authorities) -> Result { let mut roots = RootCertStore::empty(); if a.default_roots { roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); } for (i, pem) in a.pems.iter().enumerate() { add_pem_certs( &mut roots, CertificateDer::pem_slice_iter(pem.as_bytes()), &format!("CA text {}", i + 1), )?; } for path in &a.files { let certs = CertificateDer::pem_file_iter(path).map_err(|e| format!("CA file {path}: {e}"))?; add_pem_certs(&mut roots, certs, &format!("CA file {path}"))?; } Ok(roots) } /// The chain and key of `identity`; `side` names it in errors. fn load_identity( identity: &Identity, side: &str, ) -> Result<(Vec>, PrivateKeyDer<'static>), String> { let Identity { cert_file, key_file, } = identity; let certs: Vec> = CertificateDer::pem_file_iter(cert_file) .and_then(|it| it.collect()) .map_err(|e| format!("{side} certificate file {cert_file}: {e}"))?; if certs.is_empty() { return Err(format!( "{side} certificate file {cert_file}: no certificate in it" )); } // The key's own error could quote it: only the path. let key = PrivateKeyDer::from_pem_file(key_file) .map_err(|_| format!("{side} key file {key_file}: no readable private key"))?; Ok((certs, key)) } fn add_pem_certs( roots: &mut RootCertStore, certs: impl Iterator, rustls::pki_types::pem::Error>>, what: &str, ) -> Result<(), String> { let mut n = 0; for c in certs { let c = c.map_err(|e| format!("{what}: {e}"))?; roots.add(c).map_err(|e| format!("{what}: {e}"))?; n += 1; } if n == 0 { return Err(format!("{what}: no certificate in it")); } Ok(()) } /// `insecure_skip_verification`: accepts any certificate. Signatures /// are still checked, so the server proves it holds the key of the /// certificate it sent (whatever that is). #[derive(Debug)] struct NoVerification(Arc); impl ServerCertVerifier for NoVerification { fn verify_server_cert( &self, _end_entity: &CertificateDer<'_>, _intermediates: &[CertificateDer<'_>], _server_name: &ServerName<'_>, _ocsp: &[u8], _now: UnixTime, ) -> Result { Ok(ServerCertVerified::assertion()) } fn verify_tls12_signature( &self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct, ) -> Result { rustls::crypto::verify_tls12_signature( message, cert, dss, &self.0.signature_verification_algorithms, ) } fn verify_tls13_signature( &self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct, ) -> Result { rustls::crypto::verify_tls13_signature( message, cert, dss, &self.0.signature_verification_algorithms, ) } fn supported_verify_schemes(&self) -> Vec { self.0.signature_verification_algorithms.supported_schemes() } } // ---- streams -------------------------------------------------------- /// A TLS stream, either side: the connection's state, and the /// socket's token. struct Stream { inner: Mutex, token: Token, /// The peer's certificate, if any, was verified: its names may be /// given out (`peer_names`). verified: bool, } struct Inner { sock: Arc, conn: Connection, /// The socket reached its end (read 0 bytes). eof: bool, } unsafe extern "C" fn finalize_stream(p: *mut std::ffi::c_void) { // SAFETY: made by `handshake`, finalized once. The socket // closes with its last `Arc` (the TCP connection may still hold // one, to shut it down). unsafe { drop(Box::from_raw(p.cast::())); } } /// # Safety /// `r` must be a live TLS stream resource. unsafe fn stream<'a>(r: Value) -> &'a Stream { // SAFETY: caller guarantees a TLS stream. unsafe { &*tl_resource_get(r).cast::() } } fn lock(s: &Stream) -> MutexGuard<'_, Inner> { s.inner .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) } /// What a non-blocking step did. enum Step { Done, /// The socket would block: wait for it, then try again. Blocked, } /// An error, with its code. type Failure = (i64, String); /// Send what rustls has to send. fn flush(inner: &mut Inner) -> Result { while inner.conn.wants_write() { match inner.conn.write_tls(&mut NoSigPipe::new(&*inner.sock)) { Ok(_) => {} Err(e) if e.kind() == ErrorKind::WouldBlock => return Ok(Step::Blocked), Err(e) if e.kind() == ErrorKind::Interrupted => {} Err(e) => return Err((code::IO, e.to_string())), } } Ok(Step::Done) } /// Read what the socket has into rustls and process it. fn fill(inner: &mut Inner) -> Result { match inner.conn.read_tls(&mut &*inner.sock) { Ok(0) => { inner.eof = true; Ok(Step::Done) } Ok(_) => match inner.conn.process_new_packets() { Ok(_) => Ok(Step::Done), Err(e) => { // Tell the peer why, once, without waiting. let _ = flush(inner); Err(classify(&e)) } }, Err(e) if e.kind() == ErrorKind::WouldBlock => Ok(Step::Blocked), Err(e) if e.kind() == ErrorKind::Interrupted => Ok(Step::Done), Err(e) => Err((code::IO, e.to_string())), } } /// The code of a rustls error (`std/tls`'s `TlsError`). pub(crate) fn classify(e: &rustls::Error) -> Failure { use rustls::Error as E; let c = match e { E::InvalidCertificate(c) => match c { CertificateError::UnknownIssuer => code::UNTRUSTED_ISSUER, CertificateError::Expired | CertificateError::ExpiredContext { .. } => { code::EXPIRED } CertificateError::NotValidYet | CertificateError::NotValidYetContext { .. } => { code::NOT_YET_VALID } CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. } => code::WRONG_HOST_NAME, _ => code::BAD_CERTIFICATE, }, E::AlertReceived(AlertDescription::ProtocolVersion) => code::PROTOCOL_VERSION, E::PeerIncompatible(p) if format!("{p:?}").contains("Version") => { code::PROTOCOL_VERSION } _ => code::HANDSHAKE_FAILURE, }; (c, e.to_string()) } /// Run `step` until it is done, waiting on the socket when it blocks. /// `Err(None)`: the actor was stopped while waiting (it unwinds). /// /// # Safety /// `ctx` must be the running actor's context. unsafe fn drive( ctx: *mut Ctx, s: &Stream, mut step: impl FnMut(&mut Inner) -> Result, Failure>, ) -> Result> { loop { // SAFETY: forwarded caller guarantee. let seen = unsafe { io_events(ctx) }; let blocked = { let mut inner = lock(s); match step(&mut inner) { Ok(Some(done)) => return Ok(done), Ok(None) => true, Err(f) => return Err(Some(f)), } }; // The lock is released before waiting. // SAFETY: forwarded caller guarantee. if blocked && !unsafe { wait_for(ctx, s.token, seen) } { return Err(None); } } } /// The outcome as a `Result` value; unit while unwinding. fn answer(ctx: *mut Ctx, r: Result>) -> Value { match r { Ok(v) => success(ctx, v), Err(Some((c, m))) => failure(ctx, c, &m), Err(None) => UNIT, } } /// `connect(conn, host, config)`: TLS over the TCP connection `conn`, /// to `host` (whose certificate must name it), after the handshake. /// /// # Safety /// `ctx` must be the running actor's context; the arguments a TCP /// connection, a string and a TLS configuration. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_tls_connect( ctx: *mut Ctx, conn: Value, host: Value, config: Value, ) -> Value { // SAFETY: caller guarantees the types. let (host, client) = unsafe { ( text(host).to_owned(), &*tl_resource_get(config).cast::(), ) }; let name = match ServerName::try_from(host.clone()) { Ok(n) => n, Err(_) => { return failure( ctx, code::INVALID_CONFIG, &format!("not a host name or address: {host:?}"), ); } }; match ClientConnection::new(client.config.clone(), name) { // SAFETY: forwarded caller guarantees. Ok(c) => unsafe { handshake(ctx, conn, c.into(), client.verified) }, Err(e) => failure(ctx, code::INVALID_CONFIG, &e.to_string()), } } /// `accept(conn, config)`: the server side of TLS over the TCP /// connection `conn` (one `net.accept` gave), after the handshake. With /// client authorities, the client's certificate is verified. /// /// # Safety /// `ctx` must be the running actor's context; the arguments a TCP /// connection and a TLS server configuration. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_tls_accept(ctx: *mut Ctx, conn: Value, config: Value) -> Value { // SAFETY: caller guarantees a server configuration. let config = unsafe { (*tl_resource_get(config).cast::>()).clone() }; match ServerConnection::new(config) { // SAFETY: forwarded caller guarantees. Ok(c) => unsafe { handshake(ctx, conn, c.into(), true) }, Err(e) => failure(ctx, code::INVALID_CONFIG, &e.to_string()), } } /// Give `conn`'s socket to a TLS stream over `tls`, and run the /// handshake: the stream, or the handshake's error. /// /// # Safety /// `ctx` must be the running actor's context; `conn` a TCP connection. unsafe fn handshake(ctx: *mut Ctx, conn: Value, tls: Connection, verified: bool) -> Value { let peer = match tls { Connection::Client(_) => "server", Connection::Server(_) => "client", }; // SAFETY: caller guarantees a TCP connection. let (sock, token) = match unsafe { upgrade(conn) } { Ok(parts) => parts, Err(e) => return failure(ctx, code::INVALID_CONFIG, &e), }; let boxed = Box::into_raw(Box::new(Stream { inner: Mutex::new(Inner { sock, conn: tls, eof: false, }), token, verified, })); let r = tl_resource_new(ctx, boxed.cast(), Some(finalize_stream), true); // SAFETY: a stream made here; forwarded caller guarantee. let done = unsafe { drive(ctx, stream(r), |inner| { loop { // Send first (a ClientHello, then each answer). if let Step::Blocked = flush(inner)? { return Ok(None); } if !inner.conn.is_handshaking() { return Ok(Some(())); } if inner.eof { return Err(( code::HANDSHAKE_FAILURE, format!("the {peer} closed the connection during the handshake"), )); } if let Step::Blocked = fill(inner)? { return Ok(None); } } }) }; match done { Ok(()) => success(ctx, r), Err(f) => { // SAFETY: the stream made here, released once. unsafe { drop_value(ctx, r) }; answer(ctx, Err(f)) } } } /// `read(tls, max)`: up to `max` bytes of plaintext; empty once the /// peer ended the stream with `close_notify`. An end without it is /// `Truncated`: what was read may not be all that was sent. /// /// # Safety /// `ctx` must be the running actor's context; `tls` a TLS stream. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_tls_read(ctx: *mut Ctx, tls: Value, max: Value) -> Value { // SAFETY: caller guarantees a live Int. let max = unsafe { saturating(max) }.clamp(1, 1 << 20) as usize; let mut buf = vec![0u8; max]; // SAFETY: caller guarantees a stream; forwarded guarantee. let read = unsafe { drive(ctx, stream(tls), |inner| { loop { // Plaintext already decrypted comes first. match inner.conn.reader().read(&mut buf) { Ok(n) => return Ok(Some(n)), Err(e) if e.kind() == ErrorKind::WouldBlock => {} Err(e) if e.kind() == ErrorKind::UnexpectedEof => { return Err((code::TRUNCATED, TRUNCATED.into())); } Err(e) => return Err((code::IO, e.to_string())), } // Anything rustls has to send (a key update) goes first. if let Step::Blocked = flush(inner)? { return Ok(None); } if inner.eof { return Err((code::TRUNCATED, TRUNCATED.into())); } if let Step::Blocked = fill(inner)? { return Ok(None); } } }) }; answer(ctx, read.map(|n| bytes_from(ctx, &buf[..n]))) } const TRUNCATED: &str = "the connection ended without TLS's close_notify: what was read may not be all that was sent"; /// `write(tls, data)`: all of `data` (`Bytes`). /// /// # Safety /// `ctx` must be the running actor's context; `tls` a TLS stream; /// `data` live `Bytes`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_tls_write(ctx: *mut Ctx, tls: Value, data: Value) -> Value { // SAFETY: forwarded caller guarantees. unsafe { write_all(ctx, tls, data) } } /// `write_string(tls, s)`: all of `s`, as UTF-8. /// /// # Safety /// `ctx` must be the running actor's context; `tls` a TLS stream; `s` /// a live string. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_tls_write_string(ctx: *mut Ctx, tls: Value, s: Value) -> Value { // SAFETY: forwarded caller guarantees. unsafe { write_all(ctx, tls, s) } } /// # Safety /// As `tl_tls_write`; the data stays alive while the caller waits. unsafe fn write_all(ctx: *mut Ctx, tls: Value, data: Value) -> Value { // SAFETY: caller guarantees live data, kept by the parked caller. let bytes = unsafe { bytes_of(data) }; // How much rustls took: kept across waits, outside the lock. let mut taken = 0; // SAFETY: caller guarantees a stream; forwarded guarantee. let written = unsafe { drive(ctx, stream(tls), |inner| { loop { if taken < bytes.len() { // rustls takes what fits in its buffer. taken += inner .conn .writer() .write(&bytes[taken..]) .map_err(|e| (code::IO, e.to_string()))?; } if let Step::Blocked = flush(inner)? { return Ok(None); } if taken == bytes.len() { return Ok(Some(UNIT)); } } }) }; answer(ctx, written) } /// `close(tls)`: send TLS's `close_notify` (once, without waiting) and /// shut the socket down. /// /// # Safety /// `tls` must be a TLS stream. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_tls_close(_ctx: *mut Ctx, tls: Value) -> Value { // SAFETY: caller guarantees a stream. let s = unsafe { stream(tls) }; let mut inner = lock(s); inner.conn.send_close_notify(); let _ = flush(&mut inner); let _ = inner.sock.shutdown(std::net::Shutdown::Both); UNIT } /// `alpn_protocol(tls)`: `(True, protocol)` if one was agreed on (the /// server chooses). /// /// # Safety /// `tls` must be a TLS stream. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_tls_alpn(ctx: *mut Ctx, tls: Value) -> Value { // SAFETY: caller guarantees a stream. let inner = lock(unsafe { stream(tls) }); let chosen = inner .conn .alpn_protocol() .map(|p| String::from_utf8_lossy(p).into_owned()); let found = int(i64::from(chosen.is_some())); cell( ctx, 0, &[found, string(ctx, chosen.as_deref().unwrap_or(""))], ) } /// `version(tls)`: the protocol version, `"TLS 1.3"` or `"TLS 1.2"`. /// /// # Safety /// `tls` must be a TLS stream. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_tls_version(ctx: *mut Ctx, tls: Value) -> Value { // SAFETY: caller guarantees a stream. let inner = lock(unsafe { stream(tls) }); let version = match inner.conn.protocol_version() { Some(rustls::ProtocolVersion::TLSv1_3) => "TLS 1.3", Some(rustls::ProtocolVersion::TLSv1_2) => "TLS 1.2", Some(_) | None => "unknown", }; string(ctx, version) } /// `peer_names(tls)`: the DNS names of the peer's certificate, if it /// was verified; none otherwise (no certificate, or /// `insecure_skip_verification`). /// /// # Safety /// `tls` must be a TLS stream. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_tls_peer_names(ctx: *mut Ctx, tls: Value) -> Value { // SAFETY: caller guarantees a stream. let s = unsafe { stream(tls) }; let names = match lock(s).conn.peer_certificates() { Some([leaf, ..]) if s.verified => dns_names(leaf), _ => Vec::new(), }; list(ctx, names.iter().map(|n| string(ctx, n))) } // ---- peer names ---------------------------------------------------- /// The DNS names (subject alternative names) of a certificate, as /// written (wildcards included). To show or to compare exactly; to /// check that a peer is some name, `has_name`. pub(crate) fn dns_names(leaf: &CertificateDer<'_>) -> Vec { webpki::EndEntityCert::try_from(leaf) .map(|cert| cert.valid_dns_names().map(str::to_owned).collect()) .unwrap_or_default() } /// Whether a certificate is valid for `name`, by webpki's rules /// (wildcards, case): what the distribution transport (ADR 0072) checks /// a node's name with, on a verified peer's certificate. #[cfg_attr(not(test), allow(dead_code))] pub(crate) fn has_name(leaf: &CertificateDer<'_>, name: &str) -> bool { let (Ok(cert), Ok(name)) = ( webpki::EndEntityCert::try_from(leaf), ServerName::try_from(name), ) else { return false; }; cert.verify_is_valid_for_subject_name(&name).is_ok() } #[cfg(test)] mod tests { use super::*; #[test] fn errors_map_to_their_codes() { use rustls::Error as E; let cases = [ ( E::InvalidCertificate(CertificateError::UnknownIssuer), code::UNTRUSTED_ISSUER, ), ( E::InvalidCertificate(CertificateError::Expired), code::EXPIRED, ), ( E::InvalidCertificate(CertificateError::NotValidYet), code::NOT_YET_VALID, ), ( E::InvalidCertificate(CertificateError::NotValidForName), code::WRONG_HOST_NAME, ), ( E::InvalidCertificate(CertificateError::BadEncoding), code::BAD_CERTIFICATE, ), ( E::AlertReceived(AlertDescription::ProtocolVersion), code::PROTOCOL_VERSION, ), ( E::AlertReceived(AlertDescription::HandshakeFailure), code::HANDSHAKE_FAILURE, ), (E::DecryptError, code::HANDSHAKE_FAILURE), ]; for (e, want) in cases { assert_eq!(classify(&e).0, want, "{e:?}"); } } /// The certificates of `crates/louise/tests/fixtures/tls`. fn fixture(name: &str) -> String { format!( "{}/../../crates/louise/tests/fixtures/tls/{name}", env!("CARGO_MANIFEST_DIR") ) } fn client(f: impl FnOnce(&mut ClientOptions)) -> Result, String> { let mut o = ClientOptions { authorities: Authorities { default_roots: true, ..Authorities::default() }, identity: None, alpn: Vec::new(), tls13_only: false, insecure: false, }; f(&mut o); client_config(o) } fn server(f: impl FnOnce(&mut ServerOptions)) -> Result, String> { let mut o = ServerOptions { identity: Identity { cert_file: fixture("localhost.pem"), key_file: fixture("localhost.key"), }, client_authorities: None, alpn: Vec::new(), tls13_only: false, peers: false, }; f(&mut o); server_config(o) } fn refused(r: Result) -> String { r.err().unwrap_or_default() } #[test] fn client_configurations_refuse_what_cannot_work() { // No roots at all. assert!( refused(client(|o| o.authorities.default_roots = false)) .contains("no trusted roots") ); // Text that holds no certificate. assert!( refused(client(|o| o.authorities.pems = vec!["hello".into()])) .contains("no certificate") ); // A certificate without its key. assert!(refused(identity("c.pem", "")).contains("both")); // A key file that doesn't exist: its path, not its contents. let e = refused(client(|o| { o.identity = Some(Identity { cert_file: "/nonexistent/c.pem".into(), key_file: "/nonexistent/k.pem".into(), }) })); assert!(e.contains("/nonexistent/c.pem"), "{e}"); // The defaults work, and so does a client certificate. assert!( client(|o| { o.alpn = vec![b"h2".to_vec()]; o.tls13_only = true; }) .is_ok() ); assert!( client(|o| { o.identity = Some(Identity { cert_file: fixture("client.pem"), key_file: fixture("client.key"), }) }) .is_ok() ); } #[test] fn server_configurations_refuse_what_cannot_work() { assert!(server(|_| {}).is_ok()); assert!( server(|o| { o.client_authorities = Some(Authorities { files: vec![fixture("ca.pem")], ..Authorities::default() }); o.tls13_only = true; }) .is_ok() ); // A key that isn't the certificate's. let e = refused(server(|o| o.identity.key_file = fixture("client.key"))); assert!(e.starts_with("server certificate"), "{e}"); // A key file that holds no key: its path, not its contents. let e = refused(server(|o| o.identity.key_file = fixture("ca.pem"))); assert!( e.contains("no readable private key") && e.contains("ca.pem"), "{e}" ); // A certificate file without a certificate. let e = refused(server(|o| o.identity.cert_file = fixture("localhost.key"))); assert!(e.contains("no certificate"), "{e}"); // Client authorities that hold nothing. let e = refused(server(|o| { o.client_authorities = Some(Authorities::default()); })); assert!(e.starts_with("client authorities"), "{e}"); } #[test] fn certificates_name_their_peers() { let leaf = |name: &str| { CertificateDer::from_pem_file(fixture(name)).expect("a fixture certificate") }; assert_eq!(dns_names(&leaf("localhost.pem")), ["localhost"]); assert_eq!(dns_names(&leaf("client.pem")), ["client.example"]); assert!(dns_names(&CertificateDer::from(vec![0x30, 0x03, 1, 2, 3])).is_empty()); assert!(has_name(&leaf("client.pem"), "client.example")); assert!(has_name(&leaf("client.pem"), "CLIENT.example")); assert!(!has_name(&leaf("client.pem"), "other.example")); assert!(!has_name(&leaf("client.pem"), "not a name")); assert!(has_name(&leaf("localhost.pem"), "127.0.0.1")); } /// A node's client chain longer or larger than a node's is refused /// before webpki builds a path through it (#404's security review, /// SEC-4: 99 certificates of the authority's name cost 65 times a /// real handshake), and the authority's name is not hinted. #[test] fn peer_chains_are_short() { let cert = |name: &str| { CertificateDer::from_pem_file(fixture(name)).expect("a fixture certificate") }; let mut roots = RootCertStore::empty(); roots.add(cert("ca.pem")).expect("the cluster's authority"); let provider = Arc::new(rustls::crypto::ring::default_provider()); let webpki = WebPkiClientVerifier::builder_with_provider(Arc::new(roots), provider) .clear_root_hint_subjects() .build() .expect("a verifier"); let verifier = PeerChains(webpki); let now = UnixTime::now(); let leaf = cert("node-b.pem"); assert!(verifier.verify_client_cert(&leaf, &[], now).is_ok()); // The authority itself as intermediates: harmless to webpki // within the limit, refused past it. let ca = cert("ca.pem"); let chain = vec![ca.clone(); PEER_INTERMEDIATES]; assert!(verifier.verify_client_cert(&leaf, &chain, now).is_ok()); let refused = |intermediates: &[CertificateDer<'_>]| { matches!( verifier.verify_client_cert(&leaf, intermediates, now), Err(rustls::Error::InvalidCertificate( CertificateError::ApplicationVerificationFailure )) ) }; assert!(refused(&vec![ca; PEER_INTERMEDIATES + 1])); assert!(refused(&[CertificateDer::from(vec![0; PEER_CHAIN_BYTES])])); assert!(verifier.root_hint_subjects().is_empty()); // Distribution's configurations: no tickets, no session cache. let config = server(|o| { o.client_authorities = Some(Authorities { files: vec![fixture("ca.pem")], ..Authorities::default() }); o.peers = true; }) .expect("a configuration"); assert_eq!(config.send_tls13_tickets, 0); assert!(!config.session_storage.can_cache()); } } }