SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.
Python attacksurfacecticybersecurityfootprintinghackinginformation-gatheringinformation-securityinfosecintelligence-gatheringosintosint-frameworkosint-reconnaissanceosint-toolpentestingpythonreconsecurity-toolsthreat-intelligencethreatintel
Split sfp_malcheck into individual tailored modules.
Steve9ada94477483
diff --git a/modules/sfp_abusech.py b/modules/sfp_abusech.pynew file mode 100644index 00000000..0f85e974--- /dev/null+++ b/modules/sfp_abusech.py@@ -0,0 +1,320 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_abusech+# Purpose: Checks if an ASN, IP or domain is malicious.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'abuse.ch Zeus Tracker (Domain)': {+ 'id': 'abusezeusdomain',+ 'type': 'list',+ 'checks': ['domain'],+ 'url': 'https://zeustracker.abuse.ch/blocklist.php?download=baddomains'+ },+ 'abuse.ch Zeus Tracker (IP)': {+ 'id': 'abusezeusip',+ 'type': 'list',+ 'checks': ['ip', 'netblock'],+ 'url': 'https://zeustracker.abuse.ch/blocklist.php?download=badips'+ },+ 'abuse.ch Feodo Tracker (Domain)': {+ 'id': 'abusefeododomain',+ 'type': 'list',+ 'checks': ['domain'],+ 'url': 'https://feodotracker.abuse.ch/blocklist/?download=domainblocklist'+ },+ 'abuse.ch Feodo Tracker (IP)': {+ 'id': 'abusefeodoip',+ 'type': 'list',+ 'checks': ['ip', 'netblock'],+ 'url': 'https://feodotracker.abuse.ch/blocklist/?download=ipblocklist'+ },+ 'abuse.ch Palevo Tracker (Domain)': {+ 'id': 'abusepalevodomain',+ 'type': 'list',+ 'checks': ['domain'],+ 'url': 'https://palevotracker.abuse.ch/blocklists.php?download=domainblocklist'+ },+ 'abuse.ch Palevo Tracker (IP)': {+ 'id': 'abusepalevoip',+ 'type': 'list',+ 'checks': ['ip', 'netblock'],+ 'url': 'https://palevotracker.abuse.ch/blocklists.php?download=ipblocklist'+ },+ 'abuse.ch SSL Blacklist (IP)': {+ 'id': 'abusesslblip',+ 'type': 'list',+ 'checks': ['ip'],+ 'url': 'https://sslbl.abuse.ch/blacklist/sslipblacklist.csv',+ 'regex': '{0},.*'+ }+}++class sfp_abusech(SpiderFootPlugin):+ """abuse.ch:Investigate,Passive:Blacklists:slow:Check if a host/domain, IP or netblock is malicious according to abuse.ch."""++ # Default options+ opts = {+ 'abusezeusdomain': True,+ 'abusezeusip': True,+ 'abusefeododomain': True,+ 'abusefeodoip': True,+ 'abusepalevodomain': True,+ 'abusepalevoip': True,+ 'abusesslblip': True,+ 'checkaffiliates': True,+ 'checkcohosts': True,+ 'cacheperiod': 18,+ 'checknetblocks': True,+ 'checksubnets': True+ }++ # Option descriptions+ optdescs = {+ 'abusezeusdomain': "Enable abuse.ch Zeus domain check?",+ 'abusezeusip': "Enable abuse.ch Zeus IP check?",+ 'abusefeododomain': "Enable abuse.ch Feodo domain check?",+ 'abusefeodoip': "Enable abuse.ch Feodo IP check?",+ 'abusepalevodomain': "Enable abuse.ch Palevo domain check?",+ 'abusepalevoip': "Enable abuse.ch Palevo IP check?",+ 'abusesslblip': "Enable abuse.ch SSL Backlist IP check?",+ 'checkaffiliates': "Apply checks to affiliates?",+ 'checkcohosts': "Apply checks to sites found to be co-hosted on the target's IP?",+ 'cacheperiod': "Hours to cache list data before re-fetching.",+ 'checknetblocks': "Report if any malicious IPs are found within owned netblocks?",+ 'checksubnets': "Check if any malicious IPs are found within the same subnet of the target?"+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["INTERNET_NAME", "IP_ADDRESS",+ "NETBLOCK_MEMBER", "AFFILIATE_INTERNET_NAME", "AFFILIATE_IPADDR",+ "CO_HOSTED_SITE", "NETBLOCK_OWNER"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_IPADDR", "MALICIOUS_INTERNET_NAME",+ "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_AFFILIATE_INTERNET_NAME",+ "MALICIOUS_SUBNET", "MALICIOUS_COHOST", "MALICIOUS_NETBLOCK"]++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_abusech classdiff --git a/modules/sfp_alienvaultiprep.py b/modules/sfp_alienvaultiprep.pynew file mode 100644index 00000000..8dd03748--- /dev/null+++ b/modules/sfp_alienvaultiprep.py@@ -0,0 +1,267 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_alienvaultiprep+# Purpose: Checks if an ASN, IP or domain is malicious.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'AlienVault IP Reputation Database': {+ 'id': '_alienvault',+ 'type': 'list',+ 'checks': ['ip', 'netblock'],+ 'url': 'https://reputation.alienvault.com/reputation.generic',+ 'regex': '{0} #.*'+ }+}+++class sfp_alienvaultiprep(SpiderFootPlugin):+ """AlienVault IP Reputation:Investigate,Passive:Blacklists:slow:Check if an IP or netblock is malicious according to the AlienVault IP Reputation database."""++ # Default options+ opts = {+ '_alienvault': True,+ 'checkaffiliates': True,+ 'cacheperiod': 18,+ 'checknetblocks': True,+ 'checksubnets': True+ }++ # Option descriptions+ optdescs = {+ 'checkaffiliates': "Apply checks to affiliates?",+ 'cacheperiod': "Hours to cache list data before re-fetching.",+ 'checknetblocks': "Report if any malicious IPs are found within owned netblocks?",+ 'checksubnets': "Check if any malicious IPs are found within the same subnet of the target?"+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["IP_ADDRESS", "NETBLOCK_MEMBER", "AFFILIATE_IPADDR", "NETBLOCK_OWNER"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_IPADDR", "MALICIOUS_AFFILIATE_IPADDR",+ "MALICIOUS_SUBNET", "MALICIOUS_NETBLOCK"]++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_alienvaultiprep classdiff --git a/modules/sfp_badipscom.py b/modules/sfp_badipscom.pynew file mode 100644index 00000000..9dd55a87--- /dev/null+++ b/modules/sfp_badipscom.py@@ -0,0 +1,268 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_badipscom+# Purpose: Checks if an ASN, IP or domain is malicious.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'badips.com IP Reptutation List': {+ 'id': '_badips',+ 'type': 'list',+ 'checks': ['ip', 'domain'],+ 'url': 'https://www.badips.com/get/list/any/1?age=24h',+ 'regex': '{0}'+ }+}+++class sfp_badipscom(SpiderFootPlugin):+ """badips.com:Investigate,Passive:Blacklists:slow:Check if a domain or IP is malicious according to badips.com."""++ # Default options+ opts = {+ '_badips': True,+ 'checkaffiliates': True,+ 'checkcohosts': True,+ 'cacheperiod': 18+ }++ # Option descriptions+ optdescs = {+ 'checkaffiliates': "Apply checks to affiliates?",+ 'checkcohosts': "Apply checks to sites found to be co-hosted on the target's IP?",+ 'cacheperiod': "Hours to cache list data before re-fetching."+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["INTERNET_NAME", "IP_ADDRESS",+ "AFFILIATE_INTERNET_NAME", "AFFILIATE_IPADDR",+ "CO_HOSTED_SITE"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_IPADDR", "MALICIOUS_INTERNET_NAME",+ "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_AFFILIATE_INTERNET_NAME",+ "MALICIOUS_COHOST"]++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_badipscom classdiff --git a/modules/sfp_bitcash.py b/modules/sfp_bitcash.pynew file mode 100644index 00000000..14da5241--- /dev/null+++ b/modules/sfp_bitcash.py@@ -0,0 +1,263 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_bitcash+# Purpose: Checks if an ASN, IP or domain is malicious.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'bitcash.cz Blacklist': {+ 'id': '_bitcash',+ 'type': 'list',+ 'checks': [ 'ip' ],+ 'url': 'http://bitcash.cz/misc/log/blacklist',+ 'regex': '{0}\s+.*'+ }+}+++class sfp_bitcash(SpiderFootPlugin):+ """Bitcash.cz Malicious IPs:Investigate,Passive:Blacklists:slow:Check if an IP is malicious according to Bitcash.cz Malicious IPs."""++ # Default options+ opts = {+ '_bitcash': True,+ 'checkaffiliates': True,+ 'cacheperiod': 18+ }++ # Option descriptions+ optdescs = {+ 'checkaffiliates': "Apply checks to affiliates?",+ 'cacheperiod': "Hours to cache list data before re-fetching."+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["IP_ADDRESS", "AFFILIATE_IPADDR"]+++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_IPADDR", "MALICIOUS_AFFILIATE_IPADDR"]++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_bitcash classdiff --git a/modules/sfp_blocklistde.py b/modules/sfp_blocklistde.pynew file mode 100644index 00000000..c5e5f11c--- /dev/null+++ b/modules/sfp_blocklistde.py@@ -0,0 +1,267 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_blocklistde+# Purpose: Checks if an ASN, IP or domain is malicious.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'blocklist.de List': {+ 'id': '_blocklistde',+ 'type': 'list',+ 'checks': ['ip', 'netblock'],+ 'url': 'http://lists.blocklist.de/lists/all.txt'+ }+}+++class sfp_blocklistde(SpiderFootPlugin):+ """blocklist.de:Investigate,Passive:Blacklists:slow:Check if a netblock or IP is malicious according to blocklist.de."""++ # Default options+ opts = {+ '_blocklistde': True,+ 'checkaffiliates': True,+ 'cacheperiod': 18,+ 'checknetblocks': True,+ 'checksubnets': True+ }++ # Option descriptions+ optdescs = {+ 'checkaffiliates': "Apply checks to affiliates?",+ 'cacheperiod': "Hours to cache list data before re-fetching.",+ 'checknetblocks': "Report if any malicious IPs are found within owned netblocks?",+ 'checksubnets': "Check if any malicious IPs are found within the same subnet of the target?"+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["IP_ADDRESS", "NETBLOCK_MEMBER", "AFFILIATE_IPADDR",+ "NETBLOCK_OWNER"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_IPADDR", "MALICIOUS_AFFILIATE_IPADDR",+ "MALICIOUS_SUBNET", "MALICIOUS_NETBLOCK"]++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_blocklistde classdiff --git a/modules/sfp_cybercrimetracker.py b/modules/sfp_cybercrimetracker.pynew file mode 100644index 00000000..eedd8141--- /dev/null+++ b/modules/sfp_cybercrimetracker.py@@ -0,0 +1,268 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_cybercrimetracker+# Purpose: Checks if an ASN, IP or domain is malicious.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'cybercrime-tracker.net Malicious Submissions': {+ 'id': '_cybercrime',+ 'type': 'list',+ 'checks': ['ip', 'domain'],+ 'url': 'http://cybercrime-tracker.net/all.php',+ 'regex': '^{0}[/$]'+ }+}+++class sfp_cybercrimetracker(SpiderFootPlugin):+ """cybercrime-tracker.net:Investigate,Passive:Blacklists:slow:Check if a host/domain or IP is malicious according to cybercrime-tracker.net."""++ # Default options+ opts = {+ '_cybercrime': True,+ 'checkaffiliates': True,+ 'checkcohosts': True,+ 'cacheperiod': 18+ }++ # Option descriptions+ optdescs = {+ 'checkaffiliates': "Apply checks to affiliates?",+ 'checkcohosts': "Apply checks to sites found to be co-hosted on the target's IP?",+ 'cacheperiod': "Hours to cache list data before re-fetching."+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["INTERNET_NAME", "IP_ADDRESS",+ "AFFILIATE_INTERNET_NAME", "AFFILIATE_IPADDR",+ "CO_HOSTED_SITE"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_IPADDR", "MALICIOUS_INTERNET_NAME",+ "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_AFFILIATE_INTERNET_NAME",+ "MALICIOUS_COHOST"]++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_cybercrimetracker classdiff --git a/modules/sfp_fortinet.py b/modules/sfp_fortinet.pynew file mode 100644index 00000000..a02a9386--- /dev/null+++ b/modules/sfp_fortinet.py@@ -0,0 +1,263 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_fortinet+# Purpose: Checks if an ASN, IP or domain is malicious.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'Fortiguard Threat Lookup': {+ 'id': '_fortiguard',+ 'type': 'query',+ 'checks': [ 'ip' ],+ 'url': 'https://fortiguard.com/search?q={0}&engine=8',+ 'badregex': ['.*Your signature is blacklisted.*'],+ 'goodregex': ['.*Your signature is not blacklisted.*']+ }+}+++class sfp_fortinet(SpiderFootPlugin):+ """Fortiguard.com:Investigate,Passive:Blacklists:slow:Check if an IP is malicious according to Fortiguard.com."""++ # Default options+ opts = {+ '_fortiguard': True,+ 'checkaffiliates': True+ }++ # Option descriptions+ optdescs = {+ 'checkaffiliates': "Apply checks to affiliates?"+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["IP_ADDRESS", "AFFILIATE_IPADDR"]+++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_IPADDR", "MALICIOUS_AFFILIATE_IPADDR"]+++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_fortinet classdiff --git a/modules/sfp_hostsfilenet.py b/modules/sfp_hostsfilenet.pynew file mode 100644index 00000000..4091f7ee--- /dev/null+++ b/modules/sfp_hostsfilenet.py@@ -0,0 +1,265 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_hostsfilenet+# Purpose: Checks if an ASN, IP or domain is malicious.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'hosts-file.net Malicious Hosts': {+ 'id': '_hphosts',+ 'type': 'list',+ 'checks': ['domain'],+ 'url': 'http://hosts-file.net/download/hosts.txt',+ 'regex': '^127.0.0.1\s+{0}$'+ }+}+++class sfp_hostsfilenet(SpiderFootPlugin):+ """hosts-file.net Malicious Hosts:Investigate,Passive:Blacklists:slow:Check if a host/domain is malicious according to hosts-file.net Malicious Hosts."""++ # Default options+ opts = {+ '_hphosts': True,+ 'checkaffiliates': True,+ 'checkcohosts': True,+ 'cacheperiod': 18+ }++ # Option descriptions+ optdescs = {+ 'checkaffiliates': "Apply checks to affiliates?",+ 'checkcohosts': "Apply checks to sites found to be co-hosted on the target's IP?",+ 'cacheperiod': "Hours to cache list data before re-fetching."+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["INTERNET_NAME", "AFFILIATE_INTERNET_NAME", "CO_HOSTED_SITE"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_INTERNET_NAME", "MALICIOUS_AFFILIATE_INTERNET_NAME",+ "MALICIOUS_COHOST"]++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_hostsfilenet classdiff --git a/modules/sfp_isc.py b/modules/sfp_isc.pynew file mode 100644index 00000000..52e4694a--- /dev/null+++ b/modules/sfp_isc.py@@ -0,0 +1,261 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_isc+# Purpose: Checks if an ASN, IP or domain is malicious.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'Internet Storm Center': {+ 'id': '_isc',+ 'type': 'query',+ 'checks': ['ip'],+ 'url': 'https://isc.sans.edu/api/ip/{0}',+ 'badregex': ['.*<attacks>\d+</attacks>.*'],+ 'goodregex': []+ }+}+++class sfp_isc(SpiderFootPlugin):+ """Internet Storm Center:Investigate,Passive:Blacklists:slow:Check if an IP is malicious according to SANS ISC."""++ # Default options+ opts = {+ '_isc': True,+ 'checkaffiliates': True+ }++ # Option descriptions+ optdescs = {+ 'checkaffiliates': "Apply checks to affiliates?"+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["IP_ADDRESS", "AFFILIATE_IPADDR" ]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_IPADDR", "MALICIOUS_AFFILIATE_IPADDR"]++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_isc classdiff --git a/modules/sfp_malc0de.py b/modules/sfp_malc0de.pynew file mode 100644index 00000000..3f6483ff--- /dev/null+++ b/modules/sfp_malc0de.py@@ -0,0 +1,267 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_malc0de+# Purpose: Checks if an ASN, IP or domain is malicious.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'malc0de.com List': {+ 'id': '_malc0de',+ 'type': 'list',+ 'checks': ['ip', 'netblock'],+ 'url': 'http://malc0de.com/bl/IP_Blacklist.txt'+ }+}+++class sfp_malc0de(SpiderFootPlugin):+ """malc0de.com:Investigate,Passive:Blacklists:slow:Check if a netblock or IP is malicious according to malc0de.com."""++ # Default options+ opts = {+ '_malc0de': True,+ 'checkaffiliates': True,+ 'cacheperiod': 18,+ 'checknetblocks': True,+ 'checksubnets': True+ }++ # Option descriptions+ optdescs = {+ 'checkaffiliates': "Apply checks to affiliates?",+ 'cacheperiod': "Hours to cache list data before re-fetching.",+ 'checknetblocks': "Report if any malicious IPs are found within owned netblocks?",+ 'checksubnets': "Check if any malicious IPs are found within the same subnet of the target?"+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["IP_ADDRESS", "NETBLOCK_MEMBER", "AFFILIATE_IPADDR",+ "NETBLOCK_OWNER"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_IPADDR", "MALICIOUS_AFFILIATE_IPADDR",+ "MALICIOUS_SUBNET", "MALICIOUS_NETBLOCK"]++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_malc0de classdiff --git a/modules/sfp_malcheck.py b/modules/sfp_malcheck.pydeleted file mode 100644index e7de0c5b..00000000--- a/modules/sfp_malcheck.py+++ /dev/null@@ -1,613 +0,0 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_malcheck-# Purpose: Checks if an ASN, IP or domain is malicious.-#-# Author: [email protected]-#-# Created: 14/12/2013-# Copyright: (c) Steve Micallef, 2013-# Licence: GPL-# ---------------------------------------------------------------------------------from netaddr import IPAddress, IPNetwork-import re-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent--malchecks = {- 'abuse.ch Zeus Tracker (Domain)': {- 'id': 'abusezeusdomain',- 'type': 'list',- 'checks': ['domain'],- 'url': 'https://zeustracker.abuse.ch/blocklist.php?download=baddomains'- },- 'abuse.ch Zeus Tracker (IP)': {- 'id': 'abusezeusip',- 'type': 'list',- 'checks': ['ip', 'netblock'],- 'url': 'https://zeustracker.abuse.ch/blocklist.php?download=badips'- },- 'abuse.ch Feodo Tracker (Domain)': {- 'id': 'abusefeododomain',- 'type': 'list',- 'checks': ['domain'],- 'url': 'https://feodotracker.abuse.ch/blocklist/?download=domainblocklist'- },- 'abuse.ch Feodo Tracker (IP)': {- 'id': 'abusefeodoip',- 'type': 'list',- 'checks': ['ip', 'netblock'],- 'url': 'https://feodotracker.abuse.ch/blocklist/?download=ipblocklist'- },- 'abuse.ch Palevo Tracker (Domain)': {- 'id': 'abusepalevodomain',- 'type': 'list',- 'checks': ['domain'],- 'url': 'https://palevotracker.abuse.ch/blocklists.php?download=domainblocklist'- },- 'abuse.ch Palevo Tracker (IP)': {- 'id': 'abusepalevoip',- 'type': 'list',- 'checks': ['ip', 'netblock'],- 'url': 'https://palevotracker.abuse.ch/blocklists.php?download=ipblocklist'- },- 'abuse.ch SSL Blacklist (IP)': {- 'id': 'abusesslblip',- 'type': 'list',- 'checks': ['ip'],- 'url': 'https://sslbl.abuse.ch/blacklist/sslipblacklist.csv',- 'regex': '{0},.*'- },- 'Google SafeBrowsing (Domain/IP)': {- 'id': 'googledomain',- 'type': 'query',- 'checks': ['domain', 'ip'],- 'url': 'http://www.google.com/safebrowsing/diagnostic?site={0}',- 'badregex': ['.*not safe to visit.*'],- 'goodregex': []- },- 'Google SafeBrowsing (ASN)': {- 'id': 'googleasn',- 'type': 'query',- 'checks': ['asn'],- 'url': 'http://www.google.com/safebrowsing/diagnostic?site=AS:{0}',- 'badregex': ['.*for example.*, that appeared to function as intermediaries.*',- '.*this network has hosted sites that have distributed malicious.*'- ],- 'goodregex': []- },- 'McAfee Site Advisor': {- 'id': 'mcafeedomain',- 'type': 'query',- 'checks': ['domain'],- 'url': 'http://www.siteadvisor.com/sites/{0}',- 'badregex': ['.*This link might be dangerous.*'],- 'goodregex': []- },- 'AVG Safety Report': {- 'id': 'avgdomain',- 'type': 'query',- 'checks': ['domain'],- 'url': 'http://www.avgthreatlabs.com/website-safety-reports/domain/{0}',- 'badregex': ['.*potentially active malware was detected.*'],- 'goodregex': []- },- 'malwaredomainlist.com IP List': {- 'id': 'malwaredomainlistip',- 'type': 'list',- 'checks': ['ip', 'netblock'],- 'url': 'http://www.malwaredomainlist.com/hostslist/ip.txt'- },- 'malwaredomainlist.com Domain List': {- 'id': 'malwaredomainlistdomain',- 'type': 'list',- 'checks': ['domain'],- 'url': 'http://www.malwaredomainlist.com/hostslist/hosts.txt',- 'regex': '.*\s+{0}[\s$]'- },- 'PhishTank': {- 'id': 'phishtank',- 'type': 'list',- 'checks': ['domain'],- 'url': 'http://data.phishtank.com/data/online-valid.csv',- 'regex': '\d+,\w+://(.*\.)?[^a-zA-Z0-9]?{0}.*,http://www.phishtank.com/.*'- },- 'malc0de.com List': {- 'id': 'malc0de',- 'type': 'list',- 'checks': ['ip', 'netblock'],- 'url': 'http://malc0de.com/bl/IP_Blacklist.txt'- },- 'TOR Node List': {- 'id': 'tornodes',- 'type': 'list',- 'checks': ['ip', 'netblock'],- 'url': 'http://torstatus.blutmagie.de/ip_list_all.php/Tor_ip_list_ALL.csv'- },- 'blocklist.de List': {- 'id': 'blocklistde',- 'type': 'list',- 'checks': ['ip', 'netblock'],- 'url': 'http://lists.blocklist.de/lists/all.txt'- },- 'Autoshun.org List': {- 'id': 'autoshun',- 'type': 'list',- 'checks': ['ip', 'netblock'],- 'url': 'http://www.autoshun.org/files/shunlist.csv',- 'regex': '{0},.*'- },- 'Internet Storm Center': {- 'id': 'isc',- 'type': 'query',- 'checks': ['ip'],- 'url': 'https://isc.sans.edu/api/ip/{0}',- 'badregex': ['.*<attacks>\d+</attacks>.*'],- 'goodregex': []- },- 'AlienVault IP Reputation Database': {- 'id': 'alienvault',- 'type': 'list',- 'checks': ['ip', 'netblock'],- 'url': 'https://reputation.alienvault.com/reputation.generic',- 'regex': '{0} #.*'- },- 'OpenBL.org Blacklist': {- 'id': 'openbl',- 'type': 'list',- 'checks': ['ip', 'netblock'],- 'url': 'http://www.openbl.org/lists/base.txt'- },- 'ThreatExpert.com Database': {- 'id': 'threatexpert',- 'type': 'query',- 'checks': ['ip', 'domain'],- 'url': 'http://www.threatexpert.com/reports.aspx?find={0}&tf=3',- 'badregex': ['.*<strong>Findings</strong>.*'],- 'goodregex': []- },- 'TotalHash.com Database': {- 'id': 'totalhash',- 'type': 'query',- 'checks': ['ip', 'domain'],- 'url': 'http://totalhash.com/search/dnsrr:*{0}%20or%20ip:{0}',- 'badregex': ['.*<a href=\"/analysis.*'],- 'goodregex': []- },- 'Nothink.org SSH Scanners': {- 'id': 'nothinkssh',- 'type': 'list',- 'checks': ['ip', 'netblock', 'domain'],- 'url': 'http://www.nothink.org/blacklist/blacklist_ssh_week.txt'- },- 'Nothink.org Malware IRC Traffic': {- 'id': 'nothinkirc',- 'type': 'list',- 'checks': ['ip', 'netblock', 'domain'],- 'url': 'http://www.nothink.org/blacklist/blacklist_malware_irc.txt'- },- 'Nothink.org Malware HTTP Traffic': {- 'id': 'nothinkhttp',- 'type': 'list',- 'checks': ['ip', 'netblock', 'domain'],- 'url': 'http://www.nothink.org/blacklist/blacklist_malware_http.txt'- },- 'malwaredomains.com Domains': {- 'id': 'malwaredomains',- 'type': 'list',- 'checks': ['domain'],- 'url': 'http://mirror2.malwaredomains.com/files/domains.txt',- 'regex': '.*\t{0}\t[a-zA-Z].*'- },- 'kittenlasers.com IP reputation list': {- 'id': 'kittenlasers',- 'type': 'list',- 'checks': ['ip', 'netblock'],- 'url': 'http://kittenlasers.com/iprep/iprep.txt',- 'regex': '{0};.*'- },- 'bitcash.cz Blacklist': {- 'id': 'bitcash',- 'type': 'list',- 'checks': [ 'ip' ],- 'url': 'http://bitcash.cz/misc/log/blacklist',- 'regex': '{0}\s+.*'- },- 'maxmind.com Open Proxy List': {- 'id': 'maxmind',- 'type': 'list',- 'checks': [ 'ip' ],- 'url': 'https://www.maxmind.com/en/proxy-detection-sample-list',- 'regex': '.*proxy-detection-sample/{0}\".*'- },- 'cybercrime-tracker.net Malicious Submissions': {- 'id': 'cybercrime',- 'type': 'query',- 'checks': ['ip', 'domain'],- 'url': 'http://cybercrime-tracker.net/query.php?url={0}',- 'badregex': ['.*malicious.*'],- 'goodregex': []- },- 'hosts-file.net Malicious Hosts': {- 'id': 'hphosts',- 'type': 'list',- 'checks': ['domain'],- 'url': 'http://hosts-file.net/download/hosts.txt',- 'regex': '^127.0.0.1\s+{0}$'- },- 'multiproxy.org Open Proxies': {- 'id': 'multiproxy',- 'type': 'list',- 'checks': ['ip'],- 'url': 'http://multiproxy.org/txt_all/proxy.txt',- 'regex': '{0}:.*'- },- 'spys.ru Free Proxy List': {- 'id': 'spysproxy',- 'type': 'list',- 'checks': ['ip'],- 'url': 'http://txt.proxyspy.net/proxy.txt',- 'regex': '{0}:.*'- },- 'badips.com IP Reptutation List': {- 'id': 'badips',- 'type': 'list',- 'checks': ['ip', 'domain'],- 'url': 'https://www.badips.com/get/list/any/1?age=24h',- 'regex': '{0}'- },- 'VXVault Malicious URL List': {- 'id': 'vxvault',- 'type': 'list',- 'checks': ['ip', 'domain'],- 'url': 'http://vxvault.net/URL_List.php',- 'regex': '.*\/{0}/.*'- },- 'VOIPBL Publicly Accessible PBX List': {- 'id': 'voipbl',- 'type': 'list',- 'checks': ['ip', 'netblock'],- 'url': 'http://www.voipbl.org/update',- 'regex': '{0}\/'- },- 'Fortinet Threat Lookup': {- 'id': 'fortinet',- 'type': 'query',- 'checks': [ 'ip' ],- 'url': 'https://fortiguard.com/search?q={0}&engine=8',- 'badregex': ['.*Your signature is blacklisted.*'],- 'goodregex': ['.*Your signature is not blacklisted.*']- },- 'Watchguard Reputation Authority Lookup': {- 'id': 'watchguard',- 'type': 'query',- 'checks': [ 'ip' ],- 'url': 'http://reputationauthority.org/lookup?ip={0}',- 'badregex': ['.*>[6-9][0-9]/100 </td>.*','.*>100/100 </td>.*'],- 'goodregex': []- }-}---class sfp_malcheck(SpiderFootPlugin):- """Malicious Check:Investigate,Passive:Blacklists:slow:Check if a website, IP or ASN is considered malicious by various sources. Includes TOR exit nodes and open proxies."""-- # Default options- opts = {- 'abusezeusdomain': True,- 'abusezeusip': True,- 'abusefeododomain': True,- 'abusefeodoip': True,- 'abusepalevodomain': True,- 'abusepalevoip': True,- 'abusesslblip': True,- 'googledomain': True,- 'googleasn': True,- 'bitcash': True,- 'maxmind': True,- 'malwaredomainlistdomain': True,- 'malwaredomainlistip': True,- 'malwaredomains': True,- 'mcafeedomain': True,- 'cybercrime': True,- 'hphosts': True,- 'avgdomain': True,- 'phishtank': True,- 'malc0de': True,- 'blocklistde': True,- 'autoshun': True,- 'isc': True,- 'badips': True,- 'tornodes': True,- 'fortinet': True,- 'watchguard': True,- 'multiproxy': True,- 'alienvault': True,- 'openbl': True,- 'spysproxy': True,- 'totalhash': True,- 'threatexpert': True,- 'nothinkssh': True,- 'nothinkirc': True,- 'nothinkhttp': True,- 'vxvault': True,- 'voipbl': True,- 'kittenlasers': True,- 'aaacheckaffiliates': True, # prefix with aaa so they appear on the top of the UI list- 'aaacheckcohosts': True,- 'aaacacheperiod': 18,- 'aaachecknetblocks': True,- 'aaachecksubnets': True- }-- # Option descriptions- optdescs = {- 'abusezeusdomain': "Enable abuse.ch Zeus domain check?",- 'abusezeusip': "Enable abuse.ch Zeus IP check?",- 'abusefeododomain': "Enable abuse.ch Feodo domain check?",- 'abusefeodoip': "Enable abuse.ch Feodo IP check?",- 'abusepalevodomain': "Enable abuse.ch Palevo domain check?",- 'abusepalevoip': "Enable abuse.ch Palevo IP check?",- 'abusesslblip': "Enable abuse.ch SSL Backlist IP check?",- 'googledomain': "Enable Google Safe Browsing domain check?",- 'googleasn': "Enable Google Safe Browsing ASN check?",- 'bitcash': "Enable bitcash.cz Blocklist check?",- 'maxmind': "Enable maxmind.com Open Proxy list check?",- 'malwaredomainlistdomain': "Enable malwaredomainlist.com domain check?",- 'malwaredomainlistip': "Enable malwaredomainlist.com IP check?",- 'malwaredomains': "Enable malwaredomains.com Domain check?",- 'mcafeedomain': "Enable McAfee Site Advisor check?",- 'avgdomain': "Enable AVG Safety check?",- 'phishtank': "Enable PhishTank check?",- 'malc0de': "Enable malc0de.com check?",- 'fortinet': "Enable fortinet.com FortiGuard check?",- 'watchguard': "Enable Watchguard's Reputation Authority lookup?",- 'blocklistde': 'Enable blocklist.de check?',- 'tornodes': 'Enable TOR exit node check?',- 'cybercrime': 'Enable cybercrime-tracker.net Malicious IP check?',- 'hphosts': 'Enable hosts-file.net Malicious Hosts check?',- 'spysproxy': 'Enable spys.ru Free Proxy lookup?',- 'badips': 'Enable badips.com IP lookup?',- 'multiproxy': 'Enable multiproxy.org Open Proxy lookup?',- 'autoshun': 'Enable Autoshun.org check?',- 'isc': 'Enable Internet Storm Center check?',- 'alienvault': 'Enable AlienVault IP Reputation check?',- 'openbl': 'Enable OpenBL.org Blacklist check?',- 'totalhash': 'Enable totalhash.com check?',- 'vxvault': 'Enable VXVault Malicious URL check (checks hostnames and IPs)?',- 'voipbl': 'Enable checking for publicly accessible PBXs in VOIPBL?',- 'threatexpert': 'Enable threatexpert.com check?',- 'nothinkssh': 'Enable Nothink.org SSH attackers check?',- 'nothinkirc': 'Enable Nothink.org Malware DNS traffic check?',- 'nothinkhttp': 'Enable Nothink.org Malware HTTP traffic check?',- 'kittenlasers': 'Enable kittenlasers.com IP reputation list?',- 'aaacheckaffiliates': "Apply checks to affiliates?",- 'aaacheckcohosts': "Apply checks to sites found to be co-hosted on the target's IP?",- 'aaacacheperiod': "Hours to cache list data before re-fetching.",- 'aaachecknetblocks': "Report if any malicious IPs are found within owned netblocks?",- 'aaachecksubnets': "Check if any malicious IPs are found within the same subnet of the target?"- }-- # Be sure to completely clear any class variables in setup()- # or you run the risk of data persisting between scan runs.-- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- # Clear / reset any other class member variables here- # or you risk them persisting between threads.-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- # * = be notified about all events.- def watchedEvents(self):- return ["INTERNET_NAME", "IP_ADDRESS", "BGP_AS_OWNER", "BGP_AS_MEMBER",- "NETBLOCK_MEMBER", "AFFILIATE_INTERNET_NAME", "AFFILIATE_IPADDR",- "CO_HOSTED_SITE", "NETBLOCK_OWNER"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["MALICIOUS_ASN", "MALICIOUS_IPADDR", "MALICIOUS_INTERNET_NAME",- "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_AFFILIATE_INTERNET_NAME",- "MALICIOUS_SUBNET", "MALICIOUS_COHOST", "MALICIOUS_NETBLOCK"]-- # Check the regexps to see whether the content indicates maliciousness- def contentMalicious(self, content, goodregex, badregex):- # First, check for the bad indicators- if len(badregex) > 0:- for rx in badregex:- if re.match(rx, content, re.IGNORECASE | re.DOTALL):- self.sf.debug("Found to be bad against bad regex: " + rx)- return True-- # Finally, check for good indicators- if len(goodregex) > 0:- for rx in goodregex:- if re.match(rx, content, re.IGNORECASE | re.DOTALL):- self.sf.debug("Found to be good againt good regex: " + rx)- return False-- # If nothing was matched, reply None- self.sf.debug("Neither good nor bad, unknown.")- return None-- # Look up 'query' type sources- def resourceQuery(self, id, target, targetType):- self.sf.debug("Querying " + id + " for maliciousness of " + target)- for check in malchecks.keys():- cid = malchecks[check]['id']- if id == cid and malchecks[check]['type'] == "query":- url = unicode(malchecks[check]['url'])- res = self.sf.fetchUrl(url.format(target), useragent=self.opts['_useragent'])- if res['content'] is None:- self.sf.error("Unable to fetch " + url.format(target), False)- return None- if self.contentMalicious(res['content'],- malchecks[check]['goodregex'],- malchecks[check]['badregex']):- return url.format(target)-- return None-- # Look up 'list' type resources- def resourceList(self, id, target, targetType):- targetDom = ''- # Get the base domain if we're supplied a domain- if targetType == "domain":- targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])-- for check in malchecks.keys():- cid = malchecks[check]['id']- if id == cid and malchecks[check]['type'] == "list":- data = dict()- url = malchecks[check]['url']- data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts['aaacacheperiod'])- if data['content'] is None:- data = self.sf.fetchUrl(url, useragent=self.opts['_useragent'])- if data['content'] is None:- self.sf.error("Unable to fetch " + url, False)- return None- else:- self.sf.cachePut("sfmal_" + cid, data['content'])-- # If we're looking at netblocks- if targetType == "netblock":- iplist = list()- # Get the regex, replace {0} with an IP address matcher to- # build a list of IP.- # Cycle through each IP and check if it's in the netblock.- if 'regex' in malchecks[check]:- rx = malchecks[check]['regex'].replace("{0}",- "(\d+\.\d+\.\d+\.\d+)")- pat = re.compile(rx, re.IGNORECASE)- self.sf.debug("New regex for " + check + ": " + rx)- for line in data['content'].split('\n'):- grp = re.findall(pat, line)- if len(grp) > 0:- #self.sf.debug("Adding " + grp[0] + " to list.")- iplist.append(grp[0])- else:- iplist = data['content'].split('\n')-- for ip in iplist:- if len(ip) < 8 or ip.startswith("#"):- continue- ip = ip.strip()-- try:- if IPAddress(ip) in IPNetwork(target):- self.sf.debug(ip + " found within netblock/subnet " +- target + " in " + check)- return url- except Exception as e:- self.sf.debug("Error encountered parsing: " + str(e))- continue-- return None-- # If we're looking at hostnames/domains/IPs- if 'regex' not in malchecks[check]:- for line in data['content'].split('\n'):- if line == target or (targetType == "domain" and line == targetDom):- self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")- return url- else:- # Check for the domain and the hostname- rxDom = unicode(malchecks[check]['regex']).format(targetDom)- rxTgt = unicode(malchecks[check]['regex']).format(target)- for line in data['content'].split('\n'):- if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \- re.match(rxTgt, line, re.IGNORECASE):- self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")- return url- return None-- def lookupItem(self, resourceId, itemType, target):- for check in malchecks.keys():- cid = malchecks[check]['id']- if cid == resourceId and itemType in malchecks[check]['checks']:- self.sf.debug("Checking maliciousness of " + target + " (" +- itemType + ") with: " + cid)- if malchecks[check]['type'] == "query":- return self.resourceQuery(cid, target, itemType)- if malchecks[check]['type'] == "list":- return self.resourceList(cid, target, itemType)-- return None-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- if eventData in self.results:- self.sf.debug("Skipping " + eventData + ", already checked.")- return None- else:- self.results.append(eventData)-- if eventName == 'CO_HOSTED_SITE' and not self.opts['aaacheckcohosts']:- return None- if eventName == 'AFFILIATE_IPADDR' \- and not self.opts['aaacheckaffiliates']:- return None- if eventName == 'NETBLOCK_OWNER' and not self.opts['aaachecknetblocks']:- return None- if eventName == 'NETBLOCK_MEMBER' and not self.opts['aaachecksubnets']:- return None-- for check in malchecks.keys():- cid = malchecks[check]['id']- # If the module is enabled..- if self.opts[cid]:- if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:- typeId = 'ip'- if eventName == 'IP_ADDRESS':- evtType = 'MALICIOUS_IPADDR'- else:- evtType = 'MALICIOUS_AFFILIATE_IPADDR'-- if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:- typeId = 'asn'- evtType = 'MALICIOUS_ASN'-- if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',- 'AFFILIATE_INTERNET_NAME', ]:- typeId = 'domain'- if eventName == "INTERNET_NAME":- evtType = "MALICIOUS_INTERNET_NAME"- if eventName == 'AFFILIATE_INTERNET_NAME':- evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'- if eventName == 'CO_HOSTED_SITE':- evtType = 'MALICIOUS_COHOST'-- if eventName == 'NETBLOCK_OWNER':- typeId = 'netblock'- evtType = 'MALICIOUS_NETBLOCK'- if eventName == 'NETBLOCK_MEMBER':- typeId = 'netblock'- evtType = 'MALICIOUS_SUBNET'-- url = self.lookupItem(cid, typeId, eventData)- if self.checkForStop():- return None-- # Notify other modules of what you've found- if url is not None:- text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"- evt = SpiderFootEvent(evtType, text, self.__name__, event)- self.notifyListeners(evt)-- return None--# End of sfp_malcheck classdiff --git a/modules/sfp_malwaredomainlist.py b/modules/sfp_malwaredomainlist.pynew file mode 100644index 00000000..421b1e55--- /dev/null+++ b/modules/sfp_malwaredomainlist.py@@ -0,0 +1,280 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_malwaredomainlist+# Purpose: Checks if an ASN, IP or domain is malicious.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'malwaredomainlist.com IP List': {+ 'id': 'malwaredomainlistip',+ 'type': 'list',+ 'checks': ['ip', 'netblock'],+ 'url': 'http://www.malwaredomainlist.com/hostslist/ip.txt'+ },+ 'malwaredomainlist.com Domain List': {+ 'id': 'malwaredomainlistdomain',+ 'type': 'list',+ 'checks': ['domain'],+ 'url': 'http://www.malwaredomainlist.com/hostslist/hosts.txt',+ 'regex': '.*\s+{0}[\s$]'+ }+}++class sfp_malwaredomainlist(SpiderFootPlugin):+ """malwaredomainlist.com:Investigate,Passive:Blacklists:slow:Check if a host/domain, IP or netblock is malicious according to malwaredomainlist.com."""++ # Default options+ opts = {+ 'malwaredomainlistdomain': True,+ 'malwaredomainlistip': True,+ 'checkaffiliates': True,+ 'checkcohosts': True,+ 'cacheperiod': 18,+ 'checknetblocks': True,+ 'checksubnets': True+ }++ # Option descriptions+ optdescs = {+ 'malwaredomainlistdomain': "Enable malwaredomainlist.com domain check?",+ 'malwaredomainlistip': "Enable malwaredomainlist.com IP check?",+ 'checkaffiliates': "Apply checks to affiliates?",+ 'checkcohosts': "Apply checks to sites found to be co-hosted on the target's IP?",+ 'cacheperiod': "Hours to cache list data before re-fetching.",+ 'checknetblocks': "Report if any malicious IPs are found within owned netblocks?",+ 'checksubnets': "Check if any malicious IPs are found within the same subnet of the target?"+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["INTERNET_NAME", "IP_ADDRESS", "BGP_AS_OWNER", "BGP_AS_MEMBER",+ "NETBLOCK_MEMBER", "AFFILIATE_INTERNET_NAME", "AFFILIATE_IPADDR",+ "CO_HOSTED_SITE", "NETBLOCK_OWNER"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_ASN", "MALICIOUS_IPADDR", "MALICIOUS_INTERNET_NAME",+ "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_AFFILIATE_INTERNET_NAME",+ "MALICIOUS_SUBNET", "MALICIOUS_COHOST", "MALICIOUS_NETBLOCK"]++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_malwaredomainlist classdiff --git a/modules/sfp_malwaredomains.py b/modules/sfp_malwaredomains.pynew file mode 100644index 00000000..87b92aab--- /dev/null+++ b/modules/sfp_malwaredomains.py@@ -0,0 +1,264 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_malwaredomains+# Purpose: Checks if an ASN, IP or domain is malicious.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'malwaredomains.com Domains': {+ 'id': '_malwaredomains',+ 'type': 'list',+ 'checks': ['domain'],+ 'url': 'https://mirror.cedia.org.ec/malwaredomains/justdomains',+ 'regex': '^{0}$'+ }+}++class sfp_malwaredomains(SpiderFootPlugin):+ """malwaredomains.com:Investigate,Passive:Blacklists:slow:Check if a host/domain is malicious according to malwaredomains.com."""++ # Default options+ opts = {+ '_malwaredomains': True,+ 'checkaffiliates': True,+ 'checkcohosts': True,+ 'cacheperiod': 18+ }++ # Option descriptions+ optdescs = {+ 'checkaffiliates': "Apply checks to affiliates?",+ 'checkcohosts': "Apply checks to sites found to be co-hosted on the target's IP?",+ 'cacheperiod': "Hours to cache list data before re-fetching."+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["INTERNET_NAME", "AFFILIATE_INTERNET_NAME", "CO_HOSTED_SITE"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_INTERNET_NAME", "MALICIOUS_AFFILIATE_INTERNET_NAME",+ "MALICIOUS_COHOST"]++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_malwaredomains classdiff --git a/modules/sfp_mcafee.py b/modules/sfp_mcafee.pynew file mode 100644index 00000000..4feb03e8--- /dev/null+++ b/modules/sfp_mcafee.py@@ -0,0 +1,263 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_mcafee+# Purpose: Checks if an ASN, IP or domain is malicious.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'McAfee Site Advisor': {+ 'id': '_mcafee',+ 'type': 'query',+ 'checks': ['domain'],+ 'url': 'http://www.siteadvisor.com/sites/{0}',+ 'badregex': ['.*This link might be dangerous.*'],+ 'goodregex': []+ }+}++class sfp_mcafee(SpiderFootPlugin):+ """McAfee SiteAdvisor:Investigate,Passive:Blacklists:slow:Check if a host/domain is malicious according to McAfee SiteAdvisor."""++ # Default options+ opts = {+ '_mcafee': True,+ 'checkaffiliates': True,+ 'checkcohosts': True+ }++ # Option descriptions+ optdescs = {+ 'checkaffiliates': "Apply checks to affiliates?",+ 'checkcohosts': "Apply checks to sites found to be co-hosted on the target's IP?"+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["INTERNET_NAME", "AFFILIATE_INTERNET_NAME", "CO_HOSTED_SITE"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_INTERNET_NAME", "MALICIOUS_AFFILIATE_INTERNET_NAME",+ "MALICIOUS_COHOST"]++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_mcafee classdiff --git a/modules/sfp_multiproxy.py b/modules/sfp_multiproxy.pynew file mode 100644index 00000000..e57da5fa--- /dev/null+++ b/modules/sfp_multiproxy.py@@ -0,0 +1,263 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_multiproxy+# Purpose: Checks if an ASN, IP or domain is malicious.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'multiproxy.org Open Proxies': {+ 'id': '_multiproxy',+ 'type': 'list',+ 'checks': ['ip'],+ 'url': 'http://multiproxy.org/txt_all/proxy.txt',+ 'regex': '{0}:.*'+ }+}+++class sfp_multiproxy(SpiderFootPlugin):+ """multiproxy.org Open Proxies:Investigate,Passive:Blacklists:slow:Check if an IP is an open proxy according to multiproxy.org' open proxy list."""++ # Default options+ opts = {+ '_multiproxy': True,+ 'checkaffiliates': True,+ 'cacheperiod': 18+ }++ # Option descriptions+ optdescs = {+ 'checkaffiliates': "Apply checks to affiliates?",+ 'cacheperiod': "Hours to cache list data before re-fetching."+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["IP_ADDRESS", "AFFILIATE_IPADDR"]+++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_IPADDR" "MALICIOUS_AFFILIATE_IPADDR"]++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_multiproxy classdiff --git a/modules/sfp_nothink.py b/modules/sfp_nothink.pynew file mode 100644index 00000000..ffe62edd--- /dev/null+++ b/modules/sfp_nothink.py@@ -0,0 +1,287 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_nothink+# Purpose: Checks if an ASN, IP or domain is malicious.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'Nothink.org SSH Scanners': {+ 'id': 'nothinkssh',+ 'type': 'list',+ 'checks': ['ip', 'netblock', 'domain'],+ 'url': 'http://www.nothink.org/blacklist/blacklist_ssh_week.txt'+ },+ 'Nothink.org Malware IRC Traffic': {+ 'id': 'nothinkirc',+ 'type': 'list',+ 'checks': ['ip', 'netblock', 'domain'],+ 'url': 'http://www.nothink.org/blacklist/blacklist_malware_irc.txt'+ },+ 'Nothink.org Malware HTTP Traffic': {+ 'id': 'nothinkhttp',+ 'type': 'list',+ 'checks': ['ip', 'netblock', 'domain'],+ 'url': 'http://www.nothink.org/blacklist/blacklist_malware_http.txt'+ }+}++class sfp_nothink(SpiderFootPlugin):+ """Nothink.org:Investigate,Passive:Blacklists:slow:Check if a host/domain, netblock or IP is malicious according to Nothink.org."""++ # Default options+ opts = {+ 'nothinkssh': True,+ 'nothinkirc': True,+ 'nothinkhttp': True,+ 'checkaffiliates': True,+ 'checkcohosts': True,+ 'cacheperiod': 18,+ 'checknetblocks': True,+ 'checksubnets': True+ }++ # Option descriptions+ optdescs = {+ 'nothinkssh': 'Enable Nothink.org SSH attackers check?',+ 'nothinkirc': 'Enable Nothink.org Malware DNS traffic check?',+ 'nothinkhttp': 'Enable Nothink.org Malware HTTP traffic check?',+ 'checkaffiliates': "Apply checks to affiliates?",+ 'checkcohosts': "Apply checks to sites found to be co-hosted on the target's IP?",+ 'cacheperiod': "Hours to cache list data before re-fetching.",+ 'checknetblocks': "Report if any malicious IPs are found within owned netblocks?",+ 'checksubnets': "Check if any malicious IPs are found within the same subnet of the target?"+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["INTERNET_NAME", "IP_ADDRESS",+ "NETBLOCK_MEMBER", "AFFILIATE_INTERNET_NAME", "AFFILIATE_IPADDR",+ "CO_HOSTED_SITE", "NETBLOCK_OWNER"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_IPADDR", "MALICIOUS_INTERNET_NAME",+ "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_AFFILIATE_INTERNET_NAME",+ "MALICIOUS_SUBNET", "MALICIOUS_COHOST", "MALICIOUS_NETBLOCK"]++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_nothink classdiff --git a/modules/sfp_phishtank.py b/modules/sfp_phishtank.pynew file mode 100644index 00000000..bb73e022--- /dev/null+++ b/modules/sfp_phishtank.py@@ -0,0 +1,265 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_phishtank+# Purpose: Checks if an ASN, IP or domain is malicious.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'PhishTank': {+ 'id': '_phishtank',+ 'type': 'list',+ 'checks': ['domain'],+ 'url': 'http://data.phishtank.com/data/online-valid.csv',+ 'regex': '\d+,\w+://(.*\.)?[^a-zA-Z0-9]?{0}.*,http://www.phishtank.com/.*'+ }+}+++class sfp_phishtank(SpiderFootPlugin):+ """PhishTank:Investigate,Passive:Blacklists:slow:Check if a host/domain is malicious according to PhishTank."""++ # Default options+ opts = {+ '_phishtank': True,+ 'checkaffiliates': True,+ 'checkcohosts': True,+ 'cacheperiod': 18+ }++ # Option descriptions+ optdescs = {+ 'checkaffiliates': "Apply checks to affiliates?",+ 'checkcohosts': "Apply checks to sites found to be co-hosted on the target's IP?",+ 'cacheperiod': "Hours to cache list data before re-fetching."+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["INTERNET_NAME", "AFFILIATE_INTERNET_NAME", "CO_HOSTED_SITE"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_INTERNET_NAME", "MALICIOUS_AFFILIATE_INTERNET_NAME",+ "MALICIOUS_COHOST"]++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_phishtank classdiff --git a/modules/sfp_threatexpert.py b/modules/sfp_threatexpert.pynew file mode 100644index 00000000..59b7c516--- /dev/null+++ b/modules/sfp_threatexpert.py@@ -0,0 +1,266 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_threatexpert+# Purpose: Checks if an ASN, IP or domain is malicious.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'ThreatExpert.com Database': {+ 'id': '_threatexpert',+ 'type': 'query',+ 'checks': ['ip', 'domain'],+ 'url': 'http://www.threatexpert.com/reports.aspx?find={0}&tf=3',+ 'badregex': ['.*<strong>Findings</strong>.*'],+ 'goodregex': []+ }+}+++class sfp_threatexpert(SpiderFootPlugin):+ """ThreatExpert.com:Investigate,Passive:Blacklists:slow:Check if a host/domain or IP is malicious according to ThreatExpert.com."""++ # Default options+ opts = {+ '_threatexpert': True,+ 'checkaffiliates': True,+ 'checkcohosts': True+ }++ # Option descriptions+ optdescs = {+ 'checkaffiliates': "Apply checks to affiliates?",+ 'checkcohosts': "Apply checks to sites found to be co-hosted on the target's IP?"+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["INTERNET_NAME", "IP_ADDRESS", "AFFILIATE_INTERNET_NAME",+ "AFFILIATE_IPADDR", "CO_HOSTED_SITE"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_IPADDR", "MALICIOUS_INTERNET_NAME",+ "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_AFFILIATE_INTERNET_NAME",+ "MALICIOUS_COHOST"]++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_threatexpert classdiff --git a/modules/sfp_tornode.py b/modules/sfp_tornode.pynew file mode 100644index 00000000..83fc8c25--- /dev/null+++ b/modules/sfp_tornode.py@@ -0,0 +1,267 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_tornode+# Purpose: Checks if an IP or netblock appears on the TOR exit node list.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'TOR Node List': {+ 'id': '_tornodes',+ 'type': 'list',+ 'checks': ['ip', 'netblock'],+ 'url': 'http://torstatus.blutmagie.de/ip_list_all.php/Tor_ip_list_ALL.csv'+ }+}+++class sfp_tornode(SpiderFootPlugin):+ """TOR Exit Nodes:Investigate,Passive:Blacklists:slow:Check if an IP or netblock appears on the blutmagie.de TOR exit node list."""++ # Default options+ opts = {+ '_tornodes': True,+ 'checkaffiliates': True,+ 'cacheperiod': 18,+ 'checknetblocks': True,+ 'checksubnets': True+ }++ # Option descriptions+ optdescs = {+ 'checkaffiliates': "Apply checks to affiliates?",+ 'cacheperiod': "Hours to cache list data before re-fetching.",+ 'checknetblocks': "Report if any malicious IPs are found within owned netblocks?",+ 'checksubnets': "Check if any malicious IPs are found within the same subnet of the target?"+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["IP_ADDRESS", "NETBLOCK_MEMBER", "AFFILIATE_IPADDR",+ "NETBLOCK_OWNER"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_IPADDR", "MALICIOUS_AFFILIATE_IPADDR",+ "MALICIOUS_SUBNET", "MALICIOUS_NETBLOCK"]++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_tornode classdiff --git a/modules/sfp_totalhash.py b/modules/sfp_totalhash.pynew file mode 100644index 00000000..ff966f9c--- /dev/null+++ b/modules/sfp_totalhash.py@@ -0,0 +1,267 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_totalhash+# Purpose: Checks if an ASN, IP or domain is malicious.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'TotalHash.com Database': {+ 'id': '_totalhash',+ 'type': 'query',+ 'checks': ['ip', 'domain'],+ 'url': 'https://totalhash.cymru.com/search/?dnsrr:*{0}%20or%20ip:{0}',+ 'badregex': ['.*<a href=\"/analysis.*'],+ 'goodregex': []+ }+}+++class sfp_totalhash(SpiderFootPlugin):+ """TotalHash.com:Investigate,Passive:Blacklists:slow:Check if a host/domain or IP is malicious according to TotalHash.com."""++ # Default options+ opts = {+ '_totalhash': True,+ 'checkaffiliates': True,+ 'checkcohosts': True+ }++ # Option descriptions+ optdescs = {+ 'checkaffiliates': "Apply checks to affiliates?",+ 'checkcohosts': "Apply checks to sites found to be co-hosted on the target's IP?"+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["INTERNET_NAME", "IP_ADDRESS",+ "AFFILIATE_INTERNET_NAME", "AFFILIATE_IPADDR",+ "CO_HOSTED_SITE"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_IPADDR", "MALICIOUS_INTERNET_NAME",+ "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_AFFILIATE_INTERNET_NAME",+ "MALICIOUS_COHOST"]++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_totalhash classdiff --git a/modules/sfp_voipbl.py b/modules/sfp_voipbl.pynew file mode 100644index 00000000..6efde6c0--- /dev/null+++ b/modules/sfp_voipbl.py@@ -0,0 +1,268 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_voipbl+# Purpose: Checks if an ASN, IP or domain is malicious.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'VOIPBL Publicly Accessible PBX List': {+ 'id': '_voipbl',+ 'type': 'list',+ 'checks': ['ip', 'netblock'],+ 'url': 'http://www.voipbl.org/update',+ 'regex': '{0}\/'+ }+}+++class sfp_voipbl(SpiderFootPlugin):+ """VoIPBL OpenPBX IPs:Investigate,Passive:Blacklists:slow:Check if an IP or netblock is an open PBX according to VoIPBL OpenPBX IPs."""++ # Default options+ opts = {+ '_voipbl': True,+ 'checkaffiliates': True,+ 'cacheperiod': 18,+ 'checknetblocks': True,+ 'checksubnets': True+ }++ # Option descriptions+ optdescs = {+ 'checkaffiliates': "Apply checks to affiliates?",+ 'cacheperiod': "Hours to cache list data before re-fetching.",+ 'checknetblocks': "Report if any malicious IPs are found within owned netblocks?",+ 'checksubnets': "Check if any malicious IPs are found within the same subnet of the target?"+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["IP_ADDRESS", "NETBLOCK_MEMBER", "AFFILIATE_IPADDR",+ "NETBLOCK_OWNER"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_IPADDR", "MALICIOUS_AFFILIATE_IPADDR",+ "MALICIOUS_SUBNET", "MALICIOUS_NETBLOCK"]++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_voipbl classdiff --git a/modules/sfp_vxvault.py b/modules/sfp_vxvault.pynew file mode 100644index 00000000..f6076b5e--- /dev/null+++ b/modules/sfp_vxvault.py@@ -0,0 +1,268 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_vxvault+# Purpose: Checks if an ASN, IP or domain is malicious.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'VXVault Malicious URL List': {+ 'id': '_vxvault',+ 'type': 'list',+ 'checks': ['ip', 'domain'],+ 'url': 'http://vxvault.net/URL_List.php',+ 'regex': '.*\/{0}/.*'+ }+}+++class sfp_vxvault(SpiderFootPlugin):+ """VXVault.net:Investigate,Passive:Blacklists:slow:Check if a domain or IP is malicious according to VXVault.net."""++ # Default options+ opts = {+ '_vxvault': True,+ 'checkaffiliates': True,+ 'checkcohosts': True,+ 'cacheperiod': 18+ }++ # Option descriptions+ optdescs = {+ 'checkaffiliates': "Apply checks to affiliates?",+ 'checkcohosts': "Apply checks to sites found to be co-hosted on the target's IP?",+ 'cacheperiod': "Hours to cache list data before re-fetching."+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["INTERNET_NAME", "IP_ADDRESS",+ "AFFILIATE_INTERNET_NAME", "AFFILIATE_IPADDR",+ "CO_HOSTED_SITE"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_IPADDR", "MALICIOUS_INTERNET_NAME",+ "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_AFFILIATE_INTERNET_NAME",+ "MALICIOUS_COHOST"]++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_vxvault classdiff --git a/modules/sfp_watchguard.py b/modules/sfp_watchguard.pynew file mode 100644index 00000000..9e6fd27d--- /dev/null+++ b/modules/sfp_watchguard.py@@ -0,0 +1,261 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_watchguard+# Purpose: Checks if an ASN, IP or domain is malicious.+#+# Author: [email protected]+#+# Created: 14/12/2013+# Copyright: (c) Steve Micallef, 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++malchecks = {+ 'Watchguard Reputation Authority Lookup': {+ 'id': '_watchguard',+ 'type': 'query',+ 'checks': [ 'ip' ],+ 'url': 'http://reputationauthority.org/lookup?ip={0}',+ 'badregex': ['.*>[6-9][0-9]/100 </td>.*','.*>100/100 </td>.*'],+ 'goodregex': []+ }+}+++class sfp_watchguard(SpiderFootPlugin):+ """Watchguard:Investigate,Passive:Blacklists:slow:Check if an IP is malicious according to Watchguard's reputationauthority.org."""++ # Default options+ opts = {+ '_watchguard': True,+ 'checkaffiliates': True+ }++ # Option descriptions+ optdescs = {+ 'checkaffiliates': "Apply checks to affiliates?"+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ # Clear / reset any other class member variables here+ # or you risk them persisting between threads.++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["IP_ADDRESS", "AFFILIATE_IPADDR"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["MALICIOUS_IPADDR" "MALICIOUS_AFFILIATE_IPADDR" ]++ # Check the regexps to see whether the content indicates maliciousness+ def contentMalicious(self, content, goodregex, badregex):+ # First, check for the bad indicators+ if len(badregex) > 0:+ for rx in badregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be bad against bad regex: " + rx)+ return True++ # Finally, check for good indicators+ if len(goodregex) > 0:+ for rx in goodregex:+ if re.match(rx, content, re.IGNORECASE | re.DOTALL):+ self.sf.debug("Found to be good againt good regex: " + rx)+ return False++ # If nothing was matched, reply None+ self.sf.debug("Neither good nor bad, unknown.")+ return None++ # Look up 'query' type sources+ def resourceQuery(self, id, target, targetType):+ self.sf.debug("Querying " + id + " for maliciousness of " + target)+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "query":+ url = unicode(malchecks[check]['url'])+ res = self.sf.fetchUrl(url.format(target), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.error("Unable to fetch " + url.format(target), False)+ return None+ if self.contentMalicious(res['content'],+ malchecks[check]['goodregex'],+ malchecks[check]['badregex']):+ return url.format(target)++ return None++ # Look up 'list' type resources+ def resourceList(self, id, target, targetType):+ targetDom = ''+ # Get the base domain if we're supplied a domain+ if targetType == "domain":+ targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if id == cid and malchecks[check]['type'] == "list":+ data = dict()+ url = malchecks[check]['url']+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts.get('cacheperiod', 0))+ if data['content'] is None:+ data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfmal_" + cid, data['content'])++ # If we're looking at netblocks+ if targetType == "netblock":+ iplist = list()+ # Get the regex, replace {0} with an IP address matcher to+ # build a list of IP.+ # Cycle through each IP and check if it's in the netblock.+ if 'regex' in malchecks[check]:+ rx = malchecks[check]['regex'].replace("{0}",+ "(\d+\.\d+\.\d+\.\d+)")+ pat = re.compile(rx, re.IGNORECASE)+ self.sf.debug("New regex for " + check + ": " + rx)+ for line in data['content'].split('\n'):+ grp = re.findall(pat, line)+ if len(grp) > 0:+ #self.sf.debug("Adding " + grp[0] + " to list.")+ iplist.append(grp[0])+ else:+ iplist = data['content'].split('\n')++ for ip in iplist:+ if len(ip) < 8 or ip.startswith("#"):+ continue+ ip = ip.strip()++ try:+ if IPAddress(ip) in IPNetwork(target):+ self.sf.debug(ip + " found within netblock/subnet " ++ target + " in " + check)+ return url+ except Exception as e:+ self.sf.debug("Error encountered parsing: " + str(e))+ continue++ return None++ # If we're looking at hostnames/domains/IPs+ if 'regex' not in malchecks[check]:+ for line in data['content'].split('\n'):+ if line == target or (targetType == "domain" and line == targetDom):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ else:+ # Check for the domain and the hostname+ rxDom = unicode(malchecks[check]['regex']).format(targetDom)+ rxTgt = unicode(malchecks[check]['regex']).format(target)+ for line in data['content'].split('\n'):+ if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \+ re.match(rxTgt, line, re.IGNORECASE):+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ return url+ return None++ def lookupItem(self, resourceId, itemType, target):+ for check in malchecks.keys():+ cid = malchecks[check]['id']+ if cid == resourceId and itemType in malchecks[check]['checks']:+ self.sf.debug("Checking maliciousness of " + target + " (" ++ itemType + ") with: " + cid)+ if malchecks[check]['type'] == "query":+ return self.resourceQuery(cid, target, itemType)+ if malchecks[check]['type'] == "list":+ return self.resourceList(cid, target, itemType)++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + ", already checked.")+ return None+ else:+ self.results.append(eventData)++ if eventName == 'CO_HOSTED_SITE' and not self.opts.get('checkcohosts', False):+ return None+ if eventName == 'AFFILIATE_IPADDR' \+ and not self.opts.get('checkaffiliates', False):+ return None+ if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):+ return None+ if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):+ return None++ for check in malchecks.keys():+ cid = malchecks[check]['id']+ # If the module is enabled..+ if self.opts[cid]:+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ typeId = 'ip'+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['BGP_AS_OWNER', 'BGP_AS_MEMBER']:+ typeId = 'asn'+ evtType = 'MALICIOUS_ASN'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME', ]:+ typeId = 'domain'+ if eventName == "INTERNET_NAME":+ evtType = "MALICIOUS_INTERNET_NAME"+ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'+ if eventName == 'CO_HOSTED_SITE':+ evtType = 'MALICIOUS_COHOST'++ if eventName == 'NETBLOCK_OWNER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_NETBLOCK'+ if eventName == 'NETBLOCK_MEMBER':+ typeId = 'netblock'+ evtType = 'MALICIOUS_SUBNET'++ url = self.lookupItem(cid, typeId, eventData)+ if self.checkForStop():+ return None++ # Notify other modules of what you've found+ if url is not None:+ text = check + " [" + eventData + "]\n" + "<SFURL>" + url + "</SFURL>"+ evt = SpiderFootEvent(evtType, text, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_watchguard classdiff --git a/sfscan.py b/sfscan.pyindex fd2cddb5..6bd3348a 100644--- a/sfscan.py+++ b/sfscan.py@@ -142,14 +142,17 @@ class SpiderFootScanner(threading.Thread):if socksAddr not in address:sock = socks.socksocket()sock.setproxy(socks.PROXY_TYPE_SOCKS5, socksAddr, socksPort)+ sock.settimeout(self.ts.config['_fetchtimeout'])sock.connect(address)return sockelse:sock = socket.socket+ sock.settimeout(self.ts.config['_fetchtimeout'])sock.connect(address)return socksocket.socket = socks.socksocket+ socket.setdefaulttimeout(self.ts.config['_fetchtimeout'])socket.create_connection = _create_connection#socket.getaddrinfo = socks.getaddrinfoself.ts.sf.updateSocket(socket)@@ -159,6 +162,7 @@ class SpiderFootScanner(threading.Thread):# is not reverted to its default state - we still have# the SOCKS version of socket.socket.socket = socket.savedsocket+ socket.setdefaulttimeout(self.ts.config['_fetchtimeout'])socket.create_connection = socket.savedcreate_connection#socket.getaddrinfo = socket.savedgetaddrinfoself.ts.sf.revertSocket()@@ -256,8 +260,14 @@ class SpiderFootScanner(threading.Thread):psMod.notifyListeners(rootEvent)firstEvent = SpiderFootEvent(self.ts.targetType, self.ts.targetValue,"SpiderFoot UI", rootEvent)++ # If in interactive mode, this needs the storeOnly arg.psMod.notifyListeners(firstEvent)+ # If in interactive mode, loop through this shared global variable+ # waiting for inputs, and process them until my status is set to+ # FINISHED.+# Check in case the user requested to stop the scan between modules# initializingfor module in self.ts.moduleInstances.values():