SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.
Python attacksurfacecticybersecurityfootprintinghackinginformation-gatheringinformation-securityinfosecintelligence-gatheringosintosint-frameworkosint-reconnaissanceosint-toolpentestingpythonreconsecurity-toolsthreat-intelligencethreatintel
Visualization and other functionality.
smicallef94b4d0f87a43
diff --git a/sfdb.py b/sfdb.pyindex 9cf25ce8..6700b66f 100644--- a/sfdb.py+++ b/sfdb.py@@ -161,6 +161,16 @@ class SpiderFootDb:def close(self):self.dbh.close()+ # Get event types+ def eventTypes(self):+ qry = "SELECT event_descr, event, event_raw FROM tbl_event_types"+ try:+ self.dbh.execute(qry)+ return self.dbh.fetchall()+ except sqlite3.Error as e:+ sf.error("SQL error encountered when retreiving event types:" ++ e.args[0])+# Log an event to the databasedef scanLogEvent(self, instanceId, classification, message, component=None):if component == None:@@ -266,10 +276,13 @@ class SpiderFootDb:def scanResultEvent(self, instanceId, eventType='ALL'):qry = "SELECT ROUND(c.generated) AS generated, c.data, \s.data as 'source_data', \- c.module, c.type, c.confidence, c.visibility, c.risk, c.hash \- FROM tbl_scan_results c, tbl_scan_results s \+ c.module, c.type, c.confidence, c.visibility, c.risk, c.hash, \+ c.source_event_hash, t.event_descr \+ FROM tbl_scan_results c, tbl_scan_results s, tbl_event_types t \WHERE c.scan_instance_id = ? AND c.source_event_hash = s.hash AND \- s.scan_instance_id = c.scan_instance_id"+ s.scan_instance_id = c.scan_instance_id AND \+ t.event = c.type"+qvars = [instanceId]if eventType != "ALL":@@ -502,3 +515,29 @@ class SpiderFootDb:except sqlite3.Error as e:sf.error("SQL error encountered when fetching scan history: " + e.args[0])++ # Get the source IDs, types and data for a set of IDs+ def scanElementSources(self, instanceId, elementIdList):+ # the output of this needs to be aligned with scanResultEvent,+ # as other functions call both expecting the same output.+ qry = "SELECT ROUND(c.generated) AS generated, c.data, \+ s.data as 'source_data', \+ c.module, c.type, c.confidence, c.visibility, c.risk, c.hash, \+ c.source_event_hash, t.event_descr \+ FROM tbl_scan_results c, tbl_scan_results s, tbl_event_types t \+ WHERE c.scan_instance_id = ? AND c.source_event_hash = s.hash AND \+ s.scan_instance_id = c.scan_instance_id AND \+ t.event = c.type AND c.hash in ("+ qvars = [instanceId]++ for hashId in elementIdList:+ qry = qry + "'" + hashId + "',"+ qry = qry + "'')"++ try:+ self.dbh.execute(qry, qvars)+ return self.dbh.fetchall()+ except sqlite3.Error as e:+ sf.error("SQL error encountered when getting source element IDs: " + e.args[0])++diff --git a/sflib.py b/sflib.pyindex 9b10749f..9b1b9b88 100644--- a/sflib.py+++ b/sflib.py@@ -395,6 +395,50 @@ class SpiderFoot:return Falsereturn True+ # 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] == 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] == None:+ continue++ contender = True+ for ck in data.keys():+ if data[ck] == None:+ continue++ if k in data[ck]:+ contender = False++ if contender:+ root = k+ break++ if root == 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#@@ -620,11 +664,6 @@ class SpiderFootPlugin(object):eventData = sfEvent.datastoreOnly = False # Under some conditions, only store and don't notify- # Check if we've been asked to stop in the meantime, so that- # notifications stop triggering module activity.- if self.checkForStop():- return None-if eventData == None or (type(eventData) is unicode and len(eventData) == 0):#print "No data to send for " + eventName + " to " + listener.__module__return None@@ -665,6 +704,12 @@ class SpiderFootPlugin(object):#print "Notifying " + eventName + " to " + listener.__module__listener._currentEvent = sfEvent++ # Check if we've been asked to stop in the meantime, so that+ # notifications stop triggering module activity.+ if self.checkForStop():+ return None+listener.handleEvent(sfEvent)# Called to stop scanning@@ -687,6 +732,12 @@ class SpiderFootPlugin(object):def watchedEvents(self):return [ '*' ]+ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return None+# Handle events to this module# Will usually be overriden by the implementer, unless it doesn't handle# any events.diff --git a/sfwebui.py b/sfwebui.pyindex 2f7d0d6e..da1e049a 100644--- a/sfwebui.py+++ b/sfwebui.py@@ -104,8 +104,11 @@ class SpiderFootWebUi:# Configure a new scandef newscan(self):+ dbh = SpiderFootDb(self.config)+ types = dbh.eventTypes()templ = Template(filename='dyn/newscan.tmpl', lookup=self.lookup)- return templ.render(pageid='NEWSCAN', modules=self.config['__modules__'])+ return templ.render(pageid='NEWSCAN', types=types,+ modules=self.config['__modules__'])newscan.exposed = True# Main page listing scans available@@ -231,7 +234,8 @@ class SpiderFootWebUi:retdata = []for row in data:generated = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(row[0]/1000))- retdata.append([generated, row[1], row[2], cgi.escape(row[3])])+ retdata.append([generated, row[1], row[2],+ cgi.escape(unicode(row[3], errors='replace'))])return json.dumps(retdata)scanlog.exposed = True@@ -273,10 +277,10 @@ class SpiderFootWebUi:retdata = []for row in data:lastseen = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(row[0]))- escaped = cgi.escape(row[1])- # For debug- retdata.append([lastseen, escaped, row[2], row[3], row[5], row[6], row[7], row[8]])- #retdata.append([lastseen, escaped, row[2], row[3], row[5], row[6], row[7]])+ escapeddata = cgi.escape(row[1])+ escapedsrc = cgi.escape(row[2])+ retdata.append([lastseen, escapeddata, escapedsrc,+ row[3], row[5], row[6], row[7], row[8]])return json.dumps(retdata, ensure_ascii=False)scaneventresults.exposed = True@@ -287,7 +291,7 @@ class SpiderFootWebUi:retdata = []for row in data:escaped = cgi.escape(row[0])- retdata.append([escaped, row[1]])+ retdata.append([escaped, row[1], row[2]])return json.dumps(retdata, ensure_ascii=False)scaneventresultsunique.exposed = True@@ -298,3 +302,65 @@ class SpiderFootWebUi:return json.dumps(data, ensure_ascii=False)scanhistory.exposed = True+ def scanelementtypediscovery(self, id, eventType):+ keepGoing = True+ sf = SpiderFoot(self.config)+ dbh = SpiderFootDb(self.config)+ pc = dict()+ datamap = dict()++ # Get the events we will be tracing back from+ leafSet = dbh.scanResultEvent(id, eventType)++ # Get the first round of source IDs for the leafs+ nextIds = list()+ for row in leafSet:+ # these must be unique values!+ parentId = row[9]+ childId = row[8]+ datamap[childId] = row++ if pc.has_key(parentId):+ if childId not in pc[parentId]:+ pc[parentId].append(childId)+ else:+ pc[parentId] = [ childId ]++ # parents of the leaf set+ if parentId not in nextIds:+ nextIds.append(parentId)++ while keepGoing:+ #print "Next IDs: " + str(nextIds)+ parentSet = dbh.scanElementSources(id, nextIds)+ nextIds = list()+ keepGoing = False++ for row in parentSet:+ parentId = row[9]+ childId = row[8]+ datamap[childId] = row++ # Prevent us from looping at root+ # 0 = event_hash and 3 = source_event_hash+ if row[8] == "ROOT" and row[9] == "ROOT":+ continue++ if pc.has_key(parentId):+ if childId not in pc[parentId]:+ pc[parentId].append(childId)+ else:+ pc[parentId] = [ childId ]+ if parentId not in nextIds:+ nextIds.append(parentId)+ # Stop until we've found ROOT+ # 3 = source_event_hash+ if row[3] != "ROOT":+ keepGoing = True++ #print pc+ retdata = dict()+ retdata['tree'] = sf.dataParentChildToTree(pc)+ retdata['data'] = datamap+ return json.dumps(retdata, ensure_ascii=False)+ scanelementtypediscovery.exposed = Truediff --git a/static/js/viz.js b/static/js/viz.jsindex 1aa5c930..0e0a0448 100644--- a/static/js/viz.js+++ b/static/js/viz.js@@ -69,8 +69,11 @@ function sf_viz_countLevels(arg, levelsDeep, maxLevels) {return [ levels, max ];}-function sf_viz_dendrogram(targetId, plotData) {- var width = sf_viz_countLevels([plotData], 0, 0)[1] * 150;+function sf_viz_dendrogram(targetId, data) {+ var plotData = data['tree'];+ var dataMap = data['data'];+ console.dir(dataMap);+ var width = sf_viz_countLevels([plotData], 0, 0)[1] * 120;var height = sf_viz_countTailNodes([plotData]) * 20;if (width < 600) {@@ -108,7 +111,7 @@ function sf_viz_dendrogram(targetId, plotData) {.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; }).on("mouseover", function(d, i) {d3.select(this).style("fill", "silver");- showToolTip(d.name, d3.event.pageX+10, d3.event.pageY+10,true);+ showToolTip(buildPopupMessage(dataMap[d.name]), d3.event.pageX+10, d3.event.pageY+10,true);}).on("mouseout", function() {d3.select(this).style("fill", "black");@@ -119,13 +122,38 @@ function sf_viz_dendrogram(targetId, plotData) {.attr("r", 4.5);node.append("text")- .attr("dx", function(d) { return d.children ? -8 : 8; })+ .attr("dx", function(d) {+ if (d.depth == 0) {+ return 50;+ }++ return d.children ? -8 : 8;+ }).attr("dy", 3).style("text-anchor", function(d) { return d.children ? "end" : "start"; })- .text(function(d) { return 'something'; });+ .text(function(d) {+ if (dataMap[d.name][1].length > 20) {+ return dataMap[d.name][1].substring(0, 20) + "...";+ } else {+ return dataMap[d.name][1];+ }+ });d3.select(targetId).style("height", height + "px");+ function buildPopupMessage(data) {+ if (data[1].length > 200) {+ data[1] = data[1].substring(0, 200) + "...";+ }+ data[1] = data[1].replace("<", "<").replace(">", ">");+ message = "<table>";+ message += "<tr><td><b>Type:</b></td><td>" + data[10] + "</td></tr>";+ message += "<tr><td><b>Source Module:</b></td><td>" + data[3] + "</td></tr>";+ message += "<tr><td><b>Data:</b></td><td>" + data[1] + "</td></tr>";+ message += "</table>";+ return message;+ }+function showToolTip(pMessage,pX,pY,pShow) {if (typeof(tooltipDivID)=="undefined") {tooltipDivID =$('<div id="messageToolTipDiv" style="position:absolute;display:block;z-index:10000;border:2px solid black;background-color:rgba(0,0,0,0.8);margin:auto;padding:3px 5px 3px 5px;color:white;font-size:12px;font-family:arial;border-radius: 5px;vertical-align: middle;text-align: center;min-width:50px;overflow:auto;"></div>');