pki.models

Package that contains all models of the PKI App.

Submodules

Exceptions

CredentialAlreadyExistsError

The CredentialAlreadyExistsError is raised if a credential already exists in the database.

Classes

AttributeTypeAndValue

AttributeTypeAndValue Model.

CertificateExtension

Abstract Base Class of Extension Models.

GeneralNameIpAddress

GeneralNameIpAddress Model.

CertificateModel

X509 Certificate Model.

RevokedCertificateModel

Model to store revoked certificates.

CrlModel

Certificate Revocation List Model.

CaModel

Generic CA Model representing any Certificate Authority.

CredentialModel

The CredentialModel that holds all local credentials used by the Trustpoint.

OwnerCredentialModel

Device owner credential model.

PKCS11Key

Model representing a private key stored in a PKCS#11 HSM/token.

DomainModel

Domain Model.

DomainAllowedCertificateProfileModel

Model representing allowed certificate profiles for a domain.

DevIdRegistration

Represents a DevID Registration, linking a Truststore, Domain, unique name, and a serial number regex pattern.

CertificateProfileModel

Model representing a certificate profile.

TruststoreModel

Represents a truststore, which is a collection of certificates used for specific purposes.

TruststoreOrderModel

Represents the order of certificates in a truststore.

Package Contents

class pki.models.AttributeTypeAndValue(*args, **kwargs)[source]

Bases: django.db.models.Model

AttributeTypeAndValue Model.

Used for subject entries as well as the GeneralNameDirectoryName entries within the SubjectAlternativeName and IssuerAlternativeName.

See RFC5280 for more information.

oid
value
class Meta
unique_together = ('oid', 'value')
__str__()[source]

Returns a string representation of the attribute type and value.

Return type:

str

property abbreviation: str | None

Returns the abbreviation of the attribute’s OID.

Return type:

str | None

property verbose_name: str

Returns the verbose name of the attribute’s OID.

Return type:

str

class pki.models.CertificateExtension(*args, **kwargs)[source]

Bases: util.db.OrphanDeletionMixin

Abstract Base Class of Extension Models.

Due to a Metaclass conflict, this class is not derived from abc.ABC on purpose. # TODO: check if this can be rectified

_extension_oid: str
property extension_oid: str

Returns the OID of the extension.

Return type:

str

classmethod save_from_crypto_extensions(extension)[source]
Abstractmethod:

Parameters:

extension (cryptography.x509.Extension[T])

Return type:

CertificateExtension | None

Stores the extension in the database.

Meant to be called within an atomic transaction while storing a certificate.

Parameters:

extension (x509.Extension) – The X.509 extension object.

Returns:

The instance of the saved extension.

Return type:

CertificateExtension

classmethod delete_if_orphaned(instance)[source]

Removes the Extension instance if no longer referenced.

Since all extension classes are only referenced by the Certificate model with on_delete=models.PROTECT, we can rely on the database protection to remove the instance if it is no longer referenced. This saves an extra query to check if the ‘certificates’ reverse relation still exists.

Parameters:

instance (util.db.OrphanDeletionMixin | None)

Return type:

None

class pki.models.GeneralNameIpAddress(*args, **kwargs)[source]

Bases: util.db.OrphanDeletionMixin, django.db.models.Model

GeneralNameIpAddress Model.

Entries of either SubjectAlternativeNames or IssuerAlternativeNames.

See RFC5280 for more information.

class IpType(*args, **kwds)

Bases: django.db.models.TextChoices

Class for creating enumerated string choices.

IPV4_ADDRESS
IPV6_ADDRESS
IPV4_NETWORK
IPV6_NETWORK
ip_type
value
check_references_on_delete = ('general_names_set',)
class Meta
unique_together = ('ip_type', 'value')
__str__()[source]

Returns a string representation of the GeneralNameIpAddress.

Return type:

str

class pki.models.CertificateModel(*args, **kwargs)[source]

Bases: trustpoint.logger.LoggerMixin, util.db.CustomDeleteActionModel

X509 Certificate Model.

See RFC5280 for more information.

class CertificateStatus(*args, **kwds)

Bases: django.db.models.TextChoices

CertificateModel status.

OK
REVOKED
EXPIRED
NOT_YET_VALID
class Version(*args, **kwds)

Bases: django.db.models.IntegerChoices

X509 RFC 5280 - Certificate Version.

V3
class SignatureAlgorithmOidChoices(*args, **kwds)

Bases: django.db.models.TextChoices

Signature Algorithm OIDs.

RSA_MD5
RSA_SHA1
RSA_SHA1_ALT
RSA_SHA224
RSA_SHA256
RSA_SHA384
RSA_SHA512
RSA_SHA3_224
RSA_SHA3_256
RSA_SHA3_384
RSA_SHA3_512
ECDSA_SHA1
ECDSA_SHA224
ECDSA_SHA256
ECDSA_SHA384
ECDSA_SHA512
ECDSA_SHA3_224
ECDSA_SHA3_256
ECDSA_SHA3_384
ECDSA_SHA3_512
PASSWORD_BASED_MAC
class PublicKeyAlgorithmOidChoices(*args, **kwds)

Bases: django.db.models.TextChoices

Public Key Algorithm OIDs.

ECC
RSA
class PublicKeyEcCurveOidChoices(*args, **kwds)

