django_ca.models - django-ca models

django-ca uses three classes, called “models” in Django terminology, to store everything in the database. They are the core classes for this project, if you want to use this project programmatically, you’ll have to use these classes:

  • CertificateAuthority is used to store certificate authorities.

  • Certificate is used to store certificates.

  • Finally, Watcher stores email addresses for who should be notified if certificates expire.

Note that both CertificateAuthority and Certificate inherit from X509CertMixin, which provides many common convenience methods.

CertificateAuthority

class django_ca.models.CertificateAuthority(*args, **kwargs)[source]

Model representing a x509 Certificate Authority.

property allows_intermediate_ca: bool

Whether this CA allows creating intermediate CAs.

property bundle: list[CertificateAuthority]

A list of any parent CAs, including this CA.

The list is ordered so the Root CA will be the first.

cache_crls(key_backend_options: BaseModel) None[source]

Function to cache all CRLs for this CA.

Changed in version 1.25.0: Support for passing a custom hash algorithm to this function was removed.

check_usable(options: BaseModel) None[source]

Shortcut determining if the key is usable and raise ValueError otherwise.

property extensions_for_certificate: dict[ObjectIdentifier, Extension[Admissions] | Extension[AuthorityInformationAccess] | Extension[CertificatePolicies] | Extension[CRLDistributionPoints] | Extension[ExtendedKeyUsage] | Extension[FreshestCRL] | Extension[IssuerAlternativeName] | Extension[KeyUsage] | Extension[MSCertificateTemplate] | Extension[OCSPNoCheck] | Extension[PrecertPoison] | Extension[SubjectAlternativeName] | Extension[TLSFeature]]

Get a list of extensions to use for the certificate.

generate_ocsp_key(key_backend_options: BaseModel, key_type: Literal['RSA', 'DSA', 'EC', 'Ed25519', 'Ed448'] | None = None, key_size: int | None = None, elliptic_curve: EllipticCurve | None = None, profile: str = 'ocsp', algorithm: SHA224 | SHA256 | SHA384 | SHA512 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | None = None, not_after: datetime | timedelta | None = None, expires: datetime | timedelta | None = None, autogenerated: bool = True, force: bool = False) Certificate | None[source]

Generate OCSP authorized responder certificate.

By default, the certificate will have the same private and public key types as the signing certificate authority. The certificate’s subject will be the common name of the certificate authority with the suffix OCSP responder delegate certificate added, all other subject fields are discarded.

RFC 6960 does not specify much about how a certificate for an authorized responder should look like. The default ocsp profile will create a valid certificate that is usable for all known applications, but you a different profile can be used to add any extension values to the certificate.

Deprecated since version 2.1.0: The expires parameter is deprecated and will be removed in django-ca 2.3.0. use not_after instead.

Changed in version 1.26.0:

Changed in version 1.23.0:

  • The ecc_curve option was renamed to elliptic_curve.

  • The key_type, key_size, elliptic_curve and algorithm parameters now default to what was used in the certificate authority.

Parameters:
key_backend_optionsBaseModel

Options required for using the private key of the certificate authority.

profilestr, optional

The profile to use for generating the certificate. The default is "ocsp".

not_afterint or datetime, optional

Number of days or datetime when this certificate expires. The default is 3 (OCSP certificates are usually renewed frequently).

algorithmHashAlgorithm, optional

Hash algorithm used for signing the OCSP key. Defaults to the algorithm the certificate authority was signed with.

key_sizeint, optional

The key size of the private key, defaults to CA_DEFAULT_KEY_SIZE.

key_type{“RSA”, “DSA”, “EC”, “Ed25519”, “Ed448”}, optional

The private key type to use. The default is to use the same key type as the signing CA.

elliptic_curveEllipticCurve, optional

An elliptic curve to use for EC keys. This parameter is ignored if key_type is not "EC". Defaults to the CA_DEFAULT_ELLIPTIC_CURVE.

autogeneratedbool, optional

Set the autogenerated flag of the certificate. True by default, since this method is usually automatically invoked on a regular basis.

forcebool, optional

Set to True to force regeneration of keys. By default, keys are only regenerated if they expire within CA_OCSP_RESPONDER_CERTIFICATE_RENEWAL.

get_authority_key_identifier() AuthorityKeyIdentifier[source]

Return the AuthorityKeyIdentifier extension used in certificates signed by this CA.

get_authority_key_identifier_extension() Extension[AuthorityKeyIdentifier][source]

Get the AuthorityKeyIdentifier extension to use in certificates signed by this CA.

