SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.
Python attacksurfacecticybersecurityfootprintinghackinginformation-gatheringinformation-securityinfosecintelligence-gatheringosintosint-frameworkosint-reconnaissanceosint-toolpentestingpythonreconsecurity-toolsthreat-intelligencethreatintel
Full linkage between elements.
smicallef6f97119693b0
diff --git a/dyn/scaninfo.tmpl b/dyn/scaninfo.tmplindex 53bd5cfd..eb4a6003 100644--- a/dyn/scaninfo.tmpl+++ b/dyn/scaninfo.tmpl@@ -2,7 +2,7 @@<h2>${name} <img id=loader src=/static/img/loader.gif></h2><div class="btn-toolbar"><div class="btn-group">- <a id='btn-live' class="btn active" href="#" onClick='liveView("${id}")'><i class='icon-eye-open'></i> Live View</a>+ <!--<a id='btn-live' class="btn active" href="#" onClick='liveView("${id}")'><i class='icon-eye-open'></i> Live View</a> --><a id='btn-browse' class="btn" href="#" onClick='browseEventList("${id}")'><i class='icon-th-list'></i> Browse</a><a id='btn-info' class="btn" href="#" onClick='viewScanConfig("${id}")'><i class='icon-cog'></i> Scan Settings</a><a id='btn-log' class="btn" href="#" onClick='viewScanLog("${id}")'><i class='icon-book'></i> Log</a>@@ -83,6 +83,11 @@table += "<td>" + data[i][2] + "</td>";}table += "</tbody></table>"++ if (data.length < 1) {+ table = "<div id='scansummary-content' class='alert alert-warning'><h4>No data.</h4>If the scan is still running please try again soon.</div>";+ }+$("#loader").fadeOut(500);$("#mainbody").append(table);$("#scansummary-content").tablesorter();@@ -111,7 +116,7 @@crumbs += eventTypeLabel + "</a></li></ul>";var table = "<table id='scansummary-content' class='table table-bordered table-striped small'>";- table += "<thead><tr> <th>Data Element</th><th>Source Data Element</th><th>Source Module</th><th>Identified</th></tr></thead><tbody>";+ table += "<thead><tr> <th>Data Element</th><th>Source Data Element</th><th style='text-align: center'>Source Module</th><th style='text-align: center'>Identified</th></tr></thead><tbody>";for (var i = 0; i < data.length; i++) {table += "<tr><td><pre style='border: 0px; background-color: inherit'>" + data[i][1];table += "</pre></td><td><pre style='border: 0px; background-color: inherit'>" + data[i][2];diff --git a/dyn/scanlist.tmpl b/dyn/scanlist.tmplindex 140681ac..693b0952 100644--- a/dyn/scanlist.tmpl+++ b/dyn/scanlist.tmpl@@ -34,18 +34,18 @@table += "<td>" + data[i][5] + "</td>";if (data[i][6] == "FINISHED") {- status = "badge-success";+ statusy = "badge-success";}if (data[i][6].startsWith("ABORT")) {- status = "badge-warning";+ statusy = "badge-warning";}if (data[i][6] == "RUNNING" || data[i][6] == "STARTED") {- status = "badge-info";+ statusy = "badge-info";}if (data[i][6].endsWith("FAILED")) {- status = "badge-important";+ statusy = "badge-important";}- table += "<td style='text-align: center'><span class='badge " + status + "'>" + data[i][6] + "</span></td>";+ table += "<td style='text-align: center'><span class='badge " + statusy + "'>" + data[i][6] + "</span></td>";table += "<td style='text-align: center'>" + data[i][7] + "</td>";table += "<td style='text-align: center'>";if (data[i][6] == "RUNNING" || data[i][6] == "STARTING" || data[i][6] == "STARTED") {diff --git a/evtypes.sql b/evtypes.sqlindex 8a1d923a..2fa49a97 100644--- a/evtypes.sql+++ b/evtypes.sql@@ -5,6 +5,7 @@ INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('AFFILIATE',INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('EMAILADDR', 'Email Address', 0);INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('GEOINFO', 'Physical Location', 0);INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('HTTP_CODE', 'HTTP Status Code', 0);+INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('INITIAL_TARGET', 'User-Supplied Target', 0);INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('IP_ADDRESS', 'IP Address', 0);INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('NETBLOCK', 'Netblock Ownership', 0);INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('LINKED_URL_INTERNAL', 'Linked URL - Internal', 0);diff --git a/modules/sfp_dns.py b/modules/sfp_dns.pyindex d30c8ad6..378b2c5a 100644--- a/modules/sfp_dns.py+++ b/modules/sfp_dns.py@@ -15,7 +15,7 @@import sysimport reimport socket-from sflib import SpiderFoot, SpiderFootPlugin+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent# SpiderFoot standard lib (must be initialized in setup)sf = None@@ -66,7 +66,11 @@ class sfp_dns(SpiderFootPlugin):return arr# Handle events sent to this module- def handleEvent(self, srcModuleName, eventName, eventSource, eventData):+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+sf.debug("Received event, " + eventName + ", from " + srcModuleName)# Don't look up stuff twice@@ -101,9 +105,11 @@ class sfp_dns(SpiderFootPlugin):# If the returned hostname is on a different# domain to baseDomain, flag it as an affiliateif not host.lower().endswith(self.baseDomain):- self.notifyListeners("AFFILIATE", eventData, host)+ type = "AFFILIATE"else:- self.notifyListeners("SUBDOMAIN", eventData, host)+ type = "SUBDOMAIN"+ evt = SpiderFootEvent(type, host, self.__name__, event)+ self.notifyListeners(evt)# In tests addr[1] was either always the requested lookup or empty@@ -111,11 +117,13 @@ class sfp_dns(SpiderFootPlugin):if len(addrs[2]) > 0 and eventName != 'IP_ADDRESS':for ipaddr in addrs[2]:sf.info("Found IP Address: " + ipaddr)- self.notifyListeners("IP_ADDRESS", eventData, ipaddr)+ evt = SpiderFootEvent("IP_ADDRESS", ipaddr, self.__name__, event)+ self.notifyListeners(evt)return Nonedef start(self):+ sf.debug("Iterating through possible sub-domains [" + str(self.opts['commonsubs']) + "]")# Try resolving common namesfor sub in self.opts['commonsubs']:name = sub + "." + self.baseDomain@@ -127,9 +135,11 @@ class sfp_dns(SpiderFootPlugin):# If the returned hostname is on a different# domain to baseDomain, flag it as an affiliateif not host.lower().endswith(self.baseDomain):- self.notifyListeners("AFFILIATE", self.baseDomain, host)+ type = "AFFILIATE"else:- self.notifyListeners("SUBDOMAIN", self.baseDomain, host)+ type = "SUBDOMAIN"+ evt = SpiderFootEvent(type, host, self.__name__)+ self.notifyListeners(evt)except socket.error as e:sf.info("Unable to resolve " + name)diff --git a/modules/sfp_geoip.py b/modules/sfp_geoip.pyindex acf78aaf..fd05ebbe 100644--- a/modules/sfp_geoip.py+++ b/modules/sfp_geoip.py@@ -14,7 +14,7 @@ import sysimport reimport jsonimport socket-from sflib import SpiderFoot, SpiderFootPlugin+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent# SpiderFoot standard lib (must be initialized in setup)sf = None@@ -44,7 +44,11 @@ class sfp_geoip(SpiderFootPlugin):return ['IP_ADDRESS']# Handle events sent to this module- def handleEvent(self, srcModuleName, eventName, eventSource, eventData):+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+sf.debug("Received event, " + eventName + ", from " + srcModuleName)# Don't look up stuff twice@@ -61,7 +65,8 @@ class sfp_geoip(SpiderFootPlugin):sf.info("Found GeoIP for " + eventData + ": " + hostip['country_name'])countrycity = hostip['country_name']- self.notifyListeners("GEOINFO", eventData, countrycity)+ evt = SpiderFootEvent("GEOINFO", countrycity, self.__name__, event)+ self.notifyListeners(evt)return Nonediff --git a/modules/sfp_googlesearch.py b/modules/sfp_googlesearch.pyindex dfe249db..ada60d06 100644--- a/modules/sfp_googlesearch.py+++ b/modules/sfp_googlesearch.py@@ -13,7 +13,7 @@ import sysimport randomimport reimport time-from sflib import SpiderFoot, SpiderFootPlugin+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent# SpiderFoot standard lib (must be initialized in setup)sf = None@@ -135,7 +135,8 @@ class sfp_googlesearch(SpiderFootPlugin):return None# Submit the google results for analysis- self.notifyListeners("RAW_DATA", page, pages[page])+ evt = SpiderFootEvent("RAW_DATA", pages[page], self.__name__)+ self.notifyListeners(evt)self.results.append(page)# We can optionally fetch links to our domain found in the search@@ -148,17 +149,14 @@ class sfp_googlesearch(SpiderFootPlugin):for link in links:if link in self.results:continue- sf.info("Found a link: " + link)+ sf.debug("Found a link: " + link)if sf.urlBaseUrl(link).endswith(self.baseDomain):if self.checkForStop():return None- linkPage = sf.fetchUrl(link)- # Submit info from what we've fetched for analysis- self.notifyListeners("LINKED_URL_INTERNAL", page, link)- self.notifyListeners("RAW_DATA", link, linkPage['content'])- self.notifyListeners("HTTP_CODE", link, linkPage['code'])- self.notifyListeners("WEBSERVER_HTTPHEADERS", link, linkPage['headers'])+ evt = SpiderFootEvent("LINKED_URL_INTERNAL", link, self.__name__)+ self.notifyListeners(evt)+self.results.append(link)# End of sfp_googlesearch classdiff --git a/modules/sfp_mail.py b/modules/sfp_mail.pyindex 7094f782..9d6d3ca0 100644--- a/modules/sfp_mail.py+++ b/modules/sfp_mail.py@@ -12,7 +12,7 @@import sysimport re-from sflib import SpiderFoot, SpiderFootPlugin+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent# SpiderFoot standard lib (must be initialized in setup)sf = None@@ -53,7 +53,11 @@ class sfp_mail(SpiderFootPlugin):return ["RAW_DATA"]# Handle events sent to this module- def handleEvent(self, srcModuleName, eventName, eventSource, eventData):+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+sf.debug("Received event, " + eventName + ", from " + srcModuleName)matches = re.findall("([a-zA-Z\.0-9_\-]+@[a-zA-Z\.0-9_\-]+)", eventData)@@ -87,7 +91,8 @@ class sfp_mail(SpiderFootPlugin):continuesf.info("Found e-mail address: " + match)- self.notifyListeners("EMAILADDR", eventSource, match)+ evt = SpiderFootEvent("EMAILADDR", match, self.__name__, event)+ self.notifyListeners(evt)return Nonediff --git a/modules/sfp_pageinfo.py b/modules/sfp_pageinfo.pyindex 4ff382b7..3e235845 100644--- a/modules/sfp_pageinfo.py+++ b/modules/sfp_pageinfo.py@@ -13,7 +13,7 @@import sysimport re-from sflib import SpiderFoot, SpiderFootPlugin+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent# SpiderFoot standard lib (must be initialized in setup)sf = None@@ -55,7 +55,17 @@ etc.)"""return ["RAW_DATA"]# Handle events sent to this module- def handleEvent(self, srcModuleName, eventName, eventSource, eventData):+ def handleEvent(self, event):+ # We are only interested in the raw data from the spidering module+ if "sfp_spider" not in event.module:+ sf.debug("Ignoring RAW_DATA from " + event.module)+ return None++ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ eventSource = event.sourceEvent.data # will be the URL of the raw data+sf.debug("Received event, " + eventName + ", from " + srcModuleName)# We aren't interested in describing pages that are not hosted on@@ -75,13 +85,15 @@ etc.)"""matches = re.findall(regex, eventData, re.IGNORECASE)if len(matches) > 0 and regexpGrp not in self.results[eventSource]:sf.info("Matched " + regexpGrp + " in content from " + eventSource)- self.notifyListeners(regexpGrp, eventSource, eventSource)+ evt = SpiderFootEvent(regexpGrp, eventSource, self.__name__, event.sourceEvent)+ self.notifyListeners(evt)self.results[eventSource].append(regexpGrp)# If no regexps were matched, consider this a static pageif len(self.results[eventSource]) == 0:sf.info("Treating " + eventSource + " as URL_STATIC")- self.notifyListeners("URL_STATIC", eventSource, eventSource)+ evt = SpiderFootEvent("URL_STATIC", eventSource, self.__name__, event.sourceEvent)+ self.notifyListeners(evt)return Nonediff --git a/modules/sfp_portscan_basic.py b/modules/sfp_portscan_basic.pyindex b43c848d..6652540e 100644--- a/modules/sfp_portscan_basic.py+++ b/modules/sfp_portscan_basic.py@@ -14,7 +14,7 @@ import sysimport reimport socketimport random-from sflib import SpiderFoot, SpiderFootPlugin+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent# SpiderFoot standard lib (must be initialized in setup)sf = None@@ -62,7 +62,11 @@ class sfp_portscan_basic(SpiderFootPlugin):return ['IP_ADDRESS']# Handle events sent to this module- def handleEvent(self, srcModuleName, eventName, eventSource, eventData):+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+sf.debug("Received event, " + eventName + ", from " + srcModuleName)# Don't look up stuff twice@@ -80,7 +84,8 @@ class sfp_portscan_basic(SpiderFootPlugin):try:sock = socket.create_connection((eventData, port), self.opts['timeout'])sf.info("TCP Port " + str(port) + " found to be OPEN.")- self.notifyListeners("TCP_PORT_OPEN", eventData, str(port))+ evt = SpiderFootEvent("TCP_PORT_OPEN", str(port), self.__name__, event)+ self.notifyListeners(evt)sock.close()except Exception as e:sf.info("Unable to connect to " + eventData + " on port " + str(port) + \diff --git a/modules/sfp_ripe.py b/modules/sfp_ripe.pyindex bb98197a..0994fd32 100644--- a/modules/sfp_ripe.py+++ b/modules/sfp_ripe.py@@ -14,7 +14,7 @@ import sysimport reimport jsonimport socket-from sflib import SpiderFoot, SpiderFootPlugin+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent# SpiderFoot standard lib (must be initialized in setup)sf = None@@ -44,7 +44,11 @@ class sfp_ripe(SpiderFootPlugin):return ['IP_ADDRESS', 'SUBDOMAIN']# Handle events sent to this module- def handleEvent(self, srcModuleName, eventName, eventSource, eventData):+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+sf.debug("Received event, " + eventName + ", from " + srcModuleName)# Don't look up stuff twice@@ -65,10 +69,12 @@ class sfp_ripe(SpiderFootPlugin):for ns in nslist:nsclean = ns.rstrip('.')if not nsclean.endswith(self.baseDomain):- self.notifyListeners("AFFILIATE", eventData, nsclean)+ evt = SpiderFootEvent("AFFILIATE", nsclean, self.__name__, event)+ self.notifyListeners(evt)# Just send the content off for others to process- self.notifyListeners("RAW_DATA", eventData, res['content'])+ evt = SpiderFootEvent("RAW_DATA", res['content'], self.__name__, event)+ self.notifyListeners(evt)return None# First get the netblock the IP resides on@@ -88,8 +94,10 @@ class sfp_ripe(SpiderFootPlugin):# Crude and probably prone to a lot of false positives. Need to revisit.if self.baseDomain in res['content']:sf.info("Owned netblock found: " + prefix)- self.notifyListeners("NETBLOCK", eventData, prefix)- self.notifyListeners("RAW_DATA", eventData, res['content'])+ evt = SpiderFootEvent("NETBLOCK", prefix, self.__name__, event)+ self.notifyListeners(evt)+ evt = SpiderFootEvent("RAW_DATA", res['content'], self.__name__, event)+ self.notifyListeners(evt)return None@@ -105,10 +113,12 @@ class sfp_ripe(SpiderFootPlugin):for ns in nslist:nsclean = ns.rstrip('.')if not nsclean.endswith(self.baseDomain):- self.notifyListeners("AFFILIATE", self.baseDomain, nsclean)+ evt = SpiderFootEvent("AFFILIATE", nsclean, self.__name__)+ self.notifyListeners(evt)# Just send the content off for others to process- self.notifyListeners("RAW_DATA", self.baseDomain, res['content'])+ evt = SpiderFootEvent("RAW_DATA", res['content'], self.__name__)+ self.notifyListeners(evt)return None# End of sfp_ripe classdiff --git a/modules/sfp_similar.py b/modules/sfp_similar.pyindex b3d6faac..05e032e1 100644--- a/modules/sfp_similar.py+++ b/modules/sfp_similar.py@@ -14,7 +14,7 @@ import sysimport reimport timeimport random-from sflib import SpiderFoot, SpiderFootPlugin+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent# These are all string builders, {0} = the domain keyword, {1} = the page number@@ -203,9 +203,11 @@ class sfp_similar(SpiderFootPlugin):pageContent = sf.fetchUrl('http://' + result)if pageContent['content'] != None:- self.notifyListeners("SIMILARDOMAIN", source, result)+ evt = SpiderFootEvent("SIMILARDOMAIN", result, self.__name__)+ self.notifyListeners(evt)else:- self.notifyListeners("SIMILARDOMAIN", source, result)+ evt = SpiderFootEvent("SIMILARDOMAIN", result, self.__name__)+ self.notifyListeners(evt)# Search for similar sounding domainsdiff --git a/modules/sfp_spider.py b/modules/sfp_spider.pyindex 94d0af22..8a4a072f 100644--- a/modules/sfp_spider.py+++ b/modules/sfp_spider.py@@ -25,22 +25,22 @@ class sfp_spider(SpiderFootPlugin):opts = {'robotsonly': False, # only follow links specified by robots.txt'pause': 1, # number of seconds to pause between fetches- 'maxpages': 10000, # max number of pages to fetch- 'maxlevels': 10, # max number of levels to traverse within a site- 'start': [ 'http://', 'https://', 'http://www.', 'https://www.' ],+ 'maxpages': 1000, # max number of pages to fetch+ 'maxlevels': 5, # max number of levels to traverse within a site+ 'start': [ 'http://', 'https://' ],'filterfiles': ['png','gif','jpg','jpeg','tiff', 'tif', 'js', 'css','pdf','tif','ico','flv', 'mp4', 'mp3', 'avi', 'mpg','mpeg', 'iso', 'dat', 'mov', 'swf'], # Extensions to not fetch'filterusers': True, # Don't follow /~user directories'noexternal': True, # Should links to external sites be ignored? (**dangerous if False**)- 'nosubs': False # Should links to subdomains be ignored?+ 'nosubs': False, # Should links to subdomains be ignored?}# Option descriptionsoptdescs = {'robotsonly': "Only follow links specified by robots.txt?",'pause': "Number of seconds to pause between fetches.",- 'start': "Prepend the target with these until you get a hit, to start spidering.",+ 'start': "Prepend targets with these until you get a hit, to start spidering.",'maxpages': "Maximum number of pages to fetch.",'maxlevels': "Maximum levels to traverse within a site.",'filterfiles': "File extensions to ignore (don't fetch them.)",@@ -55,9 +55,6 @@ class sfp_spider(SpiderFootPlugin):# TargetbaseDomain = None- # Where to start spidering from- spiderSource = None-# Pages already fetchedfetchedPages = dict()@@ -74,31 +71,6 @@ class sfp_spider(SpiderFootPlugin):for opt in userOpts.keys():self.opts[opt] = userOpts[opt]- # Determine where to start spidering from- for prefix in self.opts['start']:- res = sf.fetchUrl(prefix + target)- if res['content'] != None:- self.spiderSource = prefix + target- break-- if self.spiderSource == None:- sf.error("Unable to fetch any start pages for the requested target.")- return None-- # Are we respecting robots.txt?- if self.opts['robotsonly']:- robotsTxt = sf.fetchUrl(self.spiderSource + '/robots.txt')- if robotsTxt['content'] != None:- sf.debug('robots.txt contents: ' + robotsTxt['content'])- self.robotsRules = sf.parseRobotsTxt(robotsTxt['content'])- else:- sf.error("Unable to fetch robots.txt and you've asked to abide by its contents.")- return None-- # This module listens to no events- def watchedEvents(self):- return None-# Fetch data from a URL and obtain all links that should be followeddef processUrl(self, url):# Fetch the contents of the supplied URL (object returned)@@ -142,6 +114,8 @@ class sfp_spider(SpiderFootPlugin):returnLinks = dict()for link in links.keys():+ linkBase = sf.urlBaseUrl(link)+# Optionally skip external sites (typical behaviour..)if self.opts['noexternal'] and not sf.urlBaseUrl(link).endswith(self.baseDomain):sf.debug('Ignoring external site: ' + link)@@ -159,7 +133,7 @@ class sfp_spider(SpiderFootPlugin):# If we are respecting robots.txt, filter those out toocheckRobots = lambda blocked: str.lower(blocked) in str.lower(str(link)) or blocked == '*'- if self.opts['robotsonly'] and filter(checkRobots, self.robotsRules):+ if self.opts['robotsonly'] and filter(checkRobots, self.robotsRules[linkBase]):sf.debug("Ignoring page found in robots.txt: " + link)continue@@ -182,50 +156,91 @@ class sfp_spider(SpiderFootPlugin):else:type = "LINKED_URL_EXTERNAL"- if parentEvent == None:- parent = "ROOT"- else:- parent = parentEvent.getHash()-- event = SpiderFootEvent(type, url, self.__name__, parent)+ event = SpiderFootEvent(type, url, self.__name__, parentEvent)self.notifyListeners(event)return event# Notify listening modules about raw data and othersdef contentNotify(self, url, httpresult, parentEvent=None):- if parentEvent == None:- parent = "ROOT"- else:- parent = parentEvent.getHash()-event = SpiderFootEvent("RAW_DATA", httpresult['content'],- self.__name__, parent)+ self.__name__, parentEvent)self.notifyListeners(event)event = SpiderFootEvent("WEBSERVER_HTTPHEADERS", httpresult['headers'],- self.__name__, parent)+ self.__name__, parentEvent)self.notifyListeners(event)event = SpiderFootEvent("HTTP_CODE", str(httpresult['code']),- self.__name__, parent)+ self.__name__, parentEvent)self.notifyListeners(event)- # Spidering is performed here- def start(self):- # ~*~ Start spidering! ~*~- # First iteration we are starting with links found on the start page- # Iterations after that are based on links found on those pages,- # and so on..+ # Trigger spidering off the following events..+ # Google search provides LINKED_URL_INTERNAL, and DNS lookups+ # provide SUBDOMAIN.+ def watchedEvents(self):+ return [ "LINKED_URL_INTERNAL", "SUBDOMAIN" ]++ # Some other modules may request we spider things+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ spiderTarget = event.data++ # Ignore self-generated events so that we don't end up in a recursive loop+ if "sfp_spider" in srcModuleName:+ sf.debug("Ignoring event from myself.")+ return None++ sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.urlEvents.keys():+ sf.debug("Ignoring " + eventData + " as already spidered.")+ return None+ else:+ self.urlEvents[eventData] = event++ # Determine where to start spidering from if it's a SUBDOMAIN event+ if eventName == "SUBDOMAIN":+ for prefix in self.opts['start']:+ res = sf.fetchUrl(prefix + eventData)+ if res['content'] != None:+ spiderTarget = prefix + eventData+ break++ sf.debug("Initiating spider of " + spiderTarget)++ # Link the spidered URL to the event that triggered it+ self.urlEvents[spiderTarget] = event+ return self.spiderFrom(spiderTarget)++ # Start spidering+ def spiderFrom(self, startingPoint):keepSpidering = True- links = self.processUrl(self.spiderSource) # fetch first pagetotalFetched = 0levelsTraversed = 0nextLinks = dict()+ targetBase = sf.urlBaseUrl(startingPoint)++ # Are we respecting robots.txt?+ if self.opts['robotsonly'] and not self.robotsRules.has_key(targetBase):+ robotsTxt = sf.fetchUrl(targetBase + '/robots.txt')+ if robotsTxt['content'] != None:+ sf.debug('robots.txt contents: ' + robotsTxt['content'])+ self.robotsRules[targetBase] = sf.parseRobotsTxt(robotsTxt['content'])+ else:+ sf.error("Unable to fetch robots.txt and you've asked to abide by its contents.")+ return None++ # First iteration we are starting with links found on the start page+ # Iterations after that are based on links found on those pages,+ # and so on..+ links = self.processUrl(startingPoint) # fetch first page# No links from the first fetch means we've got a problemif links == None:- sf.error("No links found on the first fetch!")+ sf.error("No links found on the first fetch!", exception=False)returnwhile keepSpidering:diff --git a/modules/sfp_stor_db.py b/modules/sfp_stor_db.pyindex 1f46276c..673a06f8 100644--- a/modules/sfp_stor_db.py+++ b/modules/sfp_stor_db.py@@ -51,25 +51,25 @@ class sfp_stor_db(SpiderFootPlugin):return ["*"]# Handle events sent to this module- def handleEvent(self, srcModuleName, eventName, eventSource, eventData):+ def handleEvent(self, sfEvent):+# If we get passed a dict or list, convert it to a string first, as# those types do not have a unicode converter.- if type(eventData) not in [unicode, str]:- eventData = str(eventData)+ if type(sfEvent.data) not in [unicode, str]:+ sfEvent.data = str(sfEvent.data)# Convert to a string in case we get passed integers or other things- if type(eventData) is not unicode:- eventData = unicode(eventData, 'utf-8', errors='ignore')+ if type(sfEvent.data) is not unicode:+ sfEvent.data = unicode(sfEvent.data, 'utf-8', errors='ignore')if self.opts['maxstorage'] != 0:- if len(eventData) > self.opts['maxstorage']:- sf.debug("Truncated " + eventName + " data due to storage limitation")- sfdb.scanEventStore(self.opts['__guid__'], eventName, eventSource,- eventData[0:self.opts['maxstorage']], srcModuleName)+ if len(sfEvent.data) > self.opts['maxstorage']:+ sf.debug("Truncated " + sfEvent.eventType + " data due to storage limitation")+ sfEvent.truncateData(self.opts['maxstorage'])+ sfdb.scanEventStore(self.opts['__guid__'], sfEvent)return None- sfdb.scanEventStore(self.opts['__guid__'], eventName, eventSource,- eventData, srcModuleName)+ sfdb.scanEventStore(self.opts['__guid__'], sfEvent)# End of sfp_stor_db classdiff --git a/modules/sfp_stor_print.py b/modules/sfp_stor_print.pyindex 1e537bc0..b5a03ff1 100644--- a/modules/sfp_stor_print.py+++ b/modules/sfp_stor_print.py@@ -45,7 +45,7 @@ class sfp_stor_print(SpiderFootPlugin):return ["*"]# Handle events sent to this module- def handleEvent(self, srcModuleName, eventName, eventSource, eventData):+ def handleEvent(self, srcModuleName, eventName, eventSource, eventSourceEvent, eventData):sf.debug("RESULT:")sf.debug("\tSource: " + srcModuleName)sf.debug("\tEvent: " + eventName)diff --git a/modules/sfp_subdomain.py b/modules/sfp_subdomain.pyindex c01ea77a..21940ceb 100644--- a/modules/sfp_subdomain.py+++ b/modules/sfp_subdomain.py@@ -12,7 +12,7 @@import sysimport re-from sflib import SpiderFoot, SpiderFootPlugin+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent# SpiderFoot standard lib (must be initialized in __init__)sf = None@@ -41,7 +41,12 @@ class sfp_subdomain(SpiderFootPlugin):return ["RAW_DATA", "LINKED_URL_INTERNAL"]# Handle events sent to this module- def handleEvent(self, srcModuleName, eventName, eventSource, eventData):+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ parentEvent = event.sourceEvent+sf.debug("Received event, " + eventName + ", from " + srcModuleName)matches = re.findall("([a-zA-Z0-9\-\.]+\." + self.baseDomain + ")", eventData,@@ -59,7 +64,8 @@ class sfp_subdomain(SpiderFootPlugin):continueelse:sf.info("New sub-domain/host found: " + match)- self.notifyListeners("SUBDOMAIN", eventSource, match)+ evt = SpiderFootEvent("SUBDOMAIN", match, self.__name__, event)+ self.notifyListeners(evt)self.results[match] = Truereturn Nonediff --git a/modules/sfp_template.py b/modules/sfp_template.pyindex b5dbbb86..243a7341 100644--- a/modules/sfp_template.py+++ b/modules/sfp_template.py@@ -53,7 +53,7 @@ class sfp_XXX(SpiderFootPlugin):return ["RAW_DATA"]# Handle events sent to this module- def handleEvent(self, srcModuleName, eventName, eventSource, eventData):+ def handleEvent(self, srcModuleName, eventName, eventSource, eventSourceEvent, eventData):sf.debug("Received event, " + eventName + ", from " + srcModuleName)return Nonediff --git a/modules/sfp_websvr.py b/modules/sfp_websvr.pyindex 41649c13..33c16123 100644--- a/modules/sfp_websvr.py+++ b/modules/sfp_websvr.py@@ -12,7 +12,7 @@import sysimport re-from sflib import SpiderFoot, SpiderFootPlugin+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent# SpiderFoot standard lib (must be initialized in setup)sf = None@@ -42,7 +42,12 @@ class sfp_websvr(SpiderFootPlugin):return ["WEBSERVER_HTTPHEADERS"]# Handle events sent to this module- def handleEvent(self, srcModuleName, eventName, eventSource, eventData):+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ eventSource = event.sourceEvent.data+sf.debug("Received event, " + eventName + ", from " + srcModuleName)if self.results.has_key(eventSource):return None@@ -58,35 +63,37 @@ class sfp_websvr(SpiderFootPlugin):# possibly OS. This could also trigger additional tests, such as 404s# and other errors to see what the header looks like.if eventData.has_key('server'):- self.notifyListeners("WEBSERVER_BANNER", eventSource, eventData['Server'])+ evt = SpiderFootEvent("WEBSERVER_BANNER", eventData['Server'], self.__name__, event)+ self.notifyListeners(evt)+sf.info("Found web server: " + eventData['Server'] + " (" + eventSource + ")")if (eventData.has_key('x-powered-by')):- self.notifyListeners("WEBSERVER_TECHNOLOGY", eventSource, eventData['x-powered-by'])+ evt = SpiderFootEvent("WEBSERVER_TECHNOLOGY", eventData['x-powered-by'],+ self.__name__, event)+ self.notifyListeners(evt)return None+ tech = Noneif eventData.has_key('set-cookie') and 'PHPSESS' in eventData['set-cookie']:- self.notifyListeners("WEBSERVER_TECHNOLOGY", eventSource, "PHP")- return None+ tech = "PHP"if eventData.has_key('set-cookie') and 'JSESSIONID' in eventData['set-cookie']:- self.notifyListeners("WEBSERVER_TECHNOLOGY", eventSource, "Java/JSP")- return None+ tech = "Java/JSP"if eventData.has_key('set-cookie') and 'ASP.NET' in eventData['set-cookie']:- self.notifyListeners("WEBSERVER_TECHNOLOGY", eventSource, "ASP.NET")- return None+ tech = "ASP.NET"if eventData.has_key('x-aspnet-version'):- self.notifyListeners("WEBSERVER_TECHNOLOGY", eventSource, "ASP.NET")- return None+ tech = "ASP.NET"- if '.jsp' in eventSource:- self.notifyListeners("WEBSERVER_TECHNOLOGY", eventSource, "Java/JSP")- return None+ if tech != None and '.jsp' in eventSource:+ tech = "Java/JSP"- if '.php' in eventSource:- self.notifyListeners("WEBSERVER_TECHNOLOGY", eventSource, "PHP")- return None+ if tech != None and '.php' in eventSource:+ tech = "PHP"++ evt = SpiderFootEvent("WEBSERVER_TECHNOLOGY", tech, self.__name__, event)+ self.notifyListeners(evt)# End of sfp_websvr classdiff --git a/modules/sfp_xref.py b/modules/sfp_xref.pyindex b6876faa..31065e8d 100644--- a/modules/sfp_xref.py+++ b/modules/sfp_xref.py@@ -14,7 +14,7 @@import sysimport re-from sflib import SpiderFoot, SpiderFootPlugin+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent# SpiderFoot standard lib (must be initialized in setup)sf = None@@ -63,7 +63,11 @@ class sfp_xref(SpiderFootPlugin):# Handle events sent to this module# In this module's case, eventData will be the URL or a domain which# was found in some content somewhere.- def handleEvent(self, srcModuleName, eventName, eventSource, eventData):+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+sf.debug("Received event, " + eventName + ", from " + srcModuleName)# The SIMILARDOMAIN event supplies domains, not URLs. Assume HTTP.@@ -105,8 +109,11 @@ class sfp_xref(SpiderFootPlugin):# Check the base url to see if there is an affiliationurl = sf.urlBaseUrl(eventData)res = sf.fetchUrl(url)- matches = re.findall("([\.\'\/\"\ ]" + self.baseDomain + "[\.\'\"\ ])",- res['content'], re.IGNORECASE)+ if res['content'] != None:+ matches = re.findall("([\.\'\/\"\ ]" + self.baseDomain + "[\.\'\"\ ])",+ res['content'], re.IGNORECASE)+ else:+ return Noneif len(matches) > 0:if self.results.has_key(url):@@ -114,9 +121,11 @@ class sfp_xref(SpiderFootPlugin):self.results[url] = Truesf.info("Found affiliate: " + url)- self.notifyListeners("AFFILIATE", eventSource, url)+ evt1 = SpiderFootEvent("AFFILIATE", url, self.__name__, event)+ self.notifyListeners(evt1)if self.opts['checkcontent']:- self.notifyListeners("RAW_DATA", url, res['content'])+ evt2 = SpiderFootEvent("RAW_DATA", res['content'], self.__name__, evt1)+ self.notifyListeners(evt2)return Nonediff --git a/sfdb.py b/sfdb.pyindex 57e2c15d..fde35071 100644--- a/sfdb.py+++ b/sfdb.py@@ -154,10 +154,11 @@ class SpiderFootDb:# Obtain the data for a scan and event typedef scanResultEvent(self, instanceId, eventType='ALL'):- qry = "SELECT DISTINCT ROUND(c.generated) AS generated, c.data, \+ qry = "SELECT ROUND(c.generated) AS generated, c.data, \s.data as 'source_data', \c.module, c.type FROM tbl_scan_results c, tbl_scan_results s \- WHERE c.scan_instance_id = ? AND c.source_event_hash = s.hash"+ WHERE c.scan_instance_id = ? AND c.source_event_hash = s.hash AND \+ s.scan_instance_id = c.scan_instance_id"qvars = [instanceId]if eventType != "ALL":@@ -166,6 +167,8 @@ class SpiderFootDb:qry = qry + " ORDER BY c.data"+ print "QRY: " + qry+try:self.dbh.execute(qry, qvars)return self.dbh.fetchall()diff --git a/sfdbsetup.py b/sfdbsetup.pyindex 8aa290af..21d50242 100644--- a/sfdbsetup.py+++ b/sfdbsetup.py@@ -86,6 +86,7 @@ class SpiderFootDbInit:"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('EMAILADDR', 'Email Address', 0)","INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('GEOINFO', 'Physical Location', 0)","INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('HTTP_CODE', 'HTTP Status Code', 0)",+ "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('INITIAL_TARGET', 'User-Supplied Target', 0)","INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('IP_ADDRESS', 'IP Address', 0)","INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('NETBLOCK', 'Netblock Ownership', 0)","INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('LINKED_URL_INTERNAL', 'Linked URL - Internal', 0)",diff --git a/sflib.py b/sflib.pyindex ef3dea96..4bd21159 100644--- a/sflib.py+++ b/sflib.py@@ -528,9 +528,10 @@ class SpiderFootEvent(object):risk = Nonemodule = Nonedata = None+ sourceEvent = NonesourceEventHash = None- def __init__(self, eventType, data, module, sourceEventHash="ROOT",+ def __init__(self, eventType, data, module, sourceEvent=None,confidence=100, visibility=100, risk=0):self.eventType = eventTypeself.generated = time.time()@@ -539,14 +540,27 @@ class SpiderFootEvent(object):self.risk = riskself.module = moduleself.data = data- self.sourceEventHash = sourceEventHash+ self.sourceEvent = sourceEvent++ # "ROOT" is a special "hash" reserved for elements with no+ # actual parent (e.g. the first page spidered.)+ if sourceEvent != None:+ self.sourceEventHash = sourceEvent.getHash()+ else:+ self.sourceEventHash = "ROOT"# Unique hash of this eventdef getHash(self):- if type(self.data) != unicode:- self.data = unicode(self.data, 'ascii', errors='ignore')+ if self.eventType == "INITIAL_TARGET":+ return "ROOT"++ # Handle lists and dicts+ if type(self.data) != str or type(self.data) != unicode:+ usedata = str(self.data)+ else:+ usedata = unicode(usedata, 'ascii', errors='ignore')- return hashlib.sha256(self.eventType + self.data + \+ return hashlib.sha256(self.eventType + usedata + \unicode(self.generated) + self.module).hexdigest()# Reduce data down to a certain sizediff --git a/sfscan.py b/sfscan.pyindex 66d68837..f4188616 100644--- a/sfscan.py+++ b/sfscan.py@@ -17,7 +17,7 @@ import urllib2import sysfrom copy import deepcopyfrom sfdb import SpiderFootDb-from sflib import SpiderFoot+from sflib import SpiderFoot, SpiderFootEvent# Controls all scanning activity# Eventually change this to be able to control multiple scan instances@@ -116,6 +116,11 @@ class SpiderFootScanner:dbh.scanInstanceSet(self.config['__guid__'], status='RUNNING')self.status = "RUNNING"++ # Create the "ROOT" event which un-triggered modules will link events to+ rootEvent = SpiderFootEvent("INITIAL_TARGET", self.target, "User Input")+ dbh.scanEventStore(self.config['__guid__'], rootEvent)+# Start the modules sequentially.for module in self.moduleInstances.values():# Check in case the user requested to stop the scan between modules initializing