Bases: django.db.models.TextChoices

Public Key EC Curve OIDs.

NONE = ''
SECP192R1
SECP224R1
SECP256K1
SECP256R1
SECP384R1
SECP521R1
BRAINPOOLP256R1
BRAINPOOLP384R1
BRAINPOOLP512R1
SECT163K1
SECT163R2
SECT233K1
SECT233R1
SECT283K1
SECT283R1
SECT409K1
SECT409R1
SECT571K1
SECT571R1
is_self_signed
common_name
sha256_fingerprint
signature_algorithm_oid
signature_value
version
serial_number
issuer
issuer_public_bytes
issuer_id
not_valid_before
not_valid_after
subject
subject_public_bytes
spki_algorithm_oid
spki_algorithm
spki_key_size
spki_ec_curve_oid
spki_ec_curve
cert_pem
public_key_pem
created_at
key_usage_extension
subject_alternative_name_extension
issuer_alternative_name_extension
basic_constraints_extension
authority_key_identifier_extension
subject_key_identifier_extension
certificate_policies_extension
extended_key_usage_extension
name_constraints_extension
crl_distribution_points_extension
authority_information_access_extension
subject_information_access_extension
inhibit_any_policy_extension
policy_constraints_extension
subject_directory_attributes_extension
freshest_crl_extension
class Meta

Bases: django_stubs_ext.db.models.TypedModelMeta

Meta class configuration.

__repr__()[source]

Representation of the CertificateModel instance.

Return type:

str

__str__()[source]

Human-readable representation of the CertificateModel instance.

Return type:

str

save(*_args, **_kwargs)[source]

Save method must not be called directly to protect the integrity.

This method makes sure save() is not called by mistake.

Raises:

NotImplementedError

Parameters:
  • _args (Any)

  • _kwargs (Any)

Return type:

None

property signature_algorithm: str

Name of the signature algorithm.

Return type:

str

property signature_algorithm_padding_scheme: str

Padding scheme if RSA is used, otherwise None.

Return type:

str

property signature_suite: trustpoint_core.oid.SignatureSuite

Signature Suite of the certificate.

Return type:

trustpoint_core.oid.SignatureSuite

property public_key_info: trustpoint_core.oid.PublicKeyInfo

Public Key Info of the certificate.

Return type:

trustpoint_core.oid.PublicKeyInfo

property certificate_status: CertificateStatus

Status of the certificate.

Return type:

CertificateStatus

property days_left: int

Returns number of days from now until not_valid_after. If expired, returns 0.

Return type:

int

property is_ca: bool

Check if the certificate is a CA certificate.

Return type:

bool

property is_root_ca: bool

Check if the certificate is a root CA certificate.

Return type:

bool

property is_end_entity: bool

Check if the certificate is an end entity certificate.

Return type:

bool

classmethod get_cert_by_sha256_fingerprint(sha256_fingerprint)[source]

Get a CertificateModel instance by its SHA256 fingerprint.

Parameters:

sha256_fingerprint (str)

Return type:

None | CertificateModel

static _get_subject(cert)[source]
Parameters:

cert (cryptography.x509.Certificate)

Return type:

list[tuple[str, str]]

static _get_issuer_name(cert)[source]
Parameters:

cert (cryptography.x509.Certificate)

Return type:

list[tuple[str, str]]

static _get_spki_info(cert)[source]
Parameters:

cert (cryptography.x509.Certificate)

Return type:

tuple[trustpoint_core.oid.PublicKeyAlgorithmOid, int, trustpoint_core.oid.NamedCurve]

get_certificate_serializer()[source]

Get the serializer for the certificate.

Return type:

trustpoint_core.serializer.CertificateSerializer

get_public_key_serializer()[source]

Get the serializer for the certificate’s public key.

Return type:

trustpoint_core.serializer.PublicKeySerializer

get_certificate_chain()[source]

Get the certificate chain from this certificate up to the root CA.

Return type:

list[CertificateModel]

_save(**kwargs)[source]
Parameters:

kwargs (Any)

Return type:

None

classmethod _save_certificate(certificate)[source]
Parameters:

certificate (cryptography.x509.Certificate | trustpoint_core.serializer.CertificateSerializer)

Return type:

CertificateModel

static _save_attribute_and_value_pairs(oid, value)[source]
Parameters:
  • oid (str)

  • value (str)

Return type:

pki.models.extension.AttributeTypeAndValue

classmethod _save_subject(cert_model, subject)[source]
Parameters:
Return type:

None

classmethod _save_issuer(cert_model, issuer)[source]
Parameters:
Return type:

None

EXTENSION_MAP
static _save_extensions(cert_model, cert)[source]
Parameters:
Return type:

None

classmethod _atomic_save(cert_model, certificate, subject, issuer)[source]
Parameters:
  • cert_model (CertificateModel)

  • certificate (cryptography.x509.Certificate)

  • subject (list[tuple[str, str]])

  • issuer (list[tuple[str, str]])

Return type:

CertificateModel

classmethod save_certificate(certificate)[source]

Store the certificate in the database.

Returns:

The certificate object that has just been saved.

Return type:

trustpoint.pki.models.Certificate

Parameters:

certificate (cryptography.x509.Certificate | trustpoint_core.serializer.CertificateSerializer)