get_crl(key_backend_options: BaseModel, expires: int = 86400, algorithm: SHA224 | SHA256 | SHA384 | SHA512 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | None = None, scope: Literal[None, 'ca', 'user', 'attribute'] | None = None, counter: str | None = None, full_name: Iterable[GeneralName] | None = None, relative_name: RelativeDistinguishedName | None = None, include_issuing_distribution_point: bool | None = None) CertificateRevocationList[source]

Generate a Certificate Revocation List (CRL).

Deprecated since version 2.1.0: This function is deprecated and will be removed in django-ca 2.3.0.

Changed in version 2.1.0: The algorithm, counter, full_name, relative_name and include_issuing_distribution_point parameters no longer have any effect. Using them will issue an additional warning.

Parameters:
key_backend_optionsBaseModel

Options required for using the private key of the certificate authority.

expiresint

The time in seconds when this CRL expires. Note that you should generate a new CRL until then.

scope{None, ‘ca’, ‘user’, ‘attribute’}, optional

What to include in the CRL: Use "ca" to include only revoked certificate authorities and "user" to include only certificates or None (the default) to include both.

get_crl_certs(scope: Literal[None, 'ca', 'user'], now: datetime) Iterable[X509CertMixin][source]

Get CRLs for the given scope.

Deprecated since version 2.1.0: This function is deprecated and will be removed in django-ca 2.3.0.

get_end_entity_certificate_extensions(public_key: DSAPublicKey | RSAPublicKey | EllipticCurvePublicKey | Ed25519PublicKey | Ed448PublicKey) list[Extension[Admissions] | Extension[AuthorityInformationAccess] | Extension[CertificatePolicies] | Extension[CRLDistributionPoints] | Extension[ExtendedKeyUsage] | Extension[FreshestCRL] | Extension[IssuerAlternativeName] | Extension[KeyUsage] | Extension[MSCertificateTemplate] | Extension[OCSPNoCheck] | Extension[PrecertPoison] | Extension[SubjectAlternativeName] | Extension[TLSFeature] | Extension[AuthorityKeyIdentifier] | Extension[BasicConstraints] | Extension[PrecertificateSignedCertificateTimestamps] | Extension[SignedCertificateTimestamps] | Extension[SubjectInformationAccess] | Extension[SubjectKeyIdentifier]][source]

Get extensions that are unconditionally added to every end entity certificates.

property is_openssh_ca: bool

True if this CA is an OpenSSH CA.

is_usable(options: BaseModel | None = None) bool[source]

Shortcut determining if the certificate authority can be used for signing.

property key_backend: KeyBackend[BaseModel, BaseModel, BaseModel]

The key backend that can be used to use the private key.

property key_type: Literal['RSA', 'DSA', 'EC', 'Ed25519', 'Ed448']

The type of key as a string, e.g. “RSA” or “Ed448”.

property max_path_length: int | None

The maximum path length for any intermediate CAs signed by this CA.

This value is either None, if this and all parent CAs don’t have a path_length attribute, or an int if any parent CA has the attribute.

property ocsp_key_backend: OCSPKeyBackend

The key backend for the OCSP responder.

property path_length: int | None

The path_length attribute of the BasicConstraints extension.

property root: CertificateAuthority

Get the root CA for this CA.

sign(key_backend_options: BaseModel, csr: CertificateSigningRequest, subject: Name, algorithm: SHA224 | SHA256 | SHA384 | SHA512 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | None = None, not_after: datetime | None = None, expires: datetime | None = None, extensions: list[Extension[Admissions] | Extension[AuthorityInformationAccess] | Extension[CertificatePolicies] | Extension[CRLDistributionPoints] | Extension[ExtendedKeyUsage] | Extension[FreshestCRL] | Extension[IssuerAlternativeName] | Extension[KeyUsage] | Extension[MSCertificateTemplate] | Extension[OCSPNoCheck] | Extension[PrecertPoison] | Extension[SubjectAlternativeName] | Extension[TLSFeature]] | None = None) Certificate[source]

Create a signed certificate.

This function is a low-level signing function, with optional values taken from the configuration.

Required extensions are added if not provided. Unless already included in extensions, this function will add the AuthorityKeyIdentifier, BasicConstraints and SubjectKeyIdentifier extensions with values coming from the certificate authority.

Deprecated since version 2.1.0: The expires parameter is deprecated and will be removed in django-ca 2.3.0. use not_after instead.

Parameters:
key_backend_optionsBaseModel

Options required for using the private key of the certificate authority.

csrCertificateSigningRequest

