Debian Codegraph @

src/spnego/_sspi.py

raw
1 # Copyright: (c) 2020, Jordan Borean (@jborean93) <[email protected]>
2 # MIT License (see LICENSE or https://opensource.org/licenses/MIT)
3
4 from __future__ import annotations
5
6 import base64
7 import collections.abc
8 import logging
9 import os
10 import typing as t
11
12 from spnego._context import (
13 IOV,
14 ContextProxy,
15 ContextReq,
16 IOVUnwrapResult,
17 IOVWrapResult,
18 SecPkgContextSizes,
19 UnwrapResult,
20 WinRMWrapResult,
21 WrapResult,
22 split_username,
23 wrap_system_error,
24 )
25 from spnego._credential import Credential, CredentialCache, Password, unify_credentials
26 from spnego.channel_bindings import GssChannelBindings
27 from spnego.exceptions import (
28 InvalidCredentialError,
29 NegotiateOptions,
30 NoContextError,
31 SpnegoError,
32 )
33 from spnego.exceptions import WinError as NativeError
34 from spnego.iov import BufferType, IOVBuffer, IOVResBuffer
35
36 log = logging.getLogger(__name__)
37
38 if os.name == "nt":
39 import sspilib
40
41 HAS_SSPI = True
42 else:
43 HAS_SSPI = False
44
45
46 def _available_protocols() -> list[str]:
47 """Return a list of protocols that SSPIProxy can offer."""
48 if HAS_SSPI:
49 return ["kerberos", "negotiate", "ntlm"]
50 else:
51 return []
52
53
54 def _create_iov_result(iov: sspilib.raw.SecBufferDesc) -> tuple[IOVResBuffer, ...]:
55 """Converts SSPI IOV buffer to generic IOVBuffer result."""
56 buffers = []
57 for i in iov:
58 buffer_type = int(i.buffer_type)
59 if i.buffer_flags & sspilib.raw.SecBufferFlags.SECBUFFER_READONLY_WITH_CHECKSUM:
60 buffer_type = BufferType.sign_only
61 elif i.buffer_flags & sspilib.raw.SecBufferFlags.SECBUFFER_READONLY:
62 buffer_type = BufferType.data_readonly
63
64 buffer_entry = IOVResBuffer(type=BufferType(buffer_type), data=i.data)
65 buffers.append(buffer_entry)
66
67 return tuple(buffers)
68
69
70 def _get_sspi_credential(
71 principal: str | None,
72 protocol: str,
73 usage: str,
74 credentials: list[Credential],
75 ) -> sspilib.raw.CredHandle:
76 """Get the SSPI credential.
77
78 Will get an SSPI credential for the protocol specified. Currently only
79 supports Password or CredentialCache credential types.
80
81 Args:
82 principal: The principal to use for the AcquireCredentialsHandle call
83 protocol: The protocol of the credential.
84 usage: Either `initiate` for a client context or `accept` for a server
85 context.
86 credentials: List of credentials to retrieve from.
87
88 Returns:
89 sspilib.raw.CredHandle: The handle to the SSPI credential to use.
90 """
91 credential_kwargs: dict[str, t.Any] = {
92 "package": protocol,
93 "principal": principal,
94 "credential_use": (
95 sspilib.raw.CredentialUse.SECPKG_CRED_OUTBOUND
96 if usage == "initiate"
97 else sspilib.raw.CredentialUse.SECPKG_CRED_INBOUND
98 ),
99 }
100
101 for cred in credentials:
102 if isinstance(cred, Password):
103 domain, username = split_username(cred.username)
104 auth_data = sspilib.raw.WinNTAuthIdentity(
105 username=username,
106 domain=domain,
107 password=cred.password,
108 )
109
110 return sspilib.raw.acquire_credentials_handle(**credential_kwargs, auth_data=auth_data).credential
111
112 elif isinstance(cred, CredentialCache):
113 return sspilib.raw.acquire_credentials_handle(**credential_kwargs).credential
114
115 raise InvalidCredentialError(context_msg="No applicable credentials available")
116
117
118 class SSPIProxy(ContextProxy):
119 """SSPI proxy class for pure SSPI on Windows.
120
121 This proxy class for SSPI exposes this library into a common interface for SPNEGO authentication. This context
122 uses compiled C code to interface directly into the SSPI functions on Windows to provide a native SPNEGO
123 implementation.
124 """
125
126 def __init__(
127 self,
128 username: str | Credential | list[Credential] | None = None,
129 password: str | None = None,
130 hostname: str | None = None,
131 service: str | None = None,
132 channel_bindings: GssChannelBindings | None = None,
133 context_req: ContextReq = ContextReq.default,
134 usage: str = "initiate",
135 protocol: str = "negotiate",
136 options: NegotiateOptions = NegotiateOptions.none,
137 **kwargs: t.Any,
138 ) -> None:
139
140 if not HAS_SSPI:
141 raise ImportError("SSPIProxy requires the Windows only sspilib python package")
142
143 credentials = unify_credentials(username, password)
144 super(SSPIProxy, self).__init__(
145 credentials, hostname, service, channel_bindings, context_req, usage, protocol, options
146 )
147
148 self._native_channel_bindings: sspilib.SecChannelBindings | None
149 if channel_bindings:
150 self._native_channel_bindings = self._get_native_bindings(channel_bindings)
151 else:
152 self._native_channel_bindings = None
153
154 self._block_size = 0
155 self._max_signature = 0
156 self._security_trailer = 0
157
158 self._complete = False
159 self._context: sspilib.raw.CtxtHandle | None = None
160 self.__seq_num = 0
161
162 sspi_credential = kwargs.get("_sspi_credential", None)
163 if not sspi_credential:
164 try:
165 principal = self.spn if usage == "accept" else None
166 sspi_credential = _get_sspi_credential(principal, protocol, usage, credentials)
167 except NativeError as win_err:
168 raise SpnegoError(base_error=win_err, context_msg="Getting SSPI credential") from win_err
169
170 self._credential = sspi_credential
171
172 @classmethod
173 def available_protocols(
174 cls,
175 options: NegotiateOptions | None = None,
176 ) -> list[str]:
177 return _available_protocols()
178
179 @property
180 def client_principal(self) -> str | None:
181 if self.usage == "accept":
182 names = sspilib.raw.query_context_attributes(
183 t.cast(sspilib.raw.CtxtHandle, self._context),
184 sspilib.raw.SecPkgContextNames,
185 )
186 return names.username
187 else:
188 return None
189
190 @property
191 def complete(self) -> bool:
192 return self._complete
193
194 @property
195 def negotiated_protocol(self) -> str | None:
196 # FIXME: Try and replicate GSSAPI. Will return None for acceptor until the first token is returned. Negotiate
197 # for both iniator and acceptor until the context is established.
198 package_info = sspilib.raw.query_context_attributes(
199 t.cast(sspilib.raw.CtxtHandle, self._context),
200 sspilib.raw.SecPkgContextPackageInfo,
201 )
202 return package_info.name.lower()
203
204 @property
205 @wrap_system_error(NativeError, "Retrieving session key")
206 def session_key(self) -> bytes:
207 session_key = sspilib.raw.query_context_attributes(
208 t.cast(sspilib.raw.CtxtHandle, self._context),
209 sspilib.raw.SecPkgContextSessionKey,
210 )
211 return session_key.session_key
212
213 def new_context(self) -> SSPIProxy:
214 return SSPIProxy(
215 hostname=self._hostname,
216 service=self._service,
217 channel_bindings=self.channel_bindings,
218 context_req=self.context_req,
219 usage=self.usage,
220 protocol=self.protocol,
221 options=self.options,
222 _sspi_credential=self._credential,
223 )
224
225 @wrap_system_error(NativeError, "Processing security token")
226 def step(
227 self,
228 in_token: bytes | None = None,
229 *,
230 channel_bindings: GssChannelBindings | None = None,
231 ) -> bytes | None:
232 if not self._is_wrapped:
233 log.debug("SSPI step input: %s", base64.b64encode(in_token or b"").decode())
234
235 sec_tokens: list[sspilib.raw.SecBuffer] = []
236 if in_token:
237 in_token = bytearray(in_token)
238 sec_tokens.append(sspilib.raw.SecBuffer(in_token, sspilib.raw.SecBufferType.SECBUFFER_TOKEN))
239
240 native_channel_bindings: sspilib.SecChannelBindings | None
241 if channel_bindings:
242 native_channel_bindings = self._get_native_bindings(channel_bindings)
243 else:
244 native_channel_bindings = self._native_channel_bindings
245
246 if native_channel_bindings:
247 sec_tokens.append(native_channel_bindings.dangerous_get_sec_buffer())
248
249 in_buffer: sspilib.raw.SecBufferDesc | None = None
250 if sec_tokens:
251 in_buffer = sspilib.raw.SecBufferDesc(sec_tokens)
252
253 out_buffer = sspilib.raw.SecBufferDesc(
254 [
255 sspilib.raw.SecBuffer(None, sspilib.raw.SecBufferType.SECBUFFER_TOKEN),
256 ]
257 )
258
259 context_req: int
260 res: sspilib.raw.InitializeContextResult | sspilib.raw.AcceptContextResult
261 if self.usage == "initiate":
262 context_req = self._context_req | sspilib.IscReq.ISC_REQ_ALLOCATE_MEMORY
263 res = sspilib.raw.initialize_security_context(
264 credential=self._credential,
265 context=self._context,
266 target_name=self.spn or "",
267 context_req=context_req,
268 target_data_rep=sspilib.raw.TargetDataRep.SECURITY_NATIVE_DREP,
269 input_buffers=in_buffer,
270 output_buffers=out_buffer,
271 )
272 status = res.status
273 self._context = res.context
274 else:
275 context_req = self._context_req | sspilib.AscReq.ASC_REQ_ALLOCATE_MEMORY
276 res = sspilib.raw.accept_security_context(
277 credential=self._credential,
278 context=self._context,
279 input_buffers=in_buffer,
280 context_req=context_req,
281 target_data_rep=sspilib.raw.TargetDataRep.SECURITY_NATIVE_DREP,
282 output_buffers=out_buffer,
283 )
284 status = res.status
285 self._context = res.context
286
287 out_token = out_buffer[0].data or None
288
289 self._context_attr = int(res.attributes)
290
291 if status == sspilib.raw.NtStatus.SEC_E_OK:
292 self._complete = True
293
294 attr_sizes = sspilib.raw.query_context_attributes(self._context, sspilib.raw.SecPkgContextSizes)
295 self._block_size = attr_sizes.block_size
296 self._max_signature = attr_sizes.max_signature
297 self._security_trailer = attr_sizes.security_trailer
298
299 if not self._is_wrapped:
300 log.debug("SSPI step output: %s", base64.b64encode(out_token or b"").decode())
301
302 return out_token
303
304 def query_message_sizes(self) -> SecPkgContextSizes:
305 if not self._security_trailer:
306 raise NoContextError(context_msg="Cannot get message sizes until context has been established")
307
308 return SecPkgContextSizes(header=self._security_trailer)
309
310 def wrap(
311 self,
312 data: bytes,
313 encrypt: bool = True,
314 qop: int | None = None,
315 ) -> WrapResult:
316 res = self.wrap_iov([BufferType.header, data, BufferType.padding], encrypt=encrypt, qop=qop)
317 return WrapResult(data=b"".join([r.data for r in res.buffers if r.data]), encrypted=res.encrypted)
318
319 @wrap_system_error(NativeError, "Wrapping IOV buffer")
320 def wrap_iov(
321 self,
322 iov: collections.abc.Iterable[IOV],
323 encrypt: bool = True,
324 qop: int | None = None,
325 ) -> IOVWrapResult:
326 qop = qop or 0
327 if encrypt and qop & sspilib.raw.QopFlags.SECQOP_WRAP_NO_ENCRYPT:
328 raise ValueError("Cannot set qop with SECQOP_WRAP_NO_ENCRYPT and encrypt=True")
329 elif not encrypt:
330 qop |= sspilib.raw.QopFlags.SECQOP_WRAP_NO_ENCRYPT
331
332 buffers = self._build_iov_list(iov, self._convert_iov_buffer)
333 iov_buffer = sspilib.raw.SecBufferDesc(buffers)
334
335 sspilib.raw.encrypt_message(
336 t.cast(sspilib.raw.CtxtHandle, self._context),
337 qop=qop,
338 message=iov_buffer,
339 seq_no=self._seq_num,
340 )
341
342 return IOVWrapResult(buffers=_create_iov_result(iov_buffer), encrypted=encrypt)
343
344 def wrap_winrm(self, data: bytes) -> WinRMWrapResult:
345 iov = self.wrap_iov([BufferType.header, data]).buffers
346 header = iov[0].data or b""
347 enc_data = iov[1].data or b""
348
349 return WinRMWrapResult(header=header, data=enc_data, padding_length=0)
350
351 def unwrap(self, data: bytes) -> UnwrapResult:
352 res = self.unwrap_iov([(BufferType.stream, data), BufferType.data])
353
354 dec_data = res.buffers[1].data or b""
355 return UnwrapResult(data=dec_data, encrypted=res.encrypted, qop=res.qop)
356
357 @wrap_system_error(NativeError, "Unwrapping IOV buffer")
358 def unwrap_iov(
359 self,
360 iov: collections.abc.Iterable[IOV],
361 ) -> IOVUnwrapResult:
362 buffers = self._build_iov_list(iov, self._convert_iov_buffer)
363 iov_buffer = sspilib.raw.SecBufferDesc(buffers)
364
365 qop = sspilib.raw.decrypt_message(
366 t.cast(sspilib.raw.CtxtHandle, self._context),
367 iov_buffer,
368 seq_no=self._seq_num,
369 )
370 encrypted = qop & sspilib.raw.QopFlags.SECQOP_WRAP_NO_ENCRYPT == 0
371
372 return IOVUnwrapResult(buffers=_create_iov_result(iov_buffer), encrypted=encrypted, qop=qop)
373
374 def unwrap_winrm(self, header: bytes, data: bytes) -> bytes:
375 iov = self.unwrap_iov([(BufferType.header, header), data]).buffers
376 return iov[1].data or b""
377
378 @wrap_system_error(NativeError, "Signing message")
379 def sign(
380 self,
381 data: bytes,
382 qop: int | None = None,
383 ) -> bytes:
384 data = bytearray(data)
385 signature = bytearray(self._max_signature)
386 iov = sspilib.raw.SecBufferDesc(
387 [
388 sspilib.raw.SecBuffer(data, sspilib.raw.SecBufferType.SECBUFFER_DATA),
389 sspilib.raw.SecBuffer(signature, sspilib.raw.SecBufferType.SECBUFFER_TOKEN),
390 ]
391 )
392 sspilib.raw.make_signature(
393 t.cast(sspilib.raw.CtxtHandle, self._context),
394 qop or 0,
395 iov,
396 self._seq_num,
397 )
398
399 return iov[1].data
400
401 @wrap_system_error(NativeError, "Verifying message")
402 def verify(self, data: bytes, mic: bytes) -> int:
403 data = bytearray(data)
404 mic = bytearray(mic)
405 iov = sspilib.raw.SecBufferDesc(
406 [
407 sspilib.raw.SecBuffer(data, sspilib.raw.SecBufferType.SECBUFFER_DATA),
408 sspilib.raw.SecBuffer(mic, sspilib.raw.SecBufferType.SECBUFFER_TOKEN),
409 ]
410 )
411
412 return sspilib.raw.verify_signature(
413 t.cast(sspilib.raw.CtxtHandle, self._context),
414 iov,
415 self._seq_num,
416 )
417
418 @property
419 def _context_attr_map(self) -> list[tuple[ContextReq, int]]:
420 # The flags values slightly differ for a initiate and accept context.
421 attr_map = []
422
423 sspi_req: type[int] | None
424 if self.usage == "initiate":
425 attr_map.append((ContextReq.no_integrity, "REQ_NO_INTEGRITY"))
426 sspi_req = sspilib.IscReq
427 sspi_prefix = "ISC"
428 else:
429 sspi_req = sspilib.AscReq
430 sspi_prefix = "ASC"
431
432 attr_map.extend(
433 [
434 # SSPI does not differ between delegate and delegate_policy, it always respects delegate_policy.
435 (ContextReq.delegate, "REQ_DELEGATE"),
436 (ContextReq.delegate_policy, "REQ_DELEGATE"),
437 (ContextReq.mutual_auth, "REQ_MUTUAL_AUTH"),
438 (ContextReq.replay_detect, "REQ_REPLAY_DETECT"),
439 (ContextReq.sequence_detect, "REQ_SEQUENCE_DETECT"),
440 (ContextReq.confidentiality, "REQ_CONFIDENTIALITY"),
441 (ContextReq.integrity, "REQ_INTEGRITY"),
442 (ContextReq.dce_style, "REQ_USE_DCE_STYLE"),
443 (ContextReq.identify, "REQ_IDENTIFY"),
444 ]
445 )
446
447 attrs = []
448 for spnego_flag, gssapi_name in attr_map:
449 attrs.append((spnego_flag, getattr(sspi_req, f"{sspi_prefix}_{gssapi_name}")))
450
451 return attrs
452
453 @property
454 def _seq_num(self) -> int:
455 num = self.__seq_num
456 self.__seq_num += 1
457 return num
458
459 def _convert_iov_buffer(self, buffer: IOVBuffer) -> sspilib.raw.SecBuffer:
460 data = bytearray()
461
462 if isinstance(buffer.data, bytes):
463 data = bytearray(buffer.data)
464 elif isinstance(buffer.data, int) and not isinstance(buffer.data, bool):
465 data = bytearray(buffer.data)
466 else:
467 auto_alloc_size = {
468 BufferType.header: self._security_trailer,
469 BufferType.padding: self._block_size,
470 BufferType.trailer: self._security_trailer,
471 }
472
473 # If alloc wasn't explicitly set, only alloc if the type is a specific auto alloc type.
474 alloc = buffer.data
475 if alloc is None:
476 alloc = buffer.type in auto_alloc_size
477
478 if alloc:
479 if buffer.type not in auto_alloc_size:
480 raise ValueError(
481 "Cannot auto allocate buffer of type %s.%s" % (type(buffer.type).__name__, buffer.type.name)
482 )
483
484 data = bytearray(auto_alloc_size[buffer.type])
485
486 # This buffer types need manual mapping from the generic value to the
487 # one understood by sspilib.
488 buffer_type = int(buffer.type)
489 buffer_flags = 0
490 if buffer_type == BufferType.sign_only:
491 buffer_type = sspilib.raw.SecBufferType.SECBUFFER_DATA
492 buffer_flags = sspilib.raw.SecBufferFlags.SECBUFFER_READONLY_WITH_CHECKSUM
493 elif buffer_type == BufferType.data_readonly:
494 buffer_type = sspilib.raw.SecBufferType.SECBUFFER_DATA
495 buffer_flags = sspilib.raw.SecBufferFlags.SECBUFFER_READONLY
496
497 return sspilib.raw.SecBuffer(data, buffer_type, buffer_flags)
498
499 def _get_native_bindings(
500 self,
501 channel_bindings: GssChannelBindings,
502 ) -> sspilib.SecChannelBindings:
503 """Gets the raw byte value of the SEC_CHANNEL_BINDINGS structure."""
504 return sspilib.SecChannelBindings(
505 initiator_addr_type=int(channel_bindings.initiator_addrtype),
506 initiator_addr=channel_bindings.initiator_address,
507 acceptor_addr_type=int(channel_bindings.acceptor_addrtype),
508 acceptor_addr=channel_bindings.acceptor_address,
509 application_data=channel_bindings.application_data,
510 )