pre_delete()[source]

Store the related objects before deletion.

Return type:

None

post_delete()[source]

Clean up related orphaned extension models.

Return type:

None

subjects_match(other_subject)[source]

Check if the provided subject is identical to the one of this certificate.

Parameters:

other_subject (x509.Name) – The subject to compare to.

Returns:

True if the subjects match, False otherwise.

Return type:

bool

class pki.models.RevokedCertificateModel(*args, **kwargs)[source]

Bases: django.db.models.Model

Model to store revoked certificates.

class ReasonCode(*args, **kwds)

Bases: django.db.models.TextChoices

Revocation reasons per RFC 5280.

UNSPECIFIED
KEY_COMPROMISE
CA_COMPROMISE
AFFILIATION_CHANGED
SUPERSEDED
CESSATION
CERTIFICATE_HOLD
PRIVILEGE_WITHDRAWN
AA_COMPROMISE
REMOVE_FROM_CRL
certificate
revoked_at
revocation_reason
ca
class Meta

Bases: django_stubs_ext.db.models.TypedModelMeta

Meta class configuration.

__str__()[source]

String representation of the RevokedCertificateModel instance.

Return type:

str

class pki.models.CrlModel(*args, **kwargs)[source]

Bases: trustpoint.logger.LoggerMixin, util.db.CustomDeleteActionModel

Certificate Revocation List Model.

This model stores CRLs for CAs (both issuing and non-issuing). Multiple CRLs can exist for a single CA to track CRL history.

ca
crl_pem
crl_number
this_update
next_update
is_active
created_at
updated_at
class Meta

Meta options for CrlModel.

verbose_name
verbose_name_plural
ordering: ClassVar[list[str]] = ['-this_update']
unique_together: ClassVar[list[list[str]]] = [['ca', 'crl_number']]
indexes: ClassVar[list[django.db.models.Index]]
__str__()[source]

Returns a human-readable string representation.

Returns:

Human-readable string representation.

Return type:

str

__repr__()[source]

Returns a string representation of the instance.

Return type:

str

raise_invalid_signature_error()[source]

Raises a ValidationError indicating an invalid CRL signature.

Return type:

Never

classmethod create_from_pem(ca, crl_pem, *, set_active=True, next_update_delta=None)[source]

Creates a new CRL from PEM data.

Parameters:
  • ca (pki.models.CaModel | None) – The CA that issued this CRL. Can be None for CRLs not associated with a CA.

  • crl_pem (str) – The CRL in PEM format.

  • set_active (bool) – If True and ca is provided, deactivates other CRLs for this CA and sets this as active.

  • next_update_delta (datetime.timedelta | None) – Optional timedelta to override the CRL’s nextUpdate field. If provided, sets nextUpdate to thisUpdate + delta.

Returns:

The newly created CRL model.

Return type:

CrlModel

Raises:

ValidationError – If the CRL is invalid or doesn’t match the CA.

get_crl_as_crypto()[source]

Returns the CRL as a cryptography CertificateRevocationList object.

Returns:

The CRL.

Return type:

x509.CertificateRevocationList

Raises:

ValidationError – If the CRL cannot be parsed.

get_revoked_serial_numbers()[source]

Returns a set of revoked certificate serial numbers.

Returns:

Set of revoked serial numbers.

Return type:

set[int]

is_certificate_revoked(serial_number)[source]

Checks if a certificate with the given serial number is revoked.

Parameters:

serial_number (int) – The certificate serial number to check.

Returns:

True if the certificate is revoked, False otherwise.

Return type:

bool

is_expired()[source]

Checks if this CRL has expired based on nextUpdate.

Returns:

True if the CRL has expired, False otherwise.

Return type:

bool

property days_left: int

Returns number of days from now until next_update. If expired or no next_update, returns 0.

Return type:

int

get_validity_hours()[source]

Returns the validity period in hours.

Returns:

The validity period in hours, or None if not set.

Return type:

float | None

save(*args, **kwargs)[source]

Override save to validate before saving.

Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

None

pre_delete()[source]

Called before deleting the model.

Return type:

None

class pki.models.CaModel(*args, **kwargs)[source]

Bases: trustpoint.logger.LoggerMixin, util.db.CustomDeleteActionModel

Generic CA Model representing any Certificate Authority.

This unified model can represent two types of CAs: 1. Keyless CAs: CAs where we only have the certificate (no private key).

Used for trust anchors, upstream CAs, certificate chain validation.

  1. Issuing CAs: CAs managed by Trustpoint that can issue certificates.

For keyless CAs: Only ‘certificate’ field is set, ‘credential’ is null, ca_type is KEYLESS. For issuing CAs: ‘credential’ and ‘ca_type’ are set, ‘certificate’ is null.

class CaTypeChoice(*args, **kwds)

Bases: django.db.models.IntegerChoices

The CaTypeChoice defines the type of CA.

Depending on the type, different fields are required: - KEYLESS: Only certificate field is set (no private key) - LOCAL issuing types: credential field is set, certificate obtained locally - REMOTE issuing types: credential field is set, certificate requested remotely - REMOTE RA types: no credential/certificate, used for connection to external CAs as Registration Authority

