SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.
Python attacksurfacecticybersecurityfootprintinghackinginformation-gatheringinformation-securityinfosecintelligence-gatheringosintosint-frameworkosint-reconnaissanceosint-toolpentestingpythonreconsecurity-toolsthreat-intelligencethreatintel
sfp_xforce: Support IPv6; Report blocked hosts as blacklisted (#1576)
bcoles734c471a2080
diff --git a/modules/sfp_xforce.py b/modules/sfp_xforce.pyindex 86491da6..03c87267 100644--- a/modules/sfp_xforce.py+++ b/modules/sfp_xforce.py@@ -1,7 +1,7 @@# -*- coding: utf-8 -*-# --------------------------------------------------------------------------------# Name: sfp_xforce-# Purpose: Query XForce Exchange+# Name: sfp_xforce+# Purpose: Obtain IP reputation and passive DNS information from IBM X-Force Exchange.## Author: Koen Van Impe#@@ -25,7 +25,7 @@ class sfp_xforce(SpiderFootPlugin):meta = {'name': "XForce Exchange",- 'summary': "Obtain IP reputation and passive DNS information from IBM X-Force Exchange",+ 'summary': "Obtain IP reputation and passive DNS information from IBM X-Force Exchange.",'flags': ["apikey"],'useCases': ["Investigate", "Passive"],'categories': ["Reputation Systems"],@@ -34,7 +34,7 @@ class sfp_xforce(SpiderFootPlugin):'model': "FREE_AUTH_LIMITED",'references': ["https://api.xforce.ibmcloud.com/doc/",- "https://exchange.xforce.ibmcloud.com/faq"+ "https://exchange.xforce.ibmcloud.com/faq",],'apiKeyInstructions': ["Visit https://exchange.xforce.ibmcloud.com",@@ -54,39 +54,38 @@ class sfp_xforce(SpiderFootPlugin):}}- # Default optionsopts = {"xforce_api_key": "","xforce_api_key_password": "","age_limit_days": 30,'netblocklookup': True,'maxnetblock': 24,+ 'maxv6netblock': 120,'subnetlookup': True,'maxsubnet': 24,+ 'maxv6subnet': 120,'maxcohost': 100,'cohostsamedomain': False,'checkaffiliates': True,'verify': True,}- # Option descriptionsoptdescs = {"xforce_api_key": "X-Force Exchange API Key.","xforce_api_key_password": "X-Force Exchange API Password.","age_limit_days": "Ignore any records older than this many days. 0 = unlimited.",'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible blacklisted hosts on the same target subdomain/domain?",'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",+ 'maxv6netblock': "If looking up owned netblocks, the maximum IPv6 netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",'subnetlookup': "Look up all IPs on subnets which your target is a part of for blacklisting?",'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",+ 'maxv6subnet': "If looking up subnets, the maximum IPv6 subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",'maxcohost': "Stop reporting co-hosted sites after this many are found, as it would likely indicate web hosting.","cohostsamedomain": "Treat co-hosted sites on the same target domain as co-hosting?",'checkaffiliates': "Apply checks to affiliates?",- 'verify': "Verify identified domains still resolve to the associated specified IP address.",+ 'verify': "Verify co-hosts are valid by checking if they still resolve to the shared IP.",}- # 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@@ -96,21 +95,37 @@ class sfp_xforce(SpiderFootPlugin):self.results = self.tempStorage()self.cohostcount = 0- # 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",- "NETBLOCK_OWNER", "NETBLOCK_MEMBER"]+ return [+ 'IP_ADDRESS',+ 'AFFILIATE_IPADDR',+ 'IPV6_ADDRESS',+ 'AFFILIATE_IPV6_ADDRESS',+ "NETBLOCK_MEMBER",+ "NETBLOCKV6_MEMBER",+ "NETBLOCK_OWNER",+ "NETBLOCKV6_OWNER",+ ]- # What events this module producesdef producedEvents(self):- return ["MALICIOUS_IPADDR", "CO_HOSTED_SITE",- "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_NETBLOCK"]+ return [+ "BLACKLISTED_IPADDR",+ "BLACKLISTED_AFFILIATE_IPADDR",+ "BLACKLISTED_SUBNET",+ "BLACKLISTED_NETBLOCK",+ "MALICIOUS_IPADDR",+ "MALICIOUS_AFFILIATE_IPADDR",+ "MALICIOUS_NETBLOCK",+ "MALICIOUS_SUBNET",+ "INTERNET_NAME",+ "INTERNET_NAME_UNRESOLVED",+ "DOMAIN_NAME",+ "CO_HOSTED_SITE",+ "RAW_RIR_DATA",+ ]def query(self, qry, querytype):if querytype not in ["ipr/malware", "ipr/history", "resolve"]:@@ -181,10 +196,8 @@ class sfp_xforce(SpiderFootPlugin):return None- # Handle events sent to this moduledef handleEvent(self, event):eventName = event.eventType- srcModuleName = event.moduleeventData = event.datainfield_sep = " ; "@@ -192,7 +205,7 @@ class sfp_xforce(SpiderFootPlugin):if self.errorState:return- self.debug(f"Received event, {eventName}, from {srcModuleName}")+ self.debug(f"Received event, {eventName}, from {event.module}")if self.opts['xforce_api_key'] == "" or self.opts['xforce_api_key_password'] == "":self.error("You enabled sfp_xforce but did not set an API key/password!")@@ -205,123 +218,108 @@ class sfp_xforce(SpiderFootPlugin):self.results[eventData] = True- if eventName == 'NETBLOCK_OWNER':- if not self.opts['netblocklookup']:+ if eventName in ['AFFILIATE_IPADDR', 'AFFILIATE_IPV6_ADDRESS']:+ if not self.opts.get('checkaffiliates', False):+ return+ malicious_type = "MALICIOUS_AFFILIATE_IPADDR"+ blacklist_type = "BLACKLISTED_AFFILIATE_IPADDR"+ elif eventName in ["IP_ADDRESS", "IPV6_ADDRESS"]:+ malicious_type = "MALICIOUS_IPADDR"+ blacklist_type = "BLACKLISTED_IPADDR"+ elif eventName == 'NETBLOCK_MEMBER':+ if not self.opts['subnetlookup']:return++ if eventName == 'NETBLOCKV6_MEMBER':+ max_subnet = self.opts['maxv6subnet']else:- if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:- self.debug("Network size bigger than permitted: "- + str(IPNetwork(eventData).prefixlen) + " > "- + str(self.opts['maxnetblock']))- return+ max_subnet = self.opts['maxsubnet']- if eventName == 'NETBLOCK_MEMBER':- if not self.opts['subnetlookup']:+ if IPNetwork(eventData).prefixlen < max_subnet:+ self.debug(f"Network size bigger than permitted: {IPNetwork(eventData).prefixlen} > {max_subnet}")return++ malicious_type = "MALICIOUS_SUBNET"+ blacklist_type = "BLACKLISTED_SUBNET"+ elif eventName == 'NETBLOCK_OWNER':+ if not self.opts['netblocklookup']:+ return++ if eventName == 'NETBLOCKV6_OWNER':+ max_netblock = self.opts['maxv6netblock']else:- if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:- self.debug("Network size bigger than permitted: "- + str(IPNetwork(eventData).prefixlen) + " > "- + str(self.opts['maxsubnet']))- return+ max_netblock = self.opts['maxnetblock']- if eventName.startswith('AFFILIATE_') and not self.opts.get('checkaffiliates', False):+ if IPNetwork(eventData).prefixlen < max_netblock:+ self.debug(f"Network size bigger than permitted: {IPNetwork(eventData).prefixlen} > {max_netblock}")+ return++ malicious_type = "MALICIOUS_NETBLOCK"+ blacklist_type = "BLACKLISTED_NETBLOCK"+ else:+ self.debug(f"Unexpected event type {eventName}, skipping")returnqrylist = list()- if eventName.startswith("NETBLOCK_"):+ if eventName.startswith("NETBLOCK"):for ipaddr in IPNetwork(eventData):qrylist.append(str(ipaddr))self.results[str(ipaddr)] = Trueelse:qrylist.append(eventData)- # For IP Addresses, do the additional passive DNS lookup- if eventName == "IP_ADDRESS":- if self.cohostcount > self.opts['maxcohost']:- return-- ret = self.query(eventData, "resolve")- if ret is None:- self.info("No Passive DNS info for " + eventData)- elif "Passive" in ret:- self.debug("Found passive DNS results in Xforce")- res = ret["Passive"]['records']- for rec in res:- if rec['recordType'] == "A":- last = rec.get("last", None)- if not last:- continue- last_dt = datetime.strptime(last, '%Y-%m-%dT%H:%M:%SZ')- last_ts = int(time.mktime(last_dt.timetuple()))- age_limit_ts = int(time.time()) - (86400 * self.opts['age_limit_days'])- host = rec['value']-- if self.opts['age_limit_days'] > 0 and last_ts < age_limit_ts:- self.debug("Record found but too old, skipping.")- continue-- if not self.opts["cohostsamedomain"]:- if self.getTarget().matches(host, includeParents=True):- self.debug(- f"Skipping {host} because it is on the same domain."- )- continue-- if self.opts['verify'] and not self.sf.resolveHost(host) and not self.sf.resolveHost6(host):- continue-- e = SpiderFootEvent("CO_HOSTED_SITE", host, self.__name__, event)- self.notifyListeners(e)- self.cohostcount += 1-for addr in qrylist:if self.checkForStop():return- if eventName == 'IP_ADDRESS' or eventName.startswith('NETBLOCK_'):- evtType = 'MALICIOUS_IPADDR'- if eventName == "AFFILIATE_IPADDR":- evtType = 'MALICIOUS_AFFILIATE_IPADDR'-rec = self.query(addr, "ipr/history")- if rec is not None:+ if rec:rec_history = rec.get("history", list())if len(rec_history) > 0:- self.debug("Found history results in XForce")+ self.debug(f"Found history results for {addr} in XForce")++ e = SpiderFootEvent("RAW_RIR_DATA", str(rec_history), self.__name__, event)+ self.notifyListeners(e)+for result in rec_history:created = result.get("created", None)# 2014-11-06T10:45:00.000Zif not created:continue+created_dt = datetime.strptime(created, '%Y-%m-%dT%H:%M:%S.000Z')created_ts = int(time.mktime(created_dt.timetuple()))age_limit_ts = int(time.time()) - (86400 * self.opts['age_limit_days'])if self.opts['age_limit_days'] > 0 and created_ts < age_limit_ts:- self.debug("Record found but too old, skipping.")+ self.debug(f"Record found but too old ({created_dt}), skipping.")continue+reason = result.get("reason", "")score = result.get("score", 0)- cats = result.get("cats", None)- cats_description = ""+ cats = result.get("cats", [])+ cats_description = " ".join(cats)+if int(score) < 2:- self.debug("Non-malicious results, skipping.")+ self.debug(f"Non-malicious results (score: {score} < 2), skipping.")continue- if cats is not None:- for cat in cats:- cats_description = cats_description + cat + " "+ entry = infield_sep.join([str(reason), str(score), str(created), cats_description])- # TODO: use join with infield_sep as delimeter- entry = f"{reason}{infield_sep}{score}{infield_sep}{created}{infield_sep}{cats_description}"- e = SpiderFootEvent(evtType, entry, self.__name__, event)+ text = f"{entry}\n<SFURL>https://exchange.xforce.ibmcloud.com/ip/{addr}</SFURL>"+ e = SpiderFootEvent(malicious_type, text, self.__name__, event)+ self.notifyListeners(e)+ e = SpiderFootEvent(blacklist_type, text, self.__name__, event)self.notifyListeners(e)rec = self.query(addr, "ipr/malware")- if rec is not None:+ if rec:rec_malware = rec.get("malware", list())if len(rec_malware) > 0:- self.debug("Found malware results in XForce")+ self.debug(f"Found malware results for {addr} in XForce")++ e = SpiderFootEvent("RAW_RIR_DATA", str(rec_malware), self.__name__, event)+ self.notifyListeners(e)+for result in rec_malware:origin = result.get("origin", "")domain = result.get("domain", "")@@ -329,15 +327,10 @@ class sfp_xforce(SpiderFootPlugin):md5 = result.get("md5", "")lastseen = result.get("last", "")firstseen = result.get("first", "")- family = result.get("family", None)- family_description = ""-- if family is not None:- for f in family:- family_description = family_description + f + " "+ family = result.get("family", [])+ family_description = " ".join(family)- # TODO: use join with infield_sep as delimeter- entry = f"{origin}{infield_sep}{family_description}{infield_sep}{md5}{infield_sep}{domain}{infield_sep}{uri}{infield_sep}{firstseen}{infield_sep}{lastseen}"+ entry = infield_sep.join([str(origin), family_description, str(md5), str(domain), str(uri), str(firstseen), str(lastseen)])last = rec.get("last", None)@@ -347,13 +340,83 @@ class sfp_xforce(SpiderFootPlugin):last_dt = datetime.strptime(last, '%Y-%m-%dT%H:%M:%S.000Z')last_ts = int(time.mktime(last_dt.timetuple()))age_limit_ts = int(time.time()) - (86400 * self.opts['age_limit_days'])- host = rec['value']if self.opts['age_limit_days'] > 0 and last_ts < age_limit_ts:- self.debug("Record found but too old, skipping.")+ self.debug(f"Record found but too old ({last_dt}), skipping.")continue- e = SpiderFootEvent(evtType, entry, self.__name__, event)+ text = f"{entry}\n<SFURL>https://exchange.xforce.ibmcloud.com/ip/{addr}</SFURL>"+ e = SpiderFootEvent(malicious_type, text, self.__name__, event)self.notifyListeners(e)+ e = SpiderFootEvent(blacklist_type, text, self.__name__, event)+ self.notifyListeners(e)++ # For IP addresses, do the additional passive DNS lookup+ # TODO: Add this to the loop above to support netblocks+ if eventName in ["IP_ADDRESS", "IPV6_ADDRESS"]:+ if self.cohostcount >= self.opts['maxcohost']:+ return++ ret = self.query(eventData, "resolve")+ if not ret:+ self.info(f"No Passive DNS info for {eventData}")+ return++ passive = ret.get('Passive')+ if not passive:+ return++ records = passive.get('records')+ if not records:+ return++ self.debug(f"Found passive DNS results for {eventData} in Xforce")++ e = SpiderFootEvent("RAW_RIR_DATA", str(records), self.__name__, event)+ self.notifyListeners(e)++ for rec in records:+ if self.checkForStop():+ return++ if rec['recordType'] == "A":+ last = rec.get("last", None)++ if not last:+ continue++ host = rec.get('value')+ if not host:+ continue++ last_dt = datetime.strptime(last, '%Y-%m-%dT%H:%M:%SZ')+ last_ts = int(time.mktime(last_dt.timetuple()))+ age_limit_ts = int(time.time()) - (86400 * self.opts['age_limit_days'])++ if self.opts['verify']:+ if not self.sf.validateIP(host, eventData):+ self.debug(f"Host {host} no longer resolves to {eventData}")+ continue+ else:+ if self.opts['age_limit_days'] > 0 and last_ts < age_limit_ts:+ self.debug(f"Record found but too old ({last_dt}), skipping.")+ continue++ if not self.opts["cohostsamedomain"]:+ if self.getTarget().matches(host, includeParents=True):+ if self.sf.resolveHost(host) or self.sf.resolveHost6(host):+ e = SpiderFootEvent("INTERNET_NAME", host, self.__name__, event)+ else:+ e = SpiderFootEvent("INTERNET_NAME_UNRESOLVED", host, self.__name__, event)+ self.notifyListeners(e)++ if self.sf.isDomain(host, self.opts['_internettlds']):+ e = SpiderFootEvent("DOMAIN_NAME", host, self.__name__, event)+ self.notifyListeners(e)+ continue++ e = SpiderFootEvent("CO_HOSTED_SITE", host, self.__name__, event)+ self.notifyListeners(e)+ self.cohostcount += 1# End of sfp_xforce class