Skip to content

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

sf: split main into start_scan and start_web_server

Brendan Coles42a1c40e0d99
diff --git a/sf.py b/sf.py
index 68a4fe33..a292f1c4 100755
--- a/sf.py
+++ b/sf.py
@@ -11,12 +11,6 @@
# Licence: GPL
# -------------------------------------------------------------------------------
-import sys
-
-if sys.version_info < (3, 6):
- print("SpiderFoot requires Python 3.6 or higher.")
- sys.exit(-1)
-
import argparse
import logging
import multiprocessing as mp
@@ -24,6 +18,7 @@ import os
import os.path
import random
import signal
+import sys
import time
from copy import deepcopy
from logging import handlers
@@ -31,10 +26,10 @@ from logging import handlers
import cherrypy
from cherrypy.lib import auth_digest
-from spiderfoot import SpiderFootDb
from sflib import SpiderFoot
from sfscan import SpiderFootScanner
from sfwebui import SpiderFootWebUi
+from spiderfoot import SpiderFootDb
log = logging.getLogger()
log.setLevel(logging.DEBUG)
@@ -54,65 +49,11 @@ error_handler.setLevel(logging.WARN)
error_handler.setFormatter(log_format)
log.addHandler(error_handler)
-# 'Global' configuration options
-# These can be overriden on a per-module basis, and some will
-# be overridden from saved configuration settings stored in the DB.
-sfConfig = {
- '_debug': False, # Debug
- '__logging': True, # Logging in general
- '__outputfilter': None, # Event types to filter from modules' output
- '__blocknotif': False, # Block notifications
- '_useragent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0', # User-Agent to use for HTTP requests
- '_dnsserver': '', # Override the default resolver
- '_fetchtimeout': 5, # number of seconds before giving up on a fetch
- '_internettlds': 'https://publicsuffix.org/list/effective_tld_names.dat',
- '_internettlds_cache': 72,
- '_genericusers': "abuse,admin,billing,compliance,devnull,dns,ftp,hostmaster,inoc,ispfeedback,ispsupport,list-request,list,maildaemon,marketing,noc,no-reply,noreply,null,peering,peering-notify,peering-request,phish,phishing,postmaster,privacy,registrar,registry,root,routing-registry,rr,sales,security,spam,support,sysadmin,tech,undisclosed-recipients,unsubscribe,usenet,uucp,webmaster,www",
- '__version__': '3.3-DEV',
- '__database': 'spiderfoot.db',
- '__webaddr': '127.0.0.1',
- '__webport': 5001,
- '__docroot': '', # don't put trailing /
- '__modules__': None, # List of modules. Will be set after start-up.
- '_socks1type': '',
- '_socks2addr': '',
- '_socks3port': '',
- '_socks4user': '',
- '_socks5pwd': '',
- '_torctlport': 9051,
- '__logstdout': False
-}
-
-sfOptdescs = {
- '_debug': "Enable debugging?",
- '_internettlds': "List of Internet TLDs.",
- '_genericusers': "List of usernames that if found as usernames or as part of e-mail addresses, should be treated differently to non-generics.",
- '_internettlds_cache': "Hours to cache the Internet TLD list. This can safely be quite a long time given that the list doesn't change too often.",
- '_useragent': "User-Agent string to use for HTTP requests. Prefix with an '@' to randomly select the User Agent from a file containing user agent strings for each request, e.g. @C:\\useragents.txt or @/home/bob/useragents.txt. Or supply a URL to load the list from there.",
- '_dnsserver': "Override the default resolver with another DNS server. For example, 8.8.8.8 is Google's open DNS server.",
- '_fetchtimeout': "Number of seconds before giving up on a HTTP request.",
- '_socks1type': "SOCKS Server Type. Can be '4', '5', 'HTTP' or 'TOR'",
- '_socks2addr': 'SOCKS Server IP Address.',
- '_socks3port': 'SOCKS Server TCP Port. Usually 1080 for 4/5, 8080 for HTTP and 9050 for TOR.',
- '_socks4user': 'SOCKS Username. Valid only for SOCKS4 and SOCKS5 servers.',
- '_socks5pwd': "SOCKS Password. Valid only for SOCKS5 servers.",
- '_torctlport': "The port TOR is taking control commands on. This is necessary for SpiderFoot to tell TOR to re-circuit when it suspects anonymity is compromised.",
- '_modulesenabled': "Modules enabled for the scan." # This is a hack to get a description for an option not actually available.
-}
-
scanId = None
dbh = None
-def handle_abort(signal, frame):
- """handle interrupt and abort scan."""
- log.info("Aborting...")
- if scanId and dbh:
- dbh.scanInstanceSet(scanId, None, None, "ABORTED")
- sys.exit(-1)
-
-
-if __name__ == '__main__':
+def main():
if len(sys.argv) == 0:
print("SpiderFoot requires -l <ip>:<port> to start the web server.")
sys.exit(-1)
@@ -122,6 +63,52 @@ if __name__ == '__main__':
print("SpiderFoot requires -l <ip>:<port> to start the web server.")
sys.exit(-1)
+ # 'Global' configuration options
+ # These can be overriden on a per-module basis, and some will
+ # be overridden from saved configuration settings stored in the DB.
+ sfConfig = {
+ '_debug': False, # Debug
+ '__logging': True, # Logging in general
+ '__outputfilter': None, # Event types to filter from modules' output
+ '__blocknotif': False, # Block notifications
+ '_useragent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0', # User-Agent to use for HTTP requests
+ '_dnsserver': '', # Override the default resolver
+ '_fetchtimeout': 5, # number of seconds before giving up on a fetch
+ '_internettlds': 'https://publicsuffix.org/list/effective_tld_names.dat',
+ '_internettlds_cache': 72,
+ '_genericusers': "abuse,admin,billing,compliance,devnull,dns,ftp,hostmaster,inoc,ispfeedback,ispsupport,list-request,list,maildaemon,marketing,noc,no-reply,noreply,null,peering,peering-notify,peering-request,phish,phishing,postmaster,privacy,registrar,registry,root,routing-registry,rr,sales,security,spam,support,sysadmin,tech,undisclosed-recipients,unsubscribe,usenet,uucp,webmaster,www",
+ '__version__': '3.3-DEV',
+ '__database': 'spiderfoot.db',
+ '__webaddr': '127.0.0.1',
+ '__webport': 5001,
+ '__docroot': '', # don't put trailing /
+ '__modules__': None, # List of modules. Will be set after start-up.
+ '_socks1type': '',
+ '_socks2addr': '',
+ '_socks3port': '',
+ '_socks4user': '',
+ '_socks5pwd': '',
+ '_torctlport': 9051,
+ '__logstdout': False
+ }
+
+ sfOptdescs = {
+ '_debug': "Enable debugging?",
+ '_useragent': "User-Agent string to use for HTTP requests. Prefix with an '@' to randomly select the User Agent from a file containing user agent strings for each request, e.g. @C:\\useragents.txt or @/home/bob/useragents.txt. Or supply a URL to load the list from there.",
+ '_dnsserver': "Override the default resolver with another DNS server. For example, 8.8.8.8 is Google's open DNS server.",
+ '_fetchtimeout': "Number of seconds before giving up on a HTTP request.",
+ '_internettlds': "List of Internet TLDs.",
+ '_internettlds_cache': "Hours to cache the Internet TLD list. This can safely be quite a long time given that the list doesn't change too often.",
+ '_genericusers': "List of usernames that if found as usernames or as part of e-mail addresses, should be treated differently to non-generics.",
+ '_socks1type': "SOCKS Server Type. Can be '4', '5', 'HTTP' or 'TOR'",
+ '_socks2addr': 'SOCKS Server IP Address.',
+ '_socks3port': 'SOCKS Server TCP Port. Usually 1080 for 4/5, 8080 for HTTP and 9050 for TOR.',
+ '_socks4user': 'SOCKS Username. Valid only for SOCKS4 and SOCKS5 servers.',
+ '_socks5pwd': "SOCKS Password. Valid only for SOCKS5 servers.",
+ '_torctlport': "The port TOR is taking control commands on. This is necessary for SpiderFoot to tell TOR to re-circuit when it suspects anonymity is compromised.",
+ '_modulesenabled': "Modules enabled for the scan." # This is a hack to get a description for an option not actually available.
+ }
+
# Legacy way to run the server
args = None
p = argparse.ArgumentParser(description='SpiderFoot 3.3-DEV: Open Source Intelligence Automation.')
@@ -215,223 +202,239 @@ if __name__ == '__main__':
# Add descriptions of the global config options
sfConfig['__globaloptdescs__'] = sfOptdescs
- sf = SpiderFoot(sfConfig)
+ if args.l:
+ start_web_server(sfConfig)
+ else:
+ start_scan(sfConfig, sfModules, args)
+
+
+def start_scan(sfConfig, sfModules, args):
+ global dbh
+ global scanId
+
dbh = SpiderFootDb(sfConfig, init=True)
+ sf = SpiderFoot(sfConfig)
- if not args.l:
- if args.modules:
- log.info("Modules available:")
- for m in sorted(sfModules.keys()):
- if "__" in m:
- continue
- print(('{0:25} {1}'.format(m, sfModules[m]['descr'])))
- sys.exit(0)
+ if args.modules:
+ log.info("Modules available:")
+ for m in sorted(sfModules.keys()):
+ if "__" in m:
+ continue
+ print(('{0:25} {1}'.format(m, sfModules[m]['descr'])))
+ sys.exit(0)
- if args.types:
- log.info("Types available:")
- typedata = dbh.eventTypes()
- types = dict()
- for r in typedata:
- types[r[1]] = r[0]
+ if args.types:
+ log.info("Types available:")
+ typedata = dbh.eventTypes()
+ types = dict()
+ for r in typedata:
+ types[r[1]] = r[0]
- for t in sorted(types.keys()):
- print(('{0:45} {1}'.format(t, types[t])))
- sys.exit(0)
+ for t in sorted(types.keys()):
+ print(('{0:45} {1}'.format(t, types[t])))
+ sys.exit(0)
- if not args.s:
- log.error("You must specify a target when running in scan mode. Try --help for guidance.")
- sys.exit(-1)
+ if not args.s:
+ log.error("You must specify a target when running in scan mode. Try --help for guidance.")
+ sys.exit(-1)
- if args.x and not args.t:
- log.error("-x can only be used with -t. Use --help for guidance.")
- sys.exit(-1)
+ if args.x and not args.t:
+ log.error("-x can only be used with -t. Use --help for guidance.")
+ sys.exit(-1)
- if args.x and args.m:
- log.error("-x can only be used with -t and not with -m. Use --help for guidance.")
- sys.exit(-1)
+ if args.x and args.m:
+ log.error("-x can only be used with -t and not with -m. Use --help for guidance.")
+ sys.exit(-1)
- if args.r and (args.o and args.o not in ["tab", "csv"]):
- log.error("-r can only be used when your output format is tab or csv.")
- sys.exit(-1)
+ if args.r and (args.o and args.o not in ["tab", "csv"]):
+ log.error("-r can only be used when your output format is tab or csv.")
+ sys.exit(-1)
- if args.H and (args.o and args.o not in ["tab", "csv"]):
- log.error("-H can only be used when your output format is tab or csv.")
- sys.exit(-1)
+ if args.H and (args.o and args.o not in ["tab", "csv"]):
+ log.error("-H can only be used when your output format is tab or csv.")
+ sys.exit(-1)
- if args.D and args.o != "csv":
- log.error("-D can only be used when using the csv output format.")
- sys.exit(-1)
+ if args.D and args.o != "csv":
+ log.error("-D can only be used when using the csv output format.")
+ sys.exit(-1)
- target = args.s
- # Usernames and names - quoted on the commandline - won't have quotes,
- # so add them.
- if " " in target:
- target = f"\"{target}\""
- if "." not in target and not target.startswith("+") and '"' not in target:
- target = f"\"{target}\""
- targetType = sf.targetType(target)
-
- if not targetType:
- log.error(f"Could not determine target type. Invalid target: {target}")
- sys.exit(-1)
+ target = args.s
+ # Usernames and names - quoted on the commandline - won't have quotes,
+ # so add them.
+ if " " in target:
+ target = f"\"{target}\""
+ if "." not in target and not target.startswith("+") and '"' not in target:
+ target = f"\"{target}\""
+ targetType = sf.targetType(target)
+
+ if not targetType:
+ log.error(f"Could not determine target type. Invalid target: {target}")
+ sys.exit(-1)
- target = target.strip('"')
+ target = target.strip('"')
+ modlist = list()
+ if not args.t and not args.m:
+ log.warning("You didn't specify any modules or types, so all will be enabled.")
+ for m in list(sfModules.keys()):
+ if "__" in m:
+ continue
+ modlist.append(m)
+
+ signal.signal(signal.SIGINT, handle_abort)
+ # If the user is scanning by type..
+ # 1. Find modules producing that type
+ if args.t:
+ types = args.t
+ modlist = sf.modulesProducing(types)
+ newmods = deepcopy(modlist)
+ newmodcpy = deepcopy(newmods)
+
+ # 2. For each type those modules consume, get modules producing
+ while len(newmodcpy) > 0:
+ for etype in sf.eventsToModules(newmodcpy):
+ xmods = sf.modulesProducing([etype])
+ for mod in xmods:
+ if mod not in modlist:
+ modlist.append(mod)
+ newmods.append(mod)
+ newmodcpy = deepcopy(newmods)
+ newmods = list()
+
+ # Easier if scanning by module
+ if args.m:
+ modlist = list(filter(None, args.m.split(",")))
+
+ # Add sfp__stor_stdout to the module list
+ typedata = dbh.eventTypes()
+ types = dict()
+ for r in typedata:
+ types[r[1]] = r[0]
+
+ sfp__stor_stdout_opts = sfConfig['__modules__']['sfp__stor_stdout']['opts']
+ sfp__stor_stdout_opts['_eventtypes'] = types
+ if args.f:
+ if args.f and not args.t:
+ log.error("You can only use -f with -t. Use --help for guidance.")
+ sys.exit(-1)
+ sfp__stor_stdout_opts['_showonlyrequested'] = True
+ if args.F:
+ sfp__stor_stdout_opts['_requested'] = args.F.split(",")
+ sfp__stor_stdout_opts['_showonlyrequested'] = True
+ if args.o:
+ sfp__stor_stdout_opts['_format'] = args.o
+ if args.t:
+ sfp__stor_stdout_opts['_requested'] = args.t.split(",")
+ if args.n:
+ sfp__stor_stdout_opts['_stripnewline'] = True
+ if args.r:
+ sfp__stor_stdout_opts['_showsource'] = True
+ if args.S:
+ sfp__stor_stdout_opts['_maxlength'] = args.S
+ if args.D:
+ sfp__stor_stdout_opts['_csvdelim'] = args.D
+ if args.x:
+ tmodlist = list()
modlist = list()
- if not args.t and not args.m:
- log.warning("You didn't specify any modules or types, so all will be enabled.")
- for m in list(sfModules.keys()):
- if "__" in m:
+ xmods = sf.modulesConsuming([targetType])
+ for mod in xmods:
+ if mod not in modlist:
+ tmodlist.append(mod)
+
+ # Remove any modules not producing the type requested
+ rtypes = args.t.split(",")
+ for mod in tmodlist:
+ for r in rtypes:
+ if not sfModules[mod]['provides']:
continue
- modlist.append(m)
-
- signal.signal(signal.SIGINT, handle_abort)
- # If the user is scanning by type..
- # 1. Find modules producing that type
- if args.t:
- types = args.t
- modlist = sf.modulesProducing(types)
- newmods = deepcopy(modlist)
- newmodcpy = deepcopy(newmods)
+ if r in sfModules[mod].get('provides', []) and mod not in modlist:
+ modlist.append(mod)
- # 2. For each type those modules consume, get modules producing
- while len(newmodcpy) > 0:
- for etype in sf.eventsToModules(newmodcpy):
- xmods = sf.modulesProducing([etype])
- for mod in xmods:
- if mod not in modlist:
- modlist.append(mod)
- newmods.append(mod)
- newmodcpy = deepcopy(newmods)
- newmods = list()
-
- # Easier if scanning by module
- if args.m:
- modlist = list(filter(None, args.m.split(",")))
-
- # Add sfp__stor_stdout to the module list
- outputformat = "tab"
- typedata = dbh.eventTypes()
- types = dict()
- for r in typedata:
- types[r[1]] = r[0]
-
- sfp__stor_stdout_opts = sfConfig['__modules__']['sfp__stor_stdout']['opts']
- sfp__stor_stdout_opts['_eventtypes'] = types
- if args.f:
- if args.f and not args.t:
- log.error("You can only use -f with -t. Use --help for guidance.")
- sys.exit(-1)
- sfp__stor_stdout_opts['_showonlyrequested'] = True
- if args.F:
- sfp__stor_stdout_opts['_requested'] = args.F.split(",")
- sfp__stor_stdout_opts['_showonlyrequested'] = True
- if args.o:
- sfp__stor_stdout_opts['_format'] = args.o
- if args.t:
- sfp__stor_stdout_opts['_requested'] = args.t.split(",")
- if args.n:
- sfp__stor_stdout_opts['_stripnewline'] = True
- if args.r:
- sfp__stor_stdout_opts['_showsource'] = True
- if args.S:
- sfp__stor_stdout_opts['_maxlength'] = args.S
- if args.D:
- sfp__stor_stdout_opts['_csvdelim'] = args.D
- if args.x:
- tmodlist = list()
- modlist = list()
- xmods = sf.modulesConsuming([targetType])
- for mod in xmods:
- if mod not in modlist:
- tmodlist.append(mod)
-
- # Remove any modules not producing the type requested
- rtypes = args.t.split(",")
- for mod in tmodlist:
- for r in rtypes:
- if not sfModules[mod]['provides']:
- continue
- if r in sfModules[mod].get('provides', []) and mod not in modlist:
- modlist.append(mod)
+ if len(modlist) == 0:
+ log.error("Based on your criteria, no modules were enabled.")
+ sys.exit(-1)
- if len(modlist) == 0:
- log.error("Based on your criteria, no modules were enabled.")
- sys.exit(-1)
+ modlist += ["sfp__stor_db", "sfp__stor_stdout"]
- modlist += ["sfp__stor_db", "sfp__stor_stdout"]
+ # Run the scan
+ if sfConfig['__logging']:
+ log.info(f"Modules enabled ({len(modlist)}): {','.join(modlist)}")
+ cfg = sf.configUnserialize(dbh.configGet(), sfConfig)
- # Run the scan
- if sfConfig['__logging']:
- log.info(f"Modules enabled ({len(modlist)}): {','.join(modlist)}")
- cfg = sf.configUnserialize(dbh.configGet(), sfConfig)
+ # Debug mode is a variable that gets stored to the DB, so re-apply it
+ if args.debug:
+ cfg['_debug'] = True
+ else:
+ cfg['_debug'] = False
+
+ # If strict mode is enabled, filter the output from modules.
+ if args.x and args.t:
+ cfg['__outputfilter'] = args.t.split(",")
+
+ if args.o == "json":
+ print("[", end='')
+
+ # Start running a new scan
+ scanName = target
+ scanId = sf.genScanInstanceId()
+ try:
+ p = mp.Process(target=SpiderFootScanner, args=(scanName, scanId, target, targetType, modlist, cfg))
+ p.daemon = True
+ p.start()
+ except BaseException as e:
+ log.error(f"Scan [{scanId}] failed: {e}")
+ sys.exit(-1)
- # Debug mode is a variable that gets stored to the DB, so re-apply it
- if args.debug:
- cfg['_debug'] = True
+ # If field headers weren't disabled, print them
+ if not args.H and args.o != "json":
+ if args.D:
+ delim = args.D
else:
- cfg['_debug'] = False
+ if args.o in ["tab", None]:
+ delim = "\t"
+
+ if args.o == "csv":
+ delim = ","
- # If strict mode is enabled, filter the output from modules.
- if args.x and args.t:
- cfg['__outputfilter'] = args.t.split(",")
+ if not args.r:
+ if delim != "\t":
+ print(delim.join(["Source", "Type", "Data"]))
+ else:
+ print('{0:30}{1}{2:45}{3}{4}'.format("Source", delim, "Type", delim, "Data"))
+ else:
+ if delim != "\t":
+ print(delim.join(["Source", "Type", "Source Data", "Data"]))
+ else:
+ print('{0:30}{1}{2:45}{3}{4}{5}{6}'.format("Source", delim, "Type", delim, "Source Data", delim, "Data"))
+
+ while True:
+ time.sleep(1)
+ info = dbh.scanInstanceGet(scanId)
+ if not info:
+ continue
+ if info[5] in ["ERROR-FAILED", "ABORT-REQUESTED", "ABORTED", "FINISHED"]:
+ if sfConfig['__logging']:
+ log.info(f"Scan completed with status {info[5]}")
+ if args.o == "json":
+ print("]")
+ sys.exit(0)
- if args.o == "json":
- print("[", end='')
+ return None
- # Start running a new scan
- scanName = target
- scanId = sf.genScanInstanceId()
- try:
- p = mp.Process(target=SpiderFootScanner, args=(scanName, scanId, target, targetType, modlist, cfg))
- p.daemon = True
- p.start()
- except BaseException as e:
- log.error(f"Scan [{scanId}] failed: {e}")
- sys.exit(-1)
- # If field headers weren't disabled, print them
- if not args.H and args.o != "json":
- if args.D:
- delim = args.D
- else:
- if args.o in ["tab", None]:
- delim = "\t"
+def start_web_server(sfConfig):
+ """Start the web server so you can start looking at results"""
- if args.o == "csv":
- delim = ","
+ sf = SpiderFoot(sfConfig)
- if not args.r:
- if delim != "\t":
- print(delim.join(["Source", "Type", "Data"]))
- else:
- print('{0:30}{1}{2:45}{3}{4}'.format("Source", delim, "Type", delim, "Data"))
- else:
- if delim != "\t":
- print(delim.join(["Source", "Type", "Source Data", "Data"]))
- else:
- print('{0:30}{1}{2:45}{3}{4}{5}{6}'.format("Source", delim, "Type", delim, "Source Data", delim, "Data"))
-
- while True:
- info = dbh.scanInstanceGet(scanId)
- if not info:
- time.sleep(1)
- continue
- if info[5] in ["ERROR-FAILED", "ABORT-REQUESTED", "ABORTED", "FINISHED"]:
- if sfConfig['__logging']:
- log.info(f"Scan completed with status {info[5]}")
- if args.o == "json":
- print("]")
- sys.exit(0)
- time.sleep(1)
- sys.exit(0)
+ web_host = sfConfig['__webaddr']
+ web_port = sfConfig['__webport']
- # Start the web server so you can start looking at results
- log.info('Starting web server at %s:%s ...' % (sfConfig['__webaddr'], sfConfig['__webport']))
+ log.info(f"Starting web server at {web_host}:{web_port} ...")
cherrypy.config.update({
- 'server.socket_host': sfConfig['__webaddr'],
- 'server.socket_port': sfConfig['__webport']
+ 'server.socket_host': web_host,
+ 'server.socket_port': web_port
})
# Disable auto-reloading of content
@@ -513,3 +516,22 @@ if __name__ == '__main__':
# Try starting the web server. If it fails due to a database being
# missing, start a smaller web server just for setting up the DB.
cherrypy.quickstart(SpiderFootWebUi(sfConfig), script_name=sfConfig['__docroot'], config=conf)
+
+
+def handle_abort(signal, frame):
+ """Handle interrupt and abort scan."""
+ global dbh
+ global scanId
+
+ if scanId and dbh:
+ log.info(f"Aborting scan [{scanId}] ...")
+ dbh.scanInstanceSet(scanId, None, None, "ABORTED")
+ sys.exit(-1)
+
+
+if __name__ == '__main__':
+ if sys.version_info < (3, 6):
+ print("SpiderFoot requires Python 3.6 or higher.")
+ sys.exit(-1)
+
+ main()