Skip to content

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

Move module loading to SpiderFootHelpers.loadModulesAsDict() function (#1655)

bcoles21ce2d91e446
diff --git a/sf.py b/sf.py
index f89b55ae..28037f6d 100755
--- a/sf.py
+++ b/sf.py
@@ -64,6 +64,7 @@ def main():
'_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",
'__database': f"{SpiderFootHelpers.dataPath()}/spiderfoot.db",
'__modules__': None, # List of modules. Will be set after start-up.
+ '__correlationrules__': None, # List of correlation rules. Will be set after start-up.
'_socks1type': '',
'_socks2addr': '',
'_socks3port': '',
@@ -133,51 +134,30 @@ def main():
logListenerSetup(loggingQueue, sfConfig)
logWorkerSetup(loggingQueue)
log = logging.getLogger(f"spiderfoot.{__name__}")
-
- sfModules = dict()
- correlationRulesRaw = dict()
sft = SpiderFoot(sfConfig)
# Load each module in the modules directory with a .py extension
- mod_dir = sft.myPath() + '/modules/'
-
- # Load each correlation rule in the correlations directory with
- # a .yaml extension
- corr_dir = sft.myPath() + '/correlations/'
-
- if not os.path.isdir(mod_dir):
- log.critical(f"Modules directory does not exist: {mod_dir}")
+ sfModules = dict()
+ try:
+ mod_dir = sft.myPath() + '/modules/'
+ sfModules = SpiderFootHelpers.loadModulesAsDict(mod_dir)
+ except BaseException as e:
+ log.critical(f"Failed to load modules: {e}")
sys.exit(-1)
- for filename in os.listdir(mod_dir):
- if not filename.endswith(".py"):
- continue
- if not filename.startswith("sfp_"):
- continue
- if filename in ('sfp_template.py'):
- continue
-
- modName = filename.split('.')[0]
-
- # Load and instantiate the module
- sfModules[modName] = dict()
- try:
- mod = __import__('modules.' + modName, globals(), locals(), [modName])
- sfModules[modName]['object'] = getattr(mod, modName)()
- mod_dict = sfModules[modName]['object'].asdict()
- sfModules[modName].update(mod_dict)
- except BaseException as e:
- log.critical(f"Failed to load module {modName}: {e}")
- sys.exit(-1)
-
if not sfModules:
log.critical(f"No modules found in modules directory: {mod_dir}")
sys.exit(-1)
+ # Load each correlation rule in the correlations directory with
+ # a .yaml extension
+ corr_dir = sft.myPath() + '/correlations/'
+
if not os.path.isdir(corr_dir):
log.critical(f"Correlation rules directory does not exist: {corr_dir}")
sys.exit(-1)
+ correlationRulesRaw = dict()
for filename in os.listdir(corr_dir):
if not filename.endswith(".yaml"):
continue
@@ -202,6 +182,7 @@ def main():
# Add modules and the correlator to sfConfig so they can be used elsewhere
sfConfig['__modules__'] = sfModules
sfConfig['__correlationrules__'] = sfCorrelationRules
+
# Add descriptions of the global config options
sfConfig['__globaloptdescs__'] = sfOptdescs
@@ -245,7 +226,7 @@ def main():
sfWebUiConfig['port'] = port
start_web_server(sfWebUiConfig, sfConfig, loggingQueue)
- exit(0)
+ sys.exit(0)
start_scan(sfConfig, sfModules, args, loggingQueue)
diff --git a/spiderfoot/helpers.py b/spiderfoot/helpers.py
index 72f1f666..5c4505db 100644
--- a/spiderfoot/helpers.py
+++ b/spiderfoot/helpers.py
@@ -55,6 +55,57 @@ class SpiderFootHelpers():
os.makedirs(path, exist_ok=True)
return path
+ @staticmethod
+ def loadModulesAsDict(path: str, ignore_files: list = ['sfp_template.py']) -> dict():
+ """Load modules from modules directory.
+
+ Args:
+ path (str): file system path for modules directory
+ ignore_files (list): List of module file names to ignore
+
+ Returns:
+ dict: SpiderFoot modules
+
+ Raises:
+ TypeError: ignore file list was invalid
+ ValueError: module path does not exist
+ SyntaxError: module data is malformed
+ """
+ if not isinstance(ignore_files, list):
+ raise TypeError(f"ignore_files is {type(ignore_files)}; expected list()")
+
+ if not os.path.isdir(path):
+ raise ValueError(f"Modules directory does not exist: {path}")
+
+ sfModules = dict()
+ valid_categories = ["Content Analysis", "Crawling and Scanning", "DNS",
+ "Leaks, Dumps and Breaches", "Passive DNS",
+ "Public Registries", "Real World", "Reputation Systems",
+ "Search Engines", "Secondary Networks", "Social Media"]
+
+ for filename in os.listdir(path):
+ if not filename.startswith("sfp_"):
+ continue
+ if not filename.endswith(".py"):
+ continue
+ if filename in ignore_files:
+ continue
+
+ modName = filename.split('.')[0]
+ sfModules[modName] = dict()
+ mod = __import__('modules.' + modName, globals(), locals(), [modName])
+ sfModules[modName]['object'] = getattr(mod, modName)()
+ mod_dict = sfModules[modName]['object'].asdict()
+ sfModules[modName].update(mod_dict)
+
+ if len(sfModules[modName]['cats']) > 1:
+ raise SyntaxError(f"Module {modName} has multiple categories defined but only one is supported.")
+
+ if sfModules[modName]['cats'] and sfModules[modName]['cats'][0] not in valid_categories:
+ raise SyntaxError(f"Module {modName} has invalid category '{sfModules[modName]['cats']}'.")
+
+ return sfModules
+
@staticmethod
def targetTypeFromString(target: str) -> None:
"""Return the scan target seed data type for the specified scan target input.
diff --git a/test/conftest.py b/test/conftest.py
index 4db2d5ff..b48b9d87 100644
--- a/test/conftest.py
+++ b/test/conftest.py
@@ -16,6 +16,7 @@ def default_options(request):
'_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",
'__database': f"{SpiderFootHelpers.dataPath()}/spiderfoot.test.db", # note: test database file
'__modules__': None, # List of modules. Will be set after start-up.
+ '__correlationrules__': None, # List of correlation rules. Will be set after start-up.
'_socks1type': '',
'_socks2addr': '',
'_socks3port': '',
diff --git a/test/integration/test_sfwebui.py b/test/integration/test_sfwebui.py
index 2e5ff8a9..7f957dc5 100644
--- a/test/integration/test_sfwebui.py
+++ b/test/integration/test_sfwebui.py
@@ -1,5 +1,4 @@
# test_sfwebui.py
-import os
import unittest
import cherrypy
@@ -37,39 +36,9 @@ class TestSpiderFootWebUiRoutes(helper.CPWebCase):
'root': '/'
}
- sfModules = dict()
sf = SpiderFoot(default_config)
mod_dir = sf.myPath() + '/modules/'
- for filename in os.listdir(mod_dir):
- if not filename.startswith("sfp_"):
- continue
- if not filename.endswith(".py"):
- continue
- # Skip the module template and debugging modules
- if filename in ('sfp_template.py', 'sfp_stor_print.py'):
- continue
- modName = filename.split('.')[0]
-
- # Load and instantiate the module
- sfModules[modName] = dict()
- mod = __import__('modules.' + modName, globals(), locals(), [modName])
- sfModules[modName]['object'] = getattr(mod, modName)()
- sfModules[modName]['name'] = sfModules[modName]['object'].meta['name']
- sfModules[modName]['cats'] = sfModules[modName]['object'].meta.get('categories', list())
- sfModules[modName]['group'] = sfModules[modName]['object'].meta.get('useCases', list())
- if len(sfModules[modName]['cats']) > 1:
- raise ValueError(f"Module {modName} has multiple categories defined but only one is supported.")
- sfModules[modName]['labels'] = sfModules[modName]['object'].meta.get('flags', list())
- sfModules[modName]['descr'] = sfModules[modName]['object'].meta['summary']
- sfModules[modName]['provides'] = sfModules[modName]['object'].producedEvents()
- sfModules[modName]['consumes'] = sfModules[modName]['object'].watchedEvents()
- sfModules[modName]['meta'] = sfModules[modName]['object'].meta
- if hasattr(sfModules[modName]['object'], 'opts'):
- sfModules[modName]['opts'] = sfModules[modName]['object'].opts
- if hasattr(sfModules[modName]['object'], 'optdescs'):
- sfModules[modName]['optdescs'] = sfModules[modName]['object'].optdescs
-
- default_config['__modules__'] = sfModules
+ default_config['__modules__'] = SpiderFootHelpers.loadModulesAsDict(mod_dir)
conf = {
'/query': {
diff --git a/test/unit/test_modules.py b/test/unit/test_modules.py
index 36b2a2c9..e76ef27c 100644
--- a/test/unit/test_modules.py
+++ b/test/unit/test_modules.py
@@ -1,10 +1,10 @@
-# test_spiderfoot_module_loading.py
-import os
+# test_modules.py
import pytest
import unittest
from sflib import SpiderFoot
from spiderfoot import SpiderFootDb
+from spiderfoot import SpiderFootHelpers
@pytest.mark.usefixtures
@@ -15,25 +15,8 @@ class TestSpiderFootModuleLoading(unittest.TestCase):
@staticmethod
def load_modules(sf):
- # Go through each module in the modules directory with a .py extension
- sfModules = dict()
mod_dir = sf.myPath() + '/modules/'
- for filename in os.listdir(mod_dir):
- if not filename.startswith("sfp_"):
- continue
- if not filename.endswith(".py"):
- continue
-
- modName = filename.split('.')[0]
-
- # Load and instantiate the module
- sfModules[modName] = dict()
- mod = __import__('modules.' + modName, globals(), locals(), [modName])
- sfModules[modName]['object'] = getattr(mod, modName)()
- mod_dict = sfModules[modName]['object'].asdict()
- sfModules[modName].update(mod_dict)
-
- return sfModules
+ return SpiderFootHelpers.loadModulesAsDict(mod_dir)
def test_module_use_cases_are_valid(self):
sf = SpiderFoot(self.default_options)