Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/scapy/layers/ntlm.py: 34%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# SPDX-License-Identifier: GPL-2.0-only
2# This file is part of Scapy
3# See https://scapy.net/ for more information
4# Copyright (C) Gabriel Potter
6"""
7NTLM
9This is documented in [MS-NLMP]
11.. note::
12 You will find more complete documentation for this layer over at
13 `GSSAPI <https://scapy.readthedocs.io/en/latest/layers/gssapi.html#ntlm>`_
14"""
16import copy
17import time
18import os
19import struct
21from enum import IntEnum
23from scapy.asn1.asn1 import ASN1_Codecs
24from scapy.asn1.mib import conf # loads conf.mib
25from scapy.asn1fields import (
26 ASN1F_OID,
27 ASN1F_PRINTABLE_STRING,
28 ASN1F_SEQUENCE,
29 ASN1F_SEQUENCE_OF,
30)
31from scapy.asn1packet import ASN1_Packet
32from scapy.config import crypto_validator
33from scapy.compat import bytes_base64
34from scapy.error import log_runtime
35from scapy.fields import (
36 ByteEnumField,
37 ByteField,
38 ConditionalField,
39 Field,
40 FieldLenField,
41 FlagsField,
42 LEIntEnumField,
43 LEIntField,
44 LEShortEnumField,
45 LEShortField,
46 LEThreeBytesField,
47 MultipleTypeField,
48 PacketField,
49 PacketListField,
50 StrField,
51 StrFieldUtf16,
52 StrFixedLenField,
53 StrLenFieldUtf16,
54 UTCTimeField,
55 XStrField,
56 XStrFixedLenField,
57 XStrLenField,
58 _StrField,
59)
60from scapy.packet import Packet
61from scapy.sessions import StringBuffer
63from scapy.layers.gssapi import (
64 GSS_C_FLAGS,
65 GSS_C_NO_CHANNEL_BINDINGS,
66 GSS_S_BAD_BINDINGS,
67 GSS_S_BAD_MIC,
68 GSS_S_COMPLETE,
69 GSS_S_CONTINUE_NEEDED,
70 GSS_S_DEFECTIVE_CREDENTIAL,
71 GSS_S_DEFECTIVE_TOKEN,
72 GSS_S_FLAGS,
73 GssChannelBindings,
74 SSP,
75 _GSSAPI_OIDS,
76 _GSSAPI_SIGNATURE_OIDS,
77)
79# Typing imports
80from typing import (
81 Any,
82 Callable,
83 List,
84 Optional,
85 Tuple,
86 Union,
87)
89# Crypto imports
91from scapy.layers.tls.crypto.hash import Hash_MD4, Hash_MD5
92from scapy.layers.tls.crypto.h_mac import Hmac_MD5
94##########
95# Fields #
96##########
99# NTLM structures are all in all very complicated. Many fields don't have a fixed
100# position, but are rather referred to with an offset (from the beginning of the
101# structure) and a length. In addition to that, there are variants of the structure
102# with missing fields when running old versions of Windows (sometimes also seen when
103# talking to products that reimplement NTLM, most notably backup applications).
105# We add `_NTLMPayloadField` and `_NTLMPayloadPacket` to parse fields that use an
106# offset, and `_NTLM_post_build` to be able to rebuild those offsets.
107# In addition, the `NTLM_VARIANT*` allows to select what flavor of NTLM to use
108# (NT, XP, or Recent). But in real world use only Recent should be used.
111class _NTLMPayloadField(_StrField[List[Tuple[str, Any]]]):
112 """Special field used to dissect NTLM payloads.
113 This isn't trivial because the offsets are variable."""
115 __slots__ = [
116 "fields",
117 "fields_map",
118 "fields_pad",
119 "offset",
120 "length_from",
121 "force_order",
122 "offset_name",
123 ]
124 islist = True
126 def __init__(
127 self,
128 name, # type: str
129 offset, # type: Union[int, Callable[[Packet], int]]
130 fields, # type: List[Field[Any, Any]]
131 fields_pad=0, # type: int
132 length_from=None, # type: Optional[Callable[[Packet], int]]
133 force_order=None, # type: Optional[List[str]]
134 offset_name="BufferOffset", # type: str
135 ):
136 # type: (...) -> None
137 self.offset = offset
138 self.fields = fields
139 self.fields_map = {field.name: field for field in fields}
140 self.length_from = length_from
141 self.force_order = force_order # whether the order of fields is fixed
142 self.offset_name = offset_name
143 self.fields_pad = fields_pad
144 super(_NTLMPayloadField, self).__init__(
145 name,
146 [
147 (field.name, field.default)
148 for field in fields
149 if field.default is not None
150 ],
151 )
153 def _on_payload(self, pkt, x, func):
154 # type: (Optional[Packet], bytes, str) -> List[Tuple[str, Any]]
155 if not pkt or not x:
156 return []
157 results = []
158 for field_name, value in x:
159 if field_name not in self.fields_map:
160 continue
161 if not isinstance(
162 self.fields_map[field_name], PacketListField
163 ) and not isinstance(value, Packet):
164 value = getattr(self.fields_map[field_name], func)(pkt, value)
165 results.append((field_name, value))
166 return results
168 def i2h(self, pkt, x):
169 # type: (Optional[Packet], bytes) -> List[Tuple[str, str]]
170 return self._on_payload(pkt, x, "i2h")
172 def h2i(self, pkt, x):
173 # type: (Optional[Packet], bytes) -> List[Tuple[str, str]]
174 return self._on_payload(pkt, x, "h2i")
176 def i2repr(self, pkt, x):
177 # type: (Optional[Packet], bytes) -> str
178 return repr(self._on_payload(pkt, x, "i2repr"))
180 def _o_pkt(self, pkt):
181 # type: (Optional[Packet]) -> int
182 if callable(self.offset):
183 return self.offset(pkt)
184 return self.offset
186 def addfield(self, pkt, s, val):
187 # type: (Optional[Packet], bytes, Optional[List[Tuple[str, str]]]) -> bytes
188 # Create string buffer
189 buf = StringBuffer()
190 buf.append(s, 1)
191 # Calc relative offset
192 r_off = self._o_pkt(pkt) - len(s)
193 if self.force_order:
194 val.sort(key=lambda x: self.force_order.index(x[0]))
195 for field_name, value in val:
196 if field_name not in self.fields_map:
197 continue
198 field = self.fields_map[field_name]
199 offset = pkt.getfieldval(field_name + self.offset_name)
200 if offset is None:
201 # No offset specified: calc
202 offset = len(buf)
203 if self.fields_pad:
204 pad = (-offset) % self.fields_pad
205 offset += pad
206 buf.append(pad * b"\x00", len(buf))
207 else:
208 # Calc relative offset
209 offset -= r_off
210 pad = offset + 1 - len(buf)
211 # Add padding if necessary
212 if pad > 0:
213 buf.append(pad * b"\x00", len(buf))
214 buf.append(field.addfield(pkt, bytes(buf), value)[len(buf) :], offset + 1)
215 return bytes(buf)
217 def getfield(self, pkt, s):
218 # type: (Packet, bytes) -> Tuple[bytes, List[Tuple[str, str]]]
219 if self.length_from is None:
220 ret, remain = b"", s
221 else:
222 len_pkt = self.length_from(pkt)
223 ret, remain = s[len_pkt:], s[:len_pkt]
224 if not pkt or not remain:
225 return s, []
226 results = []
227 max_offset = 0
228 o_pkt = self._o_pkt(pkt)
229 offsets = [
230 pkt.getfieldval(x.name + self.offset_name) - o_pkt for x in self.fields
231 ]
232 for i, field in enumerate(self.fields):
233 offset = offsets[i]
234 try:
235 length = pkt.getfieldval(field.name + "Len")
236 except AttributeError:
237 length = len(remain) - offset
238 # length can't be greater than the difference with the next offset
239 try:
240 length = min(length, min(x - offset for x in offsets if x > offset))
241 except ValueError:
242 pass
243 if offset < 0:
244 continue
245 max_offset = max(offset + length, max_offset)
246 if remain[offset : offset + length]:
247 results.append(
248 (
249 offset,
250 field.name,
251 field.getfield(pkt, remain[offset : offset + length])[1],
252 )
253 )
254 ret += remain[max_offset:]
255 results.sort(key=lambda x: x[0])
256 return ret, [x[1:] for x in results]
259class _NTLMPayloadPacket(Packet):
260 _NTLM_PAYLOAD_FIELD_NAME = "Payload"
262 def __init__(
263 self,
264 _pkt=b"", # type: Union[bytes, bytearray]
265 post_transform=None, # type: Any
266 _internal=0, # type: int
267 _underlayer=None, # type: Optional[Packet]
268 _parent=None, # type: Optional[Packet]
269 **fields, # type: Any
270 ):
271 # pop unknown fields. We can't process them until the packet is initialized
272 unknown = {
273 k: fields.pop(k)
274 for k in list(fields)
275 if not any(k == f.name for f in self.fields_desc)
276 }
277 super(_NTLMPayloadPacket, self).__init__(
278 _pkt=_pkt,
279 post_transform=post_transform,
280 _internal=_internal,
281 _underlayer=_underlayer,
282 _parent=_parent,
283 **fields,
284 )
285 # check unknown fields for implicit ones
286 local_fields = next(
287 [y.name for y in x.fields]
288 for x in self.fields_desc
289 if x.name == self._NTLM_PAYLOAD_FIELD_NAME
290 )
291 implicit_fields = {k: v for k, v in unknown.items() if k in local_fields}
292 for k, value in implicit_fields.items():
293 self.setfieldval(k, value)
295 def getfieldval(self, attr):
296 # Ease compatibility with _NTLMPayloadField
297 try:
298 return super(_NTLMPayloadPacket, self).getfieldval(attr)
299 except AttributeError:
300 try:
301 return next(
302 x[1]
303 for x in super(_NTLMPayloadPacket, self).getfieldval(
304 self._NTLM_PAYLOAD_FIELD_NAME
305 )
306 if x[0] == attr
307 )
308 except StopIteration:
309 raise AttributeError(attr)
311 def getfield_and_val(self, attr):
312 # Ease compatibility with _NTLMPayloadField
313 try:
314 return super(_NTLMPayloadPacket, self).getfield_and_val(attr)
315 except ValueError:
316 PayFields = self.get_field(self._NTLM_PAYLOAD_FIELD_NAME).fields_map
317 try:
318 return (
319 PayFields[attr],
320 PayFields[attr].h2i( # cancel out the i2h.. it's dumb i know
321 self,
322 next(
323 x[1]
324 for x in super(_NTLMPayloadPacket, self).__getattr__(
325 self._NTLM_PAYLOAD_FIELD_NAME
326 )
327 if x[0] == attr
328 ),
329 ),
330 )
331 except (StopIteration, KeyError):
332 raise ValueError(attr)
334 def setfieldval(self, attr, val):
335 # Ease compatibility with _NTLMPayloadField
336 try:
337 return super(_NTLMPayloadPacket, self).setfieldval(attr, val)
338 except AttributeError:
339 Payload = super(_NTLMPayloadPacket, self).__getattr__(
340 self._NTLM_PAYLOAD_FIELD_NAME
341 )
342 if attr not in self.get_field(self._NTLM_PAYLOAD_FIELD_NAME).fields_map:
343 raise AttributeError(attr)
344 try:
345 Payload.pop(
346 next(
347 i
348 for i, x in enumerate(
349 super(_NTLMPayloadPacket, self).__getattr__(
350 self._NTLM_PAYLOAD_FIELD_NAME
351 )
352 )
353 if x[0] == attr
354 )
355 )
356 except StopIteration:
357 pass
358 Payload.append([attr, val])
359 super(_NTLMPayloadPacket, self).setfieldval(
360 self._NTLM_PAYLOAD_FIELD_NAME, Payload
361 )
364class _NTLM_ENUM(IntEnum):
365 LEN = 0x0001
366 MAXLEN = 0x0002
367 OFFSET = 0x0004
368 COUNT = 0x0008
369 PAD8 = 0x1000
372_NTLM_CONFIG = [
373 ("Len", _NTLM_ENUM.LEN),
374 ("MaxLen", _NTLM_ENUM.MAXLEN),
375 ("BufferOffset", _NTLM_ENUM.OFFSET),
376]
379def _NTLM_post_build(self, p, pay_offset, fields, config=_NTLM_CONFIG):
380 """Util function to build the offset and populate the lengths"""
381 gl_fld = self.get_field(self._NTLM_PAYLOAD_FIELD_NAME)
382 for field_name, value in self.fields[self._NTLM_PAYLOAD_FIELD_NAME]:
383 fld = gl_fld.fields_map[field_name]
384 length = fld.i2len(self, value)
385 count = fld.i2count(self, value)
386 offset = fields[field_name]
387 i = 0
388 r = lambda y: {2: "H", 4: "I", 8: "Q"}[y]
389 for fname, ftype in config:
390 if isinstance(ftype, dict):
391 ftype = ftype[field_name]
392 if ftype & _NTLM_ENUM.LEN:
393 fval = length
394 elif ftype & _NTLM_ENUM.OFFSET:
395 fval = pay_offset
396 elif ftype & _NTLM_ENUM.MAXLEN:
397 fval = length
398 elif ftype & _NTLM_ENUM.COUNT:
399 fval = count
400 else:
401 raise ValueError
402 if ftype & _NTLM_ENUM.PAD8:
403 pad = (-fval) % 8
404 fval += pad
405 pay_offset += pad
406 sz = self.get_field(field_name + fname).sz
407 if self.getfieldval(field_name + fname) is None:
408 p = (
409 p[: offset + i]
410 + struct.pack("<%s" % r(sz), fval)
411 + p[offset + i + sz :]
412 )
413 i += sz
414 pay_offset += length
415 return p
418##############
419# Structures #
420##############
423# -- Util: VARIANT class
426class NTLM_VARIANT(IntEnum):
427 """
428 The message variant to use for NTLM.
429 """
431 NT_OR_2000 = 0
432 XP_OR_2003 = 1
433 RECENT = 2
436class _NTLM_VARIANT_Packet(_NTLMPayloadPacket):
437 def __init__(self, *args, **kwargs):
438 self.VARIANT = kwargs.pop("VARIANT", NTLM_VARIANT.RECENT)
439 super(_NTLM_VARIANT_Packet, self).__init__(*args, **kwargs)
441 def clone_with(self, *args, **kwargs):
442 pkt = super(_NTLM_VARIANT_Packet, self).clone_with(*args, **kwargs)
443 pkt.VARIANT = self.VARIANT
444 return pkt
446 def copy(self):
447 pkt = super(_NTLM_VARIANT_Packet, self).copy()
448 pkt.VARIANT = self.VARIANT
450 return pkt
452 def show2(self, dump=False, indent=3, lvl="", label_lvl=""):
453 return self.__class__(bytes(self), VARIANT=self.VARIANT).show(
454 dump, indent, lvl, label_lvl
455 )
458# Sect 2.2
461class NTLM_Header(Packet):
462 name = "NTLM Header"
463 fields_desc = [
464 StrFixedLenField("Signature", b"NTLMSSP\0", length=8),
465 LEIntEnumField(
466 "MessageType",
467 3,
468 {
469 1: "NEGOTIATE_MESSAGE",
470 2: "CHALLENGE_MESSAGE",
471 3: "AUTHENTICATE_MESSAGE",
472 },
473 ),
474 ]
476 @classmethod
477 def dispatch_hook(cls, _pkt=None, *args, **kargs):
478 if cls is NTLM_Header and _pkt and len(_pkt) >= 10:
479 MessageType = struct.unpack("<H", _pkt[8:10])[0]
480 if MessageType == 1:
481 return NTLM_NEGOTIATE
482 elif MessageType == 2:
483 return NTLM_CHALLENGE
484 elif MessageType == 3:
485 return NTLM_AUTHENTICATE_V2
486 return cls
489# Sect 2.2.2.5
490_negotiateFlags = [
491 "NEGOTIATE_UNICODE", # A
492 "NEGOTIATE_OEM", # B
493 "REQUEST_TARGET", # C
494 "r10",
495 "NEGOTIATE_SIGN", # D
496 "NEGOTIATE_SEAL", # E
497 "NEGOTIATE_DATAGRAM", # F
498 "NEGOTIATE_LM_KEY", # G
499 "r9",
500 "NEGOTIATE_NTLM", # H
501 "r8",
502 "J",
503 "NEGOTIATE_OEM_DOMAIN_SUPPLIED", # K
504 "NEGOTIATE_OEM_WORKSTATION_SUPPLIED", # L
505 "NEGOTIATE_LOCAL_CALL",
506 "NEGOTIATE_ALWAYS_SIGN", # M
507 "TARGET_TYPE_DOMAIN", # N
508 "TARGET_TYPE_SERVER", # O
509 "r6",
510 "NEGOTIATE_EXTENDED_SESSIONSECURITY", # P
511 "NEGOTIATE_IDENTIFY", # Q
512 "r5",
513 "REQUEST_NON_NT_SESSION_KEY", # R
514 "NEGOTIATE_TARGET_INFO", # S
515 "r4",
516 "NEGOTIATE_VERSION", # T
517 "r3",
518 "r2",
519 "r1",
520 "NEGOTIATE_128", # U
521 "NEGOTIATE_KEY_EXCH", # V
522 "NEGOTIATE_56", # W
523]
526def _NTLMStrField(name, default):
527 return MultipleTypeField(
528 [
529 (
530 StrFieldUtf16(name, default),
531 lambda pkt: pkt.NegotiateFlags.NEGOTIATE_UNICODE,
532 )
533 ],
534 StrField(name, default),
535 )
538# Sect 2.2.2.10
541class _NTLM_Version(Packet):
542 fields_desc = [
543 ByteField("ProductMajorVersion", 0),
544 ByteField("ProductMinorVersion", 0),
545 LEShortField("ProductBuild", 0),
546 LEThreeBytesField("res_ver", 0),
547 ByteEnumField("NTLMRevisionCurrent", 0x0F, {0x0F: "v15"}),
548 ]
551# Sect 2.2.1.1
554class NTLM_NEGOTIATE(_NTLM_VARIANT_Packet, NTLM_Header):
555 name = "NTLM Negotiate"
556 __slots__ = ["VARIANT"]
557 MessageType = 1
558 OFFSET = lambda pkt: (
559 32
560 if (
561 pkt.VARIANT == NTLM_VARIANT.NT_OR_2000
562 or (pkt.DomainNameBufferOffset or 40) <= 32
563 )
564 else 40
565 )
566 fields_desc = (
567 [
568 NTLM_Header,
569 FlagsField("NegotiateFlags", 0, -32, _negotiateFlags),
570 # DomainNameFields
571 LEShortField("DomainNameLen", None),
572 LEShortField("DomainNameMaxLen", None),
573 LEIntField("DomainNameBufferOffset", None),
574 # WorkstationFields
575 LEShortField("WorkstationNameLen", None),
576 LEShortField("WorkstationNameMaxLen", None),
577 LEIntField("WorkstationNameBufferOffset", None),
578 ]
579 + [
580 # VERSION
581 ConditionalField(
582 # (not present on some old Windows versions. We use a heuristic)
583 x,
584 lambda pkt: pkt.VARIANT >= NTLM_VARIANT.XP_OR_2003
585 and (
586 (
587 (
588 40
589 if pkt.DomainNameBufferOffset is None
590 else pkt.DomainNameBufferOffset or len(pkt.original or b"")
591 )
592 > 32
593 )
594 or pkt.fields.get(x.name, b"")
595 ),
596 )
597 for x in _NTLM_Version.fields_desc
598 ]
599 + [
600 # Payload
601 _NTLMPayloadField(
602 "Payload",
603 OFFSET,
604 [
605 # "MUST be encoded using the OEM character set"
606 StrField("DomainName", b""),
607 StrField("WorkstationName", b""),
608 ],
609 ),
610 ]
611 )
613 def post_build(self, pkt, pay):
614 # type: (bytes, bytes) -> bytes
615 return (
616 _NTLM_post_build(
617 self,
618 pkt,
619 self.OFFSET(),
620 {
621 "DomainName": 16,
622 "WorkstationName": 24,
623 },
624 )
625 + pay
626 )
629# Challenge
632class Single_Host_Data(Packet):
633 fields_desc = [
634 LEIntField("Size", None),
635 LEIntField("Z4", 0),
636 # "CustomData" guessed using LSAP_TOKEN_INFO_INTEGRITY.
637 FlagsField(
638 "Flags",
639 0,
640 -32,
641 {
642 0x00000001: "UAC-Restricted",
643 },
644 ),
645 LEIntEnumField(
646 "TokenIL",
647 0x00002000,
648 {
649 0x00000000: "Untrusted",
650 0x00001000: "Low",
651 0x00002000: "Medium",
652 0x00003000: "High",
653 0x00004000: "System",
654 0x00005000: "Protected process",
655 },
656 ),
657 XStrFixedLenField("MachineID", b"", length=32),
658 ConditionalField(
659 XStrFixedLenField("CrossBootMachineID", None, length=32),
660 lambda pkt: pkt.Size is None or pkt.Size > 48,
661 ),
662 ]
664 def post_build(self, pkt, pay):
665 if self.Size is None:
666 pkt = struct.pack("<I", len(pkt)) + pkt[4:]
667 return pkt + pay
669 def default_payload_class(self, payload):
670 return conf.padding_layer
673class AV_PAIR(Packet):
674 name = "NTLM AV Pair"
675 fields_desc = [
676 LEShortEnumField(
677 "AvId",
678 0,
679 {
680 0x0000: "MsvAvEOL",
681 0x0001: "MsvAvNbComputerName",
682 0x0002: "MsvAvNbDomainName",
683 0x0003: "MsvAvDnsComputerName",
684 0x0004: "MsvAvDnsDomainName",
685 0x0005: "MsvAvDnsTreeName",
686 0x0006: "MsvAvFlags",
687 0x0007: "MsvAvTimestamp",
688 0x0008: "MsvAvSingleHost",
689 0x0009: "MsvAvTargetName",
690 0x000A: "MsvAvChannelBindings",
691 },
692 ),
693 FieldLenField("AvLen", None, length_of="Value", fmt="<H"),
694 MultipleTypeField(
695 [
696 (
697 LEIntEnumField(
698 "Value",
699 1,
700 {
701 0x0001: "constrained",
702 0x0002: "MIC integrity",
703 0x0004: "SPN from untrusted source",
704 },
705 ),
706 lambda pkt: pkt.AvId == 0x0006,
707 ),
708 (
709 UTCTimeField(
710 "Value",
711 None,
712 epoch=[1601, 1, 1, 0, 0, 0],
713 custom_scaling=1e7,
714 fmt="<Q",
715 ),
716 lambda pkt: pkt.AvId == 0x0007,
717 ),
718 (
719 PacketField("Value", Single_Host_Data(), Single_Host_Data),
720 lambda pkt: pkt.AvId == 0x0008,
721 ),
722 (
723 XStrLenField("Value", b"", length_from=lambda pkt: pkt.AvLen),
724 lambda pkt: pkt.AvId == 0x000A,
725 ),
726 ],
727 StrLenFieldUtf16("Value", b"", length_from=lambda pkt: pkt.AvLen),
728 ),
729 ]
731 def default_payload_class(self, payload):
732 return conf.padding_layer
735class NTLM_CHALLENGE(_NTLM_VARIANT_Packet, NTLM_Header):
736 name = "NTLM Challenge"
737 __slots__ = ["VARIANT"]
738 MessageType = 2
739 OFFSET = lambda pkt: (
740 48
741 if (
742 pkt.VARIANT == NTLM_VARIANT.NT_OR_2000
743 or (pkt.TargetInfoBufferOffset or 56) <= 48
744 )
745 else 56
746 )
747 fields_desc = (
748 [
749 NTLM_Header,
750 # TargetNameFields
751 LEShortField("TargetNameLen", None),
752 LEShortField("TargetNameMaxLen", None),
753 LEIntField("TargetNameBufferOffset", None),
754 #
755 FlagsField("NegotiateFlags", 0, -32, _negotiateFlags),
756 XStrFixedLenField("ServerChallenge", None, length=8),
757 XStrFixedLenField("Reserved", None, length=8),
758 # TargetInfoFields
759 LEShortField("TargetInfoLen", None),
760 LEShortField("TargetInfoMaxLen", None),
761 LEIntField("TargetInfoBufferOffset", None),
762 ]
763 + [
764 # VERSION
765 ConditionalField(
766 # (not present on some old Windows versions. We use a heuristic)
767 x,
768 lambda pkt: pkt.VARIANT >= NTLM_VARIANT.XP_OR_2003
769 and (
770 ((pkt.TargetInfoBufferOffset or 56) > 40)
771 or pkt.fields.get(x.name, b"")
772 ),
773 )
774 for x in _NTLM_Version.fields_desc
775 ]
776 + [
777 # Payload
778 _NTLMPayloadField(
779 "Payload",
780 OFFSET,
781 [
782 _NTLMStrField("TargetName", b""),
783 PacketListField("TargetInfo", [AV_PAIR()], AV_PAIR),
784 ],
785 ),
786 ]
787 )
789 def getAv(self, AvId):
790 try:
791 return next(x for x in self.TargetInfo if x.AvId == AvId)
792 except (StopIteration, AttributeError):
793 raise IndexError
795 def post_build(self, pkt, pay):
796 # type: (bytes, bytes) -> bytes
797 return (
798 _NTLM_post_build(
799 self,
800 pkt,
801 self.OFFSET(),
802 {
803 "TargetName": 12,
804 "TargetInfo": 40,
805 },
806 )
807 + pay
808 )
811# Authenticate
814class LM_RESPONSE(Packet):
815 fields_desc = [
816 StrFixedLenField("Response", b"", length=24),
817 ]
820class LMv2_RESPONSE(Packet):
821 fields_desc = [
822 StrFixedLenField("Response", b"", length=16),
823 StrFixedLenField("ChallengeFromClient", b"", length=8),
824 ]
827class NTLM_RESPONSE(Packet):
828 fields_desc = [
829 StrFixedLenField("Response", b"", length=24),
830 ]
833class NTLMv2_CLIENT_CHALLENGE(Packet):
834 fields_desc = [
835 ByteField("RespType", 1),
836 ByteField("HiRespType", 1),
837 LEShortField("Reserved1", 0),
838 LEIntField("Reserved2", 0),
839 UTCTimeField(
840 "TimeStamp", None, fmt="<Q", epoch=[1601, 1, 1, 0, 0, 0], custom_scaling=1e7
841 ),
842 StrFixedLenField("ChallengeFromClient", b"12345678", length=8),
843 LEIntField("Reserved3", 0),
844 PacketListField("AvPairs", [AV_PAIR()], AV_PAIR),
845 ]
847 def getAv(self, AvId):
848 try:
849 return next(x for x in self.AvPairs if x.AvId == AvId)
850 except StopIteration:
851 raise IndexError
854class NTLMv2_RESPONSE(NTLMv2_CLIENT_CHALLENGE):
855 fields_desc = [
856 XStrFixedLenField("NTProofStr", b"", length=16),
857 NTLMv2_CLIENT_CHALLENGE,
858 ]
860 def computeNTProofStr(self, ResponseKeyNT, ServerChallenge):
861 """
862 Set temp to ConcatenationOf(Responserversion, HiResponserversion,
863 Z(6), Time, ClientChallenge, Z(4), ServerName, Z(4))
864 Set NTProofStr to HMAC_MD5(ResponseKeyNT,
865 ConcatenationOf(CHALLENGE_MESSAGE.ServerChallenge,temp))
867 Remember ServerName = AvPairs
868 """
869 Responserversion = b"\x01"
870 HiResponserversion = b"\x01"
872 ServerName = b"".join(bytes(x) for x in self.AvPairs)
873 temp = b"".join(
874 [
875 Responserversion,
876 HiResponserversion,
877 b"\x00" * 6,
878 struct.pack("<Q", self.TimeStamp),
879 self.ChallengeFromClient,
880 b"\x00" * 4,
881 ServerName,
882 # Final Z(4) is the EOL AvPair
883 ]
884 )
885 return HMAC_MD5(ResponseKeyNT, ServerChallenge + temp)
888class NTLM_AUTHENTICATE(_NTLM_VARIANT_Packet, NTLM_Header):
889 name = "NTLM Authenticate"
890 __slots__ = ["VARIANT"]
891 MessageType = 3
892 NTLM_VERSION = 1
893 OFFSET = lambda pkt: (
894 64
895 if (
896 pkt.VARIANT == NTLM_VARIANT.NT_OR_2000
897 or (pkt.DomainNameBufferOffset or 88) <= 64
898 )
899 else (
900 72
901 if pkt.VARIANT == NTLM_VARIANT.XP_OR_2003
902 or ((pkt.DomainNameBufferOffset or 88) <= 72)
903 else 88
904 )
905 )
906 fields_desc = (
907 [
908 NTLM_Header,
909 # LmChallengeResponseFields
910 LEShortField("LmChallengeResponseLen", None),
911 LEShortField("LmChallengeResponseMaxLen", None),
912 LEIntField("LmChallengeResponseBufferOffset", None),
913 # NtChallengeResponseFields
914 LEShortField("NtChallengeResponseLen", None),
915 LEShortField("NtChallengeResponseMaxLen", None),
916 LEIntField("NtChallengeResponseBufferOffset", None),
917 # DomainNameFields
918 LEShortField("DomainNameLen", None),
919 LEShortField("DomainNameMaxLen", None),
920 LEIntField("DomainNameBufferOffset", None),
921 # UserNameFields
922 LEShortField("UserNameLen", None),
923 LEShortField("UserNameMaxLen", None),
924 LEIntField("UserNameBufferOffset", None),
925 # WorkstationFields
926 LEShortField("WorkstationLen", None),
927 LEShortField("WorkstationMaxLen", None),
928 LEIntField("WorkstationBufferOffset", None),
929 # EncryptedRandomSessionKeyFields
930 LEShortField("EncryptedRandomSessionKeyLen", None),
931 LEShortField("EncryptedRandomSessionKeyMaxLen", None),
932 LEIntField("EncryptedRandomSessionKeyBufferOffset", None),
933 # NegotiateFlags
934 FlagsField("NegotiateFlags", 0, -32, _negotiateFlags),
935 # VERSION
936 ]
937 + [
938 ConditionalField(
939 # (not present on some old Windows versions. We use a heuristic)
940 x,
941 lambda pkt: pkt.VARIANT >= NTLM_VARIANT.XP_OR_2003
942 and (
943 ((pkt.DomainNameBufferOffset or 88) > 64)
944 or pkt.fields.get(x.name, b"")
945 ),
946 )
947 for x in _NTLM_Version.fields_desc
948 ]
949 + [
950 # MIC
951 ConditionalField(
952 # (not present on some old Windows versions. We use a heuristic)
953 XStrFixedLenField("MIC", b"", length=16),
954 lambda pkt: pkt.VARIANT >= NTLM_VARIANT.RECENT
955 and (
956 ((pkt.DomainNameBufferOffset or 88) > 72)
957 or pkt.fields.get("MIC", b"")
958 ),
959 ),
960 # Payload
961 _NTLMPayloadField(
962 "Payload",
963 OFFSET,
964 [
965 MultipleTypeField(
966 [
967 (
968 PacketField(
969 "LmChallengeResponse",
970 LMv2_RESPONSE(),
971 LMv2_RESPONSE,
972 ),
973 lambda pkt: pkt.NTLM_VERSION == 2,
974 )
975 ],
976 PacketField("LmChallengeResponse", LM_RESPONSE(), LM_RESPONSE),
977 ),
978 MultipleTypeField(
979 [
980 (
981 PacketField(
982 "NtChallengeResponse",
983 NTLMv2_RESPONSE(),
984 NTLMv2_RESPONSE,
985 ),
986 lambda pkt: pkt.NTLM_VERSION == 2,
987 )
988 ],
989 PacketField(
990 "NtChallengeResponse", NTLM_RESPONSE(), NTLM_RESPONSE
991 ),
992 ),
993 _NTLMStrField("DomainName", b""),
994 _NTLMStrField("UserName", b""),
995 _NTLMStrField("Workstation", b""),
996 XStrField("EncryptedRandomSessionKey", b""),
997 ],
998 ),
999 ]
1000 )
1002 def post_build(self, pkt, pay):
1003 # type: (bytes, bytes) -> bytes
1004 return (
1005 _NTLM_post_build(
1006 self,
1007 pkt,
1008 self.OFFSET(),
1009 {
1010 "LmChallengeResponse": 12,
1011 "NtChallengeResponse": 20,
1012 "DomainName": 28,
1013 "UserName": 36,
1014 "Workstation": 44,
1015 "EncryptedRandomSessionKey": 52,
1016 },
1017 )
1018 + pay
1019 )
1021 def compute_mic(self, ExportedSessionKey, negotiate, challenge):
1022 self.MIC = b"\x00" * 16
1023 self.MIC = HMAC_MD5(
1024 ExportedSessionKey, bytes(negotiate) + bytes(challenge) + bytes(self)
1025 )
1027 def verify_mic(self, ExportedSessionKey, negotiate, challenge):
1028 auth = self.copy()
1029 auth.MIC = b"\x00" * 16
1030 return self.MIC == HMAC_MD5(
1031 ExportedSessionKey, bytes(negotiate) + bytes(challenge) + bytes(auth)
1032 )
1035class NTLM_AUTHENTICATE_V2(NTLM_AUTHENTICATE):
1036 NTLM_VERSION = 2
1039def HTTP_ntlm_negotiate(ntlm_negotiate):
1040 """Create an HTTP NTLM negotiate packet from an NTLM_NEGOTIATE message"""
1041 assert isinstance(ntlm_negotiate, NTLM_NEGOTIATE)
1042 from scapy.layers.http import HTTP, HTTPRequest
1044 return HTTP() / HTTPRequest(
1045 Authorization=b"NTLM " + bytes_base64(bytes(ntlm_negotiate))
1046 )
1049# Experimental - Reversed stuff
1051# This is the GSSAPI NegoEX Exchange metadata blob. This is not documented
1052# but described as an "opaque blob": this was reversed and everything is a
1053# placeholder.
1056class NEGOEX_EXCHANGE_NTLM_ITEM(ASN1_Packet):
1057 ASN1_codec = ASN1_Codecs.BER
1058 ASN1_root = ASN1F_SEQUENCE(
1059 ASN1F_SEQUENCE(
1060 ASN1F_SEQUENCE(
1061 ASN1F_OID("oid", ""),
1062 ASN1F_PRINTABLE_STRING("token", ""),
1063 explicit_tag=0x31,
1064 ),
1065 explicit_tag=0x80,
1066 )
1067 )
1070class NEGOEX_EXCHANGE_NTLM(ASN1_Packet):
1071 """
1072 GSSAPI NegoEX Exchange metadata blob
1073 This was reversed and may be meaningless
1074 """
1076 ASN1_codec = ASN1_Codecs.BER
1077 ASN1_root = ASN1F_SEQUENCE(
1078 ASN1F_SEQUENCE(
1079 ASN1F_SEQUENCE_OF("items", [], NEGOEX_EXCHANGE_NTLM_ITEM), implicit_tag=0xA0
1080 ),
1081 )
1084# Crypto - [MS-NLMP]
1087def HMAC_MD5(key, data):
1088 return Hmac_MD5(key=key).digest(data)
1091def MD4le(x):
1092 """
1093 MD4 over a string encoded as utf-16le
1094 """
1095 return Hash_MD4().digest(x.encode("utf-16le"))
1098def RC4Init(key):
1099 """Alleged RC4"""
1100 from cryptography.hazmat.primitives.ciphers import Cipher, algorithms
1102 try:
1103 # cryptography > 43.0
1104 from cryptography.hazmat.decrepit.ciphers import (
1105 algorithms as decrepit_algorithms,
1106 )
1107 except ImportError:
1108 decrepit_algorithms = algorithms
1110 algorithm = decrepit_algorithms.ARC4(key)
1111 cipher = Cipher(algorithm, mode=None)
1112 encryptor = cipher.encryptor()
1113 return encryptor
1116def RC4(handle, data):
1117 """The RC4 Encryption Algorithm"""
1118 return handle.update(data)
1121def RC4K(key, data):
1122 """Indicates the encryption of data item D with the key K using the
1123 RC4 algorithm.
1124 """
1125 from cryptography.hazmat.primitives.ciphers import Cipher, algorithms
1127 try:
1128 # cryptography > 43.0
1129 from cryptography.hazmat.decrepit.ciphers import (
1130 algorithms as decrepit_algorithms,
1131 )
1132 except ImportError:
1133 decrepit_algorithms = algorithms
1135 algorithm = decrepit_algorithms.ARC4(key)
1136 cipher = Cipher(algorithm, mode=None)
1137 encryptor = cipher.encryptor()
1138 return encryptor.update(data) + encryptor.finalize()
1141# sect 2.2.2.9 - With Extended Session Security
1144class NTLMSSP_MESSAGE_SIGNATURE(Packet):
1145 # [MS-RPCE] sect 2.2.2.9.1/2.2.2.9.2
1146 fields_desc = [
1147 LEIntField("Version", 0x00000001),
1148 XStrFixedLenField("Checksum", b"", length=8),
1149 LEIntField("SeqNum", 0x00000000),
1150 ]
1152 def default_payload_class(self, payload):
1153 return conf.padding_layer
1156_GSSAPI_OIDS["1.3.6.1.4.1.311.2.2.10"] = NTLM_Header
1157_GSSAPI_SIGNATURE_OIDS["1.3.6.1.4.1.311.2.2.10"] = NTLMSSP_MESSAGE_SIGNATURE
1160# sect 3.3.2
1163def NTOWFv2(Passwd, User, UserDom, HashNt=None):
1164 """
1165 Computes the ResponseKeyNT (per [MS-NLMP] sect 3.3.2)
1167 :param Passwd: the plain password
1168 :param User: the username
1169 :param UserDom: the domain name
1170 :param HashNt: (out of spec) if you have the HashNt, use this and set
1171 Passwd to None
1172 """
1173 if HashNt is None:
1174 HashNt = MD4le(Passwd)
1175 return HMAC_MD5(HashNt, (User.upper() + UserDom).encode("utf-16le"))
1178def NTLMv2_ComputeSessionBaseKey(ResponseKeyNT, NTProofStr):
1179 return HMAC_MD5(ResponseKeyNT, NTProofStr)
1182# sect 3.4.4.2 - With Extended Session Security
1185def MAC(Handle, SigningKey, SeqNum, Message):
1186 chksum = HMAC_MD5(SigningKey, struct.pack("<i", SeqNum) + Message)[:8]
1187 if Handle:
1188 chksum = RC4(Handle, chksum)
1189 return NTLMSSP_MESSAGE_SIGNATURE(
1190 Version=0x00000001,
1191 Checksum=chksum,
1192 SeqNum=SeqNum,
1193 )
1196# sect 3.4.2
1199def SIGN(Handle, SigningKey, SeqNum, Message):
1200 # append? where is this used?!
1201 return Message + MAC(Handle, SigningKey, SeqNum, Message)
1204# sect 3.4.3
1207def SEAL(Handle, SigningKey, SeqNum, Message):
1208 """
1209 SEAL() according to [MS-NLMP]
1210 """
1211 # this is unused. Use GSS_WrapEx
1212 sealed_message = RC4(Handle, Message)
1213 signature = MAC(Handle, SigningKey, SeqNum, Message)
1214 return sealed_message, signature
1217def UNSEAL(Handle, SigningKey, SeqNum, Message):
1218 """
1219 UNSEAL() according to [MS-NLMP]
1220 """
1221 # this is unused. Use GSS_UnwrapEx
1222 unsealed_message = RC4(Handle, Message)
1223 signature = MAC(Handle, SigningKey, SeqNum, Message)
1224 return unsealed_message, signature
1227# sect 3.4.5.2
1230def SIGNKEY(NegFlg, ExportedSessionKey, Mode):
1231 if NegFlg.NEGOTIATE_EXTENDED_SESSIONSECURITY:
1232 if Mode == "Client":
1233 return Hash_MD5().digest(
1234 ExportedSessionKey
1235 + b"session key to client-to-server signing key magic constant\x00"
1236 )
1237 elif Mode == "Server":
1238 return Hash_MD5().digest(
1239 ExportedSessionKey
1240 + b"session key to server-to-client signing key magic constant\x00"
1241 )
1242 else:
1243 raise ValueError("Unknown Mode")
1244 else:
1245 return None
1248# sect 3.4.5.3
1251def SEALKEY(NegFlg, ExportedSessionKey, Mode):
1252 if NegFlg.NEGOTIATE_EXTENDED_SESSIONSECURITY:
1253 if NegFlg.NEGOTIATE_128:
1254 SealKey = ExportedSessionKey
1255 elif NegFlg.NEGOTIATE_56:
1256 SealKey = ExportedSessionKey[:7]
1257 else:
1258 SealKey = ExportedSessionKey[:5]
1259 if Mode == "Client":
1260 return Hash_MD5().digest(
1261 SealKey
1262 + b"session key to client-to-server sealing key magic constant\x00"
1263 )
1264 elif Mode == "Server":
1265 return Hash_MD5().digest(
1266 SealKey
1267 + b"session key to server-to-client sealing key magic constant\x00"
1268 )
1269 else:
1270 raise ValueError("Unknown Mode")
1271 elif NegFlg.NEGOTIATE_LM_KEY:
1272 if NegFlg.NEGOTIATE_56:
1273 return ExportedSessionKey[:6] + b"\xa0"
1274 else:
1275 return ExportedSessionKey[:4] + b"\xe5\x38\xb0"
1276 else:
1277 return ExportedSessionKey
1280# --- SSP
1283class NTLMSSP(SSP):
1284 """
1285 The NTLM SSP
1287 Common arguments:
1289 :param USE_MIC: whether to use a MIC or not (default: True)
1290 :param NTLM_VALUES: a dictionary used to override the following values
1292 In case of a client::
1294 - NegotiateFlags
1295 - ProductMajorVersion
1296 - ProductMinorVersion
1297 - ProductBuild
1299 In case of a server::
1301 - NetbiosDomainName
1302 - NetbiosComputerName
1303 - DnsComputerName
1304 - DnsDomainName (defaults to DOMAIN)
1305 - DnsTreeName (defaults to DOMAIN)
1306 - Flags
1307 - Timestamp
1309 Client-only arguments:
1311 :param UPN: the UPN to use for NTLM auth. If no domain is specified, will
1312 use the one provided by the server (domain in a domain, local
1313 if without domain)
1314 :param HASHNT: the password to use for NTLM auth
1315 :param PASSWORD: the password to use for NTLM auth
1316 :param LOCAL: use local authentication (must be running locally on Windows)
1318 Server-only arguments:
1320 :param DOMAIN_FQDN: the domain FQDN (default: domain.local)
1321 :param DOMAIN_NB_NAME: the domain Netbios name (default: strip DOMAIN_FQDN)
1322 :param COMPUTER_NB_NAME: the server Netbios name (default: SRV)
1323 :param COMPUTER_FQDN: the server FQDN
1324 (default: <computer_nb_name>.<domain_fqdn>)
1325 :param IDENTITIES: a dict {"username": <HashNT>}
1326 Setting this value enables signature computation and
1327 authenticates inbound users.
1328 """
1330 auth_type = 0x0A
1332 class STATE(SSP.STATE):
1333 INIT = 1
1334 CLI_SENT_NEGO = 2
1335 CLI_SENT_AUTH = 3
1336 SRV_SENT_CHAL = 4
1338 class CONTEXT(SSP.CONTEXT):
1339 __slots__ = [
1340 "SessionKey",
1341 "ExportedSessionKey",
1342 "IsAcceptor",
1343 "SendSignKey",
1344 "SendSealKey",
1345 "RecvSignKey",
1346 "RecvSealKey",
1347 "SendSealHandle",
1348 "RecvSealHandle",
1349 "SendSeqNum",
1350 "RecvSeqNum",
1351 "neg_tok",
1352 "chall_tok",
1353 "ServerHostname",
1354 "ServerDomain",
1355 ]
1357 @crypto_validator
1358 def __init__(self, IsAcceptor, req_flags=None):
1359 self.state = NTLMSSP.STATE.INIT
1360 self.SessionKey = None
1361 self.ExportedSessionKey = None
1362 self.SendSignKey = None
1363 self.SendSealKey = None
1364 self.SendSealHandle = None
1365 self.RecvSignKey = None
1366 self.RecvSealKey = None
1367 self.RecvSealHandle = None
1368 self.SendSeqNum = 0
1369 self.RecvSeqNum = 0
1370 self.neg_tok = None
1371 self.chall_tok = None
1372 self.ServerHostname = None
1373 self.ServerDomain = None
1374 self.IsAcceptor = IsAcceptor
1375 super(NTLMSSP.CONTEXT, self).__init__(req_flags=req_flags)
1377 def clifailure(self):
1378 self.__init__(self.IsAcceptor, req_flags=self.flags)
1380 def __repr__(self):
1381 return "NTLMSSP"
1383 # [MS-NLMP] note <36>: "the maximum lifetime is 36 hours" (lol, Kerberos has 5min)
1384 NTLM_MaxLifetime = 36 * 3600
1386 def __init__(
1387 self,
1388 UPN=None,
1389 HASHNT=None,
1390 PASSWORD=None,
1391 USE_MIC=True,
1392 VARIANT: NTLM_VARIANT = NTLM_VARIANT.RECENT,
1393 NTLM_VALUES={},
1394 DOMAIN_FQDN=None,
1395 DOMAIN_NB_NAME=None,
1396 COMPUTER_NB_NAME=None,
1397 COMPUTER_FQDN=None,
1398 IDENTITIES=None,
1399 DO_NOT_CHECK_LOGIN=False,
1400 SERVER_CHALLENGE=None,
1401 **kwargs,
1402 ):
1403 self.UPN = UPN
1404 if HASHNT is None and PASSWORD is not None:
1405 HASHNT = MD4le(PASSWORD)
1406 self.HASHNT = HASHNT
1407 self.VARIANT = VARIANT
1408 if self.VARIANT != NTLM_VARIANT.RECENT:
1409 log_runtime.warning(
1410 "VARIANT != NTLM_VARIANT.RECENT. You shouldn't touch this !"
1411 )
1412 self.USE_MIC = False
1413 else:
1414 self.USE_MIC = USE_MIC
1416 if UPN is not None:
1417 # Populate values used only in server mode.
1418 from scapy.layers.kerberos import _parse_upn
1420 try:
1421 user, realm = _parse_upn(UPN)
1422 if DOMAIN_FQDN is None:
1423 DOMAIN_FQDN = realm
1424 if COMPUTER_NB_NAME is None:
1425 COMPUTER_NB_NAME = user
1426 except ValueError:
1427 pass
1429 # Compute various netbios/fqdn names
1430 self.DOMAIN_FQDN = DOMAIN_FQDN or "WORKGROUP"
1431 self.DOMAIN_NB_NAME = (
1432 DOMAIN_NB_NAME or self.DOMAIN_FQDN.split(".")[0].upper()[:15]
1433 )
1434 self.COMPUTER_NB_NAME = COMPUTER_NB_NAME or "WIN10"
1435 self.COMPUTER_FQDN = COMPUTER_FQDN or (
1436 self.COMPUTER_NB_NAME.lower() + "." + self.DOMAIN_FQDN
1437 )
1438 self.NTLM_VALUES = NTLM_VALUES
1440 if IDENTITIES:
1441 self.IDENTITIES = {
1442 # Windows usernames are case insensitive
1443 user.upper(): hashnt
1444 for user, hashnt in IDENTITIES.items()
1445 }
1446 else:
1447 self.IDENTITIES = IDENTITIES
1449 self.DO_NOT_CHECK_LOGIN = DO_NOT_CHECK_LOGIN
1450 self.SERVER_CHALLENGE = SERVER_CHALLENGE
1451 super(NTLMSSP, self).__init__(**kwargs)
1453 def LegsAmount(self, Context: CONTEXT):
1454 return 3
1456 def GSS_Inquire_names_for_mech(self):
1457 return ["1.3.6.1.4.1.311.2.2.10"]
1459 def GSS_GetMICEx(self, Context, msgs, qop_req=0):
1460 """
1461 [MS-NLMP] sect 3.4.8
1462 """
1463 # Concatenate the ToSign
1464 ToSign = b"".join(x.data for x in msgs if x.sign)
1465 sig = MAC(
1466 Context.SendSealHandle,
1467 Context.SendSignKey,
1468 Context.SendSeqNum,
1469 ToSign,
1470 )
1471 Context.SendSeqNum += 1
1472 return sig
1474 def GSS_VerifyMICEx(self, Context, msgs, signature):
1475 """
1476 [MS-NLMP] sect 3.4.9
1477 """
1478 # [MS-NLMP] sect 3.4.4; [RFC2743] sect 1.2.3
1479 if (
1480 not Context.passive
1481 and Context.flags
1482 & (GSS_C_FLAGS.GSS_C_REPLAY_FLAG | GSS_C_FLAGS.GSS_C_SEQUENCE_FLAG)
1483 and signature.SeqNum != Context.RecvSeqNum
1484 ):
1485 raise ValueError("ERROR: Sequence numbers don't match")
1487 # Concatenate the ToSign
1488 ToSign = b"".join(x.data for x in msgs if x.sign)
1489 sig = MAC(
1490 Context.RecvSealHandle,
1491 Context.RecvSignKey,
1492 signature.SeqNum,
1493 ToSign,
1494 )
1495 if sig.Checksum != signature.Checksum:
1496 raise ValueError("ERROR: Checksums don't match")
1498 Context.RecvSeqNum = signature.SeqNum + 1
1500 def GSS_WrapEx(self, Context, msgs, qop_req=0):
1501 """
1502 [MS-NLMP] sect 3.4.6
1503 """
1504 msgs_cpy = copy.deepcopy(msgs) # Keep copy for signature
1505 # Encrypt
1506 for msg in msgs:
1507 if msg.conf_req_flag:
1508 msg.data = RC4(Context.SendSealHandle, msg.data)
1509 # Sign
1510 sig = self.GSS_GetMICEx(Context, msgs_cpy, qop_req=qop_req)
1511 return (
1512 msgs,
1513 sig,
1514 )
1516 def GSS_UnwrapEx(self, Context, msgs, signature):
1517 """
1518 [MS-NLMP] sect 3.4.7
1519 """
1520 # [MS-NLMP] sect 3.4.4: reject before consuming the RC4 stream.
1521 if (
1522 not Context.passive
1523 and Context.flags
1524 & (GSS_C_FLAGS.GSS_C_REPLAY_FLAG | GSS_C_FLAGS.GSS_C_SEQUENCE_FLAG)
1525 and signature.SeqNum != Context.RecvSeqNum
1526 ):
1527 raise ValueError("ERROR: Sequence numbers don't match")
1529 # Decrypt
1530 for msg in msgs:
1531 if msg.conf_req_flag:
1532 msg.data = RC4(Context.RecvSealHandle, msg.data)
1533 # Check signature
1534 self.GSS_VerifyMICEx(Context, msgs, signature)
1535 return msgs
1537 def SupportsMechListMIC(self):
1538 if not self.USE_MIC:
1539 # RFC 4178
1540 # "If the mechanism selected by the negotiation does not support integrity
1541 # protection, then no mechlistMIC token is used."
1542 return False
1543 if self.DO_NOT_CHECK_LOGIN:
1544 # In this mode, we won't negotiate any credentials.
1545 return False
1546 return True
1548 def GetMechListMIC(self, Context, input):
1549 # [MS-SPNG]
1550 # "When NTLM is negotiated, the SPNG server MUST set OriginalHandle to
1551 # ServerHandle before generating the mechListMIC, then set ServerHandle to
1552 # OriginalHandle after generating the mechListMIC."
1553 OriginalHandle = Context.SendSealHandle
1554 Context.SendSealHandle = RC4Init(Context.SendSealKey)
1555 try:
1556 return super(NTLMSSP, self).GetMechListMIC(Context, input)
1557 finally:
1558 Context.SendSealHandle = OriginalHandle
1560 def VerifyMechListMIC(self, Context, otherMIC, input):
1561 # [MS-SPNG]
1562 # "the SPNEGO Extension server MUST set OriginalHandle to ClientHandle before
1563 # validating the mechListMIC and then set ClientHandle to OriginalHandle after
1564 # validating the mechListMIC."
1565 OriginalHandle = Context.RecvSealHandle
1566 Context.RecvSealHandle = RC4Init(Context.RecvSealKey)
1567 try:
1568 return super(NTLMSSP, self).VerifyMechListMIC(Context, otherMIC, input)
1569 finally:
1570 Context.RecvSealHandle = OriginalHandle
1572 def GSS_Init_sec_context(
1573 self,
1574 Context: CONTEXT,
1575 input_token=None,
1576 target_name: Optional[str] = None,
1577 req_flags: Optional[GSS_C_FLAGS] = None,
1578 chan_bindings: GssChannelBindings = GSS_C_NO_CHANNEL_BINDINGS,
1579 ):
1580 if Context is None:
1581 Context = self.CONTEXT(False, req_flags=req_flags)
1583 if Context.state == self.STATE.INIT:
1584 # Client: negotiate
1586 # Create a default token
1587 tok = NTLM_NEGOTIATE(
1588 VARIANT=self.VARIANT,
1589 NegotiateFlags="+".join(
1590 [
1591 "NEGOTIATE_UNICODE",
1592 "REQUEST_TARGET",
1593 "NEGOTIATE_NTLM",
1594 "NEGOTIATE_ALWAYS_SIGN",
1595 "TARGET_TYPE_DOMAIN",
1596 "NEGOTIATE_EXTENDED_SESSIONSECURITY",
1597 "NEGOTIATE_TARGET_INFO",
1598 "NEGOTIATE_128",
1599 "NEGOTIATE_56",
1600 ]
1601 + (
1602 ["NEGOTIATE_VERSION"]
1603 if self.VARIANT >= NTLM_VARIANT.XP_OR_2003
1604 else []
1605 )
1606 + (
1607 [
1608 "NEGOTIATE_KEY_EXCH",
1609 ]
1610 if Context.flags
1611 & (GSS_C_FLAGS.GSS_C_INTEG_FLAG | GSS_C_FLAGS.GSS_C_CONF_FLAG)
1612 else []
1613 )
1614 + (
1615 [
1616 "NEGOTIATE_SIGN",
1617 ]
1618 if Context.flags & GSS_C_FLAGS.GSS_C_INTEG_FLAG
1619 else []
1620 )
1621 + (
1622 [
1623 "NEGOTIATE_SEAL",
1624 ]
1625 if Context.flags & GSS_C_FLAGS.GSS_C_CONF_FLAG
1626 else []
1627 )
1628 + (
1629 [
1630 "NEGOTIATE_IDENTIFY",
1631 ]
1632 if Context.flags & GSS_C_FLAGS.GSS_C_IDENTIFY_FLAG
1633 else []
1634 )
1635 ),
1636 ProductMajorVersion=10,
1637 ProductMinorVersion=0,
1638 ProductBuild=26100,
1639 )
1641 # Update that token with the customs one
1642 if self.NTLM_VALUES:
1643 for key in [
1644 "NegotiateFlags",
1645 "ProductMajorVersion",
1646 "ProductMinorVersion",
1647 "ProductBuild",
1648 "DomainName",
1649 "WorkstationName",
1650 ]:
1651 if key in self.NTLM_VALUES:
1652 setattr(tok, key, self.NTLM_VALUES[key])
1653 Context.neg_tok = tok
1654 Context.SessionKey = None # Reset signing (if previous auth failed)
1655 Context.state = self.STATE.CLI_SENT_NEGO
1656 return Context, tok, GSS_S_CONTINUE_NEEDED
1657 elif Context.state == self.STATE.CLI_SENT_NEGO:
1658 # Client: auth (token=challenge)
1659 chall_tok = input_token
1661 if self.UPN is None or self.HASHNT is None:
1662 raise ValueError(
1663 "Must provide a 'UPN' and a 'HASHNT' or 'PASSWORD' when "
1664 "running in standalone !"
1665 )
1667 from scapy.layers.kerberos import _parse_upn
1669 # Check token sanity
1670 if not chall_tok or NTLM_CHALLENGE not in chall_tok:
1671 log_runtime.debug("NTLMSSP: Unexpected token. Expected NTLM Challenge")
1672 return Context, None, GSS_S_DEFECTIVE_TOKEN
1674 # Some information from the CHALLENGE are stored
1675 try:
1676 Context.ServerHostname = chall_tok.getAv(0x0001).Value
1677 except IndexError:
1678 pass
1679 try:
1680 Context.ServerDomain = chall_tok.getAv(0x0002).Value
1681 except IndexError:
1682 pass
1683 try:
1684 # the server SHOULD set the timestamp in the CHALLENGE_MESSAGE
1685 ServerTimestamp = chall_tok.getAv(0x0007).Value
1686 ServerTime = (ServerTimestamp / 1e7) - 11644473600
1688 if abs(ServerTime - time.time()) >= NTLMSSP.NTLM_MaxLifetime:
1689 log_runtime.warning(
1690 "Server and Client times are off by more than 36h !"
1691 )
1692 # We could error here, but we don't.
1693 except IndexError:
1694 pass
1696 # Initialize a default token
1697 tok = NTLM_AUTHENTICATE_V2(
1698 VARIANT=self.VARIANT,
1699 NegotiateFlags=chall_tok.NegotiateFlags,
1700 ProductMajorVersion=10,
1701 ProductMinorVersion=0,
1702 ProductBuild=26100,
1703 )
1705 # Populate the token
1706 tok.LmChallengeResponse = LMv2_RESPONSE()
1708 # 1. Set username
1709 try:
1710 tok.UserName, realm = _parse_upn(self.UPN)
1711 except ValueError:
1712 tok.UserName, realm = self.UPN, Context.ServerDomain
1714 # 2. Set domain name
1715 if realm is None:
1716 log_runtime.warning(
1717 "No realm specified in UPN, nor provided by server."
1718 )
1719 tok.DomainName = self.DOMAIN_FQDN
1720 else:
1721 tok.DomainName = realm
1723 # 3. Set workstation name
1724 tok.Workstation = self.COMPUTER_NB_NAME
1726 # 4. Create and calculate the ChallengeResponse
1727 # 4.1 Build the payload
1728 cr = tok.NtChallengeResponse = NTLMv2_RESPONSE(
1729 ChallengeFromClient=os.urandom(8),
1730 )
1731 cr.TimeStamp = int((time.time() + 11644473600) * 1e7)
1732 cr.AvPairs = (
1733 # Repeat AvPairs from the server
1734 chall_tok.TargetInfo[:-1]
1735 + (
1736 [
1737 AV_PAIR(AvId="MsvAvFlags", Value="MIC integrity"),
1738 ]
1739 if self.USE_MIC
1740 else []
1741 )
1742 + [
1743 AV_PAIR(
1744 AvId="MsvAvSingleHost",
1745 Value=Single_Host_Data(
1746 MachineID=os.urandom(32),
1747 CrossBootMachineID=os.urandom(32),
1748 ),
1749 ),
1750 ]
1751 + (
1752 [
1753 AV_PAIR(
1754 # [MS-NLMP] sect 2.2.2.1 refers to RFC 4121 sect 4.1.1.2
1755 # "The Bnd field contains the MD5 hash of channel bindings"
1756 AvId="MsvAvChannelBindings",
1757 Value=chan_bindings.digestMD5(),
1758 ),
1759 ]
1760 if chan_bindings != GSS_C_NO_CHANNEL_BINDINGS
1761 else []
1762 )
1763 + [
1764 AV_PAIR(
1765 AvId="MsvAvTargetName",
1766 Value=target_name or ("host/" + Context.ServerHostname),
1767 ),
1768 AV_PAIR(AvId="MsvAvEOL"),
1769 ]
1770 )
1771 if self.NTLM_VALUES:
1772 # Update that token with the customs one
1773 for key in [
1774 "NegotiateFlags",
1775 "ProductMajorVersion",
1776 "ProductMinorVersion",
1777 "ProductBuild",
1778 ]:
1779 if key in self.NTLM_VALUES:
1780 setattr(tok, key, self.NTLM_VALUES[key])
1782 # 4.2 Compute the ResponseKeyNT
1783 ResponseKeyNT = NTOWFv2(
1784 None,
1785 tok.UserName,
1786 tok.DomainName,
1787 HashNt=self.HASHNT,
1788 )
1790 # 4.3 Compute the NTProofStr
1791 cr.NTProofStr = cr.computeNTProofStr(
1792 ResponseKeyNT,
1793 chall_tok.ServerChallenge,
1794 )
1796 # 4.4 Compute the Session Key
1797 SessionBaseKey = NTLMv2_ComputeSessionBaseKey(ResponseKeyNT, cr.NTProofStr)
1798 KeyExchangeKey = SessionBaseKey # Only true for NTLMv2
1799 if chall_tok.NegotiateFlags.NEGOTIATE_KEY_EXCH:
1800 ExportedSessionKey = os.urandom(16)
1801 tok.EncryptedRandomSessionKey = RC4K(
1802 KeyExchangeKey,
1803 ExportedSessionKey,
1804 )
1805 else:
1806 ExportedSessionKey = KeyExchangeKey
1808 # 4.5 Compute the MIC
1809 if self.USE_MIC:
1810 tok.compute_mic(ExportedSessionKey, Context.neg_tok, chall_tok)
1812 # 5. Perform key computations
1813 Context.ExportedSessionKey = ExportedSessionKey
1814 # [MS-SMB] 3.2.5.3
1815 Context.SessionKey = Context.ExportedSessionKey
1816 # Compute NTLM keys
1817 Context.SendSignKey = SIGNKEY(
1818 tok.NegotiateFlags, ExportedSessionKey, "Client"
1819 )
1820 Context.SendSealKey = SEALKEY(
1821 tok.NegotiateFlags, ExportedSessionKey, "Client"
1822 )
1823 Context.SendSealHandle = RC4Init(Context.SendSealKey)
1824 Context.RecvSignKey = SIGNKEY(
1825 tok.NegotiateFlags, ExportedSessionKey, "Server"
1826 )
1827 Context.RecvSealKey = SEALKEY(
1828 tok.NegotiateFlags, ExportedSessionKey, "Server"
1829 )
1830 Context.RecvSealHandle = RC4Init(Context.RecvSealKey)
1832 # Update the state
1833 Context.state = self.STATE.CLI_SENT_AUTH
1835 return Context, tok, GSS_S_COMPLETE
1836 elif Context.state == self.STATE.CLI_SENT_AUTH:
1837 if input_token:
1838 # what is that?
1839 status = GSS_S_DEFECTIVE_TOKEN
1840 else:
1841 status = GSS_S_COMPLETE
1842 return Context, None, status
1843 else:
1844 raise ValueError("NTLMSSP: unexpected state %s" % repr(Context.state))
1846 def GSS_Accept_sec_context(
1847 self,
1848 Context: CONTEXT,
1849 input_token=None,
1850 req_flags: Optional[GSS_S_FLAGS] = GSS_S_FLAGS.GSS_S_ALLOW_MISSING_BINDINGS,
1851 chan_bindings: GssChannelBindings = GSS_C_NO_CHANNEL_BINDINGS,
1852 ):
1853 if Context is None:
1854 Context = self.CONTEXT(IsAcceptor=True, req_flags=req_flags)
1856 if Context.state == self.STATE.INIT:
1857 # Server: challenge (input_token=negotiate)
1858 neg_tok = input_token
1859 if not neg_tok or NTLM_NEGOTIATE not in neg_tok:
1860 log_runtime.debug("NTLMSSP: Unexpected token. Expected NTLM Negotiate")
1861 return Context, None, GSS_S_DEFECTIVE_TOKEN
1863 Context.neg_tok = neg_tok
1865 # Build the challenge token
1866 currentTime = (time.time() + 11644473600) * 1e7
1867 tok = NTLM_CHALLENGE(
1868 VARIANT=self.VARIANT,
1869 ServerChallenge=self.SERVER_CHALLENGE or os.urandom(8),
1870 NegotiateFlags="+".join(
1871 [
1872 "NEGOTIATE_UNICODE",
1873 "REQUEST_TARGET",
1874 "NEGOTIATE_NTLM",
1875 "NEGOTIATE_ALWAYS_SIGN",
1876 "NEGOTIATE_EXTENDED_SESSIONSECURITY",
1877 "NEGOTIATE_TARGET_INFO",
1878 "TARGET_TYPE_DOMAIN",
1879 "NEGOTIATE_128",
1880 "NEGOTIATE_KEY_EXCH",
1881 "NEGOTIATE_56",
1882 ]
1883 + (
1884 ["NEGOTIATE_VERSION"]
1885 if self.VARIANT >= NTLM_VARIANT.XP_OR_2003
1886 else []
1887 )
1888 + (
1889 ["NEGOTIATE_SIGN"]
1890 if neg_tok.NegotiateFlags.NEGOTIATE_SIGN
1891 else []
1892 )
1893 + (
1894 ["NEGOTIATE_SEAL"]
1895 if neg_tok.NegotiateFlags.NEGOTIATE_SEAL
1896 else []
1897 )
1898 ),
1899 ProductMajorVersion=10,
1900 ProductMinorVersion=0,
1901 ProductBuild=26100,
1902 Payload=[
1903 ("TargetName", ""),
1904 (
1905 "TargetInfo",
1906 [
1907 # MsvAvNbComputerName
1908 AV_PAIR(AvId=1, Value=self.COMPUTER_NB_NAME),
1909 # MsvAvNbDomainName
1910 AV_PAIR(AvId=2, Value=self.DOMAIN_NB_NAME),
1911 # MsvAvDnsComputerName
1912 AV_PAIR(AvId=3, Value=self.COMPUTER_FQDN),
1913 # MsvAvDnsDomainName
1914 AV_PAIR(AvId=4, Value=self.DOMAIN_FQDN),
1915 # MsvAvDnsTreeName
1916 AV_PAIR(AvId=5, Value=self.DOMAIN_FQDN),
1917 # MsvAvTimestamp
1918 AV_PAIR(AvId=7, Value=currentTime),
1919 # MsvAvEOL
1920 AV_PAIR(AvId=0),
1921 ],
1922 ),
1923 ],
1924 )
1925 if self.NTLM_VALUES:
1926 # Update that token with the customs one
1927 for key in [
1928 "ServerChallenge",
1929 "NegotiateFlags",
1930 "ProductMajorVersion",
1931 "ProductMinorVersion",
1932 "TargetName",
1933 ]:
1934 if key in self.NTLM_VALUES:
1935 setattr(tok, key, self.NTLM_VALUES[key])
1936 avpairs = {x.AvId: x.Value for x in tok.TargetInfo}
1937 tok.TargetInfo = [
1938 AV_PAIR(AvId=i, Value=self.NTLM_VALUES.get(x, avpairs[i]))
1939 for (i, x) in [
1940 (2, "NetbiosDomainName"),
1941 (1, "NetbiosComputerName"),
1942 (4, "DnsDomainName"),
1943 (3, "DnsComputerName"),
1944 (5, "DnsTreeName"),
1945 (6, "Flags"),
1946 (7, "Timestamp"),
1947 (0, None),
1948 ]
1949 if ((x in self.NTLM_VALUES) or (i in avpairs))
1950 and self.NTLM_VALUES.get(x, True) is not None
1951 ]
1953 # Store for next step
1954 Context.chall_tok = tok
1956 # Update the state
1957 Context.state = self.STATE.SRV_SENT_CHAL
1959 return Context, tok, GSS_S_CONTINUE_NEEDED
1960 elif Context.state == self.STATE.SRV_SENT_CHAL:
1961 # server: OK or challenge again (input_token=auth)
1962 auth_tok = input_token
1964 if not auth_tok or NTLM_AUTHENTICATE_V2 not in auth_tok:
1965 log_runtime.debug(
1966 "NTLMSSP: Unexpected token. Expected NTLM Authenticate v2"
1967 )
1968 return Context, None, GSS_S_DEFECTIVE_TOKEN
1970 if self.DO_NOT_CHECK_LOGIN:
1971 # Just trust me bro. Typically used in "guest" mode.
1972 return Context, None, GSS_S_COMPLETE
1974 # Compute the session key
1975 SessionBaseKey = self._getSessionBaseKey(Context, auth_tok)
1976 if SessionBaseKey:
1977 # [MS-NLMP] sect 3.2.5.1.2
1978 KeyExchangeKey = SessionBaseKey # Only true for NTLMv2
1979 if auth_tok.NegotiateFlags.NEGOTIATE_KEY_EXCH:
1980 try:
1981 EncryptedRandomSessionKey = auth_tok.EncryptedRandomSessionKey
1982 except AttributeError:
1983 # No EncryptedRandomSessionKey. libcurl for instance
1984 # hmm. this looks bad
1985 EncryptedRandomSessionKey = b"\x00" * 16
1986 ExportedSessionKey = RC4K(KeyExchangeKey, EncryptedRandomSessionKey)
1987 else:
1988 ExportedSessionKey = KeyExchangeKey
1989 Context.ExportedSessionKey = ExportedSessionKey
1990 # [MS-SMB] 3.2.5.3
1991 Context.SessionKey = Context.ExportedSessionKey
1992 else:
1993 # Bad NTProofStr or unknown user
1994 Context.SessionKey = None
1995 Context.state = self.STATE.INIT
1996 return Context, None, GSS_S_DEFECTIVE_CREDENTIAL
1998 # Verify MIC
1999 try:
2000 Flags = auth_tok.NtChallengeResponse.getAv(0x0006).Value
2001 if Flags & 2:
2002 # MIC is required
2003 if not auth_tok.verify_mic(
2004 ExportedSessionKey, Context.neg_tok, Context.chall_tok
2005 ):
2006 log_runtime.warning("Client MIC is invalid !")
2007 return Context, None, GSS_S_BAD_MIC
2008 except IndexError:
2009 pass
2011 # Check the timestamp
2012 try:
2013 ClientTimestamp = auth_tok.NtChallengeResponse.getAv(0x0007).Value
2014 ClientTime = (ClientTimestamp / 1e7) - 11644473600
2016 if abs(ClientTime - time.time()) >= NTLMSSP.NTLM_MaxLifetime:
2017 log_runtime.warning(
2018 "Server and Client times are off by more than 36h !"
2019 )
2020 # We could error here, but we don't.
2021 except IndexError:
2022 pass
2024 # Check the channel bindings
2025 if chan_bindings == GSS_C_NO_CHANNEL_BINDINGS:
2026 if (
2027 req_flags is not None
2028 and GSS_S_FLAGS.GSS_S_ALLOW_MISSING_BINDINGS
2029 not in req_flags
2030 ):
2031 return Context, None, GSS_S_BAD_BINDINGS
2032 else:
2033 try:
2034 Bnd = auth_tok.NtChallengeResponse.getAv(0x000A).Value
2035 if Bnd != chan_bindings.digestMD5():
2036 # Bad channel bindings
2037 return Context, None, GSS_S_BAD_BINDINGS
2038 except IndexError:
2039 if GSS_S_FLAGS.GSS_S_ALLOW_MISSING_BINDINGS not in req_flags:
2040 # Uhoh, we required channel bindings
2041 return Context, None, GSS_S_BAD_BINDINGS
2043 # Compute NTLM keys
2044 Context.SendSignKey = SIGNKEY(
2045 auth_tok.NegotiateFlags, ExportedSessionKey, "Server"
2046 )
2047 Context.SendSealKey = SEALKEY(
2048 auth_tok.NegotiateFlags, ExportedSessionKey, "Server"
2049 )
2050 Context.SendSealHandle = RC4Init(Context.SendSealKey)
2051 Context.RecvSignKey = SIGNKEY(
2052 auth_tok.NegotiateFlags, ExportedSessionKey, "Client"
2053 )
2054 Context.RecvSealKey = SEALKEY(
2055 auth_tok.NegotiateFlags, ExportedSessionKey, "Client"
2056 )
2057 Context.RecvSealHandle = RC4Init(Context.RecvSealKey)
2059 # Check the NTProofStr
2060 if self._checkLogin(Context, auth_tok):
2061 # Set negotiated flags
2062 if auth_tok.NegotiateFlags.NEGOTIATE_SIGN:
2063 Context.flags |= GSS_C_FLAGS.GSS_C_INTEG_FLAG
2064 if auth_tok.NegotiateFlags.NEGOTIATE_SEAL:
2065 Context.flags |= GSS_C_FLAGS.GSS_C_CONF_FLAG
2066 return Context, None, GSS_S_COMPLETE
2068 else:
2069 raise ValueError("NTLMSSP: unexpected state %s" % repr(Context.state))
2071 def MaximumSignatureLength(self, Context: CONTEXT):
2072 """
2073 Returns the Maximum Signature length.
2075 This will be used in auth_len in DceRpc5, and is necessary for
2076 PFC_SUPPORT_HEADER_SIGN to work properly.
2077 """
2078 return 16 # len(NTLMSSP_MESSAGE_SIGNATURE())
2080 def GSS_Passive(self, Context: CONTEXT, token=None, req_flags=None):
2081 if Context is None:
2082 Context = self.CONTEXT(True)
2083 Context.passive = True
2085 # We capture the Negotiate, Challenge, then call the server's auth handling
2086 # and discard the output.
2088 if Context.state == self.STATE.INIT:
2089 if not token or NTLM_NEGOTIATE not in token:
2090 log_runtime.warning("NTLMSSP: Expected NTLM Negotiate")
2091 return None, GSS_S_DEFECTIVE_TOKEN
2092 Context.neg_tok = token
2093 Context.state = self.STATE.CLI_SENT_NEGO
2094 return Context, GSS_S_CONTINUE_NEEDED
2095 elif Context.state == self.STATE.CLI_SENT_NEGO:
2096 if not token or NTLM_CHALLENGE not in token:
2097 log_runtime.warning("NTLMSSP: Expected NTLM Challenge")
2098 return None, GSS_S_DEFECTIVE_TOKEN
2099 Context.chall_tok = token
2100 Context.state = self.STATE.SRV_SENT_CHAL
2101 return Context, GSS_S_CONTINUE_NEEDED
2102 elif Context.state == self.STATE.SRV_SENT_CHAL:
2103 if not token or NTLM_AUTHENTICATE_V2 not in token:
2104 log_runtime.warning("NTLMSSP: Expected NTLM Authenticate")
2105 return None, GSS_S_DEFECTIVE_TOKEN
2106 Context, _, status = self.GSS_Accept_sec_context(Context, token)
2107 if status != GSS_S_COMPLETE:
2108 log_runtime.info("NTLMSSP: auth failed.")
2109 Context.state = self.STATE.INIT
2110 return Context, status
2111 else:
2112 raise ValueError("NTLMSSP: unexpected state %s" % repr(Context.state))
2114 def GSS_Passive_set_Direction(self, Context: CONTEXT, IsAcceptor=False):
2115 if Context.IsAcceptor is not IsAcceptor:
2116 return
2117 # Swap everything
2118 Context.SendSignKey, Context.RecvSignKey = (
2119 Context.RecvSignKey,
2120 Context.SendSignKey,
2121 )
2122 Context.SendSealKey, Context.RecvSealKey = (
2123 Context.RecvSealKey,
2124 Context.SendSealKey,
2125 )
2126 Context.SendSealHandle, Context.RecvSealHandle = (
2127 Context.RecvSealHandle,
2128 Context.SendSealHandle,
2129 )
2130 Context.SendSeqNum, Context.RecvSeqNum = Context.RecvSeqNum, Context.SendSeqNum
2131 Context.IsAcceptor = not Context.IsAcceptor
2133 def _getSessionBaseKey(self, Context, auth_tok):
2134 """
2135 Function that returns the SessionBaseKey from the ntlm Authenticate.
2136 """
2137 try:
2138 # Windows usernames are case insensitive
2139 username = auth_tok.UserName.upper()
2140 except AttributeError:
2141 username = None
2142 try:
2143 domain = auth_tok.DomainName
2144 except AttributeError:
2145 domain = ""
2146 if self.IDENTITIES and username in self.IDENTITIES:
2147 ResponseKeyNT = NTOWFv2(
2148 None,
2149 username,
2150 domain,
2151 HashNt=self.IDENTITIES[username],
2152 )
2153 return NTLMv2_ComputeSessionBaseKey(
2154 ResponseKeyNT,
2155 auth_tok.NtChallengeResponse.NTProofStr,
2156 )
2157 elif self.IDENTITIES:
2158 log_runtime.debug("NTLMSSP: Bad credentials for %s" % username)
2159 return None
2161 def _checkLogin(self, Context, auth_tok):
2162 """
2163 Function that checks the validity of an authentication.
2165 Overwrite and return True to bypass.
2166 """
2167 try:
2168 # Windows usernames are case insensitive
2169 username = auth_tok.UserName.upper()
2170 except AttributeError:
2171 username = None
2172 try:
2173 domain = auth_tok.DomainName
2174 except AttributeError:
2175 domain = ""
2176 if username in self.IDENTITIES:
2177 ResponseKeyNT = NTOWFv2(
2178 None,
2179 username,
2180 domain,
2181 HashNt=self.IDENTITIES[username],
2182 )
2183 NTProofStr = auth_tok.NtChallengeResponse.computeNTProofStr(
2184 ResponseKeyNT,
2185 Context.chall_tok.ServerChallenge,
2186 )
2187 if NTProofStr == auth_tok.NtChallengeResponse.NTProofStr:
2188 return True
2189 return False
2192class NTLMSSP_DOMAIN(NTLMSSP):
2193 """
2194 A variant of the NTLMSSP to be used in server mode that gets the session
2195 keys from the domain using a Netlogon channel.
2197 This has the same arguments as NTLMSSP, but supports the following in server
2198 mode:
2200 :param UPN: the UPN of the machine account to login for Netlogon.
2201 :param HASHNT: the HASHNT of the machine account (use Netlogon secure channel).
2202 :param ssp: a KerberosSSP to use (use Kerberos secure channel).
2203 :param PASSWORD: the PASSWORD of the machine account to use for Netlogon.
2204 :param DC_FQDN: (optional) specify the FQDN of the DC.
2206 Netlogon example::
2208 >>> mySSP = NTLMSSP_DOMAIN(
2209 ... UPN="Server1@domain.local",
2210 ... HASHNT=bytes.fromhex("8846f7eaee8fb117ad06bdd830b7586c"),
2211 ... )
2213 Kerberos example::
2215 >>> mySSP = NTLMSSP_DOMAIN(
2216 ... UPN="Server1@domain.local",
2217 ... KEY=Key(EncryptionType.AES256_CTS_HMAC_SHA1_96,
2218 ... key=bytes.fromhex(
2219 ... "85abb9b61dc2fa49d4cc04317bbd108f8f79df28"
2220 ... "239155ed7b144c5d2ebcf016"
2221 ... )
2222 ... ),
2223 ... )
2224 """
2226 def __init__(self, UPN=None, *args, timeout=3, ssp=None, **kwargs):
2227 from scapy.layers.kerberos import KerberosSSP
2229 # Either PASSWORD or HASHNT or ssp
2230 if (
2231 "HASHNT" not in kwargs
2232 and "PASSWORD" not in kwargs
2233 and "KEY" not in kwargs
2234 and ssp is None
2235 ):
2236 raise ValueError(
2237 "Must specify either 'HASHNT', 'PASSWORD' or "
2238 "provide a ssp=KerberosSSP()"
2239 )
2240 elif ssp is not None and not isinstance(ssp, KerberosSSP):
2241 raise ValueError("'ssp' can only be None or a KerberosSSP !")
2243 self.KEY = kwargs.pop("KEY", None)
2244 self.PASSWORD = kwargs.get("PASSWORD", None)
2246 # UPN is mandatory
2247 if UPN is None and ssp is not None and ssp.UPN:
2248 UPN = ssp.UPN
2249 elif UPN is None:
2250 raise ValueError("Must specify a 'UPN' !")
2251 kwargs["UPN"] = UPN
2253 # Call parent
2254 super(NTLMSSP_DOMAIN, self).__init__(
2255 *args,
2256 **kwargs,
2257 )
2259 # Treat specific parameters
2260 self.DC_FQDN = kwargs.pop("DC_FQDN", None)
2261 if self.DC_FQDN is None:
2262 # Get DC_FQDN from dclocator
2263 from scapy.layers.ldap import dclocator
2265 dc = dclocator(
2266 self.DOMAIN_FQDN,
2267 timeout=timeout,
2268 debug=kwargs.get("debug", 0),
2269 )
2270 self.DC_FQDN = dc.samlogon.DnsHostName.decode().rstrip(".")
2272 # If logging in via Kerberos
2273 self.ssp = ssp
2275 def _getSessionBaseKey(self, Context, ntlm):
2276 """
2277 Return the Session Key by asking the DC.
2278 """
2279 # No user / no domain: skip.
2280 if not ntlm.UserNameLen or not ntlm.DomainNameLen:
2281 return super(NTLMSSP_DOMAIN, self)._getSessionBaseKey(Context, ntlm)
2283 # Import RPC stuff
2284 from scapy.layers.dcerpc import NDRUnion
2285 from scapy.layers.msrpce.msnrpc import (
2286 NETLOGON_SECURE_CHANNEL_METHOD,
2287 NetlogonClient,
2288 )
2289 from scapy.layers.msrpce.raw.ms_nrpc import (
2290 NETLOGON_LOGON_IDENTITY_INFO,
2291 NetrLogonSamLogonWithFlags_Request,
2292 PNETLOGON_AUTHENTICATOR,
2293 PNETLOGON_NETWORK_INFO,
2294 STRING,
2295 UNICODE_STRING,
2296 )
2298 # Create NetlogonClient with PRIVACY
2299 client = NetlogonClient()
2300 client.connect(self.DC_FQDN)
2302 # Establish the Netlogon secure channel (this will bind)
2303 try:
2304 if self.ssp is None and self.KEY is None:
2305 # Login via classic NetlogonSSP
2306 client.establish_secure_channel(
2307 mode=NETLOGON_SECURE_CHANNEL_METHOD.NetrServerAuthenticate3,
2308 UPN=f"{self.COMPUTER_NB_NAME}@{self.DOMAIN_NB_NAME}",
2309 DC_FQDN=self.DC_FQDN,
2310 HASHNT=self.HASHNT,
2311 )
2312 else:
2313 # Login via KerberosSSP (Windows 2025)
2314 client.establish_secure_channel(
2315 mode=NETLOGON_SECURE_CHANNEL_METHOD.NetrServerAuthenticateKerberos,
2316 UPN=self.UPN,
2317 DC_FQDN=self.DC_FQDN,
2318 PASSWORD=self.PASSWORD,
2319 KEY=self.KEY,
2320 ssp=self.ssp,
2321 )
2322 except ValueError:
2323 log_runtime.warning(
2324 "Couldn't establish the Netlogon secure channel. "
2325 "Check the credentials for '%s' !" % self.COMPUTER_NB_NAME
2326 )
2327 return super(NTLMSSP_DOMAIN, self)._getSessionBaseKey(Context, ntlm)
2329 # Request validation of the NTLM request
2330 req = NetrLogonSamLogonWithFlags_Request(
2331 LogonServer="",
2332 ComputerName=self.COMPUTER_NB_NAME,
2333 Authenticator=client.create_authenticator(),
2334 ReturnAuthenticator=PNETLOGON_AUTHENTICATOR(),
2335 LogonLevel=6, # NetlogonNetworkTransitiveInformation
2336 LogonInformation=NDRUnion(
2337 tag=6,
2338 value=PNETLOGON_NETWORK_INFO(
2339 Identity=NETLOGON_LOGON_IDENTITY_INFO(
2340 LogonDomainName=UNICODE_STRING(
2341 Buffer=ntlm.DomainName,
2342 ),
2343 ParameterControl=0x00002AE0,
2344 UserName=UNICODE_STRING(
2345 Buffer=ntlm.UserName,
2346 ),
2347 Workstation=UNICODE_STRING(
2348 Buffer=ntlm.Workstation,
2349 ),
2350 ),
2351 LmChallenge=Context.chall_tok.ServerChallenge,
2352 NtChallengeResponse=STRING(
2353 Buffer=bytes(ntlm.NtChallengeResponse),
2354 ),
2355 LmChallengeResponse=STRING(
2356 Buffer=bytes(ntlm.LmChallengeResponse),
2357 ),
2358 ),
2359 ),
2360 ValidationLevel=6,
2361 ExtraFlags=0,
2362 ndr64=client.ndr64,
2363 )
2365 # Get response
2366 resp = client.sr1_req(req)
2367 if resp and resp.status == 0:
2368 # Success
2370 # Validate DC authenticator
2371 client.validate_authenticator(resp.ReturnAuthenticator.value)
2373 # Get and return the SessionKey
2374 UserSessionKey = resp.ValidationInformation.value.value.UserSessionKey
2375 return bytes(UserSessionKey)
2376 else:
2377 # Failed
2378 return super(NTLMSSP_DOMAIN, self)._getSessionBaseKey(Context, ntlm)
2380 def _checkLogin(self, Context, auth_tok):
2381 # Always OK if we got the session key
2382 return True