KEYLESS
AUTOGEN_ROOT
AUTOGEN
LOCAL_UNPROTECTED
LOCAL_PKCS11
REMOTE_EST_RA
REMOTE_CMP_RA
REMOTE_ISSUING_EST
REMOTE_ISSUING_CMP
unique_name
parent_ca
is_active
created_at
updated_at
ca_type
certificate
credential: django.db.models.OneToOneField[pki.models.credential.CredentialModel | None]
chain_truststore
remote_host
remote_port
remote_path
onboarding_config
no_onboarding_config
class Meta

Meta options for CaModel.

verbose_name
verbose_name_plural
db_table = 'pki_genericcamodel'
ordering: ClassVar[list[str]] = ['unique_name']
constraints: ClassVar[list[django.db.models.BaseConstraint]]
__str__()[source]

Returns a human-readable string that represents this CaModel entry.

Returns:

Human-readable string that represents this CaModel entry.

Return type:

str

__repr__()[source]

Returns a string representation of the CaModel instance.

Return type:

str

property is_issuing_ca: bool

Returns True if this is an issuing CA (can issue certificates).

Return type:

bool

property is_keyless_ca: bool

Returns True if this is a keyless CA (certificate only, no private key).

Return type:

bool

property common_name: str

Returns common name.

Return type:

str

property subject_public_bytes: bytes

Returns the subject public bytes from the CA certificate.

Return type:

bytes

property ca_certificate_model: pki.models.certificate.CertificateModel

Returns the CA certificate model for both issuing and keyless CAs.

Return type:

pki.models.certificate.CertificateModel

get_certificate()[source]

Returns the CA certificate (crypto object) for both issuing and keyless CAs.

Return type:

cryptography.x509.Certificate

get_credential()[source]

Returns the credential for issuing CAs. Raises ValueError for keyless CAs.

Return type:

pki.models.credential.CredentialModel

get_ca_chain_from_truststore()[source]

Returns the CA chain from the associated chain_truststore.

This method validates that the chain_truststore contains certificates that correspond to CAs in the hierarchy path, and returns the CA objects in issuing CA to root order.

Returns:

List of CA models from issuing CA to root CA.

Return type:

list[CaModel]

Raises:

ValueError – If the chain_truststore is not properly configured or contains invalid certificates.

property last_crl_issued_at: datetime.datetime | None

Returns when the last CRL was issued (from active CRL).

Returns:

The this_update time of the active CRL, or None if no CRL exists.

Return type:

datetime | None

property crl_number: int

Returns the current CRL number (from active CRL).

Returns:

The CRL number of the active CRL, or 0 if no CRL exists.

Return type:

int

property crl_pem: str

Returns the active CRL in PEM format.

Returns:

The CRL in PEM format, or empty string if no CRL exists.

Return type:

str

clean()[source]

Validates that exactly one of certificate or credential is set.

Return type:

None

_clean_remote_non_issuing_ca()[source]

Validates remote non-issuing CA fields.

Return type:

None

_clean_remote_issuing_ca()[source]

Validates remote issuing CA fields.

Return type:

None

_clean_local_or_keyless_ca()[source]

Validates local or keyless CA fields.

Return type:

None

save(*args, **kwargs)[source]

Override save to ensure validation.

Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

None

classmethod create_keyless_ca(unique_name, certificate_obj, parent_ca=None)[source]

Creates a new keyless CA from a certificate.

Parameters:
  • unique_name (str) – The unique name that will be used to identify the CA.

  • certificate_obj (cryptography.x509.Certificate) – The CA certificate as cryptography x509.Certificate.

  • parent_ca (CaModel | None) – Optional parent CA in the hierarchy.

Returns:

The newly created keyless CA.

Return type:

CaModel

Raises:

ValidationError – If the certificate is not a valid CA certificate.

classmethod create_new_issuing_ca(credential_serializer, ca_type=None, unique_name=None, parent_ca=None)[source]

Creates a new Issuing CA model.

Parameters:
  • credential_serializer (trustpoint_core.serializer.CredentialSerializer) – The credential as CredentialSerializer instance. It will be normalized and validated, if it is a valid credential to be used as an Issuing CA.

  • ca_type (CaModel | None) – The CA type (must be an issuing type, not KEYLESS).

  • unique_name (str | None) – The unique name for the CA. If not provided, will be auto-generated from certificate common name.

  • parent_ca (CaModel | None) – Optional parent CA in the hierarchy.

Returns:

The newly created Issuing CA model.

Return type:

CaModel

Raises:
  • ValidationError – If the certificate is not a valid CA certificate.

  • ValueError – If the CA type is not supported

_issue_crl(crl_validity_hours=24)[source]

Issues a CRL with revoked certificates issued by this CA.

Only issuing CAs can issue CRLs (keyless CAs don’t have private keys).

Parameters:

crl_validity_hours (int) – Hours until the next CRL update (nextUpdate field). Defaults to 24.

Raises:

AttributeError – If called on a keyless CA.

Return type:

None

issue_crl(crl_validity_hours=24)[source]

Issues a CRL with revoked certificates issued by this CA.

Parameters:

crl_validity_hours (int) – Hours until the next CRL update (nextUpdate field). Defaults to 24.

Returns:

True if the CRL was successfully issued, False otherwise.

Return type:

bool

property signature_suite: trustpoint_core.oid.SignatureSuite

The signature suite for the CA public key certificate.

