-
Notifications
You must be signed in to change notification settings - Fork 45
/
utils.py
2514 lines (2371 loc) · 144 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import base64
import datetime
import dns.resolver
import IndicatorTypes
import json
import os
from OTXv2 import OTXv2
import re
import requests
import socket as sock
import shodan
import sqlite3
import sys
import tempfile
from urllib.parse import urlparse
import validators
import webbrowser
import whois
class Database(object):
"""Local sqlite database handler class"""
def __init__(self):
"""Initialises or updates application database, if app db doesn't exist, it creates one"""
self.api_keys = [("virustotal", "", 0), ("shodan", "", 0), ("otx", "", 0)]
# verify that db folder exists, if not create one
if sys.platform == "win32":
self.db_path = os.getenv("LOCALAPPDATA")+ "\\pockint\\"
else:
self.db_path = os.path.expanduser(os.path.join("~", ".pockint"))
if not os.path.exists(self.db_path):
os.makedirs(self.db_path)
self.create_database()
# connect to database
self.db = sqlite3.connect(self.db_path + "\\.pockint.db")
self.cursor = self.db.cursor()
# upgrades old database versions
self.upgrade_database()
def upgrade_database(self):
"""Upgrades tables of existing pockint databases"""
# create json_data table if not exist (to upgrade old databases)
self.cursor.execute("""SELECT name FROM sqlite_master WHERE type='table' AND name='json_data';""")
if not self.cursor.fetchone():
self.cursor.execute('''CREATE TABLE json_data (id INTEGER PRIMARY KEY,
investigation_id TEXT, json TEXT)''')
self.db.commit()
# updates database with new api keys added to the system
for key in self.api_keys:
self.cursor.execute('''SELECT api_key FROM api_keys WHERE api_name=?''', (key[0],))
if not self.cursor.fetchone():
self.cursor.execute(''' INSERT INTO api_keys(api_name, api_key, status) VALUES(?,?,?)''', key)
self.db.commit()
def create_database(self):
"""Creates a new database in AppData/Local"""
db = sqlite3.connect(self.db_path + "\\.pockint.db")
cursor = db.cursor()
try:
cursor.execute('''CREATE TABLE api_keys(id INTEGER PRIMARY KEY, api_name TEXT,
api_key TEXT, status INTEGER)''')
cursor.executemany(''' INSERT INTO api_keys(api_name, api_key, status) VALUES(?,?,?)''', self.api_keys)
db.commit()
cursor.execute('''CREATE TABLE json_data (id INTEGER PRIMARY KEY,
investigation_id TEXT, json TEXT)''')
db.commit()
db.close()
except sqlite3.Error:
db.rollback()
def insert_api_key(self, api: str, _key: str):
"""Updates the api key value and status for the given api"""
try:
if _key:
self.cursor.execute('''UPDATE api_keys SET api_key=?, status=1 WHERE api_name=?''', (_key, api))
self.db.commit()
if not _key:
self.cursor.execute('''UPDATE api_keys SET api_key=?, status=0 WHERE api_name=?''', (_key, api))
self.db.commit()
except sqlite3.Error:
self.db.rollback()
def get_api_key(self, api: str):
"""Returns the api key for the supplied api name"""
try:
self.cursor.execute('''SELECT api_key FROM api_keys WHERE api_name=?''', (api,))
return self.cursor.fetchone()[0]
except sqlite3.Error:
self.db.rollback()
def get_available_apis(self):
"""Returns api's that have an associated api key"""
try:
self.cursor.execute('''SELECT api_name FROM api_keys WHERE status=1''')
return [api[0] for api in self.cursor.fetchall()]
except sqlite3.Error:
self.db.rollback()
def get_apis(self):
"""Returns all api's available in the database"""
try:
self.cursor.execute('''SELECT api_name FROM api_keys''')
return [api[0] for api in self.cursor.fetchall()]
except sqlite3.Error:
self.db.rollback()
def store_investigation(self, investigation_id, data):
"""Stores investigation data in tab by investigation_id"""
data = json.dumps(data)
try:
self.cursor.execute('''SELECT * FROM json_data WHERE investigation_id=?''', (investigation_id,))
if not self.cursor.fetchone():
# insert fresh data
self.cursor.execute('''INSERT INTO json_data(investigation_id, json) Values (?,?)''',
(investigation_id, data))
else:
# update data
self.cursor.execute('''UPDATE json_data SET json=? WHERE investigation_id=?''',
(data, investigation_id))
self.db.commit()
except sqlite3.Error:
self.db.rollback()
def delete_investigation(self, investigation_id):
"""Delete investigation data"""
try:
self.cursor.execute('''DELETE FROM json_data WHERE investigation_id=?''', (investigation_id,))
self.db.commit()
except sqlite3.Error:
self.db.rollback()
def open_investigation(self, investigation_id):
"""Retrieves investigation data by investigation_id returning"""
try:
self.cursor.execute('''SELECT * FROM json_data WHERE investigation_id=?''', (investigation_id,))
response = self.cursor.fetchone()
investigation_id = response[1]
data = response[2]
except sqlite3.Error:
self.db.rollback()
return [investigation_id, json.loads(data)]
def retrieve_investigation_ids(self):
"""Retrieves investigation ids from database"""
try:
self.cursor.execute('''SELECT investigation_id FROM json_data''')
data = [row[0] for row in self.cursor.fetchall()]
return data
except sqlite3.Error:
self.db.rollback()
def close_connection(self):
"""Closes the connection to the local database file"""
self.db.close()
class Sha256Hash(object):
"""Md5 hash handler class"""
def __init__(self):
self.osint_options = {}
self.api_db = Database()
self.virustotal_api_key = self.api_db.get_api_key("virustotal")
if self.virustotal_api_key:
self.osint_options.update({
"virustotal: malicious check": self.virustotal_is_malicious,
"virustotal: malware type": self.virustotal_malware_type})
self.otx_api_key = self.api_db.get_api_key("otx")
if self.otx_api_key:
self.osint_options.update({
"otx: malicious check": self.hash_to_otx_is_malicious
})
def is_sha256(self, _input: str):
"""Validates if _input is an md5 hash"""
if validators.hashes.sha256(_input):
return True
return False
def virustotal_is_malicious(self, _hash:str):
"""Checks virustotal to see if sha256 has positive detections"""
try:
data = make_vt_api_request(
"https://www.virustotal.com/vtapi/v2/file/report",
self.virustotal_api_key,
{"resource": _hash}
)
if data:
if data.json().get("response_code") == 0:
return ["no report available"]
return ["hash malicious: {} detections".format(data.json().get("positives"))]
else:
return ["no data available"]
except Exception as e:
return e
def virustotal_malware_type(self, _hash:str):
"""Checks virustotal to return malware types detected by scans"""
try:
data = make_vt_api_request(
"https://www.virustotal.com/vtapi/v2/file/report",
self.virustotal_api_key,
{"resource": _hash}
)
if data:
if data.json().get("response_code") == 1:
return ["{}: {}".format(i, data.json().get("scans").get(i).get("result"))
for i in data.json().get("scans")
if data.json().get("scans").get(i).get("result")]
return ["no report available"]
else:
return ["no data available"]
except Exception as e:
return e
def hash_to_otx_is_malicious(self, _hash:str):
"""Queries otx to establish if hash is malicious"""
try:
otx = connect_to_otx_api(self.otx_api_key)
alerts = file(otx, _hash)
if len(alerts) > 0:
return ['Identified as potentially malicious']
else:
return ['Unknown or not identified as malicious']
except Exception as e:
return e
class Md5Hash(object):
"""Md5 hash handler class"""
def __init__(self):
self.osint_options = {}
self.api_db = Database()
self.virustotal_api_key = self.api_db.get_api_key("virustotal")
if self.virustotal_api_key:
self.osint_options.update({
"virustotal: malicious check": self.virustotal_is_malicious,
"virustotal: malware type": self.virustotal_malware_type})
self.otx_api_key = self.api_db.get_api_key("otx")
if self.otx_api_key:
self.osint_options.update({
"otx: malicious check": self.hash_to_otx_is_malicious
})
def is_md5(self, _input: str):
"""Validates if _input is an md5 hash"""
if validators.hashes.md5(_input):
return True
return False
def virustotal_is_malicious(self, _hash:str):
"""Checks virustotal to see if MD5 has positive detections"""
try:
data = make_vt_api_request(
"https://www.virustotal.com/vtapi/v2/file/report",
self.virustotal_api_key,
{"resource": _hash}
)
if data:
if data.json().get("response_code") == 0:
return ["no report available"]
return ["hash malicious: {} detections".format(data.json().get("positives"))]
else:
return ["no data available"]
except Exception as e:
return e
def virustotal_malware_type(self, _hash:str):
"""Checks virustotal to return malware types detected by scans"""
try:
data = make_vt_api_request(
"https://www.virustotal.com/vtapi/v2/file/report",
self.virustotal_api_key,
{"resource": _hash}
)
if data:
if data.json().get("response_code") == 1:
return ["{}: {}".format(i, data.json().get("scans").get(i).get("result"))
for i in data.json().get("scans")
if data.json().get("scans").get(i).get("result")]
return ["no report available"]
else:
return ["no data available"]
except Exception as e:
return e
def hash_to_otx_is_malicious(self, _hash:str):
"""Queries otx to establish if hash is malicious"""
try:
otx = connect_to_otx_api(self.otx_api_key)
alerts = file(otx, _hash)
if len(alerts) > 0:
return ['Identified as potentially malicious']
else:
return ['Unknown or not identified as malicious']
except Exception as e:
return e
class Url(object):
"""Url handler class"""
def __init__(self):
self.osint_options = {
"dns: extract hostname": self.url_to_hostname
}
self.api_db = Database()
self.virustotal_api_key = self.api_db.get_api_key("virustotal")
if self.virustotal_api_key:
self.osint_options.update({
"virustotal: malicious check": self.is_malicious,
"virustotal: reported detections": self.reported_detections})
self.otx_api_key = self.api_db.get_api_key("otx")
if self.otx_api_key:
self.osint_options.update({
"otx: geolocate" : self.url_to_otx_geolocation_data,
"otx: http response analysis" : self.url_to_otx_http_response_analysis,
"otx: parse url": self.url_to_otx_hostname_parsing,
"otx: malicious check": self.url_to_otx_is_malicious
})
def is_url(self, _input: str):
"""Validates if _input is a url"""
if validators.url(_input):
return True
return False
def is_malicious(self, url: str):
"""Checks if url is malicious"""
try:
data = make_vt_api_request(
"https://www.virustotal.com/vtapi/v2/url/report",
self.virustotal_api_key,
{"resource": url}
)
if data:
if data.json().get("response_code") == 1:
return ["url malicious: {} detections".format(data.json().get("positives"))]
return ["no report available"]
else:
return ["no data available"]
except Exception as e:
return e
def reported_detections(self, url: str):
"""Checks virustotal to determine which sites are reporting the url"""
try:
data = make_vt_api_request(
"https://www.virustotal.com/vtapi/v2/url/report",
self.virustotal_api_key,
{"resource": url}
)
if data:
if data.json().get("response_code") == 1:
return ["{}: {}".format(i, data.json().get("scans").get(i).get("result"))
for i in data.json().get("scans")
if (data.json().get("scans").get(i).get("result") == "malicious site") or
(data.json().get("scans").get(i).get("result") == "malware site")]
return ["no report available"]
else:
return ["no data available"]
except Exception as e:
return e
def url_to_hostname(self, url: str):
"""Extracts hostname from url"""
try:
return [urlparse(url).netloc]
except Exception as e:
return e
def url_to_otx_http_response_analysis(self, url:str):
"""Returns otx alienvault analysis of url http response data"""
try:
otx = connect_to_otx_api(self.otx_api_key)
results = otx.get_indicator_details_by_section(IndicatorTypes.URL, url, 'url_list')
data = [result.get("result", None).get("urlworker", None).get("http_response", None) for result in results.get("url_list", None)]
out = set()
for row in data:
for key in row:
out.add("{}: {}".format(key.lower(), row[key]))
return out
except Exception as e:
return e
def url_to_otx_geolocation_data(self, url:str):
"""Returns otx alienvault geolocation analysis for given url"""
try:
otx = connect_to_otx_api(self.otx_api_key)
results = otx.get_indicator_details_by_section(IndicatorTypes.URL, url, 'url_list')
return ["continent: {}".format(results.get("continent_code", "no data")),
"country: {}".format(results.get("country_code", "no data")),
"city: {}".format(results.get("city", "no data")),
"country: {}".format(results.get("country_code", "no data")),
"postal code: {}".format(results.get("postal_code", "no data")),
"coordinates: {},{}".format(results.get("latitude", "no data"),
results.get("longitude", "no data"))]
except Exception as e:
return e
def url_to_otx_hostname_parsing(self, url:str):
"""Returns otx alienvault url hostname parsing for given url"""
try:
otx = connect_to_otx_api(self.otx_api_key)
results = otx.get_indicator_details_by_section(IndicatorTypes.URL, url, 'url_list')
return [results.get("domain", "no domain data"), results.get("hostname", "no hostname data")]
except Exception as e:
return e
def url_to_otx_is_malicious(self, url:str):
"""Checks if otx alienvault reports url as malicious"""
otx = connect_to_otx_api(self.otx_api_key)
alerts = self.extract_url_alert_data(otx, url)
if len(alerts) > 0:
return ['Identified as potentially malicious']
else:
return ['Unknown or not identified as malicious']
def extract_url_alert_data(self, otx, url:str):
"""Helper function to extracts full data for url indicators, borrowed from
https://github.com/AlienVault-OTX/OTX-Python-SDK/tree/master/examples/is_malicious"""
try:
alerts = []
result = otx.get_indicator_details_full(IndicatorTypes.URL, url)
google = getValue( result, ['url_list', 'url_list', 'result', 'safebrowsing'])
if google and 'response_code' in str(google):
alerts.append({'google_safebrowsing': 'malicious'})
clamav = getValue( result, ['url_list', 'url_list', 'result', 'multiav','matches','clamav'])
if clamav:
alerts.append({'clamav': clamav})
avast = getValue( result, ['url_list', 'url_list', 'result', 'multiav','matches','avast'])
if avast:
alerts.append({'avast': avast})
# Get the file analysis too, if it exists
has_analysis = getValue( result, ['url_list','url_list', 'result', 'urlworker', 'has_file_analysis'])
if has_analysis:
hash = getValue( result, ['url_list','url_list', 'result', 'urlworker', 'sha256'])
file_alerts = file(otx, hash)
if file_alerts:
for alert in file_alerts:
alerts.append(alert)
# Todo: Check file page
return alerts
except Exception as e:
return e
class IPAdress(object):
"""Ipv4 address handler class"""
def __init__(self):
self.osint_options = {
"dns: reverse lookup": self.reverse_lookup,
# "dns: ip to asn": self.ip_to_asn,
}
self.api_db = Database()
shodan_api_key = self.api_db.get_api_key("shodan")
if shodan_api_key:
self.shodan_api = shodan.Shodan(shodan_api_key)
self.osint_options.update({
"shodan: ports": self.ip_to_shodan_ports,
"shodan: geolocate": self.ip_to_shodan_country_name,
"shodan: coordinates": self.ip_to_shodan_coordinates,
"shodan: cve's": self.ip_to_shodan_cves,
"shodan: isp": self.ip_to_shodan_isp,
"shodan: city": self.ip_to_shodan_city,
"shodan: asn": self.ip_to_shodan_asn})
self.virustotal_api_key = self.api_db.get_api_key("virustotal")
if self.virustotal_api_key:
self.osint_options.update({
"virustotal: network report": self.ip_to_vt_network_report,
"virustotal: communicating samples": self.ip_to_vt_communicating_samples,
"virustotal: downloaded samples": self.ip_to_vt_downloaded_samples,
"virustotal: detected urls": self.ip_to_vt_detected_urls
})
self.otx_api_key = self.api_db.get_api_key("otx")
if self.otx_api_key:
self.osint_options.update({
"otx: geolocate": self.ip_to_otx_geolocation_data,
"otx: passive dns": self.ip_to_otx_passive_dns,
"otx: malware type": self.ip_to_otx_malware_types,
"otx: malware hash": self.ip_to_otx_malware_hash,
"otx: observed urls": self.ip_to_otx_observed_urls,
"otx malicious check": self.ip_to_otx_is_malicious
})
def is_ip_address(self, _input: str):
"""Validates if _input is ip address"""
try:
sock.inet_aton(_input)
return True
except sock.error:
return False
def reverse_lookup(self, ip: str):
"""Returns PTR record for ip"""
try:
return [sock.gethostbyaddr(ip)[0]]
except Exception as e:
if "host not found" in str(e):
return ["host not found, PTR record likely missing"]
else:
return e
def ip_to_asn(self):
pass
def ip_to_shodan_ports(self, ip:str):
"""Searches shodan to see if any ports are open on the target ip"""
try:
data = self.shodan_api.host(ip)["ports"]
if data:
return data
else:
return ["no data available"]
except Exception as e:
return e
def ip_to_shodan_country_name(self, ip:str):
"""Searches shodan to determine the target ip's location"""
try:
data = self.shodan_api.host(ip)["country_name"]
if data:
return [data]
else:
return ["no data available"]
except Exception as e:
return e
def ip_to_shodan_coordinates(self, ip:str):
"""Searches shodan to determine the target ip's location co-ordinates"""
try:
latitude, longitude = self.shodan_api.host(ip)["latitude"], self.shodan_api.host(ip)["longitude"]
if latitude and longitude:
return [str(latitude) + "," + str(longitude)]
else:
return ["no data available"]
except Exception as e:
return e
def ip_to_shodan_cves(self, ip:str):
"""Searches shodan to determine if the ip is vulnerable to CVE's"""
try:
vulns = self.shodan_api.host(ip)["vulns"]
if vulns:
return vulns
else:
return ["no data available"]
except Exception as e:
return e
def ip_to_shodan_isp(self, ip:str):
"""Searches shodan to determine the ip's ISP"""
try:
isp = self.shodan_api.host(ip)["isp"]
if isp:
return [isp]
else:
return ["no data available"]
except Exception as e:
return e
def ip_to_shodan_city(self, ip:str):
"""Searches shodan to determine the ip's ISP"""
try:
city = self.shodan_api.host(ip)["city"]
if city:
return [city]
else:
return ["no data available"]
except Exception as e:
return e
def ip_to_shodan_asn(self, ip:str):
"""Searches shodan to determine the ip's ASN"""
try:
asn = self.shodan_api.host(ip)["asn"]
if asn:
return [asn]
else:
return ["no data available"]
except Exception as e:
return e
def ip_to_vt_network_report(self, ip:str):
"""Searches virustotal to return an ip network report"""
try:
data = make_vt_api_request(
"https://www.virustotal.com/vtapi/v2/ip-address/report",
self.virustotal_api_key,
{"ip":ip}
)
if data:
return ["asn owner: {}".format(data.json().get("as_owner")),
"asn: {}".format(data.json().get("asn")),
"continent: {}".format(data.json().get("continent")),
"country: {}".format(data.json().get("country")),
"network: {}".format(data.json().get("network")),
"whois: {}".format(data.json().get("whois"))
]
else:
return ["no data available"]
except Exception as e:
return e
def ip_to_vt_communicating_samples(self, ip:str):
"""Searches virustotal to search for detected communicating samples"""
try:
data = make_vt_api_request(
"https://www.virustotal.com/vtapi/v2/ip-address/report",
self.virustotal_api_key,
{"ip":ip})
if data:
return [record.get("sha256") for record in data.json()["detected_communicating_samples"]]
else:
return ["no data available"]
except Exception as e:
return e
def ip_to_vt_downloaded_samples(self, ip:str):
"""Searches virustotal to search for detected communicating samples"""
try:
data = make_vt_api_request(
"https://www.virustotal.com/vtapi/v2/ip-address/report",
self.virustotal_api_key,
{"ip":ip})
if data:
return [record.get("sha256") for record in data.json()["detected_downloaded_samples"]]
else:
return ["no data available"]
except Exception as e:
return e
def ip_to_vt_detected_urls(self, ip:str):
"""Searches virustotal to search for detected communicating samples"""
try:
data = make_vt_api_request(
"https://www.virustotal.com/vtapi/v2/ip-address/report",
self.virustotal_api_key,
{"ip":ip})
if data:
return [record.get("url") for record in data.json()["detected_urls"]]
else:
return ["no data available"]
except Exception as e:
return e
def ip_to_otx_malware_types(self, ip:str):
"""Searches OTX DirectConnect for malware type data for the given ip"""
try:
otx = connect_to_otx_api(self.otx_api_key)
results = otx.get_indicator_details_by_section(IndicatorTypes.IPv4, ip, 'malware')
if results.get("data", None):
malware_types = set()
for result in results.get("data"):
detections = result.get("detections")
for detection in detections:
if detections[detection]:
date = datetime.datetime.fromtimestamp(result.get("datetime_int")).strftime('%Y-%m-%d')
malware_types.add("[{} on {}] {}".format(detection, date, detections[detection]))
return malware_types
else:
return ["ip clean"]
except Exception as e:
return e
def ip_to_otx_malware_hash(self, ip:str):
"""Searches OTX DirectConnect for malware hash data for the given ip"""
try:
otx = connect_to_otx_api(self.otx_api_key)
results = otx.get_indicator_details_by_section(IndicatorTypes.IPv4, ip, 'malware')
data = results.get("data", None)
if data:
return list({detection.get("hash") for detection in data})
else:
return ["ip clean"]
except Exception as e:
return e
def ip_to_otx_passive_dns(self, ip:str):
"""Searches OTX DirectConnect for passive dns data for the given ip"""
try:
otx = connect_to_otx_api(self.otx_api_key)
results = otx.get_indicator_details_by_section(IndicatorTypes.IPv4, ip, 'passive_dns')
hostnames = {result["hostname"]for result in results["passive_dns"]}
if hostnames:
return list(hostnames)
else:
return ["no pdns data"]
except Exception as e:
return e
def ip_to_otx_observed_urls(self, ip:str):
"""Searches OTX DirectConnect for url data associated to the given ip"""
try:
otx = connect_to_otx_api(self.otx_api_key)
results = otx.get_indicator_details_by_section(IndicatorTypes.IPv4, ip, 'url_list')
urls = {result["url"]for result in results["url_list"]}
if urls:
return list(urls)
else:
return ["no url data"]
except Exception as e:
return e
def ip_to_otx_geolocation_data(self, ip:str):
"""Searches OTX DirectConnect for geolocation data associated to the given ip"""
try:
otx = connect_to_otx_api(self.otx_api_key)
results = otx.get_indicator_details_by_section(IndicatorTypes.IPv4, ip, 'geo')
return [ "asn: {}".format(results.get("asn", "no data")),
"city: {}".format(results.get("city", "no data")),
"country: {}".format(results.get("country_code", "no data")),
"coordinates: {},{}".format(results.get("latitude", "no data"),
results.get("longitude", "no data"))
]
except Exception as e:
return e
def extract_ip_alert_data(self, otx, ip:str):
"""Helper function to extracts full data for ip indicators, borrowed from
https://github.com/AlienVault-OTX/OTX-Python-SDK/tree/master/examples/is_malicious"""
try:
alerts = []
result = otx.get_indicator_details_by_section(IndicatorTypes.IPv4, ip, 'general')
# Return nothing if it's in the whitelist
validation = getValue(result, ['validation'])
if not validation:
pulses = getValue(result, ['pulse_info', 'pulses'])
if pulses:
for pulse in pulses:
if 'name' in pulse:
alerts.append('In pulse: ' + pulse['name'])
return alerts
except Exception as e:
return e
def ip_to_otx_is_malicious(self, ip:str):
"""Queries otx to establish if ip is malicious"""
try:
otx = connect_to_otx_api(self.otx_api_key)
alerts = self.extract_ip_alert_data(otx, ip)
if len(alerts) > 0:
return ['Identified as potentially malicious']
else:
return ['Unknown or not identified as malicious']
except Exception as e:
return e
class EmailAddress(object):
"""Email address handler class"""
def __init__(self):
self.osint_options = {
"extract domain": self.domain_extract
}
def is_valid_email(self, _input: str):
"""Checks if _input is a valid email"""
if re.match(r'^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', _input):
return True
return False
def hibp_lookup(self):
pass
def domain_extract(self, email: str):
"""Returns domain from supplied email"""
return [email.split("@")[1]]
class Domain(object):
"""Domain handler class"""
def __init__(self):
self.osint_options = {
"dns: ip lookup" : self.to_a_record,
"dns: mx lookup" : self.to_mx_records,
"dns: ns lookup" : self.to_ns_records,
"dns: txt lookup": self.to_txt_records,
"whois: emails": self.domain_to_whois_emails,
"whois: location": self.domain_to_whois_location,
"whois: creation": self.domain_to_whois_creation_date,
"whois: registrar": self.domain_to_whois_registrar,
"whois: expiration": self.domain_to_whois_expiration_date,
"whois: dnssec status": self.domain_to_whois_dnssec_status,
"whois: registrant org": self.domain_to_whois_registrant_org,
"whois: registrant name": self.domain_to_whois_registrant_name,
"whois: registrant address": self.domain_to_whois_registrant_address,
"whois: registrant zipcode": self.domain_to_whois_registrant_zipcode,
"crt.sh: subdomains" : self.domain_to_subdomains
}
self.api_db = Database()
shodan_api_key = self.api_db.get_api_key("shodan")
if shodan_api_key:
self.shodan_api = shodan.Shodan(shodan_api_key)
self.osint_options.update({"shodan: hostnames": self.to_shodan_hostnames})
self.virustotal_api_key = self.api_db.get_api_key("virustotal")
if self.virustotal_api_key:
self.osint_options.update({
"virustotal: downloaded samples": self.domain_to_vt_downloaded_samples,
"virustotal: detected urls": self.domain_to_vt_detected_urls,
"virustotal: subdomains": self.domain_to_vt_subdomains
})
self.otx_api_key = self.api_db.get_api_key("otx")
if self.otx_api_key:
self.osint_options.update({
"otx: geolocate": self.domain_to_otx_geolocation_data,
"otx: passive dns": self.domain_to_otx_passive_dns,
"otx: malware type": self.domain_to_otx_malware_types,
"otx: malware hash": self.domain_to_otx_malware_hash,
"otx: observed urls": self.domain_to_otx_observed_urls,
"otx: malicious check": self.domain_to_otx_is_malicious
})
def is_valid_domain(self, _input: str):
"""Checks if _input is a domain"""
if re.match(r'^((?!-))(xn--)?[a-z0-9][a-z0-9-_]{0,61}[a-z0-9]{0,1}\.(xn--)?([a-z0-9\-]{1,61}|[a-z0-9-]{1,30}\.[a-z]{2,})$', _input):
return True
return False
def to_a_record(self, domain: str):
"""Returns dns a record for domain"""
try:
return [sock.gethostbyname(domain)]
except Exception as e:
return e
def to_mx_records(self, domain: str):
"""Returns dns mx record for domain"""
try:
return [x.exchange for x in dns.resolver.query(domain, 'MX')]
except Exception as e:
return e
def to_txt_records(self, domain: str):
"""Returns dns txt record for domain"""
try:
return [x.to_text() for x in dns.resolver.query(domain, 'TXT')]
except Exception as e:
return e
def to_ns_records(self, domain: str):
"""Returns ns record for domain"""
try:
return [x.to_text() for x in dns.resolver.query(domain, 'NS')]
except Exception as e:
return e
def to_shodan_hostnames(self, domain: str):
"""Searches shodan to discover hostnames associated with the domain"""
try:
data = []
results = self.shodan_api.search("hostname:{}".format(domain))
if results:
for r in results["matches"]:
for h in r["hostnames"]:
data.append(h)
return data
else:
return ["no data available"]
except Exception as e:
return e
def domain_to_vt_detected_urls(self, domain:str):
"""Searches virustotal to search for detected communicating samples"""
try:
data = make_vt_api_request(
"https://www.virustotal.com/vtapi/v2/domain/report",
self.virustotal_api_key,
{"domain":domain})
if data:
return [record.get("url") for record in data.json()["detected_urls"]]
else:
return ["no data available"]
except Exception as e:
return e
def domain_to_vt_downloaded_samples(self, domain:str):
"""Searches virustotal to search for detected communicating samples"""
try:
data = make_vt_api_request(
"https://www.virustotal.com/vtapi/v2/domain/report",
self.virustotal_api_key,
{"domain":domain})
if data:
return [record.get("sha256") for record in data.json()["detected_downloaded_samples"]]
else:
return ["no data available"]
except Exception as e:
return e
def domain_to_vt_subdomains(self, domain: str):
"""Searches virustotal for subdomains"""
try:
data = make_vt_api_request(
"https://www.virustotal.com/vtapi/v2/domain/report",
self.virustotal_api_key,
{"domain":domain})
if data:
return data.json().get("subdomains")
else:
return ["no data available"]
except Exception as e:
return e
def domain_to_subdomains(self, domain: str):
"""Discovers subdomains from domain using certificate transparency logs on crt.sh"""
try:
req = requests.get("https://crt.sh/?q=%.{d}&output=json".format(d=domain))
if req.status_code == 200:
return list({value['name_value'] for (key,value) in enumerate(req.json())})
else:
return ["no data returned from crt.sh"]
except Exception as e:
return e
def domain_to_whois_expiration_date(self, domain: str):
"""Queries whois record to find domain expiration date"""
try:
date = str(whois.whois(domain).expiration_date)
if date:
return [date]
else:
return ["no expiration date returned from whois"]
except Exception as e:
return e
def domain_to_whois_creation_date(self, domain: str):
"""Queries whois record to find domain creation date"""
try:
date = str(whois.whois(domain).creation_date)
if date:
return [date]
else:
return ["no creation date returned from whois"]
except Exception as e:
return e
def domain_to_whois_emails(self, domain: str):
"""Queries whois record to find email data"""
try:
data = str(whois.whois(domain).emails)
if data:
return [data]
else:
return ["no email data returned from whois"]
except Exception as e:
return e
def domain_to_whois_registrar(self, domain: str):
"""Queries whois record to find domain registrar data"""
try:
data = str(whois.whois(domain).registrar)
if data:
return [data]
else:
return ["no registrar data returned from whois"]
except Exception as e:
return e
def domain_to_whois_location(self, domain: str):
"""Queries whois record to find domain location data"""
try:
data = []
data.append(str(whois.whois(domain).state))
data.append(str(whois.whois(domain).country))
if data[0] == "None" and data[1] == "None":
return ["None"]
else:
return [" ".join(data)]
except Exception as e:
return e
def domain_to_whois_registrant_org(self, domain: str):
"""Queries whois record to find domain registrant org"""
try:
data = str(whois.whois(domain).org)
if data:
return [data]
else:
return ["no registrant org data returned from whois"]
except Exception as e: