use alloc::sync::Arc;
use core::fmt;
use pki_types::{CertificateDer, SignatureVerificationAlgorithm, UnixTime};
use super::anchors::RootCertStore;
use super::client_verifier_builder::ClientCertVerifierBuilder;
use super::pki_error;
use crate::client::ServerName;
use crate::enums::SignatureScheme;
use crate::error::{CertRevocationListError, CertificateError, Error, PeerMisbehaved};
#[cfg(feature = "logging")]
use crate::log::trace;
use crate::msgs::handshake::DistinguishedName;
use crate::verify::{
ClientCertVerified, ClientCertVerifier, DigitallySignedStruct, HandshakeSignatureValid,
NoClientAuth, ServerCertVerified, ServerCertVerifier,
};
#[allow(dead_code)]
pub fn verify_server_cert_signed_by_trust_anchor(
cert: &ParsedCertificate,
roots: &RootCertStore,
intermediates: &[CertificateDer<'_>],
now: UnixTime,
supported_algs: &[&dyn SignatureVerificationAlgorithm],
) -> Result<(), Error> {
cert.0
.verify_for_usage(
supported_algs,
&roots.roots,
intermediates,
now,
webpki::KeyUsage::server_auth(),
None, )
.map_err(pki_error)
.map(|_| ())
}
pub fn verify_server_name(cert: &ParsedCertificate, server_name: &ServerName) -> Result<(), Error> {
match server_name {
ServerName::DnsName(dns_name) => {
let dns_name = webpki::DnsNameRef::try_from_ascii_str(dns_name.as_ref())
.map_err(|_| Error::InvalidCertificate(CertificateError::BadEncoding))?;
let name = webpki::SubjectNameRef::DnsName(dns_name);
cert.0
.verify_is_valid_for_subject_name(name)
.map_err(pki_error)?;
}
ServerName::IpAddress(ip_addr) => {
let ip_addr = webpki::IpAddr::from(*ip_addr);
cert.0
.verify_is_valid_for_subject_name(webpki::SubjectNameRef::IpAddress(
webpki::IpAddrRef::from(&ip_addr),
))
.map_err(pki_error)?;
}
}
Ok(())
}
impl ServerCertVerifier for WebPkiServerVerifier {
fn verify_server_cert(
&self,
end_entity: &CertificateDer<'_>,
intermediates: &[CertificateDer<'_>],
server_name: &ServerName,
ocsp_response: &[u8],
now: UnixTime,
) -> Result<ServerCertVerified, Error> {
let cert = ParsedCertificate::try_from(end_entity)?;
verify_server_cert_signed_by_trust_anchor(
&cert,
&self.roots,
intermediates,
now,
self.supported.all,
)?;
if !ocsp_response.is_empty() {
trace!("Unvalidated OCSP response: {:?}", ocsp_response.to_vec());
}
verify_server_name(&cert, server_name)?;
Ok(ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, Error> {
verify_signed_struct(message, cert, dss, &self.supported)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, Error> {
verify_tls13(message, cert, dss, &self.supported)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.supported.supported_schemes()
}
}
#[allow(unreachable_pub)]
pub struct WebPkiServerVerifier {
roots: Arc<RootCertStore>,
supported: WebPkiSupportedAlgorithms,
}
#[allow(unreachable_pub)]
impl WebPkiServerVerifier {
#[cfg(feature = "ring")]
pub fn new(roots: impl Into<Arc<RootCertStore>>) -> Self {
Self::new_with_algorithms(roots, SUPPORTED_SIG_ALGS)
}
pub fn new_with_algorithms(
roots: impl Into<Arc<RootCertStore>>,
supported: WebPkiSupportedAlgorithms,
) -> Self {
Self {
roots: roots.into(),
supported,
}
}
#[cfg(feature = "ring")]
pub fn default_verify_tls12_signature(
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, Error> {
verify_signed_struct(message, cert, dss, &SUPPORTED_SIG_ALGS)
}
#[cfg(feature = "ring")]
pub fn default_verify_tls13_signature(
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, Error> {
verify_tls13(message, cert, dss, &SUPPORTED_SIG_ALGS)
}
#[cfg(feature = "ring")]
pub fn default_supported_verify_schemes() -> Vec<SignatureScheme> {
SUPPORTED_SIG_ALGS.supported_schemes()
}
}
pub struct WebPkiClientVerifier {
roots: Arc<RootCertStore>,
subjects: Vec<DistinguishedName>,
crls: Vec<webpki::OwnedCertRevocationList>,
anonymous_policy: AnonymousClientPolicy,
supported_algs: WebPkiSupportedAlgorithms,
}
impl WebPkiClientVerifier {
pub fn builder(roots: Arc<RootCertStore>) -> ClientCertVerifierBuilder {
ClientCertVerifierBuilder::new(roots)
}
pub fn no_client_auth() -> Arc<dyn ClientCertVerifier> {
Arc::new(NoClientAuth {})
}
pub(crate) fn new(
roots: Arc<RootCertStore>,
crls: Vec<webpki::OwnedCertRevocationList>,
anonymous_policy: AnonymousClientPolicy,
supported_algs: WebPkiSupportedAlgorithms,
) -> Self {
Self {
subjects: roots
.roots
.iter()
.map(|ta| DistinguishedName::in_sequence(ta.subject.as_ref()))
.collect(),
crls,
roots,
anonymous_policy,
supported_algs,
}
}
}
impl ClientCertVerifier for WebPkiClientVerifier {
fn offer_client_auth(&self) -> bool {
true
}
fn client_auth_mandatory(&self) -> bool {
match self.anonymous_policy {
AnonymousClientPolicy::Allow => false,
AnonymousClientPolicy::Deny => true,
}
}
fn client_auth_root_subjects(&self) -> &[DistinguishedName] {
&self.subjects
}
fn verify_client_cert(
&self,
end_entity: &CertificateDer<'_>,
intermediates: &[CertificateDer<'_>],
now: UnixTime,
) -> Result<ClientCertVerified, Error> {
let cert = ParsedCertificate::try_from(end_entity)?;
#[allow(trivial_casts)] let crls = self
.crls
.iter()
.map(|crl| crl as &dyn webpki::CertRevocationList)
.collect::<Vec<_>>();
let revocation = if crls.is_empty() {
None
} else {
Some(
webpki::RevocationOptionsBuilder::new(&crls)
.expect("invalid crls")
.allow_unknown_status()
.build(),
)
};
cert.0
.verify_for_usage(
self.supported_algs.all,
&self.roots.roots,
intermediates,
now,
webpki::KeyUsage::client_auth(),
revocation,
)
.map_err(pki_error)
.map(|_| ClientCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, Error> {
verify_signed_struct(message, cert, dss, &self.supported_algs)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, Error> {
verify_tls13(message, cert, dss, &self.supported_algs)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.supported_algs.supported_schemes()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AnonymousClientPolicy {
Allow,
Deny,
}
impl From<webpki::Error> for CertRevocationListError {
fn from(e: webpki::Error) -> Self {
use webpki::Error::*;
match e {
InvalidCrlSignatureForPublicKey
| UnsupportedCrlSignatureAlgorithm
| UnsupportedCrlSignatureAlgorithmForPublicKey => Self::BadSignature,
InvalidCrlNumber => Self::InvalidCrlNumber,
InvalidSerialNumber => Self::InvalidRevokedCertSerialNumber,
IssuerNotCrlSigner => Self::IssuerInvalidForCrl,
MalformedExtensions | BadDer | BadDerTime => Self::ParseError,
UnsupportedCriticalExtension => Self::UnsupportedCriticalExtension,
UnsupportedCrlVersion => Self::UnsupportedCrlVersion,
UnsupportedDeltaCrl => Self::UnsupportedDeltaCrl,
UnsupportedIndirectCrl => Self::UnsupportedIndirectCrl,
UnsupportedRevocationReason => Self::UnsupportedRevocationReason,
_ => Self::Other(Arc::new(e)),
}
}
}
#[derive(Clone, Copy)]
#[allow(unreachable_pub)]
pub struct WebPkiSupportedAlgorithms {
pub all: &'static [&'static dyn SignatureVerificationAlgorithm],
pub mapping: &'static [(
SignatureScheme,
&'static [&'static dyn SignatureVerificationAlgorithm],
)],
}
impl fmt::Debug for WebPkiSupportedAlgorithms {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "WebPkiSupportedAlgorithms {{ all: [ .. ], mapping: ")?;
f.debug_list()
.entries(self.mapping.iter().map(|item| item.0))
.finish()?;
write!(f, " }}")
}
}
impl WebPkiSupportedAlgorithms {
fn supported_schemes(&self) -> Vec<SignatureScheme> {
self.mapping
.iter()
.map(|item| item.0)
.collect()
}
fn convert_scheme(
&self,
scheme: SignatureScheme,
) -> Result<&[&'static dyn SignatureVerificationAlgorithm], Error> {
self.mapping
.iter()
.filter_map(|item| if item.0 == scheme { Some(item.1) } else { None })
.next()
.ok_or_else(|| PeerMisbehaved::SignedHandshakeWithUnadvertisedSigScheme.into())
}
}
#[cfg(feature = "ring")]
pub(crate) static SUPPORTED_SIG_ALGS: WebPkiSupportedAlgorithms = WebPkiSupportedAlgorithms {
all: &[
webpki::ECDSA_P256_SHA256,
webpki::ECDSA_P256_SHA384,
webpki::ECDSA_P384_SHA256,
webpki::ECDSA_P384_SHA384,
webpki::ED25519,
webpki::RSA_PSS_2048_8192_SHA256_LEGACY_KEY,
webpki::RSA_PSS_2048_8192_SHA384_LEGACY_KEY,
webpki::RSA_PSS_2048_8192_SHA512_LEGACY_KEY,
webpki::RSA_PKCS1_2048_8192_SHA256,
webpki::RSA_PKCS1_2048_8192_SHA384,
webpki::RSA_PKCS1_2048_8192_SHA512,
webpki::RSA_PKCS1_3072_8192_SHA384,
],
mapping: &[
(
SignatureScheme::ECDSA_NISTP384_SHA384,
&[webpki::ECDSA_P384_SHA384, webpki::ECDSA_P256_SHA384],
),
(
SignatureScheme::ECDSA_NISTP256_SHA256,
&[webpki::ECDSA_P256_SHA256, webpki::ECDSA_P384_SHA256],
),
(SignatureScheme::ED25519, &[webpki::ED25519]),
(
SignatureScheme::RSA_PSS_SHA512,
&[webpki::RSA_PSS_2048_8192_SHA512_LEGACY_KEY],
),
(
SignatureScheme::RSA_PSS_SHA384,
&[webpki::RSA_PSS_2048_8192_SHA384_LEGACY_KEY],
),
(
SignatureScheme::RSA_PSS_SHA256,
&[webpki::RSA_PSS_2048_8192_SHA256_LEGACY_KEY],
),
(
SignatureScheme::RSA_PKCS1_SHA512,
&[webpki::RSA_PKCS1_2048_8192_SHA512],
),
(
SignatureScheme::RSA_PKCS1_SHA384,
&[webpki::RSA_PKCS1_2048_8192_SHA384],
),
(
SignatureScheme::RSA_PKCS1_SHA256,
&[webpki::RSA_PKCS1_2048_8192_SHA256],
),
],
};
fn verify_sig_using_any_alg(
cert: &webpki::EndEntityCert,
algs: &[&'static dyn SignatureVerificationAlgorithm],
message: &[u8],
sig: &[u8],
) -> Result<(), webpki::Error> {
for alg in algs {
match cert.verify_signature(*alg, message, sig) {
Err(webpki::Error::UnsupportedSignatureAlgorithmForPublicKey) => continue,
res => return res,
}
}
Err(webpki::Error::UnsupportedSignatureAlgorithmForPublicKey)
}
fn verify_signed_struct(
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
supported_schemes: &WebPkiSupportedAlgorithms,
) -> Result<HandshakeSignatureValid, Error> {
let possible_algs = supported_schemes.convert_scheme(dss.scheme)?;
let cert = webpki::EndEntityCert::try_from(cert).map_err(pki_error)?;
verify_sig_using_any_alg(&cert, possible_algs, message, dss.signature())
.map_err(pki_error)
.map(|_| HandshakeSignatureValid::assertion())
}
fn verify_tls13(
msg: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
supported_schemes: &WebPkiSupportedAlgorithms,
) -> Result<HandshakeSignatureValid, Error> {
if !dss.scheme.supported_in_tls13() {
return Err(PeerMisbehaved::SignedHandshakeWithUnadvertisedSigScheme.into());
}
let alg = supported_schemes.convert_scheme(dss.scheme)?[0];
let cert = webpki::EndEntityCert::try_from(cert).map_err(pki_error)?;
cert.verify_signature(alg, msg, dss.signature())
.map_err(pki_error)
.map(|_| HandshakeSignatureValid::assertion())
}
pub struct ParsedCertificate<'a>(pub(crate) webpki::EndEntityCert<'a>);
impl<'a> TryFrom<&'a CertificateDer<'a>> for ParsedCertificate<'a> {
type Error = Error;
fn try_from(value: &'a CertificateDer<'a>) -> Result<ParsedCertificate<'a>, Self::Error> {
webpki::EndEntityCert::try_from(value)
.map_err(pki_error)
.map(ParsedCertificate)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pki_crl_errors() {
assert_eq!(
pki_error(webpki::Error::InvalidCrlSignatureForPublicKey),
Error::InvalidCertRevocationList(CertRevocationListError::BadSignature),
);
assert_eq!(
pki_error(webpki::Error::UnsupportedCrlSignatureAlgorithm),
Error::InvalidCertRevocationList(CertRevocationListError::BadSignature),
);
assert_eq!(
pki_error(webpki::Error::UnsupportedCrlSignatureAlgorithmForPublicKey),
Error::InvalidCertRevocationList(CertRevocationListError::BadSignature),
);
assert_eq!(
pki_error(webpki::Error::CertRevoked),
Error::InvalidCertificate(CertificateError::Revoked),
);
assert_eq!(
pki_error(webpki::Error::IssuerNotCrlSigner),
Error::InvalidCertRevocationList(CertRevocationListError::IssuerInvalidForCrl)
);
}
#[test]
fn crl_error_from_webpki() {
use crate::CertRevocationListError::*;
let testcases = &[
(webpki::Error::InvalidCrlSignatureForPublicKey, BadSignature),
(
webpki::Error::UnsupportedCrlSignatureAlgorithm,
BadSignature,
),
(
webpki::Error::UnsupportedCrlSignatureAlgorithmForPublicKey,
BadSignature,
),
(webpki::Error::InvalidCrlNumber, InvalidCrlNumber),
(
webpki::Error::InvalidSerialNumber,
InvalidRevokedCertSerialNumber,
),
(webpki::Error::IssuerNotCrlSigner, IssuerInvalidForCrl),
(webpki::Error::MalformedExtensions, ParseError),
(webpki::Error::BadDer, ParseError),
(webpki::Error::BadDerTime, ParseError),
(
webpki::Error::UnsupportedCriticalExtension,
UnsupportedCriticalExtension,
),
(webpki::Error::UnsupportedCrlVersion, UnsupportedCrlVersion),
(webpki::Error::UnsupportedDeltaCrl, UnsupportedDeltaCrl),
(
webpki::Error::UnsupportedIndirectCrl,
UnsupportedIndirectCrl,
),
(
webpki::Error::UnsupportedRevocationReason,
UnsupportedRevocationReason,
),
];
for t in testcases {
assert_eq!(
<webpki::Error as Into<CertRevocationListError>>::into(t.0),
t.1
);
}
assert!(matches!(
<webpki::Error as Into<CertRevocationListError>>::into(
webpki::Error::NameConstraintViolation
),
Other(_)
));
}
#[test]
fn certificate_debug() {
assert_eq!(
"CertificateDer(Der([97, 98]))",
format!("{:?}", CertificateDer::from(b"ab".to_vec()))
);
}
#[cfg(feature = "ring")]
#[test]
fn webpki_supported_algorithms_is_debug() {
assert_eq!(
"WebPkiSupportedAlgorithms { all: [ .. ], mapping: [ECDSA_NISTP384_SHA384, ECDSA_NISTP256_SHA256, ED25519, RSA_PSS_SHA512, RSA_PSS_SHA384, RSA_PSS_SHA256, RSA_PKCS1_SHA512, RSA_PKCS1_SHA384, RSA_PKCS1_SHA256] }",
format!("{:?}", SUPPORTED_SIG_ALGS)
);
}
}