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,542 @@
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 random
21
+ import struct
22
+ import threading
23
+ import configparser
24
+ import socket
25
+ import secrets
26
+
27
+ from impacket.smbserver import SMBSERVER, encodeSMBString
28
+ from impacket import smb, smb3, nt_errors, smb3structs as smb2, ntlm
29
+ from impacket.spnego import (
30
+ SPNEGO_NegTokenInit,
31
+ SPNEGO_NegTokenResp,
32
+ TypesMech,
33
+ )
34
+
35
+ from dementor.config import TomlConfig, SessionConfig, get_value, Attribute as A
36
+ from dementor.logger import ProtocolLogger, dm_logger
37
+ from dementor.protocols.ntlm import (
38
+ NTLM_AUTH_decode_string,
39
+ NTLM_AUTH_to_hashcat_format,
40
+ NTLM_AUTH_CreateChallenge,
41
+ )
42
+ from dementor.protocols.spnego import negTokenInit_step
43
+
44
+
45
+ class SMBServerConfig(TomlConfig):
46
+ _section_ = "SMB"
47
+ _fields_ = [
48
+ A("smb_port", "Port"),
49
+ A("smb_server_os", "ServerOS", "Windows"),
50
+ A("smb_server_name", "ServerName", "DEMENTOR"),
51
+ A("smb_server_domain", "ServerDomain", "WORKGROUP"),
52
+ A("smb_error_code", "ErrorCode", nt_errors.STATUS_SMB_BAD_UID),
53
+ A("smb2_support", "SMB2Support", True),
54
+ A("smb_ess", "NTLM.ExtendedSessionSecurity", True),
55
+ A("smb_challenge", "NTLM.Challenge", b""),
56
+ ]
57
+
58
+ def set_smb_challenge(self, value: str | bytes):
59
+ match value:
60
+ case str():
61
+ self.smb_challenge = value.encode("utf-8", errors="replace")
62
+ case bytes():
63
+ self.smb_challenge = value
64
+
65
+
66
+ def set_smb_error_code(self, value: str | int):
67
+ match value:
68
+ case int(): # great
69
+ self.smb_error_code = value
70
+ case str():
71
+ self.smb_error_code = getattr(nt_errors, value)
72
+
73
+
74
+ def apply_config(session: SessionConfig) -> None:
75
+ if not session.smb_enabled:
76
+ # don't try to parse the following values
77
+ return
78
+
79
+ ports = set()
80
+ for server in get_value("SMB", "Server", default=[]):
81
+ smb_config = SMBServerConfig(server)
82
+ port = smb_config.smb_port
83
+ if not port:
84
+ dm_logger.warning("Configuration contains SMBServer without Port!")
85
+ continue
86
+
87
+ if port in ports:
88
+ dm_logger.warning(
89
+ f"Configuration defines two SMB servers with the same port({port})!"
90
+ )
91
+ continue
92
+
93
+ session.smb_server_config.append(smb_config)
94
+ ports.add(port)
95
+
96
+
97
+ def create_server_threads(session: SessionConfig) -> list:
98
+ servers = []
99
+ for smb_config in session.smb_server_config:
100
+ try:
101
+ servers.append(SMBServerThread(session, smb_config))
102
+ except Exception as e:
103
+ dm_logger.error(f"Failed to create SMB server: {e}")
104
+ return servers
105
+
106
+
107
+ class SMBServerThread(threading.Thread):
108
+ def __init__(
109
+ self,
110
+ config: SessionConfig,
111
+ server_config: SMBServerConfig,
112
+ ):
113
+ super().__init__()
114
+ self.config = config
115
+ self.server_config = server_config
116
+ self.logger = ProtocolLogger(
117
+ {
118
+ "protocol": "SMB",
119
+ "protocol_color": "light_goldenrod1",
120
+ "port": self.server_config.smb_port,
121
+ }
122
+ )
123
+
124
+ # smbserver setup
125
+ smb_config = configparser.ConfigParser()
126
+ smb_config.add_section("global")
127
+ smb_config.set("global", "server_name", self.server_config.smb_server_name)
128
+ smb_config.set("global", "server_domain", self.server_config.smb_server_domain)
129
+ smb_config.set("global", "server_os", self.server_config.smb_server_os)
130
+
131
+ # Next, disable logging and creds
132
+ smb_config.set("global", "log_file", "None")
133
+ smb_config.set("global", "credentials_file", "")
134
+ smb_config.set("global", "anonymous_logon", "False")
135
+
136
+ # SMB2 support
137
+ smb_config.set("global", "SMB2Support", str(self.server_config.smb2_support))
138
+
139
+ # NTLM challenge
140
+ if self.config.ntlm_challange:
141
+ smb_config.set(
142
+ "global",
143
+ "challenge",
144
+ self.server_config.smb_challenge.hex(),
145
+ )
146
+
147
+ # Missing IPC share configuration here to make clients
148
+ # always disconnect
149
+
150
+ # Change address_family to IPv6 if this is configured
151
+ address = self.config.ipv4
152
+ if self.config.ipv6:
153
+ SMBSERVER.address_family = socket.AF_INET6
154
+ # empty string means all interfaces even though IPv6 can be bound to a specific
155
+ # interface. Unfortunately, impacket's SMBSERVER does not support binding to
156
+ # specific IPv6 addresses.
157
+ address = ""
158
+
159
+ self.server = SMBSERVER(
160
+ (address, self.server_config.smb_port),
161
+ config_parser=smb_config,
162
+ )
163
+ self.server.processConfigFile()
164
+
165
+ # hook session setup
166
+ self.orig_smb2_session_setup = self.server.hookSmb2Command(
167
+ smb3.SMB2_SESSION_SETUP,
168
+ self.smb2SessionSetup,
169
+ )
170
+ self.orig_smb1_session_setup = self.server.hookSmbCommand(
171
+ smb.SMB.SMB_COM_SESSION_SETUP_ANDX,
172
+ self.smbComSessionSetupAndX,
173
+ )
174
+
175
+ def get_challenge(self, connData: dict):
176
+ challenge = self.server_config.smb_challenge
177
+ if not challenge:
178
+ challenge = connData.get("ChallengeValue")
179
+ if not challenge:
180
+ challenge = secrets.token_bytes(8)
181
+
182
+ if "ChallengeValue" not in connData:
183
+ connData["ChallengeValue"] = challenge
184
+
185
+ return challenge
186
+
187
+ def smb2SessionSetup(self, connId: dict, smbServer: SMBSERVER, recvPacket: dict):
188
+ # copied and modified from SMB2Commands to be able to drop ESS support
189
+ connData = smbServer.getConnectionData(connId, checkStatus=False)
190
+ respSMBCommand = smb2.SMB2SessionSetup_Response()
191
+ sessionSetupData = smb2.SMB2SessionSetup(recvPacket["Data"])
192
+ connData["Capabilities"] = sessionSetupData["Capabilities"]
193
+
194
+ securityBlob = sessionSetupData["Buffer"]
195
+
196
+ rawNTLM = False
197
+ match securityBlob[0]:
198
+ case 0x60: # ASN1_AID
199
+ blob = SPNEGO_NegTokenInit(securityBlob)
200
+ mech_type = blob["MechTypes"][0]
201
+ if (
202
+ mech_type
203
+ == TypesMech["NTLMSSP - Microsoft NTLM Security Support Provider"]
204
+ ):
205
+ token = blob["MechToken"]
206
+ else:
207
+ resp = negTokenInit_step(
208
+ 0x02, # reject
209
+ supportedMech="NTLMSSP - Microsoft NTLM Security Support Provider",
210
+ )
211
+ resp_data = resp.getData()
212
+ respSMBCommand["SecurityBufferOffset"] = 0x48
213
+ respSMBCommand["SecurityBufferLength"] = len(resp_data)
214
+ respSMBCommand["Buffer"] = resp_data
215
+ return [respSMBCommand], None, smb3.STATUS_MORE_PROCESSING_REQUIRED
216
+
217
+ case 0xA1: # ASN1_SUPPORTED_MECH
218
+ blob = SPNEGO_NegTokenResp(securityBlob)
219
+ token = blob["ResponseToken"]
220
+
221
+ case _: # raw
222
+ rawNTLM = True
223
+ token = securityBlob
224
+
225
+ # Here we only handle NTLMSSP, depending on what stage of the
226
+ # authentication we are, we act on it
227
+ assert len(token) >= 12 # REMOVE THIS
228
+ match struct.unpack("<L", token[8:12])[0]:
229
+ case 0x01:
230
+ # NEGOTIATE_MESSAGE
231
+ negotiateMessage = ntlm.NTLMAuthNegotiate()
232
+ negotiateMessage.fromString(token)
233
+ connData["NEGOTIATE_MESSAGE"] = negotiateMessage
234
+ challenge = self.get_challenge(connData)
235
+ challengeMessage = NTLM_AUTH_CreateChallenge(
236
+ negotiateMessage,
237
+ self.server_config.smb_server_name,
238
+ self.server_config.smb_server_domain,
239
+ challenge=challenge,
240
+ disable_ess=not self.server_config.smb_ess,
241
+ )
242
+
243
+ if rawNTLM is False:
244
+ # accept-incomplete. We want more data
245
+ respToken = negTokenInit_step(
246
+ negResult=0x01,
247
+ supportedMech="NTLMSSP - Microsoft NTLM Security Support Provider",
248
+ )
249
+ respToken["ResponseToken"] = challengeMessage.getData()
250
+ else:
251
+ respToken = challengeMessage
252
+
253
+ # Setting the packet to STATUS_MORE_PROCESSING
254
+ errorCode = smb3.STATUS_MORE_PROCESSING_REQUIRED
255
+ connData["Uid"] = random.randint(1, 0xFFFFFFFF)
256
+ connData["CHALLENGE_MESSAGE"] = challengeMessage
257
+
258
+ case 0x02:
259
+ # CHALLENGE_MESSAGE
260
+ raise Exception("Challenge Message raise, not implemented!")
261
+
262
+ case 0x03:
263
+ # AUTHENTICATE_MESSAGE, here we deal with authentication
264
+ authenticateMessage = ntlm.NTLMAuthChallengeResponse()
265
+ authenticateMessage.fromString(token)
266
+ connData["AUTHENTICATE_MESSAGE"] = authenticateMessage
267
+ if (
268
+ not authenticateMessage["flags"] & ntlm.NTLMSSP_NEGOTIATE_ANONYMOUS
269
+ and authenticateMessage["user_name"]
270
+ ):
271
+ hash_version, hash_string = NTLM_AUTH_to_hashcat_format(
272
+ self.config.ntlm_challange,
273
+ authenticateMessage["user_name"],
274
+ authenticateMessage["domain_name"],
275
+ authenticateMessage["lanman"],
276
+ authenticateMessage["ntlm"],
277
+ authenticateMessage["flags"],
278
+ )
279
+
280
+ flags = authenticateMessage["flags"]
281
+ host_name = NTLM_AUTH_decode_string(
282
+ authenticateMessage["host_name"], flags
283
+ )
284
+ user_name = NTLM_AUTH_decode_string(
285
+ authenticateMessage["user_name"], flags
286
+ )
287
+ domain_name = NTLM_AUTH_decode_string(
288
+ authenticateMessage["domain_name"], flags
289
+ )
290
+
291
+ self.logger.debug(
292
+ f"Completed NTLM AUTH flow for {domain_name}/{user_name} from {host_name}",
293
+ )
294
+ self.config.db.add_auth(
295
+ (connData["ClientIP"], self.server_config.smb_port),
296
+ credtype=hash_version,
297
+ password=hash_string,
298
+ logger=self.logger,
299
+ username=user_name,
300
+ domain=domain_name,
301
+ hostname=host_name,
302
+ )
303
+
304
+ errorCode = self.server_config.smb_error_code
305
+ respToken = negTokenInit_step(negResult=0x02)
306
+
307
+ case messageType:
308
+ raise Exception("Unknown NTLMSSP MessageType %d" % messageType)
309
+
310
+ respSMBCommand["SecurityBufferOffset"] = 0x48
311
+ respSMBCommand["SecurityBufferLength"] = len(respToken)
312
+ respSMBCommand["Buffer"] = respToken.getData()
313
+
314
+ connData["Authenticated"] = False
315
+ smbServer.setConnectionData(connId, connData)
316
+ return [respSMBCommand], None, errorCode
317
+
318
+ def smbComSessionSetupAndX(
319
+ self,
320
+ connId: dict,
321
+ smbServer: SMBSERVER,
322
+ SMBCommand: dict,
323
+ recvPacket: dict,
324
+ ):
325
+ # copied and modified from SMBCommands to be able to drop ESS support
326
+ connData = smbServer.getConnectionData(connId, checkStatus=False)
327
+ respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_SESSION_SETUP_ANDX)
328
+
329
+ # From [MS-SMB]
330
+ # When extended security is being used (see section 3.2.4.2.4), the
331
+ # request MUST take the following form
332
+ # [..]
333
+ # WordCount (1 byte): The value of this field MUST be 0x0C.
334
+ if SMBCommand["WordCount"] == 12:
335
+ # Extended security. Here we deal with all SPNEGO stuff
336
+ respParameters = smb.SMBSessionSetupAndX_Extended_Response_Parameters()
337
+ respData = smb.SMBSessionSetupAndX_Extended_Response_Data(
338
+ flags=recvPacket["Flags2"]
339
+ )
340
+ sessionSetupParameters = smb.SMBSessionSetupAndX_Extended_Parameters(
341
+ SMBCommand["Parameters"]
342
+ )
343
+ sessionSetupData = smb.SMBSessionSetupAndX_Extended_Data()
344
+ sessionSetupData["SecurityBlobLength"] = sessionSetupParameters[
345
+ "SecurityBlobLength"
346
+ ]
347
+ sessionSetupData.fromString(SMBCommand["Data"])
348
+ connData["Capabilities"] = sessionSetupParameters["Capabilities"]
349
+
350
+ rawNTLM = False
351
+ match sessionSetupData["SecurityBlob"]:
352
+ case 0x60: # ASN1_AID
353
+ # NEGOTIATE packet
354
+ blob = SPNEGO_NegTokenInit(sessionSetupData["SecurityBlob"])
355
+ mech_type = blob["MechTypes"][0]
356
+ if (
357
+ mech_type
358
+ == TypesMech[
359
+ "NTLMSSP - Microsoft NTLM Security Support Provider"
360
+ ]
361
+ ):
362
+ token = blob["MechToken"]
363
+ else:
364
+ resp = negTokenInit_step(
365
+ 0x02, # reject
366
+ supportedMech="NTLMSSP - Microsoft NTLM Security Support Provider",
367
+ )
368
+ resp_data = resp.getData()
369
+ respParameters["SecurityBlobLength"] = len(resp_data)
370
+ respData["SecurityBlobLength"] = respParameters[
371
+ "SecurityBlobLength"
372
+ ]
373
+ respData["SecurityBlob"] = resp_data
374
+ respData["NativeOS"] = encodeSMBString(
375
+ recvPacket["Flags2"], smbServer.getServerOS()
376
+ )
377
+ respData["NativeLanMan"] = encodeSMBString(
378
+ recvPacket["Flags2"], smbServer.getServerOS()
379
+ )
380
+ respSMBCommand["Parameters"] = respParameters
381
+ respSMBCommand["Data"] = respData
382
+ return (
383
+ [respSMBCommand],
384
+ None,
385
+ smb3.STATUS_MORE_PROCESSING_REQUIRED,
386
+ )
387
+
388
+ case 0xA1: # ASN1_SUPPORTED_MECH
389
+ # AUTH packet
390
+ blob = SPNEGO_NegTokenResp(sessionSetupData["SecurityBlob"])
391
+ token = blob["ResponseToken"]
392
+ case _:
393
+ # No GSSAPI stuff, raw NTLMSSP
394
+ rawNTLM = True
395
+ token = sessionSetupData["SecurityBlob"]
396
+
397
+ # Here we only handle NTLMSSP, depending on what stage of the
398
+ # authentication we are, we act on it
399
+ assert len(token) >= 12 # REMOVE THIS
400
+ match struct.unpack("<L", token[8:12])[0]:
401
+ case 0x01:
402
+ # NEGOTIATE_MESSAGE
403
+ negotiateMessage = ntlm.NTLMAuthNegotiate()
404
+ negotiateMessage.fromString(token)
405
+ connData["NEGOTIATE_MESSAGE"] = negotiateMessage
406
+ challenge = self.get_challenge(connData)
407
+ challengeMessage = NTLM_AUTH_CreateChallenge(
408
+ negotiateMessage,
409
+ self.server_config.smb_server_name,
410
+ self.server_config.smb_server_domain,
411
+ challenge=challenge,
412
+ disable_ess=not self.server_config.smb_ess,
413
+ )
414
+
415
+ if rawNTLM is False:
416
+ # accept-incomplete. We want more data
417
+ respToken = negTokenInit_step(
418
+ negResult=0x01,
419
+ supportedMech="NTLMSSP - Microsoft NTLM Security Support Provider",
420
+ )
421
+ respToken["ResponseToken"] = challengeMessage.getData()
422
+ else:
423
+ respToken = challengeMessage
424
+
425
+ # Setting the packet to STATUS_MORE_PROCESSING
426
+ errorCode = smb3.STATUS_MORE_PROCESSING_REQUIRED
427
+ connData["Uid"] = random.randint(1, 0xFFFFFFFF)
428
+ connData["CHALLENGE_MESSAGE"] = challengeMessage
429
+
430
+ case 0x02:
431
+ # CHALLENGE_MESSAGE
432
+ raise Exception("Challenge Message raise, not implemented!")
433
+
434
+ case 0x03:
435
+ # AUTHENTICATE_MESSAGE, here we deal with authentication
436
+ authenticateMessage = ntlm.NTLMAuthChallengeResponse()
437
+ authenticateMessage.fromString(token)
438
+ connData["AUTHENTICATE_MESSAGE"] = authenticateMessage
439
+ if (
440
+ not authenticateMessage["flags"]
441
+ & ntlm.NTLMSSP_NEGOTIATE_ANONYMOUS
442
+ ):
443
+ hash_version, hash_string = NTLM_AUTH_to_hashcat_format(
444
+ self.config.ntlm_challange,
445
+ authenticateMessage["user_name"],
446
+ authenticateMessage["domain_name"],
447
+ authenticateMessage["lanman"],
448
+ authenticateMessage["ntlm"],
449
+ authenticateMessage["flags"],
450
+ )
451
+
452
+ flags = authenticateMessage["flags"]
453
+ host_name = NTLM_AUTH_decode_string(
454
+ authenticateMessage["host_name"], flags
455
+ )
456
+ user_name = NTLM_AUTH_decode_string(
457
+ authenticateMessage["user_name"], flags
458
+ )
459
+ domain_name = NTLM_AUTH_decode_string(
460
+ authenticateMessage["domain_name"], flags
461
+ )
462
+
463
+ self.logger.debug(
464
+ f"Completed NTLM AUTH flow for {domain_name}/{user_name} from {host_name}",
465
+ )
466
+ self.config.db.add_auth(
467
+ (connData["ClientIP"], self.server_config.smb_port),
468
+ credtype=hash_version,
469
+ password=hash_string,
470
+ logger=self.logger,
471
+ username=user_name,
472
+ domain=domain_name,
473
+ hostname=host_name,
474
+ )
475
+
476
+ errorCode = self.server_config.smb_error_code
477
+ respToken = negTokenInit_step(negResult=0x02)
478
+
479
+ case messageType:
480
+ raise Exception("Unknown NTLMSSP MessageType %d" % messageType)
481
+
482
+ respParameters["SecurityBlobLength"] = len(respToken)
483
+ respData["SecurityBlobLength"] = respParameters["SecurityBlobLength"]
484
+ respData["SecurityBlob"] = respToken.getData()
485
+
486
+ else:
487
+ # Process Standard Security
488
+ respParameters = smb.SMBSessionSetupAndXResponse_Parameters()
489
+ respData = smb.SMBSessionSetupAndXResponse_Data()
490
+ sessionSetupParameters = smb.SMBSessionSetupAndX_Parameters(
491
+ SMBCommand["Parameters"]
492
+ )
493
+ sessionSetupData = smb.SMBSessionSetupAndX_Data()
494
+ sessionSetupData["AnsiPwdLength"] = sessionSetupParameters["AnsiPwdLength"]
495
+ sessionSetupData["UnicodePwdLength"] = sessionSetupParameters[
496
+ "UnicodePwdLength"
497
+ ]
498
+ sessionSetupData.fromString(SMBCommand["Data"])
499
+ connData["Capabilities"] = sessionSetupParameters["Capabilities"]
500
+ # Do the verification here, for just now we grant access
501
+ # TODO: Manage more UIDs for the same session
502
+ errorCode = self.server_config.smb_error_code
503
+ connData["Uid"] = 10
504
+ respParameters["Action"] = 0
505
+
506
+ hversion, hstring = NTLM_AUTH_to_hashcat_format(
507
+ b"", # no challenge
508
+ sessionSetupData["Account"],
509
+ sessionSetupData["PrimaryDomain"],
510
+ sessionSetupData["AnsiPwd"],
511
+ sessionSetupData["UnicodePwd"],
512
+ 0, # no flags, username and domain are already decoded
513
+ )
514
+ self.logger.highlight(
515
+ f"{hversion} Username: {sessionSetupData['PrimaryDomain']}/{sessionSetupData['Account']}",
516
+ host=connData["ClientIP"],
517
+ )
518
+ self.logger.highlight(
519
+ f"{hversion} Hash: {hstring}",
520
+ host=connData["ClientIP"],
521
+ )
522
+
523
+ respData["NativeOS"] = encodeSMBString(
524
+ recvPacket["Flags2"], smbServer.getServerOS()
525
+ )
526
+ respData["NativeLanMan"] = encodeSMBString(
527
+ recvPacket["Flags2"], smbServer.getServerOS()
528
+ )
529
+ respSMBCommand["Parameters"] = respParameters
530
+ respSMBCommand["Data"] = respData
531
+
532
+ # From now on, the client can ask for other commands
533
+ connData["Authenticated"] = True
534
+ smbServer.setConnectionData(connId, connData)
535
+
536
+ return [respSMBCommand], None, errorCode
537
+
538
+ def run(self):
539
+ host, port, *_ = self.server.server_address
540
+ self.logger.debug(f"Starting SMB server on {host}:{port}")
541
+ self.server.daemon_threads = True
542
+ self.server.serve_forever()