SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.
Python attacksurfacecticybersecurityfootprintinghackinginformation-gatheringinformation-securityinfosecintelligence-gatheringosintosint-frameworkosint-reconnaissanceosint-toolpentestingpythonreconsecurity-toolsthreat-intelligencethreatintel
sfp_mnemonic: code cleanup
Brendan Colesbfd2e50474d4
diff --git a/modules/sfp_mnemonic.py b/modules/sfp_mnemonic.pyindex a3d230a7..50ab6784 100644--- a/modules/sfp_mnemonic.py+++ b/modules/sfp_mnemonic.py@@ -33,7 +33,8 @@ class sfp_mnemonic(SpiderFootPlugin):'model': "FREE_NOAUTH_UNLIMITED",'references': ["https://www.mnemonic.no/resources/whitepapers/",- "https://www.mnemonic.no/research-and-development/"+ "https://www.mnemonic.no/research-and-development/",+ "https://docs.mnemonic.no/display/public/API/PassiveDNS+Integration+Guide"],'favIcon': "https://www.mnemonic.no/favicon-96x96.png",'logo': "https://www.mnemonic.no/UI/logo.svg",@@ -46,7 +47,6 @@ class sfp_mnemonic(SpiderFootPlugin):}}- # Default optionsopts = {'per_page': 500,'max_pages': 2,@@ -57,13 +57,12 @@ class sfp_mnemonic(SpiderFootPlugin):'maxcohost': 100}- # Option descriptionsoptdescs = {'per_page': "Maximum number of results per page.",'max_pages': "Maximum number of pages of results to fetch.",'timeout': "Query timeout, in seconds.",'maxage': "The maximum age of the data returned, in days, in order to be considered valid.",- 'verify': "Verify co-hosts are valid by checking if they still resolve to the shared IP.",+ 'verify': "Verify identified domains still resolve to the associated specified IP address.",'cohostsamedomain': "Treat co-hosted sites on the same target domain as co-hosting?",'maxcohost': "Stop reporting co-hosted sites after this many are found, as it would likely indicate web hosting.",}@@ -81,25 +80,45 @@ class sfp_mnemonic(SpiderFootPlugin):for opt in list(userOpts.keys()):self.opts[opt] = userOpts[opt]- # What events is this module interested in for inputdef watchedEvents(self):- return ['IP_ADDRESS', 'IPV6_ADDRESS', 'INTERNET_NAME', 'DOMAIN_NAME']+ return [+ 'IP_ADDRESS',+ 'IPV6_ADDRESS',+ 'INTERNET_NAME',+ 'DOMAIN_NAME'+ ]- # What events this module producesdef producedEvents(self):- return ['IP_ADDRESS', 'IPV6_ADDRESS', 'CO_HOSTED_SITE',- 'INTERNET_NAME', 'DOMAIN_NAME']+ return [+ 'IP_ADDRESS',+ 'IPV6_ADDRESS',+ 'CO_HOSTED_SITE',+ 'INTERNET_NAME',+ 'DOMAIN_NAME'+ ]- # Query the Mnemonic PassiveDNS v3 API- # https://docs.mnemonic.no/display/public/API/PassiveDNS+Integration+Guidedef query(self, qry, limit=500, offset=0):- params = {- 'limit': str(limit),- 'offset': str(offset)- }+ """Query the Mnemonic PassiveDNS v3 API.++ Args:+ qry (str): domain name or IP address+ limit (int): Limit the number of returned values.+ offset (int): Skip the initial <offset> number of values in the resultset.++ Returns:+ dict: results as JSON+ """- url = 'https://api.mnemonic.no/pdns/v3/' + qry + '?' + urllib.parse.urlencode(params)- res = self.sf.fetchUrl(url, timeout=self.opts['timeout'], useragent=self.opts['_useragent'])+ params = urllib.parse.urlencode({+ 'limit': limit,+ 'offset': offset+ })++ res = self.sf.fetchUrl(+ f"https://api.mnemonic.no/pdns/v3/{qry}?{params}",+ timeout=self.opts['timeout'],+ useragent=self.opts['_useragent']+ )# Unauthenticated users are limited to 100 requests per minute, and 1000 requests per day.time.sleep(0.75)@@ -108,59 +127,53 @@ class sfp_mnemonic(SpiderFootPlugin):self.sf.info("No results found for " + qry)return None- # Parse response content as JSONtry:data = json.loads(res['content'])except Exception as e:- self.sf.debug(f"Error processing JSON response: {e}")+ self.sf.debug(f"Error processing JSON response from Mnemonic: {e}")return None- # Check the response is ok- if data['responseCode'] == 402:- self.sf.debug("Error retrieving search results: Resource limit exceeded")- self.errorState = True- return None+ response_code = data.get('responseCode')- if not data['responseCode'] == 200:+ if not response_code:self.sf.debug("Error retrieving search results.")return None- if 'data' not in data:- self.sf.info("No results found for " + qry)+ if response_code == 402:+ self.sf.debug("Error retrieving search results: Resource limit exceeded")+ self.errorState = Truereturn None- if 'count' not in data:- self.sf.info("No results found for " + qry)+ if response_code != 200:+ self.sf.debug(f"Error retrieving search results: {response_code}")return None- if 'size' not in data:- self.sf.info("No results found for " + qry)+ if 'data' not in data:+ self.sf.info(f"No results found for {qry}")return None- # Check if there were any results- size = data['size']- count = data['count']+ size = data.get('size')+ count = data.get('count')if not count or not size:- self.sf.info("No results found for " + qry)+ self.sf.info(f"No results found for {qry}")return None- self.sf.info("Retrieved " + str(size) + " of " + str(count) + " results")+ self.sf.info(f"Retrieved {size} of {count} results")return data['data']- # Handle events sent to this moduledef handleEvent(self, event):eventName = event.eventTypesrcModuleName = event.moduleeventData = event.dataif self.errorState:- return None+ returnif eventData in self.results:self.sf.debug(f"Skipping {eventData}, already checked.")- return None+ returnself.results[eventData] = True@@ -183,7 +196,7 @@ class sfp_mnemonic(SpiderFootPlugin):data = self.query(eventData, limit=per_page, offset=position)if data is None:- self.sf.info("No passive DNS data found for " + eventData)+ self.sf.info(f"No passive DNS data found for {eventData}")breakposition += per_page@@ -193,58 +206,76 @@ class sfp_mnemonic(SpiderFootPlugin):continueif r['lastSeenTimestamp'] < agelimit:- self.sf.debug("Record found too old, skipping.")+ self.sf.debug(f"Record {r['answer']} found for {r['query']} is too old, skipping.")continueif eventName in ['IP_ADDRESS']:if r['rrtype'] == 'a':- cohosts.append(r['query'])+ if self.sf.validIP(r['query']):+ cohosts.append(r['query'])+ continueif eventName in ['INTERNET_NAME', 'DOMAIN_NAME']:-# Ignore PTR recordsif r['rrtype'] == 'ptr':continue- if r['rrtype'] == 'a':- if self.sf.validIP(r['answer']):- evt = SpiderFootEvent("IP_ADDRESS", r['answer'], self.__name__, event)- self.notifyListeners(evt)-- if r['rrtype'] == 'aaaa':- if self.sf.validIP6(r['answer']):- evt = SpiderFootEvent("IPV6_ADDRESS", r['answer'], self.__name__, event)- self.notifyListeners(evt)-if r['rrtype'] == 'cname':if not self.getTarget().matches(r['query'], includeParents=True):continuecohosts.append(r['query'])+ if self.opts['verify']:+ continue++ answer = r.get('answer')++ if r['rrtype'] == 'a':+ if not self.sf.validIP(answer):+ continue++ evt = SpiderFootEvent("IP_ADDRESS", answer, self.__name__, event)+ self.notifyListeners(evt)++ if r['rrtype'] == 'aaaa':+ if not self.sf.validIP6(r['answer']):+ continue++ evt = SpiderFootEvent("IPV6_ADDRESS", answer, self.__name__, event)+ self.notifyListeners(evt)+for co in set(cohosts):if self.checkForStop():- return None+ returnif co in self.results:continue- if eventName == "IP_ADDRESS" and (self.opts['verify'] and not self.sf.validateIP(co, eventData)):- self.sf.debug("Host " + co + " no longer resolves to " + eventData)+ if eventName == "IP_ADDRESS":+ if self.opts['verify'] and not self.sf.validateIP(co, eventData):+ self.sf.debug(f"Host {co} no longer resolves to {eventData}")+ continue++ if self.opts['cohostsamedomain']:+ if self.cohostcount < self.opts['maxcohost']:+ evt = SpiderFootEvent("CO_HOSTED_SITE", co, self.__name__, event)+ self.notifyListeners(evt)+ self.cohostcount += 1continue- if not self.opts['cohostsamedomain']:- if self.getTarget().matches(co, includeParents=True):- evt = SpiderFootEvent("INTERNET_NAME", co, self.__name__, event)+ if self.getTarget().matches(co, includeParents=True):+ if self.opts['verify'] and not self.sf.resolveHost(co):+ self.sf.debug(f"Host {co} could not be resolved")+ evt = SpiderFootEvent("INTERNET_NAME_UNRESOLVED", co, self.__name__, event)self.notifyListeners(evt)- if self.sf.isDomain(co, self.opts['_internettlds']):- evt = SpiderFootEvent("DOMAIN_NAME", co, self.__name__, event)- self.notifyListeners(evt)continue- if self.cohostcount < self.opts['maxcohost']:- evt = SpiderFootEvent("CO_HOSTED_SITE", co, self.__name__, event)+ evt = SpiderFootEvent("INTERNET_NAME", co, self.__name__, event)self.notifyListeners(evt)- self.cohostcount += 1++ if self.sf.isDomain(co, self.opts['_internettlds']):+ evt = SpiderFootEvent("DOMAIN_NAME", co, self.__name__, event)+ self.notifyListeners(evt)# End of sfp_mnemonic class