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(password: str | bytes | None = None) 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.

property extensions_for_certificate: Dict[ObjectIdentifier, Extension[ExtensionType]]

Get a list of extensions to use for the certificate.

generate_ocsp_key(profile: str = 'ocsp', expires: int | datetime | timedelta | None = 3, algorithm: SHA224 | SHA256 | SHA384 | SHA512 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | None = None, password: str | bytes | None = None, key_size: int | None = None, key_type: Literal['RSA', 'DSA', 'EC', 'Ed25519', 'Ed448'] | None = None, elliptic_curve: EllipticCurve | None = None, autogenerated: bool = True) Tuple[str, str, Certificate][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.

See also

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:
profilestr, optional

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

expiresint 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.

passwordbytes, optional

The password to the CA as bytes, if its private key is encrypted.

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.

get_authority_information_access_extension() Extension[AuthorityInformationAccess] | None[source]

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

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(expires: int = 86400, algorithm: SHA224 | SHA256 | SHA384 | SHA512 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | None = None, password: str | bytes | None = None, scope: Literal['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).

The full_name and relative_name parameters describe how to retrieve the CRL and are used in the Issuing Distribution Point extension. The former defaults to the crl_url field, pass None to not include the value. At most one of the two may be set.

Parameters:
expiresint

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

algorithmHashAlgorithm, optional

The hash algorithm used to generate the signature of the CRL. By default, the algorithm used for signing the CA is used. If a value is passed for an Ed25519/Ed448 CA, ValueError is raised.

passwordbytes, optional

Password used to load the private key of the certificate authority. If not passed, the private key is assumed to be unencrypted.

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. "attribute" is reserved for future use and always produces an empty CRL.

counterstr, optional

Override the counter-variable for the CRL Number extension. Passing the same key to multiple invocations will yield a different sequence then what would ordinarily be returned. The default is to use the scope as the key.

full_namelist of GeneralName, optional

List of general names to use in the Issuing Distribution Point extension. If not passed, use crl_url if set.

relative_nameRelativeDistinguishedName, optional

Used in Issuing Distribution Point extension, retrieve the CRL relative to the issuer.

include_issuing_distribution_point: bool, optional

Force the inclusion/exclusion of the IssuingDistributionPoint extension. By default, the inclusion is automatically determined.

Returns:
bytes

The CRL in the requested format.

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

Get CRLs for the given scope.

get_password() str | None[source]

Get password for the private key from the CA_PASSWORDS setting.

property is_openssh_ca: bool

True if this CA is an OpenSSH CA.

key(password: str | bytes | None = None) Ed25519PrivateKey | Ed448PrivateKey | RSAPrivateKey | DSAPrivateKey | EllipticCurvePrivateKey[source]

The CAs private key as private key.

property key_exists: bool

True if the private key is locally accessible.

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.

name

Human-readable name of the CA, only used for displaying the CA.

property path_length: int | None

The path_length attribute of the BasicConstraints extension.

property root: CertificateAuthority

Get the root CA for this CA.

sign(csr: CertificateSigningRequest, subject: Name, algorithm: SHA224 | SHA256 | SHA384 | SHA512 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | None = None, expires: datetime | None = None, extensions: Iterable[Extension[ExtensionType]] | None = None, cn_in_san: bool = True, password: str | bytes | 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. The common names in subject are added to SubjectAlternativeName if cn_in_san is True.

Parameters:
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.

expiresdatetime, 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.

cn_in_sanbool, optional

Include common names from the subject in the SubjectAlternativeName extension. True by default.

passwordstr or bytes, optional

Password for loading the private key of the CA, if any.

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 django_ca.models import CertificateAuthority
>>> from django_ca.utils import x509_name
>>> ca = CertificateAuthority.objects.init(
...   name='ca',
...   subject=x509_name('/CN=ca.example.com'),
...   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',
...   subject=x509_name('/CN=child.example.com'),
...   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',
...   subject=x509_name('/CN=full.example.com'),
...   parent=ca,  # some extensions are only valid for intermediate CAs
...   issuer_url='http://full.example.com/full.der',
...
...   # 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)
...       )
...   ],
...
...   # CRL/OCSP URLs for signed certificates. These can be changed later:
...   crl_url=['http://full.example.com/full.crl'],
...   ocsp_url='http://full.example.com/ocsp',
... )

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
>>> CertificateAuthority.objects.init(
...   name='props',
...   subject=x509_name('/CN=child.example.com'),
...   algorithm=hashes.SHA256(),  # SHA512 would be the default
...   path_length=3,  # three levels of intermediate CAs allowed,
...   password=b'foobar',  # encrypt private key with this password
...   key_type='EC',  # create a private key using Elliptic Curve cryptography
...   elliptic_curve=ec.SECP256R1()  # Elliptic curve for the key
... )
<CertificateAuthority: props>

Here are all parameters for creating CAs:

CertificateAuthorityManager.init(name: str, subject: Name, expires: int | datetime | timedelta | None = None, algorithm: SHA224 | SHA256 | SHA384 | SHA512 | SHA3_224 | SHA3_256 | SHA3_384 | SHA3_512 | None = None, parent: CertificateAuthority | None = None, default_hostname: bool | str | None = None, path_length: int | None = None, issuer_url: str | None = None, issuer_alt_name: Extension[IssuerAlternativeName] | None = None, crl_url: Iterable[str] | None = None, ocsp_url: str | None = None, ca_issuer_url: Sequence[str] | None = None, ca_crl_url: Sequence[str] | None = None, ca_ocsp_url: Sequence[str] | None = None, permitted_subtrees: Iterable[GeneralName] | None = None, excluded_subtrees: Iterable[GeneralName] | None = None, password: str | bytes | None = None, parent_password: str | bytes | None = None, elliptic_curve: EllipticCurve | None = None, key_type: Literal['RSA', 'DSA', 'EC', 'Ed25519', 'Ed448'] = 'RSA', key_size: int | None = None, extensions: Iterable[Extension[ExtensionType]] | None = None, path: PurePath | str = 'ca', caa: str = '', website: str = '', terms_of_service: str = '', acme_enabled: bool = False, acme_requires_contact: bool = True, acme_profile: str | None = None, openssh_ca: bool = False) CertificateAuthority[source]

Create a new certificate authority.

Changed in version 1.23.0:

  • The ecc_curve parameter was renamed to elliptic_curve.

  • Passing key_type="EdDSA" is deprecated, use key_type="Ed25519" instead.

  • Passing key_type="ECC" is deprecated, use key_type="EC" instead.

Changed in version 1.24.0:

  • The extra_extensions parameter was renamed to extensions.

  • The pathlen parameter was renamed to path_length.

  • The ca_issuer_url and ca_ocsp_url parameters are now list of strings. Support for bare strings will be removed in django-ca==1.26.0.

Changed in version 1.25.0:

  • The permitted_subtrees and excluded_subtrees subtrees are deprecated and will be removed in django-ca==1.26.0. Pass a NameConstraints extension in extensions instead.

Parameters:
namestr

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

subjectcryptography.x509.Name

The desired subject for the certificate.

expiresint or datetime or timedelta, optional

When this certificate authority will expire, defaults to CA_DEFAULT_EXPIRES.

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.

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.

issuer_urlstr

URL for the DER/ASN1 formatted certificate that is signing certificates.

issuer_alt_nameExtension, optional

IssuerAlternativeName used when signing certificates. The value of the extension must be an IssuerAlternativeName instance.

crl_urllist of str, optional

CRL URLs used for certificates signed by this CA.

ocsp_urlstr, optional

OCSP URL used for certificates signed by this CA. The default is no value, unless CA_DEFAULT_HOSTNAME is set.

passwordbytes or str, optional

Password to encrypt the private key with.

parent_passwordbytes or str, optional

Password that the private key of the parent CA is encrypted with.

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.

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.

key_sizeint, optional

Integer specifying the key size, must be a power of two (e.g. 2048, 4096, …). Defaults to the CA_DEFAULT_KEY_SIZE, unused if key_type="EC" or key_type="Ed25519".

extensionslist of cryptography.x509.Extension

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

pathstr or pathlib.PurePath, optional

Where to store the CA private key (default ca).

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 ACME support for this CA.

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.

Raises:
ValueError

For various cases of wrong input data (e.g. key_size not being the power of two).

PermissionError

If the private key file cannot be written to disk.

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(csr=csr, ca=ca, subject=x509_name('/CN=example.com'))
<Certificate: example.com>
class django_ca.managers.CertificateManager(*args, **kwargs)[source]

Model manager for the Certificate model.

create_cert(ca: CertificateAuthority, csr: CertificateSigningRequest, profile: Profile | None = None, autogenerated: bool | None = None, **kwargs: Any) Certificate[source]

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

Parameters:
caCertificateAuthority

The certificate authority to sign the certificate with.

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.

**kwargs

All other keyword arguments are 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.

get_compromised_time() datetime | None[source]

Return when this certificate was compromised as a naive datetime.

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

get_filename(ext: str, bundle: bool = False) str[source]

Get a filename safe for any file system and OS for this certificate based on the common name.

Parameters:
extstr

The filename extension to use (e.g. "pem").

bundlebool, optional

Adds “_bundle” as suffix.

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 as naive datetime.

property hpkp_pin: str

The HPKP public key pin for this certificate.

Inspired by https://github.com/luisgf/hpkp-python/blob/master/hpkp.py.

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.

property not_after: datetime

A timezone-aware datetime representing the end of the validity period.

property not_before: datetime

A timezone-aware datetime representing the beginning of the validity period.

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, `expires and valid_from fields.

x509_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.

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) Watcher[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.