use rustls::DigitallySignedStruct;
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::crypto::WebPkiSupportedAlgorithms;
use rustls::pki_types::{CertificateDer, ServerName, SubjectPublicKeyInfoDer, UnixTime};
use rustls::server::danger::{ClientCertVerified, ClientCertVerifier};
use rustls::{CertificateError, OtherError, PeerMisbehaved};
use std::sync::Arc;
use tokio_rustls::TlsAcceptor;
use x509_parser::x509::X509Version;
struct EndEntityKey {
version: X509Version,
spki: SubjectPublicKeyInfoDer<'static>,
}
fn end_entity_key(cert: &CertificateDer<'_>) -> Result<EndEntityKey, String> {
let (rest, parsed) =
x509_parser::parse_x509_certificate(cert.as_ref()).map_err(|e| e.to_string())?;
if !rest.is_empty() {
return Err(format!(
"{} trailing byte(s) after the certificate",
rest.len()
));
}
Ok(EndEntityKey {
version: parsed.tbs_certificate.version,
spki: SubjectPublicKeyInfoDer::from(parsed.tbs_certificate.subject_pki.raw.to_vec()),
})
}
fn v1_client_spki(cert: &CertificateDer<'_>) -> Option<SubjectPublicKeyInfoDer<'static>> {
match end_entity_key(cert) {
Ok(key) if key.version == X509Version::V1 => Some(key.spki),
_ => None,
}
}
fn signature_error(e: webpki::Error) -> rustls::Error {
match e {
webpki::Error::InvalidSignatureForPublicKey => CertificateError::BadSignature.into(),
webpki::Error::BadDer | webpki::Error::BadDerTime | webpki::Error::TrailingData(_) => {
CertificateError::BadEncoding.into()
}
webpki::Error::UnsupportedSignatureAlgorithmForPublicKeyContext(cx) => {
CertificateError::UnsupportedSignatureAlgorithmForPublicKeyContext {
signature_algorithm_id: cx.signature_algorithm_id,
public_key_algorithm_id: cx.public_key_algorithm_id,
}
.into()
}
other => CertificateError::Other(OtherError(Arc::new(other))).into(),
}
}
fn verify_tls12_signature_with_raw_key(
message: &[u8],
spki: &SubjectPublicKeyInfoDer<'_>,
dss: &DigitallySignedStruct,
supported: &WebPkiSupportedAlgorithms,
) -> Result<HandshakeSignatureValid, rustls::Error> {
let candidates = supported
.mapping
.iter()
.find(|(scheme, _)| *scheme == dss.scheme)
.map(|(_, algs)| *algs)
.ok_or(PeerMisbehaved::SignedHandshakeWithUnadvertisedSigScheme)?;
let key = webpki::RawPublicKeyEntity::try_from(spki).map_err(signature_error)?;
let mut unfit = None;
for alg in candidates {
match key.verify_signature(*alg, message, dss.signature()) {
Ok(()) => return Ok(HandshakeSignatureValid::assertion()),
Err(e @ webpki::Error::UnsupportedSignatureAlgorithmForPublicKeyContext(_)) => {
unfit = Some(e);
}
Err(e) => return Err(signature_error(e)),
}
}
Err(match unfit {
Some(e) => signature_error(e),
None => PeerMisbehaved::SignedHandshakeWithUnadvertisedSigScheme.into(),
})
}
#[derive(Debug)]
pub struct NoVerifier {
schemes: Vec<rustls::SignatureScheme>,
}
impl NoVerifier {
#[must_use]
pub fn new(provider: &rustls::crypto::CryptoProvider) -> Self {
Self {
schemes: provider
.signature_verification_algorithms
.supported_schemes(),
}
}
}
impl ServerCertVerifier for NoVerifier {
fn verify_server_cert(
&self,
_end_entity: &CertificateDer<'_>,
_intermediates: &[CertificateDer<'_>],
_server_name: &ServerName<'_>,
_ocsp_response: &[u8],
_now: UnixTime,
) -> Result<ServerCertVerified, rustls::Error> {
Ok(ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
_message: &[u8],
_cert: &CertificateDer<'_>,
_dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
Ok(HandshakeSignatureValid::assertion())
}
fn verify_tls13_signature(
&self,
_message: &[u8],
_cert: &CertificateDer<'_>,
_dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
Ok(HandshakeSignatureValid::assertion())
}
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
self.schemes.clone()
}
}
#[derive(Debug, Clone)]
pub enum ClientAuth {
Off,
RequireAny,
Verify { ca: Vec<CertificateDer<'static>> },
}
#[derive(Debug)]
pub struct AcceptAnyClientCert {
provider: Arc<rustls::crypto::CryptoProvider>,
}
impl AcceptAnyClientCert {
#[must_use]
pub fn new(provider: Arc<rustls::crypto::CryptoProvider>) -> Self {
Self { provider }
}
}
impl ClientCertVerifier for AcceptAnyClientCert {
fn root_hint_subjects(&self) -> &[rustls::DistinguishedName] {
&[]
}
fn verify_client_cert(
&self,
_end_entity: &CertificateDer<'_>,
_intermediates: &[CertificateDer<'_>],
_now: UnixTime,
) -> Result<ClientCertVerified, rustls::Error> {
Ok(ClientCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
let algs = &self.provider.signature_verification_algorithms;
match v1_client_spki(cert) {
Some(spki) => verify_tls12_signature_with_raw_key(message, &spki, dss, algs),
None => rustls::crypto::verify_tls12_signature(message, cert, dss, algs),
}
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
let algs = &self.provider.signature_verification_algorithms;
match v1_client_spki(cert) {
Some(spki) => {
rustls::crypto::verify_tls13_signature_with_raw_key(message, &spki, dss, algs)
}
None => rustls::crypto::verify_tls13_signature(message, cert, dss, algs),
}
}
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
self.provider
.signature_verification_algorithms
.supported_schemes()
}
fn offer_client_auth(&self) -> bool {
true
}
fn client_auth_mandatory(&self) -> bool {
true
}
}
#[must_use]
pub fn alpn_protocols(http1_only: bool) -> Vec<Vec<u8>> {
if http1_only {
vec![b"http/1.1".to_vec()]
} else {
vec![b"h2".to_vec(), b"http/1.1".to_vec()]
}
}
#[derive(Clone)]
pub struct TlsAcceptors {
pub negotiated: TlsAcceptor,
pub http1_only: TlsAcceptor,
}
impl TlsAcceptors {
#[must_use]
pub fn for_connection(&self, http1_only: bool) -> &TlsAcceptor {
if http1_only {
&self.http1_only
} else {
&self.negotiated
}
}
}
pub fn tls_server_config_from_pem(
cert_pem: &[u8],
key_pem: &[u8],
client_auth: &ClientAuth,
) -> Result<rustls::ServerConfig, anyhow::Error> {
let certs: Vec<CertificateDer> = rustls_pemfile::certs(&mut &cert_pem[..])
.collect::<Result<_, _>>()
.map_err(|e| anyhow::anyhow!("Failed to parse certificate PEM: {e}"))?;
if certs.is_empty() {
anyhow::bail!("No certificates found in certificate PEM");
}
let key = rustls_pemfile::private_key(&mut &key_pem[..])
.map_err(|e| anyhow::anyhow!("Failed to parse private key PEM: {e}"))?
.ok_or_else(|| anyhow::anyhow!("No private key found in key PEM"))?;
let provider = Arc::new(rustls::crypto::ring::default_provider());
let builder = rustls::ServerConfig::builder_with_provider(Arc::clone(&provider))
.with_safe_default_protocol_versions()
.map_err(|e| anyhow::anyhow!("Failed to build TLS configuration: {e}"))?;
let builder = match client_auth {
ClientAuth::Off => builder.with_no_client_auth(),
ClientAuth::RequireAny => builder
.with_client_cert_verifier(Arc::new(AcceptAnyClientCert::new(Arc::clone(&provider)))),
ClientAuth::Verify { ca } => {
let mut roots = rustls::RootCertStore::empty();
let (added, ignored) = roots.add_parsable_certificates(ca.iter().cloned());
if ignored > 0 {
anyhow::bail!(
"{ignored} of the supplied client-auth CA certificate(s) are unusable by rustls"
);
}
if added == 0 {
anyhow::bail!("no usable client-auth CA certificates were supplied");
}
let verifier = rustls::server::WebPkiClientVerifier::builder_with_provider(
Arc::new(roots),
Arc::clone(&provider),
)
.build()
.map_err(|e| anyhow::anyhow!("Failed to build the client-certificate verifier: {e}"))?;
builder.with_client_cert_verifier(verifier)
}
};
let certified = certified_key(certs, key, &provider)?;
let mut config =
builder.with_cert_resolver(Arc::new(rustls::sign::SingleCertAndKey::from(certified)));
configure_session_resumption(&mut config)?;
Ok(config)
}
pub(crate) fn certified_key(
certs: Vec<CertificateDer<'static>>,
key: rustls::pki_types::PrivateKeyDer<'static>,
provider: &rustls::crypto::CryptoProvider,
) -> Result<rustls::sign::CertifiedKey, anyhow::Error> {
let signing = provider
.key_provider
.load_private_key(key)
.map_err(|e| anyhow::anyhow!("Failed to load the TLS private key: {e}"))?;
let end_entity = certs
.first()
.ok_or_else(|| anyhow::anyhow!("No certificates found in certificate PEM"))?;
let cert_key = end_entity_key(end_entity)
.map_err(|e| anyhow::anyhow!("Failed to parse the TLS certificate: {e}"))?;
if let Some(key_spki) = signing.public_key()
&& key_spki != cert_key.spki
{
anyhow::bail!(
"Failed to build TLS configuration: the private key does not match the certificate's \
public key (cert/key mismatch)"
);
}
Ok(rustls::sign::CertifiedKey::new(certs, signing))
}
pub fn tls_acceptors_from_pem(
cert_pem: &[u8],
key_pem: &[u8],
client_auth: &ClientAuth,
) -> Result<TlsAcceptors, anyhow::Error> {
let config = tls_server_config_from_pem(cert_pem, key_pem, client_auth)?;
Ok(tls_acceptors_from_config(
config,
crate::util::http2_disabled(),
))
}
fn tls_acceptors_from_config(
config: rustls::ServerConfig,
process_http1_only: bool,
) -> TlsAcceptors {
let mut http1_only_config = config.clone();
http1_only_config.alpn_protocols = alpn_protocols(true);
let http1_only = TlsAcceptor::from(Arc::new(http1_only_config));
let negotiated = if process_http1_only {
http1_only.clone()
} else {
let mut negotiated_config = config;
negotiated_config.alpn_protocols = alpn_protocols(false);
TlsAcceptor::from(Arc::new(negotiated_config))
};
TlsAcceptors {
negotiated,
http1_only,
}
}
pub const TLS_SESSION_CACHE_SIZE: usize = 8192;
pub fn configure_session_resumption(
config: &mut rustls::ServerConfig,
) -> Result<(), anyhow::Error> {
config.session_storage = rustls::server::ServerSessionMemoryCache::new(TLS_SESSION_CACHE_SIZE);
config.ticketer = rustls::crypto::ring::Ticketer::new()
.map_err(|e| anyhow::anyhow!("Failed to build TLS session ticketer: {e}"))?;
Ok(())
}
pub fn generate_self_signed_acceptors(
client_auth: &ClientAuth,
) -> Result<TlsAcceptors, anyhow::Error> {
let cert =
rcgen::generate_simple_self_signed(vec!["localhost".to_string(), "127.0.0.1".to_string()])
.map_err(|e| anyhow::anyhow!("Failed to generate self-signed certificate: {e}"))?;
tls_acceptors_from_pem(
cert.cert.pem().as_bytes(),
cert.signing_key.serialize_pem().as_bytes(),
client_auth,
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_no_verifier_supported_schemes() {
let verifier = NoVerifier::new(&rustls::crypto::ring::default_provider());
let schemes = verifier.supported_verify_schemes();
assert!(!schemes.is_empty());
assert!(schemes.contains(&rustls::SignatureScheme::RSA_PKCS1_SHA256));
assert!(schemes.contains(&rustls::SignatureScheme::ECDSA_NISTP256_SHA256));
assert!(schemes.contains(&rustls::SignatureScheme::ED25519));
assert!(schemes.contains(&rustls::SignatureScheme::RSA_PSS_SHA256));
}
fn test_server_config() -> rustls::ServerConfig {
let cert = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
let certs = rustls_pemfile::certs(&mut cert.cert.pem().as_bytes())
.collect::<Result<Vec<_>, _>>()
.unwrap();
let key = rustls_pemfile::private_key(&mut cert.signing_key.serialize_pem().as_bytes())
.unwrap()
.unwrap();
rustls::ServerConfig::builder_with_provider(std::sync::Arc::new(
rustls::crypto::ring::default_provider(),
))
.with_safe_default_protocol_versions()
.expect("ring supports the default TLS versions")
.with_no_client_auth()
.with_single_cert(certs, key)
.unwrap()
}
const V1_CERT: &str = include_str!("testdata/x509-v1/server.crt");
const V1_KEY: &str = include_str!("testdata/x509-v1/server.key");
const OTHER_KEY: &str = include_str!("testdata/x509-v1/client.key");
#[test]
fn the_fixture_is_x509_v1() {
let der = rustls_pemfile::certs(&mut V1_CERT.as_bytes())
.next()
.expect("one cert")
.expect("pem");
assert_eq!(
end_entity_key(&der).expect("parses").version,
X509Version::V1
);
assert!(v1_client_spki(&der).is_some());
}
#[test]
fn a_v1_certificate_and_its_key_build_a_server_config() {
for auth in [ClientAuth::Off, ClientAuth::RequireAny] {
tls_server_config_from_pem(V1_CERT.as_bytes(), V1_KEY.as_bytes(), &auth)
.unwrap_or_else(|e| panic!("a v1 cert/key pair must be servable ({auth:?}): {e}"));
}
}
#[test]
fn a_v1_certificate_with_another_key_is_still_a_mismatch() {
let err =
tls_server_config_from_pem(V1_CERT.as_bytes(), OTHER_KEY.as_bytes(), &ClientAuth::Off)
.expect_err("the key-match check must survive reading the cert with x509-parser");
assert!(err.to_string().contains("does not match"), "{err}");
}
#[test]
fn a_v3_certificate_with_another_key_is_a_mismatch() {
let cert = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
let err = tls_server_config_from_pem(
cert.cert.pem().as_bytes(),
OTHER_KEY.as_bytes(),
&ClientAuth::Off,
)
.expect_err("a v3 cert with someone else's key");
assert!(err.to_string().contains("does not match"), "{err}");
}
#[test]
fn a_v3_client_certificate_keeps_rustls_own_signature_path() {
let cert = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
assert!(v1_client_spki(cert.cert.der()).is_none());
assert!(
v1_client_spki(&CertificateDer::from(vec![0x30, 0x03, 0x02, 0x01, 0x00])).is_none()
);
}
#[test]
fn trailing_bytes_after_a_certificate_are_refused() {
let mut der = rustls_pemfile::certs(&mut V1_CERT.as_bytes())
.next()
.expect("one cert")
.expect("pem")
.to_vec();
der.push(0);
let err = end_entity_key(&CertificateDer::from(der))
.err()
.expect("trailing data");
assert!(err.contains("trailing"), "{err}");
}
#[test]
fn session_resumption_installs_ticketer_and_survives_default() {
let mut config = test_server_config();
assert!(
!config.ticketer.enabled(),
"the rustls default must not issue tickets (else this test proves nothing)"
);
assert!(
config.send_tls13_tickets > 0,
"rustls still asks for N>0 tickets by default"
);
configure_session_resumption(&mut config).expect("ticketer builds under the ring provider");
assert!(
config.ticketer.enabled(),
"after configuration the TLS 1.3 ticketer must be enabled for stateless resumption"
);
}
#[test]
fn https_acceptor_builds_with_resumption() {
assert!(generate_self_signed_acceptors(&ClientAuth::Off).is_ok());
}
fn self_signed_config() -> rustls::ServerConfig {
let cert = rcgen::generate_simple_self_signed(vec!["localhost".to_string()])
.expect("self-signed cert");
tls_server_config_from_pem(
cert.cert.pem().as_bytes(),
cert.signing_key.serialize_pem().as_bytes(),
&ClientAuth::Off,
)
.expect("server config")
}
#[test]
fn the_two_acceptors_share_one_session_cache_and_ticketer() {
let acceptors = tls_acceptors_from_config(self_signed_config(), false);
let negotiated = acceptors.negotiated.config();
let http1_only = acceptors.http1_only.config();
assert!(
Arc::ptr_eq(&negotiated.session_storage, &http1_only.session_storage),
"both acceptors must share ONE session cache, or resumption breaks across a stub change"
);
assert!(
Arc::ptr_eq(&negotiated.ticketer, &http1_only.ticketer),
"and one ticketer, for the same reason"
);
}
#[test]
fn the_pair_differs_only_in_its_alpn_offer() {
let acceptors = tls_acceptors_from_config(self_signed_config(), false);
assert_eq!(
acceptors.negotiated.config().alpn_protocols,
alpn_protocols(false),
"the negotiated half offers h2 first"
);
assert_eq!(
acceptors.http1_only.config().alpn_protocols,
alpn_protocols(true),
"the http1-only half offers http/1.1 alone"
);
}
#[test]
fn the_kill_switch_collapses_both_halves_to_http1_only() {
let acceptors = tls_acceptors_from_config(self_signed_config(), true);
assert_eq!(
acceptors.negotiated.config().alpn_protocols,
alpn_protocols(true),
"with the kill switch on, even the `negotiated` half must not offer h2 — otherwise the \
switch removes h2 from what is SERVED while still advertising it, which is the exact \
mismatch this issue is about"
);
assert_eq!(
acceptors.http1_only.config().alpn_protocols,
alpn_protocols(true)
);
}
#[test]
fn alpn_offers_h2_unless_http1_only() {
assert_eq!(
alpn_protocols(false),
vec![b"h2".to_vec(), b"http/1.1".to_vec()],
"h2 must be offered first, matching the intercept listener's order (#996)"
);
assert_eq!(
alpn_protocols(true),
vec![b"http/1.1".to_vec()],
"an HTTP/1-only decision must stop h2 being ADVERTISED, not merely stop it being \
served: a client that negotiated h2 from ALPN and then met an HTTP/1-only server \
would break outright, which is worse than the downgrade this exists to force"
);
}
}