Skip to content

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

Functionality for database back-end storage of results.

Steve Micallefa8eab37f165f
diff --git a/modules/sfp_pageinfo.py b/modules/sfp_pageinfo.py
index 7d6e3d85..34939e89 100644
--- a/modules/sfp_pageinfo.py
+++ b/modules/sfp_pageinfo.py
@@ -65,6 +65,12 @@ class sfp_pageinfo(SpiderFootPlugin):
def handleEvent(self, srcModuleName, eventName, eventSource, eventData):
sf.debug("Received event, " + eventName + ", from " + srcModuleName)
+ # We aren't interested in describing pages that are not hosted on
+ # our base domain.
+ if not eventSource.endswith(self.baseDomain):
+ sf.debug("Not gathering page info for " + eventSource)
+ return None
+
if eventSource not in results.keys():
results[eventSource] = list()
else:
diff --git a/modules/sfp_stor_db.py b/modules/sfp_stor_db.py
new file mode 100644
index 00000000..90347094
--- /dev/null
+++ b/modules/sfp_stor_db.py
@@ -0,0 +1,60 @@
+#-------------------------------------------------------------------------------
+# Name: sfp_stor_db
+# Purpose: SpiderFoot plug-in for storing events to the local SpiderFoot
+# SQLite database.
+#
+# Author: Steve Micallef <[email protected]>
+#
+# Created: 14/05/2012
+# Copyright: (c) Steve Micallef 2012
+# Licence: GPL
+#-------------------------------------------------------------------------------
+
+import sys
+import re
+from sflib import SpiderFoot, SpiderFootPlugin
+
+# SpiderFoot standard lib (must be initialized in __init__)
+sf = None
+sfdb = None
+
+class sfp_stor_db(SpiderFootPlugin):
+ # Default options
+ opts = {
+ # These must always be set
+ '_debug': True,
+ '_debugfilter': ''
+ }
+
+ # URL this instance is working on
+ seedUrl = None
+
+ def __init__(self, url, userOpts=dict()):
+ global sf
+ global sfdb
+ self.seedUrl = url
+
+ for opt in userOpts.keys():
+ self.opts[opt] = userOpts[opt]
+
+ # For error reporting, debug, etc.
+ sf = SpiderFoot(self.opts)
+ # Use the database handle passed to us
+ sfdb = userOpts['__sfdb__']
+
+ # What events is this module interested in for input
+ # Because this is a storage plugin, we are interested in everything so we
+ # can store all events for later analysis.
+ def watchedEvents(self):
+ return ["*"]
+
+ # Handle events sent to this module
+ def handleEvent(self, srcModuleName, eventName, eventSource, eventData):
+ sfdb.scanEventStore(self.opts['__guid__'], eventName, eventSource,
+ eventData, srcModuleName)
+
+# End of sfp_stor_db class
+
+if __name__ == '__main__':
+ print "This module cannot be run stand-alone."
+ exit(-1)
diff --git a/sf.py b/sf.py
index 456a4d28..755c1d70 100644
--- a/sf.py
+++ b/sf.py
@@ -10,9 +10,10 @@
#-------------------------------------------------------------------------------
import imp
-
-# URL to start from. This will be set either by the CLI or UI
-seedUrl = 'http://www.binarypool.com'
+import sys
+import time
+from sflib import SpiderFoot
+from sfdb import SpiderFootDb
# These are all hard-coded for now, but will eventually
# be set by the UI or CLI
@@ -20,10 +21,12 @@ seedUrl = 'http://www.binarypool.com'
# These can be overriden on a per-module basis
sfConfig = {
'_debug': True, # Debug
- '_debugfilter': 'pageinfo', # Filter out debug strings
+ '_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',
+ '__guid__': None # unique ID of scan. Will be set after start-up
}
# Each module will have defaults configured. This will override defaults.
@@ -33,6 +36,9 @@ moduleConfig = {
'enabled': True,
'pause': 1
},
+ 'sfp_stor_db': {
+ 'enabled': True
+ },
'sfp_mail': {
'enabled': False
},
@@ -40,7 +46,7 @@ moduleConfig = {
'enabled': False
},
'sfp_stor_print': {
- 'enabled': True
+ 'enabled': False
},
'sfp_subdomain': {
'enabled': False
@@ -52,17 +58,31 @@ moduleConfig = {
'enabled': False
},
'sfp_pageinfo': {
- 'enabled': True
+ 'enabled': False
+ },
+ 'sfp_googlesearch': {
+ 'enabled': False
}
}
def main(url):
moduleInstances = dict()
+ # Library functions (in here, only for debugging, error reporting, etc.)
+ sf = SpiderFoot(sfConfig)
+
+ # Set up the back-end database
+ sfdb = SpiderFootDb(sfConfig)
+
+ # Create a unique ID for this scan and create it in the back-end DB.
+ sfConfig['__guid__'] = sfdb.scanInstanceGenGUID(seedUrl)
+ sfdb.scanInstanceCreate(sfConfig['__guid__'], 'No name', seedUrl)
+ sfdb.scanInstanceSet(sfConfig['__guid__'], time.time() * 1000, None, 'STARTED')
+
# Loop through all modules that are enabled in moduleConfig
for modName in moduleConfig.keys():
if not moduleConfig[modName]['enabled']:
- print "Skipping module " + modName + " as not enabled."
+ sf.debug("Skipping module " + modName + " as not enabled.")
continue
# Load the plug-in module
@@ -73,6 +93,13 @@ def main(url):
modConfig = sfConfig
modConfig.update(moduleConfig[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.
+ modConfig['__sfdb__'] = sfdb
+
# Instantiate the module
modInstance = getattr(mod, modName)(url, modConfig)
# Keep track of the module object so it can be referenced later
@@ -91,5 +118,12 @@ def main(url):
for module in moduleInstances.values():
module.start()
+ sfdb.scanInstanceSet(sfConfig['__guid__'], None, time.time() * 1000, 'FINISHED')
+ sfdb.close()
+
if __name__ == '__main__':
- main(seedUrl)
+ # Process command-line options here (more advanced eventually..)
+ seedUrl = sys.argv[1]
+
+ # Start scanning...
+ main(seedUrl)
diff --git a/sfdb.py b/sfdb.py
new file mode 100644
index 00000000..a9279484
--- /dev/null
+++ b/sfdb.py
@@ -0,0 +1,153 @@
+#-------------------------------------------------------------------------------
+# Name: sfdb
+# Purpose: Common functions for working with the database back-end.
+#
+# Author: Steve Micallef <[email protected]>
+#
+# Created: 15/05/2012
+# Copyright: (c) Steve Micallef 2012
+# Licence: GPL
+#-------------------------------------------------------------------------------
+
+import hashlib
+import random
+import sqlite3
+import sys
+import time
+from sflib import SpiderFoot
+
+# SpiderFoot class passed to us
+sf = None
+
+class SpiderFootDb:
+ def __init__(self, opts):
+ global sf
+
+ # 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)
+ if dbh == None:
+ sf.fatal("Could not connect to internal database. Check that " + \
+ opts['_database'] + " exists and is readable and writable.")
+ dbh.text_factory = str
+
+ self.conn = dbh
+
+ self.dbh = dbh.cursor()
+ sf = SpiderFoot(opts)
+
+ # Now we actually check to ensure the database file has the schema set
+ # up correctly.
+ try:
+ self.dbh.execute('SELECT COUNT(*) FROM tbl_scan_config')
+ except sqlite3.Error:
+ sf.fatal("Found spiderfoot.db but it doesn't appear to be in " \
+ "the expected state - ensure the schema is created.")
+
+ return
+
+ #
+ # Back-end database operations
+ #
+
+ # Close the database handle
+ def close(self):
+ self.dbh.close()
+
+ # Generate an globally unique ID for this scan
+ def scanInstanceGenGUID(self, scanName):
+ hashStr = hashlib.sha256(
+ scanName +
+ str(time.time() * 1000) +
+ str(random.randint(100000, 999999))
+ ).hexdigest()
+ sf.debug("Using GUID of: " + hashStr)
+ return hashStr
+
+ # Store a scan instance
+ def scanInstanceCreate(self, instanceId, scanName, scanTarget):
+ qry = "INSERT INTO tbl_scan_instance \
+ (guid, name, seed_target, created, status) \
+ VALUES (?, ?, ?, ?, ?)"
+ try:
+ self.dbh.execute(qry, (
+ instanceId, scanName, scanTarget, time.time() * 1000, 'CREATED'
+ ))
+ self.conn.commit()
+ except sqlite3.Error as e:
+ sf.fatal("Unable to create instance in DB: " + e.message)
+
+ return True
+
+ # Update the start time, end time or status (or all 3) of a scan instance
+ def scanInstanceSet(self, instanceId, started=None, ended=None, status=None):
+ qvars = list()
+ qry = "UPDATE tbl_scan_instance SET "
+
+ if started != None:
+ qry += " started = ?,"
+ qvars.append(started)
+
+ if ended != None:
+ qry += " ended = ?,"
+ qvars.append(ended)
+
+ if status != None:
+ qry += " status = ?,"
+ qvars.append(status)
+
+ # guid = guid is a little hack to avoid messing with , placement above
+ qry += " guid = guid WHERE guid = ?"
+ qvars.append(instanceId)
+
+ try:
+ self.dbh.execute(qry, qvars)
+ self.conn.commit()
+ except sqlite3.Error:
+ sf.fatal("Unable to set information for the scan instance.")
+
+ # Return info about a scan instance (name, target, created, started,
+ # ended, status) - don't need this yet - untested
+ def scanInstanceGet(self, instanceId):
+ qry = "SELECT name, seed_target, created, started, ended, status \
+ FROM tbl_scan_instance WHERE guid = ?"
+ try:
+ self.dbh.execute(qry, list(instanceId))
+ return self.dbh.fetchone()
+ except sqlite3.Error as e:
+ sf.fatal("SQL error encountered when retreiving scan instance:" +
+ e.message)
+
+ # Delete a scan instance - don't need this yet
+ def scanInstanceDelete(self, instanceId):
+ pass
+
+ # 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
+
+ # Retreive configuration data for a scan component
+ # don't need this yet
+ def scanConfigGet(self, instanceId, component):
+ pass
+
+ # Store an event
+ def scanEventStore(self, instanceId, eventName, eventSource,
+ eventData, eventDataSource):
+ qry = "INSERT INTO tbl_scan_results \
+ (scan_instance_id, generated, event, event_source, \
+ event_data, event_data_source) \
+ VALUES (?, ?, ?, ?, ?, ?)"
+ qvals = [instanceId, time.time() * 1000, eventName, eventSource,
+ eventData, eventDataSource]
+
+ try:
+ self.dbh.execute(qry, qvals)
+ self.conn.commit()
+ return None
+ except sqlite3.Error as e:
+ sf.fatal("SQL error encountered when storing event data: " +
+ e.message)
diff --git a/sflib.py b/sflib.py
index 91103af4..891aea2d 100644
--- a/sflib.py
+++ b/sflib.py
@@ -13,13 +13,10 @@
import inspect
import random
import re
-import sqlite3
import sys
import time
-import urllib
import urllib2
-
class SpiderFoot:
# 'options' is a dictionary of options which changes the behaviour
# of how certain things are done in this module
@@ -31,25 +28,9 @@ class SpiderFoot:
self.handle = handle
self.opts = options
- # 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(options['_database'])
- if dbh == None:
- self.fatal("Could not connect to internal database. Check that " \
- "spiderfoot.db exists and is readable and writable.")
- self.dbh = dbh.cursor()
-
- # Now we actually check to ensure the database file has the schema set
- # up correctly.
- try:
- self.dbh.execute('SELECT COUNT(*) FROM tbl_scan_config')
- except sqlite3.Error:
- self.fatal("Found spiderfoot.db but it doesn't appear to be in " \
- "the expected state - ensure the schema is created.")
-
- # initialize database handler for storing results
- return
+ #
+ # Debug, error message and logging functions
+ #
def error(self, error):
if self.handle == None:
@@ -86,6 +67,10 @@ class SpiderFoot:
print 'should not be here'
return
+ #
+ # URL parsing functions
+ #
+
# Turn a relative path into an absolute path
def urlRelativeToAbsolute(self, url):
finalBits = list()
@@ -163,6 +148,10 @@ class SpiderFoot:
domain = self.urlBaseDom(base)
return domain.split('.', 2)[0]
+ #
+ # General helper functions to automate many common tasks between modules
+ #
+
# Parse the contents of robots.txt, returns a list of patterns
# which should not be followed
def parseRobotsTxt(self, robotsTxtData):
@@ -344,6 +333,9 @@ class SpiderFoot:
return result
+#
+# SpiderFoot plug-in module base class
+#
class SpiderFootPlugin(object):
# Modules that will be notified when this module produces events
_listenerModules = list()
diff --git a/spiderfoot.schema b/spiderfoot.schema
index e860ca58..f9a12d13 100644
--- a/spiderfoot.schema
+++ b/spiderfoot.schema
@@ -19,9 +19,10 @@
--
DROP TABLE tbl_scan_instance;
CREATE TABLE tbl_scan_instance (
- id INT PRIMARY KEY,
+ guid VARCHAR NOT NULL PRIMARY KEY,
name VARCHAR NOT NULL,
seed_target VARCHAR NOT NULL,
+ created INT DEFAULT 0,
started INT DEFAULT 0,
ended INT DEFAULT 0,
status VARCHAR NOT NULL
@@ -32,7 +33,7 @@ CREATE TABLE tbl_scan_instance (
--
DROP TABLE tbl_scan_config;
CREATE TABLE tbl_scan_config (
- scan_instance_id INT NOT NULL REFERENCES tbl_scan_instance(id),
+ scan_instance_id VARCHAR NOT NULL REFERENCES tbl_scan_instance(guid),
component VARCHAR NOT NULL,
opt VARCHAR NOT NULL,
val VARCHAR NOT NULL
@@ -43,7 +44,7 @@ CREATE TABLE tbl_scan_config (
--
DROP TABLE tbl_scan_results;
CREATE TABLE tbl_scan_results (
- scan_instance_id INT NOT NULL REFERENCES tbl_scan_instance(id),
+ scan_instance_id VARCHAR NOT NULL REFERENCES tbl_scan_instance(guid),
generated INT NOT NULL,
event VARCHAR NOT NULL,
event_source VARCHAR NOT NULL,