Skip to content

Allow passing around user data inside a Policy object. #12387

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/rust/cryptography-x509-verification/src/certificate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ Xw4nMqk=
type Key = ();
type Err = ();
type CertificateExtra = ();
type PolicyExtra = ();

fn public_key(&self, _cert: &Certificate<'_>) -> Result<Self::Key, Self::Err> {
// Simulate failing to retrieve a public key.
Expand Down
3 changes: 3 additions & 0 deletions src/rust/cryptography-x509-verification/src/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ pub trait CryptoOps {
/// Extra data that's passed around with the certificate.
type CertificateExtra;

/// Extra data that's accessible alongside the PolicyDefinition.
type PolicyExtra;

/// Extracts the public key from the given `Certificate` in
/// a `Key` format known by the cryptographic backend, or `None`
/// if the key is malformed.
Expand Down
17 changes: 11 additions & 6 deletions src/rust/cryptography-x509-verification/src/policy/extension.rs
Original file line number Diff line number Diff line change
Expand Up @@ -552,7 +552,7 @@ mod tests {
use crate::certificate::tests::PublicKeyErrorOps;
use crate::ops::tests::{cert, v1_cert_pem};
use crate::ops::CryptoOps;
use crate::policy::{Policy, Subject, ValidationResult};
use crate::policy::{Policy, PolicyDefinition, Subject, ValidationResult};
use crate::types::DNSName;

#[test]
Expand Down Expand Up @@ -602,12 +602,13 @@ mod tests {
let cert_pem = v1_cert_pem();
let cert = cert(&cert_pem);
let ops = PublicKeyErrorOps {};
let policy = Policy::server(
let policy_def = PolicyDefinition::server(
ops,
Subject::DNS(DNSName::new("example.com").unwrap()),
epoch(),
None,
);
let policy = Policy::new(&policy_def, ());

// Test a policy that stipulates that a given extension MUST be present.
let extension_validator =
Expand Down Expand Up @@ -642,12 +643,13 @@ mod tests {
let cert_pem = v1_cert_pem();
let cert = cert(&cert_pem);
let ops = PublicKeyErrorOps {};
let policy = Policy::server(
let policy_def = PolicyDefinition::server(
ops,
Subject::DNS(DNSName::new("example.com").unwrap()),
epoch(),
None,
);
let policy = Policy::new(&policy_def, ());

// Test a validator that stipulates that a given extension CAN be present.
let extension_validator = ExtensionValidator::maybe_present(
Expand Down Expand Up @@ -676,12 +678,13 @@ mod tests {
let cert_pem = v1_cert_pem();
let cert = cert(&cert_pem);
let ops = PublicKeyErrorOps {};
let policy = Policy::server(
let policy_def = PolicyDefinition::server(
ops,
Subject::DNS(DNSName::new("example.com").unwrap()),
epoch(),
None,
);
let policy = Policy::new(&policy_def, ());

// Test a validator that stipulates that a given extension MUST NOT be present.
let extension_validator = ExtensionValidator::not_present();
Expand All @@ -707,12 +710,13 @@ mod tests {
let cert_pem = v1_cert_pem();
let cert = cert(&cert_pem);
let ops = PublicKeyErrorOps {};
let policy = Policy::server(
let policy_def = PolicyDefinition::server(
ops,
Subject::DNS(DNSName::new("example.com").unwrap()),
epoch(),
None,
);
let policy = Policy::new(&policy_def, ());

// Test a present policy that stipulates that a given extension MUST be critical.
let extension_validator =
Expand All @@ -736,12 +740,13 @@ mod tests {
let cert_pem = v1_cert_pem();
let cert = cert(&cert_pem);
let ops = PublicKeyErrorOps {};
let policy = Policy::server(
let policy_def = PolicyDefinition::server(
ops,
Subject::DNS(DNSName::new("example.com").unwrap()),
epoch(),
None,
);
let policy = Policy::new(&policy_def, ());

// Test a maybe present validator that stipulates that a given extension MUST be critical.
let extension_validator = ExtensionValidator::maybe_present(
Expand Down
27 changes: 23 additions & 4 deletions src/rust/cryptography-x509-verification/src/policy/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
mod extension;

use std::collections::HashSet;
use std::ops::Range;
use std::ops::{Deref, Range};
use std::sync::Arc;

use asn1::ObjectIdentifier;
Expand Down Expand Up @@ -196,8 +196,8 @@ impl Subject<'_> {
}
}

/// A `Policy` describes user-configurable aspects of X.509 path validation.
pub struct Policy<'a, B: CryptoOps> {
/// A `PolicyDefinition` describes user-configurable aspects of X.509 path validation.
pub struct PolicyDefinition<'a, B: CryptoOps> {
pub ops: B,

/// A top-level constraint on the length of intermediate CA paths
Expand Down Expand Up @@ -234,7 +234,7 @@ pub struct Policy<'a, B: CryptoOps> {
ee_extension_policy: ExtensionPolicy<B>,
}

impl<'a, B: CryptoOps> Policy<'a, B> {
impl<'a, B: CryptoOps> PolicyDefinition<'a, B> {
fn new(
ops: B,
subject: Option<Subject<'a>>,
Expand Down Expand Up @@ -372,6 +372,25 @@ impl<'a, B: CryptoOps> Policy<'a, B> {
EKU_SERVER_AUTH_OID.clone(),
)
}
}

pub struct Policy<'a, B: CryptoOps> {
definition: &'a PolicyDefinition<'a, B>,
pub extra: B::PolicyExtra,
}

impl<'a, B: CryptoOps> Deref for Policy<'a, B> {
type Target = PolicyDefinition<'a, B>;

fn deref(&self) -> &Self::Target {
self.definition
}
}

impl<'a, B: CryptoOps> Policy<'a, B> {
pub fn new(definition: &'a PolicyDefinition<'a, B>, extra: B::PolicyExtra) -> Self {
Self { definition, extra }
}

fn permits_basic<'chain>(&self, cert: &Certificate<'_>) -> ValidationResult<'chain, (), B> {
// CA/B 7.1.1:
Expand Down
50 changes: 26 additions & 24 deletions src/rust/src/x509/verify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use cryptography_x509::certificate::Certificate;
use cryptography_x509::extensions::SubjectAlternativeName;
use cryptography_x509::oid::SUBJECT_ALTERNATIVE_NAME_OID;
use cryptography_x509_verification::ops::{CryptoOps, VerificationCertificate};
use cryptography_x509_verification::policy::{Policy, Subject};
use cryptography_x509_verification::policy::{Policy, PolicyDefinition, Subject};
use cryptography_x509_verification::trust_store::Store;
use cryptography_x509_verification::types::{DNSName, IPAddress};
use pyo3::types::{PyAnyMethods, PyListMethods};
Expand All @@ -25,6 +25,7 @@ impl CryptoOps for PyCryptoOps {
type Key = pyo3::Py<pyo3::PyAny>;
type Err = CryptographyError;
type CertificateExtra = pyo3::Py<PyCertificate>;
type PolicyExtra = ();

fn public_key(&self, cert: &Certificate<'_>) -> Result<Self::Key, Self::Err> {
pyo3::Python::with_gil(|py| -> Result<Self::Key, Self::Err> {
Expand Down Expand Up @@ -158,9 +159,10 @@ impl PolicyBuilder {
};

// TODO: Pass extension policies here once implemented in cryptography-x509-verification.
let policy = Policy::client(PyCryptoOps {}, time, self.max_chain_depth);

Ok(PyClientVerifier { policy, store })
Ok(PyClientVerifier {
policy_definition: PolicyDefinition::client(PyCryptoOps {}, time, self.max_chain_depth),
store,
})
}

fn build_server_verifier(
Expand All @@ -185,11 +187,11 @@ impl PolicyBuilder {
};
let subject_owner = build_subject_owner(py, &subject)?;

let policy = OwnedPolicy::try_new(subject_owner, |subject_owner| {
let policy_definition = OwnedPolicyDefinition::try_new(subject_owner, |subject_owner| {
let subject = build_subject(py, subject_owner)?;

// TODO: Pass extension policies here once implemented in cryptography-x509-verification.
Ok::<PyCryptoPolicy<'_>, pyo3::PyErr>(Policy::server(
Ok::<PyCryptoPolicyDefinition<'_>, pyo3::PyErr>(PolicyDefinition::server(
PyCryptoOps {},
subject,
time,
Expand All @@ -199,13 +201,13 @@ impl PolicyBuilder {

Ok(PyServerVerifier {
py_subject: subject,
policy,
policy_definition,
store,
})
}
}

type PyCryptoPolicy<'a> = Policy<'a, PyCryptoOps>;
type PyCryptoPolicyDefinition<'a> = PolicyDefinition<'a, PyCryptoOps>;

/// This enum exists solely to provide heterogeneously typed ownership for `OwnedPolicy`.
enum SubjectOwner {
Expand All @@ -219,11 +221,11 @@ enum SubjectOwner {
}

self_cell::self_cell!(
struct OwnedPolicy {
struct OwnedPolicyDefinition {
owner: SubjectOwner,

#[covariant]
dependent: PyCryptoPolicy,
dependent: PyCryptoPolicyDefinition,
}
);

Expand All @@ -245,14 +247,14 @@ pub(crate) struct PyVerifiedClient {
module = "cryptography.hazmat.bindings._rust.x509"
)]
pub(crate) struct PyClientVerifier {
policy: PyCryptoPolicy<'static>,
policy_definition: PyCryptoPolicyDefinition<'static>,
#[pyo3(get)]
store: pyo3::Py<PyStore>,
}

impl PyClientVerifier {
fn as_policy(&self) -> &Policy<'_, PyCryptoOps> {
&self.policy
fn as_policy_def(&self) -> &PyCryptoPolicyDefinition<'_> {
&self.policy_definition
}
}

Expand All @@ -263,12 +265,12 @@ impl PyClientVerifier {
&self,
py: pyo3::Python<'p>,
) -> pyo3::PyResult<pyo3::Bound<'p, pyo3::PyAny>> {
datetime_to_py(py, &self.as_policy().validation_time)
datetime_to_py(py, &self.as_policy_def().validation_time)
}

#[getter]
fn max_chain_depth(&self) -> u8 {
self.as_policy().max_chain_depth
self.as_policy_def().max_chain_depth
}

fn verify(
Expand All @@ -277,7 +279,7 @@ impl PyClientVerifier {
leaf: pyo3::Py<PyCertificate>,
intermediates: Vec<pyo3::Py<PyCertificate>>,
) -> CryptographyResult<PyVerifiedClient> {
let policy = self.as_policy();
let policy = Policy::new(self.as_policy_def(), ());
let store = self.store.get();

let intermediates = intermediates
Expand All @@ -290,7 +292,7 @@ impl PyClientVerifier {
let chain = cryptography_x509_verification::verify(
&v,
&intermediates,
policy,
&policy,
store.raw.borrow_dependent(),
)
.or_else(|e| handle_validation_error(py, e))?;
Expand Down Expand Up @@ -329,14 +331,14 @@ impl PyClientVerifier {
pub(crate) struct PyServerVerifier {
#[pyo3(get, name = "subject")]
py_subject: pyo3::Py<pyo3::PyAny>,
policy: OwnedPolicy,
policy_definition: OwnedPolicyDefinition,
#[pyo3(get)]
store: pyo3::Py<PyStore>,
}

impl PyServerVerifier {
fn as_policy(&self) -> &Policy<'_, PyCryptoOps> {
self.policy.borrow_dependent()
fn as_policy_def(&self) -> &PyCryptoPolicyDefinition<'_> {
self.policy_definition.borrow_dependent()
}
}

Expand All @@ -347,12 +349,12 @@ impl PyServerVerifier {
&self,
py: pyo3::Python<'p>,
) -> pyo3::PyResult<pyo3::Bound<'p, pyo3::PyAny>> {
datetime_to_py(py, &self.as_policy().validation_time)
datetime_to_py(py, &self.as_policy_def().validation_time)
}

#[getter]
fn max_chain_depth(&self) -> u8 {
self.as_policy().max_chain_depth
self.as_policy_def().max_chain_depth
}

fn verify<'p>(
Expand All @@ -361,7 +363,7 @@ impl PyServerVerifier {
leaf: pyo3::Py<PyCertificate>,
intermediates: Vec<pyo3::Py<PyCertificate>>,
) -> CryptographyResult<pyo3::Bound<'p, pyo3::types::PyList>> {
let policy = self.as_policy();
let policy = Policy::new(self.as_policy_def(), ());
let store = self.store.get();

let intermediates = intermediates
Expand All @@ -374,7 +376,7 @@ impl PyServerVerifier {
let chain = cryptography_x509_verification::verify(
&v,
&intermediates,
policy,
&policy,
store.raw.borrow_dependent(),
)
.or_else(|e| handle_validation_error(py, e))?;
Expand Down