SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.
Python attacksurfacecticybersecurityfootprintinghackinginformation-gatheringinformation-securityinfosecintelligence-gatheringosintosint-frameworkosint-reconnaissanceosint-toolpentestingpythonreconsecurity-toolsthreat-intelligencethreatintel
sfp_binaryedge: code cleanup
Brendan Colese9826a836989
diff --git a/modules/sfp_binaryedge.py b/modules/sfp_binaryedge.pyindex 5038df27..f7c77372 100644--- a/modules/sfp_binaryedge.py+++ b/modules/sfp_binaryedge.py@@ -22,7 +22,7 @@ class sfp_binaryedge(SpiderFootPlugin):meta = {'name': "BinaryEdge",- 'summary': "Obtain information from BinaryEdge.io's Internet scanning systems about breaches, vulerabilities, torrents and passive DNS.",+ 'summary': "Obtain information from BinaryEdge.io Internet scanning systems, including breaches, vulnerabilities, torrents and passive DNS.",'flags': ["apikey"],'useCases': ["Footprint", "Investigate", "Passive"],'categories': ["Search Engines"],@@ -50,7 +50,6 @@ class sfp_binaryedge(SpiderFootPlugin):}}- # Default optionsopts = {'binaryedge_api_key': "",'torrent_age_limit_days': 30,@@ -65,7 +64,6 @@ class sfp_binaryedge(SpiderFootPlugin):'maxcohost': 100}- # Option descriptionsoptdescs = {'binaryedge_api_key': "BinaryEdge.io API Key.",'torrent_age_limit_days': "Ignore any torrent records older than this many days. 0 = unlimited.",@@ -80,9 +78,6 @@ class sfp_binaryedge(SpiderFootPlugin):'maxcohost': "Stop reporting co-hosted sites after this many are found, as it would likely indicate web hosting."}- # Be sure to completely clear any class variables in setup()- # or you run the risk of data persisting between scan runs.-results = NoneerrorState = Falsecohostcount = 0@@ -97,23 +92,31 @@ class sfp_binaryedge(SpiderFootPlugin):self.cohostcount = 0self.errorState = False- # 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", "DOMAIN_NAME", "EMAILADDR",- "NETBLOCK_OWNER", "NETBLOCK_MEMBER"]+ return [+ "IP_ADDRESS",+ "DOMAIN_NAME",+ "EMAILADDR",+ "NETBLOCK_OWNER",+ "NETBLOCK_MEMBER"+ ]- # What events this module producesdef producedEvents(self):- return ["INTERNET_NAME", "VULNERABILITY", "TCP_PORT_OPEN",- "TCP_PORT_OPEN_BANNER", "EMAILADDR_COMPROMISED",- "UDP_PORT_OPEN", "UDP_PORT_OPEN_INFO", "DOMAIN_NAME",- "CO_HOSTED_SITE", "MALICIOUS_IPADDR"]+ return [+ "INTERNET_NAME",+ "DOMAIN_NAME",+ "VULNERABILITY",+ "TCP_PORT_OPEN",+ "TCP_PORT_OPEN_BANNER",+ "EMAILADDR_COMPROMISED",+ "UDP_PORT_OPEN",+ "UDP_PORT_OPEN_INFO",+ "CO_HOSTED_SITE",+ "MALICIOUS_IPADDR"+ ]def query(self, qry, querytype, page=1):retarr = list()@@ -122,37 +125,39 @@ class sfp_binaryedge(SpiderFootPlugin):return Noneif querytype == "email":- queryurl = "/v2/query/dataleaks/email/{0}?page={1}"- if querytype == "ports":- queryurl = "/v2/query/ip/{0}?page={1}"- if querytype == "torrent":- queryurl = "/v2/query/torrent/historical/{0}?page={1}"- if querytype == "vuln":- queryurl = "/v2/query/cve/ip/{0}?page={1}"- if querytype == "subs":- queryurl = "/v2/query/domains/subdomain/{0}?page={1}"- if querytype == "passive":- queryurl = "/v2/query/domains/ip/{0}?page={1}"-- binaryedgeurl = "https://api.binaryedge.io"+ queryurl = "dataleaks/email"+ elif querytype == "ip":+ queryurl = "ip"+ elif querytype == "torrent":+ queryurl = "torrent/historical"+ elif querytype == "vuln":+ queryurl = "cve/ip"+ elif querytype == "subs":+ queryurl = "domains/subdomain"+ elif querytype == "passive":+ queryurl = "domains/ip"+ else:+ self.sf.error(f"Invalid query type: {querytype}", False)+ return None+headers = {'X-Key': self.opts['binaryedge_api_key']}- url = binaryedgeurl + queryurl.format(qry, page)- res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],- useragent="SpiderFoot", headers=headers)++ res = self.sf.fetchUrl(+ f"https://api.binaryedge.io/v2/query/{queryurl}/{qry}?page={page}",+ timeout=self.opts['_fetchtimeout'],+ useragent="SpiderFoot",+ headers=headers+ )if res['code'] in ["429", "500"]:self.sf.error("BinaryEdge.io API key seems to have been rejected or you have exceeded usage limits for the month.", False)self.errorState = Truereturn None- if res['content'] is None:- self.sf.info("No BinaryEdge.io info found for " + qry)- return None-- if len(res['content']) == 0:- self.sf.info("No BinaryEdge.io info found for " + qry)+ if not res['content']:+ self.sf.info(f"No BinaryEdge.io info found for {qry}")return Nonetry:@@ -175,7 +180,6 @@ class sfp_binaryedge(SpiderFootPlugin):return retarr- # Handle events sent to this moduledef handleEvent(self, event):eventName = event.eventTypesrcModuleName = event.module@@ -186,45 +190,59 @@ class sfp_binaryedge(SpiderFootPlugin):self.sf.debug(f"Received event, {eventName}, from {srcModuleName}")- if self.opts['binaryedge_api_key'] == "":- self.sf.error("You enabled sfp_binaryedge but did not set an API key!", False)+ if self.opts["binaryedge_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] = True++ if eventName == "EMAILADDR":+ ret = self.query(eventData, "email")+ if ret is None:+ self.sf.info(f"No leak info for {eventData}")+ return None++ for rec in ret:+ events = rec.get('events')+ if not events:+ continue++ self.sf.debug("Found compromised account results in BinaryEdge.io")++ for leak in events:+ e = SpiderFootEvent('EMAILADDR_COMPROMISED', f"{eventData} [{leak}]", self.__name__, event)+ self.notifyListeners(e)++ # No further API endpoints available for email addresses. we can bail out here+ return Noneif 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 bigger than permitted: {net_size} > {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- qrylist = list()- if eventName.startswith("NETBLOCK_"):- for ipaddr in IPNetwork(eventData):- qrylist.append(str(ipaddr))- self.results[str(ipaddr)] = True- else:- qrylist.append(eventData)+ net_size = IPNetwork(eventData).prefixlen+ max_subnet = self.opts['maxsubnet']+ if net_size < max_subnet:+ self.sf.debug(f"Network size bigger than permitted: {net_size} > {max_subnet}")+ return None# For IP Addresses, do the additional passive DNS lookupif eventName == "IP_ADDRESS":@@ -244,10 +262,12 @@ class sfp_binaryedge(SpiderFootPlugin):host = rec['domain']if host == eventData:continue+if self.getTarget().matches(host, includeParents=True):if self.opts['verify']:if not self.sf.resolveHost(host):continue+evt = SpiderFootEvent("INTERNET_NAME", host, self.__name__, event)self.notifyListeners(evt)if self.sf.isDomain(host, self.opts['_internettlds']):@@ -262,27 +282,10 @@ class sfp_binaryedge(SpiderFootPlugin):self.notifyListeners(e)self.cohostcount += 1- if eventName == "EMAILADDR":- ret = self.query(eventData, "email")- if ret is None:- self.sf.info(f"No leak info for {eventData}")- return None-- for rec in ret:- events = rec.get('events')- if not events:- continue-- self.sf.debug("Found compromised account results in BinaryEdge.io")-- for leak in events:- e = SpiderFootEvent('EMAILADDR_COMPROMISED', f"{eventData} [{leak}]", self.__name__, event)- self.notifyListeners(e)-if eventName == "DOMAIN_NAME":ret = self.query(eventData, "subs")if ret is None:- self.sf.info("No hosts found for " + eventData)+ self.sf.info(f"No hosts found for {eventData}")return Nonefor rec in ret:@@ -305,24 +308,37 @@ class sfp_binaryedge(SpiderFootPlugin):e = SpiderFootEvent('INTERNET_NAME', rec, self.__name__, event)self.notifyListeners(e)+ # Loop through all IP addresses / host names+ qrylist = list()+ if eventName.startswith("NETBLOCK_"):+ for ipaddr in IPNetwork(eventData):+ qrylist.append(str(ipaddr))+ self.results[str(ipaddr)] = True+ else:+ qrylist.append(eventData)+for addr in qrylist:if self.checkForStop():return None+ if self.errorState:+ return None+if addr in self.checkedips:continue- ret = self.query(eventData, "torrent")+ ret = self.query(addr, "torrent")if ret is None:- self.sf.info(f"No torrent info for {eventData}")- return None+ self.sf.info(f"No torrent info for {addr}")+ continuefor rec in ret:events = rec.get('events')if not events:continue- self.sf.debug("Found torrent results in BinaryEdge.io")+ self.sf.debug(f"Found torrent results for {addr} in BinaryEdge.io")+for rec in events:created_ts = rec['origin'].get('ts') / 1000age_limit_ts = int(time.time()) - (86400 * self.opts['torrent_age_limit_days'])@@ -339,13 +355,16 @@ class sfp_binaryedge(SpiderFootPlugin):if self.checkForStop():return None+ if self.errorState:+ return None+if addr in self.checkedips:continue- ret = self.query(eventData, "vuln")+ ret = self.query(addr, "vuln")if ret is None:- self.sf.info(f"No vulnerability info for {eventData}")- return None+ self.sf.info(f"No vulnerability info for {addr}")+ continuefor rec in ret:events = rec.get('events')@@ -365,21 +384,26 @@ class sfp_binaryedge(SpiderFootPlugin):self.sf.debug("Record found but too old, skipping.")continue- for c in rec['cves']:- cve = c['cve']- e = SpiderFootEvent('VULNERABILITY', cve, self.__name__, event)- self.notifyListeners(e)+ cves = rec.get('cves')+ if cves:+ for c in cves:+ cve = c['cve']+ e = SpiderFootEvent('VULNERABILITY', cve, self.__name__, event)+ self.notifyListeners(e)for addr in qrylist:if self.checkForStop():return None+ if self.errorState:+ return None+if addr in self.checkedips:continue- ret = self.query(eventData, "ports")+ ret = self.query(addr, "ip")if ret is None:- self.sf.info(f"No port/banner info for {eventData}")+ self.sf.info(f"No port/banner info for {addr}")return Nonefor rec in ret:@@ -415,10 +439,12 @@ class sfp_binaryedge(SpiderFootPlugin):try:banner = prec['result']['data']['service']['banner']- e = SpiderFootEvent(evtbtype, banner, self.__name__, ev)- self.notifyListeners(e)except BaseException:self.sf.debug("No banner information found.")+ continue++ e = SpiderFootEvent(evtbtype, banner, self.__name__, ev)+ self.notifyListeners(e)for addr in qrylist:self.checkedips[addr] = True