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

Whether this CA allows creating intermediate CAs.

property bundle

A list of any parent CAs, including this CA.

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

cache_crls(password=None, algorithm=None)[source]

Function to cache all CRLs for this CA.

generate_ocsp_key(profile='ocsp', expires=3, algorithm=None, password=None, key_size=None, key_type='RSA', ecc_curve=None, autogenerated=True)[source]

Generate OCSP keys for this CA.

Deprecated since version 1.20.0: Passing unparsed values is deprecated and will be removed in django_ca==1.22. This affects the following parameters:

  • Passing a str for ecc_curve.

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

algorithmstr, optional

Passed to parse_hash_algorithm() and defaults to CA_DIGEST_ALGORITHM.

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”, “ECC”, “EdDSA”, “Ed448”}, optional

The private key type to use, the default is "RSA".

ecc_curveEllipticCurve, optional

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

autogeneratedbool, optional

Set the autogenerated flag of the certificate. True by default, since this method is usually invoked by regular cron jobs.

get_authority_key_identifier()[source]

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

Returns
AuthorityKeyIdentifier

The value to use for this extension.

get_authority_key_identifier_extension()[source]

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

Returns
AuthorityKeyIdentifier

The extension to use.

get_crl(expires=86400, algorithm=None, password=None, scope=None, counter=None, full_name=None, relative_name=None)[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.

Changed in version 1.20.0: The full_name parameter must be a list of GeneralName, str are no longer allowed.

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 to use, defaults to CA_DIGEST_ALGORITHM.

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.

Returns
bytes

The CRL in the requested format.

get_crl_certs(scope, now)[source]

Get CRLs for the given scope.

get_password()[source]

Get password for the private key from the CA_PASSWORDS setting.

property is_openssh_ca

True if this CA is an OpenSSH CA.

key(password=None)[source]

The CAs private key as private key.

property key_exists

True if the private key is locally accessible.

property max_pathlen

The maximum pathlen for any intermediate CAs signed by this CA.

This value is either None, if this and all parent CAs don’t have a pathlen 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 pathlen

The pathlen attribute of the BasicConstraints extension (either an int or None).

property root

Get the root CA for this CA.

property usable

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'),
...   pathlen=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:

>>> 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',
...   # this CA can only sign for *.com domains:
...   name_constraints={'value': {'permitted': ['DNS:.com']}},
...
...   # 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',
...
...   # CRL/OCSP/Issuer URLs for the CA. These are only meaningful for
...   # intermediate CAs:
...   ca_crl_url=['http://parent.example.com/parent.crl', ],
...   ca_ocsp_url='http://parent.example.com/ocsp',
...   ca_issuer_url='http://parent.example.com/parent.crt'
... )

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

>>> from cryptography.hazmat.primitives.asymmetric import ec
>>> CertificateAuthority.objects.init(
...   name='props',
...   subject=x509_name('/CN=child.example.com'),
...   algorithm='SHA256',  # sha512 would be the default
...   pathlen=3,  # three levels of intermediate CAs allowed,
...   password=b'foobar',  # encrypt private key with this password
...   key_size=4096,  # key size for DSA/RSA keys - unused in this example
...   key_type='ECC',  # create an ECC private key
...   ecc_curve=ec.SECP256R1()  # ECC key curve
... )
<CertificateAuthority: props>

Here are all parameters for creating CAs:

CertificateAuthorityManager.init(name, subject, expires=None, algorithm=None, parent=None, default_hostname=None, pathlen=None, issuer_url=None, issuer_alt_name='', crl_url=None, ocsp_url=None, ca_issuer_url=None, ca_crl_url=None, ca_ocsp_url=None, name_constraints=None, password=None, parent_password=None, ecc_curve=None, key_type='RSA', key_size=None, extra_extensions=None, path='ca', caa='', website='', terms_of_service='', acme_enabled=False, acme_requires_contact=True, openssh_ca=False)[source]

Create a new certificate authority.

Deprecated since version 1.20.0: Passing unparsed values is deprecated and will be removed in django_ca==1.22. This affects the following parameters:

  • Passing a str or Subject for subject.

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.

algorithmstr or HashAlgorithm, optional

Hash algorithm used when signing the certificate, passed to parse_hash_algorithm(). The default is the value of the CA_DIGEST_ALGORITHM setting.

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 URLconfigured with CA_DEFAULT_HOSTNAME with a different hostname. Set to False to disable the hostname.

pathlenint, optional

Value of the path length attribute for the BasicConstraints extension.

issuer_urlstr

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

issuer_alt_nameIssuerAlternativeName or str, optional

IssuerAlternativeName used when signing certificates. If the value is not an instance of IssuerAlternativeName, it will be passed as argument to the constructor of the class.

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.

ca_issuer_urlstr, optional

URL for the DER/ASN1 formatted certificate that is signing this CA. For intermediate CAs, this would usually be the issuer_url of the parent CA.

ca_crl_urllist of str, optional

CRL URLs used for this CA. This value is only meaningful for intermediate CAs.

