Debian Codegraph @

src/spnego/_spnego.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 struct
6 import typing
7
8 from spnego._asn1 import (
9 TagClass,
10 TypeTagNumber,
11 get_sequence_value,
12 pack_asn1,
13 pack_asn1_bit_string,
14 pack_asn1_enumerated,
15 pack_asn1_general_string,
16 pack_asn1_object_identifier,
17 pack_asn1_octet_string,
18 pack_asn1_sequence,
19 unpack_asn1,
20 unpack_asn1_bit_string,
21 unpack_asn1_enumerated,
22 unpack_asn1_general_string,
23 unpack_asn1_object_identifier,
24 unpack_asn1_octet_string,
25 unpack_asn1_sequence,
26 unpack_asn1_tagged_sequence,
27 )
28 from spnego._context import GSSMech
29 from spnego._kerberos import KerberosV5Msg
30 from spnego._ntlm_raw.messages import NTLMMessage
31
32
33 def pack_mech_type_list(
34 mech_list: typing.Union[str, typing.List[str], typing.Tuple[str, ...], typing.Set[str]],
35 ) -> bytes:
36 """Packs a list of OIDs for the mechListMIC value.
37
38 Will pack a list of object identifiers to the raw byte string value for the mechListMIC.
39
40 Args:
41 mech_list: The list of OIDs to back
42
43 Returns:
44 bytes: The byte string of the packed ASN.1 MechTypeList SEQUENCE OF value.
45 """
46 if not isinstance(mech_list, (list, tuple, set)):
47 mech_list = [mech_list]
48
49 return pack_asn1_sequence([pack_asn1_object_identifier(oid) for oid in mech_list])
50
51
52 def unpack_token(
53 b_data: bytes,
54 mech: typing.Optional[GSSMech] = None,
55 unwrap: bool = False,
56 encoding: typing.Optional[str] = None,
57 ) -> typing.Any:
58 """Unpacks a raw GSSAPI/SPNEGO token to a Python object.
59
60 Unpacks the byte string into a Python object that represents the token passed in. This can return many different
61 token types such as:
62
63 * NTLM message(s)
64 * SPNEGO/Negotiate init or response
65 * Kerberos message(s)
66
67 Args:
68 b_data: The raw byte string to unpack.
69 mech: A hint as to what the byte string is for.
70 unwrap: Whether to unwrap raw bytes to a structured message or return the raw tokens bytes.
71 encoding: Optional encoding used when unwrapping NTLM messages.
72
73 Returns:
74 any: The unpacked SPNEGO, Kerberos, or NTLM token.
75 """
76 # First check if the message is an NTLM message.
77 if b_data.startswith(b"NTLMSSP\x00"):
78 if unwrap:
79 return NTLMMessage.unpack(b_data, encoding=encoding)
80
81 else:
82 return b_data
83
84 if mech and mech.is_kerberos_oid:
85 # A Kerberos value inside an InitialContextToken contains 2 bytes which we ignore.
86 raw_data = unpack_asn1(b_data[2:])[0]
87
88 else:
89 raw_data = unpack_asn1(b_data)[0]
90
91 if raw_data.tag_class == TagClass.application and mech and mech.is_kerberos_oid:
92 return KerberosV5Msg.unpack(unpack_asn1(raw_data.b_data)[0])
93
94 elif raw_data.tag_class == TagClass.application:
95 # The first token is encapsulated in an InitialContextToken.
96 if raw_data.tag_number != 0:
97 raise ValueError("Expecting a tag number of 0 not %s for InitialContextToken" % raw_data.tag_number)
98
99 initial_context_token = InitialContextToken.unpack(raw_data.b_data)
100
101 # unwrap=True is called from python -m spnego and we don't want to loose any info in the output.
102 if unwrap:
103 return initial_context_token
104
105 this_mech: typing.Optional[GSSMech]
106 try:
107 this_mech = GSSMech.from_oid(initial_context_token.this_mech)
108 except ValueError:
109 this_mech = None
110
111 # We currently only support SPNEGO, or raw Kerberos here.
112 if this_mech and (this_mech == GSSMech.spnego or (this_mech.is_kerberos_oid and unwrap)):
113 return unpack_token(initial_context_token.inner_context_token, mech=this_mech)
114
115 return b_data
116
117 elif raw_data.tag_class == TagClass.context_specific:
118 # This is a raw NegotiationToken that is wrapped in a CHOICE or 0 or 1.
119 if raw_data.tag_number == 0:
120 return NegTokenInit.unpack(raw_data.b_data)
121
122 elif raw_data.tag_number == 1:
123 return NegTokenResp.unpack(raw_data.b_data)
124
125 else:
126 raise ValueError("Unknown NegotiationToken CHOICE %d, only expecting 0 or 1" % raw_data.tag_number)
127
128 elif unwrap:
129 # Could also be the ASN.1 Sequence of the Kerberos message.
130 return KerberosV5Msg.unpack(raw_data)
131
132 else:
133 return b_data
134
135
136 # https://www.rfc-editor.org/rfc/rfc4178.html#section-4.2.1 - ContextFlags
137 class ContextFlags(enum.IntFlag):
138 deleg = 0
139 mutual = 1
140 replay = 2
141 sequence = 3
142 anon = 4
143 conf = 5
144 integ = 6
145
146 @classmethod
147 def native_labels(cls) -> typing.Dict["ContextFlags", str]:
148 return {
149 ContextFlags.deleg: "delegFlag",
150 ContextFlags.mutual: "mutualFlag",
151 ContextFlags.replay: "replayFlag",
152 ContextFlags.sequence: "sequenceFlag",
153 ContextFlags.anon: "anonFlag",
154 ContextFlags.conf: "confFlag",
155 ContextFlags.integ: "integFlag",
156 }
157
158
159 # https://www.rfc-editor.org/rfc/rfc4178.html#section-4.2.2 - negState
160 class NegState(enum.IntEnum):
161 accept_complete = 0
162 accept_incomplete = 1
163 reject = 2
164 request_mic = 3
165
166 @classmethod
167 def native_labels(cls) -> typing.Dict["NegState", str]:
168 return {
169 NegState.accept_complete: "accept-complete",
170 NegState.accept_incomplete: "accept-incomplete",
171 NegState.reject: "reject",
172 NegState.request_mic: "request-mic",
173 }
174
175
176 class InitialContextToken:
177 """GSSAPI InitialContextToken object.
178
179 The InitialContextToken is the ASN.1 structure that contains the first GSSAPI token that is sent across the wire.
180 The ASN.1 definition for this structure is defined in `RFC 2743 3.1`_::
181
182 MechType ::= OBJECT IDENTIFIER
183 -- data structure definitions
184 -- callers must be able to distinguish among
185 -- InitialContextToken, SubsequentContextToken,
186 -- PerMsgToken, and SealedMessage data elements
187 -- based on the usage in which they occur
188
189 InitialContextToken ::=
190 -- option indication (delegation, etc.) indicated within
191 -- mechanism-specific token
192 [APPLICATION 0] IMPLICIT SEQUENCE {
193 thisMech MechType,
194 innerContextToken ANY DEFINED BY thisMech
195 -- contents mechanism-specific
196 -- ASN.1 structure not required
197 }
198
199 Args:
200 mech: The OID that defines the structure of the `token`.
201 token: The token of the GSSAPI value.
202
203 Attributes:
204 this_mech (str): The object identifier that identifies what the inner_context_token is for.
205 inner_context_token (bytes): The token value as defined by `this_mech`.
206
207 .. _RFC 2743 3.1:
208 https://www.rfc-editor.org/rfc/rfc2743#section-3.1.
209 """
210
211 def __init__(self, mech: typing.Union[GSSMech, str], token: bytes) -> None:
212 if isinstance(mech, GSSMech):
213 mech = mech.value
214
215 self.this_mech = mech
216 self.inner_context_token = token
217
218 @property
219 def token(self) -> typing.Any:
220 mech: typing.Optional[GSSMech]
221 try:
222 mech = GSSMech.from_oid(self.this_mech)
223 except ValueError:
224 mech = None
225
226 return unpack_token(self.inner_context_token, mech=mech)
227
228 def pack(self) -> bytes:
229 """Packs the InitialContextToken as a byte string."""
230 return pack_asn1(
231 TagClass.application,
232 True,
233 0,
234 pack_asn1_object_identifier(self.this_mech, tag=True) + self.inner_context_token,
235 )
236
237 @staticmethod
238 def unpack(b_data: bytes) -> "InitialContextToken":
239 """Unpacks the InitialContextToken TLV value."""
240 this_mech, inner_context_token = unpack_asn1(b_data)
241 mech = unpack_asn1_object_identifier(this_mech)
242
243 return InitialContextToken(mech, inner_context_token)
244
245
246 class NegTokenInit:
247 """The NegTokenInit GSSAPI value.
248
249 This is the initial negotiation message token in a GSSAPI exchange. Typically the `NegTokenInit` value is sent
250 when sending the first authentication token. The `NegTokenInit2` token is an extension that adds the `negHints`
251 field. Unfortunately as the tag number for the `mechListMIC` is the same for `negHints` unpacking the value
252 requires some extra checks.
253
254 The ASN.1 definition for the NegTokenInit structure is defined in `RFC 4178 4.2.1`_::
255
256 NegTokenInit ::= SEQUENCE {
257 mechTypes [0] MechTypeList,
258 reqFlags [1] ContextFlags OPTIONAL,
259 -- inherited from RFC 2478 for backward compatibility,
260 -- RECOMMENDED to be left out
261 mechToken [2] OCTET STRING OPTIONAL,
262 mechListMIC [3] OCTET STRING OPTIONAL,
263 ...
264 }
265 ContextFlags ::= BIT STRING {
266 delegFlag (0),
267 mutualFlag (1),
268 replayFlag (2),
269 sequenceFlag (3),
270 anonFlag (4),
271 confFlag (5),
272 integFlag (6)
273 } (SIZE (32))
274
275 The ASN.1 definition for the `NegTokenInit2`_ structure is defined as::
276
277 NegHints ::= SEQUENCE {
278 hintName[0] GeneralString OPTIONAL,
279 hintAddress[1] OCTET STRING OPTIONAL
280 }
281 NegTokenInit2 ::= SEQUENCE {
282 mechTypes[0] MechTypeList OPTIONAL,
283 reqFlags [1] ContextFlags OPTIONAL,
284 mechToken [2] OCTET STRING OPTIONAL,
285 negHints [3] NegHints OPTIONAL,
286 mechListMIC [4] OCTET STRING OPTIONAL,
287 ...
288 }
289
290 Args:
291 mech_types: One or more security mechanisms available for the initiator, in decreasing preference order.
292 req_flags: Should be omitted, service options that are requested to establish the context.
293 mech_token: Contains the optimistic mechanism token.
294 hint_name: Used for the NegTokenInit2 structure only, should be omitted.
295 hint_address: Used for the NegTokenINit2 structure only, should be omitted.
296 mech_list_mic: The message integrity code (MIC) token.
297
298 Attributes:
299 mech_types (List[str]): See args.
300 req_flags (ContextFlags): See args.
301 mech_token (bytes): See args.
302 hint_name (bytes): See args.
303 hint_address (bytes): See args.
304 mech_list_mic (bytes): See args.
305
306 .. _RFC 4178 4.2.1:
307 https://www.rfc-editor.org/rfc/rfc4178.html#section-4.2.1
308
309 .. _NegTokenInit2:
310 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-spng/8e71cf53-e867-4b79-b5b5-38c92be3d472
311 """
312
313 def __init__(
314 self,
315 mech_types: typing.Optional[typing.List[str]] = None,
316 req_flags: typing.Optional[ContextFlags] = None,
317 mech_token: typing.Optional[bytes] = None,
318 hint_name: typing.Optional[bytes] = None,
319 hint_address: typing.Optional[bytes] = None,
320 mech_list_mic: typing.Optional[bytes] = None,
321 ) -> None:
322 self.mech_types = mech_types or []
323 self.req_flags = req_flags
324 self.mech_token = mech_token
325 self.hint_name = hint_name
326 self.hint_address = hint_address
327 self.mech_list_mic = mech_list_mic
328
329 def pack(self) -> bytes:
330 """Packs the NegTokenInit as a byte string."""
331
332 def pack_elements(
333 value_map: typing.Iterable[typing.Tuple[int, typing.Any, typing.Callable]],
334 ) -> typing.List[bytes]:
335 elements = []
336 for tag, value, pack_func in value_map:
337 if value is not None:
338 elements.append(pack_asn1(TagClass.context_specific, True, tag, pack_func(value)))
339
340 return elements
341
342 req_flags = struct.pack("B", self.req_flags) if self.req_flags is not None else None
343 base_map: typing.List[typing.Tuple[int, typing.Any, typing.Callable]] = [
344 (0, self.mech_types, pack_mech_type_list),
345 (1, req_flags, pack_asn1_bit_string),
346 (2, self.mech_token, pack_asn1_octet_string),
347 ]
348
349 # The placement of the mechListMIC is dependent on whether we are packing a NegTokenInit with or without the
350 # negHints field.
351 neg_hints = pack_elements(
352 [
353 (0, self.hint_name, pack_asn1_general_string),
354 (1, self.hint_address, pack_asn1_octet_string),
355 ]
356 )
357
358 if neg_hints:
359 base_map.append((3, neg_hints, pack_asn1_sequence))
360 base_map.append((4, self.mech_list_mic, pack_asn1_octet_string))
361
362 else:
363 base_map.append((3, self.mech_list_mic, pack_asn1_octet_string))
364
365 init_sequence = pack_elements(base_map)
366
367 # The NegTokenInit will always be wrapped in an InitialContextToken -> NegotiationToken - CHOICE 0.
368 b_data = pack_asn1_sequence(init_sequence)
369 return InitialContextToken(GSSMech.spnego.value, pack_asn1(TagClass.context_specific, True, 0, b_data)).pack()
370
371 @staticmethod
372 def unpack(b_data: bytes) -> "NegTokenInit":
373 """Unpacks the NegTokenInit TLV value."""
374 neg_seq = unpack_asn1_tagged_sequence(unpack_asn1(b_data)[0])
375
376 mech_types = [
377 unpack_asn1_object_identifier(m)
378 for m in get_sequence_value(neg_seq, 0, "NegTokenInit", "mechTypes", unpack_asn1_sequence) or []
379 ]
380
381 req_flags = get_sequence_value(neg_seq, 1, "NegTokenInit", "reqFlags", unpack_asn1_bit_string)
382 if req_flags:
383 # Can be up to 32 bits in length but RFC 4178 states "Implementations should not expect to receive exactly
384 # 32 bits in an encoding of ContextFlags." The spec also documents req flags up to 6 so let's just get the
385 # last byte. In reality we shouldn't ever receive this but it's left here for posterity.
386 req_flags = ContextFlags(bytearray(req_flags)[-1])
387
388 mech_token = get_sequence_value(neg_seq, 2, "NegTokenInit", "mechToken", unpack_asn1_octet_string)
389
390 hint_name = hint_address = mech_list_mic = None
391 if 3 in neg_seq:
392 # Microsoft helpfully sends a NegTokenInit2 payload which sets 'negHints [3] NegHints OPTIONAL' and the
393 # mechListMIC is actually at the 4th sequence entry. Because the NegTokenInit2 has the same choice in
394 # NegotiationToken as NegTokenInit ([0]) we can only differentiate when unpacking based on the class/tags.
395 tag_class = neg_seq[3].tag_class
396 tag_number = neg_seq[3].tag_number
397
398 if tag_class == TagClass.universal and tag_number == TypeTagNumber.sequence:
399 neg_hints = unpack_asn1_tagged_sequence(neg_seq[3].b_data)
400
401 # Windows 2000, 2003, and XP put the SPN encoded as the OEM code page, because there's no sane way
402 # to decode this without prior knowledge a GeneralString stays a byte string in Python.
403 # https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-spng/211417c4-11ef-46c0-a8fb-f178a51c2088#Appendix_A_5
404 hint_name = get_sequence_value(neg_hints, 0, "NegHints", "hintName", unpack_asn1_general_string)
405 hint_address = get_sequence_value(neg_hints, 1, "NegHints", "hintAddress", unpack_asn1_octet_string)
406
407 else:
408 # Wasn't a sequence, should be mechListMIC.
409 mech_list_mic = get_sequence_value(neg_seq, 3, "NegTokenInit", "mechListMIC", unpack_asn1_octet_string)
410
411 if not mech_list_mic:
412 mech_list_mic = get_sequence_value(neg_seq, 4, "NegTokenInit2", "mechListMIC", unpack_asn1_octet_string)
413
414 return NegTokenInit(mech_types, req_flags, mech_token, hint_name, hint_address, mech_list_mic)
415
416
417 class NegTokenResp:
418 """The NegTokenResp GSSAPI value.
419
420 This is the message token in a GSSAPI exchange that is used for subsequent messages after the `NegTokenInit` has
421 been exchanged.
422
423 The ASN.1 definition for the NegTokenResp structure is defined in `RFC 4178 4.2.2`_::
424
425 NegTokenResp ::= SEQUENCE {
426 negState [0] ENUMERATED {
427 accept-completed (0),
428 accept-incomplete (1),
429 reject (2),
430 request-mic (3)
431 } OPTIONAL,
432 -- REQUIRED in the first reply from the target
433 supportedMech [1] MechType OPTIONAL,
434 -- present only in the first reply from the target
435 responseToken [2] OCTET STRING OPTIONAL,
436 mechListMIC [3] OCTET STRING OPTIONAL,
437 ...
438 }
439
440 Args:
441 neg_state: The state of the negotiation.
442 supported_mech: Should only be present in the first reply, must be one of the mech(s) offered by the initiator.
443 response_token: Contains the token specific to the mechanism selected.
444 mech_list_mic: The message integrity code (MIC) token.
445
446 Attributes:
447 neg_state (NegState): See args.
448 supported_mech (str): See args.
449 response_token (bytes): See args.
450 mech_list_mic (bytes): See args.
451
452 .. _RFC 4178 4.2.2:
453 https://www.rfc-editor.org/rfc/rfc4178.html#section-4.2.2
454 """
455
456 def __init__(
457 self,
458 neg_state: typing.Optional[NegState] = None,
459 supported_mech: typing.Optional[str] = None,
460 response_token: typing.Optional[bytes] = None,
461 mech_list_mic: typing.Optional[bytes] = None,
462 ) -> None:
463 self.neg_state = neg_state
464 self.supported_mech = supported_mech
465 self.response_token = response_token
466 self.mech_list_mic = mech_list_mic
467
468 def pack(self) -> bytes:
469 """Packs the NegTokenResp as a byte string."""
470 value_map: typing.List[typing.Tuple[int, typing.Any, typing.Callable[[typing.Any], bytes]]] = [
471 (0, self.neg_state, pack_asn1_enumerated),
472 (1, self.supported_mech, pack_asn1_object_identifier),
473 (2, self.response_token, pack_asn1_octet_string),
474 (3, self.mech_list_mic, pack_asn1_octet_string),
475 ]
476 elements = []
477 for tag, value, pack_func in value_map:
478 if value is not None:
479 elements.append(pack_asn1(TagClass.context_specific, True, tag, pack_func(value)))
480
481 # The NegTokenResp will always be wrapped NegotiationToken - CHOICE 1.
482 b_data = pack_asn1_sequence(elements)
483 return pack_asn1(TagClass.context_specific, True, 1, b_data)
484
485 @staticmethod
486 def unpack(b_data: bytes) -> "NegTokenResp":
487 """Unpacks the NegTokenResp TLV value."""
488 neg_seq = unpack_asn1_tagged_sequence(unpack_asn1(b_data)[0])
489
490 neg_state = get_sequence_value(neg_seq, 0, "NegTokenResp", "negState", unpack_asn1_enumerated)
491 if neg_state is not None:
492 neg_state = NegState(neg_state)
493
494 supported_mech = get_sequence_value(neg_seq, 1, "NegTokenResp", "supportedMech", unpack_asn1_object_identifier)
495 response_token = get_sequence_value(neg_seq, 2, "NegTokenResp", "responseToken", unpack_asn1_octet_string)
496 mech_list_mic = get_sequence_value(neg_seq, 3, "NegTokenResp", "mechListMIC", unpack_asn1_octet_string)
497
498 return NegTokenResp(neg_state, supported_mech, response_token, mech_list_mic)