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.
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, 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[PrivateKeyUsagePeriod] | 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, allow_empty_subject: bool = False) Certificate[source]
Create and sign a new certificate based on the given profile.
Changed in version 2.4.0:
The allow_empty_subject parameter was added.
All arguments except ca, key_backend_options, csr and profile must now be given as keyword arguments.
Changed in version 2.3.0: The expires parameter was renamed to not_after.
Changed in version 2.2.1: The allow_unrecognized_extensions parameter was added.
- Parameters:
- ca
CertificateAuthority The certificate authority to sign the certificate with.
- key_backend_optionsBaseModel
Transient parameters required for signing certificates with ca (e.g. a password).
- csr
CertificateSigningRequest The certificate signing request to use when signing a certificate. Passing a
strorbytesis deprecated and will be removed in django-ca 1.20.0.- profile
Profile, optional The name of a profile or a manually created
Profileinstance. If not given, the profile configured by CA_DEFAULT_PROFILE is used.- autogeneratedbool, optional
Override the profiles
autogeneratedflag.- subject
Name, optional Passed to
Profiles.create_cert().- not_afterdatetime or timedelta, optional
Passed to
Profiles.create_cert().- algorithm
HashAlgorithm, 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().- allow_empty_subjectbool, optional
Passed to
Profiles.create_cert().
- ca
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.
- 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
Noneif 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.See also
- Returns:
- Raises:
- ValueError
If the certificate is not revoked.
- get_revocation_reason() ReasonFlags | None[source]
Get the revocation reason of this certificate.
- 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_certandpost_revoke_certsignals.- Parameters:
- reason
ReasonFlags, optional The reason for revocation, defaults to
ReasonFlags.unspecified.- compromiseddatetime, optional
When this certificate was compromised.
- reason
- sorted_extensions
List of extensions sorted by their human-readable name.
This property is used for display purposes, where a reproducible output is desired.
- 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.CertificateRevocationListobject.
- 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:
- ca
CertificateAuthority 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
Trueto generate a CRL that contains only CA certificates.- only_contains_user_certsbool, optional
Set to
Trueto generate a CRL that contains only end-entity certificates.- only_contains_attribute_certsbool, optional
Set to
Trueto 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
ReasonFlagsto limit the CRL to certificates that have been revoked for that reason.
- ca
Watchers
ACME
- class django_ca.models.AcmeAccount(*args, **kwargs)[source]
Implements an ACME account object.
See also
- 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.
- class django_ca.models.AcmeOrder(*args, **kwargs)[source]
Implements an ACME order object.
See also
- add_authorizations(identifiers: Iterable[Identifier]) list[AcmeAuthorization][source]
Add
AcmeAuthorizationinstances 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.
- identifierslist of
- Returns:
- list of
AcmeAuthorization
- list of
- class django_ca.models.AcmeAuthorization(*args, **kwargs)[source]
Implements an ACME authorization object.
See also
- property account: AcmeAccount
Account that this authorization belongs to.
- property general_name: GeneralName
Get the
GeneralNameinstance for this instance.
- get_challenges() list[AcmeChallenge][source]
Get list of
AcmeChallengeobjects for this authorization.Note that challenges will be created if they don’t exist.
- property identifier: Identifier
Get ACME identifier for this object.
- Returns:
- identifier
acme.messages.Identifier
- identifier
- class django_ca.models.AcmeChallenge(*args, **kwargs)[source]
Implements an ACME Challenge Object.
See also
- property account: AcmeAccount
Account that this challenge belongs to.
- property acme_challenge: KeyAuthorizationChallenge
Challenge as ACME challenge object.
- Returns:
acme.challenges.ChallengeThe acme representation of this class.
- 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.
- get_challenge(request: HttpRequest) ChallengeBody[source]
Get the ACME challenge body for this challenge.
- Returns:
acme.messages.ChallengeBodyThe acme representation of this class.
- class django_ca.models.AcmeCertificate(*args, **kwargs)[source]
Intermediate model for certificates to be issued via ACME.
- parse_csr() CertificateSigningRequest[source]
Load the CSR into a cryptography object.
- Returns:
CertificateSigningRequestThe CSR as used by cryptography.