Return type:

trustpoint_core.oid.SignatureSuite

property public_key_info: trustpoint_core.oid.PublicKeyInfo

The public key info for the CA certificate’s public key.

Return type:

trustpoint_core.oid.PublicKeyInfo

get_issued_certificates()[source]

Returns certificates issued by this CA, except its own in case of a self-signed CA.

This goes through all active certificates and checks issuance by this CA based on cert.issuer_public_bytes == ca.subject_public_bytes.

Warning

This means that it may inadvertently return certificates that were issued by a different CA with the same subject name.

Returns:

Certificates issued by this CA.

Return type:

QuerySet

import_crl(crl_pem, *, set_active=True)[source]

Imports a CRL for this CA.

Parameters:
  • crl_pem (str) – The CRL in PEM format.

  • set_active (bool) – If True, this CRL becomes the active one for the CA.

Returns:

The created CRL model.

Return type:

CrlModel

Raises:

ValidationError – If the CRL is invalid or doesn’t match this CA.

get_active_crl()[source]

Returns the currently active CRL for this CA.

Returns:

The active CRL or None if no CRL exists.

Return type:

CrlModel | None

get_latest_crl()[source]

Returns the most recent CRL for this CA (by this_update).

Returns:

The latest CRL or None if no CRL exists.

Return type:

CrlModel | None

get_crl_as_crypto()[source]

Returns the active CRL as a cryptography CertificateRevocationList object.

Returns:

The CRL or None if no active CRL is available.

Return type:

x509.CertificateRevocationList | None

get_hierarchy_depth()[source]

Returns the depth of this CA in the hierarchy.

Returns:

The depth (0 for root CA, 1 for intermediate, etc.)

Return type:

int

get_root_ca()[source]

Returns the root CA in the hierarchy.

Returns:

The root CA (self if this is already a root CA).

Return type:

CaModel

get_all_child_cas(*, include_self=False)[source]

Returns all descendant CAs (children, grandchildren, etc.).

Parameters:

include_self (bool) – If True, includes this CA in the result.

Returns:

All descendant CAs.

Return type:

QuerySet

get_hierarchy_path()[source]

Returns the path from root CA to this CA.

Returns:

List of CAs from root to this CA (inclusive).

Return type:

list[CaModel]

is_root_ca()[source]

Returns True if this CA has no parent (is a root CA).

Returns:

True if this is a root CA.

Return type:

bool

revoke_all_issued_certificates(reason=RevokedCertificateModel.ReasonCode.UNSPECIFIED)[source]

Revokes all certificates issued by this CA.

Parameters:

reason (str)

Return type:

None

pre_delete()[source]

Checks for unexpired certificates issued by this CA and child CAs before deleting it.

Raises:

ValidationError – If there are unexpired certificates issued by this CA or if this CA has child CAs.

Return type:

None

post_delete()[source]

Deletes the underlying credential or certificate after deleting this CA.

Return type:

None

exception pki.models.CredentialAlreadyExistsError(*args, **kwargs)[source]

Bases: django.core.exceptions.ValidationError

The CredentialAlreadyExistsError is raised if a credential already exists in the database.

Parameters:
  • args (Any)

  • kwargs (Any)

class pki.models.CredentialModel(*args, **kwargs)[source]

Bases: trustpoint.logger.LoggerMixin, util.db.CustomDeleteActionModel

The CredentialModel that holds all local credentials used by the Trustpoint.

This model holds both local unprotected credentials, for which the keys and certificates are stored in the DB, but also credentials that are stored within an HSM or TPM utilizing PKCS#11.

PKCS#11 credentials are not yet supported.

class CredentialTypeChoice(*args, **kwds)

Bases: django.db.models.IntegerChoices

The CredentialTypeChoice defines the type of the credential and thus implicitly restricts its usage.

It is intended to limit the credential usage to specific cases, e.g. usage as Issuing CA. The abstractions using the CredentialModel are responsible to check that the credential has the correct and expected CredentialTypeChoice.

TRUSTPOINT_TLS_SERVER
ROOT_CA
ISSUING_CA
ISSUED_CREDENTIAL
DEV_OWNER_ID
SIGNER
credential_type
private_key
pkcs11_private_key
certificate
certificates
certificate_chain: django.db.models.ManyToManyField[pki.models.CertificateModel, CertificateChainOrderModel]
created_at
__repr__()[source]

Returns a string representation of this CredentialModel entry.

Return type:

str

__str__()[source]

Returns a human-readable string that represents this CredentialModel entry.

Returns:

Human-readable string that represents this CredentialModel entry.

Return type:

str

clean()[source]

Validates the CredentialModel instance.

Return type:

None

classmethod save_credential_serializer(credential_serializer, credential_type)[source]

This method will try to normalize the credential_serializer and then save it to the database.

Parameters:
  • credential_serializer (trustpoint_core.serializer.CredentialSerializer) – The credential serializer to store in the database.

  • credential_type (CredentialModel) – The credential type to set.

Returns:

The stored credential model.

Return type:

CredentialModel

property ordered_certificate_chain_queryset: django.db.models.QuerySet[CertificateChainOrderModel]

Gets the ordered certificate chain queryset.

Return type:

django.db.models.QuerySet[CertificateChainOrderModel]

