authentik.sources.kerberos.models
authentik Kerberos Source Models
1"""authentik Kerberos Source Models""" 2 3import os 4from base64 import b64decode 5from pathlib import Path 6from tempfile import gettempdir 7from typing import TYPE_CHECKING, Any 8 9import pglock 10from django.db import connection, models 11from django.http import HttpRequest 12from django.shortcuts import reverse 13from django.templatetags.static import static 14from django.utils.timezone import now 15from django.utils.translation import gettext_lazy as _ 16from kadmin import KAdm5Variant, KAdmin, KAdminApiVersion 17from kadmin import exceptions as kadmin_exceptions 18from rest_framework.serializers import Serializer 19from structlog.stdlib import get_logger 20 21from authentik.core.models import ( 22 GroupSourceConnection, 23 PropertyMapping, 24 UserSourceConnection, 25 UserTypes, 26) 27from authentik.core.types import UILoginButton, UserSettingSerializer 28from authentik.flows.challenge import RedirectChallenge 29from authentik.lib.config import advisory_lock_db_alias 30from authentik.lib.sync.incoming.models import IncomingSyncSource 31from authentik.lib.utils.time import fqdn_rand 32from authentik.tasks.schedules.common import ScheduleSpec 33 34if TYPE_CHECKING: 35 import gssapi 36 37LOGGER = get_logger() 38 39 40# Creating kadmin connections is expensive. As such, this global is used to reuse 41# existing kadmin connections instead of creating new ones 42_kadmin_connections: dict[str, Any] = {} 43 44 45class KAdminType(models.TextChoices): 46 MIT = "MIT" 47 HEIMDAL = "Heimdal" 48 49 50class KerberosSource(IncomingSyncSource): 51 """Federate Kerberos realm with authentik""" 52 53 realm = models.TextField(help_text=_("Kerberos realm"), unique=True) 54 krb5_conf = models.TextField( 55 blank=True, 56 help_text=_("Custom krb5.conf to use. Uses the system one by default"), 57 ) 58 kadmin_type = models.TextField( 59 choices=KAdminType.choices, default=KAdminType.MIT, help_text=_("KAdmin server type") 60 ) 61 62 sync_users = models.BooleanField( 63 default=False, help_text=_("Sync users from Kerberos into authentik"), db_index=True 64 ) 65 sync_users_password = models.BooleanField( 66 default=True, 67 help_text=_("When a user changes their password, sync it back to Kerberos"), 68 db_index=True, 69 ) 70 sync_principal = models.TextField( 71 help_text=_("Principal to authenticate to kadmin for sync."), blank=True 72 ) 73 sync_password = models.TextField( 74 help_text=_("Password to authenticate to kadmin for sync"), blank=True 75 ) 76 sync_keytab = models.TextField( 77 help_text=_( 78 "Keytab to authenticate to kadmin for sync. " 79 "Must be base64-encoded or in the form TYPE:residual" 80 ), 81 blank=True, 82 ) 83 sync_ccache = models.TextField( 84 help_text=_( 85 "Credentials cache to authenticate to kadmin for sync. " 86 "Must be in the form TYPE:residual" 87 ), 88 blank=True, 89 ) 90 91 spnego_server_name = models.TextField( 92 help_text=_( 93 "Force the use of a specific server name for SPNEGO. Must be in the form HTTP@hostname" 94 ), 95 blank=True, 96 ) 97 spnego_keytab = models.TextField( 98 help_text=_("SPNEGO keytab base64-encoded or path to keytab in the form FILE:path"), 99 blank=True, 100 ) 101 spnego_ccache = models.TextField( 102 help_text=_("Credential cache to use for SPNEGO in form type:residual"), 103 blank=True, 104 ) 105 106 password_login_update_internal_password = models.BooleanField( 107 default=False, 108 help_text=_( 109 "If enabled, the authentik-stored password will be updated upon " 110 "login with the Kerberos password backend" 111 ), 112 ) 113 114 class Meta: 115 verbose_name = _("Kerberos Source") 116 verbose_name_plural = _("Kerberos Sources") 117 118 def __str__(self): 119 return f"Kerberos Source {self.name}" 120 121 @property 122 def component(self) -> str: 123 return "ak-source-kerberos-form" 124 125 @property 126 def serializer(self) -> type[Serializer]: 127 from authentik.sources.kerberos.api.source import KerberosSourceSerializer 128 129 return KerberosSourceSerializer 130 131 @property 132 def property_mapping_type(self) -> type[PropertyMapping]: 133 return KerberosSourcePropertyMapping 134 135 @property 136 def icon_url(self) -> str: 137 icon = super().icon_url 138 if not icon: 139 return static("authentik/sources/kerberos/light.png") 140 return icon 141 142 @property 143 def schedule_specs(self) -> list[ScheduleSpec]: 144 from authentik.sources.kerberos.tasks import kerberos_connectivity_check, kerberos_sync 145 146 return [ 147 ScheduleSpec( 148 actor=kerberos_sync, 149 uid=self.slug, 150 args=(self.pk,), 151 crontab=f"{fqdn_rand('kerberos_sync/' + str(self.pk))} */2 * * *", 152 send_on_save=True, 153 ), 154 ScheduleSpec( 155 actor=kerberos_connectivity_check, 156 uid=self.slug, 157 args=(self.pk,), 158 crontab=f"{fqdn_rand('kerberos_connectivity_check/' + str(self.pk))} * * * *", 159 send_on_save=True, 160 ), 161 ] 162 163 def ui_login_button(self, request: HttpRequest) -> UILoginButton: 164 return UILoginButton( 165 challenge=RedirectChallenge( 166 data={ 167 "to": reverse( 168 "authentik_sources_kerberos:spnego-login", 169 kwargs={"source_slug": self.slug}, 170 ), 171 } 172 ), 173 name=self.name, 174 icon_url=self.get_icon_url(request, use_cache=False) or self.icon_url, 175 icon_themed_urls=self.get_icon_themed_urls(request, use_cache=False), 176 promoted=self.promoted, 177 ) 178 179 def ui_user_settings(self) -> UserSettingSerializer | None: 180 return UserSettingSerializer( 181 data={ 182 "title": self.name, 183 "component": "ak-user-settings-source-kerberos", 184 "configure_url": reverse( 185 "authentik_sources_kerberos:spnego-login", 186 kwargs={"source_slug": self.slug}, 187 ), 188 "icon_url": self.icon_url, 189 "icon_themed_urls": self.icon_themed_urls, 190 } 191 ) 192 193 @property 194 def sync_lock(self) -> pglock.advisory: 195 """Lock for syncing Kerberos to prevent multiple parallel syncs happening""" 196 return pglock.advisory( 197 lock_id=f"goauthentik.io/{connection.schema_name}/sources/kerberos/sync/{self.slug}", 198 timeout=0, 199 side_effect=pglock.Return, 200 using=advisory_lock_db_alias(), 201 ) 202 203 def get_base_user_properties(self, principal: str, **kwargs): 204 localpart, _ = principal.rsplit("@", 1) 205 206 properties = { 207 "username": localpart, 208 "type": UserTypes.INTERNAL, 209 "path": self.get_user_path(), 210 } 211 212 if "principal_obj" in kwargs: 213 princ_expiry = kwargs["principal_obj"].expire_time 214 properties["is_active"] = princ_expiry is None or princ_expiry > now() 215 216 return properties 217 218 def get_base_group_properties(self, group_id: str, **kwargs): 219 return { 220 "name": group_id, 221 } 222 223 @property 224 def tempdir(self) -> Path: 225 """Get temporary storage for Kerberos files""" 226 path = Path(gettempdir()) / "authentik" / "sources" / "kerberos" / str(self.pk) 227 path.mkdir(mode=0o700, parents=True, exist_ok=True) 228 return path 229 230 @property 231 def krb5_conf_path(self) -> str | None: 232 """Get krb5.conf path""" 233 if not self.krb5_conf: 234 return None 235 conf_path = self.tempdir / "krb5.conf" 236 conf_path.write_text(self.krb5_conf) 237 return str(conf_path) 238 239 def _kadmin_init(self) -> KAdmin | None: 240 variant = KAdm5Variant.MitClient 241 api_version = KAdminApiVersion.Version2 242 match self.kadmin_type: 243 case KAdminType.MIT: 244 variant = KAdm5Variant.MitClient 245 api_version = KAdminApiVersion.Version4 246 case KAdminType.HEIMDAL: 247 variant = KAdm5Variant.HeimdalClient 248 api_version = KAdminApiVersion.Version2 249 # kadmin doesn't use a ccache for its connection 250 # as such, we don't need to create a separate ccache for each source 251 if not self.sync_principal: 252 return None 253 if self.sync_password: 254 return KAdmin.with_password( 255 variant, 256 self.sync_principal, 257 self.sync_password, 258 api_version=api_version, 259 ) 260 if self.sync_keytab: 261 keytab = self.sync_keytab 262 if ":" not in keytab: 263 keytab_path = self.tempdir / "kadmin_keytab" 264 keytab_path.touch(mode=0o600) 265 keytab_path.write_bytes(b64decode(self.sync_keytab)) 266 keytab = f"FILE:{keytab_path}" 267 return KAdmin.with_keytab( 268 variant, 269 self.sync_principal, 270 keytab, 271 api_version=api_version, 272 ) 273 if self.sync_ccache: 274 return KAdmin.with_ccache( 275 variant, 276 self.sync_principal, 277 self.sync_ccache, 278 api_version=api_version, 279 ) 280 return None 281 282 def connection(self) -> KAdmin | None: 283 """Get kadmin connection""" 284 if str(self.pk) not in _kadmin_connections: 285 kadm = self._kadmin_init() 286 if kadm is not None: 287 _kadmin_connections[str(self.pk)] = self._kadmin_init() 288 return _kadmin_connections.get(str(self.pk), None) 289 290 def check_connection(self) -> dict[str, str | bool]: 291 """Check Kerberos Connection""" 292 status: dict[str, str | bool] = {"status": "ok"} 293 if not self.sync_users: 294 return status 295 with Krb5ConfContext(self): 296 try: 297 kadm = self.connection() 298 if kadm is None: 299 status["status"] = "no connection" 300 return status 301 status["principal_exists"] = kadm.principal_exists(self.sync_principal) 302 except kadmin_exceptions.PyKAdminException as exc: 303 status["status"] = str(exc) 304 return status 305 306 def get_gssapi_store(self) -> dict[str, str]: 307 """Get GSSAPI credentials store for this source""" 308 ccache = self.spnego_ccache 309 keytab = None 310 311 if not ccache: 312 ccache_path = self.tempdir / "spnego_ccache" 313 ccache_path.touch(mode=0o600) 314 ccache = f"FILE:{ccache_path}" 315 316 if self.spnego_keytab: 317 # Keytab is of the form type:residual, use as-is 318 if ":" in self.spnego_keytab: 319 keytab = self.spnego_keytab 320 # Parse the keytab and write it in the file 321 else: 322 keytab_path = self.tempdir / "spnego_keytab" 323 keytab_path.touch(mode=0o600) 324 keytab_path.write_bytes(b64decode(self.spnego_keytab)) 325 keytab = f"FILE:{keytab_path}" 326 327 store = {"ccache": ccache} 328 if keytab is not None: 329 store["keytab"] = keytab 330 return store 331 332 def get_gssapi_creds(self) -> gssapi.creds.Credentials | None: 333 """Get GSSAPI credentials for this source""" 334 import gssapi 335 336 try: 337 name = None 338 if self.spnego_server_name: 339 # pylint: disable=c-extension-no-member 340 name = gssapi.names.Name( 341 base=self.spnego_server_name, 342 name_type=gssapi.raw.types.NameType.hostbased_service, 343 ) 344 return gssapi.creds.Credentials( 345 usage="accept", name=name, store=self.get_gssapi_store() 346 ) 347 except gssapi.exceptions.GSSError as exc: 348 LOGGER.warning("GSSAPI credentials failure", exc=exc) 349 return None 350 351 352class Krb5ConfContext: 353 """ 354 Context manager to set the path to the krb5.conf config file. 355 """ 356 357 def __init__(self, source: KerberosSource): 358 self._source = source 359 self._path = self._source.krb5_conf_path 360 self._previous = None 361 362 def __enter__(self): 363 if not self._path: 364 return 365 self._previous = os.environ.get("KRB5_CONFIG", None) 366 os.environ["KRB5_CONFIG"] = self._path 367 368 def __exit__(self, *args, **kwargs): 369 if not self._path: 370 return 371 if self._previous: 372 os.environ["KRB5_CONFIG"] = self._previous 373 else: 374 del os.environ["KRB5_CONFIG"] 375 376 377class KerberosSourcePropertyMapping(PropertyMapping): 378 """Map Kerberos Property to User object attribute""" 379 380 expression_allowed_types = [dict] 381 382 @property 383 def component(self) -> str: 384 return "ak-property-mapping-source-kerberos-form" 385 386 @property 387 def serializer(self) -> type[Serializer]: 388 from authentik.sources.kerberos.api.property_mappings import ( 389 KerberosSourcePropertyMappingSerializer, 390 ) 391 392 return KerberosSourcePropertyMappingSerializer 393 394 def __str__(self): 395 return str(self.name) 396 397 class Meta: 398 verbose_name = _("Kerberos Source Property Mapping") 399 verbose_name_plural = _("Kerberos Source Property Mappings") 400 401 402class UserKerberosSourceConnection(UserSourceConnection): 403 """Connection to configured Kerberos Sources.""" 404 405 @property 406 def serializer(self) -> type[Serializer]: 407 from authentik.sources.kerberos.api.source_connection import ( 408 UserKerberosSourceConnectionSerializer, 409 ) 410 411 return UserKerberosSourceConnectionSerializer 412 413 class Meta: 414 verbose_name = _("User Kerberos Source Connection") 415 verbose_name_plural = _("User Kerberos Source Connections") 416 417 418class GroupKerberosSourceConnection(GroupSourceConnection): 419 """Connection to configured Kerberos Sources.""" 420 421 @property 422 def serializer(self) -> type[Serializer]: 423 from authentik.sources.kerberos.api.source_connection import ( 424 GroupKerberosSourceConnectionSerializer, 425 ) 426 427 return GroupKerberosSourceConnectionSerializer 428 429 class Meta: 430 verbose_name = _("Group Kerberos Source Connection") 431 verbose_name_plural = _("Group Kerberos Source Connections")
Class for creating enumerated string choices.
51class KerberosSource(IncomingSyncSource): 52 """Federate Kerberos realm with authentik""" 53 54 realm = models.TextField(help_text=_("Kerberos realm"), unique=True) 55 krb5_conf = models.TextField( 56 blank=True, 57 help_text=_("Custom krb5.conf to use. Uses the system one by default"), 58 ) 59 kadmin_type = models.TextField( 60 choices=KAdminType.choices, default=KAdminType.MIT, help_text=_("KAdmin server type") 61 ) 62 63 sync_users = models.BooleanField( 64 default=False, help_text=_("Sync users from Kerberos into authentik"), db_index=True 65 ) 66 sync_users_password = models.BooleanField( 67 default=True, 68 help_text=_("When a user changes their password, sync it back to Kerberos"), 69 db_index=True, 70 ) 71 sync_principal = models.TextField( 72 help_text=_("Principal to authenticate to kadmin for sync."), blank=True 73 ) 74 sync_password = models.TextField( 75 help_text=_("Password to authenticate to kadmin for sync"), blank=True 76 ) 77 sync_keytab = models.TextField( 78 help_text=_( 79 "Keytab to authenticate to kadmin for sync. " 80 "Must be base64-encoded or in the form TYPE:residual" 81 ), 82 blank=True, 83 ) 84 sync_ccache = models.TextField( 85 help_text=_( 86 "Credentials cache to authenticate to kadmin for sync. " 87 "Must be in the form TYPE:residual" 88 ), 89 blank=True, 90 ) 91 92 spnego_server_name = models.TextField( 93 help_text=_( 94 "Force the use of a specific server name for SPNEGO. Must be in the form HTTP@hostname" 95 ), 96 blank=True, 97 ) 98 spnego_keytab = models.TextField( 99 help_text=_("SPNEGO keytab base64-encoded or path to keytab in the form FILE:path"), 100 blank=True, 101 ) 102 spnego_ccache = models.TextField( 103 help_text=_("Credential cache to use for SPNEGO in form type:residual"), 104 blank=True, 105 ) 106 107 password_login_update_internal_password = models.BooleanField( 108 default=False, 109 help_text=_( 110 "If enabled, the authentik-stored password will be updated upon " 111 "login with the Kerberos password backend" 112 ), 113 ) 114 115 class Meta: 116 verbose_name = _("Kerberos Source") 117 verbose_name_plural = _("Kerberos Sources") 118 119 def __str__(self): 120 return f"Kerberos Source {self.name}" 121 122 @property 123 def component(self) -> str: 124 return "ak-source-kerberos-form" 125 126 @property 127 def serializer(self) -> type[Serializer]: 128 from authentik.sources.kerberos.api.source import KerberosSourceSerializer 129 130 return KerberosSourceSerializer 131 132 @property 133 def property_mapping_type(self) -> type[PropertyMapping]: 134 return KerberosSourcePropertyMapping 135 136 @property 137 def icon_url(self) -> str: 138 icon = super().icon_url 139 if not icon: 140 return static("authentik/sources/kerberos/light.png") 141 return icon 142 143 @property 144 def schedule_specs(self) -> list[ScheduleSpec]: 145 from authentik.sources.kerberos.tasks import kerberos_connectivity_check, kerberos_sync 146 147 return [ 148 ScheduleSpec( 149 actor=kerberos_sync, 150 uid=self.slug, 151 args=(self.pk,), 152 crontab=f"{fqdn_rand('kerberos_sync/' + str(self.pk))} */2 * * *", 153 send_on_save=True, 154 ), 155 ScheduleSpec( 156 actor=kerberos_connectivity_check, 157 uid=self.slug, 158 args=(self.pk,), 159 crontab=f"{fqdn_rand('kerberos_connectivity_check/' + str(self.pk))} * * * *", 160 send_on_save=True, 161 ), 162 ] 163 164 def ui_login_button(self, request: HttpRequest) -> UILoginButton: 165 return UILoginButton( 166 challenge=RedirectChallenge( 167 data={ 168 "to": reverse( 169 "authentik_sources_kerberos:spnego-login", 170 kwargs={"source_slug": self.slug}, 171 ), 172 } 173 ), 174 name=self.name, 175 icon_url=self.get_icon_url(request, use_cache=False) or self.icon_url, 176 icon_themed_urls=self.get_icon_themed_urls(request, use_cache=False), 177 promoted=self.promoted, 178 ) 179 180 def ui_user_settings(self) -> UserSettingSerializer | None: 181 return UserSettingSerializer( 182 data={ 183 "title": self.name, 184 "component": "ak-user-settings-source-kerberos", 185 "configure_url": reverse( 186 "authentik_sources_kerberos:spnego-login", 187 kwargs={"source_slug": self.slug}, 188 ), 189 "icon_url": self.icon_url, 190 "icon_themed_urls": self.icon_themed_urls, 191 } 192 ) 193 194 @property 195 def sync_lock(self) -> pglock.advisory: 196 """Lock for syncing Kerberos to prevent multiple parallel syncs happening""" 197 return pglock.advisory( 198 lock_id=f"goauthentik.io/{connection.schema_name}/sources/kerberos/sync/{self.slug}", 199 timeout=0, 200 side_effect=pglock.Return, 201 using=advisory_lock_db_alias(), 202 ) 203 204 def get_base_user_properties(self, principal: str, **kwargs): 205 localpart, _ = principal.rsplit("@", 1) 206 207 properties = { 208 "username": localpart, 209 "type": UserTypes.INTERNAL, 210 "path": self.get_user_path(), 211 } 212 213 if "principal_obj" in kwargs: 214 princ_expiry = kwargs["principal_obj"].expire_time 215 properties["is_active"] = princ_expiry is None or princ_expiry > now() 216 217 return properties 218 219 def get_base_group_properties(self, group_id: str, **kwargs): 220 return { 221 "name": group_id, 222 } 223 224 @property 225 def tempdir(self) -> Path: 226 """Get temporary storage for Kerberos files""" 227 path = Path(gettempdir()) / "authentik" / "sources" / "kerberos" / str(self.pk) 228 path.mkdir(mode=0o700, parents=True, exist_ok=True) 229 return path 230 231 @property 232 def krb5_conf_path(self) -> str | None: 233 """Get krb5.conf path""" 234 if not self.krb5_conf: 235 return None 236 conf_path = self.tempdir / "krb5.conf" 237 conf_path.write_text(self.krb5_conf) 238 return str(conf_path) 239 240 def _kadmin_init(self) -> KAdmin | None: 241 variant = KAdm5Variant.MitClient 242 api_version = KAdminApiVersion.Version2 243 match self.kadmin_type: 244 case KAdminType.MIT: 245 variant = KAdm5Variant.MitClient 246 api_version = KAdminApiVersion.Version4 247 case KAdminType.HEIMDAL: 248 variant = KAdm5Variant.HeimdalClient 249 api_version = KAdminApiVersion.Version2 250 # kadmin doesn't use a ccache for its connection 251 # as such, we don't need to create a separate ccache for each source 252 if not self.sync_principal: 253 return None 254 if self.sync_password: 255 return KAdmin.with_password( 256 variant, 257 self.sync_principal, 258 self.sync_password, 259 api_version=api_version, 260 ) 261 if self.sync_keytab: 262 keytab = self.sync_keytab 263 if ":" not in keytab: 264 keytab_path = self.tempdir / "kadmin_keytab" 265 keytab_path.touch(mode=0o600) 266 keytab_path.write_bytes(b64decode(self.sync_keytab)) 267 keytab = f"FILE:{keytab_path}" 268 return KAdmin.with_keytab( 269 variant, 270 self.sync_principal, 271 keytab, 272 api_version=api_version, 273 ) 274 if self.sync_ccache: 275 return KAdmin.with_ccache( 276 variant, 277 self.sync_principal, 278 self.sync_ccache, 279 api_version=api_version, 280 ) 281 return None 282 283 def connection(self) -> KAdmin | None: 284 """Get kadmin connection""" 285 if str(self.pk) not in _kadmin_connections: 286 kadm = self._kadmin_init() 287 if kadm is not None: 288 _kadmin_connections[str(self.pk)] = self._kadmin_init() 289 return _kadmin_connections.get(str(self.pk), None) 290 291 def check_connection(self) -> dict[str, str | bool]: 292 """Check Kerberos Connection""" 293 status: dict[str, str | bool] = {"status": "ok"} 294 if not self.sync_users: 295 return status 296 with Krb5ConfContext(self): 297 try: 298 kadm = self.connection() 299 if kadm is None: 300 status["status"] = "no connection" 301 return status 302 status["principal_exists"] = kadm.principal_exists(self.sync_principal) 303 except kadmin_exceptions.PyKAdminException as exc: 304 status["status"] = str(exc) 305 return status 306 307 def get_gssapi_store(self) -> dict[str, str]: 308 """Get GSSAPI credentials store for this source""" 309 ccache = self.spnego_ccache 310 keytab = None 311 312 if not ccache: 313 ccache_path = self.tempdir / "spnego_ccache" 314 ccache_path.touch(mode=0o600) 315 ccache = f"FILE:{ccache_path}" 316 317 if self.spnego_keytab: 318 # Keytab is of the form type:residual, use as-is 319 if ":" in self.spnego_keytab: 320 keytab = self.spnego_keytab 321 # Parse the keytab and write it in the file 322 else: 323 keytab_path = self.tempdir / "spnego_keytab" 324 keytab_path.touch(mode=0o600) 325 keytab_path.write_bytes(b64decode(self.spnego_keytab)) 326 keytab = f"FILE:{keytab_path}" 327 328 store = {"ccache": ccache} 329 if keytab is not None: 330 store["keytab"] = keytab 331 return store 332 333 def get_gssapi_creds(self) -> gssapi.creds.Credentials | None: 334 """Get GSSAPI credentials for this source""" 335 import gssapi 336 337 try: 338 name = None 339 if self.spnego_server_name: 340 # pylint: disable=c-extension-no-member 341 name = gssapi.names.Name( 342 base=self.spnego_server_name, 343 name_type=gssapi.raw.types.NameType.hostbased_service, 344 ) 345 return gssapi.creds.Credentials( 346 usage="accept", name=name, store=self.get_gssapi_store() 347 ) 348 except gssapi.exceptions.GSSError as exc: 349 LOGGER.warning("GSSAPI credentials failure", exc=exc) 350 return None
Federate Kerberos realm with authentik
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.
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.
126 @property 127 def serializer(self) -> type[Serializer]: 128 from authentik.sources.kerberos.api.source import KerberosSourceSerializer 129 130 return KerberosSourceSerializer
Get serializer for this model
132 @property 133 def property_mapping_type(self) -> type[PropertyMapping]: 134 return KerberosSourcePropertyMapping
Return property mapping type used by this object
136 @property 137 def icon_url(self) -> str: 138 icon = super().icon_url 139 if not icon: 140 return static("authentik/sources/kerberos/light.png") 141 return icon
Get the URL to the source icon
143 @property 144 def schedule_specs(self) -> list[ScheduleSpec]: 145 from authentik.sources.kerberos.tasks import kerberos_connectivity_check, kerberos_sync 146 147 return [ 148 ScheduleSpec( 149 actor=kerberos_sync, 150 uid=self.slug, 151 args=(self.pk,), 152 crontab=f"{fqdn_rand('kerberos_sync/' + str(self.pk))} */2 * * *", 153 send_on_save=True, 154 ), 155 ScheduleSpec( 156 actor=kerberos_connectivity_check, 157 uid=self.slug, 158 args=(self.pk,), 159 crontab=f"{fqdn_rand('kerberos_connectivity_check/' + str(self.pk))} * * * *", 160 send_on_save=True, 161 ), 162 ]
180 def ui_user_settings(self) -> UserSettingSerializer | None: 181 return UserSettingSerializer( 182 data={ 183 "title": self.name, 184 "component": "ak-user-settings-source-kerberos", 185 "configure_url": reverse( 186 "authentik_sources_kerberos:spnego-login", 187 kwargs={"source_slug": self.slug}, 188 ), 189 "icon_url": self.icon_url, 190 "icon_themed_urls": self.icon_themed_urls, 191 } 192 )
Entrypoint to integrate with User settings. Can either return None if no user settings are available, or UserSettingSerializer.
194 @property 195 def sync_lock(self) -> pglock.advisory: 196 """Lock for syncing Kerberos to prevent multiple parallel syncs happening""" 197 return pglock.advisory( 198 lock_id=f"goauthentik.io/{connection.schema_name}/sources/kerberos/sync/{self.slug}", 199 timeout=0, 200 side_effect=pglock.Return, 201 using=advisory_lock_db_alias(), 202 )
Lock for syncing Kerberos to prevent multiple parallel syncs happening
204 def get_base_user_properties(self, principal: str, **kwargs): 205 localpart, _ = principal.rsplit("@", 1) 206 207 properties = { 208 "username": localpart, 209 "type": UserTypes.INTERNAL, 210 "path": self.get_user_path(), 211 } 212 213 if "principal_obj" in kwargs: 214 princ_expiry = kwargs["principal_obj"].expire_time 215 properties["is_active"] = princ_expiry is None or princ_expiry > now() 216 217 return properties
Get base properties for a user to build final properties upon.
219 def get_base_group_properties(self, group_id: str, **kwargs): 220 return { 221 "name": group_id, 222 }
Get base properties for a group to build final properties upon.
224 @property 225 def tempdir(self) -> Path: 226 """Get temporary storage for Kerberos files""" 227 path = Path(gettempdir()) / "authentik" / "sources" / "kerberos" / str(self.pk) 228 path.mkdir(mode=0o700, parents=True, exist_ok=True) 229 return path
Get temporary storage for Kerberos files
231 @property 232 def krb5_conf_path(self) -> str | None: 233 """Get krb5.conf path""" 234 if not self.krb5_conf: 235 return None 236 conf_path = self.tempdir / "krb5.conf" 237 conf_path.write_text(self.krb5_conf) 238 return str(conf_path)
Get krb5.conf path
283 def connection(self) -> KAdmin | None: 284 """Get kadmin connection""" 285 if str(self.pk) not in _kadmin_connections: 286 kadm = self._kadmin_init() 287 if kadm is not None: 288 _kadmin_connections[str(self.pk)] = self._kadmin_init() 289 return _kadmin_connections.get(str(self.pk), None)
Get kadmin connection
291 def check_connection(self) -> dict[str, str | bool]: 292 """Check Kerberos Connection""" 293 status: dict[str, str | bool] = {"status": "ok"} 294 if not self.sync_users: 295 return status 296 with Krb5ConfContext(self): 297 try: 298 kadm = self.connection() 299 if kadm is None: 300 status["status"] = "no connection" 301 return status 302 status["principal_exists"] = kadm.principal_exists(self.sync_principal) 303 except kadmin_exceptions.PyKAdminException as exc: 304 status["status"] = str(exc) 305 return status
Check Kerberos Connection
307 def get_gssapi_store(self) -> dict[str, str]: 308 """Get GSSAPI credentials store for this source""" 309 ccache = self.spnego_ccache 310 keytab = None 311 312 if not ccache: 313 ccache_path = self.tempdir / "spnego_ccache" 314 ccache_path.touch(mode=0o600) 315 ccache = f"FILE:{ccache_path}" 316 317 if self.spnego_keytab: 318 # Keytab is of the form type:residual, use as-is 319 if ":" in self.spnego_keytab: 320 keytab = self.spnego_keytab 321 # Parse the keytab and write it in the file 322 else: 323 keytab_path = self.tempdir / "spnego_keytab" 324 keytab_path.touch(mode=0o600) 325 keytab_path.write_bytes(b64decode(self.spnego_keytab)) 326 keytab = f"FILE:{keytab_path}" 327 328 store = {"ccache": ccache} 329 if keytab is not None: 330 store["keytab"] = keytab 331 return store
Get GSSAPI credentials store for this source
333 def get_gssapi_creds(self) -> gssapi.creds.Credentials | None: 334 """Get GSSAPI credentials for this source""" 335 import gssapi 336 337 try: 338 name = None 339 if self.spnego_server_name: 340 # pylint: disable=c-extension-no-member 341 name = gssapi.names.Name( 342 base=self.spnego_server_name, 343 name_type=gssapi.raw.types.NameType.hostbased_service, 344 ) 345 return gssapi.creds.Credentials( 346 usage="accept", name=name, store=self.get_gssapi_store() 347 ) 348 except gssapi.exceptions.GSSError as exc: 349 LOGGER.warning("GSSAPI credentials failure", exc=exc) 350 return None
Get GSSAPI credentials for this source
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Accessor to the related objects manager on the one-to-many relation created by GenericRelation.
In the example::
class Post(Model):
comments = GenericRelation(Comment)
post.comments is a ReverseGenericManyToOneDescriptor instance.
Accessor to the related objects manager on the one-to-many relation created by GenericRelation.
In the example::
class Post(Model):
comments = GenericRelation(Comment)
post.comments is a ReverseGenericManyToOneDescriptor instance.
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 object on the forward side of a one-to-one relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
Restaurant.place is a ForwardOneToOneDescriptor instance.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Inherited Members
- authentik.core.models.Source
- MANAGED_INBUILT
- name
- slug
- user_path_template
- enabled
- promoted
- user_property_mappings
- group_property_mappings
- icon
- authentication_flow
- enrollment_flow
- user_matching_mode
- group_matching_mode
- objects
- get_icon_url
- get_icon_themed_urls
- icon_themed_urls
- get_user_path
- managed
- authentication_flow_id
- enrollment_flow_id
- get_user_matching_mode_display
- get_group_matching_mode_display
- policybindingmodel_ptr_id
- policybindingmodel_ptr
- user_set
- usersourceconnection_set
- groupsourceconnection_set
- sourceuserpropertymapping_set
- sourcegrouppropertymapping_set
- kerberossource
- ldapsource
- oauthsource
- samlsource
- identificationstage_set
- identificationstagesource_set
- plexsource
- scimsource
- telegramsource
- sourcestage_set
- authentik.policies.models.PolicyBindingModel
- pbm_uuid
- policies
- policy_engine_mode
- supported_policy_binding_targets
- get_policy_engine_mode_display
- bindings
- application
- applicationentitlement
- source
- flow
- flowstagebinding
- notificationrule
- device
- deviceaccessgroup
- oauth2dynamicclientregistration
- userexpirationrule
- request_rule_bindings
- request_rule_child_bindings
- requestrulebinding
- request_rules
- requestrule
- grantrequest_set
- grantrequesttarget_set
The requested object does not exist
The query returned multiple objects when only one was expected.
353class Krb5ConfContext: 354 """ 355 Context manager to set the path to the krb5.conf config file. 356 """ 357 358 def __init__(self, source: KerberosSource): 359 self._source = source 360 self._path = self._source.krb5_conf_path 361 self._previous = None 362 363 def __enter__(self): 364 if not self._path: 365 return 366 self._previous = os.environ.get("KRB5_CONFIG", None) 367 os.environ["KRB5_CONFIG"] = self._path 368 369 def __exit__(self, *args, **kwargs): 370 if not self._path: 371 return 372 if self._previous: 373 os.environ["KRB5_CONFIG"] = self._previous 374 else: 375 del os.environ["KRB5_CONFIG"]
Context manager to set the path to the krb5.conf config file.
378class KerberosSourcePropertyMapping(PropertyMapping): 379 """Map Kerberos Property to User object attribute""" 380 381 expression_allowed_types = [dict] 382 383 @property 384 def component(self) -> str: 385 return "ak-property-mapping-source-kerberos-form" 386 387 @property 388 def serializer(self) -> type[Serializer]: 389 from authentik.sources.kerberos.api.property_mappings import ( 390 KerberosSourcePropertyMappingSerializer, 391 ) 392 393 return KerberosSourcePropertyMappingSerializer 394 395 def __str__(self): 396 return str(self.name) 397 398 class Meta: 399 verbose_name = _("Kerberos Source Property Mapping") 400 verbose_name_plural = _("Kerberos Source Property Mappings")
Map Kerberos Property to User object attribute
387 @property 388 def serializer(self) -> type[Serializer]: 389 from authentik.sources.kerberos.api.property_mappings import ( 390 KerberosSourcePropertyMappingSerializer, 391 ) 392 393 return KerberosSourcePropertyMappingSerializer
Get serializer for this model
Accessor to the related object on the forward side of a one-to-one relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
Restaurant.place is a ForwardOneToOneDescriptor instance.
Inherited Members
- authentik.core.models.PropertyMapping
- pm_uuid
- name
- expression
- objects
- evaluate
- managed
- provider_set
- source_userpropertymappings_set
- source_grouppropertymappings_set
- sourceuserpropertymapping_set
- sourcegrouppropertymapping_set
- providerpropertymapping_set
- notificationwebhookmapping
- kerberossourcepropertymapping
- ldapsourcepropertymapping
- oauthsourcepropertymapping
- scopemapping
- racpropertymapping
- radiusproviderpropertymapping
- samlsourcepropertymapping
- samlpropertymapping
- scimprovider_set
- scimprovidergrouppropertymapping_set
- scimmapping
- plexsourcepropertymapping
- scimsourcepropertymapping
- telegramsourcepropertymapping
- googleworkspaceprovider_set
- googleworkspaceproviderpropertymappingsgroup_set
- googleworkspaceprovidermapping
- microsoftentraprovider_set
- microsoftentraproviderpropertymappingsgroup_set
- microsoftentraprovidermapping
The requested object does not exist
The query returned multiple objects when only one was expected.
403class UserKerberosSourceConnection(UserSourceConnection): 404 """Connection to configured Kerberos Sources.""" 405 406 @property 407 def serializer(self) -> type[Serializer]: 408 from authentik.sources.kerberos.api.source_connection import ( 409 UserKerberosSourceConnectionSerializer, 410 ) 411 412 return UserKerberosSourceConnectionSerializer 413 414 class Meta: 415 verbose_name = _("User Kerberos Source Connection") 416 verbose_name_plural = _("User Kerberos Source Connections")
Connection to configured Kerberos Sources.
406 @property 407 def serializer(self) -> type[Serializer]: 408 from authentik.sources.kerberos.api.source_connection import ( 409 UserKerberosSourceConnectionSerializer, 410 ) 411 412 return UserKerberosSourceConnectionSerializer
Get serializer for this model
Accessor to the related object on the forward side of a one-to-one relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
Restaurant.place is a ForwardOneToOneDescriptor instance.
Inherited Members
- authentik.core.models.UserSourceConnection
- user
- source
- identifier
- objects
- created
- last_updated
- user_id
- source_id
- get_next_by_created
- get_previous_by_created
- get_next_by_last_updated
- get_previous_by_last_updated
- id
- userkerberossourceconnection
- userldapsourceconnection
- useroauthsourceconnection
- usersamlsourceconnection
- userplexsourceconnection
- usertelegramsourceconnection
The requested object does not exist
The query returned multiple objects when only one was expected.
419class GroupKerberosSourceConnection(GroupSourceConnection): 420 """Connection to configured Kerberos Sources.""" 421 422 @property 423 def serializer(self) -> type[Serializer]: 424 from authentik.sources.kerberos.api.source_connection import ( 425 GroupKerberosSourceConnectionSerializer, 426 ) 427 428 return GroupKerberosSourceConnectionSerializer 429 430 class Meta: 431 verbose_name = _("Group Kerberos Source Connection") 432 verbose_name_plural = _("Group Kerberos Source Connections")
Connection to configured Kerberos Sources.
422 @property 423 def serializer(self) -> type[Serializer]: 424 from authentik.sources.kerberos.api.source_connection import ( 425 GroupKerberosSourceConnectionSerializer, 426 ) 427 428 return GroupKerberosSourceConnectionSerializer
Get serializer for this model
Accessor to the related object on the forward side of a one-to-one relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
Restaurant.place is a ForwardOneToOneDescriptor instance.
Inherited Members
- authentik.core.models.GroupSourceConnection
- group
- source
- identifier
- objects
- created
- last_updated
- group_id
- source_id
- get_next_by_created
- get_previous_by_created
- get_next_by_last_updated
- get_previous_by_last_updated
- id
- groupkerberossourceconnection
- groupldapsourceconnection
- groupoauthsourceconnection
- groupsamlsourceconnection
- groupplexsourceconnection
- grouptelegramsourceconnection
The requested object does not exist
The query returned multiple objects when only one was expected.