dementor 1.0.0.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,205 @@
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
+ # Heavily inspired by:
22
+ # - https://github.com/xpn/ntlmquic
23
+ # - https://github.com/ctjf/Responder/tree/master
24
+ import asyncio
25
+ import os
26
+
27
+ from threading import Thread
28
+ from typing import Optional
29
+
30
+ from aioquic.asyncio.server import serve
31
+ from aioquic.asyncio.protocol import QuicConnectionProtocol, QuicStreamHandler
32
+ from aioquic.quic import events
33
+ from aioquic.quic.configuration import QuicConfiguration
34
+ from aioquic.quic.connection import QuicConnection
35
+
36
+
37
+ from dementor.config import SessionConfig, TomlConfig, Attribute as A
38
+ from dementor.logger import ProtocolLogger, ProtocolLoggerMixin, dm_logger
39
+
40
+
41
+ class QuicServerConfig(TomlConfig):
42
+ _section_ = "QUIC"
43
+ _fields_ = [
44
+ A("quic_port", "Port", 443),
45
+ A("quic_cert_path", "Cert", None, section_local=False),
46
+ A("quic_cert_key", "Key", None, section_local=False),
47
+ A("quic_smb_host", "TargetSMBHost", None),
48
+ A("quic_smb_port", "TargetSMBPort", 445), # default SMB
49
+ ]
50
+
51
+
52
+ def apply_config(session):
53
+ if session.quic_enabled:
54
+ session.quic_config = TomlConfig.build_config(QuicServerConfig)
55
+
56
+
57
+ def create_server_threads(session):
58
+ servers = []
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))
65
+
66
+ return servers
67
+
68
+
69
+ class QuicHandler(QuicConnectionProtocol, ProtocolLoggerMixin):
70
+ def __init__(
71
+ self,
72
+ config: SessionConfig,
73
+ host: str,
74
+ quic: QuicConnection,
75
+ stream_handler: Optional[QuicStreamHandler] = None,
76
+ ):
77
+ super().__init__(quic, stream_handler)
78
+ self.host = host
79
+ self.config = config
80
+ # stream_id -> (w, r)
81
+ self.conn_data = {}
82
+ ProtocolLoggerMixin.__init__(self)
83
+
84
+ def proto_logger(self) -> ProtocolLogger:
85
+ return ProtocolLogger(
86
+ extra={
87
+ "protocol": "QUIC",
88
+ "protocol_color": "turquoise2",
89
+ "port": self.config.quic_config.quic_port,
90
+ }
91
+ )
92
+
93
+ @property
94
+ def target_smb_host(self):
95
+ return self.config.quic_config.quic_smb_host or self.host
96
+
97
+ def quic_event_received(self, event: events.QuicEvent) -> None:
98
+ match event:
99
+ case events.StreamDataReceived():
100
+ self.config.loop.create_task(
101
+ self.handle_data(event.stream_id, event.data)
102
+ )
103
+
104
+ # terminate connections if present
105
+ case events.StreamReset():
106
+ self.config.loop.create_task(self.close_connection(event.stream_id))
107
+
108
+ case events.ConnectionTerminated():
109
+ self.config.loop.create_task(self.close_all_connections())
110
+
111
+ async def handle_data(self, stream_id, data):
112
+ if stream_id not in self.conn_data:
113
+ # create new connection
114
+ network_path = self._quic._network_paths[0]
115
+ self.logger.display(
116
+ f"Forwarding QUIC connection to {self.target_smb_host}"
117
+ f":{self.config.quic_config.quic_smb_port}",
118
+ host=network_path.addr[0],
119
+ )
120
+ read, write = await asyncio.open_connection(
121
+ self.target_smb_host,
122
+ self.config.quic_config.quic_smb_port,
123
+ )
124
+ self.conn_data[stream_id] = (write, read)
125
+
126
+ self.config.loop.create_task(self.proxy_quic_data(stream_id, read))
127
+ else:
128
+ write, read = self.conn_data[stream_id]
129
+
130
+ # TODO: add exception handling
131
+ write.write(data)
132
+ await write.drain() # flush
133
+
134
+ async def proxy_quic_data(self, stream_id, read):
135
+ try:
136
+ while True:
137
+ data = await read.read(8192)
138
+ if not data:
139
+ break
140
+
141
+ self._quic.send_stream_data(stream_id, data)
142
+ self.transmit()
143
+ finally:
144
+ await self.close_connection(stream_id)
145
+
146
+ async def close_connection(self, stream_id):
147
+ if stream_id in self.conn_data:
148
+ self.logger.debug(
149
+ f"Closing down QUIC connection with {self._quic._network_paths[0].addr[0]}"
150
+ )
151
+ write, _ = self.conn_data.pop(stream_id, (None, None))
152
+ if write is not None:
153
+ write.close()
154
+ await write.wait_closed()
155
+
156
+ async def close_all_connections(self):
157
+ for stream_id in self.conn_data:
158
+ await self.close_connection(stream_id)
159
+
160
+
161
+ class QuicServerThread(Thread):
162
+ def __init__(self, config: SessionConfig, host: str):
163
+ super().__init__()
164
+ self.config = config
165
+ self.host = host
166
+
167
+ def run(self) -> None:
168
+ self.config.loop.create_task(self.arun())
169
+
170
+ def create_handler(self, *args, **kwargs):
171
+ return QuicHandler(self.config, self.host, *args, **kwargs)
172
+
173
+ async def arun(self):
174
+ quic_config = QuicConfiguration(
175
+ alpn_protocols=["smb"],
176
+ is_client=False,
177
+ )
178
+
179
+ if not os.path.exists(self.config.quic_config.quic_cert_path):
180
+ dm_logger.error(
181
+ f"Failed to start QUIC server on {self.host}:{self.config.quic_config.quic_port}: "
182
+ "Certificate file does not exist!"
183
+ )
184
+ return
185
+
186
+ if not os.path.exists(self.config.quic_config.quic_cert_key):
187
+ dm_logger.error(
188
+ f"Failed to start QUIC server on {self.host}:{self.config.quic_config.quic_port}: "
189
+ "Certificate key file does not exist!"
190
+ )
191
+ return
192
+
193
+ quic_config.load_cert_chain(
194
+ self.config.quic_config.quic_cert_path,
195
+ self.config.quic_config.quic_cert_key,
196
+ )
197
+ dm_logger.debug(
198
+ f"Starting QUIC server on {self.host}:{self.config.quic_config.quic_port}"
199
+ )
200
+ await serve(
201
+ host=self.host,
202
+ port=self.config.quic_config.quic_port,
203
+ configuration=quic_config,
204
+ create_protocol=self.create_handler,
205
+ )