dementor 1.0.0.dev11__tar.gz → 1.0.0.dev13__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.
Files changed (63) hide show
  1. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/PKG-INFO +26 -1
  2. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/README.md +11 -1
  3. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/__init__.py +1 -1
  4. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/assets/Dementor.toml +40 -1
  5. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/config/session.py +11 -0
  6. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/config/util.py +8 -3
  7. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/database.py +12 -6
  8. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/loader.py +0 -2
  9. dementor-1.0.0.dev13/dementor/log/__init__.py +24 -0
  10. dementor-1.0.0.dev13/dementor/log/hexdump.py +24 -0
  11. {dementor-1.0.0.dev11/dementor → dementor-1.0.0.dev13/dementor/log}/logger.py +11 -29
  12. dementor-1.0.0.dev13/dementor/log/stream.py +214 -0
  13. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/paths.py +1 -1
  14. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/ftp.py +1 -1
  15. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/http.py +11 -8
  16. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/imap.py +4 -4
  17. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/ipp.py +9 -5
  18. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/kerberos.py +1 -1
  19. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/ldap.py +7 -3
  20. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/llmnr.py +3 -2
  21. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/mdns.py +14 -7
  22. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/msrpc/rpc.py +6 -2
  23. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/mssql.py +34 -26
  24. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/mysql.py +31 -11
  25. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/netbios.py +10 -5
  26. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/pop3.py +2 -2
  27. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/quic.py +8 -6
  28. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/smb.py +11 -7
  29. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/smtp.py +1 -1
  30. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/ssdp.py +6 -4
  31. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/upnp.py +6 -3
  32. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/x11.py +3 -3
  33. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/servers.py +18 -2
  34. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/standalone.py +62 -23
  35. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor.egg-info/PKG-INFO +26 -1
  36. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor.egg-info/SOURCES.txt +4 -1
  37. dementor-1.0.0.dev13/docs/README.pypi.md +68 -0
  38. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/pyproject.toml +2 -2
  39. dementor-1.0.0.dev11/docs/README.pypi.md +0 -43
  40. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/LICENSE +0 -0
  41. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/__main__.py +0 -0
  42. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/assets/banner.txt +0 -0
  43. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/assets/www/error_page.html +0 -0
  44. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/assets/www/upnp-default/dd.xml +0 -0
  45. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/assets/www/upnp-default/present.html +0 -0
  46. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/assets/www/upnp-default/scpd.xml +0 -0
  47. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/assets/www/wpad.dat +0 -0
  48. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/config/__init__.py +0 -0
  49. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/config/attr.py +0 -0
  50. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/config/toml.py +0 -0
  51. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/filters.py +0 -0
  52. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/__init__.py +0 -0
  53. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/msrpc/__init__.py +0 -0
  54. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/msrpc/dcom.py +0 -0
  55. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/msrpc/epm.py +0 -0
  56. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/msrpc.py +0 -0
  57. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/ntlm.py +0 -0
  58. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor/protocols/spnego.py +0 -0
  59. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor.egg-info/dependency_links.txt +0 -0
  60. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor.egg-info/entry_points.txt +0 -0
  61. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor.egg-info/requires.txt +0 -0
  62. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/dementor.egg-info/top_level.txt +0 -0
  63. {dementor-1.0.0.dev11 → dementor-1.0.0.dev13}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dementor
3
- Version: 1.0.0.dev11
3
+ Version: 1.0.0.dev13
4
4
  Summary: LLMNR/NBT-NS/mDNS Poisoner and rogue service provider
5
5
  Author: MatrixEditor
6
6
  Maintainer: MatrixEditor
@@ -90,6 +90,21 @@ Let's take a look.
90
90
 
91
91
  ![index_video](https://raw.githubusercontent.com/MatrixEditor/dementor/refs/heads/master/docs/source/_static/images/index-video.gif)
92
92
 
93
+ ### CLI Options
94
+
95
+ ```
96
+ Usage: Dementor [OPTIONS]
97
+
98
+ ╭─ Options ────────────────────────────────────────────────────────────────────────────────────────────╮
99
+ │ * --interface -I NAME Network interface to use (required for poisoning) [required] │
100
+ │ --analyze -A Only analyze traffic, don't respond to requests │
101
+ │ --config -c PATH Path to a configuration file (otherwise standard path is used) │
102
+ │ --option -O KEY=VALUE Add an extra option to the global configuration file. │
103
+ │ --yes -y Do not ask before starting attack mode. │
104
+ │ --quiet -q Don't print banner at startup │
105
+ │ --help Show this message and exit. │
106
+ ╰──────────────────────────────────────────────────────────────────────────────────────────────────────╯
107
+ ```
93
108
 
94
109
  ## You need more?
95
110
 
@@ -99,3 +114,13 @@ Take a look at the [Documentation on GitHub-Pages](https://matrixeditor.github.i
99
114
  ## License
100
115
 
101
116
  Distributed under the MIT License. See LICENSE for more information.
117
+
118
+ ## Disclaimer
119
+
120
+ **Dementor** is intended only for lawful educational purposes: learning, testing
121
+ in your own lab, or assessments on systems where you have explicit written
122
+ authorization. You agree not to use this software to access, damage, interfere
123
+ with, or exfiltrate data from systems for which you do not have permission.
124
+ We make no promises about safety, completeness, or fitness for any purpose. Use
125
+ at your own risk. If you discover a vulnerability, please follow responsible
126
+ disclosure by using the private disclosing feature offered by GitHub.
@@ -56,4 +56,14 @@ Take a look at the [Documentation on GitHub-Pages](https://matrixeditor.github.i
56
56
 
57
57
  ## License
58
58
 
59
- Distributed under the MIT License. See LICENSE for more information.
59
+ Distributed under the MIT License. See LICENSE for more information.
60
+
61
+ ## Disclaimer
62
+
63
+ **Dementor** is intended only for lawful educational purposes: learning, testing
64
+ in your own lab, or assessments on systems where you have explicit written
65
+ authorization. You agree not to use this software to access, damage, interfere
66
+ with, or exfiltrate data from systems for which you do not have permission.
67
+ We make no promises about safety, completeness, or fitness for any purpose. Use
68
+ at your own risk. If you discover a vulnerability, please follow responsible
69
+ disclosure by using the private disclosing feature offered by GitHub.
@@ -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.dev11"
21
+ __version__ = "1.0.0.dev13"
22
22
  __author__ = "MatrixEditor"
@@ -708,7 +708,7 @@ AuthMechanisms = ["PLAIN", "LOGIN", "NTLM"]
708
708
 
709
709
  # default plaintext server
710
710
  [[IMAP.Server]]
711
- Port = 110
711
+ Port = 143
712
712
 
713
713
  # Example TLS server
714
714
  # [[POP3.Server]]
@@ -901,3 +901,42 @@ DebugLoggers = [
901
901
  "quic",
902
902
  "pyipp.parser",
903
903
  ]
904
+
905
+
906
+ [Log.Stream.Hosts]
907
+
908
+ # Uncommenting the Path variable will enable logging all identified clients
909
+ # within the network that either (1) establish a direct connection to dementor,
910
+ # or (2) via multicast/broadcast messages.
911
+
912
+ # Path = "./client_hosts.txt"
913
+
914
+ # Enables/Disables logging IPv4/v6 addresses
915
+
916
+ # IPv6 = true
917
+ # IPv4 = true
918
+
919
+ [Log.Stream.DNS]
920
+
921
+ # Uncommenting the Path variable will enable logging all multicast or broadcast
922
+ # name queries (currently: mDNS, LLMNR and NetBIOS).
923
+
924
+ # Path = "/absolute/path"
925
+
926
+ [Log.Stream.Hashes]
927
+
928
+ # Enables logging captured hashes either to a single output file or into
929
+ # separate files.
930
+
931
+ # Path = "./hash-collections"
932
+
933
+ # "Splits" the collected hashes into separate files.
934
+
935
+ # Split = true
936
+
937
+ # File prefix (dynamic string) and suffix to apply when writeing hashes to
938
+ # separate files.
939
+
940
+ # FilePrefix = "{{ hash_type }}-capture"
941
+ # FileSuffix = ".txt"
942
+
@@ -21,6 +21,8 @@ import asyncio
21
21
 
22
22
  from typing import Any, List
23
23
 
24
+ from pathlib import Path
25
+
24
26
  from dementor.config.toml import TomlConfig, Attribute
25
27
  from dementor.config.util import is_true
26
28
  from dementor.paths import DEMENTOR_PATH
@@ -102,3 +104,12 @@ class SessionConfig(TomlConfig):
102
104
  @property
103
105
  def ipv6_support(self) -> bool:
104
106
  return bool(self.ipv6) and not getattr(self, "ipv4_only", False)
107
+
108
+ def resolve_path(self, path: str | Path) -> Path:
109
+ raw_path = str(path)
110
+ if raw_path[0] == "/":
111
+ return Path(raw_path)
112
+ elif raw_path.startswith("./") or raw_path.startswith("../"):
113
+ return Path(raw_path).resolve()
114
+
115
+ return (Path(self.workspace_path) / raw_path).resolve()
@@ -17,6 +17,7 @@
17
17
  # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
18
  # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
19
  # SOFTWARE.
20
+ import datetime
20
21
  import random
21
22
  import string
22
23
  import secrets
@@ -38,7 +39,7 @@ def get_value(section: str, key: str | None, default=None) -> Any:
38
39
  else:
39
40
  target = config
40
41
  for section in sections:
41
- target = target[section]
42
+ target = target.get(section, {})
42
43
 
43
44
  if key is None:
44
45
  return target
@@ -77,11 +78,15 @@ def random_value(size: int) -> str:
77
78
  return "".join(random.choice(string.ascii_letters) for _ in range(size))
78
79
 
79
80
 
80
- def format_string(value: str) -> str:
81
+ def format_string(value: str, locals: dict | None = None) -> str:
81
82
  config = _get_global_config()
82
83
  try:
83
84
  template = _SANDBOX.from_string(value)
84
- return template.render(config=config, random=random_value)
85
+ return template.render(config=config, random=random_value, **(locals or {}))
85
86
  except Exception as e:
86
87
  # TODO: log that
87
88
  return value
89
+
90
+
91
+ def now() -> str:
92
+ return datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
@@ -32,8 +32,10 @@ from sqlalchemy import sql
32
32
  from sqlalchemy.exc import NoSuchTableError, NoInspectionAvailable, OperationalError
33
33
 
34
34
 
35
- from dementor.logger import dm_logger, dm_console_lock
35
+ from dementor.log.logger import dm_logger
36
+ from dementor.log import dm_console_lock
36
37
  from dementor.config.toml import TomlConfig, Attribute as A
38
+ from dementor.log.stream import log_to
37
39
 
38
40
 
39
41
  class DatabaseConfig(TomlConfig):
@@ -69,6 +71,8 @@ def init_dementor_db(session) -> str:
69
71
  # commit and save changes
70
72
  conn.commit()
71
73
  conn.close()
74
+
75
+ dm_logger.debug("Using database at: %s", db_path)
72
76
  return db_path
73
77
 
74
78
 
@@ -134,7 +138,7 @@ class DementorDB:
134
138
  "password" TEXT
135
139
  )"""
136
140
  )
137
-
141
+ # TODO: still unused
138
142
  cursor.execute(
139
143
  """CREATE TABLE "hosts" (
140
144
  "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
@@ -171,7 +175,7 @@ class DementorDB:
171
175
  if not logger and not protocol:
172
176
  dm_logger.error(
173
177
  f"Failed to add {credtype} for {username} on {client[0]}:{client[1]}: "
174
- "Protocol must be present either in the logger or as a parameter!"
178
+ + "Protocol must be present either in the logger or as a parameter!"
175
179
  )
176
180
  return
177
181
 
@@ -182,7 +186,7 @@ class DementorDB:
182
186
 
183
187
  target_logger.debug(
184
188
  f"Adding {credtype} for {username} on {client_address}: "
185
- f"{logger} | {protocol} | {domain} | {hostname} | {username} | {password}"
189
+ + f"{logger} | {protocol} | {domain} | {hostname} | {username} | {password}"
186
190
  )
187
191
 
188
192
  q = sql.select(self.CredentialsTable).filter(
@@ -203,7 +207,7 @@ class DementorDB:
203
207
  username_text = "(blank)"
204
208
 
205
209
  full_name = (
206
- f" for [b]{username_text}[/]/[b]{markup.escape(domain)}[/]"
210
+ f" for [b]{markup.escape(domain)}[/]/[b]{username_text}[/]"
207
211
  if domain
208
212
  else f" for [b]{username_text}[/]"
209
213
  )
@@ -211,6 +215,8 @@ class DementorDB:
211
215
  full_name = ""
212
216
 
213
217
  if not results or self.config.db_config.db_duplicate_creds:
218
+ if credtype != _CLEARTEXT:
219
+ log_to("hashes", type=credtype, value=password)
214
220
  # just insert a new row
215
221
  q = sql.insert(self.CredentialsTable).values(
216
222
  {
@@ -231,7 +237,7 @@ class DementorDB:
231
237
  if "readonly database" in str(e):
232
238
  dm_logger.warning(
233
239
  f"Failed to add {credtype} for {username} on {client_address}: "
234
- "Database is read-only! (maybe restart in sudo mode?)"
240
+ + "Database is read-only! (maybe restart in sudo mode?)"
235
241
  )
236
242
  else:
237
243
  raise
@@ -17,8 +17,6 @@
17
17
  # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
18
  # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
19
  # SOFTWARE.
20
- import argparse
21
- from ntpath import isfile
22
20
  import types
23
21
  import os
24
22
  import dementor
@@ -0,0 +1,24 @@
1
+ import threading
2
+ from rich.console import Console
3
+
4
+ dm_console = Console(
5
+ soft_wrap=True,
6
+ tab_size=4,
7
+ highlight=False,
8
+ highlighter=None,
9
+ )
10
+
11
+ dm_console_lock = threading.Lock()
12
+
13
+
14
+ def dm_print(msg: str, *args, **kwargs) -> None:
15
+ # If someone has a better idea I'll be open for it. This is just
16
+ # here to synchronize the logging output
17
+ if kwargs.pop("locked", False):
18
+ dm_console.print(msg, *args, **kwargs)
19
+ else:
20
+ with dm_console_lock:
21
+ dm_console.print(msg, *args, **kwargs)
22
+
23
+
24
+ __all__ = ["dm_console", "dm_console_lock", "dm_print"]
@@ -0,0 +1,24 @@
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
+ # just reusing impacket's hexdump
22
+ from impacket.structure import hexdump
23
+
24
+ __all__ = ["hexdump"]
@@ -20,7 +20,6 @@
20
20
  import argparse
21
21
  import inspect
22
22
  import logging
23
- import threading
24
23
  import pathlib
25
24
  import datetime
26
25
  import sys
@@ -28,20 +27,12 @@ import sys
28
27
  from abc import abstractmethod
29
28
  from logging.handlers import RotatingFileHandler
30
29
 
31
- from rich.console import Console
32
30
  from rich.logging import RichHandler
33
31
  from rich.markup import render
34
32
 
33
+ from dementor.config import util
35
34
  from dementor.config.toml import TomlConfig, Attribute as A
36
-
37
- dm_console = Console(
38
- soft_wrap=True,
39
- tab_size=4,
40
- highlight=False,
41
- highlighter=None,
42
- )
43
-
44
- dm_console_lock = threading.Lock()
35
+ from dementor.log import dm_print, dm_console
45
36
 
46
37
 
47
38
  class LoggingConfig(TomlConfig):
@@ -50,6 +41,7 @@ class LoggingConfig(TomlConfig):
50
41
  A("log_debug_loggers", "DebugLoggers", list),
51
42
  A("log_dir", "LogDir", "logs"),
52
43
  A("log_enable", "Enabled", True),
44
+ A("log_capture_hosts", "CaptureHostsTo", None),
53
45
  ]
54
46
 
55
47
 
@@ -99,17 +91,6 @@ def init():
99
91
  root_logger.setLevel(logging.INFO)
100
92
 
101
93
 
102
- def dm_print(msg, *args, **kwargs) -> None:
103
- # If someone has a better idea I'll be open for it. This is just
104
- # a here to synchronize the logging output
105
- if kwargs.pop("locked", False):
106
- dm_console.print(msg, *args, **kwargs)
107
- return
108
-
109
- with dm_console_lock:
110
- dm_console.print(msg, *args, **kwargs)
111
-
112
-
113
94
  class ProtocolLogger(logging.LoggerAdapter):
114
95
  def __init__(self, extra=None) -> None:
115
96
  super().__init__(logging.getLogger("dementor"), extra or {})
@@ -226,7 +207,9 @@ class ProtocolLogger(logging.LoggerAdapter):
226
207
  outfile = pathlib.Path(log_file_path)
227
208
  file_exists = outfile.exists()
228
209
  if not file_exists:
229
- open(str(outfile), "x")
210
+ if not outfile.parent.exists():
211
+ outfile.parent.mkdir(parents=True, exist_ok=True)
212
+ open(str(outfile), "x").close()
230
213
 
231
214
  handler = RotatingFileHandler(
232
215
  outfile,
@@ -244,7 +227,7 @@ class ProtocolLogger(logging.LoggerAdapter):
244
227
 
245
228
  handler.setFormatter(formatter)
246
229
  self.logger.addHandler(handler)
247
- self.logger.debug(f"Created log file handler for {log_file_path}")
230
+ self.logger.info(f"Created log file handler for {log_file_path}")
248
231
 
249
232
  @staticmethod
250
233
  def init_logfile(session) -> None:
@@ -252,11 +235,10 @@ class ProtocolLogger(logging.LoggerAdapter):
252
235
  if not config.log_enable:
253
236
  return
254
237
 
255
- workspace = pathlib.Path(session.workspace_path)
256
- workspace /= config.log_dir or "logs"
257
- workspace.mkdir(parents=True, exist_ok=True)
258
- log_name = f"log_{datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}.log"
259
- dm_logger.add_logfile(str(workspace / log_name))
238
+ log_dir: pathlib.Path = session.resolve_path(config.log_dir or "logs")
239
+ log_dir.mkdir(parents=True, exist_ok=True)
240
+ log_name = f"dm_log-{util.now()}.log"
241
+ dm_logger.add_logfile(str(log_dir / log_name))
260
242
 
261
243
 
262
244
  class ProtocolLoggerMixin:
@@ -0,0 +1,214 @@
1
+ from collections import defaultdict
2
+ from io import IOBase
3
+ from pathlib import Path
4
+ from typing import Any, override
5
+
6
+ from dementor.config import util
7
+ from dementor.config.toml import TomlConfig, Attribute as A
8
+ from dementor.log.logger import dm_logger
9
+
10
+ dm_streams = {}
11
+
12
+
13
+ class LoggingStream:
14
+ _name_: str
15
+ _config_cls_: type[TomlConfig]
16
+
17
+ def __init__(self, stream: IOBase) -> None:
18
+ self.fp = stream
19
+
20
+ def close(self) -> None:
21
+ if not self.fp.closed:
22
+ self.fp.flush()
23
+ self.fp.close()
24
+
25
+ def write(self, data: str) -> None:
26
+ line = f"{data}\n"
27
+ self.fp.write(line.encode())
28
+ self.fp.flush()
29
+
30
+ def write_columns(self, *values: Any) -> None:
31
+ line = "\t".join(map(str, values))
32
+ self.write(line)
33
+
34
+ def add(self, **kwargs: Any) -> None:
35
+ pass
36
+
37
+ @classmethod
38
+ def start(cls, session) -> None:
39
+ config = TomlConfig.build_config(cls._config_cls_)
40
+ path = config.path
41
+ if path is not None:
42
+ path = session.resolve_path(path)
43
+ if not path.parent.exists():
44
+ dm_logger.debug(f"Creating log directory {path.parent}")
45
+ path.parent.mkdir(parents=True, exist_ok=True)
46
+
47
+ dm_streams[cls._name_] = cls(path, config)
48
+
49
+
50
+ class LoggingFileStream(LoggingStream):
51
+ def __init__(self, path: str | Path) -> None:
52
+ self.path = Path(path)
53
+ if self.path.exists():
54
+ mode = "ab"
55
+ else:
56
+ mode = "wb"
57
+
58
+ # make sure not error is thrown
59
+ self.path.parent.mkdir(parents=True, exist_ok=True)
60
+ super().__init__(self.path.open(mode))
61
+
62
+ def reopen(self) -> None:
63
+ if not self.fp.closed:
64
+ self.fp.close()
65
+
66
+ self.fp = self.path.open("wb")
67
+
68
+
69
+ class HostsStreamConfig(TomlConfig):
70
+ _section_ = "Log.Stream.Hosts"
71
+ _fields_ = [
72
+ A("path", "Path", default_val=None),
73
+ A("log_ipv4", "IPv4", default_val=True),
74
+ A("log_ipv6", "IPv6", default_val=True),
75
+ ]
76
+
77
+
78
+ class HostsStream(LoggingFileStream):
79
+ _name_ = "hosts"
80
+ _config_cls_ = HostsStreamConfig
81
+
82
+ def __init__(self, path: str | Path, config: HostsStreamConfig) -> None:
83
+ super().__init__(path)
84
+ self.hosts = set()
85
+ self.ipv4 = config.log_ipv4
86
+ self.ipv6 = config.log_ipv6
87
+ dm_logger.info(
88
+ f"Logging host IPs to {path} (IPv4={self.ipv4}, IPv6={self.ipv6})"
89
+ )
90
+
91
+ @override
92
+ def add(self, **kwargs: Any) -> None:
93
+ ip = kwargs.get("ip")
94
+ if ip and ip not in self.hosts:
95
+ if not self.ipv4 and "." in ip:
96
+ return
97
+
98
+ if not self.ipv6 and ":" in ip:
99
+ return
100
+
101
+ self.write_columns(ip)
102
+ self.hosts.add(ip)
103
+
104
+
105
+ class DNSNamesStreamConfig(TomlConfig):
106
+ _section_ = "Log.Stream.DNS"
107
+ _fields_ = [
108
+ A("path", "Path", default_val=None),
109
+ # reserved for future extensions
110
+ ]
111
+
112
+
113
+ class DNSNamesStream(LoggingFileStream):
114
+ _name_ = "dns"
115
+ _config_cls_ = DNSNamesStreamConfig
116
+
117
+ def __init__(self, path: str | Path, config: DNSNamesStreamConfig) -> None:
118
+ super().__init__(path)
119
+ self.hosts = defaultdict(set)
120
+ dm_logger.info(f"Logging DNS names to {path}")
121
+
122
+ @override
123
+ def add(self, **kwargs: Any) -> None:
124
+ name = kwargs.get("type")
125
+ query = kwargs.get("name")
126
+ if name and query:
127
+ if query not in self.hosts[name]:
128
+ self.write_columns(name, query)
129
+ self.hosts[name].add(query)
130
+
131
+
132
+ class HashesStreamConfig(TomlConfig):
133
+ _section_ = "Log.Stream.Hashes"
134
+ _fields_ = [
135
+ A("path", "Path", default_val=None),
136
+ A("split", "Split", default_val=None),
137
+ A("prefix", "FilePrefix", default_val=None),
138
+ A("suffix", "FileSuffix", default_val=".txt"),
139
+ ]
140
+
141
+
142
+ class HashStreams(LoggingFileStream):
143
+ _name_ = "hashes"
144
+ _config_cls_ = HashesStreamConfig
145
+
146
+ def __init__(self, path: str | Path, config: HashesStreamConfig) -> None:
147
+ super().__init__(path if not config.split else "/dev/null")
148
+ self.config = config
149
+ self.path = Path(path)
150
+ self.start_time = util.now()
151
+ dm_logger.info(f"Logging hashes to {path} (split files: {config.split})")
152
+
153
+ @override
154
+ def add(self, **kwargs: Any) -> None:
155
+ hash_type = kwargs.get("type").upper()
156
+ hash_value = kwargs.get("value")
157
+ if hash_type and hash_value:
158
+ if not self.config.split:
159
+ self.write(f"{hash_type} {hash_value}")
160
+ else:
161
+ prefix = self.config.prefix or ""
162
+ suffix = self.config.suffix
163
+ if not prefix:
164
+ prefix = f"{hash_type}_{self.start_time}"
165
+ else:
166
+ prefix = util.format_string(
167
+ prefix,
168
+ {
169
+ "hash_type": hash_type,
170
+ "time": self.start_time,
171
+ },
172
+ )
173
+
174
+ target_path = Path(self.path) / f"{prefix}{suffix}"
175
+ if not target_path.exists():
176
+ # create a new logging stream for that hash type
177
+ target_path.parent.mkdir(parents=True, exist_ok=True)
178
+ dm_streams[f"HASH_{hash_type}"] = LoggingFileStream(target_path)
179
+
180
+ write_to(f"HASH_{hash_type}", str(hash_value))
181
+
182
+
183
+ def init_streams(session):
184
+ HostsStream.start(session)
185
+ DNSNamesStream.start(session)
186
+ HashStreams.start(session)
187
+ session.streams = dm_streams
188
+
189
+
190
+ def add_stream(name: str, stream: LoggingStream):
191
+ dm_streams[name] = stream
192
+
193
+
194
+ def get_stream(name: str) -> LoggingStream:
195
+ return dm_streams.get(name)
196
+
197
+
198
+ def close_streams(session):
199
+ for stream in session.streams.values():
200
+ stream.close()
201
+
202
+
203
+ def log_to(__name: str, /, **kwargs):
204
+ if __name in dm_streams:
205
+ dm_streams[__name].add(**kwargs)
206
+
207
+
208
+ def write_to(name: str, line: str):
209
+ if name in dm_streams:
210
+ dm_streams[name].write(line)
211
+
212
+
213
+ def log_host(ip: str):
214
+ log_to("hosts", ip=ip)
@@ -31,7 +31,7 @@ HTTP_TEMPLATES_PATH = os.path.join(ASSETS_PATH, "www")
31
31
  if __name__ == "__main__":
32
32
  print(f"DefaultWorkspace : {DEMENTOR_PATH}")
33
33
  print(f"AssetsPath : {ASSETS_PATH}")
34
- print(f"ConfigPath : {CONFIG_PATH}")
34
+ print(f"ConfigPath : {CONFIG_PATH} (for root: /root/.dementor)")
35
35
  print(f"BannerPath : {BANNER_PATH}")
36
36
  print(f"DefaultConfigPath : {DEFAULT_CONFIG_PATH}")
37
37
  print(f"HTTPTemplatesPath : {HTTP_TEMPLATES_PATH}")
@@ -19,7 +19,7 @@
19
19
  # SOFTWARE.
20
20
  from dementor.config.toml import TomlConfig, Attribute as A
21
21
  from dementor.config.util import get_value
22
- from dementor.logger import ProtocolLogger
22
+ from dementor.log.logger import ProtocolLogger
23
23
  from dementor.servers import BaseProtoHandler, ThreadingTCPServer, ServerThread
24
24
  from dementor.database import _CLEARTEXT
25
25