The certificate signing request to sign.

subjectName

Subject for the certificate

algorithmHashAlgorithm, optional

Hash algorithm used for signing the certificate, defaults to the algorithm used in the CA.

not_afterdatetime, optional

When the certificate expires. If not provided, the CA_DEFAULT_EXPIRES setting will be used.

extensionslist of Extension, optional

List of extensions to add to the certificates. The function will add some extensions unless provided here, see above for details.

sign_data(data: bytes, key_backend_options: BaseModel | None = None, algorithm: HashAlgorithm | Prehashed | None = None, padding: AsymmetricPadding | None = None, signature_algorithm: EllipticCurveSignatureAlgorithm | None = None) bytes[source]

Shortcut to sign data using this certificate authority with its key backend.

All parameters except data will use sane default parameters, but they can be overridden in case you need to provide your own parameters for generating the signature.

Error handling will depend on the key backend used by this certificate authority. For example, a key backend may not support signing data at all or may not support a specific signature algorithm.

Parameters:
databytes

The data to sign.

key_backend_optionsBaseModel, optional

Key backend options, by default a model for the respective key backend will be created without any parameters.

algorithmHashAlgorithm or Prehashed, optional

The algorithm used for signing with RSA and DSA-based keys or Prehashed if data is already signed. The default is the algorithm is used for signing the CAs certificate.

paddingAsymmetricPadding, optional

The padding used for signing with RSA-based keys. The default is PSS padding using the maximum salt length and MGF1 with the value of algorithm as its algorithm.

signature_algorithmEllipticCurveSignatureAlgorithm, optional

The signature algorithm used for signing with Elliptic Curve based keys. The default is ECDSA with SHA512.

property usable: bool

True if the CA is currently usable or not.

Creating CAs

Use CertificateAuthority.objects.init() to create new certificate authorities. The method has many options but is designed to provide defaults that work in most cases:

>>> from datetime import datetime, timedelta, timezone
>>> from cryptography.x509.oid import NameOID
>>> from django_ca.key_backends import key_backends
>>> from django_ca.key_backends.storages.models import (
...     StoragesCreatePrivateKeyOptions,
...     StoragesUsePrivateKeyOptions,
... )
>>> from django_ca.models import CertificateAuthority
>>> key_backend = key_backends["default"]
>>> key_backend_options = StoragesCreatePrivateKeyOptions(
...     key_type="RSA", key_size=1024, password=None, path="ca"
... )
>>> not_after = datetime.now(tz=timezone.utc) + timedelta(days=365 * 10)
>>> ca = CertificateAuthority.objects.init(
...     name='ca',
...     key_backend=key_backends["default"],
...     key_backend_options=key_backend_options,
...     subject=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "example.com")]),
...     not_after=not_after,
...     path_length=1,  # so we can create one level of intermediate CAs
... )
>>> ca
<CertificateAuthority: ca>

This CA will contain all properties and X509 extensions to be a fully functioning CA. To create an intermediate CA, simply pass the parent:

>>> child = CertificateAuthority.objects.init(
...     name='child',
...     key_backend=key_backends["default"],
...     key_backend_options=key_backend_options,
...     use_parent_private_key_options=StoragesUsePrivateKeyOptions(password=None),
...     subject=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "child.example.com")]),
...     not_after=not_after,
...     parent=ca
... )
>>> child.parent
<CertificateAuthority: ca>
>>> ca.children.all()
<CertificateAuthorityQuerySet [<CertificateAuthority: child>]>

Or to create a CA with all extensions that live CAs have, you can pass many more parameters:

>>> from cryptography import x509
>>> from cryptography.x509.oid import AuthorityInformationAccessOID, ExtensionOID
>>> full = CertificateAuthority.objects.init(
...     name='full',
...     key_backend=key_backends["default"],
...     key_backend_options=key_backend_options,
...     subject=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "full.example.com")]),
...     not_after=not_after,
...     parent=ca,  # some extensions are only valid for intermediate CAs
...     use_parent_private_key_options=StoragesUsePrivateKeyOptions(password=None),
...
...     # Extensions for the certificate authority itself
...     extensions=[
...         x509.Extension(
...             oid=ExtensionOID.NAME_CONSTRAINTS,
...             critical=True,
...             value=x509.NameConstraints(
...                 permitted_subtrees=[x509.DNSName('.com')],
...                 excluded_subtrees=None
...             ),
...         ),
...         x509.Extension(
...             oid=ExtensionOID.INHIBIT_ANY_POLICY,
...             critical=True,
...             value=x509.InhibitAnyPolicy(0)
...         )
...     ],
... )

