Debian Codegraph @

src/spnego/_context.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 abc
5 import dataclasses
6 import enum
7 import typing
8 import warnings
9
10 from spnego._credential import Credential
11 from spnego._text import to_text
12 from spnego.channel_bindings import GssChannelBindings
13 from spnego.exceptions import FeatureMissingError, NegotiateOptions, SpnegoError
14 from spnego.iov import BufferType, IOVBuffer, IOVResBuffer
15
16 F = typing.TypeVar("F", bound=typing.Callable[..., typing.Any])
17 NativeIOV = typing.TypeVar("NativeIOV", bound=typing.Any)
18 IOV = typing.Union[
19 IOVBuffer,
20 IOVResBuffer,
21 typing.Tuple[typing.Union[BufferType, int], typing.Union[bool, bytes, int]],
22 typing.Union[BufferType, int],
23 bytes,
24 ]
25
26
27 def split_username(username: typing.Optional[str]) -> typing.Tuple[typing.Optional[str], typing.Optional[str]]:
28 """Splits a username and returns the domain component.
29
30 Will split a username in the Netlogon form `DOMAIN\\username` and return the domain and user part as separate
31 strings. If the user does not contain the `DOMAIN\\` prefix or is in the `UPN` form then then user stays the same
32 and the domain is an empty string.
33
34 Args:
35 username: The username to split
36
37 Returns:
38 Tuple[Optional[str], Optional[str]]: The domain and username.
39 """
40 if username is None:
41 return None, None
42
43 domain: typing.Optional[str]
44 if "\\" in username:
45 domain, username = username.split("\\", 1)
46 else:
47 domain = None
48
49 return to_text(domain, nonstring="passthru"), to_text(username, nonstring="passthru")
50
51
52 def wrap_system_error(error_type: typing.Type, context: typing.Optional[str] = None) -> typing.Callable[[F], F]:
53 """Wraps a function that makes a native GSSAPI/SSPI syscall and convert native exceptions to a SpnegoError.
54
55 Wraps a function that can potentially raise a WindowsError or GSSError and converts it to the common SpnegoError
56 that is exposed by this library. This is to ensure the context proxy functions raise a common set of errors rather
57 than a specific error for the provider. The underlying error is preserved in the SpnegoError if the user wishes to
58 inspect that.
59
60 Args:
61 error_type: The native error type that need to be wrapped.
62 context: An optional context message to add to the error if raised.
63 """
64
65 def decorator(func: F) -> F:
66 def wrapper(*args: typing.Any, **kwargs: typing.Any) -> F:
67 try:
68 return func(*args, **kwargs)
69
70 except error_type as native_err:
71 raise SpnegoError(base_error=native_err, context_msg=context) from native_err
72
73 return typing.cast(F, wrapper)
74
75 return decorator
76
77
78 class WrapResult(typing.NamedTuple):
79 """Result of the `wrap()` function."""
80
81 data: bytes #: The bytes of the wrapped data.
82 encrypted: bool #: Whether the data was encrypted (True) or not (False).
83
84
85 class IOVWrapResult(typing.NamedTuple):
86 """Result of the `wrap_iov()` function."""
87
88 buffers: typing.Tuple[IOVResBuffer, ...] #: The wrapped IOV buffers.
89 encrypted: bool #: Whether the buffer data was encrypted (True) or not (False).
90
91
92 class WinRMWrapResult(typing.NamedTuple):
93 """Result of the `wrap_winrm()` function."""
94
95 header: bytes #: The header of the wrapped result.
96 data: bytes #: The wrapped data included any padding.
97 padding_length: int #: The length of the bytes added to the data for padding.
98
99
100 class UnwrapResult(typing.NamedTuple):
101 """Result of the `unwrap()` function."""
102
103 data: bytes #: The bytes of the unwrapped data.
104 encrypted: bool #: Whether the input data was encrypted (True) or not (False)
105 qop: int #: The Quality of Protection used for the encrypted data.
106
107
108 class IOVUnwrapResult(typing.NamedTuple):
109 """Result of the `unwrap_iov()` function."""
110
111 buffers: typing.Tuple[IOVResBuffer, ...] #: The unwrapped IOV buffers.
112 encrypted: bool #: Whether the input buffers were encrypted (True) or not (False)
113 qop: int #: The Quality of Protection used for the encrypted buffers.
114
115
116 @dataclasses.dataclass(frozen=True)
117 class SecPkgContextSizes:
118 """Sizes of important structures used for messages.
119
120 This dataclass exposes the sizes of important structures used in message
121 support functions like wrap, wrap_iov, sign, etc. Use
122 :meth:`ContextReq.query_message_sizes` to retrieve this value for an
123 authenticated context.
124
125 Currently only ``header`` is exposed but other sizes may be added in the
126 future if needed.
127
128 Attributes:
129 header: The size of the header/signature of a wrapped token. This
130 corresponds to cbSecurityTrailer in SecPkgContext_Sizes in SSPI and
131 the size of the allocated GSS_IOV_BUFFER_TYPE_HEADER IOV buffer.
132 """
133
134 header: int
135
136
137 class ContextReq(enum.IntFlag):
138 none = 0x00000000
139
140 # GSSAPI|SSPI flags
141 delegate = 0x00000001
142 mutual_auth = 0x00000002
143 replay_detect = 0x00000004
144 sequence_detect = 0x00000008
145 confidentiality = 0x00000010
146 integrity = 0x00000020
147 # anonymous = 0x00000040 # TODO: Add support for anonymous auth.
148 dce_style = 0x00001000
149 identify = 0x00002000
150 # Requires newer python-gssapi version to support https://github.com/pythongssapi/python-gssapi/pull/218
151 delegate_policy = 0x00080000
152
153 # Special flag that disables integrity/confidentiality on Kerberos/Negotiate
154 # This should not be set with integrity or confidentiality.
155 no_integrity = 0x10000000
156
157 # mutual_auth | replay_detect | sequence_detect | confidentiality | integrity
158 default = 0x00000002 | 0x00000004 | 0x00000008 | 0x00000010 | 0x00000020
159
160
161 class GSSMech(str, enum.Enum):
162 ntlm = "1.3.6.1.4.1.311.2.2.10"
163 spnego = "1.3.6.1.5.5.2"
164
165 # Kerberos has been put under several OIDs over time, we should only be using 'kerberos'.
166 kerberos = "1.2.840.113554.1.2.2" # The actual Kerberos OID, this should be the one used.
167 _ms_kerberos = "1.2.840.48018.1.2.2"
168 _kerberos_draft = "1.3.5.1.5.2"
169 _iakerb = "1.3.6.1.5.2"
170
171 # Not implemented.
172 kerberos_u2u = "1.2.840.113554.1.2.2.3"
173 negoex = "1.3.6.1.4.1.311.2.2.30"
174
175 @classmethod
176 def native_labels(cls) -> typing.Dict[str, str]:
177 return {
178 GSSMech.ntlm: "NTLM",
179 GSSMech.ntlm.value: "NTLM",
180 GSSMech.spnego: "SPNEGO",
181 GSSMech.spnego.value: "SPNEGO",
182 GSSMech.kerberos: "Kerberos",
183 GSSMech.kerberos.value: "Kerberos",
184 GSSMech._ms_kerberos: "MS Kerberos",
185 GSSMech._ms_kerberos.value: "MS Kerberos",
186 GSSMech._kerberos_draft: "Kerberos (draft)",
187 GSSMech._kerberos_draft.value: "Kerberos (draft)",
188 GSSMech._iakerb: "IAKerberos",
189 GSSMech._iakerb.value: "IAKerberos",
190 GSSMech.kerberos_u2u: "Kerberos User to User",
191 GSSMech.kerberos_u2u.value: "Kerberos User to User",
192 GSSMech.negoex: "NEGOEX",
193 GSSMech.negoex.value: "NEGOEX",
194 }
195
196 @property
197 def common_name(self) -> str:
198 if self.is_kerberos_oid:
199 return "kerberos"
200
201 return self.name
202
203 @property
204 def is_kerberos_oid(self) -> bool:
205 """Determines if the mech is a Kerberos mech.
206
207 Kerberos has been known under serveral OIDs in the past. This tells the caller whether the OID is one of those
208 "known" OIDs.
209
210 Returns:
211 bool: Whether the mech is a Kerberos mech (True) or not (False).
212 """
213 return self in [GSSMech.kerberos, GSSMech._ms_kerberos, GSSMech._kerberos_draft, GSSMech._iakerb]
214
215 @staticmethod
216 def from_oid(oid: str) -> "GSSMech":
217 """Converts an OID string to a GSSMech value.
218
219 Converts an OID string to a GSSMech value if it is known.
220
221 Args:
222 oid: The OID as a string to convert from.
223
224 Raises:
225 ValueError: if the OID is not a known GSSMech.
226 """
227 for mech in GSSMech:
228 if mech.value == oid:
229 return mech
230 else:
231 raise ValueError("'%s' is not a valid GSSMech OID" % oid)
232
233
234 class ContextProxy(metaclass=abc.ABCMeta):
235 """Base class for a authentication context.
236
237 A base class the defined a common entry point for the various authentication context's that are used in this
238 library. For a new context to be added it must implement the abstract functions in this class and translate the
239 calls to what is required internally.
240
241 Args:
242 credentials: A list of credentials to use for authentication.
243 hostname: The principal part of the SPN. This is required for Kerberos auth to build the SPN.
244 service: The service part of the SPN. This is required for Kerberos auth to build the SPN.
245 channel_bindings: The optional :class:`spnego.channel_bindings.GssChannelBindings` for the context.
246 context_req: The :class:`spnego.ContextReq` flags to use when setting up the context.
247 usage: The usage of the context, `initiate` for a client and `accept` for a server.
248 protocol: The protocol to authenticate with, can be `ntlm`, `kerberos`, or `negotiate`. Not all providers
249 support all three protocols as that is handled by :class:`SPNEGOContext`.
250 options: The :class:`spnego.NegotiateOptions` that define pyspnego specific options to control the negotiation.
251
252 Attributes:
253 usage (str): The usage of the context, `initiate` for a client and `accept` for a server.
254 protocol (str): The protocol to set the context up with; `ntlm`, `kerberos`, or `negotiate`.
255 spn (str): The service principal name of the service to connect to.
256 channel_bindings (spnego.channel_bindings.GssChannelBindings): Optional channel bindings to provide with the
257 context.
258 options (NegotiateOptions): The user specified negotiation options.
259 context_req (ContextReq): The context requirements flags as an int value specific to the context provider.
260 """
261
262 def __init__(
263 self,
264 credentials: typing.List[Credential],
265 hostname: typing.Optional[str],
266 service: typing.Optional[str],
267 channel_bindings: typing.Optional[GssChannelBindings],
268 context_req: ContextReq,
269 usage: str,
270 protocol: str,
271 options: NegotiateOptions,
272 ) -> None:
273 self.usage = usage.lower()
274 if self.usage not in ["initiate", "accept"]:
275 raise ValueError("Invalid usage '%s', must be initiate or accept" % self.usage)
276
277 self.protocol = protocol.lower()
278 if self.protocol not in ["ntlm", "kerberos", "negotiate", "credssp"]:
279 raise ValueError("Invalid protocol '%s', must be ntlm, kerberos, negotiate, or credssp" % self.protocol)
280
281 if self.protocol not in self.available_protocols(options=options):
282 raise ValueError("Protocol %s is not available" % self.protocol)
283
284 self._hostname = hostname
285 self._service = service
286 self.spn = None
287 if service or hostname:
288 self.spn = to_text("%s/%s" % (service if service else "HOST", hostname or "unspecified"))
289
290 self.channel_bindings = channel_bindings
291 self.options = NegotiateOptions(options)
292
293 self.context_req = context_req # Generic context requirements.
294 self._context_req = 0 # Provider specific context requirements.
295 for generic, provider in self._context_attr_map:
296 if context_req & generic:
297 self._context_req |= provider
298
299 self._context_attr = 0 # Provider specific context attributes, set by self.step().
300
301 # Whether the context is wrapped inside another context - set by NegotiateProxy.
302 self._is_wrapped = False
303
304 if options & NegotiateOptions.wrapping_iov and not self.iov_available():
305 raise FeatureMissingError(NegotiateOptions.wrapping_iov)
306
307 @property
308 def username(self) -> None:
309 warnings.warn("username is deprecated", category=DeprecationWarning)
310 return None
311
312 @property
313 def password(self) -> None:
314 warnings.warn("password is deprecated", category=DeprecationWarning)
315 return None
316
317 @classmethod
318 def available_protocols(cls, options: typing.Optional[NegotiateOptions] = None) -> typing.List[str]:
319 """A list of protocols that the provider can offer.
320
321 Returns a list of protocols the underlying provider can implement. Currently only kerberos, negotiate, or ntlm
322 is understood. The protocols that are available for each proxy context depend on the OS platform and what
323 libraries are installed. See each proxy's `available_protocols` function for more info.
324
325 Args:
326 options: The context requirements of :class:`NegotiationOptions` that state what the client requires.
327
328 Returns:
329 List[str]: The list of protocols that the context can use.
330 """
331 return ["kerberos", "negotiate", "ntlm"] # pragma: no cover
332
333 @classmethod
334 def iov_available(cls) -> bool:
335 """Whether the context supports IOV wrapping and unwrapping.
336
337 Will return a bool that states whether the context supports IOV wrapping or unwrapping. The NTLM protocol on
338 Linux does not support IOV and some Linux gssapi implementations do not expose the extension headers for this
339 function. This gives the caller a sane way to determine whether it can use :meth:`wrap_iov` or
340 :meth:`unwrap_iov`.
341
342 Returns:
343 bool: Whether the context provider supports IOV wrapping and unwrapping (True) or not (False).
344 """
345 return True # pragma: no cover
346
347 @property
348 @abc.abstractmethod
349 def client_principal(self) -> typing.Optional[str]:
350 """The principal that was used authenticated by the acceptor.
351
352 The name of the client principal that was used in the authentication context. This is `None` when
353 `usage='initiate'` or the context has not been completed. The format of the principal name is dependent on the
354 protocol and underlying library that was used to complete the authentication.
355
356 Returns:
357 Optional[str]: The client principal name.
358 """
359 pass # pragma: no cover
360
361 @property
362 @abc.abstractmethod
363 def complete(self) -> bool:
364 """Whether the context has completed the authentication process.
365
366 Will return a bool that states whether the authentication process has completed successfully.
367
368 Returns:
369 bool: The authentication process is complete (True) or not (False).
370 """
371 pass # pragma: no cover
372
373 @property
374 def context_attr(self) -> ContextReq:
375 """The context attributes that were negotiated.
376
377 This is the context attributes that were negotiated with the counterpart server. These attributes are only
378 valid once the context is fully established.
379
380 Returns:
381 ContextReq: The flags that were negotiated.
382 """
383 attr = 0
384 for generic, provider in self._context_attr_map:
385 if self._context_attr & provider:
386 attr |= generic
387
388 return ContextReq(attr)
389
390 @property
391 @abc.abstractmethod
392 def negotiated_protocol(self) -> typing.Optional[str]:
393 """The name of the negotiated protocol.
394
395 Once the authentication process has compeleted this will return the name of the negotiated context that was
396 used. For pure NTLM and Kerberos this will always be `ntlm` or `kerberos` respectively but for SPNEGO this can
397 be either of those two.
398
399 Returns:
400 Optional[str]: The protocol that was negotiated, can be `ntlm`, `kerberos`, or `negotiate. Will be `None`
401 for the acceptor until it receives the first token from the initiator. Once the context is establish
402 `negotiate` will change to either `ntlm` or `kerberos` to reflect the protocol that was used by SPNEGO.
403 """
404 pass # pragma: no cover
405
406 @property
407 @abc.abstractmethod
408 def session_key(self) -> bytes:
409 """The derived session key.
410
411 Once the authentication process is complete, this will return the derived session key. It is recommended to not
412 use this key for your own encryption processes and is only exposed because some libraries use this key in their
413 protocols.
414
415 Returns:
416 bytes: The derived session key from the authenticated context.
417 """
418 pass # pragma: no cover
419
420 @abc.abstractmethod
421 def new_context(self) -> "ContextProxy":
422 """Creates a new security context.
423
424 Creates a new security context based on the current credential and
425 options of the current context. This is useful when needing to set up a
426 new security context without having to retrieve the credentials again.
427
428 Returns:
429 ContextProxy: The new security context.
430 """
431 pass # pragma: no cover
432
433 @abc.abstractmethod
434 def query_message_sizes(self) -> SecPkgContextSizes:
435 """Gets the important structure sizes for message functions.
436
437 Will get the important sizes for the various message functions used by
438 the current authentication context. This must only be called once the
439 context has been authenticated.
440
441 Returns:
442 SecPkgContextSizes: The sizes for the current context.
443
444 Raises:
445 NoContextError: The security context is not ready to be queried.
446 """
447 pass # pragma: no cover
448
449 @abc.abstractmethod
450 def step(
451 self,
452 in_token: typing.Optional[bytes] = None,
453 *,
454 channel_bindings: typing.Optional[GssChannelBindings] = None,
455 ) -> typing.Optional[bytes]:
456 """Performs a negotiation step.
457
458 This method performs a negotiation step and processes/generates a token. This token should be then sent to the
459 counterpart context to continue the authentication process.
460
461 This should not be called once :meth:`complete` is True as the security context is complete.
462
463 For the initiator this is equivalent to `gss_init_sec_context`_ for GSSAPI and `InitializeSecurityContext`_ for
464 SSPI.
465
466 For the acceptor this is equivalent to `gss_accept_sec_context`_ for GSSAPI and `AcceptSecurityContext`_ for
467 SSPI.
468
469 Args:
470 in_token: The input token to process (or None to process no input token).
471 channel_bindings: Optional channel bindings ot use in this step. Will take priority over channel bindings
472 set in the context if both are specified.
473
474 Returns:
475 Optional[bytes]: The output token (or None if no output token is generated.
476
477 .. _gss_init_sec_context:
478 https://tools.ietf.org/html/rfc2744.html#section-5.19
479
480 .. _InitializeSecurityContext:
481 https://docs.microsoft.com/en-us/windows/win32/api/sspi/nf-sspi-initializesecuritycontextw
482
483 .. _gss_accept_sec_context:
484 https://tools.ietf.org/html/rfc2744.html#section-5.1
485
486 .. _AcceptSecurityContext:
487 https://docs.microsoft.com/en-us/windows/win32/api/sspi/nf-sspi-acceptsecuritycontext
488 """
489 pass # pragma: no cover
490
491 @abc.abstractmethod
492 def wrap(self, data: bytes, encrypt: bool = True, qop: typing.Optional[int] = None) -> WrapResult:
493 """Wrap a message, optionally with encryption.
494
495 This wraps a message, signing it and optionally encrypting it. The :meth:`unwrap` will unwrap a message.
496
497 This is the equivalent to `gss_wrap`_ for GSSAPI and `EncryptMessage`_ for SSPI.
498
499 The SSPI function's `EncryptMessage`_ is called with the following buffers::
500
501 SecBufferDesc(SECBUFFER_VERSION, [
502 SecBuffer(SECBUFFER_TOKEN, sizes.cbSecurityTrailer, b""),
503 SecBuffer(SECBUFFER_DATA, len(data), data),
504 SecBuffer(SECBUFFER_PADDING, sizes.cbBlockSize, b""),
505 ])
506
507 Args:
508 data: The data to wrap.
509 encrypt: Whether to encrypt the data (True) or just wrap it with a MIC (False).
510 qop: The desired Quality of Protection (or None to use the default).
511
512 Returns:
513 WrapResult: The wrapped result which contains the wrapped message and whether it was encrypted or not.
514
515 .. _gss_wrap:
516 https://tools.ietf.org/html/rfc2744.html#section-5.33
517
518 .. _EncryptMessage:
519 https://docs.microsoft.com/en-us/windows/win32/secauthn/encryptmessage--general
520 """
521 pass # pragma: no cover
522
523 @abc.abstractmethod
524 def wrap_iov(
525 self,
526 iov: typing.Iterable[IOV],
527 encrypt: bool = True,
528 qop: typing.Optional[int] = None,
529 ) -> IOVWrapResult:
530 """Wrap/Encrypt an IOV buffer.
531
532 This method wraps/encrypts an IOV buffer. The IOV buffers control how the data is to be processed. Because
533 IOV wrapping is an extension to GSSAPI and not implemented for NTLM on Linux, this method may not always be
534 available to the caller. Check the :meth:`iov_available` property.
535
536 This is the equivalent to `gss_wrap_iov`_ for GSSAPI and `EncryptMessage`_ for SSPI.
537
538 Args:
539 iov: A list of :class:`spnego.iov.IOVBuffer` buffers to wrap.
540 encrypt: Whether to encrypt the message (True) or just wrap it with a MIC (False).
541 qop: The desired Quality of Protection (or None to use the default).
542
543 Returns:
544 IOVWrapResult: The wrapped result which contains the wrapped IOVBuffer bytes and whether it was encrypted
545 or not.
546
547 .. _gss_wrap_iov:
548 http://k5wiki.kerberos.org/wiki/Projects/GSSAPI_DCE
549
550 .. _EncryptMessage:
551 https://docs.microsoft.com/en-us/windows/win32/secauthn/encryptmessage--general
552 """
553 pass # pragma: no cover
554
555 @abc.abstractmethod
556 def wrap_winrm(self, data: bytes) -> WinRMWrapResult:
557 """Wrap/Encrypt data for use with WinRM.
558
559 This method wraps/encrypts bytes for use with WinRM message encryption.
560
561 Args:
562 data: The data to wrap.
563
564 Returns:
565 WinRMWrapResult: The wrapped result for use with WinRM message encryption.
566 """
567 pass # pragma: no cover
568
569 @abc.abstractmethod
570 def unwrap(self, data: bytes) -> UnwrapResult:
571 """Unwrap a message.
572
573 This unwraps a message created by :meth:`wrap`.
574
575 This is the equivalent to `gss_unwrap`_ for GSSAPI and `DecryptMessage`_ for SSPI.
576
577 The SSPI function's `DecryptMessage`_ is called with the following buffers::
578
579 SecBufferDesc(SECBUFFER_VERSION, [
580 SecBuffer(SECBUFFER_STREAM, len(data), data),
581 SecBuffer(SECBUFFER_DATA, 0, b""),
582 ])
583
584 Args:
585 data: The data to unwrap.
586
587 Returns:
588 UnwrapResult: The unwrapped message, whether it was encrypted, and the QoP used.
589
590 .. _gss_unwrap:
591 https://tools.ietf.org/html/rfc2744.html#section-5.31
592
593 .. _DecryptMessage:
594 https://docs.microsoft.com/en-us/windows/win32/secauthn/decryptmessage--general
595 """
596 pass # pragma: no cover
597
598 @abc.abstractmethod
599 def unwrap_iov(
600 self,
601 iov: typing.Iterable[IOV],
602 ) -> IOVUnwrapResult:
603 """Unwrap/Decrypt an IOV buffer.
604
605 This method unwraps/decrypts an IOV buffer. The IOV buffers control how the data is to be processed. Because
606 IOV wrapping is an extension to GSSAPI and not implemented for NTLM on Linux, this method may not always be
607 available to the caller. Check the :meth:`iov_available` property.
608
609 This is the equivalent to `gss_unwrap_iov`_ for GSSAPI and `DecryptMessage`_ for SSPI.
610
611 Args:
612 iov: A list of :class:`spnego.iov.IOVBuffer` buffers to unwrap.
613
614 Returns:
615 IOVUnwrapResult: The unwrapped buffer bytes, whether it was encrypted, and the QoP used.
616
617 .. _gss_unwrap_iov:
618 http://k5wiki.kerberos.org/wiki/Projects/GSSAPI_DCE
619
620 .. _DecryptMessage:
621 https://docs.microsoft.com/en-us/windows/win32/secauthn/decryptmessage--general
622 """
623 pass # pragma: no cover
624
625 @abc.abstractmethod
626 def unwrap_winrm(self, header: bytes, data: bytes) -> bytes:
627 """Unwrap/Decrypt a WinRM message.
628
629 This method unwraps/decrypts a WinRM message. It handles the complexities of unwrapping the data and dealing
630 with the various system library calls.
631
632 Args:
633 header: The header portion of the WinRM wrapped result.
634 data: The data portion of the WinRM wrapped result.
635
636 Returns:
637 bytes: The unwrapped message.
638 """
639 pass # pragma: no cover
640
641 @abc.abstractmethod
642 def sign(self, data: bytes, qop: typing.Optional[int] = None) -> bytes:
643 """Generates a signature/MIC for a message.
644
645 This method generates a MIC for the given data. This is unlike wrap which bundles the MIC and the message
646 together. The :meth:`verify` method can be used to verify a MIC.
647
648 This is the equivalent to `gss_get_mic`_ for GSSAPI and `MakeSignature`_ for SSPI.
649
650 Args:
651 data: The data to generate the MIC for.
652 qop: The desired Quality of Protection (or None to use the default).
653
654 Returns:
655 bytes: The MIC for the data requested.
656
657 .. _gss_get_mic:
658 https://tools.ietf.org/html/rfc2744.html#section-5.15
659
660 .. _MakeSignature:
661 https://docs.microsoft.com/en-us/windows/win32/api/sspi/nf-sspi-makesignature
662 """
663 pass # pragma: no cover
664
665 @abc.abstractmethod
666 def verify(self, data: bytes, mic: bytes) -> int:
667 """Verify the signature/MIC for a message.
668
669 Will verify that the given MIC matches the given data. If the MIC does not match the given data, an exception
670 will be raised. The :meth:`sign` method can be used to sign data.
671
672 This is the equivalent to `gss_verify_mic`_ for GSSAPI and `VerifySignature`_ for SSPI.
673
674 Args:
675 data: The data to verify against the MIC.
676 mic: The MIC to verify against the data.
677
678 Returns:
679 int: The QoP (Quality of Protection) used.
680
681 .. _gss_verify_mic:
682 https://tools.ietf.org/html/rfc2744.html#section-5.32
683
684 .. _VerifySignature:
685 https://docs.microsoft.com/en-us/windows/win32/api/sspi/nf-sspi-verifysignature
686 """
687 pass # pragma: no cover
688
689 # Internal properties/functions not for public use.
690
691 @property
692 @abc.abstractmethod
693 def _context_attr_map(self) -> typing.List[typing.Tuple[ContextReq, int]]:
694 """Map the generic ContextReq into the provider specific flags.
695
696 Will return a list of tuples that give the provider specific flag value for the generic ContextReq that is
697 exposed to end users.
698
699 Returns:
700 List[Tuple[ContextReq, int], ...]: A list of tuples where tuple[0] is the ContextReq flag and tuple[1] is
701 the relevant provider specific flag for our common one.
702 """
703 pass # pragma: no cover
704
705 def get_extra_info(
706 self,
707 name: str,
708 default: typing.Any = None,
709 ) -> typing.Any:
710 """Return information about the security context.
711
712 Returns extra information about the security context that is not defined
713 as part of the standard :class:`ContextProxy` attributes or properties.
714 By default there is no context specific information and it's up to the
715 sub classes to implement their own.
716
717 These names can be queried for a CredSSP context.
718
719 client_credential:
720 Used on an `acceptor` CredSSP context and contains the delegated
721 credential sent by the client to the server. This is only
722 available once the context is complete otherwise the default
723 value is returned. The types returned can be
724 :class:`TSPasswordCreds`, :class:`TSSmartCardCreds`, or
725 :class:`TSRemoteGuardCreds`.
726
727 sslcontext:
728 The :class:`ssl.SSLContext` instance used for the CredSSP
729 context.
730
731 ssl_object:
732 The :class:`ssl.SSLObject` instance used for the CredSSP
733 context.
734
735 auth_stage - added in 0.5.0:
736 A string representing that sub authentication stage being
737 performed in the CredSSP authentication stepping. The value
738 here is meant to be a human friendly representation and not
739 something to be relied upon.
740
741 protocol_version - added in 0.5.0:
742 The CredSSP protocol version that was negotiated between the
743 initiator and acceptor. This is the minimum version number
744 offered by both parties once the Negotiate authentication stage
745 is complete.
746
747 Args:
748 name: The name/id of the information to retrieve.
749 default: The default value to return if the information is not
750 available on the current context proxy.
751
752 Args:
753 name: The name/id of the information to retrieve.
754 default: The default value to return if the information is not
755 available on the current context proxy.
756
757 Returns:
758 The information requested or the default value specified if the
759 information isn't found.
760 """
761 return default
762
763 @property
764 def _requires_mech_list_mic(self) -> bool:
765 """Determine if the SPNEGO mechListMIC is required for the sec context.
766
767 When Microsoft hosts deal with NTLM through SPNEGO it always wants the mechListMIC to be present when the NTLM
768 authentication message contains a MIC. This goes against RFC 4178 as a mechListMIC shouldn't be required if
769 NTLM was the preferred mech from the initiator but we can't do anything about that now. Because we exclusively
770 use SSPI on Windows hosts, which does all the work for us, this function only matter for Linux hosts when this
771 library manually creates the SPNEGO token.
772
773 The function performs 2 operations. When called before the NTLM authentication message has been created it
774 tells the gss-ntlmssp mech that it's ok to generate the MIC. When the authentication message has been created
775 it returns a bool stating whether the MIC was present in the auth message and subsequently whether we need to
776 include the mechListMIC in the SPNEGO token.
777
778 See `mech_required_mechlistMIC in MIT KRB5`_ for more information about how MIT KRB5 deals with this.
779
780 Returns:
781 bool: Whether the SPNEGO mechListMIC needs to be generated or not.
782
783 .. _mech_requires_mechlistMIC:
784 https://github.com/krb5/krb5/blob/b2fe66fed560ae28917a4acae6f6c0f020156353/src/lib/gssapi/spnego/spnego_mech.c#L493
785 """
786 return False # pragma: no cover
787
788 def _build_iov_list(
789 self, iov: typing.Iterable[IOV], native_convert: typing.Callable[[IOVBuffer], NativeIOV]
790 ) -> typing.List[NativeIOV]:
791 """Creates a list of IOV buffers for the native provider needed."""
792 provider_iov: typing.List[NativeIOV] = []
793
794 for entry in iov:
795 data: typing.Optional[typing.Union[bytes, int, bool]]
796 if isinstance(entry, tuple):
797 if len(entry) != 2:
798 raise ValueError("IOV entry tuple must contain 2 values, the type and data, see IOVBuffer.")
799
800 if not isinstance(entry[0], int):
801 raise ValueError("IOV entry[0] must specify the BufferType as an int")
802 buffer_type = entry[0]
803
804 if entry[1] is not None and not isinstance(entry[1], (bytes, int, bool)):
805 raise ValueError(
806 "IOV entry[1] must specify the buffer bytes, length of the buffer, or whether "
807 "it is auto allocated."
808 )
809 data = entry[1] if entry[1] is not None else b""
810
811 elif isinstance(entry, int):
812 buffer_type = entry
813 data = None
814
815 elif isinstance(entry, bytes):
816 buffer_type = BufferType.data
817 data = entry
818
819 else:
820 raise ValueError("IOV entry must be a IOVBuffer tuple, int, or bytes")
821
822 iov_buffer = IOVBuffer(type=BufferType(buffer_type), data=data)
823 provider_iov.append(native_convert(iov_buffer))
824
825 return provider_iov
826
827 def _reset_ntlm_crypto_state(self, outgoing: bool = True) -> None:
828 """Reset the NTLM crypto handles after signing/verifying the SPNEGO mechListMIC.
829
830 `MS-SPNG`_ documents that after signing or verifying the mechListMIC, the RC4 key state needs to be the same
831 for the mechListMIC and for the first message signed/sealed by the application. Because we use SSPI on Windows
832 hosts which does all the work for us this function only matters for Linux hosts.
833
834 Args:
835 outgoing: Whether to reset the outgoing or incoming RC4 key state.
836
837 .. _MS-SPNG:
838 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-spng/b87587b3-9d72-4027-8131-b76b5368115f
839 """
840 pass # pragma: no cover