
louise
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
Dernier runRéussi#1201 · main · 9 min 57 s
1Étoiles
0Forks
0Issues
| 1 | //! TLS for compiled programs (`std/tls`, ADR 0038): clients and servers, |
| 2 | //! rustls with the ring provider, over the non-blocking sockets of |
| 3 | //! `net.rs`. |
| 4 | //! |
| 5 | //! **Security review needed before production use** (ADR 0038 lists what |
| 6 | //! to check). What this module promises: |
| 7 | //! - a server's certificate and host name are always verified, against |
| 8 | //! Mozilla's roots (webpki-roots) and the CAs the program adds, unless the |
| 9 | //! program asked for `insecure_skip_verification`, which warns on stderr; |
| 10 | //! - a server given client authorities refuses every client without a |
| 11 | //! certificate they signed (mutual TLS); there is no way to skip that; |
| 12 | //! - TLS 1.2 at least, 1.3 preferred; no 0-RTT, no key log; |
| 13 | //! - an end of the connection without TLS's `close_notify` is `Truncated`, |
| 14 | //! never a clean end of the stream; |
| 15 | //! - keys are read from files, by path; neither keys nor their contents |
| 16 | //! appear in error messages. |
| 17 | //! |
| 18 | //! **Sockets:** a TLS stream takes a TCP connection's socket and reactor |
| 19 | //! token (`net::upgrade`), so it waits on the socket like `net.rs` does. |
| 20 | //! The connection keeps it only to shut it down: another actor can stop a |
| 21 | //! handshake that hangs by closing the TCP connection. Both sides share |
| 22 | //! this: a stream is a `rustls::Connection`, client or server. |
| 23 | //! |
| 24 | //! **Configurations** are built from plain Rust values (`ClientOptions`, |
| 25 | //! `ServerOptions`), so the distribution transport (ADR 0072) can make |
| 26 | //! the same mutual-TLS configurations without going through Louise, and |
| 27 | //! check a peer's name with `has_name`. |
| 28 | //! |
| 29 | //! **Threads:** a stream may be used from any actor (one at a time is the |
| 30 | //! sensible use). Its state is behind a mutex, never held while the actor |
| 31 | //! waits. |
| 32 | //! |
| 33 | //! Errors are `(code, message)` pairs, which `std/tls` turns into its |
| 34 | //! `TlsError` (codes below). |
| 35 | |
| 36 | #[cfg(feature = "tls")] |
| 37 | use crate::abi::UNIT; |
| 38 | use crate::abi::{Ctx, Value, int}; |
| 39 | use crate::values::{cell, string}; |
| 40 | |
| 41 | /// The error codes `std/tls` maps to `TlsError`'s constructors. |
| 42 | #[cfg_attr(not(feature = "tls"), allow(dead_code))] |
| 43 | mod code { |
| 44 | pub const IO: i64 = 0; |
| 45 | pub const UNTRUSTED_ISSUER: i64 = 1; |
| 46 | pub const EXPIRED: i64 = 2; |
| 47 | pub const NOT_YET_VALID: i64 = 3; |
| 48 | pub const WRONG_HOST_NAME: i64 = 4; |
| 49 | pub const BAD_CERTIFICATE: i64 = 5; |
| 50 | pub const PROTOCOL_VERSION: i64 = 6; |
| 51 | pub const HANDSHAKE_FAILURE: i64 = 7; |
| 52 | pub const TRUNCATED: i64 = 8; |
| 53 | pub const INVALID_CONFIG: i64 = 9; |
| 54 | } |
| 55 | |
| 56 | /// `Error((code, message))`. |
| 57 | fn failure(ctx: *mut Ctx, code: i64, message: &str) -> Value { |
| 58 | let pair = cell(ctx, 0, &[int(code), string(ctx, message)]); |
| 59 | cell(ctx, 1, &[pair]) |
| 60 | } |
| 61 | |
| 62 | /// `Ok(v)`. |
| 63 | #[cfg_attr(not(feature = "tls"), allow(dead_code))] |
| 64 | fn success(ctx: *mut Ctx, v: Value) -> Value { |
| 65 | cell(ctx, 0, &[v]) |
| 66 | } |
| 67 | |
| 68 | #[cfg(feature = "tls")] |
| 69 | pub use enabled::*; |
| 70 | |
| 71 | #[cfg(not(feature = "tls"))] |
| 72 | pub use disabled::*; |
| 73 | |
| 74 | #[cfg(not(feature = "tls"))] |
| 75 | mod disabled { |
| 76 | use super::*; |
| 77 | |
| 78 | const NOT_BUILT: &str = "TLS support not built in (louise_rt's `tls` feature)"; |
| 79 | |
| 80 | /// # Safety |
| 81 | /// As the enabled version. |
| 82 | #[unsafe(no_mangle)] |
| 83 | #[allow(clippy::too_many_arguments)] |
| 84 | pub unsafe extern "C" fn tl_tls_config( |
| 85 | ctx: *mut Ctx, |
| 86 | _default_roots: Value, |
| 87 | _ca_pems: Value, |
| 88 | _ca_files: Value, |
| 89 | _alpn: Value, |
| 90 | _tls13_only: Value, |
| 91 | _insecure: Value, |
| 92 | _cert_file: Value, |
| 93 | _key_file: Value, |
| 94 | ) -> Value { |
| 95 | failure(ctx, code::INVALID_CONFIG, NOT_BUILT) |
| 96 | } |
| 97 | |
| 98 | /// # Safety |
| 99 | /// As the enabled version. |
| 100 | #[unsafe(no_mangle)] |
| 101 | pub unsafe extern "C" fn tl_tls_server_config( |
| 102 | ctx: *mut Ctx, |
| 103 | _cert_file: Value, |
| 104 | _key_file: Value, |
| 105 | _client_ca_pems: Value, |
| 106 | _client_ca_files: Value, |
| 107 | _alpn: Value, |
| 108 | _tls13_only: Value, |
| 109 | ) -> Value { |
| 110 | failure(ctx, code::INVALID_CONFIG, NOT_BUILT) |
| 111 | } |
| 112 | |
| 113 | /// # Safety |
| 114 | /// As the enabled version. |
| 115 | #[unsafe(no_mangle)] |
| 116 | pub unsafe extern "C" fn tl_tls_connect( |
| 117 | ctx: *mut Ctx, |
| 118 | _conn: Value, |
| 119 | _host: Value, |
| 120 | _config: Value, |
| 121 | ) -> Value { |
| 122 | failure(ctx, code::INVALID_CONFIG, NOT_BUILT) |
| 123 | } |
| 124 | |
| 125 | /// # Safety |
| 126 | /// As the enabled version. |
| 127 | #[unsafe(no_mangle)] |
| 128 | pub unsafe extern "C" fn tl_tls_accept(ctx: *mut Ctx, _conn: Value, _config: Value) -> Value { |
| 129 | failure(ctx, code::INVALID_CONFIG, NOT_BUILT) |
| 130 | } |
| 131 | |
| 132 | macro_rules! unreachable_stream { |
| 133 | ($($name:ident($($arg:ident),*)),*) => {$( |
| 134 | /// # Safety |
| 135 | /// Never called: no TLS stream exists without the feature. |
| 136 | #[unsafe(no_mangle)] |
| 137 | pub unsafe extern "C" fn $name(ctx: *mut Ctx, $($arg: Value),*) -> Value { |
| 138 | $(let _ = $arg;)* |
| 139 | failure(ctx, code::INVALID_CONFIG, NOT_BUILT) |
| 140 | } |
| 141 | )*}; |
| 142 | } |
| 143 | unreachable_stream!( |
| 144 | tl_tls_read(tls, max), |
| 145 | tl_tls_write(tls, data), |
| 146 | tl_tls_write_string(tls, s), |
| 147 | tl_tls_close(tls), |
| 148 | tl_tls_alpn(tls), |
| 149 | tl_tls_version(tls), |
| 150 | tl_tls_peer_names(tls) |
| 151 | ); |
| 152 | } |
| 153 | |
| 154 | #[cfg(feature = "tls")] |
| 155 | mod enabled { |
| 156 | use std::io::{ErrorKind, Read, Write}; |
| 157 | use std::sync::{Arc, Mutex, MutexGuard}; |
| 158 | |
| 159 | use mio::Token; |
| 160 | use mio::net::TcpStream; |
| 161 | use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; |
| 162 | use rustls::pki_types::pem::PemObject; |
| 163 | use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime}; |
| 164 | use rustls::server::danger::{ClientCertVerified, ClientCertVerifier}; |
| 165 | use rustls::server::{NoServerSessionStorage, WebPkiClientVerifier}; |
| 166 | use rustls::{ |
| 167 | AlertDescription, CertificateError, ClientConfig, ClientConnection, Connection, |
| 168 | DigitallySignedStruct, RootCertStore, ServerConfig, ServerConnection, SignatureScheme, |
| 169 | SupportedProtocolVersion, |
| 170 | }; |
| 171 | |
| 172 | use super::*; |
| 173 | use crate::heap::drop_value; |
| 174 | use crate::int::saturating; |
| 175 | use crate::net::{io_events, upgrade, wait_for}; |
| 176 | use crate::resource::{tl_resource_get, tl_resource_new}; |
| 177 | use crate::sock::NoSigPipe; |
| 178 | use crate::values::{bytes_from, bytes_of, list, list_items, text}; |
| 179 | |
| 180 | // ---- configurations ------------------------------------------------- |
| 181 | |
| 182 | /// Trusted authorities: Mozilla's roots, PEM texts, PEM files. |
| 183 | #[derive(Default)] |
| 184 | pub(crate) struct Authorities { |
| 185 | pub(crate) default_roots: bool, |
| 186 | pub(crate) pems: Vec<String>, |
| 187 | pub(crate) files: Vec<String>, |
| 188 | } |
| 189 | |
| 190 | /// A certificate chain and its private key, PEM files: the key is read |
| 191 | /// by path only, and never quoted. |
| 192 | pub(crate) struct Identity { |
| 193 | pub(crate) cert_file: String, |
| 194 | pub(crate) key_file: String, |
| 195 | } |
| 196 | |
| 197 | /// What a client configuration is made of (`std/tls`'s `Options`). |
| 198 | pub(crate) struct ClientOptions { |
| 199 | pub(crate) authorities: Authorities, |
| 200 | /// A client certificate, for servers that ask for one. |
| 201 | pub(crate) identity: Option<Identity>, |
| 202 | pub(crate) alpn: Vec<Vec<u8>>, |
| 203 | pub(crate) tls13_only: bool, |
| 204 | /// `insecure_skip_verification`: any server certificate. |
| 205 | pub(crate) insecure: bool, |
| 206 | } |
| 207 | |
| 208 | /// What a server configuration is made of (`std/tls`'s |
| 209 | /// `ServerOptions`). |
| 210 | pub(crate) struct ServerOptions { |
| 211 | pub(crate) identity: Identity, |
| 212 | /// Mutual TLS: every client must present a certificate from these, |
| 213 | /// or the handshake fails. `None`: no client certificate asked for. |
| 214 | pub(crate) client_authorities: Option<Authorities>, |
| 215 | pub(crate) alpn: Vec<Vec<u8>>, |
| 216 | pub(crate) tls13_only: bool, |
| 217 | /// Distribution's transport (ADR 0072), whose clients are nodes: |
| 218 | /// no session resumption, so every connection verifies the chain |
| 219 | /// and its dates; no root hints; client chains of a node's length |
| 220 | /// ([`PeerChains`]). |
| 221 | pub(crate) peers: bool, |
| 222 | } |
| 223 | |
| 224 | /// A client configuration, as a `TlsConfig` resource holds it. |
| 225 | struct Client { |
| 226 | config: Arc<ClientConfig>, |
| 227 | /// The server's certificate is verified (not `insecure`): its names |
| 228 | /// may be given out (`peer_names`). |
| 229 | verified: bool, |
| 230 | } |
| 231 | |
| 232 | unsafe extern "C" fn finalize_config(p: *mut std::ffi::c_void) { |
| 233 | // SAFETY: made by `tl_tls_config`, finalized once. |
| 234 | drop(unsafe { Box::from_raw(p.cast::<Client>()) }); |
| 235 | } |
| 236 | |
| 237 | unsafe extern "C" fn finalize_server_config(p: *mut std::ffi::c_void) { |
| 238 | // SAFETY: made by `tl_tls_server_config`, finalized once. |
| 239 | drop(unsafe { Box::from_raw(p.cast::<Arc<ServerConfig>>()) }); |
| 240 | } |
| 241 | |
| 242 | /// `config(...)`: a client configuration, from `std/tls`'s `Options`. |
| 243 | /// Reads the CA and key files (a `blocking` extern: on the pool). |
| 244 | /// |
| 245 | /// # Safety |
| 246 | /// The arguments must be live values of the types `std/tls` declares. |
| 247 | #[unsafe(no_mangle)] |
| 248 | #[allow(clippy::too_many_arguments)] |
| 249 | pub unsafe extern "C" fn tl_tls_config( |
| 250 | ctx: *mut Ctx, |
| 251 | default_roots: Value, |
| 252 | ca_pems: Value, |
| 253 | ca_files: Value, |
| 254 | alpn: Value, |
| 255 | tls13_only: Value, |
| 256 | insecure: Value, |
| 257 | cert_file: Value, |
| 258 | key_file: Value, |
| 259 | ) -> Value { |
| 260 | // SAFETY: caller guarantees the types. |
| 261 | let options = unsafe { |
| 262 | identity(text(cert_file), text(key_file)).map(|identity| ClientOptions { |
| 263 | authorities: Authorities { |
| 264 | default_roots: truthy(default_roots), |
| 265 | pems: strings(ca_pems), |
| 266 | files: strings(ca_files), |
| 267 | }, |
| 268 | identity, |
| 269 | alpn: protocols(alpn), |
| 270 | tls13_only: truthy(tls13_only), |
| 271 | insecure: truthy(insecure), |
| 272 | }) |
| 273 | }; |
| 274 | let verified = options.as_ref().is_ok_and(|o| !o.insecure); |
| 275 | match options.and_then(client_config) { |
| 276 | Ok(config) => { |
| 277 | let boxed = Box::into_raw(Box::new(Client { config, verified })); |
| 278 | let r = tl_resource_new(ctx, boxed.cast(), Some(finalize_config), true); |
| 279 | success(ctx, r) |
| 280 | } |
| 281 | Err(message) => failure(ctx, code::INVALID_CONFIG, &message), |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | /// `server_config(...)`: a server configuration, from `std/tls`'s |
| 286 | /// `ServerOptions`. Reads the certificate, key and CA files (a |
| 287 | /// `blocking` extern: on the pool). |
| 288 | /// |
| 289 | /// # Safety |
| 290 | /// The arguments must be live values of the types `std/tls` declares. |
| 291 | #[unsafe(no_mangle)] |
| 292 | pub unsafe extern "C" fn tl_tls_server_config( |
| 293 | ctx: *mut Ctx, |
| 294 | cert_file: Value, |
| 295 | key_file: Value, |
| 296 | client_ca_pems: Value, |
| 297 | client_ca_files: Value, |
| 298 | alpn: Value, |
| 299 | tls13_only: Value, |
| 300 | ) -> Value { |
| 301 | // SAFETY: caller guarantees the types. |
| 302 | let options = unsafe { |
| 303 | let (pems, files) = (strings(client_ca_pems), strings(client_ca_files)); |
| 304 | ServerOptions { |
| 305 | identity: Identity { |
| 306 | cert_file: text(cert_file).to_owned(), |
| 307 | key_file: text(key_file).to_owned(), |
| 308 | }, |
| 309 | client_authorities: (!pems.is_empty() || !files.is_empty()).then_some( |
| 310 | Authorities { |
| 311 | default_roots: false, |
| 312 | pems, |
| 313 | files, |
| 314 | }, |
| 315 | ), |
| 316 | alpn: protocols(alpn), |
| 317 | tls13_only: truthy(tls13_only), |
| 318 | peers: false, |
| 319 | } |
| 320 | }; |
| 321 | match server_config(options) { |
| 322 | Ok(config) => { |
| 323 | let boxed = Box::into_raw(Box::new(config)); |
| 324 | let r = tl_resource_new(ctx, boxed.cast(), Some(finalize_server_config), true); |
| 325 | success(ctx, r) |
| 326 | } |
| 327 | Err(message) => failure(ctx, code::INVALID_CONFIG, &message), |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | fn truthy(b: Value) -> bool { |
| 332 | b == int(1) |
| 333 | } |
| 334 | |
| 335 | /// # Safety |
| 336 | /// `l` must be a live `List<String>`. |
| 337 | unsafe fn strings(l: Value) -> Vec<String> { |
| 338 | // SAFETY: caller guarantees a list of strings. |
| 339 | unsafe { list_items(l).map(|s| text(s).to_owned()).collect() } |
| 340 | } |
| 341 | |
| 342 | /// # Safety |
| 343 | /// `l` must be a live `List<String>`. |
| 344 | unsafe fn protocols(l: Value) -> Vec<Vec<u8>> { |
| 345 | // SAFETY: caller guarantees a list of strings. |
| 346 | unsafe { list_items(l).map(|s| text(s).as_bytes().to_vec()).collect() } |
| 347 | } |
| 348 | |
| 349 | /// A client certificate from `std/tls`'s two paths: both or neither. |
| 350 | fn identity(cert_file: &str, key_file: &str) -> Result<Option<Identity>, String> { |
| 351 | match (cert_file.is_empty(), key_file.is_empty()) { |
| 352 | (true, true) => Ok(None), |
| 353 | (false, false) => Ok(Some(Identity { |
| 354 | cert_file: cert_file.to_owned(), |
| 355 | key_file: key_file.to_owned(), |
| 356 | })), |
| 357 | _ => Err("a client certificate needs both its certificate and key files".into()), |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | /// A client configuration. Fails rather than make one that can't |
| 362 | /// verify anything. |
| 363 | pub(crate) fn client_config(o: ClientOptions) -> Result<Arc<ClientConfig>, String> { |
| 364 | let roots = root_store(&o.authorities)?; |
| 365 | if roots.is_empty() && !o.insecure { |
| 366 | return Err("no trusted roots: add a CA, or keep the default roots".into()); |
| 367 | } |
| 368 | let provider = Arc::new(rustls::crypto::ring::default_provider()); |
| 369 | let builder = ClientConfig::builder_with_provider(provider.clone()) |
| 370 | .with_protocol_versions(versions(o.tls13_only)) |
| 371 | .map_err(|e| e.to_string())?; |
| 372 | let builder = if o.insecure { |
| 373 | eprintln!( |
| 374 | "louise: warning: a TLS configuration skips certificate verification (`tls.insecure_skip_verification`): connections are not authenticated" |
| 375 | ); |
| 376 | builder |
| 377 | .dangerous() |
| 378 | .with_custom_certificate_verifier(Arc::new(NoVerification(provider))) |
| 379 | } else { |
| 380 | builder.with_root_certificates(roots) |
| 381 | }; |
| 382 | let mut config = match &o.identity { |
| 383 | None => builder.with_no_client_auth(), |
| 384 | Some(identity) => { |
| 385 | let (certs, key) = load_identity(identity, "client")?; |
| 386 | builder |
| 387 | .with_client_auth_cert(certs, key) |
| 388 | .map_err(|e| format!("client certificate: {e}"))? |
| 389 | } |
| 390 | }; |
| 391 | config.alpn_protocols = o.alpn; |
| 392 | // The defaults, stated: no early data, no key log. |
| 393 | config.enable_early_data = false; |
| 394 | Ok(Arc::new(config)) |
| 395 | } |
| 396 | |
| 397 | /// A server configuration. With client authorities, a client without |
| 398 | /// a certificate they signed is refused: required, never optional. |
| 399 | pub(crate) fn server_config(o: ServerOptions) -> Result<Arc<ServerConfig>, String> { |
| 400 | let (certs, key) = load_identity(&o.identity, "server")?; |
| 401 | let provider = Arc::new(rustls::crypto::ring::default_provider()); |
| 402 | let builder = ServerConfig::builder_with_provider(provider.clone()) |
| 403 | .with_protocol_versions(versions(o.tls13_only)) |
| 404 | .map_err(|e| e.to_string())?; |
| 405 | let builder = match &o.client_authorities { |
| 406 | None => builder.with_no_client_auth(), |
| 407 | Some(authorities) => { |
| 408 | let roots = root_store(authorities)?; |
| 409 | // No revocation lists (ADR 0038), and no |
| 410 | // `allow_unauthenticated`. |
| 411 | let mut verifier = |
| 412 | WebPkiClientVerifier::builder_with_provider(Arc::new(roots), provider); |
| 413 | if o.peers { |
| 414 | verifier = verifier.clear_root_hint_subjects(); |
| 415 | } |
| 416 | let verifier = verifier |
| 417 | .build() |
| 418 | .map_err(|e| format!("client authorities: {e}"))?; |
| 419 | if o.peers { |
| 420 | builder.with_client_cert_verifier(Arc::new(PeerChains(verifier))) |
| 421 | } else { |
| 422 | builder.with_client_cert_verifier(verifier) |
| 423 | } |
| 424 | } |
| 425 | }; |
| 426 | let mut config = builder |
| 427 | .with_single_cert(certs, key) |
| 428 | .map_err(|e| format!("server certificate: {e}"))?; |
| 429 | config.alpn_protocols = o.alpn; |
| 430 | // The defaults, stated: no early data, no key log. |
| 431 | config.max_early_data_size = 0; |
| 432 | if o.peers { |
| 433 | config.session_storage = Arc::new(NoServerSessionStorage {}); |
| 434 | config.send_tls13_tickets = 0; |
| 435 | } |
| 436 | Ok(Arc::new(config)) |
| 437 | } |
| 438 | |
| 439 | /// The most certificates a node's client chain holds besides its own: |
| 440 | /// a cluster's intermediate authorities. |
| 441 | pub(crate) const PEER_INTERMEDIATES: usize = 3; |
| 442 | /// The most bytes a node's client chain takes. |
| 443 | pub(crate) const PEER_CHAIN_BYTES: usize = 16 << 10; |
| 444 | |
| 445 | /// A client verifier that refuses a chain longer or larger than a |
| 446 | /// node's ([`PEER_INTERMEDIATES`], [`PEER_CHAIN_BYTES`]) before webpki |
| 447 | /// builds paths through it: a client presenting a hundred certificates |
| 448 | /// of the authority's name made path building cost 65 times a real |
| 449 | /// handshake, on distribution's one transport thread. |
| 450 | #[derive(Debug)] |
| 451 | struct PeerChains(Arc<dyn ClientCertVerifier>); |
| 452 | |
| 453 | impl ClientCertVerifier for PeerChains { |
| 454 | fn offer_client_auth(&self) -> bool { |
| 455 | self.0.offer_client_auth() |
| 456 | } |
| 457 | |
| 458 | fn client_auth_mandatory(&self) -> bool { |
| 459 | self.0.client_auth_mandatory() |
| 460 | } |
| 461 | |
| 462 | fn root_hint_subjects(&self) -> &[rustls::DistinguishedName] { |
| 463 | self.0.root_hint_subjects() |
| 464 | } |
| 465 | |
| 466 | fn verify_client_cert( |
| 467 | &self, |
| 468 | end_entity: &CertificateDer<'_>, |
| 469 | intermediates: &[CertificateDer<'_>], |
| 470 | now: UnixTime, |
| 471 | ) -> Result<ClientCertVerified, rustls::Error> { |
| 472 | let bytes = intermediates.iter().map(|c| c.len()).sum::<usize>() + end_entity.len(); |
| 473 | if intermediates.len() > PEER_INTERMEDIATES || bytes > PEER_CHAIN_BYTES { |
| 474 | return Err(rustls::Error::InvalidCertificate( |
| 475 | CertificateError::ApplicationVerificationFailure, |
| 476 | )); |
| 477 | } |
| 478 | self.0.verify_client_cert(end_entity, intermediates, now) |
| 479 | } |
| 480 | |
| 481 | fn verify_tls12_signature( |
| 482 | &self, |
| 483 | message: &[u8], |
| 484 | cert: &CertificateDer<'_>, |
| 485 | dss: &DigitallySignedStruct, |
| 486 | ) -> Result<HandshakeSignatureValid, rustls::Error> { |
| 487 | self.0.verify_tls12_signature(message, cert, dss) |
| 488 | } |
| 489 | |
| 490 | fn verify_tls13_signature( |
| 491 | &self, |
| 492 | message: &[u8], |
| 493 | cert: &CertificateDer<'_>, |
| 494 | dss: &DigitallySignedStruct, |
| 495 | ) -> Result<HandshakeSignatureValid, rustls::Error> { |
| 496 | self.0.verify_tls13_signature(message, cert, dss) |
| 497 | } |
| 498 | |
| 499 | fn supported_verify_schemes(&self) -> Vec<SignatureScheme> { |
| 500 | self.0.supported_verify_schemes() |
| 501 | } |
| 502 | } |
| 503 | |
| 504 | fn versions(tls13_only: bool) -> &'static [&'static SupportedProtocolVersion] { |
| 505 | const ONLY_13: &[&SupportedProtocolVersion] = &[&rustls::version::TLS13]; |
| 506 | const BOTH: &[&SupportedProtocolVersion] = |
| 507 | &[&rustls::version::TLS13, &rustls::version::TLS12]; |
| 508 | if tls13_only { ONLY_13 } else { BOTH } |
| 509 | } |
| 510 | |
| 511 | fn root_store(a: &Authorities) -> Result<RootCertStore, String> { |
| 512 | let mut roots = RootCertStore::empty(); |
| 513 | if a.default_roots { |
| 514 | roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); |
| 515 | } |
| 516 | for (i, pem) in a.pems.iter().enumerate() { |
| 517 | add_pem_certs( |
| 518 | &mut roots, |
| 519 | CertificateDer::pem_slice_iter(pem.as_bytes()), |
| 520 | &format!("CA text {}", i + 1), |
| 521 | )?; |
| 522 | } |
| 523 | for path in &a.files { |
| 524 | let certs = |
| 525 | CertificateDer::pem_file_iter(path).map_err(|e| format!("CA file {path}: {e}"))?; |
| 526 | add_pem_certs(&mut roots, certs, &format!("CA file {path}"))?; |
| 527 | } |
| 528 | Ok(roots) |
| 529 | } |
| 530 | |
| 531 | /// The chain and key of `identity`; `side` names it in errors. |
| 532 | fn load_identity( |
| 533 | identity: &Identity, |
| 534 | side: &str, |
| 535 | ) -> Result<(Vec<CertificateDer<'static>>, PrivateKeyDer<'static>), String> { |
| 536 | let Identity { |
| 537 | cert_file, |
| 538 | key_file, |
| 539 | } = identity; |
| 540 | let certs: Vec<CertificateDer<'static>> = CertificateDer::pem_file_iter(cert_file) |
| 541 | .and_then(|it| it.collect()) |
| 542 | .map_err(|e| format!("{side} certificate file {cert_file}: {e}"))?; |
| 543 | if certs.is_empty() { |
| 544 | return Err(format!( |
| 545 | "{side} certificate file {cert_file}: no certificate in it" |
| 546 | )); |
| 547 | } |
| 548 | // The key's own error could quote it: only the path. |
| 549 | let key = PrivateKeyDer::from_pem_file(key_file) |
| 550 | .map_err(|_| format!("{side} key file {key_file}: no readable private key"))?; |
| 551 | Ok((certs, key)) |
| 552 | } |
| 553 | |
| 554 | fn add_pem_certs( |
| 555 | roots: &mut RootCertStore, |
| 556 | certs: impl Iterator<Item = Result<CertificateDer<'static>, rustls::pki_types::pem::Error>>, |
| 557 | what: &str, |
| 558 | ) -> Result<(), String> { |
| 559 | let mut n = 0; |
| 560 | for c in certs { |
| 561 | let c = c.map_err(|e| format!("{what}: {e}"))?; |
| 562 | roots.add(c).map_err(|e| format!("{what}: {e}"))?; |
| 563 | n += 1; |
| 564 | } |
| 565 | if n == 0 { |
| 566 | return Err(format!("{what}: no certificate in it")); |
| 567 | } |
| 568 | Ok(()) |
| 569 | } |
| 570 | |
| 571 | /// `insecure_skip_verification`: accepts any certificate. Signatures |
| 572 | /// are still checked, so the server proves it holds the key of the |
| 573 | /// certificate it sent (whatever that is). |
| 574 | #[derive(Debug)] |
| 575 | struct NoVerification(Arc<rustls::crypto::CryptoProvider>); |
| 576 | |
| 577 | impl ServerCertVerifier for NoVerification { |
| 578 | fn verify_server_cert( |
| 579 | &self, |
| 580 | _end_entity: &CertificateDer<'_>, |
| 581 | _intermediates: &[CertificateDer<'_>], |
| 582 | _server_name: &ServerName<'_>, |
| 583 | _ocsp: &[u8], |
| 584 | _now: UnixTime, |
| 585 | ) -> Result<ServerCertVerified, rustls::Error> { |
| 586 | Ok(ServerCertVerified::assertion()) |
| 587 | } |
| 588 | |
| 589 | fn verify_tls12_signature( |
| 590 | &self, |
| 591 | message: &[u8], |
| 592 | cert: &CertificateDer<'_>, |
| 593 | dss: &DigitallySignedStruct, |
| 594 | ) -> Result<HandshakeSignatureValid, rustls::Error> { |
| 595 | rustls::crypto::verify_tls12_signature( |
| 596 | message, |
| 597 | cert, |
| 598 | dss, |
| 599 | &self.0.signature_verification_algorithms, |
| 600 | ) |
| 601 | } |
| 602 | |
| 603 | fn verify_tls13_signature( |
| 604 | &self, |
| 605 | message: &[u8], |
| 606 | cert: &CertificateDer<'_>, |
| 607 | dss: &DigitallySignedStruct, |
| 608 | ) -> Result<HandshakeSignatureValid, rustls::Error> { |
| 609 | rustls::crypto::verify_tls13_signature( |
| 610 | message, |
| 611 | cert, |
| 612 | dss, |
| 613 | &self.0.signature_verification_algorithms, |
| 614 | ) |
| 615 | } |
| 616 | |
| 617 | fn supported_verify_schemes(&self) -> Vec<SignatureScheme> { |
| 618 | self.0.signature_verification_algorithms.supported_schemes() |
| 619 | } |
| 620 | } |
| 621 | |
| 622 | // ---- streams -------------------------------------------------------- |
| 623 | |
| 624 | /// A TLS stream, either side: the connection's state, and the |
| 625 | /// socket's token. |
| 626 | struct Stream { |
| 627 | inner: Mutex<Inner>, |
| 628 | token: Token, |
| 629 | /// The peer's certificate, if any, was verified: its names may be |
| 630 | /// given out (`peer_names`). |
| 631 | verified: bool, |
| 632 | } |
| 633 | |
| 634 | struct Inner { |
| 635 | sock: Arc<TcpStream>, |
| 636 | conn: Connection, |
| 637 | /// The socket reached its end (read 0 bytes). |
| 638 | eof: bool, |
| 639 | } |
| 640 | |
| 641 | unsafe extern "C" fn finalize_stream(p: *mut std::ffi::c_void) { |
| 642 | // SAFETY: made by `handshake`, finalized once. The socket |
| 643 | // closes with its last `Arc` (the TCP connection may still hold |
| 644 | // one, to shut it down). |
| 645 | unsafe { |
| 646 | drop(Box::from_raw(p.cast::<Stream>())); |
| 647 | } |
| 648 | } |
| 649 | |
| 650 | /// # Safety |
| 651 | /// `r` must be a live TLS stream resource. |
| 652 | unsafe fn stream<'a>(r: Value) -> &'a Stream { |
| 653 | // SAFETY: caller guarantees a TLS stream. |
| 654 | unsafe { &*tl_resource_get(r).cast::<Stream>() } |
| 655 | } |
| 656 | |
| 657 | fn lock(s: &Stream) -> MutexGuard<'_, Inner> { |
| 658 | s.inner |
| 659 | .lock() |
| 660 | .unwrap_or_else(std::sync::PoisonError::into_inner) |
| 661 | } |
| 662 | |
| 663 | /// What a non-blocking step did. |
| 664 | enum Step { |
| 665 | Done, |
| 666 | /// The socket would block: wait for it, then try again. |
| 667 | Blocked, |
| 668 | } |
| 669 | |
| 670 | /// An error, with its code. |
| 671 | type Failure = (i64, String); |
| 672 | |
| 673 | /// Send what rustls has to send. |
| 674 | fn flush(inner: &mut Inner) -> Result<Step, Failure> { |
| 675 | while inner.conn.wants_write() { |
| 676 | match inner.conn.write_tls(&mut NoSigPipe::new(&*inner.sock)) { |
| 677 | Ok(_) => {} |
| 678 | Err(e) if e.kind() == ErrorKind::WouldBlock => return Ok(Step::Blocked), |
| 679 | Err(e) if e.kind() == ErrorKind::Interrupted => {} |
| 680 | Err(e) => return Err((code::IO, e.to_string())), |
| 681 | } |
| 682 | } |
| 683 | Ok(Step::Done) |
| 684 | } |
| 685 | |
| 686 | /// Read what the socket has into rustls and process it. |
| 687 | fn fill(inner: &mut Inner) -> Result<Step, Failure> { |
| 688 | match inner.conn.read_tls(&mut &*inner.sock) { |
| 689 | Ok(0) => { |
| 690 | inner.eof = true; |
| 691 | Ok(Step::Done) |
| 692 | } |
| 693 | Ok(_) => match inner.conn.process_new_packets() { |
| 694 | Ok(_) => Ok(Step::Done), |
| 695 | Err(e) => { |
| 696 | // Tell the peer why, once, without waiting. |
| 697 | let _ = flush(inner); |
| 698 | Err(classify(&e)) |
| 699 | } |
| 700 | }, |
| 701 | Err(e) if e.kind() == ErrorKind::WouldBlock => Ok(Step::Blocked), |
| 702 | Err(e) if e.kind() == ErrorKind::Interrupted => Ok(Step::Done), |
| 703 | Err(e) => Err((code::IO, e.to_string())), |
| 704 | } |
| 705 | } |
| 706 | |
| 707 | /// The code of a rustls error (`std/tls`'s `TlsError`). |
| 708 | pub(crate) fn classify(e: &rustls::Error) -> Failure { |
| 709 | use rustls::Error as E; |
| 710 | let c = match e { |
| 711 | E::InvalidCertificate(c) => match c { |
| 712 | CertificateError::UnknownIssuer => code::UNTRUSTED_ISSUER, |
| 713 | CertificateError::Expired | CertificateError::ExpiredContext { .. } => { |
| 714 | code::EXPIRED |
| 715 | } |
| 716 | CertificateError::NotValidYet | CertificateError::NotValidYetContext { .. } => { |
| 717 | code::NOT_YET_VALID |
| 718 | } |
| 719 | CertificateError::NotValidForName |
| 720 | | CertificateError::NotValidForNameContext { .. } => code::WRONG_HOST_NAME, |
| 721 | _ => code::BAD_CERTIFICATE, |
| 722 | }, |
| 723 | E::AlertReceived(AlertDescription::ProtocolVersion) => code::PROTOCOL_VERSION, |
| 724 | E::PeerIncompatible(p) if format!("{p:?}").contains("Version") => { |
| 725 | code::PROTOCOL_VERSION |
| 726 | } |
| 727 | _ => code::HANDSHAKE_FAILURE, |
| 728 | }; |
| 729 | (c, e.to_string()) |
| 730 | } |
| 731 | |
| 732 | /// Run `step` until it is done, waiting on the socket when it blocks. |
| 733 | /// `Err(None)`: the actor was stopped while waiting (it unwinds). |
| 734 | /// |
| 735 | /// # Safety |
| 736 | /// `ctx` must be the running actor's context. |
| 737 | unsafe fn drive<T>( |
| 738 | ctx: *mut Ctx, |
| 739 | s: &Stream, |
| 740 | mut step: impl FnMut(&mut Inner) -> Result<Option<T>, Failure>, |
| 741 | ) -> Result<T, Option<Failure>> { |
| 742 | loop { |
| 743 | // SAFETY: forwarded caller guarantee. |
| 744 | let seen = unsafe { io_events(ctx) }; |
| 745 | let blocked = { |
| 746 | let mut inner = lock(s); |
| 747 | match step(&mut inner) { |
| 748 | Ok(Some(done)) => return Ok(done), |
| 749 | Ok(None) => true, |
| 750 | Err(f) => return Err(Some(f)), |
| 751 | } |
| 752 | }; |
| 753 | // The lock is released before waiting. |
| 754 | // SAFETY: forwarded caller guarantee. |
| 755 | if blocked && !unsafe { wait_for(ctx, s.token, seen) } { |
| 756 | return Err(None); |
| 757 | } |
| 758 | } |
| 759 | } |
| 760 | |
| 761 | /// The outcome as a `Result` value; unit while unwinding. |
| 762 | fn answer(ctx: *mut Ctx, r: Result<Value, Option<Failure>>) -> Value { |
| 763 | match r { |
| 764 | Ok(v) => success(ctx, v), |
| 765 | Err(Some((c, m))) => failure(ctx, c, &m), |
| 766 | Err(None) => UNIT, |
| 767 | } |
| 768 | } |
| 769 | |
| 770 | /// `connect(conn, host, config)`: TLS over the TCP connection `conn`, |
| 771 | /// to `host` (whose certificate must name it), after the handshake. |
| 772 | /// |
| 773 | /// # Safety |
| 774 | /// `ctx` must be the running actor's context; the arguments a TCP |
| 775 | /// connection, a string and a TLS configuration. |
| 776 | #[unsafe(no_mangle)] |
| 777 | pub unsafe extern "C" fn tl_tls_connect( |
| 778 | ctx: *mut Ctx, |
| 779 | conn: Value, |
| 780 | host: Value, |
| 781 | config: Value, |
| 782 | ) -> Value { |
| 783 | // SAFETY: caller guarantees the types. |
| 784 | let (host, client) = unsafe { |
| 785 | ( |
| 786 | text(host).to_owned(), |
| 787 | &*tl_resource_get(config).cast::<Client>(), |
| 788 | ) |
| 789 | }; |
| 790 | let name = match ServerName::try_from(host.clone()) { |
| 791 | Ok(n) => n, |
| 792 | Err(_) => { |
| 793 | return failure( |
| 794 | ctx, |
| 795 | code::INVALID_CONFIG, |
| 796 | &format!("not a host name or address: {host:?}"), |
| 797 | ); |
| 798 | } |
| 799 | }; |
| 800 | match ClientConnection::new(client.config.clone(), name) { |
| 801 | // SAFETY: forwarded caller guarantees. |
| 802 | Ok(c) => unsafe { handshake(ctx, conn, c.into(), client.verified) }, |
| 803 | Err(e) => failure(ctx, code::INVALID_CONFIG, &e.to_string()), |
| 804 | } |
| 805 | } |
| 806 | |
| 807 | /// `accept(conn, config)`: the server side of TLS over the TCP |
| 808 | /// connection `conn` (one `net.accept` gave), after the handshake. With |
| 809 | /// client authorities, the client's certificate is verified. |
| 810 | /// |
| 811 | /// # Safety |
| 812 | /// `ctx` must be the running actor's context; the arguments a TCP |
| 813 | /// connection and a TLS server configuration. |
| 814 | #[unsafe(no_mangle)] |
| 815 | pub unsafe extern "C" fn tl_tls_accept(ctx: *mut Ctx, conn: Value, config: Value) -> Value { |
| 816 | // SAFETY: caller guarantees a server configuration. |
| 817 | let config = unsafe { (*tl_resource_get(config).cast::<Arc<ServerConfig>>()).clone() }; |
| 818 | match ServerConnection::new(config) { |
| 819 | // SAFETY: forwarded caller guarantees. |
| 820 | Ok(c) => unsafe { handshake(ctx, conn, c.into(), true) }, |
| 821 | Err(e) => failure(ctx, code::INVALID_CONFIG, &e.to_string()), |
| 822 | } |
| 823 | } |
| 824 | |
| 825 | /// Give `conn`'s socket to a TLS stream over `tls`, and run the |
| 826 | /// handshake: the stream, or the handshake's error. |
| 827 | /// |
| 828 | /// # Safety |
| 829 | /// `ctx` must be the running actor's context; `conn` a TCP connection. |
| 830 | unsafe fn handshake(ctx: *mut Ctx, conn: Value, tls: Connection, verified: bool) -> Value { |
| 831 | let peer = match tls { |
| 832 | Connection::Client(_) => "server", |
| 833 | Connection::Server(_) => "client", |
| 834 | }; |
| 835 | // SAFETY: caller guarantees a TCP connection. |
| 836 | let (sock, token) = match unsafe { upgrade(conn) } { |
| 837 | Ok(parts) => parts, |
| 838 | Err(e) => return failure(ctx, code::INVALID_CONFIG, &e), |
| 839 | }; |
| 840 | let boxed = Box::into_raw(Box::new(Stream { |
| 841 | inner: Mutex::new(Inner { |
| 842 | sock, |
| 843 | conn: tls, |
| 844 | eof: false, |
| 845 | }), |
| 846 | token, |
| 847 | verified, |
| 848 | })); |
| 849 | let r = tl_resource_new(ctx, boxed.cast(), Some(finalize_stream), true); |
| 850 | // SAFETY: a stream made here; forwarded caller guarantee. |
| 851 | let done = unsafe { |
| 852 | drive(ctx, stream(r), |inner| { |
| 853 | loop { |
| 854 | // Send first (a ClientHello, then each answer). |
| 855 | if let Step::Blocked = flush(inner)? { |
| 856 | return Ok(None); |
| 857 | } |
| 858 | if !inner.conn.is_handshaking() { |
| 859 | return Ok(Some(())); |
| 860 | } |
| 861 | if inner.eof { |
| 862 | return Err(( |
| 863 | code::HANDSHAKE_FAILURE, |
| 864 | format!("the {peer} closed the connection during the handshake"), |
| 865 | )); |
| 866 | } |
| 867 | if let Step::Blocked = fill(inner)? { |
| 868 | return Ok(None); |
| 869 | } |
| 870 | } |
| 871 | }) |
| 872 | }; |
| 873 | match done { |
| 874 | Ok(()) => success(ctx, r), |
| 875 | Err(f) => { |
| 876 | // SAFETY: the stream made here, released once. |
| 877 | unsafe { drop_value(ctx, r) }; |
| 878 | answer(ctx, Err(f)) |
| 879 | } |
| 880 | } |
| 881 | } |
| 882 | |
| 883 | /// `read(tls, max)`: up to `max` bytes of plaintext; empty once the |
| 884 | /// peer ended the stream with `close_notify`. An end without it is |
| 885 | /// `Truncated`: what was read may not be all that was sent. |
| 886 | /// |
| 887 | /// # Safety |
| 888 | /// `ctx` must be the running actor's context; `tls` a TLS stream. |
| 889 | #[unsafe(no_mangle)] |
| 890 | pub unsafe extern "C" fn tl_tls_read(ctx: *mut Ctx, tls: Value, max: Value) -> Value { |
| 891 | // SAFETY: caller guarantees a live Int. |
| 892 | let max = unsafe { saturating(max) }.clamp(1, 1 << 20) as usize; |
| 893 | let mut buf = vec![0u8; max]; |
| 894 | // SAFETY: caller guarantees a stream; forwarded guarantee. |
| 895 | let read = unsafe { |
| 896 | drive(ctx, stream(tls), |inner| { |
| 897 | loop { |
| 898 | // Plaintext already decrypted comes first. |
| 899 | match inner.conn.reader().read(&mut buf) { |
| 900 | Ok(n) => return Ok(Some(n)), |
| 901 | Err(e) if e.kind() == ErrorKind::WouldBlock => {} |
| 902 | Err(e) if e.kind() == ErrorKind::UnexpectedEof => { |
| 903 | return Err((code::TRUNCATED, TRUNCATED.into())); |
| 904 | } |
| 905 | Err(e) => return Err((code::IO, e.to_string())), |
| 906 | } |
| 907 | // Anything rustls has to send (a key update) goes first. |
| 908 | if let Step::Blocked = flush(inner)? { |
| 909 | return Ok(None); |
| 910 | } |
| 911 | if inner.eof { |
| 912 | return Err((code::TRUNCATED, TRUNCATED.into())); |
| 913 | } |
| 914 | if let Step::Blocked = fill(inner)? { |
| 915 | return Ok(None); |
| 916 | } |
| 917 | } |
| 918 | }) |
| 919 | }; |
| 920 | answer(ctx, read.map(|n| bytes_from(ctx, &buf[..n]))) |
| 921 | } |
| 922 | |
| 923 | const TRUNCATED: &str = "the connection ended without TLS's close_notify: what was read may not be all that was sent"; |
| 924 | |
| 925 | /// `write(tls, data)`: all of `data` (`Bytes`). |
| 926 | /// |
| 927 | /// # Safety |
| 928 | /// `ctx` must be the running actor's context; `tls` a TLS stream; |
| 929 | /// `data` live `Bytes`. |
| 930 | #[unsafe(no_mangle)] |
| 931 | pub unsafe extern "C" fn tl_tls_write(ctx: *mut Ctx, tls: Value, data: Value) -> Value { |
| 932 | // SAFETY: forwarded caller guarantees. |
| 933 | unsafe { write_all(ctx, tls, data) } |
| 934 | } |
| 935 | |
| 936 | /// `write_string(tls, s)`: all of `s`, as UTF-8. |
| 937 | /// |
| 938 | /// # Safety |
| 939 | /// `ctx` must be the running actor's context; `tls` a TLS stream; `s` |
| 940 | /// a live string. |
| 941 | #[unsafe(no_mangle)] |
| 942 | pub unsafe extern "C" fn tl_tls_write_string(ctx: *mut Ctx, tls: Value, s: Value) -> Value { |
| 943 | // SAFETY: forwarded caller guarantees. |
| 944 | unsafe { write_all(ctx, tls, s) } |
| 945 | } |
| 946 | |
| 947 | /// # Safety |
| 948 | /// As `tl_tls_write`; the data stays alive while the caller waits. |
| 949 | unsafe fn write_all(ctx: *mut Ctx, tls: Value, data: Value) -> Value { |
| 950 | // SAFETY: caller guarantees live data, kept by the parked caller. |
| 951 | let bytes = unsafe { bytes_of(data) }; |
| 952 | // How much rustls took: kept across waits, outside the lock. |
| 953 | let mut taken = 0; |
| 954 | // SAFETY: caller guarantees a stream; forwarded guarantee. |
| 955 | let written = unsafe { |
| 956 | drive(ctx, stream(tls), |inner| { |
| 957 | loop { |
| 958 | if taken < bytes.len() { |
| 959 | // rustls takes what fits in its buffer. |
| 960 | taken += inner |
| 961 | .conn |
| 962 | .writer() |
| 963 | .write(&bytes[taken..]) |
| 964 | .map_err(|e| (code::IO, e.to_string()))?; |
| 965 | } |
| 966 | if let Step::Blocked = flush(inner)? { |
| 967 | return Ok(None); |
| 968 | } |
| 969 | if taken == bytes.len() { |
| 970 | return Ok(Some(UNIT)); |
| 971 | } |
| 972 | } |
| 973 | }) |
| 974 | }; |
| 975 | answer(ctx, written) |
| 976 | } |
| 977 | |
| 978 | /// `close(tls)`: send TLS's `close_notify` (once, without waiting) and |
| 979 | /// shut the socket down. |
| 980 | /// |
| 981 | /// # Safety |
| 982 | /// `tls` must be a TLS stream. |
| 983 | #[unsafe(no_mangle)] |
| 984 | pub unsafe extern "C" fn tl_tls_close(_ctx: *mut Ctx, tls: Value) -> Value { |
| 985 | // SAFETY: caller guarantees a stream. |
| 986 | let s = unsafe { stream(tls) }; |
| 987 | let mut inner = lock(s); |
| 988 | inner.conn.send_close_notify(); |
| 989 | let _ = flush(&mut inner); |
| 990 | let _ = inner.sock.shutdown(std::net::Shutdown::Both); |
| 991 | UNIT |
| 992 | } |
| 993 | |
| 994 | /// `alpn_protocol(tls)`: `(True, protocol)` if one was agreed on (the |
| 995 | /// server chooses). |
| 996 | /// |
| 997 | /// # Safety |
| 998 | /// `tls` must be a TLS stream. |
| 999 | #[unsafe(no_mangle)] |
| 1000 | pub unsafe extern "C" fn tl_tls_alpn(ctx: *mut Ctx, tls: Value) -> Value { |
| 1001 | // SAFETY: caller guarantees a stream. |
| 1002 | let inner = lock(unsafe { stream(tls) }); |
| 1003 | let chosen = inner |
| 1004 | .conn |
| 1005 | .alpn_protocol() |
| 1006 | .map(|p| String::from_utf8_lossy(p).into_owned()); |
| 1007 | let found = int(i64::from(chosen.is_some())); |
| 1008 | cell( |
| 1009 | ctx, |
| 1010 | 0, |
| 1011 | &[found, string(ctx, chosen.as_deref().unwrap_or(""))], |
| 1012 | ) |
| 1013 | } |
| 1014 | |
| 1015 | /// `version(tls)`: the protocol version, `"TLS 1.3"` or `"TLS 1.2"`. |
| 1016 | /// |
| 1017 | /// # Safety |
| 1018 | /// `tls` must be a TLS stream. |
| 1019 | #[unsafe(no_mangle)] |
| 1020 | pub unsafe extern "C" fn tl_tls_version(ctx: *mut Ctx, tls: Value) -> Value { |
| 1021 | // SAFETY: caller guarantees a stream. |
| 1022 | let inner = lock(unsafe { stream(tls) }); |
| 1023 | let version = match inner.conn.protocol_version() { |
| 1024 | Some(rustls::ProtocolVersion::TLSv1_3) => "TLS 1.3", |
| 1025 | Some(rustls::ProtocolVersion::TLSv1_2) => "TLS 1.2", |
| 1026 | Some(_) | None => "unknown", |
| 1027 | }; |
| 1028 | string(ctx, version) |
| 1029 | } |
| 1030 | |
| 1031 | /// `peer_names(tls)`: the DNS names of the peer's certificate, if it |
| 1032 | /// was verified; none otherwise (no certificate, or |
| 1033 | /// `insecure_skip_verification`). |
| 1034 | /// |
| 1035 | /// # Safety |
| 1036 | /// `tls` must be a TLS stream. |
| 1037 | #[unsafe(no_mangle)] |
| 1038 | pub unsafe extern "C" fn tl_tls_peer_names(ctx: *mut Ctx, tls: Value) -> Value { |
| 1039 | // SAFETY: caller guarantees a stream. |
| 1040 | let s = unsafe { stream(tls) }; |
| 1041 | let names = match lock(s).conn.peer_certificates() { |
| 1042 | Some([leaf, ..]) if s.verified => dns_names(leaf), |
| 1043 | _ => Vec::new(), |
| 1044 | }; |
| 1045 | list(ctx, names.iter().map(|n| string(ctx, n))) |
| 1046 | } |
| 1047 | |
| 1048 | // ---- peer names ---------------------------------------------------- |
| 1049 | |
| 1050 | /// The DNS names (subject alternative names) of a certificate, as |
| 1051 | /// written (wildcards included). To show or to compare exactly; to |
| 1052 | /// check that a peer is some name, `has_name`. |
| 1053 | pub(crate) fn dns_names(leaf: &CertificateDer<'_>) -> Vec<String> { |
| 1054 | webpki::EndEntityCert::try_from(leaf) |
| 1055 | .map(|cert| cert.valid_dns_names().map(str::to_owned).collect()) |
| 1056 | .unwrap_or_default() |
| 1057 | } |
| 1058 | |
| 1059 | /// Whether a certificate is valid for `name`, by webpki's rules |
| 1060 | /// (wildcards, case): what the distribution transport (ADR 0072) checks |
| 1061 | /// a node's name with, on a verified peer's certificate. |
| 1062 | #[cfg_attr(not(test), allow(dead_code))] |
| 1063 | pub(crate) fn has_name(leaf: &CertificateDer<'_>, name: &str) -> bool { |
| 1064 | let (Ok(cert), Ok(name)) = ( |
| 1065 | webpki::EndEntityCert::try_from(leaf), |
| 1066 | ServerName::try_from(name), |
| 1067 | ) else { |
| 1068 | return false; |
| 1069 | }; |
| 1070 | cert.verify_is_valid_for_subject_name(&name).is_ok() |
| 1071 | } |
| 1072 | |
| 1073 | #[cfg(test)] |
| 1074 | mod tests { |
| 1075 | use super::*; |
| 1076 | |
| 1077 | #[test] |
| 1078 | fn errors_map_to_their_codes() { |
| 1079 | use rustls::Error as E; |
| 1080 | let cases = [ |
| 1081 | ( |
| 1082 | E::InvalidCertificate(CertificateError::UnknownIssuer), |
| 1083 | code::UNTRUSTED_ISSUER, |
| 1084 | ), |
| 1085 | ( |
| 1086 | E::InvalidCertificate(CertificateError::Expired), |
| 1087 | code::EXPIRED, |
| 1088 | ), |
| 1089 | ( |
| 1090 | E::InvalidCertificate(CertificateError::NotValidYet), |
| 1091 | code::NOT_YET_VALID, |
| 1092 | ), |
| 1093 | ( |
| 1094 | E::InvalidCertificate(CertificateError::NotValidForName), |
| 1095 | code::WRONG_HOST_NAME, |
| 1096 | ), |
| 1097 | ( |
| 1098 | E::InvalidCertificate(CertificateError::BadEncoding), |
| 1099 | code::BAD_CERTIFICATE, |
| 1100 | ), |
| 1101 | ( |
| 1102 | E::AlertReceived(AlertDescription::ProtocolVersion), |
| 1103 | code::PROTOCOL_VERSION, |
| 1104 | ), |
| 1105 | ( |
| 1106 | E::AlertReceived(AlertDescription::HandshakeFailure), |
| 1107 | code::HANDSHAKE_FAILURE, |
| 1108 | ), |
| 1109 | (E::DecryptError, code::HANDSHAKE_FAILURE), |
| 1110 | ]; |
| 1111 | for (e, want) in cases { |
| 1112 | assert_eq!(classify(&e).0, want, "{e:?}"); |
| 1113 | } |
| 1114 | } |
| 1115 | |
| 1116 | /// The certificates of `crates/louise/tests/fixtures/tls`. |
| 1117 | fn fixture(name: &str) -> String { |
| 1118 | format!( |
| 1119 | "{}/../../crates/louise/tests/fixtures/tls/{name}", |
| 1120 | env!("CARGO_MANIFEST_DIR") |
| 1121 | ) |
| 1122 | } |
| 1123 | |
| 1124 | fn client(f: impl FnOnce(&mut ClientOptions)) -> Result<Arc<ClientConfig>, String> { |
| 1125 | let mut o = ClientOptions { |
| 1126 | authorities: Authorities { |
| 1127 | default_roots: true, |
| 1128 | ..Authorities::default() |
| 1129 | }, |
| 1130 | identity: None, |
| 1131 | alpn: Vec::new(), |
| 1132 | tls13_only: false, |
| 1133 | insecure: false, |
| 1134 | }; |
| 1135 | f(&mut o); |
| 1136 | client_config(o) |
| 1137 | } |
| 1138 | |
| 1139 | fn server(f: impl FnOnce(&mut ServerOptions)) -> Result<Arc<ServerConfig>, String> { |
| 1140 | let mut o = ServerOptions { |
| 1141 | identity: Identity { |
| 1142 | cert_file: fixture("localhost.pem"), |
| 1143 | key_file: fixture("localhost.key"), |
| 1144 | }, |
| 1145 | client_authorities: None, |
| 1146 | alpn: Vec::new(), |
| 1147 | tls13_only: false, |
| 1148 | peers: false, |
| 1149 | }; |
| 1150 | f(&mut o); |
| 1151 | server_config(o) |
| 1152 | } |
| 1153 | |
| 1154 | fn refused<T>(r: Result<T, String>) -> String { |
| 1155 | r.err().unwrap_or_default() |
| 1156 | } |
| 1157 | |
| 1158 | #[test] |
| 1159 | fn client_configurations_refuse_what_cannot_work() { |
| 1160 | // No roots at all. |
| 1161 | assert!( |
| 1162 | refused(client(|o| o.authorities.default_roots = false)) |
| 1163 | .contains("no trusted roots") |
| 1164 | ); |
| 1165 | // Text that holds no certificate. |
| 1166 | assert!( |
| 1167 | refused(client(|o| o.authorities.pems = vec!["hello".into()])) |
| 1168 | .contains("no certificate") |
| 1169 | ); |
| 1170 | // A certificate without its key. |
| 1171 | assert!(refused(identity("c.pem", "")).contains("both")); |
| 1172 | // A key file that doesn't exist: its path, not its contents. |
| 1173 | let e = refused(client(|o| { |
| 1174 | o.identity = Some(Identity { |
| 1175 | cert_file: "/nonexistent/c.pem".into(), |
| 1176 | key_file: "/nonexistent/k.pem".into(), |
| 1177 | }) |
| 1178 | })); |
| 1179 | assert!(e.contains("/nonexistent/c.pem"), "{e}"); |
| 1180 | // The defaults work, and so does a client certificate. |
| 1181 | assert!( |
| 1182 | client(|o| { |
| 1183 | o.alpn = vec![b"h2".to_vec()]; |
| 1184 | o.tls13_only = true; |
| 1185 | }) |
| 1186 | .is_ok() |
| 1187 | ); |
| 1188 | assert!( |
| 1189 | client(|o| { |
| 1190 | o.identity = Some(Identity { |
| 1191 | cert_file: fixture("client.pem"), |
| 1192 | key_file: fixture("client.key"), |
| 1193 | }) |
| 1194 | }) |
| 1195 | .is_ok() |
| 1196 | ); |
| 1197 | } |
| 1198 | |
| 1199 | #[test] |
| 1200 | fn server_configurations_refuse_what_cannot_work() { |
| 1201 | assert!(server(|_| {}).is_ok()); |
| 1202 | assert!( |
| 1203 | server(|o| { |
| 1204 | o.client_authorities = Some(Authorities { |
| 1205 | files: vec![fixture("ca.pem")], |
| 1206 | ..Authorities::default() |
| 1207 | }); |
| 1208 | o.tls13_only = true; |
| 1209 | }) |
| 1210 | .is_ok() |
| 1211 | ); |
| 1212 | // A key that isn't the certificate's. |
| 1213 | let e = refused(server(|o| o.identity.key_file = fixture("client.key"))); |
| 1214 | assert!(e.starts_with("server certificate"), "{e}"); |
| 1215 | // A key file that holds no key: its path, not its contents. |
| 1216 | let e = refused(server(|o| o.identity.key_file = fixture("ca.pem"))); |
| 1217 | assert!( |
| 1218 | e.contains("no readable private key") && e.contains("ca.pem"), |
| 1219 | "{e}" |
| 1220 | ); |
| 1221 | // A certificate file without a certificate. |
| 1222 | let e = refused(server(|o| o.identity.cert_file = fixture("localhost.key"))); |
| 1223 | assert!(e.contains("no certificate"), "{e}"); |
| 1224 | // Client authorities that hold nothing. |
| 1225 | let e = refused(server(|o| { |
| 1226 | o.client_authorities = Some(Authorities::default()); |
| 1227 | })); |
| 1228 | assert!(e.starts_with("client authorities"), "{e}"); |
| 1229 | } |
| 1230 | |
| 1231 | #[test] |
| 1232 | fn certificates_name_their_peers() { |
| 1233 | let leaf = |name: &str| { |
| 1234 | CertificateDer::from_pem_file(fixture(name)).expect("a fixture certificate") |
| 1235 | }; |
| 1236 | assert_eq!(dns_names(&leaf("localhost.pem")), ["localhost"]); |
| 1237 | assert_eq!(dns_names(&leaf("client.pem")), ["client.example"]); |
| 1238 | assert!(dns_names(&CertificateDer::from(vec![0x30, 0x03, 1, 2, 3])).is_empty()); |
| 1239 | assert!(has_name(&leaf("client.pem"), "client.example")); |
| 1240 | assert!(has_name(&leaf("client.pem"), "CLIENT.example")); |
| 1241 | assert!(!has_name(&leaf("client.pem"), "other.example")); |
| 1242 | assert!(!has_name(&leaf("client.pem"), "not a name")); |
| 1243 | assert!(has_name(&leaf("localhost.pem"), "127.0.0.1")); |
| 1244 | } |
| 1245 | |
| 1246 | /// A node's client chain longer or larger than a node's is refused |
| 1247 | /// before webpki builds a path through it (#404's security review, |
| 1248 | /// SEC-4: 99 certificates of the authority's name cost 65 times a |
| 1249 | /// real handshake), and the authority's name is not hinted. |
| 1250 | #[test] |
| 1251 | fn peer_chains_are_short() { |
| 1252 | let cert = |name: &str| { |
| 1253 | CertificateDer::from_pem_file(fixture(name)).expect("a fixture certificate") |
| 1254 | }; |
| 1255 | let mut roots = RootCertStore::empty(); |
| 1256 | roots.add(cert("ca.pem")).expect("the cluster's authority"); |
| 1257 | let provider = Arc::new(rustls::crypto::ring::default_provider()); |
| 1258 | let webpki = WebPkiClientVerifier::builder_with_provider(Arc::new(roots), provider) |
| 1259 | .clear_root_hint_subjects() |
| 1260 | .build() |
| 1261 | .expect("a verifier"); |
| 1262 | let verifier = PeerChains(webpki); |
| 1263 | let now = UnixTime::now(); |
| 1264 | let leaf = cert("node-b.pem"); |
| 1265 | assert!(verifier.verify_client_cert(&leaf, &[], now).is_ok()); |
| 1266 | // The authority itself as intermediates: harmless to webpki |
| 1267 | // within the limit, refused past it. |
| 1268 | let ca = cert("ca.pem"); |
| 1269 | let chain = vec![ca.clone(); PEER_INTERMEDIATES]; |
| 1270 | assert!(verifier.verify_client_cert(&leaf, &chain, now).is_ok()); |
| 1271 | let refused = |intermediates: &[CertificateDer<'_>]| { |
| 1272 | matches!( |
| 1273 | verifier.verify_client_cert(&leaf, intermediates, now), |
| 1274 | Err(rustls::Error::InvalidCertificate( |
| 1275 | CertificateError::ApplicationVerificationFailure |
| 1276 | )) |
| 1277 | ) |
| 1278 | }; |
| 1279 | assert!(refused(&vec![ca; PEER_INTERMEDIATES + 1])); |
| 1280 | assert!(refused(&[CertificateDer::from(vec![0; PEER_CHAIN_BYTES])])); |
| 1281 | assert!(verifier.root_hint_subjects().is_empty()); |
| 1282 | // Distribution's configurations: no tickets, no session cache. |
| 1283 | let config = server(|o| { |
| 1284 | o.client_authorities = Some(Authorities { |
| 1285 | files: vec![fixture("ca.pem")], |
| 1286 | ..Authorities::default() |
| 1287 | }); |
| 1288 | o.peers = true; |
| 1289 | }) |
| 1290 | .expect("a configuration"); |
| 1291 | assert_eq!(config.send_tls13_tickets, 0); |
| 1292 | assert!(!config.session_storage.can_cache()); |
| 1293 | } |
| 1294 | } |
| 1295 | } |