Debian Codegraph @

src/spnego/_ntlm_raw/messages.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 collections
5 import datetime
6 import enum
7 import io
8 import re
9 import struct
10 import typing
11
12 from spnego._text import to_text
13 from spnego._version import __version__ as pyspnego_version
14
15
16 class NegotiateFlags(enum.IntFlag):
17 """NTLM Negotiation flags.
18
19 Used during NTLM negotiation to negotiate the capabilities between the client and server.
20
21 .. _NEGOTIATE:
22 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/99d90ff4-957f-4c8a-80e4-5bfe5a9a9832
23 """
24
25 key_56 = 0x80000000
26 key_exch = 0x40000000
27 key_128 = 0x20000000
28 r1 = 0x10000000
29 r2 = 0x08000000
30 r3 = 0x04000000
31 version = 0x02000000
32 r4 = 0x01000000
33 target_info = 0x00800000
34 non_nt_session_key = 0x00400000
35 r5 = 0x00200000
36 identity = 0x00100000
37 extended_session_security = 0x00080000
38 target_type_share = 0x00040000 # Not documented in MS-NLMP
39 target_type_server = 0x00020000
40 target_type_domain = 0x00010000
41 always_sign = 0x00008000
42 local_call = 0x00004000 # Not documented in MS-NLMP
43 oem_workstation_supplied = 0x00002000
44 oem_domain_name_supplied = 0x00001000
45 anonymous = 0x00000800
46 r8 = 0x00000400
47 ntlm = 0x00000200
48 r9 = 0x00000100
49 lm_key = 0x00000080
50 datagram = 0x00000040
51 seal = 0x00000020
52 sign = 0x00000010
53 netware = 0x00000008 # Not documented in MS-NLMP
54 request_target = 0x00000004
55 oem = 0x00000002
56 unicode = 0x00000001
57
58 @classmethod
59 def native_labels(cls) -> typing.Dict["NegotiateFlags", str]:
60 return {
61 NegotiateFlags.key_56: "NTLMSSP_NEGOTIATE_56",
62 NegotiateFlags.key_exch: "NTLMSSP_NEGOTIATE_KEY_EXCH",
63 NegotiateFlags.key_128: "NTLMSSP_NEGOTIATE_128",
64 NegotiateFlags.r1: "NTLMSSP_RESERVED_R1",
65 NegotiateFlags.r2: "NTLMSSP_RESERVED_R2",
66 NegotiateFlags.r3: "NTLMSSP_RESERVED_R3",
67 NegotiateFlags.version: "NTLMSSP_NEGOTIATE_VERSION",
68 NegotiateFlags.r4: "NTLMSSP_RESERVED_R4",
69 NegotiateFlags.target_info: "NTLMSSP_NEGOTIATE_TARGET_INFO",
70 NegotiateFlags.non_nt_session_key: "NTLMSSP_REQUEST_NON_NT_SESSION_KEY",
71 NegotiateFlags.r5: "NTLMSSP_RESERVED_R5",
72 NegotiateFlags.identity: "NTLMSSP_NEGOTIATE_IDENTITY",
73 NegotiateFlags.extended_session_security: "NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY",
74 NegotiateFlags.target_type_share: "NTLMSSP_TARGET_TYPE_SHARE - R6",
75 NegotiateFlags.target_type_server: "NTLMSSP_TARGET_TYPE_SERVER",
76 NegotiateFlags.target_type_domain: "NTLMSSP_TARGET_TYPE_DOMAIN",
77 NegotiateFlags.always_sign: "NTLMSSP_NEGOTIATE_ALWAYS_SIGN",
78 NegotiateFlags.local_call: "NTLMSSP_NEGOTIATE_LOCAL_CALL - R7",
79 NegotiateFlags.oem_workstation_supplied: "NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED",
80 NegotiateFlags.oem_domain_name_supplied: "NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED",
81 NegotiateFlags.anonymous: "NTLMSSP_ANOYNMOUS",
82 NegotiateFlags.r8: "NTLMSSP_RESERVED_R8",
83 NegotiateFlags.ntlm: "NTLMSSP_NEGOTIATE_NTLM",
84 NegotiateFlags.r9: "NTLMSSP_RESERVED_R9",
85 NegotiateFlags.lm_key: "NTLMSSP_NEGOTIATE_LM_KEY",
86 NegotiateFlags.datagram: "NTLMSSP_NEGOTIATE_DATAGRAM",
87 NegotiateFlags.seal: "NTLMSSP_NEGOTIATE_SEAL",
88 NegotiateFlags.sign: "NTLMSSP_NEGOTIATE_SIGN",
89 NegotiateFlags.netware: "NTLMSSP_NEGOTIATE_NETWARE - R10",
90 NegotiateFlags.request_target: "NTLMSSP_REQUEST_TARGET",
91 NegotiateFlags.oem: "NTLMSSP_NEGOTIATE_OEM",
92 NegotiateFlags.unicode: "NTLMSSP_NEGOTIATE_UNICODE",
93 }
94
95
96 class AvId(enum.IntFlag):
97 """ID for an NTLM AV_PAIR.
98
99 These are the IDs that can be set as the `AvId` on an `AV_PAIR`_.
100
101 .. _AV_PAIR:
102 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/83f5e789-660d-4781-8491-5f8c6641f75e
103 """
104
105 eol = 0x0000
106 nb_computer_name = 0x0001
107 nb_domain_name = 0x0002
108 dns_computer_name = 0x0003
109 dns_domain_name = 0x0004
110 dns_tree_name = 0x0005
111 flags = 0x0006
112 timestamp = 0x0007
113 single_host = 0x0008
114 target_name = 0x0009
115 channel_bindings = 0x000A
116
117 @classmethod
118 def native_labels(cls) -> typing.Dict["AvId", str]:
119 return {
120 AvId.eol: "MSV_AV_EOL",
121 AvId.nb_computer_name: "MSV_AV_NB_COMPUTER_NAME",
122 AvId.nb_domain_name: "MSV_AV_NB_DOMAIN_NAME",
123 AvId.dns_computer_name: "MSV_AV_DNS_COMPUTER_NAME",
124 AvId.dns_domain_name: "MSV_AV_DNS_DOMAIN_NAME",
125 AvId.dns_tree_name: "MSV_AV_DNS_TREE_NAME",
126 AvId.flags: "MSV_AV_FLAGS",
127 AvId.timestamp: "MSV_AV_TIMESTAMP",
128 AvId.single_host: "MSV_AV_SINGLE_HOST",
129 AvId.target_name: "MSV_AV_TARGET_NAME",
130 AvId.channel_bindings: "MSV_AV_CHANNEL_BINDINGS",
131 }
132
133
134 class AvFlags(enum.IntFlag):
135 """MsvAvFlags for an AV_PAIR.
136
137 These are the flags that can be set on the MsvAvFlags entry of an NTLM `AV_PAIR`_.
138
139 .. _AV_PAIR:
140 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/83f5e789-660d-4781-8491-5f8c6641f75e
141 """
142
143 none = 0x00000000
144 constrained = 0x00000001
145 mic = 0x00000002
146 untrusted_spn = 0x00000004
147
148 @classmethod
149 def native_labels(cls) -> typing.Dict["AvFlags", str]:
150 return {
151 AvFlags.constrained: "AUTHENTICATION_CONSTRAINED",
152 AvFlags.mic: "MIC_PROVIDED",
153 AvFlags.untrusted_spn: "UNTRUSTED_SPN_SOURCE",
154 }
155
156
157 class MessageType(enum.IntEnum):
158 negotiate = 1
159 challenge = 2
160 authenticate = 3
161
162 @classmethod
163 def native_labels(cls) -> typing.Dict["MessageType", str]:
164 return {
165 MessageType.negotiate: "NEGOTIATE_MESSAGE",
166 MessageType.challenge: "CHALLENGE_MESSAGE",
167 MessageType.authenticate: "AUTHENTICATE_MESSAGE",
168 }
169
170
171 def _get_payload_offset(b_data: memoryview, field_offsets: typing.List[int]) -> int:
172 payload_offset = None
173
174 for field_offset in field_offsets:
175 offset = struct.unpack("<I", b_data[field_offset + 4 : field_offset + 8].tobytes())[0]
176 if not payload_offset or (offset and offset < payload_offset):
177 payload_offset = offset
178
179 return payload_offset or len(b_data)
180
181
182 def _pack_payload(
183 data: typing.Any,
184 b_payload: bytearray,
185 payload_offset: int,
186 pack_func: typing.Optional[typing.Callable[[typing.Any], bytes]] = None,
187 ) -> typing.Tuple[bytes, int]:
188 if data:
189 b_data = pack_func(data) if pack_func else data
190 else:
191 b_data = b""
192
193 b_payload.extend(b_data)
194 length = len(b_data)
195
196 b_field = (struct.pack("<H", length) * 2) + struct.pack("<I", payload_offset)
197 payload_offset += length
198
199 return b_field, payload_offset
200
201
202 def _unpack_payload(
203 b_data: memoryview,
204 field_offset: int,
205 unpack_func: typing.Optional[typing.Callable[[bytes], typing.Any]] = None,
206 ) -> typing.Any:
207 field_len = struct.unpack("<H", b_data[field_offset : field_offset + 2].tobytes())[0]
208 if field_len:
209 field_offset = struct.unpack("<I", b_data[field_offset + 4 : field_offset + 8].tobytes())[0]
210 b_value = b_data[field_offset : field_offset + field_len].tobytes()
211
212 return unpack_func(b_value) if unpack_func else b_value
213
214
215 class _NTLMMessageMeta(type):
216 __registry: typing.Dict[int, typing.Type] = {}
217
218 def __init__(
219 cls,
220 *args: typing.Any,
221 **kwargs: typing.Any,
222 ) -> None:
223 cls.__registry[getattr(cls, "MESSAGE_TYPE", 0)] = cls
224
225 def __call__(
226 cls,
227 *args: typing.Any,
228 **kwargs: typing.Any,
229 ) -> "_NTLMMessageMeta":
230 if "_b_data" in kwargs:
231 message_type = struct.unpack("<I", kwargs["_b_data"][8:12])[0]
232 new_cls = cls.__registry[message_type]
233
234 else:
235 new_cls = cls
236
237 return super(_NTLMMessageMeta, new_cls).__call__(*args, **kwargs)
238
239
240 class NTLMMessage(metaclass=_NTLMMessageMeta):
241 """Base NTLM message class that defines the pack and unpack functions."""
242
243 MESSAGE_TYPE = 0
244 MINIMUM_LENGTH = 0
245
246 def __init__(self, encoding: typing.Optional[str] = None, _b_data: typing.Optional[bytes] = None) -> None:
247 self.signature = b"NTLMSSP\x00" + struct.pack("<I", self.MESSAGE_TYPE)
248 self._encoding = encoding or "windows-1252"
249
250 if _b_data:
251 if len(_b_data) < self.MINIMUM_LENGTH:
252 raise ValueError("Invalid NTLM %s raw byte length" % self.__class__.__name__)
253
254 self._data = memoryview(bytearray(_b_data))
255
256 else:
257 self._data = memoryview(b"")
258
259 def pack(self) -> bytes:
260 """Packs the structure to bytes."""
261 return self._data.tobytes()
262
263 @staticmethod
264 def unpack(b_data: bytes, encoding: typing.Optional[str] = None) -> "NTLMMessage":
265 """Unpacks the structure from bytes."""
266 return NTLMMessage(encoding=encoding, _b_data=b_data)
267
268
269 class Negotiate(NTLMMessage):
270 """NTLM Negotiate Message
271
272 This structure represents an NTLM `NEGOTIATE_MESSAGE`_ that can be serialized and deserialized to and from
273 bytes.
274
275 Args:
276 flags: The `NegotiateFlags` that the client has negotiated.
277 domain_name: The `DomainName` of the client authentication domain.
278 workstation: The `Workstation` of the client.
279 version: The `Version` of the client.
280 encoding: The OEM encoding to use for text fields.
281 _b_data: The raw bytes of the message to unpack from.
282
283 .. _NEGOTIATE_MESSAGE:
284 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/b34032e5-3aae-4bc6-84c3-c6d80eadf7f2
285 """
286
287 MESSAGE_TYPE = MessageType.negotiate
288 MINIMUM_LENGTH = 32
289
290 def __init__(
291 self,
292 flags: int = 0,
293 domain_name: typing.Optional[str] = None,
294 workstation: typing.Optional[str] = None,
295 version: typing.Optional["Version"] = None,
296 encoding: typing.Optional[str] = None,
297 _b_data: typing.Optional[bytes] = None,
298 ) -> None:
299 super(Negotiate, self).__init__(encoding=encoding, _b_data=_b_data)
300
301 if not _b_data:
302 b_payload = bytearray()
303
304 payload_offset = 32
305
306 b_version = b""
307 if version:
308 flags |= NegotiateFlags.version
309 b_version = version.pack()
310 payload_offset = _pack_payload(b_version, b_payload, payload_offset)[1]
311
312 b_domain_name = b""
313 if domain_name:
314 flags |= NegotiateFlags.oem_domain_name_supplied
315 b_domain_name = domain_name.encode(self._encoding)
316 b_domain_name_fields, payload_offset = _pack_payload(b_domain_name, b_payload, payload_offset)
317
318 b_workstation = b""
319 if workstation:
320 flags |= NegotiateFlags.oem_workstation_supplied
321 b_workstation = workstation.encode(self._encoding)
322 b_workstation_fields = _pack_payload(b_workstation, b_payload, payload_offset)[0]
323
324 b_data = bytearray(self.signature)
325 b_data.extend(struct.pack("<I", flags))
326 b_data.extend(b_domain_name_fields)
327 b_data.extend(b_workstation_fields)
328 b_data.extend(b_payload)
329
330 self._data = memoryview(b_data)
331
332 @property
333 def flags(self) -> int:
334 """The negotiate flags for the Negotiate message."""
335 return struct.unpack("<I", self._data[12:16].tobytes())[0]
336
337 @flags.setter
338 def flags(self, value: int) -> None:
339 self._data[12:16] = struct.pack("<I", value)
340
341 @property
342 def domain_name(self) -> typing.Optional[str]:
343 """The name of the client authentication domain."""
344 return to_text(_unpack_payload(self._data, 16), encoding=self._encoding, errors="replace", nonstring="passthru")
345
346 @property
347 def workstation(self) -> typing.Optional[str]:
348 """The name of the client machine."""
349 return to_text(_unpack_payload(self._data, 24), encoding=self._encoding, errors="replace", nonstring="passthru")
350
351 @property
352 def version(self) -> typing.Optional["Version"]:
353 """The client NTLM version."""
354 payload_offset = self._payload_offset
355
356 # If the payload offset is at 40 or more then the Version, or at least empty bytes, is in the payload.
357 if payload_offset >= 40:
358 return Version.unpack(self._data[32:40].tobytes())
359
360 else:
361 return None
362
363 @property
364 def _payload_offset(self) -> int:
365 """Gets the offset of the first payload value."""
366 return _get_payload_offset(self._data, [16, 24])
367
368 @staticmethod
369 def unpack(b_data: bytes, encoding: typing.Optional[str] = None) -> "Negotiate":
370 msg = NTLMMessage.unpack(b_data, encoding=encoding)
371 if not isinstance(msg, Negotiate):
372 raise ValueError("Input message was not a NTLM Negotiate message")
373
374 return msg
375
376
377 class Challenge(NTLMMessage):
378 """NTLM Challenge Message
379
380 This structure represents an NTLM `CHALLENGE_MESSAGE`_ that can be serialized and deserialized to and from
381 bytes.
382
383 Args:
384 flags: The `NegotiateFlags` that the client has negotiated.
385 server_challenge: The random 64-bit `ServerChallenge` nonce.
386 target_name: The name of the acceptor server.
387 target_info: The variable length `TargetInfo` information.
388 version: The `Version` of the server.
389 encoding: The OEM encoding to use for text fields if `NTLMSSP_NEGOTIATE_UNICODE` was not supported.
390 _b_data: The raw NTLM Challenge bytes to unpack from.
391
392 .. _CHALLENGE_MESSAGE:
393 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/801a4681-8809-4be9-ab0d-61dcfe762786
394 """
395
396 MESSAGE_TYPE = MessageType.challenge
397 MINIMUM_LENGTH = 48
398
399 def __init__(
400 self,
401 flags: int = 0,
402 server_challenge: typing.Optional[bytes] = None,
403 target_name: typing.Optional[str] = None,
404 target_info: typing.Optional["TargetInfo"] = None,
405 version: typing.Optional["Version"] = None,
406 encoding: typing.Optional[str] = None,
407 _b_data: typing.Optional[bytes] = None,
408 ):
409 super(Challenge, self).__init__(encoding=encoding, _b_data=_b_data)
410
411 if _b_data:
412 self._encoding = "utf-16-le" if self.flags & NegotiateFlags.unicode else self._encoding
413
414 else:
415 self._encoding = "utf-16-le" if flags & NegotiateFlags.unicode else self._encoding
416
417 b_payload = bytearray()
418 payload_offset = 48
419
420 b_version = b""
421 if version:
422 flags |= NegotiateFlags.version
423 b_version = version.pack()
424 payload_offset = _pack_payload(b_version, b_payload, payload_offset)[1]
425
426 b_target_name = b""
427 if target_name:
428 flags |= NegotiateFlags.request_target
429 b_target_name = target_name.encode(self._encoding)
430 b_target_name_fields, payload_offset = _pack_payload(b_target_name, b_payload, payload_offset)
431
432 b_target_info = b""
433 if target_info:
434 flags |= NegotiateFlags.target_info
435 b_target_info = target_info.pack()
436 b_target_info_fields = _pack_payload(b_target_info, b_payload, payload_offset)[0]
437
438 b_data = bytearray(self.signature)
439 b_data.extend(b_target_name_fields)
440 b_data.extend(struct.pack("<I", flags))
441 b_data.extend(b"\x00" * 8) # ServerChallenge, set after self._data is initialised.
442 b_data.extend(b"\x00" * 8) # Reserved
443 b_data.extend(b_target_info_fields)
444 b_data.extend(b_payload)
445
446 self._data = memoryview(b_data)
447
448 if server_challenge:
449 self.server_challenge = server_challenge
450
451 @property
452 def target_name(self) -> typing.Optional[str]:
453 """The name of the server authentication realm."""
454 return to_text(_unpack_payload(self._data, 12), encoding=self._encoding, nonstring="passthru")
455
456 @property
457 def flags(self) -> int:
458 """The negotiate flags supported by the server."""
459 return struct.unpack("<I", self._data[20:24].tobytes())[0]
460
461 @flags.setter
462 def flags(self, value: int) -> None:
463 self._data[20:24] = struct.pack("<I", value)
464
465 @property
466 def server_challenge(self) -> bytes:
467 """The server's 8 byte nonce challenge."""
468 return self._data[24:32].tobytes()
469
470 @server_challenge.setter
471 def server_challenge(self, value: bytes) -> None:
472 if not value or len(value) != 8:
473 raise ValueError("NTLM Challenge ServerChallenge must be 8 bytes long")
474
475 self._data[24:32] = value
476
477 @property
478 def target_info(self) -> typing.Optional["TargetInfo"]:
479 """The AV_PAIR structures generated by the server."""
480 return _unpack_payload(self._data, 40, lambda d: TargetInfo.unpack(d))
481
482 @property
483 def version(self) -> typing.Optional["Version"]:
484 """The server NTLM version."""
485 payload_offset = self._payload_offset
486
487 # If the payload offset is at 56 or more then the Version, or at least empty bytes, is in the payload.
488 if payload_offset >= 56:
489 return Version.unpack(self._data[48:56].tobytes())
490
491 else:
492 return None
493
494 @property
495 def _payload_offset(self) -> int:
496 """Gets the offset of the first payload value."""
497 return _get_payload_offset(self._data, [12, 40])
498
499 @staticmethod
500 def unpack(b_data: bytes, encoding: typing.Optional[str] = None) -> "Challenge":
501 msg = NTLMMessage.unpack(b_data, encoding=encoding)
502 if not isinstance(msg, Challenge):
503 raise ValueError("Input message was not a NTLM Challenge message")
504
505 return msg
506
507
508 class Authenticate(NTLMMessage):
509 """NTLM Authentication Message
510
511 This structure represents an NTLM `AUTHENTICATION_MESSAGE`_ that can be serialized and deserialized to and from
512 bytes.
513
514 Args:
515 flags: The `NegotiateFlags` that the client has negotiated.
516 lm_challenge_response: The `LmChallengeResponse` for the client's secret.
517 nt_challenge_response: The `NtChallengeResponse` for the client's secret.
518 domain_name: The `DomainName` for the client.
519 username: The `UserName` for the cleint.
520 workstation: The `Workstation` for the client.
521 encrypted_session_key: The `EncryptedRandomSessionKey` for the set up context.
522 version: The `Version` of the client.
523 mic: The `MIC` for the authentication exchange.
524 encoding: The OEM encoding to use for text fields if `NTLMSSP_NEGOTIATE_UNICODE` was not supported.
525 _b_data: The raw NTLM Authenticate bytes to unpack from.
526
527 .. _AUTHENTICATION_MESSAGE:
528 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/033d32cc-88f9-4483-9bf2-b273055038ce
529 """
530
531 MESSAGE_TYPE = MessageType.authenticate
532 MINIMUM_LENGTH = 64
533
534 def __init__(
535 self,
536 flags: int = 0,
537 lm_challenge_response: typing.Optional[bytes] = None,
538 nt_challenge_response: typing.Optional[bytes] = None,
539 domain_name: typing.Optional[str] = None,
540 username: typing.Optional[str] = None,
541 workstation: typing.Optional[str] = None,
542 encrypted_session_key: typing.Optional[bytes] = None,
543 version: typing.Optional["Version"] = None,
544 mic: typing.Optional[bytes] = None,
545 encoding: typing.Optional[str] = None,
546 _b_data: typing.Optional[bytes] = None,
547 ) -> None:
548 super(Authenticate, self).__init__(encoding=encoding, _b_data=_b_data)
549
550 if _b_data:
551 self._encoding = "utf-16-le" if self.flags & NegotiateFlags.unicode else self._encoding
552
553 else:
554 self._encoding = "utf-16-le" if flags & NegotiateFlags.unicode else self._encoding
555
556 b_payload = bytearray()
557
558 payload_offset = 64
559
560 # While MS server accept a blank version field, other implementations aren't so kind. No need to be strict
561 # about it and only add the version bytes if it's present.
562 b_version = b""
563 if version:
564 flags |= NegotiateFlags.version
565 b_version = version.pack()
566 payload_offset = _pack_payload(b_version, b_payload, payload_offset)[1]
567
568 # MIC
569 payload_offset = _pack_payload(b"\x00" * 16, b_payload, payload_offset)[1]
570
571 b_lm_response_fields, payload_offset = _pack_payload(lm_challenge_response, b_payload, payload_offset)
572 b_nt_response_fields, payload_offset = _pack_payload(nt_challenge_response, b_payload, payload_offset)
573 b_domain_fields, payload_offset = _pack_payload(
574 domain_name, b_payload, payload_offset, lambda d: d.encode(self._encoding)
575 )
576 b_username_fields, payload_offset = _pack_payload(
577 username, b_payload, payload_offset, lambda d: d.encode(self._encoding)
578 )
579 b_workstation_fields, payload_offset = _pack_payload(
580 workstation, b_payload, payload_offset, lambda d: d.encode(self._encoding)
581 )
582 if encrypted_session_key:
583 flags |= NegotiateFlags.key_exch
584 b_session_key_fields = _pack_payload(encrypted_session_key, b_payload, payload_offset)[0]
585
586 b_data = bytearray(self.signature)
587 b_data.extend(b_lm_response_fields)
588 b_data.extend(b_nt_response_fields)
589 b_data.extend(b_domain_fields)
590 b_data.extend(b_username_fields)
591 b_data.extend(b_workstation_fields)
592 b_data.extend(b_session_key_fields)
593 b_data.extend(struct.pack("<I", flags))
594 b_data.extend(b_payload)
595
596 self._data = memoryview(b_data)
597
598 if mic:
599 self.mic = mic
600
601 @property
602 def lm_challenge_response(self) -> typing.Optional[bytes]:
603 """The LmChallengeResponse or None if not set."""
604 return _unpack_payload(self._data, 12)
605
606 @property
607 def nt_challenge_response(self) -> typing.Optional[bytes]:
608 """The NtChallengeResponse or None if not set."""
609 return _unpack_payload(self._data, 20)
610
611 @property
612 def domain_name(self) -> typing.Optional[str]:
613 """The domain or computer name hosting the user account."""
614 return to_text(_unpack_payload(self._data, 28), encoding=self._encoding, nonstring="passthru")
615
616 @property
617 def user_name(self) -> typing.Optional[str]:
618 """The name of the user to be authenticated."""
619 return to_text(_unpack_payload(self._data, 36), encoding=self._encoding, nonstring="passthru")
620
621 @property
622 def workstation(self) -> typing.Optional[str]:
623 """The name of the computer to which the user is logged on."""
624 return to_text(_unpack_payload(self._data, 44), encoding=self._encoding, nonstring="passthru")
625
626 @property
627 def encrypted_random_session_key(self) -> typing.Optional[bytes]:
628 """The client's encrypted random session key."""
629 return _unpack_payload(self._data, 52)
630
631 @property
632 def flags(self) -> int:
633 """The negotiate flags supported by the client and server."""
634 return struct.unpack("<I", self._data[60:64].tobytes())[0]
635
636 @flags.setter
637 def flags(self, value: int) -> None:
638 self._data[60:64] = struct.pack("<I", value)
639
640 @property
641 def version(self) -> typing.Optional["Version"]:
642 """The client NTLM version."""
643 payload_offset = self._payload_offset
644
645 # If the payload offset is at 64 (no MIC or Version) or 80 (only MIC) then no version is present.
646 if payload_offset not in [64, 80] and payload_offset >= 72:
647 return Version.unpack(self._data[64:72].tobytes())
648
649 else:
650 return None
651
652 @property
653 def mic(self) -> typing.Optional[bytes]:
654 """The MIC for the Authenticate message."""
655 mic_offset = self._get_mic_offset()
656 if mic_offset:
657 return self._data.tobytes()[mic_offset : mic_offset + 16]
658
659 else:
660 return None
661
662 @mic.setter
663 def mic(self, value: bytes) -> None:
664 if len(value) != 16:
665 raise ValueError("NTLM Authenticate MIC must be 16 bytes long")
666
667 mic_offset = self._get_mic_offset()
668 if mic_offset:
669 self._data[mic_offset : mic_offset + 16] = value
670 else:
671 raise ValueError("Cannot set MIC on an Authenticate message with no MIC present")
672
673 @property
674 def _payload_offset(self) -> int:
675 """Gets the offset of the first payload value."""
676 return _get_payload_offset(self._data, [12, 20, 28, 36, 44, 52])
677
678 def _get_mic_offset(self) -> int:
679 """Gets the offset of the MIC structure if present."""
680 payload_offset = self._payload_offset
681
682 # If the payload offset is 88 or more then we must have the Version (8 bytes) and the MIC (16 bytes) plus
683 # any random data after that.
684 if payload_offset >= 88:
685 return 72
686
687 # If the payload offset is between 80 and 88, then we should have just the MIC and no Version.
688 elif payload_offset >= 80:
689 return 64
690
691 # Not enough room for a MIC between the minimum size and the payload offset.
692 else:
693 return 0
694
695 @staticmethod
696 def unpack(b_data: bytes, encoding: typing.Optional[str] = None) -> "Authenticate":
697 msg = NTLMMessage.unpack(b_data, encoding=encoding)
698 if not isinstance(msg, Authenticate):
699 raise ValueError("Input message was not a NTLM Authenticate message")
700
701 return msg
702
703
704 class FileTime(datetime.datetime):
705 """Windows FILETIME structure.
706
707 FILETIME structure representing number of 100-nanosecond intervals that have elapsed since January 1, 1601 UTC.
708 This subclasses the datetime object to provide a similar interface but with the `nanosecond` attribute.
709
710 Attrs:
711 nanosecond (int): The number of nanoseconds (< 1000) in the FileTime. Note this only has a precision of up to
712 100 nanoseconds.
713
714 .. _FILETIME:
715 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/2c57429b-fdd4-488f-b5fc-9e4cf020fcdf
716 """
717
718 _EPOCH_FILETIME = 116444736000000000 # 1970-01-01 as FILETIME.
719
720 def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> "FileTime":
721 ns = 0
722 if "nanosecond" in kwargs:
723 ns = kwargs.pop("nanosecond")
724
725 dt = super(FileTime, cls).__new__(cls, *args, **kwargs)
726 dt.nanosecond = ns
727
728 return dt
729
730 def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
731 super().__init__()
732 self.nanosecond = getattr(self, "nanosecond", None) or 0
733
734 @classmethod
735 def now(cls, tz: typing.Optional[datetime.tzinfo] = None) -> "FileTime":
736 """Construct a FileTime from the current time and optional time zone info."""
737 return FileTime.from_datetime(datetime.datetime.now(tz=tz))
738
739 @classmethod
740 def from_datetime(cls, dt: datetime.datetime, ns: int = 0) -> "FileTime":
741 """Creates a FileTime object from a datetime object."""
742 return FileTime(
743 year=dt.year,
744 month=dt.month,
745 day=dt.day,
746 hour=dt.hour,
747 minute=dt.minute,
748 second=dt.second,
749 microsecond=dt.microsecond,
750 tzinfo=dt.tzinfo,
751 nanosecond=ns,
752 )
753
754 def __str__(self) -> str:
755 """Displays the datetime in ISO 8601 including the 100th nanosecond internal like .NET does."""
756 fraction_seconds = ""
757
758 if self.microsecond or self.nanosecond:
759 fraction_seconds = self.strftime(".%f")
760
761 if self.nanosecond:
762 fraction_seconds += str(self.nanosecond // 100)
763
764 timezone = "Z"
765 if self.tzinfo:
766 utc_offset = self.strftime("%z")
767 timezone = "%s:%s" % (utc_offset[:3], utc_offset[3:])
768
769 # strftime doesn't support dates < 1900 on Python 2.7
770 return "{0}-{1:02d}-{2:02d}T{3:02d}:{4:02d}:{5:02d}{6}{7}".format(
771 self.year, self.month, self.day, self.hour, self.minute, self.second, fraction_seconds, timezone
772 )
773
774 def pack(self) -> bytes:
775 """Packs the structure to bytes."""
776 # Make sure we are dealing with a timezone aware datetime
777 utc_tz = datetime.timezone.utc
778 utc_dt = typing.cast(datetime.datetime, self.replace(tzinfo=self.tzinfo if self.tzinfo else utc_tz))
779
780 # Get the time since UTC EPOCH in microseconds
781 td = utc_dt.astimezone(utc_tz) - datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=utc_tz)
782 epoch_time_ms = td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6
783
784 # Add the EPOCH_FILETIME to the microseconds since EPOCH and finally the nanoseconds part.
785 ns100 = FileTime._EPOCH_FILETIME + (epoch_time_ms * 10) + (self.nanosecond // 100)
786
787 return struct.pack("<Q", ns100)
788
789 @staticmethod
790 def unpack(b_data: bytes) -> "FileTime":
791 """Unpacks the structure from bytes."""
792 filetime = struct.unpack("<Q", b_data)[0] # 100 nanosecond intervals since 1601-01-01.
793
794 # Create a datetime object based on the filetime microseconds
795 epoch_time_ms = (filetime - FileTime._EPOCH_FILETIME) // 10
796 dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(microseconds=epoch_time_ms)
797
798 # Create the FileTime object from the datetime object and add the nanoseconds.
799 ns = int(filetime % 10) * 100
800
801 return FileTime.from_datetime(dt, ns=ns)
802
803
804 class NTClientChallengeV2:
805 """NTLMv2 Client Challenge
806
807 The `NTLMv2_CLIENT_CHALLENGE`_ structure defines the client challenge in the AUTHENTICATE_MESSAGE. This structure
808 is only used when NTLMv2 authentication is configured and is transported in the NT Challenge Response.
809
810 Args:
811 time_stamp: The timestamp, defaults to the current time.
812 client_challenge: The 8 byte nonce generated by the client.
813 av_pairs: The TargetInfo AV_PAIRS for the client challenge.
814 _b_data: Raw byte string for the NTClientChallengeV2, when set the other args are ignored.
815
816 .. _NTLMv2_CLIENT_CHALLENGE:
817 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/aee311d6-21a7-4470-92a5-c4ecb022a87b
818 """
819
820 def __init__(
821 self,
822 time_stamp: typing.Optional["FileTime"] = None,
823 client_challenge: typing.Optional[bytes] = None,
824 av_pairs: typing.Optional["TargetInfo"] = None,
825 _b_data: typing.Optional[bytes] = None,
826 ) -> None:
827 if _b_data:
828 if len(_b_data) < 32:
829 raise ValueError("Invalid NTClientChallengeV2 raw byte length")
830
831 self._data = memoryview(bytearray(_b_data))
832
833 else:
834 time_stamp = time_stamp or FileTime.now()
835 av_pairs = av_pairs or TargetInfo()
836
837 b_data = bytearray(b"\x01\x01\x00\x00\x00\x00\x00\x00")
838 b_data.extend(time_stamp.pack())
839 b_data.extend(b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
840 b_data.extend(av_pairs.pack())
841
842 self._data = memoryview(b_data)
843
844 client_challenge = client_challenge or b"\x00" * 8
845 self.challenge_from_client = client_challenge
846
847 @property
848 def resp_type(self) -> int:
849 """The current response type version, must be set to 1."""
850 return struct.unpack("B", self._data[:1].tobytes())[0]
851
852 @resp_type.setter
853 def resp_type(self, value: int) -> None:
854 self._data[:1] = struct.pack("B", value)
855
856 @property
857 def hi_resp_type(self) -> int:
858 """The maximum response type supported, must be set to 1."""
859 return struct.unpack("B", self._data[1:2].tobytes())[0]
860
861 @hi_resp_type.setter
862 def hi_resp_type(self, value: int) -> None:
863 self._data[1:2] = struct.pack("B", value)
864
865 @property
866 def time_stamp(self) -> "FileTime":
867 """The current system time."""
868 return FileTime.unpack(self._data[8:16].tobytes())
869
870 @time_stamp.setter
871 def time_stamp(self, value: "FileTime") -> None:
872 self._data[8:16] = value.pack()
873
874 @property
875 def challenge_from_client(self) -> bytes:
876 """8 byte client challenge."""
877 return self._data[16:24].tobytes()
878
879 @challenge_from_client.setter
880 def challenge_from_client(self, value: bytes) -> None:
881 if len(value) != 8:
882 raise ValueError("NTClientChallengeV2 ChallengeFromClient must be 8 bytes long")
883 self._data[16:24] = value
884
885 @property
886 def av_pairs(self) -> "TargetInfo":
887 """The target info AV_PAIR structures."""
888 return TargetInfo.unpack(self._data[28:].tobytes())
889
890 def pack(self) -> bytes:
891 """Packs the NTClientChallengeV2 to bytes."""
892 return self._data.tobytes()
893
894 @staticmethod
895 def unpack(b_data: bytes) -> "NTClientChallengeV2":
896 """Unpacks the raw bytes to the NTClientChallengeV2 structure."""
897 return NTClientChallengeV2(_b_data=b_data)
898
899
900 class TargetInfo(collections.OrderedDict):
901 """A collection of AV_PAIR structures for the TargetInfo field.
902
903 The `AV_PAIR`_ structure defines an attribute/value pair and sequences of these pairs are using in the
904 :class:`Challenge` and :class:`Authenticate` messages. The value for each pair depends on the AvId specified.
905 Each value can be get/set/del like a normal dictionary where the key is the AvId of the value.
906
907 .. _AV_PAIR:
908 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/83f5e789-660d-4781-8491-5f8c6641f75e
909 """
910
911 _FIELD_TYPES = {
912 "text": (
913 AvId.nb_computer_name,
914 AvId.nb_domain_name,
915 AvId.dns_computer_name,
916 AvId.dns_domain_name,
917 AvId.dns_tree_name,
918 AvId.target_name,
919 ),
920 "int32": (AvId.flags,),
921 "struct": (AvId.timestamp, AvId.single_host),
922 }
923
924 def __setitem__(self, key: AvId, value: typing.Any) -> None:
925 if isinstance(value, bytes):
926 if key == AvId.timestamp:
927 value = FileTime.unpack(value)
928 elif key == AvId.single_host:
929 value = SingleHost.unpack(value)
930
931 super(TargetInfo, self).__setitem__(key, value)
932
933 def pack(self) -> bytes:
934 """Packs the structure to bytes."""
935 b_data = io.BytesIO()
936
937 for av_id, value in self.items():
938 # MsvAvEOL should only be set at the end, will just ignore these entries.
939 if av_id == AvId.eol:
940 continue
941
942 if av_id in self._FIELD_TYPES["text"]:
943 b_value = value.encode("utf-16-le")
944 elif av_id in self._FIELD_TYPES["int32"]:
945 b_value = struct.pack("<I", value)
946 elif av_id in self._FIELD_TYPES["struct"]:
947 b_value = value.pack()
948 else:
949 b_value = value
950
951 b_data.write(struct.pack("<HH", av_id, len(b_value)) + b_value)
952
953 b_data.write(b"\x00\x00\x00\x00") # MsvAvEOL
954 return b_data.getvalue()
955
956 @staticmethod
957 def unpack(b_data: bytes) -> "TargetInfo":
958 """Unpacks the structure from bytes."""
959 target_info = TargetInfo()
960 b_io = io.BytesIO(b_data)
961
962 b_av_id = b_io.read(2)
963
964 while b_av_id:
965 av_id = struct.unpack("<H", b_av_id)[0]
966 length = struct.unpack("<H", b_io.read(2))[0]
967 b_value = b_io.read(length)
968
969 value: typing.Any
970 if av_id in TargetInfo._FIELD_TYPES["text"]:
971 # All AV_PAIRS are UNICODE encoded.
972 value = b_value.decode("utf-16-le")
973
974 elif av_id in TargetInfo._FIELD_TYPES["int32"]:
975 value = AvFlags(struct.unpack("<I", b_value)[0])
976
977 elif av_id == AvId.timestamp:
978 value = FileTime.unpack(b_value)
979
980 elif av_id == AvId.single_host:
981 value = SingleHost.unpack(b_value)
982
983 else:
984 value = b_value
985
986 target_info[AvId(av_id)] = value
987 b_av_id = b_io.read(2)
988
989 return target_info
990
991
992 class SingleHost:
993 """Single_Host_Data structure for NTLM TargetInfo entry.
994
995 `Single_Host_Data`_ structure allows a client to send machine-specific information within an authentication
996 exchange to services on the same machine. If the server and client platforms are different or if they are on
997 different hosts, then the information MUST be ignores.
998
999 Args:
1000 size: A 32-bit unsigned int that defines size of the structure.
1001 z4: A 32-bit integer value, currently set to 0.
1002 custom_data: An 8-byte platform-specific blob containing info only relevant when the client and server are on
1003 the same host.
1004 machine_id: A 32-byte random number created at computer startup to identify the calling machine.
1005 _b_data: Create a SingleHost object from the raw data byte string.
1006
1007 Attributes:
1008 size: See args.
1009 z4: See args.
1010 custom_data: See args.
1011 machine_id: See args.
1012
1013 .. _Single_Host_Data:
1014 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/f221c061-cc40-4471-95da-d2ff71c85c5b
1015 """
1016
1017 def __init__(
1018 self,
1019 size: int = 0,
1020 z4: int = 0,
1021 custom_data: typing.Optional[bytes] = None,
1022 machine_id: typing.Optional[bytes] = None,
1023 _b_data: typing.Optional[bytes] = None,
1024 ) -> None:
1025 if _b_data:
1026 if len(_b_data) != 48:
1027 raise ValueError("SingleHost bytes must have a length of 48")
1028 self._data = memoryview(_b_data)
1029
1030 else:
1031 self._data = memoryview(bytearray(48))
1032 self.size = size
1033 self.z4 = z4
1034 self.custom_data = custom_data or b"\x00" * 8
1035 self.machine_id = machine_id or b"\x00" * 32
1036
1037 def __eq__(self, other: object) -> bool:
1038 if not isinstance(other, (bytes, SingleHost)):
1039 return False
1040
1041 if isinstance(other, SingleHost):
1042 other = other.pack()
1043
1044 return self.pack() == other
1045
1046 @property
1047 def size(self) -> int:
1048 return struct.unpack("<I", self._data[:4].tobytes())[0]
1049
1050 @size.setter
1051 def size(self, value: int) -> None:
1052 self._data[:4] = struct.pack("<I", value)
1053
1054 @property
1055 def z4(self) -> int:
1056 return struct.unpack("<I", self._data[4:8].tobytes())[0]
1057
1058 @z4.setter
1059 def z4(self, value: int) -> None:
1060 self._data[4:8] = struct.pack("<I", value)
1061
1062 @property
1063 def custom_data(self) -> bytes:
1064 return self._data[8:16].tobytes()
1065
1066 @custom_data.setter
1067 def custom_data(self, value: bytes) -> None:
1068 if len(value) != 8:
1069 raise ValueError("custom_data length must be 8 bytes long")
1070
1071 self._data[8:16] = value
1072
1073 @property
1074 def machine_id(self) -> bytes:
1075 return self._data[16:48].tobytes()
1076
1077 @machine_id.setter
1078 def machine_id(self, value: bytes) -> None:
1079 if len(value) != 32:
1080 raise ValueError("machine_id length must be 32 bytes long")
1081
1082 self._data[16:48] = value
1083
1084 def pack(self) -> bytes:
1085 """Packs the structure to bytes."""
1086 return self._data.tobytes()
1087
1088 @staticmethod
1089 def unpack(b_data: bytes) -> "SingleHost":
1090 """Creates a SignleHost object from raw bytes."""
1091 return SingleHost(_b_data=b_data)
1092
1093
1094 class Version:
1095 """A structure contains the OS information.
1096
1097 The `VERSION`_ structure contains operating system version information that SHOULD be ignored. This structure is
1098 used for debugging purposes only and its value does not affect NTLM message processing. It is populated in the NTLM
1099 messages only if `NTLMSSP_NEGOTIATE_VERSION` (`NegotiateFlags.version`) is negotiated.
1100
1101 Args:
1102 major: See args. The 8-bit unsigned int for the version major part.
1103 minor: The 8-bit unsigned int for the version minor part.
1104 build: The 16-bit unsigned int for the version build part.
1105 revision: An 8-bit unsigned integer for the current NTLMSSP revision. This field SHOULD be `0x0F`.
1106 _b_data: Create a Version object from the raw data byte string.
1107
1108 Attrs:
1109 major: See args.
1110 minor: See args.
1111 build: See args.
1112 reserved: A reserved 3-byte field that isn't used in the NTLM spec.
1113 revision: See args.
1114
1115 .. _VERSION:
1116 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/b1a6ceb2-f8ad-462b-b5af-f18527c48175
1117 """
1118
1119 def __init__(
1120 self,
1121 major: int = 0,
1122 minor: int = 0,
1123 build: int = 0,
1124 revision: int = 0x0F,
1125 _b_data: typing.Optional[bytes] = None,
1126 ) -> None:
1127 if _b_data:
1128 if len(_b_data) != 8:
1129 raise ValueError("Version bytes must have a length of 8")
1130
1131 self._data = memoryview(_b_data)
1132
1133 else:
1134 self._data = memoryview(bytearray(8))
1135 self.major = major
1136 self.minor = minor
1137 self.build = build
1138 self.revision = revision
1139
1140 def __eq__(self, other: object) -> bool:
1141 if not isinstance(other, (bytes, Version)):
1142 return False
1143
1144 if isinstance(other, Version):
1145 other = other.pack()
1146
1147 return self.pack() == other
1148
1149 def __len__(self) -> int:
1150 return 8
1151
1152 @property
1153 def major(self) -> int:
1154 return struct.unpack("B", self._data[0:1].tobytes())[0]
1155
1156 @major.setter
1157 def major(self, value: int) -> None:
1158 self._data[0:1] = struct.pack("B", value)
1159
1160 @property
1161 def minor(self) -> int:
1162 return struct.unpack("B", self._data[1:2].tobytes())[0]
1163
1164 @minor.setter
1165 def minor(self, value: int) -> None:
1166 self._data[1:2] = struct.pack("B", value)
1167
1168 @property
1169 def build(self) -> int:
1170 return struct.unpack("<H", self._data[2:4].tobytes())[0]
1171
1172 @build.setter
1173 def build(self, value: int) -> None:
1174 self._data[2:4] = struct.pack("<H", value)
1175
1176 @property
1177 def reserved(self) -> bytes:
1178 return self._data[4:7].tobytes()
1179
1180 @property
1181 def revision(self) -> int:
1182 return struct.unpack("B", self._data[7:8].tobytes())[0]
1183
1184 @revision.setter
1185 def revision(self, value: int) -> None:
1186 self._data[7:8] = struct.pack("B", value)
1187
1188 def __repr__(self) -> str:
1189 return "<{0}.{1} {2}.{3}.{4}.{5}>".format(
1190 type(self).__module__, type(self).__name__, self.major, self.minor, self.build, self.revision
1191 )
1192
1193 def __str__(self) -> str:
1194 return "%s.%s.%s.%s" % (self.major, self.minor, self.build, self.revision)
1195
1196 def pack(self) -> bytes:
1197 """Packs the structure to bytes."""
1198 return self._data.tobytes()
1199
1200 @staticmethod
1201 def get_current() -> "Version":
1202 """Generates an NTLM Version structure based on the pyspnego package version."""
1203 versions = []
1204 for v in pyspnego_version.split(".", 3):
1205 if not v:
1206 continue
1207
1208 match = re.match(r"^(\d+)", v)
1209 if match:
1210 versions.append(int(match.group(1)))
1211
1212 versions += [0] * (3 - len(versions))
1213
1214 return Version(major=int(versions[0]), minor=int(versions[1]), build=int(versions[2]))
1215
1216 @staticmethod
1217 def unpack(b_data: bytes) -> "Version":
1218 """Creates a Version object from raw bytes."""
1219 return Version(_b_data=b_data)