You can also add extensions to be added to certificates when they are signed by this CA. These parameters can always be added later (but of course, only new certificates will have the changed values).

Note

The Authority Information Access extension and the CRL Distribution Points extension are added automatically if you have the CA_DEFAULT_HOSTNAME setting configured. If you still give the parameters to init(), the default values will be overwritten.

>>> from cryptography import x509
>>> from cryptography.x509.oid import AuthorityInformationAccessOID, CertificatePoliciesOID, ExtensionOID
>>> authority_information_access = x509.Extension(
...     oid=ExtensionOID.AUTHORITY_INFORMATION_ACCESS,
...     critical=False,  # RFC 5280 says it should not be critical
...     value=x509.AuthorityInformationAccess(
...         [
...             x509.AccessDescription(
...                 access_method=AuthorityInformationAccessOID.OCSP,
...                 access_location=x509.UniformResourceIdentifier("http://ca.example.com/ocsp")
...             )
...         ]
...     )
... )
>>> certificate_policies = x509.Extension(
...     oid=ExtensionOID.CERTIFICATE_POLICIES,
...     critical=False,  # RFC 5280 says it should not be critical
...     value=x509.CertificatePolicies(
...          [
...              x509.PolicyInformation(
...                  policy_identifier=CertificatePoliciesOID.CPS_USER_NOTICE,
...                  policy_qualifiers=["https://ca.example.com/cps"]
...              )
...          ]
...     )
... )
>>> crl_distribution_points = x509.Extension(
...     oid=ExtensionOID.CRL_DISTRIBUTION_POINTS,
...     critical=False,
...     value=x509.CRLDistributionPoints(
...         [
...             x509.DistributionPoint(
...                 full_name=[x509.UniformResourceIdentifier("http://ca.example.com/crl")],
...                 relative_name=None,
...                 crl_issuer=None,
...                 reasons=None
...             )
...         ]
...     )
... )
>>> issuer_alternative_name = x509.Extension(
...     oid=ExtensionOID.ISSUER_ALTERNATIVE_NAME,
...     critical=False,
...     value=x509.IssuerAlternativeName(
...         [
...             x509.UniformResourceIdentifier("https://ca.example.com")
...         ]
...     )
... )
>>> CertificateAuthority.objects.init(
...     name='add-extensions',
...     key_backend=key_backends["default"],
...     key_backend_options=key_backend_options,
...     subject=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "add-extensions")]),
...     not_after=not_after,
...     sign_authority_information_access=authority_information_access,
...     sign_certificate_policies=certificate_policies,
...     sign_crl_distribution_points=crl_distribution_points,
...     sign_issuer_alternative_name=None,
... )
<CertificateAuthority: add-extensions>

There are some more parameters to configure how the CA will be signed:

>>> from cryptography.hazmat.primitives.asymmetric import ec
>>> from cryptography.hazmat.primitives import hashes
>>> key_backend_options = StoragesCreatePrivateKeyOptions(
...     key_type="EC", elliptic_curve=ec.SECP256R1(), password=b"secret", path="ca"
... )
>>> CertificateAuthority.objects.init(
...     name="props",
...     key_backend=key_backends["default"],
...     key_backend_options=key_backend_options,
...     subject=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "child.example.com")]),
...     not_after=not_after,
...     algorithm=hashes.SHA256(),  # SHA512 would be the default
...     path_length=3,  # three levels of intermediate CAs allowed,
...     key_type='EC',  # create a private key using Elliptic Curve cryptography
... )
<CertificateAuthority: props>

Here are all parameters for creating CAs:

CertificateAuthorityManager.init(name: str, key_backend: KeyBackend[Any, Any, Any], key_backend_options: BaseModel, subject: Name, not_after: datetime | None = None, expires: datetime | None = None, algorithm: SHA224 | SHA256 | SHA384 | SHA512 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | None = None, parent: CertificateAuthority | None = None, use_parent_private_key_options: BaseModel | None = None, default_hostname: bool | str | None = None, path_length: int | None = None, key_type: Literal['RSA', 'DSA', 'EC', 'Ed25519', 'Ed448'] = 'RSA', extensions: Iterable[Extension[Admissions] | Extension[AuthorityInformationAccess] | Extension[CertificatePolicies] | Extension[CRLDistributionPoints] | Extension[ExtendedKeyUsage] | Extension[FreshestCRL] | Extension[IssuerAlternativeName] | Extension[KeyUsage] | Extension[MSCertificateTemplate] | Extension[OCSPNoCheck] | Extension[PrecertPoison] | Extension[SubjectAlternativeName] | Extension[TLSFeature] | Extension[AuthorityKeyIdentifier] | Extension[BasicConstraints] | Extension[PrecertificateSignedCertificateTimestamps] | Extension[SignedCertificateTimestamps] | Extension[SubjectInformationAccess] | Extension[SubjectKeyIdentifier] | Extension[InhibitAnyPolicy] | Extension[NameConstraints] | Extension[PolicyConstraints] | Extension[UnrecognizedExtension]] | None = None, caa: str = '', website: str = '', terms_of_service: str = '', acme_enabled: bool = False, acme_registration: bool = True, acme_requires_contact: bool = True, acme_profile: str | None = None, openssh_ca: bool = False, sign_authority_information_access: Extension[AuthorityInformationAccess] | None = None, sign_certificate_policies: Extension[CertificatePolicies] | None = None, sign_crl_distribution_points: Extension[CRLDistributionPoints] | None = None, sign_issuer_alternative_name: Extension[IssuerAlternativeName] | None = None, ocsp_key_backend_alias: str = 'default', ocsp_responder_key_validity: int | None = None, ocsp_response_validity: int | None = None, api_enabled: bool | None = None) CertificateAuthority[source]

Create a new certificate authority.

Deprecated since version 2.1.0: The expires parameter is deprecated and will be removed in django-ca 2.3.0. use not_after instead.

Changed in version 2.0.0:

  • Support for passing an int or timedelta for expires has been deprecated and will be removed in django-ca 2.0.

Changed in version 1.29.0:

  • The expires parameter is now mandatory, passing None will raise ValueError.

Changed in version 1.28.0:

  • The key_backend and key_backend_options parameters where added.

  • The path, password, key_size and elliptic_curve parameters where removed, they are now part of key_backend.

  • The parent_password parameter was removed, it is now part of the backend loaded for the parent.

  • The issuer_alt_name parameter was renamed to sign_issuer_alternative_name.

  • The crl_url option was removed in favor of sign_crl_distribution_points.

  • The issuer_url and ocsp_url options where removed in favor of sign_authority_information_access.

Changed in version 1.26.0:

  • The permitted_subtrees and excluded_subtrees subtrees where removed. Pass a NameConstraints extension in extensions instead.

  • Added the acme_registration option.

Parameters:
namestr

The name of the CA. This is a human-readable string and is used for administrative purposes only.

key_backendKeyBackend

A subclass of KeyBackend to use for storing the private key.

key_backend_optionsBaseModel

Parameters required for creating the private key using key_backend.

subjectcryptography.x509.Name

The desired subject for the certificate.

not_afterdatetime

When this certificate authority will expire.

algorithmHashAlgorithm, optional

Hash algorithm used when signing the certificate, defaults to CA_DEFAULT_SIGNATURE_HASH_ALGORITHM for RSA/EC keys, and CA_DEFAULT_DSA_SIGNATURE_HASH_ALGORITHM for DSA keys. Passing an algorithm for Ed448/Ed25519 keys is an error.

parentCertificateAuthority, optional

Parent certificate authority for the new CA. Passing this value makes the CA an intermediate authority. Let unset if this CA will be used for OpenSSH.

use_parent_private_key_optionsBaseModel, optional

Transient parameters required for signing certificates with parent (e.g. a password). This argument is required if parent is given.

default_hostnamestr, optional

Override the URL configured with CA_DEFAULT_HOSTNAME with a different hostname. Set to False to disable the hostname.

path_lengthint, optional

Value of the path length attribute for the Basic Constraints extension.

key_type: str, optional

The type of private key to generate, must be one of "RSA", "DSA", "EC", or "Ed25519" , with "RSA" being the default.

extensionslist of cryptography.x509.Extension

An optional list of additional extensions to add to the certificate.

caastr, optional

CAA identity. Note that this field is not yet currently used.

websitestr, optional

URL to a human-readable website.

terms_of_servicestr, optional

URL to the terms of service for the CA.

acme_enabledbool, optional

Set to True to enable ACMEv2 support for this CA.

acme_registrationbool, optional

Whether to allow ACMEv2 clients to register new ACMEv2 accounts (if support is enabled in the first place). By default, account registration is enabled.

acme_profilestr, optional

The profile to use when issuing certificates via ACMEv2. Defaults to the CA_DEFAULT_PROFILE.

acme_requires_contactbool, optional

Set to False if you do not want to force clients to register with an email address.

openssh_cabool, optional