classmethod _import_private_key_to_hsm(crypto_private_key, token_config, key_label)[source]

Import a private key to HSM and create corresponding PKCS11Key model.

Parameters:
  • crypto_private_key (trustpoint_core.crypto_types.PrivateKey) – The private key from cryptography library

  • key_label (str) – Custom label for the key (auto-generated if None)

  • token_config (management.models.PKCS11Token) – PKCS11Token configuration

Returns:

The created model instance referencing the HSM key

Return type:

PKCS11Key

Raises:
  • RuntimeError – If HSM import fails

  • ValueError – If unsupported key type

  • NotImplementedError – If EC key import not yet supported

classmethod _create_private_key_in_hsm(key_type, token_config, key_label, key_size=None, key_curve=None)[source]

Generate a new private key in HSM and create corresponding PKCS11Key model.

Parameters:
  • key_type (type[trustpoint_core.crypto_types.PrivateKey]) – Type of key to generate (‘rsa.PrivateKey’ or ‘ec.PrivateKey’)

  • token_config (management.models.PKCS11Token) – PKCS11Token configuration

  • key_label (str) – Label for the new key in HSM

  • key_size (int | None) – For RSA keys: key size in bits (e.g., 2048, 4096)

  • key_curve (cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve | None) – For EC keys: curve instance (e.g., ec.SECP256R1())

Returns:

The created model instance referencing the HSM key

Return type:

PKCS11Key

Raises:
  • RuntimeError – If HSM key generation fails

  • ValueError – If unsupported key type or invalid parameters

  • NotImplementedError – If EC key generation not yet supported

static _validate_hsm_inputs(token_config, key_label, key_type, key_size, key_curve)[source]

Validates the inputs for HSM key creation.

Parameters:
  • token_config (management.models.PKCS11Token)

  • key_label (str)

  • key_type (type[trustpoint_core.crypto_types.PrivateKey])

  • key_size (int | None)

  • key_curve (cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve | None)

Return type:

None

static _initialize_key_handler(key_type, token_config, key_label, key_size, key_curve)[source]

Initializes the PKCS#11 key handler.

Parameters:
  • key_type (type[trustpoint_core.crypto_types.PrivateKey])

  • token_config (management.models.PKCS11Token)

  • key_label (str)

  • key_size (int | None)

  • key_curve (cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve | None)

Return type:

tuple[management.pkcs11_util.Pkcs11RSAPrivateKey | management.pkcs11_util.Pkcs11ECPrivateKey, str]

classmethod _save_normalized_credential_serializer(normalized_credential_serializer, credential_type)[source]

This method will store a credential that is expected to be normalized.

Parameters:
  • normalized_credential_serializer (trustpoint_core.serializer.CredentialSerializer)

  • credential_type (CredentialModel)

Return type:

CredentialModel

static _validate_and_save_certificate(normalized_credential_serializer)[source]

Validates and saves the certificate from the provided serializer.

Parameters:

normalized_credential_serializer (CredentialSerializer) – The serializer containing the certificate to be validated and saved.

Raises:

ValueError – If the certificate in the serializer is None.

Returns:

The saved certificate model instance.

Return type:

CertificateModel

classmethod _process_private_key(normalized_credential_serializer)[source]

Processes the private key based on its location and returns the appropriate values.

Parameters:

normalized_credential_serializer (trustpoint_core.serializer.CredentialSerializer)

Return type:

tuple[PKCS11Key | None, str]

classmethod _handle_hsm_key(normalized_credential_serializer)[source]

Handles the creation or import of a private key in an HSM (Hardware Security Module).

Parameters:

normalized_credential_serializer (trustpoint_core.serializer.CredentialSerializer)

Return type:

PKCS11Key

classmethod _create_credential_model(certificate, credential_type, private_key_pem, pkcs11_private_key)[source]

Creates and saves a CredentialModel instance.

Parameters:
Return type:

CredentialModel

static _save_additional_certificates(credential_model, additional_certificates)[source]

Saves additional certificates in the certificate chain.

Parameters:
  • credential_model (CredentialModel)

  • additional_certificates (list[cryptography.x509.Certificate])

Return type:

None

classmethod save_keyless_credential(certificate, certificate_chain, credential_type)[source]

Stores a credential without a private key.

Parameters:
  • certificate (cryptography.x509.Certificate)

  • certificate_chain (list[cryptography.x509.Certificate])

  • credential_type (CredentialModel)

Return type:

CredentialModel

update_keyless_credential(certificate, certificate_chain)[source]

Updates the primary certificate and certificate chain of the credential.

Previous certificates are kept as part of the credential.

Parameters:
  • certificate (cryptography.x509.Certificate)

  • certificate_chain (list[cryptography.x509.Certificate])

Return type:

None

pre_delete()[source]

Deletes related models, only allow deletion if there are no more active certificates.

Return type:

None

get_private_key()[source]

Gets an abstraction of the credential private key.

Note, in the case of keys stored in an HSM or TPM using PKCS#11, it will only be possible to use the key abstraction to sign and verify, but not to export the key in any way.

Returns:

The credential private key abstraction.

Return type:

PrivateKey

get_pkcs11_private_key()[source]

Gets the private key abstraction.

Return type:

trustpoint_core.crypto_types.PrivateKey

get_private_key_serializer()[source]

