dementor 1.0.0.dev0__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 (33) hide show
  1. dementor-1.0.0.dev0/LICENSE +21 -0
  2. dementor-1.0.0.dev0/PKG-INFO +89 -0
  3. dementor-1.0.0.dev0/README.md +42 -0
  4. dementor-1.0.0.dev0/dementor/__init__.py +22 -0
  5. dementor-1.0.0.dev0/dementor/__main__.py +3 -0
  6. dementor-1.0.0.dev0/dementor/config.py +233 -0
  7. dementor-1.0.0.dev0/dementor/database.py +238 -0
  8. dementor-1.0.0.dev0/dementor/filters.py +153 -0
  9. dementor-1.0.0.dev0/dementor/loader.py +90 -0
  10. dementor-1.0.0.dev0/dementor/logger.py +224 -0
  11. dementor-1.0.0.dev0/dementor/paths.py +26 -0
  12. dementor-1.0.0.dev0/dementor/protocols/__init__.py +19 -0
  13. dementor-1.0.0.dev0/dementor/protocols/ftp.py +104 -0
  14. dementor-1.0.0.dev0/dementor/protocols/kerberos.py +304 -0
  15. dementor-1.0.0.dev0/dementor/protocols/ldap.py +419 -0
  16. dementor-1.0.0.dev0/dementor/protocols/llmnr.py +143 -0
  17. dementor-1.0.0.dev0/dementor/protocols/mdns.py +195 -0
  18. dementor-1.0.0.dev0/dementor/protocols/netbios.py +243 -0
  19. dementor-1.0.0.dev0/dementor/protocols/ntlm.py +200 -0
  20. dementor-1.0.0.dev0/dementor/protocols/quic.py +205 -0
  21. dementor-1.0.0.dev0/dementor/protocols/smb.py +542 -0
  22. dementor-1.0.0.dev0/dementor/protocols/smtp.py +383 -0
  23. dementor-1.0.0.dev0/dementor/protocols/spnego.py +35 -0
  24. dementor-1.0.0.dev0/dementor/servers.py +185 -0
  25. dementor-1.0.0.dev0/dementor/standalone.py +371 -0
  26. dementor-1.0.0.dev0/dementor.egg-info/PKG-INFO +89 -0
  27. dementor-1.0.0.dev0/dementor.egg-info/SOURCES.txt +31 -0
  28. dementor-1.0.0.dev0/dementor.egg-info/dependency_links.txt +1 -0
  29. dementor-1.0.0.dev0/dementor.egg-info/entry_points.txt +2 -0
  30. dementor-1.0.0.dev0/dementor.egg-info/top_level.txt +1 -0
  31. dementor-1.0.0.dev0/docs/README.pypi.md +42 -0
  32. dementor-1.0.0.dev0/pyproject.toml +36 -0
  33. dementor-1.0.0.dev0/setup.cfg +4 -0
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025-present MatrixEditor
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,89 @@
1
+ Metadata-Version: 2.4
2
+ Name: dementor
3
+ Version: 1.0.0.dev0
4
+ Summary: LLMNR/NBT-NS/mDNS Poisoner and rogue service provider
5
+ Author: MatrixEditor
6
+ Maintainer: MatrixEditor
7
+ License: The MIT License (MIT)
8
+
9
+ Copyright (c) 2025-present MatrixEditor
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
28
+ Project-URL: homepage, https://matrixeditor.github.io/dementor
29
+ Project-URL: documentation, https://matrixeditor.github.io/dementor
30
+ Project-URL: source, https://github.com/MatrixEditor/dementor
31
+ Classifier: Development Status :: 4 - Beta
32
+ Classifier: Intended Audience :: Developers
33
+ Classifier: Intended Audience :: Science/Research
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Programming Language :: Python :: 3
36
+ Classifier: Programming Language :: Python :: 3.13
37
+ Classifier: Programming Language :: Python :: 3 :: Only
38
+ Classifier: Programming Language :: Python :: Implementation :: CPython
39
+ Classifier: Topic :: Security
40
+ Classifier: Topic :: System :: Networking
41
+ Classifier: Typing :: Typed
42
+ Classifier: Operating System :: POSIX
43
+ Classifier: Operating System :: Unix
44
+ Description-Content-Type: text/markdown
45
+ License-File: LICENSE
46
+ Dynamic: license-file
47
+
48
+ # Dementor
49
+
50
+ IPv6/IPv4 LLMNR/NBT-NS/mDNS Poisoner and rogue service provider - you can think if it as Responder 2.0. Get more information
51
+ on the [Documentation](https://matrixeditor.github.io/dementor/) page.
52
+
53
+ ### Offers
54
+
55
+ - No reliance on hardcoded or precomputed packets
56
+ - Fine-grained, per-protocol configuration using a modular system (see [Docs - Configuration](https://matrixeditor.github.io/dementor/config/index.html))
57
+ - Near-complete protocol parity with Responder (see [Docs - Compatibility](https://matrixeditor.github.io/dementor/compat.html))
58
+ - Easy integration of new protocols via the extension system
59
+
60
+ ## Installation
61
+
62
+ Installation via `pip` from GitHub or PyPI:
63
+
64
+ ```bash
65
+ pip install dementor
66
+ ```
67
+
68
+ ## Usage
69
+
70
+ Just type in _Dementor_, specify the target interface and you are good to go! It is recommended
71
+ to run _Dementor_ with `sudo` as most protocol servers use privileged ports.
72
+
73
+ ```bash
74
+ sudo Dementor -I "$INTERFACE_NAME"
75
+ ```
76
+
77
+ Let's take a look.
78
+
79
+ ![index_video](https://raw.githubusercontent.com/MatrixEditor/dementor/refs/heads/master/docs/source/_static/images/index-video.gif)
80
+
81
+
82
+ ## You need more?
83
+
84
+ Take a look at the [Documentation on GitHub-Pages](https://matrixeditor.github.io/dementor/)
85
+
86
+
87
+ ## License
88
+
89
+ Distributed under the MIT License. See LICENSE for more information.
@@ -0,0 +1,42 @@
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.
@@ -0,0 +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.
20
+
21
+ __version__ = "1.0.0.dev0"
22
+ __author__ = "MatrixEditor"
@@ -0,0 +1,3 @@
1
+ from dementor.standalone import run_from_cli
2
+
3
+ run_from_cli()
@@ -0,0 +1,233 @@
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 tomllib
21
+ import os
22
+ import asyncio
23
+
24
+ from typing import Any, List, Optional, NamedTuple, Callable
25
+
26
+ from dementor.paths import ASSETS_PATH, CONFIG_PATH, DEMENTOR_PATH
27
+
28
+
29
+ _LOCAL = object()
30
+
31
+
32
+ class Attribute(NamedTuple):
33
+ attr_name: str
34
+ qname: str
35
+ default_val: Any | None = _LOCAL
36
+ section_local: bool = True
37
+ factory: Callable[[Any], Any] | None = None
38
+
39
+
40
+ class TomlConfig:
41
+ _section_: str | None
42
+ _fields_: list[Attribute]
43
+
44
+ def __init__(self, config: dict) -> None:
45
+ for field in self._fields_:
46
+ self._set_field(
47
+ config,
48
+ field.attr_name,
49
+ field.qname,
50
+ field.default_val,
51
+ field.section_local,
52
+ field.factory,
53
+ )
54
+
55
+ def __getitem__(self, key: str) -> Any:
56
+ if hasattr(self, key):
57
+ return getattr(self, key)
58
+
59
+ for attrname, qname, _ in getattr(self, "_fields_", []):
60
+ if "." in qname:
61
+ _, qname = qname.rsplit(".", 1)
62
+
63
+ if key == qname:
64
+ return getattr(self, attrname)
65
+
66
+ raise KeyError(f"Could not find config with key {key!r}")
67
+
68
+ @staticmethod
69
+ def build_config(cls_ty, section: str | None = None) -> Any:
70
+ return cls_ty(get_value(section or cls_ty._section_, key=None, default={}))
71
+
72
+ def _set_field(
73
+ self,
74
+ config: dict,
75
+ field_name: str,
76
+ qname: str,
77
+ default_val=None,
78
+ section_local=False,
79
+ factory=None,
80
+ ) -> None:
81
+ # Behaviour:
82
+ # 1. resolve default value:
83
+ # - If default_val is _LOCAL, there will be no default value
84
+ # - If self._section_ is present, it will be used to fetch the
85
+ # defualt value. The name may contain "."
86
+ # 2. Retrieve value from target section
87
+ # 3. Apply value by either
88
+ # - Calling a function with 'set_<attr_name>', or
89
+ # - using setattr directly
90
+
91
+ section = getattr(self, "_section_", None)
92
+ if "." in qname:
93
+ # REVISIT: section will be overwritten here
94
+ # get section path and target property name
95
+ alt_section, qname = qname.rsplit(".", 1)
96
+ else:
97
+ alt_section = None
98
+
99
+ if default_val is not _LOCAL:
100
+ # PRIOROTY list:
101
+ # 1. _section_
102
+ # 2. alternative section in qname
103
+ # 3. variable in dm_config.Globals
104
+ sections = [
105
+ get_value(section or "", key=None, default={}),
106
+ get_value(alt_section or "", key=None, default={}),
107
+ ]
108
+ if not section_local:
109
+ sections.append(get_value("Globals", key=None, default={}))
110
+
111
+ for section_config in sections:
112
+ if qname in section_config:
113
+ default_val = section_config[qname]
114
+ break
115
+
116
+ value = config.get(qname, default_val)
117
+ if value is _LOCAL:
118
+ raise Exception(
119
+ f"Expected '{qname}' in config or section({section}) for {self.__class__.__name__}!"
120
+ )
121
+
122
+ if value is default_val and isinstance(value, type):
123
+ # use factory instead of return value
124
+ value = value()
125
+
126
+ if factory:
127
+ value = factory(value)
128
+
129
+ func = getattr(self, f"set_{field_name}", None)
130
+ if func:
131
+ func(value)
132
+ else:
133
+ setattr(self, field_name, value)
134
+
135
+
136
+ def is_true(value) -> bool:
137
+ return str(value).lower() in ("true", "1", "yes", "on")
138
+
139
+
140
+ class SessionConfig(TomlConfig):
141
+ _section_ = "Dementor"
142
+ _fields_ = [
143
+ Attribute("llmnr_enabled", "LLMNR", True, factory=is_true),
144
+ Attribute("nbtns_enabled", "NBTNS", True, factory=is_true),
145
+ Attribute("nbtds_enabled", "NBTDS", True, factory=is_true),
146
+ Attribute("smtp_enabled", "SMTP", True, factory=is_true),
147
+ Attribute("smb_enabled", "SMB", True, factory=is_true),
148
+ Attribute("ftp_enabled", "FTP", True, factory=is_true),
149
+ Attribute("kdc_enabled", "KDC", True, factory=is_true),
150
+ Attribute("ldap_enabled", "LDAP", True, factory=is_true),
151
+ Attribute("quic_enabled", "QUIC", True, factory=is_true),
152
+ Attribute("mdns_enabled", "QUIC", True, factory=is_true),
153
+ Attribute("extra_modules", "ExtraModules", list),
154
+ Attribute("workspace_path", "Workspace", DEMENTOR_PATH),
155
+ ]
156
+
157
+ # TODO: move into .pyi
158
+ db: Any
159
+ db_config: Any
160
+ krb5_config: Any
161
+ mdns_config: Any
162
+ llmnr_config: Any
163
+ quic_config: Any
164
+ netbiosns_config: Any
165
+ ldap_config: List[Any]
166
+
167
+ def __init__(self) -> None:
168
+ super().__init__(dm_config.get("Dementor", {}))
169
+ # global options that are not loaded from configuration
170
+ self.ipv6: Optional[str] = None
171
+ self.ipv4: Optional[str] = None
172
+ self.interface = None
173
+ self.analysis = False
174
+ self.loop = asyncio.get_event_loop()
175
+ self.protocols = {}
176
+
177
+ # SMTP configuration
178
+ self.smtp_servers = []
179
+
180
+ # NTLM configuration
181
+ self.ntlm_challange = b"1337LEET"
182
+ self.ntlm_ess = True
183
+
184
+ # SMB configuration
185
+ self.smb_server_config = []
186
+
187
+ def is_bound_to_all(self) -> bool:
188
+ # REVISIT: this should raise an exception
189
+ return self.interface == "ALL"
190
+
191
+
192
+ def _read(path: str):
193
+ with open(path, "rb") as f:
194
+ return tomllib.load(f)
195
+
196
+
197
+ dm_default_config = _read(os.path.join(ASSETS_PATH, "Dementor.toml"))
198
+
199
+ if os.path.exists(CONFIG_PATH):
200
+ dm_config = _read(CONFIG_PATH)
201
+ else:
202
+ dm_config = {}
203
+
204
+ if not dm_config or "Dementor" not in dm_config:
205
+ # TODO: do first run
206
+ dm_config = dm_default_config
207
+
208
+
209
+ def get_bool(section: str, key: str, default=False) -> bool:
210
+ value = str(get_value(section, key=key, default=str(default)))
211
+ return is_true(value)
212
+
213
+
214
+ def get_value(section: str, key: str | None, default=None) -> Any:
215
+ sections = section.split(".")
216
+ if len(sections) == 1:
217
+ target = dm_config.get(sections[0], {})
218
+ else:
219
+ target = dm_config
220
+ for section in sections:
221
+ target = target[section]
222
+
223
+ if key is None:
224
+ return target
225
+
226
+ return target.get(key, default)
227
+
228
+
229
+ def init_from_file(path: str):
230
+ global dm_config
231
+
232
+ if os.path.exists(path):
233
+ dm_config = _read(path)
@@ -0,0 +1,238 @@
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 threading
21
+ import os
22
+ import sqlite3
23
+ import pathlib
24
+
25
+ from datetime import datetime
26
+ from typing import Any, Tuple
27
+
28
+ from sqlalchemy.engine import Engine, create_engine
29
+ from sqlalchemy.orm import scoped_session, sessionmaker
30
+ from sqlalchemy.schema import MetaData, Table
31
+ from sqlalchemy import sql
32
+ from sqlalchemy.exc import NoSuchTableError, NoInspectionAvailable
33
+
34
+
35
+ from dementor.logger import dm_logger, dm_console_lock
36
+ from dementor.config import TomlConfig, Attribute as A
37
+
38
+
39
+ class DatabaseConfig(TomlConfig):
40
+ _section_ = "DB"
41
+ _fields_ = [
42
+ A("db_dir", "Directory", None),
43
+ A("db_name", "Name", "Dementor.db"),
44
+ A("db_duplicate_creds", "DuplicateCreds", False),
45
+ ]
46
+
47
+
48
+ def init_dementor_db(session) -> str:
49
+ workspace_path = session.workspace_path
50
+ if session.db_config.db_dir:
51
+ workspace_path = session.db_config.db_dir
52
+
53
+ name = session.db_config.db_name
54
+ db_path = pathlib.Path(workspace_path) / name
55
+
56
+ if not db_path.exists():
57
+ dm_logger.info("Initializing Dementor database")
58
+ # TODO: check for parent dirs
59
+ if not db_path.parent.exists():
60
+ dm_logger.info(f"Creating directory {db_path.parent}")
61
+ db_path.parent.mkdir(parents=True, exist_ok=True)
62
+
63
+ conn = sqlite3.connect(db_path)
64
+ cursor = conn.cursor()
65
+
66
+ cursor.execute("PRAGMA journal_mode = OFF")
67
+ cursor.execute("PRAGMA foreign_keys = 1")
68
+ DementorDB.db_schema(cursor)
69
+
70
+ # commit and save changes
71
+ conn.commit()
72
+ conn.close()
73
+ return db_path
74
+
75
+
76
+ def init_engine(db_path: str) -> Engine:
77
+ return create_engine(
78
+ f"sqlite:///{db_path}",
79
+ isolation_level="AUTOCOMMIT",
80
+ future=True,
81
+ )
82
+
83
+
84
+ def normalize_client_address(client: str) -> str:
85
+ return client.removeprefix("::ffff:")
86
+
87
+
88
+ _CLEARTEXT = "Cleartext"
89
+
90
+
91
+ class DementorDB:
92
+ def __init__(self, engine: Engine, config) -> None:
93
+ self.db_engine = engine
94
+ self.db_path = engine.url.database
95
+ self.metadata = MetaData()
96
+ self.config = config
97
+
98
+ with self.db_engine.connect():
99
+ try:
100
+ # reflect tables
101
+ self.CredentialsTable = Table(
102
+ "credentials",
103
+ self.metadata,
104
+ autoload_with=self.db_engine,
105
+ )
106
+ self.HostsTable = Table(
107
+ "hosts",
108
+ self.metadata,
109
+ autoload_with=self.db_engine,
110
+ )
111
+ except (NoSuchTableError, NoInspectionAvailable):
112
+ dm_logger.error(f"Failed to connect to database {self.db_path}!")
113
+ raise
114
+
115
+ session_factory = sessionmaker(bind=self.db_engine, expire_on_commit=True)
116
+ session_ty = scoped_session(session_factory)
117
+
118
+ self.session = session_ty()
119
+ self.lock = threading.Lock()
120
+
121
+ # now, lets create those tables
122
+ @staticmethod
123
+ def db_schema(cursor: sqlite3.Cursor) -> None:
124
+ cursor.execute(
125
+ """CREATE TABLE "credentials" (
126
+ "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
127
+ "timestamp" TEXT NOT NULL,
128
+ "protocol" TEXT NOT NULL,
129
+ "credtype" TEXT NOT NULL,
130
+ "client" TEXT NOT NULL,
131
+ "hostname" TEXT,
132
+ "domain" TEXT,
133
+ "username" TEXT NOT NULL,
134
+ "password" TEXT
135
+ )"""
136
+ )
137
+
138
+ cursor.execute(
139
+ """CREATE TABLE "hosts" (
140
+ "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
141
+ "hostname" TEXT NOT NULL,
142
+ "ip" TEXT NOT NULL,
143
+ "port" INTEGER NOT NULL,
144
+ "banner" TEXT,
145
+ "os" TEXT
146
+ )"""
147
+ )
148
+
149
+ def close(self) -> None:
150
+ self.session.close()
151
+
152
+ def db_exec(self, *args, **kwargs):
153
+ self.lock.acquire()
154
+ result = self.session.execute(*args, **kwargs)
155
+ self.lock.release()
156
+ return result
157
+
158
+ def add_auth(
159
+ self,
160
+ client: Tuple[str, int],
161
+ credtype: str,
162
+ username: str,
163
+ password: str,
164
+ logger: Any = None,
165
+ protocol: str | None = None,
166
+ domain: str | None = None,
167
+ hostname: str | None = None,
168
+ ) -> None:
169
+ if not logger and not protocol:
170
+ dm_logger.error(
171
+ f"Failed to add {credtype} for {username} on {client[0]}:{client[1]}: "
172
+ "Protocol must be present either in the logger or as a parameter!"
173
+ )
174
+ return
175
+
176
+ target_logger = logger or dm_logger
177
+ protocol = str(protocol or logger.extra["protocol"])
178
+ client_address, port, *_ = client
179
+ client_address = normalize_client_address(client_address)
180
+
181
+ target_logger.debug(
182
+ f"Adding {credtype} for {username} on {client_address}: "
183
+ f"{logger} | {protocol} | {domain} | {hostname} | {username} | {password}"
184
+ )
185
+
186
+ q = sql.select(self.CredentialsTable).filter(
187
+ sql.func.lower(self.CredentialsTable.c.domain)
188
+ == sql.func.lower(domain or ""),
189
+ sql.func.lower(self.CredentialsTable.c.username)
190
+ == sql.func.lower(username),
191
+ sql.func.lower(self.CredentialsTable.c.credtype)
192
+ == sql.func.lower(credtype),
193
+ sql.func.lower(self.CredentialsTable.c.protocol)
194
+ == sql.func.lower(protocol),
195
+ )
196
+ results = self.db_exec(q).all()
197
+ text = "Password" if credtype == _CLEARTEXT else "Hash"
198
+ full_name = (
199
+ f"[b]{username}[/]/[b]{domain}[/]" if domain else f"[b]{username}[/]"
200
+ )
201
+ if not results or self.config.db_config.db_duplicate_creds:
202
+ # just insert a new row
203
+ q = sql.insert(self.CredentialsTable).values(
204
+ {
205
+ "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
206
+ "protocol": protocol.lower(),
207
+ "credtype": credtype.lower(),
208
+ "client": f"{client_address}:{port}",
209
+ "hostname": hostname or "",
210
+ "domain": (domain or "").lower(),
211
+ "username": username.lower(),
212
+ "password": password,
213
+ }
214
+ )
215
+ self.db_exec(q)
216
+ with dm_console_lock:
217
+ target_logger.success(
218
+ f"Captured {credtype} {text} for {full_name} from {client_address}:",
219
+ host=hostname or client_address,
220
+ locked=True,
221
+ )
222
+ target_logger.highlight(
223
+ f"{credtype} Username: {username}",
224
+ host=hostname or client_address,
225
+ locked=True,
226
+ )
227
+
228
+ target_logger.highlight(
229
+ f"{credtype} {text}: {password}",
230
+ host=hostname or client_address,
231
+ locked=True,
232
+ )
233
+
234
+ else:
235
+ target_logger.highlight(
236
+ f"Skipping previously captured {credtype} {text} for {full_name} from {client_address}",
237
+ host=hostname or client_address,
238
+ )