Skip to content

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

Configurability via the UI.

smicalleff1e8ad594471
diff --git a/dyn/HEADER.tmpl b/dyn/HEADER.tmpl
index 488943e7..4b8eb4ef 100644
--- a/dyn/HEADER.tmpl
+++ b/dyn/HEADER.tmpl
@@ -28,7 +28,7 @@
<body>
- <div class="navbar navbar-inverse navbar-fixed-top">
+ <div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
@@ -43,16 +43,20 @@
% if pageid == "NEWSCAN":
class="active"
% endif
-><a href="/newscan"><i class="icon-screenshot icon-white"></i>&nbsp;New Scan</a></li>
+><a href="/newscan"><i class="icon-screenshot"></i>&nbsp;New Scan</a></li>
<li
% if pageid == "SCANLIST":
class="active"
% endif
-><a href="/"><i class="icon-book icon-white"></i>&nbsp;Scans</a></li>
- <li><a href="#config"><i class="icon-wrench icon-white"></i>&nbsp;Settings</a></li>
+><a href="/"><i class="icon-book"></i>&nbsp;Scans</a></li>
+ <li
+% if pageid == "SETTINGS":
+ class="active"
+%endif
+><a href="/opts"><i class="icon-wrench"></i>&nbsp;Settings</a></li>
</ul>
<ul class="nav pull-right">
- <li><a href="#"><i class="icon-info-sign icon-white"></i>&nbsp;About</a></li>
+ <li><a href="#"><i class="icon-info-sign"></i>&nbsp;About</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
diff --git a/dyn/opts.tmpl b/dyn/opts.tmpl
new file mode 100644
index 00000000..51d40fdf
--- /dev/null
+++ b/dyn/opts.tmpl
@@ -0,0 +1,107 @@
+<%include file="HEADER.tmpl"/>
+<script type='text/javascript'>
+ function saveSettings() {
+ var retarr = {}
+ $(":input").each(function(i) {
+ retarr[$(this).attr('id')] = $(this).val();
+ });
+
+ $("#allopts").val(JSON.stringify(retarr));
+ }
+
+ function clearSettings() {
+ $("#allopts").val("RESET");
+ }
+
+</script>
+ <h2>Settings</h2>
+% if updated:
+<div class="alert alert-success">
+ <button type="button" class="close" data-dismiss="alert">&times;</button>
+ <h4>Success!</h4>
+ Settings updated. These will take effect the next time you run a scan.
+</div>
+% endif
+<form class="form" action='/savesettings' method='POST'>
+<h4>Global Settings</h4>
+<table class='table table-bordered table-striped'>
+<thead><tr> <th>Option</th> <th>Value</th></tr></thead><tbody>
+% for opt in sorted(opts.keys()):
+ % if not opt.startswith("__"):
+ <tr><td>${opt}</td><td>
+ % if type(opts[opt]) is int:
+ <input id='${opt}' class='input-mini' type=text value="${opts[opt]}">
+ % endif
+ % if type(opts[opt]) is str:
+ <input id='${opt}' class='input-xxlarge' type=text value="${opts[opt]}">
+ % endif
+ % if type(opts[opt]) is bool:
+ <%
+ if opts[opt] == True:
+ seltrue = "selected"
+ selfalse = ""
+ else:
+ selfalse = "selected"
+ seltrue = ""
+ %>
+ <select id='${opt}'>
+ <option value=1 ${seltrue}>True</option>
+ <option value=0 ${selfalse}>False</option>
+ </select>
+ % endif
+ % if type(opts[opt]) is list:
+ <% expandedopt = ','.join(opts[opt]) %>
+ <input id='${opt}' class='input-xxlarge' type=text value="${expandedopt}">
+ % endif
+ </td></tr>
+ % endif
+% endfor
+</tbody>
+</table>
+<br>
+<h4>Module Settings</h4>
+<table class='table table-bordered table-striped'>
+<thead><tr> <th>Module</th> <th>Option</th> <th>Value</th></tr></thead><tbody>
+% for mod in sorted(opts['__modules__'].keys()):
+ % for opt in opts['__modules__'][mod]['opts'].keys():
+ <% modopts = opts['__modules__'][mod]['opts'] %>
+ % if not opt.startswith("_"):
+ <tr><td>${mod}</td><td>${opt}</td><td>
+ % if type(modopts[opt]) is int:
+ <input id='${mod}:${opt}' class='input-mini' type=text value="${modopts[opt]}">
+ % endif
+ % if type(modopts[opt]) is str:
+ <input id='${mod}:${opt}' class='input-xxlarge' type=text value="${modopts[opt]}">
+ % endif
+ % if type(modopts[opt]) is bool:
+ <%
+ if modopts[opt] == True:
+ seltrue = "selected"
+ selfalse = ""
+ else:
+ selfalse = "selected"
+ seltrue = ""
+ %>
+ <select id='${mod}:${opt}'>
+ <option value=1 ${seltrue}>True</option>
+ <option value=0 ${selfalse}>False</option>
+ </select>
+ % endif
+ % if type(modopts[opt]) is list:
+ <% expandedopt = ','.join(modopts[opt]) %>
+ <input id='${mod}:${opt}' class='input-xxlarge' type=text value="${expandedopt}">
+ % endif
+ </td></tr>
+ % endif
+ % endfor
+% endfor
+</tbody>
+</table>
+<div style='text-align: right'>
+ <input type=hidden id='allopts' name='allopts' value=''>
+ <button onClick='clearSettings();' class='btn btn-danger'>Reset to Default</button>
+ <button onClick='saveSettings();' class='btn btn-primary'>Save Changes</button>
+</div>
+</form>
+<br><br>
+<%include file="FOOTER.tmpl"/>
diff --git a/dyn/scaninfo.tmpl b/dyn/scaninfo.tmpl
index 2a10f9e0..e4913eb4 100644
--- a/dyn/scaninfo.tmpl
+++ b/dyn/scaninfo.tmpl
@@ -2,8 +2,9 @@
<h2>${name}</h2>
<div class="btn-toolbar">
<div class="btn-group">
+ <a class="btn" href="#">Report</a>
<a class="btn active" href="#" onClick='browseEventList("${id}")'>Browse</a>
- <a class="btn" href="#">Config</a>
+ <a class="btn" href="#">Scan Info</a>
<a class="btn" href="#">Search</a>
</div>
</div>
@@ -41,7 +42,7 @@ Loading...
$("#scansummary-content").remove();
$("#loader").show();
sf.fetchData('/scaneventresults', {'id': instanceId, 'eventType': eventType }, function(data) {
- var table = "<table id='scansummary-content' class='table table-bordered table-striped'>";
+ var table = "<table id='scansummary-content' class='table table-bordered table-striped small'>";
table += "<thead><tr> <th>Data Element</th><th>Obtained</th><th>Source</th><th>Module</th></tr></thead><tbody>";
for (var i = 0; i < data.length; i++) {
table += "<tr><td>" + data[i][1] + "</td><td>" + data[i][0] + "</td><td>" + data[i][2] + "</td><td>" + data[i][3] + "</td></tr>";
diff --git a/dyn/scanlist.tmpl b/dyn/scanlist.tmpl
index 49b0d223..72393fb1 100644
--- a/dyn/scanlist.tmpl
+++ b/dyn/scanlist.tmpl
@@ -22,6 +22,15 @@ Loading...
</div>
<script type='text/javascript'>
sf.fetchData('/scanlist', null, function(data) {
+ if (data.length == 0) {
+ $("#loader").fadeOut(250);
+ welcome = "<div class='alert alert-info'>";
+ welcome += "<h4>Welcome to SpiderFoot!</h4>";
+ welcome += "There is currently no history of previously run scans. Please click 'New Scan' to initiate a new scan."
+ welcome += "</div>";
+ $("#mainbody").append(welcome);
+ return;
+ }
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><th>Action</th> </tr></thead><tbody>";
for (var i = 0; i < data.length; i++) {
diff --git a/evtypes.sql b/evtypes.sql
index aec420a7..0c1f9035 100644
--- a/evtypes.sql
+++ b/evtypes.sql
@@ -14,5 +14,5 @@ INSERT INTO tbl_event_types (event, event_descr) VALUES ('WEBCONTENT_JAVASCRIPT'
INSERT INTO tbl_event_types (event, event_descr) VALUES ('WEBCONTENT_STATIC', 'Web Content (Purely Static)');
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 ('WEBCONTENT_BANNER', 'Web Server');
-INSERT INTO tbl_event_types (event, event_descr) VALUES ('WEBCONTENT_HTTPHEADERS', 'HTTP Headers');
+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');
diff --git a/modules/sfp_dns.py b/modules/sfp_dns.py
index 237f7c6b..47a68bb7 100644
--- a/modules/sfp_dns.py
+++ b/modules/sfp_dns.py
@@ -26,8 +26,8 @@ class sfp_dns(SpiderFootPlugin):
# Default options
opts = {
# These must always be set
- '_debug': True,
- '_debugfilter': '',
+ '__debug': True,
+ '__debugfilter': '',
'resolveaffiliate': True, # Get IPs for affiliate domains
'reverselookup': True # Reverse-resolve IPs to names for
# more clues.
diff --git a/modules/sfp_googlesearch.py b/modules/sfp_googlesearch.py
index 96e3bf2d..98dbf8cd 100644
--- a/modules/sfp_googlesearch.py
+++ b/modules/sfp_googlesearch.py
@@ -22,9 +22,9 @@ class sfp_googlesearch(SpiderFootPlugin):
# Default options
opts = {
# These must always be set
- '_debug': True,
- '_debugfilter': '',
- '_useragent': 'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0',
+ '__debug': True,
+ '__debugfilter': '',
+ 'useragent': 'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0',
'fetchlinks': True, # Should we fetch links on the base domain?
'pages': 20 # Number of google results pages to iterate
}
diff --git a/modules/sfp_mail.py b/modules/sfp_mail.py
index 11f5a939..96a94234 100644
--- a/modules/sfp_mail.py
+++ b/modules/sfp_mail.py
@@ -23,8 +23,8 @@ class sfp_mail(SpiderFootPlugin):
# Default options
opts = {
# These must always be set
- '_debug': True,
- '_debugfilter': '',
+ '__debug': True,
+ '__debugfilter': '',
# options specific to this module
'basedomainonly': False, # Only capture e-mail addrs on the base domain
'includeexternal': False # Include e-mail addrs on external domains
diff --git a/modules/sfp_pageinfo.py b/modules/sfp_pageinfo.py
index 305b000e..97656cb9 100644
--- a/modules/sfp_pageinfo.py
+++ b/modules/sfp_pageinfo.py
@@ -36,8 +36,8 @@ etc.)"""
# Default options
opts = {
# These must always be set
- '_debug': True,
- '_debugfilter': ''
+ '__debug': True,
+ '__debugfilter': ''
}
# URL this instance is working on
diff --git a/modules/sfp_similar.py b/modules/sfp_similar.py
index 25a50667..d6746a8b 100644
--- a/modules/sfp_similar.py
+++ b/modules/sfp_similar.py
@@ -46,10 +46,10 @@ class sfp_similar(SpiderFootPlugin):
# Default options
opts = {
- '_debug': True,
- '_debugfilter': '',
+ '__debug': True,
+ '__debugfilter': '',
# Domaintools will 403 you without a browser-like useragent
- '_useragent': 'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0',
+ 'useragent': 'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0',
'source': 'ALL', # whois, domaintools, namedroppers or ALL
'method': 'left,right', # left and/or right (doesn't apply to whois.com)
'activeonly': False # Only report domains that have content (try to fetch the page)
diff --git a/modules/sfp_spider.py b/modules/sfp_spider.py
index aaba7dd5..ea087e9d 100644
--- a/modules/sfp_spider.py
+++ b/modules/sfp_spider.py
@@ -24,8 +24,8 @@ class sfp_spider(SpiderFootPlugin):
# Default options
opts = {
# These must always be set
- '_debug': True,
- '_debugfilter': '',
+ '__debug': True,
+ '__debugfilter': '',
# options specific to this module
'robotsonly': False, # only follow links specified by robots.txt
'pause': 0, # number of seconds to pause between fetches
diff --git a/modules/sfp_stor_db.py b/modules/sfp_stor_db.py
index 5c007c48..85e80bee 100644
--- a/modules/sfp_stor_db.py
+++ b/modules/sfp_stor_db.py
@@ -24,8 +24,9 @@ class sfp_stor_db(SpiderFootPlugin):
# Default options
opts = {
# These must always be set
- '_debug': True,
- '_debugfilter': ''
+ '__debug': True,
+ '__debugfilter': '',
+ 'maxstorage': 0 # max bytes for any piece of info stored (0 = unlimited)
}
# URL this instance is working on
@@ -52,8 +53,13 @@ class sfp_stor_db(SpiderFootPlugin):
# Handle events sent to this module
def handleEvent(self, srcModuleName, eventName, eventSource, eventData):
- sfdb.scanEventStore(self.opts['__guid__'], eventName, eventSource,
- eventData, srcModuleName)
+ 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)
+
# End of sfp_stor_db class
diff --git a/modules/sfp_stor_print.py b/modules/sfp_stor_print.py
index 0fa9ffad..96b30006 100644
--- a/modules/sfp_stor_print.py
+++ b/modules/sfp_stor_print.py
@@ -21,8 +21,8 @@ class sfp_stor_print(SpiderFootPlugin):
# Default options
opts = {
# These must always be set
- '_debug': True,
- '_debugfilter': '',
+ '__debug': True,
+ '__debugfilter': '',
'datasize': 100 # Number of characters to print from event data
}
diff --git a/modules/sfp_subdomain.py b/modules/sfp_subdomain.py
index 6d577759..d06c2186 100644
--- a/modules/sfp_subdomain.py
+++ b/modules/sfp_subdomain.py
@@ -22,8 +22,8 @@ class sfp_subdomain(SpiderFootPlugin):
# Default options
opts = {
# These must always be set
- '_debug': True,
- '_debugfilter': ''
+ '__debug': True,
+ '__debugfilter': ''
}
# URL this instance is working on
diff --git a/modules/sfp_template.py b/modules/sfp_template.py
index a4adb2a9..d46eec22 100644
--- a/modules/sfp_template.py
+++ b/modules/sfp_template.py
@@ -22,8 +22,8 @@ class sfp_XXX(SpiderFootPlugin):
# Default options
opts = {
# These must always be set
- '_debug': True,
- '_debugfilter': ''
+ '__debug': True,
+ '__debugfilter': ''
}
# Be sure to completely clear any class variables in setup()
diff --git a/modules/sfp_websvr.py b/modules/sfp_websvr.py
index d965530f..d690bccb 100644
--- a/modules/sfp_websvr.py
+++ b/modules/sfp_websvr.py
@@ -23,8 +23,8 @@ class sfp_websvr(SpiderFootPlugin):
# Default options
opts = {
# These must always be set
- '_debug': True,
- '_debugfilter': ''
+ '__debug': True,
+ '__debugfilter': ''
}
# URL this instance is working on
diff --git a/modules/sfp_xref.py b/modules/sfp_xref.py
index b944caef..f97f07f6 100644
--- a/modules/sfp_xref.py
+++ b/modules/sfp_xref.py
@@ -25,8 +25,8 @@ class sfp_xref(SpiderFootPlugin):
# Default options
opts = {
# These must always be set
- '_debug': True,
- '_debugfilter': '',
+ '__debug': True,
+ '__debugfilter': '',
'forcebase': True, # Check the base URL for a link back to the seed
# domain in order to be considered a valid xref
'checkbase': True, # Only check the base URL for a relationship if
diff --git a/sf.py b/sf.py
index 990c9f6c..ce3884da 100755
--- a/sf.py
+++ b/sf.py
@@ -17,19 +17,18 @@ import os
from sflib import SpiderFoot
from sfwebui import SpiderFootWebUi
-# These are all hard-coded for now, but will eventually
-# be set by the UI or CLI
# 'Global' configuration options
-# These can be overriden on a per-module basis
+# These can be overriden on a per-module basis, and some will
+# be overridden from saved configuration settings stored in the DB.
sfConfig = {
'_debug': True, # Debug
- '_debugfilter': '', # Filter out debug strings
- '_blocknotif': False, # Block notifications
+ '__debugfilter': '', # Filter out debug strings
+ '__blocknotif': False, # Block notifications
'_useragent': 'SpiderFoot/2.0', # User-Agent to use for HTTP requests
'_fetchtimeout': 1, # number of seconds before giving up on a fetch
- '_database': 'spiderfoot.db',
- '_webaddr': '0.0.0.0',
- '_webport': 5001,
+ '__database': 'spiderfoot.db',
+ '__webaddr': '0.0.0.0',
+ '__webport': 5001,
'__guid__': None, # unique ID of scan. Will be set after start-up.
'__modules__': None # List of modules. Will be set after start-up.
}
@@ -51,6 +50,7 @@ if __name__ == '__main__':
mod = __import__('modules.' + modName, globals(), locals(), [modName])
sfModules[modName]['object'] = getattr(mod, modName)()
sfModules[modName]['descr'] = sfModules[modName]['object'].__doc__
+ sfModules[modName]['opts'] = sfModules[modName]['object'].opts
if len(sfModules.keys()) < 1:
print "No modules found in the modules directory."
@@ -60,12 +60,12 @@ if __name__ == '__main__':
sfConfig['__modules__'] = sfModules
# Start the web server so you can start looking at results
- print "Starting web server at http://" + sfConfig['_webaddr'] + \
- ":" + str(sfConfig['_webport']) + "..."
+ print "Starting web server at http://" + sfConfig['__webaddr'] + \
+ ":" + str(sfConfig['__webport']) + "..."
cherrypy.config.update({
- 'server.socket_host': sfConfig['_webaddr'],
- 'server.socket_port': sfConfig['_webport']
+ 'server.socket_host': sfConfig['__webaddr'],
+ 'server.socket_port': sfConfig['__webport']
})
# Enable access to static files via the web directory
diff --git a/sfdb.py b/sfdb.py
index a9c8dfdf..56f1bf8b 100644
--- a/sfdb.py
+++ b/sfdb.py
@@ -26,10 +26,10 @@ class SpiderFootDb:
# connect() will create the database file if it doesn't exist, but
# at least we can use this opportunity to ensure we have permissions to
# read and write to such a file.
- dbh = sqlite3.connect(opts['_database'], timeout=10)
+ dbh = sqlite3.connect(opts['__database'], timeout=10)
if dbh == None:
sf.fatal("Could not connect to internal database. Check that " + \
- opts['_database'] + " exists and is readable and writable.")
+ opts['__database'] + " exists and is readable and writable.")
dbh.text_factory = str
self.conn = dbh
@@ -162,16 +162,92 @@ class SpiderFootDb:
sf.error("SQL error encountered when deleting scan: " +
e.args[0])
+ # Store the default configuration
+ def configSet(self, optMap=dict()):
+ qry = "REPLACE INTO tbl_config (scope, opt, val) VALUES (?, ?, ?)"
+ for opt in optMap.keys():
+ # Module option
+ if ":" in opt:
+ parts = opt.split(':')
+ qvals = [ parts[0], parts[1], optMap[opt] ]
+ else:
+ # Global option
+ qvals = [ "GLOBAL", opt, optMap[opt] ]
+
+ try:
+ self.dbh.execute(qry, qvals)
+ except sqlite3.Error as e:
+ sf.error("SQL error encountered when storing config, aborting: " +
+ e.args[0])
+
+ self.conn.commit()
+
+ # Retreive the config from the database
+ def configGet(self):
+ qry = "SELECT scope, opt, val FROM tbl_config"
+ try:
+ retval = dict()
+ self.dbh.execute(qry)
+ for [scope, opt, val] in self.dbh.fetchall():
+ if scope == "GLOBAL":
+ retval[opt] = val
+ else:
+ retval[scope + ":" + opt] = val
+
+ return retval
+ except sqlite3.Error as e:
+ sf.error("SQL error encountered when fetching configuration: " + e.args[0])
+
+ # Reset the config to default (clear it from the DB and let the hard-coded
+ # settings in the code take effect.)
+ def configClear(self):
+ qry = "DELETE from tbl_config"
+ try:
+ self.dbh.execute(qry)
+ self.conn.commit()
+ except sqlite3.Error as e:
+ sf.error("Unable to clear configuration from the database: " + e.args[0])
+
# Store a configuration value for a scan
- # To unset, simply set the optMap key value to None
- # don't need this yet
- def scanConfigSet(self, instanceId, component, optMap=dict()):
- pass
+ def scanConfigSet(self, id, optMap=dict()):
+ qry = "REPLACE INTO tbl_scan_config \
+ (scan_instance_id, component, opt, val) VALUES (?, ?, ?, ?)"
+
+ for opt in optMap.keys():
+ # Module option
+ if ":" in opt:
+ parts = opt.split(':')
+ qvals = [ id, parts[0], parts[1], optMap[opt] ]
+ else:
+ # Global option
+ qvals = [ id, "GLOBAL", opt, optMap[opt] ]
+
+ try:
+ self.dbh.execute(qry, qvals)
+ except sqlite3.Error as e:
+ sf.error("SQL error encountered when storing config, aborting: " +
+ e.args[0])
+
+ self.conn.commit()
# Retreive configuration data for a scan component
# don't need this yet
def scanConfigGet(self, instanceId, component):
- pass
+ qry = "SELECT component, opt, val FROM tbl_scan_config \
+ WHERE scan_instance_id = ?"
+ qvars = [instanceId]
+ try:
+ retval = dict()
+ self.dbh.execute(qry, qvars)
+ for [component, opt, val] in self.dbh.fetchall():
+ if component == "GLOBAL":
+ retval[opt] = val
+ else:
+ retval[component + ":" + opt] = val
+
+ return retval
+ except sqlite3.Error as e:
+ sf.error("SQL error encountered when fetching configuration: " + e.args[0])
# Store an event
def scanEventStore(self, instanceId, eventName, eventSource,
diff --git a/sflib.py b/sflib.py
index e7e31daa..949ffbc6 100644
--- a/sflib.py
+++ b/sflib.py
@@ -35,6 +35,7 @@ class SpiderFoot:
def error(self, error):
if self.handle == None:
print '[Error] ' + error
+ raise Exception(error)
else:
#self.handle.error(error)
print 'should not be here'
@@ -62,7 +63,7 @@ class SpiderFoot:
mod = inspect.getmodule(frm[0])
msg = '[d:' + mod.__name__ + '] ' + message
- if self.opts['_debugfilter'] != None and self.opts['_debugfilter'] not in msg:
+ if self.opts['__debugfilter'] != None and self.opts['__debugfilter'] not in msg:
return
print msg
@@ -71,6 +72,104 @@ class SpiderFoot:
print 'should not be here'
return
+ #
+ # Configuration process
+ #
+
+ # Convert a Python dictionary to something storable
+ # in the database.
+ def configSerialize(self, opts, filterSystem=True):
+ storeopts = dict()
+
+ for opt in opts.keys():
+ if opt.startswith('__') and filterSystem:
+ continue
+
+ if type(opts[opt]) is int or type(opts[opt]) is str:
+ storeopts[opt] = opts[opt]
+
+ if type(opts[opt]) is bool:
+ if opts[opt]:
+ storeopts[opt] = 1
+ else:
+ storeopts[opt] = 0
+ if type(opts[opt]) is list:
+ storeopts[opt] = ','.join(opts[opt])
+
+ if not opts.has_key('__modules__'):
+ return storeopts
+
+ for mod in opts['__modules__']:
+ for opt in opts['__modules__'][mod]['opts']:
+ if opt.startswith('_') and filterSystem:
+ continue
+
+ if type(opts['__modules__'][mod]['opts'][opt]) is int or type(opts['__modules__'][mod]['opts'][opt]) is str:
+ storeopts[mod + ":" + opt] = opts['__modules__'][mod]['opts'][opt]
+
+ if type(opts['__modules__'][mod]['opts'][opt]) is bool:
+ if opts['__modules__'][mod]['opts'][opt]:
+ storeopts[mod + ":" + opt] = 1
+ else:
+ storeopts[mod + ":" + opt] = 0
+ if type(opts['__modules__'][mod]['opts'][opt]) is list:
+ storeopts[mod + ":" + opt] = ','.join(opts['__modules__'][mod]['opts'][opt])
+
+ return storeopts
+
+ # Take strings, etc. from the database or UI and convert them
+ # to a dictionary for Python to process.
+ # referencePoint is needed to know the actual types the options
+ # are supposed to be.
+ def configUnserialize(self, opts, referencePoint, filterSystem=True):
+ returnOpts = referencePoint
+
+ # Global options
+ for opt in referencePoint.keys():
+ if opt.startswith('__') and filterSystem:
+ # Leave out system variables
+ continue
+ if opts.has_key(opt):
+ if type(referencePoint[opt]) is bool:
+ if opts[opt] == "1":
+ returnOpts[opt] = True
+ else:
+ returnOpts[opt] = False
+
+ if type(referencePoint[opt]) is str:
+ returnOpts[opt] = str(opts[opt])
+
+ if type(referencePoint[opt]) is int:
+ returnOpts[opt] = int(opts[opt])
+
+ if type(referencePoint[opt]) is list:
+ returnOpts[opt] = str(opts[opt]).split(",")
+
+ if not referencePoint.has_key('__modules__'):
+ return returnOpts
+
+ # Module options
+ for modName in referencePoint['__modules__']:
+ for opt in referencePoint['__modules__'][modName]['opts']:
+ if opt.startswith('_') and filterSystem:
+ continue
+ if opts.has_key(modName + ":" + opt):
+ if type(referencePoint['__modules__'][modName]['opts'][opt]) is bool:
+ if opts[modName + ":" + opt] == "1":
+ returnOpts['__modules__'][modName]['opts'][opt] = True
+ else:
+ returnOpts['__modules__'][modName]['opts'][opt] = False
+
+ if type(referencePoint['__modules__'][modName]['opts'][opt]) is str:
+ returnOpts['__modules__'][modName]['opts'][opt] = str(opts[modName + ":" + opt])
+
+ if type(referencePoint['__modules__'][modName]['opts'][opt]) is int:
+ returnOpts['__modules__'][modName]['opts'][opt] = int(opts[modName + ":" + opt])
+
+ if type(referencePoint['__modules__'][modName]['opts'][opt]) is list:
+ returnOpts['__modules__'][modName]['opts'][opt] = str(opts[modName + ":" + opt]).split(",")
+ return returnOpts
+
#
# URL parsing functions
#
@@ -315,6 +414,10 @@ class SpiderFoot:
header = dict()
if self.opts.has_key('_useragent'):
header['User-Agent'] = self.opts['_useragent']
+ # Let modules override
+ if self.opts.has_key('useragent'):
+ header['User-Agent'] = self.opts['useragent']
+
if not self.opts.has_key('_fetchtimeout'):
self.opts['_fetchtimeout'] = 30
req = urllib2.Request(url, None, header)
@@ -382,7 +485,7 @@ class SpiderFootPlugin(object):
if self.checkForStop():
return None
- if self.opts.has_key('blocknotif') and self.opts['_blocknotif']:
+ if self.opts.has_key('blocknotif') and self.opts['__blocknotif']:
#print "Notifications blocked for " + eventName + " to " + listener.__module__
return None
diff --git a/sfwebui.py b/sfwebui.py
index aa83504d..bd413640 100644
--- a/sfwebui.py
+++ b/sfwebui.py
@@ -13,9 +13,12 @@ import threading
import cherrypy
import cgi
import time
+import urllib2
+from copy import deepcopy
from mako.lookup import TemplateLookup
from mako.template import Template
from sfdb import SpiderFootDb
+from sflib import SpiderFoot
# Data providers called by front-end javascript
# Each name maps to the data provider interface below, e.g. scanlistData()
@@ -65,17 +68,21 @@ class SpiderFootDataProvider:
retdata.append([lastseen, escaped, row[2], row[3]])
return json.dumps(retdata, ensure_ascii=False)
- def startScan(self, name, target, moduleList, moduleOpts):
- dbh = SpiderFootDb(self.config)
+ def startScan(self, name, target, moduleList, globalOpts, moduleOpts):
+ dbh = SpiderFootDb(globalOpts)
self.moduleInstances = dict()
aborted = False
- # Take a copy of the configuration
- sfConfig = self.config
+ # 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)
+ dbh.scanConfigSet(sfConfig['__guid__'], sf.configSerialize(sfConfig))
print "Scan [" + sfConfig['__guid__'] + "] initiated."
# moduleList = list of modules the user wants to run
@@ -90,7 +97,7 @@ class SpiderFootDataProvider:
# 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)
+ #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
@@ -135,8 +142,8 @@ class SpiderFootDataProvider:
else:
print "Scan [" + sfConfig['__guid__'] + "] completed."
dbh.scanInstanceSet(sfConfig['__guid__'], None, time.time() * 1000, 'FINISHED')
- except Exception:
- print "Scan [" + sfConfig['__guid__'] + "] failed."
+ except Exception as e:
+ print "Scan [" + sfConfig['__guid__'] + "] failed: " + str(e)
dbh.scanInstanceSet(sfConfig['__guid__'], None, time.time() * 1000, 'ERROR-FAILED')
self.moduleInstances = None
@@ -145,12 +152,18 @@ class SpiderFootDataProvider:
class SpiderFootWebUi:
dp = None
lookup = TemplateLookup(directories=[''])
+ defaultConfig = dict()
def __init__(self, config):
+ self.defaultConfig = deepcopy(config)
# Data provider will provide all data from the DB
self.dp = SpiderFootDataProvider(config)
- self.config = config
- return
+ dbh = SpiderFootDb(config)
+ # 'config' supplied will be the defaults, let's supplement them
+ # now with any configuration which may have previously been
+ # saved.
+ sf = SpiderFoot(config)
+ self.config = sf.configUnserialize(dbh.configGet(), config)
#
# USER INTERFACE PAGES
@@ -177,9 +190,15 @@ 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='SCANINFO')
+ return templ.render(id=id, name=res[0], pageid='SCANLIST')
scaninfo.exposed = True
+ # Settings
+ def opts(self):
+ templ = Template(filename='dyn/opts.tmpl', lookup=self.lookup)
+ return templ.render(opts=self.config, pageid='SETTINGS')
+ opts.exposed = True
+
def error(self, message):
templ = Template(filename='dyn/error.tmpl', lookup=self.lookup)
return templ.render(message=message)
@@ -218,6 +237,31 @@ class SpiderFootWebUi:
return self.dp.scaneventresultsData(id, eventType)
scaneventresults.exposed = True
+ # Save settings, also used to completely reset them to default
+ def savesettings(self, allopts):
+ try:
+ dbh = SpiderFootDb(self.config)
+ # Reset config to default
+ if allopts == "RESET":
+ dbh.configClear() # Clear it in the DB
+ self.config = deepcopy(self.defaultConfig) # Clear in memory
+ else:
+ useropts = json.loads(allopts)
+ currentopts = deepcopy(self.config)
+
+ # Make a new config where the user options override
+ # 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))
+
+ templ = Template(filename='dyn/opts.tmpl', lookup=self.lookup)
+ return templ.render(opts=self.config, pageid='SETTINGS', updated=True)
+ savesettings.exposed = True
+
# Initiate a scan
def startscan(self, scanname, scantarget, modulelist):
modopts = dict()
@@ -235,7 +279,7 @@ class SpiderFootWebUi:
# 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, modopts))
+ t = threading.Thread(name="SF_" + scanname, target=self.dp.startScan, args=(scanname, scantarget, modlist, self.config, modopts))
t.start()
templ = Template(filename='dyn/scanlist.tmpl', lookup=self.lookup)
diff --git a/spiderfoot.schema b/spiderfoot.schema
index 3c1575d0..a78b4bb8 100644
--- a/spiderfoot.schema
+++ b/spiderfoot.schema
@@ -23,6 +23,17 @@ CREATE TABLE tbl_event_types (
event_descr VARCHAR NOT NULL
);
+--
+-- Configuration: The configuration last set.
+--
+DROP TABLE tbl_config;
+CREATE TABLE tbl_config (
+ scope VARCHAR NOT NULL,
+ opt VARCHAR NOT NULL,
+ val VARCHAR NOT NULL,
+ PRIMARY KEY (scope, opt)
+);
+
--
-- Scan instances: Each scan run by the user against a target.
--