SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.
Python attacksurfacecticybersecurityfootprintinghackinginformation-gatheringinformation-securityinfosecintelligence-gatheringosintosint-frameworkosint-reconnaissanceosint-toolpentestingpythonreconsecurity-toolsthreat-intelligencethreatintel
sfp_spamhaus: Report blocked hosts as malicious (#1522)
bcolese94bf5612d9e
diff --git a/modules/sfp_spamhaus.py b/modules/sfp_spamhaus.pyindex 3f5f3753..c889d83b 100644--- a/modules/sfp_spamhaus.py+++ b/modules/sfp_spamhaus.py@@ -20,8 +20,8 @@ from spiderfoot import SpiderFootEvent, SpiderFootPluginclass sfp_spamhaus(SpiderFootPlugin):meta = {- 'name': "Spamhaus",- 'summary': "Query the Spamhaus databases for open relays, open proxies, vulnerable servers, etc.",+ 'name': "Spamhaus Zen",+ 'summary': "Check if a netblock or IP address is in the Spamhaus Zen database.",'flags': [],'useCases': ["Investigate", "Passive"],'categories': ["Reputation Systems"],@@ -29,6 +29,7 @@ class sfp_spamhaus(SpiderFootPlugin):'website': "https://www.spamhaus.org/",'model': "FREE_NOAUTH_UNLIMITED",'references': [+ "https://www.spamhaus.org/zen/","https://www.spamhaus.org/organization/dnsblusage/","https://www.spamhaus.org/datafeed/","https://www.spamhaus.org/whitepapers/dnsbl_function/",@@ -40,11 +41,12 @@ class sfp_spamhaus(SpiderFootPlugin):"tracks spam and related cyber threats such as phishing, malware and botnets, ""provides realtime actionable and highly accurate threat intelligence to ""the Internet's major networks, corporations and security vendors, "- "and works with law enforcement agencies to identify and pursue spam and malware sources worldwide.",+ "and works with law enforcement agencies to identify and pursue spam and malware sources worldwide. "+ "ZEN is the combination of all Spamhaus IP-based DNSBLs into one single powerful and comprehensive "+ "blocklist to make querying faster and simpler. It contains the SBL, SBLCSS, XBL and PBL blocklists.",}}- # Default optionsopts = {'netblocklookup': True,'maxnetblock': 24,@@ -52,7 +54,6 @@ class sfp_spamhaus(SpiderFootPlugin):'maxsubnet': 24}- # Option descriptionsoptdescs = {'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.)",@@ -60,24 +61,17 @@ class sfp_spamhaus(SpiderFootPlugin):'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"}- # Targetresults = None- # Whole bunch here:- # http://en.wikipedia.org/wiki/Comparison_of_DNS_blacklists- # Check out:- # http://www.blocklist.de/en/rbldns.htmlchecks = {- 'zen.spamhaus.org': {- '127.0.0.2': "Spamhaus (Zen) - Spammer",- '127.0.0.3': "Spamhaus (Zen) - Spammer",- '127.0.0.4': "Spamhaus (Zen) - Proxies, Trojans, etc.",- '127.0.0.5': "Spamhaus (Zen) - Proxies, Trojans, etc.",- '127.0.0.6': "Spamhaus (Zen) - Proxies, Trojans, etc.",- '127.0.0.7': "Spamhaus (Zen) - Proxies, Trojans, etc.",- '127.0.0.10': "Spamhaus (Zen) - Potential Spammer",- '127.0.0.11': "Spamhaus (Zen) - Potential Spammer"- }+ '127.0.0.2': "Spamhaus (Zen) - Spammer",+ '127.0.0.3': "Spamhaus (Zen) - Spammer",+ '127.0.0.4': "Spamhaus (Zen) - Proxies, Trojans, etc.",+ '127.0.0.5': "Spamhaus (Zen) - Proxies, Trojans, etc.",+ '127.0.0.6': "Spamhaus (Zen) - Proxies, Trojans, etc.",+ '127.0.0.7': "Spamhaus (Zen) - Proxies, Trojans, etc.",+ '127.0.0.10': "Spamhaus (Zen) - Potential Spammer",+ '127.0.0.11': "Spamhaus (Zen) - Potential Spammer",}def setup(self, sfc, userOpts=dict()):@@ -88,76 +82,83 @@ class sfp_spamhaus(SpiderFootPlugin):self.opts[opt] = userOpts[opt]def watchedEvents(self):- return ['IP_ADDRESS', 'AFFILIATE_IPADDR', 'NETBLOCK_OWNER',- 'NETBLOCK_MEMBER']+ return [+ 'IP_ADDRESS',+ 'AFFILIATE_IPADDR',+ 'NETBLOCK_OWNER',+ 'NETBLOCK_MEMBER'+ ]def producedEvents(self):- return ["BLACKLISTED_IPADDR", "BLACKLISTED_AFFILIATE_IPADDR",- "BLACKLISTED_SUBNET", "BLACKLISTED_NETBLOCK"]+ return [+ "BLACKLISTED_IPADDR",+ "BLACKLISTED_AFFILIATE_IPADDR",+ "BLACKLISTED_SUBNET",+ "BLACKLISTED_NETBLOCK",+ "MALICIOUS_IPADDR",+ "MALICIOUS_AFFILIATE_IPADDR",+ "MALICIOUS_NETBLOCK",+ "MALICIOUS_SUBNET",+ ]# Swap 1.2.3.4 to 4.3.2.1def reverseAddr(self, ipaddr):+ if not self.sf.validIP(ipaddr):+ self.debug(f"Invalid IPv4 address {ipaddr}")+ return Nonereturn '.'.join(reversed(ipaddr.split('.')))- def queryAddr(self, qaddr, parentEvent):- eventName = parentEvent.eventType-- for domain in self.checks:- if self.checkForStop():- return-- try:- lookup = self.reverseAddr(qaddr) + "." + domain- self.debug("Checking Blacklist: " + lookup)- addrs = self.sf.resolveHost(lookup)- self.debug("Addresses returned: " + str(addrs))+ def queryAddr(self, qaddr):+ """Query Spamhaus Zen DNS for an IPv4 address.- if not addrs:- continue+ Args:+ qaddr (str): IPv4 address.- text = None- for addr in addrs:- if type(self.checks[domain]) is str:- text = self.checks[domain] + " (" + qaddr + ")"- break+ Returns:+ list: Spamhaus Zen DNS entries+ """+ if not self.sf.validIP(qaddr):+ self.debug(f"Invalid IPv4 address {qaddr}")+ return None- if str(addr) in list(self.checks[domain].keys()):- k = str(addr)- text = self.checks[domain][k] + " (" + qaddr + ")"- break+ try:+ lookup = self.reverseAddr(qaddr) + '.zen.spamhaus.org'+ self.debug(f"Checking Spamhaus Zen blacklist: {lookup}")+ return self.sf.resolveHost(lookup)+ except Exception as e:+ self.debug(f"Spamhaus Zen did not resolve {qaddr} / {lookup}: {e}")- self.debug(f"Return code not found in list: {addr}")-- if text is not None:- if eventName == "AFFILIATE_IPADDR":- e = "BLACKLISTED_AFFILIATE_IPADDR"- if eventName == "IP_ADDRESS":- e = "BLACKLISTED_IPADDR"- if eventName == "NETBLOCK_OWNER":- e = "BLACKLISTED_NETBLOCK"- if eventName == "NETBLOCK_MEMBER":- e = "BLACKLISTED_SUBNET"-- evt = SpiderFootEvent(e, text, self.__name__, parentEvent)- self.notifyListeners(evt)-- except Exception as e:- self.debug("Unable to resolve " + qaddr + " / " + lookup + ": " + str(e))+ return Nonedef handleEvent(self, event):eventName = event.eventType- srcModuleName = event.moduleeventData = event.data- parentEvent = event- self.debug(f"Received event, {eventName}, from {srcModuleName}")+ self.debug(f"Received event, {eventName}, from {event.module}")if eventData in self.results:returnself.results[eventData] = True- if eventName == 'NETBLOCK_OWNER':+ if eventName == "AFFILIATE_IPADDR":+ malicious_type = "MALICIOUS_AFFILIATE_IPADDR"+ blacklist_type = "BLACKLISTED_AFFILIATE_IPADDR"+ elif eventName == "IP_ADDRESS":+ malicious_type = "MALICIOUS_IPADDR"+ blacklist_type = "BLACKLISTED_IPADDR"+ elif eventName == 'NETBLOCK_MEMBER':+ if not self.opts['subnetlookup']:+ return++ max_subnet = self.opts['maxsubnet']+ 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@@ -166,21 +167,58 @@ class sfp_spamhaus(SpiderFootPlugin):self.debug(f"Network size bigger than permitted: {IPNetwork(eventData).prefixlen} > {max_netblock}")return- if eventName == 'NETBLOCK_MEMBER':- if not self.opts['subnetlookup']:- return-- max_subnet = self.opts['maxsubnet']- if IPNetwork(eventData).prefixlen < max_subnet:- self.debug(f"Network size bigger than permitted: {IPNetwork(eventData).prefixlen} > {max_subnet}")- return+ malicious_type = "MALICIOUS_NETBLOCK"+ blacklist_type = "BLACKLISTED_NETBLOCK"+ else:+ self.debug(f"Unexpected event type {eventName}, skipping")+ return+ addrs = list()if eventName.startswith("NETBLOCK_"):for addr in IPNetwork(eventData):- if self.checkForStop():- return- self.queryAddr(str(addr), parentEvent)+ addrs.append(str(addr))else:- self.queryAddr(eventData, parentEvent)+ addrs.append(eventData)++ for addr in addrs:+ if self.checkForStop():+ return++ res = self.queryAddr(addr)++ self.results[addr] = True++ if not res:+ continue++ self.debug(f"{addr} found in Spaumhaus Zen DNS")++ for result in res:+ k = str(result)++ if k == '127.255.255.252':+ self.error('Spamhaus rejected malformed request')+ continue++ if k == '127.255.255.254':+ self.error('Spamhaus denied query via public/open resolver')+ self.errorState = True+ continue++ if k == '127.255.255.255':+ self.error('Spamhaus rejected query due to excessive number of queries')+ self.errorState = True+ continue++ if k not in self.checks:+ # This is an error. The "checks" dict may need to be updated.+ self.error(f"Spamhaus Zen resolved address {addr} to unknown IP address {result} not found in Spamhaus Zen list.")+ continue++ evt = SpiderFootEvent(blacklist_type, f"{self.checks[k]} [{addr}]", self.__name__, event)+ self.notifyListeners(evt)++ evt = SpiderFootEvent(malicious_type, f"{self.checks[k]} [{addr}]", self.__name__, event)+ self.notifyListeners(evt)# End of sfp_spamhaus classdiff --git a/test/unit/modules/test_sfp_spamhaus.py b/test/unit/modules/test_sfp_spamhaus.pyindex f860d517..58668e54 100644--- a/test/unit/modules/test_sfp_spamhaus.py+++ b/test/unit/modules/test_sfp_spamhaus.py@@ -34,26 +34,34 @@ class TestModulespamhaus(unittest.TestCase):module = sfp_spamhaus()self.assertIsInstance(module.producedEvents(), list)- def test_handleEvent(self):- """- Test handleEvent(self, event)- """+ def test_handleEvent_event_data_safe_ip_address_not_blocked_should_not_return_event(self):sf = SpiderFoot(self.default_options)module = sfp_spamhaus()module.setup(sf, dict())- target_value = '1.1.1.1'- target_type = 'IP_ADDRESS'+ target_value = 'spiderfoot.net'+ target_type = 'INTERNET_NAME'target = SpiderFootTarget(target_value, target_type)module.setTarget(target)+ def new_notifyListeners(self, event):+ raise Exception(f"Raised event {event.eventType}: {event.data}")++ module.notifyListeners = new_notifyListeners.__get__(module, sfp_spamhaus)+event_type = 'ROOT'- event_data = '1.1.1.1'+ event_data = 'example data'event_module = ''source_event = ''evt = SpiderFootEvent(event_type, event_data, event_module, source_event)+ event_type = 'IP_ADDRESS'+ event_data = '1.1.1.1'+ event_module = 'example module'+ source_event = evt++ evt = SpiderFootEvent(event_type, event_data, event_module, source_event)result = module.handleEvent(evt)self.assertIsNone(result)