Debian Codegraph @

src/spnego/_gss.py

raw
1 # Copyright: (c) 2020, Jordan Borean (@jborean93) <[email protected]>
2 # MIT License (see LICENSE or https://opensource.org/licenses/MIT)
3
4 import base64
5 import copy
6 import logging
7 import sys
8 import typing
9
10 from spnego._context import (
11 IOV,
12 ContextProxy,
13 ContextReq,
14 GSSMech,
15 IOVUnwrapResult,
16 IOVWrapResult,
17 SecPkgContextSizes,
18 UnwrapResult,
19 WinRMWrapResult,
20 WrapResult,
21 wrap_system_error,
22 )
23 from spnego._credential import (
24 Credential,
25 CredentialCache,
26 KerberosCCache,
27 KerberosKeytab,
28 Password,
29 unify_credentials,
30 )
31 from spnego._text import to_bytes, to_text
32 from spnego.channel_bindings import GssChannelBindings
33 from spnego.exceptions import GSSError as NativeError
34 from spnego.exceptions import (
35 InvalidCredentialError,
36 NegotiateOptions,
37 NoContextError,
38 SpnegoError,
39 )
40 from spnego.iov import BufferType, IOVBuffer, IOVResBuffer
41
42 log = logging.getLogger(__name__)
43
44 HAS_GSSAPI = True
45 GSSAPI_IMP_ERR = None
46 try:
47 import gssapi
48 import krb5
49 from gssapi.raw import ChannelBindings, GSSError
50 from gssapi.raw import exceptions as gss_errors
51 from gssapi.raw import inquire_sec_context_by_oid, set_cred_option
52 except ImportError as e:
53 GSSAPI_IMP_ERR = str(e)
54 HAS_GSSAPI = False
55 log.debug("Python gssapi not available, cannot use any GSSAPIProxy protocols: %s" % e)
56
57
58 HAS_IOV = True
59 GSSAPI_IOV_IMP_ERR = None
60 try:
61 from gssapi.raw import IOV as GSSIOV
62 from gssapi.raw import IOVBuffer as GSSIOVBuffer
63 from gssapi.raw import IOVBufferType, unwrap_iov, wrap_iov, wrap_iov_length
64 except ImportError as err:
65 GSSAPI_IOV_IMP_ERR = sys.exc_info()
66 HAS_IOV = False
67 log.debug("Python gssapi IOV extension not available: %s" % str(GSSAPI_IOV_IMP_ERR[1]))
68
69 _GSS_C_INQ_SSPI_SESSION_KEY = "1.2.840.113554.1.2.2.5.5"
70
71 _GSS_KRB5_CRED_NO_CI_FLAGS_X = "1.2.752.43.13.29"
72
73
74 def _create_iov_result(iov: "GSSIOV") -> typing.Tuple[IOVResBuffer, ...]:
75 """Converts GSSAPI IOV buffer to generic IOVBuffer result."""
76 buffers = []
77 for i in iov:
78 buffer_entry = IOVResBuffer(type=BufferType(i.type), data=i.value)
79 buffers.append(buffer_entry)
80
81 return tuple(buffers)
82
83
84 def _get_gssapi_credential(
85 mech: "gssapi.OID",
86 usage: str,
87 credentials: typing.List[Credential],
88 context_req: typing.Optional[ContextReq] = None,
89 ) -> typing.Optional["gssapi.creds.Credentials"]:
90 """Gets the GSSAPI credential.
91
92 Will get a GSSAPI credential for the mech specified. If the username and password is specified then a new
93 set of credentials are explicitly required for the mech specified. Otherwise the credentials are retrieved based on
94 the credential type specified.
95
96 Args:
97 mech: The mech OID to get the credentials for, only Kerberos is supported.
98 usage: Either `initiate` for a client context or `accept` for a server context.
99 credentials: List of credentials to retreive from.
100 context_req: Context requirement flags that can control how the credential is retrieved.
101
102 Returns:
103 gssapi.creds.Credentials: The credential set that was created/retrieved.
104 """
105 name_type = getattr(gssapi.NameType, "user" if usage == "initiate" else "hostbased_service")
106 forwardable = bool(context_req and (context_req & ContextReq.delegate or context_req & ContextReq.delegate_policy))
107
108 for cred in credentials:
109 if isinstance(cred, CredentialCache):
110 principal = None
111 if cred.username:
112 principal = gssapi.Name(base=cred.username, name_type=name_type)
113
114 elif usage == "initiate":
115 # https://github.com/jborean93/pyspnego/issues/15
116 # Using None as a credential when creating the sec context is better than getting the default
117 # credential as the former takes into account the target SPN when selecting the principal to use.
118 return None
119
120 gss_cred = gssapi.Credentials(name=principal, usage=usage, mechs=[mech])
121
122 # We don't need to check the actual lifetime, just trying to get the valid will have gssapi check the
123 # lifetime and raise an ExpiredCredentialsError if it is expired.
124 _ = gss_cred.lifetime
125
126 return gss_cred
127
128 elif isinstance(cred, KerberosCCache):
129 if usage != "initiate":
130 log.debug("Skipping %s as it can only be used for an initiate Kerberos context", cred)
131 continue
132
133 ctx = krb5.init_context()
134 ccache = krb5.cc_resolve(ctx, to_bytes(cred.ccache))
135 krb5_principal: typing.Optional[krb5.Principal] = None
136 if cred.principal:
137 krb5_principal = krb5.parse_name_flags(ctx, to_bytes(cred.principal))
138
139 return gssapi.Credentials(base=_gss_acquire_cred_from_ccache(ccache, krb5_principal), usage=usage)
140
141 elif isinstance(cred, (KerberosKeytab, Password)):
142 if usage != "initiate":
143 log.debug("Skipping %s as it can only be used for an initiate Kerberos context", cred)
144 continue
145
146 if isinstance(cred, KerberosKeytab):
147 username = cred.principal or ""
148 password = cred.keytab
149 is_keytab = True
150 else:
151 username = cred.username
152 password = cred.password
153 is_keytab = False
154
155 raw_cred = _kinit(
156 to_bytes(username),
157 to_bytes(password),
158 forwardable=forwardable,
159 is_keytab=is_keytab,
160 )
161
162 return gssapi.Credentials(base=raw_cred, usage=usage)
163
164 else:
165 log.debug("Skipping credential %s as it does not support required mech type", cred)
166 continue
167
168 raise InvalidCredentialError(context_msg="No applicable credentials available")
169
170
171 def _gss_sasl_description(mech: "gssapi.OID") -> typing.Optional[bytes]:
172 """Attempts to get the SASL description of the mech specified."""
173 try:
174 res = _gss_sasl_description.result # type: ignore
175 return res[mech.dotted_form]
176
177 except (AttributeError, KeyError):
178 res = getattr(_gss_sasl_description, "result", {})
179
180 try:
181 sasl_desc = gssapi.raw.inquire_saslname_for_mech(mech).mech_description
182 except Exception as e:
183 log.debug("gss_inquire_saslname_for_mech(%s) failed: %s" % (mech.dotted_form, str(e)))
184 sasl_desc = None
185
186 res[mech.dotted_form] = sasl_desc
187 _gss_sasl_description.result = res # type: ignore
188 return _gss_sasl_description(mech)
189
190
191 def _kinit(
192 username: bytes,
193 password: bytes,
194 forwardable: typing.Optional[bool] = None,
195 is_keytab: bool = False,
196 ) -> "gssapi.raw.Creds":
197 """Gets a Kerberos credential.
198
199 This will get the GSSAPI credential that contains the Kerberos TGT inside
200 it. This is used instead of gss_acquire_cred_with_password as the latter
201 does not expose a way to request a forwardable ticket or to retrieve a TGT
202 from a keytab. This way makes it possible to request whatever is needed
203 before making it usable in GSSAPI.
204
205 Args:
206 username: The username to get the credential for.
207 password: The password to use to retrieve the credential.
208 forwardable: Whether to request a forwardable credential.
209 is_keytab: Whether password is a keytab or just a password.
210
211 Returns:
212 gssapi.raw.Creds: The GSSAPI credential for the Kerberos mech.
213 """
214 ctx = krb5.init_context()
215
216 kt: typing.Optional[krb5.KeyTab] = None
217 princ: typing.Optional[krb5.Principal] = None
218 if is_keytab:
219 kt = krb5.kt_resolve(ctx, password)
220
221 # If the username was not specified get the principal of the first entry.
222 if not username:
223 # The principal handle is deleted once the entry is deallocated. Make sure it is stored in a var before
224 # being copied.
225 first_entry = list(kt)[0]
226 princ = copy.copy(first_entry.principal)
227
228 if not princ:
229 princ = krb5.parse_name_flags(ctx, username)
230
231 init_opt = krb5.get_init_creds_opt_alloc(ctx)
232
233 if hasattr(krb5, "get_init_creds_opt_set_default_flags"):
234 # Heimdal requires this to be set in order to load the default options from krb5.conf. This follows the same
235 # code that it's own gss_acquire_cred_with_password does.
236 realm = krb5.principal_get_realm(ctx, princ)
237 krb5.get_init_creds_opt_set_default_flags(ctx, init_opt, b"gss_krb5", realm)
238
239 krb5.get_init_creds_opt_set_canonicalize(init_opt, True)
240 if forwardable is not None:
241 krb5.get_init_creds_opt_set_forwardable(init_opt, forwardable)
242
243 if kt:
244 cred = krb5.get_init_creds_keytab(ctx, princ, init_opt, keytab=kt)
245 else:
246 cred = krb5.get_init_creds_password(ctx, princ, init_opt, password=password)
247
248 mem_ccache = krb5.cc_new_unique(ctx, b"MEMORY")
249 krb5.cc_initialize(ctx, mem_ccache, princ)
250 krb5.cc_store_cred(ctx, mem_ccache, cred)
251
252 return _gss_acquire_cred_from_ccache(mem_ccache, None)
253
254
255 def _gss_acquire_cred_from_ccache(
256 ccache: "krb5.CCache",
257 principal: typing.Optional["krb5.Principal"],
258 ) -> "gssapi.raw.Creds":
259 """Acquire GSSAPI credential from CCache.
260
261 Args:
262 ccache: The CCache to acquire the credential from.
263 principal: The optional principal to acquire the cred for.
264
265 Returns:
266 gssapi.raw.Creds: The GSSAPI credentials from the ccache.
267 """
268 # acquire_cred_from is less dangerous than krb5_import_cred which uses a raw pointer to access the ccache. Heimdal
269 # has only recently added this API (not in a release as of 2021) so there's a fallback to the latter API.
270 if hasattr(gssapi.raw, "acquire_cred_from"):
271 kerberos = gssapi.OID.from_int_seq(GSSMech.kerberos.value)
272 name = None
273 if principal:
274 name = gssapi.Name(base=to_text(principal.name), name_type=gssapi.NameType.user)
275
276 ccache_name = ccache.name or b""
277 if ccache.cache_type:
278 ccache_name = ccache.cache_type + b":" + ccache_name
279
280 return gssapi.raw.acquire_cred_from(
281 {b"ccache": ccache_name},
282 name=name,
283 mechs=[kerberos],
284 usage="initiate",
285 ).creds
286
287 else:
288 gssapi_creds = gssapi.raw.Creds()
289 gssapi.raw.krb5_import_cred(
290 gssapi_creds, cache=ccache.addr, keytab_principal=principal.addr if principal else None
291 )
292
293 return gssapi_creds
294
295
296 class GSSAPIProxy(ContextProxy):
297 """GSSAPI proxy class for GSSAPI on Linux.
298
299 This proxy class for GSSAPI exposes GSSAPI calls into a common interface for Kerberos authentication. This context
300 uses the Python gssapi library to interface with the gss_* calls to provider Kerberos.
301 """
302
303 def __init__(
304 self,
305 username: typing.Optional[typing.Union[str, Credential, typing.List[Credential]]] = None,
306 password: typing.Optional[str] = None,
307 hostname: typing.Optional[str] = None,
308 service: typing.Optional[str] = None,
309 channel_bindings: typing.Optional[GssChannelBindings] = None,
310 context_req: ContextReq = ContextReq.default,
311 usage: str = "initiate",
312 protocol: str = "kerberos",
313 options: NegotiateOptions = NegotiateOptions.none,
314 **kwargs: typing.Any,
315 ) -> None:
316
317 if not HAS_GSSAPI:
318 raise ImportError("GSSAPIProxy requires the Python gssapi library: %s" % GSSAPI_IMP_ERR)
319
320 credentials = unify_credentials(username, password)
321 super(GSSAPIProxy, self).__init__(
322 credentials, hostname, service, channel_bindings, context_req, usage, protocol, options
323 )
324
325 self._mech = gssapi.OID.from_int_seq(GSSMech.kerberos.value)
326
327 gssapi_credential = kwargs.get("_gssapi_credential", None)
328 if not gssapi_credential:
329 try:
330 gssapi_credential = _get_gssapi_credential(
331 self._mech,
332 self.usage,
333 credentials=credentials,
334 context_req=context_req,
335 )
336 except GSSError as gss_err:
337 raise SpnegoError(base_error=gss_err, context_msg="Getting GSSAPI credential") from gss_err
338
339 if context_req & ContextReq.no_integrity and self.usage == "initiate":
340 if gssapi_credential is None:
341 gssapi_credential = gssapi.Credentials(usage=self.usage, mechs=[self._mech])
342
343 set_cred_option(
344 gssapi.OID.from_int_seq(_GSS_KRB5_CRED_NO_CI_FLAGS_X),
345 gssapi_credential,
346 )
347
348 self._credential = gssapi_credential
349 self._context: typing.Optional[gssapi.SecurityContext] = None
350
351 @classmethod
352 def available_protocols(cls, options: typing.Optional[NegotiateOptions] = None) -> typing.List[str]:
353 # We can't offer Kerberos if the caller requires WinRM wrapping and IOV isn't available.
354 avail = []
355 if not (options and options & NegotiateOptions.wrapping_winrm and not HAS_IOV):
356 avail.append("kerberos")
357
358 return avail
359
360 @classmethod
361 def iov_available(cls) -> bool:
362 return HAS_IOV
363
364 @property
365 def client_principal(self) -> typing.Optional[str]:
366 # Looks like a bug in python-gssapi where the value still has the terminating null char.
367 if self._context and self.usage == "accept":
368 return to_text(self._context.initiator_name).rstrip("\x00")
369 else:
370 return None
371
372 @property
373 def complete(self) -> bool:
374 return self._context is not None and self._context.complete
375
376 @property
377 def negotiated_protocol(self) -> typing.Optional[str]:
378 return "kerberos"
379
380 @property
381 @wrap_system_error(NativeError, "Retrieving session key")
382 def session_key(self) -> bytes:
383 if self._context:
384 return inquire_sec_context_by_oid(self._context, gssapi.OID.from_int_seq(_GSS_C_INQ_SSPI_SESSION_KEY))[0]
385 else:
386 raise NoContextError(context_msg="Retrieving session key failed as no context was initialized")
387
388 def new_context(self) -> "GSSAPIProxy":
389 return GSSAPIProxy(
390 hostname=self._hostname,
391 service=self._service,
392 channel_bindings=self.channel_bindings,
393 context_req=self.context_req,
394 usage=self.usage,
395 protocol=self.protocol,
396 options=self.options,
397 _gssapi_credential=self._credential,
398 )
399
400 @wrap_system_error(NativeError, "Processing security token")
401 def step(
402 self,
403 in_token: typing.Optional[bytes] = None,
404 *,
405 channel_bindings: typing.Optional[GssChannelBindings] = None,
406 ) -> typing.Optional[bytes]:
407 if not self._is_wrapped:
408 log.debug("GSSAPI step input: %s", base64.b64encode(in_token or b"").decode())
409
410 if not self._context:
411 context_kwargs: typing.Dict[str, typing.Any] = {}
412
413 channel_bindings = channel_bindings or self.channel_bindings
414 if channel_bindings:
415 context_kwargs["channel_bindings"] = ChannelBindings(
416 initiator_address_type=channel_bindings.initiator_addrtype,
417 initiator_address=channel_bindings.initiator_address,
418 acceptor_address_type=channel_bindings.acceptor_addrtype,
419 acceptor_address=channel_bindings.acceptor_address,
420 application_data=channel_bindings.application_data,
421 )
422
423 if self.usage == "initiate":
424 spn = "%s@%s" % (self._service or "host", self._hostname or "unspecified")
425 context_kwargs["name"] = gssapi.Name(spn, name_type=gssapi.NameType.hostbased_service)
426 context_kwargs["mech"] = self._mech
427 context_kwargs["flags"] = self._context_req
428
429 self._context = gssapi.SecurityContext(creds=self._credential, usage=self.usage, **context_kwargs)
430
431 out_token = self._context.step(in_token)
432
433 try:
434 self._context_attr = int(self._context.actual_flags)
435 except gss_errors.MissingContextError: # pragma: no cover
436 # MIT krb5 before 1.14.x will raise this error if the context isn't
437 # complete. We should only treat it as an error if it happens when
438 # the context is complete (last step).
439 # https://github.com/jborean93/pyspnego/issues/55
440 if self._context.complete:
441 raise
442
443 if not self._is_wrapped:
444 log.debug("GSSAPI step output: %s", base64.b64encode(out_token or b"").decode())
445
446 return out_token
447
448 @wrap_system_error(NativeError, "Getting context sizes")
449 def query_message_sizes(self) -> SecPkgContextSizes:
450 if not self._context:
451 raise NoContextError(context_msg="Cannot get message sizes until context has been established")
452
453 iov = GSSIOV(
454 IOVBufferType.header,
455 b"",
456 std_layout=False,
457 )
458 wrap_iov_length(self._context, iov)
459 return SecPkgContextSizes(header=len(iov[0].value or b""))
460
461 @wrap_system_error(NativeError, "Wrapping data")
462 def wrap(self, data: bytes, encrypt: bool = True, qop: typing.Optional[int] = None) -> WrapResult:
463 if not self._context:
464 raise NoContextError(context_msg="Cannot wrap until context has been established")
465 res = gssapi.raw.wrap(self._context, data, confidential=encrypt, qop=qop)
466
467 return WrapResult(data=res.message, encrypted=res.encrypted)
468
469 @wrap_system_error(NativeError, "Wrapping IOV buffer")
470 def wrap_iov(
471 self,
472 iov: typing.Iterable[IOV],
473 encrypt: bool = True,
474 qop: typing.Optional[int] = None,
475 ) -> IOVWrapResult:
476 if not self._context:
477 raise NoContextError(context_msg="Cannot wrap until context has been established")
478
479 buffers = self._build_iov_list(iov, self._convert_iov_buffer)
480 iov_buffer = GSSIOV(*buffers, std_layout=False)
481 encrypted = wrap_iov(self._context, iov_buffer, confidential=encrypt, qop=qop)
482
483 return IOVWrapResult(buffers=_create_iov_result(iov_buffer), encrypted=encrypted)
484
485 def wrap_winrm(self, data: bytes) -> WinRMWrapResult:
486 iov = self.wrap_iov([BufferType.header, data, BufferType.padding]).buffers
487 header = iov[0].data or b""
488 enc_data = iov[1].data or b""
489 padding = iov[2].data or b""
490
491 return WinRMWrapResult(header=header, data=enc_data + padding, padding_length=len(padding))
492
493 @wrap_system_error(NativeError, "Unwrapping data")
494 def unwrap(self, data: bytes) -> UnwrapResult:
495 if not self._context:
496 raise NoContextError(context_msg="Cannot unwrap until context has been established")
497
498 res = gssapi.raw.unwrap(self._context, data)
499
500 return UnwrapResult(data=res.message, encrypted=res.encrypted, qop=res.qop)
501
502 @wrap_system_error(NativeError, "Unwrapping IOV buffer")
503 def unwrap_iov(
504 self,
505 iov: typing.Iterable[IOV],
506 ) -> IOVUnwrapResult:
507 if not self._context:
508 raise NoContextError(context_msg="Cannot unwrap until context has been established")
509
510 buffers = self._build_iov_list(iov, self._convert_iov_buffer)
511 iov_buffer = GSSIOV(*buffers, std_layout=False)
512 res = unwrap_iov(self._context, iov_buffer)
513
514 return IOVUnwrapResult(buffers=_create_iov_result(iov_buffer), encrypted=res.encrypted, qop=res.qop)
515
516 def unwrap_winrm(self, header: bytes, data: bytes) -> bytes:
517 # This is an extremely weird setup, Kerberos depends on the underlying provider that is used. Right now the
518 # proper IOV buffers required to work on both AES and RC4 encrypted only works for MIT KRB5 whereas Heimdal
519 # fails. It currently mandates a padding buffer of a variable size which we cannot achieve in the way that
520 # WinRM encrypts the data. This is fixed in the source code but until it is widely distributed we just need to
521 # use a way that is known to just work with AES. To ensure that MIT works on both RC4 and AES we check the
522 # description which differs between the 2 implemtations. It's not perfect but I don't know of another way to
523 # achieve this until more time has passed.
524 # https://github.com/heimdal/heimdal/issues/739
525 if not self._context:
526 raise NoContextError(context_msg="Cannot unwrap until context has been established")
527
528 sasl_desc = _gss_sasl_description(self._context.mech)
529
530 # https://github.com/krb5/krb5/blob/f2e28f13156785851819fc74cae52100e0521690/src/lib/gssapi/krb5/gssapi_krb5.c#L686
531 if sasl_desc and sasl_desc == b"Kerberos 5 GSS-API Mechanism":
532 iov = self.unwrap_iov([(IOVBufferType.header, header), data, IOVBufferType.data]).buffers
533 return iov[1].data or b""
534
535 else:
536 return self.unwrap(header + data).data
537
538 @wrap_system_error(NativeError, "Signing message")
539 def sign(self, data: bytes, qop: typing.Optional[int] = None) -> bytes:
540 if not self._context:
541 raise NoContextError(context_msg="Cannot sign until context has been established")
542
543 return gssapi.raw.get_mic(self._context, data, qop=qop)
544
545 @wrap_system_error(NativeError, "Verifying message")
546 def verify(self, data: bytes, mic: bytes) -> int:
547 if not self._context:
548 raise NoContextError(context_msg="Cannot verify until context has been established")
549
550 return gssapi.raw.verify_mic(self._context, data, mic)
551
552 @property
553 def _context_attr_map(self) -> typing.List[typing.Tuple[ContextReq, int]]:
554 attr_map = [
555 (ContextReq.delegate, "delegate_to_peer"),
556 (ContextReq.mutual_auth, "mutual_authentication"),
557 (ContextReq.replay_detect, "replay_detection"),
558 (ContextReq.sequence_detect, "out_of_sequence_detection"),
559 (ContextReq.confidentiality, "confidentiality"),
560 (ContextReq.integrity, "integrity"),
561 (ContextReq.dce_style, "dce_style"),
562 # Only present when the DCE extensions are installed.
563 (ContextReq.identify, "identify"),
564 # Only present with newer versions of python-gssapi https://github.com/pythongssapi/python-gssapi/pull/218.
565 (ContextReq.delegate_policy, "ok_as_delegate"),
566 ]
567 attrs = []
568 for spnego_flag, gssapi_name in attr_map:
569 if hasattr(gssapi.RequirementFlag, gssapi_name):
570 attrs.append((spnego_flag, getattr(gssapi.RequirementFlag, gssapi_name)))
571
572 return attrs
573
574 def _convert_iov_buffer(self, buffer: IOVBuffer) -> "GSSIOVBuffer":
575 buffer_data = None
576 buffer_alloc = False
577
578 if isinstance(buffer.data, bytes):
579 buffer_data = buffer.data
580 elif isinstance(buffer.data, bool):
581 buffer_alloc = buffer.data
582 elif isinstance(buffer.data, int):
583 # This shouldn't really occur on GSSAPI but is here to mirror what SSPI does.
584 buffer_data = b"\x00" * buffer.data
585 else:
586 auto_alloc = [BufferType.header, BufferType.padding, BufferType.trailer]
587 buffer_alloc = buffer.type in auto_alloc
588
589 buffer_type = buffer.type
590 if buffer.type == BufferType.data_readonly:
591 # GSSAPI doesn't have the SSPI equivalent of SECBUFFER_READONLY.
592 # the GSS_IOV_BUFFER_TYPE_EMPTY seems to produce the same behaviour
593 # so that's going to be used instead.
594 buffer_type = BufferType.empty
595
596 return GSSIOVBuffer(IOVBufferType(buffer_type), buffer_alloc, buffer_data)