Gets a serializer of the credential private key.

For PKCS#11 keys, since the private key cannot be exported, this method returns a PrivateKeySerializer constructed from the public key extracted from the certificate. This allows code that needs the public key (via .public_key_serializer) to work with both software-stored and HSM-stored credentials.

Returns:

The credential private key serializer.

Return type:

PrivateKeySerializer

Raises:

RuntimeError – If no private key information is available.

get_certificate()[source]

Gets the credential certificate as x509.Certificate instance.

Returns:

The credential certificate.

Return type:

x509.Certificate

get_certificate_chain()[source]

Gets the credential certificate chain as a list of x509.Certificate instances.

Returns:

The credential certificate chain as list of x509.Certificate instances.

Return type:

list[x509.Certificate]

get_certificate_serializer()[source]

Gets the credential certificate as a CertificateSerializer instance.

Returns:

The credential certificate.

Return type:

CertificateSerializer

get_certificate_chain_serializer()[source]

Gets the credential certificate chain as a CertificateCollectionSerializer instance.

Returns:

The credential certificate chain.

Return type:

CertificateCollectionSerializer

get_last_in_chain()[source]

Gets the root ca certificate model, if any.

Return type:

None | pki.models.CertificateModel

get_root_ca_certificate()[source]

Gets the root CA certificate of the credential certificate chain.

Return type:

None | cryptography.x509.Certificate

get_root_ca_certificate_serializer()[source]

Gets the root CA certificate serializer.

Return type:

None | trustpoint_core.serializer.CertificateSerializer

get_credential_serializer()[source]

Gets the serializer for this credential.

Return type:

trustpoint_core.serializer.CredentialSerializer

property signature_suite: trustpoint_core.oid.SignatureSuite

Returns the signature suite used by the current credential primary certificate.

Return type:

trustpoint_core.oid.SignatureSuite

property public_key_info: trustpoint_core.oid.PublicKeyInfo

Returns the PublicKeyInfo the current credential primary certificate.

Return type:

trustpoint_core.oid.PublicKeyInfo

property hash_algorithm: cryptography.hazmat.primitives.hashes.HashAlgorithm | None

Returns the hash algorithm used by the current credential.

Return type:

cryptography.hazmat.primitives.hashes.HashAlgorithm | None

is_valid_issued_credential()[source]

Determines if this issued credential is valid.

This method performs the following checks:
  1. The credential must be of type ISSUED_CREDENTIAL.

  2. A primary certificate must exist.

  3. The certificate’s status must be ‘OK’.

Returns:

A tuple where:
  • The first value is True if the credential meets all criteria, False otherwise.

  • The second value is a reason string explaining why the credential is invalid.

Return type:

tuple[bool, str]

class pki.models.OwnerCredentialModel(*args, **kwargs)[source]

Bases: trustpoint.logger.LoggerMixin, util.db.CustomDeleteActionModel

Device owner credential model.

This model is a wrapper to store a DevOwnerID Credential for use by devices to trust the Trustpoint.

unique_name
credential: django.db.models.OneToOneField[CredentialModel]
created_at
__str__()[source]

Returns a human-readable string that represents this OwnerCredentialModel entry.

Returns:

Human-readable string that represents this OwnerCredentialModel entry.

Return type:

str

__repr__()[source]

Returns a string representation of the OwnerCredentialModel instance.

Return type:

str

classmethod create_new_owner_credential(unique_name, credential_serializer)[source]

Creates a new owner credential model and returns it.

Parameters:
  • unique_name (str) – The unique name that will be used to identify the Owner Credential.

  • credential_serializer (trustpoint_core.serializer.CredentialSerializer) – The credential as CredentialSerializer instance.

Returns:

The newly created owner credential model.

Return type:

OwnerCredentialModel

post_delete()[source]

Deletes the credential of this owner credential after deleting it.

Return type:

None

class pki.models.PKCS11Key(*args, **kwargs)[source]

Bases: django.db.models.Model

Model representing a private key stored in a PKCS#11 HSM/token.

class KeyType(*args, **kwds)

Bases: django.db.models.TextChoices

Supported key types in PKCS#11.

RSA
EC
AES
token_label
key_label
key_type
created_at
class Meta

Meta class to define unique constraints and verbose names for the PKCS11Key model.

unique_together: ClassVar = [['token_label', 'key_label']]
verbose_name
verbose_name_plural
__str__()[source]

Return a string representation of the PKCS11Key instance.

Return type:

str

get_pkcs11_key_instance(lib_path, user_pin)[source]

Get the appropriate PKCS#11 key instance.

Parameters:
  • lib_path (str)

  • user_pin (str)

Return type:

management.pkcs11_util.Pkcs11RSAPrivateKey | management.pkcs11_util.Pkcs11ECPrivateKey | management.pkcs11_util.Pkcs11AESKey

class pki.models.DomainModel(*args, **kwargs)[source]

Bases: django.db.models.Model

Domain Model.

unique_name
issuing_ca
is_active
created_at
updated_at
__repr__()[source]

Machine-readable representation of the Domain model instance.

Returns:

Machine-readable representation of the Domain model model instance.

Return type:

str

__str__()[source]

Human-readable representation of the Domain model instance.

Returns:

Human-readable representation of the Domain model model instance.

Return type:

str

