SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.
Python attacksurfacecticybersecurityfootprintinghackinginformation-gatheringinformation-securityinfosecintelligence-gatheringosintosint-frameworkosint-reconnaissanceosint-toolpentestingpythonreconsecurity-toolsthreat-intelligencethreatintel
Scan aborting and bug fixes.
smicallefd3a3e906f99a
diff --git a/dyn/scanlist.tmpl b/dyn/scanlist.tmplindex d23fe3c5..849fa77d 100644--- a/dyn/scanlist.tmpl+++ b/dyn/scanlist.tmpl@@ -7,6 +7,13 @@Scan '${newscan}' has successfully been initiated. Reload this page for up-to-date status on the scan.</div>% endif+% if stoppedscan:+<div class="alert alert-warning">+ <button type="button" class="close" data-dismiss="alert">×</button>+ <h4>Scan aborted.</h4>+ Please allow a minute or two for the scan to cleanly shut itself down.+</div>+% endif<div id=loader>Loading...<div class="progress progress-striped active">@@ -18,12 +25,16 @@ Loading...var table = "<table class='table table-bordered table-striped'>";table += "<thead><tr> <th>Name</th> <th>Target</th> <th>Started</th> <th>Finished</th> <th>Status</th> <th>Events</th> </tr></thead><tbody>";for (var i = 0; i < data.length; i++) {- table += "<tr><td><a href=/scaninfo?id=" + data[i][0] + ">" + data[i][1] + "</a></td>";- table += "<td>" + data[i][2] + " <a target='_new' href='" + data[i][2] + "'><i class='icon-share icon-gray'></a></td>";- table += "<td>" + data[i][3] + "</td>";- table += "<td>" + data[i][5] + "</td>";- table += "<td>" + data[i][6] + "</td>";- table += "<td>" + data[i][7] + "</td></tr>";+ table += "<tr><td><a href=/scaninfo?id=" + data[i][0] + ">" + data[i][1] + "</a></td>";+ table += "<td>" + data[i][2] + " <a target='_new' href='" + data[i][2] + "'><i class='icon-share icon-gray'></a></td>";+ table += "<td>" + data[i][3] + "</td>";+ if (data[i][6] == "RUNNING") {+ table += "<td><a href=/stopscan?id=" + data[i][0] +">Abort</a></td>";+ } else {+ table += "<td>" + data[i][5] + "</td>";+ }+ table += "<td>" + data[i][6] + "</td>";+ table += "<td>" + data[i][7] + "</td></tr>";}table += "</tbody></table>"$("#loader").fadeOut(250);diff --git a/modules/sfp_googlesearch.py b/modules/sfp_googlesearch.pyindex cbf68af1..96e3bf2d 100644--- a/modules/sfp_googlesearch.py+++ b/modules/sfp_googlesearch.py@@ -60,6 +60,10 @@ class sfp_googlesearch(SpiderFootPlugin):if page in self.results:continue+ # Check if we've been asked to stop+ if self.checkForStop():+ return None+self.notifyListeners("WEBCONTENT", page, pages[page])self.results.append(page)@@ -78,6 +82,8 @@ class sfp_googlesearch(SpiderFootPlugin):if baseDom == None:continueif baseDom.endswith(self.baseDomain):+ if self.checkForStop():+ return NonelinkPage = sf.fetchUrl(link)self.notifyListeners("URL", page, link)self.notifyListeners("WEBCONTENT", link, linkPage['content'])diff --git a/modules/sfp_similar.py b/modules/sfp_similar.pyindex 9506d2ec..25a50667 100644--- a/modules/sfp_similar.py+++ b/modules/sfp_similar.py@@ -99,6 +99,10 @@ class sfp_similar(SpiderFootPlugin):# Subsequent iterations have a different URL (in chunks of 16)fetchPage = whoisUrlN.format(keyword, i * whoisIncrement)+ # Check if we've been asked to stop+ if self.checkForStop():+ return None+whois = sf.fetchUrl(fetchPage)if whois['content'] == None:return None@@ -127,6 +131,9 @@ class sfp_similar(SpiderFootPlugin):else:fetchPage = domtoolUrlRight.format(keyword, i)+ if self.checkForStop():+ return None+domtool = sf.fetchUrl(fetchPage)if domtool['content'] == None:return None@@ -158,6 +165,9 @@ class sfp_similar(SpiderFootPlugin):else:fetchPage = namedropUrlRight.format(keyword, i)+ if self.checkForStop():+ return None+namedrop = sf.fetchUrl(fetchPage)if namedrop['content'] == None:return None@@ -184,6 +194,9 @@ class sfp_similar(SpiderFootPlugin):# Inform listening modulesif self.opts['activeonly']:+ if self.checkForStop():+ return None+pageContent = sf.fetchUrl('http://' + result)if pageContent['content'] != None:self.notifyListeners("SIMILARDOMAIN", source, result)diff --git a/modules/sfp_spider.py b/modules/sfp_spider.pyindex dff0c280..aaba7dd5 100644--- a/modules/sfp_spider.py+++ b/modules/sfp_spider.py@@ -212,6 +212,10 @@ class sfp_spider(SpiderFootPlugin):sf.debug("Already fetched " + link + ", skipping.")continue+ # Check if we've been asked to stop+ if self.checkForStop():+ return None+sf.debug("Fetching fresh content from: " + link)time.sleep(self.opts['pause'])freshLinks = self.processUrl(link)@@ -245,6 +249,10 @@ class sfp_spider(SpiderFootPlugin):sf.debug("No more links found to spider, finishing..")keepSpidering = False+ # We've been asked to stop scanning+ if self.checkForStop():+ keepSpidering = False+return# End of sfp_spider classdiff --git a/modules/sfp_template.py b/modules/sfp_template.pyindex 216730b7..a4adb2a9 100644--- a/modules/sfp_template.py+++ b/modules/sfp_template.py@@ -59,6 +59,11 @@ class sfp_XXX(SpiderFootPlugin):return None+ # If you intend for this module to act on its own (e.g. not solely rely+ # on events from other modules, then you need to have a start() method+ # and within that method call self.checkForStop() to see if you've been+ # politely asked by the controller to stop your activities.+# End of sfp_XXX classif __name__ == '__main__':diff --git a/sfdb.py b/sfdb.pyindex 1479e0cc..851a9540 100644--- a/sfdb.py+++ b/sfdb.py@@ -76,7 +76,7 @@ class SpiderFootDb:))self.conn.commit()except sqlite3.Error as e:- sf.fatal("Unable to create instance in DB: " + e.message)+ sf.fatal("Unable to create instance in DB: " + e.args[0])return True@@ -118,7 +118,7 @@ class SpiderFootDb:return self.dbh.fetchone()except sqlite3.Error as e:sf.error("SQL error encountered when retreiving scan instance:" +- e.message)+ e.args[0])# Obtain a summary of the results per event typedef scanResultSummary(self, instanceId):@@ -132,7 +132,7 @@ class SpiderFootDb:return self.dbh.fetchall()except sqlite3.Error as e:sf.error("SQL error encountered when fetching result summary: " +- e.message)+ e.args[0])# Obtain the data for a scan and event typedef scanResultEvent(self, instanceId, eventType):@@ -145,7 +145,7 @@ class SpiderFootDb:return self.dbh.fetchall()except sqlite3.Error as e:sf.error("SQL error encountered when fetching result events: " +- e.message)+ e.args[0])# Delete a scan instance - don't need this yetdef scanInstanceDelete(self, instanceId):@@ -178,7 +178,7 @@ class SpiderFootDb:return Noneexcept sqlite3.Error as e:sf.fatal("SQL error encountered when storing event data (" + str(self.dbh) + ": " +- e.message)+ e.args[0])# List of all previously run scansdef scanInstanceList(self):@@ -199,4 +199,4 @@ class SpiderFootDb:self.dbh.execute(qry)return self.dbh.fetchall()except sqlite3.Error as e:- sf.error("SQL error encountered when fetching scan list: " + e.message)+ sf.error("SQL error encountered when fetching scan list: " + e.args[0])diff --git a/sflib.py b/sflib.pyindex f59177e3..e7e31daa 100644--- a/sflib.py+++ b/sflib.py@@ -257,6 +257,10 @@ class SpiderFoot:self.error("Google doesn't like us right now..")return None+ if firstPage['content'] == None:+ self.error("Failed to fetch content from Google.")+ return None+returnResults[seedUrl] = firstPage['content']matches = re.findall("(\/search\S+start=\d+.[^\'\"]*sa=N)", firstPage['content'])@@ -284,6 +288,10 @@ class SpiderFoot:self.error("Google doesn't like us any more..")return returnResults+ if nextPage['content'] == None:+ self.error("Failed to fetch subsequent content from Google.")+ return returnResults+returnResults[nextUrl] = nextPage['content']matches = re.findall("(\/search\S+start=\d+.[^\'\"]*)", nextPage['content'])@@ -330,7 +338,7 @@ class SpiderFoot:if fatal:self.fatal('URL could not be fetched (' + str(e) + ')')except Exception as x:- self.error("Unexpected exception occurred: " + str(x))+ self.error("Unexpected exception occurred fetching: " + url + "(" + str(x) + ")")result['status'] = str(x)if fatal:self.fatal('URL could not be fetched (' + str(x) + ')')@@ -341,6 +349,8 @@ class SpiderFoot:# SpiderFoot plug-in module base class#class SpiderFootPlugin(object):+ # Will be set to True by the controller if the user aborts scanning+ _stopScanning = False# Modules that will be notified when this module produces events_listenerModules = list()@@ -348,10 +358,11 @@ class SpiderFootPlugin(object):def __init__(self):pass- # Used to clear any listener relationships. This is needed because+ # Used to clear any listener relationships, etc. This is needed because# Python seems to cache local variables even between threads.def clearListeners(self):self._listenerModules = list()+ self._stopScanning = False# Will always be overriden by the implementer.def setup(self, url, userOpts=dict()):@@ -366,6 +377,11 @@ class SpiderFootPlugin(object):# events from this plug-in. Remember that those plug-ins will be called# within the same execution context of this thread, not on their own.def notifyListeners(self, eventName, eventSource, eventData):+ # Check if we've been asked to stop in the meantime, so that+ # notifications stop triggering module activity.+ if self.checkForStop():+ return None+if self.opts.has_key('blocknotif') and self.opts['_blocknotif']:#print "Notifications blocked for " + eventName + " to " + listener.__module__return None@@ -377,11 +393,19 @@ class SpiderFootPlugin(object):for listener in self._listenerModules:#print listener.__module__ + ": " + listener.watchedEvents().__str__()if eventName not in listener.watchedEvents() and '*' not in listener.watchedEvents():- #print listener.__module__ + " not listening for " + eventName+ #print listener.__module__ + " not listening for " + eventNamecontinue#print "Notifying " + eventName + " to " + listener.__module__listener.handleEvent(self.__module__, eventName, eventSource, eventData)+ # Called to stop scanning+ def stopScanning(self):+ self._stopScanning = True++ # For modules to use to check for when they should give back control+ def checkForStop(self):+ return self._stopScanning+# Return a list of the default configuration options for the module.def defaultOpts(self):return self.optsdiff --git a/sfwebui.py b/sfwebui.pyindex 983c1f52..d13b4ef8 100644--- a/sfwebui.py+++ b/sfwebui.py@@ -22,6 +22,7 @@ from sfdb import SpiderFootDb# provides data for calls to /scanlist (scanlist())class SpiderFootDataProvider:config = None+ moduleInstances = Nonedef __init__(self, config):self.config = config@@ -66,59 +67,79 @@ class SpiderFootDataProvider:def startScan(self, name, target, moduleList, moduleOpts):dbh = SpiderFootDb(self.config)- moduleInstances = dict()+ self.moduleInstances = dict()+ aborted = False# Take a copy of the configurationsfConfig = self.config# Create a unique ID for this scan and create it in the back-end DB.sfConfig['__guid__'] = dbh.scanInstanceGenGUID(target)dbh.scanInstanceCreate(sfConfig['__guid__'], name, target)- dbh.scanInstanceSet(sfConfig['__guid__'], time.time() * 1000, None, 'STARTED')+ dbh.scanInstanceSet(sfConfig['__guid__'], time.time() * 1000, None, 'STARTING')print "Scan [" + sfConfig['__guid__'] + "] initiated."# moduleList = list of modules the user wants to run- for modName in moduleList:- if modName == '':- continue-- module = __import__('modules.' + modName, globals(), locals(), [modName])- mod = getattr(module, modName)()-- # Build up config to consist of general and module-specific config- # to override defaults within the module itself- # *** Modules are not yet configurable via the UI ***- sfConfig.update(moduleOpts)-- # A bit hacky: we pass the database object as part of the config. This- # object should only be used by the internal SpiderFoot modules writing- # to the database, which at present is only sfp_stor_db.- # Individual modules cannot create their own SpiderFootDb instance or- # we'll get database locking issues, so it all goes through this.- sfConfig['__sfdb__'] = dbh-- # Set up the module- mod.clearListeners() # clear any listener relationships from the past- mod.setup(target, sfConfig)- moduleInstances[modName] = mod- print modName + " module loaded."-- # Register listener modules and then start all modules sequentially- for module in moduleInstances.values():- for listenerModule in moduleInstances.values():- # Careful not to register twice or you will get duplicate events- if listenerModule in module._listenerModules:- continue- if listenerModule != module and listenerModule.watchedEvents() != None:- module.registerListener(listenerModule)-- # Start the modules sequentially.- for module in moduleInstances.values():- module.start()-- print "Scan [" + sfConfig['__guid__'] + "] completed."- dbh.scanInstanceSet(sfConfig['__guid__'], None, time.time() * 1000, 'FINISHED')- dbh.close()+ try:+ for modName in moduleList:+ if modName == '':+ continue++ module = __import__('modules.' + modName, globals(), locals(), [modName])+ mod = getattr(module, modName)()++ # Build up config to consist of general and module-specific config+ # to override defaults within the module itself+ # *** Modules are not yet configurable via the UI ***+ sfConfig.update(moduleOpts)++ # A bit hacky: we pass the database object as part of the config. This+ # object should only be used by the internal SpiderFoot modules writing+ # to the database, which at present is only sfp_stor_db.+ # Individual modules cannot create their own SpiderFootDb instance or+ # we'll get database locking issues, so it all goes through this.+ sfConfig['__sfdb__'] = dbh++ # Set up the module+ mod.clearListeners() # clear any listener relationships from the past+ mod.setup(target, sfConfig)+ self.moduleInstances[modName] = mod+ print modName + " module loaded."++ # Register listener modules and then start all modules sequentially+ for module in self.moduleInstances.values():+ for listenerModule in self.moduleInstances.values():+ # Careful not to register twice or you will get duplicate events+ if listenerModule in module._listenerModules:+ continue+ if listenerModule != module and listenerModule.watchedEvents() != None:+ module.registerListener(listenerModule)++ dbh.scanInstanceSet(sfConfig['__guid__'], status='RUNNING')+ # Start the modules sequentially.+ for module in self.moduleInstances.values():+ # Check in case the user requested to stop the scan between modules initializing+ if module.checkForStop():+ dbh.scanInstanceSet(sfConfig['__guid__'], status='ABORTING')+ aborted = True+ break+ module.start()++ # Check if any of the modules ended due to being stopped+ for module in self.moduleInstances.values():+ if module.checkForStop():+ aborted = True++ if aborted:+ print "Scan [" + sfConfig['__guid__'] + "] aborted."+ dbh.scanInstanceSet(sfConfig['__guid__'], None, time.time() * 1000, 'ABORTED')+ else:+ print "Scan [" + sfConfig['__guid__'] + "] completed."+ dbh.scanInstanceSet(sfConfig['__guid__'], None, time.time() * 1000, 'FINISHED')+ except Exception:+ print "Scan [" + sfConfig['__guid__'] + "] failed."+ dbh.scanInstanceSet(sfConfig['__guid__'], None, time.time() * 1000, 'ERROR-FAILED')+ dbh.close()class SpiderFootWebUi:dp = None@@ -196,15 +217,22 @@ class SpiderFootWebUi:templ = Template(filename='dyn/newscan.tmpl', lookup=self.lookup)return templ.render(modules=self.config['__modules__'], alreadyRunning=True, runningScan=thread.name[3:])+ # Start running a new scanprint "Spawning thread for new scan..."t = threading.Thread(name="SF_" + scanname, target=self.dp.startScan, args=(scanname, scantarget, modlist, modopts))t.start()+templ = Template(filename='dyn/scanlist.tmpl', lookup=self.lookup)return templ.render(pageid='SCANLIST',newscan=scanname)startscan.exposed = True- # Stop a scan+ # Stop a scan (id variable is unnecessary for now given that only one simultaneous+ # scan is permitted.)def stopscan(self, id):- return self.dp.stopScan(id)+ for modName in self.dp.moduleInstances.keys():+ print "Signalling module " + modName + " to stop."+ self.dp.moduleInstances[modName].stopScanning()+ templ = Template(filename='dyn/scanlist.tmpl', lookup=self.lookup)+ return templ.render(pageid='SCANLIST',stoppedscan=True)stopscan.exposed = True