-
-
Notifications
You must be signed in to change notification settings - Fork 207
/
Sooty.py
1231 lines (1078 loc) · 46 KB
/
Sooty.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 python3
"""
Title: Sooty
Desc: The SOC Analysts all-in-one CLI tool to automate and speed up workflow.
Author: Connor Jackson
Version: 1.3.2
GitHub URL: https://github.com/TheresAFewConors/Sooty
"""
import base64
from unfurl import core
import hashlib
import html.parser
import re
import json
import time
import os
import socket
import strictyaml
import urllib.parse
import requests
from ipwhois import IPWhois
import tkinter
import sys
from Modules import iplists
from Modules import phishtank
from Modules import TitleOpen
from datetime import datetime, date
try:
import win32com.client
except:
print('Cant install Win32com package')
versionNo = '1.3.2'
try:
f = open("config.yaml", "r")
configvars = strictyaml.load(f.read())
f.close()
except FileNotFoundError:
print("Config.yaml not found. Check the example config file and rename to 'config.yaml'.")
linksFoundList = []
linksRatingList = []
linksSanitized = []
linksDict = {}
def switchMenu(choice):
if choice == '1':
urlSanitise()
if choice == '2':
decoderMenu()
if choice == '3':
repChecker()
if choice == '4':
dnsMenu()
if choice == '5':
hashMenu()
if choice == '6':
phishingMenu()
if choice == '7':
urlscanio()
if choice == '9':
extrasMenu()
if choice == '0':
sys.exit("Exiting Sooty... done")
else:
mainMenu()
def decoderSwitch(choice):
if choice == '1':
proofPointDecoder()
if choice == '2':
urlDecoder()
if choice == '3':
safelinksDecoder()
if choice == '4':
unshortenUrl()
if choice == '5':
b64Decoder()
if choice == '6':
cisco7Decoder()
if choice == '7':
unfurlUrl()
if choice == '0':
mainMenu()
def dnsSwitch(choice):
if choice == '1':
reverseDnsLookup()
if choice == '2':
dnsLookup()
if choice == '3':
whoIs()
if choice == '0':
mainMenu()
def hashSwitch(choice):
if choice == '1':
hashFile()
if choice == '2':
hashText()
if choice == '3':
hashRating()
if choice == '4':
hashAndFileUpload()
if choice == '0':
mainMenu()
def phishingSwitch(choice):
if choice == '1':
analyzePhish()
if choice == '2':
analyzeEmailInput()
if choice == '3':
emailTemplateGen()
if choice == '4':
phishtankModule()
if choice == '9':
haveIBeenPwned()
else:
mainMenu()
def extrasSwitch(choice):
if choice == '1':
aboutSooty()
if choice == '2':
contributors()
if choice == '3':
extrasVersion()
if choice == '4':
wikiLink()
if choice == '5':
ghLink()
else:
mainMenu()
def decodev1(rewrittenurl):
match = re.search(r'u=(.+?)&k=', rewrittenurl)
if match:
urlencodedurl = match.group(1)
htmlencodedurl = urllib.parse.unquote(urlencodedurl)
url = html.unescape(htmlencodedurl)
url = re.sub("http://", "", url)
if url not in linksFoundList:
linksFoundList.append(url)
def decodev2(rewrittenurl):
match = re.search(r'u=(.+?)&[dc]=', rewrittenurl)
if match:
specialencodedurl = match.group(1)
trans = str.maketrans('-_', '%/')
urlencodedurl = specialencodedurl.translate(trans)
htmlencodedurl = urllib.parse.unquote(urlencodedurl)
url = html.unescape(htmlencodedurl)
url = re.sub("http://", "", url)
if url not in linksFoundList:
linksFoundList.append(url)
def decodev3(rewrittenurl):
match = re.search(r'v3/__(?P<url>.+?)__;', rewrittenurl)
if match:
url = match.group('url')
if re.search(r'\*(\*.)?', url):
url = re.sub('\*', '+', url)
if url not in linksFoundList:
linksFoundList.append(url)
def titleLogo():
TitleOpen.titleOpen()
os.system('cls||clear')
def mainMenu():
print("\n --------------------------------- ")
print("\n S O O T Y ")
print("\n --------------------------------- ")
print(" What would you like to do? ")
print("\n OPTION 1: Sanitise URL For emails ")
print(" OPTION 2: Decoders (PP, URL, SafeLinks) ")
print(" OPTION 3: Reputation Checker")
print(" OPTION 4: DNS Tools")
print(" OPTION 5: Hashing Function")
print(" OPTION 6: Phishing Analysis")
print(" OPTION 7: URL scan")
print(" OPTION 9: Extras")
print(" OPTION 0: Exit Tool")
switchMenu(input())
def urlSanitise():
print("\n --------------------------------- ")
print(" U R L S A N I T I S E T O O L ")
print(" --------------------------------- ")
url = str(input("Enter URL to sanitize: ").strip())
x = re.sub(r"\.", "[.]", url)
x = re.sub("http://", "hxxp://", x)
x = re.sub("https://", "hxxps://", x)
print("\n" + x)
mainMenu()
def decoderMenu():
print("\n --------------------------------- ")
print(" D E C O D E R S ")
print(" --------------------------------- ")
print(" What would you like to do? ")
print(" OPTION 1: ProofPoint Decoder")
print(" OPTION 2: URL Decoder")
print(" OPTION 3: Office SafeLinks Decoder")
print(" OPTION 4: URL unShortener")
print(" OPTION 5: Base64 Decoder")
print(" OPTION 6: Cisco Password 7 Decoder")
print(" OPTION 7: Unfurl URL")
print(" OPTION 0: Exit to Main Menu")
decoderSwitch(input())
def proofPointDecoder():
print("\n --------------------------------- ")
print(" P R O O F P O I N T D E C O D E R ")
print(" --------------------------------- ")
rewrittenurl = str(input(" Enter ProofPoint Link: ").strip())
match = re.search(r'https://urldefense.proofpoint.com/(v[0-9])/', rewrittenurl)
matchv3 = re.search(r'urldefense.com/(v3)/', rewrittenurl)
if match:
if match.group(1) == 'v1':
decodev1(rewrittenurl)
for each in linksFoundList:
print('\n Decoded Link: %s' % each)
linksFoundList.clear()
elif match.group(1) == 'v2':
decodev2(rewrittenurl)
for each in linksFoundList:
print('\n Decoded Link: %s' % each)
linksFoundList.clear()
if matchv3 is not None:
if matchv3.group(1) == 'v3':
decodev3(rewrittenurl)
for each in linksFoundList:
print('\n Decoded Link: %s' % each)
linksFoundList.clear()
else:
print(' No valid URL found in input: ', rewrittenurl)
mainMenu()
def urlDecoder():
print("\n --------------------------------- ")
print(" U R L D E C O D E R ")
print(" --------------------------------- ")
url = str(input(' Enter URL: ').strip())
decodedUrl = urllib.parse.unquote(url)
print(decodedUrl)
mainMenu()
def safelinksDecoder():
print("\n --------------------------------- ")
print(" S A F E L I N K S D E C O D E R ")
print(" --------------------------------- ")
url = str(input(' Enter URL: ').strip())
dcUrl = urllib.parse.unquote(url)
dcUrl = dcUrl.replace('https://nam02.safelinks.protection.outlook.com/?url=', '')
print(dcUrl)
mainMenu()
def urlscanio():
print("\n --------------------------------- ")
print("\n U R L S C A N . I O ")
print("\n --------------------------------- ")
url_to_scan = str(input('\nEnter url: ').strip())
try:
type_prompt = str(input('\nSet scan visibility to Public? \nType "1" for Public or "2" for Private: '))
if type_prompt == '1':
scan_type = 'public'
else:
scan_type = 'private'
except:
print('Please make a selection again.. ')
headers = {
'Content-Type': 'application/json',
'API-Key': configvars.data['URLSCAN_IO_KEY'],
}
response = requests.post('https://urlscan.io/api/v1/scan/', headers=headers, data='{"url": "%s", "%s": "on"}' % (url_to_scan, scan_type)).json()
try:
if 'successful' in response['message']:
print('\nNow scanning %s. Check back in around 1 minute.' % url_to_scan)
uuid_variable = str(response['uuid']) # uuid, this is the factor that identifies the scan
time.sleep(45) # sleep for 45 seconds. The scan takes awhile, if we try to retrieve the scan too soon, it will return an error.
scan_results = requests.get('https://urlscan.io/api/v1/result/%s/' % uuid_variable).json() # retrieving the scan using the uuid for this scan
task_url = scan_results['task']['url']
verdicts_overall_score = scan_results['verdicts']['overall']['score']
verdicts_overall_malicious = scan_results['verdicts']['overall']['malicious']
task_report_URL = scan_results['task']['reportURL']
print("\nurlscan.io Report:")
print("\nURL: " + task_url)
print("\nOverall Verdict: " + str(verdicts_overall_score))
print("Malicious: " + str(verdicts_overall_malicious))
print("urlscan.io: " + str(scan_results['verdicts']['urlscan']['score']))
if scan_results['verdicts']['urlscan']['malicious']:
print("Malicious: " + str(scan_results['verdicts']['urlscan']['malicious'])) # True
if scan_results['verdicts']['urlscan']['categories']:
print("Categories: ")
for line in scan_results['verdicts']['urlscan']['categories']:
print("\t"+ str(line)) # phishing
for line in scan_results['verdicts']['engines']['verdicts']:
print(str(line['engine']) + " score: " + str(line['score'])) # googlesafebrowsing
print("Categories: ")
for item in line['categories']:
print("\t" + item) # social_engineering
print("\nSee full report for more details: " + str(task_report_URL))
print('')
else:
print(response['message'])
except:
print(' Error reaching URLScan.io')
def unshortenUrl():
print("\n --------------------------------- ")
print(" U R L U N S H O R T E N E R ")
print(" --------------------------------- ")
link = str(input(' Enter URL: ').strip())
req = requests.get(str('https://unshorten.me/s/' + link))
print(req.text)
decoderMenu()
def b64Decoder():
url = str(input(' Enter URL: ').strip())
try:
b64 = str(base64.b64decode(url))
a = re.split("'", b64)[1]
print(" B64 String: " + url)
print(" Decoded String: " + a)
except:
print(' No Base64 Encoded String Found')
decoderMenu()
def cisco7Decoder():
pw = input(' Enter Cisco Password 7: ').strip()
key = [0x64, 0x73, 0x66, 0x64, 0x3b, 0x6b, 0x66, 0x6f, 0x41,
0x2c, 0x2e, 0x69, 0x79, 0x65, 0x77, 0x72, 0x6b, 0x6c,
0x64, 0x4a, 0x4b, 0x44, 0x48, 0x53, 0x55, 0x42]
try:
# the first 2 characters of the password are the starting index in the key array
index = int(pw[:2],16)
# the remaining values are the characters in the password, as hex bytes
pw_text = pw[2:]
pw_hex_values = [pw_text[start:start+2] for start in range(0,len(pw_text),2)]
# XOR those values against the key values, starting at the index, and convert to ASCII
pw_chars = [chr(key[index+i] ^ int(pw_hex_values[i],16)) for i in range(0,len(pw_hex_values))]
pw_plaintext = ''.join(pw_chars)
print("Password: " + pw_plaintext)
except Exception as e:
print(e)
decoderMenu()
def unfurlUrl():
url_to_unfurl = str(input('Enter URL to Unfurl: ')).strip()
unfurl_instance = core.Unfurl()
unfurl_instance.add_to_queue(data_type='url', key=None, value=url_to_unfurl)
unfurl_instance.parse_queue()
print(unfurl_instance.generate_text_tree())
decoderMenu()
def repChecker():
print("\n --------------------------------- ")
print(" R E P U T A T I O N C H E C K ")
print(" --------------------------------- ")
rawInput = input("Enter IP, URL or Email Address: ").split()
ip = str(rawInput[0])
s = re.findall(r'\S+@\S+', ip)
if s:
print(' Email Detected...')
analyzeEmail(''.join(s))
else:
whoIsPrint(ip)
wIP = socket.gethostbyname(ip)
now = datetime.now()
today = now.strftime("%m-%d-%Y")
if not os.path.exists('output/'+today):
os.makedirs('output/'+today)
f= open('output/'+today+'/'+str(rawInput) + ".txt","a+")
print("\n VirusTotal Report:")
f.write("\n --------------------------------- ")
f.write("\n VirusTotal Report:")
f.write("\n --------------------------------- \n")
url = 'https://www.virustotal.com/vtapi/v2/url/report'
params = {'apikey': configvars.data['VT_API_KEY'], 'resource': wIP}
response = requests.get(url, params=params)
pos = 0 # Total positives found in VT
tot = 0 # Total number of scans
if response.status_code == 200:
try:
result = response.json()
for each in result:
tot = result['total']
if result['positives'] != 0:
pos = pos +1
avg = pos/tot
print(" No of Databases Checked: " + str(tot))
print(" No of Reportings: " + str(pos))
print(" Average Score: " + str(avg))
print(" VirusTotal Report Link: " + result['permalink'])
f.write("\n\n No of Databases Checked: " + str(tot))
f.write("\n No of Reportings: " + str(pos))
f.write("\n Average Score: " + str(avg))
f.write("\n VirusTotal Report Link: " + result['permalink'])
except:
print('error')
else:
print(" There's been an error, check your API Key or VirusTotal may be down")
try:
TOR_URL = "https://check.torproject.org/cgi-bin/TorBulkExitList.py?ip=1.1.1.1"
req = requests.get(TOR_URL)
print("\n TOR Exit Node Report: ")
f.write("\n\n --------------------------------- ")
f.write("\n TOR Exit Node Report: ")
f.write("\n --------------------------------- \n")
if req.status_code == 200:
tl = req.text.split('\n')
c = 0
for i in tl:
if wIP == i:
print(" " + i + " is a TOR Exit Node")
f.write("\n " + " " + i + " is a TOR Exit Node")
c = c+1
if c == 0:
print(" " + wIP + " is NOT a TOR Exit Node")
f.write("\n " + wIP + " is NOT a TOR Exit Node")
else:
print(" TOR LIST UNREACHABLE")
f.write("\n TOR LIST UNREACHABLE")
except Exception as e:
print("There is an error with checking for Tor exit nodes:\n" + str(e))
print("\n Checking BadIP's... ")
f.write("\n\n ---------------------------------")
f.write("\n BadIP's Report : ")
f.write("\n --------------------------------- \n")
try:
BAD_IPS_URL = 'https://www.badips.com/get/info/' + wIP
response = requests.get(BAD_IPS_URL)
if response.status_code == 200:
result = response.json()
print(" " + str(result['suc']))
print(" Total Reports : " + str(result['ReporterCount']['sum']))
print("\n IP has been reported in the following Categories:")
f.write(" " + str(result['suc']))
f.write("\n Total Reports : " + str(result['ReporterCount']['sum']))
f.write("\n IP has been reported in the following Categories:")
for each in result['LastReport']:
timeReport = datetime.fromtimestamp(result['LastReport'].get(each))
print(' - ' + each + ': ' + str(timeReport))
f.write('\n - ' + each + ': ' + str(timeReport))
else:
print(' Error reaching BadIPs')
except:
print(' IP not found') #Defaults to IP not found - not actually accurate
f.write('\n IP not found')
print("\n ABUSEIPDB Report:")
f.write("\n\n ---------------------------------")
f.write("\n ABUSEIPDB Report:")
f.write("\n ---------------------------------\n")
try:
AB_URL = 'https://api.abuseipdb.com/api/v2/check'
days = '180'
querystring = {
'ipAddress': wIP,
'maxAgeInDays': days
}
headers = {
'Accept': 'application/json',
'Key': configvars.data['AB_API_KEY']
}
response = requests.request(method='GET', url=AB_URL, headers=headers, params=querystring)
if response.status_code == 200:
req = response.json()
print(" IP: " + str(req['data']['ipAddress']))
print(" Reports: " + str(req['data']['totalReports']))
print(" Abuse Score: " + str(req['data']['abuseConfidenceScore']) + "%")
print(" Last Report: " + str(req['data']['lastReportedAt']))
f.write("\n\n IP: " + str(req['data']['ipAddress']))
f.write("\n Reports: " + str(req['data']['totalReports']))
f.write("\n Abuse Score: " + str(req['data']['abuseConfidenceScore']) + "%")
f.write("\n Last Report: " + str(req['data']['lastReportedAt']))
f.close()
else:
print(" Error Reaching ABUSE IPDB")
except:
print(' IP Not Found')
print("\n\nChecking against IP blacklists: ")
iplists.main(rawInput)
mainMenu()
def dnsMenu():
print("\n --------------------------------- ")
print(" D N S T O O L S ")
print(" --------------------------------- ")
print(" What would you like to do? ")
print(" OPTION 1: Reverse DNS Lookup")
print(" OPTION 2: DNS Lookup")
print(" OPTION 3: WHOIS Lookup")
print(" OPTION 0: Exit to Main Menu")
dnsSwitch(input())
def reverseDnsLookup():
d = str(input(" Enter IP to check: ").strip())
try:
s = socket.gethostbyaddr(d)
print('\n ' + s[0])
except:
print(" Hostname not found")
dnsMenu()
def dnsLookup():
d = str(input(" Enter Domain Name to check: ").strip())
d = re.sub("http://", "", d)
d = re.sub("https://", "", d)
try:
s = socket.gethostbyname(d)
print('\n ' + s)
except:
print("Website not found")
dnsMenu()
def whoIs():
ip = str(input(' Enter IP / Domain: ').strip())
whoIsPrint(ip)
dnsMenu()
def whoIsPrint(ip):
try:
w = IPWhois(ip)
w = w.lookup_whois()
addr = str(w['nets'][0]['address'])
addr = addr.replace('\n', ', ')
print("\n WHO IS REPORT:")
print(" CIDR: " + str(w['nets'][0]['cidr']))
print(" Name: " + str(w['nets'][0]['name']))
# print(" Handle: " + str(w['nets'][0]['handle']))
print(" Range: " + str(w['nets'][0]['range']))
print(" Descr: " + str(w['nets'][0]['description']))
print(" Country: " + str(w['nets'][0]['country']))
print(" State: " + str(w['nets'][0]['state']))
print(" City: " + str(w['nets'][0]['city']))
print(" Address: " + addr)
print(" Post Code: " + str(w['nets'][0]['postal_code']))
# print(" Emails: " + str(w['nets'][0]['emails']))
print(" Created: " + str(w['nets'][0]['created']))
print(" Updated: " + str(w['nets'][0]['updated']))
now = datetime.now() # current date and time
today = now.strftime("%m-%d-%Y")
if not os.path.exists('output/'+today):
os.makedirs('output/'+today)
f= open('output/'+today+'/'+str(ip.split()) + ".txt","a+")
f.write("\n ---------------------------------")
f.write("\n WHO IS REPORT:")
f.write("\n ---------------------------------\n")
f.write("\n CIDR: " + str(w['nets'][0]['cidr']))
f.write("\n Name: " + str(w['nets'][0]['name']))
# print(" Handle: " + str(w['nets'][0]['handle']))
f.write("\n Range: " + str(w['nets'][0]['range']))
f.write("\n Descr: " + str(w['nets'][0]['description']))
f.write("\n Country: " + str(w['nets'][0]['country']))
f.write("\n State: " + str(w['nets'][0]['state']))
f.write("\n City: " + str(w['nets'][0]['city']))
f.write("\n Address: " + addr)
f.write("\n Post Code: " + str(w['nets'][0]['postal_code']))
# print(" Emails: " + str(w['nets'][0]['emails']))
f.write("\n Created: " + str(w['nets'][0]['created']))
f.write("\n Updated: " + str(w['nets'][0]['updated']))
f.close();
c = 0
except:
print("\n IP Not Found - Checking Domains")
ip = re.sub('https://', '', ip)
ip = re.sub('http://', '', ip)
try:
if c == 0:
s = socket.gethostbyname(ip)
print( ' Resolved Address: %s' % s)
c = 1
whoIsPrint(s)
except:
print(' IP or Domain not Found')
return
def hashMenu():
print("\n --------------------------------- ")
print(" H A S H I N G F U N C T I O N S ")
print(" --------------------------------- ")
print(" What would you like to do? ")
print(" OPTION 1: Hash a file")
print(" OPTION 2: Input and hash text")
print(" OPTION 3: Check a hash for known malicious activity")
print(" OPTION 4: Hash a file, check a hash for known malicious activity")
print(" OPTION 0: Exit to Main Menu")
hashSwitch(input())
def hashFile():
root = tkinter.Tk()
root.filename = tkinter.filedialog.askopenfilename(initialdir="/", title="Select file")
hasher = hashlib.md5()
with open(root.filename, 'rb') as afile:
buf = afile.read()
hasher.update(buf)
print(" MD5 Hash: " + hasher.hexdigest())
root.destroy()
hashMenu()
def hashText():
userinput = input(" Enter the text to be hashed: ")
print(" MD5 Hash: " + hashlib.md5(userinput.encode("utf-8")).hexdigest())
hashMenu()
def hashRating():
apierror = False
# VT Hash Checker
fileHash = str(input(" Enter Hash of file: ").strip())
url = 'https://www.virustotal.com/vtapi/v2/file/report'
params = {'apikey': configvars.data['VT_API_KEY'], 'resource': fileHash}
response = requests.get(url, params=params)
try: # EAFP
result = response.json()
except:
apierror = True
print("Error: Invalid API Key")
if not apierror:
if result['response_code'] == 0:
print("\n Hash was not found in Malware Database")
elif result['response_code'] == 1:
print(" VirusTotal Report: " + str(result['positives']) + "/" + str(result['total']) + " detections found")
print(" Report Link: " + "https://www.virustotal.com/gui/file/" + fileHash + "/detection")
else:
print("No Reponse")
hashMenu()
def hashAndFileUpload():
root = tkinter.Tk()
root.filename = tkinter.filedialog.askopenfilename(initialdir="/", title="Select file")
hasher = hashlib.md5()
with open(root.filename, 'rb') as afile:
buf = afile.read()
hasher.update(buf)
fileHash = hasher.hexdigest()
print(" MD5 Hash: " + fileHash)
root.destroy()
apierror = False
# VT Hash Checker
url = 'https://www.virustotal.com/vtapi/v2/file/report'
params = {'apikey': configvars.data['VT_API_KEY'], 'resource': fileHash}
response = requests.get(url, params=params)
try: # EAFP
result = response.json()
except:
apierror = True
print("Error: Invalid API Key")
if not apierror:
if result['response_code'] == 0:
print("\n Hash was not found in Malware Database")
elif result['response_code'] == 1:
print(" VirusTotal Report: " + str(result['positives']) + "/" + str(result['total']) + " detections found")
print(" Report Link: " + "https://www.virustotal.com/gui/file/" + fileHash + "/detection")
else:
print("No Response")
hashMenu()
def phishingMenu():
print("\n --------------------------------- ")
print(" P H I S H I N G ")
print(" --------------------------------- ")
print(" What would you like to do? ")
print(" OPTION 1: Analyze an Email ")
print(" OPTION 2: Analyze an Email Address for Known Activity")
print(" OPTION 3: Generate an Email Template based on Analysis")
print(" OPTION 4: Analyze an URL with Phishtank")
print(" OPTION 9: HaveIBeenPwned")
print(" OPTION 0: Exit to Main Menu")
phishingSwitch(input())
def analyzePhish():
try:
file = tkinter.filedialog.askopenfilename(initialdir="/", title="Select file")
with open(file, encoding='Latin-1') as f:
msg = f.read()
# Fixes issue with file name / dir name exceptions
file = file.replace('//', '/') # dir
file2 = file.replace(' ', '') # file name (remove spaces / %20)
os.rename(file, file2)
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
msg = outlook.OpenSharedItem(file)
except:
print(' Error Opening File')
print("\n Extracting Headers...")
try:
print(" FROM: ", str(msg.SenderName), ", ", str(msg.SenderEmailAddress))
print(" TO: ", str(msg.To))
print(" SUBJECT: ", str(msg.Subject))
print(" NameBehalf:", str(msg.SentOnBehalfOfName))
print(" CC: ", str(msg.CC))
print(" BCC: ", str(msg.BCC))
print(" Sent On: ", str(msg.SentOn))
print(" Created: ", str(msg.CreationTime))
s = str(msg.Body)
except:
print(' Header Error')
f.close()
print("\n Extracting Links... ")
try:
match = r"((www\.|http://|https://)(www\.)*.*?(?=(www\.|http://|https://|$)))"
a = re.findall(match, msg.Body, re.M | re.I)
for b in a:
match = re.search(r'https://urldefense.proofpoint.com/(v[0-9])/', b[0])
if match:
if match.group(1) == 'v1':
decodev1(b[0])
elif match.group(1) == 'v2':
decodev2(b[0])
else:
if b[0] not in linksFoundList:
linksFoundList.append(b[0])
if len(a) == 0:
print(' No Links Found...')
except:
print(' Links Error')
f.close()
for each in linksFoundList:
print(' %s' % each)
print("\n Extracting Emails Addresses... ")
try:
match = r'([\w0-9._-]+@[\w0-9._-]+\.[\w0-9_-]+)'
emailList = list()
a = re.findall(match, s, re.M | re.I)
for b in a:
if b not in emailList:
emailList.append(b)
print(" ", b)
if len(emailList) == 0:
print(' No Emails Found')
if len(a) == 0:
print(' No Emails Found...')
except:
print(' Emails Error')
f.close()
print("\n Extracting IP's...")
try:
ipList = []
foundIP = re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', s)
ipList.append(foundIP)
if not ipList:
for each in ipList:
print(each)
else:
print(' No IP Addresses Found...')
except:
print(' IP error')
try:
analyzeEmail(msg.SenderEmailAddress)
except:
print('')
phishingMenu()
def haveIBeenPwned():
print("\n --------------------------------- ")
print(" H A V E I B E E N P W N E D ")
print(" --------------------------------- ")
try:
acc = str(input(' Enter email: ').strip())
haveIBeenPwnedPrintOut(acc)
except:
print('')
phishingMenu()
def haveIBeenPwnedPrintOut(acc):
try:
url = 'https://haveibeenpwned.com/api/v3/breachedaccount/%s' % acc
userAgent = 'Sooty'
headers = {'Content-Type': 'application/json', 'hibp-api-key': configvars.data['HIBP_API_KEY'], 'user-agent': userAgent}
try:
req = requests.get(url, headers=headers)
response = req.json()
lr = len(response)
if lr != 0:
print('\n The account has been found in the following breaches: ')
for each in range(lr):
breach = 'https://haveibeenpwned.com/api/v3/breach/%s' % response[each]['Name']
breachReq = requests.get(breach, headers=headers)
breachResponse = breachReq.json()
breachList = []
print('\n Title: %s' % breachResponse['Title'])
print(' Domain: %s' % breachResponse['Domain'])
print(' Breach Date: %s' % breachResponse['BreachDate'])
print(' Pwn Count: %s' % breachResponse['PwnCount'])
for each in breachResponse['DataClasses']:
breachList.append(each)
print(' Data leaked: %s' % breachList)
except:
print(' No Entries found in Database')
except:
print('')
def analyzeEmailInput():
print("\n --------------------------------- ")
print(" E M A I L A N A L Y S I S ")
print(" --------------------------------- ")
try:
email = str(input(' Enter Email Address to Analyze: ').strip())
analyzeEmail(email)
phishingMenu()
except:
print(" Error Scanning Email Address")
def analyzeEmail(email):
try:
url = 'https://emailrep.io/'
userAgent = 'Sooty'
summary = '?summary=true'
url = url + email + summary
if 'API Key' not in configvars.data['EMAILREP_API_KEY']:
erep_key = configvars.data['EMAILREP_API_KEY']
headers = {'Content-Type': 'application/json', 'Key': configvars.data['EMAILREP_API_KEY'], 'User-Agent': userAgent}
response = requests.get(url, headers=headers)
else:
response = requests.get(url)
req = response.json()
emailDomain = re.split('@', email)[1]
print('\n Email Analysis Report ')
if response.status_code == 400:
print(' Invalid Email / Bad Request')
if response.status_code == 401:
print(' Unauthorized / Invalid API Key (for Authenticated Requests)')
if response.status_code == 429:
print(' Too many requests, ')
if response.status_code == 200:
now = datetime.now() # current date and time
today = now.strftime("%m-%d-%Y")
if not os.path.exists('output/'+today):
os.makedirs('output/'+today)
f = open('output/'+today+'/'+str(email) + ".txt","w+")
f.write("\n --------------------------------- ")
f.write('\n Email Analysis Report : ')
f.write("\n ---------------------------------\n ")
print(' Email: %s' % req['email'])
print(' Reputation: %s' % req['reputation'])
print(' Suspicious: %s' % req['suspicious'])
print(' Spotted: %s' % req['references'] + ' Times')
print(' Blacklisted: %s' % req['details']['blacklisted'])
print(' Last Seen: %s' % req['details']['last_seen'])
print(' Known Spam: %s' % req['details']['spam'])
f.write(' Email: %s' % req['email'])
f.write('\n Reputation: %s' % req['reputation'])
f.write('\n Suspicious: %s' % req['suspicious'])
f.write('\n Spotted: %s' % req['references'] + ' Times')
f.write('\n Blacklisted: %s' % req['details']['blacklisted'])
f.write('\n Last Seen: %s' % req['details']['last_seen'])
f.write('\n Known Spam: %s' % req['details']['spam'])
print('\n Domain Report ')
print(' Domain: @%s' % emailDomain)
print(' Domain Exists: %s' % req['details']['domain_exists'])
print(' Domain Rep: %s' % req['details']['domain_reputation'])
print(' Domain Age: %s' % req['details']['days_since_domain_creation'] + ' Days')
print(' New Domain: %s' % req['details']['new_domain'])
print(' Deliverable: %s' % req['details']['deliverable'])
print(' Free Provider: %s' % req['details']['free_provider'])
print(' Disposable: %s' % req['details']['disposable'])
print(' Spoofable: %s' % req['details']['spoofable'])
f.write("\n\n --------------------------------- ")
f.write('\n Domain Report ')
f.write("\n --------------------------------- \n")
f.write('\n Domain: @%s' % emailDomain)
f.write('\n Domain Exists: %s' % req['details']['domain_exists'])
f.write('\n Domain Rep: %s' % req['details']['domain_reputation'])
f.write('\n Domain Age: %s' % req['details']['days_since_domain_creation'] + ' Days')
f.write('\n New Domain: %s' % req['details']['new_domain'])
f.write('\n Deliverable: %s' % req['details']['deliverable'])
f.write('\n Free Provider: %s' % req['details']['free_provider'])
f.write('\n Disposable: %s' % req['details']['disposable'])
f.write('\n Spoofable: %s' % req['details']['spoofable'])
print('\n Malicious Activity Report ')
print(' Malicious Activity: %s' % req['details']['malicious_activity'])
print(' Recent Activity: %s' % req['details']['malicious_activity_recent'])
print(' Credentials Leaked: %s' % req['details']['credentials_leaked'])
print(' Found in breach: %s' % req['details']['data_breach'])
f.write("\n\n --------------------------------- ")
f.write('\n Malicious Activity Report ')
f.write("\n --------------------------------- \n")
f.write('\n Malicious Activity: %s' % req['details']['malicious_activity'])
f.write('\n Recent Activity: %s' % req['details']['malicious_activity_recent'])
f.write('\n Credentials Leaked: %s' % req['details']['credentials_leaked'])
f.write('\n Found in breach: %s' % req['details']['data_breach'])
if (req['details']['data_breach']):
try:
url = 'https://haveibeenpwned.com/api/v3/breachedaccount/%s' % email
headers = {'Content-Type': 'application/json', 'hibp-api-key': configvars.data['HIBP_API_KEY'], 'user-agent': userAgent}
try:
reqHIBP = requests.get(url, headers=headers)
response = reqHIBP.json()
lr = len(response)
if lr != 0:
print('\nThe account has been found in the following breaches: ')
for each in range(lr):
breach = 'https://haveibeenpwned.com/api/v3/breach/%s' % response[each]['Name']
breachReq = requests.get(breach, headers=headers)
breachResponse = breachReq.json()
breachList = []
print(' Title: %s' % breachResponse['Title'])
print(' Breach Date: %s' % breachResponse['BreachDate'])
f.write('\n Title: %s' % breachResponse['Title'])
f.write('\n Breach Date: %s' % breachResponse['BreachDate'])
for each in breachResponse['DataClasses']:
breachList.append(each)
print(' Data leaked: %s' % breachList,'\n')
f.write('\n Data leaked: %s' % breachList,'\n')
except:
print(' Error')
except:
print(' No API Key Found')
print('\n Profiles Found ')
f.write("\n\n --------------------------------- ")
f.write('\n Profiles Found ')
f.write("\n --------------------------------- \n")
if (len(req['details']['profiles']) != 0):
profileList = (req['details']['profiles'])
for each in profileList:
print(' - %s' % each)
f.write('\n - %s' % each)
else:
print(' No Profiles Found For This User')
f.write(' \n No Profiles Found For This User')
print('\n Summary of Report: ')