Debian Codegraph @

src/spnego/exceptions.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 enum
5 import typing
6
7 GSSError: typing.Type[Exception]
8 try:
9 from gssapi.raw import GSSError # type: ignore
10 except ImportError as e:
11 GSSError = Exception
12
13 WinError: typing.Type[Exception]
14 try:
15 WinError = WindowsError # type: ignore
16 except NameError:
17 WinError = Exception
18
19
20 class NativeError(Exception):
21 """Stub for a native error that can be used to generate a SpnegoError from a known platform native code."""
22
23 def __init__(self, msg: str, **kwargs: typing.Any) -> None:
24 self.msg = msg
25 for key in ["maj_code", "winerror"]:
26 if key in kwargs:
27 setattr(self, key, kwargs[key])
28
29
30 class NegotiateOptions(enum.IntFlag):
31 """Flags that the caller can use to control the negotiation behaviour.
32
33 A list of features as bit flags that the caller can specify when creating the security context. These flags can
34 be used on both Windows or Linux but are a no-op on Windows as it should always have the same features available.
35 On Linux the features it can implement depend on a wide range of factors like the system libraries/headers that
36 are installed, what GSSAPI implementation is present, and what Python libraries are available.
37
38 This is a pretty advanced feature and is mostly a way to control the kerberos to ntlm fallback behaviour on Linux.
39 The `use_*` options when combined with `protocol='credssp'` control the underlying auth proxy provider that is used
40 in the CredSSP authentication process and not the parent context proxy the user interacts with.
41
42 These are the currently implemented feature flags:
43
44 use_sspi:
45 Ensures the context proxy used is :class:`spnego._sspi.SSPIProxy`.
46
47 use_gssapi:
48 Ensures the context proxy used is :class:`spnego._gss.GSSAPIProxy`.
49
50 use_negotiate:
51 Ensures the context proxy used is :class:`spnego._negotiate.NegotiateProxy`.
52
53 use_ntlm:
54 Ensures the context proxy used is :class:`spnego._ntlm.NTLMProxy`.
55
56 negotiate_kerberos:
57 Will make sure that Kerberos is at least available to try for authentication when using the `negotiate`
58 protocol. If Kerberos cannot be used due to the Python gssapi library not being installed then it will raise a
59 :class:`spnego.exceptions.FeatureMissingError`. If Kerberos was available but it cannot get a credential or
60 create a context then it will just fallback to NTLM auth. If you wish to only use Kerberos with no NTLM
61 fallback, set `protocol='kerberos'` when creating the security context.
62
63 session_key:
64 Ensure that the authenticated context will be able to return the session key that was negotiated between the
65 client and the server. Older versions of `gss-ntlmssp`_ do not expose the functions required to retrieve this
66 info so when this feature flag is set then the NTLM fallback process will use a builtin NTLM process and not
67 `gss-ntlmssp`_ if the latter is too old to retrieve the session key. Cannot be used in combination with
68 `protocol='credssp'` as CredSSP does not provide a session key.
69
70 wrapping_iov:
71 The GSSAPI IOV methods are extensions to the Kerberos spec and not implemented or exposed on all platforms,
72 macOS is a popular example. If the caller requires the wrap_iov and unwrap_iov methods this will ensure it
73 fails fast before the auth has been set up. Unfortunately there is no fallback for this as if the headers
74 aren't present for GSSAPI then we can't do anything to fix that. This won't fail if `negotiate` was used and
75 NTLM was the chosen protocol as that happens post negotiation.
76
77 wrapping_winrm:
78 To created a wrapped WinRM message the IOV extensions are required when using Kerberos auth. Setting this flag
79 will skip Kerberos when `protocol='negotiate'` if the IOV headers aren't present and just fallback to NTLM.
80
81 .. _gss-ntlmssp:
82 https://github.com/gssapi/gss-ntlmssp
83 """
84
85 none = 0x00000000
86
87 # Force a specific provider
88 use_sspi = 0x00000001
89 use_gssapi = 0x00000002
90 use_negotiate = 0x00000004
91 use_ntlm = 0x00000008
92
93 negotiate_kerberos = 0x00000010
94 session_key = 0x00000020
95 wrapping_iov = 0x00000040
96 wrapping_winrm = 0x00000080
97
98
99 class FeatureMissingError(Exception):
100 @property
101 def feature_id(self) -> NegotiateOptions:
102 return self.args[0]
103
104 @property
105 def message(self) -> str:
106 msg = {
107 NegotiateOptions.negotiate_kerberos: "The Python gssapi library is not installed so Kerberos cannot be "
108 "negotiated.",
109 NegotiateOptions.wrapping_iov: "The system is missing the GSSAPI IOV extension headers or CredSSP is "
110 "being requested, cannot utilize wrap_iov and unwrap_iov",
111 NegotiateOptions.wrapping_winrm: "The system is missing the GSSAPI IOV extension headers required for "
112 "WinRM encryption with Kerberos.",
113 NegotiateOptions.session_key: "The protocol selected does not support getting the session key.",
114 }.get(self.feature_id, "Unknown option flag: %d" % self.feature_id)
115
116 return msg
117
118 def __str__(self) -> str:
119 return self.message
120
121
122 class ErrorCode(enum.IntEnum):
123 """Common error codes for SPNEGO operations.
124
125 Mostly a copy of the `GSS major error codes`_ with the names made more pythonic. Not all codes have a corresponding
126 SpnegoError class as they are reserved for the codes that apply to both GSSAPI and SSPI.
127
128 .. _GSS major error codes:
129 https://docs.oracle.com/cd/E19683-01/816-1331/reference-4/index.html
130 """
131
132 bad_mech = 1 # BadMechanismError
133 bad_name = 2 # BadNameError
134 # bad_nametype = 3 # No equivalent in SSPI, shouldn't happen in our code as well.
135 bad_bindings = 4 # BadBindings
136 # bad_status = 5 # Only used in gss_display_status which we don't care about.
137 bad_mic = 6 # BadMICError
138 no_cred = 7 # NoCredentialError
139 no_context = 8 # NoContextError
140 invalid_token = 9 # InvalidTokenError
141 invalid_credential = 10 # InvalidCredentialError
142 credentials_expired = 11 # CredentialsExpiredError
143 context_expired = 12 # ContextExpiredError
144 failure = 13 # This is a generic error with the error coming from the minor code, uses SpnegoError directly.
145 bad_qop = 14 # UnsupportedQop
146 # unauthorized = 15 # Shouldn't happen in our code, we don't do any authorization functions.
147 unavailable = 16 # OperationNotAvailableError
148 # duplicate_element = 17 # Shouldn't happen in our code.
149 # name_not_mn = 18 # Shouldn't happen in our code.
150
151
152 # Implementation is inspired by the python-gssapi project https://github.com/pythongssapi/python-gssapi.
153 # https://github.com/pythongssapi/python-gssapi/blob/826c02de1c1885896924bf342c60087f369c6b1a/gssapi/raw/misc.pyx#L180
154 class _SpnegoErrorRegistry(type):
155 __registry: typing.Dict[int, typing.Type] = {}
156 __gssapi_map: typing.Dict[int, int] = {}
157 __sspi_map: typing.Dict[int, int] = {}
158
159 def __init__(
160 cls,
161 *args: typing.Any,
162 **kwargs: typing.Any,
163 ) -> None:
164 # Load up the registry with the instantiated class so we can look it up when creating a SpnegoError.
165 error_code = getattr(cls, "ERROR_CODE", None)
166
167 if error_code is not None and error_code not in cls.__registry:
168 cls.__registry[error_code] = cls
169
170 # Map the system error codes to the common spnego error code.
171 for system_attr, mapping in [("_GSSAPI_CODE", cls.__gssapi_map), ("_SSPI_CODE", cls.__sspi_map)]:
172 codes = getattr(cls, system_attr, None)
173
174 if codes is None:
175 continue
176
177 if not isinstance(codes, (list, tuple)):
178 codes = [codes]
179
180 for c in codes:
181 mapping[c] = error_code or 0
182
183 def __call__(
184 cls,
185 error_code: typing.Optional[int] = None,
186 base_error: typing.Optional[Exception] = None,
187 *args: typing.Any,
188 **kwargs: typing.Any,
189 ) -> "_SpnegoErrorRegistry":
190 error_code = error_code if error_code is not None else getattr(cls, "ERROR_CODE", None)
191
192 if error_code is None:
193 if not base_error:
194 raise ValueError("%s requires either an error_code or base_error" % cls.__name__)
195
196 # GSSError
197 maj_code = getattr(base_error, "maj_code", None)
198 # WindowsError
199 winerror = getattr(base_error, "winerror", None)
200
201 if maj_code is not None:
202 error_code = cls.__gssapi_map.get(maj_code, None)
203
204 elif winerror is not None:
205 error_code = cls.__sspi_map.get(winerror, None)
206
207 else:
208 raise ValueError(
209 "base_error of type '%s' is not supported, must be a gssapi.exceptions.GSSError or "
210 "WindowsError" % type(base_error).__name__
211 )
212
213 new_cls = cls.__registry.get(error_code or 0, cls)
214 return super(_SpnegoErrorRegistry, new_cls).__call__(
215 error_code, # type: ignore[arg-type] # I cannot understand this, seems to be bug?
216 base_error,
217 *args,
218 **kwargs,
219 )
220
221
222 class SpnegoError(Exception, metaclass=_SpnegoErrorRegistry):
223 """Common error for SPNEGO exception.
224
225 Creates an common error record for SPNEGO errors raised by pyspnego. This error record can wrap system level error
226 records raised by GSSAPI or SSPI and wrap them into a common error record across the various platforms. While this
227 reflects the GSSAPI major codes that can be raised, it is up to the GSSAPI platform to conform to those error
228 codes. Some platforms like MIT krb5 always report `GSS_S_FAILURE` and use the minor code to report the actual
229 error message.
230
231 Args:
232 error_code: The ErrorCode for the error, this must be set if base_error is not set.
233 base_error: The system level error from SSPI or GSSAPI, this must be set if error_code is not set.
234 context_msg: Optional message to provide more context around the error.
235
236 Attributes:
237 base_error (Optional[Union[GSSError, WinError]]): The system level error if one was provided.
238 """
239
240 # Classes the subclass this type need to provide the following class attribute:
241 #
242 # ERROR_CODE = common ErrorCode value for the exception
243 # _BASE_MESSAGE = common string that explains the error code in the absence of the system error message.
244 #
245 # The following attributes are used to map specific system error codes to the common ErrorCode error.
246 # _GSSAPI_CODE = The GSSAPI major_code from GSSError to map to the common error code
247 # _SSPI_CODE = The winerror value from an WindowsError to map to the common error code
248
249 def __init__(
250 self,
251 error_code: typing.Optional[typing.Union[int, ErrorCode]] = None,
252 base_error: typing.Optional[Exception] = None,
253 context_msg: typing.Optional[str] = None,
254 ) -> None:
255 self.base_error = base_error
256 self._error_code = error_code
257 self._context_message = context_msg
258
259 super(SpnegoError, self).__init__(self.message)
260
261 @property
262 def nt_status(self) -> int:
263 """The Windows NT Status code that represents this error."""
264 codes = getattr(self, "_SSPI_CODE", self._error_code) or 0xFFFFFFFF
265 return codes[0] if isinstance(codes, (list, tuple)) else codes
266
267 @property
268 def message(self) -> str:
269 error_code = self._error_code if self._error_code is not None else 0xFFFFFFFF
270
271 if self.base_error:
272 base_message = str(self.base_error)
273
274 else:
275 base_message = getattr(self, "_BASE_MESSAGE", "Unknown error code")
276
277 msg = "SpnegoError (%d): %s" % (error_code, base_message)
278 if self._context_message:
279 msg += ", Context: %s" % self._context_message
280
281 return msg
282
283
284 class BadMechanismError(SpnegoError):
285 ERROR_CODE = ErrorCode.bad_mech
286
287 _BASE_MESSAGE = "An unsupported mechanism was requested"
288 _GSSAPI_CODE = 65536 # GSS_S_BAD_MECH
289 _SSPI_CODE = -2146893051 # SEC_E_SECPKG_NOT_FOUND
290
291
292 class BadNameError(SpnegoError):
293 ERROR_CODE = ErrorCode.bad_name
294
295 _BASE_MESSAGE = "An invalid name was supplied"
296 _GSSAPI_CODE = 1310722 # GSS_S_BAD_NAME
297 _SSPI_CODE = -2146893053 # SEC_E_TARGET_UNKNOWN
298
299
300 class BadBindingsError(SpnegoError):
301 ERROR_CODE = ErrorCode.bad_bindings
302
303 _BASE_MESSAGE = "Invalid channel bindings"
304 _GSSAPI_CODE = 262144 # GSS_BAD_BINDINGS
305 _SSPI_CODE = -2146892986 # SEC_E_BAD_BINDINGS
306
307
308 class BadMICError(SpnegoError):
309 ERROR_CODE = ErrorCode.bad_mic
310
311 _BASE_MESSAGE = "A token had an invalid Message Integrity Check (MIC)"
312 _GSSAPI_CODE = 3932166 # GSS_BAD_MIC
313 _SSPI_CODE = -2146893041 # SEC_E_MESSAGE_ALTERED
314
315
316 class NoCredentialError(SpnegoError):
317 ERROR_CODE = ErrorCode.no_cred
318
319 _BASE_MESSAGE = "No credentials were supplied, or the credentials were unavailable or inaccessible"
320 _GSSAPI_CODE = 458752 # GSS_NO_CRED
321 _SSPI_CODE = -2146893042 # SEC_E_NO_CREDENTIALS
322
323
324 class NoContextError(SpnegoError):
325 ERROR_CODE = ErrorCode.no_context
326
327 _BASE_MESSAGE = "No context has been established, or invalid handled passed in"
328 _GSSAPI_CODE = 524288 # GSS_S_NO_CONTEXT
329 _SSPI_CODE = -2146893055 # SEC_E_INVALID_HANDLE
330
331
332 class InvalidTokenError(SpnegoError):
333 ERROR_CODE = ErrorCode.invalid_token
334
335 _BASE_MESSAGE = "A token was invalid, or the logon was denied"
336 _GSSAPI_CODE = 589824 # GSS_S_DEFECTIVE_TOKEN
337 _SSPI_CODE = [-2146893044, -2146893048] # SEC_E_LOGON_DENIED, SEC_E_INVALID_TOKEN
338
339
340 class InvalidCredentialError(SpnegoError):
341 ERROR_CODE = ErrorCode.invalid_credential
342
343 _BASE_MESSAGE = "A credential was invalid"
344 _GSSAPI_CODE = 655360 # GSS_S_DEFECTIVE_CREDENTIAL
345 _SSPI_CODE = -1073741715 # STATUS_LOGON_FAILURE
346
347
348 class CredentialsExpiredError(SpnegoError):
349 ERROR_CODE = ErrorCode.credentials_expired
350
351 _BASE_MESSAGE = "The referenced credentials have expired"
352 _GSSAPI_CODE = 720896 # * GSS_S_CREDENTIALS_EXPIRED
353 _SSPI_CODE = -1073741711 # STATUS_PASSWORD_EXPIRED
354
355
356 class ContextExpiredError(SpnegoError):
357 ERROR_CODE = ErrorCode.context_expired
358
359 _BASE_MESSAGE = "Security context has expired"
360 _GSSAPI_CODE = 786432 # GSS_S_CONTEXT_EXPIRED
361 _SSPI_CODE = -2146893033 # SEC_E_CONTEXT_EXPIRED
362
363
364 class UnsupportedQop(SpnegoError):
365 ERROR_CODE = ErrorCode.bad_qop
366
367 _BASE_MESSAGE = "The quality-of-protection requested could not be provided"
368 _GSSAPI_CODE = 917504 # GSS_S_BAD_QOP
369 _SSPI_CODE = -2146893046 # SEC_E_QOP_NOT_SUPPORTED
370
371
372 class OperationNotAvailableError(SpnegoError):
373 ERROR_CODE = ErrorCode.unavailable
374
375 _BASE_MESSAGE = "Operation not supported or available"
376 _GSSAPI_CODE = 1048576 # GSS_S_UNAVAILABLE
377 _SSPI_CODE = -2146893054 # SEC_E_UNSUPPORTED_FUNCTION