Skip to main content

ostrya_fetch/
tls.rs

1//! The TLS configuration of the fetcher.
2//!
3//! Each [`Fetcher`](crate::Fetcher) builds two rustls [`ClientConfig`]s. One
4//! presents the configured client certificate, and one presents none. Both
5//! hold the same crypto provider, protocol versions, trust anchors, and ALPN
6//! offer. With no client certificate, the two are one `Arc`.
7//!
8//! ALPN offers `h2` before `http/1.1` unless HTTP/2 is off. The server picks
9//! the protocol from the offer during the handshake.
10//!
11//! The read of the host trust store and the key derivation of an encrypted
12//! key run on the blocking pool, so the build is async. All other work
13//! decodes bytes that are already in memory. Under a bypass variant, no store
14//! is read, and [`ClientConfigs::has_trust_anchors`] is `true`.
15//!
16//! [`server_config`] builds the configuration of an HTTP server with the same
17//! provider and the same key loaders. [`client_cert_verifier`] builds the
18//! verifier of a client certificate that the server configuration takes.
19
20use std::io::BufReader;
21use std::sync::Arc;
22
23use ostrya_rt as rt;
24use rustls::ClientConfig;
25use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
26use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
27use rustls::{DigitallySignedStruct, SignatureScheme};
28
29use super::{Error, Result};
30
31/// The trust setting that a fetcher verifies a server certificate with.
32///
33/// The default is [`System`](TrustRoots::System). No variant checks
34/// revocation, because the anchored path configures no CRL.
35///
36/// All TLS connections use the `graviola` crypto provider of rustls. The
37/// provider is Rust and assembly, with formally verified assembly where it is
38/// available. It adds no C code and no `cc` build dependency.
39///
40/// # Bypass variants
41///
42/// [`DangerousAcceptAnyChain`](TrustRoots::DangerousAcceptAnyChain) and
43/// [`DangerousAcceptAny`](TrustRoots::DangerousAcceptAny) bypass the
44/// verification of the server certificate. They are for an origin whose
45/// certificate the operator does not want to check. Under a bypass variant,
46/// the fetcher reads no trust store.
47///
48/// Both variants verify the handshake signature, so the peer proves that it
49/// holds the private key of the certificate that it presents. Nobody vouches
50/// for that certificate, so the peer is not authenticated.
51///
52/// An active attacker on the path can present a certificate of its own, and
53/// the handshake completes. A credential sent to such an origin goes to the
54/// party that answers the connection.
55///
56/// The cleartext credential checks of the fetcher read the scheme alone, so a
57/// credential goes to a bypass origin. The `ostree` command and `curl -k` also
58/// send it. The operator who selects a bypass accepts this risk.
59#[derive(Clone, Debug, Default, Eq, PartialEq)]
60#[non_exhaustive]
61pub enum TrustRoots {
62    /// The certificates that the host system trusts.
63    #[default]
64    System,
65    /// The PEM-encoded certificates in this blob, and no other certificates.
66    ///
67    /// If the blob does not decode as PEM, holds no certificate, or holds a
68    /// certificate that the root store refuses, [`Fetcher::new`] returns
69    /// [`Error::Fetch`].
70    ///
71    /// [`Fetcher::new`]: crate::Fetcher::new
72    Pem(Vec<u8>),
73    /// A bypass that accepts any server chain and keeps the host name check.
74    ///
75    /// The chain needs no trust anchor. The fetcher checks no expiry and no
76    /// key usage, so a client certificate or a CA certificate passes as a
77    /// server leaf. The certificate must carry the host name that the request
78    /// names. [`TrustRoots`](TrustRoots#bypass-variants) states the risk.
79    DangerousAcceptAnyChain,
80    /// A bypass that accepts any server certificate, with no host name check.
81    ///
82    /// This variant is
83    /// [`DangerousAcceptAnyChain`](TrustRoots::DangerousAcceptAnyChain) with
84    /// the host name check removed. The certificate can carry any name.
85    /// [`TrustRoots`](TrustRoots#bypass-variants) states the risk.
86    DangerousAcceptAny,
87}
88
89/// A client certificate and its private key, for TLS client authentication.
90///
91/// Both are PEM-encoded. A remote that authenticates its clients with TLS
92/// needs an identity.
93#[derive(Clone, Eq, PartialEq)]
94pub struct ClientIdentity {
95    /// The client certificate, followed by any intermediate certificates.
96    ///
97    /// If the blob holds no certificate, [`Fetcher::new`] returns
98    /// [`Error::Fetch`].
99    ///
100    /// [`Fetcher::new`]: crate::Fetcher::new
101    pub cert_chain_pem: Vec<u8>,
102    /// The private key of the client certificate.
103    ///
104    /// The blob holds one section or more. The fetcher reads the first
105    /// section whose armor label names a private key, and that section
106    /// selects the path:
107    ///
108    /// - A `PRIVATE KEY`, `RSA PRIVATE KEY`, or `EC PRIVATE KEY` section is
109    ///   read as it is.
110    /// - An `ENCRYPTED PRIVATE KEY` section is PKCS#8 under PBES2.
111    ///   [`key_passphrase`](ClientIdentity::key_passphrase) decrypts it.
112    ///
113    /// If the blob holds no private key section, [`Fetcher::new`] returns
114    /// [`Error::Fetch`].
115    ///
116    /// [`Fetcher::new`]: crate::Fetcher::new
117    pub key_pem: Vec<u8>,
118    /// The passphrase of an encrypted PKCS#8 private key.
119    ///
120    /// If this is set and the key section carries no encryption, the fetcher
121    /// refuses the key. A passphrase that decrypts nothing hides a
122    /// configuration mistake.
123    ///
124    /// # Algorithms
125    ///
126    /// - Ciphers: AES-128-CBC, AES-192-CBC, AES-256-CBC, AES-128-GCM, and
127    ///   AES-256-GCM.
128    /// - GCM parameters: a 12-byte nonce as a bare OCTET STRING. The 16-byte
129    ///   tag is at the end of the ciphertext.
130    /// - Key derivation functions: PBKDF2 with an HMAC-SHA-2 pseudorandom
131    ///   function, and scrypt.
132    ///
133    /// # Key derivation cost
134    ///
135    /// The key file sets the cost of the key derivation. The iteration count
136    /// of PBKDF2 and the cost parameter of scrypt come from the file. A file
137    /// with an extreme parameter uses that much processor time or memory. The
138    /// operator supplies the key file, so ostrya applies no bound to either
139    /// parameter.
140    ///
141    /// # Refusals
142    ///
143    /// [`Fetcher::new`] returns [`Error::Fetch`], with a message of its own,
144    /// in each of these cases:
145    ///
146    /// - The key is encrypted, and no passphrase is set.
147    /// - A passphrase is set, and the key section carries no encryption.
148    /// - The passphrase does not decrypt the key.
149    /// - This build has no implementation of the PBES2 cipher or key
150    ///   derivation function. The message names the OID. DES, 3DES, and
151    ///   PBKDF2 with an HMAC-SHA-1 pseudorandom function get this refusal.
152    /// - The key is under PKCS#5 PBES1, which the `pkcs5` crate parses and
153    ///   does not decrypt. The message names PBES1. `pkcs5` recognizes six
154    ///   PBES1 OIDs, and an OID outside that set gives a DER decoding failure.
155    ///   A corrupted document gives the same failure, so the two cases look
156    ///   the same.
157    /// - The parameters of a GCM cipher are the RFC 5084 `GCMParameters`
158    ///   SEQUENCE. The message is a DER decoding failure.
159    /// - The salt of PBKDF2 or scrypt is longer than 32 bytes. The message is
160    ///   a DER decoding failure. The OpenSSL default salt is 16 bytes.
161    /// - The key is in the legacy OpenSSL traditional PEM format, with a
162    ///   `Proc-Type: 4,ENCRYPTED` header line in the section. The message
163    ///   names the `openssl pkcs8 -topk8` conversion, which gives a PKCS#8
164    ///   key. This refusal applies with or without a passphrase.
165    ///
166    /// [`Fetcher::new`]: crate::Fetcher::new
167    pub key_passphrase: Option<String>,
168}
169
170/// Redacts the private key and the passphrase.
171///
172/// A logged configuration holds neither. The key shows as its length in
173/// bytes, and the passphrase shows as `"<redacted>"` if it is set. The
174/// certificate chain is public material and shows in full.
175impl std::fmt::Debug for ClientIdentity {
176    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
177        f.debug_struct("ClientIdentity")
178            .field("cert_chain_pem", &self.cert_chain_pem)
179            .field(
180                "key_pem",
181                &format!("<{} bytes redacted>", self.key_pem.len()),
182            )
183            .field(
184                "key_passphrase",
185                &self.key_passphrase.as_ref().map(|_| "<redacted>"),
186            )
187            .finish()
188    }
189}
190
191/// The TLS options of a fetcher.
192///
193/// The default trusts the host system store, [`TrustRoots::System`], and
194/// presents no client certificate.
195#[derive(Clone, Debug, Default, Eq, PartialEq)]
196pub struct TlsOptions {
197    /// The trust setting for the server certificate.
198    pub roots: TrustRoots,
199    /// The client certificate to present, for a remote that requires one.
200    ///
201    /// The fetcher presents the certificate to the origin that a request
202    /// names, the origin of a mirror or of a URL target. A redirect hop at
203    /// another origin gets no certificate. [`Fetcher::fetch`] states the
204    /// redirect rules.
205    ///
206    /// [`Fetcher::fetch`]: crate::Fetcher::fetch
207    pub client_identity: Option<ClientIdentity>,
208}
209
210/// The client configurations one fetcher opens its connections with.
211#[derive(Debug)]
212pub(crate) struct ClientConfigs {
213    /// What a connection to the origin a route named is opened with. It
214    /// presents the configured client certificate.
215    pub(crate) with_identity: Arc<ClientConfig>,
216    /// What a connection to a redirect hop at any other origin is opened with.
217    /// It presents no client certificate. With none configured this is the
218    /// other field's own `Arc`.
219    pub(crate) without_identity: Arc<ClientConfig>,
220    /// `true` if a handshake has what it needs to verify the peer. A store
221    /// with no anchor reaches here for a fetcher whose mirrors are all
222    /// cleartext, which opens no handshake to reach them. The caller refuses
223    /// a fetch that opens one, from the origin of the route or from a redirect
224    /// hop. A bypass variant of [`TrustRoots`] reads no store and reports
225    /// `true`, because its handshake consults no anchor and completes.
226    pub(crate) has_trust_anchors: bool,
227}
228
229/// Builds the shared client configurations.
230///
231/// `http2` selects whether ALPN offers `h2`. `https` tells whether any mirror
232/// is reached over TLS, which makes an empty system trust store fatal.
233/// `reaches_tls` tells whether any fetch can open a handshake, through a
234/// mirror, a URL target, or a redirect. Without it, [`TrustRoots::System`]
235/// reads no store and gives the empty one. `https` implies `reaches_tls`.
236pub(crate) async fn client_config(
237    options: &TlsOptions,
238    http2: bool,
239    https: bool,
240    reaches_tls: bool,
241) -> Result<ClientConfigs> {
242    let provider = Arc::new(rustls_graviola::default_provider());
243    let verification = verification(&options.roots, https, reaches_tls, &provider).await?;
244    let has_trust_anchors = match &verification {
245        Verification::Anchors(store) => !store.is_empty(),
246        Verification::Bypass(_) => true,
247    };
248    let alpn = if http2 {
249        vec![b"h2".to_vec(), b"http/1.1".to_vec()]
250    } else {
251        vec![b"http/1.1".to_vec()]
252    };
253    let mut plain = shared(&provider, &verification)?.with_no_client_auth();
254    plain.alpn_protocols = alpn.clone();
255    let without_identity = Arc::new(plain);
256    // The certificate half is built only where a certificate is configured, so
257    // a fetcher without one holds one configuration under two names.
258    let with_identity = match &options.client_identity {
259        Some(identity) => {
260            let chain = parse_certs(&identity.cert_chain_pem)?;
261            if chain.is_empty() {
262                return Err(Error::Fetch(
263                    "client certificate holds no certificate".into(),
264                ));
265            }
266            let key = parse_key(&identity.key_pem, identity.key_passphrase.as_deref()).await?;
267            let mut config = shared(&provider, &verification)?
268                .with_client_auth_cert(chain, key)
269                .map_err(|e| Error::Fetch(format!("client certificate rejected: {e}")))?;
270            config.alpn_protocols = alpn;
271            Arc::new(config)
272        }
273        None => without_identity.clone(),
274    };
275    Ok(ClientConfigs {
276        with_identity,
277        without_identity,
278        has_trust_anchors,
279    })
280}
281
282/// Builds the verifier of a client certificate from the PEM CA certificates
283/// `client_ca_pem`.
284///
285/// The verifier is the WebPKI verifier of rustls with the `graviola` crypto
286/// provider. It verifies a certificate chain against the CA certificates as
287/// trust anchors, the validity period of each certificate, and the
288/// `clientAuth` extended key usage of the end-entity certificate. It checks
289/// no revocation. A TLS handshake with this verifier also serves a client
290/// that presents no certificate.
291///
292/// A server builds one verifier, and gives it to [`server_config`] and to
293/// each other check of a client certificate, for example of a certificate
294/// that a proxy forwards.
295///
296/// # Errors
297///
298/// - [`Error::Fetch`] if `client_ca_pem` does not decode as PEM, holds no
299///   certificate, or holds a certificate that the root store refuses.
300/// - [`Error::Fetch`] if rustls refuses the verifier that it builds from the
301///   certificates.
302pub fn client_cert_verifier(
303    client_ca_pem: &[u8],
304) -> Result<Arc<dyn rustls::server::danger::ClientCertVerifier>> {
305    let provider = Arc::new(rustls_graviola::default_provider());
306    rustls::server::WebPkiClientVerifier::builder_with_provider(
307        Arc::new(pem_store(client_ca_pem)?),
308        provider,
309    )
310    .allow_unauthenticated()
311    .build()
312    .map_err(|e| Error::Fetch(format!("client ca rejected: {e}")))
313}
314
315/// Builds the TLS configuration of an HTTP server from PEM bytes.
316///
317/// The inputs are the certificate chain, the private key, and the passphrase
318/// of an encrypted key. With `client_verifier`, the server verifies a client
319/// certificate with that verifier, which [`client_cert_verifier`] builds. A
320/// client that presents a certificate must present one that the verifier
321/// accepts. A client that presents none completes the handshake.
322///
323/// The key is read as the key of a [`ClientIdentity`] is read, with the same
324/// refusals. ALPN offers `h2`, then `http/1.1`.
325///
326/// # Errors
327///
328/// - [`Error::Fetch`] if `cert_chain_pem` does not decode as PEM, or holds no
329///   certificate.
330/// - [`Error::Fetch`] if `key_pem` holds no private key that decodes, or if a
331///   refusal of [`ClientIdentity::key_passphrase`] applies.
332/// - [`Error::Fetch`] if the crypto provider supports no default protocol
333///   version.
334/// - [`Error::Fetch`] if rustls refuses the certificate chain with the key,
335///   for example a key of another certificate.
336pub async fn server_config(
337    cert_chain_pem: &[u8],
338    key_pem: &[u8],
339    key_passphrase: Option<&str>,
340    client_verifier: Option<Arc<dyn rustls::server::danger::ClientCertVerifier>>,
341) -> Result<Arc<rustls::ServerConfig>> {
342    let provider = Arc::new(rustls_graviola::default_provider());
343    let chain = parse_certs(cert_chain_pem)?;
344    if chain.is_empty() {
345        return Err(Error::Fetch(
346            "server certificate holds no certificate".into(),
347        ));
348    }
349    let key = parse_key(key_pem, key_passphrase).await?;
350    let builder = rustls::ServerConfig::builder_with_provider(provider)
351        .with_safe_default_protocol_versions()
352        .map_err(|e| Error::Fetch(format!("tls setup: {e}")))?;
353    let builder = match client_verifier {
354        Some(verifier) => builder.with_client_cert_verifier(verifier),
355        None => builder.with_no_client_auth(),
356    };
357    let mut config = builder
358        .with_single_cert(chain, key)
359        .map_err(|e| Error::Fetch(format!("server certificate rejected: {e}")))?;
360    config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
361    Ok(Arc::new(config))
362}
363
364/// Returns the builder state that both client configurations hold.
365///
366/// The state is the crypto provider, the protocol versions, and the
367/// verification of the server certificate. Both share the store and the
368/// bypass verifier by `Arc`, so the store is parsed once and held once.
369fn shared(
370    provider: &Arc<rustls::crypto::CryptoProvider>,
371    verification: &Verification,
372) -> Result<rustls::ConfigBuilder<ClientConfig, rustls::client::WantsClientCert>> {
373    let builder = ClientConfig::builder_with_provider(provider.clone())
374        .with_safe_default_protocol_versions()
375        .map_err(|e| Error::Fetch(format!("tls setup: {e}")))?;
376    Ok(match verification {
377        Verification::Anchors(store) => builder.with_root_certificates(store.clone()),
378        Verification::Bypass(verifier) => builder
379            .dangerous()
380            .with_custom_certificate_verifier(verifier.clone()),
381    })
382}
383
384/// How the client configurations verify the server certificate.
385enum Verification {
386    /// Against these trust anchors, which is the full check.
387    Anchors(Arc<rustls::RootCertStore>),
388    /// Against this verifier, which drops part of the check.
389    Bypass(Arc<dyn ServerCertVerifier>),
390}
391
392/// Resolves the trust setting into what the configurations verify with.
393///
394/// `https` tells whether a handshake will consult the anchors, and
395/// `reaches_tls` tells whether any handshake can open. A bypass variant and
396/// [`TrustRoots::System`] without `reaches_tls` read nothing, so they touch no
397/// file system and no blocking pool.
398async fn verification(
399    roots: &TrustRoots,
400    https: bool,
401    reaches_tls: bool,
402    provider: &Arc<rustls::crypto::CryptoProvider>,
403) -> Result<Verification> {
404    Ok(match roots {
405        TrustRoots::System if !reaches_tls => {
406            Verification::Anchors(Arc::new(rustls::RootCertStore::empty()))
407        }
408        TrustRoots::System => Verification::Anchors(Arc::new(system_store(https).await?)),
409        TrustRoots::Pem(pem) => Verification::Anchors(Arc::new(pem_store(pem)?)),
410        TrustRoots::DangerousAcceptAnyChain => Verification::Bypass(Arc::new(AcceptAnyChain {
411            provider: provider.clone(),
412            check_name: true,
413        })),
414        TrustRoots::DangerousAcceptAny => Verification::Bypass(Arc::new(AcceptAnyChain {
415            provider: provider.clone(),
416            check_name: false,
417        })),
418    })
419}
420
421/// The verifier that the bypass variants of [`TrustRoots`] install.
422///
423/// It accepts the chain that the server presents with no trust anchor, no
424/// expiry check, and no key-usage check. The anchored path holds the leaf to
425/// webpki's `KeyUsage::server_auth`, and this verifier holds it to nothing. So
426/// a client certificate or a CA certificate passes as a server leaf. Neither
427/// path checks revocation.
428///
429/// `check_name` selects whether the end-entity certificate must carry the name
430/// that the request names. That is the one difference between
431/// [`TrustRoots::DangerousAcceptAnyChain`] and [`TrustRoots::DangerousAcceptAny`].
432///
433/// The three signature members delegate to the crypto provider, so the
434/// handshake signature is verified as under the full check. That proves
435/// possession of the private key of a certificate that nobody vouches for, so
436/// it authenticates no peer.
437#[derive(Debug)]
438struct AcceptAnyChain {
439    provider: Arc<rustls::crypto::CryptoProvider>,
440    check_name: bool,
441}
442
443impl ServerCertVerifier for AcceptAnyChain {
444    fn verify_server_cert(
445        &self,
446        end_entity: &CertificateDer<'_>,
447        _intermediates: &[CertificateDer<'_>],
448        server_name: &ServerName<'_>,
449        _ocsp_response: &[u8],
450        _now: UnixTime,
451    ) -> std::result::Result<ServerCertVerified, rustls::Error> {
452        if self.check_name {
453            let cert = rustls::server::ParsedCertificate::try_from(end_entity)?;
454            rustls::client::verify_server_name(&cert, server_name)?;
455        }
456        Ok(ServerCertVerified::assertion())
457    }
458
459    fn verify_tls12_signature(
460        &self,
461        message: &[u8],
462        cert: &CertificateDer<'_>,
463        dss: &DigitallySignedStruct,
464    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
465        rustls::crypto::verify_tls12_signature(
466            message,
467            cert,
468            dss,
469            &self.provider.signature_verification_algorithms,
470        )
471    }
472
473    fn verify_tls13_signature(
474        &self,
475        message: &[u8],
476        cert: &CertificateDer<'_>,
477        dss: &DigitallySignedStruct,
478    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
479        rustls::crypto::verify_tls13_signature(
480            message,
481            cert,
482            dss,
483            &self.provider.signature_verification_algorithms,
484        )
485    }
486
487    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
488        self.provider
489            .signature_verification_algorithms
490            .supported_schemes()
491    }
492}
493
494#[cfg(test)]
495thread_local! {
496    /// The reads of the host trust store that this thread started.
497    pub(crate) static SYSTEM_STORE_READS: std::cell::Cell<usize> =
498        const { std::cell::Cell::new(0) };
499}
500
501/// Assembles the trust anchors that the host system holds. `https` tells
502/// whether a handshake will consult them.
503async fn system_store(https: bool) -> Result<rustls::RootCertStore> {
504    #[cfg(test)]
505    SYSTEM_STORE_READS.with(|reads| reads.set(reads.get() + 1));
506    let mut store = rustls::RootCertStore::empty();
507    // The read and the parse of the host store are file system work, so they
508    // run on the blocking pool, away from the executor thread of the caller.
509    // The certificates come back as bytes. The add to the store does no I/O.
510    let (certs, detail) = rt::unblock(|| {
511        let loaded = rustls_native_certs::load_native_certs();
512        let detail = loaded.errors.first().map(|e| e.to_string());
513        (loaded.certs, detail)
514    })
515    .await;
516    for cert in certs {
517        // The loop skips a malformed certificate in the system store, as other
518        // consumers of that store do.
519        let _ = store.add(cert);
520    }
521    // A host without a CA bundle holds no anchors. That fails a fetcher with
522    // an `https` mirror, because its handshake needs them. A cleartext-only
523    // fetcher opens no handshake, so it keeps the empty store.
524    if store.is_empty() && https {
525        let detail = detail.unwrap_or_else(|| "the system trust store is empty".to_string());
526        return Err(Error::Fetch(format!("no trusted certificates: {detail}")));
527    }
528    Ok(store)
529}
530
531/// Assembles the trust anchors that a PEM blob holds.
532fn pem_store(pem: &[u8]) -> Result<rustls::RootCertStore> {
533    let mut store = rustls::RootCertStore::empty();
534    for cert in parse_certs(pem)? {
535        store
536            .add(cert)
537            .map_err(|e| Error::Fetch(format!("trust anchor rejected: {e}")))?;
538    }
539    if store.is_empty() {
540        return Err(Error::Fetch("trust anchors hold no certificate".into()));
541    }
542    Ok(store)
543}
544
545/// Decodes each certificate in a PEM blob.
546fn parse_certs(pem: &[u8]) -> Result<Vec<CertificateDer<'static>>> {
547    rustls_pemfile::certs(&mut BufReader::new(pem))
548        .collect::<std::result::Result<Vec<_>, _>>()
549        .map_err(|e| Error::Fetch(format!("certificate pem: {e}")))
550}
551
552/// The armor label of an encrypted PKCS#8 section, which this module
553/// decrypts.
554const ENCRYPTED_KEY_LABEL: &[u8] = b"ENCRYPTED PRIVATE KEY";
555
556/// The armor labels `rustls_pemfile` reads a private key out of.
557const PLAIN_KEY_LABELS: [&[u8]; 3] = [b"PRIVATE KEY", b"RSA PRIVATE KEY", b"EC PRIVATE KEY"];
558
559/// The header that a legacy OpenSSL traditional encrypted PEM carries on a
560/// line of its own inside the section.
561///
562/// RFC 7468 allows no header, so the PEM readers here stop on such a section.
563/// The fetcher finds the line first and names the conversion. RFC 1421 makes
564/// the space after the colon optional.
565const LEGACY_ENCRYPTED_HEADER: &[u8] = b"Proc-Type:";
566
567/// The value of that header in an encrypted section.
568const LEGACY_ENCRYPTED_VALUE: &[u8] = b"4,ENCRYPTED";
569
570/// The first section of a PEM blob whose armor label names a private key.
571enum KeySection<'a> {
572    /// An `ENCRYPTED PRIVATE KEY` section, cut out of the blob, so the
573    /// decoder sees that section and nothing around it.
574    Encrypted(&'a [u8]),
575    /// A section under a label that `rustls_pemfile` reads a key from.
576    Plain(&'a [u8]),
577}
578
579/// Decodes the private key that a PEM blob holds.
580///
581/// The first section whose armor label names a private key selects the path.
582/// So a blob with a certificate and a key, or with two plain keys, reads as
583/// `rustls_pemfile` reads it. An `ENCRYPTED PRIVATE KEY` section in front of a
584/// plain key is a difference: that reader does not know the label and skips
585/// to the plain key.
586///
587/// `passphrase` decrypts an `ENCRYPTED PRIVATE KEY` section. A passphrase on a
588/// section that carries no encryption is refused, because a passphrase that
589/// decrypts nothing hides a configuration mistake.
590async fn parse_key(pem: &[u8], passphrase: Option<&str>) -> Result<PrivateKeyDer<'static>> {
591    match first_key_section(pem) {
592        Some(KeySection::Encrypted(section)) => decrypt_key(section, passphrase).await,
593        Some(KeySection::Plain(section)) => {
594            if is_legacy_encrypted(section) {
595                return Err(Error::Fetch(
596                    "private key pem is in the legacy openssl encrypted format. \
597                     convert the key to pkcs#8 with `openssl pkcs8 -topk8`"
598                        .into(),
599                ));
600            }
601            if passphrase.is_some() {
602                return Err(Error::Fetch(
603                    "a passphrase is set for a private key pem that carries no encryption".into(),
604                ));
605            }
606            read_plain_key(pem)
607        }
608        // A blob with no private-key section holds no key, whatever else it
609        // carries. `rustls_pemfile` reports that.
610        None => read_plain_key(pem),
611    }
612}
613
614/// Reads the key that `rustls_pemfile` finds first. The section scan selects
615/// that section before this call.
616fn read_plain_key(pem: &[u8]) -> Result<PrivateKeyDer<'static>> {
617    rustls_pemfile::private_key(&mut BufReader::new(pem))
618        .map_err(|e| Error::Fetch(format!("private key pem: {e}")))?
619        .ok_or_else(|| Error::Fetch("private key pem holds no key".into()))
620}
621
622/// Finds the first section whose armor label names a private key.
623///
624/// A key blob is a small configuration buffer, so this walks its lines. The
625/// walk skips a certificate section and a section under any other label.
626fn first_key_section(pem: &[u8]) -> Option<KeySection<'_>> {
627    for (start, end) in line_ranges(pem, 0) {
628        let Some(label) = armor_label(pem[start..end].trim_ascii(), b"BEGIN") else {
629            continue;
630        };
631        if label == ENCRYPTED_KEY_LABEL {
632            return Some(KeySection::Encrypted(section_at(pem, start, label)));
633        }
634        if PLAIN_KEY_LABELS.contains(&label) {
635            return Some(KeySection::Plain(section_at(pem, start, label)));
636        }
637    }
638    None
639}
640
641/// Returns the bytes of the section that opens at `begin`.
642///
643/// The bytes run from that line through the end of the matching end line. A
644/// section with no end line runs to the end of the blob, and the decoder
645/// reports it as no key.
646fn section_at<'a>(pem: &'a [u8], begin: usize, label: &[u8]) -> &'a [u8] {
647    for (start, end) in line_ranges(pem, begin) {
648        if armor_label(pem[start..end].trim_ascii(), b"END") == Some(label) {
649            return &pem[begin..end];
650        }
651    }
652    &pem[begin..]
653}
654
655/// Returns the label of a PEM armor line.
656///
657/// The line is `-----BEGIN <label>-----` for the keyword `BEGIN` and
658/// `-----END <label>-----` for `END`. A line that is neither gives `None`.
659fn armor_label<'a>(line: &'a [u8], keyword: &[u8]) -> Option<&'a [u8]> {
660    line.strip_prefix(b"-----".as_slice())?
661        .strip_prefix(keyword)?
662        .strip_prefix(b" ".as_slice())?
663        .strip_suffix(b"-----".as_slice())
664}
665
666/// Returns `true` if a section carries the header of the legacy OpenSSL
667/// traditional encrypted PEM.
668///
669/// The header opens a line of its own, so the same text in the free space
670/// around a section reads as free text.
671fn is_legacy_encrypted(section: &[u8]) -> bool {
672    line_ranges(section, 0).any(|(start, end)| {
673        section[start..end]
674            .trim_ascii()
675            .strip_prefix(LEGACY_ENCRYPTED_HEADER)
676            .is_some_and(|value| value.trim_ascii_start() == LEGACY_ENCRYPTED_VALUE)
677    })
678}
679
680/// Returns the byte range of each line of `pem` from `from`. Each range holds
681/// the newline that ends its line.
682fn line_ranges(pem: &[u8], from: usize) -> impl Iterator<Item = (usize, usize)> + '_ {
683    let mut offset = from;
684    std::iter::from_fn(move || {
685        let start = offset;
686        if start >= pem.len() {
687            return None;
688        }
689        offset = pem[start..]
690            .iter()
691            .position(|byte| *byte == b'\n')
692            .map_or(pem.len(), |index| start + index + 1);
693        Some((start, offset))
694    })
695}
696
697/// Decrypts an encrypted PKCS#8 section with `passphrase`.
698///
699/// PBKDF2 and scrypt are slow by design, and the key file sets how slow, so
700/// the work runs on the blocking pool, away from the executor thread of the
701/// caller. The closure owns its inputs, which costs one copy of the section
702/// and one of the passphrase for each fetcher.
703async fn decrypt_key(section: &[u8], passphrase: Option<&str>) -> Result<PrivateKeyDer<'static>> {
704    let Some(passphrase) = passphrase else {
705        return Err(Error::Fetch(
706            "private key pem is encrypted, and no passphrase is set".into(),
707        ));
708    };
709    let section = section.to_vec();
710    let passphrase = passphrase.to_string();
711    rt::unblock(move || decrypt_pkcs8(&section, &passphrase)).await
712}
713
714/// Decodes an encrypted PKCS#8 section and decrypts it.
715///
716/// If the decoder reads no document from the section, the error is the error
717/// of an empty blob, because neither holds a key.
718fn decrypt_pkcs8(section: &[u8], passphrase: &str) -> Result<PrivateKeyDer<'static>> {
719    let no_key = || Error::Fetch("private key pem holds no key".into());
720    let text = std::str::from_utf8(section).map_err(|_| no_key())?;
721    let (_, document) = pkcs8::SecretDocument::from_pem(text).map_err(|_| no_key())?;
722    // The document names the cipher and the key derivation function by OID.
723    // The decoder refuses an OID that it has no implementation for. DES and
724    // 3DES are compiled out, so a PBES2 key under either stops here.
725    let info = document
726        .decode_msg::<pkcs8::EncryptedPrivateKeyInfoRef<'_>>()
727        .map_err(|e| match e.kind() {
728            pkcs8::der::ErrorKind::OidUnknown { oid } => unsupported_algorithm(&oid),
729            _ => Error::Fetch(format!("encrypted private key pem: {e}")),
730        })?;
731    // `pkcs5` panics on a scrypt cost parameter of 0 when it computes the
732    // base-2 logarithm of the parameter. The check gives the refusal of an
733    // invalid scrypt parameter first.
734    let scrypt = info
735        .encryption_algorithm
736        .pbes2()
737        .and_then(|parameters| parameters.kdf.scrypt());
738    if scrypt.is_some_and(|scrypt| scrypt.cost_parameter == 0) {
739        let invalid = pkcs8::pkcs5::Error::AlgorithmParametersInvalid {
740            oid: pkcs8::pkcs5::pbes2::SCRYPT_OID,
741        };
742        return Err(Error::Fetch(format!("encrypted private key: {invalid}")));
743    }
744    let key = info.decrypt(passphrase).map_err(|e| match e {
745        // A wrong passphrase derives a wrong key. Under CBC the plaintext of
746        // that key carries invalid padding, and under GCM the tag does not
747        // match. `pkcs5` reports both failures as `DecryptFailed`.
748        pkcs8::Error::EncryptedPrivateKey(pkcs8::pkcs5::Error::DecryptFailed) => {
749            Error::Fetch("the passphrase does not decrypt the private key".into())
750        }
751        // A PBES2 pseudorandom function that is compiled out gives this
752        // error. An unknown cipher OID gives the decoder error.
753        pkcs8::Error::EncryptedPrivateKey(pkcs8::pkcs5::Error::UnsupportedAlgorithm { oid }) => {
754            unsupported_algorithm(&oid)
755        }
756        // `pkcs5` parses PBES1 and decrypts none of it.
757        pkcs8::Error::EncryptedPrivateKey(pkcs8::pkcs5::Error::NoPbes1CryptSupport) => {
758            Error::Fetch(
759                "private key pem is encrypted under pkcs#5 pbes1, \
760                 which this build does not decrypt"
761                    .into(),
762            )
763        }
764        other => Error::Fetch(format!("encrypted private key: {other}")),
765    })?;
766    Ok(PrivateKeyDer::Pkcs8(key.as_bytes().to_vec().into()))
767}
768
769/// Returns the refusal for an algorithm that this build has no implementation
770/// of. The document names the algorithm by OID, and the message does too.
771fn unsupported_algorithm(oid: &pkcs8::ObjectIdentifier) -> Error {
772    Error::Fetch(format!(
773        "private key pem is encrypted with algorithm {oid}, \
774         which this build does not decrypt"
775    ))
776}
777
778#[cfg(test)]
779mod tests {
780    use super::*;
781    use ostrya_rt::block_on;
782
783    const CA_PEM: &[u8] = include_bytes!("../../../tests/fixtures/tls/ca.pem");
784    const CLIENT_CERT_PEM: &[u8] = include_bytes!("../../../tests/fixtures/tls/client.pem");
785    const CLIENT_KEY_PEM: &[u8] = include_bytes!("../../../tests/fixtures/tls/client.key.pem");
786    /// The same key, in PKCS#8 under PBES2 with AES-256-CBC.
787    const CLIENT_KEY_ENC_PEM: &[u8] =
788        include_bytes!("../../../tests/fixtures/tls/client.key.enc.pem");
789    /// The same key, in the legacy OpenSSL traditional encrypted PEM.
790    const CLIENT_KEY_LEGACY_PEM: &[u8] =
791        include_bytes!("../../../tests/fixtures/tls/client.key.legacy.pem");
792    /// The same key, in PKCS#8 under PBES1 with pbeWithMD5AndDES-CBC.
793    const CLIENT_KEY_PBES1_PEM: &[u8] =
794        include_bytes!("../../../tests/fixtures/tls/client.key.pbes1.pem");
795    /// The same key, in PKCS#8 under PBES2 with AES-256-CBC and a PBKDF2 salt
796    /// of 64 bytes.
797    const CLIENT_KEY_SALT64_PEM: &[u8] =
798        include_bytes!("../../../tests/fixtures/tls/client.key.salt64.pem");
799    /// The passphrase that `tests/fixtures/tls/generate.sh` encrypts all
800    /// four with.
801    const KEY_PASSPHRASE: &str = "ostrya test passphrase";
802
803    /// Builds the configurations from a client key and its passphrase, so a
804    /// test states the one pair that it checks.
805    fn configs_for_key(key_pem: &[u8], passphrase: Option<&str>) -> Result<ClientConfigs> {
806        block_on(client_config(
807            &TlsOptions {
808                roots: TrustRoots::Pem(CA_PEM.to_vec()),
809                client_identity: Some(ClientIdentity {
810                    cert_chain_pem: CLIENT_CERT_PEM.to_vec(),
811                    key_pem: key_pem.to_vec(),
812                    key_passphrase: passphrase.map(str::to_string),
813                }),
814            },
815            true,
816            true,
817            true,
818        ))
819    }
820
821    #[test]
822    fn alpn_offers_h2_first_unless_disabled() {
823        let options = TlsOptions {
824            roots: TrustRoots::Pem(CA_PEM.to_vec()),
825            client_identity: None,
826        };
827        let with_h2 = block_on(client_config(&options, true, true, true)).unwrap();
828        assert_eq!(
829            with_h2.without_identity.alpn_protocols,
830            vec![b"h2".to_vec(), b"http/1.1".to_vec()]
831        );
832        let without = block_on(client_config(&options, false, true, true)).unwrap();
833        assert_eq!(
834            without.without_identity.alpn_protocols,
835            vec![b"http/1.1".to_vec()]
836        );
837    }
838
839    /// A configuration built from its own anchors reports that it holds them,
840    /// for each scheme of the mirrors.
841    #[test]
842    fn pem_anchors_are_reported_as_held() {
843        let options = TlsOptions {
844            roots: TrustRoots::Pem(CA_PEM.to_vec()),
845            client_identity: None,
846        };
847        for (https, reaches_tls) in [(true, true), (false, true), (false, false)] {
848            let configs = block_on(client_config(&options, true, https, reaches_tls)).unwrap();
849            assert!(configs.has_trust_anchors, "https={https} {reaches_tls}");
850        }
851    }
852
853    /// A configured client certificate makes two separate configurations
854    /// with the same ALPN offer. With no certificate, the two are one `Arc`.
855    #[test]
856    fn a_client_identity_is_accepted() {
857        let options = TlsOptions {
858            roots: TrustRoots::Pem(CA_PEM.to_vec()),
859            client_identity: Some(ClientIdentity {
860                cert_chain_pem: CLIENT_CERT_PEM.to_vec(),
861                key_pem: CLIENT_KEY_PEM.to_vec(),
862                key_passphrase: None,
863            }),
864        };
865        let configs = block_on(client_config(&options, true, true, true)).unwrap();
866        assert!(!Arc::ptr_eq(
867            &configs.with_identity,
868            &configs.without_identity
869        ));
870        assert_eq!(
871            configs.with_identity.alpn_protocols,
872            configs.without_identity.alpn_protocols
873        );
874
875        let options = TlsOptions {
876            roots: TrustRoots::Pem(CA_PEM.to_vec()),
877            client_identity: None,
878        };
879        let configs = block_on(client_config(&options, true, true, true)).unwrap();
880        assert!(Arc::ptr_eq(
881            &configs.with_identity,
882            &configs.without_identity
883        ));
884    }
885
886    /// A bypass variant builds with no anchors and reports that a handshake
887    /// can proceed. With no client identity, the two configurations are one
888    /// `Arc`. `tests/fetch_no_trust_store.rs` checks that the host store is
889    /// not read. It runs the constructor in a child process with an empty
890    /// store.
891    #[test]
892    fn a_bypass_needs_no_trust_store() {
893        for roots in [
894            TrustRoots::DangerousAcceptAnyChain,
895            TrustRoots::DangerousAcceptAny,
896        ] {
897            let options = TlsOptions {
898                roots: roots.clone(),
899                client_identity: None,
900            };
901            for (https, reaches_tls) in [(true, true), (false, true), (false, false)] {
902                let configs = block_on(client_config(&options, true, https, reaches_tls)).unwrap();
903                assert!(configs.has_trust_anchors, "{roots:?} https={https}");
904                assert!(Arc::ptr_eq(
905                    &configs.with_identity,
906                    &configs.without_identity
907                ));
908            }
909        }
910    }
911
912    /// A client identity with a bypass builds two configurations. Both verify
913    /// with the one bypass verifier.
914    #[test]
915    fn a_bypass_carries_a_client_identity() {
916        for roots in [
917            TrustRoots::DangerousAcceptAnyChain,
918            TrustRoots::DangerousAcceptAny,
919        ] {
920            let options = TlsOptions {
921                roots,
922                client_identity: Some(ClientIdentity {
923                    cert_chain_pem: CLIENT_CERT_PEM.to_vec(),
924                    key_pem: CLIENT_KEY_PEM.to_vec(),
925                    key_passphrase: None,
926                }),
927            };
928            let configs = block_on(client_config(&options, true, true, true)).unwrap();
929            assert!(!Arc::ptr_eq(
930                &configs.with_identity,
931                &configs.without_identity
932            ));
933            assert!(configs.has_trust_anchors);
934        }
935    }
936
937    #[test]
938    fn empty_trust_anchors_and_bad_keys_are_rejected() {
939        let no_roots = TlsOptions {
940            roots: TrustRoots::Pem(b"not a certificate\n".to_vec()),
941            client_identity: None,
942        };
943        let err = block_on(client_config(&no_roots, true, true, true)).unwrap_err();
944        assert!(err.to_string().contains("no certificate"), "{err}");
945
946        // A well-formed PEM blob that holds a certificate and no key.
947        let no_key = TlsOptions {
948            roots: TrustRoots::Pem(CA_PEM.to_vec()),
949            client_identity: Some(ClientIdentity {
950                cert_chain_pem: CLIENT_CERT_PEM.to_vec(),
951                key_pem: CA_PEM.to_vec(),
952                key_passphrase: None,
953            }),
954        };
955        let err = block_on(client_config(&no_key, true, true, true)).unwrap_err();
956        assert!(err.to_string().contains("no key"), "{err}");
957
958        let unparsable_key = TlsOptions {
959            roots: TrustRoots::Pem(CA_PEM.to_vec()),
960            client_identity: Some(ClientIdentity {
961                cert_chain_pem: CLIENT_CERT_PEM.to_vec(),
962                key_pem: b"-----BEGIN PRIVATE KEY-----\n".to_vec(),
963                key_passphrase: None,
964            }),
965        };
966        let err = block_on(client_config(&unparsable_key, true, true, true)).unwrap_err();
967        assert!(err.to_string().contains("private key pem"), "{err}");
968    }
969
970    /// An encrypted PKCS#8 key with its passphrase builds the two
971    /// configurations, the same as the key that carries no encryption.
972    #[test]
973    fn an_encrypted_client_key_is_decrypted() {
974        let configs = configs_for_key(CLIENT_KEY_ENC_PEM, Some(KEY_PASSPHRASE)).unwrap();
975        assert!(!Arc::ptr_eq(
976            &configs.with_identity,
977            &configs.without_identity
978        ));
979    }
980
981    /// Each refusal of the encrypted-key path names its own case:
982    ///
983    /// - a wrong passphrase
984    /// - an encrypted key with no passphrase
985    /// - a passphrase on a key that carries no encryption
986    /// - the legacy OpenSSL format
987    #[test]
988    fn the_encrypted_key_refusals_name_their_case() {
989        let err = configs_for_key(CLIENT_KEY_ENC_PEM, Some("not the passphrase")).unwrap_err();
990        assert_eq!(
991            err.to_string(),
992            "fetch: the passphrase does not decrypt the private key"
993        );
994
995        let err = configs_for_key(CLIENT_KEY_ENC_PEM, None).unwrap_err();
996        assert_eq!(
997            err.to_string(),
998            "fetch: private key pem is encrypted, and no passphrase is set"
999        );
1000
1001        let err = configs_for_key(CLIENT_KEY_PEM, Some(KEY_PASSPHRASE)).unwrap_err();
1002        assert_eq!(
1003            err.to_string(),
1004            "fetch: a passphrase is set for a private key pem that carries no \
1005             encryption"
1006        );
1007
1008        // The legacy form is refused with or without a passphrase. The message
1009        // names the conversion that gives a readable key.
1010        for passphrase in [Some(KEY_PASSPHRASE), None] {
1011            let err = configs_for_key(CLIENT_KEY_LEGACY_PEM, passphrase).unwrap_err();
1012            assert_eq!(
1013                err.to_string(),
1014                "fetch: private key pem is in the legacy openssl encrypted \
1015                 format. convert the key to pkcs#8 with `openssl pkcs8 -topk8`"
1016            );
1017        }
1018    }
1019
1020    /// A PKCS#8 key under PBES2 with AES-128-GCM or AES-256-GCM is decrypted,
1021    /// and a wrong passphrase gives the refusal of the CBC path. OpenSSL
1022    /// writes no PKCS#8 key under an AEAD cipher, so the test encrypts the
1023    /// plain client key with `pkcs5`.
1024    #[test]
1025    fn a_gcm_encrypted_client_key_is_decrypted() {
1026        use pkcs8::pkcs5::pbes2::{EncryptionScheme, Parameters, Pbkdf2Params};
1027
1028        let text = std::str::from_utf8(CLIENT_KEY_PEM).unwrap();
1029        let (_, plain) = pkcs8::SecretDocument::from_pem(text).unwrap();
1030        let info: pkcs8::PrivateKeyInfoRef<'_> = plain.decode_msg().unwrap();
1031        for encryption in [
1032            EncryptionScheme::Aes128Gcm { nonce: [7; 12] },
1033            EncryptionScheme::Aes256Gcm { nonce: [7; 12] },
1034        ] {
1035            let parameters = Parameters {
1036                kdf: Pbkdf2Params::hmac_sha256(1000, b"ostrya test salt")
1037                    .unwrap()
1038                    .into(),
1039                encryption,
1040            };
1041            let pem = info
1042                .encrypt_with_params(parameters, KEY_PASSPHRASE)
1043                .unwrap()
1044                .to_pem("ENCRYPTED PRIVATE KEY", pkcs8::LineEnding::LF)
1045                .unwrap();
1046
1047            let configs = configs_for_key(pem.as_bytes(), Some(KEY_PASSPHRASE)).unwrap();
1048            assert!(!Arc::ptr_eq(
1049                &configs.with_identity,
1050                &configs.without_identity
1051            ));
1052
1053            let err = configs_for_key(pem.as_bytes(), Some("not the passphrase")).unwrap_err();
1054            assert_eq!(
1055                err.to_string(),
1056                "fetch: the passphrase does not decrypt the private key"
1057            );
1058        }
1059    }
1060
1061    /// A PBKDF2 salt longer than 32 bytes gives a DER decoding failure. The
1062    /// decoder of `pkcs5` holds a salt of at most 32 bytes.
1063    #[test]
1064    fn a_salt_longer_than_32_bytes_is_refused() {
1065        let err = configs_for_key(CLIENT_KEY_SALT64_PEM, Some(KEY_PASSPHRASE)).unwrap_err();
1066        assert_eq!(
1067            err.to_string(),
1068            "fetch: encrypted private key pem: incorrect length for OCTET STRING \
1069             at DER byte 2"
1070        );
1071    }
1072
1073    /// A scrypt cost parameter of 0 is refused before the key derivation, and
1074    /// the refusal names the scrypt OID. `pkcs5` encodes the parameter and
1075    /// does not derive a key from it, so the test writes the document with an
1076    /// encrypted part that is never read.
1077    #[test]
1078    fn a_scrypt_cost_of_zero_is_refused() {
1079        use pkcs8::pkcs5::pbes2::{EncryptionScheme, Parameters, Salt, ScryptParams};
1080
1081        let kdf = ScryptParams {
1082            salt: Salt::new(b"ostrya test salt").unwrap(),
1083            cost_parameter: 0,
1084            block_size: 8,
1085            parallelization: 1,
1086            key_length: None,
1087        };
1088        let info = pkcs8::EncryptedPrivateKeyInfoRef {
1089            encryption_algorithm: pkcs8::pkcs5::EncryptionScheme::Pbes2(Parameters {
1090                kdf: kdf.into(),
1091                encryption: EncryptionScheme::Aes256Cbc { iv: [7; 16] },
1092            }),
1093            encrypted_data: pkcs8::der::asn1::OctetStringRef::new(&[0; 32]).unwrap(),
1094        };
1095        let pem = pkcs8::SecretDocument::encode_msg(&info)
1096            .unwrap()
1097            .to_pem("ENCRYPTED PRIVATE KEY", pkcs8::LineEnding::LF)
1098            .unwrap();
1099
1100        let err = configs_for_key(pem.as_bytes(), Some(KEY_PASSPHRASE)).unwrap_err();
1101        assert_eq!(
1102            err.to_string(),
1103            "fetch: encrypted private key: PKCS#5 parameters for algorithm \
1104             1.3.6.1.4.1.11591.4.11 are invalid"
1105        );
1106    }
1107
1108    /// The formatted identity carries neither the private key nor the
1109    /// passphrase, so a logged fetcher configuration carries neither. The key
1110    /// is stated by its length. The certificate chain is public material and
1111    /// is formatted in full.
1112    #[test]
1113    fn debug_redacts_the_key_and_the_passphrase() {
1114        // A `Debug` leak costs most for a key that carries no encryption. A
1115        // pull configures that case.
1116        let identity = ClientIdentity {
1117            cert_chain_pem: CLIENT_CERT_PEM.to_vec(),
1118            key_pem: CLIENT_KEY_PEM.to_vec(),
1119            key_passphrase: Some(KEY_PASSPHRASE.to_string()),
1120        };
1121        let text = format!("{identity:?}");
1122        assert!(!text.contains(KEY_PASSPHRASE), "{text}");
1123        assert!(
1124            text.contains("key_passphrase: Some(\"<redacted>\")"),
1125            "{text}"
1126        );
1127        for line in std::str::from_utf8(CLIENT_KEY_PEM)
1128            .unwrap()
1129            .lines()
1130            .filter(|line| !line.starts_with("-----"))
1131        {
1132            assert!(!text.contains(line), "{line} in {text}");
1133        }
1134        assert!(
1135            text.contains(&format!("<{} bytes redacted>", CLIENT_KEY_PEM.len())),
1136            "{text}"
1137        );
1138        assert!(text.contains("cert_chain_pem: ["), "{text}");
1139
1140        let without = ClientIdentity {
1141            key_passphrase: None,
1142            ..identity
1143        };
1144        let text = format!("{without:?}");
1145        assert!(text.contains("key_passphrase: None"), "{text}");
1146        assert!(!text.contains(KEY_PASSPHRASE), "{text}");
1147    }
1148
1149    /// The encrypted section is read whatever is around it: a trailing blank
1150    /// line, or the certificate that the usual bundle carries in front of the
1151    /// key. The decoder sees that one section, cut out of the blob.
1152    #[test]
1153    fn an_encrypted_key_is_read_out_of_a_longer_blob() {
1154        let blobs = [
1155            [CLIENT_KEY_ENC_PEM, b"\n"].concat(),
1156            [CLIENT_CERT_PEM, CLIENT_KEY_ENC_PEM].concat(),
1157            [CLIENT_KEY_ENC_PEM, CLIENT_CERT_PEM].concat(),
1158        ];
1159        for blob in blobs {
1160            let configs = configs_for_key(&blob, Some(KEY_PASSPHRASE)).unwrap();
1161            assert!(!Arc::ptr_eq(
1162                &configs.with_identity,
1163                &configs.without_identity
1164            ));
1165        }
1166    }
1167
1168    /// The first section whose label names a private key selects the path. So
1169    /// a blob with an encrypted key and a plain key is read as the first one.
1170    #[test]
1171    fn the_first_key_section_decides_the_path() {
1172        // Encrypted first: the passphrase decrypts it. With no passphrase, the
1173        // key is refused, and the plain key behind it is not read.
1174        let encrypted_first = [CLIENT_KEY_ENC_PEM, CLIENT_KEY_PEM].concat();
1175        configs_for_key(&encrypted_first, Some(KEY_PASSPHRASE)).unwrap();
1176        let err = configs_for_key(&encrypted_first, None).unwrap_err();
1177        assert_eq!(
1178            err.to_string(),
1179            "fetch: private key pem is encrypted, and no passphrase is set"
1180        );
1181
1182        // Plain first: it is read as it is. A passphrase is refused, although
1183        // an encrypted section is behind it.
1184        let plain_first = [CLIENT_KEY_PEM, CLIENT_KEY_ENC_PEM].concat();
1185        configs_for_key(&plain_first, None).unwrap();
1186        let err = configs_for_key(&plain_first, Some(KEY_PASSPHRASE)).unwrap_err();
1187        assert_eq!(
1188            err.to_string(),
1189            "fetch: a passphrase is set for a private key pem that carries no \
1190             encryption"
1191        );
1192    }
1193
1194    /// The legacy header is read inside the section that carries it. A plain
1195    /// key in front of a legacy key is read. The same text in the free space
1196    /// around a plain key reads as free text.
1197    #[test]
1198    fn the_legacy_header_is_read_inside_its_own_section() {
1199        let plain_first = [CLIENT_KEY_PEM, CLIENT_KEY_LEGACY_PEM].concat();
1200        configs_for_key(&plain_first, None).unwrap();
1201
1202        let with_note = [
1203            b"Proc-Type: 4,ENCRYPTED\n".as_slice(),
1204            b"# Proc-Type: 4,ENCRYPTED\n".as_slice(),
1205            CLIENT_KEY_PEM,
1206        ]
1207        .concat();
1208        configs_for_key(&with_note, None).unwrap();
1209    }
1210
1211    /// RFC 1421 makes the space after the colon optional. The header is
1212    /// found with or without the space.
1213    #[test]
1214    fn the_legacy_header_is_named_without_the_space() {
1215        let text = std::str::from_utf8(CLIENT_KEY_LEGACY_PEM)
1216            .unwrap()
1217            .replace("Proc-Type: 4,ENCRYPTED", "Proc-Type:4,ENCRYPTED");
1218        let err = configs_for_key(text.as_bytes(), Some(KEY_PASSPHRASE)).unwrap_err();
1219        assert_eq!(
1220            err.to_string(),
1221            "fetch: private key pem is in the legacy openssl encrypted \
1222             format. convert the key to pkcs#8 with `openssl pkcs8 -topk8`"
1223        );
1224    }
1225
1226    /// A key under PKCS#5 PBES1 is refused, and the message names PBES1.
1227    #[test]
1228    fn a_pbes1_key_is_refused_by_name() {
1229        let err = configs_for_key(CLIENT_KEY_PBES1_PEM, Some(KEY_PASSPHRASE)).unwrap_err();
1230        assert_eq!(
1231            err.to_string(),
1232            "fetch: private key pem is encrypted under pkcs#5 pbes1, \
1233             which this build does not decrypt"
1234        );
1235    }
1236
1237    const SERVER_CERT_PEM: &[u8] = include_bytes!("../../../tests/fixtures/tls/server.pem");
1238    const SERVER_KEY_PEM: &[u8] = include_bytes!("../../../tests/fixtures/tls/server.key.pem");
1239
1240    /// A server configuration offers `h2` then `http/1.1`, with and without a
1241    /// client CA.
1242    #[test]
1243    fn a_server_config_offers_h2_and_http1() {
1244        for ca in [None, Some(client_cert_verifier(CA_PEM).unwrap())] {
1245            let config =
1246                block_on(server_config(SERVER_CERT_PEM, SERVER_KEY_PEM, None, ca)).unwrap();
1247            assert_eq!(
1248                config.alpn_protocols,
1249                [b"h2".to_vec(), b"http/1.1".to_vec()]
1250            );
1251        }
1252    }
1253
1254    /// The key loaders of the client identity read the server key. So an
1255    /// encrypted key is decrypted with its passphrase and refused without
1256    /// one.
1257    #[test]
1258    fn a_server_config_reads_an_encrypted_key() {
1259        block_on(server_config(
1260            CLIENT_CERT_PEM,
1261            CLIENT_KEY_ENC_PEM,
1262            Some(KEY_PASSPHRASE),
1263            None,
1264        ))
1265        .unwrap();
1266        let err = block_on(server_config(
1267            CLIENT_CERT_PEM,
1268            CLIENT_KEY_ENC_PEM,
1269            None,
1270            None,
1271        ))
1272        .unwrap_err();
1273        assert!(err.to_string().contains("passphrase"), "{err}");
1274    }
1275
1276    /// An empty chain and a key of another certificate are each refused.
1277    #[test]
1278    fn a_server_config_refuses_bad_material() {
1279        let refused = |cert: &[u8], key: &[u8]| {
1280            block_on(server_config(cert, key, None, None))
1281                .unwrap_err()
1282                .to_string()
1283        };
1284        assert!(refused(b"", SERVER_KEY_PEM).contains("no certificate"));
1285        assert!(refused(SERVER_CERT_PEM, CLIENT_KEY_PEM).contains("rejected"));
1286    }
1287
1288    /// The DER bytes of the one certificate of `pem`.
1289    fn der(pem: &[u8]) -> CertificateDer<'static> {
1290        let mut certs = parse_certs(pem).unwrap();
1291        assert_eq!(certs.len(), 1);
1292        certs.remove(0)
1293    }
1294
1295    /// The verifier of the fixture CA accepts the fixture client certificate
1296    /// with no intermediate. It refuses a certificate that another CA
1297    /// signed, and a certificate of the CA with no `clientAuth` extended key
1298    /// usage.
1299    #[test]
1300    fn the_client_verifier_checks_the_ca_and_the_key_usage() {
1301        let verifier = client_cert_verifier(CA_PEM).unwrap();
1302        assert!(!verifier.client_auth_mandatory());
1303        verifier
1304            .verify_client_cert(&der(CLIENT_CERT_PEM), &[], UnixTime::now())
1305            .unwrap();
1306        let untrusted = include_bytes!("../../../tests/fixtures/tls/server-untrusted.pem");
1307        for pem in [&untrusted[..], SERVER_CERT_PEM] {
1308            assert!(
1309                verifier
1310                    .verify_client_cert(&der(pem), &[], UnixTime::now())
1311                    .is_err()
1312            );
1313        }
1314    }
1315
1316    /// A CA blob with no certificate and a blob that is not PEM are refused.
1317    #[test]
1318    fn the_client_verifier_refuses_a_bad_ca() {
1319        for pem in [
1320            &b""[..],
1321            b"no certificate here",
1322            b"-----BEGIN CERTIFICATE-----\n!\n",
1323        ] {
1324            let err = client_cert_verifier(pem).unwrap_err().to_string();
1325            assert!(
1326                err.contains("no certificate") || err.contains("certificate pem"),
1327                "{err}"
1328            );
1329        }
1330    }
1331}