blob: aaeefae9958bbe1b21fc02402b227a78c72c3787 [file] [log] [blame]
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import binascii
import datetime
import ipaddress
import os
from pyasn1.codec.der import decoder
from pyasn1_modules import rfc2459
import pytest
import six
from cryptography import utils, x509
from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.backends.interfaces import (
DSABackend, EllipticCurveBackend, RSABackend, X509Backend
)
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import dsa, ec, padding, rsa
from cryptography.hazmat.primitives.asymmetric.utils import (
decode_dss_signature
)
from cryptography.x509.oid import (
AuthorityInformationAccessOID, ExtendedKeyUsageOID, ExtensionOID, NameOID
)
from .hazmat.primitives.fixtures_dsa import DSA_KEY_2048
from .hazmat.primitives.fixtures_rsa import RSA_KEY_2048, RSA_KEY_512
from .hazmat.primitives.test_ec import _skip_curve_unsupported
from .utils import load_vectors_from_file
@utils.register_interface(x509.ExtensionType)
class DummyExtension(object):
oid = x509.ObjectIdentifier("1.2.3.4")
@utils.register_interface(x509.GeneralName)
class FakeGeneralName(object):
def __init__(self, value):
self._value = value
value = utils.read_only_property("_value")
def _load_cert(filename, loader, backend):
cert = load_vectors_from_file(
filename=filename,
loader=lambda pemfile: loader(pemfile.read(), backend),
mode="rb"
)
return cert
@pytest.mark.requires_backend_interface(interface=X509Backend)
class TestCertificateRevocationList(object):
def test_load_pem_crl(self, backend):
crl = _load_cert(
os.path.join("x509", "custom", "crl_all_reasons.pem"),
x509.load_pem_x509_crl,
backend
)
assert isinstance(crl, x509.CertificateRevocationList)
fingerprint = binascii.hexlify(crl.fingerprint(hashes.SHA1()))
assert fingerprint == b"3234b0cb4c0cedf6423724b736729dcfc9e441ef"
assert isinstance(crl.signature_hash_algorithm, hashes.SHA256)
def test_load_der_crl(self, backend):
crl = _load_cert(
os.path.join("x509", "PKITS_data", "crls", "GoodCACRL.crl"),
x509.load_der_x509_crl,
backend
)
assert isinstance(crl, x509.CertificateRevocationList)
fingerprint = binascii.hexlify(crl.fingerprint(hashes.SHA1()))
assert fingerprint == b"dd3db63c50f4c4a13e090f14053227cb1011a5ad"
assert isinstance(crl.signature_hash_algorithm, hashes.SHA256)
def test_invalid_pem(self, backend):
with pytest.raises(ValueError):
x509.load_pem_x509_crl(b"notacrl", backend)
def test_invalid_der(self, backend):
with pytest.raises(ValueError):
x509.load_der_x509_crl(b"notacrl", backend)
def test_unknown_signature_algorithm(self, backend):
crl = _load_cert(
os.path.join(
"x509", "custom", "crl_md2_unknown_crit_entry_ext.pem"
),
x509.load_pem_x509_crl,
backend
)
with pytest.raises(UnsupportedAlgorithm):
crl.signature_hash_algorithm()
def test_issuer(self, backend):
crl = _load_cert(
os.path.join("x509", "PKITS_data", "crls", "GoodCACRL.crl"),
x509.load_der_x509_crl,
backend
)
assert isinstance(crl.issuer, x509.Name)
assert list(crl.issuer) == [
x509.NameAttribute(x509.OID_COUNTRY_NAME, u'US'),
x509.NameAttribute(
x509.OID_ORGANIZATION_NAME, u'Test Certificates 2011'
),
x509.NameAttribute(x509.OID_COMMON_NAME, u'Good CA')
]
assert crl.issuer.get_attributes_for_oid(x509.OID_COMMON_NAME) == [
x509.NameAttribute(x509.OID_COMMON_NAME, u'Good CA')
]
def test_equality(self, backend):
crl1 = _load_cert(
os.path.join("x509", "PKITS_data", "crls", "GoodCACRL.crl"),
x509.load_der_x509_crl,
backend
)
crl2 = _load_cert(
os.path.join("x509", "PKITS_data", "crls", "GoodCACRL.crl"),
x509.load_der_x509_crl,
backend
)
crl3 = _load_cert(
os.path.join("x509", "custom", "crl_all_reasons.pem"),
x509.load_pem_x509_crl,
backend
)
assert crl1 == crl2
assert crl1 != crl3
assert crl1 != object()
def test_update_dates(self, backend):
crl = _load_cert(
os.path.join("x509", "custom", "crl_all_reasons.pem"),
x509.load_pem_x509_crl,
backend
)
assert isinstance(crl.next_update, datetime.datetime)
assert isinstance(crl.last_update, datetime.datetime)
assert crl.next_update.isoformat() == "2016-01-01T00:00:00"
assert crl.last_update.isoformat() == "2015-01-01T00:00:00"
def test_revoked_cert_retrieval(self, backend):
crl = _load_cert(
os.path.join("x509", "custom", "crl_all_reasons.pem"),
x509.load_pem_x509_crl,
backend
)
for r in crl:
assert isinstance(r, x509.RevokedCertificate)
# Check that len() works for CRLs.
assert len(crl) == 12
def test_revoked_cert_retrieval_retain_only_revoked(self, backend):
"""
This test attempts to trigger the crash condition described in
https://github.com/pyca/cryptography/issues/2557
PyPy does gc at its own pace, so it will only be reliable on CPython.
"""
revoked = _load_cert(
os.path.join("x509", "custom", "crl_all_reasons.pem"),
x509.load_pem_x509_crl,
backend
)[11]
assert revoked.revocation_date == datetime.datetime(2015, 1, 1, 0, 0)
assert revoked.serial_number == 11
def test_extensions(self, backend):
crl = _load_cert(
os.path.join("x509", "custom", "crl_ian_aia_aki.pem"),
x509.load_pem_x509_crl,
backend
)
crl_number = crl.extensions.get_extension_for_oid(
ExtensionOID.CRL_NUMBER
)
aki = crl.extensions.get_extension_for_class(
x509.AuthorityKeyIdentifier
)
aia = crl.extensions.get_extension_for_class(
x509.AuthorityInformationAccess
)
ian = crl.extensions.get_extension_for_class(
x509.IssuerAlternativeName
)
assert crl_number.value == x509.CRLNumber(1)
assert crl_number.critical is False
assert aki.value == x509.AuthorityKeyIdentifier(
key_identifier=(
b'yu\xbb\x84:\xcb,\xdez\t\xbe1\x1bC\xbc\x1c*MSX'
),
authority_cert_issuer=None,
authority_cert_serial_number=None
)
assert aia.value == x509.AuthorityInformationAccess([
x509.AccessDescription(
AuthorityInformationAccessOID.CA_ISSUERS,
x509.DNSName(u"cryptography.io")
)
])
assert ian.value == x509.IssuerAlternativeName([
x509.UniformResourceIdentifier(u"https://cryptography.io"),
])
def test_signature(self, backend):
crl = _load_cert(
os.path.join("x509", "custom", "crl_all_reasons.pem"),
x509.load_pem_x509_crl,
backend
)
assert crl.signature == binascii.unhexlify(
b"536a5a0794f68267361e7bc2f19167a3e667a2ab141535616855d8deb2ba1af"
b"9fd4546b1fe76b454eb436af7b28229fedff4634dfc9dd92254266219ae0ea8"
b"75d9ff972e9a2da23d5945f073da18c50a4265bfed9ca16586347800ef49dd1"
b"6856d7265f4f3c498a57f04dc04404e2bd2e2ada1f5697057aacef779a18371"
b"c621edc9a5c2b8ec1716e8fa22feeb7fcec0ce9156c8d344aa6ae8d1a5d99d0"
b"9386df36307df3b63c83908f4a61a0ff604c1e292ad63b349d1082ddd7ae1b7"
b"c178bba995523ec6999310c54da5706549797bfb1230f5593ba7b4353dade4f"
b"d2be13a57580a6eb20b5c4083f000abac3bf32cd8b75f23e4c8f4b3a79e1e2d"
b"58a472b0"
)
def test_tbs_certlist_bytes(self, backend):
crl = _load_cert(
os.path.join("x509", "PKITS_data", "crls", "GoodCACRL.crl"),
x509.load_der_x509_crl,
backend
)
ca_cert = _load_cert(
os.path.join("x509", "PKITS_data", "certs", "GoodCACert.crt"),
x509.load_der_x509_certificate,
backend
)
verifier = ca_cert.public_key().verifier(
crl.signature, padding.PKCS1v15(), crl.signature_hash_algorithm
)
verifier.update(crl.tbs_certlist_bytes)
verifier.verify()
def test_public_bytes_pem(self, backend):
crl = _load_cert(
os.path.join("x509", "custom", "crl_empty.pem"),
x509.load_pem_x509_crl,
backend
)
# Encode it to PEM and load it back.
crl = x509.load_pem_x509_crl(crl.public_bytes(
encoding=serialization.Encoding.PEM,
), backend)
assert len(crl) == 0
assert crl.last_update == datetime.datetime(2015, 12, 20, 23, 44, 47)
assert crl.next_update == datetime.datetime(2015, 12, 28, 0, 44, 47)
def test_public_bytes_der(self, backend):
crl = _load_cert(
os.path.join("x509", "custom", "crl_all_reasons.pem"),
x509.load_pem_x509_crl,
backend
)
# Encode it to DER and load it back.
crl = x509.load_der_x509_crl(crl.public_bytes(
encoding=serialization.Encoding.DER,
), backend)
assert len(crl) == 12
assert crl.last_update == datetime.datetime(2015, 1, 1, 0, 0, 0)
assert crl.next_update == datetime.datetime(2016, 1, 1, 0, 0, 0)
@pytest.mark.parametrize(
("cert_path", "loader_func", "encoding"),
[
(
os.path.join("x509", "custom", "crl_all_reasons.pem"),
x509.load_pem_x509_crl,
serialization.Encoding.PEM,
),
(
os.path.join("x509", "PKITS_data", "crls", "GoodCACRL.crl"),
x509.load_der_x509_crl,
serialization.Encoding.DER,
),
]
)
def test_public_bytes_match(self, cert_path, loader_func, encoding,
backend):
crl_bytes = load_vectors_from_file(
cert_path, lambda pemfile: pemfile.read(), mode="rb"
)
crl = loader_func(crl_bytes, backend)
serialized = crl.public_bytes(encoding)
assert serialized == crl_bytes
def test_public_bytes_invalid_encoding(self, backend):
crl = _load_cert(
os.path.join("x509", "custom", "crl_empty.pem"),
x509.load_pem_x509_crl,
backend
)
with pytest.raises(TypeError):
crl.public_bytes('NotAnEncoding')
@pytest.mark.requires_backend_interface(interface=X509Backend)
class TestRevokedCertificate(object):
def test_revoked_basics(self, backend):
crl = _load_cert(
os.path.join("x509", "custom", "crl_all_reasons.pem"),
x509.load_pem_x509_crl,
backend
)
for i, rev in enumerate(crl):
assert isinstance(rev, x509.RevokedCertificate)
assert isinstance(rev.serial_number, int)
assert isinstance(rev.revocation_date, datetime.datetime)
assert isinstance(rev.extensions, x509.Extensions)
assert rev.serial_number == i
assert rev.revocation_date.isoformat() == "2015-01-01T00:00:00"
def test_revoked_extensions(self, backend):
crl = _load_cert(
os.path.join("x509", "custom", "crl_all_reasons.pem"),
x509.load_pem_x509_crl,
backend
)
exp_issuer = [
x509.DirectoryName(x509.Name([
x509.NameAttribute(x509.OID_COUNTRY_NAME, u"US"),
x509.NameAttribute(x509.OID_COMMON_NAME, u"cryptography.io"),
]))
]
# First revoked cert doesn't have extensions, test if it is handled
# correctly.
rev0 = crl[0]
# It should return an empty Extensions object.
assert isinstance(rev0.extensions, x509.Extensions)
assert len(rev0.extensions) == 0
with pytest.raises(x509.ExtensionNotFound):
rev0.extensions.get_extension_for_oid(x509.OID_CRL_REASON)
with pytest.raises(x509.ExtensionNotFound):
rev0.extensions.get_extension_for_oid(x509.OID_CERTIFICATE_ISSUER)
with pytest.raises(x509.ExtensionNotFound):
rev0.extensions.get_extension_for_oid(x509.OID_INVALIDITY_DATE)
# Test manual retrieval of extension values.
rev1 = crl[1]
assert isinstance(rev1.extensions, x509.Extensions)
reason = rev1.extensions.get_extension_for_class(
x509.CRLReason).value
assert reason == x509.CRLReason(x509.ReasonFlags.unspecified)
issuer = rev1.extensions.get_extension_for_class(
x509.CertificateIssuer).value
assert issuer == x509.CertificateIssuer(exp_issuer)
date = rev1.extensions.get_extension_for_class(
x509.InvalidityDate).value
assert date == x509.InvalidityDate(datetime.datetime(2015, 1, 1, 0, 0))
# Check if all reason flags can be found in the CRL.
flags = set(x509.ReasonFlags)
for rev in crl:
try:
r = rev.extensions.get_extension_for_class(x509.CRLReason)
except x509.ExtensionNotFound:
# Not all revoked certs have a reason extension.
pass
else:
flags.discard(r.value.reason)
assert len(flags) == 0
def test_no_revoked_certs(self, backend):
crl = _load_cert(
os.path.join("x509", "custom", "crl_empty.pem"),
x509.load_pem_x509_crl,
backend
)
assert len(crl) == 0
def test_duplicate_entry_ext(self, backend):
crl = _load_cert(
os.path.join("x509", "custom", "crl_dup_entry_ext.pem"),
x509.load_pem_x509_crl,
backend
)
with pytest.raises(x509.DuplicateExtension):
crl[0].extensions
def test_unsupported_crit_entry_ext(self, backend):
crl = _load_cert(
os.path.join(
"x509", "custom", "crl_md2_unknown_crit_entry_ext.pem"
),
x509.load_pem_x509_crl,
backend
)
with pytest.raises(x509.UnsupportedExtension):
crl[0].extensions
def test_unsupported_reason(self, backend):
crl = _load_cert(
os.path.join(
"x509", "custom", "crl_unsupported_reason.pem"
),
x509.load_pem_x509_crl,
backend
)
with pytest.raises(ValueError):
crl[0].extensions
def test_invalid_cert_issuer_ext(self, backend):
crl = _load_cert(
os.path.join(
"x509", "custom", "crl_inval_cert_issuer_entry_ext.pem"
),
x509.load_pem_x509_crl,
backend
)
with pytest.raises(ValueError):
crl[0].extensions
def test_indexing(self, backend):
crl = _load_cert(
os.path.join("x509", "custom", "crl_all_reasons.pem"),
x509.load_pem_x509_crl,
backend
)
with pytest.raises(IndexError):
crl[-13]
with pytest.raises(IndexError):
crl[12]
assert crl[-1].serial_number == crl[11].serial_number
assert len(crl[2:4]) == 2
assert crl[2:4][0].serial_number == crl[2].serial_number
assert crl[2:4][1].serial_number == crl[3].serial_number
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
class TestRSACertificate(object):
def test_load_pem_cert(self, backend):
cert = _load_cert(
os.path.join("x509", "custom", "post2000utctime.pem"),
x509.load_pem_x509_certificate,
backend
)
assert isinstance(cert, x509.Certificate)
assert cert.serial == 11559813051657483483
fingerprint = binascii.hexlify(cert.fingerprint(hashes.SHA1()))
assert fingerprint == b"2b619ed04bfc9c3b08eb677d272192286a0947a8"
assert isinstance(cert.signature_hash_algorithm, hashes.SHA1)
def test_load_der_cert(self, backend):
cert = _load_cert(
os.path.join("x509", "PKITS_data", "certs", "GoodCACert.crt"),
x509.load_der_x509_certificate,
backend
)
assert isinstance(cert, x509.Certificate)
assert cert.serial == 2
fingerprint = binascii.hexlify(cert.fingerprint(hashes.SHA1()))
assert fingerprint == b"6f49779533d565e8b7c1062503eab41492c38e4d"
assert isinstance(cert.signature_hash_algorithm, hashes.SHA256)
def test_signature(self, backend):
cert = _load_cert(
os.path.join("x509", "custom", "post2000utctime.pem"),
x509.load_pem_x509_certificate,
backend
)
assert cert.signature == binascii.unhexlify(
b"8e0f72fcbebe4755abcaf76c8ce0bae17cde4db16291638e1b1ce04a93cdb4c"
b"44a3486070986c5a880c14fdf8497e7d289b2630ccb21d24a3d1aa1b2d87482"
b"07f3a1e16ccdf8daa8a7ea1a33d49774f513edf09270bd8e665b6300a10f003"
b"66a59076905eb63cf10a81a0ca78a6ef3127f6cb2f6fb7f947fce22a30d8004"
b"8c243ba2c1a54c425fe12310e8a737638f4920354d4cce25cbd9dea25e6a2fe"
b"0d8579a5c8d929b9275be221975479f3f75075bcacf09526523b5fd67f7683f"
b"3cda420fabb1e9e6fc26bc0649cf61bb051d6932fac37066bb16f55903dfe78"
b"53dc5e505e2a10fbba4f9e93a0d3b53b7fa34b05d7ba6eef869bfc34b8e514f"
b"d5419f75"
)
assert len(cert.signature) == cert.public_key().key_size // 8
def test_tbs_certificate_bytes(self, backend):
cert = _load_cert(
os.path.join("x509", "custom", "post2000utctime.pem"),
x509.load_pem_x509_certificate,
backend
)
assert cert.tbs_certificate_bytes == binascii.unhexlify(
b"308202d8a003020102020900a06cb4b955f7f4db300d06092a864886f70d010"
b"10505003058310b3009060355040613024155311330110603550408130a536f"
b"6d652d53746174653121301f060355040a1318496e7465726e6574205769646"
b"769747320507479204c74643111300f0603550403130848656c6c6f20434130"
b"1e170d3134313132363231343132305a170d3134313232363231343132305a3"
b"058310b3009060355040613024155311330110603550408130a536f6d652d53"
b"746174653121301f060355040a1318496e7465726e657420576964676974732"
b"0507479204c74643111300f0603550403130848656c6c6f2043413082012230"
b"0d06092a864886f70d01010105000382010f003082010a0282010100b03af70"
b"2059e27f1e2284b56bbb26c039153bf81f295b73a49132990645ede4d2da0a9"
b"13c42e7d38d3589a00d3940d194f6e6d877c2ef812da22a275e83d8be786467"
b"48b4e7f23d10e873fd72f57a13dec732fc56ab138b1bb308399bb412cd73921"
b"4ef714e1976e09603405e2556299a05522510ac4574db5e9cb2cf5f99e8f48c"
b"1696ab3ea2d6d2ddab7d4e1b317188b76a572977f6ece0a4ad396f0150e7d8b"
b"1a9986c0cb90527ec26ca56e2914c270d2a198b632fa8a2fda55079d3d39864"
b"b6fb96ddbe331cacb3cb8783a8494ccccd886a3525078847ca01ca5f803e892"
b"14403e8a4b5499539c0b86f7a0daa45b204a8e079d8a5b03db7ba1ba3d7011a"
b"70203010001a381bc3081b9301d0603551d0e04160414d8e89dc777e4472656"
b"f1864695a9f66b7b0400ae3081890603551d23048181307f8014d8e89dc777e"
b"4472656f1864695a9f66b7b0400aea15ca45a3058310b300906035504061302"
b"4155311330110603550408130a536f6d652d53746174653121301f060355040"
b"a1318496e7465726e6574205769646769747320507479204c74643111300f06"
b"03550403130848656c6c6f204341820900a06cb4b955f7f4db300c0603551d1"
b"3040530030101ff"
)
verifier = cert.public_key().verifier(
cert.signature, padding.PKCS1v15(), cert.signature_hash_algorithm
)
verifier.update(cert.tbs_certificate_bytes)
verifier.verify()
def test_issuer(self, backend):
cert = _load_cert(
os.path.join(
"x509", "PKITS_data", "certs",
"Validpre2000UTCnotBeforeDateTest3EE.crt"
),
x509.load_der_x509_certificate,
backend
)
issuer = cert.issuer
assert isinstance(issuer, x509.Name)
assert list(issuer) == [
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
x509.NameAttribute(
NameOID.ORGANIZATION_NAME, u'Test Certificates 2011'
),
x509.NameAttribute(NameOID.COMMON_NAME, u'Good CA')
]
assert issuer.get_attributes_for_oid(NameOID.COMMON_NAME) == [
x509.NameAttribute(NameOID.COMMON_NAME, u'Good CA')
]
def test_all_issuer_name_types(self, backend):
cert = _load_cert(
os.path.join(
"x509", "custom",
"all_supported_names.pem"
),
x509.load_pem_x509_certificate,
backend
)
issuer = cert.issuer
assert isinstance(issuer, x509.Name)
assert list(issuer) == [
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
x509.NameAttribute(NameOID.COUNTRY_NAME, u'CA'),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'Texas'),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'Illinois'),
x509.NameAttribute(NameOID.LOCALITY_NAME, u'Chicago'),
x509.NameAttribute(NameOID.LOCALITY_NAME, u'Austin'),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'Zero, LLC'),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'One, LLC'),
x509.NameAttribute(NameOID.COMMON_NAME, u'common name 0'),
x509.NameAttribute(NameOID.COMMON_NAME, u'common name 1'),
x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u'OU 0'),
x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u'OU 1'),
x509.NameAttribute(NameOID.DN_QUALIFIER, u'dnQualifier0'),
x509.NameAttribute(NameOID.DN_QUALIFIER, u'dnQualifier1'),
x509.NameAttribute(NameOID.SERIAL_NUMBER, u'123'),
x509.NameAttribute(NameOID.SERIAL_NUMBER, u'456'),
x509.NameAttribute(NameOID.TITLE, u'Title 0'),
x509.NameAttribute(NameOID.TITLE, u'Title 1'),
x509.NameAttribute(NameOID.SURNAME, u'Surname 0'),
x509.NameAttribute(NameOID.SURNAME, u'Surname 1'),
x509.NameAttribute(NameOID.GIVEN_NAME, u'Given Name 0'),
x509.NameAttribute(NameOID.GIVEN_NAME, u'Given Name 1'),
x509.NameAttribute(NameOID.PSEUDONYM, u'Incognito 0'),
x509.NameAttribute(NameOID.PSEUDONYM, u'Incognito 1'),
x509.NameAttribute(NameOID.GENERATION_QUALIFIER, u'Last Gen'),
x509.NameAttribute(NameOID.GENERATION_QUALIFIER, u'Next Gen'),
x509.NameAttribute(NameOID.DOMAIN_COMPONENT, u'dc0'),
x509.NameAttribute(NameOID.DOMAIN_COMPONENT, u'dc1'),
x509.NameAttribute(NameOID.EMAIL_ADDRESS, u'test0@test.local'),
x509.NameAttribute(NameOID.EMAIL_ADDRESS, u'test1@test.local'),
]
def test_subject(self, backend):
cert = _load_cert(
os.path.join(
"x509", "PKITS_data", "certs",
"Validpre2000UTCnotBeforeDateTest3EE.crt"
),
x509.load_der_x509_certificate,
backend
)
subject = cert.subject
assert isinstance(subject, x509.Name)
assert list(subject) == [
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
x509.NameAttribute(
NameOID.ORGANIZATION_NAME, u'Test Certificates 2011'
),
x509.NameAttribute(
NameOID.COMMON_NAME,
u'Valid pre2000 UTC notBefore Date EE Certificate Test3'
)
]
assert subject.get_attributes_for_oid(NameOID.COMMON_NAME) == [
x509.NameAttribute(
NameOID.COMMON_NAME,
u'Valid pre2000 UTC notBefore Date EE Certificate Test3'
)
]
def test_unicode_name(self, backend):
cert = _load_cert(
os.path.join(
"x509", "custom",
"utf8_common_name.pem"
),
x509.load_pem_x509_certificate,
backend
)
assert cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME) == [
x509.NameAttribute(
NameOID.COMMON_NAME,
u'We heart UTF8!\u2122'
)
]
assert cert.issuer.get_attributes_for_oid(NameOID.COMMON_NAME) == [
x509.NameAttribute(
NameOID.COMMON_NAME,
u'We heart UTF8!\u2122'
)
]
def test_all_subject_name_types(self, backend):
cert = _load_cert(
os.path.join(
"x509", "custom",
"all_supported_names.pem"
),
x509.load_pem_x509_certificate,
backend
)
subject = cert.subject
assert isinstance(subject, x509.Name)
assert list(subject) == [
x509.NameAttribute(NameOID.COUNTRY_NAME, u'AU'),
x509.NameAttribute(NameOID.COUNTRY_NAME, u'DE'),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'California'),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'New York'),
x509.NameAttribute(NameOID.LOCALITY_NAME, u'San Francisco'),
x509.NameAttribute(NameOID.LOCALITY_NAME, u'Ithaca'),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'Org Zero, LLC'),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'Org One, LLC'),
x509.NameAttribute(NameOID.COMMON_NAME, u'CN 0'),
x509.NameAttribute(NameOID.COMMON_NAME, u'CN 1'),
x509.NameAttribute(
NameOID.ORGANIZATIONAL_UNIT_NAME, u'Engineering 0'
),
x509.NameAttribute(
NameOID.ORGANIZATIONAL_UNIT_NAME, u'Engineering 1'
),
x509.NameAttribute(NameOID.DN_QUALIFIER, u'qualified0'),
x509.NameAttribute(NameOID.DN_QUALIFIER, u'qualified1'),
x509.NameAttribute(NameOID.SERIAL_NUMBER, u'789'),
x509.NameAttribute(NameOID.SERIAL_NUMBER, u'012'),
x509.NameAttribute(NameOID.TITLE, u'Title IX'),
x509.NameAttribute(NameOID.TITLE, u'Title X'),
x509.NameAttribute(NameOID.SURNAME, u'Last 0'),
x509.NameAttribute(NameOID.SURNAME, u'Last 1'),
x509.NameAttribute(NameOID.GIVEN_NAME, u'First 0'),
x509.NameAttribute(NameOID.GIVEN_NAME, u'First 1'),
x509.NameAttribute(NameOID.PSEUDONYM, u'Guy Incognito 0'),
x509.NameAttribute(NameOID.PSEUDONYM, u'Guy Incognito 1'),
x509.NameAttribute(NameOID.GENERATION_QUALIFIER, u'32X'),
x509.NameAttribute(NameOID.GENERATION_QUALIFIER, u'Dreamcast'),
x509.NameAttribute(NameOID.DOMAIN_COMPONENT, u'dc2'),
x509.NameAttribute(NameOID.DOMAIN_COMPONENT, u'dc3'),
x509.NameAttribute(NameOID.EMAIL_ADDRESS, u'test2@test.local'),
x509.NameAttribute(NameOID.EMAIL_ADDRESS, u'test3@test.local'),
]
def test_load_good_ca_cert(self, backend):
cert = _load_cert(
os.path.join("x509", "PKITS_data", "certs", "GoodCACert.crt"),
x509.load_der_x509_certificate,
backend
)
assert cert.not_valid_before == datetime.datetime(2010, 1, 1, 8, 30)
assert cert.not_valid_after == datetime.datetime(2030, 12, 31, 8, 30)
assert cert.serial == 2
public_key = cert.public_key()
assert isinstance(public_key, rsa.RSAPublicKey)
assert cert.version is x509.Version.v3
fingerprint = binascii.hexlify(cert.fingerprint(hashes.SHA1()))
assert fingerprint == b"6f49779533d565e8b7c1062503eab41492c38e4d"
def test_utc_pre_2000_not_before_cert(self, backend):
cert = _load_cert(
os.path.join(
"x509", "PKITS_data", "certs",
"Validpre2000UTCnotBeforeDateTest3EE.crt"
),
x509.load_der_x509_certificate,
backend
)
assert cert.not_valid_before == datetime.datetime(1950, 1, 1, 12, 1)
def test_pre_2000_utc_not_after_cert(self, backend):
cert = _load_cert(
os.path.join(
"x509", "PKITS_data", "certs",
"Invalidpre2000UTCEEnotAfterDateTest7EE.crt"
),
x509.load_der_x509_certificate,
backend
)
assert cert.not_valid_after == datetime.datetime(1999, 1, 1, 12, 1)
def test_post_2000_utc_cert(self, backend):
cert = _load_cert(
os.path.join("x509", "custom", "post2000utctime.pem"),
x509.load_pem_x509_certificate,
backend
)
assert cert.not_valid_before == datetime.datetime(
2014, 11, 26, 21, 41, 20
)
assert cert.not_valid_after == datetime.datetime(
2014, 12, 26, 21, 41, 20
)
def test_generalized_time_not_before_cert(self, backend):
cert = _load_cert(
os.path.join(
"x509", "PKITS_data", "certs",
"ValidGeneralizedTimenotBeforeDateTest4EE.crt"
),
x509.load_der_x509_certificate,
backend
)
assert cert.not_valid_before == datetime.datetime(2002, 1, 1, 12, 1)
assert cert.not_valid_after == datetime.datetime(2030, 12, 31, 8, 30)
assert cert.version is x509.Version.v3
def test_generalized_time_not_after_cert(self, backend):
cert = _load_cert(
os.path.join(
"x509", "PKITS_data", "certs",
"ValidGeneralizedTimenotAfterDateTest8EE.crt"
),
x509.load_der_x509_certificate,
backend
)
assert cert.not_valid_before == datetime.datetime(2010, 1, 1, 8, 30)
assert cert.not_valid_after == datetime.datetime(2050, 1, 1, 12, 1)
assert cert.version is x509.Version.v3
def test_invalid_version_cert(self, backend):
cert = _load_cert(
os.path.join("x509", "custom", "invalid_version.pem"),
x509.load_pem_x509_certificate,
backend
)
with pytest.raises(x509.InvalidVersion) as exc:
cert.version
assert exc.value.parsed_version == 7
def test_eq(self, backend):
cert = _load_cert(
os.path.join("x509", "custom", "post2000utctime.pem"),
x509.load_pem_x509_certificate,
backend
)
cert2 = _load_cert(
os.path.join("x509", "custom", "post2000utctime.pem"),
x509.load_pem_x509_certificate,
backend
)
assert cert == cert2
def test_ne(self, backend):
cert = _load_cert(
os.path.join("x509", "custom", "post2000utctime.pem"),
x509.load_pem_x509_certificate,
backend
)
cert2 = _load_cert(
os.path.join(
"x509", "PKITS_data", "certs",
"ValidGeneralizedTimenotAfterDateTest8EE.crt"
),
x509.load_der_x509_certificate,
backend
)
assert cert != cert2
assert cert != object()
def test_hash(self, backend):
cert1 = _load_cert(
os.path.join("x509", "custom", "post2000utctime.pem"),
x509.load_pem_x509_certificate,
backend
)
cert2 = _load_cert(
os.path.join("x509", "custom", "post2000utctime.pem"),
x509.load_pem_x509_certificate,
backend
)
cert3 = _load_cert(
os.path.join(
"x509", "PKITS_data", "certs",
"ValidGeneralizedTimenotAfterDateTest8EE.crt"
),
x509.load_der_x509_certificate,
backend
)
assert hash(cert1) == hash(cert2)
assert hash(cert1) != hash(cert3)
def test_version_1_cert(self, backend):
cert = _load_cert(
os.path.join("x509", "v1_cert.pem"),
x509.load_pem_x509_certificate,
backend
)
assert cert.version is x509.Version.v1
def test_invalid_pem(self, backend):
with pytest.raises(ValueError):
x509.load_pem_x509_certificate(b"notacert", backend)
def test_invalid_der(self, backend):
with pytest.raises(ValueError):
x509.load_der_x509_certificate(b"notacert", backend)
def test_unsupported_signature_hash_algorithm_cert(self, backend):
cert = _load_cert(
os.path.join("x509", "verisign_md2_root.pem"),
x509.load_pem_x509_certificate,
backend
)
with pytest.raises(UnsupportedAlgorithm):
cert.signature_hash_algorithm
def test_public_bytes_pem(self, backend):
# Load an existing certificate.
cert = _load_cert(
os.path.join("x509", "PKITS_data", "certs", "GoodCACert.crt"),
x509.load_der_x509_certificate,
backend
)
# Encode it to PEM and load it back.
cert = x509.load_pem_x509_certificate(cert.public_bytes(
encoding=serialization.Encoding.PEM,
), backend)
# We should recover what we had to start with.
assert cert.not_valid_before == datetime.datetime(2010, 1, 1, 8, 30)
assert cert.not_valid_after == datetime.datetime(2030, 12, 31, 8, 30)
assert cert.serial == 2
public_key = cert.public_key()
assert isinstance(public_key, rsa.RSAPublicKey)
assert cert.version is x509.Version.v3
fingerprint = binascii.hexlify(cert.fingerprint(hashes.SHA1()))
assert fingerprint == b"6f49779533d565e8b7c1062503eab41492c38e4d"
def test_public_bytes_der(self, backend):
# Load an existing certificate.
cert = _load_cert(
os.path.join("x509", "PKITS_data", "certs", "GoodCACert.crt"),
x509.load_der_x509_certificate,
backend
)
# Encode it to DER and load it back.
cert = x509.load_der_x509_certificate(cert.public_bytes(
encoding=serialization.Encoding.DER,
), backend)
# We should recover what we had to start with.
assert cert.not_valid_before == datetime.datetime(2010, 1, 1, 8, 30)
assert cert.not_valid_after == datetime.datetime(2030, 12, 31, 8, 30)
assert cert.serial == 2
public_key = cert.public_key()
assert isinstance(public_key, rsa.RSAPublicKey)
assert cert.version is x509.Version.v3
fingerprint = binascii.hexlify(cert.fingerprint(hashes.SHA1()))
assert fingerprint == b"6f49779533d565e8b7c1062503eab41492c38e4d"
def test_public_bytes_invalid_encoding(self, backend):
cert = _load_cert(
os.path.join("x509", "PKITS_data", "certs", "GoodCACert.crt"),
x509.load_der_x509_certificate,
backend
)
with pytest.raises(TypeError):
cert.public_bytes('NotAnEncoding')
@pytest.mark.parametrize(
("cert_path", "loader_func", "encoding"),
[
(
os.path.join("x509", "v1_cert.pem"),
x509.load_pem_x509_certificate,
serialization.Encoding.PEM,
),
(
os.path.join("x509", "PKITS_data", "certs", "GoodCACert.crt"),
x509.load_der_x509_certificate,
serialization.Encoding.DER,
),
]
)
def test_public_bytes_match(self, cert_path, loader_func, encoding,
backend):
cert_bytes = load_vectors_from_file(
cert_path, lambda pemfile: pemfile.read(), mode="rb"
)
cert = loader_func(cert_bytes, backend)
serialized = cert.public_bytes(encoding)
assert serialized == cert_bytes
def test_certificate_repr(self, backend):
cert = _load_cert(
os.path.join(
"x509", "cryptography.io.pem"
),
x509.load_pem_x509_certificate,
backend
)
if six.PY3:
assert repr(cert) == (
"<Certificate(subject=<Name([<NameAttribute(oid=<ObjectIdentif"
"ier(oid=2.5.4.11, name=organizationalUnitName)>, value='GT487"
"42965')>, <NameAttribute(oid=<ObjectIdentifier(oid=2.5.4.11, "
"name=organizationalUnitName)>, value='See www.rapidssl.com/re"
"sources/cps (c)14')>, <NameAttribute(oid=<ObjectIdentifier(oi"
"d=2.5.4.11, name=organizationalUnitName)>, value='Domain Cont"
"rol Validated - RapidSSL(R)')>, <NameAttribute(oid=<ObjectIde"
"ntifier(oid=2.5.4.3, name=commonName)>, value='www.cryptograp"
"hy.io')>])>, ...)>"
)
else:
assert repr(cert) == (
"<Certificate(subject=<Name([<NameAttribute(oid=<ObjectIdentif"
"ier(oid=2.5.4.11, name=organizationalUnitName)>, value=u'GT48"
"742965')>, <NameAttribute(oid=<ObjectIdentifier(oid=2.5.4.11,"
" name=organizationalUnitName)>, value=u'See www.rapidssl.com/"
"resources/cps (c)14')>, <NameAttribute(oid=<ObjectIdentifier("
"oid=2.5.4.11, name=organizationalUnitName)>, value=u'Domain C"
"ontrol Validated - RapidSSL(R)')>, <NameAttribute(oid=<Object"
"Identifier(oid=2.5.4.3, name=commonName)>, value=u'www.crypto"
"graphy.io')>])>, ...)>"
)
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
class TestRSACertificateRequest(object):
@pytest.mark.parametrize(
("path", "loader_func"),
[
[
os.path.join("x509", "requests", "rsa_sha1.pem"),
x509.load_pem_x509_csr
],
[
os.path.join("x509", "requests", "rsa_sha1.der"),
x509.load_der_x509_csr
],
]
)
def test_load_rsa_certificate_request(self, path, loader_func, backend):
request = _load_cert(path, loader_func, backend)
assert isinstance(request.signature_hash_algorithm, hashes.SHA1)
public_key = request.public_key()
assert isinstance(public_key, rsa.RSAPublicKey)
subject = request.subject
assert isinstance(subject, x509.Name)
assert list(subject) == [
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'Texas'),
x509.NameAttribute(NameOID.LOCALITY_NAME, u'Austin'),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'PyCA'),
x509.NameAttribute(NameOID.COMMON_NAME, u'cryptography.io'),
]
extensions = request.extensions
assert isinstance(extensions, x509.Extensions)
assert list(extensions) == []
@pytest.mark.parametrize(
"loader_func",
[x509.load_pem_x509_csr, x509.load_der_x509_csr]
)
def test_invalid_certificate_request(self, loader_func, backend):
with pytest.raises(ValueError):
loader_func(b"notacsr", backend)
def test_unsupported_signature_hash_algorithm_request(self, backend):
request = _load_cert(
os.path.join("x509", "requests", "rsa_md4.pem"),
x509.load_pem_x509_csr,
backend
)
with pytest.raises(UnsupportedAlgorithm):
request.signature_hash_algorithm
def test_duplicate_extension(self, backend):
request = _load_cert(
os.path.join(
"x509", "requests", "two_basic_constraints.pem"
),
x509.load_pem_x509_csr,
backend
)
with pytest.raises(x509.DuplicateExtension) as exc:
request.extensions
assert exc.value.oid == ExtensionOID.BASIC_CONSTRAINTS
def test_unsupported_critical_extension(self, backend):
request = _load_cert(
os.path.join(
"x509", "requests", "unsupported_extension_critical.pem"
),
x509.load_pem_x509_csr,
backend
)
with pytest.raises(x509.UnsupportedExtension) as exc:
request.extensions
assert exc.value.oid == x509.ObjectIdentifier('1.2.3.4')
def test_unsupported_extension(self, backend):
request = _load_cert(
os.path.join(
"x509", "requests", "unsupported_extension.pem"
),
x509.load_pem_x509_csr,
backend
)
extensions = request.extensions
assert len(extensions) == 1
assert extensions[0].oid == x509.ObjectIdentifier("1.2.3.4")
assert extensions[0].value == x509.UnrecognizedExtension(
x509.ObjectIdentifier("1.2.3.4"), b"value"
)
def test_request_basic_constraints(self, backend):
request = _load_cert(
os.path.join(
"x509", "requests", "basic_constraints.pem"
),
x509.load_pem_x509_csr,
backend
)
extensions = request.extensions
assert isinstance(extensions, x509.Extensions)
assert list(extensions) == [
x509.Extension(
ExtensionOID.BASIC_CONSTRAINTS,
True,
x509.BasicConstraints(ca=True, path_length=1),
),
]
def test_subject_alt_name(self, backend):
request = _load_cert(
os.path.join("x509", "requests", "san_rsa_sha1.pem"),
x509.load_pem_x509_csr,
backend,
)
ext = request.extensions.get_extension_for_oid(
ExtensionOID.SUBJECT_ALTERNATIVE_NAME
)
assert list(ext.value) == [
x509.DNSName(u"cryptography.io"),
x509.DNSName(u"sub.cryptography.io"),
]
def test_public_bytes_pem(self, backend):
# Load an existing CSR.
request = _load_cert(
os.path.join("x509", "requests", "rsa_sha1.pem"),
x509.load_pem_x509_csr,
backend
)
# Encode it to PEM and load it back.
request = x509.load_pem_x509_csr(request.public_bytes(
encoding=serialization.Encoding.PEM,
), backend)
# We should recover what we had to start with.
assert isinstance(request.signature_hash_algorithm, hashes.SHA1)
public_key = request.public_key()
assert isinstance(public_key, rsa.RSAPublicKey)
subject = request.subject
assert isinstance(subject, x509.Name)
assert list(subject) == [
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'Texas'),
x509.NameAttribute(NameOID.LOCALITY_NAME, u'Austin'),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'PyCA'),
x509.NameAttribute(NameOID.COMMON_NAME, u'cryptography.io'),
]
def test_public_bytes_der(self, backend):
# Load an existing CSR.
request = _load_cert(
os.path.join("x509", "requests", "rsa_sha1.pem"),
x509.load_pem_x509_csr,
backend
)
# Encode it to DER and load it back.
request = x509.load_der_x509_csr(request.public_bytes(
encoding=serialization.Encoding.DER,
), backend)
# We should recover what we had to start with.
assert isinstance(request.signature_hash_algorithm, hashes.SHA1)
public_key = request.public_key()
assert isinstance(public_key, rsa.RSAPublicKey)
subject = request.subject
assert isinstance(subject, x509.Name)
assert list(subject) == [
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'Texas'),
x509.NameAttribute(NameOID.LOCALITY_NAME, u'Austin'),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'PyCA'),
x509.NameAttribute(NameOID.COMMON_NAME, u'cryptography.io'),
]
def test_signature(self, backend):
request = _load_cert(
os.path.join("x509", "requests", "rsa_sha1.pem"),
x509.load_pem_x509_csr,
backend
)
assert request.signature == binascii.unhexlify(
b"8364c86ffbbfe0bfc9a21f831256658ca8989741b80576d36f08a934603a43b1"
b"837246d00167a518abb1de7b51a1e5b7ebea14944800818b1a923c804f120a0d"
b"624f6310ef79e8612755c2b01dcc7f59dfdbce0db3f2630f185f504b8c17af80"
b"cbd364fa5fda68337153930948226cd4638287a0aed6524d3006885c19028a1e"
b"e2f5a91d6e77dbaa0b49996ee0a0c60b55b61bd080a08bb34aa7f3e07e91f37f"
b"6a11645be2d8654c1570dcda145ed7cc92017f7d53225d7f283f3459ec5bda41"
b"cf6dd75d43676c543483385226b7e4fa29c8739f1b0eaf199613593991979862"
b"e36181e8c4c270c354b7f52c128db1b70639823324c7ea24791b7bc3d7005f3b"
)
def test_tbs_certrequest_bytes(self, backend):
request = _load_cert(
os.path.join("x509", "requests", "rsa_sha1.pem"),
x509.load_pem_x509_csr,
backend
)
assert request.tbs_certrequest_bytes == binascii.unhexlify(
b"308201840201003057310b3009060355040613025553310e300c060355040813"
b"055465786173310f300d0603550407130641757374696e310d300b060355040a"
b"130450794341311830160603550403130f63727970746f6772617068792e696f"
b"30820122300d06092a864886f70d01010105000382010f003082010a02820101"
b"00a840a78460cb861066dfa3045a94ba6cf1b7ab9d24c761cffddcc2cb5e3f1d"
b"c3e4be253e7039ef14fe9d6d2304f50d9f2e1584c51530ab75086f357138bff7"
b"b854d067d1d5f384f1f2f2c39cc3b15415e2638554ef8402648ae3ef08336f22"
b"b7ecc6d4331c2b21c3091a7f7a9518180754a646640b60419e4cc6f5c798110a"
b"7f030a639fe87e33b4776dfcd993940ec776ab57a181ad8598857976dc303f9a"
b"573ca619ab3fe596328e92806b828683edc17cc256b41948a2bfa8d047d2158d"
b"3d8e069aa05fa85b3272abb1c4b4422b6366f3b70e642377b145cd6259e5d3e7"
b"db048d51921e50766a37b1b130ee6b11f507d20a834001e8de16a92c14f2e964"
b"a30203010001a000"
)
verifier = request.public_key().verifier(
request.signature,
padding.PKCS1v15(),
request.signature_hash_algorithm
)
verifier.update(request.tbs_certrequest_bytes)
verifier.verify()
def test_public_bytes_invalid_encoding(self, backend):
request = _load_cert(
os.path.join("x509", "requests", "rsa_sha1.pem"),
x509.load_pem_x509_csr,
backend
)
with pytest.raises(TypeError):
request.public_bytes('NotAnEncoding')
def test_signature_invalid(self, backend):
request = _load_cert(
os.path.join("x509", "requests", "invalid_signature.pem"),
x509.load_pem_x509_csr,
backend
)
assert not request.is_signature_valid
def test_signature_valid(self, backend):
request = _load_cert(
os.path.join("x509", "requests", "rsa_sha256.pem"),
x509.load_pem_x509_csr,
backend
)
assert request.is_signature_valid
@pytest.mark.parametrize(
("request_path", "loader_func", "encoding"),
[
(
os.path.join("x509", "requests", "rsa_sha1.pem"),
x509.load_pem_x509_csr,
serialization.Encoding.PEM,
),
(
os.path.join("x509", "requests", "rsa_sha1.der"),
x509.load_der_x509_csr,
serialization.Encoding.DER,
),
]
)
def test_public_bytes_match(self, request_path, loader_func, encoding,
backend):
request_bytes = load_vectors_from_file(
request_path, lambda pemfile: pemfile.read(), mode="rb"
)
request = loader_func(request_bytes, backend)
serialized = request.public_bytes(encoding)
assert serialized == request_bytes
def test_eq(self, backend):
request1 = _load_cert(
os.path.join("x509", "requests", "rsa_sha1.pem"),
x509.load_pem_x509_csr,
backend
)
request2 = _load_cert(
os.path.join("x509", "requests", "rsa_sha1.pem"),
x509.load_pem_x509_csr,
backend
)
assert request1 == request2
def test_ne(self, backend):
request1 = _load_cert(
os.path.join("x509", "requests", "rsa_sha1.pem"),
x509.load_pem_x509_csr,
backend
)
request2 = _load_cert(
os.path.join("x509", "requests", "san_rsa_sha1.pem"),
x509.load_pem_x509_csr,
backend
)
assert request1 != request2
assert request1 != object()
def test_hash(self, backend):
request1 = _load_cert(
os.path.join("x509", "requests", "rsa_sha1.pem"),
x509.load_pem_x509_csr,
backend
)
request2 = _load_cert(
os.path.join("x509", "requests", "rsa_sha1.pem"),
x509.load_pem_x509_csr,
backend
)
request3 = _load_cert(
os.path.join("x509", "requests", "san_rsa_sha1.pem"),
x509.load_pem_x509_csr,
backend
)
assert hash(request1) == hash(request2)
assert hash(request1) != hash(request3)
def test_build_cert(self, backend):
issuer_private_key = RSA_KEY_2048.private_key(backend)
subject_private_key = RSA_KEY_2048.private_key(backend)
not_valid_before = datetime.datetime(2002, 1, 1, 12, 1)
not_valid_after = datetime.datetime(2030, 12, 31, 8, 30)
builder = x509.CertificateBuilder().serial_number(
777
).issuer_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'Texas'),
x509.NameAttribute(NameOID.LOCALITY_NAME, u'Austin'),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'PyCA'),
x509.NameAttribute(NameOID.COMMON_NAME, u'cryptography.io'),
])).subject_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'Texas'),
x509.NameAttribute(NameOID.LOCALITY_NAME, u'Austin'),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'PyCA'),
x509.NameAttribute(NameOID.COMMON_NAME, u'cryptography.io'),
])).public_key(
subject_private_key.public_key()
).add_extension(
x509.BasicConstraints(ca=False, path_length=None), True,
).add_extension(
x509.SubjectAlternativeName([x509.DNSName(u"cryptography.io")]),
critical=False,
).not_valid_before(
not_valid_before
).not_valid_after(
not_valid_after
)
cert = builder.sign(issuer_private_key, hashes.SHA1(), backend)
assert cert.version is x509.Version.v3
assert cert.not_valid_before == not_valid_before
assert cert.not_valid_after == not_valid_after
basic_constraints = cert.extensions.get_extension_for_oid(
ExtensionOID.BASIC_CONSTRAINTS
)
assert basic_constraints.value.ca is False
assert basic_constraints.value.path_length is None
subject_alternative_name = cert.extensions.get_extension_for_oid(
ExtensionOID.SUBJECT_ALTERNATIVE_NAME
)
assert list(subject_alternative_name.value) == [
x509.DNSName(u"cryptography.io"),
]
def test_build_cert_printable_string_country_name(self, backend):
issuer_private_key = RSA_KEY_2048.private_key(backend)
subject_private_key = RSA_KEY_2048.private_key(backend)
not_valid_before = datetime.datetime(2002, 1, 1, 12, 1)
not_valid_after = datetime.datetime(2030, 12, 31, 8, 30)
builder = x509.CertificateBuilder().serial_number(
777
).issuer_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'Texas'),
])).subject_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'Texas'),
])).public_key(
subject_private_key.public_key()
).not_valid_before(
not_valid_before
).not_valid_after(
not_valid_after
)
cert = builder.sign(issuer_private_key, hashes.SHA256(), backend)
parsed, _ = decoder.decode(
cert.public_bytes(serialization.Encoding.DER),
asn1Spec=rfc2459.Certificate()
)
tbs_cert = parsed.getComponentByName('tbsCertificate')
subject = tbs_cert.getComponentByName('subject')
issuer = tbs_cert.getComponentByName('issuer')
# \x13 is printable string. The first byte of the value of the
# node corresponds to the ASN.1 string type.
assert subject[0][0][0][1][0] == b"\x13"[0]
assert issuer[0][0][0][1][0] == b"\x13"[0]
class TestCertificateBuilder(object):
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_checks_for_unsupported_extensions(self, backend):
private_key = RSA_KEY_2048.private_key(backend)
builder = x509.CertificateBuilder().subject_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])).issuer_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])).public_key(
private_key.public_key()
).serial_number(
777
).not_valid_before(
datetime.datetime(1999, 1, 1)
).not_valid_after(
datetime.datetime(2020, 1, 1)
).add_extension(
DummyExtension(), False
)
with pytest.raises(NotImplementedError):
builder.sign(private_key, hashes.SHA1(), backend)
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_encode_nonstandard_aia(self, backend):
private_key = RSA_KEY_2048.private_key(backend)
aia = x509.AuthorityInformationAccess([
x509.AccessDescription(
x509.ObjectIdentifier("2.999.7"),
x509.UniformResourceIdentifier(u"http://example.com")
),
])
builder = x509.CertificateBuilder().subject_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])).issuer_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])).public_key(
private_key.public_key()
).serial_number(
777
).not_valid_before(
datetime.datetime(1999, 1, 1)
).not_valid_after(
datetime.datetime(2020, 1, 1)
).add_extension(
aia, False
)
builder.sign(private_key, hashes.SHA256(), backend)
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_no_subject_name(self, backend):
subject_private_key = RSA_KEY_2048.private_key(backend)
builder = x509.CertificateBuilder().serial_number(
777
).issuer_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])).public_key(
subject_private_key.public_key()
).not_valid_before(
datetime.datetime(2002, 1, 1, 12, 1)
).not_valid_after(
datetime.datetime(2030, 12, 31, 8, 30)
)
with pytest.raises(ValueError):
builder.sign(subject_private_key, hashes.SHA256(), backend)
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_no_issuer_name(self, backend):
subject_private_key = RSA_KEY_2048.private_key(backend)
builder = x509.CertificateBuilder().serial_number(
777
).subject_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])).public_key(
subject_private_key.public_key()
).not_valid_before(
datetime.datetime(2002, 1, 1, 12, 1)
).not_valid_after(
datetime.datetime(2030, 12, 31, 8, 30)
)
with pytest.raises(ValueError):
builder.sign(subject_private_key, hashes.SHA256(), backend)
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_no_public_key(self, backend):
subject_private_key = RSA_KEY_2048.private_key(backend)
builder = x509.CertificateBuilder().serial_number(
777
).issuer_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])).subject_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])).not_valid_before(
datetime.datetime(2002, 1, 1, 12, 1)
).not_valid_after(
datetime.datetime(2030, 12, 31, 8, 30)
)
with pytest.raises(ValueError):
builder.sign(subject_private_key, hashes.SHA256(), backend)
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_no_not_valid_before(self, backend):
subject_private_key = RSA_KEY_2048.private_key(backend)
builder = x509.CertificateBuilder().serial_number(
777
).issuer_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])).subject_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])).public_key(
subject_private_key.public_key()
).not_valid_after(
datetime.datetime(2030, 12, 31, 8, 30)
)
with pytest.raises(ValueError):
builder.sign(subject_private_key, hashes.SHA256(), backend)
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_no_not_valid_after(self, backend):
subject_private_key = RSA_KEY_2048.private_key(backend)
builder = x509.CertificateBuilder().serial_number(
777
).issuer_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])).subject_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])).public_key(
subject_private_key.public_key()
).not_valid_before(
datetime.datetime(2002, 1, 1, 12, 1)
)
with pytest.raises(ValueError):
builder.sign(subject_private_key, hashes.SHA256(), backend)
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_no_serial_number(self, backend):
subject_private_key = RSA_KEY_2048.private_key(backend)
builder = x509.CertificateBuilder().issuer_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])).subject_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])).public_key(
subject_private_key.public_key()
).not_valid_before(
datetime.datetime(2002, 1, 1, 12, 1)
).not_valid_after(
datetime.datetime(2030, 12, 31, 8, 30)
)
with pytest.raises(ValueError):
builder.sign(subject_private_key, hashes.SHA256(), backend)
def test_issuer_name_must_be_a_name_type(self):
builder = x509.CertificateBuilder()
with pytest.raises(TypeError):
builder.issuer_name("subject")
with pytest.raises(TypeError):
builder.issuer_name(object)
def test_issuer_name_may_only_be_set_once(self):
name = x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])
builder = x509.CertificateBuilder().issuer_name(name)
with pytest.raises(ValueError):
builder.issuer_name(name)
def test_subject_name_must_be_a_name_type(self):
builder = x509.CertificateBuilder()
with pytest.raises(TypeError):
builder.subject_name("subject")
with pytest.raises(TypeError):
builder.subject_name(object)
def test_subject_name_may_only_be_set_once(self):
name = x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])
builder = x509.CertificateBuilder().subject_name(name)
with pytest.raises(ValueError):
builder.subject_name(name)
def test_not_valid_before_after_not_valid_after(self):
builder = x509.CertificateBuilder()
builder = builder.not_valid_after(
datetime.datetime(2002, 1, 1, 12, 1)
)
with pytest.raises(ValueError):
builder.not_valid_before(
datetime.datetime(2003, 1, 1, 12, 1)
)
def test_not_valid_after_before_not_valid_before(self):
builder = x509.CertificateBuilder()
builder = builder.not_valid_before(
datetime.datetime(2002, 1, 1, 12, 1)
)
with pytest.raises(ValueError):
builder.not_valid_after(
datetime.datetime(2001, 1, 1, 12, 1)
)
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_public_key_must_be_public_key(self, backend):
private_key = RSA_KEY_2048.private_key(backend)
builder = x509.CertificateBuilder()
with pytest.raises(TypeError):
builder.public_key(private_key)
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_public_key_may_only_be_set_once(self, backend):
private_key = RSA_KEY_2048.private_key(backend)
public_key = private_key.public_key()
builder = x509.CertificateBuilder().public_key(public_key)
with pytest.raises(ValueError):
builder.public_key(public_key)
def test_serial_number_must_be_an_integer_type(self):
with pytest.raises(TypeError):
x509.CertificateBuilder().serial_number(10.0)
def test_serial_number_must_be_non_negative(self):
with pytest.raises(ValueError):
x509.CertificateBuilder().serial_number(-10)
def test_serial_number_must_be_less_than_160_bits_long(self):
with pytest.raises(ValueError):
# 2 raised to the 160th power is actually 161 bits
x509.CertificateBuilder().serial_number(2 ** 160)
def test_serial_number_may_only_be_set_once(self):
builder = x509.CertificateBuilder().serial_number(10)
with pytest.raises(ValueError):
builder.serial_number(20)
def test_invalid_not_valid_after(self):
with pytest.raises(TypeError):
x509.CertificateBuilder().not_valid_after(104204304504)
with pytest.raises(TypeError):
x509.CertificateBuilder().not_valid_after(datetime.time())
with pytest.raises(ValueError):
x509.CertificateBuilder().not_valid_after(
datetime.datetime(1960, 8, 10)
)
def test_not_valid_after_may_only_be_set_once(self):
builder = x509.CertificateBuilder().not_valid_after(
datetime.datetime.now()
)
with pytest.raises(ValueError):
builder.not_valid_after(
datetime.datetime.now()
)
def test_invalid_not_valid_before(self):
with pytest.raises(TypeError):
x509.CertificateBuilder().not_valid_before(104204304504)
with pytest.raises(TypeError):
x509.CertificateBuilder().not_valid_before(datetime.time())
with pytest.raises(ValueError):
x509.CertificateBuilder().not_valid_before(
datetime.datetime(1960, 8, 10)
)
def test_not_valid_before_may_only_be_set_once(self):
builder = x509.CertificateBuilder().not_valid_before(
datetime.datetime.now()
)
with pytest.raises(ValueError):
builder.not_valid_before(
datetime.datetime.now()
)
def test_add_extension_checks_for_duplicates(self):
builder = x509.CertificateBuilder().add_extension(
x509.BasicConstraints(ca=False, path_length=None), True,
)
with pytest.raises(ValueError):
builder.add_extension(
x509.BasicConstraints(ca=False, path_length=None), True,
)
def test_add_invalid_extension_type(self):
builder = x509.CertificateBuilder()
with pytest.raises(TypeError):
builder.add_extension(object(), False)
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_sign_with_unsupported_hash(self, backend):
private_key = RSA_KEY_2048.private_key(backend)
builder = x509.CertificateBuilder()
builder = builder.subject_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u'US')])
).issuer_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u'US')])
).serial_number(
1
).public_key(
private_key.public_key()
).not_valid_before(
datetime.datetime(2002, 1, 1, 12, 1)
).not_valid_after(
datetime.datetime(2032, 1, 1, 12, 1)
)
with pytest.raises(TypeError):
builder.sign(private_key, object(), backend)
@pytest.mark.parametrize(
"cdp",
[
x509.CRLDistributionPoints([
x509.DistributionPoint(
full_name=None,
relative_name=x509.Name([
x509.NameAttribute(
NameOID.COMMON_NAME,
u"indirect CRL for indirectCRL CA3"
),
]),
reasons=None,
crl_issuer=[x509.DirectoryName(
x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
x509.NameAttribute(
NameOID.ORGANIZATION_NAME,
u"Test Certificates 2011"
),
x509.NameAttribute(
NameOID.ORGANIZATIONAL_UNIT_NAME,
u"indirectCRL CA3 cRLIssuer"
),
])
)],
)
]),
x509.CRLDistributionPoints([
x509.DistributionPoint(
full_name=[x509.DirectoryName(
x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
])
)],
relative_name=None,
reasons=None,
crl_issuer=[x509.DirectoryName(
x509.Name([
x509.NameAttribute(
NameOID.ORGANIZATION_NAME,
u"cryptography Testing"
),
])
)],
)
]),
x509.CRLDistributionPoints([
x509.DistributionPoint(
full_name=[
x509.UniformResourceIdentifier(
u"http://myhost.com/myca.crl"
),
x509.UniformResourceIdentifier(
u"http://backup.myhost.com/myca.crl"
)
],
relative_name=None,
reasons=frozenset([
x509.ReasonFlags.key_compromise,
x509.ReasonFlags.ca_compromise
]),
crl_issuer=[x509.DirectoryName(
x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
x509.NameAttribute(
NameOID.COMMON_NAME, u"cryptography CA"
),
])
)],
)
]),
x509.CRLDistributionPoints([
x509.DistributionPoint(
full_name=[x509.UniformResourceIdentifier(
u"http://domain.com/some.crl"
)],
relative_name=None,
reasons=frozenset([
x509.ReasonFlags.key_compromise,
x509.ReasonFlags.ca_compromise,
x509.ReasonFlags.affiliation_changed,
x509.ReasonFlags.superseded,
x509.ReasonFlags.privilege_withdrawn,
x509.ReasonFlags.cessation_of_operation,
x509.ReasonFlags.aa_compromise,
x509.ReasonFlags.certificate_hold,
]),
crl_issuer=None
)
]),
x509.CRLDistributionPoints([
x509.DistributionPoint(
full_name=None,
relative_name=None,
reasons=None,
crl_issuer=[x509.DirectoryName(
x509.Name([
x509.NameAttribute(
NameOID.COMMON_NAME, u"cryptography CA"
),
])
)],
)
]),
x509.CRLDistributionPoints([
x509.DistributionPoint(
full_name=[x509.UniformResourceIdentifier(
u"http://domain.com/some.crl"
)],
relative_name=None,
reasons=frozenset([x509.ReasonFlags.aa_compromise]),
crl_issuer=None
)
])
]
)
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_crl_distribution_points(self, backend, cdp):
issuer_private_key = RSA_KEY_2048.private_key(backend)
subject_private_key = RSA_KEY_2048.private_key(backend)
builder = x509.CertificateBuilder().serial_number(
4444444
).issuer_name(x509.Name([
x509.NameAttribute(NameOID.LOCALITY_NAME, u'Austin'),
])).subject_name(x509.Name([
x509.NameAttribute(NameOID.LOCALITY_NAME, u'Austin'),
])).public_key(
subject_private_key.public_key()
).add_extension(
cdp,
critical=False,
).not_valid_before(
datetime.datetime(2002, 1, 1, 12, 1)
).not_valid_after(
datetime.datetime(2030, 12, 31, 8, 30)
)
cert = builder.sign(issuer_private_key, hashes.SHA1(), backend)
ext = cert.extensions.get_extension_for_oid(
ExtensionOID.CRL_DISTRIBUTION_POINTS
)
assert ext.critical is False
assert ext.value == cdp
@pytest.mark.requires_backend_interface(interface=DSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_build_cert_with_dsa_private_key(self, backend):
if backend._lib.OPENSSL_VERSION_NUMBER < 0x10001000:
pytest.skip("Requires a newer OpenSSL. Must be >= 1.0.1")
issuer_private_key = DSA_KEY_2048.private_key(backend)
subject_private_key = DSA_KEY_2048.private_key(backend)
not_valid_before = datetime.datetime(2002, 1, 1, 12, 1)
not_valid_after = datetime.datetime(2030, 12, 31, 8, 30)
builder = x509.CertificateBuilder().serial_number(
777
).issuer_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])).subject_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])).public_key(
subject_private_key.public_key()
).add_extension(
x509.BasicConstraints(ca=False, path_length=None), True,
).add_extension(
x509.SubjectAlternativeName([x509.DNSName(u"cryptography.io")]),
critical=False,
).not_valid_before(
not_valid_before
).not_valid_after(
not_valid_after
)
cert = builder.sign(issuer_private_key, hashes.SHA1(), backend)
assert cert.version is x509.Version.v3
assert cert.not_valid_before == not_valid_before
assert cert.not_valid_after == not_valid_after
basic_constraints = cert.extensions.get_extension_for_oid(
ExtensionOID.BASIC_CONSTRAINTS
)
assert basic_constraints.value.ca is False
assert basic_constraints.value.path_length is None
subject_alternative_name = cert.extensions.get_extension_for_oid(
ExtensionOID.SUBJECT_ALTERNATIVE_NAME
)
assert list(subject_alternative_name.value) == [
x509.DNSName(u"cryptography.io"),
]
@pytest.mark.requires_backend_interface(interface=EllipticCurveBackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_build_cert_with_ec_private_key(self, backend):
if backend._lib.OPENSSL_VERSION_NUMBER < 0x10001000:
pytest.skip("Requires a newer OpenSSL. Must be >= 1.0.1")
_skip_curve_unsupported(backend, ec.SECP256R1())
issuer_private_key = ec.generate_private_key(ec.SECP256R1(), backend)
subject_private_key = ec.generate_private_key(ec.SECP256R1(), backend)
not_valid_before = datetime.datetime(2002, 1, 1, 12, 1)
not_valid_after = datetime.datetime(2030, 12, 31, 8, 30)
builder = x509.CertificateBuilder().serial_number(
777
).issuer_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])).subject_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])).public_key(
subject_private_key.public_key()
).add_extension(
x509.BasicConstraints(ca=False, path_length=None), True,
).add_extension(
x509.SubjectAlternativeName([x509.DNSName(u"cryptography.io")]),
critical=False,
).not_valid_before(
not_valid_before
).not_valid_after(
not_valid_after
)
cert = builder.sign(issuer_private_key, hashes.SHA1(), backend)
assert cert.version is x509.Version.v3
assert cert.not_valid_before == not_valid_before
assert cert.not_valid_after == not_valid_after
basic_constraints = cert.extensions.get_extension_for_oid(
ExtensionOID.BASIC_CONSTRAINTS
)
assert basic_constraints.value.ca is False
assert basic_constraints.value.path_length is None
subject_alternative_name = cert.extensions.get_extension_for_oid(
ExtensionOID.SUBJECT_ALTERNATIVE_NAME
)
assert list(subject_alternative_name.value) == [
x509.DNSName(u"cryptography.io"),
]
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_build_cert_with_rsa_key_too_small(self, backend):
issuer_private_key = RSA_KEY_512.private_key(backend)
subject_private_key = RSA_KEY_512.private_key(backend)
not_valid_before = datetime.datetime(2002, 1, 1, 12, 1)
not_valid_after = datetime.datetime(2030, 12, 31, 8, 30)
builder = x509.CertificateBuilder().serial_number(
777
).issuer_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])).subject_name(x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])).public_key(
subject_private_key.public_key()
).not_valid_before(
not_valid_before
).not_valid_after(
not_valid_after
)
with pytest.raises(ValueError):
builder.sign(issuer_private_key, hashes.SHA512(), backend)
@pytest.mark.parametrize(
"cp",
[
x509.CertificatePolicies([
x509.PolicyInformation(
x509.ObjectIdentifier("2.16.840.1.12345.1.2.3.4.1"),
[u"http://other.com/cps"]
)
]),
x509.CertificatePolicies([
x509.PolicyInformation(
x509.ObjectIdentifier("2.16.840.1.12345.1.2.3.4.1"),
None
)
]),
x509.CertificatePolicies([
x509.PolicyInformation(
x509.ObjectIdentifier("2.16.840.1.12345.1.2.3.4.1"),
[
u"http://example.com/cps",
u"http://other.com/cps",
x509.UserNotice(
x509.NoticeReference(u"my org", [1, 2, 3, 4]),
u"thing"
)
]
)
]),
x509.CertificatePolicies([
x509.PolicyInformation(
x509.ObjectIdentifier("2.16.840.1.12345.1.2.3.4.1"),
[
u"http://example.com/cps",
x509.UserNotice(
x509.NoticeReference(u"UTF8\u2122'", [1, 2, 3, 4]),
u"We heart UTF8!\u2122"
)
]
)
]),
x509.CertificatePolicies([
x509.PolicyInformation(
x509.ObjectIdentifier("2.16.840.1.12345.1.2.3.4.1"),
[x509.UserNotice(None, u"thing")]
)
]),
x509.CertificatePolicies([
x509.PolicyInformation(
x509.ObjectIdentifier("2.16.840.1.12345.1.2.3.4.1"),
[
x509.UserNotice(
x509.NoticeReference(u"my org", [1, 2, 3, 4]),
None
)
]
)
])
]
)
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_certificate_policies(self, cp, backend):
issuer_private_key = RSA_KEY_2048.private_key(backend)
subject_private_key = RSA_KEY_2048.private_key(backend)
not_valid_before = datetime.datetime(2002, 1, 1, 12, 1)
not_valid_after = datetime.datetime(2030, 12, 31, 8, 30)
cert = x509.CertificateBuilder().subject_name(
x509.Name([x509.NameAttribute(x509.OID_COUNTRY_NAME, u'US')])
).issuer_name(
x509.Name([x509.NameAttribute(x509.OID_COUNTRY_NAME, u'US')])
).not_valid_before(
not_valid_before
).not_valid_after(
not_valid_after
).public_key(
subject_private_key.public_key()
).serial_number(
123
).add_extension(
cp, critical=False
).sign(issuer_private_key, hashes.SHA256(), backend)
ext = cert.extensions.get_extension_for_oid(
x509.OID_CERTIFICATE_POLICIES
)
assert ext.value == cp
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_issuer_alt_name(self, backend):
issuer_private_key = RSA_KEY_2048.private_key(backend)
subject_private_key = RSA_KEY_2048.private_key(backend)
not_valid_before = datetime.datetime(2002, 1, 1, 12, 1)
not_valid_after = datetime.datetime(2030, 12, 31, 8, 30)
cert = x509.CertificateBuilder().subject_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u'US')])
).issuer_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u'US')])
).not_valid_before(
not_valid_before
).not_valid_after(
not_valid_after
).public_key(
subject_private_key.public_key()
).serial_number(
123
).add_extension(
x509.IssuerAlternativeName([
x509.DNSName(u"myissuer"),
x509.RFC822Name(u"email@domain.com"),
]), critical=False
).sign(issuer_private_key, hashes.SHA256(), backend)
ext = cert.extensions.get_extension_for_oid(
ExtensionOID.ISSUER_ALTERNATIVE_NAME
)
assert ext.critical is False
assert ext.value == x509.IssuerAlternativeName([
x509.DNSName(u"myissuer"),
x509.RFC822Name(u"email@domain.com"),
])
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_extended_key_usage(self, backend):
issuer_private_key = RSA_KEY_2048.private_key(backend)
subject_private_key = RSA_KEY_2048.private_key(backend)
not_valid_before = datetime.datetime(2002, 1, 1, 12, 1)
not_valid_after = datetime.datetime(2030, 12, 31, 8, 30)
cert = x509.CertificateBuilder().subject_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u'US')])
).issuer_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u'US')])
).not_valid_before(
not_valid_before
).not_valid_after(
not_valid_after
).public_key(
subject_private_key.public_key()
).serial_number(
123
).add_extension(
x509.ExtendedKeyUsage([
ExtendedKeyUsageOID.CLIENT_AUTH,
ExtendedKeyUsageOID.SERVER_AUTH,
ExtendedKeyUsageOID.CODE_SIGNING,
]), critical=False
).sign(issuer_private_key, hashes.SHA256(), backend)
eku = cert.extensions.get_extension_for_oid(
ExtensionOID.EXTENDED_KEY_USAGE
)
assert eku.critical is False
assert eku.value == x509.ExtendedKeyUsage([
ExtendedKeyUsageOID.CLIENT_AUTH,
ExtendedKeyUsageOID.SERVER_AUTH,
ExtendedKeyUsageOID.CODE_SIGNING,
])
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_inhibit_any_policy(self, backend):
issuer_private_key = RSA_KEY_2048.private_key(backend)
subject_private_key = RSA_KEY_2048.private_key(backend)
not_valid_before = datetime.datetime(2002, 1, 1, 12, 1)
not_valid_after = datetime.datetime(2030, 12, 31, 8, 30)
cert = x509.CertificateBuilder().subject_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u'US')])
).issuer_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u'US')])
).not_valid_before(
not_valid_before
).not_valid_after(
not_valid_after
).public_key(
subject_private_key.public_key()
).serial_number(
123
).add_extension(
x509.InhibitAnyPolicy(3), critical=False
).sign(issuer_private_key, hashes.SHA256(), backend)
ext = cert.extensions.get_extension_for_oid(
ExtensionOID.INHIBIT_ANY_POLICY
)
assert ext.value == x509.InhibitAnyPolicy(3)
@pytest.mark.parametrize(
"pc",
[
x509.PolicyConstraints(
require_explicit_policy=None,
inhibit_policy_mapping=1
),
x509.PolicyConstraints(
require_explicit_policy=3,
inhibit_policy_mapping=1
),
x509.PolicyConstraints(
require_explicit_policy=0,
inhibit_policy_mapping=None
),
]
)
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_policy_constraints(self, backend, pc):
issuer_private_key = RSA_KEY_2048.private_key(backend)
subject_private_key = RSA_KEY_2048.private_key(backend)
not_valid_before = datetime.datetime(2002, 1, 1, 12, 1)
not_valid_after = datetime.datetime(2030, 12, 31, 8, 30)
cert = x509.CertificateBuilder().subject_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u'US')])
).issuer_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u'US')])
).not_valid_before(
not_valid_before
).not_valid_after(
not_valid_after
).public_key(
subject_private_key.public_key()
).serial_number(
123
).add_extension(
pc, critical=False
).sign(issuer_private_key, hashes.SHA256(), backend)
ext = cert.extensions.get_extension_for_class(
x509.PolicyConstraints
)
assert ext.critical is False
assert ext.value == pc
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_name_constraints(self, backend):
issuer_private_key = RSA_KEY_2048.private_key(backend)
subject_private_key = RSA_KEY_2048.private_key(backend)
not_valid_before = datetime.datetime(2002, 1, 1, 12, 1)
not_valid_after = datetime.datetime(2030, 12, 31, 8, 30)
excluded = [x509.DNSName(u"name.local")]
nc = x509.NameConstraints(
permitted_subtrees=None, excluded_subtrees=excluded
)
cert = x509.CertificateBuilder().subject_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u'US')])
).issuer_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u'US')])
).not_valid_before(
not_valid_before
).not_valid_after(
not_valid_after
).public_key(
subject_private_key.public_key()
).serial_number(
123
).add_extension(
nc, critical=False
).sign(issuer_private_key, hashes.SHA256(), backend)
ext = cert.extensions.get_extension_for_oid(
ExtensionOID.NAME_CONSTRAINTS
)
assert ext.value == nc
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_key_usage(self, backend):
issuer_private_key = RSA_KEY_2048.private_key(backend)
subject_private_key = RSA_KEY_2048.private_key(backend)
not_valid_before = datetime.datetime(2002, 1, 1, 12, 1)
not_valid_after = datetime.datetime(2030, 12, 31, 8, 30)
cert = x509.CertificateBuilder().subject_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u'US')])
).issuer_name(
x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u'US')])
).not_valid_before(
not_valid_before
).not_valid_after(
not_valid_after
).public_key(
subject_private_key.public_key()
).serial_number(
123
).add_extension(
x509.KeyUsage(
digital_signature=True,
content_commitment=True,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=True,
crl_sign=False,
encipher_only=False,
decipher_only=False
),
critical=False
).sign(issuer_private_key, hashes.SHA256(), backend)
ext = cert.extensions.get_extension_for_oid(ExtensionOID.KEY_USAGE)
assert ext.critical is False
assert ext.value == x509.KeyUsage(
digital_signature=True,
content_commitment=True,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=True,
crl_sign=False,
encipher_only=False,
decipher_only=False
)
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_build_ca_request_with_path_length_none(self, backend):
private_key = RSA_KEY_2048.private_key(backend)
request = x509.CertificateSigningRequestBuilder().subject_name(
x509.Name([
x509.NameAttribute(NameOID.ORGANIZATION_NAME,
u'PyCA'),
])
).add_extension(
x509.BasicConstraints(ca=True, path_length=None), critical=True
).sign(private_key, hashes.SHA1(), backend)
loaded_request = x509.load_pem_x509_csr(
request.public_bytes(encoding=serialization.Encoding.PEM), backend
)
subject = loaded_request.subject
assert isinstance(subject, x509.Name)
basic_constraints = request.extensions.get_extension_for_oid(
ExtensionOID.BASIC_CONSTRAINTS
)
assert basic_constraints.value.path_length is None
@pytest.mark.parametrize(
"unrecognized", [
x509.UnrecognizedExtension(
x509.ObjectIdentifier("1.2.3.4.5"),
b"abcdef",
)
]
)
@pytest.mark.requires_backend_interface(interface=RSABackend)
@pytest.mark.requires_backend_interface(interface=X509Backend)
def test_unrecognized_extension(self, backend, unrecognized):
private_key = RSA_KEY_2048.private_key(backend)
cert = x509.CertificateBuilder().subject_name(
x509.Name([x509.NameAttribute(x509.OID_COUNTRY_NAME, u'US')])
).issuer_name(
x509.Name([x509.NameAttribute(x509.OID_COUNTRY_NAME, u'US')])
).not_valid_before(
datetime.datetime(2002, 1, 1, 12, 1)
).not_valid_after(
datetime.datetime(2030, 12, 31, 8, 30)
).public_key(
private_key.public_key()
).serial_number(
123
).add_extension(
unrecognized, critical=False
).sign(private_key, hashes.SHA256(), backend)
ext = cert.extensions.get_extension_for_oid(unrecognized.oid)
assert ext.value == unrecognized
@pytest.mark.requires_backend_interface(interface=X509Backend)
class TestCertificateSigningRequestBuilder(object):
@pytest.mark.requires_backend_interface(interface=RSABackend)
def test_sign_invalid_hash_algorithm(self, backend):
private_key = RSA_KEY_2048.private_key(backend)
builder = x509.CertificateSigningRequestBuilder().subject_name(
x509.Name([])
)
with pytest.raises(TypeError):
builder.sign(private_key, 'NotAHash', backend)
@pytest.mark.requires_backend_interface(interface=RSABackend)
def test_no_subject_name(self, backend):
private_key = RSA_KEY_2048.private_key(backend)
builder = x509.CertificateSigningRequestBuilder()
with pytest.raises(ValueError):
builder.sign(private_key, hashes.SHA256(), backend)
@pytest.mark.requires_backend_interface(interface=RSABackend)
def test_build_ca_request_with_rsa(self, backend):
private_key = RSA_KEY_2048.private_key(backend)
request = x509.CertificateSigningRequestBuilder().subject_name(
x509.Name([
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'PyCA'),
])
).add_extension(
x509.BasicConstraints(ca=True, path_length=2), critical=True
).sign(private_key, hashes.SHA1(), backend)
assert isinstance(request.signature_hash_algorithm, hashes.SHA1)
public_key = request.public_key()
assert isinstance(public_key, rsa.RSAPublicKey)
subject = request.subject
assert isinstance(subject, x509.Name)
assert list(subject) == [
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'PyCA'),
]
basic_constraints = request.extensions.get_extension_for_oid(
ExtensionOID.BASIC_CONSTRAINTS
)
assert basic_constraints.value.ca is True
assert basic_constraints.value.path_length == 2
@pytest.mark.requires_backend_interface(interface=RSABackend)
def test_build_ca_request_with_unicode(self, backend):
private_key = RSA_KEY_2048.private_key(backend)
request = x509.CertificateSigningRequestBuilder().subject_name(
x509.Name([
x509.NameAttribute(NameOID.ORGANIZATION_NAME,
u'PyCA\U0001f37a'),
])
).add_extension(
x509.BasicConstraints(ca=True, path_length=2), critical=True
).sign(private_key, hashes.SHA1(), backend)
loaded_request = x509.load_pem_x509_csr(
request.public_bytes(encoding=serialization.Encoding.PEM), backend
)
subject = loaded_request.subject
assert isinstance(subject, x509.Name)
assert list(subject) == [
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'PyCA\U0001f37a'),
]
@pytest.mark.requires_backend_interface(interface=RSABackend)
def test_build_nonca_request_with_rsa(self, backend):
private_key = RSA_KEY_2048.private_key(backend)
request = x509.CertificateSigningRequestBuilder().subject_name(
x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
])
).add_extension(
x509.BasicConstraints(ca=False, path_length=None), critical=True,
).sign(private_key, hashes.SHA1(), backend)
assert isinstance(request.signature_hash_algorithm, hashes.SHA1)
public_key = request.public_key()
assert isinstance(public_key, rsa.RSAPublicKey)
subject = request.subject
assert isinstance(subject, x509.Name)
assert list(subject) == [
x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
]
basic_constraints = request.extensions.get_extension_for_oid(
ExtensionOID.BASIC_CONSTRAINTS
)
assert basic_constraints.value.ca is False
assert basic_constraints.value.path_length is None
@pytest.mark.requires_backend_interface(interface=EllipticCurveBackend)
def test_build_ca_request_with_ec(self, backend):
if backend._lib.OPENSSL_VERSION_NUMBER < 0x10001000:
pytest.skip("Requires a newer OpenSSL. Must be >= 1.0.1")
_skip_curve_unsupported(backend, ec.SECP256R1())
private_key = ec.generate_private_key(ec.SECP256R1(), backend)
request = x509.CertificateSigningRequestBuilder().subject_name(
x509.Name([
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'Texas'),
])
).add_extension(
x509.BasicConstraints(ca=True, path_length=2), critical=True
).sign(private_key, hashes.SHA1(), backend)
assert isinstance(request.signature_hash_algorithm, hashes.SHA1)
public_key = request.public_key()
assert isinstance(public_key, ec.EllipticCurvePublicKey)
subject = request.subject
assert isinstance(subject, x509.Name)
assert list(subject) == [
x509.NameAttribute