save(**kwargs)[source]

Save the Domain model and add default certificate profiles.

Parameters:

kwargs (Any)

Return type:

None

property signature_suite: trustpoint_core.oid.SignatureSuite

Get the signature suite for the domain (based on its Issuing CA).

Return type:

trustpoint_core.oid.SignatureSuite

property public_key_info: trustpoint_core.oid.PublicKeyInfo

Get the public key info for the domain (based on its Issuing CA).

Return type:

trustpoint_core.oid.PublicKeyInfo

clean()[source]

Validate that the issuing CA is not an auto-generated root CA.

Return type:

None

get_issuing_ca_or_value_error()[source]

Gets the corresponding Issuing CA.

Returns:

The corresponding Issuing CA.

Raises:

ValueError – If no Issuing CA is set.

Return type:

pki.models.CaModel

get_allowed_cert_profiles()[source]

Gets the allowed certificate profiles for this domain.

Returns:

QuerySet of allowed DomainAllowedCertificateProfileModel instances.

Return type:

django.db.models.QuerySet[DomainAllowedCertificateProfileModel]

get_allowed_cert_profile_names()[source]

Gets the set of allowed certificate profile names for this domain.

Returns:

Set of allowed certificate profile names.

Return type:

set[str]

get_allowed_cert_profile(cert_profile_str)[source]

Gets the requested certificate profile if it is allowed for this domain. Else, raises a ValueError.

Parameters:

cert_profile_str (str) – The name of the certificate profile to check.

Returns:

The requested CertificateProfileModel (if allowed).

Return type:

pki.models.cert_profile.CertificateProfileModel

set_allowed_cert_profiles(allowed_profile_data)[source]

Sets the certificate profiles allowed in the domain.

Parameters:

allowed_profile_data (dict[str, str]) – Dict where key is allowed certificate profile ID (str) and value is optional alias

Returns:

Set of rejected aliases due to duplication in the form of (alias, profile unique name)

Return type:

set[tuple[str, str]]

_add_default_profiles()[source]

Adds default certificate profiles to the domain as allowed.

Return type:

None

class pki.models.DomainAllowedCertificateProfileModel(*args, **kwargs)[source]

Bases: django.db.models.Model

Model representing allowed certificate profiles for a domain.

domain
certificate_profile
alias
class Meta

Bases: django_stubs_ext.db.models.TypedModelMeta

Meta information.

constraints: ClassVar
__str__()[source]

String representation of the DomainAllowedCertificateProfileModel.

Return type:

str

class pki.models.DevIdRegistration(*args, **kwargs)[source]

Bases: django.db.models.Model

Represents a DevID Registration, linking a Truststore, Domain, unique name, and a serial number regex pattern.

unique_name
truststore
domain
serial_number_pattern
__str__()[source]

Returns a human-readable string representation of the DevIdRegistration instance.

Return type:

str

save(**kwargs)[source]

Ensures the model is valid and enforces validations before saving.

Parameters:

kwargs (Any)

Return type:

None

class pki.models.CertificateProfileModel(*args, **kwargs)[source]

Bases: django.db.models.Model

Model representing a certificate profile.

unique_name
display_name
profile_json
created_at
updated_at
is_default
class Meta

Bases: django_stubs_ext.db.models.TypedModelMeta

Meta information.

__str__()[source]

String representation of the CertificateProfileModel.

Return type:

str

class pki.models.TruststoreModel(*args, **kwargs)[source]

Bases: django.db.models.Model

Represents a truststore, which is a collection of certificates used for specific purposes.

This model allows organizing certificates into a logical grouping for specific intended usages such as IDevID, TLS, or Generic. Each truststore is identified by a unique name and supports operations like retrieving the number of certificates or serializing its content.

class IntendedUsage(*args, **kwds)

Bases: django.db.models.IntegerChoices

Intended Usage of the Truststore.

IDEVID
TLS
GENERIC
DEVICE_OWNER_ID
ISSUING_CA_CHAIN
OPC_UA_GDS_PUSH
unique_name
certificates: django.db.models.ManyToManyField[pki.models.certificate.CertificateModel, TruststoreOrderModel]
intended_usage
created_at
class Meta

Bases: django_stubs_ext.db.models.TypedModelMeta

Meta class configuration.

__str__()[source]

Returns a human-readable string representation of the TruststoreModel.

Return type:

str

save(**kwargs)[source]

Ensures the model is valid before saving.

Parameters:

kwargs (Any)

Return type:

None

property number_of_certificates: int

Returns the number of certificates in the truststore.

Return type:

int

get_certificate_collection_serializer()[source]

Returns a serializer for all certificates in the truststore.

This method gathers all the certificates associated with the truststore, serializes them using CertificateCollectionSerializer, and returns the serialized result.

Returns:

The serialized representation of the certificates.

Return type:

trustpoint_core.serializer.CertificateCollectionSerializer

class pki.models.TruststoreOrderModel(*args, **kwargs)[source]

Bases: django.db.models.Model

Represents the order of certificates in a truststore.

order
certificate
trust_store
class Meta

Bases: django_stubs_ext.db.models.TypedModelMeta

Meta class configuration.

unique_together = ('order', 'trust_store')
__str__()[source]

Returns a human-readable string representation of the TruststoreOrderModel.

Return type:

str