-
Notifications
You must be signed in to change notification settings - Fork 0
/
sflib.py
1664 lines (1312 loc) · 51.9 KB
/
sflib.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
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# Name: sflib
# Purpose: Common functions used by SpiderFoot modules.
#
# Author: Steve Micallef <steve@binarypool.com>
#
# Created: 26/03/2012
# Copyright: (c) Steve Micallef 2012
# Licence: MIT
# -------------------------------------------------------------------------------
import hashlib
import inspect
import io
import json
import logging
import os
import random
import re
import socket
import ssl
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from copy import deepcopy
from datetime import datetime
import cryptography
import dns.resolver
import netaddr
import OpenSSL
import requests
import urllib3
from publicsuffixlist import PublicSuffixList
from spiderfoot import SpiderFootHelpers
# For hiding the SSL warnings coming from the requests lib
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # noqa: DUO131
class SpiderFoot:
"""SpiderFoot
Attributes:
dbh (SpiderFootDb): database handle
scanId (str): scan ID this instance of SpiderFoot is being used in
socksProxy (str): SOCKS proxy
opts (dict): configuration options
"""
_dbh = None
_scanId = None
_socksProxy = None
opts = dict()
def __init__(self, options: dict) -> None:
"""Initialize SpiderFoot object.
Args:
options (dict): dictionary of configuration options.
Raises:
TypeError: options argument was invalid type
"""
if not isinstance(options, dict):
raise TypeError(f"options is {type(options)}; expected dict()")
self.opts = deepcopy(options)
self.log = logging.getLogger(f"spiderfoot.{__name__}")
# This is ugly but we don't want any fetches to fail - we expect
# to encounter unverified SSL certs!
ssl._create_default_https_context = ssl._create_unverified_context # noqa: DUO122
if self.opts.get('_dnsserver', "") != "":
res = dns.resolver.Resolver()
res.nameservers = [self.opts['_dnsserver']]
dns.resolver.override_system_resolver(res)
@property
def dbh(self):
"""Database handle
Returns:
SpiderFootDb: database handle
"""
return self._dbh
@property
def scanId(self) -> str:
"""Scan instance ID
Returns:
str: scan instance ID
"""
return self._scanId
@property
def socksProxy(self) -> str:
"""SOCKS proxy
Returns:
str: socks proxy
"""
return self._socksProxy
@dbh.setter
def dbh(self, dbh):
"""Called usually some time after instantiation
to set up a database handle and scan ID, used
for logging events to the database about a scan.
Args:
dbh (SpiderFootDb): database handle
"""
self._dbh = dbh
@scanId.setter
def scanId(self, scanId: str) -> str:
"""Set the scan ID this instance of SpiderFoot is being used in.
Args:
scanId (str): scan instance ID
"""
self._scanId = scanId
@socksProxy.setter
def socksProxy(self, socksProxy: str) -> str:
"""SOCKS proxy
Bit of a hack to support SOCKS because of the loading order of
modules. sfscan will call this to update the socket reference
to the SOCKS one.
Args:
socksProxy (str): SOCKS proxy
"""
self._socksProxy = socksProxy
def optValueToData(self, val: str) -> str:
"""Supplied an option value, return the data based on what the
value is. If val is a URL, you'll get back the fetched content,
if val is a file path it will be loaded and get back the contents,
and if a string it will simply be returned back.
Args:
val (str): option name
Returns:
str: option data
"""
if not isinstance(val, str):
self.error(f"Invalid option value {val}")
return None
if val.startswith('@'):
fname = val.split('@')[1]
self.info(f"Loading configuration data from: {fname}")
try:
with open(fname, "r") as f:
return f.read()
except Exception as e:
self.error(f"Unable to open option file, {fname}: {e}")
return None
if val.lower().startswith('http://') or val.lower().startswith('https://'):
try:
self.info(f"Downloading configuration data from: {val}")
session = self.getSession()
res = session.get(val)
return res.content.decode('utf-8')
except BaseException as e:
self.error(f"Unable to open option URL, {val}: {e}")
return None
return val
def error(self, message: str) -> None:
"""Print and log an error message
Args:
message (str): error message
"""
if not self.opts['__logging']:
return
self.log.error(message, extra={'scanId': self._scanId})
def fatal(self, error: str) -> None:
"""Print an error message and stacktrace then exit.
Args:
error (str): error message
"""
self.log.critical(error, extra={'scanId': self._scanId})
print(str(inspect.stack()))
sys.exit(-1)
def status(self, message: str) -> None:
"""Log and print a status message.
Args:
message (str): status message
"""
if not self.opts['__logging']:
return
self.log.info(message, extra={'scanId': self._scanId})
def info(self, message: str) -> None:
"""Log and print an info message.
Args:
message (str): info message
"""
if not self.opts['__logging']:
return
self.log.info(f"{message}", extra={'scanId': self._scanId})
def debug(self, message: str) -> None:
"""Log and print a debug message.
Args:
message (str): debug message
"""
if not self.opts['_debug']:
return
if not self.opts['__logging']:
return
self.log.debug(f"{message}", extra={'scanId': self._scanId})
def hashstring(self, string: str) -> str:
"""Returns a SHA256 hash of the specified input.
Args:
string (str): data to be hashed
Returns:
str: SHA256 hash
"""
s = string
if type(string) in [list, dict]:
s = str(string)
return hashlib.sha256(s.encode('raw_unicode_escape')).hexdigest()
def cachePut(self, label: str, data: str) -> None:
"""Store data to the cache.
Args:
label (str): Name of the cached data to be used when retrieving the cached data.
data (str): Data to cache
"""
pathLabel = hashlib.sha224(label.encode('utf-8')).hexdigest()
cacheFile = SpiderFootHelpers.cachePath() + "/" + pathLabel
with io.open(cacheFile, "w", encoding="utf-8", errors="ignore") as fp:
if isinstance(data, list):
for line in data:
if isinstance(line, str):
fp.write(line)
fp.write("\n")
else:
fp.write(line.decode('utf-8') + '\n')
elif isinstance(data, bytes):
fp.write(data.decode('utf-8'))
else:
fp.write(data)
def cacheGet(self, label: str, timeoutHrs: int) -> str:
"""Retreive data from the cache.
Args:
label (str): Name of the cached data to retrieve
timeoutHrs (int): Age of the cached data (in hours)
for which the data is considered to be too old and ignored.
Returns:
str: cached data
"""
if not label:
return None
pathLabel = hashlib.sha224(label.encode('utf-8')).hexdigest()
cacheFile = SpiderFootHelpers.cachePath() + "/" + pathLabel
try:
cache_stat = os.stat(cacheFile)
except OSError:
return None
if cache_stat.st_size == 0:
return None
if cache_stat.st_mtime > time.time() - timeoutHrs * 3600 or timeoutHrs == 0:
with open(cacheFile, "r", encoding='utf-8') as fp:
return fp.read()
return None
def configSerialize(self, opts: dict, filterSystem: bool = True):
"""Convert a Python dictionary to something storable in the database.
Args:
opts (dict): Dictionary of SpiderFoot configuration options
filterSystem (bool): TBD
Returns:
dict: config options
Raises:
TypeError: arg type was invalid
"""
if not isinstance(opts, dict):
raise TypeError(f"opts is {type(opts)}; expected dict()")
storeopts = dict()
if not opts:
return storeopts
for opt in list(opts.keys()):
# Filter out system temporary variables like GUID and others
if opt.startswith('__') and filterSystem:
continue
if isinstance(opts[opt], (int, str)):
storeopts[opt] = opts[opt]
if isinstance(opts[opt], bool):
if opts[opt]:
storeopts[opt] = 1
else:
storeopts[opt] = 0
if isinstance(opts[opt], list):
storeopts[opt] = ','.join(opts[opt])
if '__modules__' not in opts:
return storeopts
if not isinstance(opts['__modules__'], dict):
raise TypeError(f"opts['__modules__'] is {type(opts['__modules__'])}; expected dict()")
for mod in opts['__modules__']:
for opt in opts['__modules__'][mod]['opts']:
if opt.startswith('_') and filterSystem:
continue
mod_opt = f"{mod}:{opt}"
mod_opt_val = opts['__modules__'][mod]['opts'][opt]
if isinstance(mod_opt_val, (int, str)):
storeopts[mod_opt] = mod_opt_val
if isinstance(mod_opt_val, bool):
if mod_opt_val:
storeopts[mod_opt] = 1
else:
storeopts[mod_opt] = 0
if isinstance(mod_opt_val, list):
storeopts[mod_opt] = ','.join(str(x) for x in mod_opt_val)
return storeopts
def configUnserialize(self, opts: dict, referencePoint: dict, filterSystem: bool = True):
"""Take strings, etc. from the database or UI and convert them
to a dictionary for Python to process.
Args:
opts (dict): SpiderFoot configuration options
referencePoint (dict): needed to know the actual types the options are supposed to be.
filterSystem (bool): Ignore global "system" configuration options
Returns:
dict: TBD
Raises:
TypeError: arg type was invalid
"""
if not isinstance(opts, dict):
raise TypeError(f"opts is {type(opts)}; expected dict()")
if not isinstance(referencePoint, dict):
raise TypeError(f"referencePoint is {type(referencePoint)}; expected dict()")
returnOpts = referencePoint
# Global options
for opt in list(referencePoint.keys()):
if opt.startswith('__') and filterSystem:
# Leave out system variables
continue
if opt not in opts:
continue
if isinstance(referencePoint[opt], bool):
if opts[opt] == "1":
returnOpts[opt] = True
else:
returnOpts[opt] = False
continue
if isinstance(referencePoint[opt], str):
returnOpts[opt] = str(opts[opt])
continue
if isinstance(referencePoint[opt], int):
returnOpts[opt] = int(opts[opt])
continue
if isinstance(referencePoint[opt], list):
if isinstance(referencePoint[opt][0], int):
returnOpts[opt] = list()
for x in str(opts[opt]).split(","):
returnOpts[opt].append(int(x))
else:
returnOpts[opt] = str(opts[opt]).split(",")
if '__modules__' not in referencePoint:
return returnOpts
if not isinstance(referencePoint['__modules__'], dict):
raise TypeError(f"referencePoint['__modules__'] is {type(referencePoint['__modules__'])}; expected dict()")
# Module options
# A lot of mess to handle typing..
for modName in referencePoint['__modules__']:
for opt in referencePoint['__modules__'][modName]['opts']:
if opt.startswith('_') and filterSystem:
continue
if modName + ":" + opt in opts:
ref_mod = referencePoint['__modules__'][modName]['opts'][opt]
if isinstance(ref_mod, bool):
if opts[modName + ":" + opt] == "1":
returnOpts['__modules__'][modName]['opts'][opt] = True
else:
returnOpts['__modules__'][modName]['opts'][opt] = False
continue
if isinstance(ref_mod, str):
returnOpts['__modules__'][modName]['opts'][opt] = str(opts[modName + ":" + opt])
continue
if isinstance(ref_mod, int):
returnOpts['__modules__'][modName]['opts'][opt] = int(opts[modName + ":" + opt])
continue
if isinstance(ref_mod, list):
if isinstance(ref_mod[0], int):
returnOpts['__modules__'][modName]['opts'][opt] = list()
for x in str(opts[modName + ":" + opt]).split(","):
returnOpts['__modules__'][modName]['opts'][opt].append(int(x))
else:
returnOpts['__modules__'][modName]['opts'][opt] = str(opts[modName + ":" + opt]).split(",")
return returnOpts
def modulesProducing(self, events: list) -> list:
"""Return an array of modules that produce the list of types supplied.
Args:
events (list): list of event types
Returns:
list: list of modules
"""
modlist = list()
if not events:
return modlist
loaded_modules = self.opts.get('__modules__')
if not loaded_modules:
return modlist
for mod in list(loaded_modules.keys()):
provides = loaded_modules[mod].get('provides')
if not provides:
continue
if "*" in events:
modlist.append(mod)
for evtype in provides:
if evtype in events:
modlist.append(mod)
return list(set(modlist))
def modulesConsuming(self, events: list) -> list:
"""Return an array of modules that consume the list of types supplied.
Args:
events (list): list of event types
Returns:
list: list of modules
"""
modlist = list()
if not events:
return modlist
loaded_modules = self.opts.get('__modules__')
if not loaded_modules:
return modlist
for mod in list(loaded_modules.keys()):
consumes = loaded_modules[mod].get('consumes')
if not consumes:
continue
if "*" in consumes:
modlist.append(mod)
continue
for evtype in consumes:
if evtype in events:
modlist.append(mod)
return list(set(modlist))
def eventsFromModules(self, modules: list) -> list:
"""Return an array of types that are produced by the list of modules supplied.
Args:
modules (list): list of modules
Returns:
list: list of types
"""
evtlist = list()
if not modules:
return evtlist
loaded_modules = self.opts.get('__modules__')
if not loaded_modules:
return evtlist
for mod in modules:
if mod in list(loaded_modules.keys()):
provides = loaded_modules[mod].get('provides')
if provides:
for evt in provides:
evtlist.append(evt)
return evtlist
def eventsToModules(self, modules: list) -> list:
"""Return an array of types that are consumed by the list of modules supplied.
Args:
modules (list): list of modules
Returns:
list: list of types
"""
evtlist = list()
if not modules:
return evtlist
loaded_modules = self.opts.get('__modules__')
if not loaded_modules:
return evtlist
for mod in modules:
if mod in list(loaded_modules.keys()):
consumes = loaded_modules[mod].get('consumes')
if consumes:
for evt in consumes:
evtlist.append(evt)
return evtlist
def urlFQDN(self, url: str) -> str:
"""Extract the FQDN from a URL.
Args:
url (str): URL
Returns:
str: FQDN
"""
if not url:
self.error(f"Invalid URL: {url}")
return None
baseurl = SpiderFootHelpers.urlBaseUrl(url)
if '://' in baseurl:
count = 2
else:
count = 0
# http://abc.com will split to ['http:', '', 'abc.com']
return baseurl.split('/')[count].lower()
def domainKeyword(self, domain: str, tldList: list) -> str:
"""Extract the keyword (the domain without the TLD or any subdomains) from a domain.
Args:
domain (str): The domain to check.
tldList (list): The list of TLDs based on the Mozilla public list.
Returns:
str: The keyword
"""
if not domain:
self.error(f"Invalid domain: {domain}")
return None
# Strip off the TLD
dom = self.hostDomain(domain.lower(), tldList)
if not dom:
return None
tld = '.'.join(dom.split('.')[1:])
ret = domain.lower().replace('.' + tld, '')
# If the user supplied a domain with a sub-domain, return the second part
if '.' in ret:
return ret.split('.')[-1]
return ret
def domainKeywords(self, domainList: list, tldList: list) -> set:
"""Extract the keywords (the domains without the TLD or any subdomains) from a list of domains.
Args:
domainList (list): The list of domains to check.
tldList (list): The list of TLDs based on the Mozilla public list.
Returns:
set: List of keywords
"""
if not domainList:
self.error(f"Invalid domain list: {domainList}")
return set()
keywords = list()
for domain in domainList:
keywords.append(self.domainKeyword(domain, tldList))
self.debug(f"Keywords: {keywords}")
return set([k for k in keywords if k])
def hostDomain(self, hostname: str, tldList: list) -> str:
"""Obtain the domain name for a supplied hostname.
Args:
hostname (str): The hostname to check.
tldList (list): The list of TLDs based on the Mozilla public list.
Returns:
str: The domain name.
"""
if not tldList:
return None
if not hostname:
return None
ps = PublicSuffixList(tldList, only_icann=True)
return ps.privatesuffix(hostname)
def validHost(self, hostname: str, tldList: str) -> bool:
"""Check if the provided string is a valid hostname with a valid public suffix TLD.
Args:
hostname (str): The hostname to check.
tldList (str): The list of TLDs based on the Mozilla public list.
Returns:
bool
"""
if not tldList:
return False
if not hostname:
return False
if "." not in hostname:
return False
if not re.match(r"^[a-z0-9-\.]*$", hostname, re.IGNORECASE):
return False
ps = PublicSuffixList(tldList, only_icann=True, accept_unknown=False)
sfx = ps.privatesuffix(hostname)
return sfx is not None
def isDomain(self, hostname: str, tldList: list) -> bool:
"""Check if the provided hostname string is a valid domain name.
Given a possible hostname, check if it's a domain name
By checking whether it rests atop a valid TLD.
e.g. www.example.com = False because tld of hostname is com,
and www.example has a . in it.
Args:
hostname (str): The hostname to check.
tldList (list): The list of TLDs based on the Mozilla public list.
Returns:
bool
"""
if not tldList:
return False
if not hostname:
return False
ps = PublicSuffixList(tldList, only_icann=True, accept_unknown=False)
sfx = ps.privatesuffix(hostname)
return sfx == hostname
def validIP(self, address: str) -> bool:
"""Check if the provided string is a valid IPv4 address.
Args:
address (str): The IPv4 address to check.
Returns:
bool
"""
if not address:
return False
return netaddr.valid_ipv4(address)
def validIP6(self, address: str) -> bool:
"""Check if the provided string is a valid IPv6 address.
Args:
address (str): The IPv6 address to check.
Returns:
bool: string is a valid IPv6 address
"""
if not address:
return False
return netaddr.valid_ipv6(address)
def validIpNetwork(self, cidr: str) -> bool:
"""Check if the provided string is a valid CIDR netblock.
Args:
cidr (str): The netblock to check.
Returns:
bool: string is a valid CIDR netblock
"""
if not isinstance(cidr, str):
return False
if '/' not in cidr:
return False
try:
return netaddr.IPNetwork(str(cidr)).size > 0
except BaseException:
return False
def isPublicIpAddress(self, ip: str) -> bool:
"""Check if an IP address is public.
Args:
ip (str): IP address
Returns:
bool: IP address is public
"""
if not isinstance(ip, (str, netaddr.IPAddress)):
return False
if not self.validIP(ip) and not self.validIP6(ip):
return False
if not netaddr.IPAddress(ip).is_unicast():
return False
if netaddr.IPAddress(ip).is_loopback():
return False
if netaddr.IPAddress(ip).is_reserved():
return False
if netaddr.IPAddress(ip).is_multicast():
return False
if netaddr.IPAddress(ip).is_private():
return False
return True
def normalizeDNS(self, res: list) -> list:
"""Clean DNS results to be a simple list
Args:
res (list): List of DNS names
Returns:
list: list of domains
"""
ret = list()
if not res:
return ret
for addr in res:
if isinstance(addr, list):
for host in addr:
host = str(host).rstrip(".")
if host:
ret.append(host)
else:
host = str(addr).rstrip(".")
if host:
ret.append(host)
return ret
def resolveHost(self, host: str) -> list:
"""Return a normalised IPv4 resolution of a hostname.
Args:
host (str): host to resolve
Returns:
list: IP addresses
"""
if not host:
self.error(f"Unable to resolve host: {host} (Invalid host)")
return list()
addrs = list()
try:
addrs = self.normalizeDNS(socket.gethostbyname_ex(host))
except BaseException as e:
self.debug(f"Unable to resolve host: {host} ({e})")
return addrs
if not addrs:
self.debug(f"Unable to resolve host: {host}")
return addrs
self.debug(f"Resolved {host} to IPv4: {addrs}")
return list(set(addrs))
def resolveIP(self, ipaddr: str) -> list:
"""Return a normalised resolution of an IPv4 or IPv6 address.
Args:
ipaddr (str): IP address to reverse resolve
Returns:
list: list of domain names
"""
if not self.validIP(ipaddr) and not self.validIP6(ipaddr):
self.error(f"Unable to reverse resolve {ipaddr} (Invalid IP address)")
return list()
self.debug(f"Performing reverse resolve of {ipaddr}")
try:
addrs = self.normalizeDNS(socket.gethostbyaddr(ipaddr))
except BaseException as e:
self.debug(f"Unable to reverse resolve IP address: {ipaddr} ({e})")
return list()
if not addrs:
self.debug(f"Unable to reverse resolve IP address: {ipaddr}")
return list()
self.debug(f"Reverse resolved {ipaddr} to: {addrs}")
return list(set(addrs))
def resolveHost6(self, hostname: str) -> list:
"""Return a normalised IPv6 resolution of a hostname.
Args:
hostname (str): hostname to resolve
Returns:
list
"""
if not hostname:
self.error(f"Unable to resolve host: {hostname} (Invalid host)")
return list()
addrs = list()
try:
res = socket.getaddrinfo(hostname, None, socket.AF_INET6)
for addr in res:
if addr[4][0] not in addrs:
addrs.append(addr[4][0])
except BaseException as e:
self.debug(f"Unable to resolve host: {hostname} ({e})")
return addrs
if not addrs:
self.debug(f"Unable to resolve host: {hostname}")
return addrs
self.debug(f"Resolved {hostname} to IPv6: {addrs}")
return list(set(addrs))
def validateIP(self, host: str, ip: str) -> bool:
"""Verify a host resolves to a given IP.
Args:
host (str): host
ip (str): IP address
Returns:
bool: host resolves to the given IP address
"""
if not host:
self.error(f"Unable to resolve host: {host} (Invalid host)")
return False
if self.validIP(ip):
addrs = self.resolveHost(host)
elif self.validIP6(ip):
addrs = self.resolveHost6(host)
else:
self.error(f"Unable to verify hostname {host} resolves to {ip} (Invalid IP address)")
return False
if not addrs:
return False
return any(str(addr) == ip for addr in addrs)
def safeSocket(self, host: str, port: int, timeout: int) -> 'ssl.SSLSocket':
"""Create a safe socket that's using SOCKS/TOR if it was enabled.
Args:
host (str): host
port (int): port
timeout (int): timeout
Returns:
sock
"""
sock = socket.create_connection((host, int(port)), int(timeout))
sock.settimeout(int(timeout))
return sock
def safeSSLSocket(self, host: str, port: int, timeout: int) -> 'ssl.SSLSocket':
"""Create a safe SSL connection that's using SOCKs/TOR if it was enabled.
Args:
host (str): host
port (int): port
timeout (int): timeout
Returns:
sock
"""
s = socket.socket()
s.settimeout(int(timeout))
s.connect((host, int(port)))
sock = ssl.wrap_socket(s)
sock.do_handshake()
return sock
def parseCert(self, rawcert: str, fqdn: str = None, expiringdays: int = 30) -> dict:
"""Parse a PEM-format SSL certificate.
Args:
rawcert (str): PEM-format SSL certificate
fqdn (str): expected FQDN for certificate
expiringdays (int): The certificate will be considered as "expiring" if within this number of days of expiry.
Returns:
dict: certificate details
"""
if not rawcert:
self.error(f"Invalid certificate: {rawcert}")
return None
ret = dict()
if '\r' in rawcert:
rawcert = rawcert.replace('\r', '')
if isinstance(rawcert, str):
rawcert = rawcert.encode('utf-8')
from cryptography.hazmat.backends.openssl import backend
cert = cryptography.x509.load_pem_x509_certificate(rawcert, backend)
sslcert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, rawcert)
sslcert_dump = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_TEXT, sslcert)