Set to True if you want to use this to use this CA for signing OpenSSH certs.

sign_authority_information_accessExtension, optional

Add the given Authority Information Access extension when signing certificates.

sign_certificate_policiesExtension, optional

Add the given Certificate Policies extension when signing certificates.

sign_crl_distribution_pointsExtension, optional

Add the given CRL Distribution Points extension when signing certificates.

sign_issuer_alternative_nameExtension, optional

Add the given Issuer Alternative Name extension when signing certificates.

ocsp_key_backend_aliasstr, optional

The OCSP key backend to use, defaults to “default”.

ocsp_responder_key_validityint, optional

How long (in days) OCSP responder keys should be valid.

ocsp_response_validityint, optional

How long (in seconds) OCSP responses should be valid.

api_enabledbool, optional

If the REST API shall be enabled.

Raises:
ValueError

For various cases of wrong input data (e.g. extensions of invalid type).

Certificate

class django_ca.models.Certificate(*args, **kwargs)[source]

Model representing a x509 Certificate.

property bundle: list[X509CertMixin]

The complete certificate bundle. This includes all CAs as well as the certificates itself.

property root: CertificateAuthority

Get the root CA for this certificate.

Manager methods

CertificateManager is the default manager for Certificate, meaning you can access it using Certificate.objects, e.g.:

>>> csr  
<...CertificateSigningRequest object at ...>
>>> from django_ca.models import Certificate
>>> Certificate.objects.create_cert(
...     ca=ca,
...     key_backend_options=StoragesUsePrivateKeyOptions(password=None),
...     csr=csr,
...     subject=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "example.com")])
... )
<Certificate: example.com>
class django_ca.managers.CertificateManager(*args, **kwargs)[source]

Model manager for the Certificate model.

create_cert(ca: CertificateAuthority, key_backend_options: BaseModel, csr: CertificateSigningRequest, profile: Profile | None = None, autogenerated: bool | None = None, subject: Name | None = None, expires: datetime | timedelta | None = None, not_after: datetime | timedelta | None = None, algorithm: SHA224 | SHA256 | SHA384 | SHA512 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | None = None, extensions: Iterable[Extension[Admissions] | Extension[AuthorityInformationAccess] | Extension[CertificatePolicies] | Extension[CRLDistributionPoints] | Extension[ExtendedKeyUsage] | Extension[FreshestCRL] | Extension[IssuerAlternativeName] | Extension[KeyUsage] | Extension[MSCertificateTemplate] | Extension[OCSPNoCheck] | Extension[PrecertPoison] | Extension[SubjectAlternativeName] | Extension[TLSFeature]] | None = None, add_crl_url: bool | None = None, add_ocsp_url: bool | None = None, add_issuer_url: bool | None = None, add_issuer_alternative_name: bool | None = None, allow_unrecognized_extensions: bool = False) Certificate[source]

Create and sign a new certificate based on the given profile.

Changed in version 2.2.1: The allow_unrecognized_extensions parameter was added.

Deprecated since version 2.1.0: The expires parameter is deprecated and will be removed in django-ca 2.3.0. use not_after instead.

Parameters:
caCertificateAuthority

The certificate authority to sign the certificate with.

key_backend_optionsBaseModel

Transient parameters required for signing certificates with ca (e.g. a password).

csrCertificateSigningRequest

The certificate signing request to use when signing a certificate. Passing a str or bytes is deprecated and will be removed in django-ca 1.20.0.

profileProfile, optional

The name of a profile or a manually created Profile instance. If not given, the profile configured by CA_DEFAULT_PROFILE is used.

autogeneratedbool, optional

Override the profiles autogenerated flag.

subjectName, optional

Passed to Profiles.create_cert().

not_afterdatetime or timedelta, optional

Passed to Profiles.create_cert().

algorithmHashAlgorithm, optional

Passed to Profiles.create_cert().

extensionslist or of Extension

Passed to Profiles.create_cert().

add_crl_urlbool, optional

Passed to Profiles.create_cert().

add_ocsp_urlbool, optional

Passed to Profiles.create_cert().

add_issuer_urlbool, optional

Passed to Profiles.create_cert().

add_issuer_alternative_namebool, optional

Passed to Profiles.create_cert().

allow_unrecognized_extensionsbool, optional

Passed to Profiles.create_cert().

X509CertMixin

X509CertMixin is a common base class to both CertificateAuthority and Certificate and provides many convenience attributes.

class django_ca.models.X509CertMixin(*args, **kwargs)[source]

Mixin class with common attributes for Certificates and Certificate Authorities.

property algorithm: SHA224 | SHA256 | SHA384 | SHA512 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | None

A shortcut for signature_hash_algorithm.

property bundle_as_pem: str

Get the bundle as PEM.

extensions

All extensions of this certificate in a dict.

The key is the OID for the respective extension, allowing easy to look up a particular extension.

get_compromised_time() datetime | None[source]

Return when this certificate was compromised.

Returns None if the time is not known or if the certificate is not revoked.

get_fingerprint(algorithm: HashAlgorithm) str[source]

Get the digest for a certificate as string, including colons.

get_revocation() RevokedCertificate[source]

Get the RevokedCertificate instance for this certificate for CRLs.

This function is just a shortcut for RevokedCertificateBuilder.

Returns:
RevokedCertificate
Raises:
ValueError

If the certificate is not revoked.

get_revocation_reason() ReasonFlags | None[source]

Get the revocation reason of this certificate.

get_revocation_time() datetime | None[source]

Get the revocation time.

property issuer: Name

The certificate issuer field as Name.

property jwk: JWKRSA | JWKEC

Get a JOSE JWK public key for this certificate.

Note

josepy (the underlying library) does not currently support loading Ed448 or Ed25519 public keys. This property will raise ValueError if called for a public key based on those algorithms. The issue is addressed in this pull request.

revoke(reason: ReasonFlags = ReasonFlags.unspecified, compromised: datetime | None = None) None[source]

Revoke the current certificate.

This function emits the pre_revoke_cert and post_revoke_cert signals.

Parameters:
reasonReasonFlags, optional

The reason for revocation, defaults to ReasonFlags.unspecified.

compromiseddatetime, optional

When this certificate was compromised.

sorted_extensions

List of extensions sorted by their human-readable name.

This property is used for display purposes, where a reproducible output is desired.

property subject: Name

The certificate subject field as Name.

update_certificate(value: Certificate) None[source]

Update this instance with data from a cryptography.x509.Certificate.

This function will also populate the cn, serial, `not_after and not_before fields.

CertificateRevocationList

class django_ca.models.CertificateRevocationList(*args, **kwargs)[source]

The CertificateRevocationList is used to store CRLs in the database.

Only one of only_contains_ca_certs, only_contains_ca_certs and only_contains_attribute_certs can be True.

Added in version 2.1.0.

ca

Certificate Authority that the CRL is generated for.

cache(serial: str | None = None) None[source]

Cache this instance.

If serial is not given, self.ca will be accessed (possibly triggering a database query) to generate the cache keys.

data

The DER-encoded binary data of the CRL.

last_update

When the CRL was generated.

loaded

The CRL loaded into a cryptography.x509.CertificateRevocationList object.

next_update

When the CRL expires.

number

CRL Number used in this CRL.

only_contains_attribute_certs

True if the CRL contains only attribute certificates.

only_contains_ca_certs

True if the CRL contains only CA certificates.

only_contains_user_certs

True if the CRL contains only end-entity certificates.

only_some_reasons

Optional list of revocation reasons. If set, the CRL only contains certificates revoked for the given reasons.

pem

The CRL encoded in PEM format.

class django_ca.managers.CertificateRevocationListManager(*args, **kwargs)[source]

The model manager for CertificateRevocationList.

Added in version 2.1.0.

create_certificate_revocation_list(ca: CertificateAuthority, key_backend_options: BaseModel, *, next_update: datetime | None = None, only_contains_ca_certs: bool = False, only_contains_user_certs: bool = False, only_contains_attribute_certs: bool = False, only_some_reasons: frozenset[ReasonFlags] | None = None) CertificateRevocationList[source]

Create or update a certificate revocation list.

Apart from ca and key_backend_options, all arguments are optional and must be passed as keyword arguments.

Parameters:
caCertificateAuthority

The certificate authority to generate the CRL for.

key_backend_optionsBaseModel

Key backend options for using the private key.

next_updatedatetime, optional

When the CRL will be updated again, defaults to one day.

only_contains_ca_certsbool, optional

Set to True to generate a CRL that contains only CA certificates.

only_contains_user_certsbool, optional

Set to True to generate a CRL that contains only end-entity certificates.

only_contains_attribute_certsbool, optional

Set to True to generate a CRL that contains only attribute certificates. Note that this is not supported and will always return an empty CRL.

only_some_reasonsfrozenset[ReasonFlags], optional

Pass a set of ReasonFlags to limit the CRL to certificates that have been revoked for that reason.

Watchers

class django_ca.models.Watcher(*args, **kwargs)[source]

A watcher represents an email address that will receive notifications about expiring certificates.

classmethod from_addr(addr: str) Self[source]

Class constructor that creates an instance from an email address.

ACME

class django_ca.models.AcmeAccount(*args, **kwargs)[source]

Implements an ACME account object.

See also

RFC 8555, 7.1.2

property serial: str

Serial of the CA for this account.

set_kid(request: HttpRequest) None[source]

Set the ACME kid based on this accounts CA and slug.

Note that slug and ca must be already set when using this method.

property usable: bool

Boolean if the account is currently usable.

An account is usable if the terms of service have been agreed, the status is “valid” and the associated CA is usable.

class django_ca.models.AcmeOrder(*args, **kwargs)[source]

Implements an ACME order object.

See also

RFC 8555, 7.1.3

property acme_finalize_url: str

Get the ACME “finalize” URL path for this order.

property acme_url: str

Get the ACME URL path for this order.

add_authorizations(identifiers: Iterable[Identifier]) list[AcmeAuthorization][source]

Add AcmeAuthorization instances for the given identifiers.

Note that this method already adds the account authorization to the database. It does not verify if it already exists and will raise an IntegrityError if it does.

Example:

>>> from acme import messages
>>> identifier = messages.Identifier(typ=messages.IDENTIFIER_FQDN, value='example.com')
>>> order.add_authorizations([identifier])  
Parameters:
identifierslist of acme.messages.Identifier

The identifiers for this order.

Returns:
list of AcmeAuthorization
property serial: str

Serial of the CA for this order.

property usable: bool

Boolean defining if an order is “usable”, meaning it can be used to issue a certificate.

An order is usable if it is in the “pending” status, has not expired and the account is usable.

class django_ca.models.AcmeAuthorization(*args, **kwargs)[source]

Implements an ACME authorization object.

See also

RFC 8555, 7.1.4

property account: AcmeAccount

Account that this authorization belongs to.

property acme_url: str

Get the ACME URL path for this account authorization.

property expires: datetime

When this authorization expires.

property general_name: GeneralName

Get the GeneralName instance for this instance.

get_challenges() list[AcmeChallenge][source]

Get list of AcmeChallenge objects for this authorization.

Note that challenges will be created if they don’t exist.

property identifier: Identifier

Get ACME identifier for this object.

Returns:
identifieracme.messages.Identifier
property serial: str

Serial of the CA for this authorization.

property subject_alternative_name: str

Get the domain for this challenge as prefixed SubjectAlternativeName.

This method is intended to be used when creating the django_ca.extensions.SubjectAlternativeName extension for a certificate to be signed.

property usable: bool

Boolean defining if an authentication can still can be used in order validation.

An order is usable if it is in the “pending” or “invalid” status, the order is usable. An authorization that is in the “invalid” status is eligible to be retried by the client.

class django_ca.models.AcmeChallenge(*args, **kwargs)[source]

Implements an ACME Challenge Object.

property account: AcmeAccount

Account that this challenge belongs to.

property acme_challenge: KeyAuthorizationChallenge

Challenge as ACME challenge object.

Returns:
acme.challenges.Challenge

The acme representation of this class.

property acme_url: str

Get the ACME URL path for this challenge.

property acme_validated: datetime | None

Timestamp when this challenge was validated.

This property is a wrapper around the validated field. It always returns None if the challenge is not marked as valid (even if it had a timestamp), and the timestamp will always have a timezone, even if USE_TZ=False.

property encoded_token: bytes

Token in base64url encoded form.

property expected: bytes

Expected value for the challenge based on its type.

get_challenge(request: HttpRequest) ChallengeBody[source]

Get the ACME challenge body for this challenge.

Returns:
acme.messages.ChallengeBody

The acme representation of this class.

property serial: str

Serial of the CA for this challenge.

property usable: bool

Boolean defining if a challenge is “usable”, meaning it still can be used in order validation.

A challenge is usable if it is in the “pending” or “invalid status and the authorization is usable.

class django_ca.models.AcmeCertificate(*args, **kwargs)[source]

Intermediate model for certificates to be issued via ACME.

property acme_url: str

Get the ACME URL path for this certificate.

parse_csr() CertificateSigningRequest[source]

Load the CSR into a cryptography object.

Returns:
CertificateSigningRequest

The CSR as used by cryptography.

property usable: bool

Boolean defining if this instance is “usable”, meaning we can use it to issue a certificate.

An ACME certificate is considered usable if no actual certificate has yet been issued, the order is not expired and in the “processing” state.