SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.
Python attacksurfacecticybersecurityfootprintinghackinginformation-gatheringinformation-securityinfosecintelligence-gatheringosintosint-frameworkosint-reconnaissanceosint-toolpentestingpythonreconsecurity-toolsthreat-intelligencethreatintel
sfp_virustotal: code cleanup
Brendan Colesccc9a16b40fa
diff --git a/modules/sfp_virustotal.py b/modules/sfp_virustotal.pyindex 1a8d2260..3eb771c0 100644--- a/modules/sfp_virustotal.py+++ b/modules/sfp_virustotal.py@@ -12,6 +12,9 @@import jsonimport time+import urllib.error+import urllib.parse+import urllib.requestfrom netaddr import IPNetwork@@ -30,7 +33,7 @@ class sfp_virustotal(SpiderFootPlugin):'website': "https://www.virustotal.com/",'model': "FREE_AUTH_LIMITED",'references': [- "https://developers.virustotal.com/v3.0/reference"+ "https://developers.virustotal.com/reference"],'apiKeyInstructions': ["Visit https://www.virustotal.com/",@@ -46,7 +49,6 @@ class sfp_virustotal(SpiderFootPlugin):}}- # Default optionsopts = {'api_key': '','verify': True,@@ -59,7 +61,6 @@ class sfp_virustotal(SpiderFootPlugin):'maxsubnet': 24}- # Option descriptionsoptdescs = {'api_key': 'VirusTotal API Key.','publicapi': 'Are you using a public key? If so SpiderFoot will pause for 15 seconds after each query to avoid VirusTotal dropping requests.',@@ -72,9 +73,6 @@ class sfp_virustotal(SpiderFootPlugin):'verify': 'Verify that any hostnames found on the target domain still resolve?'}- # Be sure to completely clear any class variables in setup()- # or you run the risk of data persisting between scan runs.-results = NoneerrorState = False@@ -82,55 +80,92 @@ class sfp_virustotal(SpiderFootPlugin):self.sf = sfcself.results = self.tempStorage()- # Clear / reset any other class member variables here- # or you risk them persisting between threads.-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", "AFFILIATE_IPADDR", "INTERNET_NAME",- "CO_HOSTED_SITE", "NETBLOCK_OWNER",- "NETBLOCK_MEMBER"]+ return [+ "IP_ADDRESS",+ "AFFILIATE_IPADDR",+ "INTERNET_NAME",+ "CO_HOSTED_SITE",+ "NETBLOCK_OWNER",+ "NETBLOCK_MEMBER"+ ]- # What events this module producesdef producedEvents(self):- return ["MALICIOUS_IPADDR", "MALICIOUS_INTERNET_NAME",- "MALICIOUS_COHOST", "MALICIOUS_AFFILIATE_INTERNET_NAME",- "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_NETBLOCK",- "MALICIOUS_SUBNET", "INTERNET_NAME", "AFFILIATE_INTERNET_NAME",- "INTERNET_NAME_UNRESOLVED", 'DOMAIN_NAME']+ return [+ "MALICIOUS_IPADDR",+ "MALICIOUS_INTERNET_NAME",+ "MALICIOUS_COHOST",+ "MALICIOUS_AFFILIATE_INTERNET_NAME",+ "MALICIOUS_AFFILIATE_IPADDR",+ "MALICIOUS_NETBLOCK",+ "MALICIOUS_SUBNET",+ "INTERNET_NAME",+ "AFFILIATE_INTERNET_NAME",+ "INTERNET_NAME_UNRESOLVED",+ "DOMAIN_NAME"+ ]++ def queryIp(self, qry):+ params = urllib.parse.urlencode({+ 'ip': qry,+ 'apikey': self.opts['api_key'],+ })++ res = self.sf.fetchUrl(+ f"https://www.virustotal.com/vtapi/v2/ip-address/report?{params}",+ timeout=self.opts['_fetchtimeout'],+ useragent="SpiderFoot"+ )- def query(self, qry):- ret = None+ # Public API is limited to 4 queries per minute+ if self.opts['publicapi']:+ time.sleep(15)- if self.sf.validIP(qry):- url = "https://www.virustotal.com/vtapi/v2/ip-address/report?ip=" + qry- else:- url = "https://www.virustotal.com/vtapi/v2/domain/report?domain=" + qry+ if res['content'] is None:+ self.sf.info(f"No VirusTotal info found for {qry}")+ return None++ try:+ data = json.loads(res['content'])+ except Exception as e:+ self.sf.error(f"Error processing JSON response from VirusTotal: {e}", False)+ self.errorState = True+ return None++ return data++ def queryDomain(self, qry):+ params = urllib.parse.urlencode({+ 'domain': qry,+ 'apikey': self.opts['api_key'],+ })- res = self.sf.fetchUrl(url + "&apikey=" + self.opts['api_key'],- timeout=self.opts['_fetchtimeout'], useragent="SpiderFoot")+ res = self.sf.fetchUrl(+ f"https://www.virustotal.com/vtapi/v2/domain/report?{params}",+ timeout=self.opts['_fetchtimeout'],+ useragent="SpiderFoot"+ )# Public API is limited to 4 queries per minuteif self.opts['publicapi']:time.sleep(15)if res['content'] is None:- self.sf.info("No VirusTotal info found for " + qry)+ self.sf.info(f"No VirusTotal info found for {qry}")return Nonetry:- ret = json.loads(res['content'])+ data = json.loads(res['content'])except Exception as e:self.sf.error(f"Error processing JSON response from VirusTotal: {e}", False)self.errorState = Truereturn None- return ret+ return data- # Handle events sent to this moduledef handleEvent(self, event):eventName = event.eventTypesrcModuleName = event.module@@ -141,17 +176,19 @@ class sfp_virustotal(SpiderFootPlugin):self.sf.debug(f"Received event, {eventName}, from {srcModuleName}")- if self.opts['api_key'] == "":- self.sf.error("You enabled sfp_virustotal but did not set an API key!", False)+ if self.opts["api_key"] == "":+ self.sf.error(+ f"You enabled {self.__class__.__name__} but did not set an API key!",+ False,+ )self.errorState = Truereturn None- # Don't look up stuff twiceif eventData in self.results:self.sf.debug(f"Skipping {eventData}, already checked.")return None- else:- self.results[eventData] = True++ self.results[eventData] = Trueif eventName.startswith("AFFILIATE") and not self.opts['checkaffiliates']:return None@@ -162,22 +199,22 @@ class sfp_virustotal(SpiderFootPlugin):if eventName == 'NETBLOCK_OWNER':if not self.opts['netblocklookup']:return None- else:- if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:- self.sf.debug("Network size bigger than permitted: "- + str(IPNetwork(eventData).prefixlen) + " > "- + str(self.opts['maxnetblock']))- return None++ net_size = IPNetwork(eventData).prefixlen+ max_netblock = self.opts['maxnetblock']+ if net_size < max_netblock:+ self.sf.debug(f"Network size {net_size} bigger than permitted: {max_netblock}")+ return Noneif eventName == 'NETBLOCK_MEMBER':if not self.opts['subnetlookup']:return None- else:- if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:- self.sf.debug("Network size bigger than permitted: "- + str(IPNetwork(eventData).prefixlen) + " > "- + str(self.opts['maxsubnet']))- return None++ net_size = IPNetwork(eventData).prefixlen+ max_subnet = self.opts['maxsubnet']+ if net_size < max_subnet:+ self.sf.debug(f"Network size {net_size} bigger than permitted: {max_subnet}")+ return Noneqrylist = list()if eventName.startswith("NETBLOCK_"):@@ -191,11 +228,17 @@ class sfp_virustotal(SpiderFootPlugin):if self.checkForStop():return None- info = self.query(addr)+ if self.sf.validIP(addr):+ info = self.queryIp(addr)+ else:+ info = self.queryDomain(addr)+if info is None:continue+if len(info.get('detected_urls', [])) > 0:- self.sf.info("Found VirusTotal URL data for " + addr)+ self.sf.info(f"Found VirusTotal URL data for {addr}")+if eventName in ["IP_ADDRESS"] or eventName.startswith("NETBLOCK_"):evt = "MALICIOUS_IPADDR"infotype = "ip-address"@@ -216,49 +259,51 @@ class sfp_virustotal(SpiderFootPlugin):evt = "MALICIOUS_COHOST"infotype = "domain"- infourl = "<SFURL>https://www.virustotal.com/en/" + infotype + "/" + \- addr + "/information/</SFURL>"+ infourl = f"<SFURL>https://www.virustotal.com/en/{infotype}/{addr}/information/</SFURL>"- # Notify other modules of what you've found- e = SpiderFootEvent(evt, "VirusTotal [" + addr + "]\n" + infourl, self.__name__, event)+ e = SpiderFootEvent(+ evt, f"VirusTotal [{addr}]\n{infourl}",+ self.__name__,+ event+ )self.notifyListeners(e)+ domains = list()+# Treat siblings as affiliates if they are of the original target, otherwise# they are additional hosts within the target.if 'domain_siblings' in info:if eventName in ["IP_ADDRESS", "INTERNET_NAME"]:- for s in info['domain_siblings']:- if self.getTarget().matches(s):- if s not in self.results:- if self.opts['verify']:- if not self.sf.resolveHost(s):- e = SpiderFootEvent("INTERNET_NAME_UNRESOLVED", s, self.__name__, event)- self.notifyListeners(e)- else:- e = SpiderFootEvent("INTERNET_NAME", s, self.__name__, event)- self.notifyListeners(e)-- if self.sf.isDomain(s, self.opts['_internettlds']):- e = SpiderFootEvent("DOMAIN_NAME", s, self.__name__, event)- self.notifyListeners(e)- else:- if s not in self.results:- e = SpiderFootEvent("AFFILIATE_INTERNET_NAME", s, self.__name__, event)- self.notifyListeners(e)-- if 'subdomains' in info and eventName == "INTERNET_NAME":- for n in info['subdomains']:- if n not in self.results:- if self.opts['verify']:- if not self.sf.resolveHost(n):- e = SpiderFootEvent("INTERNET_NAME_UNRESOLVED", n, self.__name__, event)- self.notifyListeners(e)- else:- e = SpiderFootEvent("INTERNET_NAME", n, self.__name__, event)- self.notifyListeners(e)-- if self.sf.isDomain(n, self.opts['_internettlds']):- e = SpiderFootEvent("DOMAIN_NAME", n, self.__name__, event)- self.notifyListeners(e)+ for domain in info['domain_siblings']:+ domains.append(domain)++ if 'subdomains' in info:+ if eventName == "INTERNET_NAME":+ for domain in info['subdomains']:+ domains.append(domain)++ for domain in set(domains):+ if domain in self.results:+ continue++ if self.getTarget().matches(domain):+ evt_type = 'INTERNET_NAME'+ else:+ evt_type = 'AFFILIATE_INTERNET_NAME'++ if self.opts['verify'] and not self.sf.resolveHost(domain):+ self.sf.debug(f"Host {domain} could not be resolved")+ evt_type += '_UNRESOLVED'++ evt = SpiderFootEvent(evt_type, domain, self.__name__, event)+ self.notifyListeners(evt)++ if self.sf.isDomain(domain, self.opts['_internettlds']):+ if evt_type.startswith('AFFILIATE'):+ evt = SpiderFootEvent('AFFILIATE_DOMAIN_NAME', domain, self.__name__, event)+ self.notifyListeners(evt)+ else:+ evt = SpiderFootEvent('DOMAIN_NAME', domain, self.__name__, event)+ self.notifyListeners(evt)# End of sfp_virustotal class