Skip to content
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

src, tests: add max_chain_depth to validation API #9844

Merged
merged 4 commits into from
Nov 9, 2023
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
14 changes: 14 additions & 0 deletions docs/x509/verification.rst
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,20 @@ chain building, etc.

:returns: A new instance of :class:`PolicyBuilder`

.. method:: max_chain_depth(new_max_chain_depth)

Sets the verifier's maximum chain building depth.

This depth behaves tracks the length of the intermediate CA
chain: a maximum depth of zero means that the leaf must be directly
issued by a member of the store, a depth of one means no more than
one intermediate CA, and so forth. Note that self-issued intermediates
don't count against the chain depth, per RFC 5280.

:param new_max_chain_depth: The maximum depth to allow in the verifier

:returns: A new instance of :class:`PolicyBuilder`

.. method:: build_server_verifier(subject)

Builds a verifier for verifying server certificates.
Expand Down
3 changes: 3 additions & 0 deletions src/cryptography/hazmat/bindings/_rust/x509.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ def create_server_verifier(
name: x509.verification.Subject,
store: Store,
time: datetime.datetime | None,
max_chain_depth: int | None,
) -> x509.verification.ServerVerifier: ...

class Sct: ...
Expand All @@ -56,6 +57,8 @@ class ServerVerifier:
def validation_time(self) -> datetime.datetime: ...
@property
def store(self) -> Store: ...
@property
def max_chain_depth(self) -> int: ...
def verify(
self,
leaf: x509.Certificate,
Expand Down
17 changes: 17 additions & 0 deletions src/cryptography/x509/verification.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,11 @@ def __init__(
*,
time: datetime.datetime | None = None,
store: Store | None = None,
max_chain_depth: int | None = None,
):
self._time = time
self._store = store
self._max_chain_depth = max_chain_depth

def time(self, new_time: datetime.datetime) -> PolicyBuilder:
"""
Expand All @@ -48,6 +50,20 @@ def store(self, new_store: Store) -> PolicyBuilder:

return PolicyBuilder(time=self._time, store=new_store)

def max_chain_depth(self, new_max_chain_depth: int) -> PolicyBuilder:
"""
Sets the maximum chain depth.
"""

if self._max_chain_depth is not None:
raise ValueError("The maximum chain depth may only be set once.")

return PolicyBuilder(
time=self._time,
store=self._store,
max_chain_depth=new_max_chain_depth,
)

def build_server_verifier(self, subject: Subject) -> ServerVerifier:
"""
Builds a verifier for verifying server certificates.
Expand All @@ -60,4 +76,5 @@ def build_server_verifier(self, subject: Subject) -> ServerVerifier:
subject,
self._store,
self._time,
self._max_chain_depth,
)
10 changes: 5 additions & 5 deletions src/rust/cryptography-x509-validation/src/policy/extension.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ mod tests {
let cert_pem = v1_cert_pem();
let cert = cert(&cert_pem);
let ops = NullOps {};
let policy = Policy::new(ops, None, epoch());
let policy = Policy::new(ops, None, epoch(), None);

// Test a policy that stipulates that a given extension MUST be present.
let extension_policy = ExtensionPolicy::present(
Expand Down Expand Up @@ -280,7 +280,7 @@ mod tests {
let cert_pem = v1_cert_pem();
let cert = cert(&cert_pem);
let ops = NullOps {};
let policy = Policy::new(ops, None, epoch());
let policy = Policy::new(ops, None, epoch(), None);

// Test a policy that stipulates that a given extension CAN be present.
let extension_policy = ExtensionPolicy::maybe_present(
Expand Down Expand Up @@ -316,7 +316,7 @@ mod tests {
let cert_pem = v1_cert_pem();
let cert = cert(&cert_pem);
let ops = NullOps {};
let policy = Policy::new(ops, None, epoch());
let policy = Policy::new(ops, None, epoch(), None);

// Test a policy that stipulates that a given extension MUST NOT be present.
let extension_policy = ExtensionPolicy::not_present(BASIC_CONSTRAINTS_OID);
Expand Down Expand Up @@ -348,7 +348,7 @@ mod tests {
let cert_pem = v1_cert_pem();
let cert = cert(&cert_pem);
let ops = NullOps {};
let policy = Policy::new(ops, None, epoch());
let policy = Policy::new(ops, None, epoch(), None);

// Test a present policy that stipulates that a given extension MUST be critical.
let extension_policy = ExtensionPolicy::present(
Expand Down Expand Up @@ -376,7 +376,7 @@ mod tests {
let cert_pem = v1_cert_pem();
let cert = cert(&cert_pem);
let ops = NullOps {};
let policy = Policy::new(ops, None, epoch());
let policy = Policy::new(ops, None, epoch(), None);

// Test a maybe present policy that stipulates that a given extension MUST be critical.
let extension_policy = ExtensionPolicy::maybe_present(
Expand Down
31 changes: 23 additions & 8 deletions src/rust/cryptography-x509-validation/src/policy/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,17 @@ const RFC5280_CRITICAL_CA_EXTENSIONS: &[asn1::ObjectIdentifier] =
const RFC5280_CRITICAL_EE_EXTENSIONS: &[asn1::ObjectIdentifier] =
&[BASIC_CONSTRAINTS_OID, SUBJECT_ALTERNATIVE_NAME_OID];

/// A default reasonable maximum chain depth.
///
/// This depth was chosen to balance between common validation lengths
/// (chains in the Web PKI are ordinarily no longer than 2 or 3 intermediates
/// in the longest cases) and support for pathological cases.
///
/// Relatively little prior art for selecting a default depth exists;
/// OpenSSL defaults to a limit of 100, which is far more permissive than
/// necessary.
const DEFAULT_MAX_CHAIN_DEPTH: u8 = 8;

pub enum PolicyError {
Other(&'static str),
}
Expand Down Expand Up @@ -195,12 +206,11 @@ impl From<IPAddress> for Subject<'_> {
pub struct Policy<'a, B: CryptoOps> {
_ops: B,

/// A top-level constraint on the length of paths constructed under
/// this policy.
/// A top-level constraint on the length of intermediate CA paths
/// constructed under this policy.
///
/// Note that this has different semantics from `pathLenConstraint`:
/// it controls the *overall* non-self-issued chain length, not the number
/// of non-self-issued intermediates in the chain.
/// Per RFC 5280, this limits the length of the non-self-issued intermediate
/// CA chain, without counting either the leaf or trust anchor.
pub max_chain_depth: u8,

/// A subject (i.e. DNS name or other name format) that any EE certificates
Expand Down Expand Up @@ -230,10 +240,15 @@ pub struct Policy<'a, B: CryptoOps> {
impl<'a, B: CryptoOps> Policy<'a, B> {
/// Create a new policy with defaults for the certificate profile defined in
/// the CA/B Forum's Basic Requirements.
pub fn new(ops: B, subject: Option<Subject<'a>>, time: asn1::DateTime) -> Self {
pub fn new(
ops: B,
subject: Option<Subject<'a>>,
time: asn1::DateTime,
max_chain_depth: Option<u8>,
) -> Self {
Self {
_ops: ops,
max_chain_depth: 8,
max_chain_depth: max_chain_depth.unwrap_or(DEFAULT_MAX_CHAIN_DEPTH),
subject,
validation_time: time,
extended_key_usage: EKU_SERVER_AUTH_OID.clone(),
Expand Down Expand Up @@ -383,7 +398,7 @@ mod tests {
#[test]
fn test_policy_critical_extensions() {
let time = asn1::DateTime::new(2023, 9, 12, 1, 1, 1).unwrap();
let policy = Policy::new(NullOps {}, None, time);
let policy = Policy::new(NullOps {}, None, time, None);

assert_eq!(
policy.critical_ca_extensions,
Expand Down
8 changes: 8 additions & 0 deletions src/rust/src/x509/verify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use cryptography_x509_validation::{
policy::{Policy, Subject},
types::{DNSName, IPAddress},
};
use pyo3::IntoPy;

use crate::error::{CryptographyError, CryptographyResult};
use crate::types;
Expand Down Expand Up @@ -93,6 +94,11 @@ impl PyServerVerifier {
datetime_to_py(py, &self.as_policy().validation_time)
}

#[getter]
fn max_chain_depth(&self, py: pyo3::Python<'_>) -> pyo3::PyResult<pyo3::PyObject> {
Ok(self.as_policy().max_chain_depth.into_py(py))
}

fn verify<'p>(
&self,
_py: pyo3::Python<'p>,
Expand Down Expand Up @@ -155,6 +161,7 @@ fn create_server_verifier(
subject: pyo3::Py<pyo3::PyAny>,
store: pyo3::Py<PyStore>,
time: Option<&pyo3::PyAny>,
max_chain_depth: Option<u8>,
) -> pyo3::PyResult<PyServerVerifier> {
let time = match time {
Some(time) => py_to_datetime(py, time)?,
Expand All @@ -168,6 +175,7 @@ fn create_server_verifier(
PyCryptoOps {},
subject,
time,
max_chain_depth,
)))
})?;

Expand Down
7 changes: 7 additions & 0 deletions tests/x509/test_verification.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ def test_store_already_set(self):
with pytest.raises(ValueError):
PolicyBuilder().store(dummy_store()).store(dummy_store())

def test_max_chain_depth_already_set(self):
with pytest.raises(ValueError):
PolicyBuilder().max_chain_depth(8).max_chain_depth(9)

def test_ipaddress_subject(self):
policy = (
PolicyBuilder()
Expand Down Expand Up @@ -71,15 +75,18 @@ def test_subject_bad_types(self):
def test_builder_pattern(self):
now = datetime.datetime.now().replace(microsecond=0)
store = dummy_store()
max_chain_depth = 16

builder = PolicyBuilder()
builder = builder.time(now)
builder = builder.store(store)
builder = builder.max_chain_depth(max_chain_depth)

verifier = builder.build_server_verifier(DNSName("cryptography.io"))
assert verifier.subject == DNSName("cryptography.io")
assert verifier.validation_time == now
assert verifier.store == store
assert verifier.max_chain_depth == max_chain_depth

def test_build_server_verifier_missing_store(self):
with pytest.raises(
Expand Down
Loading