SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.
Python attacksurfacecticybersecurityfootprintinghackinginformation-gatheringinformation-securityinfosecintelligence-gatheringosintosint-frameworkosint-reconnaissanceosint-toolpentestingpythonreconsecurity-toolsthreat-intelligencethreatintel
Flake8: Resolve ANN and SIM violations (#1662)
bcolesbee7c496380d
diff --git a/modules/sfp_dnsbrute.py b/modules/sfp_dnsbrute.pyindex 3172af32..d3b711f8 100644--- a/modules/sfp_dnsbrute.py+++ b/modules/sfp_dnsbrute.py@@ -65,21 +65,17 @@ class sfp_dnsbrute(SpiderFootPlugin):self.opts[opt] = userOpts[opt]dicts_dir = f"{self.sf.myPath()}/spiderfoot/dicts/"- cslines = list()if self.opts['commons']:- cs = open(f"{dicts_dir}/subdomains.txt", 'r')- cslines = cs.readlines()- for s in cslines:- s = s.strip()- self.sublist[s] = True+ with open(f"{dicts_dir}/subdomains.txt", 'r') as f:+ for s in f.readlines():+ s = s.strip()+ self.sublist[s] = True- ttlines = list()if self.opts['top10000']:- tt = open(f"{dicts_dir}/subdomains-10000.txt", 'r')- ttlines = tt.readlines()- for s in ttlines:- s = s.strip()- self.sublist[s] = True+ with open(f"{dicts_dir}/subdomains-10000.txt", 'r') as f:+ for s in f.readlines():+ s = s.strip()+ self.sublist[s] = True# What events is this module interested in for inputdef watchedEvents(self):diff --git a/modules/sfp_reversewhois.py b/modules/sfp_reversewhois.pyindex 8e0b021e..69039228 100644--- a/modules/sfp_reversewhois.py+++ b/modules/sfp_reversewhois.py@@ -48,6 +48,7 @@ class sfp_reversewhois(SpiderFootPlugin):def setup(self, sfc, userOpts=dict()):self.sf = sfcself.results = self.tempStorage()+ self.errorState = False# Clear / reset any other class member variables here# or you risk them persisting between threads.@@ -67,14 +68,12 @@ class sfp_reversewhois(SpiderFootPlugin):def query(self, qry):url = f"https://reversewhois.io?searchterm={qry}"- ret = ([], [])-res = self.sf.fetchUrl(url, timeout=self.opts.get("_fetchtimeout", 30))if res["code"] not in ["200"]:self.error("You may have exceeded ReverseWhois usage limits.")self.errorState = True- return ret+ return ([], [])html = BeautifulSoup(res["content"], features="lxml")date_regex = re.compile(r'\d{4}-\d{2}-\d{2}')@@ -95,12 +94,10 @@ class sfp_reversewhois(SpiderFootPlugin):self.debug(f"Invalid row {table_row}")continue- ret = (list(domains), list(registrars))-if not registrars and not domains:self.info(f"No ReverseWhois info found for {qry}")- return ret+ return (list(domains), list(registrars))# Handle events sent to this moduledef handleEvent(self, event):@@ -121,7 +118,7 @@ class sfp_reversewhois(SpiderFootPlugin):domains, registrars = self.query(eventData)- for domain in domains:+ for domain in set(domains):# if this domain isn't the main targetif not self.getTarget().matches(domain, includeChildren=False):e = SpiderFootEvent("AFFILIATE_INTERNET_NAME", domain, self.__name__, event)@@ -130,7 +127,7 @@ class sfp_reversewhois(SpiderFootPlugin):evt = SpiderFootEvent("AFFILIATE_DOMAIN_NAME", domain, self.__name__, event)self.notifyListeners(evt)- for registrar in registrars:+ for registrar in set(registrars):e = SpiderFootEvent("DOMAIN_REGISTRAR", registrar, self.__name__, event)self.notifyListeners(e)diff --git a/modules/sfp_s3bucket.py b/modules/sfp_s3bucket.pyindex dd05ae2e..c40a757c 100644--- a/modules/sfp_s3bucket.py+++ b/modules/sfp_s3bucket.py@@ -91,10 +91,9 @@ class sfp_s3bucket(SpiderFootPlugin):def threadSites(self, siteList):self.s3results = dict()running = True- i = 0t = []- for site in siteList:+ for i, site in enumerate(siteList):if self.checkForStop():return False@@ -103,7 +102,6 @@ class sfp_s3bucket(SpiderFootPlugin):t.append(threading.Thread(name='thread_sfp_s3buckets_' + tname,target=self.checkSite, args=(site,)))t[i].start()- i += 1# Block until all threads are finishedwhile running:diff --git a/modules/sfp_similar.py b/modules/sfp_similar.pyindex 82f76545..4764ae4f 100644--- a/modules/sfp_similar.py+++ b/modules/sfp_similar.py@@ -141,10 +141,8 @@ class sfp_similar(SpiderFootPlugin):domlist.append(c + dom)# Search for double character domains- pos = 0- for c in dom:+ for pos, c in enumerate(dom):domlist.append(dom[0:pos] + c + c + dom[(pos + 1):len(dom)])- pos += 1for d in domlist:try:diff --git a/modules/sfp_tldsearch.py b/modules/sfp_tldsearch.pyindex 9ae5a345..2d7bb91f 100644--- a/modules/sfp_tldsearch.py+++ b/modules/sfp_tldsearch.py@@ -95,17 +95,15 @@ class sfp_tldsearch(SpiderFootPlugin):def tryTldWrapper(self, tldList, sourceEvent):self.tldResults = dict()running = True- i = 0t = []# Spawn threads for scanning- self.info("Spawning threads to check TLDs: " + str(tldList))- for pair in tldList:+ self.info(f"Spawning threads to check TLDs: {tldList}")+ for i, pair in enumerate(tldList):(domain, tld) = pairtn = 'thread_sfp_tldsearch_' + str(random.SystemRandom().randint(0, 999999999))t.append(threading.Thread(name=tn, target=self.tryTld, args=(domain, tld,)))t[i].start()- i += 1# Block until all threads are finishedwhile running:diff --git a/modules/sfp_zetalytics.py b/modules/sfp_zetalytics.pyindex 59768724..beb877fd 100644--- a/modules/sfp_zetalytics.py+++ b/modules/sfp_zetalytics.py@@ -132,46 +132,62 @@ class sfp_zetalytics(SpiderFootPlugin):if self.verify_emit_internet_name(qname, pevent):events_generated = True- return events_generated+ return events_generated # noqa R504def generate_hostname_events(self, data, pevent):- events_generated = False+ if not isinstance(data, dict):+ return False++ results = data.get("results")+ if not isinstance(results, list):+ return False+hostnames = set()- if isinstance(data, dict):- results = data.get("results")- if isinstance("results", list):- for r in results:- qname = r.get("qname")- if isinstance("qname", str):- hostnames.add(qname)+ for r in results:+ qname = r.get("qname")+ if isinstance("qname", str):+ hostnames.add(qname)++ events_generated = Falsefor hostname in hostnames:if self.verify_emit_internet_name(hostname, pevent):events_generated = True- return events_generated++ return events_generated # noqa R504def generate_email_events(self, data, pevent):+ if not isinstance(data, dict):+ return False++ results = data.get("results")+ if not isinstance(results, list):+ return False+events_generated = False- if isinstance(data, dict):- results = data.get("results")- if isinstance(results, list):- for r in results:- domain = r.get("d")- if isinstance(domain, str):- self.emit("AFFILIATE_DOMAIN_NAME", domain, pevent)- events_generated = True- return events_generated+ for r in results:+ domain = r.get("d")+ if isinstance(domain, str):+ self.emit("AFFILIATE_DOMAIN_NAME", domain, pevent)+ events_generated = True++ return events_generated # noqa R504def generate_email_domain_events(self, data, pevent):+ if not isinstance(data, dict):+ return False++ results = data.get("results")+ if not isinstance(results, list):+ return False+events_generated = False- if isinstance(data, dict):- results = data.get("results")- if isinstance(results, list):- for r in results:- domain = r.get("d")- if isinstance(domain, str):- self.emit("AFFILIATE_DOMAIN_NAME", domain, pevent)- events_generated = True- return events_generated+ for r in results:+ domain = r.get("d")+ if isinstance(domain, str):+ self.emit("AFFILIATE_DOMAIN_NAME", domain, pevent)+ events_generated = True++ return events_generated # noqa R504def handleEvent(self, event):eventName = event.eventTypediff --git a/setup.cfg b/setup.cfgindex 40f20374..3596273f 100644--- a/setup.cfg+++ b/setup.cfg@@ -5,29 +5,25 @@ docstring-convention = googleignore-decorators = propertyselect = C,E,F,W,B,B9,DAR,DUO,R,A,S,Q0,SIM,SFS# Note: ANN and SIM tests should be reviewed and fixed instead of ignored-ignore = E501 W503 B006 E800 B904 B950 SFS301 SF01 Q000 SIM102 SIM111 SIM113 SIM114 SIM115 I D ANN+extend-ignore = E501 W503 B006 E800 B950 SFS301 SF01 Q000 SIM102 SIM113 SIM114 I D ANN# Note: most of these should be fixed instead of ignoredper-file-ignores =- spiderfoot/event.py:A+ spiderfoot/event.py:A003spiderfoot/plugin.py:B902spiderfoot/db.py:SFS101,B902sf.py:SFS201,B902- sflib.py:SFS101,SIM110,SIM111,B902+ sflib.py:SFS101,SIM110,B902sfscan.py:SIM105,B902- modules/*:B902+ modules/*:SIM115,B902modules/sfp_alienvault.py:B902,C901modules/sfp_binaryedge.py:B902,C901modules/sfp__stor_stdout.py:SFS201modules/sfp_bitcoin.py:SFS101- modules/sfp_reversewhois.py:R504- modules/sfp_ripe.py:SIM110,B902- modules/sfp_zetalytics.py:R504,B902-spiderfoot/correlation.py:SIM110,B902spiderfoot/__init__.py:F401sfcli.py:DAR,B902sfwebui.py:A001,A002,B902- test/*:SIM117,ANN+ test/*:SIM117,B904,ANNdocs/conf.py:A[darglint]diff --git a/sf.py b/sf.pyindex a3696363..ed21b27c 100755--- a/sf.py+++ b/sf.py@@ -39,7 +39,7 @@ scanId = Nonedbh = None-def main():+def main() -> None:# web server configsfWebUiConfig = {'host': '127.0.0.1',@@ -233,7 +233,7 @@ def main():start_scan(sfConfig, sfModules, args, loggingQueue)-def start_scan(sfConfig, sfModules, args, loggingQueue):+def start_scan(sfConfig: dict, sfModules: dict, args, loggingQueue) -> None:"""Start scanArgs:@@ -452,7 +452,7 @@ def start_scan(sfConfig, sfModules, args, loggingQueue):return-def start_web_server(sfWebUiConfig, sfConfig, loggingQueue=None):+def start_web_server(sfWebUiConfig: dict, sfConfig: dict, loggingQueue=None) -> None:"""Start the web server so you can start looking at resultsArgs:@@ -497,9 +497,10 @@ def start_web_server(sfWebUiConfig, sfConfig, loggingQueue=None):log.error("Could not read passwd file. Permission denied.")sys.exit(-1)- pw = open(passwd_file, 'r')+ with open(passwd_file, 'r') as f:+ passwd_data = f.readlines()- for line in pw.readlines():+ for line in passwd_data:if line.strip() == '':continue@@ -581,7 +582,7 @@ def start_web_server(sfWebUiConfig, sfConfig, loggingQueue=None):cherrypy.quickstart(SpiderFootWebUi(sfWebUiConfig, sfConfig, loggingQueue), script_name=web_root, config=conf)-def handle_abort(signal, frame):+def handle_abort(signal, frame) -> None:"""Handle interrupt and abort scan.Args:diff --git a/sfcli.py b/sfcli.pyindex 0ad56504..e319e3bb 100755--- a/sfcli.py+++ b/sfcli.py@@ -248,8 +248,7 @@ class SpiderFootCli(cmd.Cmd):spaces = 2# Find the maximum column sizesfor r in data:- i = 0- for c in r:+ for i, c in enumerate(r):if type(r) == list:# we have list indexcn = str(i)@@ -264,7 +263,6 @@ class SpiderFootCli(cmd.Cmd):# print(str(cn) + ", " + str(c) + ", " + str(v))if len(v) > maxsize.get(cn, 0):maxsize[cn] = len(v)- i += 1# Adjust for long titlesif titlemap:@@ -273,8 +271,7 @@ class SpiderFootCli(cmd.Cmd):maxsize[c] = len(titlemap.get(c, c))# Display the column titles- i = 0- for c in cols:+ for i, c in enumerate(cols):if titlemap:t = titlemap.get(c, c)else:@@ -287,19 +284,16 @@ class SpiderFootCli(cmd.Cmd):if sdiff > 0 and i < len(cols) - 1:# out += " " * sdiffout.append(" " * sdiff)- i += 1# out += "\n"out.append('\n')# Then the separator- i = 0- for c in cols:+ for i, c in enumerate(cols):# out += "-" * ((maxsize[c]+spaces))out.append("-" * ((maxsize[c] + spaces)))if i < len(cols) - 1:# out += "+"out.append("+")- i += 1# out += "\n"out.append("\n")@@ -1364,9 +1358,10 @@ if __name__ == "__main__":# Load commands from a fileif args.e:try:- cin = open(args.e, "r")+ with open(args.e, 'r') as f:+ cin = f.read()except BaseException as e:- print("Unable to open " + args.e + ":" + " (" + str(e) + ")")+ print(f"Unable to open {args.e}: ({e})")sys.exit(-1)else:cin = sys.stdin@@ -1380,9 +1375,8 @@ if __name__ == "__main__":s.ownopts['cli.password'] = args.pif args.P:try:- pf = open(args.P, "r")- s.ownopts['cli.password'] = pf.readlines()[0].strip('\n')- pf.close()+ with open(args.P, 'r') as f:+ s.ownopts['cli.password'] = f.readlines()[0].strip('\n')except BaseException as e:print(f"Unable to open {args.P}: ({e})")sys.exit(-1)diff --git a/sflib.py b/sflib.pyindex 96b786d7..d655a336 100644--- a/sflib.py+++ b/sflib.py@@ -117,7 +117,7 @@ class SpiderFoot:for logging events to the database about a scan.Args:- dbh (SpiderFootDB): database handle+ dbh (SpiderFootDb): database handle"""self._dbh = dbh@@ -1014,11 +1014,10 @@ class SpiderFoot:for d in dicts:try:- wdct = open(f"{self.myPath()}/spiderfoot/dicts/ispell/{d}.dict", 'r')- dlines = wdct.readlines()- wdct.close()+ with open(f"{self.myPath()}/spiderfoot/dicts/ispell/{d}.dict", 'r') as wdct:+ dlines = wdct.readlines()except BaseException as e:- self.debug("Could not read dictionary: " + str(e))+ self.debug(f"Could not read dictionary: {e}")continuefor w in dlines:@@ -2364,7 +2363,7 @@ class SpiderFoot:return True- def cveInfo(self, cveId: str, sources="circl,nist") -> (str, str):+ def cveInfo(self, cveId: str, sources: str = "circl,nist") -> (str, str):"""Look up a CVE ID for more information in the first available source.Args:@@ -2379,7 +2378,7 @@ class SpiderFoot:# a real/mappable CVE.eventType = "VULNERABILITY_GENERAL"- def cveRating(score):+ def cveRating(score: int) -> str:if score == "Unknown":return Noneif score >= 0 and score <= 3.9:diff --git a/sfscan.py b/sfscan.pyindex 85988393..2e2fa61a 100644--- a/sfscan.py+++ b/sfscan.py@@ -51,7 +51,7 @@ class SpiderFootScanner():__modconfig = dict()__scanName = None- def __init__(self, scanName, scanId, targetValue, targetType, moduleList, globalOpts, start=True):+ def __init__(self, scanName: str, scanId: str, targetValue: str, targetType: str, moduleList: list, globalOpts: dict, start: bool = True) -> None:"""Initialize SpiderFootScanner object.Args:@@ -128,7 +128,7 @@ class SpiderFootScanner():except (TypeError, ValueError) as e:self.__sf.status(f"Scan [{self.__scanId}] failed: {e}")self.__setStatus("ERROR-FAILED", None, time.time() * 1000)- raise ValueError(f"Invalid target: {e}")+ raise ValueError(f"Invalid target: {e}") from None# Save the config current set for this scanself.__config['_modulesenabled'] = self.__moduleList@@ -221,14 +221,14 @@ class SpiderFootScanner():self.__startScan()@property- def scanId(self):+ def scanId(self) -> str:return self.__scanId@property- def status(self):+ def status(self) -> str:return self.__status- def __setStatus(self, status, started=None, ended=None):+ def __setStatus(self, status: str, started: float = None, ended: float = None) -> None:"""Set the status of the currently running scan (if any).Args:@@ -259,7 +259,7 @@ class SpiderFootScanner():self.__status = statusself.__dbh.scanInstanceSet(self.__scanId, started, ended, status)- def __startScan(self):+ def __startScan(self) -> None:"""Start running a scan.Raises:@@ -416,9 +416,11 @@ class SpiderFootScanner():except BaseException as e:exc_type, exc_value, exc_traceback = sys.exc_info()- self.__sf.error(f"Unhandled exception ({e.__class__.__name__}) encountered during scan."- + "Please report this as a bug: "- + repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))+ self.__sf.error(+ f"Unhandled exception ({e.__class__.__name__}) encountered during scan."+ + "Please report this as a bug: " ++ + repr(traceback.format_exception(exc_type, exc_value, exc_traceback))+ )self.__sf.status(f"Scan [{self.__scanId}] failed: {e}")self.__setStatus("ERROR-FAILED", None, time.time() * 1000)@@ -429,7 +431,9 @@ class SpiderFootScanner():self.__sf.status(f"Scan [{self.__scanId}] completed.")self.__dbh.close()- def runCorrelations(self):+ def runCorrelations(self) -> None:+ """Run correlation rules."""+self.__sf.status(f"Running {len(self.__config['__correlationrules__'])} correlation rules.")ruleset = dict()for rule in self.__config['__correlationrules__']:@@ -437,7 +441,14 @@ class SpiderFootScanner():corr = SpiderFootCorrelator(self.__dbh, ruleset, self.__scanId)corr.run_correlations()- def waitForThreads(self):+ def waitForThreads(self) -> None:+ """Wait for threads.++ Raises:+ TypeError: queue tried to process a malformed event+ AssertionError: scan halted for some reason+ """+counter = 0try:@@ -510,7 +521,15 @@ class SpiderFootScanner():mod._stopScanning = Trueself.__sharedThreadPool.shutdown(wait=True)- def threadsFinished(self, log_status=False):+ def threadsFinished(self, log_status: bool = False) -> bool:+ """Check if all threads are complete.++ Args:+ log_status (bool): print thread queue status to debug log++ Returns:+ bool: True if all threads are finished+ """if self.eventQueue is None:return Truediff --git a/spiderfoot/correlation.py b/spiderfoot/correlation.pyindex cbbc5e05..76d36938 100644--- a/spiderfoot/correlation.py+++ b/spiderfoot/correlation.py@@ -81,7 +81,7 @@ class SpiderFootCorrelator:self.rules.append(yaml.safe_load(ruleset[rule_id]))self.rules[len(self.rules) - 1]['rawYaml'] = ruleset[rule_id]except Exception as e:- raise SyntaxError(f"Unable to process a YAML correlation rule [{rule_id}]: {e}")+ raise SyntaxError(f"Unable to process a YAML correlation rule [{rule_id}]") from e# Strip any trailing newlines that may have creeped into meta name/descriptionfor rule in self.rules:@@ -508,7 +508,7 @@ class SpiderFootCorrelator:for se in e['source']:se['_collection'] = collectIndex- self.log.debug("returning collection...")+ self.log.debug(f"returning collection ({len(events)})...")return eventsdef aggregate_events(self, rule: dict, events: list) -> dict:@@ -595,6 +595,15 @@ class SpiderFootCorrelator:self.log.debug(f"called with buckets {buckets}")def check_event(events: list, reference: list) -> bool:+ """Check event.++ Args:+ events (list): TBD+ reference (list): TBD++ Returns:+ bool: TBD+ """for event_data in events:if rule['match_method'] == 'subnet':for r in reference:@@ -647,6 +656,13 @@ class SpiderFootCorrelator:del(buckets[bucket])def analysis_first_collection_only(self, rule: dict, buckets: dict) -> None:+ """analysis_first_collection_only TBD++ Args:+ rule (dict): TBD+ buckets (dict): TBD+ """+colzero = set()for bucket in buckets:@@ -671,6 +687,13 @@ class SpiderFootCorrelator:breakdef analysis_outlier(self, rule: dict, buckets: dict) -> None:+ """analysis_outlier TBD++ Args:+ rule (dict): TBD+ buckets (dict): TBD+ """+countmap = dict()for bucket in list(buckets.keys()):countmap[bucket] = len(buckets[bucket])@@ -701,6 +724,13 @@ class SpiderFootCorrelator:del(buckets[bucket])def analysis_threshold(self, rule: dict, buckets: dict) -> None:+ """analysis_treshold TBD++ Args:+ rule (dict): TBD+ buckets (dict): TBD+ """+for bucket in list(buckets.keys()):countmap = dict()for event in buckets[bucket]:@@ -727,22 +757,32 @@ class SpiderFootCorrelator:del(buckets[bucket])def analyze_field_scope(self, field: str) -> list:- children = False- source = False- entity = False+ """Analysis field scope.- if field.startswith('child.'):- children = True- if field.startswith('source.'):- source = True- if field.startswith('entity.'):- entity = True+ Args:+ field (str): TBD- return children, source, entity+ Returns:+ list: TBD+ """++ return [+ field.startswith('child.'),+ field.startswith('source.'),+ field.startswith('entity.')+ ]- # Analyze the rule for use of children, sources or entities- # so that they can be fetched during collectiondef analyze_rule_scope(self, rule: dict) -> list:+ """Analyze the rule for use of children, sources or entities+ so that they can be fetched during collection.++ Args:+ rule (dict): TBD++ Returns:+ list: TBD+ """+children = Falsesource = Falseentity = False@@ -798,17 +838,15 @@ class SpiderFootCorrelator:fetchChildren, fetchSources, fetchEntities = self.analyze_rule_scope(rule)# Go through collections and collect the data from the DB- collectIndex = 0- for c in rule.get('collections'):+ for collectIndex, c in enumerate(rule.get('collections')):events.extend(self.collect_events(c['collect'],fetchChildren,fetchSources,fetchEntities,collectIndex))- collectIndex += 1if not events:- self.log.debug("no events found after going through collections")+ self.log.debug("No events found after going through collections.")return Noneself.log.debug(f"{len(events)} proceeding to next stage: aggregation.")@@ -841,7 +879,7 @@ class SpiderFootCorrelator:data (list): TBDReturns:- str: TBD+ str: correlation rule title"""title = rule['headline']if type(title) == dict:@@ -965,12 +1003,10 @@ class SpiderFootCorrelator:for opt in strictoptions:if type(rule[field]) == list:- item = 0- for optelement in rule[field]:+ for item, optelement in enumerate(rule[field]):if not optelement.get(opt):self.log.error(f"Required field for {field} missing in {rule['id']}, item {item}: {opt}")ok = False- item += 1continueif not rule[field].get(opt):diff --git a/spiderfoot/db.py b/spiderfoot/db.pyindex f0556e76..9234c2fc 100644--- a/spiderfoot/db.py+++ b/spiderfoot/db.py@@ -283,7 +283,7 @@ class SpiderFootDb:['WIKIPEDIA_PAGE_EDIT', 'Wikipedia Page Edit', 0, 'DESCRIPTOR'],]- def __init__(self, opts, init=False):+ def __init__(self, opts: dict, init: bool = False) -> None:"""Initialize database and create handle to the SQLite database file.Creates the database file if it does not exist.Creates database schema if it does not exist.@@ -300,11 +300,11 @@ class SpiderFootDb:"""if not isinstance(opts, dict):- raise TypeError(f"opts is {type(opts)}; expected dict()")+ raise TypeError(f"opts is {type(opts)}; expected dict()") from Noneif not opts:- raise ValueError("opts is empty")+ raise ValueError("opts is empty") from Noneif not opts.get('__database'):- raise ValueError("opts['__database'] is empty")+ raise ValueError("opts['__database'] is empty") from Nonedatabase_path = opts['__database']@@ -317,19 +317,28 @@ class SpiderFootDb:try:dbh = sqlite3.connect(database_path)except Exception as e:- raise IOError(f"Error connecting to internal database {database_path}: {e}")+ raise IOError(f"Error connecting to internal database {database_path}") from eif dbh is None:- raise IOError(f"Could not connect to internal database, and could not create {database_path}")+ raise IOError(f"Could not connect to internal database, and could not create {database_path}") from Nonedbh.text_factory = strself.conn = dbhself.dbh = dbh.cursor()- # SQLite doesn't support regex queries, so we create- # a custom function to do so..- def __dbregex__(qry, data):+ def __dbregex__(qry: str, data: str) -> bool:+ """SQLite doesn't support regex queries, so we create+ a custom function to do so.++ Args:+ qry (str): TBD+ data (str): TBD++ Returns:+ bool: matches+ """+try:rx = re.compile(qry, re.IGNORECASE | re.DOTALL)ret = rx.match(data)@@ -348,7 +357,7 @@ class SpiderFootDb:try:self.create()except Exception as e:- raise IOError(f"Tried to set up the SpiderFoot database schema, but failed: {e.args[0]}")+ raise IOError("Tried to set up the SpiderFoot database schema, but failed") from e# For users with pre 4.0 databases, add the correlation# tables + indexes if they don't exist.@@ -363,7 +372,7 @@ class SpiderFootDb:except sqlite3.Error:raise IOError("Looks like you are running a pre-4.0 database. Unfortunately ""SpiderFoot wasn't able to migrate you, so you'll need to delete "- "your SpiderFoot database in order to proceed.")+ "your SpiderFoot database in order to proceed.") from Noneif init:for row in self.eventDetails:@@ -386,7 +395,7 @@ class SpiderFootDb:# Back-end database operations#- def create(self):+ def create(self) -> None:"""Create the database schema.Raises:@@ -410,15 +419,15 @@ class SpiderFootDb:))self.conn.commit()except sqlite3.Error as e:- raise IOError(f"SQL error encountered when setting up database: {e.args[0]}")+ raise IOError("SQL error encountered when setting up database") from e- def close(self):+ def close(self) -> None:"""Close the database handle."""with self.dbhLock:self.dbh.close()- def search(self, criteria, filterFp=False):+ def search(self, criteria: dict, filterFp: bool = False) -> list:"""Search database.Args:@@ -439,7 +448,7 @@ class SpiderFootDb:IOError: database I/O failed"""if not isinstance(criteria, dict):- raise TypeError(f"criteria is {type(criteria)}; expected dict()")+ raise TypeError(f"criteria is {type(criteria)}; expected dict()") from Nonevalid_criteria = ['scan_id', 'type', 'value', 'regex']@@ -449,14 +458,14 @@ class SpiderFootDb:continueif not isinstance(criteria.get(key), str):- raise TypeError(f"criteria[{key}] is {type(criteria.get(key))}; expected str()")+ raise TypeError(f"criteria[{key}] is {type(criteria.get(key))}; expected str()") from Noneif not criteria[key]:criteria.pop(key, None)continueif len(criteria) == 0:- raise ValueError(f"No valid search criteria provided; expected: {', '.join(valid_criteria)}")+ raise ValueError(f"No valid search criteria provided; expected: {', '.join(valid_criteria)}") from Noneif len(criteria) == 1:raise ValueError("Only one search criteria provided; expected at least two")@@ -499,9 +508,9 @@ class SpiderFootDb:self.dbh.execute(qry, qvars)return self.dbh.fetchall()except sqlite3.Error as e:- raise IOError(f"SQL error encountered when fetching search results: {e.args[0]}")+ raise IOError("SQL error encountered when fetching search results") from e- def eventTypes(self):+ def eventTypes(self) -> list:"""Get event types.Returns:@@ -517,9 +526,9 @@ class SpiderFootDb:self.dbh.execute(qry)return self.dbh.fetchall()except sqlite3.Error as e:- raise IOError(f"SQL error encountered when retrieving event types: {e.args[0]}")+ raise IOError("SQL error encountered when retrieving event types") from e- def scanLogEvents(self, batch):+ def scanLogEvents(self, batch: list) -> bool:"""Logs a batch of events to the database.Args:@@ -530,20 +539,20 @@ class SpiderFootDb:IOError: database I/O failedReturns:- logResult: Whether the logging operation succeeded+ bool: Whether the logging operation succeeded"""inserts = []for instanceId, classification, message, component, logTime in batch:if not isinstance(instanceId, str):- raise TypeError(f"instanceId is {type(instanceId)}; expected str()")+ raise TypeError(f"instanceId is {type(instanceId)}; expected str()") from Noneif not isinstance(classification, str):- raise TypeError(f"classification is {type(classification)}; expected str()")+ raise TypeError(f"classification is {type(classification)}; expected str()") from Noneif not isinstance(message, str):- raise TypeError(f"message is {type(message)}; expected str()")+ raise TypeError(f"message is {type(message)}; expected str()") from Noneif not component:component = "SpiderFoot"@@ -561,11 +570,11 @@ class SpiderFootDb:self.conn.commit()except sqlite3.Error as e:if "locked" not in e.args[0] and "thread" not in e.args[0]:- raise IOError(f"Unable to log scan event in DB: {e.args[0]}")+ raise IOError("Unable to log scan event in database") from ereturn Falsereturn True- def scanLogEvent(self, instanceId, classification, message, component=None):+ def scanLogEvent(self, instanceId: str, classification: str, message: str, component: str = None) -> None:"""Log an event to the database.Args:@@ -583,13 +592,13 @@ class SpiderFootDb:"""if not isinstance(instanceId, str):- raise TypeError(f"instanceId is {type(instanceId)}; expected str()")+ raise TypeError(f"instanceId is {type(instanceId)}; expected str()") from Noneif not isinstance(classification, str):- raise TypeError(f"classification is {type(classification)}; expected str()")+ raise TypeError(f"classification is {type(classification)}; expected str()") from Noneif not isinstance(message, str):- raise TypeError(f"message is {type(message)}; expected str()")+ raise TypeError(f"message is {type(message)}; expected str()") from Noneif not component:component = "SpiderFoot"@@ -606,12 +615,12 @@ class SpiderFootDb:self.conn.commit()except sqlite3.Error as e:if "locked" not in e.args[0] and "thread" not in e.args[0]:- raise IOError(f"Unable to log scan event in DB: {e.args[0]}")+ raise IOError("Unable to log scan event in database") from e# print("[warning] Couldn't log due to SQLite limitations. You can probably ignore this.")# log.critical(f"Unable to log event in DB due to lock: {e.args[0]}")pass- def scanInstanceCreate(self, instanceId, scanName, scanTarget):+ def scanInstanceCreate(self, instanceId: str, scanName: str, scanTarget: str) -> None:"""Store a scan instance in the database.Args:@@ -625,13 +634,13 @@ class SpiderFootDb:"""if not isinstance(instanceId, str):- raise TypeError(f"instanceId is {type(instanceId)}; expected str()")+ raise TypeError(f"instanceId is {type(instanceId)}; expected str()") from Noneif not isinstance(scanName, str):- raise TypeError(f"scanName is {type(scanName)}; expected str()")+ raise TypeError(f"scanName is {type(scanName)}; expected str()") from Noneif not isinstance(scanTarget, str):- raise TypeError(f"scanTarget is {type(scanTarget)}; expected str()")+ raise TypeError(f"scanTarget is {type(scanTarget)}; expected str()") from Noneqry = "INSERT INTO tbl_scan_instance \(guid, name, seed_target, created, status) \@@ -644,9 +653,9 @@ class SpiderFootDb:))self.conn.commit()except sqlite3.Error as e:- raise IOError(f"Unable to create scan instance in DB: {e.args[0]}")+ raise IOError("Unable to create scan instance in database") from e- def scanInstanceSet(self, instanceId, started=None, ended=None, status=None):+ def scanInstanceSet(self, instanceId: str, started: str = None, ended: str = None, status: str = None) -> None:"""Update the start time, end time or status (or all 3) of a scan instance.Args:@@ -661,7 +670,7 @@ class SpiderFootDb:"""if not isinstance(instanceId, str):- raise TypeError(f"instanceId is {type(instanceId)}; expected str()")+ raise TypeError(f"instanceId is {type(instanceId)}; expected str()") from Noneqvars = list()qry = "UPDATE tbl_scan_instance SET "@@ -687,9 +696,9 @@ class SpiderFootDb:self.dbh.execute(qry, qvars)self.conn.commit()except sqlite3.Error:- raise IOError("Unable to set information for the scan instance.")+ raise IOError("Unable to set information for the scan instance.") from None- def scanInstanceGet(self, instanceId):+ def scanInstanceGet(self, instanceId: str) -> list:"""Return info about a scan instance (name, target, created, started, ended, status)Args:@@ -704,7 +713,7 @@ class SpiderFootDb:"""if not isinstance(instanceId, str):- raise TypeError(f"instanceId is {type(instanceId)}; expected str()")+ raise TypeError(f"instanceId is {type(instanceId)}; expected str()") from Noneqry = "SELECT name, seed_target, ROUND(created/1000) AS created, \ROUND(started/1000) AS started, ROUND(ended/1000) AS ended, status \@@ -716,9 +725,9 @@ class SpiderFootDb:self.dbh.execute(qry, qvars)return self.dbh.fetchone()except sqlite3.Error as e:- raise IOError(f"SQL error encountered when retrieving scan instance: {e.args[0]}")+ raise IOError("SQL error encountered when retrieving scan instance") from e- def scanResultSummary(self, instanceId, by="type"):+ def scanResultSummary(self, instanceId: str, by: str = "type") -> list:"""Obtain a summary of the results, filtered by event type, module or entity.Args:@@ -735,13 +744,13 @@ class SpiderFootDb:"""if not isinstance(instanceId, str):- raise TypeError(f"instanceId is {type(instanceId)}; expected str()")+ raise TypeError(f"instanceId is {type(instanceId)}; expected str()") from Noneif not isinstance(by, str):- raise TypeError(f"by is {type(by)}; expected str()")+ raise TypeError(f"by is {type(by)}; expected str()") from Noneif by not in ["type", "module", "entity"]:- raise ValueError(f"Invalid filter by value: {by}")+ raise ValueError(f"Invalid filter by value: {by}") from Noneif by == "type":qry = "SELECT r.type, e.event_descr, MAX(ROUND(generated)) AS last_in, \@@ -770,9 +779,9 @@ class SpiderFootDb:self.dbh.execute(qry, qvars)return self.dbh.fetchall()except sqlite3.Error as e:- raise IOError(f"SQL error encountered when fetching result summary: {e.args[0]}")+ raise IOError("SQL error encountered when fetching result summary") from e- def scanCorrelationSummary(self, instanceId, by="rule"):+ def scanCorrelationSummary(self, instanceId: str, by: str = "rule") -> list:"""Obtain a summary of the correlations, filtered by rule or riskArgs:@@ -789,13 +798,13 @@ class SpiderFootDb:"""if not isinstance(instanceId, str):- raise TypeError(f"instanceId is {type(instanceId)}; expected str()")+ raise TypeError(f"instanceId is {type(instanceId)}; expected str()") from Noneif not isinstance(by, str):- raise TypeError(f"by is {type(by)}; expected str()")+ raise TypeError(f"by is {type(by)}; expected str()") from Noneif by not in ["rule", "risk"]:- raise ValueError(f"Invalid filter by value: {by}")+ raise ValueError(f"Invalid filter by value: {by}") from Noneif by == "risk":qry = "SELECT rule_risk, count(*) AS total FROM \@@ -815,9 +824,9 @@ class SpiderFootDb:self.dbh.execute(qry, qvars)return self.dbh.fetchall()except sqlite3.Error as e:- raise IOError(f"SQL error encountered when fetching correlation summary: {e.args[0]}")+ raise IOError("SQL error encountered when fetching correlation summary") from e- def scanCorrelationList(self, instanceId):+ def scanCorrelationList(self, instanceId: str) -> list:"""Obtain a list of the correlations from a scanArgs:@@ -832,7 +841,7 @@ class SpiderFootDb:"""if not isinstance(instanceId, str):- raise TypeError(f"instanceId is {type(instanceId)}; expected str()")+ raise TypeError(f"instanceId is {type(instanceId)}; expected str()") from Noneqry = "SELECT c.id, c.title, c.rule_id, c.rule_risk, c.rule_name, \c.rule_descr, c.rule_logic, count(e.event_hash) AS event_count FROM \@@ -847,18 +856,26 @@ class SpiderFootDb:self.dbh.execute(qry, qvars)return self.dbh.fetchall()except sqlite3.Error as e:- raise IOError(f"SQL error encountered when fetching correlation list: {e.args[0]}")-- def scanResultEvent(self, instanceId, eventType='ALL', srcModule=None,- data=None, sourceId=None, correlationId=None, filterFp=False):+ raise IOError("SQL error encountered when fetching correlation list") from e++ def scanResultEvent(+ self,+ instanceId: str,+ eventType: str = 'ALL',+ srcModule: str = None,+ data: list = None,+ sourceId: list = None,+ correlationId: str = None,+ filterFp: bool = False+ ) -> list:"""Obtain the data for a scan and event type.Args:instanceId (str): scan instance IDeventType (str): filter by event typesrcModule (str): filter by the generating module- data (list[str]): filter by the data- sourceId (list[str]): filter by the ID of the source event+ data (list): filter by the data+ sourceId (list): filter by the ID of the source eventcorrelationId (str): filter by the ID of a correlation resultfilterFp (bool): filter false positives@@ -871,10 +888,10 @@ class SpiderFootDb:"""if not isinstance(instanceId, str):- raise TypeError(f"instanceId is {type(instanceId)}; expected str()")+ raise TypeError(f"instanceId is {type(instanceId)}; expected str()") from Noneif not isinstance(eventType, str) and not isinstance(eventType, list):- raise TypeError(f"eventType is {type(eventType)}; expected str() or list()")+ raise TypeError(f"eventType is {type(eventType)}; expected str() or list()") from Noneqry = "SELECT ROUND(c.generated) AS generated, c.data, \s.data as 'source_data', \@@ -937,9 +954,9 @@ class SpiderFootDb:self.dbh.execute(qry, qvars)return self.dbh.fetchall()except sqlite3.Error as e:- raise IOError(f"SQL error encountered when fetching result events: {e.args[0]}")+ raise IOError("SQL error encountered when fetching result events") from e- def scanResultEventUnique(self, instanceId, eventType='ALL', filterFp=False):+ def scanResultEventUnique(self, instanceId: str, eventType: str = 'ALL', filterFp: bool = False) -> list:"""Obtain a unique list of elements.Args:@@ -956,10 +973,10 @@ class SpiderFootDb:"""if not isinstance(instanceId, str):- raise TypeError(f"instanceId is {type(instanceId)}; expected str()")+ raise TypeError(f"instanceId is {type(instanceId)}; expected str()") from Noneif not isinstance(eventType, str):- raise TypeError(f"eventType is {type(eventType)}; expected str()")+ raise TypeError(f"eventType is {type(eventType)}; expected str()") from Noneqry = "SELECT DISTINCT data, type, COUNT(*) FROM tbl_scan_results \WHERE scan_instance_id = ?"@@ -979,9 +996,9 @@ class SpiderFootDb:self.dbh.execute(qry, qvars)return self.dbh.fetchall()except sqlite3.Error as e:- raise IOError(f"SQL error encountered when fetching unique result events: {e.args[0]}")+ raise IOError("SQL error encountered when fetching unique result events") from e- def scanLogs(self, instanceId, limit=None, fromRowId=None, reverse=False):+ def scanLogs(self, instanceId: str, limit: int = None, fromRowId: int = 0, reverse: bool = False) -> list:"""Get scan logs.Args:@@ -999,7 +1016,7 @@ class SpiderFootDb:"""if not isinstance(instanceId, str):- raise TypeError(f"instanceId is {type(instanceId)}; expected str()")+ raise TypeError(f"instanceId is {type(instanceId)}; expected str()") from Noneqry = "SELECT generated AS generated, component, \type, message, rowid FROM tbl_scan_log WHERE scan_instance_id = ?"@@ -1014,20 +1031,20 @@ class SpiderFootDb:qvars = [instanceId]if fromRowId:- qvars.append(fromRowId)+ qvars.append(str(fromRowId))if limit is not None:qry += " LIMIT ?"- qvars.append(limit)+ qvars.append(str(limit))with self.dbhLock:try:self.dbh.execute(qry, qvars)return self.dbh.fetchall()except sqlite3.Error as e:- raise IOError(f"SQL error encountered when fetching scan logs: {e.args[0]}")+ raise IOError("SQL error encountered when fetching scan logs") from e- def scanErrors(self, instanceId, limit=None):+ def scanErrors(self, instanceId: str, limit: int = 0) -> list:"""Get scan errors.Args:@@ -1043,38 +1060,43 @@ class SpiderFootDb:"""if not isinstance(instanceId, str):- raise TypeError(f"instanceId is {type(instanceId)}; expected str()")+ raise TypeError(f"instanceId is {type(instanceId)}; expected str()") from None++ if not isinstance(limit, int):+ raise TypeError(f"limit is {type(limit)}; expected int()") from Noneqry = "SELECT generated AS generated, component, \message FROM tbl_scan_log WHERE scan_instance_id = ? \AND type = 'ERROR' ORDER BY generated DESC"qvars = [instanceId]- if limit is not None:+ if limit:qry += " LIMIT ?"- qvars.append(limit)+ qvars.append(str(limit))with self.dbhLock:try:self.dbh.execute(qry, qvars)return self.dbh.fetchall()except sqlite3.Error as e:- raise IOError(f"SQL error encountered when fetching scan errors: {e.args[0]}")+ raise IOError("SQL error encountered when fetching scan errors") from e- # Delete a scan instance- def scanInstanceDelete(self, instanceId):+ def scanInstanceDelete(self, instanceId: str) -> bool:"""Delete a scan instance.Args:instanceId (str): scan instance ID+ Returns:+ bool: success+Raises:TypeError: arg type was invalidIOError: database I/O failed"""if not isinstance(instanceId, str):- raise TypeError(f"instanceId is {type(instanceId)}; expected str()")+ raise TypeError(f"instanceId is {type(instanceId)}; expected str()") from Noneqry1 = "DELETE FROM tbl_scan_instance WHERE guid = ?"qry2 = "DELETE FROM tbl_scan_config WHERE scan_instance_id = ?"@@ -1090,9 +1112,11 @@ class SpiderFootDb:self.dbh.execute(qry4, qvars)self.conn.commit()except sqlite3.Error as e:- raise IOError(f"SQL error encountered when deleting scan: {e.args[0]}")+ raise IOError("SQL error encountered when deleting scan") from e++ return True- def scanResultsUpdateFP(self, instanceId, resultHashes, fpFlag):+ def scanResultsUpdateFP(self, instanceId: str, resultHashes: list, fpFlag: int) -> bool:"""Set the false positive flag for a result.Args:@@ -1109,10 +1133,10 @@ class SpiderFootDb:"""if not isinstance(instanceId, str):- raise TypeError(f"instanceId is {type(instanceId)}; expected str()")+ raise TypeError(f"instanceId is {type(instanceId)}; expected str()") from Noneif not isinstance(resultHashes, list):- raise TypeError(f"resultHashes is {type(resultHashes)}; expected list()")+ raise TypeError(f"resultHashes is {type(resultHashes)}; expected list()") from Nonewith self.dbhLock:for resultHash in resultHashes:@@ -1122,21 +1146,24 @@ class SpiderFootDb:try:self.dbh.execute(qry, qvars)except sqlite3.Error as e:- raise IOError(f"SQL error encountered when updating F/P: {e.args[0]}")+ raise IOError("SQL error encountered when updating false-positive") from etry:self.conn.commit()except sqlite3.Error as e:- raise IOError(f"SQL error encountered when updating F/P: {e.args[0]}")+ raise IOError("SQL error encountered when updating false-positive") from ereturn True- def configSet(self, optMap=dict()):+ def configSet(self, optMap: dict = {}) -> bool:"""Store the default configuration in the database.Args:optMap (dict): config options+ Returns:+ bool: success+Raises:TypeError: arg type was invalidValueError: arg value was invalid@@ -1144,9 +1171,9 @@ class SpiderFootDb:"""if not isinstance(optMap, dict):- raise TypeError(f"optMap is {type(optMap)}; expected dict()")+ raise TypeError(f"optMap is {type(optMap)}; expected dict()") from Noneif not optMap:- raise ValueError("optMap is empty")+ raise ValueError("optMap is empty") from Noneqry = "REPLACE INTO tbl_config (scope, opt, val) VALUES (?, ?, ?)"@@ -1163,14 +1190,16 @@ class SpiderFootDb:try:self.dbh.execute(qry, qvals)except sqlite3.Error as e:- raise IOError(f"SQL error encountered when storing config, aborting: {e.args[0]}")+ raise IOError("SQL error encountered when storing config, aborting") from etry:self.conn.commit()except sqlite3.Error as e:- raise IOError(f"SQL error encountered when storing config, aborting: {e.args[0]}")+ raise IOError("SQL error encountered when storing config, aborting") from e- def configGet(self):+ return True++ def configGet(self) -> dict:"""Retreive the config from the databaseReturns:@@ -1195,10 +1224,11 @@ class SpiderFootDb:return retvalexcept sqlite3.Error as e:- raise IOError(f"SQL error encountered when fetching configuration: {e.args[0]}")+ raise IOError("SQL error encountered when fetching configuration") from e- def configClear(self):+ def configClear(self) -> None:"""Reset the config to default.+Clears the config from the database and lets the hard-coded settings in the code take effect.Raises:@@ -1211,9 +1241,9 @@ class SpiderFootDb:self.dbh.execute(qry)self.conn.commit()except sqlite3.Error as e:- raise IOError(f"Unable to clear configuration from the database: {e.args[0]}")+ raise IOError("Unable to clear configuration from the database") from e- def scanConfigSet(self, scan_id, optMap=dict()):+ def scanConfigSet(self, scan_id, optMap=dict()) -> None:"""Store a configuration value for a scan.Args:@@ -1227,9 +1257,9 @@ class SpiderFootDb:"""if not isinstance(optMap, dict):- raise TypeError(f"optMap is {type(optMap)}; expected dict()")+ raise TypeError(f"optMap is {type(optMap)}; expected dict()") from Noneif not optMap:- raise ValueError("optMap is empty")+ raise ValueError("optMap is empty") from Noneqry = "REPLACE INTO tbl_scan_config \(scan_instance_id, component, opt, val) VALUES (?, ?, ?, ?)"@@ -1247,18 +1277,18 @@ class SpiderFootDb:try:self.dbh.execute(qry, qvals)except sqlite3.Error as e:- raise IOError(f"SQL error encountered when storing config, aborting: {e.args[0]}")+ raise IOError("SQL error encountered when storing config, aborting") from etry:self.conn.commit()except sqlite3.Error as e:- raise IOError(f"SQL error encountered when storing config, aborting: {e.args[0]}")+ raise IOError("SQL error encountered when storing config, aborting") from e- def scanConfigGet(self, instanceId):+ def scanConfigGet(self, instanceId: str) -> dict:"""Retrieve configuration data for a scan component.Args:- instanceId (int): scan instance ID+ instanceId (str): scan instance IDReturns:dict: configuration data@@ -1269,7 +1299,7 @@ class SpiderFootDb:"""if not isinstance(instanceId, str):- raise TypeError(f"instanceId is {type(instanceId)}; expected str()")+ raise TypeError(f"instanceId is {type(instanceId)}; expected str()") from Noneqry = "SELECT component, opt, val FROM tbl_scan_config \WHERE scan_instance_id = ? ORDER BY component, opt"@@ -1287,9 +1317,9 @@ class SpiderFootDb:retval[f"{component}:{opt}"] = valreturn retvalexcept sqlite3.Error as e:- raise IOError(f"SQL error encountered when fetching configuration: {e.args[0]}")+ raise IOError("SQL error encountered when fetching configuration") from e- def scanEventStore(self, instanceId, sfEvent, truncateSize=0):+ def scanEventStore(self, instanceId: str, sfEvent, truncateSize: int = 0) -> None:"""Store an event in the database.Args:@@ -1305,66 +1335,66 @@ class SpiderFootDb:from spiderfoot import SpiderFootEventif not isinstance(instanceId, str):- raise TypeError(f"instanceId is {type(instanceId)}; expected str()")+ raise TypeError(f"instanceId is {type(instanceId)}; expected str()") from Noneif not instanceId:- raise ValueError("instanceId is empty")+ raise ValueError("instanceId is empty") from Noneif not isinstance(sfEvent, SpiderFootEvent):- raise TypeError(f"sfEvent is {type(sfEvent)}; expected SpiderFootEvent()")+ raise TypeError(f"sfEvent is {type(sfEvent)}; expected SpiderFootEvent()") from Noneif not isinstance(sfEvent.generated, float):- raise TypeError(f"sfEvent.generated is {type(sfEvent.generated)}; expected float()")+ raise TypeError(f"sfEvent.generated is {type(sfEvent.generated)}; expected float()") from Noneif not sfEvent.generated:- raise ValueError("sfEvent.generated is empty")+ raise ValueError("sfEvent.generated is empty") from Noneif not isinstance(sfEvent.eventType, str):- raise TypeError(f"sfEvent.eventType is {type(sfEvent.eventType,)}; expected str()")+ raise TypeError(f"sfEvent.eventType is {type(sfEvent.eventType,)}; expected str()") from Noneif not sfEvent.eventType:- raise ValueError("sfEvent.eventType is empty")+ raise ValueError("sfEvent.eventType is empty") from Noneif not isinstance(sfEvent.data, str):- raise TypeError(f"sfEvent.data is {type(sfEvent.data)}; expected str()")+ raise TypeError(f"sfEvent.data is {type(sfEvent.data)}; expected str()") from Noneif not sfEvent.data:- raise ValueError("sfEvent.data is empty")+ raise ValueError("sfEvent.data is empty") from Noneif not isinstance(sfEvent.module, str):- raise TypeError(f"sfEvent.module is {type(sfEvent.module)}; expected str()")+ raise TypeError(f"sfEvent.module is {type(sfEvent.module)}; expected str()") from Noneif not sfEvent.module:if sfEvent.eventType != "ROOT":- raise ValueError("sfEvent.module is empty")+ raise ValueError("sfEvent.module is empty") from Noneif not isinstance(sfEvent.confidence, int):- raise TypeError(f"sfEvent.confidence is {type(sfEvent.confidence)}; expected int()")+ raise TypeError(f"sfEvent.confidence is {type(sfEvent.confidence)}; expected int()") from Noneif not 0 <= sfEvent.confidence <= 100:- raise ValueError(f"sfEvent.confidence value is {type(sfEvent.confidence)}; expected 0 - 100")+ raise ValueError(f"sfEvent.confidence value is {type(sfEvent.confidence)}; expected 0 - 100") from Noneif not isinstance(sfEvent.visibility, int):- raise TypeError(f"sfEvent.visibility is {type(sfEvent.visibility)}; expected int()")+ raise TypeError(f"sfEvent.visibility is {type(sfEvent.visibility)}; expected int()") from Noneif not 0 <= sfEvent.visibility <= 100:- raise ValueError(f"sfEvent.visibility value is {type(sfEvent.visibility)}; expected 0 - 100")+ raise ValueError(f"sfEvent.visibility value is {type(sfEvent.visibility)}; expected 0 - 100") from Noneif not isinstance(sfEvent.risk, int):- raise TypeError(f"sfEvent.risk is {type(sfEvent.risk)}; expected int()")+ raise TypeError(f"sfEvent.risk is {type(sfEvent.risk)}; expected int()") from Noneif not 0 <= sfEvent.risk <= 100:- raise ValueError(f"sfEvent.risk value is {type(sfEvent.risk)}; expected 0 - 100")+ raise ValueError(f"sfEvent.risk value is {type(sfEvent.risk)}; expected 0 - 100") from Noneif not isinstance(sfEvent.sourceEvent, SpiderFootEvent):if sfEvent.eventType != "ROOT":- raise TypeError(f"sfEvent.sourceEvent is {type(sfEvent.sourceEvent)}; expected str()")+ raise TypeError(f"sfEvent.sourceEvent is {type(sfEvent.sourceEvent)}; expected str()") from Noneif not isinstance(sfEvent.sourceEventHash, str):- raise TypeError(f"sfEvent.sourceEventHash is {type(sfEvent.sourceEventHash)}; expected str()")+ raise TypeError(f"sfEvent.sourceEventHash is {type(sfEvent.sourceEventHash)}; expected str()") from Noneif not sfEvent.sourceEventHash:- raise ValueError("sfEvent.sourceEventHash is empty")+ raise ValueError("sfEvent.sourceEventHash is empty") from NonestoreData = sfEvent.data@@ -1388,9 +1418,9 @@ class SpiderFootDb:self.dbh.execute(qry, qvals)self.conn.commit()except sqlite3.Error as e:- raise IOError(f"SQL error encountered when storing event data ({self.dbh}): {e.args[0]}")+ raise IOError(f"SQL error encountered when storing event data ({self.dbh})") from e- def scanInstanceList(self):+ def scanInstanceList(self) -> list:"""List all previously run scans.Returns:@@ -1419,9 +1449,9 @@ class SpiderFootDb:self.dbh.execute(qry)return self.dbh.fetchall()except sqlite3.Error as e:- raise IOError(f"SQL error encountered when fetching scan list: {e.args[0]}")+ raise IOError("SQL error encountered when fetching scan list") from e- def scanResultHistory(self, instanceId):+ def scanResultHistory(self, instanceId: str) -> list:"""History of data from the scan.Args:@@ -1436,7 +1466,7 @@ class SpiderFootDb:"""if not isinstance(instanceId, str):- raise TypeError(f"instanceId is {type(instanceId)}; expected str()")+ raise TypeError(f"instanceId is {type(instanceId)}; expected str()") from Noneqry = "SELECT STRFTIME('%H:%M %w', generated, 'unixepoch') AS hourmin, \type, COUNT(*) FROM tbl_scan_results \@@ -1448,9 +1478,9 @@ class SpiderFootDb:self.dbh.execute(qry, qvars)return self.dbh.fetchall()except sqlite3.Error as e:- raise IOError(f"SQL error encountered when fetching scan history: {e.args[0]}")+ raise IOError(f"SQL error encountered when fetching history for scan {instanceId}") from e- def scanElementSourcesDirect(self, instanceId, elementIdList):+ def scanElementSourcesDirect(self, instanceId: str, elementIdList: list) -> list:"""Get the source IDs, types and data for a set of IDs.Args:@@ -1466,10 +1496,10 @@ class SpiderFootDb:"""if not isinstance(instanceId, str):- raise TypeError(f"instanceId is {type(instanceId)}; expected str()")+ raise TypeError(f"instanceId is {type(instanceId)}; expected str()") from Noneif not isinstance(elementIdList, list):- raise TypeError(f"elementIdList is {type(elementIdList)}; expected list()")+ raise TypeError(f"elementIdList is {type(elementIdList)}; expected list()") from NonehashIds = []for hashId in elementIdList:@@ -1499,9 +1529,9 @@ class SpiderFootDb:self.dbh.execute(qry, qvars)return self.dbh.fetchall()except sqlite3.Error as e:- raise IOError(f"SQL error encountered when getting source element IDs: {e.args[0]}")+ raise IOError("SQL error encountered when getting source element IDs") from e- def scanElementChildrenDirect(self, instanceId, elementIdList):+ def scanElementChildrenDirect(self, instanceId: str, elementIdList: list) -> list:"""Get the child IDs, types and data for a set of IDs.Args:@@ -1548,9 +1578,9 @@ class SpiderFootDb:self.dbh.execute(qry, qvars)return self.dbh.fetchall()except sqlite3.Error as e:- raise IOError(f"SQL error encountered when getting child element IDs: {e.args[0]}")+ raise IOError("SQL error encountered when getting child element IDs") from e- def scanElementSourcesAll(self, instanceId, childData):+ def scanElementSourcesAll(self, instanceId: str, childData: list) -> list:"""Get the full set of upstream IDs which are parents to the supplied set of IDs.Args:@@ -1621,7 +1651,7 @@ class SpiderFootDb:datamap[parentId] = rowreturn [datamap, pc]- def scanElementChildrenAll(self, instanceId, parentIds):+ def scanElementChildrenAll(self, instanceId: str, parentIds: list) -> list:"""Get the full set of downstream IDs which are children of the supplied set of IDs.Args:@@ -1669,8 +1699,17 @@ class SpiderFootDb:return datamap- def correlationResultCreate(self, instanceId, ruleId, ruleName, ruleDescr,- ruleRisk, ruleYaml, correlationTitle, eventHashes):+ def correlationResultCreate(+ self,+ instanceId: str,+ ruleId: str,+ ruleName: str,+ ruleDescr: str,+ ruleRisk: str,+ ruleYaml: str,+ correlationTitle: str,+ eventHashes: list+ ) -> str:"""Create a correlation result in the database.Args:@@ -1728,7 +1767,7 @@ class SpiderFootDb:))self.conn.commit()except sqlite3.Error as e:- raise IOError(f"Unable to create correlation result in DB: {e.args[0]}")+ raise IOError("Unable to create correlation result in database") from e# Map events to the correlation resultqry = "INSERT INTO tbl_scan_correlation_results_events \@@ -1743,6 +1782,6 @@ class SpiderFootDb:))self.conn.commit()except sqlite3.Error as e:- raise IOError(f"Unable to create correlation result in DB: {e.args[0]}")+ raise IOError("Unable to create correlation result in database") from ereturn uniqueIddiff --git a/spiderfoot/helpers.py b/spiderfoot/helpers.pyindex 2c2ef0b2..36f5e21c 100644--- a/spiderfoot/helpers.py+++ b/spiderfoot/helpers.py@@ -56,7 +56,7 @@ class SpiderFootHelpers():return path@staticmethod- def loadModulesAsDict(path: str, ignore_files: list = ['sfp_template.py']) -> dict():+ def loadModulesAsDict(path: str, ignore_files: list = ['sfp_template.py']) -> dict:"""Load modules from modules directory.Args:@@ -107,7 +107,7 @@ class SpiderFootHelpers():return sfModules@staticmethod- def loadCorrelationRulesRaw(path: str, ignore_files: list = ['template.yaml']) -> dict():+ def loadCorrelationRulesRaw(path: str, ignore_files: list = ['template.yaml']) -> dict:"""Load correlation rules from correlations directory.Args:@@ -135,12 +135,13 @@ class SpiderFootHelpers():continueruleName = filename.split('.')[0]- correlationRulesRaw[ruleName] = open(path + filename, 'r').read()+ with open(path + filename, 'r') as f:+ correlationRulesRaw[ruleName] = f.read()return correlationRulesRaw@staticmethod- def targetTypeFromString(target: str) -> None:+ def targetTypeFromString(target: str) -> str:"""Return the scan target seed data type for the specified scan target input.Args:@@ -321,7 +322,7 @@ class SpiderFootHelpers():if not data:raise ValueError("data is empty")- def get_next_parent_entities(item: str, pids: list) -> list:+ def get_next_parent_entities(item: str, pids: list = []) -> list:ret = list()for [parent, entity_id] in parents[item]:@@ -362,9 +363,8 @@ class SpiderFootHelpers():# Add entity parentmapping.add((entity, parent))else:- ppids = list()# Check parent for entityship.- next_parents = get_next_parent_entities(parent, ppids)+ next_parents = get_next_parent_entities(parent)for next_parent in next_parents:if entity != next_parent:# Add next entity parentdiff --git a/spiderfoot/plugin.py b/spiderfoot/plugin.pyindex 01cb4602..382c5951 100644--- a/spiderfoot/plugin.py+++ b/spiderfoot/plugin.py@@ -30,16 +30,16 @@ class SpiderFootPluginLogger(logging.Logger):Preserves filename, module, line numbers, etc. from the caller."""- def findCaller(self, stack_info=False, stacklevel=1):+ def findCaller(self, stack_info: bool = False, stacklevel: int = 1) -> tuple:"""Find the stack frame of the caller so that we can note the sourcefile name, line number and function name.Args:- stack_info: boolean- stacklevel: int+ stack_info (bool): TBD+ stacklevel (int): TBDReturns:- rv: tuple, filename, line number, module name, and stack trace+ tuple: filename, line number, module name, and stack trace"""f = logging.currentframe()# On some versions of IronPython, currentframe() returns None if@@ -132,7 +132,7 @@ class SpiderFootPlugin():# Maximum threadsmaxThreads = 1- def __init__(self):+ def __init__(self) -> None:# Holds the thread object when module threading is enabledself.thread = None# logging overrides@@ -148,7 +148,7 @@ class SpiderFootPlugin():logging.setLoggerClass(logging.Logger) # reset logger class to defaultreturn self._log- def _updateSocket(self, socksProxy):+ def _updateSocket(self, socksProxy: str) -> None:"""Hack to override module's use of socket, replacing it withone that uses the supplied SOCKS server.@@ -157,14 +157,14 @@ class SpiderFootPlugin():"""self.socksProxy = socksProxy- def clearListeners(self):+ def clearListeners(self) -> None:"""Used to clear any listener relationships, etc. This is needed becausePython seems to cache local variables even between threads."""self._listenerModules = list()self._stopScanning = False- def setup(self, sf, userOpts={}):+ def setup(self, sf, userOpts: dict = {}) -> None:"""Will always be overriden by the implementer.Args:@@ -173,7 +173,7 @@ class SpiderFootPlugin():"""pass- def debug(self, *args, **kwargs):+ def debug(self, *args, **kwargs) -> None:"""For logging.A wrapper around logging.debug() that adds the scanId to LogRecord@@ -183,7 +183,7 @@ class SpiderFootPlugin():"""self.log.debug(*args, extra={'scanId': self.__scanId__}, **kwargs)- def info(self, *args, **kwargs):+ def info(self, *args, **kwargs) -> None:"""For logging.A wrapper around logging.info() that adds the scanId to LogRecord@@ -193,7 +193,7 @@ class SpiderFootPlugin():"""self.log.info(*args, extra={'scanId': self.__scanId__}, **kwargs)- def error(self, *args, **kwargs):+ def error(self, *args, **kwargs) -> None:"""For logging.A wrapper around logging.error() that adds the scanId to LogRecord@@ -203,7 +203,7 @@ class SpiderFootPlugin():"""self.log.error(*args, extra={'scanId': self.__scanId__}, **kwargs)- def enrichTarget(self, target):+ def enrichTarget(self, target: str) -> None:"""Find aliases for a target.Note: rarely used in special cases@@ -213,7 +213,7 @@ class SpiderFootPlugin():"""pass- def setTarget(self, target):+ def setTarget(self, target) -> None:"""Assigns the current target this module is acting against.Args:@@ -229,7 +229,7 @@ class SpiderFootPlugin():self._currentTarget = target- def setDbh(self, dbh):+ def setDbh(self, dbh) -> None:"""Used to set the database handle, which is only to be usedby modules in very rare/exceptional cases (e.g. sfp__stor_db)@@ -238,7 +238,7 @@ class SpiderFootPlugin():"""self.__sfdb__ = dbh- def setScanId(self, scanId):+ def setScanId(self, scanId: str) -> None:"""Set the scan ID.Args:@@ -252,7 +252,7 @@ class SpiderFootPlugin():self.__scanId__ = scanId- def getScanId(self):+ def getScanId(self) -> str:"""Get the scan ID.Returns:@@ -266,7 +266,7 @@ class SpiderFootPlugin():return self.__scanId__- def getTarget(self):+ def getTarget(self) -> str:"""Gets the current target this module is acting against.Returns:@@ -280,7 +280,7 @@ class SpiderFootPlugin():return self._currentTarget- def registerListener(self, listener):+ def registerListener(self, listener) -> None:"""Listener modules which will get notified once we have data for them towork with.@@ -290,10 +290,10 @@ class SpiderFootPlugin():self._listenerModules.append(listener)- def setOutputFilter(self, types):+ def setOutputFilter(self, types) -> None:self.__outputFilter__ = types- def tempStorage(self):+ def tempStorage(self) -> dict:"""For future use. Module temporary storage.A dictionary used to persist state (in memory) for a module.@@ -309,7 +309,7 @@ class SpiderFootPlugin():"""return dict()- def notifyListeners(self, sfEvent):+ def notifyListeners(self, sfEvent) -> None:"""Call the handleEvent() method of every other plug-in listening forevents from this plug-in. Remember that those plug-ins will be calledwithin the same execution context of this thread, not on their own.@@ -399,11 +399,11 @@ class SpiderFootPlugin():while 1:self.incomingEventQueue.get_nowait()- def checkForStop(self):+ def checkForStop(self) -> bool:"""For modules to use to check for when they should give back control.Returns:- bool+ bool: True if scan should stop"""# Stop if module is in error state.if self.errorState:@@ -429,16 +429,16 @@ class SpiderFootPlugin():return False@property- def running(self):+ def running(self) -> bool:"""Indicates whether the module is currently processing data.Modules that process data in pools/batches typically override this method.Returns:- bool+ bool: True if the module is currently processing data."""return self.sharedThreadPool.countQueuedTasks(f"{self.__name__}_threadWorker") > 0- def watchedEvents(self):+ def watchedEvents(self) -> list:"""What events is this module interested in for input. The format is a listof event types that are applied to event types that this module wants tobe notified of, or * if it wants everything.@@ -451,7 +451,7 @@ class SpiderFootPlugin():return ['*']- def producedEvents(self):+ def producedEvents(self) -> list:"""What events this module producesThis is to support the end user in selecting modules based on eventsproduced.@@ -462,7 +462,7 @@ class SpiderFootPlugin():return []- def handleEvent(self, sfEvent):+ def handleEvent(self, sfEvent) -> None:"""Handle events to this module.Will usually be overriden by the implementer, unless it doesn't handle any events.@@ -472,7 +472,7 @@ class SpiderFootPlugin():return- def asdict(self):+ def asdict(self) -> dict:return {'name': self.meta.get('name'),'descr': self.meta.get('summary'),@@ -486,7 +486,7 @@ class SpiderFootPlugin():'optdescs': self.optdescs,}- def start(self):+ def start(self) -> None:self.thread = threading.Thread(target=self.threadWorker)self.thread.start()@@ -498,7 +498,7 @@ class SpiderFootPlugin():return- def threadWorker(self):+ def threadWorker(self) -> None:try:# create new database handle since we're in our own threadfrom spiderfoot import SpiderFootDb@@ -541,7 +541,7 @@ class SpiderFootPlugin():# if there are leftover objects in the queue, the scan will hang.self.incomingEventQueue = None- def poolExecute(self, callback, *args, **kwargs):+ def poolExecute(self, callback, *args, **kwargs) -> None:"""Execute a callback with the given args.If we're in a storage module, execute normally.Otherwise, use the shared thread pool.@@ -559,7 +559,7 @@ class SpiderFootPlugin():def threadPool(self, *args, **kwargs):return SpiderFootThreadPool(*args, **kwargs)- def setSharedThreadPool(self, sharedThreadPool):+ def setSharedThreadPool(self, sharedThreadPool) -> None:self.sharedThreadPool = sharedThreadPool# end of SpiderFootPlugin classdiff --git a/spiderfoot/threadpool.py b/spiderfoot/threadpool.pyindex deb17d26..c5204042 100644--- a/spiderfoot/threadpool.py+++ b/spiderfoot/threadpool.py@@ -31,17 +31,14 @@ class SpiderFootThreadPool:yield result"""- def __init__(self, threads=100, qsize=10, name=None):+ def __init__(self, threads: int = 100, qsize: int = 10, name: str = '') -> None:"""Initialize the SpiderFootThreadPool class.Args:- threads: Max number of threads- qsize: Queue size- name: Name+ threads (int): Max number of threads+ qsize (int): Queue size+ name (str): Name"""- if name is None:- name = ""-self.log = logging.getLogger(f"spiderfoot.{__name__}")self.threads = int(threads)self.qsize = int(qsize)@@ -53,7 +50,7 @@ class SpiderFootThreadPool:self._stop = Falseself._lock = threading.Lock()- def start(self):+ def start(self) -> None:self.log.debug(f'Starting thread pool "{self.name}" with {self.threads:,} threads')for i in range(self.threads):t = ThreadPoolWorker(pool=self, name=f"{self.name}_worker_{i + 1}")@@ -61,18 +58,18 @@ class SpiderFootThreadPool:self.pool[i] = t@property- def stop(self):+ def stop(self) -> bool:return self._stop@stop.setter- def stop(self, val):+ def stop(self, val: bool):assert val in (True, False), "stop must be either True or False"for t in self.pool:with suppress(Exception):t.stop = valself._stop = val- def shutdown(self, wait=True):+ def shutdown(self, wait: bool = True) -> dict:"""Shut down the pool.Args:@@ -117,7 +114,7 @@ class SpiderFootThreadPool:q.close()return results- def submit(self, callback, *args, **kwargs):+ def submit(self, callback, *args, **kwargs) -> None:"""Submit a function call to the pool.The "taskName" and "maxThreads" arguments are optional.@@ -135,7 +132,7 @@ class SpiderFootThreadPool:self.log.debug(f"Submitting function \"{callback.__name__}\" from module \"{taskName}\" to thread pool \"{self.name}\"")self.inputQueue(taskName).put((callback, args, kwargs))- def countQueuedTasks(self, taskName):+ def countQueuedTasks(self, taskName: str) -> int:"""For the specified task, returns the number of queued function callsplus the number of functions which are currently executing@@ -143,7 +140,7 @@ class SpiderFootThreadPool:taskName (str): Name of taskReturns:- the number of queued function calls plus the number of functions which are currently executing+ int: the number of queued function calls plus the number of functions which are currently executing"""queuedTasks = 0with suppress(Exception):@@ -155,25 +152,26 @@ class SpiderFootThreadPool:runningTasks += 1return queuedTasks + runningTasks- def inputQueue(self, taskName="default"):+ def inputQueue(self, taskName: str = "default") -> str:try:return self.inputQueues[taskName]except KeyError:self.inputQueues[taskName] = queue.Queue(self.qsize)return self.inputQueues[taskName]- def outputQueue(self, taskName="default"):+ def outputQueue(self, taskName: str = "default") -> str:try:return self.outputQueues[taskName]except KeyError:self.outputQueues[taskName] = queue.Queue(self.qsize)return self.outputQueues[taskName]- def map(self, callback, iterable, *args, **kwargs): # noqa: A003- """+ def map(self, callback, iterable, *args, **kwargs) -> None: # noqa: A003+ """map.+Args:- iterable: each entry will be passed as the first argument to the functioncallback: the function to thread+ iterable: each entry will be passed as the first argument to the functionargs: additional arguments to pass to callback functionkwargs: keyword arguments to pass to callback function@@ -187,7 +185,7 @@ class SpiderFootThreadPool:sleep(.1)yield from self.results(taskName, wait=True)- def results(self, taskName="default", wait=False):+ def results(self, taskName: str = "default", wait: bool = False) -> None:while 1:result = Falsewith suppress(Exception):@@ -200,7 +198,7 @@ class SpiderFootThreadPool:# sleep briefly to save CPUsleep(.1)- def feedQueue(self, callback, iterable, args, kwargs):+ def feedQueue(self, callback, iterable, args, kwargs) -> None:for i in iterable:if self.stop:break@@ -210,14 +208,15 @@ class SpiderFootThreadPool:def finished(self):if self.stop:return True- else:- finishedThreads = [not t.busy for t in self.pool if t is not None]- try:- inputThreadAlive = self.inputThread.is_alive()- except AttributeError:- inputThreadAlive = False- inputQueuesEmpty = [q.empty() for q in self.inputQueues.values()]- return not inputThreadAlive and all(inputQueuesEmpty) and all(finishedThreads)++ finishedThreads = [not t.busy for t in self.pool if t is not None]+ try:+ inputThreadAlive = self.inputThread.is_alive()+ except AttributeError:+ inputThreadAlive = False++ inputQueuesEmpty = [q.empty() for q in self.inputQueues.values()]+ return not inputThreadAlive and all(inputQueuesEmpty) and all(finishedThreads)def __enter__(self):return self@@ -228,7 +227,7 @@ class SpiderFootThreadPool:class ThreadPoolWorker(threading.Thread):- def __init__(self, pool, name=None):+ def __init__(self, pool, name: str = None) -> None:self.log = logging.getLogger(f"spiderfoot.{__name__}")self.pool = pool@@ -238,7 +237,7 @@ class ThreadPoolWorker(threading.Thread):super().__init__(name=name)- def run(self):+ def run(self) -> None:# Round-robin through each module's input queuewhile not self.stop:ran = Falsediff --git a/test/unit/spiderfoot/test_spiderfootdb.py b/test/unit/spiderfoot/test_spiderfootdb.pyindex 8de9c73e..db3949a0 100644--- a/test/unit/spiderfoot/test_spiderfootdb.py+++ b/test/unit/spiderfoot/test_spiderfootdb.py@@ -491,7 +491,7 @@ class TestSpiderFootDb(unittest.TestCase):"""sfdb = SpiderFootDb(self.default_options, False)instance_id = "example instance id"- scan_instance = sfdb.scanErrors(instance_id, None)+ scan_instance = sfdb.scanErrors(instance_id)self.assertIsInstance(scan_instance, list)def test_scanErrors_argument_instanceId_of_invalid_type_should_raise_TypeError(self):@@ -500,12 +500,11 @@ class TestSpiderFootDb(unittest.TestCase):"""sfdb = SpiderFootDb(self.default_options, False)- limit = Noneinvalid_types = [None, list(), dict(), int()]for invalid_type in invalid_types:with self.subTest(invalid_type=invalid_type):with self.assertRaises(TypeError):- sfdb.scanErrors(invalid_type, limit)+ sfdb.scanErrors(invalid_type)def test_scanInstanceDelete(self):"""