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 programatically, 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(id, created, valid_from, expires, pub, cn, serial, revoked, revoked_date, revoked_reason, compromised, name, enabled, parent, private_key_path, crl_url, crl_number, issuer_url, ocsp_url, issuer_alt_name)[source]
allows_intermediate_ca

Wether this CA allows creating intermediate CAs.

bundle

A list of any parent CAs, including this CA.

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

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

Generate OCSP keys for this CA.

Parameters:
profile : str, optional

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

expires : int or datetime, optional

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

algorithm : str, optional

Passed to parse_hash_algorithm() and defaults to CA_DIGEST_ALGORITHM.

password : bytes, optional

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

key_size : int, optional

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

key_type : {“RSA”, “DSA”, “ECC”}, optional

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

ecc_curve : str, optional

Passed to parse_key_curve(), defaults to the CA_DEFAULT_ECC_CURVE.

get_authority_key_identifier(self)[source]

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

get_crl(self, expires=86400, algorithm=None, password=None, scope=None, counter=None, **kwargs)[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:
expires : int

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

algorithm : Hash or str, optional

The hash algorithm to use, passed to parse_hash_algorithm(). The default is to use CA_DIGEST_ALGORITHM.

password : bytes, 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.

counter : str, 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_name : list of str or GeneralName, optional

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

relative_name : RelativeDistinguishedName, optional

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

Returns:
bytes

The CRL in the requested format.

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.

pathlen

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

root

Get the root CA for this CA.

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
>>> ca = CertificateAuthority.objects.init(
...   name='ca', subject='/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='/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='/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:

>>> CertificateAuthority.objects.init(
...   name='props', subject='/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 RSA keys - unused in this example
...   key_type='ECC',  # create an ECC private key
...   ecc_curve='SECP256R1'
... )
<CertificateAuthority: props>

Here are all parameters for creating CAs:

CertificateAuthorityManager.init(self, 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')[source]

Create a new certificate authority.

Parameters:
name : str

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

subject : dict or str or Subject

Subject string, e.g. "/CN=example.com" or Subject("/CN=example.com"). The value is actually passed to Subject if it is not already an instance of that class.

expires : datetime, optional

Datetime for when this certificate authority will expire, defaults to CA_DEFAULT_EXPIRES.

algorithm : str 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.

parent : CertificateAuthority, optional

Parent certificate authority for the new CA. Passing this value makes the CA an intermediate authority.

default_hostname : str, optional

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

pathlen : int, optional

Value of the path length attribute for the BasicConstraints extension.

issuer_url : str

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

issuer_alt_name : IssuerAlternativeName 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_url : list of str, optional

CRL URLs used for certificates signed by this CA.

ocsp_url : str, optional

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

ca_issuer_url : str, 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_url : list of str, optional

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

ca_ocsp_url : str, 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_constraints : list 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.

password : bytes, optional

Password to encrypt the private key with.

parent_password : bytes, optional

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

ecc_curve : str or EllipticCurve, optional

The elliptic curve to use for ECC type keys, passed verbatim to parse_key_curve().

key_type: str, optional

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

key_size : int, 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".

extra_extensions : list of cryptography.x509.Extension or django_ca.extensions.Extension, optional

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

path : str or pathlib.PurePath, optional

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

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(id, created, valid_from, expires, pub, cn, serial, revoked, revoked_date, revoked_reason, compromised, ca, csr)[source]
bundle

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

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

>>> 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]
create_cert(self, ca, csr, csr_format=<Encoding.PEM: 'PEM'>, profile=None, **kwargs)[source]

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

Parameters:
ca : CertificateAuthority

The certificate authority to sign the certificate with.

csr : str or CertificateSigningRequest

A valid CSR. If not already a CertificateSigningRequest, the format is given by the csr_format parameter.

csr_format : Encoding, optional

The format of the CSR. The default is PEM.

profile : str or Profile, optional

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

**kwargs

All other keyword arguments are passed to Profiles.create_cert().

init(self, ca, csr, **kwargs)[source]

Create a signed certificate from a CSR and store it to the database.

Warning

This function is deprecated and will be removed in django-ca==1.16. Please use create_cert() instead.

All parameters are passed on to Certificate.objects.sign_cert().

sign_cert(self, ca, csr, expires=None, algorithm=None, subject=None, cn_in_san=True, csr_format=<Encoding.PEM: 'PEM'>, subject_alternative_name=None, key_usage=None, extended_key_usage=None, tls_feature=None, ocsp_no_check=False, issuer_url=None, crl_url=None, ocsp_url=None, issuer_alternative_name=None, extra_extensions=None, password=None)[source]

Create a signed certificate from a CSR.

Warning

This function is deprecated and will be removed in django-ca==1.16. Please use create_cert() instead.

PLEASE NOTE: This function creates the raw certificate and is usually not invoked directly. It is called by Certificate.objects.init(), which passes along all parameters unchanged and saves the raw certificate to the database.

Parameters:
ca : CertificateAuthority

The certificate authority to sign the certificate with.

csr : str or CertificateSigningRequest

A valid CSR. If not already a CertificateSigningRequest, the format is given by the csr_format parameter.

expires : datetime, optional

Datetime for when this certificate will expire, defaults to the CA_DEFAULT_EXPIRES setting.

algorithm : str 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.

subject : dict or str or Subject

Subject string, e.g. "/CN=example.com" or Subject("/CN=example.com"). The value is actually passed to Subject if it is not already an instance of that class. If this value is not passed or if the value does not contain a CommonName, the first value of the subject_alternative_name parameter is used as CommonName.

cn_in_san : bool, optional

Wether the CommonName should also be included as subjectAlternativeName. The default is True, but the parameter is ignored if no CommonName is given. This is typically set to False when creating a client certificate, where the subjects CommonName has no meaningful value as subjectAlternativeName.

csr_format : Encoding, optional

The format of the CSR. The default is PEM.

subject_alternative_name : dict or SubjectAlternativeName, optional

A dict passed to SubjectAlternativeName if not already an instance of that class.

key_usage : dict or KeyUsage, optional

Value for the keyUsage X509 extension. A dict passed to KeyUsage if not already an instance of that class.

extended_key_usage : dict or ExtendedKeyUsage, optional

Value for the extendedKeyUsage X509 extension. A dict passed to ExtendedKeyUsage if not already an instance of that class.

tls_feature : dict or TLSFeature, optional

Value for the TLSFeature X509 extension. The dict passed to TLSFeature if not already an instance of that class.

ocsp_no_check : bool, optional

Add the OCSPNoCheck flag, indicating that an OCSP client should trust this certificate for it’s lifetime. This value only makes sense if you intend to use the certificate for an OCSP responder, the default is False. See RFC 6990, section 4.2.2.2.1 for more information.

issuer_url : str or bool, optional

Pass a custom issuer URL overriding the value configured in the CA or pass False to disable getting any issuer_url from the CA (e.g. to pass a custom extension in extra_extensions).

crl_url : str or bool, optional

Pass a custom CRL URL overriding the value configured in the CA or pass False to disable getting any issuer_url from the CA (e.g. to pass a custom extension in extra_extensions).

ocsp_url : str or bool, optional

Pass a custom OCSP URL overriding the value configured in the CA or pass False to disable getting any issuer_url from the CA (e.g. to pass a custom extension in extra_extensions).

issuer_alternative_name : dict or IssuerAlternativeName, optional

Pass a custom issuer alternative name URL overriding the value configured in the CA or pass an empty dict to disable getting any issuer_url from the CA.

extra_extensions : list of cryptography.x509.Extension or django_ca.extensions.Extension, optional

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

password : bytes, optional

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

Returns:
cryptography.x509.Certificate

The signed certificate.

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]
authority_key_identifier

The AuthorityKeyIdentifier extension, or None if it doesn’t exist.

extended_key_usage

The ExtendedKeyUsage extension, or None if it doesn’t exist.

get_revocation_reason(self)[source]

Get the revocation reason of this certificate.

get_revocation_time(self)[source]

Get the revocation time as naive datetime.

Note that this method is only used by cryptography>=2.4.

issuer

The certificate issuer field as Subject.

key_usage

The KeyUsage extension, or None if it doesn’t exist.

not_after

Date/Time this certificate expires.

not_before

Date/Time this certificate was created

subject

The certificates subject as Subject.

subject_key_identifier

The SubjectKeyIdentifier extension, or None if it doesn’t exist.

tls_feature

The TLSFeature extension, or None if it doesn’t exist.

x509

The underlying cryptography.x509.Certificate.

Watchers

class django_ca.models.Watcher(id, name, mail)[source]