authentik.sources.kerberos.views
Kerberos source SPNEGO views
1"""Kerberos source SPNEGO views""" 2 3from base64 import b64decode, b64encode 4from typing import TYPE_CHECKING 5 6from django.core.cache import cache 7from django.core.exceptions import SuspiciousOperation 8from django.http import HttpResponse 9from django.shortcuts import get_object_or_404, redirect, render, reverse 10from django.utils.crypto import get_random_string 11from django.utils.translation import gettext_lazy as _ 12from django.views import View 13from structlog.stdlib import get_logger 14 15from authentik.core.sources.flow_manager import SourceFlowManager 16from authentik.sources.kerberos.models import ( 17 GroupKerberosSourceConnection, 18 KerberosSource, 19 Krb5ConfContext, 20 UserKerberosSourceConnection, 21) 22 23if TYPE_CHECKING: 24 import gssapi 25 26LOGGER = get_logger() 27 28SPNEGO_REQUEST_STATUS = 401 29WWW_AUTHENTICATE = "WWW-Authenticate" 30HTTP_AUTHORIZATION = "Authorization" 31NEGOTIATE = "Negotiate" 32 33SPNEGO_STATE_CACHE_PREFIX = "goauthentik.io/sources/spnego" 34SPNEGO_STATE_CACHE_TIMEOUT = 60 * 5 # 5 minutes 35 36 37def add_negotiate_to_response( 38 response: HttpResponse, token: str | bytes | None = None 39) -> HttpResponse: 40 if isinstance(token, str): 41 token = token.encode() 42 response[WWW_AUTHENTICATE] = ( 43 NEGOTIATE if token is None else f"{NEGOTIATE} {b64encode(token).decode('ascii')}" 44 ) 45 return response 46 47 48class SPNEGOView(View): 49 """SPNEGO login""" 50 51 source: KerberosSource 52 53 def challenge(self, request, token: str | bytes | None = None) -> HttpResponse: 54 """Get SNPEGO challenge response""" 55 response = render( 56 request, 57 "if/error.html", 58 context={ 59 "title": _("SPNEGO authentication required"), 60 "message": _(""" 61 Make sure you have valid tickets (obtainable via kinit) 62 and configured the browser correctly. 63 Please contact your administrator. 64 """), 65 }, 66 status=401, 67 ) 68 return add_negotiate_to_response(response, token) 69 70 def get_authstr(self, request) -> str | None: 71 """Get SPNEGO authentication string from headers""" 72 authorization_header = request.headers.get(HTTP_AUTHORIZATION, "") 73 if NEGOTIATE.lower() not in authorization_header.lower(): 74 return None 75 76 auth_tuple = authorization_header.split(" ", 1) 77 if not auth_tuple or auth_tuple[0].lower() != NEGOTIATE.lower(): 78 return None 79 if len(auth_tuple) != 2: # noqa: PLR2004 80 raise SuspiciousOperation("Malformed authorization header") 81 return auth_tuple[1] 82 83 def new_state(self) -> str: 84 """Generate request state""" 85 return get_random_string(32) 86 87 def get_server_ctx(self, key: str) -> gssapi.sec_contexts.SecurityContext | None: 88 """Get GSSAPI server context from cache or create it""" 89 import gssapi 90 91 server_creds = self.source.get_gssapi_creds() 92 if server_creds is None: 93 return None 94 95 state = cache.get(f"{SPNEGO_STATE_CACHE_PREFIX}/{key}", None) 96 97 if state: 98 # pylint: disable=c-extension-no-member 99 return gssapi.sec_contexts.SecurityContext( 100 base=gssapi.raw.sec_contexts.import_sec_context(state), 101 ) 102 103 return gssapi.sec_contexts.SecurityContext(creds=server_creds, usage="accept") 104 105 def set_server_ctx(self, key: str, ctx: gssapi.sec_contexts.SecurityContext): 106 """Store the GSSAPI server context in cache""" 107 cache.set(f"{SPNEGO_STATE_CACHE_PREFIX}/{key}", ctx.export(), SPNEGO_STATE_CACHE_TIMEOUT) 108 109 # pylint: disable=too-many-return-statements 110 def dispatch(self, request, *args, **kwargs) -> HttpResponse: 111 """Process SPNEGO request""" 112 import gssapi 113 114 self.source: KerberosSource = get_object_or_404( 115 KerberosSource, 116 slug=kwargs.get("source_slug", ""), 117 enabled=True, 118 ) 119 120 qstring = request.GET if request.method == "GET" else request.POST 121 state = qstring.get("state", None) 122 if not state: 123 return redirect( 124 reverse( 125 "authentik_sources_kerberos:spnego-login", 126 kwargs={"source_slug": self.source.slug}, 127 ) 128 + f"?state={self.new_state()}" 129 ) 130 131 authstr = self.get_authstr(request) 132 if not authstr: 133 LOGGER.debug("authstr not present, sending challenge") 134 return self.challenge(request) 135 136 try: 137 in_token = b64decode(authstr) 138 except TypeError, ValueError: 139 return self.challenge(request) 140 141 with Krb5ConfContext(self.source): 142 server_ctx = self.get_server_ctx(state) 143 if not server_ctx: 144 return self.challenge(request) 145 146 try: 147 out_token = server_ctx.step(in_token) 148 except gssapi.exceptions.GSSError as exc: 149 LOGGER.debug("GSSAPI security context failure", exc=exc) 150 return self.challenge(request) 151 152 if not server_ctx.complete or server_ctx.initiator_name is None: 153 self.set_server_ctx(state, server_ctx) 154 return self.challenge(request, out_token) 155 156 def name_to_str(n: gssapi.names.Name) -> str: 157 return n.display_as(n.name_type) 158 159 identifier = name_to_str(server_ctx.initiator_name) 160 context = { 161 "spnego_info": { 162 "initiator_name": name_to_str(server_ctx.initiator_name), 163 "target_name": name_to_str(server_ctx.target_name), 164 "mech": str(server_ctx.mech), 165 "actual_flags": server_ctx.actual_flags, 166 }, 167 } 168 169 response = SPNEGOSourceFlowManager( 170 source=self.source, 171 request=request, 172 identifier=identifier, 173 user_info={ 174 "principal": identifier, 175 **context, 176 }, 177 policy_context=context, 178 ).get_flow() 179 return add_negotiate_to_response(response, out_token) 180 181 182class SPNEGOSourceFlowManager(SourceFlowManager): 183 """Flow manager for Kerberos SPNEGO sources""" 184 185 user_connection_type = UserKerberosSourceConnection 186 group_connection_type = GroupKerberosSourceConnection
LOGGER =
<BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
SPNEGO_REQUEST_STATUS =
401
WWW_AUTHENTICATE =
'WWW-Authenticate'
HTTP_AUTHORIZATION =
'Authorization'
NEGOTIATE =
'Negotiate'
SPNEGO_STATE_CACHE_PREFIX =
'goauthentik.io/sources/spnego'
SPNEGO_STATE_CACHE_TIMEOUT =
300
def
add_negotiate_to_response( response: django.http.response.HttpResponse, token: str | bytes | None = None) -> django.http.response.HttpResponse:
38def add_negotiate_to_response( 39 response: HttpResponse, token: str | bytes | None = None 40) -> HttpResponse: 41 if isinstance(token, str): 42 token = token.encode() 43 response[WWW_AUTHENTICATE] = ( 44 NEGOTIATE if token is None else f"{NEGOTIATE} {b64encode(token).decode('ascii')}" 45 ) 46 return response
class
SPNEGOView(django.views.generic.base.View):
49class SPNEGOView(View): 50 """SPNEGO login""" 51 52 source: KerberosSource 53 54 def challenge(self, request, token: str | bytes | None = None) -> HttpResponse: 55 """Get SNPEGO challenge response""" 56 response = render( 57 request, 58 "if/error.html", 59 context={ 60 "title": _("SPNEGO authentication required"), 61 "message": _(""" 62 Make sure you have valid tickets (obtainable via kinit) 63 and configured the browser correctly. 64 Please contact your administrator. 65 """), 66 }, 67 status=401, 68 ) 69 return add_negotiate_to_response(response, token) 70 71 def get_authstr(self, request) -> str | None: 72 """Get SPNEGO authentication string from headers""" 73 authorization_header = request.headers.get(HTTP_AUTHORIZATION, "") 74 if NEGOTIATE.lower() not in authorization_header.lower(): 75 return None 76 77 auth_tuple = authorization_header.split(" ", 1) 78 if not auth_tuple or auth_tuple[0].lower() != NEGOTIATE.lower(): 79 return None 80 if len(auth_tuple) != 2: # noqa: PLR2004 81 raise SuspiciousOperation("Malformed authorization header") 82 return auth_tuple[1] 83 84 def new_state(self) -> str: 85 """Generate request state""" 86 return get_random_string(32) 87 88 def get_server_ctx(self, key: str) -> gssapi.sec_contexts.SecurityContext | None: 89 """Get GSSAPI server context from cache or create it""" 90 import gssapi 91 92 server_creds = self.source.get_gssapi_creds() 93 if server_creds is None: 94 return None 95 96 state = cache.get(f"{SPNEGO_STATE_CACHE_PREFIX}/{key}", None) 97 98 if state: 99 # pylint: disable=c-extension-no-member 100 return gssapi.sec_contexts.SecurityContext( 101 base=gssapi.raw.sec_contexts.import_sec_context(state), 102 ) 103 104 return gssapi.sec_contexts.SecurityContext(creds=server_creds, usage="accept") 105 106 def set_server_ctx(self, key: str, ctx: gssapi.sec_contexts.SecurityContext): 107 """Store the GSSAPI server context in cache""" 108 cache.set(f"{SPNEGO_STATE_CACHE_PREFIX}/{key}", ctx.export(), SPNEGO_STATE_CACHE_TIMEOUT) 109 110 # pylint: disable=too-many-return-statements 111 def dispatch(self, request, *args, **kwargs) -> HttpResponse: 112 """Process SPNEGO request""" 113 import gssapi 114 115 self.source: KerberosSource = get_object_or_404( 116 KerberosSource, 117 slug=kwargs.get("source_slug", ""), 118 enabled=True, 119 ) 120 121 qstring = request.GET if request.method == "GET" else request.POST 122 state = qstring.get("state", None) 123 if not state: 124 return redirect( 125 reverse( 126 "authentik_sources_kerberos:spnego-login", 127 kwargs={"source_slug": self.source.slug}, 128 ) 129 + f"?state={self.new_state()}" 130 ) 131 132 authstr = self.get_authstr(request) 133 if not authstr: 134 LOGGER.debug("authstr not present, sending challenge") 135 return self.challenge(request) 136 137 try: 138 in_token = b64decode(authstr) 139 except TypeError, ValueError: 140 return self.challenge(request) 141 142 with Krb5ConfContext(self.source): 143 server_ctx = self.get_server_ctx(state) 144 if not server_ctx: 145 return self.challenge(request) 146 147 try: 148 out_token = server_ctx.step(in_token) 149 except gssapi.exceptions.GSSError as exc: 150 LOGGER.debug("GSSAPI security context failure", exc=exc) 151 return self.challenge(request) 152 153 if not server_ctx.complete or server_ctx.initiator_name is None: 154 self.set_server_ctx(state, server_ctx) 155 return self.challenge(request, out_token) 156 157 def name_to_str(n: gssapi.names.Name) -> str: 158 return n.display_as(n.name_type) 159 160 identifier = name_to_str(server_ctx.initiator_name) 161 context = { 162 "spnego_info": { 163 "initiator_name": name_to_str(server_ctx.initiator_name), 164 "target_name": name_to_str(server_ctx.target_name), 165 "mech": str(server_ctx.mech), 166 "actual_flags": server_ctx.actual_flags, 167 }, 168 } 169 170 response = SPNEGOSourceFlowManager( 171 source=self.source, 172 request=request, 173 identifier=identifier, 174 user_info={ 175 "principal": identifier, 176 **context, 177 }, 178 policy_context=context, 179 ).get_flow() 180 return add_negotiate_to_response(response, out_token)
SPNEGO login
def
challenge( self, request, token: str | bytes | None = None) -> django.http.response.HttpResponse:
54 def challenge(self, request, token: str | bytes | None = None) -> HttpResponse: 55 """Get SNPEGO challenge response""" 56 response = render( 57 request, 58 "if/error.html", 59 context={ 60 "title": _("SPNEGO authentication required"), 61 "message": _(""" 62 Make sure you have valid tickets (obtainable via kinit) 63 and configured the browser correctly. 64 Please contact your administrator. 65 """), 66 }, 67 status=401, 68 ) 69 return add_negotiate_to_response(response, token)
Get SNPEGO challenge response
def
get_authstr(self, request) -> str | None:
71 def get_authstr(self, request) -> str | None: 72 """Get SPNEGO authentication string from headers""" 73 authorization_header = request.headers.get(HTTP_AUTHORIZATION, "") 74 if NEGOTIATE.lower() not in authorization_header.lower(): 75 return None 76 77 auth_tuple = authorization_header.split(" ", 1) 78 if not auth_tuple or auth_tuple[0].lower() != NEGOTIATE.lower(): 79 return None 80 if len(auth_tuple) != 2: # noqa: PLR2004 81 raise SuspiciousOperation("Malformed authorization header") 82 return auth_tuple[1]
Get SPNEGO authentication string from headers
def
get_server_ctx(unknown):
88 def get_server_ctx(self, key: str) -> gssapi.sec_contexts.SecurityContext | None: 89 """Get GSSAPI server context from cache or create it""" 90 import gssapi 91 92 server_creds = self.source.get_gssapi_creds() 93 if server_creds is None: 94 return None 95 96 state = cache.get(f"{SPNEGO_STATE_CACHE_PREFIX}/{key}", None) 97 98 if state: 99 # pylint: disable=c-extension-no-member 100 return gssapi.sec_contexts.SecurityContext( 101 base=gssapi.raw.sec_contexts.import_sec_context(state), 102 ) 103 104 return gssapi.sec_contexts.SecurityContext(creds=server_creds, usage="accept")
Get GSSAPI server context from cache or create it
def
set_server_ctx(unknown):
106 def set_server_ctx(self, key: str, ctx: gssapi.sec_contexts.SecurityContext): 107 """Store the GSSAPI server context in cache""" 108 cache.set(f"{SPNEGO_STATE_CACHE_PREFIX}/{key}", ctx.export(), SPNEGO_STATE_CACHE_TIMEOUT)
Store the GSSAPI server context in cache
def
dispatch(self, request, *args, **kwargs) -> django.http.response.HttpResponse:
111 def dispatch(self, request, *args, **kwargs) -> HttpResponse: 112 """Process SPNEGO request""" 113 import gssapi 114 115 self.source: KerberosSource = get_object_or_404( 116 KerberosSource, 117 slug=kwargs.get("source_slug", ""), 118 enabled=True, 119 ) 120 121 qstring = request.GET if request.method == "GET" else request.POST 122 state = qstring.get("state", None) 123 if not state: 124 return redirect( 125 reverse( 126 "authentik_sources_kerberos:spnego-login", 127 kwargs={"source_slug": self.source.slug}, 128 ) 129 + f"?state={self.new_state()}" 130 ) 131 132 authstr = self.get_authstr(request) 133 if not authstr: 134 LOGGER.debug("authstr not present, sending challenge") 135 return self.challenge(request) 136 137 try: 138 in_token = b64decode(authstr) 139 except TypeError, ValueError: 140 return self.challenge(request) 141 142 with Krb5ConfContext(self.source): 143 server_ctx = self.get_server_ctx(state) 144 if not server_ctx: 145 return self.challenge(request) 146 147 try: 148 out_token = server_ctx.step(in_token) 149 except gssapi.exceptions.GSSError as exc: 150 LOGGER.debug("GSSAPI security context failure", exc=exc) 151 return self.challenge(request) 152 153 if not server_ctx.complete or server_ctx.initiator_name is None: 154 self.set_server_ctx(state, server_ctx) 155 return self.challenge(request, out_token) 156 157 def name_to_str(n: gssapi.names.Name) -> str: 158 return n.display_as(n.name_type) 159 160 identifier = name_to_str(server_ctx.initiator_name) 161 context = { 162 "spnego_info": { 163 "initiator_name": name_to_str(server_ctx.initiator_name), 164 "target_name": name_to_str(server_ctx.target_name), 165 "mech": str(server_ctx.mech), 166 "actual_flags": server_ctx.actual_flags, 167 }, 168 } 169 170 response = SPNEGOSourceFlowManager( 171 source=self.source, 172 request=request, 173 identifier=identifier, 174 user_info={ 175 "principal": identifier, 176 **context, 177 }, 178 policy_context=context, 179 ).get_flow() 180 return add_negotiate_to_response(response, out_token)
Process SPNEGO request
183class SPNEGOSourceFlowManager(SourceFlowManager): 184 """Flow manager for Kerberos SPNEGO sources""" 185 186 user_connection_type = UserKerberosSourceConnection 187 group_connection_type = GroupKerberosSourceConnection
Flow manager for Kerberos SPNEGO sources
user_connection_type =
<class 'authentik.sources.kerberos.models.UserKerberosSourceConnection'>
group_connection_type =
<class 'authentik.sources.kerberos.models.GroupKerberosSourceConnection'>
Inherited Members
- authentik.core.sources.flow_manager.SourceFlowManager
- SourceFlowManager
- source
- mapper
- matcher
- request
- identifier
- user_info
- policy_context
- user_properties
- groups_properties
- is_user_switch_add_user
- get_action
- update_user_connection
- get_flow
- handle_match_failure
- error_handler
- get_stages_to_append
- handle_auth
- handle_existing_link
- handle_enroll