123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998 |
- # 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.
- import abc
- import datetime
- import os
- import typing
- from cryptography import utils
- from cryptography.hazmat.backends import _get_backend
- from cryptography.hazmat.backends.interfaces import Backend
- from cryptography.hazmat.bindings._rust import x509 as rust_x509
- from cryptography.hazmat.primitives import hashes, serialization
- from cryptography.hazmat.primitives.asymmetric import (
- dsa,
- ec,
- ed25519,
- ed448,
- rsa,
- )
- from cryptography.hazmat.primitives.asymmetric.types import (
- PRIVATE_KEY_TYPES as PRIVATE_KEY_TYPES,
- PUBLIC_KEY_TYPES as PUBLIC_KEY_TYPES,
- )
- from cryptography.x509.extensions import Extension, ExtensionType, Extensions
- from cryptography.x509.name import Name
- from cryptography.x509.oid import ObjectIdentifier
- _EARLIEST_UTC_TIME = datetime.datetime(1950, 1, 1)
- class AttributeNotFound(Exception):
- def __init__(self, msg: str, oid: ObjectIdentifier) -> None:
- super(AttributeNotFound, self).__init__(msg)
- self.oid = oid
- def _reject_duplicate_extension(
- extension: Extension[ExtensionType],
- extensions: typing.List[Extension[ExtensionType]],
- ) -> None:
- # This is quadratic in the number of extensions
- for e in extensions:
- if e.oid == extension.oid:
- raise ValueError("This extension has already been set.")
- def _reject_duplicate_attribute(
- oid: ObjectIdentifier,
- attributes: typing.List[typing.Tuple[ObjectIdentifier, bytes]],
- ) -> None:
- # This is quadratic in the number of attributes
- for attr_oid, _ in attributes:
- if attr_oid == oid:
- raise ValueError("This attribute has already been set.")
- def _convert_to_naive_utc_time(time: datetime.datetime) -> datetime.datetime:
- """Normalizes a datetime to a naive datetime in UTC.
- time -- datetime to normalize. Assumed to be in UTC if not timezone
- aware.
- """
- if time.tzinfo is not None:
- offset = time.utcoffset()
- offset = offset if offset else datetime.timedelta()
- return time.replace(tzinfo=None) - offset
- else:
- return time
- class Version(utils.Enum):
- v1 = 0
- v3 = 2
- class InvalidVersion(Exception):
- def __init__(self, msg: str, parsed_version: int) -> None:
- super(InvalidVersion, self).__init__(msg)
- self.parsed_version = parsed_version
- class Certificate(metaclass=abc.ABCMeta):
- @abc.abstractmethod
- def fingerprint(self, algorithm: hashes.HashAlgorithm) -> bytes:
- """
- Returns bytes using digest passed.
- """
- @abc.abstractproperty
- def serial_number(self) -> int:
- """
- Returns certificate serial number
- """
- @abc.abstractproperty
- def version(self) -> Version:
- """
- Returns the certificate version
- """
- @abc.abstractmethod
- def public_key(self) -> PUBLIC_KEY_TYPES:
- """
- Returns the public key
- """
- @abc.abstractproperty
- def not_valid_before(self) -> datetime.datetime:
- """
- Not before time (represented as UTC datetime)
- """
- @abc.abstractproperty
- def not_valid_after(self) -> datetime.datetime:
- """
- Not after time (represented as UTC datetime)
- """
- @abc.abstractproperty
- def issuer(self) -> Name:
- """
- Returns the issuer name object.
- """
- @abc.abstractproperty
- def subject(self) -> Name:
- """
- Returns the subject name object.
- """
- @abc.abstractproperty
- def signature_hash_algorithm(
- self,
- ) -> typing.Optional[hashes.HashAlgorithm]:
- """
- Returns a HashAlgorithm corresponding to the type of the digest signed
- in the certificate.
- """
- @abc.abstractproperty
- def signature_algorithm_oid(self) -> ObjectIdentifier:
- """
- Returns the ObjectIdentifier of the signature algorithm.
- """
- @abc.abstractproperty
- def extensions(self) -> Extensions:
- """
- Returns an Extensions object.
- """
- @abc.abstractproperty
- def signature(self) -> bytes:
- """
- Returns the signature bytes.
- """
- @abc.abstractproperty
- def tbs_certificate_bytes(self) -> bytes:
- """
- Returns the tbsCertificate payload bytes as defined in RFC 5280.
- """
- @abc.abstractmethod
- def __eq__(self, other: object) -> bool:
- """
- Checks equality.
- """
- @abc.abstractmethod
- def __ne__(self, other: object) -> bool:
- """
- Checks not equal.
- """
- @abc.abstractmethod
- def __hash__(self) -> int:
- """
- Computes a hash.
- """
- @abc.abstractmethod
- def public_bytes(self, encoding: serialization.Encoding) -> bytes:
- """
- Serializes the certificate to PEM or DER format.
- """
- # Runtime isinstance checks need this since the rust class is not a subclass.
- Certificate.register(rust_x509.Certificate)
- class RevokedCertificate(metaclass=abc.ABCMeta):
- @abc.abstractproperty
- def serial_number(self) -> int:
- """
- Returns the serial number of the revoked certificate.
- """
- @abc.abstractproperty
- def revocation_date(self) -> datetime.datetime:
- """
- Returns the date of when this certificate was revoked.
- """
- @abc.abstractproperty
- def extensions(self) -> Extensions:
- """
- Returns an Extensions object containing a list of Revoked extensions.
- """
- # Runtime isinstance checks need this since the rust class is not a subclass.
- RevokedCertificate.register(rust_x509.RevokedCertificate)
- class CertificateRevocationList(metaclass=abc.ABCMeta):
- @abc.abstractmethod
- def public_bytes(self, encoding: serialization.Encoding) -> bytes:
- """
- Serializes the CRL to PEM or DER format.
- """
- @abc.abstractmethod
- def fingerprint(self, algorithm: hashes.HashAlgorithm) -> bytes:
- """
- Returns bytes using digest passed.
- """
- @abc.abstractmethod
- def get_revoked_certificate_by_serial_number(
- self, serial_number: int
- ) -> typing.Optional[RevokedCertificate]:
- """
- Returns an instance of RevokedCertificate or None if the serial_number
- is not in the CRL.
- """
- @abc.abstractproperty
- def signature_hash_algorithm(
- self,
- ) -> typing.Optional[hashes.HashAlgorithm]:
- """
- Returns a HashAlgorithm corresponding to the type of the digest signed
- in the certificate.
- """
- @abc.abstractproperty
- def signature_algorithm_oid(self) -> ObjectIdentifier:
- """
- Returns the ObjectIdentifier of the signature algorithm.
- """
- @abc.abstractproperty
- def issuer(self) -> Name:
- """
- Returns the X509Name with the issuer of this CRL.
- """
- @abc.abstractproperty
- def next_update(self) -> typing.Optional[datetime.datetime]:
- """
- Returns the date of next update for this CRL.
- """
- @abc.abstractproperty
- def last_update(self) -> datetime.datetime:
- """
- Returns the date of last update for this CRL.
- """
- @abc.abstractproperty
- def extensions(self) -> Extensions:
- """
- Returns an Extensions object containing a list of CRL extensions.
- """
- @abc.abstractproperty
- def signature(self) -> bytes:
- """
- Returns the signature bytes.
- """
- @abc.abstractproperty
- def tbs_certlist_bytes(self) -> bytes:
- """
- Returns the tbsCertList payload bytes as defined in RFC 5280.
- """
- @abc.abstractmethod
- def __eq__(self, other: object) -> bool:
- """
- Checks equality.
- """
- @abc.abstractmethod
- def __ne__(self, other: object) -> bool:
- """
- Checks not equal.
- """
- @abc.abstractmethod
- def __len__(self) -> int:
- """
- Number of revoked certificates in the CRL.
- """
- @typing.overload
- def __getitem__(self, idx: int) -> RevokedCertificate:
- ...
- @typing.overload
- def __getitem__(self, idx: slice) -> typing.List[RevokedCertificate]:
- ...
- @abc.abstractmethod
- def __getitem__(
- self, idx: typing.Union[int, slice]
- ) -> typing.Union[RevokedCertificate, typing.List[RevokedCertificate]]:
- """
- Returns a revoked certificate (or slice of revoked certificates).
- """
- @abc.abstractmethod
- def __iter__(self) -> typing.Iterator[RevokedCertificate]:
- """
- Iterator over the revoked certificates
- """
- @abc.abstractmethod
- def is_signature_valid(self, public_key: PUBLIC_KEY_TYPES) -> bool:
- """
- Verifies signature of revocation list against given public key.
- """
- CertificateRevocationList.register(rust_x509.CertificateRevocationList)
- class CertificateSigningRequest(metaclass=abc.ABCMeta):
- @abc.abstractmethod
- def __eq__(self, other: object) -> bool:
- """
- Checks equality.
- """
- @abc.abstractmethod
- def __ne__(self, other: object) -> bool:
- """
- Checks not equal.
- """
- @abc.abstractmethod
- def __hash__(self) -> int:
- """
- Computes a hash.
- """
- @abc.abstractmethod
- def public_key(self) -> PUBLIC_KEY_TYPES:
- """
- Returns the public key
- """
- @abc.abstractproperty
- def subject(self) -> Name:
- """
- Returns the subject name object.
- """
- @abc.abstractproperty
- def signature_hash_algorithm(
- self,
- ) -> typing.Optional[hashes.HashAlgorithm]:
- """
- Returns a HashAlgorithm corresponding to the type of the digest signed
- in the certificate.
- """
- @abc.abstractproperty
- def signature_algorithm_oid(self) -> ObjectIdentifier:
- """
- Returns the ObjectIdentifier of the signature algorithm.
- """
- @abc.abstractproperty
- def extensions(self) -> Extensions:
- """
- Returns the extensions in the signing request.
- """
- @abc.abstractmethod
- def public_bytes(self, encoding: serialization.Encoding) -> bytes:
- """
- Encodes the request to PEM or DER format.
- """
- @abc.abstractproperty
- def signature(self) -> bytes:
- """
- Returns the signature bytes.
- """
- @abc.abstractproperty
- def tbs_certrequest_bytes(self) -> bytes:
- """
- Returns the PKCS#10 CertificationRequestInfo bytes as defined in RFC
- 2986.
- """
- @abc.abstractproperty
- def is_signature_valid(self) -> bool:
- """
- Verifies signature of signing request.
- """
- @abc.abstractmethod
- def get_attribute_for_oid(self, oid: ObjectIdentifier) -> bytes:
- """
- Get the attribute value for a given OID.
- """
- # Runtime isinstance checks need this since the rust class is not a subclass.
- CertificateSigningRequest.register(rust_x509.CertificateSigningRequest)
- # Backend argument preserved for API compatibility, but ignored.
- def load_pem_x509_certificate(
- data: bytes, backend: typing.Any = None
- ) -> Certificate:
- return rust_x509.load_pem_x509_certificate(data)
- # Backend argument preserved for API compatibility, but ignored.
- def load_der_x509_certificate(
- data: bytes, backend: typing.Any = None
- ) -> Certificate:
- return rust_x509.load_der_x509_certificate(data)
- # Backend argument preserved for API compatibility, but ignored.
- def load_pem_x509_csr(
- data: bytes, backend: typing.Optional[Backend] = None
- ) -> CertificateSigningRequest:
- return rust_x509.load_pem_x509_csr(data)
- # Backend argument preserved for API compatibility, but ignored.
- def load_der_x509_csr(
- data: bytes, backend: typing.Optional[Backend] = None
- ) -> CertificateSigningRequest:
- return rust_x509.load_der_x509_csr(data)
- # Backend argument preserved for API compatibility, but ignored.
- def load_pem_x509_crl(
- data: bytes, backend: typing.Optional[Backend] = None
- ) -> CertificateRevocationList:
- return rust_x509.load_pem_x509_crl(data)
- # Backend argument preserved for API compatibility, but ignored.
- def load_der_x509_crl(
- data: bytes, backend: typing.Optional[Backend] = None
- ) -> CertificateRevocationList:
- return rust_x509.load_der_x509_crl(data)
- class CertificateSigningRequestBuilder(object):
- def __init__(
- self,
- subject_name: typing.Optional[Name] = None,
- extensions: typing.List[Extension[ExtensionType]] = [],
- attributes: typing.List[typing.Tuple[ObjectIdentifier, bytes]] = [],
- ):
- """
- Creates an empty X.509 certificate request (v1).
- """
- self._subject_name = subject_name
- self._extensions = extensions
- self._attributes = attributes
- def subject_name(self, name: Name) -> "CertificateSigningRequestBuilder":
- """
- Sets the certificate requestor's distinguished name.
- """
- if not isinstance(name, Name):
- raise TypeError("Expecting x509.Name object.")
- if self._subject_name is not None:
- raise ValueError("The subject name may only be set once.")
- return CertificateSigningRequestBuilder(
- name, self._extensions, self._attributes
- )
- def add_extension(
- self, extval: ExtensionType, critical: bool
- ) -> "CertificateSigningRequestBuilder":
- """
- Adds an X.509 extension to the certificate request.
- """
- if not isinstance(extval, ExtensionType):
- raise TypeError("extension must be an ExtensionType")
- extension = Extension(extval.oid, critical, extval)
- _reject_duplicate_extension(extension, self._extensions)
- return CertificateSigningRequestBuilder(
- self._subject_name,
- self._extensions + [extension],
- self._attributes,
- )
- def add_attribute(
- self, oid: ObjectIdentifier, value: bytes
- ) -> "CertificateSigningRequestBuilder":
- """
- Adds an X.509 attribute with an OID and associated value.
- """
- if not isinstance(oid, ObjectIdentifier):
- raise TypeError("oid must be an ObjectIdentifier")
- if not isinstance(value, bytes):
- raise TypeError("value must be bytes")
- _reject_duplicate_attribute(oid, self._attributes)
- return CertificateSigningRequestBuilder(
- self._subject_name,
- self._extensions,
- self._attributes + [(oid, value)],
- )
- def sign(
- self,
- private_key: PRIVATE_KEY_TYPES,
- algorithm: typing.Optional[hashes.HashAlgorithm],
- backend: typing.Optional[Backend] = None,
- ) -> CertificateSigningRequest:
- """
- Signs the request using the requestor's private key.
- """
- backend = _get_backend(backend)
- if self._subject_name is None:
- raise ValueError("A CertificateSigningRequest must have a subject")
- return backend.create_x509_csr(self, private_key, algorithm)
- class CertificateBuilder(object):
- _extensions: typing.List[Extension[ExtensionType]]
- def __init__(
- self,
- issuer_name: typing.Optional[Name] = None,
- subject_name: typing.Optional[Name] = None,
- public_key: typing.Optional[PUBLIC_KEY_TYPES] = None,
- serial_number: typing.Optional[int] = None,
- not_valid_before: typing.Optional[datetime.datetime] = None,
- not_valid_after: typing.Optional[datetime.datetime] = None,
- extensions: typing.List[Extension[ExtensionType]] = [],
- ) -> None:
- self._version = Version.v3
- self._issuer_name = issuer_name
- self._subject_name = subject_name
- self._public_key = public_key
- self._serial_number = serial_number
- self._not_valid_before = not_valid_before
- self._not_valid_after = not_valid_after
- self._extensions = extensions
- def issuer_name(self, name: Name) -> "CertificateBuilder":
- """
- Sets the CA's distinguished name.
- """
- if not isinstance(name, Name):
- raise TypeError("Expecting x509.Name object.")
- if self._issuer_name is not None:
- raise ValueError("The issuer name may only be set once.")
- return CertificateBuilder(
- name,
- self._subject_name,
- self._public_key,
- self._serial_number,
- self._not_valid_before,
- self._not_valid_after,
- self._extensions,
- )
- def subject_name(self, name: Name) -> "CertificateBuilder":
- """
- Sets the requestor's distinguished name.
- """
- if not isinstance(name, Name):
- raise TypeError("Expecting x509.Name object.")
- if self._subject_name is not None:
- raise ValueError("The subject name may only be set once.")
- return CertificateBuilder(
- self._issuer_name,
- name,
- self._public_key,
- self._serial_number,
- self._not_valid_before,
- self._not_valid_after,
- self._extensions,
- )
- def public_key(
- self,
- key: PUBLIC_KEY_TYPES,
- ) -> "CertificateBuilder":
- """
- Sets the requestor's public key (as found in the signing request).
- """
- if not isinstance(
- key,
- (
- dsa.DSAPublicKey,
- rsa.RSAPublicKey,
- ec.EllipticCurvePublicKey,
- ed25519.Ed25519PublicKey,
- ed448.Ed448PublicKey,
- ),
- ):
- raise TypeError(
- "Expecting one of DSAPublicKey, RSAPublicKey,"
- " EllipticCurvePublicKey, Ed25519PublicKey or"
- " Ed448PublicKey."
- )
- if self._public_key is not None:
- raise ValueError("The public key may only be set once.")
- return CertificateBuilder(
- self._issuer_name,
- self._subject_name,
- key,
- self._serial_number,
- self._not_valid_before,
- self._not_valid_after,
- self._extensions,
- )
- def serial_number(self, number: int) -> "CertificateBuilder":
- """
- Sets the certificate serial number.
- """
- if not isinstance(number, int):
- raise TypeError("Serial number must be of integral type.")
- if self._serial_number is not None:
- raise ValueError("The serial number may only be set once.")
- if number <= 0:
- raise ValueError("The serial number should be positive.")
- # ASN.1 integers are always signed, so most significant bit must be
- # zero.
- if number.bit_length() >= 160: # As defined in RFC 5280
- raise ValueError(
- "The serial number should not be more than 159 " "bits."
- )
- return CertificateBuilder(
- self._issuer_name,
- self._subject_name,
- self._public_key,
- number,
- self._not_valid_before,
- self._not_valid_after,
- self._extensions,
- )
- def not_valid_before(
- self, time: datetime.datetime
- ) -> "CertificateBuilder":
- """
- Sets the certificate activation time.
- """
- if not isinstance(time, datetime.datetime):
- raise TypeError("Expecting datetime object.")
- if self._not_valid_before is not None:
- raise ValueError("The not valid before may only be set once.")
- time = _convert_to_naive_utc_time(time)
- if time < _EARLIEST_UTC_TIME:
- raise ValueError(
- "The not valid before date must be on or after"
- " 1950 January 1)."
- )
- if self._not_valid_after is not None and time > self._not_valid_after:
- raise ValueError(
- "The not valid before date must be before the not valid after "
- "date."
- )
- return CertificateBuilder(
- self._issuer_name,
- self._subject_name,
- self._public_key,
- self._serial_number,
- time,
- self._not_valid_after,
- self._extensions,
- )
- def not_valid_after(self, time: datetime.datetime) -> "CertificateBuilder":
- """
- Sets the certificate expiration time.
- """
- if not isinstance(time, datetime.datetime):
- raise TypeError("Expecting datetime object.")
- if self._not_valid_after is not None:
- raise ValueError("The not valid after may only be set once.")
- time = _convert_to_naive_utc_time(time)
- if time < _EARLIEST_UTC_TIME:
- raise ValueError(
- "The not valid after date must be on or after"
- " 1950 January 1."
- )
- if (
- self._not_valid_before is not None
- and time < self._not_valid_before
- ):
- raise ValueError(
- "The not valid after date must be after the not valid before "
- "date."
- )
- return CertificateBuilder(
- self._issuer_name,
- self._subject_name,
- self._public_key,
- self._serial_number,
- self._not_valid_before,
- time,
- self._extensions,
- )
- def add_extension(
- self, extval: ExtensionType, critical: bool
- ) -> "CertificateBuilder":
- """
- Adds an X.509 extension to the certificate.
- """
- if not isinstance(extval, ExtensionType):
- raise TypeError("extension must be an ExtensionType")
- extension = Extension(extval.oid, critical, extval)
- _reject_duplicate_extension(extension, self._extensions)
- return CertificateBuilder(
- self._issuer_name,
- self._subject_name,
- self._public_key,
- self._serial_number,
- self._not_valid_before,
- self._not_valid_after,
- self._extensions + [extension],
- )
- def sign(
- self,
- private_key: PRIVATE_KEY_TYPES,
- algorithm: typing.Optional[hashes.HashAlgorithm],
- backend: typing.Optional[Backend] = None,
- ) -> Certificate:
- """
- Signs the certificate using the CA's private key.
- """
- backend = _get_backend(backend)
- if self._subject_name is None:
- raise ValueError("A certificate must have a subject name")
- if self._issuer_name is None:
- raise ValueError("A certificate must have an issuer name")
- if self._serial_number is None:
- raise ValueError("A certificate must have a serial number")
- if self._not_valid_before is None:
- raise ValueError("A certificate must have a not valid before time")
- if self._not_valid_after is None:
- raise ValueError("A certificate must have a not valid after time")
- if self._public_key is None:
- raise ValueError("A certificate must have a public key")
- return backend.create_x509_certificate(self, private_key, algorithm)
- class CertificateRevocationListBuilder(object):
- _extensions: typing.List[Extension[ExtensionType]]
- _revoked_certificates: typing.List[RevokedCertificate]
- def __init__(
- self,
- issuer_name: typing.Optional[Name] = None,
- last_update: typing.Optional[datetime.datetime] = None,
- next_update: typing.Optional[datetime.datetime] = None,
- extensions: typing.List[Extension[ExtensionType]] = [],
- revoked_certificates: typing.List[RevokedCertificate] = [],
- ):
- self._issuer_name = issuer_name
- self._last_update = last_update
- self._next_update = next_update
- self._extensions = extensions
- self._revoked_certificates = revoked_certificates
- def issuer_name(
- self, issuer_name: Name
- ) -> "CertificateRevocationListBuilder":
- if not isinstance(issuer_name, Name):
- raise TypeError("Expecting x509.Name object.")
- if self._issuer_name is not None:
- raise ValueError("The issuer name may only be set once.")
- return CertificateRevocationListBuilder(
- issuer_name,
- self._last_update,
- self._next_update,
- self._extensions,
- self._revoked_certificates,
- )
- def last_update(
- self, last_update: datetime.datetime
- ) -> "CertificateRevocationListBuilder":
- if not isinstance(last_update, datetime.datetime):
- raise TypeError("Expecting datetime object.")
- if self._last_update is not None:
- raise ValueError("Last update may only be set once.")
- last_update = _convert_to_naive_utc_time(last_update)
- if last_update < _EARLIEST_UTC_TIME:
- raise ValueError(
- "The last update date must be on or after" " 1950 January 1."
- )
- if self._next_update is not None and last_update > self._next_update:
- raise ValueError(
- "The last update date must be before the next update date."
- )
- return CertificateRevocationListBuilder(
- self._issuer_name,
- last_update,
- self._next_update,
- self._extensions,
- self._revoked_certificates,
- )
- def next_update(
- self, next_update: datetime.datetime
- ) -> "CertificateRevocationListBuilder":
- if not isinstance(next_update, datetime.datetime):
- raise TypeError("Expecting datetime object.")
- if self._next_update is not None:
- raise ValueError("Last update may only be set once.")
- next_update = _convert_to_naive_utc_time(next_update)
- if next_update < _EARLIEST_UTC_TIME:
- raise ValueError(
- "The last update date must be on or after" " 1950 January 1."
- )
- if self._last_update is not None and next_update < self._last_update:
- raise ValueError(
- "The next update date must be after the last update date."
- )
- return CertificateRevocationListBuilder(
- self._issuer_name,
- self._last_update,
- next_update,
- self._extensions,
- self._revoked_certificates,
- )
- def add_extension(
- self, extval: ExtensionType, critical: bool
- ) -> "CertificateRevocationListBuilder":
- """
- Adds an X.509 extension to the certificate revocation list.
- """
- if not isinstance(extval, ExtensionType):
- raise TypeError("extension must be an ExtensionType")
- extension = Extension(extval.oid, critical, extval)
- _reject_duplicate_extension(extension, self._extensions)
- return CertificateRevocationListBuilder(
- self._issuer_name,
- self._last_update,
- self._next_update,
- self._extensions + [extension],
- self._revoked_certificates,
- )
- def add_revoked_certificate(
- self, revoked_certificate: RevokedCertificate
- ) -> "CertificateRevocationListBuilder":
- """
- Adds a revoked certificate to the CRL.
- """
- if not isinstance(revoked_certificate, RevokedCertificate):
- raise TypeError("Must be an instance of RevokedCertificate")
- return CertificateRevocationListBuilder(
- self._issuer_name,
- self._last_update,
- self._next_update,
- self._extensions,
- self._revoked_certificates + [revoked_certificate],
- )
- def sign(
- self,
- private_key: PRIVATE_KEY_TYPES,
- algorithm: typing.Optional[hashes.HashAlgorithm],
- backend: typing.Optional[Backend] = None,
- ) -> CertificateRevocationList:
- backend = _get_backend(backend)
- if self._issuer_name is None:
- raise ValueError("A CRL must have an issuer name")
- if self._last_update is None:
- raise ValueError("A CRL must have a last update time")
- if self._next_update is None:
- raise ValueError("A CRL must have a next update time")
- return backend.create_x509_crl(self, private_key, algorithm)
- class RevokedCertificateBuilder(object):
- def __init__(
- self,
- serial_number: typing.Optional[int] = None,
- revocation_date: typing.Optional[datetime.datetime] = None,
- extensions: typing.List[Extension[ExtensionType]] = [],
- ):
- self._serial_number = serial_number
- self._revocation_date = revocation_date
- self._extensions = extensions
- def serial_number(self, number: int) -> "RevokedCertificateBuilder":
- if not isinstance(number, int):
- raise TypeError("Serial number must be of integral type.")
- if self._serial_number is not None:
- raise ValueError("The serial number may only be set once.")
- if number <= 0:
- raise ValueError("The serial number should be positive")
- # ASN.1 integers are always signed, so most significant bit must be
- # zero.
- if number.bit_length() >= 160: # As defined in RFC 5280
- raise ValueError(
- "The serial number should not be more than 159 " "bits."
- )
- return RevokedCertificateBuilder(
- number, self._revocation_date, self._extensions
- )
- def revocation_date(
- self, time: datetime.datetime
- ) -> "RevokedCertificateBuilder":
- if not isinstance(time, datetime.datetime):
- raise TypeError("Expecting datetime object.")
- if self._revocation_date is not None:
- raise ValueError("The revocation date may only be set once.")
- time = _convert_to_naive_utc_time(time)
- if time < _EARLIEST_UTC_TIME:
- raise ValueError(
- "The revocation date must be on or after" " 1950 January 1."
- )
- return RevokedCertificateBuilder(
- self._serial_number, time, self._extensions
- )
- def add_extension(
- self, extval: ExtensionType, critical: bool
- ) -> "RevokedCertificateBuilder":
- if not isinstance(extval, ExtensionType):
- raise TypeError("extension must be an ExtensionType")
- extension = Extension(extval.oid, critical, extval)
- _reject_duplicate_extension(extension, self._extensions)
- return RevokedCertificateBuilder(
- self._serial_number,
- self._revocation_date,
- self._extensions + [extension],
- )
- def build(
- self, backend: typing.Optional[Backend] = None
- ) -> RevokedCertificate:
- backend = _get_backend(backend)
- if self._serial_number is None:
- raise ValueError("A revoked certificate must have a serial number")
- if self._revocation_date is None:
- raise ValueError(
- "A revoked certificate must have a revocation date"
- )
- return backend.create_x509_revoked_certificate(self)
- def random_serial_number() -> int:
- return int.from_bytes(os.urandom(20), "big") >> 1
|