-
Notifications
You must be signed in to change notification settings - Fork 149
/
munin.py
executable file
·1603 lines (1429 loc) · 61.3 KB
/
munin.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
__AUTHOR__ = 'Florian Roth'
__VERSION__ = "0.22.0 January 2023"
"""
Install dependencies with:
pip install -r requirements.txt
pip3 install -r requirements.txt
"""
import codecs
import configparser
import requests
from requests.auth import HTTPBasicAuth
import time
import re
import os
import math
import ast
import signal
import sys
import json
import hashlib
import codecs
import traceback
import argparse
import logging
import gzip
import pyzipper
import shutil
from valhallaAPI.valhalla import ValhallaAPI
from collections import defaultdict
from io import BytesIO
from datetime import datetime
from colorama import init, Fore, Back, Style
from lib.helper import generateResultFilename
import lib.munin_vt as munin_vt
from lib.munin_csv import writeCSVHeader, writeCSV, CSV_FIELDS
import lib.connections as connections
from lib.munin_stdout import printResult, printHighlighted, printKeyLine
import cfscrape
# Handle modules that may be difficult to install
# e.g. pymisp has no Debian package, selenium is obsolete
deactivated_features = []
try:
import pymisp
except ImportError as e:
print("ERROR: Module 'PyMISP' not found (this feature will be deactivated: MISP queries)")
deactivated_features.append("pymisp")
try:
from flask import Flask
from flask_caching import Cache
app = Flask(__name__)
flask_cache = Cache(config={'CACHE_TYPE': 'simple', "CACHE_DEFAULT_TIMEOUT": 15})
flask_cache.init_app(app)
except ImportError as e:
traceback.print_exc()
print("ERROR: Module 'flask' or 'flask_caching' not found (try to fix this with 'pip3 install flask flask_caching'")
deactivated_features.append("flask")
# CONFIG ##############################################################
# API keys / secrets - please configure them in 'munin.ini'
MAL_SHARE_API_KEY = '-'
PAYLOAD_SEC_API_KEY = '-'
TAGS = ['HARMLESS', 'SIGNED', 'MSSOFT', 'REVOKED', 'EXPIRED']
# MalwareShare URL
MAL_SHARE_API = 'https://malshare.com/api.php?api_key=%s&action=details&hash=%s'
MAL_SHARE_LINK = 'https://malshare.com/sample.php?action=detail&hash='
# Hybrid Analysis URL
HYBRID_ANALYSIS_URL = 'https://www.hybrid-analysis.com/api/v2/search/hash'
# Hybrid Analysis Download URL
HYBRID_ANALYSIS_DOWNLOAD_URL = 'https://www.hybrid-analysis.com/api/v2/overview/%s/sample'
# Hybrid Analysis Sample URL
URL_HA = 'https://hybrid-analysis.com/sample'
# TotalHash URL
TOTAL_HASH_URL = 'https://totalhash.cymru.com/analysis/'
# VirusBay URL
VIRUSBAY_URL = 'https://beta.virusbay.io/sample/search?q='
# URLhaus
URL_HAUS_URL = "https://urlhaus-api.abuse.ch/v1/payload/"
URL_HAUS_MAX_URLS = 5
# AnyRun
URL_ANYRUN = "https://any.run/report/%s"
# CAPE
URL_CAPE_MD5 = "https://www.capesandbox.com/api/tasks/search/md5/%s/"
URL_CAPE_SHA1 = "https://www.capesandbox.com/api/tasks/search/sha1/%s/"
URL_CAPE_SHA256 = "https://www.capesandbox.com/api/tasks/search/sha256/%s/"
CAPE_MAX_REPORTS = 5
# MALWARE Bazar
MALWARE_BAZAR_API = "https://mb-api.abuse.ch/api/v1/"
MALWARE_BAZAR_LINK = "https://bazaar.abuse.ch/sample/%s/"
# Intezer URL
INTEZER_URL = "https://analyze.intezer.com/api/v2-0"
INTEZER_NON_QUOTA_URL = "https://analyze.intezer.com/api/v1-2/code-items/%s/latest-public-analysis"
INTEZER_ANALYSIS_URL = "https://analyze.intezer.com/files/%s"
# Valhalla URL
VALHALLA_URL = "https://valhalla.nextron-systems.com/api/v1/hashinfo"
############### The following defaults can be overwritten by munin.ini
# maximum number of hashes to collect from matches of multiple Valhalla rules to be collected before querying VT and the other services
VALHALLA_MAX_QUERY_SIZE = 10000
# maximum number of hashes to collect from matches of multiple Virustotal searches (300 comments per search, might be multiple per hash!) to be collected before querying VT and the other services
VIRUSTOTAL_MAX_QUERY_SIZE = 600
WAIT_TIME = 17 # Public VT API allows 4 request per minute, so we wait 15 secs by default
QUOTA_EXCEEDED_WAIT_TIME = 1200 # wait if quota is exceeded and --vtwaitquota is used
VH_RULE_CUTOFF = 0
VENDORS = ['Microsoft', 'Kaspersky', 'McAfee', 'CrowdStrike', 'TrendMicro',
'ESET-NOD32', 'Symantec', 'F-Secure', 'Sophos', 'GData']
############### End of munin.ini overwrittable vars
# Header to Fake a Real Browser
FAKE_HEADERS = {
'referer': 'https://www.google.com',
'pragma': 'no-cache',
'cache-control': 'no-cache',
'sec-ch-ua': '"Chromium";v="88", "Google Chrome";v="88", ";Not A Brand";v="99"',
'accept': 'application/json, text/plain, */*',
'dnt': '1',
'sec-ch-ua-mobile': '?0',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36',
'sec-fetch-site': 'same-origin',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
'accept-language': 'en-US,en;q=0.9,de-DE;q=0.8,de;q=0.7,es;q=0.6'
}
def processLine(line, debug):
"""
Process a single line of input
:param line:
:param debug:
:return info:
:return cooldown_time: remaining cooldown time
:return cache_result:
"""
# Measure time for VT cooldown
start_time = time.time()
cooldown_time = 0
# Info dictionary
info = {"md5": "-", "sha1": "-", "sha256": "-", "vt_queried": False}
# Remove line break
line = line.rstrip("\n").rstrip("\r")
# Skip comments
if line.startswith("#"):
return (info, cooldown_time, None)
# Get all hashes in line
# ... and the rest of the line as comment
hashVal, hashType, comment = fetchHash(line)
info['hash'] = hashVal
info[hashType] = hashVal
info['comment'] = comment
# If no hash found
if hashVal == '':
return (info, cooldown_time, None)
# Cache
cache_result = inCache(hashVal)
if cache_result:
info = cache_result
# But keep the new comment
info["comment"] = comment
# New fields - add them to old cache entries
for key, value in CSV_FIELDS.items():
if value not in info:
info[value] = "-"
# Fix old cached used names
if ',' in info["commenter"]:
info["commenter"] = info["commenter"].split(',')
if debug:
print("[D] Value found in cache: %s" % cache_result)
# If not found in cache or --nocache set
if args.nocache or not cache_result:
# Get Information
# Virustotal
vt_info = munin_vt.getVTInfo(hashVal, args.debug, VENDORS, QUOTA_EXCEEDED_WAIT_TIME, args.vtwaitquota)
info.update(vt_info)
# Valhalla
valhalla_info = getValhalla(info['sha256'])
info.update(valhalla_info)
if not config.has_option('VIRUSTOTAL', 'SKIP_SERVICES'):
# MISP
misp_info = getMISPInfo(hashVal)
info.update(misp_info)
# MalShare
ms_info = getMalShareInfo(hashVal)
info.update(ms_info)
# Hybrid Analysis
ha_info = getHybridAnalysisInfo(hashVal)
info.update(ha_info)
# Intezer
int_info = getIntezerInfo(info['sha256'])
info.update(int_info)
# URLhaus
uh_info = getURLhaus(info['md5'], info['sha256'])
info.update(uh_info)
# AnyRun
#ar_info = getAnyRun(info['sha256'])
#info.update(ar_info)
# CAPE
ca_info = getCAPE(info['md5'], info['sha1'], info['sha256'])
info.update(ca_info)
# Malware Bazar
mb_info = getMalwareBazarInfo(hashVal)
info.update(mb_info)
# Hashlookup
hashlookup_info = getHashlookup(info['md5'], info['sha1'], info['sha256'])
info.update(hashlookup_info)
# TotalHash
# th_info = {'totalhash_available': False}
# if 'sha1' in info:
# th_info = getTotalHashInfo(info['sha1'])
# info.update(th_info)
# VirusBay
vb_info = getVirusBayInfo(info['md5'])
info.update(vb_info)
# Add to hash cache and current batch info list
if not cache_result:
cache.append(info)
# else set vt_queried to False to avoid sleep time
else:
info['vt_queried'] = False
# Wait some time for the next request
cooldown_time = 0
if 'vt_queried' in info: # could be missing on cache values
if info["vt_queried"]:
cooldown_time = max(0, WAIT_TIME - int(time.time() - start_time))
return info, cooldown_time, cache_result
def processLines(lines, resultFile, nocsv=False, debug=False, limit=0):
"""
Process the input file line by line
"""
# Infos of the current batch
infos = []
# count fetched results for --limit
uncached_hashes = 0
printHighlighted("[+] Processing %d lines ..." % len(lines))
# Sorted
if args.sort:
lines = sorted(lines)
for i, line in enumerate(lines):
# Measure time (used for VT request throttling)
start_time = time.time()
# Process the line
info, cooldown_time, cache_result = processLine(line, debug)
if not cache_result:
uncached_hashes += 1
# Empty result
if not info or (info['md5'] == "-" and info['sha1'] == "-" and info['sha256'] == "-"):
# do nothing but don't "continue" bec of the possible "break" later
pass
else:
# Print result
printResult(info, i, len(lines))
# Comment on sample
if args.comment and info['sha256'] != "-":
munin_vt.commentVTSample(info['sha256'], "%s %s" % (args.p, info['comment']))
# Rescan a sample
if args.rescan and info['sha256'] != "-":
munin_vt.rescanVTSample(info['sha256'])
# Download samples
if args.download and 'sha256' in info:
downloadHybridAnalysisSample(info['sha256'])
downloadMalwareBazarSample(info['sha256'])
elif args.debug and args.download:
print("[D] Didn't start download: No sha256 hash found!")
# Print to CSV
if not nocsv:
writeCSV(info, resultFile)
# Add to infos list
infos.append(info)
# Comparison Checks
peChecks(info, infos)
# Platform Checks
platformChecks(info)
# only respect limit of > 0
if limit and uncached_hashes >= limit:
print("Exiting because limit of %d uncached hashes reached!" % limit )
break
# Wait the remaining cooldown time
time.sleep(cooldown_time)
return infos
def fetchHash(line):
"""
Extracts hashes from a line
:param line:
:return:
"""
hashTypes = {32: 'md5', 40: 'sha1', 64: 'sha256'}
pattern = r'((?<!FIRSTBYTES:\s)|[\b\s]|^)([0-9a-fA-F]{32}|[0-9a-fA-F]{40}|[0-9a-fA-F]{64})(\b|$)'
hash_search = re.findall(pattern, line)
# print hash_search
if len(hash_search) > 0:
hash = hash_search[0][1]
rest = ' '.join(re.sub('({0}|;|,|:)'.format(hash), ' ', line).strip().split())
return hash, hashTypes[len(hash)], rest
return '', '', ''
def getMalShareInfo(hash):
"""
Retrieves information from MalwareShare https://malshare.com
:param hash: hash value
:return info: info object
"""
info = {'malshare_available': False}
if MAL_SHARE_API_KEY == "-" or not MAL_SHARE_API_KEY:
return info
try:
#print("Malshare URL: %s" % (MAL_SHARE_API % (MAL_SHARE_API_KEY, hash)))
response_query = requests.get(MAL_SHARE_API % (MAL_SHARE_API_KEY, hash),
timeout=15,
proxies=connections.PROXY,
headers=FAKE_HEADERS)
if args.debug:
print("[D] Querying Malshare: %s" % response_query.request.url)
#print(response_query.content)
response = json.loads(response_query.content)
# If response is MD5 hash
if 'ERROR' in response:
info['malshare_available'] = False
if args.debug:
print("[D] Malshare response: %s" % response_query.content)
else:
info['malshare_available'] = True
# Making sure that an MD5 hash is available for link generation
info['md5'] = response['MD5']
if args.debug:
print("[D] Malshare response: %s" % response_query.content)
except Exception as e:
if args.debug:
traceback.print_exc()
return info
def getMalwareBazarInfo(hash):
"""
Retrieves info from Malware Bazar
:param hash:
:return:
"""
info = {'malware_bazar_available': False}
if MALWARE_BAZAR_API == "-" or not MALWARE_BAZAR_API:
return info
try:
data = {"query": 'get_info', "hash": hash}
response = requests.post(MALWARE_BAZAR_API, data=data, timeout=3, proxies=connections.PROXY)
#print("Response: '%s'" % response.json())
res = response.json()
if res['query_status'] == "ok":
info['malware_bazar_available'] = True
# Making sure that a sha256 hash is available for link generation
if 'sha256_hash' in res:
if res['sha256_hash'] != "":
info['sha256'] = res['sha256_hash']
except Exception as e:
print("Error while accessing Malware Bazar")
if args.debug:
traceback.print_exc()
return info
def getIntezerInfo(sha256):
"""
Retrieves info from Intezer
:param hash:
:return:
"""
info = {'intezer_available': False}
if sha256 == "-":
return info
try:
response_query = requests.get(INTEZER_NON_QUOTA_URL % sha256,
timeout=3,
proxies=connections.PROXY,
headers={
'referer': INTEZER_ANALYSIS_URL % sha256,
'authority': 'analyze.intezer.com',
'pragma': 'no-cache',
'cache-control': 'no-cache',
'sec-ch-ua': '"Chromium";v="88", "Google Chrome";v="88", ";Not A Brand";v="99"',
'accept': 'application/json, text/plain, */*',
'dnt': '1',
'sec-ch-ua-mobile': '?0',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36',
'sec-fetch-site': 'same-origin',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
'accept-language': 'en-US,en;q=0.9,de-DE;q=0.8,de;q=0.7,es;q=0.6'
})
if b"File not found" not in response_query.content:
info['intezer_available'] = True
"""
if INTEZER_API_KEY == "-" or not INTEZER_API_KEY:
return info
try:
response = requests.post(INTEZER_URL + '/get-access-token', json={'api_key': INTEZER_API_KEY})
response.raise_for_status()
session = requests.session()
session.headers['Authorization'] = session.headers['Authorization'] = 'Bearer %s' % response.json()['result']
response = session.get(INTEZER_URL + '/files/{}'.format(hash))
if response.status_code == 404 or response.status_code == 410:
return info
else:
info['intezer_available'] = True
response.raise_for_status()
report = response.json()
if args.debug:
print("[D] Intezer: %s" % report)
info['intezer_analysis'] = report['result']['analysis_url']
info['intezer_family'] = report['result']['family_name']
"""
except Exception as e:
if args.debug:
traceback.print_exc()
return info
def getMISPInfo(hash):
"""
Retrieves information from a MISP instance
:param hash: hash value
:return info: info object
"""
info = {'misp_available': False, 'misp_events': ''}
requests.packages.urllib3.disable_warnings() # I don't care
# Check whether the MISP section exists
if not has_MISP:
return info
# Check if any auth key is set
key_set = False
for m in MISP_AUTH_KEYS:
if m != '' and m != '-':
key_set = True
if not key_set or 'pymisp' in deactivated_features:
return info
# Loop through MISP instances
misp_info = []
misp_events = []
for c, m_url in enumerate(MISP_URLS, start=0):
# Get the corresponding auth key
m_auth_key = MISP_AUTH_KEYS[c]
if args.debug:
print("[D] Querying MISP: %s" % m_url)
try:
# Preparing API request
misp = pymisp.PyMISP(m_url, m_auth_key, args.verifycert, debug=args.debug, proxies={},cert=None,auth=None,tool='Munin : Online hash checker')
if args.debug:
print("[D] Query: values=%s" % hash)
result = misp.search('attributes', type_attribute=fetchHash(hash)[1] ,value=hash)
# Processing the result
if result['Attribute']:
events_added = list()
if args.debug:
print("[D] Dump Attribute : "+json.dumps(result['Attribute'], indent=2))
for r in result['Attribute']:
# Check for duplicates
if r['event_id'] in events_added:
continue
# Try to get info on the events
event_info = ""
misp_events.append('MISP%d:%s' % (c+1, r['event_id']))
e_result = misp.search('events', eventid=r['event_id'])
if e_result:
event_info = e_result[0]['Event']['info']
# too much
# if args.debug:
# print(json.dumps(e_result['response'], indent=2))
# Create MISP info object
misp_info.append({
'misp_nr': c+1,
'event_info': event_info,
'event_id': r['event_id'],
'comment': r['comment'],
'url': '%s/events/view/%s' % (m_url, r['event_id'])
})
events_added.append(r['event_id'])
else:
info['misp_available'] = False
except Exception as e:
if args.debug:
traceback.print_exc()
info['misp_info'] = misp_info
info['misp_events'] = ", ".join(misp_events)
if len(misp_events) > 0:
info['misp_available'] = True
return info
def getHashlookup(md5, sha1, sha256):
"""
Retrieves information from Hashlookup services
:param md5: hash value
:param sha1: hash value
:param sha256: hash value
:return info: info object
"""
info = {'hashlookup_available': False}
if not has_hashlookup:
return info
# Loop through hsahlookup instances
hashlookup_info = []
for c, h_url in enumerate(HASHLOOKUP_URLS, start=0):
tags = []
# Get the corresponding data
h_auth_key = HASHLOOKUP_AUTH_KEYS[c]
h_name = HASHLOOKUP_HANDLES[c]
if args.debug:
print("[D] Querying Hashlookup Service {}".format(h_name))
h_url = h_url + '{}/{}'
try:
if sha256 != "-":
response = requests.get(h_url.format('sha256', sha256), timeout=3, proxies=connections.PROXY, headers={'Authorization': h_auth_key})
elif sha1 != "-":
response = requests.get(h_url.format('sha1', sha1), timeout=3, proxies=connections.PROXY, headers={'Authorization': h_auth_key})
elif md5 != "-":
response = requests.get(h_url.format('md5', md5), timeout=3, proxies=connections.PROXY, headers={'Authorization': h_auth_key})
if args.debug:
print("[D] Hashlookup Response Code: %s" % response.status_code)
if response.status_code == 200:
hashlookup_info.append({
'hashlookup_source': h_name,
'source_url': response.url,
'response': response.json()
})
info['hashlookup_available'] = True
except Exception as e:
if args.debug:
print("Error while accessing hashlookup")
traceback.print_exc()
info['hashlookup_info'] = hashlookup_info
return info
def getHybridAnalysisInfo(hash):
"""
Retrieves information from Payload Security's public sandbox https://www.hybrid-analysis.com
:param hash: hash value
:return info: info object
"""
info = {'hybrid_available': False, 'hybrid_score': '-', 'hybrid_date': '-', 'hybrid_compromised': '-'}
if PAYLOAD_SEC_API_KEY == "-" or not PAYLOAD_SEC_API_KEY:
return info
try:
# Set headers
headers = {'User-Agent': 'VxStream', 'api-key': PAYLOAD_SEC_API_KEY}
data = {'hash': hash}
# Querying Hybrid Analysis
if args.debug:
print("[D] Querying Hybrid Analysis")
response = requests.post(HYBRID_ANALYSIS_URL, headers=headers,
timeout=4, proxies=connections.PROXY, data=data)
res_json = response.json()
# If response has content
info['hybrid_available'] = len(res_json) > 0
if len(res_json) > 0:
info['hybrid_available'] = True
if 'threat_score' in res_json[0]:
info['hybrid_score'] = res_json[0]['threat_score']
if 'analysis_start_time' in res_json[0]:
info['hybrid_date'] = res_json[0]['analysis_start_time']
if 'compromised_hosts' in res_json[0]:
info['hybrid_compromised'] = res_json[0]['compromised_hosts']
except ConnectionError as e:
print("Error while accessing HA: connection failed")
if args.debug:
traceback.print_exc()
except Exception as e:
print("Error while accessing Hybrid Analysis: %s" % response.content)
if args.debug:
traceback.print_exc()
finally:
return info
def getValhalla(sha256):
"""
Retrieves information from Valhalla
:param sha256: hash value
:return info: info object
"""
info = {'valhalla_match': False, 'valhalla_matches': []}
if sha256 == "-":
return info
if not VALHALLA_API_KEY or VALHALLA_API_KEY == "-":
return info
# Ready to go
if args.debug:
print("[D] Querying VALHALLA: %s" % sha256)
try:
data = {
"sha256": sha256,
"apikey": VALHALLA_API_KEY,
}
response = requests.post(VALHALLA_URL, data=data, proxies=connections.PROXY)
if args.debug:
print("[D] VALHALLA Response: '%s'" % response.json())
res = response.json()
if res['status'] == "success":
info['valhalla_match'] = True
info['valhalla_matches'] = res['results']
except Exception as e:
print("Error while accessing VALHALLA")
if args.debug:
traceback.print_exc()
finally:
return info
def downloadHybridAnalysisSample(hash):
"""
Downloads Sample from https://www.hybrid-analysis.com
:param hash: sha256 hash value
:return success: bool Download Success
"""
info = {'hybrid_score': '-', 'hybrid_date': '-', 'hybrid_compromised': '-'}
try:
# Prepare request
preparedURL = HYBRID_ANALYSIS_DOWNLOAD_URL % hash
# Set user agent string
headers = {'User-Agent': 'Falcon Sandbox', 'api-key': PAYLOAD_SEC_API_KEY}
# Prepare Output filename and write the sample
outfile = os.path.join(args.d, hash)
# Querying Hybrid Analysis
if args.debug:
print("[D] Requesting download of sample: %s" % preparedURL)
response = requests.get(preparedURL, params={'environmentId':'100'}, headers=headers, proxies=connections.PROXY)
# If the response is a json file
if response.headers["Content-Type"] == "application/json":
responsejson = json.loads(response.text)
if args.debug:
print("[D] Something went wrong: " +responsejson["message"])
return False
# If the content is an octet stream
elif response.headers["Content-Type"] == "application/gzip":
plaintextContent = gzip.decompress(response.content)
f_out = open(outfile, 'wb')
f_out.write(plaintextContent)
f_out.close()
print("[+] Downloaded sample from Hybrid-Analysis to: %s" % outfile)
# Return successful
return True
else:
if args.debug:
print("[D] Unexpected content type: " + response.headers["Content-Type"])
return False
except ConnectionError as e:
print("Error while accessing HA: connection failed")
if args.debug:
traceback.print_exc()
except Exception as e:
print("Error while accessing Hybrid Analysis: %s" % response.content)
if args.debug:
traceback.print_exc()
finally:
return False
def downloadMalwareBazarSample(hash):
"""
Downloads Sample from https://bazaar.abuse.ch/
:param hash: sha256 hash value
:return success: bool Download Success
"""
# Check API Key
if MAL_BAZAR_API_KEY == "" or MAL_BAZAR_API_KEY == "-":
print("You cannot download samples from Malware Bazar without an API key")
return False
try:
if args.debug:
print("[D] Requesting download of sample from Malware Bazar")
# Rquest
data = {"API-KEY": MAL_BAZAR_API_KEY, "query": 'get_file', "sha256_hash": hash}
response = requests.post(MALWARE_BAZAR_API, data=data, timeout=3, proxies=connections.PROXY)
#print(response.headers)
# Process the Response
if response.headers["Content-Type"] == "application/zip":
buffer = BytesIO()
buffer.write(response.content)
with pyzipper.AESZipFile(buffer) as f:
f.setpassword(b'infected')
for file in f.filelist:
# Prepare Output filename and write the sample
outfile = os.path.join(args.d, file.filename)
with open(outfile, 'wb') as f_out:
f_out.write(f.read(file.filename))
print("[+] Downloaded sample from Malware Bazar to: %s" % outfile)
return True
except Exception as e:
print("Error while downloading from Malware Bazar")
if args.debug:
traceback.print_exc()
return False
def getTotalHashInfo(sha1):
"""
Retrieves information from Totalhash https://totalhash.cymru.com
:param hash: hash value
:return info: info object
"""
info = {'totalhash_available': False}
try:
# Prepare request
preparedURL = "%s?%s" % (TOTAL_HASH_URL, sha1)
# Set user agent string
# headers = {'User-Agent': ''}
# Querying Hybrid Analysis
if args.debug:
print("[D] Querying Totalhash: %s" % preparedURL)
response = requests.get(preparedURL, proxies=connections.PROXY)
# print "Response: '%s'" % response.content
if response.content and \
'0 of 0 results' not in response.content and \
'Sorry something went wrong' not in response.content:
info['totalhash_available'] = True
except ConnectionError as e:
print("Error while accessing Total Hash: connection failed")
if args.debug:
traceback.print_exc()
except Exception as e:
print("Error while accessing Totalhash: %s" % response.content)
if args.debug:
traceback.print_exc()
return info
def getURLhaus(md5, sha256):
"""
Retrieves information from URLhaus https://urlhaus-api.abuse.ch/#download-sample
:param md5: hash value
:param sha256: hash value
:return info: info object
"""
info = {'urlhaus_available': False}
if 'md5' == "-" and 'sha256' == "-":
return info
try:
if sha256:
data = {"sha256_hash": sha256}
else:
data = {"md5_hash": md5}
response = requests.post(URL_HAUS_URL, data=data, timeout=3, proxies=connections.PROXY)
#print("Response: '%s'" % response.json())
res = response.json()
if res['query_status'] == "ok" and res['md5_hash']:
info['urlhaus_available'] = True
info['urlhaus_type'] = res['file_type']
info['urlhaus_url_count'] = res['url_count']
info['urlhaus_first'] = res['firstseen']
info['urlhaus_last'] = res['lastseen']
info['urlhaus_download'] = res['urlhaus_download']
info['urlhaus_urls'] = res['urls']
except Exception as e:
print("Error while accessing URLhaus")
if args.debug:
traceback.print_exc()
return info
def getCAPE(md5, sha1, sha256):
"""
Retrieves information from CAPE
:param md5: hash value
:param sha1:
:param sha256:
:return info: info object
"""
info = {'cape_available': False}
try:
if sha256 != "-":
response = requests.get(URL_CAPE_SHA256 % sha256, timeout=3, proxies=connections.PROXY)
elif sha1 != "-":
response = requests.get(URL_CAPE_SHA1 % sha1, timeout=3, proxies=connections.PROXY)
elif md5 != "-":
response = requests.get(URL_CAPE_MD5 % md5, timeout=3, proxies=connections.PROXY)
#print("CAPE Response: '%s'" % response.content)
res = response.json()
if not res['error'] and len(res['data']) > 0:
info['cape_available'] = True
c = 0
info['cape_reports'] = []
for report in res['data']:
info['cape_reports'].append(report['id'])
if c >= CAPE_MAX_REPORTS:
break
except Exception as e:
if args.debug:
print("Error while accessing CAPE")
traceback.print_exc()
return info
def getAnyRun(sha256):
"""
Retrieves information from AnyRun Service
:param sha256: hash value
:return info: info object
"""
info = {'anyrun_available': False}
if sha256 == "-":
return info
try:
if args.debug:
print("[D] Querying Anyrun")
cfscraper = cfscrape.create_scraper()
response = cfscraper.get(URL_ANYRUN % sha256, proxies=connections.PROXY)
if args.debug:
print("[D] Anyrun Response Code: %s" %response.status_code)
if response.status_code == 200:
info['anyrun_available'] = True
except ConnectionError as e:
print("Error while accessing AnyRun: connection failed")
if args.debug:
traceback.print_exc()
except Exception as e:
print("Error while accessing AnyRun")
if args.debug:
traceback.print_exc()
return info
def getVirusBayInfo(hash):
"""
Retrieves information from VirusBay https://beta.virusbay.io/
:param hash: hash value
:return info: info object
"""
info = {'virusbay_available': False}
if hash == "-":
return info
try:
# Prepare request
preparedURL = "%s%s" % (VIRUSBAY_URL, hash)
if args.debug:
print("[D] Querying Virusbay: %s" % preparedURL)
response = requests.get(preparedURL, proxies=connections.PROXY).json()
# If response has the correct content
info['virusbay_available'] = False
#print(response)
tags = []
if response['search'] != []:
info['virusbay_available'] = True
for tag in response['search'][0]['tags']:
tags.append(tag['name'])
info['vb_tags'] = tags
info['vb_link'] = "https://beta.virusbay.io/sample/browse/%s" % response['search'][0]['md5']
except Exception as e:
if args.debug:
print("Error while accessing VirusBay")
traceback.print_exc()
return info
def peChecks(info, infos):
"""
Check for duplicate imphashes
:param info:
:param infos:
:return:
"""
# Some static values
SIGNER_WHITELIST = ["Microsoft Windows", "Microsoft Corporation"]
# Imphash check
imphash_count = 0
for i in infos:
if 'imphash' in i and 'imphash' in info:
if i['imphash'] != "-" and i['imphash'] == info['imphash']:
imphash_count += 1
if imphash_count > 1:
printHighlighted("[!] Imphash - appeared %d times in this batch %s" %
(imphash_count, info['imphash']))
# Signed Appeared multiple times
try:
signer_count = 0
for s in infos:
if 'signer' in s and 'signer' in info:
if s['signer'] != "-" and s['signer'] and s['signer'] == info['signer'] and \
not any(s in info['signer'] for s in SIGNER_WHITELIST):
signer_count += 1
if signer_count > 1:
printHighlighted("[!] Signer - appeared %d times in this batch %s" %
(signer_count, info['signer'].encode('raw-unicode-escape')))
except KeyError as e:
if args.debug:
traceback.print_exc()
def platformChecks(info):
"""
Performs certain comparison checks on the given info object compared to past
evaluations from the current batch and cache
:param info:
:return:
"""
try:
# MISP results
if 'misp_available' in info:
if info['misp_available']:
for e in info['misp_info']:
printHighlighted("[!] MISP event found EVENT_ID: {0} EVENT_INFO: {1} URL: {2}".format(
e['event_id'], e['event_info'], e['url'])
)
except KeyError as e:
if args.debug:
traceback.print_exc()
try:
# Malware Share availability
if 'malshare_available' in info:
if info['malshare_available']:
printHighlighted("[!] Sample is available on malshare.com URL: {0}{1}".format(
MAL_SHARE_LINK, info['md5']))
except KeyError as e:
if args.debug:
traceback.print_exc()
try:
# Malware Bazar availability
if 'malware_bazar_available' in info:
if info['malware_bazar_available']:
printHighlighted("[!] Sample is available on Malware Bazar URL: {0}".format(
MALWARE_BAZAR_LINK % info['sha256']))
except KeyError as e:
if args.debug:
traceback.print_exc()
try:
# Hybrid Analysis availability
if 'hybrid_available' in info:
if info['hybrid_available']:
printHighlighted("[!] Sample is on hybrid-analysis.com SCORE: {0} URL: {1}/{2}".format(
info["hybrid_score"], URL_HA, info['sha256']))
except KeyError as e:
if args.debug:
traceback.print_exc()
try:
# Intezer availability
if 'intezer_available' in info:
if info['intezer_available']: