forked from smicallef/spiderfoot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sflib.py
1968 lines (1627 loc) · 69 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.
# Also defines the SpiderFootPlugin abstract class for modules.
#
# Author: Steve Micallef <[email protected]>
#
# Created: 26/03/2012
# Copyright: (c) Steve Micallef 2012
# Licence: GPL
# -------------------------------------------------------------------------------
from stem import Signal
from stem.control import Controller
import inspect
import hashlib
import binascii
import gzip
import gexf
import json
import re
import os
import random
import requests
import socket
import ssl
import sys
import time
import netaddr
import urllib2
import StringIO
import threading
from bs4 import BeautifulSoup, SoupStrainer
from copy import deepcopy, copy
# For hiding the SSL warnings coming from the requests lib
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
class SpiderFoot:
dbh = None
GUID = None
savedsock = socket
urllib2.savedsock = urllib2.socket
# 'options' is a dictionary of options which changes the behaviour
# of how certain things are done in this module
# 'handle' will be supplied if the module is being used within the
# SpiderFoot GUI, in which case all feedback should be fed back
def __init__(self, options, handle=None):
self.handle = handle
self.opts = deepcopy(options)
# This is ugly but we don't want any fetches to fail - we expect
# to encounter unverified SSL certs!
if sys.version_info >= (2, 7, 9):
ssl._create_default_https_context = ssl._create_unverified_context
# 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.
def updateSocket(self, sock):
socket = sock
urllib2.socket = sock
def revertSocket(self):
socket = self.savedsock
urllib2.socket = urllib2.savedsock
# Tell TOR to re-circuit
def refreshTorIdent(self):
if self.opts['_socks1type'] != "TOR":
return None
try:
self.info("Re-circuiting TOR...")
with Controller.from_port(address=self.opts['_socks2addr'],
port=self.opts['_torctlport']) as controller:
controller.authenticate()
controller.signal(Signal.NEWNYM)
time.sleep(10)
except BaseException as e:
self.fatal("Unable to re-circuit TOR: " + str(e))
# 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.
def optValueToData(self, val, fatal=True, splitLines=True):
if val.startswith('@'):
fname = val.split('@')[1]
try:
self.info("Loading configuration data from: " + fname)
f = open(fname, "r")
if splitLines:
arr = f.readlines()
ret = list()
for x in arr:
ret.append(x.rstrip('\n'))
else:
ret = f.read()
return ret
except BaseException as b:
if fatal:
self.error("Unable to open option file, " + fname + ".")
else:
return None
if val.lower().startswith('http://') or val.lower().startswith('https://'):
try:
self.info("Downloading configuration data from: " + val)
res = urllib2.urlopen(val)
data = res.read()
if splitLines:
return data.splitlines()
else:
return data
except BaseException as e:
if fatal:
self.error("Unable to open option URL, " + val + ": " + str(e))
else:
return None
return val
# Return a format-agnostic collection of tuples to use as the
# basis for building graphs in various formats.
def buildGraphData(self, data, flt=list()):
mapping = set()
entities = dict()
parents = dict()
def get_next_parent_entities(item, pids):
ret = list()
for [parent, id] in parents[item]:
if id in pids:
continue
if parent in entities:
ret.append(parent)
else:
pids.append(id)
for p in get_next_parent_entities(parent, pids):
ret.append(p)
return ret
for row in data:
if row[11] == "ENTITY" or row[11] == "INTERNAL":
# List of all valid entity values
if len(flt) > 0:
if row[4] in flt or row[11] == "INTERNAL":
entities[row[1]] = True
else:
entities[row[1]] = True
if row[1] not in parents:
parents[row[1]] = list()
parents[row[1]].append([row[2], row[8]])
for entity in entities:
for [parent, id] in parents[entity]:
if parent in entities:
if entity != parent:
#print "Adding entity parent: " + parent
mapping.add((entity, parent))
else:
ppids = list()
#print "Checking " + parent + " for entityship."
next_parents = get_next_parent_entities(parent, ppids)
for next_parent in next_parents:
if entity != next_parent:
#print "Adding next entity parent: " + next_parent
mapping.add((entity, next_parent))
return mapping
# Convert supplied raw data into GEXF format (e.g. for Gephi)
# GEXF produced by PyGEXF doesn't work with SigmaJS because
# SJS needs coordinates for each node.
# flt is a list of event types to include, if not set everything is
# included.
def buildGraphGexf(self, root, title, data, flt=[]):
mapping = self.buildGraphData(data, flt)
g = gexf.Gexf(title, title)
graph = g.addGraph("undirected", "static", "SpiderFoot Export")
nodelist = dict()
ecounter = 0
ncounter = 0
for pair in mapping:
(dst, src) = pair
col = ["0", "0", "0"]
# Leave out this special case
if dst == "ROOT" or src == "ROOT":
continue
if dst not in nodelist:
ncounter = ncounter + 1
if dst in root:
col = ["255", "0", "0"]
graph.addNode(str(ncounter), unicode(dst, errors="replace"),
r=col[0], g=col[1], b=col[2])
nodelist[dst] = ncounter
if src not in nodelist:
ncounter = ncounter + 1
if src in root:
col = ["255", "0", "0"]
graph.addNode(str(ncounter), unicode(src, errors="replace"),
r=col[0], g=col[1], b=col[2])
nodelist[src] = ncounter
ecounter = ecounter + 1
graph.addEdge(str(ecounter), str(nodelist[src]), str(nodelist[dst]))
output = StringIO.StringIO()
g.write(output)
return output.getvalue()
# Convert supplied raw data into JSON format for SigmaJS
def buildGraphJson(self, root, data, flt=list()):
mapping = self.buildGraphData(data, flt)
ret = dict()
ret['nodes'] = list()
ret['edges'] = list()
nodelist = dict()
ecounter = 0
ncounter = 0
for pair in mapping:
(dst, src) = pair
col = "#000"
# Leave out this special case
if dst == "ROOT" or src == "ROOT":
continue
if dst not in nodelist:
ncounter = ncounter + 1
if dst in root:
col = "#f00"
ret['nodes'].append({'id': str(ncounter),
'label': unicode(dst, errors="replace"),
'x': random.randint(1,1000),
'y': random.randint(1,1000),
'size': "1",
'color': col
})
nodelist[dst] = ncounter
if src not in nodelist:
if src in root:
col = "#f00"
ncounter = ncounter + 1
ret['nodes'].append({'id': str(ncounter),
'label': unicode(src, errors="replace"),
'x': random.randint(1,1000),
'y': random.randint(1,1000),
'size': "1",
'color': col
})
nodelist[src] = ncounter
ecounter = ecounter + 1
ret['edges'].append({'id': str(ecounter),
'source': str(nodelist[src]),
'target': str(nodelist[dst])
})
return json.dumps(ret)
# Called usually some time after instantiation
# to set up a database handle and scan GUID, used
# for logging events to the database about a scan.
def setDbh(self, handle):
self.dbh = handle
# Set the GUID this instance of SpiderFoot is being
# used in.
def setGUID(self, uid):
self.GUID = uid
# Generate an globally unique ID for this scan
def genScanInstanceGUID(self, scanName):
# hashStr = hashlib.sha256(
# scanName +
# str(time.time() * 1000) +
# str(random.randint(100000, 999999))
# ).hexdigest()
rstr = str(time.time()) + str(random.randint(100000, 999999))
hashStr = "%08X" % int(binascii.crc32(rstr) & 0xffffffff)
return hashStr
def _dblog(self, level, message, component=None):
#print str(self.GUID) + ":" + str(level) + ":" + str(message) + ":" + str(component)
return self.dbh.scanLogEvent(self.GUID, level, message, component)
def error(self, error, exception=True):
if not self.opts['__logging']:
return None
if self.dbh is None:
print '[Error] ' + error
else:
self._dblog("ERROR", error)
if self.opts.get('__logstdout'):
print "[Error] " + error
if exception:
raise BaseException("Internal Error Encountered: " + error)
def fatal(self, error):
if self.dbh is None:
print '[Fatal] ' + error
else:
self._dblog("FATAL", error)
print str(inspect.stack())
sys.exit(-1)
def status(self, message):
if not self.opts['__logging']:
return None
if self.dbh is None:
print "[Status] " + message
else:
self._dblog("STATUS", message)
if self.opts.get('__logstdout'):
print "[*] " + message
def info(self, message):
if not self.opts['__logging']:
return None
frm = inspect.stack()[1]
mod = inspect.getmodule(frm[0])
if mod is None:
modName = "Unknown"
else:
if mod.__name__ == "sflib":
frm = inspect.stack()[2]
mod = inspect.getmodule(frm[0])
if mod is None:
modName = "Unknown"
else:
modName = mod.__name__
else:
modName = mod.__name__
if self.dbh is None:
print '[' + modName + '] ' + message
else:
self._dblog("INFO", message, modName)
if self.opts.get('__logstdout'):
print "[*] " + message
return
def debug(self, message):
if not self.opts['_debug']:
return
if not self.opts['__logging']:
return None
frm = inspect.stack()[1]
mod = inspect.getmodule(frm[0])
if mod is None:
modName = "Unknown"
else:
if mod.__name__ == "sflib":
frm = inspect.stack()[2]
mod = inspect.getmodule(frm[0])
if mod is None:
modName = "Unknown"
else:
modName = mod.__name__
else:
modName = mod.__name__
if self.dbh is None:
print '[' + modName + '] ' + message
else:
self._dblog("DEBUG", message, modName)
if self.opts.get('__logstdout'):
print "[d:" + modName +"] " + message
return
def myPath(self):
# This will get us the program's directory, even if we are frozen using py2exe.
# Determine whether we've been compiled by py2exe
if hasattr(sys, "frozen"):
return os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding()))
return os.path.dirname(unicode(__file__, sys.getfilesystemencoding()))
def hashstring(self, string):
s = string
if type(string) in [list, dict]:
s = str(string)
if type(s) == str:
s = unicode(s, 'utf-8', errors='replace')
return hashlib.sha256(s.encode('raw_unicode_escape')).hexdigest()
#
# Caching
#
# Return the cache path
def cachePath(self):
path = self.myPath() + '/cache'
if not os.path.isdir(path):
os.mkdir(path)
return path
# Store data to the cache
def cachePut(self, label, data):
pathLabel = hashlib.sha224(label).hexdigest()
cacheFile = self.cachePath() + "/" + pathLabel
fp = file(cacheFile, "w")
if type(data) is list:
for line in data:
fp.write(line + '\n')
else:
data = data.encode('utf-8')
fp.write(data)
fp.close()
# Retreive data from the cache
def cacheGet(self, label, timeoutHrs):
pathLabel = hashlib.sha224(label).hexdigest()
cacheFile = self.cachePath() + "/" + pathLabel
try:
(m, i, d, n, u, g, sz, atime, mtime, ctime) = os.stat(cacheFile)
if sz == 0:
return None
if mtime > time.time() - timeoutHrs * 3600 or timeoutHrs == 0:
fp = file(cacheFile, "r")
fileContents = fp.read()
fp.close()
fileContents = fileContents.decode('utf-8')
return fileContents
else:
return None
except BaseException as e:
return None
#
# Configuration process
#
# Convert a Python dictionary to something storable
# in the database.
def configSerialize(self, opts, filterSystem=True):
storeopts = dict()
for opt in opts.keys():
# Filter out system temporary variables like GUID and others
if opt.startswith('__') and filterSystem:
continue
if type(opts[opt]) is int or type(opts[opt]) is str:
storeopts[opt] = opts[opt]
if type(opts[opt]) is bool:
if opts[opt]:
storeopts[opt] = 1
else:
storeopts[opt] = 0
if type(opts[opt]) is list:
storeopts[opt] = ','.join(opts[opt])
if '__modules__' not in opts:
return storeopts
for mod in opts['__modules__']:
for opt in opts['__modules__'][mod]['opts']:
if opt.startswith('_') and filterSystem:
continue
if type(opts['__modules__'][mod]['opts'][opt]) is int or \
type(opts['__modules__'][mod]['opts'][opt]) is str:
storeopts[mod + ":" + opt] = opts['__modules__'][mod]['opts'][opt]
if type(opts['__modules__'][mod]['opts'][opt]) is bool:
if opts['__modules__'][mod]['opts'][opt]:
storeopts[mod + ":" + opt] = 1
else:
storeopts[mod + ":" + opt] = 0
if type(opts['__modules__'][mod]['opts'][opt]) is list:
storeopts[mod + ":" + opt] = ','.join(str(x) \
for x in opts['__modules__'][mod]['opts'][opt])
return storeopts
# Take strings, etc. from the database or UI and convert them
# to a dictionary for Python to process.
# referencePoint is needed to know the actual types the options
# are supposed to be.
def configUnserialize(self, opts, referencePoint, filterSystem=True):
returnOpts = referencePoint
# Global options
for opt in referencePoint.keys():
if opt.startswith('__') and filterSystem:
# Leave out system variables
continue
if opt in opts:
if type(referencePoint[opt]) is bool:
if opts[opt] == "1":
returnOpts[opt] = True
else:
returnOpts[opt] = False
if type(referencePoint[opt]) is str:
returnOpts[opt] = str(opts[opt])
if type(referencePoint[opt]) is int:
returnOpts[opt] = int(opts[opt])
if type(referencePoint[opt]) is list:
if type(referencePoint[opt][0]) is 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
# 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:
if type(referencePoint['__modules__'][modName]['opts'][opt]) is bool:
if opts[modName + ":" + opt] == "1":
returnOpts['__modules__'][modName]['opts'][opt] = True
else:
returnOpts['__modules__'][modName]['opts'][opt] = False
if type(referencePoint['__modules__'][modName]['opts'][opt]) is str:
returnOpts['__modules__'][modName]['opts'][opt] = \
str(opts[modName + ":" + opt])
if type(referencePoint['__modules__'][modName]['opts'][opt]) is int:
returnOpts['__modules__'][modName]['opts'][opt] = \
int(opts[modName + ":" + opt])
if type(referencePoint['__modules__'][modName]['opts'][opt]) is list:
if type(referencePoint['__modules__'][modName]['opts'][opt][0]) is 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
# Return the type for a scan
def targetType(self, target):
targetType = None
regexToType = [
{"^\d+\.\d+\.\d+\.\d+$": "IP_ADDRESS"},
{"^\d+\.\d+\.\d+\.\d+/\d+$": "NETBLOCK_OWNER"},
{"^.*@.*$": "EMAILADDR"},
{"^\".*\"$": "HUMAN_NAME"},
{"\d+": "BGP_AS_OWNER"},
{".*\..*": "INTERNET_NAME"}
]
# Parse the target and set the targetType
for rxpair in regexToType:
rx = rxpair.keys()[0]
if re.match(rx, target, re.IGNORECASE|re.UNICODE):
targetType = rxpair.values()[0]
break
return targetType
# Return an array of module names for returning the
# types specified.
def modulesProducing(self, events):
modlist = list()
for mod in self.opts['__modules__'].keys():
if self.opts['__modules__'][mod]['provides'] is None:
continue
for evtype in self.opts['__modules__'][mod]['provides']:
if evtype in events and mod not in modlist:
modlist.append(mod)
if "*" in events and mod not in modlist:
modlist.append(mod)
return modlist
# Return an array of modules that consume the types
# specified.
def modulesConsuming(self, events):
modlist = list()
for mod in self.opts['__modules__'].keys():
if self.opts['__modules__'][mod]['consumes'] is None:
continue
if "*" in self.opts['__modules__'][mod]['consumes'] and mod not in modlist:
modlist.append(mod)
for evtype in self.opts['__modules__'][mod]['consumes']:
if evtype in events and mod not in modlist:
modlist.append(mod)
return modlist
# Return an array of types that are produced by the list
# of modules supplied.
def eventsFromModules(self, modules):
evtlist = list()
for mod in modules:
if mod in self.opts['__modules__'].keys():
if self.opts['__modules__'][mod]['provides'] is not None:
for evt in self.opts['__modules__'][mod]['provides']:
evtlist.append(evt)
return evtlist
# Return an array of types that are consumed by the list
# of modules supplied.
def eventsToModules(self, modules):
evtlist = list()
for mod in modules:
if mod in self.opts['__modules__'].keys():
if self.opts['__modules__'][mod]['consumes'] is not None:
for evt in self.opts['__modules__'][mod]['consumes']:
evtlist.append(evt)
return evtlist
#
# URL parsing functions
#
# Turn a relative path into an absolute path
def urlRelativeToAbsolute(self, url):
finalBits = list()
if '..' not in url:
return url
bits = url.split('/')
for chunk in bits:
if chunk == '..':
# Don't pop the last item off if we're at the top
if len(finalBits) <= 1:
continue
# Don't pop the last item off if the first bits are not the path
if '://' in url and len(finalBits) <= 3:
continue
finalBits.pop()
continue
finalBits.append(chunk)
#self.debug('xfrmed rel to abs path: ' + url + ' to ' + '/'.join(finalBits))
return '/'.join(finalBits)
# Extract the top level directory from a URL
def urlBaseDir(self, url):
bits = url.split('/')
# For cases like 'www.somesite.com'
if len(bits) == 0:
#self.debug('base dir of ' + url + ' not identified, using URL as base.')
return url + '/'
# For cases like 'http://www.blah.com'
if '://' in url and url.count('/') < 3:
#self.debug('base dir of ' + url + ' is: ' + url + '/')
return url + '/'
base = '/'.join(bits[:-1])
#self.debug('base dir of ' + url + ' is: ' + base + '/')
return base + '/'
# Extract the scheme and domain from a URL
# Does not return the trailing slash! So you can do .endswith()
# checks.
def urlBaseUrl(self, url):
if '://' in url:
bits = re.match('(\w+://.[^/:\?]*)[:/\?].*', url)
else:
bits = re.match('(.[^/:\?]*)[:/\?]', url)
if bits is None:
return url.lower()
#self.debug('base url of ' + url + ' is: ' + bits.group(1))
return bits.group(1).lower()
# Extract the FQDN from a URL
def urlFQDN(self, url):
baseurl = self.urlBaseUrl(url)
if '://' not in baseurl:
count = 0
else:
count = 2
# http://abc.com will split to ['http:', '', 'abc.com']
return baseurl.split('/')[count].lower()
# Extract the keyword (the domain without the TLD or any subdomains)
# from a domain.
def domainKeyword(self, domain, tldList):
# Strip off the TLD
tld = '.'.join(self.hostDomain(domain.lower(), tldList).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]
else:
return ret
# Extract the keywords (the domains without the TLD or any subdomains)
# from a list of domains.
def domainKeywords(self, domainList, tldList):
arr = list()
for domain in domainList:
# Strip off the TLD
tld = '.'.join(self.hostDomain(domain.lower(), tldList).split('.')[1:])
ret = domain.lower().replace('.' + tld, '')
# If the user supplied a domain with a sub-domain, return the second part
if '.' in ret:
arr.append(ret.split('.')[-1])
else:
arr.append(ret)
self.debug("Keywords: " + str(arr))
return arr
# Obtain the domain name for a supplied hostname
# tldList needs to be an array based on the Mozilla public list
def hostDomain(self, hostname, tldList):
ps = PublicSuffixList(tldList)
return ps.get_public_suffix(hostname)
# Simple way to verify IPs.
def validIP(self, address):
return netaddr.valid_ipv4(address)
# Clean DNS results to be a simple list
def normalizeDNS(self, res):
ret = list()
for addr in res:
if type(addr) == list:
for host in addr:
ret.append(unicode(host, 'utf-8', errors='replace'))
else:
ret.append(unicode(addr, 'utf-8', errors='replace'))
return ret
# Verify input is OK to execute
def sanitiseInput(self, cmd):
chars = ['a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z',
'0','1','2','3','4','5','6','7','8','9','-','.']
for c in cmd:
if c.lower() not in chars:
return False
return True
# Return dictionary words and/or names
def dictwords(self):
wd = dict()
dicts = [ "english", "german", "french", "spanish" ]
for d in dicts:
wdct = open(self.myPath() + "/ext/ispell/" + d + ".dict", 'r')
dlines = wdct.readlines()
for w in dlines:
w = w.strip().lower()
wd[w.split('/')[0]] = True
return wd.keys()
# Return dictionary names
def dictnames(self):
wd = dict()
dicts = [ "names" ]
for d in dicts:
wdct = open(self.myPath() + "/ext/ispell/" + d + ".dict", 'r')
dlines = wdct.readlines()
for w in dlines:
w = w.strip().lower()
wd[w.split('/')[0]] = True
return wd.keys()
# Converts a dictionary of k -> array to a nested
# tree that can be digested by d3 for visualizations.
def dataParentChildToTree(self, data):
def get_children(needle, haystack):
#print "called"
ret = list()
if needle not in haystack.keys():
return None
if haystack[needle] is None:
return None
for c in haystack[needle]:
#print "found child of " + needle + ": " + c
ret.append({"name": c, "children": get_children(c, haystack)})
return ret
# Find the element with no parents, that's our root.
root = None
for k in data.keys():
if data[k] is None:
continue
contender = True
for ck in data.keys():
if data[ck] is None:
continue
if k in data[ck]:
contender = False
if contender:
root = k
break
if root is None:
#print "*BUG*: Invalid structure - needs to go back to one root."
final = {}
else:
final = {"name": root, "children": get_children(root, data)}
return final
#
# General helper functions to automate many common tasks between modules
#
# Parse the contents of robots.txt, returns a list of patterns
# which should not be followed
def parseRobotsTxt(self, robotsTxtData):
returnArr = list()
# We don't check the User-Agent rule yet.. probably should at some stage
for line in robotsTxtData.splitlines():
if line.lower().startswith('disallow:'):
m = re.match('disallow:\s*(.[^ #]*)', line, re.IGNORECASE)
self.debug('robots.txt parsing found disallow: ' + m.group(1))
returnArr.append(m.group(1))
continue
return returnArr
# Find all URLs within the supplied content. This does not fetch any URLs!
# A dictionary will be returned, where each link will have the keys
# 'source': The URL where the link was obtained from
# 'original': What the link looked like in the content it was obtained from
# The key will be the *absolute* URL of the link obtained, so for example if
# the link '/abc' was obtained from 'http://xyz.com', the key in the dict will
# be 'http://xyz.com/abc' with the 'original' attribute set to '/abc'
def parseLinks(self, url, data, domains, parseText=True):
returnLinks = dict()
urlsRel = []
if type(domains) is str:
domains = [domains]
tags = {
'a': 'href',
'img': 'src',
'script': 'src',
'link': 'href',
'area': 'href',
'base': 'href',
'form': 'action'
}
try:
proto = url.split(":")[0]
except BaseException as e:
proto = "http"
if proto == None:
proto = "http"
if data is None or len(data) == 0:
self.debug("parseLinks() called with no data to parse.")
return None
try:
for t in tags.keys():
for lnk in BeautifulSoup(data, "lxml",
parse_only=SoupStrainer(t)).find_all(t):
if lnk.has_attr(tags[t]):
urlsRel.append([None, lnk[tags[t]]])
except BaseException as e:
self.error("Error parsing with BeautifulSoup: " + str(e), False)
return None
# Find potential links that aren't links (text possibly in comments, etc.)
data = urllib2.unquote(data)
for domain in domains:
if parseText:
try:
# Because we're working with a big blob of text now, don't worry
# about clobbering proper links by url decoding them.
regRel = re.compile('(.)([a-zA-Z0-9\-\.]+\.' + domain + ')',
re.IGNORECASE)
urlsRel = urlsRel + regRel.findall(data)
except Exception as e:
self.error("Error applying regex2 to: " + data + "(" + str(e) + ")", False)
try:
# Some links are sitting inside a tag, e.g. Google's use of <cite>
regRel = re.compile('([>\"])([a-zA-Z0-9\-\.\:\/]+\.' + domain + '/.[^<\"]+)', re.IGNORECASE)
urlsRel = urlsRel + regRel.findall(data)
except Exception as e:
self.error("Error applying regex3 to: " + data + "(" + str(e) + ")", False)
# Loop through all the URLs/links found
for linkTuple in urlsRel:
# Remember the regex will return two vars (two groups captured)
junk = linkTuple[0]
link = linkTuple[1]
if type(link) != unicode:
link = unicode(link, 'utf-8', errors='replace')
linkl = link.lower()
absLink = None
if len(link) < 1:
continue
# Don't include stuff likely part of some dynamically built incomplete
# URL found in Javascript code (character is part of some logic)
if link[len(link) - 1] == '.' or link[0] == '+' or \
'javascript:' in linkl or '()' in link:
self.debug('unlikely link: ' + link)
continue
# Filter in-page links
if re.match('.*#.[^/]+', link):
self.debug('in-page link: ' + link)
continue
# Ignore mail links
if 'mailto:' in linkl:
self.debug("Ignoring mail link: " + link)
continue
# URL decode links
if '%2f' in linkl:
link = urllib2.unquote(link)
# Capture the absolute link:
# If the link contains ://, it is already an absolute link
if '://' in link:
absLink = link
# If the link starts with a /, the absolute link is off the base URL
if link.startswith('/'):
absLink = self.urlBaseUrl(url) + link
# Protocol relative URLs
if link.startswith('//'):
absLink = proto + ':' + link
# Maybe the domain was just mentioned and not a link, so we make it one
if absLink is None and domain.lower() in link.lower():
absLink = proto + '://' + link
# Otherwise, it's a flat link within the current directory
if absLink is None:
absLink = self.urlBaseDir(url) + link
# Translate any relative pathing (../)
absLink = self.urlRelativeToAbsolute(absLink)
returnLinks[absLink] = {'source': url, 'original': link}
return returnLinks
def urlEncodeUnicode(self, url):