Skip to content

SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.

Bug fixes, re-structuring, RIPE search.

smicallefc90ec677217b
diff --git a/dyn/newscan.tmpl b/dyn/newscan.tmpl
index c235f125..45e86523 100644
--- a/dyn/newscan.tmpl
+++ b/dyn/newscan.tmpl
@@ -27,9 +27,9 @@ Another scan is currently running (${runningScan}). Please either wait for that
</div>
</div>
<div class="control-group">
- <label class="control-label" for="scantarget">Target Domain</label>
+ <label class="control-label" for="scantarget">Seed URL</label>
<div class="controls">
- <input type="text" id="scantarget" name="scantarget" placeholder="The domain-name to target.">
+ <input type="text" id="scantarget" name="scantarget" placeholder="e.g. http://www.scantarget.com">
</div>
</div>
<div class="control-group">
diff --git a/dyn/scaninfo.tmpl b/dyn/scaninfo.tmpl
index f8215acc..7e5d82a6 100644
--- a/dyn/scaninfo.tmpl
+++ b/dyn/scaninfo.tmpl
@@ -1,5 +1,5 @@
<%include file="HEADER.tmpl"/>
-<h2>${name} <img id=loader src=/static/img/loader.gif></h2>
+<h2>${name} &nbsp;<img id=loader src=/static/img/loader.gif></h2>
<div class="btn-toolbar">
<div class="btn-group">
<a id='btn-browse' class="btn active" href="#" onClick='browseEventList("${id}")'>Browse</a>
@@ -70,7 +70,7 @@
function exportEventData(instanceId, eventType) {
$("#loader").show();
var efr = document.getElementById('exportframe');
- efr.src = '/scaneventresultexport?id=' + instanceId + '&eventType=' + eventType;
+ efr.src = '/scaneventresultexport?id=' + instanceId + '&type=' + eventType;
$("#loader").fadeOut(500);
}
diff --git a/dyn/scanlist.tmpl b/dyn/scanlist.tmpl
index 19a0e193..d5adb75e 100644
--- a/dyn/scanlist.tmpl
+++ b/dyn/scanlist.tmpl
@@ -1,5 +1,5 @@
<%include file="HEADER.tmpl"/>
- <h2>Scans<img id=loader src=/static/img/loader.gif></h2>
+ <h2>Scans &nbsp;<img id=loader src=/static/img/loader.gif></h2>
% if newscan:
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert">&times;</button>
diff --git a/evtypes.sql b/evtypes.sql
index 3eb933f0..bbdad3cb 100644
--- a/evtypes.sql
+++ b/evtypes.sql
@@ -6,6 +6,7 @@ INSERT INTO tbl_event_types (event, event_descr) VALUES ('EMAILADDR', 'Email Add
INSERT INTO tbl_event_types (event, event_descr) VALUES ('GEOINFO', 'Physical Location')
INSERT INTO tbl_event_types (event, event_descr) VALUES ('HTTP_CODE', 'HTTP Status Code');
INSERT INTO tbl_event_types (event, event_descr) VALUES ('IP_ADDRESS', 'IP Address');
+INSERT INTO tbl_event_types (event, event_descr) VALUES ('NETBLOCK', 'Netblock Ownership');
INSERT INTO tbl_event_types (event, event_descr) VALUES ('SUBDOMAIN', 'Sub-domain');
INSERT INTO tbl_event_types (event, event_descr) VALUES ('SIMILARDOMAIN', 'Similar Domain');
INSERT INTO tbl_event_types (event, event_descr) VALUES ('TCP_PORT_OPEN', 'Open TCP Port');
@@ -20,3 +21,4 @@ INSERT INTO tbl_event_types (event, event_descr) VALUES ('WEBCONTENT_PASSWORD',
INSERT INTO tbl_event_types (event, event_descr) VALUES ('WEBCONTENT_UPLOAD', 'Web Content (Accepts Uploads)');
INSERT INTO tbl_event_types (event, event_descr) VALUES ('WEBSERVER_BANNER', 'Web Server');
INSERT INTO tbl_event_types (event, event_descr) VALUES ('WEBSERVER_HTTPHEADERS', 'HTTP Headers');
+INSERT INTO tbl_event_types (event, event_descr) VALUES ('WEBSERVER_TECHNOLOGY', 'Web Technology');
diff --git a/modules/sfp_dns.py b/modules/sfp_dns.py
index 5dd43648..d6658dac 100644
--- a/modules/sfp_dns.py
+++ b/modules/sfp_dns.py
@@ -36,7 +36,7 @@ class sfp_dns(SpiderFootPlugin):
# Option descriptions
optdescs = {
'resolveaffiliate': "Obtain IPs for confirmed affiliates?",
- 'reverselookup': "Obtain new URLs and more based on reverse-resolved IPs?"
+ 'reverselookup': "Obtain new URLs and possible affiliates based on reverse-resolved IPs?"
}
# URL this instance is working on
diff --git a/modules/sfp_googlesearch.py b/modules/sfp_googlesearch.py
index 6822db5d..3e9252b7 100644
--- a/modules/sfp_googlesearch.py
+++ b/modules/sfp_googlesearch.py
@@ -10,7 +10,9 @@
#-------------------------------------------------------------------------------
import sys
+import random
import re
+import time
from sflib import SpiderFoot, SpiderFootPlugin
# SpiderFoot standard lib (must be initialized in setup)
@@ -60,9 +62,79 @@ class sfp_googlesearch(SpiderFootPlugin):
def watchedEvents(self):
return None
+ # Scrape Google for content, starting at startUrl and iterating through
+ # results based on options supplied. Will return a dictionary of all pages
+ # fetched and their contents {page => content}.
+ # Options accepted:
+ # limit: number of search result pages before returning, default is 10
+ # nopause: don't randomly pause between fetches
+ def googleIterate(self, searchString, opts=dict()):
+ limit = 10
+ fetches = 0
+ returnResults = dict()
+
+ if opts.has_key('limit'):
+ limit = opts['limit']
+
+ # We attempt to make the URL look as authentically human as possible
+ seedUrl = "http://www.google.com/search?q={0}".format(searchString) + \
+ "&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a"
+ firstPage = sf.fetchUrl(seedUrl)
+ if firstPage['code'] == "403":
+ sf.error("Google doesn't like us right now..")
+ return None
+
+ if firstPage['content'] == None:
+ sf.error("Failed to fetch content from Google.")
+ return None
+
+ returnResults[seedUrl] = firstPage['content']
+
+ matches = re.findall("(\/search\S+start=\d+.[^\'\"]*sa=N)", firstPage['content'])
+ while matches > 0 and fetches < limit:
+ nextUrl = None
+ fetches += 1
+ for match in matches:
+ # Google moves in increments of 10
+ if "start=" + str(fetches*10) in match:
+ nextUrl = match.replace("&amp;", "&")
+
+ if nextUrl == None:
+ sf.debug("Nothing left to scan for in Google results.")
+ return returnResults
+ sf.debug("Next Google URL: " + nextUrl)
+
+ # Wait for a random number of seconds between fetches
+ if not opts.has_key('nopause'):
+ pauseSecs = random.randint(4, 15)
+ sf.debug("Pausing for " + str(pauseSecs))
+ time.sleep(pauseSecs)
+
+ # Check if we've been asked to stop
+ if self.checkForStop():
+ return None
+
+ nextPage = sf.fetchUrl('http://www.google.com' + nextUrl)
+ if firstPage['code'] == 403:
+ sf.error("Google doesn't like us any more..")
+ return returnResults
+
+ if nextPage['content'] == None:
+ sf.error("Failed to fetch subsequent content from Google.")
+ return returnResults
+
+ returnResults[nextUrl] = nextPage['content']
+ matches = re.findall("(\/search\S+start=\d+.[^\'\"]*)", nextPage['content'])
+
+ return returnResults
+
def start(self):
# Sites hosted on the domain
- pages = sf.googleIterate("site:" + self.baseDomain, dict(limit=self.opts['pages']))
+ pages = self.googleIterate("site:" + self.baseDomain, dict(limit=self.opts['pages']))
+ if pages == None:
+ sf.debug("No results returned from Google.")
+ return None
+
for page in pages.keys():
if page in self.results:
continue
diff --git a/modules/sfp_ripe.py b/modules/sfp_ripe.py
new file mode 100644
index 00000000..c74f1e06
--- /dev/null
+++ b/modules/sfp_ripe.py
@@ -0,0 +1,102 @@
+#-------------------------------------------------------------------------------
+# Name: sfp_ripe
+# Purpose: Some RIPE (http://stat.ripe.net) queries to get netblocks owned
+# and other bits of info.
+#
+# Author: Steve Micallef <[email protected]>
+#
+# Created: 11/03/2013
+# Copyright: (c) Steve Micallef 2013
+# Licence: GPL
+#-------------------------------------------------------------------------------
+
+import sys
+import re
+import json
+import socket
+from sflib import SpiderFoot, SpiderFootPlugin
+
+# SpiderFoot standard lib (must be initialized in setup)
+sf = None
+
+class sfp_ripe(SpiderFootPlugin):
+ """Queries RIPE to identify netblocks and other info."""
+
+ # Default options
+ opts = {
+ # These must always be set
+ '__debug': True,
+ '__debugfilter': ''
+ }
+
+ # URL this instance is working on
+ seedUrl = None
+ baseDomain = None # calculated from the URL in setup
+ results = dict()
+
+ def setup(self, url, userOpts=dict()):
+ global sf
+ self.seedUrl = url
+ self.results = dict()
+
+ for opt in userOpts.keys():
+ self.opts[opt] = userOpts[opt]
+
+ # For error reporting, debug, etc.
+ sf = SpiderFoot(self.opts)
+
+ # Extract the 'meaningful' part of the FQDN from the URL
+ self.baseDomain = sf.urlBaseDom(self.seedUrl)
+ sf.debug('Base Domain: ' + self.baseDomain)
+
+ # What events is this module interested in for input
+ def watchedEvents(self):
+ return ['IP_ADDRESS', 'SUBDOMAIN']
+
+ # Handle events sent to this module
+ def handleEvent(self, srcModuleName, eventName, eventSource, eventData):
+ sf.debug("Received event, " + eventName + ", from " + srcModuleName)
+
+ # Don't look up stuff twice
+ if self.results.has_key(eventData):
+ sf.debug("Skipping " + eventData + " as already mapped.")
+ return None
+ else:
+ self.results[eventData] = True
+
+ if eventName == 'SUBDOMAIN':
+ res = sf.fetchUrl("http://stat.ripe.net/data/dns-chain/data.json?resource=" + eventData)
+ if res['content'] == None:
+ sf.debug("No RIPE info found/available for " + eventData)
+ return None
+
+ # Just send the content off for others to process
+ self.notifyListeners("WEBCONTENT", eventData, res['content'])
+ return None
+
+ # First get the netblock the IP resides on
+ res = sf.fetchUrl("http://stat.ripe.net/data/network-info/data.json?resource=" + eventData)
+ if res['content'] == None:
+ sf.debug("No RIPE info found/available for " + eventData)
+ return None
+
+ j = json.loads(res['content'])
+ prefix = j["data"]["prefix"]
+ # Now see who owns the prefix
+ res = sf.fetchUrl("http://stat.ripe.net/data/whois/data.json?resource=" + prefix)
+ if res['content'] == None:
+ sf.debug("No RIPE info found/available for prefix: " + prefix)
+ return None
+
+ # Crude..
+ if self.baseDomain in res['content']:
+ self.notifyListeners("NETBLOCK", eventData, prefix)
+ self.notifyListeners("WEBCONTENT", eventData, res['content'])
+
+ return None
+
+# End of sfp_ripe class
+
+if __name__ == '__main__':
+ print "This module cannot be run stand-alone."
+ exit(-1)
diff --git a/modules/sfp_spider.py b/modules/sfp_spider.py
index 4bf0c6f2..366278bb 100644
--- a/modules/sfp_spider.py
+++ b/modules/sfp_spider.py
@@ -108,7 +108,7 @@ class sfp_spider(SpiderFootPlugin):
if source != None:
self.results[url]['source'] = source
- if self.baseDomain + "/" in url:
+ if self.baseDomain == sf.urlBaseDom(url):
self.notifyListeners("URL_INTERNAL", source, url)
else:
self.notifyListeners("URL_EXTERNAL", source, url)
@@ -156,7 +156,7 @@ class sfp_spider(SpiderFootPlugin):
sf.debug("No links found at " + url)
return None
- #sf.debug('Links found from parsing: ' + str(links))
+ sf.debug('Links found from parsing: ' + str(links))
return links
# Clear out links that we don't want to follow
diff --git a/modules/sfp_stor_db.py b/modules/sfp_stor_db.py
index 421543d7..058ecd35 100644
--- a/modules/sfp_stor_db.py
+++ b/modules/sfp_stor_db.py
@@ -60,12 +60,15 @@ class sfp_stor_db(SpiderFootPlugin):
def handleEvent(self, srcModuleName, eventName, eventSource, eventData):
# Convert to a string in case we get passed integers or other things
eventData = str(eventData)
- if self.opts['maxstorage'] != 0 and len(eventData) > self.opts['maxstorage']:
- sfdb.scanEventStore(self.opts['__guid__'], eventName, eventSource,
- eventData[0:self.opts['maxstorage']], srcModuleName)
- else:
- sfdb.scanEventStore(self.opts['__guid__'], eventName, eventSource,
- eventData, srcModuleName)
+ 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)
+ return None
+
+ sfdb.scanEventStore(self.opts['__guid__'], eventName, eventSource,
+ eventData, srcModuleName)
# End of sfp_stor_db class
diff --git a/modules/sfp_websvr.py b/modules/sfp_websvr.py
index d690bccb..9d28abcf 100644
--- a/modules/sfp_websvr.py
+++ b/modules/sfp_websvr.py
@@ -59,15 +59,45 @@ class sfp_websvr(SpiderFootPlugin):
else:
self.results[eventSource] = True
+ if sf.urlBaseDom(eventSource) != self.baseDomain:
+ sf.debug("Not collecting web server information for external sites.")
+ return None
+
# Could apply some smarts here, for instance looking for certain
# banners and therefore classifying them further (type and version,
# possibly OS. This could also trigger additional tests, such as 404s
# and other errors to see what the header looks like.
- if sf.urlBaseDom(eventSource) == self.baseDomain and eventData.has_key('server'):
+ if eventData.has_key('server'):
self.notifyListeners("WEBSERVER_BANNER", eventSource, eventData['Server'])
sf.debug("Found web server: " + eventData['Server'] + " (" + eventSource + ")")
- return None
+ if (eventData.has_key('x-powered-by')):
+ self.notifyListeners("WEBSERVER_TECHNOLOGY", eventSource, eventData['x-powered-by'])
+ return None
+
+ if eventData.has_key('set-cookie') and 'PHPSESS' in eventData['set-cookie']:
+ self.notifyListeners("WEBSERVER_TECHNOLOGY", eventSource, "PHP")
+ return None
+
+ if eventData.has_key('set-cookie') and 'JSESSIONID' in eventData['set-cookie']:
+ self.notifyListeners("WEBSERVER_TECHNOLOGY", eventSource, "Java/JSP")
+ return None
+
+ if eventData.has_key('set-cookie') and 'ASP.NET' in eventData['set-cookie']:
+ self.notifyListeners("WEBSERVER_TECHNOLOGY", eventSource, "ASP.NET")
+ return None
+
+ if eventData.has_key('x-aspnet-version'):
+ self.notifyListeners("WEBSERVER_TECHNOLOGY", eventSource, "ASP.NET")
+ return None
+
+ if '.jsp' in eventSource:
+ self.notifyListeners("WEBSERVER_TECHNOLOGY", eventSource, "Java/JSP")
+ return None
+
+ if '.php' in eventSource:
+ self.notifyListeners("WEBSERVER_TECHNOLOGY", eventSource, "PHP")
+ return None
# End of sfp_websvr class
diff --git a/sfdb.py b/sfdb.py
index cfa4df85..8df8c098 100644
--- a/sfdb.py
+++ b/sfdb.py
@@ -126,7 +126,7 @@ class SpiderFootDb:
qry = "SELECT r.event, e.event_descr, max(ROUND(generated))/1000 AS last_in, \
count(*) AS total FROM \
tbl_scan_results r, tbl_event_types e WHERE e.event = r.event \
- AND r.scan_instance_id = ? GROUP BY r.event"
+ AND r.scan_instance_id = ? GROUP BY r.event ORDER BY e.event_descr"
qvars = [instanceId]
try:
self.dbh.execute(qry, qvars)
@@ -265,6 +265,8 @@ class SpiderFootDb:
qvals = [instanceId, time.time() * 1000, eventName, eventSource,
eventData.__str__(), eventDataSource]
+ #print "STORING: " + str(qvals)
+
try:
self.dbh.execute(qry, qvals)
self.conn.commit()
diff --git a/sfdbsetup.py b/sfdbsetup.py
index f89de644..1c7d4f38 100644
--- a/sfdbsetup.py
+++ b/sfdbsetup.py
@@ -72,6 +72,7 @@ class SpiderFootDbInit:
"INSERT INTO tbl_event_types (event, event_descr) VALUES ('GEOINFO', 'Physical Location')",
"INSERT INTO tbl_event_types (event, event_descr) VALUES ('HTTP_CODE', 'HTTP Status Code')",
"INSERT INTO tbl_event_types (event, event_descr) VALUES ('IP_ADDRESS', 'IP Address')",
+ "INSERT INTO tbl_event_types (event, event_descr) VALUES ('NETBLOCK', 'Netblock Ownership')",
"INSERT INTO tbl_event_types (event, event_descr) VALUES ('SUBDOMAIN', 'Sub-domain')",
"INSERT INTO tbl_event_types (event, event_descr) VALUES ('SIMILARDOMAIN', 'Similar Domain')",
"INSERT INTO tbl_event_types (event, event_descr) VALUES ('TCP_PORT_OPEN', 'Open TCP Port')",
@@ -85,6 +86,7 @@ class SpiderFootDbInit:
"INSERT INTO tbl_event_types (event, event_descr) VALUES ('WEBCONTENT_PASSWORD', 'Web Content (Accepts Passwords)')",
"INSERT INTO tbl_event_types (event, event_descr) VALUES ('WEBCONTENT_UPLOAD', 'Web Content (Accepts Uploads)')",
"INSERT INTO tbl_event_types (event, event_descr) VALUES ('WEBSERVER_BANNER', 'Web Server')",
+ "INSERT INTO tbl_event_types (event, event_descr) VALUES ('WEBSERVER_TECHNOLOGY', 'Web Technology')",
"INSERT INTO tbl_event_types (event, event_descr) VALUES ('WEBSERVER_HTTPHEADERS', 'HTTP Headers')"
]
diff --git a/sflib.py b/sflib.py
index edc8b839..0b92808b 100644
--- a/sflib.py
+++ b/sflib.py
@@ -11,10 +11,8 @@
#-------------------------------------------------------------------------------
import inspect
-import random
import re
import sys
-import time
import urllib2
class SpiderFoot:
@@ -52,7 +50,7 @@ class SpiderFoot:
return
def status(self, message):
- print "STATUS: " + message
+ print "[Status] " + message
def debug(self, message):
if self.opts['_debug'] == False:
@@ -296,19 +294,32 @@ class SpiderFoot:
self.debug('parseLinks() called with no data to parse')
return None
+ # Find actual links
try:
regRel = re.compile('(href|src|action|url)[:=][ \'\"]*(.[^\'\"<> ]*)',
- re.IGNORECASE)
+ re.IGNORECASE)
urlsRel = regRel.findall(data)
except Exception as e:
- self.error("Error applying regex to " + data + ", continuing anyway.")
+ self.error("Error applying regex to: " + data)
return None
+ # Find potential links that aren't links (text possibly in comments, etc.)
+ try:
+ # Because we're working with a big blob of text now, don't worry
+ # about clobbering proper links by url decoding them.
+ data = urllib2.unquote(data)
+ regRel = re.compile('(.)([a-zA-Z0-9\-\.]+\.'+self.urlBaseDom(url)+')',
+ re.IGNORECASE)
+ urlsRel = urlsRel + regRel.findall(data)
+ except Exception as e:
+ self.error("Error applying regex2 to: " + data)
+
# Loop through all the URLs/links found by the regex
for linkTuple in urlsRel:
# Remember the regex will return two vars (two groups captured)
meta = linkTuple[0]
link = linkTuple[1]
+ absLink = None
# Don't include stuff likely part of some dynamically built incomplete
# URL found in Javascript code (character is part of some logic)
@@ -326,6 +337,10 @@ class SpiderFoot:
self.debug("Ignoring mail link: " + link)
continue
+ # URL decode links
+ if '%2F' in link or '%2f' in link:
+ link = urllib2.unquote(link)
+
# Capture the absolute link:
# If the link contains ://, it is already an absolute link
if '://' in link:
@@ -335,8 +350,12 @@ class SpiderFoot:
if link.startswith('/'):
absLink = self.urlBaseUrl(url) + link
+ # Maybe the domain was just mentioned and not a link, so we make it one
+ if absLink == None and self.urlBaseDom(url) in link:
+ absLink = 'http://' + link
+
# Otherwise, it's a flat link within the current directory
- if '://' not in link and not link.startswith('/'):
+ if absLink == None:
absLink = self.urlBaseDir(url) + link
# Translate any relative pathing (../)
@@ -345,68 +364,6 @@ class SpiderFoot:
return returnLinks
- # Scrape Google for content, starting at startUrl and iterating through
- # results based on options supplied. Will return a dictionary of all pages
- # fetched and their contents {page => content}.
- # Options accepted:
- # limit: number of search result pages before returning, default is 10
- # nopause: don't randomly pause between fetches
- def googleIterate(self, searchString, opts=dict()):
- limit = 10
- fetches = 0
- returnResults = dict()
-
- if opts.has_key('limit'):
- limit = opts['limit']
-
- # We attempt to make the URL look as authentically human as possible
- seedUrl = "http://www.google.com/search?q={0}".format(searchString) + \
- "&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a"
- firstPage = self.fetchUrl(seedUrl)
- if firstPage['code'] == "403":
- 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'])
- while matches > 0 and fetches < limit:
- nextUrl = None
- fetches += 1
- for match in matches:
- # Google moves in increments of 10
- if "start=" + str(fetches*10) in match:
- nextUrl = match.replace("&amp;", "&")
-
- if nextUrl == None:
- self.debug("Nothing left to scan for in Google results.")
- return returnResults
- self.debug("Next Google URL: " + nextUrl)
-
- # Wait for a random number of seconds between fetches
- if not opts.has_key('nopause'):
- pauseSecs = random.randint(4, 15)
- self.debug("Pausing for " + str(pauseSecs))
- time.sleep(pauseSecs)
-
- nextPage = self.fetchUrl('http://www.google.com' + nextUrl)
- if firstPage['code'] == 403:
- 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'])
-
- return returnResults
-
# Fetch a URL, return the response object
def fetchUrl(self, url, fatal=False):
result = {
@@ -445,6 +402,7 @@ class SpiderFoot:
self.debug("HTTP code " + str(h.code) + " encountered for " + url)
# Capture the HTTP error code
result['code'] = h.code
+ result['headers'] = h.info()
if fatal:
self.fatal('URL could not be fetched (' + h.code + ')')
except urllib2.URLError as e:
diff --git a/sfscan.py b/sfscan.py
new file mode 100644
index 00000000..68502643
--- /dev/null
+++ b/sfscan.py
@@ -0,0 +1,145 @@
+#-----------------------------------------------------------------
+# Name: sfscan
+# Purpose: Scanning control functionality
+#
+# Author: Steve Micallef <[email protected]>
+#
+# Created: 11/03/2013
+# Copyright: (c) Steve Micallef 2013
+# License: GPL
+#-----------------------------------------------------------------
+import json
+import threading
+import os
+import time
+import urllib2
+from copy import deepcopy
+from sfdb import SpiderFootDb
+from sflib import SpiderFoot
+
+# Controls all scanning activity
+# Eventually change this to be able to control multiple scan instances
+class SpiderFootScanner:
+ moduleInstances = None
+ status = "UNKNOWN"
+ myId = None
+
+ def __init__(self, name, target, moduleList, globalOpts, moduleOpts):
+ self.config = deepcopy(globalOpts)
+ self.sf = SpiderFoot(self.config)
+ self.target = target
+ self.moduleList = moduleList
+ self.name = name
+
+ return
+
+ # Status of the currently running scan (if any)
+ def scanStatus(self, id):
+ if id != self.myId:
+ return "UNKNOWN"
+ return self.status
+
+ # Stop a scan (id variable is unnecessary for now given that only one simultaneous
+ # scan is permitted.)
+ def stopScan(self, id):
+ if id != self.myId:
+ return None
+
+ if self.moduleInstances == None:
+ return None
+
+ for modName in self.moduleInstances.keys():
+ print "Signalling module " + modName + " to stop."
+ self.moduleInstances[modName].stopScanning()
+
+ # Start running a scan
+ def startScan(self):
+ self.moduleInstances = dict()
+ dbh = SpiderFootDb(self.config)
+ aborted = False
+
+ # Create a unique ID for this scan and create it in the back-end DB.
+ self.config['__guid__'] = dbh.scanInstanceGenGUID(self.target)
+ self.myId = self.config['__guid__']
+ dbh.scanInstanceCreate(self.config['__guid__'], self.name, self.target)
+ dbh.scanInstanceSet(self.config['__guid__'], time.time() * 1000, None, 'STARTING')
+ self.status = "STARTING"
+
+ # Save the config current set for this scan
+ self.config['_modulesenabled'] = self.moduleList
+ dbh.scanConfigSet(self.config['__guid__'], self.sf.configSerialize(self.config))
+
+ print "Scan [" + self.config['__guid__'] + "] initiated."
+ # moduleList = list of modules the user wants to run
+ try:
+ for modName in self.moduleList:
+ if modName == '':
+ continue
+
+ module = __import__('modules.' + modName, globals(), locals(), [modName])
+ mod = getattr(module, modName)()
+
+ # 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.
+ self.config['__sfdb__'] = dbh
+
+ # Set up the module
+ # Configuration is a combined global config with module-specific options
+ #modConfig = deepcopy(self.config)
+ modConfig = self.config['__modules__'][modName]['opts']
+ for opt in self.config.keys():
+ modConfig[opt] = self.config[opt]
+
+ mod.clearListeners() # clear any listener relationships from the past
+ mod.setup(self.target, modConfig)
+ 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
+ # Note the absence of a check for whether a module can register
+ # to itself. That is intentional because some modules will
+ # act on their own notifications (e.g. sfp_dns)!
+ if listenerModule.watchedEvents() != None:
+ module.registerListener(listenerModule)
+
+ dbh.scanInstanceSet(self.config['__guid__'], status='RUNNING')
+ self.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(self.config['__guid__'], status='ABORTING')
+ self.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:
+ self.sf.status("Scan [" + self.config['__guid__'] + "] aborted.")
+ dbh.scanInstanceSet(self.config['__guid__'], None, time.time() * 1000, 'ABORTED')
+ self.status = "ABORTED"
+ else:
+ self.sf.status("Scan [" + self.config['__guid__'] + "] completed.")
+ dbh.scanInstanceSet(self.config['__guid__'], None, time.time() * 1000, 'FINISHED')
+ self.status = "FINISHED"
+ except Exception as e:
+ self.sf.status("Scan [" + self.config['__guid__'] + "] failed: " + str(e))
+ dbh.scanInstanceSet(self.config['__guid__'], None, time.time() * 1000, 'ERROR-FAILED')
+ self.status = "ERROR-FAILED"
+
+ self.moduleInstances = None
+ dbh.close()
+
diff --git a/sfwebui.py b/sfwebui.py
index 9d411163..f61b129c 100644
--- a/sfwebui.py
+++ b/sfwebui.py
@@ -21,147 +21,16 @@ from mako.template import Template
from sfdb import SpiderFootDb
from sfdbsetup import SpiderFootDbInit
from sflib import SpiderFoot
-
-# Data providers called by front-end javascript
-# Each name maps to the data provider interface below, e.g. scanlistData()
-# provides data for calls to /scanlist (scanlist())
-class SpiderFootDataProvider:
- config = None
- moduleInstances = None
-
- def __init__(self, config):
- self.config = config
- return
-
- def scanlistData(self):
- dbh = SpiderFootDb(self.config)
- data = dbh.scanInstanceList()
- retdata = []
- for row in data:
- created = time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(row[3]))
- if row[4] != 0:
- started = time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(row[4]))
- else:
- started = "Not yet"
-
- if row[5] != 0:
- finished = time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(row[5]))
- else:
- finished = "Not yet"
- retdata.append([row[0], row[1], row[2], created, started, finished, row[6], row[7]])
- return json.dumps(retdata)
-
- def scansummaryData(self, instanceId):
- dbh = SpiderFootDb(self.config)
- data = dbh.scanResultSummary(instanceId)
- retdata = []
- for row in data:
- lastseen = time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(row[2]))
- retdata.append([row[0], row[1], lastseen, row[3]])
- return json.dumps(retdata)
-
- def scaneventresultsData(self, instanceId, eventType):
- dbh = SpiderFootDb(self.config)
- data = dbh.scanResultEvent(instanceId, eventType)
- retdata = []
- for row in data:
- lastseen = time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(row[0]))
- escaped = cgi.escape(row[1])
- retdata.append([lastseen, escaped, row[2], row[3]])
- return json.dumps(retdata, ensure_ascii=False)
-
- def startScan(self, name, target, moduleList, globalOpts, moduleOpts):
- dbh = SpiderFootDb(globalOpts)
- self.moduleInstances = dict()
- aborted = False
-
- # Take a copy of the configuration supplied
- sfConfig = deepcopy(globalOpts)
- # 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, 'STARTING')
-
- # Save the config current set for this scan
- sf = SpiderFoot(sfConfig)
- sfConfig['_modulesenabled'] = moduleList
- dbh.scanConfigSet(sfConfig['__guid__'], sf.configSerialize(sfConfig))
-
- print "Scan [" + sfConfig['__guid__'] + "] initiated."
- # moduleList = list of modules the user wants to run
- 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 as e:
- print "Scan [" + sfConfig['__guid__'] + "] failed: " + str(e)
- dbh.scanInstanceSet(sfConfig['__guid__'], None, time.time() * 1000, 'ERROR-FAILED')
-
- self.moduleInstances = None
- dbh.close()
+from sfscan import SpiderFootScanner
class SpiderFootWebUi:
- dp = None
lookup = TemplateLookup(directories=[''])
defaultConfig = dict()
config = dict()
+ scanner = None
def __init__(self, config):
self.defaultConfig = deepcopy(config)
- # Data provider will provide all data from the DB
- self.dp = SpiderFootDataProvider(config)
dbh = SpiderFootDb(config)
# 'config' supplied will be the defaults, let's supplement them
# now with any configuration which may have previously been
@@ -169,8 +38,9 @@ class SpiderFootWebUi:
sf = SpiderFoot(config)
self.config = sf.configUnserialize(dbh.configGet(), config)
- # DATA PROVIDERS (need to migrate all the ones from SpiderFootDataProvider
- # to here)
+ #
+ # USER INTERFACE PAGES
+ #
# Get result data in CSV format
def scaneventresultexport(self, id, type):
@@ -223,10 +93,6 @@ class SpiderFootWebUi:
return json.dumps(ret)
scanopts.exposed = True
- #
- # USER INTERFACE PAGES
- #
-
# Configure a new scan
def newscan(self):
templ = Template(filename='dyn/newscan.tmpl', lookup=self.lookup)
@@ -254,7 +120,7 @@ class SpiderFootWebUi:
return self.error("Scan ID not found.")
templ = Template(filename='dyn/scaninfo.tmpl', lookup=self.lookup)
- return templ.render(id=id, name=res[0], pageid='SCANLIST')
+ return templ.render(id=id, name=res[0], status=res[5], pageid='SCANLIST')
scaninfo.exposed = True
# Settings
@@ -283,25 +149,6 @@ class SpiderFootWebUi:
return templ.render(id=id, name=res[0])
scandelete.exposed = True
- #
- # DATA PROVIDERS
- #
-
- # Produce a list of scans
- def scanlist(self):
- return self.dp.scanlistData()
- scanlist.exposed = True
-
- # Summary of scan results
- def scansummary(self, id):
- return self.dp.scansummaryData(id)
- scansummary.exposed = True
-
- # Event results for a scan
- def scaneventresults(self, id, eventType):
- return self.dp.scaneventresultsData(id, eventType)
- scaneventresults.exposed = True
-
# Save settings, also used to completely reset them to default
def savesettings(self, allopts):
try:
@@ -318,7 +165,7 @@ class SpiderFootWebUi:
# the current system config.
sf = SpiderFoot(self.config)
self.config = sf.configUnserialize(useropts, currentopts)
-
+
dbh.configSet(sf.configSerialize(currentopts))
except Exception as e:
return self.error("Processing one or more of your inputs failed: " + str(e))
@@ -340,11 +187,12 @@ class SpiderFootWebUi:
for thread in threading.enumerate():
if thread.name.startswith("SF_"):
templ = Template(filename='dyn/newscan.tmpl', lookup=self.lookup)
- return templ.render(modules=self.config['__modules__'], alreadyRunning=True, runningScan=thread.name[3:])
-
+ return templ.render(modules=self.config['__modules__'], alreadyRunning=True, runningScan=thread.name[3:])
+
# Start running a new scan
print "Spawning thread for new scan..."
- t = threading.Thread(name="SF_" + scanname, target=self.dp.startScan, args=(scanname, scantarget, modlist, self.config, modopts))
+ self.scanner = SpiderFootScanner(scanname, scantarget, modlist, self.config, modopts)
+ t = threading.Thread(name="SF_" + scanname, target=self.scanner.startScan)
t.start()
templ = Template(filename='dyn/scanlist.tmpl', lookup=self.lookup)
@@ -354,16 +202,66 @@ class SpiderFootWebUi:
# Stop a scan (id variable is unnecessary for now given that only one simultaneous
# scan is permitted.)
def stopscan(self, id):
- if self.dp.moduleInstances == None:
+ if self.scanner == None:
return self.error("There are no scans running. A data consistency error for this scan probably exists. <a href='/scandelete?id=" + id + "&confirm=1'>Click here to delete it.</a>")
- for modName in self.dp.moduleInstances.keys():
- print "Signalling module " + modName + " to stop."
- self.dp.moduleInstances[modName].stopScanning()
+ if self.scanner.scanStatus(id) == "ABORTED":
+ return self.error("The scan is already aborted.")
+
+ if not self.scanner.scanStatus(id) == "RUNNING":
+ return self.error("The running scan is currently in the state '" + self.scanner.scanStatus(id) + "', please try again later or restart SpiderFoot.")
+
+ self.scanner.stopScan(id)
templ = Template(filename='dyn/scanlist.tmpl', lookup=self.lookup)
return templ.render(pageid='SCANLIST',stoppedscan=True)
stopscan.exposed = True
+ #
+ # DATA PROVIDERS
+ #
+
+ # Produce a list of scans
+ def scanlist(self):
+ dbh = SpiderFootDb(self.config)
+ data = dbh.scanInstanceList()
+ retdata = []
+ for row in data:
+ created = time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(row[3]))
+ if row[4] != 0:
+ started = time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(row[4]))
+ else:
+ started = "Not yet"
+
+ if row[5] != 0:
+ finished = time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(row[5]))
+ else:
+ finished = "Not yet"
+ retdata.append([row[0], row[1], row[2], created, started, finished, row[6], row[7]])
+ return json.dumps(retdata)
+ scanlist.exposed = True
+
+ # Summary of scan results
+ def scansummary(self, id):
+ dbh = SpiderFootDb(self.config)
+ data = dbh.scanResultSummary(id)
+ retdata = []
+ for row in data:
+ lastseen = time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(row[2]))
+ retdata.append([row[0], row[1], lastseen, row[3]])
+ return json.dumps(retdata)
+ scansummary.exposed = True
+
+ # Event results for a scan
+ def scaneventresults(self, id, eventType):
+ dbh = SpiderFootDb(self.config)
+ data = dbh.scanResultEvent(id, eventType)
+ retdata = []
+ for row in data:
+ lastseen = time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(row[0]))
+ escaped = cgi.escape(row[1])
+ retdata.append([lastseen, escaped, row[2], row[3]])
+ return json.dumps(retdata, ensure_ascii=False)
+ scaneventresults.exposed = True
# Special class used when SpiderFoot is started without a
# database pre-existing. This will step the user through