Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs

This commit is contained in:
2026-09-15 10:41:00 -06:00
parent 6dc77e8eb0
commit a2b65bb47f
16427 changed files with 6972976 additions and 3 deletions
+250
View File
@@ -0,0 +1,250 @@
//! On Android, initialization must be done before any verification is attempted.
//!
//! <div class="warning">
//! Some manual setup is required outside of cargo to use this crate on Android. In order to use
//! Android’s certificate verifier, the crate needs to call into the JVM. A small Kotlin component
//! must be included in your app’s build to support rustls-platform-verifier.
//!
//! See the [crate's Android section][crate#android] for more details.
//! </div>
//!
//! # Examples
//!
//! ```
//! // A typical entrypoint signature for obtaining the necessary pointers
//! pub fn android_init(raw_env: *mut c_void, raw_context: *mut c_void) -> Result<(), jni::errors::Error> {
//! let mut env = unsafe { JNIEnv::from_raw(raw_env as *mut jni::sys::JNIEnv).unwrap() };
//! let context = unsafe { JObject::from_raw(raw_context as jni::sys::jobject) };
//! rustls_platform_verifier::android::init_with_env(&mut env, context)?;
//! }
//! ```
use jni::errors::Error as JNIError;
use jni::objects::{Global, JClass, JClassLoader, JObject};
use jni::strings::JNIStr;
use jni::{jni_sig, jni_str, Env, JavaVM};
use once_cell::sync::OnceCell;
static GLOBAL: OnceCell<GlobalStorage> = OnceCell::new();
/// A layer to access the Android runtime which is hosting the current
/// application process.
///
/// Generally this trait should be implemented in your Rust app component's FFI
/// initialization layer.
pub trait Runtime: Send + Sync {
/// Returns a handle to the current process' JVM.
fn java_vm(&self) -> &JavaVM;
/// Returns a reference to the current app's [Context].
///
/// [Context]: <https://developer.android.com/reference/android/content/Context>
fn context(&self) -> &Global<JObject<'static>>;
/// Returns a reference to the class returned by the current JVM's `getClassLoader` call.
fn class_loader(&self) -> &Global<JClassLoader<'static>>;
}
enum GlobalStorage {
Internal {
java_vm: JavaVM,
context: Global<JObject<'static>>,
loader: Global<JClassLoader<'static>>,
},
External(&'static dyn Runtime),
}
impl GlobalStorage {
fn vm(&self) -> &JavaVM {
match self {
GlobalStorage::Internal { java_vm, .. } => java_vm,
GlobalStorage::External(runtime) => runtime.java_vm(),
}
}
fn context(&self, env: &mut Env) -> Result<GlobalContext, Error> {
let context = match self {
Self::Internal { context, .. } => context,
Self::External(global) => global.context(),
};
let loader = match self {
Self::Internal { loader, .. } => loader,
Self::External(global) => global.class_loader(),
};
Ok(GlobalContext {
context: env.new_global_ref(context)?,
loader: env.new_global_ref(loader)?,
})
}
}
pub(super) struct GlobalContext {
/// The Android application [Context](https://developer.android.com/reference/android/app/Application).
pub(super) context: Global<JObject<'static>>,
loader: Global<JClassLoader<'static>>,
}
fn global() -> &'static GlobalStorage {
GLOBAL
.get()
.expect("Expect rustls-platform-verifier to be initialized")
}
/// Initialize given a typical Android NDK [`Env`] and [`JObject`] context.
///
/// This method will setup and store an environment locally. This is useful if nothing else in your
/// application needs to access the Android runtime.
pub fn init_with_env(env: &mut Env, context: JObject) -> Result<(), JNIError> {
GLOBAL.get_or_try_init(|| -> Result<_, JNIError> {
let loader = env
.call_method(
&context,
jni_str!("getClassLoader"),
jni_sig!(() -> JClassLoader),
&[],
)?
.l()?;
let loader = env.cast_local::<JClassLoader>(loader)?;
Ok(GlobalStorage::Internal {
java_vm: env.get_java_vm()?,
context: env.new_global_ref(context)?,
loader: env.new_global_ref(loader)?,
})
})?;
Ok(())
}
/// Initialize with a runtime that can dynamically serve references to
/// the JVM, context, and class loader.
///
/// This is the most flexible option, and is useful for advanced use cases.
///
/// This function will never panic.
pub fn init_with_runtime(runtime: &'static dyn Runtime) {
GLOBAL.get_or_init(|| GlobalStorage::External(runtime));
}
/// Initialize with references to the JVM, context, and class loader.
///
/// This is useful when you're already interacting with `jni-rs` wrapped objects and want to use
/// global references to objects for efficiency.
///
/// This function will never panic.
///
/// # Examples
///
/// ```
/// pub fn android_init(raw_env: *mut c_void, raw_context: *mut c_void) -> Result<(), jni::errors::Error> {
/// let mut env = unsafe { jni::EnvUnowned::from_raw(raw_env as *mut jni::sys::JNIEnv).unwrap() };
/// let context = unsafe { JObject::from_raw(raw_context as jni::sys::jobject) };
/// let loader = env.get_object_class(&context)?.get_class_loader(env)?;
///
/// env.with_env(|env| {
/// rustls_platform_verifier::android::init_with_refs(
/// env.get_java_vm(),
/// env.new_global_ref(context)?,
/// env.new_global_ref(loader)?,
/// );
/// });
/// }
/// ```
pub fn init_with_refs(
java_vm: JavaVM,
context: Global<JObject<'static>>,
loader: Global<JClassLoader<'static>>,
) {
GLOBAL.get_or_init(|| GlobalStorage::Internal {
java_vm,
context,
loader,
});
}
/// Wrapper for JNI errors that will log and clear exceptions
/// It should generally be preferred to `jni::errors::Error`
#[derive(Debug)]
pub(super) struct Error;
impl From<JNIError> for Error {
#[track_caller]
fn from(cause: JNIError) -> Self {
if let JNIError::JavaException = cause {
let _ = global()
.vm()
.with_top_local_frame(|env| -> Result<(), JNIError> {
env.exception_describe();
env.exception_clear();
Ok(())
});
}
Self
}
}
pub(super) struct LocalContext<'a, 'env> {
pub(super) env: &'a mut Env<'env>,
pub(super) global: GlobalContext,
}
impl<'env> LocalContext<'_, 'env> {
/// Load a class from the application class loader
///
/// This should be used instead of `JNIEnv::find_class` to ensure all classes
/// in the application can be found.
fn load_class(&mut self, name: &'static JNIStr) -> Result<JClass<'env>, Error> {
let name = self.env.new_string(name.to_str())?;
self.global
.loader
.load_class(self.env, name)
.map_err(Error::from)
}
}
/// Borrow the Android application context and execute the closure
/// `with_context, ensuring locals are properly freed and exceptions
/// are cleared.
pub(super) fn with_context<F, T: 'static>(f: F) -> Result<T, Error>
where
F: FnOnce(&mut LocalContext) -> Result<T, Error>,
{
let global = global();
// Use `attach_current_thread_for_scope()` to avoid permanently attaching any threads.
// See https://github.com/rustls/rustls-platform-verifier/pull/185.
global.vm().attach_current_thread_for_scope(|env| {
let global_context = global.context(env)?;
let mut context = LocalContext {
env,
global: global_context,
};
f(&mut context)
})
}
/// Loads and caches a class on first use
pub(super) struct CachedClass {
name: &'static JNIStr,
class: OnceCell<Global<JClass<'static>>>,
}
impl CachedClass {
/// Creates a lazily initialized class reference to the class with `name`.
pub(super) const fn new(name: &'static JNIStr) -> Self {
Self {
name,
class: OnceCell::new(),
}
}
/// Gets the cached class reference, loaded on first use
pub(super) fn get(&self, cx: &mut LocalContext) -> Result<&JClass<'static>, Error> {
let class = self.class.get_or_try_init(|| -> Result<_, Error> {
let class = cx.load_class(self.name)?;
Ok(cx.env.new_global_ref(class)?)
})?;
Ok(class)
}
}
+92
View File
@@ -0,0 +1,92 @@
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]
use std::sync::Arc;
#[cfg(feature = "dbg")]
use rustls::crypto::CryptoProvider;
#[cfg(feature = "dbg")]
use rustls::pki_types::CertificateDer;
use rustls::{client::WantsClientCert, ClientConfig, ConfigBuilder, WantsVerifier};
mod verification;
pub use verification::Verifier;
// Build the Android module when generating docs so that
// the Android-specific functions are included regardless of
// the host.
#[cfg(any(all(doc, docsrs), target_os = "android"))]
#[cfg_attr(docsrs, doc(cfg(target_os = "android")))]
pub mod android;
/// Fixures and data to support testing the server
/// certificate verifier.
#[cfg(any(test, feature = "ffi-testing"))]
mod tests;
// Re-export any exported functions that are required for
// tests to run in a platform-native environment.
#[cfg(feature = "ffi-testing")]
#[cfg_attr(feature = "ffi-testing", allow(unused_imports))]
pub use tests::ffi::*;
/// Exposed for debugging certificate issues with standalone tools.
///
/// This is not intended for production use, you should use [`BuilderVerifierExt`] or
/// [`ConfigVerifierExt`] instead.
#[cfg(feature = "dbg")]
pub fn verifier_for_dbg(
root: CertificateDer<'static>,
crypto_provider: Arc<CryptoProvider>,
) -> Arc<dyn rustls::client::danger::ServerCertVerifier> {
Arc::new(Verifier::new_with_fake_root(root, crypto_provider))
}
/// Extension trait to help configure [`ClientConfig`]s with the platform verifier.
pub trait BuilderVerifierExt {
/// Configures the `ClientConfig` with the platform verifier.
///
/// ```rust
/// use rustls::ClientConfig;
/// use rustls_platform_verifier::BuilderVerifierExt;
/// let config = ClientConfig::builder()
/// .with_platform_verifier()
/// .unwrap()
/// .with_no_client_auth();
/// ```
fn with_platform_verifier(
self,
) -> Result<ConfigBuilder<ClientConfig, WantsClientCert>, rustls::Error>;
}
impl BuilderVerifierExt for ConfigBuilder<ClientConfig, WantsVerifier> {
fn with_platform_verifier(
self,
) -> Result<ConfigBuilder<ClientConfig, WantsClientCert>, rustls::Error> {
let verifier = Verifier::new(self.crypto_provider().clone())?;
Ok(self
.dangerous()
.with_custom_certificate_verifier(Arc::new(verifier)))
}
}
/// Extension trait to help build a [`ClientConfig`] with the platform verifier.
pub trait ConfigVerifierExt {
/// Build a [`ClientConfig`] with the platform verifier and the default `CryptoProvider`.
///
/// ```rust
/// use rustls::ClientConfig;
/// use rustls_platform_verifier::ConfigVerifierExt;
/// let config = ClientConfig::with_platform_verifier();
/// ```
fn with_platform_verifier() -> Result<ClientConfig, rustls::Error>;
}
impl ConfigVerifierExt for ClientConfig {
fn with_platform_verifier() -> Result<ClientConfig, rustls::Error> {
Ok(ClientConfig::builder()
.with_platform_verifier()?
.with_no_client_auth())
}
}
+142
View File
@@ -0,0 +1,142 @@
//! Thin wrappers ontop the existing test suites that allow them to be ran
//! in the context of a platform-native environment as required by the verifier implementation.
#![allow(missing_docs)]
#[cfg(target_os = "android")]
pub use android::*;
#[cfg(target_os = "android")]
mod android {
//! Tests which run inside the context of a Android device, typically an emulator.
//!
//! Note: These tests run inside the same application context, so they share the same mock test
//! store. This will remain non-problematic as long as roots are different enough (for the use case) and
//! real roots are never removed from the store.
//!
//! It is intentional that the tests run sequentially, as dropping a `Verifier` will reset its mock
//! root store.
use crate::tests;
use jni::{
objects::{JClass, JObject, JString},
sys::jstring,
EnvUnowned, Outcome,
};
use std::sync::Once;
static ANDROID_INIT: Once = Once::new();
/// A marker that the Kotlin test runner looks for to determine
/// if a set of integration tests passed or not.
const SUCCESS_MARKER: &str = "success";
fn run_android_test<'caller>(
env: &mut EnvUnowned<'caller>,
cx: JObject,
suite_name: &'static str,
test_cases: &'static [fn()],
) -> JString<'caller> {
let outcome = env
.with_env(|env| {
// These can't fail, and even if they did, Android will crash the process like we want.
ANDROID_INIT.call_once(|| {
let log_filter = android_logger::FilterBuilder::new()
.parse("trace")
.filter_module("jni", log::LevelFilter::Off)
.build();
android_logger::init_once(
android_logger::Config::default()
.with_max_level(log::Level::Trace.to_level_filter())
.with_filter(log_filter),
);
crate::android::init_with_env(env, cx).unwrap();
});
for test in test_cases {
test();
}
env.new_string(SUCCESS_MARKER)
})
.into_outcome();
match outcome {
Outcome::Ok(success) => success,
Outcome::Err(_) | Outcome::Panic(_) => {
panic!("failed to run test suite '{suite_name}'")
}
}
}
#[export_name = "Java_org_rustls_platformverifier_CertificateVerifierTests_mockTests"]
pub extern "C" fn rustls_platform_verifier_mock_test_suite(
mut env: EnvUnowned<'_>,
_class: JClass,
cx: JObject,
) -> jstring {
log::info!("running mock test suite...");
run_android_test(
&mut env,
cx,
"mock tests",
tests::verification_mock::ALL_TEST_CASES,
)
.into_raw()
}
#[export_name = "Java_org_rustls_platformverifier_CertificateVerifierTests_verifyMockRootUsage"]
pub extern "C" fn rustls_platform_verifier_verify_mock_root_usage(
mut env: EnvUnowned<'_>,
_class: JClass,
cx: JObject,
) -> jstring {
log::info!("verifying mock roots are not used by default...");
run_android_test(
&mut env,
cx,
"mock root verification",
&[tests::verification_mock::verification_without_mock_root],
)
.into_raw()
}
#[export_name = "Java_org_rustls_platformverifier_CertificateVerifierTests_realWorldTests"]
pub extern "C" fn rustls_platform_verifier_real_world_test_suite(
mut env: EnvUnowned<'_>,
_class: JClass,
cx: JObject,
) -> jstring {
log::info!("running real world suite...");
run_android_test(
&mut env,
cx,
"real world",
tests::verification_real_world::ALL_TEST_CASES,
)
.into_raw()
}
}
#[cfg(not(target_os = "android"))]
mod dummy {
//! A module to prevent dead-code warnings all over
//! the `tests` module due to the weird combination of
//! feature flags and `--all-features`. These test case
//! lists are only used via the FFI.
use crate::tests;
#[allow(dead_code)]
fn dummy() {
#[cfg(any(
windows,
target_os = "android",
target_vendor = "apple",
target_os = "linux"
))]
let _ = tests::verification_mock::ALL_TEST_CASES;
let _ = tests::verification_real_world::ALL_TEST_CASES;
}
}
+71
View File
@@ -0,0 +1,71 @@
#[cfg(feature = "ffi-testing")]
pub mod ffi;
use std::time::Duration;
use std::{error::Error as StdError, sync::Arc};
mod verification_real_world;
mod verification_mock;
use rustls::{
crypto::CryptoProvider,
pki_types, CertificateError,
Error::{self as TlsError, InvalidCertificate},
};
struct TestCase<'a, E: StdError> {
/// The name of the server we're connecting to.
pub reference_id: &'a str,
/// The certificates presented by the TLS server, in the same order.
pub chain: &'a [&'a [u8]],
/// The stapled OCSP response given to us by Rustls, if any.
pub stapled_ocsp: Option<&'a [u8]>,
/// The time to use as the current time for verification.
pub verification_time: pki_types::UnixTime,
pub expected_result: Result<(), TlsError>,
/// An error that should be present inside an expected `CertificateError::Other` variant.
///
/// Set this if the error being tested uses `CertificateError::Other` and not statically known
/// variants in [TlsError]
#[allow(dead_code)]
pub other_error: Option<E>,
}
pub fn assert_cert_error_eq<E: StdError + PartialEq + 'static>(
result: &Result<(), TlsError>,
expected: &Result<(), TlsError>,
expected_err: Option<&E>,
) {
// If the expected error is an "Other" CertificateError we can't directly assert equality, we rely
// on the test caller to provide the correct value to compare.
if let Err(InvalidCertificate(CertificateError::Other(err))) = &expected {
let expected_err = expected_err.expect("error not provided for `Other` case handling");
let err: &E = err
.0
.downcast_ref()
.expect("incorrect `Other` inner error kind");
assert_eq!(err, expected_err);
} else {
assert_eq!(result, expected);
}
}
/// Return a fixed [`pki_types::UnixTime`] for certificate validation purposes.
///
/// We fix the "now" value used for certificate validation to a fixed point in time at which
/// we know the test certificates are valid. This must be updated if the mock certificates
/// are regenerated.
pub(crate) fn verification_time() -> pki_types::UnixTime {
// Wed, 8 April 2026 12:03 UTC
pki_types::UnixTime::since_unix_epoch(Duration::from_secs(1_775_649_786))
}
fn test_provider() -> Arc<CryptoProvider> {
Arc::new(rustls::crypto::ring::default_provider())
}
@@ -0,0 +1,314 @@
// Generates the test data files used in the tests in verification_mock.rs.
//
// After re-generating mock certificates be sure to also update the fixed
// verification timestamp in `mod.rs`'s `verification_time` fn to match
// the current time.
//
// The primary point of this program is to fully automate the creation of the
// test data, with minimal tool dependencies (e.g. no OpenSSL), with low effort.
//
// This program isn't run as part of the build. Instead, it generates data files
// that are valid for a long time, so they don't need to be regenerated to avoid
// expiration.
//
// Files generated by this program are named "A-B-ee_C[-D].{crt, ocsp}" where
// A is the (subject) name the root certificate, B is the (subject) name of the
// intermediate certificate, C is the (subjectAltName DNS name) name of the
// end-entity certificate, and D is some distinguishing feature (e.g. "revoked").
//
// When this program was first written, it was thought that such conventions,
// and the structure of the program, would make it easy to create certificates
// that are similar but slightly different, e.g. same hostname, same issuer
// name, but different roots. It's still to be determined if this structure
// actually facilitates that.
//
// The other goal of this program is to serve as a model for the `webpki`
// crate's planned self-contained all-Rust test suite. In particular, this
// program was originally developed to accelerate the Rust test data generator
// for the `webpki` crate.
package main
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"errors"
"fmt"
"io/ioutil"
"math/big"
"net"
"os"
"strings"
"time"
"golang.org/x/crypto/ocsp"
)
const (
OneDay = time.Hour * 24
OneYear = OneDay * 365
)
func main() {
err := doIt()
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
func doIt() error {
now := time.Now().Truncate(time.Minute).UTC()
// "ee_1" -> "::1" is IPv6 localhost, omitting ":" characters b/c invalid for file paths on Windows
end_entities := [3]string{"ee_example.com", "ee_127.0.0.1", "ee_1"}
var err error = nil
root1_key, err := generateRoot("root1", now)
if err != nil {
return err
}
root1_int1_key, err := generateInt("root1-int1", 2, now, root1_key)
if err != nil {
return err
}
for _, ee := range end_entities {
err = generateEndEntity("root1-int1-"+ee+"-good", 1, now, root1_int1_key)
if err != nil {
return err
}
err = generateEndEntity("root1-int1-"+ee+"-revoked", 2, now, root1_int1_key)
if err != nil {
return err
}
err = generateEndEntity("root1-int1-"+ee+"-wrong_eku", 3, now, root1_int1_key)
if err != nil {
return err
}
}
return nil
}
// Generates a binary DER X.509 file with name `eeName` + ".crt". The certificate will have
// the given serial number (which should be unique per issuer), OCSP status (ocsp.Good,
// ocsp.Revoked, etc.), signed by the given key.
func generateEndEntity(eeName string, serial int64, now time.Time, caKey crypto.Signer) error {
nameParts := strings.Split(eeName, "-")
caName := nameParts[0] + "-" + nameParts[1]
eeBaseName := nameParts[2]
label := nameParts[3]
caCert, err := readCert(caName)
if err != nil {
return err
}
eePubKey, err := generatePubKey()
if err != nil {
return err
}
// macOS requirements reference: https://support.apple.com/en-us/HT210176
template := x509.Certificate{
NotBefore: now.Add(-OneDay),
// macOS >=10.15 requires that certificates must have a
// validity period of 825 days or fewer.
NotAfter: now.Add(2 * OneYear),
// macOS >=10.15 requires that server certificates must have the
// id-kp-serverAuth OID present in the EKU.
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
switch eeBaseName {
case "ee_example.com":
template.SerialNumber = big.NewInt(serial)
template.DNSNames = []string{"example.com"}
case "ee_127.0.0.1": // IPv4 localhost
template.SerialNumber = big.NewInt(serial)
template.IPAddresses = []net.IP{net.IPv4(127, 0, 0, 1)}
case "ee_1": // IPv6 localhost, e.g. "::1"
template.SerialNumber = big.NewInt(serial)
template.IPAddresses = []net.IP{net.IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}
default:
return errors.New("Unrecognized end entity certificate:" + eeName)
}
ocspStatus := ocsp.Unknown // Don't generate an OCSP response.
switch label {
case "good":
ocspStatus = ocsp.Good
case "revoked":
ocspStatus = ocsp.Revoked
case "wrong_eku":
template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageEmailProtection}
}
cert, err := x509.CreateCertificate(rand.Reader, &template, caCert, eePubKey, caKey)
if err != nil {
return err
}
err = ioutil.WriteFile(eeName+".crt", cert, 0666)
if err != nil {
return err
}
if ocspStatus != ocsp.Unknown {
err = generateOCSPResponse(eeName, ocspStatus, now, caKey)
if err != nil {
return err
}
}
return nil
}
// Generates a binary DER X.509 file with name `intName` + ".crt".
func generateInt(intName string, serial int64, now time.Time, caKey crypto.Signer) (crypto.Signer, error) {
nameParts := strings.Split(intName, "-")
caName := nameParts[0]
caCert, err := readCert(caName)
if err != nil {
return nil, err
}
intKey, err := generateKey()
if err != nil {
return nil, err
}
template := x509.Certificate{
Subject: pkix.Name{
Organization: []string{intName},
},
NotBefore: now.Add(-OneDay),
NotAfter: now.Add(OneYear),
IsCA: true,
KeyUsage: x509.KeyUsageCertSign,
BasicConstraintsValid: true,
SerialNumber: big.NewInt(serial),
}
cert, err := x509.CreateCertificate(rand.Reader, &template, caCert, intKey.Public(), caKey)
if err != nil {
return nil, err
}
err = ioutil.WriteFile(intName+".crt", cert, 0666)
if err != nil {
return nil, err
}
return intKey, nil
}
func generateRoot(name string, now time.Time) (crypto.Signer, error) {
caKey, err := generateKey()
if err != nil {
return nil, err
}
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
Organization: []string{name},
},
NotBefore: now.Add(-OneDay),
NotAfter: now.Add(OneYear),
IsCA: true,
KeyUsage: x509.KeyUsageCertSign,
BasicConstraintsValid: true,
}
cert, err := x509.CreateCertificate(rand.Reader, &template, &template, caKey.Public(), caKey)
if err != nil {
return nil, err
}
return caKey, ioutil.WriteFile(name+".crt", cert, 0666)
}
func generateOCSPResponse(name string, status int, now time.Time, caKey crypto.Signer) error {
nameParts := strings.Split(name, "-")
caName := nameParts[0] + "-" + nameParts[1]
caCert, err := readCert(caName)
if err != nil {
return err
}
eeCert, err := readCert(name)
if err != nil {
return err
}
// It seems we must have `thisUpdate >= eeCert.NotBefore` or else
// Windows won't trust the OCSP response. In particular, if the
// response is `revoked` but this date is too early, then it will
// not consider the response revoked!
thisUpdate := eeCert.NotBefore.Add(1)
template := ocsp.Response{
Status: status,
SerialNumber: eeCert.SerialNumber,
ThisUpdate: thisUpdate,
NextUpdate: thisUpdate.Add(1 * OneYear),
}
if status == ocsp.Revoked {
template.RevokedAt = thisUpdate
}
response, err := ocsp.CreateResponse(caCert, caCert, template, caKey)
if err != nil {
return err
}
return ioutil.WriteFile(name+".ocsp", response, 0666)
}
func generateKey() (crypto.Signer, error) {
key, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
if err != nil {
return nil, err
}
return key, nil
}
func generatePubKey() (*ecdsa.PublicKey, error) {
privateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
if err != nil {
return nil, err
}
return &privateKey.PublicKey, nil
}
func readCert(name string) (*x509.Certificate, error) {
der, err := ioutil.ReadFile(name + ".crt")
if err != nil {
return nil, err
}
return x509.ParseCertificate(der)
}
func readKey(name string) (*ecdsa.PrivateKey, error) {
pkcs8, err := ioutil.ReadFile(name + ".p8")
if err != nil {
return nil, err
}
privateKey, err := x509.ParsePKCS8PrivateKey(pkcs8)
if err != nil {
return nil, err
}
switch k := privateKey.(type) {
case *ecdsa.PrivateKey:
return k, nil
default:
return nil, errors.New("Unexpected private key type")
}
}
@@ -0,0 +1,5 @@
module briansmith.org/webpki-test-certs
go 1.17
require golang.org/x/crypto v0.0.0-20211117183948-ae814b36b871
@@ -0,0 +1,2 @@
golang.org/x/crypto v0.0.0-20211117183948-ae814b36b871 h1:/pEO3GD/ABYAjuakUS6xSEmmlyVS4kxBNkeA9tLJiTI=
golang.org/x/crypto v0.0.0-20211117183948-ae814b36b871/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
@@ -0,0 +1,391 @@
//! Tests of certificate verification that require our own test CA to be
//! trusted.
//!
//! # Re-generating the test data
//!
//! `cd src/tests/verification_mock && go run ca.go`
//!
//! # Repeatability and Self-containedness
//!
//! These tests are only supported on platforms where we have implemented the
//! ability to trust a CA (only) for the duration of a test, without modifying
//! the operating system's trust store--i.e. without affecting the security of
//! any parts of the system outside of these tests. See the `#![cfg(...)]`
//! immediately below to see which platforms run these tests.
#![cfg(all(
any(windows, unix, target_os = "android"),
// These OSes require a simulator runtime and bundle.
not(target_os = "tvos"),
not(target_os = "watchos"),
not(target_os = "visionos")
))]
use std::convert::TryFrom;
use std::net::IpAddr;
#[cfg(not(any(target_vendor = "apple", windows)))]
use std::net::{Ipv4Addr, Ipv6Addr};
use std::sync::Arc;
use rustls::client::danger::ServerCertVerifier;
use rustls::pki_types;
#[cfg(not(any(target_vendor = "apple", windows)))]
use rustls::pki_types::{DnsName, ServerName};
use rustls::{CertificateError, Error as TlsError, OtherError};
use super::TestCase;
use crate::tests::{assert_cert_error_eq, test_provider, verification_time};
use crate::verification::{EkuError, Verifier};
macro_rules! mock_root_test_cases {
{ $( $name:ident [ $target:meta ] => $test_case:expr ),+ , } => {
mock_root_test_cases!(@ $($name [ $target ] => $test_case),+,);
#[cfg(test)]
mod tests {
$(
#[cfg($target)]
#[test]
pub fn $name() {
super::$name()
}
)+
}
#[cfg(feature = "ffi-testing")]
pub static ALL_TEST_CASES: &'static [fn()] = &[
$(
#[cfg($target)]
$name,
)+
];
};
{@ $( $name:ident [ $target:meta ] => $test_case:expr ),+ , } => {
$(
#[cfg($target)]
pub(super) fn $name() {
test_with_mock_root(&$test_case, Roots::OnlyExtra);
#[cfg(all($target, not(target_os = "android")))]
test_with_mock_root(&$test_case, Roots::ExtraAndPlatform);
}
)+
};
}
macro_rules! no_error {
() => {
None::<std::convert::Infallible>
};
}
const ROOT1: pki_types::CertificateDer<'static> =
pki_types::CertificateDer::from_slice(include_bytes!("root1.crt"));
const ROOT1_INT1: &[u8] = include_bytes!("root1-int1.crt");
const ROOT1_INT1_EXAMPLE_COM_GOOD: &[u8] = include_bytes!("root1-int1-ee_example.com-good.crt");
const ROOT1_INT1_LOCALHOST_IPV4_GOOD: &[u8] = include_bytes!("root1-int1-ee_127.0.0.1-good.crt");
const ROOT1_INT1_LOCALHOST_IPV6_GOOD: &[u8] = include_bytes!("root1-int1-ee_1-good.crt");
const EXAMPLE_COM: &str = "example.com";
const LOCALHOST_IPV4: &str = "127.0.0.1";
const LOCALHOST_IPV6: &str = "::1";
#[cfg(any(test, feature = "ffi-testing"))]
#[cfg_attr(feature = "ffi-testing", allow(dead_code))]
pub(super) fn verification_without_mock_root() {
let crypto_provider = test_provider();
// Since Rustls 0.22 constructing a webpki verifier (like the one backing Verifier on unix
// systems) without any roots produces `OtherError(NoRootAnchors)` - since our FreeBSD CI
// runner fails to find any roots with openssl-probe we need to provide webpki-root-certs here
// or the test will fail with the `OtherError` instead of the expected `CertificateError`.
#[cfg(target_os = "freebsd")]
let verifier = Verifier::new_with_extra_roots(
webpki_root_certs::TLS_SERVER_ROOT_CERTS.iter().cloned(),
crypto_provider,
)
.unwrap();
#[cfg(not(target_os = "freebsd"))]
let verifier = Verifier::new(crypto_provider).unwrap();
let server_name = pki_types::ServerName::try_from(EXAMPLE_COM).unwrap();
let end_entity = pki_types::CertificateDer::from(ROOT1_INT1_EXAMPLE_COM_GOOD);
let intermediates = [pki_types::CertificateDer::from(ROOT1_INT1)];
// Fails because the server cert has no trust root in Windows, and can't since it uses a self-signed CA.
// Similarly on UNIX platforms using the Webpki verifier, it can't fetch extra certificates through
// AIA chasing or other mechanisms, and so we know this test will correctly verify an unknown
// root in a chain fails validation.
let result = verifier.verify_server_cert(
&end_entity,
&intermediates,
&server_name,
&[],
verification_time(),
);
assert_eq!(
result.map(|_| ()),
Err(TlsError::InvalidCertificate(
CertificateError::UnknownIssuer
))
);
}
#[test]
fn test_verification_without_mock_root() {
verification_without_mock_root()
}
// Note: Android does not currently support IP address hosts, so these tests are disabled for
// Android.
// Verifies that our test trust anchor(s) are not trusted when `Verifier::new()`
// is used.
mock_root_test_cases! {
valid_no_stapling_dns [ any(windows, unix) ] => TestCase {
reference_id: EXAMPLE_COM,
chain: &[ROOT1_INT1_EXAMPLE_COM_GOOD, ROOT1_INT1],
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
valid_no_stapling_ipv4 [ any(windows, unix) ] => TestCase {
reference_id: LOCALHOST_IPV4,
chain: &[ROOT1_INT1_LOCALHOST_IPV4_GOOD, ROOT1_INT1],
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
valid_no_stapling_ipv6 [ any(windows, unix) ] => TestCase {
reference_id: LOCALHOST_IPV6,
chain: &[ROOT1_INT1_LOCALHOST_IPV6_GOOD, ROOT1_INT1],
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
valid_stapled_good_dns [ any(windows, unix) ] => TestCase {
reference_id: EXAMPLE_COM,
chain: &[ROOT1_INT1_EXAMPLE_COM_GOOD, ROOT1_INT1],
stapled_ocsp: Some(include_bytes!("root1-int1-ee_example.com-good.ocsp")),
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
valid_stapled_good_ipv4 [ any(windows, unix) ] => TestCase {
reference_id: LOCALHOST_IPV4,
chain: &[ROOT1_INT1_LOCALHOST_IPV4_GOOD, ROOT1_INT1],
stapled_ocsp: Some(include_bytes!("root1-int1-ee_127.0.0.1-good.ocsp")),
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
valid_stapled_good_ipv6 [ any(windows, unix) ] => TestCase {
reference_id: LOCALHOST_IPV6,
chain: &[ROOT1_INT1_LOCALHOST_IPV6_GOOD, ROOT1_INT1],
stapled_ocsp: Some(include_bytes!("root1-int1-ee_1-good.ocsp")),
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
// The revocation tests use a separate certificate from the one used in the "good" case to deal
// with operating systems with validation data caches (e.g. Windows).
// Linux is not included, since the webpki verifier does not presently support OCSP revocation
// checking.
// Check that self-signed certificates, which may or may not be revokved, do not return any
// kind of revocation error. It is expected that non-public certificates without revocation information
// have no revocation checking performed across platforms.
revoked_dns [ any(windows, target_os = "android", target_vendor = "apple") ] => TestCase {
reference_id: EXAMPLE_COM,
chain: &[include_bytes!("root1-int1-ee_example.com-revoked.crt"), ROOT1_INT1],
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
stapled_revoked_dns [ any(windows, target_os = "android", target_vendor = "apple") ] => TestCase {
reference_id: EXAMPLE_COM,
chain: &[include_bytes!("root1-int1-ee_example.com-revoked.crt"), ROOT1_INT1],
stapled_ocsp: Some(include_bytes!("root1-int1-ee_example.com-revoked.ocsp")),
verification_time: verification_time(),
expected_result: Err(TlsError::InvalidCertificate(CertificateError::Revoked)),
other_error: no_error!(),
},
stapled_revoked_ipv4 [ any(windows, target_os = "android", target_vendor = "apple") ] => TestCase {
reference_id: LOCALHOST_IPV4,
chain: &[include_bytes!("root1-int1-ee_127.0.0.1-revoked.crt"), ROOT1_INT1],
stapled_ocsp: Some(include_bytes!("root1-int1-ee_127.0.0.1-revoked.ocsp")),
verification_time: verification_time(),
expected_result: Err(TlsError::InvalidCertificate(CertificateError::Revoked)),
other_error: no_error!(),
},
stapled_revoked_ipv6 [ any(windows, target_os = "android", target_vendor = "apple") ] => TestCase {
reference_id: LOCALHOST_IPV6,
chain: &[include_bytes!("root1-int1-ee_1-revoked.crt"), ROOT1_INT1],
stapled_ocsp: Some(include_bytes!("root1-int1-ee_1-revoked.ocsp")),
verification_time: verification_time(),
expected_result: Err(TlsError::InvalidCertificate(CertificateError::Revoked)),
other_error: no_error!(),
},
// Validation fails with no intermediate (that can't be fetched
// with AIA because there's no AIA issuer field in the certificate).
// (AIA is an extension that allows downloading of missing data,
// like missing certificates, during validation; see
// https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.2.1).
ee_only_dns [ any(windows, unix) ] => TestCase {
reference_id: EXAMPLE_COM,
chain: &[ROOT1_INT1_EXAMPLE_COM_GOOD],
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Err(TlsError::InvalidCertificate(CertificateError::UnknownIssuer)),
other_error: no_error!(),
},
ee_only_ipv4 [ any(windows, unix) ] => TestCase {
reference_id: LOCALHOST_IPV4,
chain: &[ROOT1_INT1_LOCALHOST_IPV4_GOOD],
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Err(TlsError::InvalidCertificate(CertificateError::UnknownIssuer)),
other_error: no_error!(),
},
ee_only_ipv6 [ any(windows, unix) ] => TestCase {
reference_id: LOCALHOST_IPV6,
chain: &[ROOT1_INT1_LOCALHOST_IPV6_GOOD],
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Err(TlsError::InvalidCertificate(CertificateError::UnknownIssuer)),
other_error: no_error!(),
},
// Validation fails when the certificate isn't valid for the reference ID.
domain_mismatch_dns [ any(windows, unix) ] => TestCase {
reference_id: "example.org",
chain: &[ROOT1_INT1_EXAMPLE_COM_GOOD, ROOT1_INT1],
stapled_ocsp: None,
verification_time: verification_time(),
#[cfg(not(any(target_vendor = "apple", windows)))]
expected_result: Err(TlsError::InvalidCertificate(CertificateError::NotValidForNameContext {
expected: ServerName::DnsName(DnsName::try_from("example.org").unwrap()),
presented: vec!["DnsName(\"example.com\")".to_owned()]
})),
#[cfg(any(target_vendor = "apple", windows))]
expected_result: Err(TlsError::InvalidCertificate(CertificateError::NotValidForName)),
other_error: no_error!(),
},
domain_mismatch_ipv4 [ any(windows, unix) ] => TestCase {
reference_id: "198.168.0.1",
chain: &[ROOT1_INT1_LOCALHOST_IPV4_GOOD, ROOT1_INT1],
stapled_ocsp: None,
verification_time: verification_time(),
#[cfg(not(any(target_vendor = "apple", windows)))]
expected_result: Err(TlsError::InvalidCertificate(CertificateError::NotValidForNameContext {
expected: ServerName::IpAddress(pki_types::IpAddr::V4(Ipv4Addr::from([198, 168, 0, 1]).into())),
presented: vec!["IpAddress(127.0.0.1)".to_owned()],
})),
#[cfg(any(target_vendor = "apple", windows))]
expected_result: Err(TlsError::InvalidCertificate(CertificateError::NotValidForName)),
other_error: no_error!(),
},
domain_mismatch_ipv6 [ any(windows, unix) ] => TestCase {
reference_id: "::ffff:c6a8:1",
chain: &[ROOT1_INT1_LOCALHOST_IPV6_GOOD, ROOT1_INT1],
stapled_ocsp: None,
verification_time: verification_time(),
#[cfg(not(any(target_vendor = "apple", windows)))]
expected_result: Err(TlsError::InvalidCertificate(CertificateError::NotValidForNameContext {
expected: ServerName::IpAddress(pki_types::IpAddr::V6(Ipv6Addr::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 198, 168, 0, 1]).into())),
presented: vec!["IpAddress(0::1)".to_owned()],
})),
#[cfg(any(target_vendor = "apple", windows))]
expected_result: Err(TlsError::InvalidCertificate(CertificateError::NotValidForName)),
other_error: no_error!(),
},
wrong_eku_dns [ any(windows, unix) ] => TestCase {
reference_id: EXAMPLE_COM,
chain: &[include_bytes!("root1-int1-ee_example.com-wrong_eku.crt"), ROOT1_INT1],
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Err(TlsError::InvalidCertificate(
CertificateError::Other(OtherError(Arc::from(EkuError))))),
other_error: Some(EkuError),
},
wrong_eku_ipv4 [ any(windows, unix) ] => TestCase {
reference_id: LOCALHOST_IPV4,
chain: &[include_bytes!("root1-int1-ee_127.0.0.1-wrong_eku.crt"), ROOT1_INT1],
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Err(TlsError::InvalidCertificate(
CertificateError::Other(OtherError(Arc::from(EkuError))))),
other_error: Some(EkuError),
},
wrong_eku_ipv6 [ any(windows, unix) ] => TestCase {
reference_id: LOCALHOST_IPV6,
chain: &[include_bytes!("root1-int1-ee_1-wrong_eku.crt"), ROOT1_INT1],
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Err(TlsError::InvalidCertificate(
CertificateError::Other(OtherError(Arc::from(EkuError))))),
other_error: Some(EkuError),
},
}
fn test_with_mock_root<E: std::error::Error + PartialEq + 'static>(
test_case: &TestCase<E>,
root_src: Roots,
) {
log::info!("verifying {:?}", test_case.expected_result);
let provider = test_provider();
let verifier = match root_src {
Roots::OnlyExtra => Verifier::new_with_fake_root(ROOT1, provider), // TODO: time
#[cfg(not(target_os = "android"))]
Roots::ExtraAndPlatform => Verifier::new_with_extra_roots([ROOT1], provider).unwrap(),
};
let mut chain = test_case
.chain
.iter()
.map(|bytes| pki_types::CertificateDer::from(*bytes));
let end_entity = chain.next().unwrap();
let intermediates: Vec<pki_types::CertificateDer<'_>> = chain.collect();
let server_name = pki_types::ServerName::try_from(test_case.reference_id).unwrap();
if test_case.reference_id.parse::<IpAddr>().is_ok() {
assert!(matches!(server_name, pki_types::ServerName::IpAddress(_)));
} else {
assert!(matches!(server_name, pki_types::ServerName::DnsName(_)));
}
let result = verifier.verify_server_cert(
&end_entity,
&intermediates,
&server_name,
test_case.stapled_ocsp.unwrap_or(&[]),
test_case.verification_time,
);
assert_cert_error_eq(
&result.map(|_| ()),
&test_case.expected_result,
test_case.other_error.as_ref(),
);
// TODO: get into specifics of errors returned when it fails.
}
enum Roots {
/// Test with only extra roots, without loading the platform trust store.
///
/// We want to keep things reproducible given the background-managed nature of trust roots on platforms.
OnlyExtra,
/// Test with loading the extra roots and the platform trust store.
///
/// Right now, not all platforms are supported.
#[cfg(not(target_os = "android"))]
ExtraAndPlatform,
}
@@ -0,0 +1,276 @@
//! Certificate verification tests that use real-world certificates and the
//! "real" (non-mock) Rustls configuration returned.
//!
//! # Repeatability and Self-containedness
//!
//! These tests are written to reduce the time-bomb nature of testing with
//! real certificates, which expire and/or can be revoked over time. For
//! example, rather than connecting to the TLS server over the network,
//! these tests operate on a locally-cached copy of the certificates
//! downloaded at a point in time. However, there are some inherent
//! limitations of what we can do when using real-world certificates. We
//! accept that the benefit of having these tests outweigh this downside.
//! If we encounter cases where these tests are flaky we'll spend additional
//! effort
//!
//! * If these certificates are ever revoked then it is possible that, even if
//! with the measures mentioned in the next paragraphs, the operating system
//! might learn of the revocation externally and cause the tests to fail.
//!
//! * Some operating systems, Windows in particular, download the set of
//! trusted roots dynamically as-needed. If there is a failure during that
//! fetching then the trust anchors for these certificates might not be
//! trusted by the operating system's root store.
//!
//! XXX: These tests should be using a stapled OCSP responses so that the
//! (operating-system-based) verifier doesn't try to fetch an OCSP
//! response or CRL certificate. However, until we can fix the validation
//! at a specific point in time, we can't do this, as the OCSP responses
//! will generally expire within a matter of days of being produced. Also,
//! we'd need to upgrade to a version of Rustls that supports passing in
//! stapled OCSP responses for each certificate in the chain. Most certificate
//! verifiers that do fetching of OCSP responses will "fail open"; that is, if
//! a networking error causes the fetch of the OCSP response to fail, then
//! they will continue roughly as though they received a "Good" response.
//! Thus we don't expect these tests to be flaky w.r.t. that, except for
//! potentially poor performance.
use rustls::client::danger::ServerCertVerifier;
use rustls::pki_types;
#[cfg(not(any(target_vendor = "apple", windows)))]
use rustls::pki_types::{DnsName, ServerName};
use rustls::{CertificateError, Error as TlsError};
use super::TestCase;
use crate::tests::{assert_cert_error_eq, test_provider, verification_time};
use crate::Verifier;
// This is the certificate chain presented by one server for
// `aws.amazon.com` when this test was updated 2025-08-13.
//
// Use this to template view the certificate using OpenSSL:
// ```sh
// openssl x509 -inform der -text -in aws_amazon_com_valid_1.crt | less
// ```
//
// You can update these cert files with `examples/update-certs.rs`
const VALID_AWS_AMAZON_COM_CHAIN: &[&[u8]] = &[
include_bytes!("aws_amazon_com_valid_1.crt"),
include_bytes!("aws_amazon_com_valid_2.crt"),
include_bytes!("aws_amazon_com_valid_3.crt"),
// XXX: This certificate is included for testing in environments that might need
// a cross-signed root certificate instead of the just the server-provided one.
include_bytes!("aws_amazon_com_valid_4.crt"),
];
/// Returns a list of names valid for [VALID_AWS_AMAZON_COM_CHAIN], in a format
/// expected by `CertificateError::NotValidForContext`.
#[cfg(not(any(target_vendor = "apple", windows)))]
fn valid_aws_chain_names() -> Vec<String> {
const VALID_AWS_NAMES: &[&str] = &[
"aws.amazon.com",
"aws-us-west-2.amazon.com",
"www.aws.amazon.com",
"1.aws-lbr.amazonaws.com",
"amazonaws-china.com",
"www.amazonaws-china.com",
"aws-us-east-1.amazon.com",
];
VALID_AWS_NAMES
.iter()
.copied()
.map(|name| format!("DnsName(\"{name}\")"))
.collect()
}
const AWS_AMAZON_COM: &str = "aws.amazon.com";
// Domain names for which `VALID_AWS_AMAZON_COM_CHAIN` isn't valid.
const VALID_UNRELATED_DOMAIN: &str = "my.1password.com";
const VALID_UNRELATED_SUBDOMAIN: &str = "www.amazon.com";
const LETSENCRYPT_ORG: &str = "letsencrypt.org";
const VALID_LETSENCRYPT_ORG_CHAIN: &[&[u8]] = &[
include_bytes!("letsencrypt_org_valid_1.crt"),
include_bytes!("letsencrypt_org_valid_2.crt"),
];
macro_rules! real_world_test_cases {
{ $( $name:ident => $test_case:expr ),+ , } => {
real_world_test_cases!(@ $($name => $test_case),+,);
#[cfg(test)]
mod tests {
$(
#[test]
pub fn $name() {
super::$name()
}
)+
}
#[cfg(feature = "ffi-testing")]
pub static ALL_TEST_CASES: &'static [fn()] = &[
$($name),+
];
};
{@ $( $name:ident => $test_case:expr ),+ , } => {
$(
pub(super) fn $name() {
real_world_test(&$test_case);
}
)+
}
}
macro_rules! no_error {
() => {
None::<std::convert::Infallible>
};
}
fn real_world_test<E: std::error::Error>(test_case: &TestCase<E>) {
log::info!(
"verifying ref ID {:?} expected {:?}",
test_case.reference_id,
test_case.expected_result
);
let crypto_provider = test_provider();
// On BSD systems openssl-probe fails to find the system CA bundle,
// so we must provide extra roots from webpki-root-cert.
#[cfg(target_os = "freebsd")]
let verifier = Verifier::new_with_extra_roots(
webpki_root_certs::TLS_SERVER_ROOT_CERTS.iter().cloned(),
crypto_provider,
)
.unwrap();
#[cfg(not(target_os = "freebsd"))]
let verifier = Verifier::new(crypto_provider).unwrap();
let mut chain = test_case
.chain
.iter()
.map(|bytes| pki_types::CertificateDer::from(*bytes));
let end_entity_cert = chain.next().unwrap();
let intermediates: Vec<pki_types::CertificateDer<'_>> = chain.collect();
let server_name = pki_types::ServerName::try_from(test_case.reference_id).unwrap();
let stapled_ocsp = test_case.stapled_ocsp.unwrap_or(&[]);
let result = verifier
.verify_server_cert(
&end_entity_cert,
&intermediates,
&server_name,
stapled_ocsp,
test_case.verification_time,
)
.map(|_| ());
assert_cert_error_eq(
&result.map(|_| ()),
&test_case.expected_result,
None::<&std::convert::Infallible>,
);
// TODO: get into specifics of errors returned when it fails.
}
// Prefer to staple the OCSP response for the end-entity certificate for
// performance and repeatability.
real_world_test_cases! {
// The certificate is valid for *.aws.amazon.com.
aws_amazon_com_valid => TestCase {
reference_id: AWS_AMAZON_COM,
chain: VALID_AWS_AMAZON_COM_CHAIN,
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
// Same as above but without stapled OCSP.
aws_amazon_com_valid_no_stapled => TestCase {
reference_id: AWS_AMAZON_COM,
chain: VALID_AWS_AMAZON_COM_CHAIN,
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
// Valid also for www.amazon.amazon.com (extra subdomain).
_aws_amazon_com_valid => TestCase {
reference_id: "www.aws.amazon.com",
chain: VALID_AWS_AMAZON_COM_CHAIN,
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
// The certificate isn't valid for an unrelated subdomain.
unrelated_domain_invalid => TestCase {
reference_id: VALID_UNRELATED_SUBDOMAIN,
chain: VALID_AWS_AMAZON_COM_CHAIN,
stapled_ocsp: None,
verification_time: verification_time(),
#[cfg(not(any(target_vendor = "apple", windows)))]
expected_result: Err(TlsError::InvalidCertificate(CertificateError::NotValidForNameContext {
expected: ServerName::DnsName(DnsName::try_from(VALID_UNRELATED_SUBDOMAIN).unwrap()),
presented: valid_aws_chain_names(),
})),
#[cfg(any(target_vendor = "apple", windows))]
expected_result: Err(TlsError::InvalidCertificate(CertificateError::NotValidForName)),
other_error: no_error!(),
},
// The certificate chain for the unrelated domain is not valid for
// my.1password.com.
unrelated_chain_not_valid_for_my_1password_com => TestCase {
reference_id: VALID_UNRELATED_DOMAIN,
chain: VALID_AWS_AMAZON_COM_CHAIN,
stapled_ocsp: None,
verification_time: verification_time(),
#[cfg(not(any(target_vendor = "apple", windows)))]
expected_result: Err(TlsError::InvalidCertificate(CertificateError::NotValidForNameContext {
expected: ServerName::DnsName(DnsName::try_from(VALID_UNRELATED_DOMAIN).unwrap()),
presented: valid_aws_chain_names(),
})),
#[cfg(any(target_vendor = "apple", windows))]
expected_result: Err(TlsError::InvalidCertificate(CertificateError::NotValidForName)),
other_error: no_error!(),
},
letsencrypt => TestCase {
reference_id: LETSENCRYPT_ORG,
chain: VALID_LETSENCRYPT_ORG_CHAIN,
stapled_ocsp: None,
verification_time: verification_time(),
expected_result: Ok(()),
other_error: no_error!(),
},
// OCSP stapling works.
//
// XXX: This test is commented-out because it is a time-bomb due to the
// short lifetime of the OCSP responses for the certificate.
//
// TODO: If/when we can validate a certificate for a specific point in time
// during a test, re-enable this and have it test the certificate validity
// at a point in time where the OCSP response is valid.
//
// revoked_badssl_com_stapled => TestCase {
// reference_id: "revoked.badssl.com",
// chain: &[
// include_bytes!("revoked_badssl_com_1.crt"),
// include_bytes!("revoked_badssl_com_2.crt"),
// ],
// stapled_ocsp: Some(include_bytes!("revoked_badssl_com_1.ocsp")),
// // XXX: We only do OCSP stapling on Windows.
// valid: !cfg!(windows),
// },
}
@@ -0,0 +1,336 @@
use jni::{
jni_sig, jni_str,
objects::{JByteArray, JObject, JObjectArray, JString, JValue},
signature::MethodSignature,
Env,
};
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerifier};
use rustls::crypto::{verify_tls12_signature, verify_tls13_signature, CryptoProvider};
use rustls::pki_types;
use rustls::Error::InvalidCertificate;
use rustls::{
CertificateError, DigitallySignedStruct, Error as TlsError, OtherError, SignatureScheme,
};
use std::sync::Arc;
use super::{log_server_cert, ALLOWED_EKUS};
use crate::android::{with_context, CachedClass};
static CERT_VERIFIER_CLASS: CachedClass =
CachedClass::new(jni_str!("org.rustls.platformverifier.CertificateVerifier"));
// Note: Keep these in sync with the Kotlin enum.
#[derive(Debug)]
enum VerifierStatus {
Ok,
Unavailable,
Expired,
UnknownCert,
Revoked,
InvalidEncoding,
InvalidExtension,
}
// Android's certificate verifier ignores this outright and this is considered the
// official recommendation. See https://bugs.chromium.org/p/chromium/issues/detail?id=627154.
const AUTH_TYPE: &str = "RSA";
/// A TLS certificate verifier that utilizes the Android platform verifier.
#[derive(Debug)]
pub struct Verifier {
/// Testing only: The root CA certificate to trust.
#[cfg(any(test, feature = "ffi-testing"))]
test_only_root_ca_override: Option<pki_types::CertificateDer<'static>>,
crypto_provider: Arc<CryptoProvider>,
}
#[cfg(any(test, feature = "ffi-testing"))]
impl Drop for Verifier {
fn drop(&mut self) {
with_context::<_, ()>(|cx| {
let cert_verifier_class = CERT_VERIFIER_CLASS.get(cx)?;
cx.env
.call_static_method(
cert_verifier_class,
jni_str!("clearMockRoots"),
jni_sig!(() -> void),
&[],
)?
.v()?;
Ok(())
})
.expect("failed to clear test roots")
}
}
impl Verifier {
/// Creates a new instance of a TLS certificate verifier that utilizes the
/// Android certificate facilities.
#[cfg_attr(docsrs, doc(cfg(all())))]
pub fn new(crypto_provider: Arc<CryptoProvider>) -> Result<Self, TlsError> {
Ok(Self {
#[cfg(any(test, feature = "ffi-testing"))]
test_only_root_ca_override: None,
crypto_provider,
})
}
/// Creates a test-only TLS certificate verifier which trusts our fake root CA cert.
#[cfg(any(test, feature = "ffi-testing"))]
pub(crate) fn new_with_fake_root(
root: pki_types::CertificateDer<'static>,
crypto_provider: Arc<CryptoProvider>,
) -> Self {
Self {
test_only_root_ca_override: Some(root),
crypto_provider,
}
}
fn verify_certificate(
&self,
end_entity: &pki_types::CertificateDer<'_>,
intermediates: &[pki_types::CertificateDer<'_>],
server_name: &pki_types::ServerName<'_>,
ocsp_response: Option<&[u8]>,
now: pki_types::UnixTime,
) -> Result<(), TlsError> {
let certificate_chain = std::iter::once(end_entity)
.chain(intermediates)
.map(|cert| cert.as_ref())
.enumerate();
// Convert the unix timestamp into milliseconds, expressed as
// an i64 to later be converted into a Java Long used for a Date
// constructor.
let now: i64 = (now.as_secs() * 1000)
.try_into()
.map_err(|_| TlsError::FailedToGetCurrentTime)?;
let verification_result = with_context(|cx| {
let cert_verifier_class = CERT_VERIFIER_CLASS.get(cx)?;
let cert_list = {
let array = JObjectArray::<JByteArray>::new(
cx.env,
intermediates.len() + 1,
&JByteArray::null(),
)?;
for (idx, cert) in certificate_chain {
let cert_buffer = cx.env.byte_array_from_slice(cert)?;
array.set_element(cx.env, idx, cert_buffer)?;
}
array
};
let allowed_ekus = {
let array =
JObjectArray::<JString>::new(cx.env, ALLOWED_EKUS.len(), &JString::null())?;
for (idx, eku) in ALLOWED_EKUS.iter().enumerate() {
let eku = cx.env.new_string(eku.to_str().expect(
"ALLOWED_EKUS entries are ASCII constants -- always valid UTF-8",
))?;
array.set_element(cx.env, idx, eku)?
}
array
};
let ocsp_response = match ocsp_response {
Some(b) => cx.env.byte_array_from_slice(b)?,
None => JByteArray::null(),
};
#[cfg(any(test, feature = "ffi-testing"))]
{
if let Some(mock_root) = &self.test_only_root_ca_override {
let mock_root = cx.env.byte_array_from_slice(mock_root)?;
cx.env
.call_static_method(
cert_verifier_class,
jni_str!("addMockRoot"),
jni_sig!((byte[]) -> void),
&[JValue::from(&mock_root)],
)?
.v()
.expect("failed to add test root")
}
}
const VERIFIER_CALL: MethodSignature<'static, 'static> = jni_sig!(
(
android.content.Context,
JString,
JString,
JString[],
byte[],
jlong,
byte[][]
) -> org.rustls.platformverifier.VerificationResult
);
let server_name = cx.env.new_string(server_name.to_str())?;
let auth_type = cx.env.new_string(AUTH_TYPE)?;
let result = cx
.env
.call_static_method(
cert_verifier_class,
jni_str!("verifyCertificateChain"),
VERIFIER_CALL,
&[
JValue::from(cx.global.context.as_ref()),
JValue::from(&server_name),
JValue::from(&auth_type),
JValue::from(&JObject::from(allowed_ekus)),
JValue::from(&ocsp_response),
JValue::Long(now),
JValue::from(&JObject::from(cert_list)),
],
)?
.l()?;
Ok(extract_result_info(cx.env, result))
});
match verification_result {
Ok((status, maybe_msg)) => {
// `maybe_msg` is safe to log as its exactly what the system told us.
//
// The branches which unwrap it will never fail since the Kotlin side always sets it
// for the variants.
match status {
VerifierStatus::Ok => {
// If everything else was OK, check the hostname.
rustls::client::verify_server_name(
&rustls::server::ParsedCertificate::try_from(end_entity)?,
server_name,
)
}
VerifierStatus::Unavailable => Err(TlsError::General(String::from(
"No system trust stores available",
))),
VerifierStatus::Expired => Err(InvalidCertificate(CertificateError::Expired)),
VerifierStatus::UnknownCert => {
log::warn!("certificate was not trusted: {}", maybe_msg.unwrap());
Err(InvalidCertificate(CertificateError::UnknownIssuer))
}
VerifierStatus::Revoked => {
log::warn!("certificate was revoked: {}", maybe_msg.unwrap());
Err(InvalidCertificate(CertificateError::Revoked))
}
VerifierStatus::InvalidEncoding => {
Err(InvalidCertificate(CertificateError::BadEncoding))
}
VerifierStatus::InvalidExtension => Err(InvalidCertificate(
CertificateError::Other(OtherError(std::sync::Arc::new(super::EkuError))),
)),
}
}
Err(e) => Err(TlsError::General(format!(
"failed to call native verifier: {e:?}",
))),
}
}
}
fn extract_result_info(env: &mut Env<'_>, result: JObject<'_>) -> (VerifierStatus, Option<String>) {
let status_code = env
.get_field(&result, jni_str!("code"), jni_sig!(jint))
.and_then(|code| code.i())
.unwrap();
let status = match status_code {
0 => VerifierStatus::Ok,
1 => VerifierStatus::Unavailable,
2 => VerifierStatus::Expired,
3 => VerifierStatus::UnknownCert,
4 => VerifierStatus::Revoked,
5 => VerifierStatus::InvalidEncoding,
6 => VerifierStatus::InvalidExtension,
i => unreachable!("unknown status code: {i}"),
};
// Extract the `String?`.
let msg = env
.get_field(result, jni_str!("message"), jni_sig!(java.lang.String))
.and_then(|m| m.l())
.map(|s| {
if s.is_null() {
None
} else {
env.cast_local::<JString>(s)
.and_then(|s| s.try_to_string(env))
.ok()
}
})
.unwrap();
(status, msg)
}
#[cfg_attr(docsrs, doc(cfg(all())))]
impl ServerCertVerifier for Verifier {
fn verify_server_cert(
&self,
end_entity: &pki_types::CertificateDer<'_>,
intermediates: &[pki_types::CertificateDer<'_>],
server_name: &pki_types::ServerName,
ocsp_response: &[u8],
now: pki_types::UnixTime,
) -> Result<rustls::client::danger::ServerCertVerified, TlsError> {
log_server_cert(end_entity);
let ocsp_data = if !ocsp_response.is_empty() {
Some(ocsp_response)
} else {
None
};
match self.verify_certificate(end_entity, intermediates, server_name, ocsp_data, now) {
Ok(()) => Ok(rustls::client::danger::ServerCertVerified::assertion()),
Err(e) => {
// This error only tells us what the system errored with, so it doesn't leak anything
// sensitive.
log::error!("failed to verify TLS certificate: {}", e);
Err(e)
}
}
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &pki_types::CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, TlsError> {
verify_tls12_signature(
message,
cert,
dss,
&self.crypto_provider.signature_verification_algorithms,
)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &pki_types::CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, TlsError> {
verify_tls13_signature(
message,
cert,
dss,
&self.crypto_provider.signature_verification_algorithms,
)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.crypto_provider
.signature_verification_algorithms
.supported_schemes()
}
}
@@ -0,0 +1,311 @@
use std::sync::Arc;
use core_foundation::date::CFDate;
use core_foundation_sys::date::kCFAbsoluteTimeIntervalSince1970;
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerifier};
use rustls::crypto::{verify_tls12_signature, verify_tls13_signature, CryptoProvider};
use rustls::pki_types;
use rustls::{
CertificateError, DigitallySignedStruct, Error as TlsError, OtherError, SignatureScheme,
};
use security_framework::{
certificate::SecCertificate, policy::SecPolicy, secure_transport::SslProtocolSide,
trust::SecTrust,
};
use super::log_server_cert;
use crate::verification::invalid_certificate;
mod errors {
pub(super) use security_framework_sys::base::{
errSecCertificateRevoked, errSecCreateChainFailed, errSecHostNameMismatch,
errSecInvalidExtendedKeyUsage,
};
}
#[allow(clippy::as_conversions)]
fn system_time_to_cfdate(time: pki_types::UnixTime) -> Result<CFDate, TlsError> {
// SAFETY: The interval is defined by macOS externally, but is always present and never modified at runtime
// since its a global variable.
//
// See https://developer.apple.com/documentation/corefoundation/kcfabsolutetimeintervalsince1970.
let unix_adjustment = unsafe { kCFAbsoluteTimeIntervalSince1970 as u64 };
// Convert a system timestamp based off the UNIX epoch into the
// Apple epoch used by all `CFAbsoluteTime` values.
// Subtracting Durations with sub() will panic on overflow
time.as_secs()
.checked_sub(unix_adjustment)
.ok_or(TlsError::FailedToGetCurrentTime)
.map(|epoch| CFDate::new(epoch as f64))
}
/// A TLS certificate verifier that utilizes the Apple platform certificate facilities.
#[derive(Debug)]
pub struct Verifier {
/// Extra trust anchors to add to the verifier above and beyond those provided by
/// the system-provided trust stores.
extra_roots: Vec<SecCertificate>,
/// Testing only: The root CA certificate to trust.
#[cfg(any(test, feature = "ffi-testing", feature = "dbg"))]
test_only_root_ca_override: Option<SecCertificate>,
crypto_provider: Arc<CryptoProvider>,
}
impl Verifier {
/// Creates a new instance of a TLS certificate verifier that utilizes the Apple certificate
/// facilities.
#[cfg_attr(docsrs, doc(cfg(all())))]
pub fn new(crypto_provider: Arc<CryptoProvider>) -> Result<Self, TlsError> {
Ok(Self {
extra_roots: Vec::new(),
#[cfg(any(test, feature = "ffi-testing", feature = "dbg"))]
test_only_root_ca_override: None,
crypto_provider,
})
}
/// Creates a new instance of a TLS certificate verifier that utilizes the Apple certificate
/// facilities with the addition of extra root certificates to trust.
///
/// See [Verifier::new] for the external requirements the verifier needs.
#[cfg_attr(docsrs, doc(cfg(not(target_os = "android"))))]
pub fn new_with_extra_roots(
roots: impl IntoIterator<Item = pki_types::CertificateDer<'static>>,
crypto_provider: Arc<CryptoProvider>,
) -> Result<Self, TlsError> {
let extra_roots = roots
.into_iter()
.map(|root| {
SecCertificate::from_der(&root)
.map_err(|_| TlsError::InvalidCertificate(CertificateError::BadEncoding))
})
.collect::<Result<Vec<_>, _>>()?;
Ok(Self {
extra_roots,
#[cfg(any(test, feature = "ffi-testing", feature = "dbg"))]
test_only_root_ca_override: None,
crypto_provider,
})
}
/// Creates a test-only TLS certificate verifier which trusts our fake root CA cert.
#[cfg(any(test, feature = "ffi-testing", feature = "dbg"))]
pub(crate) fn new_with_fake_root(
root: pki_types::CertificateDer<'static>,
crypto_provider: Arc<CryptoProvider>,
) -> Self {
Self {
extra_roots: Vec::new(),
test_only_root_ca_override: Some(SecCertificate::from_der(root.as_ref()).unwrap()),
crypto_provider,
}
}
fn verify_certificate(
&self,
end_entity: &pki_types::CertificateDer<'_>,
intermediates: &[pki_types::CertificateDer<'_>],
server_name: &str,
ocsp_response: Option<&[u8]>,
now: pki_types::UnixTime,
) -> Result<(), TlsError> {
let certificates: Vec<SecCertificate> = std::iter::once(end_entity.as_ref())
.chain(intermediates.iter().map(|cert| cert.as_ref()))
.map(|cert| {
SecCertificate::from_der(cert)
.map_err(|_| TlsError::InvalidCertificate(CertificateError::BadEncoding))
})
.collect::<Result<Vec<SecCertificate>, _>>()?;
// Create our verification policy suitable for verifying TLS chains.
// This uses the "default" verification engine and parameters, the same as Windows.
//
// The protocol side should be set to `server` for a client to verify server TLS
// certificates.
//
// The server name will be required to match what the end-entity certificate reports
//
// Ref: https://developer.apple.com/documentation/security/1392592-secpolicycreatessl
let policy = SecPolicy::create_ssl(SslProtocolSide::SERVER, Some(server_name));
// Create our trust evaluation context/chain.
//
// Apple requires that the certificate to be verified is always first in the array, and we
// always place the end-entity certificate at the start.
//
// Ref: https://developer.apple.com/documentation/security/1401555-sectrustcreatewithcertificates
let mut trust_evaluation = SecTrust::create_with_certificates(&certificates, &[policy])
.map_err(|e| TlsError::General(e.to_string()))?;
// Tell the system that we want to consider the certificates evaluation at the point
// in time that `rustls` provided.
let now = system_time_to_cfdate(now)?;
trust_evaluation
.set_trust_verify_date(&now)
.map_err(|e| invalid_certificate(e.to_string()))?;
// If we have OCSP response data, make sure the system makes use of it.
if let Some(ocsp_response) = ocsp_response {
trust_evaluation
.set_trust_ocsp_response(std::iter::once(ocsp_response))
.map_err(|e| invalid_certificate(e.to_string()))?;
}
#[cfg(not(any(test, feature = "ffi-testing", feature = "dbg")))]
let extra_roots = self.extra_roots.as_slice();
#[cfg(any(test, feature = "ffi-testing", feature = "dbg"))]
let extra_roots: Vec<_> = self
.extra_roots
.iter()
.chain(self.test_only_root_ca_override.as_ref())
.cloned()
.collect();
#[cfg(any(test, feature = "ffi-testing", feature = "dbg"))]
let extra_roots = extra_roots.as_slice();
// If any extra roots were provided by the user (or tests), provide them to the trust
// evaluation regardless of their system trust settings or status.
if !extra_roots.is_empty() {
trust_evaluation
.set_anchor_certificates(extra_roots)
.map_err(|e| TlsError::Other(OtherError(Arc::new(e))))?;
// We want to trust both the system-installed and the extra roots. This must be set
// since calling `SecTrustSetAnchorCertificates` "disables the trusting of any
// anchors other than the ones specified by this function call" by default.
trust_evaluation
.set_trust_anchor_certificates_only(false)
.map_err(|e| TlsError::Other(OtherError(Arc::new(e))))?;
}
// When testing, support using fake roots and ignoring default roots present on the system for
// consistency/reproducibility reasons.
//
// XXX: This does not currently limit revocation from fetching information online, or prevent
// the downloading of root CAs.
#[cfg(any(test, feature = "ffi-testing", feature = "dbg"))]
{
if self.test_only_root_ca_override.is_some() {
// XXX: The test root was already provided to the trust evaluation as an extra root.
// We only need to stop use of the default system-installed roots.
// As per [Apple's docs], building and verifying a certificate chain will
// search through the system and keychain to find certificates that it
// needs to try and construct a trust chain back to the root.
//
// `SecTrustSetAnchorCertificatesOnly` must be called after setting custom
// anchor certificates, which "disables trusting any other anchors than the ones passed in
// with the `SecTrustSetAnchorCertificates` function".
//
// [Apple's docs]: https://developer.apple.com/documentation/security/certificate_key_and_trust_services/trust/creating_a_trust_object
trust_evaluation
.set_trust_anchor_certificates_only(true)
.expect("failed to tell trust to only use provided anchors");
}
}
let trust_error = match trust_evaluation.evaluate_with_error() {
Ok(()) => return Ok(()),
Err(e) => e,
};
let err_code = trust_error.code();
let err = err_code
.try_into()
.map_err(|_| ())
.and_then(|code| {
// Only map the errors we need for tests.
match code {
errors::errSecHostNameMismatch => Ok(TlsError::InvalidCertificate(
CertificateError::NotValidForName,
)),
errors::errSecCreateChainFailed => Ok(TlsError::InvalidCertificate(
CertificateError::UnknownIssuer,
)),
errors::errSecInvalidExtendedKeyUsage => Ok(TlsError::InvalidCertificate(
CertificateError::Other(OtherError(Arc::new(super::EkuError))),
)),
errors::errSecCertificateRevoked => {
Ok(TlsError::InvalidCertificate(CertificateError::Revoked))
}
_ => Err(()),
}
})
// Fallback to an error containing the description and specific error code so that
// the exact error cause can be looked up easily.
.unwrap_or_else(|_| invalid_certificate(format!("{trust_error}: {err_code}")));
Err(err)
}
}
#[cfg_attr(docsrs, doc(cfg(all())))]
impl ServerCertVerifier for Verifier {
fn verify_server_cert(
&self,
end_entity: &pki_types::CertificateDer<'_>,
intermediates: &[pki_types::CertificateDer<'_>],
server_name: &pki_types::ServerName,
ocsp_response: &[u8],
now: pki_types::UnixTime,
) -> Result<rustls::client::danger::ServerCertVerified, TlsError> {
log_server_cert(end_entity);
// Convert IP addresses to name strings to ensure match check on leaf certificate.
// Ref: https://developer.apple.com/documentation/security/1392592-secpolicycreatessl
let server = server_name.to_str();
let ocsp_data = if !ocsp_response.is_empty() {
Some(ocsp_response)
} else {
None
};
match self.verify_certificate(end_entity, intermediates, &server, ocsp_data, now) {
Ok(()) => Ok(rustls::client::danger::ServerCertVerified::assertion()),
Err(e) => {
// This error only tells us what the system errored with, so it doesn't leak anything
// sensitive.
log::error!("failed to verify TLS certificate: {}", e);
Err(e)
}
}
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &pki_types::CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, TlsError> {
verify_tls12_signature(
message,
cert,
dss,
&self.crypto_provider.signature_verification_algorithms,
)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &pki_types::CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, TlsError> {
verify_tls13_signature(
message,
cert,
dss,
&self.crypto_provider.signature_verification_algorithms,
)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.crypto_provider
.signature_verification_algorithms
.supported_schemes()
}
}
+86
View File
@@ -0,0 +1,86 @@
#[cfg(any(windows, target_vendor = "apple"))]
use std::sync::Arc;
#[cfg(all(
any(unix, target_arch = "wasm32"),
not(target_os = "android"),
not(target_vendor = "apple"),
))]
mod others;
#[cfg(all(
any(unix, target_arch = "wasm32"),
not(target_os = "android"),
not(target_vendor = "apple"),
))]
pub use others::Verifier;
#[cfg(target_vendor = "apple")]
mod apple;
#[cfg(target_vendor = "apple")]
pub use apple::Verifier;
#[cfg(target_os = "android")]
pub(crate) mod android;
#[cfg(target_os = "android")]
pub use android::Verifier;
#[cfg(windows)]
mod windows;
#[cfg(windows)]
pub use windows::Verifier;
/// An EKU was invalid for the use case of verifying a server certificate.
///
/// This error is used primarily for tests.
#[cfg_attr(windows, allow(dead_code))] // not used by windows verifier
#[derive(Debug, PartialEq)]
pub(crate) struct EkuError;
impl std::fmt::Display for EkuError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("certificate had invalid extensions")
}
}
impl std::error::Error for EkuError {}
// Log the certificate we are verifying so that we can try and find what may be wrong with it
// if we need to debug a user's situation.
fn log_server_cert(_end_entity: &rustls::pki_types::CertificateDer<'_>) {
#[cfg(feature = "cert-logging")]
{
use base64::Engine;
log::debug!(
"verifying certificate: {}",
base64::engine::general_purpose::STANDARD.encode(_end_entity.as_ref())
);
}
}
// Unknown certificate error shorthand. Used when we need to construct an "Other" certificate
// error with a platform specific error message.
#[cfg(any(windows, target_vendor = "apple"))]
fn invalid_certificate(reason: impl Into<String>) -> rustls::Error {
rustls::Error::InvalidCertificate(rustls::CertificateError::Other(rustls::OtherError(
Arc::from(Box::from(reason.into())),
)))
}
/// List of EKUs that one or more of that *must* be in the end-entity certificate.
///
/// Legacy server-gated crypto OIDs are assumed to no longer be in use.
///
/// Currently supported:
/// - id-kp-serverAuth
// TODO: Chromium also allows for `OID_ANY_EKU` on Android.
#[cfg(target_os = "windows")]
// XXX: Windows requires that we NUL terminate EKU strings.
// See https://github.com/rustls/rustls-platform-verifier/issues/126#issuecomment-2306232794.
const ALLOWED_EKUS: &[windows_sys::core::PCSTR] =
&[windows_sys::Win32::Security::Cryptography::szOID_PKIX_KP_SERVER_AUTH];
#[cfg(target_os = "android")]
pub const ALLOWED_EKUS: &[&std::ffi::CStr] = &[c"1.3.6.1.5.5.7.3.1"];
@@ -0,0 +1,187 @@
use std::fmt::Debug;
use std::sync::Arc;
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::client::WebPkiServerVerifier;
use rustls::pki_types;
use rustls::{
crypto::CryptoProvider, CertificateError, DigitallySignedStruct, Error as TlsError, OtherError,
SignatureScheme,
};
use super::log_server_cert;
/// A TLS certificate verifier that uses the system's root store and WebPKI.
#[derive(Debug)]
pub struct Verifier {
// We currently keep one set of certificates per-verifier so that
// recreating the verifier will pull fresh root certificates from disk,
// picking up on any changes that might have been made since.
inner: Arc<WebPkiServerVerifier>,
}
impl Verifier {
/// Creates a new verifier whose certificate validation is provided by
/// WebPKI, using root certificates provided by the platform.
#[cfg_attr(docsrs, doc(cfg(all())))]
pub fn new(crypto_provider: Arc<CryptoProvider>) -> Result<Self, TlsError> {
Self::new_inner([], None, crypto_provider)
}
/// Creates a new verifier whose certificate validation is provided by
/// WebPKI, using root certificates provided by the platform and augmented by
/// the provided extra root certificates.
#[cfg_attr(docsrs, doc(cfg(not(target_os = "android"))))]
pub fn new_with_extra_roots(
extra_roots: impl IntoIterator<Item = pki_types::CertificateDer<'static>>,
crypto_provider: Arc<CryptoProvider>,
) -> Result<Self, TlsError> {
Self::new_inner(extra_roots, None, crypto_provider)
}
/// Creates a test-only TLS certificate verifier which trusts our fake root CA cert.
#[cfg(any(test, feature = "ffi-testing", feature = "dbg"))]
pub(crate) fn new_with_fake_root(
root: pki_types::CertificateDer<'static>,
crypto_provider: Arc<CryptoProvider>,
) -> Self {
Self::new_inner([], Some(root), crypto_provider)
.expect("failed to create verifier with fake root")
}
/// Creates a new verifier whose certificate validation is provided by
/// WebPKI, using root certificates provided by the platform and augmented by
/// the provided extra root certificates.
fn new_inner(
extra_roots: impl IntoIterator<Item = pki_types::CertificateDer<'static>>,
#[allow(unused)] // test_root is only used in tests
test_root: Option<pki_types::CertificateDer<'static>>,
crypto_provider: Arc<CryptoProvider>,
) -> Result<Self, TlsError> {
let mut root_store = rustls::RootCertStore::empty();
// For testing only: load fake root cert, instead of native/WebPKI roots
#[cfg(any(test, feature = "ffi-testing", feature = "dbg"))]
{
if let Some(test_root) = test_root {
root_store.add(test_root)?;
return Ok(Self {
inner: WebPkiServerVerifier::builder_with_provider(
root_store.into(),
crypto_provider.clone(),
)
.build()
.map_err(|e| TlsError::Other(OtherError(Arc::new(e))))?,
});
}
}
// While we ignore invalid certificates from the system, we forward errors from
// parsing the extra roots to the caller.
for cert in extra_roots {
root_store.add(cert)?;
}
#[cfg(all(
unix,
not(target_os = "android"),
not(target_vendor = "apple"),
not(target_arch = "wasm32"),
))]
{
let result = rustls_native_certs::load_native_certs();
let (added, ignored) = root_store.add_parsable_certificates(result.certs);
if ignored > 0 {
log::warn!("{ignored} platform CA root certificates were ignored due to errors");
}
for error in result.errors {
log::warn!("Error loading CA root certificate: {error}");
}
// Don't return an error if this fails when other roots have already been loaded via
// `new_with_extra_roots`. It leads to extra failure cases where connections would otherwise still work.
if root_store.is_empty() {
return Err(rustls::Error::General(
"No CA certificates were loaded from the system".to_owned(),
));
} else {
log::debug!("Loaded {added} CA root certificates from the system");
}
}
#[cfg(target_arch = "wasm32")]
{
root_store.add_parsable_certificates(
webpki_root_certs::TLS_SERVER_ROOT_CERTS.iter().cloned(),
);
};
Ok(Self {
inner: WebPkiServerVerifier::builder_with_provider(
root_store.into(),
crypto_provider.clone(),
)
.build()
.map_err(|e| TlsError::Other(OtherError(Arc::new(e))))?,
})
}
}
#[cfg_attr(docsrs, doc(cfg(all())))]
impl ServerCertVerifier for Verifier {
fn verify_server_cert(
&self,
end_entity: &pki_types::CertificateDer<'_>,
intermediates: &[pki_types::CertificateDer<'_>],
server_name: &pki_types::ServerName,
ocsp_response: &[u8],
now: pki_types::UnixTime,
) -> Result<ServerCertVerified, TlsError> {
log_server_cert(end_entity);
self.inner
.verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)
.map_err(map_webpki_errors)
// This only contains information from the system or other public
// bits of the TLS handshake, so it can't leak anything.
.map_err(|e| {
log::error!("failed to verify TLS certificate: {}", e);
e
})
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &pki_types::CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, TlsError> {
self.inner.verify_tls12_signature(message, cert, dss)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &pki_types::CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, TlsError> {
self.inner.verify_tls13_signature(message, cert, dss)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.inner.supported_verify_schemes()
}
}
fn map_webpki_errors(err: TlsError) -> TlsError {
match &err {
TlsError::InvalidCertificate(CertificateError::InvalidPurpose)
| TlsError::InvalidCertificate(CertificateError::InvalidPurposeContext { .. }) => {
TlsError::InvalidCertificate(CertificateError::Other(OtherError(Arc::new(
super::EkuError,
))))
}
_ => err,
}
}
@@ -0,0 +1,792 @@
//! `Verifier` implementation for Windows targets.
//!
//! The design of the rustls-native-certs crate for Windows doesn't work
//! completely enough. In general it is hard to emulate enough of what
//! Windows does to be compatible with all users' configurations, especially
//! when corporate MitM proxies or custom CAs or complex trust policies are
//! used. Instead, delegate to Windows's own certificate validation engine
//! directly.
//!
//! This implementation was modeled on:
//! * Chromium's [cert_verify_proc_win.cc] and [x509_util_win.cc]
//! * Golang's [root_windows.go]
//! * [Microsoft's Documentation] and [Microsoft's Example]
//!
//! [cert_verify_proc_win.cc]: <https://chromium.googlesource.com/chromium/src/net/+/refs/heads/main/cert/cert_verify_proc_win.cc>
//! [x509_util_win.cc]: <https://chromium.googlesource.com/chromium/src/net/+/refs/heads/main/cert/x509_util_win.cc>
//! [root_windows.go]: <https://github.com/golang/go/blob/master/src/crypto/x509/root_windows.go>
//! [Microsoft's Documentation]: <https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certgetcertificatechain>
//! [Microsoft's Example]: <https://docs.microsoft.com/en-us/windows/win32/seccrypto/example-c-program-creating-a-certificate-chain>
use std::{
convert::TryInto,
mem::{self, MaybeUninit},
os::raw::c_void,
ptr::{self, NonNull},
sync::Arc,
};
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerifier};
use rustls::crypto::{verify_tls12_signature, verify_tls13_signature, CryptoProvider};
use rustls::pki_types;
use rustls::{
CertificateError, DigitallySignedStruct, Error as TlsError, Error::InvalidCertificate,
SignatureScheme,
};
use windows_sys::Win32::{
Foundation::{
CERT_E_CN_NO_MATCH, CERT_E_EXPIRED, CERT_E_INVALID_NAME, CERT_E_UNTRUSTEDROOT,
CERT_E_WRONG_USAGE, CRYPT_E_REVOKED, FILETIME, TRUE,
},
Security::Cryptography::{
CertAddEncodedCertificateToStore, CertCloseStore, CertCreateCertificateChainEngine,
CertFreeCertificateChain, CertFreeCertificateChainEngine, CertFreeCertificateContext,
CertGetCertificateChain, CertOpenStore, CertSetCertificateContextProperty,
CertVerifyCertificateChainPolicy, HTTPSPolicyCallbackData, AUTHTYPE_SERVER,
CERT_CHAIN_CACHE_END_CERT, CERT_CHAIN_CONTEXT,
CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS, CERT_CHAIN_POLICY_PARA,
CERT_CHAIN_POLICY_SSL, CERT_CHAIN_POLICY_STATUS,
CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT, CERT_CHAIN_REVOCATION_CHECK_END_CERT,
CERT_CONTEXT, CERT_OCSP_RESPONSE_PROP_ID, CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG,
CERT_STORE_ADD_ALWAYS, CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, CERT_STORE_PROV_MEMORY,
CERT_STRONG_SIGN_PARA, CERT_TRUST_IS_PARTIAL_CHAIN, CERT_TRUST_IS_UNTRUSTED_ROOT,
CERT_USAGE_MATCH, CRYPT_INTEGER_BLOB, CTL_USAGE, HCERTSTORE, USAGE_MATCH_TYPE_AND,
X509_ASN_ENCODING,
},
};
use super::{log_server_cert, ALLOWED_EKUS};
// The `windows-sys` definition for `CERT_CHAIN_PARA` does not take old OS versions
// into account so we define it ourselves for better OS backwards compat.
// In the future a compile-time size assertion can be added against the upstream type to help stay in sync.
#[allow(non_camel_case_types, non_snake_case)]
#[repr(C)]
struct CERT_CHAIN_PARA {
pub cbSize: u32,
pub RequestedUsage: CERT_USAGE_MATCH,
pub RequestedIssuancePolicy: CERT_USAGE_MATCH,
pub dwUrlRetrievalTimeout: u32,
pub fCheckRevocationFreshnessTime: i32, // BOOL
pub dwRevocationFreshnessTime: u32,
pub pftCacheResync: *mut FILETIME,
// XXX: `pStrongSignPara` and `dwStrongSignFlags` might or might not be defined on the current system. It started
// being available in Windows 8. See https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-cert_chain_para
#[cfg(not(target_vendor = "win7"))]
pub pStrongSignPara: *const CERT_STRONG_SIGN_PARA,
#[cfg(not(target_vendor = "win7"))]
pub dwStrongSignFlags: u32,
}
// Same workaround with CERT_CHAIN_PARA
#[allow(non_camel_case_types, non_snake_case)]
#[repr(C)]
#[derive(Clone, Copy)]
pub struct CERT_CHAIN_ENGINE_CONFIG {
pub cbSize: u32,
pub hRestrictedRoot: HCERTSTORE,
pub hRestrictedTrust: HCERTSTORE,
pub hRestrictedOther: HCERTSTORE,
pub cAdditionalStore: u32,
pub rghAdditionalStore: *mut HCERTSTORE,
pub dwFlags: u32,
pub dwUrlRetrievalTimeout: u32,
pub MaximumCachedCertificates: u32,
pub CycleDetectionModulus: u32,
pub hExclusiveRoot: HCERTSTORE,
pub hExclusiveTrustedPeople: HCERTSTORE,
// XXX: `dwExclusiveFlags` started being available in Windows 8 and Windows Server 2012
// See https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-cert_chain_engine_config
#[cfg(not(target_vendor = "win7"))]
pub dwExclusiveFlags: u32,
}
use crate::verification::invalid_certificate;
// SAFETY: see method implementation
unsafe impl ZeroedWithSize for CERT_CHAIN_PARA {
fn zeroed_with_size() -> Self {
// SAFETY: `CERT_CHAIN_PARA` only contains pointers and integers, which are safe to zero.
// Additionally, MSDN states you *MUST* zero all unused fields.
let mut new: Self = unsafe { mem::zeroed() };
new.cbSize = Self::SIZE;
new
}
}
// SAFETY: see method implementation
unsafe impl ZeroedWithSize for HTTPSPolicyCallbackData {
fn zeroed_with_size() -> Self {
// SAFETY: zeroed is needed here since it contains a union.
let mut new: Self = unsafe { mem::zeroed() };
new.Anonymous.cbSize = Self::SIZE;
new
}
}
// SAFETY: see method implementation
unsafe impl ZeroedWithSize for CERT_CHAIN_POLICY_PARA {
fn zeroed_with_size() -> Self {
// SAFETY: This structure only contains integers and pointers.
let mut new: Self = unsafe { mem::zeroed() };
new.cbSize = Self::SIZE;
new
}
}
// SAFETY: see method implementation
unsafe impl ZeroedWithSize for CERT_CHAIN_ENGINE_CONFIG {
fn zeroed_with_size() -> Self {
// SAFETY: This structure only contains integers and pointers.
let mut new: Self = unsafe { mem::zeroed() };
new.cbSize = Self::SIZE;
new
}
}
struct CertChain {
inner: NonNull<CERT_CHAIN_CONTEXT>,
}
impl CertChain {
fn verify_chain_policy(
&self,
mut server_null_terminated: Vec<u16>,
) -> Result<CERT_CHAIN_POLICY_STATUS, TlsError> {
let mut extra_params = HTTPSPolicyCallbackData::zeroed_with_size();
extra_params.dwAuthType = AUTHTYPE_SERVER;
// `server_null_terminated` outlives `extra_params`.
extra_params.pwszServerName = server_null_terminated.as_mut_ptr();
let mut params = CERT_CHAIN_POLICY_PARA::zeroed_with_size();
// Ignore any errors when trying to obtain OCSP revocation information.
// This is also done in OpenSSL, Secure Transport from Apple, etc.
params.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
// `extra_params` outlives `params`.
params.pvExtraPolicyPara = NonNull::from(&mut extra_params).cast::<c_void>().as_ptr();
let mut status: MaybeUninit<CERT_CHAIN_POLICY_STATUS> = MaybeUninit::uninit();
// SAFETY: The certificate chain is non-null, `params` is valid for reads, and its valid to write to `status`.
let res = unsafe {
CertVerifyCertificateChainPolicy(
CERT_CHAIN_POLICY_SSL,
self.inner.as_ptr(),
&params,
status.as_mut_ptr(),
)
};
// This should rarely, if ever, be false since it would imply no TLS verification
// is currently possible on the system: https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certverifycertificatechainpolicy#return-value
if res != TRUE {
return Err(TlsError::General(String::from(
"TLS certificate verification was unavailable on the system!",
)));
}
// SAFETY: The verification call was checked to have succeeded, so the status
// is written correctly and initialized.
let status = unsafe { status.assume_init() };
Ok(status)
}
}
impl Drop for CertChain {
fn drop(&mut self) {
// SAFETY: The pointer is guaranteed to be non-null.
unsafe { CertFreeCertificateChain(self.inner.as_ptr()) }
}
}
/// A representation of a certificate.
///
/// The `CertificateStore` must be opened with the correct flags to ensure the
/// certificate may outlive it; see the `CertificateStore` documentation.
struct Certificate {
inner: NonNull<CERT_CONTEXT>,
}
impl Certificate {
/// Sets the specified property of this certificate context.
///
/// ### Safety
/// `prop_data` must be a valid pointer for the property type.
unsafe fn set_property(
&mut self,
prop_id: u32,
prop_data: *const c_void,
) -> Result<(), TlsError> {
// SAFETY: `cert` points to a valid certificate context and the OCSP data is valid to read.
call_with_last_error(|| {
(CertSetCertificateContextProperty(
self.inner.as_ptr(),
prop_id,
CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG,
prop_data,
) == TRUE)
.then_some(())
})
}
}
impl Drop for Certificate {
fn drop(&mut self) {
// SAFETY: The certificate context is non-null and points to a valid location.
unsafe { CertFreeCertificateContext(self.inner.as_ptr()) };
}
}
#[derive(Debug)]
struct CertEngine {
inner: NonNull<c_void>, // HCERTENGINECONTEXT
}
impl CertEngine {
fn new_with_extra_roots(
roots: impl IntoIterator<Item = pki_types::CertificateDer<'static>>,
) -> Result<Self, TlsError> {
let mut exclusive_store = CertificateStore::new()?;
for root in roots {
exclusive_store.add_cert(&root)?;
}
let mut config = CERT_CHAIN_ENGINE_CONFIG::zeroed_with_size();
config.hExclusiveRoot = exclusive_store.inner.as_ptr();
let mut engine = EnginePtr::NULL;
// XXX: Due to the redefinition of `CERT_CHAIN_ENGINE_CONFIG`, we need to do pointer casts
// in order to pass our expanded structure into `CertCreateCertificateChainEngine`.
// See also `CERT_CHAIN_PARA` casting below.
let config = NonNull::from(&config).cast().as_ptr();
// SAFETY: `engine` is valid to be written to and the config is valid to be read.
let res = unsafe { CertCreateCertificateChainEngine(config, &mut engine) };
#[allow(clippy::as_conversions)]
let engine = call_with_last_error(|| match NonNull::new(engine as *mut c_void) {
Some(c) if res == TRUE => Some(c),
_ => None,
})?;
Ok(Self { inner: engine })
}
#[cfg(any(test, feature = "ffi-testing", feature = "dbg"))]
fn new_with_fake_root(root: &[u8]) -> Result<Self, TlsError> {
use windows_sys::Win32::Security::Cryptography::{
CERT_CHAIN_CACHE_ONLY_URL_RETRIEVAL, CERT_CHAIN_ENABLE_CACHE_AUTO_UPDATE,
};
let mut root_store = CertificateStore::new()?;
root_store.add_cert(root)?;
let mut config = CERT_CHAIN_ENGINE_CONFIG::zeroed_with_size();
// We use these flags for the following reasons:
//
// - CERT_CHAIN_CACHE_ONLY_URL_RETRIEVAL is used in an attempt to stop Windows from using the internet to
// fetch anything during the tests, regardless of what test data is used.
//
// - CERT_CHAIN_ENABLE_CACHE_AUTO_UPDATE is used as a minor performance optimization to allow Windows to reuse
// data inside of a test and avoid any extra parsing, etc, it might need to do pulling directly from the store each time.
//
// Ref: https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-cert_chain_engine_config
config.dwFlags = CERT_CHAIN_CACHE_ONLY_URL_RETRIEVAL | CERT_CHAIN_ENABLE_CACHE_AUTO_UPDATE;
config.hExclusiveRoot = root_store.inner.as_ptr();
let mut engine = EnginePtr::NULL;
// Same workaround with as above when creating the engine.
let config = NonNull::from(&config).cast().as_ptr();
// SAFETY: `engine` is valid to be written to and the config is valid to be read.
let res = unsafe { CertCreateCertificateChainEngine(config, &mut engine) };
#[allow(clippy::as_conversions)]
let engine = call_with_last_error(|| match NonNull::new(engine as *mut c_void) {
Some(c) if res == TRUE => Some(c),
_ => None,
})?;
Ok(Self { inner: engine })
}
}
impl Drop for CertEngine {
fn drop(&mut self) {
// SAFETY: The engine pointer is guaranteed to be non-null.
unsafe { CertFreeCertificateChainEngine(EnginePtr::from_raw(self.inner)) };
}
}
// SAFETY: We know no other threads is mutating the `CertEngine`, because it would require `unsafe`.
// Across the FFI, `CertGetCertificateChain` don't mutate it either.
unsafe impl Sync for CertEngine {}
// SAFETY: All methods of `CertEngine`, including `Drop`, are safe to be called from other
// threads, because all contained resources are owned by Windows and we only maintain reference counted handles to them.
unsafe impl Send for CertEngine {}
/// An in-memory Windows certificate store.
///
/// # Safety
///
/// `CertificateStore` creates `Certificate` objects that may outlive the
/// `CertificateStore`. This is only safe to do if the certificate store is
/// constructed with `CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG`.
struct CertificateStore {
inner: NonNull<c_void>, // HCERTSTORE
// In production code, this is always `None`.
//
// During tests, we set this to `Some` as the tests use a
// custom verification engine that only uses specific roots.
engine: Option<CertEngine>, // HCERTENGINECONTEXT
}
impl Drop for CertificateStore {
fn drop(&mut self) {
// SAFETY: See the `CertificateStore` documentation.
unsafe { CertCloseStore(self.inner.as_ptr(), 0) };
}
}
impl CertificateStore {
/// Creates a new, in-memory certificate store.
fn new() -> Result<Self, TlsError> {
let store = call_with_last_error(|| {
// SAFETY: Called with valid constants and result is checked to be non-null.
// The `CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG` flag is critical;
// see the `CertificateStore` documentation for more info.
NonNull::new(unsafe {
CertOpenStore(
CERT_STORE_PROV_MEMORY,
0, // Set to zero since this uses `PROV_MEMORY`.
0, // This field shouldn't be used.
CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG,
ptr::null(),
)
})
})?;
// Use the system's default root store and rules.
Ok(Self {
inner: store,
engine: None,
})
}
#[cfg(any(test, feature = "ffi-testing", feature = "dbg"))]
fn new_with_fake_root(root: &[u8]) -> Result<Self, TlsError> {
let mut inner = Self::new()?;
let mut root_store = CertificateStore::new()?;
root_store.add_cert(root)?;
let engine = CertEngine::new_with_fake_root(root)?;
inner.engine = Some(engine);
Ok(inner)
}
/// Adds the provided certificate to the store.
///
/// The certificate must be encoded as ASN.1 DER.
///
/// Errors if the certificate was malformed and couldn't be added.
fn add_cert(&mut self, cert: &[u8]) -> Result<Certificate, TlsError> {
let mut cert_context: *mut CERT_CONTEXT = ptr::null_mut();
// SAFETY: `inner` is a valid certificate store, and `cert` is a valid a byte array valid
// for reads, the correct length is being provided, and `cert_context` is valid to write to.
let res = unsafe {
CertAddEncodedCertificateToStore(
self.inner.as_ptr(),
X509_ASN_ENCODING,
cert.as_ptr(),
cert.len()
.try_into()
.map_err(|_| InvalidCertificate(CertificateError::BadEncoding))?,
CERT_STORE_ADD_ALWAYS,
&mut cert_context,
)
};
// SAFETY: Constructing a `Certificate` is only safe if the store was
// created with the right flags; see the `CertificateStore` docs.
match (res, NonNull::new(cert_context)) {
(TRUE, Some(cert)) => Ok(Certificate { inner: cert }),
_ => Err(InvalidCertificate(CertificateError::BadEncoding)),
}
}
fn new_chain_in(
&self,
certificate: &Certificate,
now: pki_types::UnixTime,
engine: Option<&CertEngine>,
) -> Result<CertChain, TlsError> {
let mut cert_chain = ptr::null_mut();
let mut parameters = CERT_CHAIN_PARA::zeroed_with_size();
#[allow(clippy::as_conversions)]
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/ns-wincrypt-cert_usage_match
let usage = CERT_USAGE_MATCH {
dwType: USAGE_MATCH_TYPE_AND,
Usage: CTL_USAGE {
cUsageIdentifier: ALLOWED_EKUS.len() as u32,
rgpszUsageIdentifier: ALLOWED_EKUS.as_ptr() as *mut windows_sys::core::PSTR,
},
};
parameters.RequestedUsage = usage;
#[allow(clippy::as_conversions)]
let time = {
/// Seconds between Jan 1st, 1601 and Jan 1, 1970.
const UNIX_ADJUSTMENT: std::time::Duration =
std::time::Duration::from_secs(11_644_473_600);
let since_unix_epoch = now.as_secs();
// Convert the duration from the UNIX epoch to the Window one, and then convert
// the result into a `FILETIME` structure.
let since_windows_epoch = since_unix_epoch + UNIX_ADJUSTMENT.as_secs();
let intervals = (since_windows_epoch * 1_000_000_000) / 100;
FILETIME {
dwLowDateTime: (intervals & u32::MAX as u64) as u32,
dwHighDateTime: (intervals >> 32) as u32,
}
};
// `CERT_CHAIN_REVOCATION_CHECK_END_CERT` only checks revocation for end cert. See the crate's revocation documentation
// for more details.
// `CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT` accumulates network retrievals timeouts
// to limit network time and improve performance.
// `CERT_CHAIN_CACHE_END_CERT` speeds up the common case of multiple connections to same server.
const FLAGS: u32 = CERT_CHAIN_REVOCATION_CHECK_END_CERT
| CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT
| CERT_CHAIN_CACHE_END_CERT;
// Lowering URL retrieval timeout from default 15s to 10s to account for higher internet speeds
parameters.dwUrlRetrievalTimeout = 10 * 1000; // milliseconds
// SAFETY: `cert` points to a valid certificate context, parameters is valid for reads, `cert_chain` is valid
// for writes, and the certificate store is valid and initialized.
let res = unsafe {
// XXX: Due to the redefinition of `CERT_CHAIN_PARA`, we need to do pointer casts
// in order to pass our expanded structure into `CertGetCertificateChain`.
// This is safe because the OS uses `cbSize` to know if the extra parameters
// are present or not. As we set `cbSize` correctly, the fields can be read from correctly.
let parameters = NonNull::from(&parameters).cast().as_ptr();
CertGetCertificateChain(
match engine {
Some(eng) => EnginePtr::from_raw(eng.inner),
None => EnginePtr::NULL,
},
certificate.inner.as_ptr(),
&time,
self.inner.as_ptr(),
parameters,
FLAGS,
ptr::null_mut(),
&mut cert_chain,
)
};
// XXX: Windows will internally map the chain's `TrustStatus.dwErrorStatus` to a `dwError` when
// a chain policy is verified, so we only check for errors there.
call_with_last_error(|| match NonNull::new(cert_chain) {
Some(c) if res == TRUE => Some(CertChain { inner: c }),
_ => None,
})
}
}
// `windows-sys` >= 0.60
impl EnginePtr for *mut c_void {
fn from_raw(val: NonNull<c_void>) -> Self {
val.as_ptr()
}
const NULL: Self = ptr::null_mut();
}
// `windows-sys` 0.52-0.59
impl EnginePtr for isize {
#[allow(clippy::as_conversions)]
fn from_raw(val: NonNull<c_void>) -> Self {
val.as_ptr() as isize
}
const NULL: Self = 0;
}
/// An abstraction trait over the different ways various `windows-sys` versions represent
/// the type of `HCERTCHAINENGINE`.
trait EnginePtr: Sized {
fn from_raw(val: NonNull<c_void>) -> Self;
const NULL: Self;
}
fn call_with_last_error<T, F: FnMut() -> Option<T>>(mut call: F) -> Result<T, TlsError> {
if let Some(res) = call() {
Ok(res)
} else {
Err(TlsError::General(
std::io::Error::last_os_error().to_string(),
))
}
}
/// A TLS certificate verifier that utilizes the Windows certificate facilities.
#[derive(Debug)]
pub struct Verifier {
/// Testing only: The root CA certificate to trust.
#[cfg(any(test, feature = "ffi-testing", feature = "dbg"))]
test_only_root_ca_override: Option<pki_types::CertificateDer<'static>>,
crypto_provider: Arc<CryptoProvider>,
/// Extra trust anchors to add to the verifier above and beyond those provided by
/// the system-provided trust stores.
extra_roots: Option<CertEngine>,
}
impl Verifier {
/// Creates a new instance of a TLS certificate verifier that utilizes the
/// Windows certificate facilities.
#[cfg_attr(docsrs, doc(cfg(all())))]
pub fn new(crypto_provider: Arc<CryptoProvider>) -> Result<Self, TlsError> {
Ok(Self {
#[cfg(any(test, feature = "ffi-testing", feature = "dbg"))]
test_only_root_ca_override: None,
crypto_provider,
extra_roots: None,
})
}
/// Creates a new instance of a TLS certificate verifier that utilizes the
/// Windows certificate facilities and augmented by the provided extra root certificates.
#[cfg_attr(docsrs, doc(cfg(not(target_os = "android"))))]
pub fn new_with_extra_roots(
roots: impl IntoIterator<Item = pki_types::CertificateDer<'static>>,
crypto_provider: Arc<CryptoProvider>,
) -> Result<Self, TlsError> {
let cert_engine = CertEngine::new_with_extra_roots(roots)?;
Ok(Self {
#[cfg(any(test, feature = "ffi-testing", feature = "dbg"))]
test_only_root_ca_override: None,
crypto_provider,
extra_roots: Some(cert_engine),
})
}
/// Creates a test-only TLS certificate verifier which trusts our fake root CA cert.
#[cfg(any(test, feature = "ffi-testing", feature = "dbg"))]
pub(crate) fn new_with_fake_root(
root: pki_types::CertificateDer<'static>,
crypto_provider: Arc<CryptoProvider>,
) -> Self {
Self {
test_only_root_ca_override: Some(root),
crypto_provider,
extra_roots: None,
}
}
/// Verifies a certificate and its chain for the specified `server`.
///
/// Return `Ok(())` if the certificate was valid.
fn verify_certificate(
&self,
primary_cert: &[u8],
intermediate_certs: &[&[u8]],
server: &[u8],
ocsp_data: Option<&[u8]>,
now: pki_types::UnixTime,
) -> Result<(), TlsError> {
#[cfg(any(test, feature = "ffi-testing", feature = "dbg"))]
let mut store = match self.test_only_root_ca_override.as_ref() {
Some(test_only_root_ca_override) => {
CertificateStore::new_with_fake_root(test_only_root_ca_override)?
}
None => CertificateStore::new()?,
};
#[cfg(not(any(test, feature = "ffi-testing", feature = "dbg")))]
let mut store = CertificateStore::new()?;
let mut primary_cert = store.add_cert(primary_cert)?;
for cert in intermediate_certs.iter().copied() {
store.add_cert(cert)?;
}
if let Some(ocsp_data) = ocsp_data {
#[allow(clippy::as_conversions)]
let data = CRYPT_INTEGER_BLOB {
cbData: ocsp_data.len().try_into().map_err(|_| {
invalid_certificate("Malformed OCSP response stapled to server certificate")
})?,
pbData: ocsp_data.as_ptr() as *mut u8,
};
// SAFETY: `data` is a valid pointer and matches the property ID.
unsafe {
primary_cert.set_property(
CERT_OCSP_RESPONSE_PROP_ID,
NonNull::from(&data).cast::<c_void>().as_ptr(),
)?;
}
}
// Encode UTF-16, null-terminated
let server: Vec<u16> = server
.iter()
.map(|c| u16::from(*c))
.chain(Some(0))
.collect();
let mut cert_chain = store.new_chain_in(&primary_cert, now, store.engine.as_ref())?;
// We only use `TrustStatus` here because it hasn't had verification performed on it.
// SAFETY: The pointer is guaranteed to be non-null.
let cert_error_status = unsafe { *cert_chain.inner.as_ptr() }
.TrustStatus
.dwErrorStatus;
let extra_roots_may_needed =
(cert_error_status & (CERT_TRUST_IS_PARTIAL_CHAIN | CERT_TRUST_IS_UNTRUSTED_ROOT)) != 0;
// If we have extra roots and building the chain gave us an error, we try to build a
// new one with the extra roots.
if extra_roots_may_needed && self.extra_roots.is_some() {
let mut store = CertificateStore::new()?;
for cert in intermediate_certs.iter().copied() {
store.add_cert(cert)?;
}
cert_chain = store.new_chain_in(&primary_cert, now, self.extra_roots.as_ref())?;
}
let status = cert_chain.verify_chain_policy(server)?;
if status.dwError == 0 {
return Ok(());
}
// Only map the errors we have tests for.
#[allow(clippy::as_conversions)]
let win_error = status.dwError as i32;
Err(match win_error {
CERT_E_CN_NO_MATCH | CERT_E_INVALID_NAME => {
InvalidCertificate(CertificateError::NotValidForName)
}
CRYPT_E_REVOKED => InvalidCertificate(CertificateError::Revoked),
CERT_E_EXPIRED => InvalidCertificate(CertificateError::Expired),
CERT_E_UNTRUSTEDROOT => InvalidCertificate(CertificateError::UnknownIssuer),
CERT_E_WRONG_USAGE => InvalidCertificate(CertificateError::InvalidPurpose),
error_num => {
let err = std::io::Error::from_raw_os_error(error_num);
// The included error message has both the description and raw OS error code.
invalid_certificate(err.to_string())
}
})
}
}
#[cfg_attr(docsrs, doc(cfg(all())))]
impl ServerCertVerifier for Verifier {
fn verify_server_cert(
&self,
end_entity: &pki_types::CertificateDer<'_>,
intermediates: &[pki_types::CertificateDer<'_>],
server_name: &pki_types::ServerName,
ocsp_response: &[u8],
now: pki_types::UnixTime,
) -> Result<rustls::client::danger::ServerCertVerified, TlsError> {
log_server_cert(end_entity);
let name = server_name.to_str();
let intermediate_certs: Vec<&[u8]> = intermediates.iter().map(|c| c.as_ref()).collect();
let ocsp_data = if !ocsp_response.is_empty() {
Some(ocsp_response)
} else {
None
};
match self.verify_certificate(
end_entity.as_ref(),
&intermediate_certs,
name.as_bytes(),
ocsp_data,
now,
) {
Ok(()) => Ok(rustls::client::danger::ServerCertVerified::assertion()),
Err(e) => {
// SAFETY:
// Errors are our own custom errors, WinAPI errors, or static strings.
log::error!("failed to verify TLS certificate: {}", e);
Err(e)
}
}
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &pki_types::CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, TlsError> {
verify_tls12_signature(
message,
cert,
dss,
&self.crypto_provider.signature_verification_algorithms,
)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &pki_types::CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, TlsError> {
verify_tls13_signature(
message,
cert,
dss,
&self.crypto_provider.signature_verification_algorithms,
)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.crypto_provider
.signature_verification_algorithms
.supported_schemes()
}
}
/// A trait to represent an object that can be safely created with all zero values
/// and have a size assigned to it.
///
/// # Safety
///
/// This has the same safety requirements as [std::mem::zeroed].
unsafe trait ZeroedWithSize: Sized {
const SIZE: u32 = {
let size = core::mem::size_of::<Self>();
// NB: `TryInto` isn't stable in const yet.
#[allow(clippy::as_conversions)]
if size <= u32::MAX as usize {
size as u32
} else {
panic!("structure was larger then DWORD")
}
};
/// Returns a zeroed structure with its structure size (`cbSize`) field set to the correct value.
fn zeroed_with_size() -> Self;
}