Skip to content

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

sfwebui: Return JSON from various routes (#1213)

bcolesb81b1e5d9f24
diff --git a/sfwebui.py b/sfwebui.py
index 9059b25a..6610b30e 100644
--- a/sfwebui.py
+++ b/sfwebui.py
@@ -184,6 +184,9 @@ class SpiderFootWebUi:
ret = list()
for item in inputList:
+ if not item:
+ ret.append('')
+ continue
c = html.escape(item, True)
c = c.replace('\'', '"')
# We don't actually want & translated to &
@@ -203,10 +206,9 @@ class SpiderFootWebUi:
Returns:
list: search results
"""
-
retdata = []
- if [id, eventType, value].count('') == 3 or [id, eventType, value].count(None) == 3:
+ if not id and not eventType and not value:
return retdata
if not value:
@@ -224,10 +226,10 @@ class SpiderFootWebUi:
dbh = SpiderFootDb(self.config)
criteria = {
- 'scan_id': None if id == '' else id,
- 'type': None if eventType == '' else eventType,
- 'value': None if value == '' else value,
- 'regex': None if regex == '' else regex
+ 'scan_id': id or '',
+ 'type': eventType or '',
+ 'value': value or '',
+ 'regex': regex or '',
}
try:
@@ -249,6 +251,7 @@ class SpiderFootWebUi:
# USER INTERFACE PAGES
#
+ @cherrypy.expose
def scaneventresultexport(self, id, type, dialect="excel"):
"""Get scan event result data in CSV format
@@ -277,8 +280,7 @@ class SpiderFootWebUi:
cherrypy.response.headers['Pragma'] = "no-cache"
return fileobj.getvalue().encode('utf-8')
- scaneventresultexport.exposed = True
-
+ @cherrypy.expose
def scaneventresultexportmulti(self, ids, dialect="excel"):
"""Get scan event result data in CSV format for multiple scans
@@ -312,8 +314,7 @@ class SpiderFootWebUi:
cherrypy.response.headers['Pragma'] = "no-cache"
return fileobj.getvalue().encode('utf-8')
- scaneventresultexportmulti.exposed = True
-
+ @cherrypy.expose
def scansearchresultexport(self, id, eventType=None, value=None, dialect="excel"):
"""Get search result data in CSV format
@@ -343,8 +344,7 @@ class SpiderFootWebUi:
cherrypy.response.headers['Pragma'] = "no-cache"
return fileobj.getvalue().encode('utf-8')
- scansearchresultexport.exposed = True
-
+ @cherrypy.expose
def scanexportjsonmulti(self, ids):
"""Get scan event result data in JSON format for multiple scans
@@ -399,8 +399,7 @@ class SpiderFootWebUi:
cherrypy.response.headers['Pragma'] = "no-cache"
return json.dumps(scaninfo).encode('utf-8')
- scanexportjsonmulti.exposed = True
-
+ @cherrypy.expose
def scanviz(self, id, gexf="0"):
"""Export entities from scan results for visualising
@@ -432,8 +431,7 @@ class SpiderFootWebUi:
cherrypy.response.headers['Pragma'] = "no-cache"
return SpiderFootHelpers.buildGraphGexf([root], "SpiderFoot Export", data)
- scanviz.exposed = True
-
+ @cherrypy.expose
def scanvizmulti(self, ids, gexf="1"):
"""Export entities results from multiple scans in GEXF format
@@ -444,7 +442,6 @@ class SpiderFootWebUi:
Returns:
string: GEXF data
"""
-
dbh = SpiderFootDb(self.config)
data = list()
roots = list()
@@ -467,8 +464,8 @@ class SpiderFootWebUi:
cherrypy.response.headers['Pragma'] = "no-cache"
return SpiderFootHelpers.buildGraphGexf(roots, "SpiderFoot Export", data)
- scanvizmulti.exposed = True
-
+ @cherrypy.expose
+ @cherrypy.tools.json_out()
def scanopts(self, id):
"""Configuration used for a scan
@@ -478,9 +475,24 @@ class SpiderFootWebUi:
Returns:
str: options as JSON string
"""
-
- ret = dict()
dbh = SpiderFootDb(self.config)
+ ret = dict()
+
+ meta = dbh.scanInstanceGet(id)
+ if not meta:
+ return ret
+
+ if meta[3] != 0:
+ started = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(meta[3]))
+ else:
+ started = "Not yet"
+
+ if meta[4] != 0:
+ finished = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(meta[4]))
+ else:
+ finished = "Not yet"
+
+ ret['meta'] = [meta[0], meta[1], meta[2], started, finished, meta[5]]
ret['config'] = dbh.scanConfigGet(id)
ret['configdesc'] = dict()
for key in list(ret['config'].keys()):
@@ -498,24 +510,9 @@ class SpiderFootWebUi:
ret['configdesc'][key] = self.config['__modules__'][modName]['optdescs'][modOpt]
- meta = dbh.scanInstanceGet(id)
- if not meta:
- return json.dumps([]).encode('utf-8')
- if meta[3] != 0:
- started = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(meta[3]))
- else:
- started = "Not yet"
-
- if meta[4] != 0:
- finished = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(meta[4]))
- else:
- finished = "Not yet"
- ret['meta'] = [meta[0], meta[1], meta[2], started, finished, meta[5]]
-
- return json.dumps(ret).encode('utf-8')
-
- scanopts.exposed = True
+ return ret
+ @cherrypy.expose
def rerunscan(self, id):
"""Rerun a scan
@@ -577,8 +574,7 @@ class SpiderFootWebUi:
raise cherrypy.HTTPRedirect(f"{self.docroot}/scaninfo?id={scanId}", status=302)
- rerunscan.exposed = True
-
+ @cherrypy.expose
def rerunscanmulti(self, ids):
"""Rerun scans
@@ -635,8 +631,7 @@ class SpiderFootWebUi:
templ = Template(filename='dyn/scanlist.tmpl', lookup=self.lookup)
return templ.render(rerunscans=True, docroot=self.docroot, pageid="SCANLIST", version=__version__)
- rerunscanmulti.exposed = True
-
+ @cherrypy.expose
def newscan(self):
"""Configure a new scan
@@ -651,8 +646,7 @@ class SpiderFootWebUi:
modules=self.config['__modules__'], scanname="",
selectedmods="", scantarget="", version=__version__)
- newscan.exposed = True
-
+ @cherrypy.expose
def clonescan(self, id):
"""
Clone an existing scan (pre-selected options in the newscan page)
@@ -692,8 +686,7 @@ class SpiderFootWebUi:
scanname=str(scanname),
scantarget=str(scantarget), version=__version__)
- clonescan.exposed = True
-
+ @cherrypy.expose
def index(self):
"""Main page listing scans available
@@ -704,8 +697,7 @@ class SpiderFootWebUi:
templ = Template(filename='dyn/scanlist.tmpl', lookup=self.lookup)
return templ.render(pageid='SCANLIST', docroot=self.docroot, version=__version__)
- index.exposed = True
-
+ @cherrypy.expose
def scaninfo(self, id):
"""Information about a selected scan
@@ -725,8 +717,7 @@ class SpiderFootWebUi:
return templ.render(id=id, name=html.escape(res[0]), status=res[5], docroot=self.docroot, version=__version__,
pageid="SCANLIST")
- scaninfo.exposed = True
-
+ @cherrypy.expose
def opts(self, updated=None):
"""Settings
@@ -742,8 +733,7 @@ class SpiderFootWebUi:
return templ.render(opts=self.config, pageid='SETTINGS', token=self.token, version=__version__,
updated=updated, docroot=self.docroot)
- opts.exposed = True
-
+ @cherrypy.expose
def optsexport(self, pattern=None):
"""Export configuration
@@ -772,17 +762,14 @@ class SpiderFootWebUi:
cherrypy.response.headers['Content-Type'] = "text/plain"
return content
- optsexport.exposed = True
-
+ @cherrypy.expose
+ @cherrypy.tools.json_out()
def optsraw(self):
"""Settings
Returns:
str: settings as JSON
"""
-
- cherrypy.response.headers['Content-Type'] = "application/json; charset=utf-8"
-
ret = dict()
self.token = random.SystemRandom().randint(0, 99999999)
for opt in self.config:
@@ -797,9 +784,7 @@ class SpiderFootWebUi:
continue
ret["module." + mod + "." + mo] = self.config['__modules__'][mod]['opts'][mo]
- return json.dumps(['SUCCESS', {'token': self.token, 'data': ret}]).encode('utf-8')
-
- optsraw.exposed = True
+ return ['SUCCESS', {'token': self.token, 'data': ret}]
@cherrypy.expose
@cherrypy.tools.json_out()
@@ -831,6 +816,7 @@ class SpiderFootWebUi:
return b""
+ @cherrypy.expose
def savesettings(self, allopts, token, configFile=None):
"""Save settings, also used to completely reset them to default
@@ -898,8 +884,7 @@ class SpiderFootWebUi:
raise cherrypy.HTTPRedirect(f"{self.docroot}/opts?updated=1")
- savesettings.exposed = True
-
+ @cherrypy.expose
def savesettingsraw(self, allopts, token):
"""Save settings, also used to completely reset them to default
@@ -942,8 +927,6 @@ class SpiderFootWebUi:
return json.dumps(["SUCCESS", ""]).encode('utf-8')
- savesettingsraw.exposed = True
-
def reset_settings(self):
"""Reset settings to default.
@@ -960,6 +943,7 @@ class SpiderFootWebUi:
return True
+ @cherrypy.expose
def resultsetfp(self, id, resultids, fp):
"""Set a bunch of results (hashes) as false positive
@@ -1016,10 +1000,10 @@ class SpiderFootWebUi:
return json.dumps(["ERROR", "Exception encountered."]).encode('utf-8')
- resultsetfp.exposed = True
-
+ @cherrypy.expose
+ @cherrypy.tools.json_out()
def eventtypes(self):
- """For the CLI to fetch a list of event types.
+ """List all event types.
Returns:
str: list of event types
@@ -1034,14 +1018,12 @@ class SpiderFootWebUi:
for r in types:
ret.append([r[1], r[0]])
- ret = sorted(ret, key=itemgetter(0))
-
- return json.dumps(ret).encode('utf-8')
-
- eventtypes.exposed = True
+ return sorted(ret, key=itemgetter(0))
+ @cherrypy.expose
+ @cherrypy.tools.json_out()
def modules(self):
- """For the CLI to fetch a list of modules.
+ """List all modules.
Returns:
str: list of modules
@@ -1057,23 +1039,20 @@ class SpiderFootWebUi:
continue
ret.append({'name': m, 'descr': self.config['__modules__'][m]['descr']})
- return json.dumps(ret).encode('utf-8')
-
- modules.exposed = True
+ return ret
+ @cherrypy.expose
+ @cherrypy.tools.json_out()
def ping(self):
"""For the CLI to test connectivity to this server.
Returns:
str: SpiderFoot version as JSON
"""
+ return ["SUCCESS", __version__]
- cherrypy.response.headers['Content-Type'] = "application/json; charset=utf-8"
-
- return json.dumps(["SUCCESS", __version__]).encode('utf-8')
-
- ping.exposed = True
-
+ @cherrypy.expose
+ @cherrypy.tools.json_out()
def query(self, query):
"""For the CLI to run queries against the database.
@@ -1083,39 +1062,32 @@ class SpiderFootWebUi:
Returns:
str: query results as JSON
"""
-
- cherrypy.response.headers['Content-Type'] = "application/json; charset=utf-8"
-
- data = None
dbh = SpiderFootDb(self.config)
if not query:
- return json.dumps(["ERROR", "Invalid query."]).encode('utf-8')
+ return self.jsonify_error('400', "Invalid query.")
if not query.lower().startswith("select"):
- return json.dumps(["ERROR", "Non-SELECTs are unpredictable and not recommended."]).encode('utf-8')
+ return self.jsonify_error('400', "Non-SELECTs are unpredictable and not recommended.")
try:
ret = dbh.dbh.execute(query)
data = ret.fetchall()
columnNames = [c[0] for c in dbh.dbh.description]
- data = [dict(zip(columnNames, row)) for row in data]
+ return [dict(zip(columnNames, row)) for row in data]
except Exception as e:
- return json.dumps(["ERROR", str(e)]).encode('utf-8')
-
- return json.dumps(data).encode('utf-8')
-
- query.exposed = True
+ return self.jsonify_error('500', str(e))
+ @cherrypy.expose
def startscan(self, scanname, scantarget, modulelist, typelist, usecase):
"""Initiate a scan
Args:
scanname (str): scan name
scantarget (str): scan target
- modulelist (str): TBD
- typelist (str): TBD
- usecase (str): module group (passive, investigate, footprint, all)
+ modulelist (str): comma separated list of modules to use
+ typelist (str): selected modules based on produced event data types
+ usecase (str): selected module group (passive, investigate, footprint, all)
Returns:
str: start scan status as JSON
@@ -1123,37 +1095,52 @@ class SpiderFootWebUi:
Raises:
HTTPRedirect: redirect to new scan info page
"""
+ [scanname, scantarget] = self.cleanUserInput([scanname, scantarget])
- # Swap the globalscantable for the database handler
- dbh = SpiderFootDb(self.config)
+ if not scanname:
+ if cherrypy.request.headers.get('Accept') and 'application/json' in cherrypy.request.headers.get('Accept'):
+ cherrypy.response.headers['Content-Type'] = "application/json; charset=utf-8"
+ return json.dumps(["ERROR", "Incorrect usage: scan name was not specified."]).encode('utf-8')
- # Snapshot the current configuration to be used by the scan
- cfg = deepcopy(self.config)
- modlist = list()
- sf = SpiderFoot(cfg)
- targetType = None
- [scanname, scantarget] = self.cleanUserInput([scanname, scantarget])
+ return self.error("Invalid request: scan name was not specified.")
- if scanname == "" or scantarget == "":
+ if not scantarget:
if cherrypy.request.headers.get('Accept') and 'application/json' in cherrypy.request.headers.get('Accept'):
cherrypy.response.headers['Content-Type'] = "application/json; charset=utf-8"
- return json.dumps(["ERROR", "Incorrect usage: scan name or target was not specified."]).encode('utf-8')
+ return json.dumps(["ERROR", "Incorrect usage: scan target was not specified."]).encode('utf-8')
- return self.error("Invalid request: scan name or target was not specified.")
+ return self.error("Invalid request: scan target was not specified.")
- if typelist == "" and modulelist == "" and usecase == "":
+ if not typelist and not modulelist and not usecase:
if cherrypy.request.headers.get('Accept') and 'application/json' in cherrypy.request.headers.get('Accept'):
cherrypy.response.headers['Content-Type'] = "application/json; charset=utf-8"
return json.dumps(["ERROR", "Incorrect usage: no modules specified for scan."]).encode('utf-8')
return self.error("Invalid request: no modules specified for scan.")
+ targetType = SpiderFootHelpers.targetType(scantarget)
+ if targetType is None:
+ if cherrypy.request.headers.get('Accept') and 'application/json' in cherrypy.request.headers.get('Accept'):
+ cherrypy.response.headers['Content-Type'] = "application/json; charset=utf-8"
+ return json.dumps(["ERROR", "Unrecognised target type."]).encode('utf-8')
+
+ return self.error("Invalid target type. Could not recognize it as a target SpiderFoot supports.")
+
+ # Swap the globalscantable for the database handler
+ dbh = SpiderFootDb(self.config)
+
+ # Snapshot the current configuration to be used by the scan
+ cfg = deepcopy(self.config)
+ sf = SpiderFoot(cfg)
+
+ modlist = list()
+
# User selected modules
- if modulelist != "":
+ if modulelist:
modlist = modulelist.replace('module_', '').split(',')
# User selected types
- if len(modlist) == 0 and typelist != "":
+ if len(modlist) == 0 and typelist:
typesx = typelist.replace('type_', '').split(',')
# 1. Find all modules that produce the requested types
@@ -1173,23 +1160,23 @@ class SpiderFootWebUi:
newmods = list()
# User selected a use case
- if len(modlist) == 0 and usecase != "":
+ if len(modlist) == 0 and usecase:
for mod in self.config['__modules__']:
if usecase == 'all' or usecase in self.config['__modules__'][mod]['group']:
modlist.append(mod)
- # Add our mandatory storage module..
- if "sfp__stor_db" not in modlist:
- modlist.append("sfp__stor_db")
- modlist.sort()
-
- targetType = SpiderFootHelpers.targetType(scantarget)
- if targetType is None:
+ # If we somehow got all the way through to here and still don't have any modules selected
+ if not modlist:
if cherrypy.request.headers.get('Accept') and 'application/json' in cherrypy.request.headers.get('Accept'):
cherrypy.response.headers['Content-Type'] = "application/json; charset=utf-8"
- return json.dumps(["ERROR", "Unrecognised target type."]).encode('utf-8')
+ return json.dumps(["ERROR", "Incorrect usage: no modules specified for scan."]).encode('utf-8')
- return self.error("Invalid target type. Could not recognize it as a target SpiderFoot supports.")
+ return self.error("Invalid request: no modules specified for scan.")
+
+ # Add our mandatory storage module
+ if "sfp__stor_db" not in modlist:
+ modlist.append("sfp__stor_db")
+ modlist.sort()
# Delete the stdout module in case it crept in
if "sfp__stor_stdout" in modlist:
@@ -1223,8 +1210,6 @@ class SpiderFootWebUi:
raise cherrypy.HTTPRedirect(f"{self.docroot}/scaninfo?id={scanId}")
- startscan.exposed = True
-
@cherrypy.expose
@cherrypy.tools.json_out()
def stopscan(self, id):
@@ -1267,6 +1252,8 @@ class SpiderFootWebUi:
# DATA PROVIDERS
#
+ @cherrypy.expose
+ @cherrypy.tools.json_out()
def scanlog(self, id, limit=None, rowId=None, reverse=None):
"""Scan log data
@@ -1279,27 +1266,24 @@ class SpiderFootWebUi:
Returns:
str: JSON
"""
-
- cherrypy.response.headers['Content-Type'] = "application/json; charset=utf-8"
-
dbh = SpiderFootDb(self.config)
retdata = []
try:
data = dbh.scanLogs(id, limit, rowId, reverse)
except Exception:
- return json.dumps(retdata).encode('utf-8')
+ return 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], html.escape(row[3]), row[4]])
- return json.dumps(retdata).encode('utf-8')
-
- scanlog.exposed = True
+ return retdata
+ @cherrypy.expose
+ @cherrypy.tools.json_out()
def scanerrors(self, id, limit=None):
- """Scan error data
+ """Scan error data.
Args:
id (str): scan ID
@@ -1308,37 +1292,32 @@ class SpiderFootWebUi:
Returns:
str: scan errors as JSON
"""
-
- cherrypy.response.headers['Content-Type'] = "application/json; charset=utf-8"
-
dbh = SpiderFootDb(self.config)
retdata = []
try:
data = dbh.scanErrors(id, limit)
except Exception:
- return json.dumps(retdata).encode('utf-8')
+ return retdata
for row in data:
generated = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(row[0] / 1000))
retdata.append([generated, row[1], html.escape(str(row[2]))])
- return json.dumps(retdata).encode('utf-8')
-
- scanerrors.exposed = True
+ return retdata
+ @cherrypy.expose
+ @cherrypy.tools.json_out()
def scanlist(self):
"""Produce a list of scans.
Returns:
str: scan list as JSON
"""
-
- cherrypy.response.headers['Content-Type'] = "application/json; charset=utf-8"
-
dbh = SpiderFootDb(self.config)
data = dbh.scanInstanceList()
retdata = []
+
for row in data:
created = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(row[3]))
@@ -1354,12 +1333,12 @@ class SpiderFootWebUi:
retdata.append([row[0], row[1], row[2], created, started, finished, row[6], row[7]])
- return json.dumps(retdata).encode('utf-8')
-
- scanlist.exposed = True
+ return retdata
+ @cherrypy.expose
+ @cherrypy.tools.json_out()
def scanstatus(self, id):
- """Basic information about a scan
+ """Basic information about a scan.
Args:
id (str): scan ID
@@ -1367,37 +1346,30 @@ class SpiderFootWebUi:
Returns:
str: scan status as JSON
"""
-
- cherrypy.response.headers['Content-Type'] = "application/json; charset=utf-8"
-
dbh = SpiderFootDb(self.config)
data = dbh.scanInstanceGet(id)
if not data:
- return json.dumps([]).encode('utf-8')
+ return []
created = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(data[2]))
started = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(data[3]))
ended = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(data[4]))
- retdata = [data[0], data[1], created, started, ended, data[5]]
- return json.dumps(retdata).encode('utf-8')
-
- scanstatus.exposed = True
+ return [data[0], data[1], created, started, ended, data[5]]
+ @cherrypy.expose
+ @cherrypy.tools.json_out()
def scansummary(self, id, by):
- """Summary of scan results
+ """Summary of scan results.
Args:
id (str): scan ID
by: TBD
Returns:
- scan summary as JSON
+ str: scan summary as JSON
"""
-
- cherrypy.response.headers['Content-Type'] = "application/json; charset=utf-8"
-
retdata = []
dbh = SpiderFootDb(self.config)
@@ -1405,24 +1377,25 @@ class SpiderFootWebUi:
try:
scandata = dbh.scanResultSummary(id, by)
except Exception:
- return json.dumps(retdata).encode('utf-8')
+ return retdata
try:
statusdata = dbh.scanInstanceGet(id)
except Exception:
- return json.dumps(retdata).encode('utf-8')
+ return retdata
for row in scandata:
if row[0] == "ROOT":
continue
lastseen = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(row[2]))
retdata.append([row[0], row[1], lastseen, row[3], row[4], statusdata[5]])
- return json.dumps(retdata).encode('utf-8')
- scansummary.exposed = True
+ return retdata
+ @cherrypy.expose
+ @cherrypy.tools.json_out()
def scaneventresults(self, id, eventType, filterfp=False):
- """Event results for a scan
+ """Event results for a scan.
Args:
id (str): scan ID
@@ -1432,9 +1405,6 @@ class SpiderFootWebUi:
Returns:
str: scan results as JSON
"""
-
- cherrypy.response.headers['Content-Type'] = "application/json; charset=utf-8"
-
retdata = []
dbh = SpiderFootDb(self.config)
@@ -1442,71 +1412,73 @@ class SpiderFootWebUi:
try:
data = dbh.scanResultEvent(id, eventType, filterfp)
except Exception:
- return json.dumps(retdata).encode('utf-8')
+ return retdata
for row in data:
lastseen = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(row[0]))
- escapeddata = html.escape(row[1])
- escapedsrc = html.escape(row[2])
- retdata.append([lastseen, escapeddata, escapedsrc,
- row[3], row[5], row[6], row[7], row[8],
- row[13], row[14], row[4]])
- return json.dumps(retdata).encode('utf-8')
+ retdata.append([
+ lastseen,
+ html.escape(row[1]),
+ html.escape(row[2]),
+ row[3],
+ row[5],
+ row[6],
+ row[7],
+ row[8],
+ row[13],
+ row[14],
+ row[4]
+ ])
- scaneventresults.exposed = True
+ return retdata
+ @cherrypy.expose
+ @cherrypy.tools.json_out()
def scaneventresultsunique(self, id, eventType, filterfp=False):
- """Unique event results for a scan
+ """Unique event results for a scan.
Args:
- id (str): scan ID
- eventType (str): filter by event type
- filterfp: TBD
+ id (str): filter search results by scan ID
+ eventType (str): filter search results by event type
+ filterfp (bool): remove false positives from search results
Returns:
- str: unique results as JSON
+ str: unique search results as JSON
"""
-
- cherrypy.response.headers['Content-Type'] = "application/json; charset=utf-8"
-
dbh = SpiderFootDb(self.config)
retdata = []
try:
data = dbh.scanResultEventUnique(id, eventType, filterfp)
except Exception:
- return json.dumps(retdata).encode('utf-8')
+ return retdata
for row in data:
escaped = html.escape(row[0])
retdata.append([escaped, row[1], row[2]])
- return json.dumps(retdata).encode('utf-8')
- scaneventresultsunique.exposed = True
+ return retdata
+ @cherrypy.expose
+ @cherrypy.tools.json_out()
def search(self, id=None, eventType=None, value=None):
- """Search
+ """Search scans.
Args:
- id: TBD
- eventType (str): filter by event type
- value: TBD
+ id (str): filter search results by scan ID
+ eventType (str): filter search results by event type
+ value (str): filter search results by event value
Returns:
str: search results as JSON
"""
-
- cherrypy.response.headers['Content-Type'] = "application/json; charset=utf-8"
-
try:
- search_results = self.searchBase(id, eventType, value)
+ return self.searchBase(id, eventType, value)
except Exception:
- search_results = []
-
- return json.dumps(search_results).encode('utf-8')
-
- search.exposed = True
+ return []
+ @cherrypy.expose
+ @cherrypy.tools.json_out()
def scanhistory(self, id):
"""Historical data for a scan.
@@ -1516,33 +1488,28 @@ class SpiderFootWebUi:
Returns:
str: scan history as JSON
"""
-
- cherrypy.response.headers['Content-Type'] = "application/json; charset=utf-8"
+ if not id:
+ return self.jsonify_error('404', "No scan specified")
dbh = SpiderFootDb(self.config)
try:
- scan_history = dbh.scanResultHistory(id)
+ return dbh.scanResultHistory(id)
except Exception:
- scan_history = []
-
- return json.dumps(scan_history).encode('utf-8')
-
- scanhistory.exposed = True
+ return []
+ @cherrypy.expose
+ @cherrypy.tools.json_out()
def scanelementtypediscovery(self, id, eventType):
- """scan element type discovery
+ """Scan element type discovery.
Args:
- id: TBD
+ id (str): scan ID
eventType (str): filter by event type
Returns:
str: JSON
"""
-
- cherrypy.response.headers['Content-Type'] = "application/json; charset=utf-8"
-
dbh = SpiderFootDb(self.config)
pc = dict()
datamap = dict()
@@ -1553,13 +1520,11 @@ class SpiderFootWebUi:
leafSet = dbh.scanResultEvent(id, eventType)
[datamap, pc] = dbh.scanElementSourcesAll(id, leafSet)
except Exception:
- return json.dumps(retdata).encode('utf-8')
+ return retdata
# Delete the ROOT key as it adds no value from a viz perspective
del pc['ROOT']
retdata['tree'] = SpiderFootHelpers.dataParentChildToTree(pc)
retdata['data'] = datamap
- return json.dumps(retdata).encode('utf-8')
-
- scanelementtypediscovery.exposed = True
+ return retdata
diff --git a/test/integration/test_sfwebui.py b/test/integration/test_sfwebui.py
index b4826fc1..6a5be518 100644
--- a/test/integration/test_sfwebui.py
+++ b/test/integration/test_sfwebui.py
@@ -208,19 +208,35 @@ class TestSpiderFootWebUiRoutes(helper.CPWebCase):
self.assertStatus('200 OK')
self.assertInBody('[{"1": 1}]')
- def test_startscan(self):
+ def test_startscan_invalid_scan_name_returns_error(self):
self.getPage("/startscan?scanname=&scantarget=&modulelist=&typelist=&usecase=")
self.assertStatus('200 OK')
- self.assertInBody('Invalid request: scan name or target was not specified.')
+ self.assertInBody('Invalid request: scan name was not specified.')
- self.getPage("/startscan?scanname=example-scan&scantarget=invalid-target&modulelist=&typelist=&usecase=")
+ def test_startscan_invalid_scan_target_returns_error(self):
+ self.getPage("/startscan?scanname=example-scan&scantarget=&modulelist=&typelist=&usecase=")
self.assertStatus('200 OK')
- self.assertInBody('Invalid request: no modules specified for scan.')
+ self.assertInBody('Invalid request: scan target was not specified.')
+ def test_startscan_unrecognized_scan_target_returns_error(self):
self.getPage("/startscan?scanname=example-scan&scantarget=invalid-target&modulelist=doesnotexist&typelist=doesnotexist&usecase=doesnotexist")
self.assertStatus('200 OK')
self.assertInBody('Invalid target type. Could not recognize it as a target SpiderFoot supports.')
+ def test_startscan_invalid_modules_returns_error(self):
+ self.getPage("/startscan?scanname=example-scan&scantarget=spiderfoot.net&modulelist=&typelist=&usecase=")
+ self.assertStatus('200 OK')
+ self.assertInBody('Invalid request: no modules specified for scan.')
+
+ def test_startscan_invalid_typelist_returns_error(self):
+ self.getPage("/startscan?scanname=example-scan&scantarget=spiderfoot.net&modulelist=&typelist=doesnotexist&usecase=")
+ self.assertStatus('200 OK')
+ self.assertInBody('Invalid request: no modules specified for scan.')
+
+ def test_startscan_should_start_a_scan(self):
+ self.getPage("/startscan?scanname=spiderfoot.net&scantarget=spiderfoot.net&modulelist=doesnotexist&typelist=doesnotexist&usecase=doesnotexist")
+ self.assertStatus('303 See Other')
+
def test_stopscan_invalid_scan_id_returns_404(self):
self.getPage("/stopscan?id=doesnotexist")
self.assertStatus('404 Not Found')
diff --git a/test/unit/test_spiderfootwebui.py b/test/unit/test_spiderfootwebui.py
index 09c51843..9d4621e9 100644
--- a/test/unit/test_spiderfootwebui.py
+++ b/test/unit/test_spiderfootwebui.py
@@ -241,7 +241,7 @@ class TestSpiderFootWebUi(unittest.TestCase):
opts_export = sfwebui.optsexport(None)
self.assertIsInstance(opts_export, str)
- def test_optsraw_should_return_bytes(self):
+ def test_optsraw_should_return_a_list(self):
"""
Test optsraw(self)
"""
@@ -249,7 +249,8 @@ class TestSpiderFootWebUi(unittest.TestCase):
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
opts_raw = sfwebui.optsraw()
- self.assertIsInstance(opts_raw, bytes)
+ self.assertIsInstance(opts_raw, list)
+ self.assertEqual(opts_raw[0], 'SUCCESS')
def test_error(self):
"""
@@ -296,7 +297,7 @@ class TestSpiderFootWebUi(unittest.TestCase):
"""
self.assertEqual('TBD', 'TBD')
- def test_eventtypes_should_return_bytes(self):
+ def test_eventtypes_should_return_list(self):
"""
Test eventtypes(self)
"""
@@ -304,9 +305,9 @@ class TestSpiderFootWebUi(unittest.TestCase):
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
event_types = sfwebui.eventtypes()
- self.assertIsInstance(event_types, bytes)
+ self.assertIsInstance(event_types, list)
- def test_modules_should_return_bytes(self):
+ def test_modules_should_return_list(self):
"""
Test modules(self)
"""
@@ -314,9 +315,9 @@ class TestSpiderFootWebUi(unittest.TestCase):
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
modules = sfwebui.eventtypes()
- self.assertIsInstance(modules, bytes)
+ self.assertIsInstance(modules, list)
- def test_ping_should_return_bytes(self):
+ def test_ping_should_return_list(self):
"""
Test ping(self)
"""
@@ -324,26 +325,109 @@ class TestSpiderFootWebUi(unittest.TestCase):
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
ping = sfwebui.ping()
- self.assertIsInstance(ping, bytes)
+ self.assertIsInstance(ping, list)
+ self.assertEqual(ping[0], 'SUCCESS')
- def test_query_should_perform_a_sql_query(self):
+ def test_query_should_perform_sql_query(self):
"""
Test query(self, query)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
- query = sfwebui.query("SELECT 12345")
- self.assertIsInstance(query, bytes)
- self.assertIn(b"12345", query)
+
+ select = "12345"
+ query = sfwebui.query(f"SELECT {select}")
+ self.assertIsInstance(query, list)
+ self.assertEqual(len(query), 1)
+ self.assertEqual(str(query[0].get(select)), str(select))
+
+ def test_query_invalid_query_should_return_error(self):
+ """
+ Test query(self, query)
+ """
+ opts = self.default_options
+ opts['__modules__'] = dict()
+ sfwebui = SpiderFootWebUi(self.web_default_options, opts)
+
+ query = sfwebui.query(None)
+ self.assertIsInstance(query, dict)
+ self.assertEqual("Invalid query.", query.get('error').get('message'))
+
+ query = sfwebui.query("UPDATE 1")
+ self.assertIsInstance(query, dict)
+ self.assertEqual("Non-SELECTs are unpredictable and not recommended.", query.get('error').get('message'))
@unittest.skip("todo")
- def test_start_scan(self):
+ def test_start_scan_should_start_a_scan(self):
"""
Test startscan(self, scanname, scantarget, modulelist, typelist, usecase)
"""
+ opts = self.default_options
+ opts['__modules__'] = dict()
+ sfwebui = SpiderFootWebUi(self.web_default_options, opts)
+ start_scan = sfwebui.startscan('example scan name', 'spiderfoot.net', 'example module list', None, None)
+ self.assertEqual(start_scan, start_scan)
self.assertEqual('TBD', 'TBD')
+ def test_start_scan_invalid_scanname_should_return_error(self):
+ """
+ Test startscan(self, scanname, scantarget, modulelist, typelist, usecase)
+ """
+ opts = self.default_options
+ opts['__modules__'] = dict()
+ sfwebui = SpiderFootWebUi(self.web_default_options, opts)
+ start_scan = sfwebui.startscan(None, 'example scan target', None, None, None)
+ self.assertIn('Invalid request: scan name was not specified.', start_scan)
+ start_scan = sfwebui.startscan('', 'example scan target', None, None, None)
+ self.assertIn('Invalid request: scan name was not specified.', start_scan)
+
+ def test_start_scan_invalid_scantarget_should_return_error(self):
+ """
+ Test startscan(self, scanname, scantarget, modulelist, typelist, usecase)
+ """
+ opts = self.default_options
+ opts['__modules__'] = dict()
+ sfwebui = SpiderFootWebUi(self.web_default_options, opts)
+ start_scan = sfwebui.startscan('example scan name', None, None, None, None)
+ self.assertIn('Invalid request: scan target was not specified.', start_scan)
+ start_scan = sfwebui.startscan('example scan name', '', None, None, None)
+ self.assertIn('Invalid request: scan target was not specified.', start_scan)
+
+ def test_start_scan_unrecognized_scantarget_type_should_return_error(self):
+ """
+ Test startscan(self, scanname, scantarget, modulelist, typelist, usecase)
+ """
+ opts = self.default_options
+ opts['__modules__'] = dict()
+ sfwebui = SpiderFootWebUi(self.web_default_options, opts)
+ start_scan = sfwebui.startscan('example scan name', 'example scan target', 'example module list', None, None)
+ self.assertIn('Invalid target type. Could not recognize it as a target SpiderFoot supports.', start_scan)
+
+ def test_start_scan_invalid_modules_should_return_error(self):
+ """
+ Test startscan(self, scanname, scantarget, modulelist, typelist, usecase)
+ """
+ opts = self.default_options
+ opts['__modules__'] = dict()
+ sfwebui = SpiderFootWebUi(self.web_default_options, opts)
+ start_scan = sfwebui.startscan('example scan name', 'spiderfoot.net', None, None, None)
+ self.assertIn('Invalid request: no modules specified for scan.', start_scan)
+ start_scan = sfwebui.startscan('example scan name', 'spiderfoot.net', '', '', '')
+ self.assertIn('Invalid request: no modules specified for scan.', start_scan)
+
+ def test_start_scan_invalid_typelist_should_return_error(self):
+ """
+ Test startscan(self, scanname, scantarget, modulelist, typelist, usecase)
+ """
+ opts = self.default_options
+ opts['__modules__'] = dict()
+ sfwebui = SpiderFootWebUi(self.web_default_options, opts)
+ start_scan = sfwebui.startscan('example scan name', 'spiderfoot.net', None, 'invalid type list', None)
+ self.assertIn('Invalid request: no modules specified for scan.', start_scan)
+ start_scan = sfwebui.startscan('example scan name', 'spiderfoot.net', '', 'invalid type list', '')
+ self.assertIn('Invalid request: no modules specified for scan.', start_scan)
+
def test_stopscan_invalid_scanid_should_return_an_error(self):
"""
Test stopscan(self, id)
@@ -355,7 +439,7 @@ class TestSpiderFootWebUi(unittest.TestCase):
self.assertIsInstance(stop_scan, dict)
self.assertEqual("Scan example scan id does not exist", stop_scan.get('error').get('message'))
- def test_scanlog_should_return_bytes(self):
+ def test_scanlog_should_return_a_list(self):
"""
Test scanlog(self, id, limit=None, rowId=None, reverse=None)
"""
@@ -363,9 +447,11 @@ class TestSpiderFootWebUi(unittest.TestCase):
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
scan_log = sfwebui.scanlog(None, None, None, None)
- self.assertIsInstance(scan_log, bytes)
+ self.assertIsInstance(scan_log, list)
+ scan_log = sfwebui.scanlog('', '', '', '')
+ self.assertIsInstance(scan_log, list)
- def test_scanerrors_should_return_bytes(self):
+ def test_scanerrors_should_return_a_list(self):
"""
Test scanerrors(self, id, limit=None)
"""
@@ -373,9 +459,11 @@ class TestSpiderFootWebUi(unittest.TestCase):
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
scan_errors = sfwebui.scanerrors(None, None)
- self.assertIsInstance(scan_errors, bytes)
+ self.assertIsInstance(scan_errors, list)
+ scan_errors = sfwebui.scanerrors('', '')
+ self.assertIsInstance(scan_errors, list)
- def test_scanlist_should_return_bytes(self):
+ def test_scanlist_should_return_a_list(self):
"""
Test scanlist(self)
"""
@@ -383,9 +471,9 @@ class TestSpiderFootWebUi(unittest.TestCase):
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
scan_list = sfwebui.scanlist()
- self.assertIsInstance(scan_list, bytes)
+ self.assertIsInstance(scan_list, list)
- def test_scanstatus_should_return_bytes(self):
+ def test_scanstatus_should_return_a_list(self):
"""
Test scanstatus(self, id)
"""
@@ -393,9 +481,9 @@ class TestSpiderFootWebUi(unittest.TestCase):
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
scan_status = sfwebui.scanstatus("example scan instance")
- self.assertIsInstance(scan_status, bytes)
+ self.assertIsInstance(scan_status, list)
- def test_scansummary_should_return_bytes(self):
+ def test_scansummary_should_return_a_list(self):
"""
Test scansummary(self, id, by)
"""
@@ -403,9 +491,11 @@ class TestSpiderFootWebUi(unittest.TestCase):
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
scan_summary = sfwebui.scansummary(None, None)
- self.assertIsInstance(scan_summary, bytes)
+ self.assertIsInstance(scan_summary, list)
+ scan_summary = sfwebui.scansummary('', '')
+ self.assertIsInstance(scan_summary, list)
- def test_scaneventresults_should_return_bytes(self):
+ def test_scaneventresults_should_return_a_list(self):
"""
Test scaneventresults(self, id, eventType, filterfp=False)
"""
@@ -413,10 +503,11 @@ class TestSpiderFootWebUi(unittest.TestCase):
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
scan_results = sfwebui.scaneventresults(None, None, None)
- self.assertIsInstance(scan_results, bytes)
+ self.assertIsInstance(scan_results, list)
+ scan_results = sfwebui.scaneventresults('', '', '')
+ self.assertIsInstance(scan_results, list)
- @unittest.skip("todo")
- def test_scaneventresultsunique_should_return_a_string(self):
+ def test_scaneventresultsunique_should_return_a_list(self):
"""
Test scaneventresultsunique(self, id, eventType, filterfp=False)
"""
@@ -424,9 +515,11 @@ class TestSpiderFootWebUi(unittest.TestCase):
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
scan_results = sfwebui.scaneventresultsunique(None, None, None)
- self.assertIsInstance(scan_results, str)
+ self.assertIsInstance(scan_results, list)
+ scan_results = sfwebui.scaneventresultsunique('', '', '')
+ self.assertIsInstance(scan_results, list)
- def test_search_should_return_bytes(self):
+ def test_search_should_return_a_list(self):
"""
Test search(self, id=None, eventType=None, value=None)
"""
@@ -434,20 +527,35 @@ class TestSpiderFootWebUi(unittest.TestCase):
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
search_results = sfwebui.search(None, None, None)
- self.assertIsInstance(search_results, bytes)
+ self.assertIsInstance(search_results, list)
+ search_results = sfwebui.search('', '', '')
+ self.assertIsInstance(search_results, list)
- def test_scan_history_should_return_bytes(self):
+ def test_scan_history_missing_scanid_should_return_error(self):
"""
Test scanhistory(self, id)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
+
scan_history = sfwebui.scanhistory(None)
- self.assertIsInstance(scan_history, bytes)
+ self.assertIsInstance(scan_history, dict)
+ self.assertEqual("No scan specified", scan_history.get('error').get('message'))
+ scan_history = sfwebui.scanhistory("example scan id")
+ self.assertIsInstance(scan_history, list)
- @unittest.skip("todo")
- def test_scan_element_type_discovery_should_return_a_string(self):
+ def test_scan_history_should_return_a_list(self):
+ """
+ Test scanhistory(self, id)
+ """
+ opts = self.default_options
+ opts['__modules__'] = dict()
+ sfwebui = SpiderFootWebUi(self.web_default_options, opts)
+ scan_history = sfwebui.scanhistory("example scan id")
+ self.assertIsInstance(scan_history, list)
+
+ def test_scan_element_type_discovery_should_return_a_dict(self):
"""
Test scanelementtypediscovery(self, id, eventType)
"""
@@ -455,4 +563,6 @@ class TestSpiderFootWebUi(unittest.TestCase):
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
scan_element_type_discovery = sfwebui.scanelementtypediscovery(None, None)
- self.assertIsInstance(scan_element_type_discovery, str)
+ self.assertIsInstance(scan_element_type_discovery, dict)
+ scan_element_type_discovery = sfwebui.scanelementtypediscovery('', '')
+ self.assertIsInstance(scan_element_type_discovery, dict)