ca_ocsp_urlstr, optional

OCSP URL used for this CA. This value is only meaningful for intermediate CAs. The default is no value, unless CA_DEFAULT_HOSTNAME is set.

name_constraintslist of lists or NameConstraints

List of names that this CA can sign and/or cannot sign. The value is passed to NameConstraints if the value is not already an instance of that class.

passwordbytes, optional

Password to encrypt the private key with.

parent_passwordbytes, optional

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

ecc_curveEllipticCurve, optional

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

key_type: str, optional

The type of private key to generate, must be one of "RSA", "DSA", "ECC", or "EdDSA" , 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="ECC" or key_type="EdDSA".

extra_extensionslist of cryptography.x509.Extension or django_ca.extensions.base.Extension, optional

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_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

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

property root

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  
<builtins.CertificateSigningRequest object at ...>
>>> from django_ca.models import Certificate
>>> Certificate.objects.create_cert(csr=csr, ca=ca, subject='/CN=example.com')
<Certificate: example.com>
class django_ca.managers.CertificateManager[source]

Model manager for the Certificate model.

create_cert(ca, csr, profile=None, autogenerated=None, **kwargs)[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

A shortcut for signature_hash_algorithm.

authority_information_access

The AuthorityInformationAccess extension or None if not present.

authority_key_identifier

The AuthorityKeyIdentifier extension or None if not present.

basic_constraints

The BasicConstraints extension or None if not present.

property bundle_as_pem

Get the bundle as PEM.

certificate_policies

The CertificatePolicies extension or None if not present.

crl_distribution_points

The CRLDistributionPoints extension or None if not present.

property distinguished_name

The certificates distinguished name formatted as string.

extended_key_usage

The ExtendedKeyUsage extension or None if not present.

extension_fields

List of all extensions fields for this certificate.

extensions

List of all extensions for this certificate.

freshest_crl

The FreshestCRL extension or None if not present.

get_compromised_time()[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_digest(algo)[source]

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

get_filename(ext, bundle=False)[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_revocation()[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()[source]

Get the revocation reason of this certificate.

get_revocation_time()[source]

Get the revocation time as naive datetime.

property hpkp_pin

The HPKP public key pin for this certificate.

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

inhibit_any_policy

The InhibitAnyPolicy extension or None if not present.

property issuer

The certificate issuer field as Name.

Changed in version 1.20.0: This property was a Subject before django-ca==1.20.0.

issuer_alternative_name

The IssuerAlternativeName extension or None if not present.

key_usage

The KeyUsage extension or None if not present.

name_constraints

The NameConstraints extension or None if not present.

property not_after

Date/Time this certificate expires.

property not_before

Date/Time this certificate was created

ocsp_no_check

The OCSPNoCheck extension or None if not present.

policy_constraints

The PolicyConstraints extension or None if not present.

precert_poison

The PrecertPoison extension or None if not present.

precertificate_signed_certificate_timestamps

The PrecertificateSignedCertificateTimestamps extension or None if not present.

revoke(reason=ReasonFlags.unspecified, compromised=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.

property subject

The certificate subject field as Name.

Changed in version 1.20.0: This property was a Subject before django-ca==1.20.0.

subject_alternative_name

The SubjectAlternativeName extension or None if not present.

subject_key_identifier

The SubjectKeyIdentifier extension or None if not present.

tls_feature

The TLSFeature extension or None if not present.

update_certificate(value)[source]

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

This function will also populate the cn, serial, `expires and valid_from fields.

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

Serial of the CA for this account.

set_kid(request)[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

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

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

property acme_url

Get the ACME URL path for this order.

add_authorizations(identifiers)[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 for this order.

Returns
list ofpy:class:~django_ca.models.AcmeAuthorization
property serial

Serial of the CA for this order.

property usable

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

Account that this authorization belongs to.

property acme_url

Get the ACME URL path for this account authorization.

property expires

When this authorization expires.

get_challenges()[source]

Get list of AcmeChallenge objects for this authorization.

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

property identifier

Get ACME identifier for this object.

Returns
identifieracme.messages.Identifier
property serial

Serial of the CA for this authorization.

property subject_alternative_name

Get the domain for this challenge as prefixed SubjectAlternativeName.

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

property usable

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

Account that this challenge belongs to.

property acme_challenge

Challenge as ACME challenge object.

Returns
acme.challenges.Challenge

The acme representation of this class.

property acme_url

Get the ACME URL path for this challenge.

property acme_validated

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

Token in base64url encoded form.

property expected

Expected value for the challenge based on its type.

get_challenge(request)[source]

Get the ACME challenge body for this challenge.

Returns
acme.messages.ChallengeBody

The acme representation of this class.

property serial

Serial of the CA for this challenge.

property usable

Boolean defining if an 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

Get the ACME URL path for this certificate.

parse_csr()[source]

Load the CSR into a cryptography object.

Returns
CertificateSigningRequest

The CSR as used by cryptography.

property usable

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.