authentik.crypto.models
authentik crypto models
1"""authentik crypto models""" 2 3from base64 import urlsafe_b64encode 4from binascii import hexlify 5from collections.abc import Callable 6from functools import lru_cache 7from hashlib import md5, sha512 8from ssl import PEM_FOOTER, PEM_HEADER 9from textwrap import wrap 10from uuid import uuid4 11 12from cryptography.hazmat.backends import default_backend 13from cryptography.hazmat.primitives import hashes 14from cryptography.hazmat.primitives.asymmetric.dsa import DSAPublicKey 15from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey 16from cryptography.hazmat.primitives.asymmetric.ed448 import Ed448PublicKey 17from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey 18from cryptography.hazmat.primitives.asymmetric.mldsa import ( 19 MLDSA44PublicKey, 20 MLDSA65PublicKey, 21 MLDSA87PublicKey, 22) 23from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey 24from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes, PublicKeyTypes 25from cryptography.hazmat.primitives.serialization import load_pem_private_key 26from cryptography.x509 import Certificate, load_pem_x509_certificate 27from django.db import models 28from django.utils.translation import gettext_lazy as _ 29from rest_framework.serializers import Serializer 30from structlog.stdlib import get_logger 31 32from authentik.blueprints.models import ManagedModel 33from authentik.lib.jwt_mldsa import KEY_LOAD_ERRORS 34from authentik.lib.models import CreatedUpdatedModel, SerializerModel 35 36LOGGER = get_logger() 37 38 39@lru_cache(maxsize=128) 40def _load_certificate(certificate_data: str) -> Certificate: 41 """Load a PEM certificate.""" 42 return load_pem_x509_certificate(certificate_data.encode("utf-8"), default_backend()) 43 44 45@lru_cache(maxsize=128) 46def _load_private_key(key_data: str) -> PrivateKeyTypes: 47 """Load and validate a normalized PEM private key.""" 48 return load_pem_private_key( 49 key_data.encode("utf-8"), 50 password=None, 51 backend=default_backend(), 52 ) 53 54 55@lru_cache(maxsize=128) 56def _load_public_key(key_data: str) -> PublicKeyTypes: 57 """Load the public key of a normalized PEM private key. 58 59 Loading an RSA private key normally checks its private components, including that both 60 primes are prime, which takes tens of milliseconds for a 3072-bit key and more for a 4096-bit 61 one. That check protects signing, and every path that stores a key already ran it. The public 62 key is only the modulus and exponent, so this skips the check and returns nothing that can 63 sign. Keep the unvalidated private key inside this function.""" 64 return load_pem_private_key( 65 key_data.encode("utf-8"), 66 password=None, 67 backend=default_backend(), 68 unsafe_skip_rsa_key_validation=True, 69 ).public_key() 70 71 72def format_cert(raw_pam: str) -> str: 73 """Format a PEM certificate that is either missing its header/footer or is in a single line""" 74 return "\n".join([PEM_HEADER, *wrap(raw_pam.replace("\n", ""), 64), PEM_FOOTER]) 75 76 77class KeyType(models.TextChoices): 78 """Cryptographic key algorithm types""" 79 80 RSA = "rsa", _("RSA") 81 EC = "ec", _("Elliptic Curve") 82 DSA = "dsa", _("DSA") 83 ED25519 = "ed25519", _("Ed25519") 84 ED448 = "ed448", _("Ed448") 85 MLDSA44 = "mldsa44", _("ML-DSA-44") 86 MLDSA65 = "mldsa65", _("ML-DSA-65") 87 MLDSA87 = "mldsa87", _("ML-DSA-87") 88 89 90def fingerprint_sha256(cert: Certificate) -> str: 91 """Get SHA256 Fingerprint of certificate""" 92 return hexlify(cert.fingerprint(hashes.SHA256()), ":").decode("utf-8") 93 94 95def detect_key_type(certificate: Certificate) -> str | None: 96 """Detect the key algorithm type by parsing the certificate's public key""" 97 try: 98 public_key = certificate.public_key() 99 if isinstance(public_key, RSAPublicKey): 100 return KeyType.RSA 101 if isinstance(public_key, EllipticCurvePublicKey): 102 return KeyType.EC 103 if isinstance(public_key, DSAPublicKey): 104 return KeyType.DSA 105 if isinstance(public_key, Ed25519PublicKey): 106 return KeyType.ED25519 107 if isinstance(public_key, Ed448PublicKey): 108 return KeyType.ED448 109 if isinstance(public_key, MLDSA44PublicKey): 110 return KeyType.MLDSA44 111 if isinstance(public_key, MLDSA65PublicKey): 112 return KeyType.MLDSA65 113 if isinstance(public_key, MLDSA87PublicKey): 114 return KeyType.MLDSA87 115 except (ValueError, TypeError, AttributeError) as exc: 116 LOGGER.warning("Failed to detect key type", exc=exc) 117 return None 118 119 120def generate_key_id(key_data: str) -> str: 121 """Generate Key ID using SHA512 + urlsafe_b64encode.""" 122 if not key_data: 123 return "" 124 return urlsafe_b64encode(sha512(key_data.encode("utf-8")).digest()).decode("utf-8").rstrip("=") 125 126 127def generate_key_id_legacy(key_data: str) -> str: 128 """Generate Key ID using MD5 (legacy format for backwards compatibility).""" 129 if not key_data: 130 return "" 131 return md5(key_data.encode("utf-8"), usedforsecurity=False).hexdigest() # nosec 132 133 134class CertificateKeyPair(SerializerModel, ManagedModel, CreatedUpdatedModel): 135 """CertificateKeyPair that can be used for signing or encrypting if `key_data` 136 is set, otherwise it can be used to verify remote data.""" 137 138 kp_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4) 139 140 name = models.TextField(unique=True) 141 certificate_data = models.TextField(help_text=_("PEM-encoded Certificate data")) 142 key_data = models.TextField( 143 help_text=_( 144 "Optional Private Key. If this is set, you can use this keypair for encryption." 145 ), 146 blank=True, 147 default="", 148 ) 149 key_type = models.CharField( 150 max_length=16, 151 choices=KeyType.choices, 152 null=True, 153 blank=True, 154 help_text=_("Key algorithm type detected from the certificate's public key"), 155 ) 156 cert_expiry = models.DateTimeField( 157 null=True, 158 blank=True, 159 help_text=_("Certificate expiry date"), 160 ) 161 cert_subject = models.TextField( 162 null=True, 163 blank=True, 164 help_text=_("Certificate subject as RFC4514 string"), 165 ) 166 fingerprint_sha256 = models.CharField( 167 max_length=95, 168 null=True, 169 blank=True, 170 help_text=_("SHA256 fingerprint of the certificate"), 171 ) 172 fingerprint_sha1 = models.CharField( 173 max_length=59, 174 null=True, 175 blank=True, 176 help_text=_("SHA1 fingerprint of the certificate"), 177 ) 178 kid = models.CharField( 179 max_length=128, 180 null=True, 181 blank=True, 182 help_text=_("Key ID generated from private key"), 183 ) 184 185 _cert: Certificate | None = None 186 _private_key: PrivateKeyTypes | None = None 187 _public_key: PublicKeyTypes | None = None 188 189 @property 190 def serializer(self) -> Serializer: 191 from authentik.crypto.api import CertificateKeyPairSerializer 192 193 return CertificateKeyPairSerializer 194 195 @property 196 def certificate(self) -> Certificate: 197 """Get python cryptography Certificate instance""" 198 if not self._cert: 199 self._cert = _load_certificate(self.certificate_data) 200 return self._cert 201 202 @property 203 def public_key(self) -> PublicKeyTypes | None: 204 """Get public key of the private key, without loading the private key for signing""" 205 if not self._public_key: 206 self._public_key = self._load_key(_load_public_key, "public") 207 return self._public_key 208 209 @property 210 def private_key( 211 self, 212 ) -> PrivateKeyTypes | None: 213 """Get python cryptography PrivateKey instance""" 214 if not self._private_key: 215 self._private_key = self._load_key(_load_private_key, "private") 216 return self._private_key 217 218 def _load_key[T](self, loader: Callable[[str], T], kind: str) -> T | None: 219 if self.key_data == "": 220 return None 221 try: 222 return loader("\n".join(x.strip() for x in self.key_data.split("\n"))) 223 except KEY_LOAD_ERRORS as exc: 224 # InternalError/UnsupportedAlgorithm: OpenSSL has no implementation for the key's 225 # algorithm in the current configuration (e.g. ML-DSA under a FIPS provider that 226 # predates it), so treat the key as unusable rather than failing the caller 227 LOGGER.warning(f"Failed to load {kind} key", exc=exc) 228 return None 229 230 def __str__(self) -> str: 231 return f"Certificate-Key Pair {self.name}" 232 233 class Meta: 234 verbose_name = _("Certificate-Key Pair") 235 verbose_name_plural = _("Certificate-Key Pairs") 236 permissions = [ 237 ("view_certificatekeypair_certificate", _("View Certificate-Key pair's certificate")), 238 ("view_certificatekeypair_key", _("View Certificate-Key pair's private key")), 239 ]
73def format_cert(raw_pam: str) -> str: 74 """Format a PEM certificate that is either missing its header/footer or is in a single line""" 75 return "\n".join([PEM_HEADER, *wrap(raw_pam.replace("\n", ""), 64), PEM_FOOTER])
Format a PEM certificate that is either missing its header/footer or is in a single line
78class KeyType(models.TextChoices): 79 """Cryptographic key algorithm types""" 80 81 RSA = "rsa", _("RSA") 82 EC = "ec", _("Elliptic Curve") 83 DSA = "dsa", _("DSA") 84 ED25519 = "ed25519", _("Ed25519") 85 ED448 = "ed448", _("Ed448") 86 MLDSA44 = "mldsa44", _("ML-DSA-44") 87 MLDSA65 = "mldsa65", _("ML-DSA-65") 88 MLDSA87 = "mldsa87", _("ML-DSA-87")
Cryptographic key algorithm types
91def fingerprint_sha256(cert: Certificate) -> str: 92 """Get SHA256 Fingerprint of certificate""" 93 return hexlify(cert.fingerprint(hashes.SHA256()), ":").decode("utf-8")
Get SHA256 Fingerprint of certificate
96def detect_key_type(certificate: Certificate) -> str | None: 97 """Detect the key algorithm type by parsing the certificate's public key""" 98 try: 99 public_key = certificate.public_key() 100 if isinstance(public_key, RSAPublicKey): 101 return KeyType.RSA 102 if isinstance(public_key, EllipticCurvePublicKey): 103 return KeyType.EC 104 if isinstance(public_key, DSAPublicKey): 105 return KeyType.DSA 106 if isinstance(public_key, Ed25519PublicKey): 107 return KeyType.ED25519 108 if isinstance(public_key, Ed448PublicKey): 109 return KeyType.ED448 110 if isinstance(public_key, MLDSA44PublicKey): 111 return KeyType.MLDSA44 112 if isinstance(public_key, MLDSA65PublicKey): 113 return KeyType.MLDSA65 114 if isinstance(public_key, MLDSA87PublicKey): 115 return KeyType.MLDSA87 116 except (ValueError, TypeError, AttributeError) as exc: 117 LOGGER.warning("Failed to detect key type", exc=exc) 118 return None
Detect the key algorithm type by parsing the certificate's public key
121def generate_key_id(key_data: str) -> str: 122 """Generate Key ID using SHA512 + urlsafe_b64encode.""" 123 if not key_data: 124 return "" 125 return urlsafe_b64encode(sha512(key_data.encode("utf-8")).digest()).decode("utf-8").rstrip("=")
Generate Key ID using SHA512 + urlsafe_b64encode.
128def generate_key_id_legacy(key_data: str) -> str: 129 """Generate Key ID using MD5 (legacy format for backwards compatibility).""" 130 if not key_data: 131 return "" 132 return md5(key_data.encode("utf-8"), usedforsecurity=False).hexdigest() # nosec
Generate Key ID using MD5 (legacy format for backwards compatibility).
135class CertificateKeyPair(SerializerModel, ManagedModel, CreatedUpdatedModel): 136 """CertificateKeyPair that can be used for signing or encrypting if `key_data` 137 is set, otherwise it can be used to verify remote data.""" 138 139 kp_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4) 140 141 name = models.TextField(unique=True) 142 certificate_data = models.TextField(help_text=_("PEM-encoded Certificate data")) 143 key_data = models.TextField( 144 help_text=_( 145 "Optional Private Key. If this is set, you can use this keypair for encryption." 146 ), 147 blank=True, 148 default="", 149 ) 150 key_type = models.CharField( 151 max_length=16, 152 choices=KeyType.choices, 153 null=True, 154 blank=True, 155 help_text=_("Key algorithm type detected from the certificate's public key"), 156 ) 157 cert_expiry = models.DateTimeField( 158 null=True, 159 blank=True, 160 help_text=_("Certificate expiry date"), 161 ) 162 cert_subject = models.TextField( 163 null=True, 164 blank=True, 165 help_text=_("Certificate subject as RFC4514 string"), 166 ) 167 fingerprint_sha256 = models.CharField( 168 max_length=95, 169 null=True, 170 blank=True, 171 help_text=_("SHA256 fingerprint of the certificate"), 172 ) 173 fingerprint_sha1 = models.CharField( 174 max_length=59, 175 null=True, 176 blank=True, 177 help_text=_("SHA1 fingerprint of the certificate"), 178 ) 179 kid = models.CharField( 180 max_length=128, 181 null=True, 182 blank=True, 183 help_text=_("Key ID generated from private key"), 184 ) 185 186 _cert: Certificate | None = None 187 _private_key: PrivateKeyTypes | None = None 188 _public_key: PublicKeyTypes | None = None 189 190 @property 191 def serializer(self) -> Serializer: 192 from authentik.crypto.api import CertificateKeyPairSerializer 193 194 return CertificateKeyPairSerializer 195 196 @property 197 def certificate(self) -> Certificate: 198 """Get python cryptography Certificate instance""" 199 if not self._cert: 200 self._cert = _load_certificate(self.certificate_data) 201 return self._cert 202 203 @property 204 def public_key(self) -> PublicKeyTypes | None: 205 """Get public key of the private key, without loading the private key for signing""" 206 if not self._public_key: 207 self._public_key = self._load_key(_load_public_key, "public") 208 return self._public_key 209 210 @property 211 def private_key( 212 self, 213 ) -> PrivateKeyTypes | None: 214 """Get python cryptography PrivateKey instance""" 215 if not self._private_key: 216 self._private_key = self._load_key(_load_private_key, "private") 217 return self._private_key 218 219 def _load_key[T](self, loader: Callable[[str], T], kind: str) -> T | None: 220 if self.key_data == "": 221 return None 222 try: 223 return loader("\n".join(x.strip() for x in self.key_data.split("\n"))) 224 except KEY_LOAD_ERRORS as exc: 225 # InternalError/UnsupportedAlgorithm: OpenSSL has no implementation for the key's 226 # algorithm in the current configuration (e.g. ML-DSA under a FIPS provider that 227 # predates it), so treat the key as unusable rather than failing the caller 228 LOGGER.warning(f"Failed to load {kind} key", exc=exc) 229 return None 230 231 def __str__(self) -> str: 232 return f"Certificate-Key Pair {self.name}" 233 234 class Meta: 235 verbose_name = _("Certificate-Key Pair") 236 verbose_name_plural = _("Certificate-Key Pairs") 237 permissions = [ 238 ("view_certificatekeypair_certificate", _("View Certificate-Key pair's certificate")), 239 ("view_certificatekeypair_key", _("View Certificate-Key pair's private key")), 240 ]
CertificateKeyPair that can be used for signing or encrypting if key_data
is set, otherwise it can be used to verify remote data.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
190 @property 191 def serializer(self) -> Serializer: 192 from authentik.crypto.api import CertificateKeyPairSerializer 193 194 return CertificateKeyPairSerializer
Get serializer for this model
196 @property 197 def certificate(self) -> Certificate: 198 """Get python cryptography Certificate instance""" 199 if not self._cert: 200 self._cert = _load_certificate(self.certificate_data) 201 return self._cert
Get python cryptography Certificate instance
203 @property 204 def public_key(self) -> PublicKeyTypes | None: 205 """Get public key of the private key, without loading the private key for signing""" 206 if not self._public_key: 207 self._public_key = self._load_key(_load_public_key, "public") 208 return self._public_key
Get public key of the private key, without loading the private key for signing
210 @property 211 def private_key( 212 self, 213 ) -> PrivateKeyTypes | None: 214 """Get python cryptography PrivateKey instance""" 215 if not self._private_key: 216 self._private_key = self._load_key(_load_private_key, "private") 217 return self._private_key
Get python cryptography PrivateKey instance
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.
In the example::
class Pizza(Model):
toppings = ManyToManyField(Topping, related_name='pizzas')
Pizza.toppings and Topping.pizzas are ManyToManyDescriptor
instances.
Most of the implementation is delegated to a dynamically defined manager
class built by create_forward_many_to_many_manager() defined below.
Accessor to the related objects manager on the reverse side of a many-to-one relation.
In the example::
class Child(Model):
parent = ForeignKey(Parent, related_name='children')
Parent.children is a ReverseManyToOneDescriptor instance.
Most of the implementation is delegated to a dynamically defined manager
class built by create_forward_many_to_many_manager() defined below.
Accessor to the related objects manager on the reverse side of a many-to-one relation.
In the example::
class Child(Model):
parent = ForeignKey(Parent, related_name='children')
Parent.children is a ReverseManyToOneDescriptor instance.
Most of the implementation is delegated to a dynamically defined manager
class built by create_forward_many_to_many_manager() defined below.
Accessor to the related objects manager on the reverse side of a many-to-one relation.
In the example::
class Child(Model):
parent = ForeignKey(Parent, related_name='children')
Parent.children is a ReverseManyToOneDescriptor instance.
Most of the implementation is delegated to a dynamically defined manager
class built by create_forward_many_to_many_manager() defined below.
Accessor to the related objects manager on the reverse side of a many-to-one relation.
In the example::
class Child(Model):
parent = ForeignKey(Parent, related_name='children')
Parent.children is a ReverseManyToOneDescriptor instance.
Most of the implementation is delegated to a dynamically defined manager
class built by create_forward_many_to_many_manager() defined below.
Accessor to the related objects manager on the reverse side of a many-to-one relation.
In the example::
class Child(Model):
parent = ForeignKey(Parent, related_name='children')
Parent.children is a ReverseManyToOneDescriptor instance.
Most of the implementation is delegated to a dynamically defined manager
class built by create_forward_many_to_many_manager() defined below.
Accessor to the related objects manager on the reverse side of a many-to-one relation.
In the example::
class Child(Model):
parent = ForeignKey(Parent, related_name='children')
Parent.children is a ReverseManyToOneDescriptor instance.
Most of the implementation is delegated to a dynamically defined manager
class built by create_forward_many_to_many_manager() defined below.
Accessor to the related objects manager on the reverse side of a many-to-one relation.
In the example::
class Child(Model):
parent = ForeignKey(Parent, related_name='children')
Parent.children is a ReverseManyToOneDescriptor instance.
Most of the implementation is delegated to a dynamically defined manager
class built by create_forward_many_to_many_manager() defined below.
Accessor to the related objects manager on the reverse side of a many-to-one relation.
In the example::
class Child(Model):
parent = ForeignKey(Parent, related_name='children')
Parent.children is a ReverseManyToOneDescriptor instance.
Most of the implementation is delegated to a dynamically defined manager
class built by create_forward_many_to_many_manager() defined below.
Accessor to the related objects manager on the reverse side of a many-to-one relation.
In the example::
class Child(Model):
parent = ForeignKey(Parent, related_name='children')
Parent.children is a ReverseManyToOneDescriptor instance.
Most of the implementation is delegated to a dynamically defined manager
class built by create_forward_many_to_many_manager() defined below.
Accessor to the related objects manager on the reverse side of a many-to-one relation.
In the example::
class Child(Model):
parent = ForeignKey(Parent, related_name='children')
Parent.children is a ReverseManyToOneDescriptor instance.
Most of the implementation is delegated to a dynamically defined manager
class built by create_forward_many_to_many_manager() defined below.
Accessor to the related objects manager on the reverse side of a many-to-one relation.
In the example::
class Child(Model):
parent = ForeignKey(Parent, related_name='children')
Parent.children is a ReverseManyToOneDescriptor instance.
Most of the implementation is delegated to a dynamically defined manager
class built by create_forward_many_to_many_manager() defined below.
Accessor to the related objects manager on the reverse side of a many-to-one relation.
In the example::
class Child(Model):
parent = ForeignKey(Parent, related_name='children')
Parent.children is a ReverseManyToOneDescriptor instance.
Most of the implementation is delegated to a dynamically defined manager
class built by create_forward_many_to_many_manager() defined below.
Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.
In the example::
class Pizza(Model):
toppings = ManyToManyField(Topping, related_name='pizzas')
Pizza.toppings and Topping.pizzas are ManyToManyDescriptor
instances.
Most of the implementation is delegated to a dynamically defined manager
class built by create_forward_many_to_many_manager() defined below.
Accessor to the related objects manager on the reverse side of a many-to-one relation.
In the example::
class Child(Model):
parent = ForeignKey(Parent, related_name='children')
Parent.children is a ReverseManyToOneDescriptor instance.
Most of the implementation is delegated to a dynamically defined manager
class built by create_forward_many_to_many_manager() defined below.
Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.
In the example::
class Pizza(Model):
toppings = ManyToManyField(Topping, related_name='pizzas')
Pizza.toppings and Topping.pizzas are ManyToManyDescriptor
instances.
Most of the implementation is delegated to a dynamically defined manager
class built by create_forward_many_to_many_manager() defined below.
Inherited Members
The requested object does not exist
The query returned multiple objects when only one was expected.