SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.
Python attacksurfacecticybersecurityfootprintinghackinginformation-gatheringinformation-securityinfosecintelligence-gatheringosintosint-frameworkosint-reconnaissanceosint-toolpentestingpythonreconsecurity-toolsthreat-intelligencethreatintel
Updated categories and cleaned formatting.
Steve611e902419a3
diff --git a/modules/__init__.py b/modules/__init__.pyindex d3f5a12f..8b137891 100644--- a/modules/__init__.py+++ b/modules/__init__.py@@ -1 +1 @@-+diff --git a/modules/sfp__stor_db.py b/modules/sfp__stor_db.pyindex 246eda20..d5eee0db 100644--- a/modules/sfp__stor_db.py+++ b/modules/sfp__stor_db.py@@ -1,54 +1,54 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_stor_db-# Purpose: SpiderFoot plug-in for storing events to the local SpiderFoot-# SQLite database.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 14/05/2012-# Copyright: (c) Steve Micallef 2012-# Licence: GPL-# ---------------------------------------------------------------------------------from sflib import SpiderFoot, SpiderFootPlugin---class sfp__stor_db(SpiderFootPlugin):- """Storage::::Stores scan results into the back-end SpiderFoot database. You will need this."""-- # Default options- opts = {- 'maxstorage': 1024 # max bytes for any piece of info stored (0 = unlimited)- }-- # Option descriptions- optdescs = {- 'maxstorage': "Maximum bytes to store for any piece of information retreived (0 = unlimited.)"- }-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- # Because this is a storage plugin, we are interested in everything so we- # can store all events for later analysis.- def watchedEvents(self):- return ["*"]-- # Handle events sent to this module- def handleEvent(self, sfEvent):- if self.opts['maxstorage'] != 0:- if len(sfEvent.data) > self.opts['maxstorage']:- self.sf.debug("Storing an event: " + sfEvent.eventType)- self.__sfdb__.scanEventStore(self.getScanId(), sfEvent, self.opts['maxstorage'])- return None-- self.sf.debug("Storing an event: " + sfEvent.eventType)- self.__sfdb__.scanEventStore(self.getScanId(), sfEvent)---# End of sfp__stor_db class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_stor_db+# Purpose: SpiderFoot plug-in for storing events to the local SpiderFoot+# SQLite database.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 14/05/2012+# Copyright: (c) Steve Micallef 2012+# Licence: GPL+# -------------------------------------------------------------------------------++from sflib import SpiderFoot, SpiderFootPlugin+++class sfp__stor_db(SpiderFootPlugin):+ """Storage::::Stores scan results into the back-end SpiderFoot database. You will need this."""++ # Default options+ opts = {+ 'maxstorage': 1024 # max bytes for any piece of info stored (0 = unlimited)+ }++ # Option descriptions+ optdescs = {+ 'maxstorage': "Maximum bytes to store for any piece of information retreived (0 = unlimited.)"+ }++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ # Because this is a storage plugin, we are interested in everything so we+ # can store all events for later analysis.+ def watchedEvents(self):+ return ["*"]++ # Handle events sent to this module+ def handleEvent(self, sfEvent):+ if self.opts['maxstorage'] != 0:+ if len(sfEvent.data) > self.opts['maxstorage']:+ self.sf.debug("Storing an event: " + sfEvent.eventType)+ self.__sfdb__.scanEventStore(self.getScanId(), sfEvent, self.opts['maxstorage'])+ return None++ self.sf.debug("Storing an event: " + sfEvent.eventType)+ self.__sfdb__.scanEventStore(self.getScanId(), sfEvent)+++# End of sfp__stor_db classdiff --git a/modules/sfp_abusech.py b/modules/sfp_abusech.pyindex 0f85e974..ec40e62d 100644--- a/modules/sfp_abusech.py+++ b/modules/sfp_abusech.py@@ -1,320 +1,321 @@-# -*- 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 class+# -*- 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:Reputation Systems: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_accounts.py b/modules/sfp_accounts.pyindex fe2a39aa..ec477f0a 100644--- a/modules/sfp_accounts.py+++ b/modules/sfp_accounts.py@@ -1,236 +1,237 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_accounts-# Purpose: Identify the existence of a given acount on various sites thanks-# to Micah Hoffman's (https://github.com/WebBreacher) list.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 18/02/2015-# Copyright: (c) Steve Micallef 2015-# Licence: GPL-# ---------------------------------------------------------------------------------import time-import threading-import json-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent--class sfp_accounts(SpiderFootPlugin):- """Accounts:Footprint,Passive:Social:slow:Look for possible associated accounts on nearly 200 websites like Ebay, Slashdot, reddit, etc."""-- # Default options- opts = {- "generic": ["root", "abuse", "sysadm", "sysadmin", "noc", "support", "admin",- "contact", "help", "flame", "test", "info", "sales", "hostmaster"],- "ignorenamedict": True,- "ignoreworddict": True,- "musthavename": True,- "maxthreads": 25- }-- # Option descriptions- optdescs = {- "generic": "Generic internal accounts to not bother looking up externally.",- "ignorenamedict": "Don't bother looking up names that are just stand-alone first names (too many false positives).",- "ignoreworddict": "Don't bother looking up names that appear in the dictionary.",- "musthavename": "The username must be mentioned on the social media page to consider it valid (helps avoid false positives).",- "maxthreads": "Maximum number of simultaneous threads (one thread per site the account is being checked on.)"- }-- results = dict()- reportedUsers = list()- siteResults = dict()- sites = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()- self.commonNames = list()- self.reportedUsers = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- self.commonNames = set(self.sf.dictnames())- self.words = set(self.sf.dictwords())-- content = self.sf.cacheGet("sfaccounts", 48)- if content is None:- url = "https://raw.githubusercontent.com/WebBreacher/WhatsMyName/master/web_accounts_list.json"- data = self.sf.fetchUrl(url, useragent="SpiderFoot")- if data['content'] is None:- self.sf.error("Unable to fetch " + url, False)- return None- else:- self.sf.cachePut("sfaccounts", data['content'])- content = data['content']-- self.sites = json.loads(content)-- # What events is this module interested in for input- # * = be notified about all events.- def watchedEvents(self):- return ["EMAILADDR", "DOMAIN_NAME"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["USERNAME", "ACCOUNT_EXTERNAL_OWNED",- "ACCOUNT_EXTERNAL_USER_SHARED"]-- def checkSite(self, name, site):- if 'check_uri' not in site:- return None-- url = site['check_uri'].format(account=name)- retname = site['name'] + " (Category: " + site['category'] + ")\n<SFURL>" + \- url + "</SFURL>"-- res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'], noLog=True)-- if not res['content']:- self.siteResults[retname] = False- return-- try:- found = False- site['account_existence_code'] = str(site['account_existence_code'])- if site['account_existence_code']:- if site['account_existence_code'] == res['code']:- found = True- if site['account_missing_code']:- if site['account_missing_code'] == res['code']:- found = False- if site['account_existence_string']:- if site['account_existence_string'] in res['content']:- found = True- if site['account_missing_string']:- if site['account_missing_string'] in res['content']:- found = False- except BaseException:- #self.sf.debug("Error parsing configuration: " + str(site))- found = False-- if found and self.opts['musthavename']:- if name not in res['content']:- found = False-- self.siteResults[retname] = found-- def threadSites(self, name, siteList):- ret = list()- self.siteResults = dict()- running = True- i = 0- t = []-- for site in siteList:- if self.checkForStop():- return None-- self.sf.info("Spawning thread to check site: " + site['name'] + \- " / " + site['check_uri'].format(account=name))- t.append(threading.Thread(name='sfp_accounts_' + site['name'],- target=self.checkSite, args=(name, site)))- t[i].start()- i += 1-- # Block until all threads are finished- while running:- found = False- for rt in threading.enumerate():- if rt.name.startswith("sfp_accounts_"):- found = True-- if not found:- running = False-- time.sleep(2)-- # Return once the scanning has completed- return self.siteResults-- def batchSites(self, name):- i = 0- res = list()- siteList = list()-- for site in self.sites['sites']:- if not site['valid'] or 'check_uri' not in site:- continue- if i >= self.opts['maxthreads']:- data = self.threadSites(name, siteList)- if data == None:- return res-- for ret in data.keys():- if data[ret]:- res.append(ret)- i = 0- siteList = list()-- siteList.append(site)- i += 1-- return res-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- users = list()-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- if eventData not in self.results.keys():- self.results[eventData] = True- else:- return None-- if eventName == "DOMAIN_NAME":- kw = self.sf.domainKeyword(eventData, self.opts['_internettlds'])-- res = self.batchSites(kw)- for site in res:- evt = SpiderFootEvent("ACCOUNT_EXTERNAL_OWNED", site,- self.__name__, event)- self.notifyListeners(evt)- return None-- if eventName == "EMAILADDR":- name = eventData.split("@")[0].lower()- if self.opts['generic'] is list() and name in self.opts['generic']:- self.sf.debug(name + " is a generic account name, skipping.")- return None-- if self.opts['ignorenamedict'] and name in self.commonNames:- self.sf.debug(name + " is found in our name dictionary, skipping.")- return None-- if self.opts['ignoreworddict'] and name in self.words:- self.sf.debug(name + " is found in our word dictionary, skipping.")- return None-- users.append(name)- if "." in name:- # steve.micallef -> smicallef- users.append(str(name[0] + name.split(".")[1]).lower())-- for user in users:- if user not in self.reportedUsers:- evt = SpiderFootEvent("USERNAME", user, self.__name__, event)- self.notifyListeners(evt)- self.reportedUsers.append(user)-- res = self.batchSites(user)-- for site in res:- evt = SpiderFootEvent("ACCOUNT_EXTERNAL_USER_SHARED", site,- self.__name__, event)- self.notifyListeners(evt)--# End of sfp_accounts class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_accounts+# Purpose: Identify the existence of a given acount on various sites thanks+# to Micah Hoffman's (https://github.com/WebBreacher) list.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 18/02/2015+# Copyright: (c) Steve Micallef 2015+# Licence: GPL+# -------------------------------------------------------------------------------++import time+import threading+import json+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++class sfp_accounts(SpiderFootPlugin):+ """Accounts:Footprint,Passive:Social Media:slow:Look for possible associated accounts on nearly 200 websites like Ebay, Slashdot, reddit, etc."""+++ # Default options+ opts = {+ "generic": ["root", "abuse", "sysadm", "sysadmin", "noc", "support", "admin",+ "contact", "help", "flame", "test", "info", "sales", "hostmaster"],+ "ignorenamedict": True,+ "ignoreworddict": True,+ "musthavename": True,+ "maxthreads": 25+ }++ # Option descriptions+ optdescs = {+ "generic": "Generic internal accounts to not bother looking up externally.",+ "ignorenamedict": "Don't bother looking up names that are just stand-alone first names (too many false positives).",+ "ignoreworddict": "Don't bother looking up names that appear in the dictionary.",+ "musthavename": "The username must be mentioned on the social media page to consider it valid (helps avoid false positives).",+ "maxthreads": "Maximum number of simultaneous threads (one thread per site the account is being checked on.)"+ }++ results = dict()+ reportedUsers = list()+ siteResults = dict()+ sites = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()+ self.commonNames = list()+ self.reportedUsers = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ self.commonNames = set(self.sf.dictnames())+ self.words = set(self.sf.dictwords())++ content = self.sf.cacheGet("sfaccounts", 48)+ if content is None:+ url = "https://raw.githubusercontent.com/WebBreacher/WhatsMyName/master/web_accounts_list.json"+ data = self.sf.fetchUrl(url, useragent="SpiderFoot")+ if data['content'] is None:+ self.sf.error("Unable to fetch " + url, False)+ return None+ else:+ self.sf.cachePut("sfaccounts", data['content'])+ content = data['content']++ self.sites = json.loads(content)++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["EMAILADDR", "DOMAIN_NAME"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["USERNAME", "ACCOUNT_EXTERNAL_OWNED",+ "ACCOUNT_EXTERNAL_USER_SHARED"]++ def checkSite(self, name, site):+ if 'check_uri' not in site:+ return None++ url = site['check_uri'].format(account=name)+ retname = site['name'] + " (Category: " + site['category'] + ")\n<SFURL>" + \+ url + "</SFURL>"++ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'], noLog=True)++ if not res['content']:+ self.siteResults[retname] = False+ return++ try:+ found = False+ site['account_existence_code'] = str(site['account_existence_code'])+ if site['account_existence_code']:+ if site['account_existence_code'] == res['code']:+ found = True+ if site['account_missing_code']:+ if site['account_missing_code'] == res['code']:+ found = False+ if site['account_existence_string']:+ if site['account_existence_string'] in res['content']:+ found = True+ if site['account_missing_string']:+ if site['account_missing_string'] in res['content']:+ found = False+ except BaseException:+ #self.sf.debug("Error parsing configuration: " + str(site))+ found = False++ if found and self.opts['musthavename']:+ if name not in res['content']:+ found = False++ self.siteResults[retname] = found++ def threadSites(self, name, siteList):+ ret = list()+ self.siteResults = dict()+ running = True+ i = 0+ t = []++ for site in siteList:+ if self.checkForStop():+ return None++ self.sf.info("Spawning thread to check site: " + site['name'] + \+ " / " + site['check_uri'].format(account=name))+ t.append(threading.Thread(name='sfp_accounts_' + site['name'],+ target=self.checkSite, args=(name, site)))+ t[i].start()+ i += 1++ # Block until all threads are finished+ while running:+ found = False+ for rt in threading.enumerate():+ if rt.name.startswith("sfp_accounts_"):+ found = True++ if not found:+ running = False++ time.sleep(2)++ # Return once the scanning has completed+ return self.siteResults++ def batchSites(self, name):+ i = 0+ res = list()+ siteList = list()++ for site in self.sites['sites']:+ if not site['valid'] or 'check_uri' not in site:+ continue+ if i >= self.opts['maxthreads']:+ data = self.threadSites(name, siteList)+ if data == None:+ return res++ for ret in data.keys():+ if data[ret]:+ res.append(ret)+ i = 0+ siteList = list()++ siteList.append(site)+ i += 1++ return res++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ users = list()++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData not in self.results.keys():+ self.results[eventData] = True+ else:+ return None++ if eventName == "DOMAIN_NAME":+ kw = self.sf.domainKeyword(eventData, self.opts['_internettlds'])++ res = self.batchSites(kw)+ for site in res:+ evt = SpiderFootEvent("ACCOUNT_EXTERNAL_OWNED", site,+ self.__name__, event)+ self.notifyListeners(evt)+ return None++ if eventName == "EMAILADDR":+ name = eventData.split("@")[0].lower()+ if self.opts['generic'] is list() and name in self.opts['generic']:+ self.sf.debug(name + " is a generic account name, skipping.")+ return None++ if self.opts['ignorenamedict'] and name in self.commonNames:+ self.sf.debug(name + " is found in our name dictionary, skipping.")+ return None++ if self.opts['ignoreworddict'] and name in self.words:+ self.sf.debug(name + " is found in our word dictionary, skipping.")+ return None++ users.append(name)+ if "." in name:+ # steve.micallef -> smicallef+ users.append(str(name[0] + name.split(".")[1]).lower())++ for user in users:+ if user not in self.reportedUsers:+ evt = SpiderFootEvent("USERNAME", user, self.__name__, event)+ self.notifyListeners(evt)+ self.reportedUsers.append(user)++ res = self.batchSites(user)++ for site in res:+ evt = SpiderFootEvent("ACCOUNT_EXTERNAL_USER_SHARED", site,+ self.__name__, event)+ self.notifyListeners(evt)++# End of sfp_accounts classdiff --git a/modules/sfp_adblock.py b/modules/sfp_adblock.pyindex 01e813a9..b4ac967a 100644--- a/modules/sfp_adblock.py+++ b/modules/sfp_adblock.py@@ -1,100 +1,101 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_adblock-# Purpose: SpiderFoot plug-in to test if external/internally linked pages-# would be blocked by AdBlock Plus.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 22/09/2014-# Copyright: (c) Steve Micallef 2014-# Licence: GPL-# ---------------------------------------------------------------------------------import adblockparser-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_adblock(SpiderFootPlugin):- """AdBlock Check:Investigate,Passive:Blacklists:errorprone:Check if linked pages would be blocked by AdBlock Plus."""-- # Default options- opts = {- "blocklist": "https://easylist-downloads.adblockplus.org/easylist.txt"- }-- optdescs = {- "blocklist": "AdBlockPlus block list."- }-- results = list()- rules = None- errorState = False-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()- self.rules = None- self.errorState = False-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["LINKED_URL_INTERNAL", "LINKED_URL_EXTERNAL"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["URL_ADBLOCKED_INTERNAL", "URL_ADBLOCKED_EXTERNAL"]-- # 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 self.errorState:- return None-- if self.rules is None:- raw = self.sf.fetchUrl(self.opts['blocklist'], timeout=30)- if raw['content'] is not None:- lines = raw['content'].split('\n')- self.sf.debug("RULE LINES: " + str(len(lines)))- try:- self.rules = adblockparser.AdblockRules(lines)- except BaseException as e:- self.errorState = True- self.sf.error("Parsing error handling AdBlock list: " + str(e), False)- else:- self.errorState = True- self.sf.error("Unable to download AdBlockPlus list: " + self.opts['blocklist'], False)-- if "_EXTERNAL" in eventName:- pagetype = "_EXTERNAL"- else:- pagetype = "_INTERNAL"-- if eventData not in self.results:- self.results.append(eventData)- else:- self.sf.debug("Already checked this page for AdBlock matching, skipping.")- return None-- try:- if self.rules and self.rules.should_block(eventData):- evt = SpiderFootEvent("URL_ADBLOCKED" + pagetype, eventData,- self.__name__, event)- self.notifyListeners(evt)- except BaseException as e:- self.sf.error("Parsing error handling AdBlock list: " + str(e), False)- self.errorState = True-- return None--# End of sfp_adblock class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_adblock+# Purpose: SpiderFoot plug-in to test if external/internally linked pages+# would be blocked by AdBlock Plus.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 22/09/2014+# Copyright: (c) Steve Micallef 2014+# Licence: GPL+# -------------------------------------------------------------------------------++import adblockparser+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_adblock(SpiderFootPlugin):+ """AdBlock Check:Investigate,Passive:Reputation Systems:errorprone:Check if linked pages would be blocked by AdBlock Plus."""+++ # Default options+ opts = {+ "blocklist": "https://easylist-downloads.adblockplus.org/easylist.txt"+ }++ optdescs = {+ "blocklist": "AdBlockPlus block list."+ }++ results = list()+ rules = None+ errorState = False++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()+ self.rules = None+ self.errorState = False++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["LINKED_URL_INTERNAL", "LINKED_URL_EXTERNAL"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["URL_ADBLOCKED_INTERNAL", "URL_ADBLOCKED_EXTERNAL"]++ # 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 self.errorState:+ return None++ if self.rules is None:+ raw = self.sf.fetchUrl(self.opts['blocklist'], timeout=30)+ if raw['content'] is not None:+ lines = raw['content'].split('\n')+ self.sf.debug("RULE LINES: " + str(len(lines)))+ try:+ self.rules = adblockparser.AdblockRules(lines)+ except BaseException as e:+ self.errorState = True+ self.sf.error("Parsing error handling AdBlock list: " + str(e), False)+ else:+ self.errorState = True+ self.sf.error("Unable to download AdBlockPlus list: " + self.opts['blocklist'], False)++ if "_EXTERNAL" in eventName:+ pagetype = "_EXTERNAL"+ else:+ pagetype = "_INTERNAL"++ if eventData not in self.results:+ self.results.append(eventData)+ else:+ self.sf.debug("Already checked this page for AdBlock matching, skipping.")+ return None++ try:+ if self.rules and self.rules.should_block(eventData):+ evt = SpiderFootEvent("URL_ADBLOCKED" + pagetype, eventData,+ self.__name__, event)+ self.notifyListeners(evt)+ except BaseException as e:+ self.sf.error("Parsing error handling AdBlock list: " + str(e), False)+ self.errorState = True++ return None++# End of sfp_adblock classdiff --git a/modules/sfp_ahmia.py b/modules/sfp_ahmia.pyindex e8ae64fe..6f89e540 100644--- a/modules/sfp_ahmia.py+++ b/modules/sfp_ahmia.py@@ -1,110 +1,111 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_ahmia-# Purpose: Searches the Tor search engine 'Ahmia' for content related-# to the domain in question.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 20/06/2017-# Copyright: (c) Steve Micallef 2017-# Licence: GPL-# ---------------------------------------------------------------------------------from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-import re--class sfp_ahmia(SpiderFootPlugin):- """Ahmia:Footprint,Investigate:Search Engines::Search Tor 'Ahmia' search engine for mentions of the target domain."""-- # Default options- opts = {- # We don't bother with pagination as ahmia seems fairly limited in coverage- 'fetchlinks': False- }-- # Option descriptions- optdescs = {- 'fetchlinks': "Fetch the darknet pages (via TOR, if enabled) to verify they mention your target."- }-- # Target- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["DOMAIN_NAME"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["DARKNET_MENTION_URL", "SEARCH_ENGINE_WEB_CONTENT"]-- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if eventData in self.results:- self.sf.debug("Already did a search for " + eventData + ", skipping.")- return None- else:- self.results.append(eventData)-- # Sites hosted on the domain- data = self.sf.fetchUrl("https://ahmia.fi/search/?q=" + eventData,- useragent=self.opts['_useragent'],- timeout=self.opts['_fetchtimeout'])- if data is None or not data.get('content'):- self.sf.info("No results returned from ahmia.fi.")- return None-- if "onion_key" in data['content']:- # Check if we've been asked to stop- if self.checkForStop():- return None-- # Submit the google results for analysis- evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", data['content'],- self.__name__, event)- self.notifyListeners(evt)-- links = re.findall("\<li\s+class=\"result\"\s+href=\"(.*?)\"\s+id=\"onion_key\"\>",- data['content'], re.IGNORECASE | re.DOTALL)-- for link in links:- if link in self.results:- continue- else:- self.results.append(link)- self.sf.debug("Found a darknet mention: " + link)- if self.sf.urlFQDN(link).endswith(".onion"):- if self.checkForStop():- return None- if self.opts['fetchlinks']:- res = self.sf.fetchUrl(link, timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])-- if res['content'] is None:- self.sf.debug("Ignoring " + link + " as no data returned")- continue-- if eventData not in res['content']:- self.sf.debug("Ignoring " + link + " as no mention of " + eventData)- continue- evt = SpiderFootEvent("DARKNET_MENTION_URL", link, self.__name__, event)- self.notifyListeners(evt)- else:- evt = SpiderFootEvent("DARKNET_MENTION_URL", link, self.__name__, event)- self.notifyListeners(evt)---# End of sfp_ahmia class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_ahmia+# Purpose: Searches the Tor search engine 'Ahmia' for content related+# to the domain in question.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 20/06/2017+# Copyright: (c) Steve Micallef 2017+# Licence: GPL+# -------------------------------------------------------------------------------++from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+import re++class sfp_ahmia(SpiderFootPlugin):+ """Ahmia:Footprint,Investigate:Search Engines::Search Tor 'Ahmia' search engine for mentions of the target domain."""+++ # Default options+ opts = {+ # We don't bother with pagination as ahmia seems fairly limited in coverage+ 'fetchlinks': False+ }++ # Option descriptions+ optdescs = {+ 'fetchlinks': "Fetch the darknet pages (via TOR, if enabled) to verify they mention your target."+ }++ # Target+ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["DOMAIN_NAME"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["DARKNET_MENTION_URL", "SEARCH_ENGINE_WEB_CONTENT"]++ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if eventData in self.results:+ self.sf.debug("Already did a search for " + eventData + ", skipping.")+ return None+ else:+ self.results.append(eventData)++ # Sites hosted on the domain+ data = self.sf.fetchUrl("https://ahmia.fi/search/?q=" + eventData,+ useragent=self.opts['_useragent'],+ timeout=self.opts['_fetchtimeout'])+ if data is None or not data.get('content'):+ self.sf.info("No results returned from ahmia.fi.")+ return None++ if "onion_key" in data['content']:+ # Check if we've been asked to stop+ if self.checkForStop():+ return None++ # Submit the google results for analysis+ evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", data['content'],+ self.__name__, event)+ self.notifyListeners(evt)++ links = re.findall("\<li\s+class=\"result\"\s+href=\"(.*?)\"\s+id=\"onion_key\"\>",+ data['content'], re.IGNORECASE | re.DOTALL)++ for link in links:+ if link in self.results:+ continue+ else:+ self.results.append(link)+ self.sf.debug("Found a darknet mention: " + link)+ if self.sf.urlFQDN(link).endswith(".onion"):+ if self.checkForStop():+ return None+ if self.opts['fetchlinks']:+ res = self.sf.fetchUrl(link, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])++ if res['content'] is None:+ self.sf.debug("Ignoring " + link + " as no data returned")+ continue++ if eventData not in res['content']:+ self.sf.debug("Ignoring " + link + " as no mention of " + eventData)+ continue+ evt = SpiderFootEvent("DARKNET_MENTION_URL", link, self.__name__, event)+ self.notifyListeners(evt)+ else:+ evt = SpiderFootEvent("DARKNET_MENTION_URL", link, self.__name__, event)+ self.notifyListeners(evt)+++# End of sfp_ahmia classdiff --git a/modules/sfp_alienvault.py b/modules/sfp_alienvault.pyindex 57a62610..6c0178aa 100644--- a/modules/sfp_alienvault.py+++ b/modules/sfp_alienvault.py@@ -18,7 +18,8 @@ from netaddr import IPNetworkfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEventclass sfp_alienvault(SpiderFootPlugin):- """AlienVault OTX:Investigate,Passive:Blacklists:apikey:Obtain information from AlienVault Open Threat Exchange (OTX)"""+ """AlienVault OTX:Investigate,Passive:Reputation Systems:apikey:Obtain information from AlienVault Open Threat Exchange (OTX)"""+# Default optionsopts = {diff --git a/modules/sfp_alienvaultiprep.py b/modules/sfp_alienvaultiprep.pyindex 8dd03748..f601a5ff 100644--- a/modules/sfp_alienvaultiprep.py+++ b/modules/sfp_alienvaultiprep.py@@ -1,267 +1,268 @@-# -*- 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 class+# -*- 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:Reputation Systems: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_archiveorg.py b/modules/sfp_archiveorg.pyindex 7b8b9df3..585ec1ac 100644--- a/modules/sfp_archiveorg.py+++ b/modules/sfp_archiveorg.py@@ -1,151 +1,152 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_archiveorg-# Purpose: Queries archive.org (Wayback machine) for historic versions of-# certain pages.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 20/07/2015-# Copyright: (c) Steve Micallef 2015-# Licence: GPL-# ---------------------------------------------------------------------------------import re-import urllib-import datetime-import time-import json-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_archiveorg(SpiderFootPlugin):- """Archive.org:Footprint:Search Engines:slow:Identifies historic versions of interesting files/pages from the Wayback Machine."""-- # Default options- opts = {- 'farback': "30,60,90",- 'intfiles': True,- 'passwordpages': True,- 'formpages': False,- 'flashpages': False,- 'javapages': False,- 'staticpages': False,- 'uploadpages': False,- 'webframeworkpages': False,- 'javascriptpages': False- }-- # Option descriptions- optdescs = {- 'farback': "Number of days back to look for older versions of files/pages in the Wayback Machine snapshots. Comma-separate the values, so for example 30,60,90 means to look for snapshots 30 days, 60 days and 90 days back.",- 'intfiles': "Query the Wayback Machine for historic versions of Interesting Files.",- 'passwordpages': "Query the Wayback Machine for historic versions of URLs with passwords.",- 'formpages': "Query the Wayback Machine for historic versions of URLs with forms.",- 'uploadpages': "Query the Wayback Machine for historic versions of URLs accepting uploads.",- 'flashpages': "Query the Wayback Machine for historic versions of URLs containing Flash.",- 'javapages': "Query the Wayback Machine for historic versions of URLs using Java Applets.",- 'staticpages': "Query the Wayback Machine for historic versions of purely static URLs.",- "webframeworkpages": "Query the Wayback Machine for historic versions of URLs using Javascript frameworks.",- "javascriptpages": "Query the Wayback Machine for historic versions of URLs using Javascript."- }-- results = list()- foundDates = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()- self.foundDates = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["INTERESTING_FILE", "URL_PASSWORD", "URL_FORM", "URL_FLASH",- "URL_STATIC", "URL_JAVA_APPLET", "URL_UPLOAD", "URL_JAVASCRIPT",- "URL_WEB_FRAMEWORK"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["INTERESTING_FILE_HISTORIC", "URL_PASSWORD_HISTORIC",- "URL_FORM_HISTORIC", "URL_FLASH_HISTORIC",- "URL_STATIC_HISTORIC", "URL_JAVA_APPLET_HISTORIC",- "URL_UPLOAD_HISTORIC", "URL_WEB_FRAMEWORK_HISTORIC",- "URL_JAVASCRIPT_HISTORIC"]-- # 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 eventName == "INTERESTING_FILE" and not self.opts['intfiles']:- return None- if eventName == "URL_PASSWORD" and not self.opts['passwordpages']:- return None- if eventName == "URL_STATIC" and not self.opts['staticpages']:- return None- if eventName == "URL_FORM" and not self.opts['formpages']:- return None- if eventName == "URL_UPLOAD" and not self.opts['uploadpages']:- return None- if eventName == "URL_JAVA_APPLET" and not self.opts['javapages']:- return None- if eventName == "URL_FLASH" and not self.opts['flashpages']:- return None- if eventName == "URL_JAVASCRIPT" and not self.opts['javascriptpages']:- return None- if eventName == "URL_WEB_FRAMEWORK" and not self.opts['webframeworkpages']:- return None-- if eventData in self.results:- return None- else:- self.results.append(eventData)-- for daysback in self.opts['farback'].split(","):- newDate = datetime.datetime.now() - datetime.timedelta(days=int(daysback))- maxDate = newDate.strftime("%Y%m%d")-- url = "http://archive.org/wayback/available?url=" + eventData + \- "×tamp=" + maxDate- res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])-- if res['content'] == None:- self.sf.error("Unable to fetch " + url, False)- continue-- try:- ret = json.loads(res['content'])- except BaseException as e:- ret = None-- if ret == None:- self.sf.error("Unable to process empty response from archive.org: " + \- eventData, False)- continue-- if len(ret['archived_snapshots']) < 1:- self.sf.debug("No archived snapshots for " + eventData)- continue-- wbmlink = ret['archived_snapshots']['closest']['url']- if wbmlink in self.foundDates:- self.sf.debug("Snapshot already fetched.")- continue-- self.foundDates.append(wbmlink)- name = eventName + "_HISTORIC"-- self.sf.info("Found a historic file: " + wbmlink)- evt = SpiderFootEvent(name, wbmlink, self.__name__, event)- self.notifyListeners(evt)--# End of sfp_archiveorg class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_archiveorg+# Purpose: Queries archive.org (Wayback machine) for historic versions of+# certain pages.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 20/07/2015+# Copyright: (c) Steve Micallef 2015+# Licence: GPL+# -------------------------------------------------------------------------------++import re+import urllib+import datetime+import time+import json+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_archiveorg(SpiderFootPlugin):+ """Archive.org:Footprint:Search Engines:slow:Identifies historic versions of interesting files/pages from the Wayback Machine."""+++ # Default options+ opts = {+ 'farback': "30,60,90",+ 'intfiles': True,+ 'passwordpages': True,+ 'formpages': False,+ 'flashpages': False,+ 'javapages': False,+ 'staticpages': False,+ 'uploadpages': False,+ 'webframeworkpages': False,+ 'javascriptpages': False+ }++ # Option descriptions+ optdescs = {+ 'farback': "Number of days back to look for older versions of files/pages in the Wayback Machine snapshots. Comma-separate the values, so for example 30,60,90 means to look for snapshots 30 days, 60 days and 90 days back.",+ 'intfiles': "Query the Wayback Machine for historic versions of Interesting Files.",+ 'passwordpages': "Query the Wayback Machine for historic versions of URLs with passwords.",+ 'formpages': "Query the Wayback Machine for historic versions of URLs with forms.",+ 'uploadpages': "Query the Wayback Machine for historic versions of URLs accepting uploads.",+ 'flashpages': "Query the Wayback Machine for historic versions of URLs containing Flash.",+ 'javapages': "Query the Wayback Machine for historic versions of URLs using Java Applets.",+ 'staticpages': "Query the Wayback Machine for historic versions of purely static URLs.",+ "webframeworkpages": "Query the Wayback Machine for historic versions of URLs using Javascript frameworks.",+ "javascriptpages": "Query the Wayback Machine for historic versions of URLs using Javascript."+ }++ results = list()+ foundDates = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()+ self.foundDates = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["INTERESTING_FILE", "URL_PASSWORD", "URL_FORM", "URL_FLASH",+ "URL_STATIC", "URL_JAVA_APPLET", "URL_UPLOAD", "URL_JAVASCRIPT",+ "URL_WEB_FRAMEWORK"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["INTERESTING_FILE_HISTORIC", "URL_PASSWORD_HISTORIC",+ "URL_FORM_HISTORIC", "URL_FLASH_HISTORIC",+ "URL_STATIC_HISTORIC", "URL_JAVA_APPLET_HISTORIC",+ "URL_UPLOAD_HISTORIC", "URL_WEB_FRAMEWORK_HISTORIC",+ "URL_JAVASCRIPT_HISTORIC"]++ # 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 eventName == "INTERESTING_FILE" and not self.opts['intfiles']:+ return None+ if eventName == "URL_PASSWORD" and not self.opts['passwordpages']:+ return None+ if eventName == "URL_STATIC" and not self.opts['staticpages']:+ return None+ if eventName == "URL_FORM" and not self.opts['formpages']:+ return None+ if eventName == "URL_UPLOAD" and not self.opts['uploadpages']:+ return None+ if eventName == "URL_JAVA_APPLET" and not self.opts['javapages']:+ return None+ if eventName == "URL_FLASH" and not self.opts['flashpages']:+ return None+ if eventName == "URL_JAVASCRIPT" and not self.opts['javascriptpages']:+ return None+ if eventName == "URL_WEB_FRAMEWORK" and not self.opts['webframeworkpages']:+ return None++ if eventData in self.results:+ return None+ else:+ self.results.append(eventData)++ for daysback in self.opts['farback'].split(","):+ newDate = datetime.datetime.now() - datetime.timedelta(days=int(daysback))+ maxDate = newDate.strftime("%Y%m%d")++ url = "http://archive.org/wayback/available?url=" + eventData + \+ "×tamp=" + maxDate+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])++ if res['content'] == None:+ self.sf.error("Unable to fetch " + url, False)+ continue++ try:+ ret = json.loads(res['content'])+ except BaseException as e:+ ret = None++ if ret == None:+ self.sf.error("Unable to process empty response from archive.org: " + \+ eventData, False)+ continue++ if len(ret['archived_snapshots']) < 1:+ self.sf.debug("No archived snapshots for " + eventData)+ continue++ wbmlink = ret['archived_snapshots']['closest']['url']+ if wbmlink in self.foundDates:+ self.sf.debug("Snapshot already fetched.")+ continue++ self.foundDates.append(wbmlink)+ name = eventName + "_HISTORIC"++ self.sf.info("Found a historic file: " + wbmlink)+ evt = SpiderFootEvent(name, wbmlink, self.__name__, event)+ self.notifyListeners(evt)++# End of sfp_archiveorg classdiff --git a/modules/sfp_badipscom.py b/modules/sfp_badipscom.pyindex 9dd55a87..cca83173 100644--- a/modules/sfp_badipscom.py+++ b/modules/sfp_badipscom.py@@ -1,268 +1,269 @@-# -*- 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 class+# -*- 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:Reputation Systems: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_base64.py b/modules/sfp_base64.pyindex a2f9eb58..abec2bef 100644--- a/modules/sfp_base64.py+++ b/modules/sfp_base64.py@@ -1,78 +1,79 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_base64-# Purpose: Identifies (best-effort) Base64-encoded strings in content and URLs.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 31/01/2017-# Copyright: (c) Steve Micallef 2017-# ---------------------------------------------------------------------------------import base64-import re-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_base64(SpiderFootPlugin):- """Base64:Investigate:Data Analysis::Identify Base64-encoded strings in any content and URLs, often revealing interesting hidden information."""-- # Default options- opts = {- 'minlength': 10- }-- # Option descriptions- optdescs = {- 'minlength': "The minimum length a string that looks like a base64-encoded string needs to be."- }-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["LINKED_URL_INTERNAL", "TARGET_WEB_CONTENT"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["BASE64_DATA"]-- # 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)-- pat = re.compile("([A-Za-z0-9+\/]+\=\=|[A-Za-z0-9+\/]+\=)")- m = re.findall(pat, eventData)- for match in m:- minlen = int(self.opts['minlength'])- if len(match) >= minlen:- caps = sum(1 for c in match if c.isupper())- # Base64-encoded strings don't look like normal strings- if caps < (minlen/4):- return None- self.sf.info("Found Base64 string: " + match)- if type(match) == str:- string = unicode(match, 'utf-8', errors='replace')- else:- string = match-- try:- string += " (" + base64.b64decode(match) + ")"- evt = SpiderFootEvent("BASE64_DATA", string, self.__name__, event)- self.notifyListeners(evt)- except BaseException as e:- self.sf.debug("Unable to base64-decode a string.")-- return None--# End of sfp_base64 class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_base64+# Purpose: Identifies (best-effort) Base64-encoded strings in content and URLs.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 31/01/2017+# Copyright: (c) Steve Micallef 2017+# -------------------------------------------------------------------------------++import base64+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_base64(SpiderFootPlugin):+ """Base64:Investigate:Content Analysis::Identify Base64-encoded strings in any content and URLs, often revealing interesting hidden information."""+++ # Default options+ opts = {+ 'minlength': 10+ }++ # Option descriptions+ optdescs = {+ 'minlength': "The minimum length a string that looks like a base64-encoded string needs to be."+ }++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["LINKED_URL_INTERNAL", "TARGET_WEB_CONTENT"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["BASE64_DATA"]++ # 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)++ pat = re.compile("([A-Za-z0-9+\/]+\=\=|[A-Za-z0-9+\/]+\=)")+ m = re.findall(pat, eventData)+ for match in m:+ minlen = int(self.opts['minlength'])+ if len(match) >= minlen:+ caps = sum(1 for c in match if c.isupper())+ # Base64-encoded strings don't look like normal strings+ if caps < (minlen/4):+ return None+ self.sf.info("Found Base64 string: " + match)+ if type(match) == str:+ string = unicode(match, 'utf-8', errors='replace')+ else:+ string = match++ try:+ string += " (" + base64.b64decode(match) + ")"+ evt = SpiderFootEvent("BASE64_DATA", string, self.__name__, event)+ self.notifyListeners(evt)+ except BaseException as e:+ self.sf.debug("Unable to base64-decode a string.")++ return None++# End of sfp_base64 classdiff --git a/modules/sfp_bingsearch.py b/modules/sfp_bingsearch.pyindex 31fa3d3e..fd669841 100644--- a/modules/sfp_bingsearch.py+++ b/modules/sfp_bingsearch.py@@ -1,101 +1,102 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_bingsearch-# Purpose: Searches Bing for content related to the domain in question.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 06/10/2013-# Copyright: (c) Steve Micallef 2013-# Licence: GPL-# ---------------------------------------------------------------------------------from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_bingsearch(SpiderFootPlugin):- """Bing:Footprint,Investigate,Passive:Search Engines:errorprone:Some light Bing scraping to identify sub-domains and links."""-- # Default options- opts = {- 'pages': 20 # Number of bing results pages to iterate- }-- # Option descriptions- optdescs = {- 'pages': "Number of Bing results pages to iterate through."- }-- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["INTERNET_NAME"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["LINKED_URL_INTERNAL", "SEARCH_ENGINE_WEB_CONTENT"]-- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if eventData in self.results:- self.sf.debug("Already did a search for " + eventData + ", skipping.")- return None- else:- self.results.append(eventData)-- # Sites hosted on the domain- pages = self.sf.bingIterate("site:" + eventData, dict(limit=self.opts['pages'],- useragent=self.opts['_useragent'],- timeout=self.opts['_fetchtimeout']))- if pages is None:- self.sf.info("No results returned from Bing.")- return None-- for page in pages.keys():- found = False- if page in self.results:- continue- else:- self.results.append(page)-- links = self.sf.parseLinks(page, pages[page], eventData)- if len(links) == 0:- continue-- for link in links:- if self.checkForStop():- return None-- if link in self.results:- continue- else:- self.results.append(link)- if self.sf.urlFQDN(link).endswith(eventData):- found = True- self.sf.debug("Found a link: " + link)-- evt = SpiderFootEvent("LINKED_URL_INTERNAL", link,- self.__name__, event)- self.notifyListeners(evt)-- if found:- # Submit the bing results for analysis- evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", pages[page],- self.__name__, event)- self.notifyListeners(evt)---# End of sfp_bingsearch class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_bingsearch+# Purpose: Searches Bing for content related to the domain in question.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 06/10/2013+# Copyright: (c) Steve Micallef 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_bingsearch(SpiderFootPlugin):+ """Bing:Footprint,Investigate,Passive:Search Engines:errorprone:Some light Bing scraping to identify sub-domains and links."""+++ # Default options+ opts = {+ 'pages': 20 # Number of bing results pages to iterate+ }++ # Option descriptions+ optdescs = {+ 'pages': "Number of Bing results pages to iterate through."+ }++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["INTERNET_NAME"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["LINKED_URL_INTERNAL", "SEARCH_ENGINE_WEB_CONTENT"]++ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if eventData in self.results:+ self.sf.debug("Already did a search for " + eventData + ", skipping.")+ return None+ else:+ self.results.append(eventData)++ # Sites hosted on the domain+ pages = self.sf.bingIterate("site:" + eventData, dict(limit=self.opts['pages'],+ useragent=self.opts['_useragent'],+ timeout=self.opts['_fetchtimeout']))+ if pages is None:+ self.sf.info("No results returned from Bing.")+ return None++ for page in pages.keys():+ found = False+ if page in self.results:+ continue+ else:+ self.results.append(page)++ links = self.sf.parseLinks(page, pages[page], eventData)+ if len(links) == 0:+ continue++ for link in links:+ if self.checkForStop():+ return None++ if link in self.results:+ continue+ else:+ self.results.append(link)+ if self.sf.urlFQDN(link).endswith(eventData):+ found = True+ self.sf.debug("Found a link: " + link)++ evt = SpiderFootEvent("LINKED_URL_INTERNAL", link,+ self.__name__, event)+ self.notifyListeners(evt)++ if found:+ # Submit the bing results for analysis+ evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", pages[page],+ self.__name__, event)+ self.notifyListeners(evt)+++# End of sfp_bingsearch classdiff --git a/modules/sfp_bingsharedip.py b/modules/sfp_bingsharedip.pyindex fef50d00..cd2724ba 100644--- a/modules/sfp_bingsharedip.py+++ b/modules/sfp_bingsharedip.py@@ -1,133 +1,134 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_bingsharedip-# Purpose: Searches Bing for hosts sharing the same IP.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 12/04/2014-# Copyright: (c) Steve Micallef 2014-# Licence: GPL-# ---------------------------------------------------------------------------------import re-import socket-from netaddr import IPNetwork-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_bingsharedip(SpiderFootPlugin):- """Bing (Shared IPs):Footprint,Investigate,Passive:Networking:errorprone:Search Bing for hosts sharing the same IP."""-- # Default options- opts = {- 'cohostsamedomain': False,- 'pages': 20,- 'verify': True- }-- # Option descriptions- optdescs = {- 'cohostsamedomain': "Treat co-hosted sites on the same target domain as co-hosting?",- 'pages': "How many pages of results to iterate through.",- 'verify': "Verify co-hosts are valid by checking if they still resolve to the shared IP."- }-- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["IP_ADDRESS", "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 ["CO_HOSTED_SITE", "SEARCH_ENGINE_WEB_CONTENT"]-- def validateIP(self, host, ip):- try:- addrs = socket.gethostbyname_ex(host)- except BaseException as e:- self.sf.debug("Unable to resolve " + host + ": " + str(e))- return False-- for addr in addrs:- if type(addr) == list:- for a in addr:- if str(a) == ip:- return True- else:- if str(addr) == ip:- return True- return False-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- self.currentEventSrc = event-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- # Don't look up stuff twice- if eventData in self.results:- self.sf.debug("Skipping " + eventData + " as already mapped.")- return None-- qrylist = list()- if eventName.startswith("NETBLOCK_"):- for ipaddr in IPNetwork(eventData):- if str(ipaddr) not in self.results:- qrylist.append(str(ipaddr))- self.results.append(str(ipaddr))- else:- qrylist.append(eventData)- self.results.append(eventData)-- myres = list()-- for ip in qrylist:- if self.checkForStop():- return None-- results = self.sf.bingIterate("ip:" + ip, dict(limit=self.opts['pages'],- useragent=self.opts['_useragent'],- timeout=self.opts['_fetchtimeout']))- if results is None:- self.sf.info("No data returned from Bing.")- continue-- for key in results.keys():- res = results[key]- pat = re.compile("<h2><a href=\"(\S+)\"", re.IGNORECASE)- matches = re.findall(pat, res)- for match in matches:- self.sf.info("Found something on same IP: " + match)- site = self.sf.urlFQDN(match.lower())- if site not in myres and site != ip:- if not self.opts['cohostsamedomain']:- if self.getTarget().matches(site, includeParents=True):- self.sf.debug("Skipping " + site + " because it is on the same domain.")- continue- if self.opts['verify'] and not self.validateIP(site, ip):- self.sf.debug("Host no longer resolves to our IP.")- continue- evt = SpiderFootEvent("CO_HOSTED_SITE", site, self.__name__, event)- self.notifyListeners(evt)- myres.append(site)-- # Submit the bing results for analysis- evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", results[key],- self.__name__, event)- self.notifyListeners(evt)--# End of sfp_bingsharedip class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_bingsharedip+# Purpose: Searches Bing for hosts sharing the same IP.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 12/04/2014+# Copyright: (c) Steve Micallef 2014+# Licence: GPL+# -------------------------------------------------------------------------------++import re+import socket+from netaddr import IPNetwork+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_bingsharedip(SpiderFootPlugin):+ """Bing (Shared IPs):Footprint,Investigate,Passive:Search Engines:errorprone:Search Bing for hosts sharing the same IP."""+++ # Default options+ opts = {+ 'cohostsamedomain': False,+ 'pages': 20,+ 'verify': True+ }++ # Option descriptions+ optdescs = {+ 'cohostsamedomain': "Treat co-hosted sites on the same target domain as co-hosting?",+ 'pages': "How many pages of results to iterate through.",+ 'verify': "Verify co-hosts are valid by checking if they still resolve to the shared IP."+ }++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["IP_ADDRESS", "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 ["CO_HOSTED_SITE", "SEARCH_ENGINE_WEB_CONTENT"]++ def validateIP(self, host, ip):+ try:+ addrs = socket.gethostbyname_ex(host)+ except BaseException as e:+ self.sf.debug("Unable to resolve " + host + ": " + str(e))+ return False++ for addr in addrs:+ if type(addr) == list:+ for a in addr:+ if str(a) == ip:+ return True+ else:+ if str(addr) == ip:+ return True+ return False++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ self.currentEventSrc = event++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ # Don't look up stuff twice+ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + " as already mapped.")+ return None++ qrylist = list()+ if eventName.startswith("NETBLOCK_"):+ for ipaddr in IPNetwork(eventData):+ if str(ipaddr) not in self.results:+ qrylist.append(str(ipaddr))+ self.results.append(str(ipaddr))+ else:+ qrylist.append(eventData)+ self.results.append(eventData)++ myres = list()++ for ip in qrylist:+ if self.checkForStop():+ return None++ results = self.sf.bingIterate("ip:" + ip, dict(limit=self.opts['pages'],+ useragent=self.opts['_useragent'],+ timeout=self.opts['_fetchtimeout']))+ if results is None:+ self.sf.info("No data returned from Bing.")+ continue++ for key in results.keys():+ res = results[key]+ pat = re.compile("<h2><a href=\"(\S+)\"", re.IGNORECASE)+ matches = re.findall(pat, res)+ for match in matches:+ self.sf.info("Found something on same IP: " + match)+ site = self.sf.urlFQDN(match.lower())+ if site not in myres and site != ip:+ if not self.opts['cohostsamedomain']:+ if self.getTarget().matches(site, includeParents=True):+ self.sf.debug("Skipping " + site + " because it is on the same domain.")+ continue+ if self.opts['verify'] and not self.validateIP(site, ip):+ self.sf.debug("Host no longer resolves to our IP.")+ continue+ evt = SpiderFootEvent("CO_HOSTED_SITE", site, self.__name__, event)+ self.notifyListeners(evt)+ myres.append(site)++ # Submit the bing results for analysis+ evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", results[key],+ self.__name__, event)+ self.notifyListeners(evt)++# End of sfp_bingsharedip classdiff --git a/modules/sfp_binstring.py b/modules/sfp_binstring.pyindex fcc6d603..fe23db2f 100644--- a/modules/sfp_binstring.py+++ b/modules/sfp_binstring.py@@ -1,142 +1,143 @@-# coding: utf-8-# --------------------------------------------------------------------------------# Name: sfp_binstring-# Purpose: Identify strings in binary content.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 03/12/2016-# Copyright: (c) Steve Micallef-# Licence: GPL-# ---------------------------------------------------------------------------------import re-import string-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent--class sfp_binstring(SpiderFootPlugin):- """Binary String Extractor:Footprint:Data Analysis:errorprone:Attempt to identify strings in binary content."""-- # Default options- opts = {- 'minwordsize': 5,- 'maxwords': 100,- 'maxfilesize': 1000000,- 'usedict': True,- 'fileexts': ['png', 'gif', 'jpg', 'jpeg', 'tiff', 'tif',- 'ico', 'flv', 'mp4', 'mp3', 'avi', 'mpg',- 'mpeg', 'dat', 'mov', 'swf', 'exe', 'bin'],- 'filterchars': '#}{|%^&*()=+,;[]~'- }-- # Option descriptions- optdescs = {- 'minwordsize': "Upon finding a string in a binary, ensure it is at least this length. Helps weed out false positives.",- 'usedict': "Use the dictionary to further reduce false positives - any string found must contain a word from the dictionary (can be very slow, especially for larger files).",- 'fileexts': "File types to fetch and analyse.",- 'maxfilesize': "Maximum file size in bytes to download for analysis.",- 'maxwords': "Stop reporting strings from a single binary after this many are found.",- 'filterchars': "Ignore strings with these characters, as they may just be garbage ASCII."- }-- results = list()- d = None- n = None- fq = None-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- self.d = set(self.sf.dictwords())-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- def getStrings(self, content):- words = list()- result = ""-- if not content:- return None-- for c in content:- if len(words) >= self.opts['maxwords']:- break- if c in string.printable and c not in string.whitespace:- result += c- continue- if len(result) >= self.opts['minwordsize']:- if self.opts['usedict']:- accept = False- for w in self.d:- if result.startswith(w) or result.endswith(w):- accept = True- break-- if self.opts['filterchars']:- accept = True- for x in self.opts['filterchars']:- if x in result:- accept = False- break-- if not self.opts['filterchars'] and not self.opts['usedict']:- accept = True-- if accept:- words.append(result)-- result = ""-- if len(words) == 0:- return None-- return words-- # What events is this module interested in for input- # * = be notified about all events.- def watchedEvents(self):- return ["LINKED_URL_INTERNAL"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["RAW_FILE_META_DATA"]-- # 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:- return None- else:- self.results.append(eventData)-- # if the file matches any of the file extensions we are interested in- # then fetch the file and write it to aa temporary place- res = None- for fileExt in self.opts['fileexts']:- if eventData.lower().endswith("." + fileExt.lower()) or "." + fileExt + "?" in eventData.lower():- res = self.sf.fetchUrl(eventData,- useragent=self.opts['_useragent'],- dontMangle=True,- sizeLimit=self.opts['maxfilesize'])-- if res:- self.sf.debug("Searching for strings")- words = self.getStrings(res['content'])-- if words:- wordstr = '\n'.join(words[0:self.opts['maxwords']])-- # Notify other modules of what you've found- evt = SpiderFootEvent("RAW_FILE_META_DATA", wordstr, self.__name__, event)- self.notifyListeners(evt)--# End of sfp_binstring class+# coding: utf-8+# -------------------------------------------------------------------------------+# Name: sfp_binstring+# Purpose: Identify strings in binary content.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 03/12/2016+# Copyright: (c) Steve Micallef+# Licence: GPL+# -------------------------------------------------------------------------------++import re+import string+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++class sfp_binstring(SpiderFootPlugin):+ """Binary String Extractor:Footprint:Content Analysis:errorprone:Attempt to identify strings in binary content."""+++ # Default options+ opts = {+ 'minwordsize': 5,+ 'maxwords': 100,+ 'maxfilesize': 1000000,+ 'usedict': True,+ 'fileexts': ['png', 'gif', 'jpg', 'jpeg', 'tiff', 'tif',+ 'ico', 'flv', 'mp4', 'mp3', 'avi', 'mpg',+ 'mpeg', 'dat', 'mov', 'swf', 'exe', 'bin'],+ 'filterchars': '#}{|%^&*()=+,;[]~'+ }++ # Option descriptions+ optdescs = {+ 'minwordsize': "Upon finding a string in a binary, ensure it is at least this length. Helps weed out false positives.",+ 'usedict': "Use the dictionary to further reduce false positives - any string found must contain a word from the dictionary (can be very slow, especially for larger files).",+ 'fileexts': "File types to fetch and analyse.",+ 'maxfilesize': "Maximum file size in bytes to download for analysis.",+ 'maxwords': "Stop reporting strings from a single binary after this many are found.",+ 'filterchars': "Ignore strings with these characters, as they may just be garbage ASCII."+ }++ results = list()+ d = None+ n = None+ fq = None++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ self.d = set(self.sf.dictwords())++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ def getStrings(self, content):+ words = list()+ result = ""++ if not content:+ return None++ for c in content:+ if len(words) >= self.opts['maxwords']:+ break+ if c in string.printable and c not in string.whitespace:+ result += c+ continue+ if len(result) >= self.opts['minwordsize']:+ if self.opts['usedict']:+ accept = False+ for w in self.d:+ if result.startswith(w) or result.endswith(w):+ accept = True+ break++ if self.opts['filterchars']:+ accept = True+ for x in self.opts['filterchars']:+ if x in result:+ accept = False+ break++ if not self.opts['filterchars'] and not self.opts['usedict']:+ accept = True++ if accept:+ words.append(result)++ result = ""++ if len(words) == 0:+ return None++ return words++ # What events is this module interested in for input+ # * = be notified about all events.+ def watchedEvents(self):+ return ["LINKED_URL_INTERNAL"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["RAW_FILE_META_DATA"]++ # 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:+ return None+ else:+ self.results.append(eventData)++ # if the file matches any of the file extensions we are interested in+ # then fetch the file and write it to aa temporary place+ res = None+ for fileExt in self.opts['fileexts']:+ if eventData.lower().endswith("." + fileExt.lower()) or "." + fileExt + "?" in eventData.lower():+ res = self.sf.fetchUrl(eventData,+ useragent=self.opts['_useragent'],+ dontMangle=True,+ sizeLimit=self.opts['maxfilesize'])++ if res:+ self.sf.debug("Searching for strings")+ words = self.getStrings(res['content'])++ if words:+ wordstr = '\n'.join(words[0:self.opts['maxwords']])++ # Notify other modules of what you've found+ evt = SpiderFootEvent("RAW_FILE_META_DATA", wordstr, self.__name__, event)+ self.notifyListeners(evt)++# End of sfp_binstring classdiff --git a/modules/sfp_bitcash.py b/modules/sfp_bitcash.pyindex 14da5241..716a49a4 100644--- a/modules/sfp_bitcash.py+++ b/modules/sfp_bitcash.py@@ -1,263 +1,264 @@-# -*- 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 class+# -*- 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:Reputation Systems: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_bitcoin.py b/modules/sfp_bitcoin.pyindex 4ab1ee47..e07a1aff 100644--- a/modules/sfp_bitcoin.py+++ b/modules/sfp_bitcoin.py@@ -1,86 +1,87 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_bitcoin-# Purpose: SpiderFoot plug-in for scanning retreived content by other-# modules (such as sfp_spider) and identifying bitcoin numbers.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 27/05/2017-# Copyright: (c) Steve Micallef 2017-# Licence: GPL-# ---------------------------------------------------------------------------------try:- import re2 as re-except ImportError:- import re-from hashlib import sha256-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent--class sfp_bitcoin(SpiderFootPlugin):- """Bitcoin Finder:Footprint,Investigate:Social::Identify bitcoin addresses in scraped webpages."""-- # Default options- opts = {}-- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["TARGET_WEB_CONTENT"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["BITCOIN_ADDRESS"]-- def to_bytes(self, n, length):- h = '%x' % n- s = ('0'*(len(h) % 2) + h).zfill(length*2).decode('hex')- return s-- def decode_base58(self, bc, length):- digits58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'- n = 0- for char in bc:- n = n * 58 + digits58.index(char)- return self.to_bytes(n, length)-- def check_bc(self, bc):- bcbytes = self.decode_base58(bc, 25)- return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4]-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- sourceData = self.sf.hashstring(eventData)-- if sourceData in self.results:- return None- else:- self.results.append(sourceData)-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- # thanks to https://stackoverflow.com/questions/21683680/regex-to-match-bitcoin-addresses- matches = re.findall("[\s:=\>]([13][a-km-zA-HJ-NP-Z1-9]{25,34})", eventData)- for m in matches:- self.sf.debug("Bitcoin potential match: " + m)- if self.check_bc(m):- evt = SpiderFootEvent("BITCOIN_ADDRESS", m, self.__name__, event)- self.notifyListeners(evt)-- return None--# End of sfp_bitcoin class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_bitcoin+# Purpose: SpiderFoot plug-in for scanning retreived content by other+# modules (such as sfp_spider) and identifying bitcoin numbers.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 27/05/2017+# Copyright: (c) Steve Micallef 2017+# Licence: GPL+# -------------------------------------------------------------------------------++try:+ import re2 as re+except ImportError:+ import re+from hashlib import sha256+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++class sfp_bitcoin(SpiderFootPlugin):+ """Bitcoin Finder:Footprint,Investigate:Content Analysis::Identify bitcoin addresses in scraped webpages."""+++ # Default options+ opts = {}++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["TARGET_WEB_CONTENT"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["BITCOIN_ADDRESS"]++ def to_bytes(self, n, length):+ h = '%x' % n+ s = ('0'*(len(h) % 2) + h).zfill(length*2).decode('hex')+ return s++ def decode_base58(self, bc, length):+ digits58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'+ n = 0+ for char in bc:+ n = n * 58 + digits58.index(char)+ return self.to_bytes(n, length)++ def check_bc(self, bc):+ bcbytes = self.decode_base58(bc, 25)+ return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4]++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ sourceData = self.sf.hashstring(eventData)++ if sourceData in self.results:+ return None+ else:+ self.results.append(sourceData)++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ # thanks to https://stackoverflow.com/questions/21683680/regex-to-match-bitcoin-addresses+ matches = re.findall("[\s:=\>]([13][a-km-zA-HJ-NP-Z1-9]{25,34})", eventData)+ for m in matches:+ self.sf.debug("Bitcoin potential match: " + m)+ if self.check_bc(m):+ evt = SpiderFootEvent("BITCOIN_ADDRESS", m, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_bitcoin classdiff --git a/modules/sfp_blockchain.py b/modules/sfp_blockchain.pyindex 28186927..9e2b30c7 100644--- a/modules/sfp_blockchain.py+++ b/modules/sfp_blockchain.py@@ -1,75 +1,76 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_blockchain-# Purpose: SpiderFoot plug-in to look up a bitcoin wallet's balance by-# querying blockchain.info.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 18/06/2017-# Copyright: (c) Steve Micallef 2017-# Licence: GPL-# ---------------------------------------------------------------------------------import json-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_blockchain(SpiderFootPlugin):- """Blockchain:Footprint,Investigate,Passive:Social::Queries blockchain.info to find the balance of identified bitcoin wallet addresses."""-- # Default options- opts = {}- results = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ['BITCOIN_ADDRESS']-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["BITCOIN_BALANCE"]-- # 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)-- # Don't look up stuff twice- if eventData in self.results:- self.sf.debug("Skipping " + eventData + " as already mapped.")- return None- else:- self.results[eventData] = True-- # Wallet balance- res = self.sf.fetchUrl("https://blockchain.info/balance?active=" + eventData,- timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])- if res['content'] is None:- self.sf.info("No Blockchain info found for " + eventData)- return None- try:- data = json.loads(res['content'])- balance = float(data[eventData]['final_balance']) / 100000000- except Exception as e:- self.sf.debug("Error processing JSON response.")- return None-- evt = SpiderFootEvent("BITCOIN_BALANCE", str(balance) + " BTC", self.__name__, event)- self.notifyListeners(evt)-- return None--# End of sfp_blockchain class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_blockchain+# Purpose: SpiderFoot plug-in to look up a bitcoin wallet's balance by+# querying blockchain.info.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 18/06/2017+# Copyright: (c) Steve Micallef 2017+# Licence: GPL+# -------------------------------------------------------------------------------++import json+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_blockchain(SpiderFootPlugin):+ """Blockchain:Footprint,Investigate,Passive:Public Registries::Queries blockchain.info to find the balance of identified bitcoin wallet addresses."""+++ # Default options+ opts = {}+ results = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ['BITCOIN_ADDRESS']++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["BITCOIN_BALANCE"]++ # 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)++ # Don't look up stuff twice+ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + " as already mapped.")+ return None+ else:+ self.results[eventData] = True++ # Wallet balance+ res = self.sf.fetchUrl("https://blockchain.info/balance?active=" + eventData,+ timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.info("No Blockchain info found for " + eventData)+ return None+ try:+ data = json.loads(res['content'])+ balance = float(data[eventData]['final_balance']) / 100000000+ except Exception as e:+ self.sf.debug("Error processing JSON response.")+ return None++ evt = SpiderFootEvent("BITCOIN_BALANCE", str(balance) + " BTC", self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_blockchain classdiff --git a/modules/sfp_blocklistde.py b/modules/sfp_blocklistde.pyindex c5e5f11c..37874ef6 100644--- a/modules/sfp_blocklistde.py+++ b/modules/sfp_blocklistde.py@@ -1,267 +1,268 @@-# -*- 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 class+# -*- 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:Reputation Systems: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_botscout.py b/modules/sfp_botscout.pyindex 73d55e1d..bf4340c3 100644--- a/modules/sfp_botscout.py+++ b/modules/sfp_botscout.py@@ -1,95 +1,96 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_botscout-# Purpose: SpiderFoot plug-in to search botsout.com using their API, for-# potential malicious IPs and e-mail addresses.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 25/07/2016-# Copyright: (c) Steve Micallef 2016-# Licence: GPL-# ---------------------------------------------------------------------------------import json-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_botscout(SpiderFootPlugin):- """BotScout:Investigate:Blacklists:apikey:Searches botscout.com's database of spam-bot IPs and e-mail addresses."""-- # Default options- opts = {- "api_key": ""- }- optdescs = {- "api_key": "botscout.com API key. Without this you will be limited to 50 look-ups per day."- }- results = dict()- errorState = False-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ['IP_ADDRESS','EMAILADDR']-- # 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_EMAILADDR"]-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if self.errorState:- return None-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- if self.opts['api_key'] == "":- self.sf.error("You enabled sfp_botscout but did not set an API key!", False)- self.errorState = True- return None-- # Don't look up stuff twice- if eventData in self.results:- self.sf.debug("Skipping " + eventData + " as already searched.")- return None- else:- self.results[eventData] = True-- if self.opts['api_key']:- url = "http://botscout.com/test/?key=" + self.opts['api_key'] + "&all="- else:- url = "http://botscout.com/test/?all="-- res = self.sf.fetchUrl(url + eventData,- timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])- if res['content'] is None or "|" not in res['content']:- self.sf.error("Error encountered processing " + eventData, False)- return None-- if res['content'].startswith("Y|"):- self.sf.info("Found Botscout entry for " + eventData + ": " + res['content'])- if eventName == "IP_ADDRESS":- t = "MALICIOUS_IPADDR"- else:- t = "MALICIOUS_EMAILADDR"-- evt = SpiderFootEvent(t, eventData, self.__name__, event)- self.notifyListeners(evt)-- return None--# End of sfp_botscout class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_botscout+# Purpose: SpiderFoot plug-in to search botsout.com using their API, for+# potential malicious IPs and e-mail addresses.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 25/07/2016+# Copyright: (c) Steve Micallef 2016+# Licence: GPL+# -------------------------------------------------------------------------------++import json+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_botscout(SpiderFootPlugin):+ """BotScout:Investigate:Reputation Systems:apikey:Searches botscout.com's database of spam-bot IPs and e-mail addresses."""+++ # Default options+ opts = {+ "api_key": ""+ }+ optdescs = {+ "api_key": "botscout.com API key. Without this you will be limited to 50 look-ups per day."+ }+ results = dict()+ errorState = False++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ['IP_ADDRESS','EMAILADDR']++ # 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_EMAILADDR"]++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if self.errorState:+ return None++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if self.opts['api_key'] == "":+ self.sf.error("You enabled sfp_botscout but did not set an API key!", False)+ self.errorState = True+ return None++ # Don't look up stuff twice+ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + " as already searched.")+ return None+ else:+ self.results[eventData] = True++ if self.opts['api_key']:+ url = "http://botscout.com/test/?key=" + self.opts['api_key'] + "&all="+ else:+ url = "http://botscout.com/test/?all="++ res = self.sf.fetchUrl(url + eventData,+ timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])+ if res['content'] is None or "|" not in res['content']:+ self.sf.error("Error encountered processing " + eventData, False)+ return None++ if res['content'].startswith("Y|"):+ self.sf.info("Found Botscout entry for " + eventData + ": " + res['content'])+ if eventName == "IP_ADDRESS":+ t = "MALICIOUS_IPADDR"+ else:+ t = "MALICIOUS_EMAILADDR"++ evt = SpiderFootEvent(t, eventData, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_botscout classdiff --git a/modules/sfp_censys.py b/modules/sfp_censys.pyindex 06f39f4f..111d3e7f 100644--- a/modules/sfp_censys.py+++ b/modules/sfp_censys.py@@ -20,6 +20,7 @@ from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEventclass sfp_censys(SpiderFootPlugin):"""Censys:Investigate,Passive:Search Engines:apikey:Obtain information from Censys.io"""+# Default optionsopts = {"censys_api_key_uid": "",diff --git a/modules/sfp_clearbit.py b/modules/sfp_clearbit.pyindex 0f4dfe26..2c40e51e 100644--- a/modules/sfp_clearbit.py+++ b/modules/sfp_clearbit.py@@ -1,172 +1,173 @@-#--------------------------------------------------------------------------------# Name: sfp_clearbit-# Purpose: Query clearbit.com using their API.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 20/03/2017-# Copyright: (c) Steve Micallef-# Licence: GPL-#---------------------------------------------------------------------------------import json-import base64-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent--class sfp_clearbit(SpiderFootPlugin):- """Clearbit:Footprint,Investigate,Passive:Search Engines:apikey:Check for names, addresses, domains and more based on lookups of e-mail addresses on clearbit.com."""-- # Default options- opts = {- "api_key": ""- }-- # Option descriptions- optdescs = {- "api_key": "Your API key from clearbit.com."- }-- # Be sure to completely clear any class variables in setup()- # or you run the risk of data persisting between scan runs.-- results = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- # 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- def watchedEvents(self):- return [ "EMAILADDR" ]-- # What events this module produces- def producedEvents(self):- return [ "HUMAN_NAME", "PHONE_NUMBER", "PHYSICAL_ADDRESS",- "AFFILIATE_INTERNET_NAME", "EMAILADDR" ]-- def query(self, t):- ret = None-- url = "https://person.clearbit.com/v2/combined/find?email=" + t- headers = {- 'Accept': 'application/json',- 'Authorization': "Basic " + base64.b64encode(self.opts['api_key'] + ":")- }- res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],- useragent="SpiderFoot", headers=headers)-- if res['code'] != "200":- self.sf.error("Return code indicates no results or potential API key failure.",- False)- return None-- try:- ret = json.loads(res['content'])- except Exception as e:- self.sf.error("Error processing JSON response from clearbit.io: " + \- str(e), False)- return None-- return ret-- # 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)-- # Don't look up stuff twice- if self.results.has_key(eventData):- self.sf.debug("Skipping " + eventData + " as already mapped.")- return None- else:- self.results[eventData] = True-- data = self.query(eventData)- if not data:- return None-- try:- # Get the name associated with the e-mail- if "person" in data:- name = data['person']['name']['fullName']- evt = SpiderFootEvent("HUMAN_NAME", name, self.__name__, event)- self.notifyListeners(evt)- except Exception:- self.sf.debug("Unable to extract name from JSON.")- pass-- # Get the location of the person, also indicating- # the location of the employer.- try:- if "geo" in data:- loc = ""-- if 'streetNumber' in data['geo']:- loc += data['geo']['streetNumber'] + ", "- if 'streetName' in data['geo']:- loc += data['geo']['streetName'] + ", "- if 'city' in data['geo']:- loc += data['geo']['city'] + ", "- if 'postalCode' in data['geo']:- loc += data['geo']['postalCode'] + ", "- if 'state' in data['geo']:- loc += data['geo']['state'] + ", "- if 'country' in data['geo']:- loc += data['geo']['country']- evt = SpiderFootEvent("PHYSICAL_ADDRESS", loc, self.__name__, event)- self.notifyListeners(evt)- except Exception:- self.sf.debug("Unable to extract location from JSON.")- pass-- try:- if "company" in data:- if 'domainAliases' in data['company']:- for d in data['company']['domainAliases']:- evt = SpiderFootEvent("AFFILIATE_INTERNET_NAME", d,- self.__name__, event)- self.notifyListeners(evt)-- if 'site' in data['company']:- if 'phoneNumbers' in data['company']['site']:- for p in data['company']['site']['phoneNumbers']:- evt = SpiderFootEvent("PHONE_NUMBER", p, self.__name__, event)- self.notifyListeners(evt)- if 'emailAddresses' in data['company']['site']:- for e in data['company']['site']['emailAddresses']:- evt = SpiderFootEvent("EMAILADDR", e, self.__name__, event)- self.notifyListeners(evt)-- # Get the location of the person, also indicating- # the location of the employer.- if 'geo' in data['company']:- loc = ""-- if 'streetNumber' in data['company']['geo']:- loc += data['company']['geo']['streetNumber'] + ", "- if 'streetName' in data['company']['geo']:- loc += data['company']['geo']['streetName'] + ", "- if 'city' in data['company']['geo']:- loc += data['company']['geo']['city'] + ", "- if 'postalCode' in data['company']['geo']:- loc += data['company']['geo']['postalCode'] + ", "- if 'state' in data['company']['geo']:- loc += data['company']['geo']['state'] + ", "- if 'country' in data['company']['geo']:- loc += data['company']['geo']['country']- evt = SpiderFootEvent("PHYSICAL_ADDRESS", loc, self.__name__, event)- self.notifyListeners(evt)- except Exception:- self.sf.debug("Unable to company info from JSON.")- pass--# End of sfp_clearbit class+#-------------------------------------------------------------------------------+# Name: sfp_clearbit+# Purpose: Query clearbit.com using their API.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 20/03/2017+# Copyright: (c) Steve Micallef+# Licence: GPL+#-------------------------------------------------------------------------------++import json+import base64+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++class sfp_clearbit(SpiderFootPlugin):+ """Clearbit:Footprint,Investigate,Passive:Search Engines:apikey:Check for names, addresses, domains and more based on lookups of e-mail addresses on clearbit.com."""+++ # Default options+ opts = {+ "api_key": ""+ }++ # Option descriptions+ optdescs = {+ "api_key": "Your API key from clearbit.com."+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ # 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+ def watchedEvents(self):+ return [ "EMAILADDR" ]++ # What events this module produces+ def producedEvents(self):+ return [ "HUMAN_NAME", "PHONE_NUMBER", "PHYSICAL_ADDRESS",+ "AFFILIATE_INTERNET_NAME", "EMAILADDR" ]++ def query(self, t):+ ret = None++ url = "https://person.clearbit.com/v2/combined/find?email=" + t+ headers = {+ 'Accept': 'application/json',+ 'Authorization': "Basic " + base64.b64encode(self.opts['api_key'] + ":")+ }+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],+ useragent="SpiderFoot", headers=headers)++ if res['code'] != "200":+ self.sf.error("Return code indicates no results or potential API key failure.",+ False)+ return None++ try:+ ret = json.loads(res['content'])+ except Exception as e:+ self.sf.error("Error processing JSON response from clearbit.io: " + \+ str(e), False)+ return None++ return ret++ # 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)++ # Don't look up stuff twice+ if self.results.has_key(eventData):+ self.sf.debug("Skipping " + eventData + " as already mapped.")+ return None+ else:+ self.results[eventData] = True++ data = self.query(eventData)+ if not data:+ return None++ try:+ # Get the name associated with the e-mail+ if "person" in data:+ name = data['person']['name']['fullName']+ evt = SpiderFootEvent("HUMAN_NAME", name, self.__name__, event)+ self.notifyListeners(evt)+ except Exception:+ self.sf.debug("Unable to extract name from JSON.")+ pass++ # Get the location of the person, also indicating+ # the location of the employer.+ try:+ if "geo" in data:+ loc = ""++ if 'streetNumber' in data['geo']:+ loc += data['geo']['streetNumber'] + ", "+ if 'streetName' in data['geo']:+ loc += data['geo']['streetName'] + ", "+ if 'city' in data['geo']:+ loc += data['geo']['city'] + ", "+ if 'postalCode' in data['geo']:+ loc += data['geo']['postalCode'] + ", "+ if 'state' in data['geo']:+ loc += data['geo']['state'] + ", "+ if 'country' in data['geo']:+ loc += data['geo']['country']+ evt = SpiderFootEvent("PHYSICAL_ADDRESS", loc, self.__name__, event)+ self.notifyListeners(evt)+ except Exception:+ self.sf.debug("Unable to extract location from JSON.")+ pass++ try:+ if "company" in data:+ if 'domainAliases' in data['company']:+ for d in data['company']['domainAliases']:+ evt = SpiderFootEvent("AFFILIATE_INTERNET_NAME", d,+ self.__name__, event)+ self.notifyListeners(evt)++ if 'site' in data['company']:+ if 'phoneNumbers' in data['company']['site']:+ for p in data['company']['site']['phoneNumbers']:+ evt = SpiderFootEvent("PHONE_NUMBER", p, self.__name__, event)+ self.notifyListeners(evt)+ if 'emailAddresses' in data['company']['site']:+ for e in data['company']['site']['emailAddresses']:+ evt = SpiderFootEvent("EMAILADDR", e, self.__name__, event)+ self.notifyListeners(evt)++ # Get the location of the person, also indicating+ # the location of the employer.+ if 'geo' in data['company']:+ loc = ""++ if 'streetNumber' in data['company']['geo']:+ loc += data['company']['geo']['streetNumber'] + ", "+ if 'streetName' in data['company']['geo']:+ loc += data['company']['geo']['streetName'] + ", "+ if 'city' in data['company']['geo']:+ loc += data['company']['geo']['city'] + ", "+ if 'postalCode' in data['company']['geo']:+ loc += data['company']['geo']['postalCode'] + ", "+ if 'state' in data['company']['geo']:+ loc += data['company']['geo']['state'] + ", "+ if 'country' in data['company']['geo']:+ loc += data['company']['geo']['country']+ evt = SpiderFootEvent("PHYSICAL_ADDRESS", loc, self.__name__, event)+ self.notifyListeners(evt)+ except Exception:+ self.sf.debug("Unable to company info from JSON.")+ pass++# End of sfp_clearbit classdiff --git a/modules/sfp_cookie.py b/modules/sfp_cookie.pyindex b174dedc..4a65199b 100644--- a/modules/sfp_cookie.py+++ b/modules/sfp_cookie.py@@ -1,64 +1,65 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_cookie-# Purpose: SpiderFoot plug-in for extracting cookies from HTTP headers.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 06/04/2014-# Copyright: (c) Steve Micallef 2014-# Licence: GPL-# ---------------------------------------------------------------------------------from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_cookie(SpiderFootPlugin):- """Cookies:Footprint,Investigate:Web Spidering::Extract Cookies from HTTP headers."""-- # Default options- opts = {}-- results = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["WEBSERVER_HTTPHEADERS"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["TARGET_WEB_COOKIE"]-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- parentEvent = event.sourceEvent- eventSource = event.sourceEvent.data-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)- if eventSource in self.results:- return None- else:- self.results[eventSource] = True-- if not self.getTarget().matches(self.sf.urlFQDN(eventSource)):- self.sf.debug("Not collecting cookies from external sites.")- return None-- if 'set-cookie' in eventData:- evt = SpiderFootEvent("TARGET_WEB_COOKIE", eventData['set-cookie'],- self.__name__, parentEvent)- self.notifyListeners(evt)--# End of sfp_cookie class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_cookie+# Purpose: SpiderFoot plug-in for extracting cookies from HTTP headers.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 06/04/2014+# Copyright: (c) Steve Micallef 2014+# Licence: GPL+# -------------------------------------------------------------------------------++from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_cookie(SpiderFootPlugin):+ """Cookies:Footprint,Investigate:Crawling and Scanning::Extract Cookies from HTTP headers."""+++ # Default options+ opts = {}++ results = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["WEBSERVER_HTTPHEADERS"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["TARGET_WEB_COOKIE"]++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ parentEvent = event.sourceEvent+ eventSource = event.sourceEvent.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ if eventSource in self.results:+ return None+ else:+ self.results[eventSource] = True++ if not self.getTarget().matches(self.sf.urlFQDN(eventSource)):+ self.sf.debug("Not collecting cookies from external sites.")+ return None++ if 'set-cookie' in eventData:+ evt = SpiderFootEvent("TARGET_WEB_COOKIE", eventData['set-cookie'],+ self.__name__, parentEvent)+ self.notifyListeners(evt)++# End of sfp_cookie classdiff --git a/modules/sfp_crossref.py b/modules/sfp_crossref.pyindex e42dc972..771640c4 100644--- a/modules/sfp_crossref.py+++ b/modules/sfp_crossref.py@@ -1,132 +1,133 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_crossref-# Purpose: SpiderFoot plug-in for scanning links identified from the-# spidering process, and for external links, fetching them to-# see if those sites link back to the original site, indicating a-# potential relationship between the external sites.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 06/04/2012-# Copyright: (c) Steve Micallef 2012-# Licence: GPL-# ---------------------------------------------------------------------------------import re-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_crossref(SpiderFootPlugin):- """Cross-Reference:Footprint:Web Spidering::Identify whether other domains are associated ('Affiliates') of the target."""-- # Default options- opts = {- 'checkbase': True- }-- # Option descriptions- optdescs = {- "checkbase": "Check the base URL of the potential affiliate if no direct affiliation found?"- }-- # Internal results tracking- results = dict()- fetched = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()- self.fetched = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ['LINKED_URL_EXTERNAL', 'SIMILARDOMAIN',- 'CO_HOSTED_SITE', 'DARKNET_MENTION_URL']-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["AFFILIATE_INTERNET_NAME", "AFFILIATE_WEB_CONTENT"]-- # Handle events sent to this module- # In this module's case, eventData will be the URL or a domain which- # was found in some content somewhere.- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- # The SIMILARDOMAIN and CO_HOSTED_SITE events supply domains,- # not URLs. Assume HTTP.- if eventName in ['SIMILARDOMAIN', 'CO_HOSTED_SITE']:- eventData = 'http://' + eventData.lower()-- # We are only interested in external sites for the crossref- if self.getTarget().matches(self.sf.urlFQDN(eventData)):- self.sf.debug("Ignoring " + eventData + " as not external")- return None-- if eventData in self.fetched:- self.sf.debug("Ignoring " + eventData + " as already tested")- return- else:- self.fetched.append(eventData)-- self.sf.debug("Testing for affiliation: " + eventData)- res = self.sf.fetchUrl(eventData, timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])-- if res['content'] is None:- self.sf.debug("Ignoring " + eventData + " as no data returned")- return None-- matched = False- for name in self.getTarget().getNames():- # Search for mentions of our host/domain in the external site's data- pat = re.compile("([\.\'\/\"\ ]" + name + "[\.\'\/\"\ ])", re.IGNORECASE)- matches = re.findall(pat, res['content'])-- if len(matches) > 0:- matched = True- url = eventData- break-- if not matched:- # If the name wasn't found in the affiliate, and checkbase is set,- # fetch the base URL of the affiliate to check for a crossref.- if eventName == "LINKED_URL_EXTERNAL" and self.opts['checkbase']:- # Check the base url to see if there is an affiliation- url = self.sf.urlBaseUrl(eventData)- if url in self.fetched:- return None- else:- self.fetched.append(url)-- res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])- if res['content'] is not None:- for name in self.getTarget().getNames():- pat = re.compile("([\.\'\/\"\ ]" + name + "[\'\/\"\ ])",- re.IGNORECASE)- matches = re.findall(pat, res['content'])-- if len(matches) > 0:- matched = True-- if matched:- self.sf.info("Found affiliate: " + url)- evt1 = SpiderFootEvent("AFFILIATE_INTERNET_NAME", self.sf.urlFQDN(url),- self.__name__, event)- self.notifyListeners(evt1)- evt2 = SpiderFootEvent("AFFILIATE_WEB_CONTENT", res['content'],- self.__name__, evt1)- self.notifyListeners(evt2)--# End of sfp_crossref class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_crossref+# Purpose: SpiderFoot plug-in for scanning links identified from the+# spidering process, and for external links, fetching them to+# see if those sites link back to the original site, indicating a+# potential relationship between the external sites.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 06/04/2012+# Copyright: (c) Steve Micallef 2012+# Licence: GPL+# -------------------------------------------------------------------------------++import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_crossref(SpiderFootPlugin):+ """Cross-Reference:Footprint:Crawling and Scanning::Identify whether other domains are associated ('Affiliates') of the target."""+++ # Default options+ opts = {+ 'checkbase': True+ }++ # Option descriptions+ optdescs = {+ "checkbase": "Check the base URL of the potential affiliate if no direct affiliation found?"+ }++ # Internal results tracking+ results = dict()+ fetched = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()+ self.fetched = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ['LINKED_URL_EXTERNAL', 'SIMILARDOMAIN',+ 'CO_HOSTED_SITE', 'DARKNET_MENTION_URL']++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["AFFILIATE_INTERNET_NAME", "AFFILIATE_WEB_CONTENT"]++ # Handle events sent to this module+ # In this module's case, eventData will be the URL or a domain which+ # was found in some content somewhere.+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ # The SIMILARDOMAIN and CO_HOSTED_SITE events supply domains,+ # not URLs. Assume HTTP.+ if eventName in ['SIMILARDOMAIN', 'CO_HOSTED_SITE']:+ eventData = 'http://' + eventData.lower()++ # We are only interested in external sites for the crossref+ if self.getTarget().matches(self.sf.urlFQDN(eventData)):+ self.sf.debug("Ignoring " + eventData + " as not external")+ return None++ if eventData in self.fetched:+ self.sf.debug("Ignoring " + eventData + " as already tested")+ return+ else:+ self.fetched.append(eventData)++ self.sf.debug("Testing for affiliation: " + eventData)+ res = self.sf.fetchUrl(eventData, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])++ if res['content'] is None:+ self.sf.debug("Ignoring " + eventData + " as no data returned")+ return None++ matched = False+ for name in self.getTarget().getNames():+ # Search for mentions of our host/domain in the external site's data+ pat = re.compile("([\.\'\/\"\ ]" + name + "[\.\'\/\"\ ])", re.IGNORECASE)+ matches = re.findall(pat, res['content'])++ if len(matches) > 0:+ matched = True+ url = eventData+ break++ if not matched:+ # If the name wasn't found in the affiliate, and checkbase is set,+ # fetch the base URL of the affiliate to check for a crossref.+ if eventName == "LINKED_URL_EXTERNAL" and self.opts['checkbase']:+ # Check the base url to see if there is an affiliation+ url = self.sf.urlBaseUrl(eventData)+ if url in self.fetched:+ return None+ else:+ self.fetched.append(url)++ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])+ if res['content'] is not None:+ for name in self.getTarget().getNames():+ pat = re.compile("([\.\'\/\"\ ]" + name + "[\'\/\"\ ])",+ re.IGNORECASE)+ matches = re.findall(pat, res['content'])++ if len(matches) > 0:+ matched = True++ if matched:+ self.sf.info("Found affiliate: " + url)+ evt1 = SpiderFootEvent("AFFILIATE_INTERNET_NAME", self.sf.urlFQDN(url),+ self.__name__, event)+ self.notifyListeners(evt1)+ evt2 = SpiderFootEvent("AFFILIATE_WEB_CONTENT", res['content'],+ self.__name__, evt1)+ self.notifyListeners(evt2)++# End of sfp_crossref classdiff --git a/modules/sfp_crt.py b/modules/sfp_crt.pyindex 6038bdfc..f58e4b8e 100644--- a/modules/sfp_crt.py+++ b/modules/sfp_crt.py@@ -1,99 +1,100 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_crt-# Purpose: SpiderFoot plug-in to identify historical certificates for a domain-# from crt.sh, and from this identify hostnames.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 17/03/2017-# Copyright: (c) Steve Micallef 2017-# Licence: GPL-# ---------------------------------------------------------------------------------import json-import re-import M2Crypto-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_crt(SpiderFootPlugin):- """Certificate Transparency:Footprint,Investigate,Passive:Networking::Gather hostnames from historical certificates in crt.sh."""-- # Default options- opts = {}- results = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ['DOMAIN_NAME', 'INTERNET_NAME']-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["INTERNET_NAME", "SSL_CERTIFICATE_ISSUED",- "SSL_CERTIFICATE_ISSUER", "SSL_CERTIFICATE_RAW"]-- def getIssued(self, cert, sevt):- issued = cert.get_subject().as_text().encode('raw_unicode_escape')- evt = SpiderFootEvent("SSL_CERTIFICATE_ISSUED", issued, self.__name__, sevt)- self.notifyListeners(evt)-- # Report back the certificate issuer- def getIssuer(self, cert, sevt):- issuer = cert.get_issuer().as_text().encode('raw_unicode_escape')- evt = SpiderFootEvent("SSL_CERTIFICATE_ISSUER", issuer, self.__name__, sevt)- self.notifyListeners(evt)-- # 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)-- # Don't look up stuff twice- if eventData in self.results:- self.sf.debug("Skipping " + eventData + " as already mapped.")- return None- else:- self.results[eventData] = True-- res = self.sf.fetchUrl("https://crt.sh/?CN=%25." + eventData + "&output=json",- timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])- if res['content'] is None:- self.sf.info("No certificate transparency info found for " + eventData)- return None-- try:- evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", res['content'], self.__name__, event)- self.notifyListeners(evt)-- matches = re.findall("\"min_cert_id\":(\d+),", res['content'], re.IGNORECASE)- for m in matches:- dat = self.sf.fetchUrl("https://crt.sh/?d=" + m, timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])-- m2cert = M2Crypto.X509.load_cert_string(str(dat['content']).replace('\r', ''))- rawevt = SpiderFootEvent("SSL_CERTIFICATE_RAW",- m2cert.as_text().encode('raw_unicode_escape'),- self.__name__, event)- self.notifyListeners(rawevt)- self.getIssuer(m2cert, evt)- self.getIssued(m2cert, evt)- except Exception as e:- self.sf.debug("Error processing JSON response: " + str(e))- return None-- return None--# End of sfp_crt class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_crt+# Purpose: SpiderFoot plug-in to identify historical certificates for a domain+# from crt.sh, and from this identify hostnames.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 17/03/2017+# Copyright: (c) Steve Micallef 2017+# Licence: GPL+# -------------------------------------------------------------------------------++import json+import re+import M2Crypto+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_crt(SpiderFootPlugin):+ """Certificate Transparency:Footprint,Investigate,Passive:Search Engines::Gather hostnames from historical certificates in crt.sh."""+++ # Default options+ opts = {}+ results = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ['DOMAIN_NAME', 'INTERNET_NAME']++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["INTERNET_NAME", "SSL_CERTIFICATE_ISSUED",+ "SSL_CERTIFICATE_ISSUER", "SSL_CERTIFICATE_RAW"]++ def getIssued(self, cert, sevt):+ issued = cert.get_subject().as_text().encode('raw_unicode_escape')+ evt = SpiderFootEvent("SSL_CERTIFICATE_ISSUED", issued, self.__name__, sevt)+ self.notifyListeners(evt)++ # Report back the certificate issuer+ def getIssuer(self, cert, sevt):+ issuer = cert.get_issuer().as_text().encode('raw_unicode_escape')+ evt = SpiderFootEvent("SSL_CERTIFICATE_ISSUER", issuer, self.__name__, sevt)+ self.notifyListeners(evt)++ # 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)++ # Don't look up stuff twice+ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + " as already mapped.")+ return None+ else:+ self.results[eventData] = True++ res = self.sf.fetchUrl("https://crt.sh/?CN=%25." + eventData + "&output=json",+ timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.info("No certificate transparency info found for " + eventData)+ return None++ try:+ evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", res['content'], self.__name__, event)+ self.notifyListeners(evt)++ matches = re.findall("\"min_cert_id\":(\d+),", res['content'], re.IGNORECASE)+ for m in matches:+ dat = self.sf.fetchUrl("https://crt.sh/?d=" + m, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])++ m2cert = M2Crypto.X509.load_cert_string(str(dat['content']).replace('\r', ''))+ rawevt = SpiderFootEvent("SSL_CERTIFICATE_RAW",+ m2cert.as_text().encode('raw_unicode_escape'),+ self.__name__, event)+ self.notifyListeners(rawevt)+ self.getIssuer(m2cert, evt)+ self.getIssued(m2cert, evt)+ except Exception as e:+ self.sf.debug("Error processing JSON response: " + str(e))+ return None++ return None++# End of sfp_crt classdiff --git a/modules/sfp_cybercrimetracker.py b/modules/sfp_cybercrimetracker.pyindex eedd8141..2543bd55 100644--- a/modules/sfp_cybercrimetracker.py+++ b/modules/sfp_cybercrimetracker.py@@ -1,268 +1,269 @@-# -*- 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 class+# -*- 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:Reputation Systems: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_cymon.py b/modules/sfp_cymon.pyindex 1a8348ef..3b81ca2c 100644--- a/modules/sfp_cymon.py+++ b/modules/sfp_cymon.py@@ -18,7 +18,8 @@ from netaddr import IPNetworkfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEventclass sfp_cymon(SpiderFootPlugin):- """Cymon:Investigate,Passive:Blacklists:apikey:Obtain information from Cymon.io"""+ """Cymon:Investigate,Passive:Reputation Systems:apikey:Obtain information from Cymon.io"""+# Default optionsopts = {diff --git a/modules/sfp_dns.py b/modules/sfp_dns.pyindex 4495345c..500933c6 100644--- a/modules/sfp_dns.py+++ b/modules/sfp_dns.py@@ -1,518 +1,519 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_dns-# Purpose: SpiderFoot plug-in for gathering IP addresses from sub-domains-# and hostnames identified, and optionally affiliates.-# Can also identify affiliates and other sub-domains based on-# reverse-looking up the IP address identified.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 16/09/2012-# Copyright: (c) Steve Micallef 2012-# Licence: GPL-# ---------------------------------------------------------------------------------import socket-import re-import dns-import urllib2-from netaddr import IPAddress, IPNetwork-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent--class sfp_dns(SpiderFootPlugin):- """DNS:Footprint,Investigate:Networking::Performs a number of DNS checks to obtain Sub-domains/Hostnames, IP Addresses and Affiliates."""-- # Default options- opts = {- 'netblocklookup': True,- 'maxnetblock': 24,- 'lookaside': True,- 'lookasidecount': 10,- 'onlyactive': True,- 'validatereverse': True,- "skipcommononwildcard": True,- "commonsubs": ["www", "web", "ns", "mail", "dns", "mx", "gw", "proxy",- "ssl", "fw", "gateway", "firewall", "www1", "www2",- "ns0", "ns1", "ns2", "dns0", "dns1", "dns2", "mx1", "mx2"- ] # Common sub-domains to try.-- }-- # Option descriptions- optdescs = {- 'skipcommononwildcard': "If wildcard DNS is detected, only attempt to look up the first common sub-domain from the common sub-domain list.",- 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible hosts on the same target subdomain/domain?",- 'maxnetblock': "Maximum owned netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",- 'onlyactive': "Only report sub-domains/hostnames that resolve to an IP.",- 'validatereverse': "Validate that reverse-resolved hostnames still resolve back to that IP before considering them as aliases of your target.",- 'lookaside': "For each IP discovered, try and reverse look-up IPs 'next to' that IP for potential hostnames on the same subdomain/domain.",- 'lookasidecount': "If look-aside is enabled, the number of IPs on each 'side' of the IP to look up",- 'commonsubs': "Common sub-domains to try to resolve on the target subdomain/domain. Prefix with an '@' to iterate through a file containing sub-domains to try (one per line), e.g. @C:\subdomains.txt or @/home/bob/subdomains.txt. Or supply a URL to load the list from there."- }-- events = dict()- domresults = dict()- hostresults = dict()- rawresults = dict()- resolveCache = dict()- resolveCache6 = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.events = dict()- self.domresults = dict()- self.hostresults = dict()- self.resolveCache = dict()- self.resolveCache6 = dict()- self.rawresults = dict()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- self.sublist = self.opts['commonsubs']- # User may have supplied a file or URL containing the subdomains- if self.opts['commonsubs'][0].startswith("http://") or \- self.opts['commonsubs'][0].startswith("https://") or \- self.opts['commonsubs'][0].startswith("@"):- self.sublist = self.sf.optValueToData(self.opts['commonsubs'][0])-- def enrichTarget(self, target):- ret = list()- # If it's an IP, get the hostname it reverse resolves to- if target.getType() == "IP_ADDRESS":- ret = self.resolveIP(target.getValue())- if target.getType() == "INTERNET_NAME":- ret = self.resolveHost(target.getValue())- if target.getType() == "NETBLOCK_OWNER":- ret = list()- for addr in IPNetwork(target.getValue()):- ipaddr = str(addr)- if ipaddr.split(".")[3] in ['255', '0']:- continue- if '255' in ipaddr.split("."):- continue- ret.append(ipaddr)-- # Add the reverse-resolved hostnames as aliases too..- names = self.resolveIP(ipaddr)-- if self.opts['validatereverse']:- for host in names:- chk = self.resolveHost(host)- if ipaddr in chk:- ret.append(host)- else:- ret.extend(names)-- for host in ret:- if self.sf.validIP(host):- target.setAlias(host, "IP_ADDRESS")- else:- target.setAlias(host, "INTERNET_NAME")- # If the target was a hostname/sub-domain, we can- # add the domain as an alias for the target. But- # not if the target was an IP or subnet.- #if target.getType() == "INTERNET_NAME":- # dom = self.sf.hostDomain(host, self.opts['_internettlds'])- # target.setAlias(dom, "INTERNET_NAME")-- self.sf.debug("Aliases identified: " + str(target.getAliases()))-- return target-- # What events is this module interested in for input- def watchedEvents(self):- arr = ['RAW_DNS_RECORDS', 'SEARCH_ENGINE_WEB_CONTENT', 'RAW_RIR_DATA',- 'TARGET_WEB_CONTENT', 'LINKED_URL_INTERNAL', 'INTERNET_NAME',- 'IP_ADDRESS', 'NETBLOCK_OWNER', "DNS_TEXT", "SSL_CERTIFICATE_RAW"]- return arr-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["IP_ADDRESS", "INTERNET_NAME", "PROVIDER_MAIL", "DOMAIN_NAME",- "PROVIDER_DNS", "AFFILIATE_INTERNET_NAME", "RAW_DNS_RECORDS",- "DNS_TEXT", "DNS_SPF", "IPV6_ADDRESS", "DOMAIN_NAME_PARENT"]-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- eventDataHash = self.sf.hashstring(eventData)- addrs = None- parentEvent = event-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- if eventDataHash in self.events:- return None-- self.events[eventDataHash] = True- # Identify potential sub-domains/hostnames- if eventName in ["SEARCH_ENGINE_WEB_CONTENT", "TARGET_WEB_CONTENT", "SSL_CERTIFICATE_RAW",- "LINKED_URL_INTERNAL", "RAW_RIR_DATA", "RAW_DNS_RECORDS", "DNS_TEXT"]:- # If we've received a link or some raw data, extract potential sub-domains- # from the data for resolving later.- for name in self.getTarget().getNames():- if self.checkForStop():- return None- pat = re.compile("(%..)?([a-zA-Z0-9\-\.]+\." + name + ")", re.IGNORECASE)- matches = re.findall(pat, urllib2.unquote(eventData))- if matches is not None:- for match in matches:- self.processHost(match[1], parentEvent, affiliate=False)- # Nothing left to do with internal links and raw data- return None-- if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:- if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:- self.sf.debug("Network size bigger than permitted: " +- str(IPNetwork(eventData).prefixlen) + " > " +- str(self.opts['maxnetblock']))- return None-- if "::" in eventData:- return None-- self.sf.debug("Looking up IPs in owned netblock: " + eventData)- for ip in IPNetwork(eventData):- ipaddr = str(ip)- if "::" in ipaddr:- continue- if ipaddr.split(".")[3] in ['255', '0']:- continue- if '255' in ipaddr.split("."):- continue-- if self.checkForStop():- return None- addrs = self.resolveIP(ipaddr)-- if len(addrs) > 0:- self.sf.debug("Found a reversed hostname from " + ipaddr +- " (" + str(addrs) + ")")- for addr in addrs:- # Generate an event for the IP, then- # let the handling by this module take- # care of follow-up processing.- if self.checkForStop():- return None-- self.processHost(ipaddr, parentEvent, False)- return None-- # Handling INTERNET_NAME and IP_ADDRESS events..- if eventName in ["IP_ADDRESS", "INTERNET_NAME"]:- if eventName != 'IP_ADDRESS':- if '://' in eventData:- addrs = self.resolveHost(self.sf.urlFQDN(eventData))- else:- addrs = self.resolveHost(eventData)- else:- addrs = self.resolveIP(eventData)-- for addr in addrs:- if self.checkForStop():- return None-- if self.getTarget().matches(addr):- self.processHost(addr, parentEvent, False)- else:- # IP addresses resolved from hosts are assumed- # to be part of the target (non-affiliates).- if self.sf.validIP(addr):- self.processHost(addr, parentEvent, False)- else:- self.processHost(addr, parentEvent, True)-- # Try to reverse-resolve IPs 'near' the identified IP- if self.opts['lookaside'] and eventName == 'IP_ADDRESS':- ip = IPAddress(eventData)- minip = IPAddress(int(ip) - self.opts['lookasidecount'])- maxip = IPAddress(int(ip) + self.opts['lookasidecount'])- self.sf.debug("Lookaside max: " + str(maxip) + ", min: " + str(minip))- s = int(minip)- c = int(maxip)- parentEventUp = parentEvent.sourceEvent-- while s <= c:- sip = str(IPAddress(s))- self.sf.debug("Attempting look-aside lookup of: " + sip)- if self.checkForStop():- return None-- if sip in self.hostresults:- s += 1- continue-- addrs = self.resolveIP(sip)- if len(addrs) == 0:- self.sf.debug("Look-aside resolve for " + sip + " failed.")- s += 1- continue-- # Report addresses that resolve to hostnames on the same- # domain or sub-domain as the target.- if self.getTarget().matches(sip):- affil = False- else:- affil = True- for a in addrs:- if self.getTarget().matches(a):- affil = False-- # Generate the event for the look-aside IP, but don't let it re-trigger- # this module by adding it to self.events first.- self.events[sip] = True- ev = self.processHost(sip, parentEventUp, affil)-- for addr in addrs:- if self.checkForStop():- return None-- if addr == sip:- continue- # IP Addresses should be linked to whatever provided the IP- if self.sf.validIP(addr):- parent = parentEventUp- else:- # Hostnames from the IP need to be linked to the IP- parent = ev-- if self.getTarget().matches(addr):- # Generate an event for the IP, then- # let the handling by this module take- # care of follow-up processing.- self.processHost(addr, parent, False)- else:- self.processHost(addr, parent, True)- s += 1- return None-- # Resolve an IP- def resolveIP(self, ipaddr):- ret = list()- self.sf.debug("Performing reverse-resolve of " + ipaddr)-- if ipaddr in self.resolveCache:- self.sf.debug("Returning cached result for " + ipaddr + " (" +- str(self.resolveCache[ipaddr]) + ")")- return self.resolveCache[ipaddr]-- try:- addrs = self.sf.normalizeDNS(socket.gethostbyaddr(ipaddr))- self.resolveCache[ipaddr] = addrs- self.sf.debug("Resolved " + ipaddr + " to: " + str(addrs))- return addrs- except BaseException as e:- self.sf.debug("Unable to resolve " + ipaddr + " (" + str(e) + ")")- self.resolveCache[ipaddr] = list()- return ret-- # Resolve a host- def resolveHost(self, hostname):- if hostname in self.resolveCache:- self.sf.debug("Returning cached result for " + hostname + " (" +- str(self.resolveCache[hostname]) + ")")- return self.resolveCache[hostname]-- try:- addrs = self.sf.normalizeDNS(socket.gethostbyname_ex(hostname))- self.resolveCache[hostname] = addrs- self.sf.debug("Resolved " + hostname + " to: " + str(addrs))- return addrs- except BaseException as e:- self.sf.debug("Unable to resolve " + hostname + " (" + str(e) + ")")- return list()-- # Resolve a host to IPv6- def resolveHost6(self, hostname):- if hostname in self.resolveCache6:- self.sf.debug("Returning IPv6 cached result for " + hostname + " (" +- str(self.resolveCache6[hostname]) + ")")- return self.resolveCache6[hostname]-- try:- addrs = list()- res = socket.getaddrinfo(hostname, None, socket.AF_INET6)- for addr in res:- if addr[4][0] not in addrs:- addrs.append(addr[4][0])- if len(addrs) < 1:- return None- self.resolveCache6[hostname] = addrs- self.sf.debug("Resolved " + hostname + " to IPv6: " + str(addrs))- return addrs- except BaseException as e:- self.sf.debug("Unable to IPv6 resolve " + hostname + " (" + str(e) + ")")- return list()-- # Process a host/IP, parentEvent is the event that represents this entity- def processHost(self, host, parentEvent, affiliate=None):- parentHash = self.sf.hashstring(parentEvent.data)- if host not in self.hostresults:- self.hostresults[host] = list(parentHash)- else:- if parentHash in self.hostresults[host] or parentEvent.data == host:- self.sf.debug("Skipping host, " + host + ", already processed.")- return None- else:- self.hostresults[host].append(parentHash)-- self.sf.debug("Found host: " + host)- # If the returned hostname is aliaseed to our- # target in some way, flag it as an affiliate- if affiliate is None:- affil = True- if self.getTarget().matches(host):- affil = False- # If the IP the host resolves to is in our- # list of aliases,- if not self.sf.validIP(host):- for hostip in self.resolveHost(host):- if self.getTarget().matches(hostip):- affil = False- else:- affil = affiliate-- if affil:- if self.sf.validIP(host):- htype = "AFFILIATE_IPADDR"- else:- htype = "AFFILIATE_INTERNET_NAME"- else:- if self.sf.validIP(host):- htype = "IP_ADDRESS"- else:- htype = "INTERNET_NAME"-- if htype.endswith("INTERNET_NAME") and self.opts['onlyactive']:- if len(self.resolveHost(host)) == 0:- return None-- # Report the host- evt = SpiderFootEvent(htype, host, self.__name__, parentEvent)- self.notifyListeners(evt)- # Report the domain for that host- if htype == "INTERNET_NAME":- dom = self.sf.hostDomain(host, self.opts['_internettlds'])- self.processDomain(dom, evt)- self.getRawDns(host, evt)-- # Try obtain the IPv6 address- for ip6 in self.resolveHost6(host):- evt6 = SpiderFootEvent("IPV6_ADDRESS", ip6, self.__name__, evt)- self.notifyListeners(evt6)-- return evt-- def processDomain(self, domainName, parentEvent):- if domainName not in self.domresults:- self.domresults[domainName] = True- else:- self.sf.debug("Skipping domain, " + domainName + ", already processed.")- return None-- if self.getTarget().matches(domainName):- domevt = SpiderFootEvent("DOMAIN_NAME", domainName,- self.__name__, parentEvent)- self.notifyListeners(domevt)- else:- domevt = SpiderFootEvent("DOMAIN_NAME_PARENT", domainName,- self.__name__, parentEvent)- self.notifyListeners(domevt)- return None-- self.getRawDns(domainName, domevt, True)-- def getRawDns(self, entity, parentEvent, iterate=False):- if entity in self.rawresults:- return None- else:- self.rawresults[entity] = True-- self.sf.debug("Gathering DNS records for " + entity)- # Process the raw data alone- recdata = dict()- recs = {- 'MX': ['\S+\s+(?:\d+)?\s+IN\s+MX\s+\d+\s+(\S+)\.', 'PROVIDER_MAIL'],- 'NS': ['\S+\s+(?:\d+)?\s+IN\s+NS\s+(\S+)\.', 'PROVIDER_DNS'],- 'TXT': ['\S+\s+TXT\s+\"(.[^\"]*)"', 'DNS_TEXT']- }-- for rec in recs.keys():- if self.checkForStop():- return None-- try:- req = dns.message.make_query(entity, dns.rdatatype.from_text(rec))-- if self.opts['_dnsserver'] != "":- n = self.opts['_dnsserver']- else:- ns = dns.resolver.get_default_resolver()- n = ns.nameservers[0]-- res = dns.query.udp(req, n, timeout=30)- for x in res.answer:- for rx in recs.keys():- self.sf.debug("Checking " + str(x) + " + against " + recs[rx][0])- pat = re.compile(recs[rx][0], re.IGNORECASE | re.DOTALL)- grps = re.findall(pat, str(x))- if len(grps) > 0:- for m in grps:- self.sf.debug("Matched: " + m)- strdata = unicode(m, 'utf-8', errors='replace')- evt = SpiderFootEvent(recs[rx][1], strdata,- self.__name__, parentEvent)- self.notifyListeners(evt)- if rec != "TXT" and not strdata.endswith(entity):- evt = SpiderFootEvent("AFFILIATE_INTERNET_NAME",- strdata, self.__name__, parentEvent)- self.notifyListeners(evt)- if rec == "TXT" and "v=spf" in strdata:- evt = SpiderFootEvent("DNS_SPF", strdata,- self.__name__, parentEvent)- self.notifyListeners(evt)-- else:- strdata = unicode(str(x), 'utf-8', errors='replace')- evt = SpiderFootEvent("RAW_DNS_RECORDS", strdata,- self.__name__, parentEvent)- self.notifyListeners(evt)- except BaseException as e:- self.sf.error("Failed to obtain DNS response for " + entity +- "(" + rec + "): " + str(e), False)-- if not iterate:- return None-- self.sf.debug("Iterating through possible sub-domains [" + str(self.sublist) + "]")- count = 0- wildcard = self.sf.checkDnsWildcard(entity)- # Try resolving common names- for sub in self.sublist:- if wildcard and self.opts['skipcommononwildcard'] and count > 0:- self.sf.debug("Wildcard DNS detected, skipping iterating through remaining hosts.")- return None-- if self.checkForStop():- return None-- count += 1- if sub != "":- name = sub + "." + entity- else:- continue-- # Skip hosts we've processed already- if name in self.events.keys():- continue-- if len(self.resolveHost(name)) > 0:- self.processHost(name, parentEvent, affiliate=False)--# End of sfp_dns class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_dns+# Purpose: SpiderFoot plug-in for gathering IP addresses from sub-domains+# and hostnames identified, and optionally affiliates.+# Can also identify affiliates and other sub-domains based on+# reverse-looking up the IP address identified.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 16/09/2012+# Copyright: (c) Steve Micallef 2012+# Licence: GPL+# -------------------------------------------------------------------------------++import socket+import re+import dns+import urllib2+from netaddr import IPAddress, IPNetwork+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++class sfp_dns(SpiderFootPlugin):+ """DNS:Footprint,Investigate:DNS::Performs a number of DNS checks to obtain Sub-domains/Hostnames, IP Addresses and Affiliates."""+++ # Default options+ opts = {+ 'netblocklookup': True,+ 'maxnetblock': 24,+ 'lookaside': True,+ 'lookasidecount': 10,+ 'onlyactive': True,+ 'validatereverse': True,+ "skipcommononwildcard": True,+ "commonsubs": ["www", "web", "ns", "mail", "dns", "mx", "gw", "proxy",+ "ssl", "fw", "gateway", "firewall", "www1", "www2",+ "ns0", "ns1", "ns2", "dns0", "dns1", "dns2", "mx1", "mx2"+ ] # Common sub-domains to try.++ }++ # Option descriptions+ optdescs = {+ 'skipcommononwildcard': "If wildcard DNS is detected, only attempt to look up the first common sub-domain from the common sub-domain list.",+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible hosts on the same target subdomain/domain?",+ 'maxnetblock': "Maximum owned netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",+ 'onlyactive': "Only report sub-domains/hostnames that resolve to an IP.",+ 'validatereverse': "Validate that reverse-resolved hostnames still resolve back to that IP before considering them as aliases of your target.",+ 'lookaside': "For each IP discovered, try and reverse look-up IPs 'next to' that IP for potential hostnames on the same subdomain/domain.",+ 'lookasidecount': "If look-aside is enabled, the number of IPs on each 'side' of the IP to look up",+ 'commonsubs': "Common sub-domains to try to resolve on the target subdomain/domain. Prefix with an '@' to iterate through a file containing sub-domains to try (one per line), e.g. @C:\subdomains.txt or @/home/bob/subdomains.txt. Or supply a URL to load the list from there."+ }++ events = dict()+ domresults = dict()+ hostresults = dict()+ rawresults = dict()+ resolveCache = dict()+ resolveCache6 = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.events = dict()+ self.domresults = dict()+ self.hostresults = dict()+ self.resolveCache = dict()+ self.resolveCache6 = dict()+ self.rawresults = dict()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ self.sublist = self.opts['commonsubs']+ # User may have supplied a file or URL containing the subdomains+ if self.opts['commonsubs'][0].startswith("http://") or \+ self.opts['commonsubs'][0].startswith("https://") or \+ self.opts['commonsubs'][0].startswith("@"):+ self.sublist = self.sf.optValueToData(self.opts['commonsubs'][0])++ def enrichTarget(self, target):+ ret = list()+ # If it's an IP, get the hostname it reverse resolves to+ if target.getType() == "IP_ADDRESS":+ ret = self.resolveIP(target.getValue())+ if target.getType() == "INTERNET_NAME":+ ret = self.resolveHost(target.getValue())+ if target.getType() == "NETBLOCK_OWNER":+ ret = list()+ for addr in IPNetwork(target.getValue()):+ ipaddr = str(addr)+ if ipaddr.split(".")[3] in ['255', '0']:+ continue+ if '255' in ipaddr.split("."):+ continue+ ret.append(ipaddr)++ # Add the reverse-resolved hostnames as aliases too..+ names = self.resolveIP(ipaddr)++ if self.opts['validatereverse']:+ for host in names:+ chk = self.resolveHost(host)+ if ipaddr in chk:+ ret.append(host)+ else:+ ret.extend(names)++ for host in ret:+ if self.sf.validIP(host):+ target.setAlias(host, "IP_ADDRESS")+ else:+ target.setAlias(host, "INTERNET_NAME")+ # If the target was a hostname/sub-domain, we can+ # add the domain as an alias for the target. But+ # not if the target was an IP or subnet.+ #if target.getType() == "INTERNET_NAME":+ # dom = self.sf.hostDomain(host, self.opts['_internettlds'])+ # target.setAlias(dom, "INTERNET_NAME")++ self.sf.debug("Aliases identified: " + str(target.getAliases()))++ return target++ # What events is this module interested in for input+ def watchedEvents(self):+ arr = ['RAW_DNS_RECORDS', 'SEARCH_ENGINE_WEB_CONTENT', 'RAW_RIR_DATA',+ 'TARGET_WEB_CONTENT', 'LINKED_URL_INTERNAL', 'INTERNET_NAME',+ 'IP_ADDRESS', 'NETBLOCK_OWNER', "DNS_TEXT", "SSL_CERTIFICATE_RAW"]+ return arr++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["IP_ADDRESS", "INTERNET_NAME", "PROVIDER_MAIL", "DOMAIN_NAME",+ "PROVIDER_DNS", "AFFILIATE_INTERNET_NAME", "RAW_DNS_RECORDS",+ "DNS_TEXT", "DNS_SPF", "IPV6_ADDRESS", "DOMAIN_NAME_PARENT"]++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ eventDataHash = self.sf.hashstring(eventData)+ addrs = None+ parentEvent = event++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventDataHash in self.events:+ return None++ self.events[eventDataHash] = True+ # Identify potential sub-domains/hostnames+ if eventName in ["SEARCH_ENGINE_WEB_CONTENT", "TARGET_WEB_CONTENT", "SSL_CERTIFICATE_RAW",+ "LINKED_URL_INTERNAL", "RAW_RIR_DATA", "RAW_DNS_RECORDS", "DNS_TEXT"]:+ # If we've received a link or some raw data, extract potential sub-domains+ # from the data for resolving later.+ for name in self.getTarget().getNames():+ if self.checkForStop():+ return None+ pat = re.compile("(%..)?([a-zA-Z0-9\-\.]+\." + name + ")", re.IGNORECASE)+ matches = re.findall(pat, urllib2.unquote(eventData))+ if matches is not None:+ for match in matches:+ self.processHost(match[1], parentEvent, affiliate=False)+ # Nothing left to do with internal links and raw data+ return None++ if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:+ if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:+ self.sf.debug("Network size bigger than permitted: " ++ str(IPNetwork(eventData).prefixlen) + " > " ++ str(self.opts['maxnetblock']))+ return None++ if "::" in eventData:+ return None++ self.sf.debug("Looking up IPs in owned netblock: " + eventData)+ for ip in IPNetwork(eventData):+ ipaddr = str(ip)+ if "::" in ipaddr:+ continue+ if ipaddr.split(".")[3] in ['255', '0']:+ continue+ if '255' in ipaddr.split("."):+ continue++ if self.checkForStop():+ return None+ addrs = self.resolveIP(ipaddr)++ if len(addrs) > 0:+ self.sf.debug("Found a reversed hostname from " + ipaddr ++ " (" + str(addrs) + ")")+ for addr in addrs:+ # Generate an event for the IP, then+ # let the handling by this module take+ # care of follow-up processing.+ if self.checkForStop():+ return None++ self.processHost(ipaddr, parentEvent, False)+ return None++ # Handling INTERNET_NAME and IP_ADDRESS events..+ if eventName in ["IP_ADDRESS", "INTERNET_NAME"]:+ if eventName != 'IP_ADDRESS':+ if '://' in eventData:+ addrs = self.resolveHost(self.sf.urlFQDN(eventData))+ else:+ addrs = self.resolveHost(eventData)+ else:+ addrs = self.resolveIP(eventData)++ for addr in addrs:+ if self.checkForStop():+ return None++ if self.getTarget().matches(addr):+ self.processHost(addr, parentEvent, False)+ else:+ # IP addresses resolved from hosts are assumed+ # to be part of the target (non-affiliates).+ if self.sf.validIP(addr):+ self.processHost(addr, parentEvent, False)+ else:+ self.processHost(addr, parentEvent, True)++ # Try to reverse-resolve IPs 'near' the identified IP+ if self.opts['lookaside'] and eventName == 'IP_ADDRESS':+ ip = IPAddress(eventData)+ minip = IPAddress(int(ip) - self.opts['lookasidecount'])+ maxip = IPAddress(int(ip) + self.opts['lookasidecount'])+ self.sf.debug("Lookaside max: " + str(maxip) + ", min: " + str(minip))+ s = int(minip)+ c = int(maxip)+ parentEventUp = parentEvent.sourceEvent++ while s <= c:+ sip = str(IPAddress(s))+ self.sf.debug("Attempting look-aside lookup of: " + sip)+ if self.checkForStop():+ return None++ if sip in self.hostresults:+ s += 1+ continue++ addrs = self.resolveIP(sip)+ if len(addrs) == 0:+ self.sf.debug("Look-aside resolve for " + sip + " failed.")+ s += 1+ continue++ # Report addresses that resolve to hostnames on the same+ # domain or sub-domain as the target.+ if self.getTarget().matches(sip):+ affil = False+ else:+ affil = True+ for a in addrs:+ if self.getTarget().matches(a):+ affil = False++ # Generate the event for the look-aside IP, but don't let it re-trigger+ # this module by adding it to self.events first.+ self.events[sip] = True+ ev = self.processHost(sip, parentEventUp, affil)++ for addr in addrs:+ if self.checkForStop():+ return None++ if addr == sip:+ continue+ # IP Addresses should be linked to whatever provided the IP+ if self.sf.validIP(addr):+ parent = parentEventUp+ else:+ # Hostnames from the IP need to be linked to the IP+ parent = ev++ if self.getTarget().matches(addr):+ # Generate an event for the IP, then+ # let the handling by this module take+ # care of follow-up processing.+ self.processHost(addr, parent, False)+ else:+ self.processHost(addr, parent, True)+ s += 1+ return None++ # Resolve an IP+ def resolveIP(self, ipaddr):+ ret = list()+ self.sf.debug("Performing reverse-resolve of " + ipaddr)++ if ipaddr in self.resolveCache:+ self.sf.debug("Returning cached result for " + ipaddr + " (" ++ str(self.resolveCache[ipaddr]) + ")")+ return self.resolveCache[ipaddr]++ try:+ addrs = self.sf.normalizeDNS(socket.gethostbyaddr(ipaddr))+ self.resolveCache[ipaddr] = addrs+ self.sf.debug("Resolved " + ipaddr + " to: " + str(addrs))+ return addrs+ except BaseException as e:+ self.sf.debug("Unable to resolve " + ipaddr + " (" + str(e) + ")")+ self.resolveCache[ipaddr] = list()+ return ret++ # Resolve a host+ def resolveHost(self, hostname):+ if hostname in self.resolveCache:+ self.sf.debug("Returning cached result for " + hostname + " (" ++ str(self.resolveCache[hostname]) + ")")+ return self.resolveCache[hostname]++ try:+ addrs = self.sf.normalizeDNS(socket.gethostbyname_ex(hostname))+ self.resolveCache[hostname] = addrs+ self.sf.debug("Resolved " + hostname + " to: " + str(addrs))+ return addrs+ except BaseException as e:+ self.sf.debug("Unable to resolve " + hostname + " (" + str(e) + ")")+ return list()++ # Resolve a host to IPv6+ def resolveHost6(self, hostname):+ if hostname in self.resolveCache6:+ self.sf.debug("Returning IPv6 cached result for " + hostname + " (" ++ str(self.resolveCache6[hostname]) + ")")+ return self.resolveCache6[hostname]++ try:+ addrs = list()+ res = socket.getaddrinfo(hostname, None, socket.AF_INET6)+ for addr in res:+ if addr[4][0] not in addrs:+ addrs.append(addr[4][0])+ if len(addrs) < 1:+ return None+ self.resolveCache6[hostname] = addrs+ self.sf.debug("Resolved " + hostname + " to IPv6: " + str(addrs))+ return addrs+ except BaseException as e:+ self.sf.debug("Unable to IPv6 resolve " + hostname + " (" + str(e) + ")")+ return list()++ # Process a host/IP, parentEvent is the event that represents this entity+ def processHost(self, host, parentEvent, affiliate=None):+ parentHash = self.sf.hashstring(parentEvent.data)+ if host not in self.hostresults:+ self.hostresults[host] = list(parentHash)+ else:+ if parentHash in self.hostresults[host] or parentEvent.data == host:+ self.sf.debug("Skipping host, " + host + ", already processed.")+ return None+ else:+ self.hostresults[host].append(parentHash)++ self.sf.debug("Found host: " + host)+ # If the returned hostname is aliaseed to our+ # target in some way, flag it as an affiliate+ if affiliate is None:+ affil = True+ if self.getTarget().matches(host):+ affil = False+ # If the IP the host resolves to is in our+ # list of aliases,+ if not self.sf.validIP(host):+ for hostip in self.resolveHost(host):+ if self.getTarget().matches(hostip):+ affil = False+ else:+ affil = affiliate++ if affil:+ if self.sf.validIP(host):+ htype = "AFFILIATE_IPADDR"+ else:+ htype = "AFFILIATE_INTERNET_NAME"+ else:+ if self.sf.validIP(host):+ htype = "IP_ADDRESS"+ else:+ htype = "INTERNET_NAME"++ if htype.endswith("INTERNET_NAME") and self.opts['onlyactive']:+ if len(self.resolveHost(host)) == 0:+ return None++ # Report the host+ evt = SpiderFootEvent(htype, host, self.__name__, parentEvent)+ self.notifyListeners(evt)+ # Report the domain for that host+ if htype == "INTERNET_NAME":+ dom = self.sf.hostDomain(host, self.opts['_internettlds'])+ self.processDomain(dom, evt)+ self.getRawDns(host, evt)++ # Try obtain the IPv6 address+ for ip6 in self.resolveHost6(host):+ evt6 = SpiderFootEvent("IPV6_ADDRESS", ip6, self.__name__, evt)+ self.notifyListeners(evt6)++ return evt++ def processDomain(self, domainName, parentEvent):+ if domainName not in self.domresults:+ self.domresults[domainName] = True+ else:+ self.sf.debug("Skipping domain, " + domainName + ", already processed.")+ return None++ if self.getTarget().matches(domainName):+ domevt = SpiderFootEvent("DOMAIN_NAME", domainName,+ self.__name__, parentEvent)+ self.notifyListeners(domevt)+ else:+ domevt = SpiderFootEvent("DOMAIN_NAME_PARENT", domainName,+ self.__name__, parentEvent)+ self.notifyListeners(domevt)+ return None++ self.getRawDns(domainName, domevt, True)++ def getRawDns(self, entity, parentEvent, iterate=False):+ if entity in self.rawresults:+ return None+ else:+ self.rawresults[entity] = True++ self.sf.debug("Gathering DNS records for " + entity)+ # Process the raw data alone+ recdata = dict()+ recs = {+ 'MX': ['\S+\s+(?:\d+)?\s+IN\s+MX\s+\d+\s+(\S+)\.', 'PROVIDER_MAIL'],+ 'NS': ['\S+\s+(?:\d+)?\s+IN\s+NS\s+(\S+)\.', 'PROVIDER_DNS'],+ 'TXT': ['\S+\s+TXT\s+\"(.[^\"]*)"', 'DNS_TEXT']+ }++ for rec in recs.keys():+ if self.checkForStop():+ return None++ try:+ req = dns.message.make_query(entity, dns.rdatatype.from_text(rec))++ if self.opts['_dnsserver'] != "":+ n = self.opts['_dnsserver']+ else:+ ns = dns.resolver.get_default_resolver()+ n = ns.nameservers[0]++ res = dns.query.udp(req, n, timeout=30)+ for x in res.answer:+ for rx in recs.keys():+ self.sf.debug("Checking " + str(x) + " + against " + recs[rx][0])+ pat = re.compile(recs[rx][0], re.IGNORECASE | re.DOTALL)+ grps = re.findall(pat, str(x))+ if len(grps) > 0:+ for m in grps:+ self.sf.debug("Matched: " + m)+ strdata = unicode(m, 'utf-8', errors='replace')+ evt = SpiderFootEvent(recs[rx][1], strdata,+ self.__name__, parentEvent)+ self.notifyListeners(evt)+ if rec != "TXT" and not strdata.endswith(entity):+ evt = SpiderFootEvent("AFFILIATE_INTERNET_NAME",+ strdata, self.__name__, parentEvent)+ self.notifyListeners(evt)+ if rec == "TXT" and "v=spf" in strdata:+ evt = SpiderFootEvent("DNS_SPF", strdata,+ self.__name__, parentEvent)+ self.notifyListeners(evt)++ else:+ strdata = unicode(str(x), 'utf-8', errors='replace')+ evt = SpiderFootEvent("RAW_DNS_RECORDS", strdata,+ self.__name__, parentEvent)+ self.notifyListeners(evt)+ except BaseException as e:+ self.sf.error("Failed to obtain DNS response for " + entity ++ "(" + rec + "): " + str(e), False)++ if not iterate:+ return None++ self.sf.debug("Iterating through possible sub-domains [" + str(self.sublist) + "]")+ count = 0+ wildcard = self.sf.checkDnsWildcard(entity)+ # Try resolving common names+ for sub in self.sublist:+ if wildcard and self.opts['skipcommononwildcard'] and count > 0:+ self.sf.debug("Wildcard DNS detected, skipping iterating through remaining hosts.")+ return None++ if self.checkForStop():+ return None++ count += 1+ if sub != "":+ name = sub + "." + entity+ else:+ continue++ # Skip hosts we've processed already+ if name in self.events.keys():+ continue++ if len(self.resolveHost(name)) > 0:+ self.processHost(name, parentEvent, affiliate=False)++# End of sfp_dns classdiff --git a/modules/sfp_dronebl.py b/modules/sfp_dronebl.pyindex 36a35866..4be650ef 100644--- a/modules/sfp_dronebl.py+++ b/modules/sfp_dronebl.py@@ -1,167 +1,168 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_dronebl-# Purpose: SpiderFoot plug-in for looking up whether IPs/Netblocks/Domains-# appear in the DroneBL blocklist, indicating potential open-relays,-# open proxies, malicious servers, vulnerable servers, etc.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 07/01/2014-# Copyright: (c) Steve Micallef 2014-# Licence: GPL-# ---------------------------------------------------------------------------------import socket-from netaddr import IPNetwork-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_dronebl(SpiderFootPlugin):- """DroneBL:Investigate,Passive:Blacklists::Query the DroneBL database for open relays, open proxies, vulnerable servers, etc."""-- # Default options- opts = {- 'netblocklookup': True,- 'maxnetblock': 24,- 'subnetlookup': True,- 'maxsubnet': 24- }-- # Option descriptions- optdescs = {- 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible blacklisted hosts on the same target subdomain/domain?",- 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",- 'subnetlookup': "Look up all IPs on subnets which your target is a part of for blacklisting?",- 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"- }-- # Target- results = dict()-- # Whole bunch here:- # http://en.wikipedia.org/wiki/Comparison_of_DNS_blacklists- # Check out:- # http://www.blocklist.de/en/rbldns.html- checks = {- "dnsbl.dronebl.org": {- "127.0.0.3": "dronebl.org - IRC Drone",- "127.0.0.5": "dronebl.org - Bottler",- "127.0.0.6": "dronebl.org - Unknown spambot or drone",- "127.0.0.7": "dronebl.org - DDOS Drone",- "127.0.0.8": "dronebl.org - SOCKS Proxy",- "127.0.0.9": "dronebl.org - HTTP Proxy",- "127.0.0.10": "dronebl.org - ProxyChain",- "127.0.0.13": "dronebl.org - Brute force attackers",- "127.0.0.14": "dronebl.org - Open Wingate Proxy",- "127.0.0.15": "dronebl.org - Compromised router / gateway",- "127.0.0.17": "dronebl.org - Automatically determined botnet IPs (experimental)",- "127.0.0.255": "dronebl.org - Unknown"- }- }-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ['IP_ADDRESS', 'AFFILIATE_IPADDR', 'NETBLOCK_OWNER',- 'NETBLOCK_MEMBER']-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["BLACKLISTED_IPADDR", "BLACKLISTED_AFFILIATE_IPADDR",- "BLACKLISTED_SUBNET", "BLACKLISTED_NETBLOCK"]-- # Swap 1.2.3.4 to 4.3.2.1- def reverseAddr(self, ipaddr):- return '.'.join(reversed(ipaddr.split('.')))-- def queryAddr(self, qaddr, parentEvent):- eventName = parentEvent.eventType-- for domain in self.checks:- if self.checkForStop():- return None-- try:- lookup = self.reverseAddr(qaddr) + "." + domain- self.sf.debug("Checking Blacklist: " + lookup)- addrs = self.sf.normalizeDNS(socket.gethostbyname_ex(lookup))- self.sf.debug("Addresses returned: " + str(addrs))-- text = None- for addr in addrs:- if type(self.checks[domain]) is str:- text = self.checks[domain] + " (" + qaddr + ")"- break- else:- if str(addr) not in self.checks[domain].keys():- self.sf.debug("Return code not found in list: " + str(addr))- continue-- k = str(addr)- text = self.checks[domain][k] + " (" + qaddr + ")"- break-- if text is not None:- if eventName == "AFFILIATE_IPADDR":- e = "BLACKLISTED_AFFILIATE_IPADDR"- if eventName == "IP_ADDRESS":- e = "BLACKLISTED_IPADDR"- if eventName == "NETBLOCK_OWNER":- e = "BLACKLISTED_NETBLOCK"- if eventName == "NETBLOCK_MEMBER":- e = "BLACKLISTED_SUBNET"-- evt = SpiderFootEvent(e, text, self.__name__, parentEvent)- self.notifyListeners(evt)-- except BaseException as e:- self.sf.debug("Unable to resolve " + qaddr + " / " + lookup + ": " + str(e))-- return None-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- parentEvent = event- addrlist = list()-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- if eventData in self.results:- return None- self.results[eventData] = True-- if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:- if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:- self.sf.debug("Network size bigger than permitted: " +- str(IPNetwork(eventData).prefixlen) + " > " +- str(self.opts['maxnetblock']))- return None-- if eventName == 'NETBLOCK_MEMBER' and self.opts['subnetlookup']:- if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:- self.sf.debug("Network size bigger than permitted: " +- str(IPNetwork(eventData).prefixlen) + " > " +- str(self.opts['maxsubnet']))- return None-- if eventName.startswith("NETBLOCK_"):- for addr in IPNetwork(eventData):- if self.checkForStop():- return None- self.queryAddr(str(addr), parentEvent)- else:- self.queryAddr(eventData, parentEvent)--# End of sfp_dronebl class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_dronebl+# Purpose: SpiderFoot plug-in for looking up whether IPs/Netblocks/Domains+# appear in the DroneBL blocklist, indicating potential open-relays,+# open proxies, malicious servers, vulnerable servers, etc.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 07/01/2014+# Copyright: (c) Steve Micallef 2014+# Licence: GPL+# -------------------------------------------------------------------------------++import socket+from netaddr import IPNetwork+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_dronebl(SpiderFootPlugin):+ """DroneBL:Investigate,Passive:Reputation Systems::Query the DroneBL database for open relays, open proxies, vulnerable servers, etc."""+++ # Default options+ opts = {+ 'netblocklookup': True,+ 'maxnetblock': 24,+ 'subnetlookup': True,+ 'maxsubnet': 24+ }++ # Option descriptions+ optdescs = {+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible blacklisted hosts on the same target subdomain/domain?",+ 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",+ 'subnetlookup': "Look up all IPs on subnets which your target is a part of for blacklisting?",+ 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"+ }++ # Target+ results = dict()++ # Whole bunch here:+ # http://en.wikipedia.org/wiki/Comparison_of_DNS_blacklists+ # Check out:+ # http://www.blocklist.de/en/rbldns.html+ checks = {+ "dnsbl.dronebl.org": {+ "127.0.0.3": "dronebl.org - IRC Drone",+ "127.0.0.5": "dronebl.org - Bottler",+ "127.0.0.6": "dronebl.org - Unknown spambot or drone",+ "127.0.0.7": "dronebl.org - DDOS Drone",+ "127.0.0.8": "dronebl.org - SOCKS Proxy",+ "127.0.0.9": "dronebl.org - HTTP Proxy",+ "127.0.0.10": "dronebl.org - ProxyChain",+ "127.0.0.13": "dronebl.org - Brute force attackers",+ "127.0.0.14": "dronebl.org - Open Wingate Proxy",+ "127.0.0.15": "dronebl.org - Compromised router / gateway",+ "127.0.0.17": "dronebl.org - Automatically determined botnet IPs (experimental)",+ "127.0.0.255": "dronebl.org - Unknown"+ }+ }++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ['IP_ADDRESS', 'AFFILIATE_IPADDR', 'NETBLOCK_OWNER',+ 'NETBLOCK_MEMBER']++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["BLACKLISTED_IPADDR", "BLACKLISTED_AFFILIATE_IPADDR",+ "BLACKLISTED_SUBNET", "BLACKLISTED_NETBLOCK"]++ # Swap 1.2.3.4 to 4.3.2.1+ def reverseAddr(self, ipaddr):+ return '.'.join(reversed(ipaddr.split('.')))++ def queryAddr(self, qaddr, parentEvent):+ eventName = parentEvent.eventType++ for domain in self.checks:+ if self.checkForStop():+ return None++ try:+ lookup = self.reverseAddr(qaddr) + "." + domain+ self.sf.debug("Checking Blacklist: " + lookup)+ addrs = self.sf.normalizeDNS(socket.gethostbyname_ex(lookup))+ self.sf.debug("Addresses returned: " + str(addrs))++ text = None+ for addr in addrs:+ if type(self.checks[domain]) is str:+ text = self.checks[domain] + " (" + qaddr + ")"+ break+ else:+ if str(addr) not in self.checks[domain].keys():+ self.sf.debug("Return code not found in list: " + str(addr))+ continue++ k = str(addr)+ text = self.checks[domain][k] + " (" + qaddr + ")"+ break++ if text is not None:+ if eventName == "AFFILIATE_IPADDR":+ e = "BLACKLISTED_AFFILIATE_IPADDR"+ if eventName == "IP_ADDRESS":+ e = "BLACKLISTED_IPADDR"+ if eventName == "NETBLOCK_OWNER":+ e = "BLACKLISTED_NETBLOCK"+ if eventName == "NETBLOCK_MEMBER":+ e = "BLACKLISTED_SUBNET"++ evt = SpiderFootEvent(e, text, self.__name__, parentEvent)+ self.notifyListeners(evt)++ except BaseException as e:+ self.sf.debug("Unable to resolve " + qaddr + " / " + lookup + ": " + str(e))++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ parentEvent = event+ addrlist = list()++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ return None+ self.results[eventData] = True++ if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:+ if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:+ self.sf.debug("Network size bigger than permitted: " ++ str(IPNetwork(eventData).prefixlen) + " > " ++ str(self.opts['maxnetblock']))+ return None++ if eventName == 'NETBLOCK_MEMBER' and self.opts['subnetlookup']:+ if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:+ self.sf.debug("Network size bigger than permitted: " ++ str(IPNetwork(eventData).prefixlen) + " > " ++ str(self.opts['maxsubnet']))+ return None++ if eventName.startswith("NETBLOCK_"):+ for addr in IPNetwork(eventData):+ if self.checkForStop():+ return None+ self.queryAddr(str(addr), parentEvent)+ else:+ self.queryAddr(eventData, parentEvent)++# End of sfp_dronebl classdiff --git a/modules/sfp_duckduckgo.py b/modules/sfp_duckduckgo.pyindex ba15bb97..3ecf064f 100644--- a/modules/sfp_duckduckgo.py+++ b/modules/sfp_duckduckgo.py@@ -1,118 +1,119 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_duckduckgo-# Purpose: Queries DuckDuckGo's API for information abotut the target.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 21/07/2015-# Copyright: (c) Steve Micallef 2015-# Licence: GPL-# ---------------------------------------------------------------------------------import json-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent--class sfp_duckduckgo(SpiderFootPlugin):- """DuckDuckGo:Footprint,Investigate,Passive:Search Engines::Query DuckDuckGo's API for descriptive information about your target."""-- # Default options- opts = {- "affiliatedomains": True- }-- # Option descriptions- optdescs = {- "affiliatedomains": "For affiliates, look up the domain name, not the hostname. This will usually return more meaningful information about the affiliate."- }-- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["DOMAIN_NAME", "DOMAIN_NAME_PARENT",- "INTERNET_NAME", "AFFILIATE_INTERNET_NAME"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["DESCRIPTION_CATEGORY", "DESCRIPTION_ABSTRACT",- "AFFILIATE_DESCRIPTION_CATEGORY",- "AFFILIATE_DESCRIPTION_ABSTRACT"]--- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if self.opts['affiliatedomains'] and "AFFILIATE_" in eventName:- eventData = self.sf.hostDomain(eventData, self.opts['_internettlds'])-- if eventData in self.results:- self.sf.debug("Already did a search for " + eventData + ", skipping.")- return None- else:- self.results.append(eventData)-- url = "https://api.duckduckgo.com/?q=" + eventData + "&format=json&pretty=1"- res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],- useragent="SpiderFoot")-- if res['content'] == None:- self.sf.error("Unable to fetch " + url, False)- return None-- try:- ret = json.loads(res['content'])- except BaseException as e:- ret = None-- if ret == None:- self.sf.error("Unable to process empty response from DuckDuckGo for: " + \- eventData, False)- return None-- if ret['Heading'] == "":- self.sf.debug("No DuckDuckGo information for " + eventData)- return None-- # Submit the bing results for analysis- evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", res['content'],- self.__name__, event)- self.notifyListeners(evt)-- if 'AbstractText' in ret:- name = "DESCRIPTION_ABSTRACT"- if "AFFILIATE" in eventName:- name = "AFFILIATE_" + name-- evt = SpiderFootEvent(name, ret['AbstractText'],- self.__name__, event)- self.notifyListeners(evt)-- if 'RelatedTopics' in ret:- name = "DESCRIPTION_CATEGORY"- if "AFFILIATE" in eventName:- name = "AFFILIATE_" + name-- for item in ret['RelatedTopics']:- cat = None- if 'Text' in item:- cat = item['Text']- if cat == None or cat == "":- self.sf.debug("No category text found from DuckDuckGo.")- continue-- evt = SpiderFootEvent(name, cat, self.__name__, event)- self.notifyListeners(evt)--# End of sfp_duckduckgo class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_duckduckgo+# Purpose: Queries DuckDuckGo's API for information abotut the target.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 21/07/2015+# Copyright: (c) Steve Micallef 2015+# Licence: GPL+# -------------------------------------------------------------------------------++import json+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++class sfp_duckduckgo(SpiderFootPlugin):+ """DuckDuckGo:Footprint,Investigate,Passive:Search Engines::Query DuckDuckGo's API for descriptive information about your target."""+++ # Default options+ opts = {+ "affiliatedomains": True+ }++ # Option descriptions+ optdescs = {+ "affiliatedomains": "For affiliates, look up the domain name, not the hostname. This will usually return more meaningful information about the affiliate."+ }++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["DOMAIN_NAME", "DOMAIN_NAME_PARENT",+ "INTERNET_NAME", "AFFILIATE_INTERNET_NAME"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["DESCRIPTION_CATEGORY", "DESCRIPTION_ABSTRACT",+ "AFFILIATE_DESCRIPTION_CATEGORY",+ "AFFILIATE_DESCRIPTION_ABSTRACT"]+++ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if self.opts['affiliatedomains'] and "AFFILIATE_" in eventName:+ eventData = self.sf.hostDomain(eventData, self.opts['_internettlds'])++ if eventData in self.results:+ self.sf.debug("Already did a search for " + eventData + ", skipping.")+ return None+ else:+ self.results.append(eventData)++ url = "https://api.duckduckgo.com/?q=" + eventData + "&format=json&pretty=1"+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],+ useragent="SpiderFoot")++ if res['content'] == None:+ self.sf.error("Unable to fetch " + url, False)+ return None++ try:+ ret = json.loads(res['content'])+ except BaseException as e:+ ret = None++ if ret == None:+ self.sf.error("Unable to process empty response from DuckDuckGo for: " + \+ eventData, False)+ return None++ if ret['Heading'] == "":+ self.sf.debug("No DuckDuckGo information for " + eventData)+ return None++ # Submit the bing results for analysis+ evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", res['content'],+ self.__name__, event)+ self.notifyListeners(evt)++ if 'AbstractText' in ret:+ name = "DESCRIPTION_ABSTRACT"+ if "AFFILIATE" in eventName:+ name = "AFFILIATE_" + name++ evt = SpiderFootEvent(name, ret['AbstractText'],+ self.__name__, event)+ self.notifyListeners(evt)++ if 'RelatedTopics' in ret:+ name = "DESCRIPTION_CATEGORY"+ if "AFFILIATE" in eventName:+ name = "AFFILIATE_" + name++ for item in ret['RelatedTopics']:+ cat = None+ if 'Text' in item:+ cat = item['Text']+ if cat == None or cat == "":+ self.sf.debug("No category text found from DuckDuckGo.")+ continue++ evt = SpiderFootEvent(name, cat, self.__name__, event)+ self.notifyListeners(evt)++# End of sfp_duckduckgo classdiff --git a/modules/sfp_email.py b/modules/sfp_email.pyindex b34c0a19..9856032c 100644--- a/modules/sfp_email.py+++ b/modules/sfp_email.py@@ -1,97 +1,98 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_email-# Purpose: SpiderFoot plug-in for scanning retreived content by other-# modules (such as sfp_spider) and identifying e-mail addresses-#-# Author: Steve Micallef <[email protected]>-#-# Created: 06/04/2012-# Copyright: (c) Steve Micallef 2012-# Licence: GPL-# ---------------------------------------------------------------------------------import re-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_email(SpiderFootPlugin):- """E-Mail:Footprint,Investigate,Passive:Data Analysis::Identify e-mail addresses in any obtained data."""-- # Default options- opts = {- # options specific to this module- }-- # Option descriptions- optdescs = {- }-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["*"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["EMAILADDR"]-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if eventName.startswith("EMAILADDR"):- return None-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- if type(eventData) not in [str, unicode]:- self.sf.debug("Unhandled type to find e-mails: " + str(type(eventData)))- return None-- pat = re.compile("([\%a-zA-Z\.0-9_\-]+@[a-zA-Z\.0-9\-]+\.[a-zA-Z\.0-9\-]+)")- matches = re.findall(pat, eventData)- myres = list()- for match in matches:- if len(match) < 4:- self.sf.debug("Likely invalid address: " + match)- continue-- # Handle messed up encodings- if "%" in match:- self.sf.debug("Skipped address: " + match)- continue-- # Get the doain and strip potential ending .- mailDom = match.lower().split('@')[1].strip('.')- if not self.getTarget().matches(mailDom):- self.sf.debug("Ignoring e-mail address on an external domain: " + match)- continue-- self.sf.info("Found e-mail address: " + match)- if type(match) == str:- mail = unicode(match.strip('.'), 'utf-8', errors='replace')- else:- mail = match.strip('.')-- if mail in myres:- self.sf.debug("Already found from this source.")- continue- else:- myres.append(mail)-- evt = SpiderFootEvent("EMAILADDR", mail, self.__name__, event)- self.notifyListeners(evt)-- return None--# End of sfp_email class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_email+# Purpose: SpiderFoot plug-in for scanning retreived content by other+# modules (such as sfp_spider) and identifying e-mail addresses+#+# Author: Steve Micallef <[email protected]>+#+# Created: 06/04/2012+# Copyright: (c) Steve Micallef 2012+# Licence: GPL+# -------------------------------------------------------------------------------++import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_email(SpiderFootPlugin):+ """E-Mail:Footprint,Investigate,Passive:Content Analysis::Identify e-mail addresses in any obtained data."""+++ # Default options+ opts = {+ # options specific to this module+ }++ # Option descriptions+ optdescs = {+ }++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["*"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["EMAILADDR"]++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if eventName.startswith("EMAILADDR"):+ return None++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if type(eventData) not in [str, unicode]:+ self.sf.debug("Unhandled type to find e-mails: " + str(type(eventData)))+ return None++ pat = re.compile("([\%a-zA-Z\.0-9_\-]+@[a-zA-Z\.0-9\-]+\.[a-zA-Z\.0-9\-]+)")+ matches = re.findall(pat, eventData)+ myres = list()+ for match in matches:+ if len(match) < 4:+ self.sf.debug("Likely invalid address: " + match)+ continue++ # Handle messed up encodings+ if "%" in match:+ self.sf.debug("Skipped address: " + match)+ continue++ # Get the doain and strip potential ending .+ mailDom = match.lower().split('@')[1].strip('.')+ if not self.getTarget().matches(mailDom):+ self.sf.debug("Ignoring e-mail address on an external domain: " + match)+ continue++ self.sf.info("Found e-mail address: " + match)+ if type(match) == str:+ mail = unicode(match.strip('.'), 'utf-8', errors='replace')+ else:+ mail = match.strip('.')++ if mail in myres:+ self.sf.debug("Already found from this source.")+ continue+ else:+ myres.append(mail)++ evt = SpiderFootEvent("EMAILADDR", mail, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_email classdiff --git a/modules/sfp_errors.py b/modules/sfp_errors.pyindex 433acf4c..52758a4e 100644--- a/modules/sfp_errors.py+++ b/modules/sfp_errors.py@@ -1,108 +1,109 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_errors-# Purpose: Identify common error messages in content like SQL errors, etc.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 18/01/2015-# Copyright: (c) Steve Micallef 2015-# Licence: GPL-# ---------------------------------------------------------------------------------import re-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent--# Taken from Google Dorks on exploit-db.com-regexps = dict({- "PHP Error": ["PHP pase error", "PHP warning", "PHP error",- "unexpected T_VARIABLE", "warning: failed opening", "include_path="],- "Generic Error": ["Internal Server Error", "Incorrect syntax"],- "Oracle Error": ["ORA-\d+", "TNS:.?no listen"],- "ASP Error": ["NET_SessionId"],- "MySQL Error": ["mysql_query\(", "mysql_connect\("],- "ODBC Error": ["\[ODBC SQL"]--})---class sfp_errors(SpiderFootPlugin):- """Errors:Footprint:Data Analysis::Identify common error messages in content like SQL errors, etc."""-- # Default options- opts = {}-- # Option descriptions- optdescs = {- # For each option in opts you should have a key/value pair here- # describing it. It will end up in the UI to explain the option- # to the end-user.- }-- # Target- results = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- 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 ["TARGET_WEB_CONTENT"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["ERROR_MESSAGE"]-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- # We only want web content from the target- if srcModuleName != "sfp_spider":- return None-- # If you are processing TARGET_WEB_CONTENT, this is how you would get the- # source of that raw data (e.g. a URL.)- eventSource = event.sourceEvent.data-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- if eventSource not in self.results.keys():- self.results[eventSource] = list()-- # We only want web content for pages on the target site- if not self.getTarget().matches(self.sf.urlFQDN(eventSource)):- self.sf.debug("Not collecting web content information for external sites.")- return None-- for regexpGrp in regexps.keys():- if regexpGrp in self.results[eventSource]:- continue-- for regex in regexps[regexpGrp]:- pat = re.compile(regex, re.IGNORECASE)- matches = re.findall(pat, eventData)- if len(matches) > 0 and regexpGrp not in self.results[eventSource]:- self.sf.info("Matched " + regexpGrp + " in content from " + eventSource)- self.results[eventSource].append(regexpGrp)- evt = SpiderFootEvent("ERROR_MESSAGE", regexpGrp,- self.__name__, event.sourceEvent)- self.notifyListeners(evt)-- return None-- # If you intend for this module to act on its own (e.g. not solely rely- # on events from other modules, then you need to have a start() method- # and within that method call self.checkForStop() to see if you've been- # politely asked by the controller to stop your activities (user abort.)--# End of sfp_errors class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_errors+# Purpose: Identify common error messages in content like SQL errors, etc.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 18/01/2015+# Copyright: (c) Steve Micallef 2015+# Licence: GPL+# -------------------------------------------------------------------------------++import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++# Taken from Google Dorks on exploit-db.com+regexps = dict({+ "PHP Error": ["PHP pase error", "PHP warning", "PHP error",+ "unexpected T_VARIABLE", "warning: failed opening", "include_path="],+ "Generic Error": ["Internal Server Error", "Incorrect syntax"],+ "Oracle Error": ["ORA-\d+", "TNS:.?no listen"],+ "ASP Error": ["NET_SessionId"],+ "MySQL Error": ["mysql_query\(", "mysql_connect\("],+ "ODBC Error": ["\[ODBC SQL"]++})+++class sfp_errors(SpiderFootPlugin):+ """Errors:Footprint:Content Analysis::Identify common error messages in content like SQL errors, etc."""+++ # Default options+ opts = {}++ # Option descriptions+ optdescs = {+ # For each option in opts you should have a key/value pair here+ # describing it. It will end up in the UI to explain the option+ # to the end-user.+ }++ # Target+ results = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ 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 ["TARGET_WEB_CONTENT"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["ERROR_MESSAGE"]++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ # We only want web content from the target+ if srcModuleName != "sfp_spider":+ return None++ # If you are processing TARGET_WEB_CONTENT, this is how you would get the+ # source of that raw data (e.g. a URL.)+ eventSource = event.sourceEvent.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventSource not in self.results.keys():+ self.results[eventSource] = list()++ # We only want web content for pages on the target site+ if not self.getTarget().matches(self.sf.urlFQDN(eventSource)):+ self.sf.debug("Not collecting web content information for external sites.")+ return None++ for regexpGrp in regexps.keys():+ if regexpGrp in self.results[eventSource]:+ continue++ for regex in regexps[regexpGrp]:+ pat = re.compile(regex, re.IGNORECASE)+ matches = re.findall(pat, eventData)+ if len(matches) > 0 and regexpGrp not in self.results[eventSource]:+ self.sf.info("Matched " + regexpGrp + " in content from " + eventSource)+ self.results[eventSource].append(regexpGrp)+ evt = SpiderFootEvent("ERROR_MESSAGE", regexpGrp,+ self.__name__, event.sourceEvent)+ self.notifyListeners(evt)++ return None++ # If you intend for this module to act on its own (e.g. not solely rely+ # on events from other modules, then you need to have a start() method+ # and within that method call self.checkForStop() to see if you've been+ # politely asked by the controller to stop your activities (user abort.)++# End of sfp_errors classdiff --git a/modules/sfp_filemeta.py b/modules/sfp_filemeta.pyindex 8c477584..e7cf1b3b 100644--- a/modules/sfp_filemeta.py+++ b/modules/sfp_filemeta.py@@ -1,171 +1,172 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_filemeta-# Purpose: From Spidering and from searching search engines, extracts file-# meta data from files matching certain file extensions.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 25/04/2014-# Copyright: (c) Steve Micallef 2014-# Licence: GPL-# ---------------------------------------------------------------------------------import mimetypes-import PyPDF2-import openxmllib-import exifread-import lxml-from StringIO import StringIO-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_filemeta(SpiderFootPlugin):- """File Metadata:Footprint:Data Analysis:invasive,slow:Extracts meta data from documents and images."""-- # Default options- opts = {- 'fileexts': ["docx", "pptx", 'xlsx', 'pdf', 'jpg', 'jpeg', 'tiff', 'tif'],- 'timeout': 300- }-- # Option descriptions- optdescs = {- 'fileexts': "File extensions of files you want to analyze the meta data of (only PDF, DOCX, XLSX and PPTX are supported.)",- 'timeout': "Download timeout for files, in seconds."- }-- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["LINKED_URL_INTERNAL", "INTERESTING_FILE"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["RAW_FILE_META_DATA", "SOFTWARE_USED"]-- # 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:- return None- else:- self.results.append(eventData)-- for fileExt in self.opts['fileexts']:- if self.checkForStop():- return None-- if "." + fileExt.lower() in eventData.lower():- # Fetch the file, allow much more time given that these files are- # typically large.- ret = self.sf.fetchUrl(eventData, timeout=self.opts['timeout'],- useragent=self.opts['_useragent'], dontMangle=True,- sizeLimit=10000000)- if ret['content'] is None:- self.sf.error("Unable to fetch file for meta analysis: " +- eventData, False)- return None-- if len(ret['content']) < 512:- self.sf.error("Strange content encountered, size of " +- str(len(ret['content'])), False)- return None-- meta = None- data = None- # Based on the file extension, handle it- if fileExt.lower() == "pdf":- try:- raw = StringIO(ret['content'])- #data = metapdf.MetaPdfReader().read_metadata(raw)- pdf = PyPDF2.PdfFileReader(raw, strict=False)- data = pdf.getDocumentInfo()- meta = str(data)- self.sf.debug("Obtained meta data from " + eventData)- except BaseException as e:- self.sf.error("Unable to parse meta data from: " +- eventData + "(" + str(e) + ")", False)- return None-- if fileExt.lower() in ["pptx", "docx", "xlsx"]:- try:- mtype = mimetypes.guess_type(eventData)[0]- doc = openxmllib.openXmlDocument(data=ret['content'], mime_type=mtype)- self.sf.debug("Office type: " + doc.mimeType)- data = doc.allProperties- meta = str(data)- except ValueError as e:- self.sf.error("Unable to parse meta data from: " +- eventData + "(" + str(e) + ")", False)- return None- except lxml.etree.XMLSyntaxError as e:- self.sf.error("Unable to parse XML within: " +- eventData + "(" + str(e) + ")", False)- return None- except BaseException as e:- self.sf.error("Unable to process file: " +- eventData + "(" + str(e) + ")", False)- return None-- if fileExt.lower() in ["jpg", "jpeg", "tiff"]:- try:- raw = StringIO(ret['content'])- data = exifread.process_file(raw)- if data is None or len(data) == 0:- continue- meta = str(data)- except BaseException as e:- self.sf.error("Unable to parse meta data from: " +- eventData + "(" + str(e) + ")", False)- return None-- if meta is not None and data is not None:- evt = SpiderFootEvent("RAW_FILE_META_DATA", meta,- self.__name__, event)- self.notifyListeners(evt)-- val = None- try:- if "/Producer" in data:- val = data['/Producer']-- if "/Creator" in data:- if "/Producer" in data:- if data['/Creator'] != data['/Producer']:- val = data['/Creator']- else:- val = data['/Creator']-- if "Application" in data:- val = data['Application']-- if "Image Software" in data:- val = str(data['Image Software'])- except BaseException as e:- self.sf.error("Failed to parse PDF, " + eventData + ": " + str(e), False)- return None-- if val is not None:- # Strip non-ASCII- val = ''.join([i if ord(i) < 128 else ' ' for i in val])- evt = SpiderFootEvent("SOFTWARE_USED", val,- self.__name__, event)- self.notifyListeners(evt)--# End of sfp_filemeta class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_filemeta+# Purpose: From Spidering and from searching search engines, extracts file+# meta data from files matching certain file extensions.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 25/04/2014+# Copyright: (c) Steve Micallef 2014+# Licence: GPL+# -------------------------------------------------------------------------------++import mimetypes+import PyPDF2+import openxmllib+import exifread+import lxml+from StringIO import StringIO+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_filemeta(SpiderFootPlugin):+ """File Metadata:Footprint:Content Analysis:invasive,slow:Extracts meta data from documents and images."""+++ # Default options+ opts = {+ 'fileexts': ["docx", "pptx", 'xlsx', 'pdf', 'jpg', 'jpeg', 'tiff', 'tif'],+ 'timeout': 300+ }++ # Option descriptions+ optdescs = {+ 'fileexts': "File extensions of files you want to analyze the meta data of (only PDF, DOCX, XLSX and PPTX are supported.)",+ 'timeout': "Download timeout for files, in seconds."+ }++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["LINKED_URL_INTERNAL", "INTERESTING_FILE"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["RAW_FILE_META_DATA", "SOFTWARE_USED"]++ # 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:+ return None+ else:+ self.results.append(eventData)++ for fileExt in self.opts['fileexts']:+ if self.checkForStop():+ return None++ if "." + fileExt.lower() in eventData.lower():+ # Fetch the file, allow much more time given that these files are+ # typically large.+ ret = self.sf.fetchUrl(eventData, timeout=self.opts['timeout'],+ useragent=self.opts['_useragent'], dontMangle=True,+ sizeLimit=10000000)+ if ret['content'] is None:+ self.sf.error("Unable to fetch file for meta analysis: " ++ eventData, False)+ return None++ if len(ret['content']) < 512:+ self.sf.error("Strange content encountered, size of " ++ str(len(ret['content'])), False)+ return None++ meta = None+ data = None+ # Based on the file extension, handle it+ if fileExt.lower() == "pdf":+ try:+ raw = StringIO(ret['content'])+ #data = metapdf.MetaPdfReader().read_metadata(raw)+ pdf = PyPDF2.PdfFileReader(raw, strict=False)+ data = pdf.getDocumentInfo()+ meta = str(data)+ self.sf.debug("Obtained meta data from " + eventData)+ except BaseException as e:+ self.sf.error("Unable to parse meta data from: " ++ eventData + "(" + str(e) + ")", False)+ return None++ if fileExt.lower() in ["pptx", "docx", "xlsx"]:+ try:+ mtype = mimetypes.guess_type(eventData)[0]+ doc = openxmllib.openXmlDocument(data=ret['content'], mime_type=mtype)+ self.sf.debug("Office type: " + doc.mimeType)+ data = doc.allProperties+ meta = str(data)+ except ValueError as e:+ self.sf.error("Unable to parse meta data from: " ++ eventData + "(" + str(e) + ")", False)+ return None+ except lxml.etree.XMLSyntaxError as e:+ self.sf.error("Unable to parse XML within: " ++ eventData + "(" + str(e) + ")", False)+ return None+ except BaseException as e:+ self.sf.error("Unable to process file: " ++ eventData + "(" + str(e) + ")", False)+ return None++ if fileExt.lower() in ["jpg", "jpeg", "tiff"]:+ try:+ raw = StringIO(ret['content'])+ data = exifread.process_file(raw)+ if data is None or len(data) == 0:+ continue+ meta = str(data)+ except BaseException as e:+ self.sf.error("Unable to parse meta data from: " ++ eventData + "(" + str(e) + ")", False)+ return None++ if meta is not None and data is not None:+ evt = SpiderFootEvent("RAW_FILE_META_DATA", meta,+ self.__name__, event)+ self.notifyListeners(evt)++ val = None+ try:+ if "/Producer" in data:+ val = data['/Producer']++ if "/Creator" in data:+ if "/Producer" in data:+ if data['/Creator'] != data['/Producer']:+ val = data['/Creator']+ else:+ val = data['/Creator']++ if "Application" in data:+ val = data['Application']++ if "Image Software" in data:+ val = str(data['Image Software'])+ except BaseException as e:+ self.sf.error("Failed to parse PDF, " + eventData + ": " + str(e), False)+ return None++ if val is not None:+ # Strip non-ASCII+ val = ''.join([i if ord(i) < 128 else ' ' for i in val])+ evt = SpiderFootEvent("SOFTWARE_USED", val,+ self.__name__, event)+ self.notifyListeners(evt)++# End of sfp_filemeta classdiff --git a/modules/sfp_fortinet.py b/modules/sfp_fortinet.pyindex a02a9386..d25be366 100644--- a/modules/sfp_fortinet.py+++ b/modules/sfp_fortinet.py@@ -1,263 +1,264 @@-# -*- 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 class+# -*- 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:Reputation Systems: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_fraudguard.py b/modules/sfp_fraudguard.pyindex 0bf2b3aa..315cc22d 100644--- a/modules/sfp_fraudguard.py+++ b/modules/sfp_fraudguard.py@@ -18,7 +18,8 @@ from netaddr import IPNetworkfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEventclass sfp_fraudguard(SpiderFootPlugin):- """Fraudguard:Investigate,Passive:Search Engines:apikey:Obtain threat information from Fraudguard.io"""+ """Fraudguard:Investigate,Passive:Reputation Systems:apikey:Obtain threat information from Fraudguard.io"""+# Default optionsopts = {diff --git a/modules/sfp_freegeoip.py b/modules/sfp_freegeoip.pyindex e2f3c27c..a697935b 100644--- a/modules/sfp_freegeoip.py+++ b/modules/sfp_freegeoip.py@@ -1,75 +1,76 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_freegeoip-# Purpose: SpiderFoot plug-in to identify the Geo-location of IP addresses-# identified by other modules using freegeoip.net.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 18/02/2013-# Copyright: (c) Steve Micallef 2013-# Licence: GPL-# ---------------------------------------------------------------------------------import json-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_freegeoip(SpiderFootPlugin):- """FreeGeoIP:Footprint,Investigate,Passive:Networking::Identifies the physical location of IP addresses identified using freegeoip.net."""-- # Default options- opts = {}- results = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ['IP_ADDRESS']-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["GEOINFO"]-- # 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)-- # Don't look up stuff twice- if eventData in self.results:- self.sf.debug("Skipping " + eventData + " as already mapped.")- return None- else:- self.results[eventData] = True-- res = self.sf.fetchUrl("https://freegeoip.net/json/" + eventData,- timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])- if res['content'] is None:- self.sf.info("No GeoIP info found for " + eventData)- try:- hostip = json.loads(res['content'])- except Exception as e:- self.sf.debug("Error processing JSON response.")- return None-- self.sf.info("Found GeoIP for " + eventData + ": " + hostip['country_name'])- countrycity = hostip['country_name']-- evt = SpiderFootEvent("GEOINFO", countrycity, self.__name__, event)- self.notifyListeners(evt)-- return None--# End of sfp_freegeoip class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_freegeoip+# Purpose: SpiderFoot plug-in to identify the Geo-location of IP addresses+# identified by other modules using freegeoip.net.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 18/02/2013+# Copyright: (c) Steve Micallef 2013+# Licence: GPL+# -------------------------------------------------------------------------------++import json+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_freegeoip(SpiderFootPlugin):+ """FreeGeoIP:Footprint,Investigate,Passive:Real World::Identifies the physical location of IP addresses identified using freegeoip.net."""+++ # Default options+ opts = {}+ results = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ['IP_ADDRESS']++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["GEOINFO"]++ # 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)++ # Don't look up stuff twice+ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + " as already mapped.")+ return None+ else:+ self.results[eventData] = True++ res = self.sf.fetchUrl("https://freegeoip.net/json/" + eventData,+ timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.info("No GeoIP info found for " + eventData)+ try:+ hostip = json.loads(res['content'])+ except Exception as e:+ self.sf.debug("Error processing JSON response.")+ return None++ self.sf.info("Found GeoIP for " + eventData + ": " + hostip['country_name'])+ countrycity = hostip['country_name']++ evt = SpiderFootEvent("GEOINFO", countrycity, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_freegeoip classdiff --git a/modules/sfp_github.py b/modules/sfp_github.pyindex 3f3a0608..40cf9f63 100644--- a/modules/sfp_github.py+++ b/modules/sfp_github.py@@ -1,180 +1,181 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_github-# Purpose: Identifies public code repositories in Github associated with-# your target.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 21/07/2015-# Copyright: (c) Steve Micallef 2015-# Licence: GPL-# ---------------------------------------------------------------------------------import json-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent--class sfp_github(SpiderFootPlugin):- """Github:Footprint,Passive:Social::Identify associated public code repositories on Github."""-- # Default options- opts = {- 'namesonly': True- }-- # Option descriptions- optdescs = {- 'namesonly': "Match repositories by name only, not by their descriptions. Helps reduce false positives."- }-- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["DOMAIN_NAME", "USERNAME", "SOCIAL_MEDIA"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["PUBLIC_CODE_REPO"]-- # Build up repo info for use as an event- def buildRepoInfo(self, item):- repo_info = None-- # Get repos matching the name- if item['name'] == None:- self.sf.debug("Incomplete Github information found (name).")- return None- if item['html_url'] == None:- self.sf.debug("Incomplete Github information found (url).")- return None- if item['description'] == None:- self.sf.debug("Incomplete Github information found (description).")- return None-- repo_info = "Name: " + item['name'] + "\n" + "URL: " + item['html_url'] + \- "\n" + "Description: " + item['description']-- return repo_info--- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if eventData in self.results:- self.sf.debug("Already did a search for " + eventData + ", skipping.")- return None- else:- self.results.append(eventData)-- if eventName == "DOMAIN_NAME":- name = self.sf.domainKeyword(eventData, self.opts['_internettlds'])- if eventName == "USERNAME":- name = eventData- if eventName == "SOCIAL_MEDIA":- name = eventData.split(": ")[1]-- self.sf.debug("Looking at " + name)- failed = False- # Get all the repositories based on direct matches with the- # name identified- url = "https://api.github.com/search/repositories?q=" + name- res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],- useragent="SpiderFoot")-- if res['content'] == None:- self.sf.error("Unable to fetch " + url, False)- failed = True-- try:- ret = json.loads(res['content'])- except BaseException as e:- ret = None-- if ret == None:- self.sf.error("Unable to process empty response from Github for: " + \- name, False)- failed = True-- if not failed:- if ret['total_count'] == "0" or len(ret['items']) == 0:- self.sf.debug("No Github information for " + name)- failed = True-- if not failed:- for item in ret['items']:- repo_info = self.buildRepoInfo(item)- if repo_info != None:- if self.opts['namesonly'] and name not in item['name']:- continue-- evt = SpiderFootEvent("PUBLIC_CODE_REPO", repo_info,- self.__name__, event)- self.notifyListeners(evt)-- # Now look for users matching the name found- failed = False- url = "https://api.github.com/search/users?q=" + name- res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],- useragent="SpiderFoot")-- if res['content'] == None:- self.sf.error("Unable to fetch " + url, False)- failed = True-- if not failed:- ret = json.loads(res['content'])- if ret == None:- self.sf.error("Unable to process empty response from Github for: " + \- name, False)- failed = True-- if not failed:- if ret['total_count'] == "0" or len(ret['items']) == 0:- self.sf.debug("No Github information for " + name)- failed = True-- if not failed:- # For each user matching the name, get their repos- for item in ret['items']:- if item['repos_url'] == None:- self.sf.debug("Incomplete Github information found (repos_url).")- continue-- url = item['repos_url']- res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],- useragent="SpiderFoot")-- if res['content'] == None:- self.sf.error("Unable to fetch " + url, False)- continue-- repret = json.loads(res['content'])- if repret == None:- self.sf.error("Unable to process empty response from Github for: " + \- name, False)- continue-- for item in repret:- repo_info = self.buildRepoInfo(item)- if repo_info != None:- if self.opts['namesonly'] and name not in item['name']:- continue-- evt = SpiderFootEvent("PUBLIC_CODE_REPO", repo_info,- self.__name__, event)- self.notifyListeners(evt)---# End of sfp_github class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_github+# Purpose: Identifies public code repositories in Github associated with+# your target.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 21/07/2015+# Copyright: (c) Steve Micallef 2015+# Licence: GPL+# -------------------------------------------------------------------------------++import json+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++class sfp_github(SpiderFootPlugin):+ """Github:Footprint,Passive:Social Media::Identify associated public code repositories on Github."""+++ # Default options+ opts = {+ 'namesonly': True+ }++ # Option descriptions+ optdescs = {+ 'namesonly': "Match repositories by name only, not by their descriptions. Helps reduce false positives."+ }++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["DOMAIN_NAME", "USERNAME", "SOCIAL_MEDIA"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["PUBLIC_CODE_REPO"]++ # Build up repo info for use as an event+ def buildRepoInfo(self, item):+ repo_info = None++ # Get repos matching the name+ if item['name'] == None:+ self.sf.debug("Incomplete Github information found (name).")+ return None+ if item['html_url'] == None:+ self.sf.debug("Incomplete Github information found (url).")+ return None+ if item['description'] == None:+ self.sf.debug("Incomplete Github information found (description).")+ return None++ repo_info = "Name: " + item['name'] + "\n" + "URL: " + item['html_url'] + \+ "\n" + "Description: " + item['description']++ return repo_info+++ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if eventData in self.results:+ self.sf.debug("Already did a search for " + eventData + ", skipping.")+ return None+ else:+ self.results.append(eventData)++ if eventName == "DOMAIN_NAME":+ name = self.sf.domainKeyword(eventData, self.opts['_internettlds'])+ if eventName == "USERNAME":+ name = eventData+ if eventName == "SOCIAL_MEDIA":+ name = eventData.split(": ")[1]++ self.sf.debug("Looking at " + name)+ failed = False+ # Get all the repositories based on direct matches with the+ # name identified+ url = "https://api.github.com/search/repositories?q=" + name+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],+ useragent="SpiderFoot")++ if res['content'] == None:+ self.sf.error("Unable to fetch " + url, False)+ failed = True++ try:+ ret = json.loads(res['content'])+ except BaseException as e:+ ret = None++ if ret == None:+ self.sf.error("Unable to process empty response from Github for: " + \+ name, False)+ failed = True++ if not failed:+ if ret['total_count'] == "0" or len(ret['items']) == 0:+ self.sf.debug("No Github information for " + name)+ failed = True++ if not failed:+ for item in ret['items']:+ repo_info = self.buildRepoInfo(item)+ if repo_info != None:+ if self.opts['namesonly'] and name not in item['name']:+ continue++ evt = SpiderFootEvent("PUBLIC_CODE_REPO", repo_info,+ self.__name__, event)+ self.notifyListeners(evt)++ # Now look for users matching the name found+ failed = False+ url = "https://api.github.com/search/users?q=" + name+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],+ useragent="SpiderFoot")++ if res['content'] == None:+ self.sf.error("Unable to fetch " + url, False)+ failed = True++ if not failed:+ ret = json.loads(res['content'])+ if ret == None:+ self.sf.error("Unable to process empty response from Github for: " + \+ name, False)+ failed = True++ if not failed:+ if ret['total_count'] == "0" or len(ret['items']) == 0:+ self.sf.debug("No Github information for " + name)+ failed = True++ if not failed:+ # For each user matching the name, get their repos+ for item in ret['items']:+ if item['repos_url'] == None:+ self.sf.debug("Incomplete Github information found (repos_url).")+ continue++ url = item['repos_url']+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],+ useragent="SpiderFoot")++ if res['content'] == None:+ self.sf.error("Unable to fetch " + url, False)+ continue++ repret = json.loads(res['content'])+ if repret == None:+ self.sf.error("Unable to process empty response from Github for: " + \+ name, False)+ continue++ for item in repret:+ repo_info = self.buildRepoInfo(item)+ if repo_info != None:+ if self.opts['namesonly'] and name not in item['name']:+ continue++ evt = SpiderFootEvent("PUBLIC_CODE_REPO", repo_info,+ self.__name__, event)+ self.notifyListeners(evt)+++# End of sfp_github classdiff --git a/modules/sfp_googlemaps.py b/modules/sfp_googlemaps.pyindex e6d2d588..a44119b6 100644--- a/modules/sfp_googlemaps.py+++ b/modules/sfp_googlemaps.py@@ -1,90 +1,91 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_googlemaps-# Purpose: SpiderFoot plug-in to identify historical certificates for a domain-# from googlemaps.sh, and from this identify hostnames.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 18/03/2017-# Copyright: (c) Steve Micallef 2017-# Licence: GPL-# ---------------------------------------------------------------------------------import json-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_googlemaps(SpiderFootPlugin):- """Google Maps:Footprint,Investigate,Passive:Search Engines::Identifies potential physical addresses and latitude/longitude coordinates."""-- # Default options- opts = {}- results = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ['DOMAIN_NAME', 'PHYSICAL_ADDRESS']-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["PHYSICAL_ADDRESS", "PHYSICAL_COORDINATES"]-- # 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)-- # Don't look up stuff twice- if eventData in self.results:- self.sf.debug("Skipping " + eventData + " as already mapped.")- return None- else:- self.results[eventData] = True-- res = self.sf.fetchUrl("https://maps.googleapis.com/maps/api/geocode/json?address=" + \- eventData, timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])- if res['content'] is None:- self.sf.info("No location info found for " + eventData)- return None-- evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", res['content'],- self.__name__, event)- self.notifyListeners(evt)-- try:- data = json.loads(res['content'])['results'][0]-- if eventName in ["PHYSICAL_ADDRESS", "DOMAIN_NAME"] and \- srcModuleName != "sfp_googlemaps":- if 'geometry' in data:- lat = str(data['geometry']['location']['lat'])- lng = str(data['geometry']['location']['lng'])- evt = SpiderFootEvent("PHYSICAL_COORDINATES", lat + "," + lng,- self.__name__, event)- self.notifyListeners(evt)-- if 'formatted_address' in data:- evt = SpiderFootEvent("PHYSICAL_ADDRESS", data['formatted_address'],- self.__name__, event)- self.notifyListeners(evt)- except Exception as e:- self.sf.debug("Error processing JSON response: " + str(e))- return None-- return None--# End of sfp_googlemaps class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_googlemaps+# Purpose: SpiderFoot plug-in to identify historical certificates for a domain+# from googlemaps.sh, and from this identify hostnames.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 18/03/2017+# Copyright: (c) Steve Micallef 2017+# Licence: GPL+# -------------------------------------------------------------------------------++import json+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_googlemaps(SpiderFootPlugin):+ """Google Maps:Footprint,Investigate,Passive:Real World::Identifies potential physical addresses and latitude/longitude coordinates."""+++ # Default options+ opts = {}+ results = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ['DOMAIN_NAME', 'PHYSICAL_ADDRESS']++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["PHYSICAL_ADDRESS", "PHYSICAL_COORDINATES"]++ # 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)++ # Don't look up stuff twice+ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + " as already mapped.")+ return None+ else:+ self.results[eventData] = True++ res = self.sf.fetchUrl("https://maps.googleapis.com/maps/api/geocode/json?address=" + \+ eventData, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])+ if res['content'] is None:+ self.sf.info("No location info found for " + eventData)+ return None++ evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", res['content'],+ self.__name__, event)+ self.notifyListeners(evt)++ try:+ data = json.loads(res['content'])['results'][0]++ if eventName in ["PHYSICAL_ADDRESS", "DOMAIN_NAME"] and \+ srcModuleName != "sfp_googlemaps":+ if 'geometry' in data:+ lat = str(data['geometry']['location']['lat'])+ lng = str(data['geometry']['location']['lng'])+ evt = SpiderFootEvent("PHYSICAL_COORDINATES", lat + "," + lng,+ self.__name__, event)+ self.notifyListeners(evt)++ if 'formatted_address' in data:+ evt = SpiderFootEvent("PHYSICAL_ADDRESS", data['formatted_address'],+ self.__name__, event)+ self.notifyListeners(evt)+ except Exception as e:+ self.sf.debug("Error processing JSON response: " + str(e))+ return None++ return None++# End of sfp_googlemaps classdiff --git a/modules/sfp_googlesearch.py b/modules/sfp_googlesearch.pyindex 0ba51125..d0367879 100644--- a/modules/sfp_googlesearch.py+++ b/modules/sfp_googlesearch.py@@ -1,101 +1,102 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_googlesearch-# Purpose: Searches Google for content related to the domain in question.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 07/05/2012-# Copyright: (c) Steve Micallef 2012-# Licence: GPL-# ---------------------------------------------------------------------------------from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_googlesearch(SpiderFootPlugin):- """Google Search:Footprint,Investigate,Passive:Search Engines:errorprone:Some light Google scraping to identify sub-domains and links."""-- # Default options- opts = {- 'pages': 20 # Number of google results pages to iterate- }-- # Option descriptions- optdescs = {- 'pages': "Number of Google results pages to iterate through."- }-- # Target- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["INTERNET_NAME"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["LINKED_URL_INTERNAL", "SEARCH_ENGINE_WEB_CONTENT"]-- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if eventData in self.results:- self.sf.debug("Already did a search for " + eventData + ", skipping.")- return None- else:- self.results.append(eventData)-- # Sites hosted on the domain- pages = self.sf.googleIterate("site:" + eventData,- dict(limit=self.opts['pages'], useragent=self.opts['_useragent'],- timeout=self.opts['_fetchtimeout']))- if pages is None:- self.sf.info("No results returned from Google.")- return None-- for page in pages.keys():- found = False- if page in self.results:- continue- else:- self.results.append(page)-- links = self.sf.parseLinks(page, pages[page], eventData)- if len(links) == 0:- continue-- for link in links:- if self.checkForStop():- return None-- if link in self.results:- continue- else:- self.results.append(link)- self.sf.debug("Found a link: " + link)- if self.sf.urlFQDN(link).endswith(eventData):- found = True- evt = SpiderFootEvent("LINKED_URL_INTERNAL", link,- self.__name__, event)- self.notifyListeners(evt)-- if found:- # Submit the google results for analysis- evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", pages[page],- self.__name__, event)- self.notifyListeners(evt)---# End of sfp_googlesearch class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_googlesearch+# Purpose: Searches Google for content related to the domain in question.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 07/05/2012+# Copyright: (c) Steve Micallef 2012+# Licence: GPL+# -------------------------------------------------------------------------------++from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_googlesearch(SpiderFootPlugin):+ """Google Search:Footprint,Investigate,Passive:Search Engines:errorprone:Some light Google scraping to identify sub-domains and links."""+++ # Default options+ opts = {+ 'pages': 20 # Number of google results pages to iterate+ }++ # Option descriptions+ optdescs = {+ 'pages': "Number of Google results pages to iterate through."+ }++ # Target+ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["INTERNET_NAME"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["LINKED_URL_INTERNAL", "SEARCH_ENGINE_WEB_CONTENT"]++ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if eventData in self.results:+ self.sf.debug("Already did a search for " + eventData + ", skipping.")+ return None+ else:+ self.results.append(eventData)++ # Sites hosted on the domain+ pages = self.sf.googleIterate("site:" + eventData,+ dict(limit=self.opts['pages'], useragent=self.opts['_useragent'],+ timeout=self.opts['_fetchtimeout']))+ if pages is None:+ self.sf.info("No results returned from Google.")+ return None++ for page in pages.keys():+ found = False+ if page in self.results:+ continue+ else:+ self.results.append(page)++ links = self.sf.parseLinks(page, pages[page], eventData)+ if len(links) == 0:+ continue++ for link in links:+ if self.checkForStop():+ return None++ if link in self.results:+ continue+ else:+ self.results.append(link)+ self.sf.debug("Found a link: " + link)+ if self.sf.urlFQDN(link).endswith(eventData):+ found = True+ evt = SpiderFootEvent("LINKED_URL_INTERNAL", link,+ self.__name__, event)+ self.notifyListeners(evt)++ if found:+ # Submit the google results for analysis+ evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", pages[page],+ self.__name__, event)+ self.notifyListeners(evt)+++# End of sfp_googlesearch classdiff --git a/modules/sfp_googlesearchdomain.py b/modules/sfp_googlesearchdomain.pyindex 5d4b5ee7..b3aa9c21 100644--- a/modules/sfp_googlesearchdomain.py+++ b/modules/sfp_googlesearchdomain.py@@ -1,116 +1,117 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_googlesearchdomain-# Purpose: Searches Google for content related to the domain in question.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 07/05/2012-# Copyright: (c) Steve Micallef 2012-# Licence: GPL-# ---------------------------------------------------------------------------------from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_googlesearchdomain(SpiderFootPlugin):- """Google Search, by domain:Footprint,Investigate,Passive:Search Engines:errorprone:Some light Google scraping to identify sub-domains and links within site:domain contexts you specify."""-- # Default options- opts = {- 'pages': 20, # Number of google results pages to iterate- 'sites': ""- }-- # Option descriptions- optdescs = {- 'pages': "Number of Google results pages to iterate through.",- 'sites': "Comma-separated list of site: entries to search for your target. For example, specifying youtube.com,facebook.com will use Google to search within youtube.com and facebook.com for mentions of your target. This should NOT be set to the domain name of your target, because that is what the sfp_googlesearch module will cover."- }-- # Target- results = list()- errorState = False-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["INTERNET_NAME"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["LINKED_URL_EXTERNAL", "SEARCH_ENGINE_WEB_CONTENT"]-- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if self.errorState:- return None-- if eventData in self.results:- self.sf.debug("Already did a search for " + eventData + ", skipping.")- return None- else:- self.results.append(eventData)-- if len(self.opts['sites']) == 0:- self.sf.error("You enabled sfp_googlesearchdomain but did not specify any sites!", False)- self.errorState = True- return None-- for dom in self.opts['sites'].split(","):- if self.checkForStop():- return None-- # Sites hosted on the domain- pages = self.sf.googleIterate(eventData + "%20site:" + dom,- dict(limit=self.opts['pages'], useragent=self.opts['_useragent'],- timeout=self.opts['_fetchtimeout']))- if pages is None:- self.sf.info("No results returned from Google for " + dom + ".")- return None-- for page in pages.keys():- found = False- if page in self.results:- continue- else:- self.results.append(page)-- links = self.sf.parseLinks(page, pages[page], dom)- if len(links) == 0:- continue-- for link in links:- if self.checkForStop():- return None-- if link in self.results:- continue- else:- self.results.append(link)- self.sf.debug("Found a link: " + link)- if self.sf.urlFQDN(link).endswith(dom):- found = True- evt = SpiderFootEvent("LINKED_URL_EXTERNAL", link,- self.__name__, event)- self.notifyListeners(evt)-- if found:- # Submit the google results for analysis- evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", pages[page],- self.__name__, event)- self.notifyListeners(evt)---# End of sfp_googlesearchdomain class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_googlesearchdomain+# Purpose: Searches Google for content related to the domain in question.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 07/05/2012+# Copyright: (c) Steve Micallef 2012+# Licence: GPL+# -------------------------------------------------------------------------------++from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_googlesearchdomain(SpiderFootPlugin):+ """Google Search, by domain:Footprint,Investigate,Passive:Search Engines:errorprone:Some light Google scraping to identify sub-domains and links within site:domain contexts you specify."""+++ # Default options+ opts = {+ 'pages': 20, # Number of google results pages to iterate+ 'sites': ""+ }++ # Option descriptions+ optdescs = {+ 'pages': "Number of Google results pages to iterate through.",+ 'sites': "Comma-separated list of site: entries to search for your target. For example, specifying youtube.com,facebook.com will use Google to search within youtube.com and facebook.com for mentions of your target. This should NOT be set to the domain name of your target, because that is what the sfp_googlesearch module will cover."+ }++ # Target+ results = list()+ errorState = False++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["INTERNET_NAME"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["LINKED_URL_EXTERNAL", "SEARCH_ENGINE_WEB_CONTENT"]++ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if self.errorState:+ return None++ if eventData in self.results:+ self.sf.debug("Already did a search for " + eventData + ", skipping.")+ return None+ else:+ self.results.append(eventData)++ if len(self.opts['sites']) == 0:+ self.sf.error("You enabled sfp_googlesearchdomain but did not specify any sites!", False)+ self.errorState = True+ return None++ for dom in self.opts['sites'].split(","):+ if self.checkForStop():+ return None++ # Sites hosted on the domain+ pages = self.sf.googleIterate(eventData + "%20site:" + dom,+ dict(limit=self.opts['pages'], useragent=self.opts['_useragent'],+ timeout=self.opts['_fetchtimeout']))+ if pages is None:+ self.sf.info("No results returned from Google for " + dom + ".")+ return None++ for page in pages.keys():+ found = False+ if page in self.results:+ continue+ else:+ self.results.append(page)++ links = self.sf.parseLinks(page, pages[page], dom)+ if len(links) == 0:+ continue++ for link in links:+ if self.checkForStop():+ return None++ if link in self.results:+ continue+ else:+ self.results.append(link)+ self.sf.debug("Found a link: " + link)+ if self.sf.urlFQDN(link).endswith(dom):+ found = True+ evt = SpiderFootEvent("LINKED_URL_EXTERNAL", link,+ self.__name__, event)+ self.notifyListeners(evt)++ if found:+ # Submit the google results for analysis+ evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", pages[page],+ self.__name__, event)+ self.notifyListeners(evt)+++# End of sfp_googlesearchdomain classdiff --git a/modules/sfp_hackertarget.py b/modules/sfp_hackertarget.pyindex ccc18b13..5724118c 100644--- a/modules/sfp_hackertarget.py+++ b/modules/sfp_hackertarget.py@@ -1,126 +1,127 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_hackertarget-# Purpose: Searches Hackertarget.com for hosts sharing the same IP.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 12/04/2014-# Copyright: (c) Steve Micallef 2014-# Licence: GPL-# ---------------------------------------------------------------------------------import re-import socket-from netaddr import IPNetwork-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_hackertarget(SpiderFootPlugin):- """HackerTarget.com:Footprint,Investigate,Passive:Networking:errorprone:Search HackerTarget.com for hosts sharing the same IP."""-- # Default options- opts = {- 'cohostsamedomain': False,- 'verify': True- }-- # Option descriptions- optdescs = {- 'cohostsamedomain': "Treat co-hosted sites on the same target domain as co-hosting?",- 'verify': "Verify co-hosts are valid by checking if they still resolve to the shared IP."- }-- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["IP_ADDRESS", "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 ["CO_HOSTED_SITE"]-- def validateIP(self, host, ip):- try:- addrs = socket.gethostbyname_ex(host)- except BaseException as e:- self.sf.debug("Unable to resolve " + host + ": " + str(e))- return False-- for addr in addrs:- if type(addr) == list:- for a in addr:- if str(a) == ip:- return True- else:- if str(addr) == ip:- return True- return False-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- self.currentEventSrc = event-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- # Don't look up stuff twice- if eventData in self.results:- self.sf.debug("Skipping " + eventData + " as already mapped.")- return None-- qrylist = list()- if eventName.startswith("NETBLOCK_"):- for ipaddr in IPNetwork(eventData):- if str(ipaddr) not in self.results:- qrylist.append(str(ipaddr))- self.results.append(str(ipaddr))- else:- qrylist.append(eventData)- self.results.append(eventData)-- myres = list()-- for ip in qrylist:- if self.checkForStop():- return None-- res = self.sf.fetchUrl("http://api.hackertarget.com/reverseiplookup/?q=" + eventData,- useragent=self.opts['_useragent'],- timeout=self.opts['_fetchtimeout'])- if res['content'] is None:- self.sf.error("Unable to fetch hackertarget.com content.", False)- continue-- if "No records" not in res['content']:- hosts = res['content'].split('\n')- for h in hosts:- if " " in h:- continue- self.sf.info("Found something on same IP: " + h)- if not self.opts['cohostsamedomain']:- if self.getTarget().matches(h, includeParents=True):- self.sf.debug("Skipping " + h + " because it is on the same domain.")- continue-- if h not in myres and h != ip:- if self.opts['verify'] and not self.validateIP(h, ip):- self.sf.debug("Host no longer resolves to our IP.")- continue- evt = SpiderFootEvent("CO_HOSTED_SITE", h.lower(), self.__name__, event)- self.notifyListeners(evt)- myres.append(h.lower())--# End of sfp_hackertarget class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_hackertarget+# Purpose: Searches Hackertarget.com for hosts sharing the same IP.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 12/04/2014+# Copyright: (c) Steve Micallef 2014+# Licence: GPL+# -------------------------------------------------------------------------------++import re+import socket+from netaddr import IPNetwork+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_hackertarget(SpiderFootPlugin):+ """HackerTarget.com:Footprint,Investigate,Passive:Reputation Systems:errorprone:Search HackerTarget.com for hosts sharing the same IP."""+++ # Default options+ opts = {+ 'cohostsamedomain': False,+ 'verify': True+ }++ # Option descriptions+ optdescs = {+ 'cohostsamedomain': "Treat co-hosted sites on the same target domain as co-hosting?",+ 'verify': "Verify co-hosts are valid by checking if they still resolve to the shared IP."+ }++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["IP_ADDRESS", "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 ["CO_HOSTED_SITE"]++ def validateIP(self, host, ip):+ try:+ addrs = socket.gethostbyname_ex(host)+ except BaseException as e:+ self.sf.debug("Unable to resolve " + host + ": " + str(e))+ return False++ for addr in addrs:+ if type(addr) == list:+ for a in addr:+ if str(a) == ip:+ return True+ else:+ if str(addr) == ip:+ return True+ return False++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ self.currentEventSrc = event++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ # Don't look up stuff twice+ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + " as already mapped.")+ return None++ qrylist = list()+ if eventName.startswith("NETBLOCK_"):+ for ipaddr in IPNetwork(eventData):+ if str(ipaddr) not in self.results:+ qrylist.append(str(ipaddr))+ self.results.append(str(ipaddr))+ else:+ qrylist.append(eventData)+ self.results.append(eventData)++ myres = list()++ for ip in qrylist:+ if self.checkForStop():+ return None++ res = self.sf.fetchUrl("http://api.hackertarget.com/reverseiplookup/?q=" + eventData,+ useragent=self.opts['_useragent'],+ timeout=self.opts['_fetchtimeout'])+ if res['content'] is None:+ self.sf.error("Unable to fetch hackertarget.com content.", False)+ continue++ if "No records" not in res['content']:+ hosts = res['content'].split('\n')+ for h in hosts:+ if " " in h:+ continue+ self.sf.info("Found something on same IP: " + h)+ if not self.opts['cohostsamedomain']:+ if self.getTarget().matches(h, includeParents=True):+ self.sf.debug("Skipping " + h + " because it is on the same domain.")+ continue++ if h not in myres and h != ip:+ if self.opts['verify'] and not self.validateIP(h, ip):+ self.sf.debug("Host no longer resolves to our IP.")+ continue+ evt = SpiderFootEvent("CO_HOSTED_SITE", h.lower(), self.__name__, event)+ self.notifyListeners(evt)+ myres.append(h.lower())++# End of sfp_hackertarget classdiff --git a/modules/sfp_honeypot.py b/modules/sfp_honeypot.pyindex 074d7ac4..790a2e45 100644--- a/modules/sfp_honeypot.py+++ b/modules/sfp_honeypot.py@@ -1,185 +1,186 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_honeypot-# Purpose: SpiderFoot plug-in for looking up whether IPs appear in the-# projecthoneypot.org database.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 16/04/2014-# Copyright: (c) Steve Micallef 2014-# Licence: GPL-# ---------------------------------------------------------------------------------import socket-from netaddr import IPNetwork-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_honeypot(SpiderFootPlugin):- """Honeypot Checker:Investigate,Passive:Blacklists:apikey:Query the projecthoneypot.org database for entries."""-- # Default options- opts = {- 'api_key': "",- 'searchengine': False,- 'threatscore': 0,- 'timelimit': 30,- 'netblocklookup': True,- 'maxnetblock': 24,- 'subnetlookup': True,- 'maxsubnet': 24- }-- # Option descriptions- optdescs = {- 'api_key': "The API key you obtained from projecthoneypot.org",- 'searchengine': "Include entries considered search engines?",- 'threatscore': "Threat score minimum, 0 being everything and 255 being only the most serious.",- 'timelimit': "Maximum days old an entry can be. 255 is the maximum, 0 means you'll get nothing.",- 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible hosts on the same target subdomain/domain?",- 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",- 'subnetlookup': "Look up all IPs on subnets which your target is a part of?",- 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"- }-- results = dict()- errorState = False-- # Status codes according to:- # http://www.projecthoneypot.org/httpbl_api.php- statuses = {- "0": "Search Engine",- "1": "Suspicious",- "2": "Harvester",- "3": "Suspicious & Harvester",- "4": "Comment Spammer",- "5": "Suspicious & Comment Spammer",- "6": "Harvester & Comment Spammer",- "7": "Suspicious & Harvester & Comment Spammer",- "8": "Unknown (8)",- "9": "Unknown (9)",- "10": "Unknown (10)"- }-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ['IP_ADDRESS', 'AFFILIATE_IPADDR', 'NETBLOCK_OWNER',- 'NETBLOCK_MEMBER']-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["BLACKLISTED_IPADDR", "BLACKLISTED_AFFILIATE_IPADDR",- "BLACKLISTED_SUBNET", "BLACKLISTED_NETBLOCK"]-- # Swap 1.2.3.4 to 4.3.2.1- def reverseAddr(self, ipaddr):- return '.'.join(reversed(ipaddr.split('.')))-- # Returns text about the IP status returned from DNS- def reportIP(self, addr):- bits = addr.split(".")- if int(bits[1]) > self.opts['timelimit']:- return None-- if int(bits[2]) < self.opts['threatscore']:- return None-- if int(bits[3]) == 0 and self.opts['searchengine']:- return None-- text = "Honeypotproject ({0}): " + self.statuses[bits[3]] + \- "\nLast Activity: " + bits[1] + " days ago" + \- "\nThreat Level: " + bits[2]- return text-- def queryAddr(self, qaddr, parentEvent):- eventName = parentEvent.eventType-- try:- lookup = self.opts['api_key'] + "." + \- self.reverseAddr(qaddr) + ".dnsbl.httpbl.org"-- self.sf.debug("Checking Honeypot: " + lookup)- addrs = self.sf.normalizeDNS(socket.gethostbyname_ex(lookup))- self.sf.debug("Addresses returned: " + str(addrs))-- text = None- for addr in addrs:- text = self.reportIP(addr)- if text is None:- continue- else:- break-- if text is not None:- if eventName == "AFFILIATE_IPADDR":- e = "BLACKLISTED_AFFILIATE_IPADDR"- if eventName == "IP_ADDRESS":- e = "BLACKLISTED_IPADDR"- if eventName == "NETBLOCK_OWNER":- e = "BLACKLISTED_NETBLOCK"- if eventName == "NETBLOCK_MEMBER":- e = "BLACKLISTED_SUBNET"-- evt = SpiderFootEvent(e, text.format(qaddr), self.__name__, parentEvent)- self.notifyListeners(evt)- except BaseException as e:- self.sf.debug("Unable to resolve " + qaddr + " / " + lookup + ": " + str(e))-- return None-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- parentEvent = event- addrlist = list()-- if self.errorState:- return None-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- if self.opts['api_key'] == "":- self.sf.error("You enabled sfp_honeypot but did not set an API key!", False)- self.errorState = True- return None-- if eventData in self.results:- return None- self.results[eventData] = True-- if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:- if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:- self.sf.debug("Network size bigger than permitted: " +- str(IPNetwork(eventData).prefixlen) + " > " +- str(self.opts['maxnetblock']))- return None-- if eventName == 'NETBLOCK_MEMBER' and self.opts['subnetlookup']:- if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:- self.sf.debug("Network size bigger than permitted: " +- str(IPNetwork(eventData).prefixlen) + " > " +- str(self.opts['maxsubnet']))- return None-- if eventName.startswith("NETBLOCK_"):- for addr in IPNetwork(eventData):- if self.checkForStop():- return None- self.queryAddr(str(addr), parentEvent)- else:- self.queryAddr(eventData, parentEvent)--# End of sfp_honeypot class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_honeypot+# Purpose: SpiderFoot plug-in for looking up whether IPs appear in the+# projecthoneypot.org database.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 16/04/2014+# Copyright: (c) Steve Micallef 2014+# Licence: GPL+# -------------------------------------------------------------------------------++import socket+from netaddr import IPNetwork+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_honeypot(SpiderFootPlugin):+ """Honeypot Checker:Investigate,Passive:Reputation Systems:apikey:Query the projecthoneypot.org database for entries."""+++ # Default options+ opts = {+ 'api_key': "",+ 'searchengine': False,+ 'threatscore': 0,+ 'timelimit': 30,+ 'netblocklookup': True,+ 'maxnetblock': 24,+ 'subnetlookup': True,+ 'maxsubnet': 24+ }++ # Option descriptions+ optdescs = {+ 'api_key': "The API key you obtained from projecthoneypot.org",+ 'searchengine': "Include entries considered search engines?",+ 'threatscore': "Threat score minimum, 0 being everything and 255 being only the most serious.",+ 'timelimit': "Maximum days old an entry can be. 255 is the maximum, 0 means you'll get nothing.",+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible hosts on the same target subdomain/domain?",+ 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",+ 'subnetlookup': "Look up all IPs on subnets which your target is a part of?",+ 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"+ }++ results = dict()+ errorState = False++ # Status codes according to:+ # http://www.projecthoneypot.org/httpbl_api.php+ statuses = {+ "0": "Search Engine",+ "1": "Suspicious",+ "2": "Harvester",+ "3": "Suspicious & Harvester",+ "4": "Comment Spammer",+ "5": "Suspicious & Comment Spammer",+ "6": "Harvester & Comment Spammer",+ "7": "Suspicious & Harvester & Comment Spammer",+ "8": "Unknown (8)",+ "9": "Unknown (9)",+ "10": "Unknown (10)"+ }++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ['IP_ADDRESS', 'AFFILIATE_IPADDR', 'NETBLOCK_OWNER',+ 'NETBLOCK_MEMBER']++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["BLACKLISTED_IPADDR", "BLACKLISTED_AFFILIATE_IPADDR",+ "BLACKLISTED_SUBNET", "BLACKLISTED_NETBLOCK"]++ # Swap 1.2.3.4 to 4.3.2.1+ def reverseAddr(self, ipaddr):+ return '.'.join(reversed(ipaddr.split('.')))++ # Returns text about the IP status returned from DNS+ def reportIP(self, addr):+ bits = addr.split(".")+ if int(bits[1]) > self.opts['timelimit']:+ return None++ if int(bits[2]) < self.opts['threatscore']:+ return None++ if int(bits[3]) == 0 and self.opts['searchengine']:+ return None++ text = "Honeypotproject ({0}): " + self.statuses[bits[3]] + \+ "\nLast Activity: " + bits[1] + " days ago" + \+ "\nThreat Level: " + bits[2]+ return text++ def queryAddr(self, qaddr, parentEvent):+ eventName = parentEvent.eventType++ try:+ lookup = self.opts['api_key'] + "." + \+ self.reverseAddr(qaddr) + ".dnsbl.httpbl.org"++ self.sf.debug("Checking Honeypot: " + lookup)+ addrs = self.sf.normalizeDNS(socket.gethostbyname_ex(lookup))+ self.sf.debug("Addresses returned: " + str(addrs))++ text = None+ for addr in addrs:+ text = self.reportIP(addr)+ if text is None:+ continue+ else:+ break++ if text is not None:+ if eventName == "AFFILIATE_IPADDR":+ e = "BLACKLISTED_AFFILIATE_IPADDR"+ if eventName == "IP_ADDRESS":+ e = "BLACKLISTED_IPADDR"+ if eventName == "NETBLOCK_OWNER":+ e = "BLACKLISTED_NETBLOCK"+ if eventName == "NETBLOCK_MEMBER":+ e = "BLACKLISTED_SUBNET"++ evt = SpiderFootEvent(e, text.format(qaddr), self.__name__, parentEvent)+ self.notifyListeners(evt)+ except BaseException as e:+ self.sf.debug("Unable to resolve " + qaddr + " / " + lookup + ": " + str(e))++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ parentEvent = event+ addrlist = list()++ if self.errorState:+ return None++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if self.opts['api_key'] == "":+ self.sf.error("You enabled sfp_honeypot but did not set an API key!", False)+ self.errorState = True+ return None++ if eventData in self.results:+ return None+ self.results[eventData] = True++ if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:+ if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:+ self.sf.debug("Network size bigger than permitted: " ++ str(IPNetwork(eventData).prefixlen) + " > " ++ str(self.opts['maxnetblock']))+ return None++ if eventName == 'NETBLOCK_MEMBER' and self.opts['subnetlookup']:+ if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:+ self.sf.debug("Network size bigger than permitted: " ++ str(IPNetwork(eventData).prefixlen) + " > " ++ str(self.opts['maxsubnet']))+ return None++ if eventName.startswith("NETBLOCK_"):+ for addr in IPNetwork(eventData):+ if self.checkForStop():+ return None+ self.queryAddr(str(addr), parentEvent)+ else:+ self.queryAddr(eventData, parentEvent)++# End of sfp_honeypot classdiff --git a/modules/sfp_hosting.py b/modules/sfp_hosting.pyindex 5081174a..54b3039a 100644--- a/modules/sfp_hosting.py+++ b/modules/sfp_hosting.py@@ -1,94 +1,95 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_hosting-# Purpose: SpiderFoot plug-in for looking up whether IPs/Netblocks/Domains-# appear in an IP categorization table of hosting providers.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 16/08/2015-# Copyright: (c) Steve Micallef 2015-# Licence: GPL-# ---------------------------------------------------------------------------------import socket-from netaddr import IPAddress, IPNetwork-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_hosting(SpiderFootPlugin):- """Hosting Providers:Footprint,Investigate,Passive:Networking::Find out if any IP addresses identified fall within known 3rd party hosting ranges, e.g. Amazon, Azure, etc."""-- # Default options- opts = {- }-- # Option descriptions- optdescs = {- }-- # Target- results = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ['IP_ADDRESS']-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["PROVIDER_HOSTING"]-- def queryAddr(self, qaddr):- data = dict()- url = "https://raw.githubusercontent.com/client9/ipcat/master/datacenters.csv"-- data['content'] = self.sf.cacheGet("sfipcat", 48)- 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("sfipcat", data['content'])-- for line in data['content'].split('\n'):- if "," not in line:- continue- try:- [start,end,title,url] = line.split(",")- except BaseException as e:- continue-- if IPAddress(qaddr) > IPAddress(start) and IPAddress(qaddr) < IPAddress(end):- return [title, url]-- return False-- # 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:- return None- self.results[eventData] = True-- ret = self.queryAddr(eventData)- if ret != False:- evt = SpiderFootEvent("PROVIDER_HOSTING", ret[0] + ": " + ret[1],- self.__name__, event)- self.notifyListeners(evt)--# End of sfp_hosting class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_hosting+# Purpose: SpiderFoot plug-in for looking up whether IPs/Netblocks/Domains+# appear in an IP categorization table of hosting providers.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 16/08/2015+# Copyright: (c) Steve Micallef 2015+# Licence: GPL+# -------------------------------------------------------------------------------++import socket+from netaddr import IPAddress, IPNetwork+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_hosting(SpiderFootPlugin):+ """Hosting Providers:Footprint,Investigate,Passive:Crawling and Scanning::Find out if any IP addresses identified fall within known 3rd party hosting ranges, e.g. Amazon, Azure, etc."""+++ # Default options+ opts = {+ }++ # Option descriptions+ optdescs = {+ }++ # Target+ results = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ['IP_ADDRESS']++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["PROVIDER_HOSTING"]++ def queryAddr(self, qaddr):+ data = dict()+ url = "https://raw.githubusercontent.com/client9/ipcat/master/datacenters.csv"++ data['content'] = self.sf.cacheGet("sfipcat", 48)+ 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("sfipcat", data['content'])++ for line in data['content'].split('\n'):+ if "," not in line:+ continue+ try:+ [start,end,title,url] = line.split(",")+ except BaseException as e:+ continue++ if IPAddress(qaddr) > IPAddress(start) and IPAddress(qaddr) < IPAddress(end):+ return [title, url]++ return False++ # 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:+ return None+ self.results[eventData] = True++ ret = self.queryAddr(eventData)+ if ret != False:+ evt = SpiderFootEvent("PROVIDER_HOSTING", ret[0] + ": " + ret[1],+ self.__name__, event)+ self.notifyListeners(evt)++# End of sfp_hosting classdiff --git a/modules/sfp_hostsfilenet.py b/modules/sfp_hostsfilenet.pyindex 4091f7ee..189f1306 100644--- a/modules/sfp_hostsfilenet.py+++ b/modules/sfp_hostsfilenet.py@@ -1,265 +1,266 @@-# -*- 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 class+# -*- 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:Reputation Systems: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_hunter.py b/modules/sfp_hunter.pyindex 784a9755..fc899c1d 100644--- a/modules/sfp_hunter.py+++ b/modules/sfp_hunter.py@@ -1,106 +1,107 @@-#--------------------------------------------------------------------------------# Name: sfp_hunter-# Purpose: Query hunter.io using their API.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 22/02/2017-# Copyright: (c) Steve Micallef-# Licence: GPL-#---------------------------------------------------------------------------------import sys-import json-import time-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent--class sfp_hunter(SpiderFootPlugin):- """Hunter.io:Footprint,Investigate,Passive:Search Engines:apikey:Check for e-mail addresses and names on hunter.io."""-- # Default options- opts = {- "api_key": ""- }-- # Option descriptions- optdescs = {- "api_key": "Your API key from hunter.io."- }-- # Be sure to completely clear any class variables in setup()- # or you run the risk of data persisting between scan runs.-- results = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- # 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- def watchedEvents(self):- return [ "DOMAIN_NAME", "INTERNET_NAME" ]-- # What events this module produces- def producedEvents(self):- return [ "EMAILADDR", "HUMAN_NAME" ]-- def query(self, t):- ret = None-- url = "https://api.hunter.io/v2/domain-search?domain=" + t + "&api_key=" + self.opts['api_key']-- res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],- useragent="SpiderFoot")-- if res['code'] == "404":- return None-- try:- ret = json.loads(res['content'])['data']- except Exception as e:- self.sf.error("Error processing JSON response from hunter.io: " + str(e), False)- return None-- return ret-- # 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)-- # Don't look up stuff twice- if self.results.has_key(eventData):- self.sf.debug("Skipping " + eventData + " as already mapped.")- return None- else:- self.results[eventData] = True-- data = self.query(eventData)- if data == None:- return None-- if 'emails' not in data:- return None-- for email in data['emails']:- # Notify other modules of what you've found- e = SpiderFootEvent("EMAILADDR", email['value'], self.__name__, event)- self.notifyListeners(e)-- if 'first_name' in email and 'last_name' in email:- if email['first_name'] != None and email['last_name'] != None:- n = email['first_name'] + " " + email['last_name']- e = SpiderFootEvent("HUMAN_NAME", n, self.__name__, event)- self.notifyListeners(e)---# End of sfp_hunter class+#-------------------------------------------------------------------------------+# Name: sfp_hunter+# Purpose: Query hunter.io using their API.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 22/02/2017+# Copyright: (c) Steve Micallef+# Licence: GPL+#-------------------------------------------------------------------------------++import sys+import json+import time+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++class sfp_hunter(SpiderFootPlugin):+ """Hunter.io:Footprint,Investigate,Passive:Search Engines:apikey:Check for e-mail addresses and names on hunter.io."""+++ # Default options+ opts = {+ "api_key": ""+ }++ # Option descriptions+ optdescs = {+ "api_key": "Your API key from hunter.io."+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ # 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+ def watchedEvents(self):+ return [ "DOMAIN_NAME", "INTERNET_NAME" ]++ # What events this module produces+ def producedEvents(self):+ return [ "EMAILADDR", "HUMAN_NAME" ]++ def query(self, t):+ ret = None++ url = "https://api.hunter.io/v2/domain-search?domain=" + t + "&api_key=" + self.opts['api_key']++ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],+ useragent="SpiderFoot")++ if res['code'] == "404":+ return None++ try:+ ret = json.loads(res['content'])['data']+ except Exception as e:+ self.sf.error("Error processing JSON response from hunter.io: " + str(e), False)+ return None++ return ret++ # 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)++ # Don't look up stuff twice+ if self.results.has_key(eventData):+ self.sf.debug("Skipping " + eventData + " as already mapped.")+ return None+ else:+ self.results[eventData] = True++ data = self.query(eventData)+ if data == None:+ return None++ if 'emails' not in data:+ return None++ for email in data['emails']:+ # Notify other modules of what you've found+ e = SpiderFootEvent("EMAILADDR", email['value'], self.__name__, event)+ self.notifyListeners(e)++ if 'first_name' in email and 'last_name' in email:+ if email['first_name'] != None and email['last_name'] != None:+ n = email['first_name'] + " " + email['last_name']+ e = SpiderFootEvent("HUMAN_NAME", n, self.__name__, event)+ self.notifyListeners(e)+++# End of sfp_hunter classdiff --git a/modules/sfp_intfiles.py b/modules/sfp_intfiles.pyindex 168bfbb0..402b7798 100644--- a/modules/sfp_intfiles.py+++ b/modules/sfp_intfiles.py@@ -1,156 +1,157 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_intfiles-# Purpose: From Spidering and from searching search engines, identifies-# files of potential interest.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 06/04/2014-# Copyright: (c) Steve Micallef 2014-# Licence: GPL-# ---------------------------------------------------------------------------------import re-import urllib-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_intfiles(SpiderFootPlugin):- """Interesting Files:Footprint:Data Analysis::Identifies potential files of interest, e.g. office documents, zip files."""-- # Default options- opts = {- 'pages': 20, # Number of search results pages to iterate- 'fileexts': ["doc", "docx", "ppt", "pptx", "pdf", 'xls', 'xlsx', 'zip'],- 'usesearch': True,- 'searchengine': "yahoo"- }-- # Option descriptions- optdescs = {- 'pages': "Number of search engine results pages to iterate through if using one.",- 'fileexts': "File extensions of files you consider interesting.",- 'usesearch': "Use search engines to quickly find files. If false, only spidering will be used.",- 'searchengine': "If using a search engine, which one? google, yahoo or bing."- }-- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["INTERNET_NAME", "LINKED_URL_INTERNAL"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["SEARCH_ENGINE_WEB_CONTENT", "INTERESTING_FILE"]-- def yahooCleaner(self, string):- return " url=\"" + urllib.unquote(string.group(1)) + "\" "-- # 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 eventName == "INTERNET_NAME" and not self.opts['usesearch']:- self.sf.debug("Not using a search engine to find interesting files.")- return None-- if eventData in self.results:- return None-- if eventName == "LINKED_URL_INTERNAL":- for fileExt in self.opts['fileexts']:- if "." + fileExt.lower() in eventData.lower():- if eventData in self.results:- continue- else:- self.results.append(eventData)-- evt = SpiderFootEvent("INTERESTING_FILE", eventData,- self.__name__, event)- self.notifyListeners(evt)- return None-- if eventData not in self.results:- self.results.append(eventData)-- # Handling INTERNET_NAME event..- for fileExt in self.opts['fileexts']:- # Sites hosted on the domain- if self.opts['searchengine'].lower() == "google":- pages = self.sf.googleIterate("site:" + eventData + "+" +- "%2Bext:" + fileExt, dict(limit=self.opts['pages'],- useragent=self.opts['_useragent'],- timeout=self.opts['_fetchtimeout']))-- if self.opts['searchengine'].lower() == "bing":- pages = self.sf.bingIterate("site:" + eventData + "+" +- "%2Bext:" + fileExt, dict(limit=self.opts['pages'],- useragent=self.opts['_useragent'],- timeout=self.opts['_fetchtimeout']))-- if self.opts['searchengine'].lower() == "yahoo":- pages = self.sf.yahooIterate("site:" + eventData + "+" +- "%2Bext:" + fileExt, dict(limit=self.opts['pages'],- useragent=self.opts['_useragent'],- timeout=self.opts['_fetchtimeout']))-- if pages is None:- self.sf.info("No results returned from " + self.opts['searchengine'] +- " for " + fileExt + " files.")- continue-- for page in pages.keys():- if page in self.results:- continue- else:- self.results.append(page)-- # Check if we've been asked to stop- if self.checkForStop():- return None-- if self.opts['searchengine'].lower() == "yahoo":- res = re.sub("RU=(.*?)/RK=", self.yahooCleaner, pages[page])- else:- res = pages[page]-- # Submit the gresults for analysis- evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", res,- self.__name__, event)- self.notifyListeners(evt)-- links = self.sf.parseLinks(page, res, eventData)- if len(links) == 0:- continue-- for link in links.keys():- if link in self.results:- continue-- if self.sf.urlFQDN(link).endswith(eventData):- # This for loop might seem redundant but sometimes search engines return results- # for other file extensions.- for fe in self.opts['fileexts']:- if "." + fe.lower() in link.lower():- self.sf.info("Found an interesting file: " + link)- evt = SpiderFootEvent("INTERESTING_FILE", link,- self.__name__, event)- self.notifyListeners(evt)- self.results.append(link)--# End of sfp_intfiles class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_intfiles+# Purpose: From Spidering and from searching search engines, identifies+# files of potential interest.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 06/04/2014+# Copyright: (c) Steve Micallef 2014+# Licence: GPL+# -------------------------------------------------------------------------------++import re+import urllib+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_intfiles(SpiderFootPlugin):+ """Interesting Files:Footprint:Crawling and Scanning::Identifies potential files of interest, e.g. office documents, zip files."""+++ # Default options+ opts = {+ 'pages': 20, # Number of search results pages to iterate+ 'fileexts': ["doc", "docx", "ppt", "pptx", "pdf", 'xls', 'xlsx', 'zip'],+ 'usesearch': True,+ 'searchengine': "yahoo"+ }++ # Option descriptions+ optdescs = {+ 'pages': "Number of search engine results pages to iterate through if using one.",+ 'fileexts': "File extensions of files you consider interesting.",+ 'usesearch': "Use search engines to quickly find files. If false, only spidering will be used.",+ 'searchengine': "If using a search engine, which one? google, yahoo or bing."+ }++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["INTERNET_NAME", "LINKED_URL_INTERNAL"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["SEARCH_ENGINE_WEB_CONTENT", "INTERESTING_FILE"]++ def yahooCleaner(self, string):+ return " url=\"" + urllib.unquote(string.group(1)) + "\" "++ # 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 eventName == "INTERNET_NAME" and not self.opts['usesearch']:+ self.sf.debug("Not using a search engine to find interesting files.")+ return None++ if eventData in self.results:+ return None++ if eventName == "LINKED_URL_INTERNAL":+ for fileExt in self.opts['fileexts']:+ if "." + fileExt.lower() in eventData.lower():+ if eventData in self.results:+ continue+ else:+ self.results.append(eventData)++ evt = SpiderFootEvent("INTERESTING_FILE", eventData,+ self.__name__, event)+ self.notifyListeners(evt)+ return None++ if eventData not in self.results:+ self.results.append(eventData)++ # Handling INTERNET_NAME event..+ for fileExt in self.opts['fileexts']:+ # Sites hosted on the domain+ if self.opts['searchengine'].lower() == "google":+ pages = self.sf.googleIterate("site:" + eventData + "+" ++ "%2Bext:" + fileExt, dict(limit=self.opts['pages'],+ useragent=self.opts['_useragent'],+ timeout=self.opts['_fetchtimeout']))++ if self.opts['searchengine'].lower() == "bing":+ pages = self.sf.bingIterate("site:" + eventData + "+" ++ "%2Bext:" + fileExt, dict(limit=self.opts['pages'],+ useragent=self.opts['_useragent'],+ timeout=self.opts['_fetchtimeout']))++ if self.opts['searchengine'].lower() == "yahoo":+ pages = self.sf.yahooIterate("site:" + eventData + "+" ++ "%2Bext:" + fileExt, dict(limit=self.opts['pages'],+ useragent=self.opts['_useragent'],+ timeout=self.opts['_fetchtimeout']))++ if pages is None:+ self.sf.info("No results returned from " + self.opts['searchengine'] ++ " for " + fileExt + " files.")+ continue++ for page in pages.keys():+ if page in self.results:+ continue+ else:+ self.results.append(page)++ # Check if we've been asked to stop+ if self.checkForStop():+ return None++ if self.opts['searchengine'].lower() == "yahoo":+ res = re.sub("RU=(.*?)/RK=", self.yahooCleaner, pages[page])+ else:+ res = pages[page]++ # Submit the gresults for analysis+ evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", res,+ self.__name__, event)+ self.notifyListeners(evt)++ links = self.sf.parseLinks(page, res, eventData)+ if len(links) == 0:+ continue++ for link in links.keys():+ if link in self.results:+ continue++ if self.sf.urlFQDN(link).endswith(eventData):+ # This for loop might seem redundant but sometimes search engines return results+ # for other file extensions.+ for fe in self.opts['fileexts']:+ if "." + fe.lower() in link.lower():+ self.sf.info("Found an interesting file: " + link)+ evt = SpiderFootEvent("INTERESTING_FILE", link,+ self.__name__, event)+ self.notifyListeners(evt)+ self.results.append(link)++# End of sfp_intfiles classdiff --git a/modules/sfp_ipinfo.py b/modules/sfp_ipinfo.pyindex 35c37a80..76d30639 100644--- a/modules/sfp_ipinfo.py+++ b/modules/sfp_ipinfo.py@@ -1,96 +1,97 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_ipinfo-# Purpose: SpiderFoot plug-in to identify the Geo-location of IP addresses-# identified by other modules using ipinfo.io.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 17/06/2017-# Copyright: (c) Steve Micallef 2017-# Licence: GPL-# ---------------------------------------------------------------------------------import json-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_ipinfo(SpiderFootPlugin):- """IPInfo.io:Footprint,Investigate,Passive:Networking::Identifies the physical location of IP addresses identified using ipinfo.io."""-- # Default options- opts = {- "api_key": ""- }- optdescs = {- "api_key": "Your ipinfo.io access token."- }- results = dict()- errorState = False-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()- self.errorState = False-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ['IP_ADDRESS']-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["GEOINFO"]-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if self.errorState:- return None-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- if self.opts['api_key'] == "":- self.sf.error("You enabled sfp_ipinfo but did not set an API key!", False)- self.errorState = True- return None-- # Don't look up stuff twice- if eventData in self.results:- self.sf.debug("Skipping " + eventData + " as already mapped.")- return None- else:- self.results[eventData] = True-- res = self.sf.fetchUrl("https://ipinfo.io/" + eventData + "/json?token=" + self.opts['api_key'],- timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])-- if res['code'] == "429":- self.sf.error("You are being rate-limited by ipinfo.io.", False)- return-- if res['content'] is None:- self.sf.info("No GeoIP info found for " + eventData)- try:- hostip = json.loads(res['content'])- except Exception as e:- self.sf.debug("Error processing JSON response.")- return None-- self.sf.info("Found GeoIP for " + eventData + ": " + hostip['country'])- countrycity = hostip['country'] + ", " + hostip.get('region', "Unknown region") + \- ", " + hostip.get('city', "Unknown city")-- evt = SpiderFootEvent("GEOINFO", countrycity, self.__name__, event)- self.notifyListeners(evt)-- return None--# End of sfp_ipinfo class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_ipinfo+# Purpose: SpiderFoot plug-in to identify the Geo-location of IP addresses+# identified by other modules using ipinfo.io.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 17/06/2017+# Copyright: (c) Steve Micallef 2017+# Licence: GPL+# -------------------------------------------------------------------------------++import json+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_ipinfo(SpiderFootPlugin):+ """IPInfo.io:Footprint,Investigate,Passive:Real World::Identifies the physical location of IP addresses identified using ipinfo.io."""+++ # Default options+ opts = {+ "api_key": ""+ }+ optdescs = {+ "api_key": "Your ipinfo.io access token."+ }+ results = dict()+ errorState = False++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()+ self.errorState = False++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ['IP_ADDRESS']++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["GEOINFO"]++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if self.errorState:+ return None++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if self.opts['api_key'] == "":+ self.sf.error("You enabled sfp_ipinfo but did not set an API key!", False)+ self.errorState = True+ return None++ # Don't look up stuff twice+ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + " as already mapped.")+ return None+ else:+ self.results[eventData] = True++ res = self.sf.fetchUrl("https://ipinfo.io/" + eventData + "/json?token=" + self.opts['api_key'],+ timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])++ if res['code'] == "429":+ self.sf.error("You are being rate-limited by ipinfo.io.", False)+ return++ if res['content'] is None:+ self.sf.info("No GeoIP info found for " + eventData)+ try:+ hostip = json.loads(res['content'])+ except Exception as e:+ self.sf.debug("Error processing JSON response.")+ return None++ self.sf.info("Found GeoIP for " + eventData + ": " + hostip['country'])+ countrycity = hostip['country'] + ", " + hostip.get('region', "Unknown region") + \+ ", " + hostip.get('city', "Unknown city")++ evt = SpiderFootEvent("GEOINFO", countrycity, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_ipinfo classdiff --git a/modules/sfp_isc.py b/modules/sfp_isc.pyindex 52e4694a..e001e2ba 100644--- a/modules/sfp_isc.py+++ b/modules/sfp_isc.py@@ -1,261 +1,262 @@-# -*- 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 class+# -*- 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:Reputation Systems: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_junkfiles.py b/modules/sfp_junkfiles.pyindex 2a2123c4..937e43d5 100644--- a/modules/sfp_junkfiles.py+++ b/modules/sfp_junkfiles.py@@ -1,184 +1,185 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_junkfiles-# Purpose: From Spidering, identifies backup and temporary files.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 23/08/2014-# Copyright: (c) Steve Micallef 2014-# Licence: GPL-# ---------------------------------------------------------------------------------from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-import random--class sfp_junkfiles(SpiderFootPlugin):- """Junk Files:Footprint:Web Spidering:slow,invasive:Looks for old/temporary and other similar files."""-- # Default options- opts = {- 'fileexts': ['tmp', 'bak', 'old', 'backup', 'new'],- 'urlextstry': ['asp', 'php', 'jsp',],- 'files': ['x', 'xxx', 'crap', 'old', 'a', 'aaa', 'z', 'zzz',- 'out', 'sql', "passwd", ".htaccess", ".htpasswd",- "Thumbs.db", "asd", "asdf"],- 'dirs': ['zip', 'tar.gz', 'tgz', 'tar'],- 'skipfake': True- }-- # Option descriptions- optdescs = {- 'fileexts': "File extensions to try.",- 'urlextstry': "Try those extensions against URLs with these extensions.",- 'files': "Try to fetch each of these files from the directory of the URL.",- 'dirs': "Try to fetch the containing folder with these extensions.",- 'skipfake': "Try to fetch an obviously fake page and if no 404 is returned, stop trying that particular host for junk files. Good for avoiding false positives in cases where servers return content for pages that don't exist."- }-- results = list()- hosts = list()- skiphosts = list()- bases = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()- self.hosts = list()- self.skiphosts = list()- self.bases = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["LINKED_URL_INTERNAL"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["JUNK_FILE"]-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- host = self.sf.urlBaseUrl(eventData)-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- if eventData in self.results:- return None- else:- self.results.append(eventData)-- if self.opts['skipfake'] and host in self.skiphosts:- self.sf.debug("Skipping " + host + " because it doesn't return 404s.")- return None-- # Try and fetch an obviously missing page- if host not in self.hosts and self.opts['skipfake']:- fetch = host + "/" + str(random.randint(0, 99999999)) + ".html"- res = self.sf.fetchUrl(fetch, headOnly=True,- timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])- if res['code'] != "404":- self.skiphosts.append(host)-- self.hosts.append(host)-- # http://www/blah/abc.php -> try http://www/blah/abc.php.[fileexts]- for ext in self.opts['urlextstry']:- if "." + ext + "?" in eventData or "." + ext + "#" in eventData or \- eventData.endswith("." + ext):- bits = eventData.split("?")- for x in self.opts['fileexts']:- if self.checkForStop():- return None-- self.sf.debug("Trying " + x + " against " + eventData)- fetch = bits[0] + "." + x- if fetch not in self.results:- self.results.append(fetch)- else:- self.sf.debug("Skipping, already fetched.")- continue- res = self.sf.fetchUrl(fetch, headOnly=True,- timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'],- sizeLimit=10000000)- if res['realurl'] != fetch:- self.sf.debug("Skipping because " + res['realurl'] + " isn't the fetched URL of " + fetch)- continue- if res['code'] == "200":- evt = SpiderFootEvent("JUNK_FILE", fetch,- self.__name__, event)- self.notifyListeners(evt)-- base = self.sf.urlBaseDir(eventData)- if base in self.bases:- return None- else:- self.bases.append(base)-- # don't do anything with the root directory of a site- self.sf.debug("Base: " + base + ", event: " + eventData)- if base == eventData + "/" or base == eventData:- return None-- # http://www/blah/abc.html -> try http://www/blah.[dirs]- for dirfile in self.opts['dirs']:- if self.checkForStop():- return None-- if base.count('/') == 3:- self.sf.debug("Skipping base url.")- continue-- self.sf.debug("Trying " + dirfile + " against " + eventData)- fetch = base[0:len(base) - 1] + "." + dirfile- if fetch not in self.results:- self.results.append(fetch)- else:- self.sf.debug("Skipping, already fetched.")- continue- res = self.sf.fetchUrl(fetch, headOnly=True,- timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])- if res['realurl'] != fetch:- self.sf.debug("Skipping because " + res['realurl'] + " isn't the fetched URL of " + fetch)- continue- if res['code'] == "200":- evt = SpiderFootEvent("JUNK_FILE", fetch,- self.__name__, event)- self.notifyListeners(evt)-- # http://www/blah/abc.html -> try http://www/blah/[files]- for f in self.opts['files']:- if self.checkForStop():- return None-- self.sf.debug("Trying " + f + " against " + eventData)- fetch = base + f- if fetch not in self.results:- self.results.append(fetch)- else:- self.sf.debug("Skipping, already fetched.")- continue- res = self.sf.fetchUrl(fetch, headOnly=True,- timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])- if res['realurl'] != fetch:- self.sf.debug("Skipping because " + res['realurl'] + " isn't the fetched URL of " + fetch)- continue- if res['code'] == "200":- evt = SpiderFootEvent("JUNK_FILE", fetch,- self.__name__, event)- self.notifyListeners(evt)-- return None--# End of sfp_junkfiles class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_junkfiles+# Purpose: From Spidering, identifies backup and temporary files.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 23/08/2014+# Copyright: (c) Steve Micallef 2014+# Licence: GPL+# -------------------------------------------------------------------------------++from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+import random++class sfp_junkfiles(SpiderFootPlugin):+ """Junk Files:Footprint:Crawling and Scanning:slow,invasive:Looks for old/temporary and other similar files."""+++ # Default options+ opts = {+ 'fileexts': ['tmp', 'bak', 'old', 'backup', 'new'],+ 'urlextstry': ['asp', 'php', 'jsp',],+ 'files': ['x', 'xxx', 'crap', 'old', 'a', 'aaa', 'z', 'zzz',+ 'out', 'sql', "passwd", ".htaccess", ".htpasswd",+ "Thumbs.db", "asd", "asdf"],+ 'dirs': ['zip', 'tar.gz', 'tgz', 'tar'],+ 'skipfake': True+ }++ # Option descriptions+ optdescs = {+ 'fileexts': "File extensions to try.",+ 'urlextstry': "Try those extensions against URLs with these extensions.",+ 'files': "Try to fetch each of these files from the directory of the URL.",+ 'dirs': "Try to fetch the containing folder with these extensions.",+ 'skipfake': "Try to fetch an obviously fake page and if no 404 is returned, stop trying that particular host for junk files. Good for avoiding false positives in cases where servers return content for pages that don't exist."+ }++ results = list()+ hosts = list()+ skiphosts = list()+ bases = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()+ self.hosts = list()+ self.skiphosts = list()+ self.bases = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["LINKED_URL_INTERNAL"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["JUNK_FILE"]++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ host = self.sf.urlBaseUrl(eventData)++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ return None+ else:+ self.results.append(eventData)++ if self.opts['skipfake'] and host in self.skiphosts:+ self.sf.debug("Skipping " + host + " because it doesn't return 404s.")+ return None++ # Try and fetch an obviously missing page+ if host not in self.hosts and self.opts['skipfake']:+ fetch = host + "/" + str(random.randint(0, 99999999)) + ".html"+ res = self.sf.fetchUrl(fetch, headOnly=True,+ timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])+ if res['code'] != "404":+ self.skiphosts.append(host)++ self.hosts.append(host)++ # http://www/blah/abc.php -> try http://www/blah/abc.php.[fileexts]+ for ext in self.opts['urlextstry']:+ if "." + ext + "?" in eventData or "." + ext + "#" in eventData or \+ eventData.endswith("." + ext):+ bits = eventData.split("?")+ for x in self.opts['fileexts']:+ if self.checkForStop():+ return None++ self.sf.debug("Trying " + x + " against " + eventData)+ fetch = bits[0] + "." + x+ if fetch not in self.results:+ self.results.append(fetch)+ else:+ self.sf.debug("Skipping, already fetched.")+ continue+ res = self.sf.fetchUrl(fetch, headOnly=True,+ timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'],+ sizeLimit=10000000)+ if res['realurl'] != fetch:+ self.sf.debug("Skipping because " + res['realurl'] + " isn't the fetched URL of " + fetch)+ continue+ if res['code'] == "200":+ evt = SpiderFootEvent("JUNK_FILE", fetch,+ self.__name__, event)+ self.notifyListeners(evt)++ base = self.sf.urlBaseDir(eventData)+ if base in self.bases:+ return None+ else:+ self.bases.append(base)++ # don't do anything with the root directory of a site+ self.sf.debug("Base: " + base + ", event: " + eventData)+ if base == eventData + "/" or base == eventData:+ return None++ # http://www/blah/abc.html -> try http://www/blah.[dirs]+ for dirfile in self.opts['dirs']:+ if self.checkForStop():+ return None++ if base.count('/') == 3:+ self.sf.debug("Skipping base url.")+ continue++ self.sf.debug("Trying " + dirfile + " against " + eventData)+ fetch = base[0:len(base) - 1] + "." + dirfile+ if fetch not in self.results:+ self.results.append(fetch)+ else:+ self.sf.debug("Skipping, already fetched.")+ continue+ res = self.sf.fetchUrl(fetch, headOnly=True,+ timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])+ if res['realurl'] != fetch:+ self.sf.debug("Skipping because " + res['realurl'] + " isn't the fetched URL of " + fetch)+ continue+ if res['code'] == "200":+ evt = SpiderFootEvent("JUNK_FILE", fetch,+ self.__name__, event)+ self.notifyListeners(evt)++ # http://www/blah/abc.html -> try http://www/blah/[files]+ for f in self.opts['files']:+ if self.checkForStop():+ return None++ self.sf.debug("Trying " + f + " against " + eventData)+ fetch = base + f+ if fetch not in self.results:+ self.results.append(fetch)+ else:+ self.sf.debug("Skipping, already fetched.")+ continue+ res = self.sf.fetchUrl(fetch, headOnly=True,+ timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])+ if res['realurl'] != fetch:+ self.sf.debug("Skipping because " + res['realurl'] + " isn't the fetched URL of " + fetch)+ continue+ if res['code'] == "200":+ evt = SpiderFootEvent("JUNK_FILE", fetch,+ self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_junkfiles classdiff --git a/modules/sfp_malc0de.py b/modules/sfp_malc0de.pyindex 3f6483ff..bdef3353 100644--- a/modules/sfp_malc0de.py+++ b/modules/sfp_malc0de.py@@ -1,267 +1,268 @@-# -*- 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 class+# -*- 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:Reputation Systems: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_malwaredomainlist.py b/modules/sfp_malwaredomainlist.pyindex 421b1e55..d00fe21e 100644--- a/modules/sfp_malwaredomainlist.py+++ b/modules/sfp_malwaredomainlist.py@@ -1,280 +1,281 @@-# -*- 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 class+# -*- 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:Reputation Systems: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.pyindex 87b92aab..049b7ff0 100644--- a/modules/sfp_malwaredomains.py+++ b/modules/sfp_malwaredomains.py@@ -1,264 +1,265 @@-# -*- 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 class+# -*- 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:Reputation Systems: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_malwarepatrol.py b/modules/sfp_malwarepatrol.pyindex 16d75615..b6d5299b 100644--- a/modules/sfp_malwarepatrol.py+++ b/modules/sfp_malwarepatrol.py@@ -1,118 +1,119 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_malwarepatrol-# Purpose: SpiderFoot plug-in to search MalwarePatrol's daatabase for-# potential malicious IPs/hostnames.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 25/07/2016-# Copyright: (c) Steve Micallef 2016-# Licence: GPL-# ---------------------------------------------------------------------------------import json-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_malwarepatrol(SpiderFootPlugin):- """MalwarePatrol:Investigate,Passive:Blacklists:apikey:Searches malwarepatrol.net's database of malicious URLs/IPs."""-- # Default options- opts = {- "api_key": ""- }- optdescs = {- "api_key": "malwarepatrol.com 'receipt' ID, provided once signing up for their open-source feed. Without this you cannot obtain their feed."- }- results = dict()- errorState = False-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- 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"]-- def queryAddr(self, qaddr):- data = dict()- url = "http://lists.malwarepatrol.net/cgi/getfile?receipt=" + \- self.opts['api_key'] + "&product=8&list=smoothwall"-- data['content'] = self.sf.cacheGet("sfmalwarepatrol", 72)- 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("sfmalwarepatrol", data['content'])-- for line in data['content'].split('\n'):- if len(line) < 2 or line.startswith('#'):- continue-- if line.startswith(qaddr):- return True-- return False-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if self.errorState:- return None-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- if not self.opts['api_key']:- self.sf.error("You enabled sfp_malwarepatrol but did not provide an receipt ID!", False)- self.errorState = True- return None-- # Don't look up stuff twice- if eventData in self.results:- self.sf.debug("Skipping " + eventData + " as already searched.")- return None- else:- self.results[eventData] = True-- evtType = ""- if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:- if eventName == 'IP_ADDRESS':- evtType = 'MALICIOUS_IPADDR'- else:- evtType = 'MALICIOUS_AFFILIATE_IPADDR'-- if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',- 'AFFILIATE_INTERNET_NAME' ]:- 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 self.queryAddr(eventData):- evt = SpiderFootEvent(evtType, eventData, self.__name__, event)- self.notifyListeners(evt)--# End of sfp_malwarepatrol class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_malwarepatrol+# Purpose: SpiderFoot plug-in to search MalwarePatrol's daatabase for+# potential malicious IPs/hostnames.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 25/07/2016+# Copyright: (c) Steve Micallef 2016+# Licence: GPL+# -------------------------------------------------------------------------------++import json+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_malwarepatrol(SpiderFootPlugin):+ """MalwarePatrol:Investigate,Passive:Reputation Systems:apikey:Searches malwarepatrol.net's database of malicious URLs/IPs."""+++ # Default options+ opts = {+ "api_key": ""+ }+ optdescs = {+ "api_key": "malwarepatrol.com 'receipt' ID, provided once signing up for their open-source feed. Without this you cannot obtain their feed."+ }+ results = dict()+ errorState = False++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ 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"]++ def queryAddr(self, qaddr):+ data = dict()+ url = "http://lists.malwarepatrol.net/cgi/getfile?receipt=" + \+ self.opts['api_key'] + "&product=8&list=smoothwall"++ data['content'] = self.sf.cacheGet("sfmalwarepatrol", 72)+ 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("sfmalwarepatrol", data['content'])++ for line in data['content'].split('\n'):+ if len(line) < 2 or line.startswith('#'):+ continue++ if line.startswith(qaddr):+ return True++ return False++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if self.errorState:+ return None++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if not self.opts['api_key']:+ self.sf.error("You enabled sfp_malwarepatrol but did not provide an receipt ID!", False)+ self.errorState = True+ return None++ # Don't look up stuff twice+ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + " as already searched.")+ return None+ else:+ self.results[eventData] = True++ evtType = ""+ if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:+ if eventName == 'IP_ADDRESS':+ evtType = 'MALICIOUS_IPADDR'+ else:+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'++ if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',+ 'AFFILIATE_INTERNET_NAME' ]:+ 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 self.queryAddr(eventData):+ evt = SpiderFootEvent(evtType, eventData, self.__name__, event)+ self.notifyListeners(evt)++# End of sfp_malwarepatrol classdiff --git a/modules/sfp_mcafee.py b/modules/sfp_mcafee.pyindex 4feb03e8..6da8c183 100644--- a/modules/sfp_mcafee.py+++ b/modules/sfp_mcafee.py@@ -1,263 +1,264 @@-# -*- 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 class+# -*- 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:Reputation Systems: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.pyindex e57da5fa..fdff8912 100644--- a/modules/sfp_multiproxy.py+++ b/modules/sfp_multiproxy.py@@ -1,263 +1,264 @@-# -*- 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 class+# -*- 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:Reputation Systems: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_names.py b/modules/sfp_names.pyindex 2f35612d..d6d4a0e8 100644--- a/modules/sfp_names.py+++ b/modules/sfp_names.py@@ -1,133 +1,134 @@-# coding: utf-8-# --------------------------------------------------------------------------------# Name: sfp_names-# Purpose: Identify human names in content fetched.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 24/03/2014-# Copyright: (c) Steve Micallef-# Licence: GPL-# ---------------------------------------------------------------------------------import re-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_names(SpiderFootPlugin):- """Name Extractor:Footprint,Passive:Social:errorprone:Attempt to identify human names in fetched content."""-- # Default options- opts = {- 'algotune': 50,- 'emailtoname': True- }-- # Option descriptions- optdescs = {- 'algotune': "A value between 0-100 to tune the sensitivity of the name finder. Less than 40 will give you a lot of junk, over 50 and you'll probably miss things but will have less false positives.",- 'emailtoname': "Convert e-mail addresses in the form of firstname.surname@target to names?"- }-- results = dict()- d = None- n = None-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- d = self.sf.dictwords()- self.n = self.sf.dictnames()- # Take dictionary words out of the names list to keep things clean- self.d = set(set(d) - set(self.n))-- # 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 ["TARGET_WEB_CONTENT", "EMAILADDR",- "DOMAIN_WHOIS", "NETBLOCK_WHOIS"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["HUMAN_NAME"]-- # 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 eventName == "EMAILADDR" and self.opts['emailtoname']:- if "." in eventData.split("@")[0]:- if type(eventData) == unicode:- name = " ".join(map(unicode.capitalize, eventData.split("@")[0].split(".")))- else:- name = " ".join(map(str.capitalize, eventData.split("@")[0].split(".")))- name = unicode(name, 'utf-8', errors='replace')- # Notify other modules of what you've found- evt = SpiderFootEvent("HUMAN_NAME", name, self.__name__, event)- self.notifyListeners(evt)- return None-- # Stage 1: Find things that look (very vaguely) like names- rx = re.compile("([A-Z][a-z�������������]+)\s+.?.?\s?([A-Z][�������������a-zA-Z\'\-]+)")- m = re.findall(rx, eventData)- for r in m:- # Start off each match as 0 points.- p = 0- notindict = False-- # Shouldn't encounter "Firstname's Secondname"- first = r[0].lower()- if first[len(first) - 2] == "'" or first[len(first) - 1] == "'":- continue-- # Strip off trailing ' or 's- secondOrig = r[1].replace("'s", "")- secondOrig = secondOrig.rstrip("'")- second = r[1].lower().replace("'s", "")- second = second.rstrip("'")-- # If both words are not in the dictionary, add 75 points.- if first not in self.d and second not in self.d:- p += 75- notindict = True-- # If the first word is a known popular first name, award 50 points.- if first in self.n:- p += 50-- # If either word is 2 characters, subtract 50 points.- if len(first) == 2 or len(second) == 2:- p -= 50-- # If the first word is in the dictionary but the second isn't,- # subtract 40 points.- if not notindict:- if first in self.d and second not in self.d:- p -= 20-- # If the second word is in the dictionary but the first isn't,- # reduce 20 points.- if first not in self.d and second in self.d:- p -= 40-- name = r[0] + " " + secondOrig-- if p > self.opts['algotune']:- # Notify other modules of what you've found- evt = SpiderFootEvent("HUMAN_NAME", name, self.__name__, event)- self.notifyListeners(evt)--# End of sfp_names class+# coding: utf-8+# -------------------------------------------------------------------------------+# Name: sfp_names+# Purpose: Identify human names in content fetched.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 24/03/2014+# Copyright: (c) Steve Micallef+# Licence: GPL+# -------------------------------------------------------------------------------++import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_names(SpiderFootPlugin):+ """Name Extractor:Footprint,Passive:Real World:errorprone:Attempt to identify human names in fetched content."""+++ # Default options+ opts = {+ 'algotune': 50,+ 'emailtoname': True+ }++ # Option descriptions+ optdescs = {+ 'algotune': "A value between 0-100 to tune the sensitivity of the name finder. Less than 40 will give you a lot of junk, over 50 and you'll probably miss things but will have less false positives.",+ 'emailtoname': "Convert e-mail addresses in the form of firstname.surname@target to names?"+ }++ results = dict()+ d = None+ n = None++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ d = self.sf.dictwords()+ self.n = self.sf.dictnames()+ # Take dictionary words out of the names list to keep things clean+ self.d = set(set(d) - set(self.n))++ # 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 ["TARGET_WEB_CONTENT", "EMAILADDR",+ "DOMAIN_WHOIS", "NETBLOCK_WHOIS"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["HUMAN_NAME"]++ # 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 eventName == "EMAILADDR" and self.opts['emailtoname']:+ if "." in eventData.split("@")[0]:+ if type(eventData) == unicode:+ name = " ".join(map(unicode.capitalize, eventData.split("@")[0].split(".")))+ else:+ name = " ".join(map(str.capitalize, eventData.split("@")[0].split(".")))+ name = unicode(name, 'utf-8', errors='replace')+ # Notify other modules of what you've found+ evt = SpiderFootEvent("HUMAN_NAME", name, self.__name__, event)+ self.notifyListeners(evt)+ return None++ # Stage 1: Find things that look (very vaguely) like names+ rx = re.compile("([A-Z][a-z�������������]+)\s+.?.?\s?([A-Z][�������������a-zA-Z\'\-]+)")+ m = re.findall(rx, eventData)+ for r in m:+ # Start off each match as 0 points.+ p = 0+ notindict = False++ # Shouldn't encounter "Firstname's Secondname"+ first = r[0].lower()+ if first[len(first) - 2] == "'" or first[len(first) - 1] == "'":+ continue++ # Strip off trailing ' or 's+ secondOrig = r[1].replace("'s", "")+ secondOrig = secondOrig.rstrip("'")+ second = r[1].lower().replace("'s", "")+ second = second.rstrip("'")++ # If both words are not in the dictionary, add 75 points.+ if first not in self.d and second not in self.d:+ p += 75+ notindict = True++ # If the first word is a known popular first name, award 50 points.+ if first in self.n:+ p += 50++ # If either word is 2 characters, subtract 50 points.+ if len(first) == 2 or len(second) == 2:+ p -= 50++ # If the first word is in the dictionary but the second isn't,+ # subtract 40 points.+ if not notindict:+ if first in self.d and second not in self.d:+ p -= 20++ # If the second word is in the dictionary but the first isn't,+ # reduce 20 points.+ if first not in self.d and second in self.d:+ p -= 40++ name = r[0] + " " + secondOrig++ if p > self.opts['algotune']:+ # Notify other modules of what you've found+ evt = SpiderFootEvent("HUMAN_NAME", name, self.__name__, event)+ self.notifyListeners(evt)++# End of sfp_names classdiff --git a/modules/sfp_nothink.py b/modules/sfp_nothink.pyindex ffe62edd..594175c8 100644--- a/modules/sfp_nothink.py+++ b/modules/sfp_nothink.py@@ -1,287 +1,288 @@-# -*- 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 class+# -*- 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:Reputation Systems: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_onioncity.py b/modules/sfp_onioncity.pyindex 9d181d7e..d53e7ad6 100644--- a/modules/sfp_onioncity.py+++ b/modules/sfp_onioncity.py@@ -1,134 +1,135 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_onioncity-# Purpose: Searches the Tor search engine 'Onion City' for content related-# to the domain in question.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 15/07/2015-# Copyright: (c) Steve Micallef 2015-# Licence: GPL-# ---------------------------------------------------------------------------------from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-import re--class sfp_onioncity(SpiderFootPlugin):- """Onion.city:Footprint,Investigate:Search Engines::Search Tor 'Onion City' search engine for mentions of the target domain."""-- # Default options- opts = {- 'pages': 20, # Number of results pages to iterate- 'fetchlinks': False- }-- # Option descriptions- optdescs = {- 'pages': "Number of results pages to iterate through.",- 'fetchlinks': "Fetch the darknet pages (via TOR, if enabled) to verify they mention your target."- }-- # Target- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["INTERNET_NAME", "DOMAIN_NAME"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["DARKNET_MENTION_URL", "DARKNET_MENTION_CONTENT",- "SEARCH_ENGINE_WEB_CONTENT"]-- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if eventData in self.results:- self.sf.debug("Already did a search for " + eventData + ", skipping.")- return None- else:- self.results.append(eventData)-- # Sites hosted on the domain- pages = self.sf.googleIterate("site:onion.city+" + eventData,- dict(limit=self.opts['pages'], useragent=self.opts['_useragent'],- timeout=self.opts['_fetchtimeout']))- if pages is None:- self.sf.info("No results returned from Google.")- return None-- for page in pages.keys():- if page in self.results:- continue- else:- self.results.append(page)-- # Check if we've been asked to stop- if self.checkForStop():- return None-- # Submit the google results for analysis- evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", pages[page],- self.__name__, event)- self.notifyListeners(evt)-- links = self.sf.parseLinks(page, pages[page], eventData)- if len(links) == 0:- continue-- for link in links:- if link in self.results:- continue- else:- self.results.append(link)- self.sf.debug("Found a darknet mention: " + link)- if self.sf.urlFQDN(link).endswith(".onion.city"):- if self.checkForStop():- return None- torlink = link.replace(".onion.city", ".onion")- if self.opts['fetchlinks']:- res = self.sf.fetchUrl(torlink, timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])-- if res['content'] is None:- self.sf.debug("Ignoring " + link + " as no data returned")- continue-- # Sometimes onion city search results false positives- if re.search("[^a-zA-Z\-\_0-9]" + re.escape(eventData) +- "[^a-zA-Z\-\_0-9]", res['content'], re.IGNORECASE) is None:- self.sf.debug("Ignoring " + link + " as no mention of " + eventData)- continue-- evt = SpiderFootEvent("DARKNET_MENTION_URL", torlink, self.__name__, event)- self.notifyListeners(evt)-- try:- startIndex = res['content'].index(eventData) - 120- endIndex = startIndex + len(eventData) + 240- except BaseException as e:- self.sf.debug("String not found in content.")- continue-- data = res['content'][startIndex:endIndex]- evt = SpiderFootEvent("DARKNET_MENTION_CONTENT", "..." + data + "...",- self.__name__, evt)- self.notifyListeners(evt)- else:- evt = SpiderFootEvent("DARKNET_MENTION_URL", torlink, self.__name__, event)- self.notifyListeners(evt)---# End of sfp_onioncity class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_onioncity+# Purpose: Searches the Tor search engine 'Onion City' for content related+# to the domain in question.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 15/07/2015+# Copyright: (c) Steve Micallef 2015+# Licence: GPL+# -------------------------------------------------------------------------------++from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+import re++class sfp_onioncity(SpiderFootPlugin):+ """Onion.city:Footprint,Investigate:Search Engines::Search Tor 'Onion City' search engine for mentions of the target domain."""+++ # Default options+ opts = {+ 'pages': 20, # Number of results pages to iterate+ 'fetchlinks': False+ }++ # Option descriptions+ optdescs = {+ 'pages': "Number of results pages to iterate through.",+ 'fetchlinks': "Fetch the darknet pages (via TOR, if enabled) to verify they mention your target."+ }++ # Target+ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["INTERNET_NAME", "DOMAIN_NAME"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["DARKNET_MENTION_URL", "DARKNET_MENTION_CONTENT",+ "SEARCH_ENGINE_WEB_CONTENT"]++ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if eventData in self.results:+ self.sf.debug("Already did a search for " + eventData + ", skipping.")+ return None+ else:+ self.results.append(eventData)++ # Sites hosted on the domain+ pages = self.sf.googleIterate("site:onion.city+" + eventData,+ dict(limit=self.opts['pages'], useragent=self.opts['_useragent'],+ timeout=self.opts['_fetchtimeout']))+ if pages is None:+ self.sf.info("No results returned from Google.")+ return None++ for page in pages.keys():+ if page in self.results:+ continue+ else:+ self.results.append(page)++ # Check if we've been asked to stop+ if self.checkForStop():+ return None++ # Submit the google results for analysis+ evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", pages[page],+ self.__name__, event)+ self.notifyListeners(evt)++ links = self.sf.parseLinks(page, pages[page], eventData)+ if len(links) == 0:+ continue++ for link in links:+ if link in self.results:+ continue+ else:+ self.results.append(link)+ self.sf.debug("Found a darknet mention: " + link)+ if self.sf.urlFQDN(link).endswith(".onion.city"):+ if self.checkForStop():+ return None+ torlink = link.replace(".onion.city", ".onion")+ if self.opts['fetchlinks']:+ res = self.sf.fetchUrl(torlink, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])++ if res['content'] is None:+ self.sf.debug("Ignoring " + link + " as no data returned")+ continue++ # Sometimes onion city search results false positives+ if re.search("[^a-zA-Z\-\_0-9]" + re.escape(eventData) ++ "[^a-zA-Z\-\_0-9]", res['content'], re.IGNORECASE) is None:+ self.sf.debug("Ignoring " + link + " as no mention of " + eventData)+ continue++ evt = SpiderFootEvent("DARKNET_MENTION_URL", torlink, self.__name__, event)+ self.notifyListeners(evt)++ try:+ startIndex = res['content'].index(eventData) - 120+ endIndex = startIndex + len(eventData) + 240+ except BaseException as e:+ self.sf.debug("String not found in content.")+ continue++ data = res['content'][startIndex:endIndex]+ evt = SpiderFootEvent("DARKNET_MENTION_CONTENT", "..." + data + "...",+ self.__name__, evt)+ self.notifyListeners(evt)+ else:+ evt = SpiderFootEvent("DARKNET_MENTION_URL", torlink, self.__name__, event)+ self.notifyListeners(evt)+++# End of sfp_onioncity classdiff --git a/modules/sfp_openbugbounty.py b/modules/sfp_openbugbounty.pyindex 7159e4d1..a8bba99f 100644--- a/modules/sfp_openbugbounty.py+++ b/modules/sfp_openbugbounty.py@@ -1,102 +1,103 @@-#--------------------------------------------------------------------------------# Name: sfp_openbugbounty-# Purpose: Query the Open Bug Bounty database to see if our target appears.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 04/10/2015-# Copyright: (c) Steve Micallef-# Licence: GPL-#---------------------------------------------------------------------------------import sys-import time-import datetime-import re-import json-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent--class sfp_openbugbounty(SpiderFootPlugin):- """Open Bug Bounty:Footprint,Investigate,Passive:Blacklists:errorprone:Check external vulnerability scanning/reporting service openbugbounty.org to see if the target is listed."""-- # Default options- opts = {- }-- # Option descriptions- optdescs = {- }-- # Be sure to completely clear any class variables in setup()- # or you run the risk of data persisting between scan runs.-- results = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- # 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- def watchedEvents(self):- return ["INTERNET_NAME"]-- # What events this module produces- def producedEvents(self):- ret = ["VULNERABILITY"]-- return ret-- # Query XSSposed.org- def queryOBB(self, qry):- ret = list()- base = "https://www.openbugbounty.org"- url = "https://www.openbugbounty.org/search/?search=" + qry- res = self.sf.fetchUrl(url, timeout=30, useragent=self.opts['_useragent'])-- if res['content'] is None:- self.sf.debug("No content returned from openbugbounty.org")- return None-- try:- rx = re.compile(".*<div class=.cell1.><a href=.(.*).>(.*" + qry + ").*?</a></div>.*", re.IGNORECASE)- for m in rx.findall(res['content']):- # Report it- if m[1] == qry or m[1].endswith("."+qry):- ret.append("From openbugbounty.org: <SFURL>" + base + m[0] + "</SFURL>")- except Exception as e:- self.sf.error("Error processing response from openbugbounty.org: " + str(e), False)- return None- return ret-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- data = list()-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- # Don't look up stuff twice- if self.results.has_key(eventData):- self.sf.debug("Skipping " + eventData + " as already mapped.")- return None- else:- self.results[eventData] = True-- obb = self.queryOBB(eventData)- if obb:- data.extend(obb)-- for n in data:- # Notify other modules of what you've found- e = SpiderFootEvent("VULNERABILITY", n, self.__name__, event)- self.notifyListeners(e)--# End of sfp_openbugbounty class+#-------------------------------------------------------------------------------+# Name: sfp_openbugbounty+# Purpose: Query the Open Bug Bounty database to see if our target appears.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 04/10/2015+# Copyright: (c) Steve Micallef+# Licence: GPL+#-------------------------------------------------------------------------------++import sys+import time+import datetime+import re+import json+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++class sfp_openbugbounty(SpiderFootPlugin):+ """Open Bug Bounty:Footprint,Investigate,Passive:Leaks, Dumps and Breaches:errorprone:Check external vulnerability scanning/reporting service openbugbounty.org to see if the target is listed."""+++ # Default options+ opts = {+ }++ # Option descriptions+ optdescs = {+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ # 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+ def watchedEvents(self):+ return ["INTERNET_NAME"]++ # What events this module produces+ def producedEvents(self):+ ret = ["VULNERABILITY"]++ return ret++ # Query XSSposed.org+ def queryOBB(self, qry):+ ret = list()+ base = "https://www.openbugbounty.org"+ url = "https://www.openbugbounty.org/search/?search=" + qry+ res = self.sf.fetchUrl(url, timeout=30, useragent=self.opts['_useragent'])++ if res['content'] is None:+ self.sf.debug("No content returned from openbugbounty.org")+ return None++ try:+ rx = re.compile(".*<div class=.cell1.><a href=.(.*).>(.*" + qry + ").*?</a></div>.*", re.IGNORECASE)+ for m in rx.findall(res['content']):+ # Report it+ if m[1] == qry or m[1].endswith("."+qry):+ ret.append("From openbugbounty.org: <SFURL>" + base + m[0] + "</SFURL>")+ except Exception as e:+ self.sf.error("Error processing response from openbugbounty.org: " + str(e), False)+ return None+ return ret++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ data = list()++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ # Don't look up stuff twice+ if self.results.has_key(eventData):+ self.sf.debug("Skipping " + eventData + " as already mapped.")+ return None+ else:+ self.results[eventData] = True++ obb = self.queryOBB(eventData)+ if obb:+ data.extend(obb)++ for n in data:+ # Notify other modules of what you've found+ e = SpiderFootEvent("VULNERABILITY", n, self.__name__, event)+ self.notifyListeners(e)++# End of sfp_openbugbounty classdiff --git a/modules/sfp_pageinfo.py b/modules/sfp_pageinfo.pyindex 47684590..40d57f6e 100644--- a/modules/sfp_pageinfo.py+++ b/modules/sfp_pageinfo.py@@ -1,118 +1,119 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_pageinfo-# Purpose: SpiderFoot plug-in for scanning retreived content by other-# modules (such as sfp_spider) and building up information about-# the page, such as whether it uses Javascript, has forms, and more.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 02/05/2012-# Copyright: (c) Steve Micallef 2012-# Licence: GPL-# ---------------------------------------------------------------------------------import re-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent--# Indentify pages that use Javascript libs, handle passwords, have forms,-# permit file uploads and more to come.-regexps = dict({- 'URL_JAVASCRIPT': list(['text/javascript', '<script ']),- 'URL_FORM': list(['<form ', 'method=[PG]', '<input ']),- 'URL_PASSWORD': list(['<input.*type=[\"\']*password']),- 'URL_UPLOAD': list(['type=[\"\']*file']),- 'URL_JAVA_APPLET': list(['<applet ']),- 'URL_FLASH': list(['\.swf[ \'\"]'])-})---class sfp_pageinfo(SpiderFootPlugin):- """Page Info:Footprint,Investigate:Data Analysis::Obtain information about web pages (do they take passwords, do they contain forms, etc.)"""-- # Default options- opts = {}-- results = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["TARGET_WEB_CONTENT"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["URL_STATIC", "URL_JAVASCRIPT", "URL_FORM", "URL_PASSWORD",- "URL_UPLOAD", "URL_JAVA_APPLET", "URL_FLASH", "PROVIDER_JAVASCRIPT"]-- # Handle events sent to this module- def handleEvent(self, event):- # We are only interested in the raw data from the spidering module- # because the spidering module will always provide events with the- # event.sourceEvent.data set to the URL of the source.- if "sfp_spider" not in event.module:- self.sf.debug("Ignoring web content from " + event.module)- return None-- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- eventSource = event.sourceEvent.data # will be the URL of the raw data-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- # We aren't interested in describing pages that are not hosted on- # our base domain.- if not self.getTarget().matches(self.sf.urlFQDN(eventSource)):- self.sf.debug("Not gathering page info for external site " + eventSource)- return None-- if eventSource not in self.results.keys():- self.results[eventSource] = list()- else:- self.sf.debug("Already checked this page for a page type, skipping.")- return None-- # Check the configured regexps to determine the page type- for regexpGrp in regexps.keys():- if regexpGrp in self.results[eventSource]:- continue-- for regex in regexps[regexpGrp]:- rx = re.compile(regex, re.IGNORECASE)- matches = re.findall(rx, eventData)- if len(matches) > 0 and regexpGrp not in self.results[eventSource]:- self.sf.info("Matched " + regexpGrp + " in content from " + eventSource)- self.results[eventSource].append(regexpGrp)- evt = SpiderFootEvent(regexpGrp, eventSource,- self.__name__, event.sourceEvent)- self.notifyListeners(evt)-- # If no regexps were matched, consider this a static page- if len(self.results[eventSource]) == 0:- self.sf.info("Treating " + eventSource + " as URL_STATIC")- evt = SpiderFootEvent("URL_STATIC", eventSource, self.__name__, event.sourceEvent)- self.notifyListeners(evt)-- # Check for externally referenced Javascript pages- pat = re.compile("<script.*src=[\'\"]?([^\'\">]*)", re.IGNORECASE)- matches = re.findall(pat, eventData)- if len(matches) > 0:- for match in matches:- if '://' in match and not self.getTarget().matches(self.sf.urlFQDN(match)):- self.sf.debug("Externally hosted Javascript found at: " + match)- evt = SpiderFootEvent("PROVIDER_JAVASCRIPT", match,- self.__name__, event.sourceEvent)- self.notifyListeners(evt)-- return None--# End of sfp_pageinfo class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_pageinfo+# Purpose: SpiderFoot plug-in for scanning retreived content by other+# modules (such as sfp_spider) and building up information about+# the page, such as whether it uses Javascript, has forms, and more.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 02/05/2012+# Copyright: (c) Steve Micallef 2012+# Licence: GPL+# -------------------------------------------------------------------------------++import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++# Indentify pages that use Javascript libs, handle passwords, have forms,+# permit file uploads and more to come.+regexps = dict({+ 'URL_JAVASCRIPT': list(['text/javascript', '<script ']),+ 'URL_FORM': list(['<form ', 'method=[PG]', '<input ']),+ 'URL_PASSWORD': list(['<input.*type=[\"\']*password']),+ 'URL_UPLOAD': list(['type=[\"\']*file']),+ 'URL_JAVA_APPLET': list(['<applet ']),+ 'URL_FLASH': list(['\.swf[ \'\"]'])+})+++class sfp_pageinfo(SpiderFootPlugin):+ """Page Info:Footprint,Investigate:Content Analysis::Obtain information about web pages (do they take passwords, do they contain forms, etc.)"""+++ # Default options+ opts = {}++ results = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["TARGET_WEB_CONTENT"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["URL_STATIC", "URL_JAVASCRIPT", "URL_FORM", "URL_PASSWORD",+ "URL_UPLOAD", "URL_JAVA_APPLET", "URL_FLASH", "PROVIDER_JAVASCRIPT"]++ # Handle events sent to this module+ def handleEvent(self, event):+ # We are only interested in the raw data from the spidering module+ # because the spidering module will always provide events with the+ # event.sourceEvent.data set to the URL of the source.+ if "sfp_spider" not in event.module:+ self.sf.debug("Ignoring web content from " + event.module)+ return None++ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ eventSource = event.sourceEvent.data # will be the URL of the raw data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ # We aren't interested in describing pages that are not hosted on+ # our base domain.+ if not self.getTarget().matches(self.sf.urlFQDN(eventSource)):+ self.sf.debug("Not gathering page info for external site " + eventSource)+ return None++ if eventSource not in self.results.keys():+ self.results[eventSource] = list()+ else:+ self.sf.debug("Already checked this page for a page type, skipping.")+ return None++ # Check the configured regexps to determine the page type+ for regexpGrp in regexps.keys():+ if regexpGrp in self.results[eventSource]:+ continue++ for regex in regexps[regexpGrp]:+ rx = re.compile(regex, re.IGNORECASE)+ matches = re.findall(rx, eventData)+ if len(matches) > 0 and regexpGrp not in self.results[eventSource]:+ self.sf.info("Matched " + regexpGrp + " in content from " + eventSource)+ self.results[eventSource].append(regexpGrp)+ evt = SpiderFootEvent(regexpGrp, eventSource,+ self.__name__, event.sourceEvent)+ self.notifyListeners(evt)++ # If no regexps were matched, consider this a static page+ if len(self.results[eventSource]) == 0:+ self.sf.info("Treating " + eventSource + " as URL_STATIC")+ evt = SpiderFootEvent("URL_STATIC", eventSource, self.__name__, event.sourceEvent)+ self.notifyListeners(evt)++ # Check for externally referenced Javascript pages+ pat = re.compile("<script.*src=[\'\"]?([^\'\">]*)", re.IGNORECASE)+ matches = re.findall(pat, eventData)+ if len(matches) > 0:+ for match in matches:+ if '://' in match and not self.getTarget().matches(self.sf.urlFQDN(match)):+ self.sf.debug("Externally hosted Javascript found at: " + match)+ evt = SpiderFootEvent("PROVIDER_JAVASCRIPT", match,+ self.__name__, event.sourceEvent)+ self.notifyListeners(evt)++ return None++# End of sfp_pageinfo classdiff --git a/modules/sfp_pastebin.py b/modules/sfp_pastebin.pyindex 8b6a1464..c7fb3db0 100644--- a/modules/sfp_pastebin.py+++ b/modules/sfp_pastebin.py@@ -1,125 +1,126 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_pastebin-# Purpose: Searches Google for PasteBin content related to the domain in-# question.-#-# Author: Steve Micallef <[email protected]> and ShellCodeNoobx-#-# Created: 20/03/2014-# Copyright: (c) Steve Micallef 2014-# Licence: GPL-# ---------------------------------------------------------------------------------import re-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_pastebin(SpiderFootPlugin):- """PasteBin:Footprint,Investigate,Passive:Search Engines:errorprone:PasteBin scraping (via Google) to identify related content."""-- # Default options- opts = {- 'searchpages': 20 # Number of google results pages to iterate- }-- # Option descriptions- optdescs = {- 'searchpages': "Number of search results pages to iterate through."- }-- domains = {- 'pastebin': "pastebin.com"- }-- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["DOMAIN_NAME", "INTERNET_NAME", "EMAILADDR"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["LEAKSITE_CONTENT", "LEAKSITE_URL"]-- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if eventData in self.results:- return None- else:- self.results.append(eventData)-- for dom in self.domains.keys():- links = list()- target = self.domains[dom]- pages = self.sf.googleIterate("site:" + target + "%20+\"" + eventData + "\"",- dict(limit=self.opts['searchpages'],- useragent=self.opts['_useragent'],- timeout=self.opts['_fetchtimeout']))-- if pages is None:- self.sf.info("No results returned from Google search of " + target + ".")- return None-- for page in pages.keys():- if page in self.results:- continue- else:- self.results.append(page)-- # Check if we've been asked to stop- if self.checkForStop():- return None-- # Fetch the paste site content- links += self.sf.parseLinks(page, pages[page], target)-- for link in links:- if link in self.results:- continue- else:- self.results.append(link)-- self.sf.debug("Found a link: " + link)- if self.sf.urlBaseUrl(link).endswith(target):- if self.checkForStop():- return None-- res = self.sf.fetchUrl(link, timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])-- if res['content'] is None:- self.sf.debug("Ignoring " + link + " as no data returned")- continue-- # Sometimes pastes search results false positives- if re.search("[^a-zA-Z\-\_0-9]" + re.escape(eventData) +- "[^a-zA-Z\-\_0-9]", res['content'], re.IGNORECASE) is None:- continue-- try:- startIndex = res['content'].index(eventData)- except BaseException as e:- self.sf.debug("String not found in pastes content.")- continue-- evt1 = SpiderFootEvent("LEAKSITE_URL", link, self.__name__, event)- self.notifyListeners(evt1)-- evt2 = SpiderFootEvent("LEAKSITE_CONTENT", res['content'], self.__name__, evt1)- self.notifyListeners(evt2)---# End of sfp_pastebin class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_pastebin+# Purpose: Searches Google for PasteBin content related to the domain in+# question.+#+# Author: Steve Micallef <[email protected]> and ShellCodeNoobx+#+# Created: 20/03/2014+# Copyright: (c) Steve Micallef 2014+# Licence: GPL+# -------------------------------------------------------------------------------++import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_pastebin(SpiderFootPlugin):+ """PasteBin:Footprint,Investigate,Passive:Leaks, Dumps and Breaches:errorprone:PasteBin scraping (via Google) to identify related content."""+++ # Default options+ opts = {+ 'searchpages': 20 # Number of google results pages to iterate+ }++ # Option descriptions+ optdescs = {+ 'searchpages': "Number of search results pages to iterate through."+ }++ domains = {+ 'pastebin': "pastebin.com"+ }++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["DOMAIN_NAME", "INTERNET_NAME", "EMAILADDR"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["LEAKSITE_CONTENT", "LEAKSITE_URL"]++ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if eventData in self.results:+ return None+ else:+ self.results.append(eventData)++ for dom in self.domains.keys():+ links = list()+ target = self.domains[dom]+ pages = self.sf.googleIterate("site:" + target + "%20+\"" + eventData + "\"",+ dict(limit=self.opts['searchpages'],+ useragent=self.opts['_useragent'],+ timeout=self.opts['_fetchtimeout']))++ if pages is None:+ self.sf.info("No results returned from Google search of " + target + ".")+ return None++ for page in pages.keys():+ if page in self.results:+ continue+ else:+ self.results.append(page)++ # Check if we've been asked to stop+ if self.checkForStop():+ return None++ # Fetch the paste site content+ links += self.sf.parseLinks(page, pages[page], target)++ for link in links:+ if link in self.results:+ continue+ else:+ self.results.append(link)++ self.sf.debug("Found a link: " + link)+ if self.sf.urlBaseUrl(link).endswith(target):+ if self.checkForStop():+ return None++ res = self.sf.fetchUrl(link, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])++ if res['content'] is None:+ self.sf.debug("Ignoring " + link + " as no data returned")+ continue++ # Sometimes pastes search results false positives+ if re.search("[^a-zA-Z\-\_0-9]" + re.escape(eventData) ++ "[^a-zA-Z\-\_0-9]", res['content'], re.IGNORECASE) is None:+ continue++ try:+ startIndex = res['content'].index(eventData)+ except BaseException as e:+ self.sf.debug("String not found in pastes content.")+ continue++ evt1 = SpiderFootEvent("LEAKSITE_URL", link, self.__name__, event)+ self.notifyListeners(evt1)++ evt2 = SpiderFootEvent("LEAKSITE_CONTENT", res['content'], self.__name__, evt1)+ self.notifyListeners(evt2)+++# End of sfp_pastebin classdiff --git a/modules/sfp_pastie.py b/modules/sfp_pastie.pyindex 53ae067d..7d3bca6f 100644--- a/modules/sfp_pastie.py+++ b/modules/sfp_pastie.py@@ -1,125 +1,126 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_pastie-# Purpose: Searches Google for Pastie.org content related to the domain in-# question.-#-# Author: Steve Micallef <[email protected]> and ShellCodeNoobx-#-# Created: 20/03/2014-# Copyright: (c) Steve Micallef 2014-# Licence: GPL-# ---------------------------------------------------------------------------------import re-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_pastie(SpiderFootPlugin):- """Pastie.org:Footprint,Investigate,Passive:Search Engines:errorprone:Pastie.org scraping (via Google) to identify related content."""-- # Default options- opts = {- 'searchpages': 20 # Number of google results pages to iterate- }-- # Option descriptions- optdescs = {- 'searchpages': "Number of search results pages to iterate through."- }-- domains = {- 'pastie': "pastie.org"- }-- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["DOMAIN_NAME", "INTERNET_NAME", "EMAILADDR"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["LEAKSITE_CONTENT", "LEAKSITE_URL"]-- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if eventData in self.results:- return None- else:- self.results.append(eventData)-- for dom in self.domains.keys():- links = list()- target = self.domains[dom]- pages = self.sf.googleIterate("site:" + target + "%20+\"" + eventData + "\"",- dict(limit=self.opts['searchpages'],- useragent=self.opts['_useragent'],- timeout=self.opts['_fetchtimeout']))-- if pages is None:- self.sf.info("No results returned from Google search of " + target + ".")- return None-- for page in pages.keys():- if page in self.results:- continue- else:- self.results.append(page)-- # Check if we've been asked to stop- if self.checkForStop():- return None-- # Fetch the paste site content- links += self.sf.parseLinks(page, pages[page], target)-- for link in links:- if link in self.results:- continue- else:- self.results.append(link)-- self.sf.debug("Found a link: " + link)- if self.sf.urlBaseUrl(link).endswith(target):- if self.checkForStop():- return None-- res = self.sf.fetchUrl(link, timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])-- if res['content'] is None:- self.sf.debug("Ignoring " + link + " as no data returned")- continue-- # Sometimes pastes search results false positives- if re.search("[^a-zA-Z\-\_0-9]" + re.escape(eventData) +- "[^a-zA-Z\-\_0-9]", res['content'], re.IGNORECASE) is None:- continue-- try:- startIndex = res['content'].index(eventData)- except BaseException as e:- self.sf.debug("String not found in pastes content.")- continue-- evt1 = SpiderFootEvent("LEAKSITE_URL", link, self.__name__, event)- self.notifyListeners(evt1)-- evt2 = SpiderFootEvent("LEAKSITE_CONTENT", res['content'], self.__name__, evt1)- self.notifyListeners(evt2)---# End of sfp_pastie class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_pastie+# Purpose: Searches Google for Pastie.org content related to the domain in+# question.+#+# Author: Steve Micallef <[email protected]> and ShellCodeNoobx+#+# Created: 20/03/2014+# Copyright: (c) Steve Micallef 2014+# Licence: GPL+# -------------------------------------------------------------------------------++import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_pastie(SpiderFootPlugin):+ """Pastie.org:Footprint,Investigate,Passive:Leaks, Dumps and Breaches:errorprone:Pastie.org scraping (via Google) to identify related content."""+++ # Default options+ opts = {+ 'searchpages': 20 # Number of google results pages to iterate+ }++ # Option descriptions+ optdescs = {+ 'searchpages': "Number of search results pages to iterate through."+ }++ domains = {+ 'pastie': "pastie.org"+ }++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["DOMAIN_NAME", "INTERNET_NAME", "EMAILADDR"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["LEAKSITE_CONTENT", "LEAKSITE_URL"]++ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if eventData in self.results:+ return None+ else:+ self.results.append(eventData)++ for dom in self.domains.keys():+ links = list()+ target = self.domains[dom]+ pages = self.sf.googleIterate("site:" + target + "%20+\"" + eventData + "\"",+ dict(limit=self.opts['searchpages'],+ useragent=self.opts['_useragent'],+ timeout=self.opts['_fetchtimeout']))++ if pages is None:+ self.sf.info("No results returned from Google search of " + target + ".")+ return None++ for page in pages.keys():+ if page in self.results:+ continue+ else:+ self.results.append(page)++ # Check if we've been asked to stop+ if self.checkForStop():+ return None++ # Fetch the paste site content+ links += self.sf.parseLinks(page, pages[page], target)++ for link in links:+ if link in self.results:+ continue+ else:+ self.results.append(link)++ self.sf.debug("Found a link: " + link)+ if self.sf.urlBaseUrl(link).endswith(target):+ if self.checkForStop():+ return None++ res = self.sf.fetchUrl(link, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])++ if res['content'] is None:+ self.sf.debug("Ignoring " + link + " as no data returned")+ continue++ # Sometimes pastes search results false positives+ if re.search("[^a-zA-Z\-\_0-9]" + re.escape(eventData) ++ "[^a-zA-Z\-\_0-9]", res['content'], re.IGNORECASE) is None:+ continue++ try:+ startIndex = res['content'].index(eventData)+ except BaseException as e:+ self.sf.debug("String not found in pastes content.")+ continue++ evt1 = SpiderFootEvent("LEAKSITE_URL", link, self.__name__, event)+ self.notifyListeners(evt1)++ evt2 = SpiderFootEvent("LEAKSITE_CONTENT", res['content'], self.__name__, evt1)+ self.notifyListeners(evt2)+++# End of sfp_pastie classdiff --git a/modules/sfp_pgp.py b/modules/sfp_pgp.pyindex df417fb7..8d721667 100644--- a/modules/sfp_pgp.py+++ b/modules/sfp_pgp.py@@ -1,125 +1,126 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_pgp-# Purpose: SpiderFoot plug-in for looking up received e-mails in PGP-# key servers as well as finding e-mail addresses belonging to-# your target.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 17/02/2015-# Copyright: (c) Steve Micallef 2015-# Licence: GPL-# ---------------------------------------------------------------------------------import re-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_pgp(SpiderFootPlugin):- """PGP Key Look-up:Footprint,Investigate,Passive:Social::Look up e-mail addresses in PGP public key servers."""-- results = list()-- # Default options- opts = {- # options specific to this module- 'keyserver1_search': "http://pgp.mit.edu/pks/lookup?op=index&search=",- 'keyserver1_fetch': "http://pgp.mit.edu/pks/lookup?op=get&search=",- 'keyserver2_search': "https://hkps.pool.sks-keyservers.net/pks/lookup?op=vindex&search=",- 'keyserver2_fetch': "https://hkps.pool.sks-keyservers.net/pks/lookup?op=get&search="- }-- # Option descriptions- optdescs = {- 'keyserver1_search': "PGP public key server URL to find e-mail addresses on a domain. Domain will get appended.",- 'keyserver1_fetch': "PGP public key server URL to find the public key for an e-mail address. Email address will get appended.",- 'keyserver2_search': "Backup PGP public key server URL to find e-mail addresses on a domain. Domain will get appended.",- 'keyserver2_fetch': "Backup PGP public key server URL to find the public key for an e-mail address. Email address will get appended."- }-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc-- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["EMAILADDR", "DOMAIN_NAME"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["EMAILADDR", "PGP_KEY"]-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if eventData in self.results:- return None- else:- self.results.append(eventData)-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- # Get e-mail addresses on this domain- if eventName == "DOMAIN_NAME":- res = self.sf.fetchUrl(self.opts['keyserver1_search'] + eventData,- timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])-- if res['content'] is None:- res = self.sf.fetchUrl(self.opts['keyserver2_search'] + eventData,- timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])-- if res['content'] is not None:- pat = re.compile("([a-zA-Z\.0-9_\-]+@[a-zA-Z\.0-9\-]+\.[a-zA-Z\.0-9\-]+)")- matches = re.findall(pat, res['content'])- for match in matches:- self.sf.debug("Found possible email: " + match)- if len(match) < 4:- self.sf.debug("Likely invalid address.")- continue-- mailDom = match.lower().split('@')[1]- if not self.getTarget().matches(mailDom):- self.sf.debug("Ignoring e-mail address on an external domain: " + match)- continue-- self.sf.info("Found e-mail address: " + match)- evt = SpiderFootEvent("EMAILADDR", match, self.__name__, event)- self.notifyListeners(evt)-- if eventName == "EMAILADDR":- res = self.sf.fetchUrl(self.opts['keyserver1_fetch'] + eventData,- timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])-- if res['content'] is None:- res = self.sf.fetchUrl(self.opts['keyserver2_fetch'] + eventData,- timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])-- if res['content'] is not None:- pat = re.compile("(-----BEGIN.*END.*BLOCK-----)", re.MULTILINE | re.DOTALL)- matches = re.findall(pat, res['content'])- for match in matches:- self.sf.debug("Found public key: " + match)- if len(match) < 300:- self.sf.debug("Likely invalid public key.")- continue-- evt = SpiderFootEvent("PGP_KEY", match, self.__name__, event)- self.notifyListeners(evt)-- return None--# End of sfp_pgp class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_pgp+# Purpose: SpiderFoot plug-in for looking up received e-mails in PGP+# key servers as well as finding e-mail addresses belonging to+# your target.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 17/02/2015+# Copyright: (c) Steve Micallef 2015+# Licence: GPL+# -------------------------------------------------------------------------------++import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_pgp(SpiderFootPlugin):+ """PGP Key Look-up:Footprint,Investigate,Passive:Public Registries::Look up e-mail addresses in PGP public key servers."""+++ results = list()++ # Default options+ opts = {+ # options specific to this module+ 'keyserver1_search': "http://pgp.mit.edu/pks/lookup?op=index&search=",+ 'keyserver1_fetch': "http://pgp.mit.edu/pks/lookup?op=get&search=",+ 'keyserver2_search': "https://hkps.pool.sks-keyservers.net/pks/lookup?op=vindex&search=",+ 'keyserver2_fetch': "https://hkps.pool.sks-keyservers.net/pks/lookup?op=get&search="+ }++ # Option descriptions+ optdescs = {+ 'keyserver1_search': "PGP public key server URL to find e-mail addresses on a domain. Domain will get appended.",+ 'keyserver1_fetch': "PGP public key server URL to find the public key for an e-mail address. Email address will get appended.",+ 'keyserver2_search': "Backup PGP public key server URL to find e-mail addresses on a domain. Domain will get appended.",+ 'keyserver2_fetch': "Backup PGP public key server URL to find the public key for an e-mail address. Email address will get appended."+ }++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc++ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["EMAILADDR", "DOMAIN_NAME"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["EMAILADDR", "PGP_KEY"]++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if eventData in self.results:+ return None+ else:+ self.results.append(eventData)++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ # Get e-mail addresses on this domain+ if eventName == "DOMAIN_NAME":+ res = self.sf.fetchUrl(self.opts['keyserver1_search'] + eventData,+ timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])++ if res['content'] is None:+ res = self.sf.fetchUrl(self.opts['keyserver2_search'] + eventData,+ timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])++ if res['content'] is not None:+ pat = re.compile("([a-zA-Z\.0-9_\-]+@[a-zA-Z\.0-9\-]+\.[a-zA-Z\.0-9\-]+)")+ matches = re.findall(pat, res['content'])+ for match in matches:+ self.sf.debug("Found possible email: " + match)+ if len(match) < 4:+ self.sf.debug("Likely invalid address.")+ continue++ mailDom = match.lower().split('@')[1]+ if not self.getTarget().matches(mailDom):+ self.sf.debug("Ignoring e-mail address on an external domain: " + match)+ continue++ self.sf.info("Found e-mail address: " + match)+ evt = SpiderFootEvent("EMAILADDR", match, self.__name__, event)+ self.notifyListeners(evt)++ if eventName == "EMAILADDR":+ res = self.sf.fetchUrl(self.opts['keyserver1_fetch'] + eventData,+ timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])++ if res['content'] is None:+ res = self.sf.fetchUrl(self.opts['keyserver2_fetch'] + eventData,+ timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])++ if res['content'] is not None:+ pat = re.compile("(-----BEGIN.*END.*BLOCK-----)", re.MULTILINE | re.DOTALL)+ matches = re.findall(pat, res['content'])+ for match in matches:+ self.sf.debug("Found public key: " + match)+ if len(match) < 300:+ self.sf.debug("Likely invalid public key.")+ continue++ evt = SpiderFootEvent("PGP_KEY", match, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_pgp classdiff --git a/modules/sfp_phishtank.py b/modules/sfp_phishtank.pyindex bb73e022..71b849f2 100644--- a/modules/sfp_phishtank.py+++ b/modules/sfp_phishtank.py@@ -1,265 +1,266 @@-# -*- 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 class+# -*- 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:Reputation Systems: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_phone.py b/modules/sfp_phone.pyindex 1f4a4686..5972ad76 100644--- a/modules/sfp_phone.py+++ b/modules/sfp_phone.py@@ -1,70 +1,71 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_phone-# Purpose: SpiderFoot plug-in for scanning retreived content by other-# modules (such as sfp_spider) and identifying phone numbers.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 19/06/2016-# Copyright: (c) Steve Micallef 2016-# Licence: GPL-# ---------------------------------------------------------------------------------try:- import re2 as re-except ImportError:- import re-import phonenumbers-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent--class sfp_phone(SpiderFootPlugin):- """Phone Numbers:Footprint,Investigate:Social::Identify phone numbers in scraped webpages."""-- # Default options- opts = {}-- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["TARGET_WEB_CONTENT", "DOMAIN_WHOIS", "NETBLOCK_WHOIS"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["PHONE_NUMBER"]-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- sourceData = self.sf.hashstring(eventData)-- if sourceData in self.results:- return None- else:- self.results.append(sourceData)-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- # Make potential phone numbers more friendly to parse- content = eventData.replace('.','-')- for match in phonenumbers.PhoneNumberMatcher(content, region=None):- n = phonenumbers.format_number(match.number,- phonenumbers.PhoneNumberFormat.E164)- evt = SpiderFootEvent("PHONE_NUMBER", n, self.__name__, event)- self.notifyListeners(evt)-- return None--# End of sfp_phone class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_phone+# Purpose: SpiderFoot plug-in for scanning retreived content by other+# modules (such as sfp_spider) and identifying phone numbers.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 19/06/2016+# Copyright: (c) Steve Micallef 2016+# Licence: GPL+# -------------------------------------------------------------------------------++try:+ import re2 as re+except ImportError:+ import re+import phonenumbers+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++class sfp_phone(SpiderFootPlugin):+ """Phone Numbers:Footprint,Investigate:Real World::Identify phone numbers in scraped webpages."""+++ # Default options+ opts = {}++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["TARGET_WEB_CONTENT", "DOMAIN_WHOIS", "NETBLOCK_WHOIS"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["PHONE_NUMBER"]++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ sourceData = self.sf.hashstring(eventData)++ if sourceData in self.results:+ return None+ else:+ self.results.append(sourceData)++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ # Make potential phone numbers more friendly to parse+ content = eventData.replace('.','-')+ for match in phonenumbers.PhoneNumberMatcher(content, region=None):+ n = phonenumbers.format_number(match.number,+ phonenumbers.PhoneNumberFormat.E164)+ evt = SpiderFootEvent("PHONE_NUMBER", n, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_phone classdiff --git a/modules/sfp_portscan_tcp.py b/modules/sfp_portscan_tcp.pyindex 1be96ec1..81af9b85 100644--- a/modules/sfp_portscan_tcp.py+++ b/modules/sfp_portscan_tcp.py@@ -1,196 +1,197 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_portscan_tcp-# Purpose: SpiderFoot plug-in for performing a basic TCP port scan of IP-# addresses identified.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 20/02/2013-# Copyright: (c) Steve Micallef 2013-# Licence: GPL-# ---------------------------------------------------------------------------------from netaddr import IPAddress, IPNetwork-import socket-import random-import threading-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_portscan_tcp(SpiderFootPlugin):- """Port Scanner - TCP:Footprint,Investigate:Networking:slow,invasive:Scans for commonly open TCP ports on Internet-facing systems."""-- # Default options- opts = {- # Commonly used ports on external-facing systems- 'ports': ['21', '22', '23', '25', '53', '79', '80', '81', '88', '110', '111',- '113', '119', '123', '137', '138', '139', '143', '161', '179',- '389', '443', '445', '465', '512', '513', '514', '515', '3306',- '5432', '1521', '2638', '1433', '3389', '5900', '5901', '5902',- '5903', '5631', '631', '636',- '990', '992', '993', '995', '1080', '8080', '8888', '9000'],- 'timeout': 15,- 'maxthreads': 10,- 'randomize': True,- 'netblockscan': True,- 'netblockscanmax': 24- }-- # Option descriptions- optdescs = {- 'maxthreads': "Number of ports to try to open simultaneously (number of threads to spawn at once.)",- 'ports': "The TCP ports to scan. Prefix with an '@' to iterate through a file containing ports to try (one per line), e.g. @C:\ports.txt or @/home/bob/ports.txt. Or supply a URL to load the list from there.",- 'timeout': "Seconds before giving up on a port.",- 'randomize': "Randomize the order of ports scanned.",- 'netblockscan': "Port scan all IPs within identified owned netblocks?",- 'netblockscanmax': "Maximum netblock/subnet size to scan IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"- }-- results = dict()- portlist = list()- portResults = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- if self.opts['ports'][0].startswith("http://") or \- self.opts['ports'][0].startswith("https://") or \- self.opts['ports'][0].startswith("@"):- self.portlist = self.sf.optValueToData(self.opts['ports'][0])- else:- self.portlist = self.opts['ports']-- # Convert to integers- self.portlist = [int(x) for x in self.portlist]-- if self.opts['randomize']:- random.shuffle(self.portlist)-- # What events is this module interested in for input- def watchedEvents(self):- return ['IP_ADDRESS', '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 ["TCP_PORT_OPEN", "TCP_PORT_OPEN_BANNER"]-- def tryPort(self, ip, port):- try:- sock = socket.create_connection((ip, port), self.opts['timeout'])- sock.settimeout(self.opts['timeout'])- self.portResults[ip + ":" + str(port)] = True- except Exception as e:- self.portResults[ip + ":" + str(port)] = False- return-- # If the port was open, see what we can read- try:- self.portResults[ip + ":" + str(port)] = sock.recv(4096)- except Exception as e:- sock.close()- return-- sock.close()-- def tryPortWrapper(self, ip, portList):- self.portResults = dict()- running = True- i = 0- t = []-- # Spawn threads for scanning- while i < len(portList):- self.sf.info("Spawning thread to check port: " + str(portList[i]) + " on " + ip)- t.append(threading.Thread(name='sfp_portscan_tcp_' + str(portList[i]),- target=self.tryPort, args=(ip, portList[i])))- t[i].start()- i += 1-- # Block until all threads are finished- while running:- found = False- for rt in threading.enumerate():- if rt.name.startswith("sfp_portscan_tcp_"):- found = True-- if not found:- running = False-- return self.portResults-- # Generate TCP_PORT_OPEN_BANNER event- def sendEvent(self, resArray, srcEvent):- for cp in resArray:- if resArray[cp]:- self.sf.info("TCP Port " + cp + " found to be OPEN.")- evt = SpiderFootEvent("TCP_PORT_OPEN", cp, self.__name__, srcEvent)- self.notifyListeners(evt)- if resArray[cp] != "" and resArray[cp] != True:- bevt = SpiderFootEvent("TCP_PORT_OPEN_BANNER", resArray[cp],- self.__name__, evt)- self.notifyListeners(bevt)--- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- scanIps = list()-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- try:- if eventName == "NETBLOCK_OWNER" and self.opts['netblockscan']:- net = IPNetwork(eventData)- if net.prefixlen < self.opts['netblockscanmax']:- self.sf.debug("Skipping port scanning of " + eventData + ", too big.")- return None-- for ip in net:- ipaddr = str(ip)- if ipaddr.split(".")[3] in ['255', '0']:- continue- if '255' in ipaddr.split("."):- continue- scanIps.append(ipaddr)- else:- scanIps.append(eventData)- except BaseException as e:- self.sf.error("Strange netblock identified, unable to parse: " +- eventData + " (" + str(e) + ")", False)- return None-- for ipAddr in scanIps:- # Don't look up stuff twice- if ipAddr in self.results:- self.sf.debug("Skipping " + ipAddr + " as already scanned.")- return None- else:- self.results[ipAddr] = True-- i = 0- portArr = []- for port in self.portlist:- if self.checkForStop():- return None-- if i < self.opts['maxthreads']:- portArr.append(port)- i += 1- else:- self.sendEvent(self.tryPortWrapper(ipAddr, portArr), event)- i = 1- portArr = [port]-- # Scan whatever is remaining- self.sendEvent(self.tryPortWrapper(ipAddr, portArr), event)--# End of sfp_portscan_tcp class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_portscan_tcp+# Purpose: SpiderFoot plug-in for performing a basic TCP port scan of IP+# addresses identified.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 20/02/2013+# Copyright: (c) Steve Micallef 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from netaddr import IPAddress, IPNetwork+import socket+import random+import threading+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_portscan_tcp(SpiderFootPlugin):+ """Port Scanner - TCP:Footprint,Investigate:Crawling and Scanning:slow,invasive:Scans for commonly open TCP ports on Internet-facing systems."""+++ # Default options+ opts = {+ # Commonly used ports on external-facing systems+ 'ports': ['21', '22', '23', '25', '53', '79', '80', '81', '88', '110', '111',+ '113', '119', '123', '137', '138', '139', '143', '161', '179',+ '389', '443', '445', '465', '512', '513', '514', '515', '3306',+ '5432', '1521', '2638', '1433', '3389', '5900', '5901', '5902',+ '5903', '5631', '631', '636',+ '990', '992', '993', '995', '1080', '8080', '8888', '9000'],+ 'timeout': 15,+ 'maxthreads': 10,+ 'randomize': True,+ 'netblockscan': True,+ 'netblockscanmax': 24+ }++ # Option descriptions+ optdescs = {+ 'maxthreads': "Number of ports to try to open simultaneously (number of threads to spawn at once.)",+ 'ports': "The TCP ports to scan. Prefix with an '@' to iterate through a file containing ports to try (one per line), e.g. @C:\ports.txt or @/home/bob/ports.txt. Or supply a URL to load the list from there.",+ 'timeout': "Seconds before giving up on a port.",+ 'randomize': "Randomize the order of ports scanned.",+ 'netblockscan': "Port scan all IPs within identified owned netblocks?",+ 'netblockscanmax': "Maximum netblock/subnet size to scan IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"+ }++ results = dict()+ portlist = list()+ portResults = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ if self.opts['ports'][0].startswith("http://") or \+ self.opts['ports'][0].startswith("https://") or \+ self.opts['ports'][0].startswith("@"):+ self.portlist = self.sf.optValueToData(self.opts['ports'][0])+ else:+ self.portlist = self.opts['ports']++ # Convert to integers+ self.portlist = [int(x) for x in self.portlist]++ if self.opts['randomize']:+ random.shuffle(self.portlist)++ # What events is this module interested in for input+ def watchedEvents(self):+ return ['IP_ADDRESS', '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 ["TCP_PORT_OPEN", "TCP_PORT_OPEN_BANNER"]++ def tryPort(self, ip, port):+ try:+ sock = socket.create_connection((ip, port), self.opts['timeout'])+ sock.settimeout(self.opts['timeout'])+ self.portResults[ip + ":" + str(port)] = True+ except Exception as e:+ self.portResults[ip + ":" + str(port)] = False+ return++ # If the port was open, see what we can read+ try:+ self.portResults[ip + ":" + str(port)] = sock.recv(4096)+ except Exception as e:+ sock.close()+ return++ sock.close()++ def tryPortWrapper(self, ip, portList):+ self.portResults = dict()+ running = True+ i = 0+ t = []++ # Spawn threads for scanning+ while i < len(portList):+ self.sf.info("Spawning thread to check port: " + str(portList[i]) + " on " + ip)+ t.append(threading.Thread(name='sfp_portscan_tcp_' + str(portList[i]),+ target=self.tryPort, args=(ip, portList[i])))+ t[i].start()+ i += 1++ # Block until all threads are finished+ while running:+ found = False+ for rt in threading.enumerate():+ if rt.name.startswith("sfp_portscan_tcp_"):+ found = True++ if not found:+ running = False++ return self.portResults++ # Generate TCP_PORT_OPEN_BANNER event+ def sendEvent(self, resArray, srcEvent):+ for cp in resArray:+ if resArray[cp]:+ self.sf.info("TCP Port " + cp + " found to be OPEN.")+ evt = SpiderFootEvent("TCP_PORT_OPEN", cp, self.__name__, srcEvent)+ self.notifyListeners(evt)+ if resArray[cp] != "" and resArray[cp] != True:+ bevt = SpiderFootEvent("TCP_PORT_OPEN_BANNER", resArray[cp],+ self.__name__, evt)+ self.notifyListeners(bevt)+++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ scanIps = list()++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ try:+ if eventName == "NETBLOCK_OWNER" and self.opts['netblockscan']:+ net = IPNetwork(eventData)+ if net.prefixlen < self.opts['netblockscanmax']:+ self.sf.debug("Skipping port scanning of " + eventData + ", too big.")+ return None++ for ip in net:+ ipaddr = str(ip)+ if ipaddr.split(".")[3] in ['255', '0']:+ continue+ if '255' in ipaddr.split("."):+ continue+ scanIps.append(ipaddr)+ else:+ scanIps.append(eventData)+ except BaseException as e:+ self.sf.error("Strange netblock identified, unable to parse: " ++ eventData + " (" + str(e) + ")", False)+ return None++ for ipAddr in scanIps:+ # Don't look up stuff twice+ if ipAddr in self.results:+ self.sf.debug("Skipping " + ipAddr + " as already scanned.")+ return None+ else:+ self.results[ipAddr] = True++ i = 0+ portArr = []+ for port in self.portlist:+ if self.checkForStop():+ return None++ if i < self.opts['maxthreads']:+ portArr.append(port)+ i += 1+ else:+ self.sendEvent(self.tryPortWrapper(ipAddr, portArr), event)+ i = 1+ portArr = [port]++ # Scan whatever is remaining+ self.sendEvent(self.tryPortWrapper(ipAddr, portArr), event)++# End of sfp_portscan_tcp classdiff --git a/modules/sfp_psbdmp.py b/modules/sfp_psbdmp.pyindex 0cd992ef..619316e3 100644--- a/modules/sfp_psbdmp.py+++ b/modules/sfp_psbdmp.py@@ -1,111 +1,112 @@-#--------------------------------------------------------------------------------# Name: sfp_psbdmp-# Purpose: Query psbdmp.com for potentially hacked e-mail addresses.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 21/11/2016-# Copyright: (c) Steve Micallef-# Licence: GPL-#---------------------------------------------------------------------------------import sys-import json-import time-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent--class sfp_psbdmp(SpiderFootPlugin):- """Psbdmp.com:Footprint,Investigate,Passive:Search Engines::Check psbdmp.com (PasteBin Dump) for potentially hacked e-mails and domains."""-- # Default options- opts = {- }-- # Option descriptions- optdescs = {- }-- # Be sure to completely clear any class variables in setup()- # or you run the risk of data persisting between scan runs.-- results = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- # 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- def watchedEvents(self):- ret = ["EMAILADDR", "DOMAIN_NAME", "INTERNET_NAME"]-- return ret-- # What events this module produces- def producedEvents(self):- ret = ["LEAKSITE_URL"]-- return ret-- def query(self, qry):- ret = None-- if "@" in qry:- url = "http://psbdmp.com/api/search/email/" + qry- else:- url = "http://psbdmp.com/api/search/domain/" + qry-- res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],- useragent="SpiderFoot")-- if res['code'] == "403":- self.sf.info("Unable to fetch data from psbdmp.com right now.")- return None-- try:- ret = json.loads(res['content'])- except Exception as e:- self.sf.error("Error processing JSON response from psbdmp.com: " + str(e), False)- return None-- ids = list()- if 'count' in ret:- if ret['count'] > 0:- for d in ret['data']:- ids.append("http://psbdmp.com/" + d['id'])- else:- return None- else:- return None-- return ids-- # 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)-- # Don't look up stuff twice- if self.results.has_key(eventData):- self.sf.debug("Skipping " + eventData + " as already mapped.")- return None- else:- self.results[eventData] = True-- data = self.query(eventData)- if data == None:- return None-- for n in data:- e = SpiderFootEvent("LEAKSITE_URL", n, self.__name__, event)- self.notifyListeners(e)--# End of sfp_psbdmp class+#-------------------------------------------------------------------------------+# Name: sfp_psbdmp+# Purpose: Query psbdmp.com for potentially hacked e-mail addresses.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 21/11/2016+# Copyright: (c) Steve Micallef+# Licence: GPL+#-------------------------------------------------------------------------------++import sys+import json+import time+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++class sfp_psbdmp(SpiderFootPlugin):+ """Psbdmp.com:Footprint,Investigate,Passive:Leaks, Dumps and Breaches::Check psbdmp.com (PasteBin Dump) for potentially hacked e-mails and domains."""+++ # Default options+ opts = {+ }++ # Option descriptions+ optdescs = {+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ # 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+ def watchedEvents(self):+ ret = ["EMAILADDR", "DOMAIN_NAME", "INTERNET_NAME"]++ return ret++ # What events this module produces+ def producedEvents(self):+ ret = ["LEAKSITE_URL"]++ return ret++ def query(self, qry):+ ret = None++ if "@" in qry:+ url = "http://psbdmp.com/api/search/email/" + qry+ else:+ url = "http://psbdmp.com/api/search/domain/" + qry++ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],+ useragent="SpiderFoot")++ if res['code'] == "403":+ self.sf.info("Unable to fetch data from psbdmp.com right now.")+ return None++ try:+ ret = json.loads(res['content'])+ except Exception as e:+ self.sf.error("Error processing JSON response from psbdmp.com: " + str(e), False)+ return None++ ids = list()+ if 'count' in ret:+ if ret['count'] > 0:+ for d in ret['data']:+ ids.append("http://psbdmp.com/" + d['id'])+ else:+ return None+ else:+ return None++ return ids++ # 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)++ # Don't look up stuff twice+ if self.results.has_key(eventData):+ self.sf.debug("Skipping " + eventData + " as already mapped.")+ return None+ else:+ self.results[eventData] = True++ data = self.query(eventData)+ if data == None:+ return None++ for n in data:+ e = SpiderFootEvent("LEAKSITE_URL", n, self.__name__, event)+ self.notifyListeners(e)++# End of sfp_psbdmp classdiff --git a/modules/sfp_pwned.py b/modules/sfp_pwned.pyindex 3bf1ed6c..79704f85 100644--- a/modules/sfp_pwned.py+++ b/modules/sfp_pwned.py@@ -1,106 +1,107 @@-#--------------------------------------------------------------------------------# Name: sfp_pwned-# Purpose: Query haveibeenpwned.com to see if an e-mail account has been hacked.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 19/02/2015-# Copyright: (c) Steve Micallef-# Licence: GPL-#---------------------------------------------------------------------------------import sys-import json-import time-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent--class sfp_pwned(SpiderFootPlugin):- """Pwned Password:Footprint,Investigate,Passive:Search Engines:errorprone:Check Have I Been Pwned? for hacked e-mail addresses identified."""-- # Default options- opts = {- }-- # Option descriptions- optdescs = {- }-- # Be sure to completely clear any class variables in setup()- # or you run the risk of data persisting between scan runs.-- results = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- # 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- def watchedEvents(self):- return ["EMAILADDR"]-- # What events this module produces- def producedEvents(self):- return ["EMAILADDR_COMPROMISED"]-- def query(self, qry):- ret = None- url = "https://haveibeenpwned.com/api/v2/breachedaccount/" + qry- hdrs = { "Accept": "application/vnd.haveibeenpwned.v2+json" }- retry = 0-- while retry < 2:- # https://haveibeenpwned.com/API/v2#RateLimiting- time.sleep(1.5)- res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],- useragent="SpiderFoot", headers=hdrs)-- if res['code'] == "404":- return None-- if res['code'] == "429":- # Back off a little further- time.sleep(2)- retry += 1-- try:- ret = json.loads(res['content'])- except Exception as e:- self.sf.error("Error processing JSON response from HaveIBeenPwned?: " + str(e), False)- return None-- return ret-- # 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)-- # Don't look up stuff twice- if eventData in self.results:- self.sf.debug("Skipping " + eventData + " as already mapped.")- return None- else:- self.results[eventData] = True-- data = self.query(eventData)- if data == None:- return None-- for n in data:- site = n["Title"]- evt = eventName + "_COMPROMISED"- # Notify other modules of what you've found- e = SpiderFootEvent(evt, eventData + " [" + site + "]",- self.__name__, event)- self.notifyListeners(e)--# End of sfp_pwned class+#-------------------------------------------------------------------------------+# Name: sfp_pwned+# Purpose: Query haveibeenpwned.com to see if an e-mail account has been hacked.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 19/02/2015+# Copyright: (c) Steve Micallef+# Licence: GPL+#-------------------------------------------------------------------------------++import sys+import json+import time+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++class sfp_pwned(SpiderFootPlugin):+ """Pwned Password:Footprint,Investigate,Passive:Leaks, Dumps and Breaches:errorprone:Check Have I Been Pwned? for hacked e-mail addresses identified."""+++ # Default options+ opts = {+ }++ # Option descriptions+ optdescs = {+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ # 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+ def watchedEvents(self):+ return ["EMAILADDR"]++ # What events this module produces+ def producedEvents(self):+ return ["EMAILADDR_COMPROMISED"]++ def query(self, qry):+ ret = None+ url = "https://haveibeenpwned.com/api/v2/breachedaccount/" + qry+ hdrs = { "Accept": "application/vnd.haveibeenpwned.v2+json" }+ retry = 0++ while retry < 2:+ # https://haveibeenpwned.com/API/v2#RateLimiting+ time.sleep(1.5)+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],+ useragent="SpiderFoot", headers=hdrs)++ if res['code'] == "404":+ return None++ if res['code'] == "429":+ # Back off a little further+ time.sleep(2)+ retry += 1++ try:+ ret = json.loads(res['content'])+ except Exception as e:+ self.sf.error("Error processing JSON response from HaveIBeenPwned?: " + str(e), False)+ return None++ return ret++ # 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)++ # Don't look up stuff twice+ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + " as already mapped.")+ return None+ else:+ self.results[eventData] = True++ data = self.query(eventData)+ if data == None:+ return None++ for n in data:+ site = n["Title"]+ evt = eventName + "_COMPROMISED"+ # Notify other modules of what you've found+ e = SpiderFootEvent(evt, eventData + " [" + site + "]",+ self.__name__, event)+ self.notifyListeners(e)++# End of sfp_pwned classdiff --git a/modules/sfp_ripe.py b/modules/sfp_ripe.pyindex c6e527f1..1e4db724 100644--- a/modules/sfp_ripe.py+++ b/modules/sfp_ripe.py@@ -1,341 +1,342 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_ripe-# Purpose: Queries Internet registryes like RIPE (incl. ARIN) to get-# netblocks and other bits of info.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 8/12/2013-# Copyright: (c) Steve Micallef 2013-# Licence: GPL-# ---------------------------------------------------------------------------------import re-import json-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_ripe(SpiderFootPlugin):- """RIPE Internet Registry:Footprint,Investigate,Passive:Networking::Queries the RIPE registry (includes ARIN data) to identify netblocks and other info."""-- # Default options- opts = {}-- results = dict()- currentEventSrc = None- memCache = dict()- nbreported = dict()- keywords = None-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()- self.memCache = dict()- self.currentEventSrc = None- self.nbreported = dict()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ['IP_ADDRESS', 'NETBLOCK_MEMBER', 'NETBLOCK_OWNER',- 'BGP_AS_OWNER', 'BGP_AS_MEMBER']-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["NETBLOCK_MEMBER", "NETBLOCK_OWNER", "BGP_AS_MEMBER",- "RAW_RIR_DATA", "BGP_AS_OWNER", "BGP_AS_PEER"]-- # Fetch content and notify of the raw data- def fetchRir(self, url):- if url in self.memCache:- res = self.memCache[url]- else:- res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])- if res['content'] is not None:- self.memCache[url] = res- evt = SpiderFootEvent("RAW_RIR_DATA", res['content'], self.__name__,- self.currentEventSrc)- self.notifyListeners(evt)- return res-- # Get the netblock the IP resides in- def ipNetblock(self, ipaddr):- prefix = None-- res = self.fetchRir("https://stat.ripe.net/data/network-info/data.json?resource=" + ipaddr)- if res['content'] is None:- self.sf.debug("No Netblock info found/available for " + ipaddr + " at RIPE.")- return None-- try:- j = json.loads(res['content'])- except Exception as e:- self.sf.debug("Error processing JSON response.")- return None-- prefix = j["data"]["prefix"]- if prefix is None:- self.sf.debug("Could not identify network prefix.")- return None-- return prefix-- # Get the AS owning the netblock- def netblockAs(self, prefix):- asn = None-- res = self.fetchRir("https://stat.ripe.net/data/whois/data.json?resource=" + prefix)- if res['content'] is None:- self.sf.debug("No AS info found/available for prefix: " + prefix + " at RIPE.")- return None-- try:- j = json.loads(res['content'])- if len(j["data"]["irr_records"]) > 0:- data = j["data"]["irr_records"][0]- else:- data = j["data"]["records"][0]- except Exception as e:- self.sf.debug("Error processing JSON response.")- return None-- for rec in data:- if rec["key"] == "origin":- asn = rec["value"]- break-- if asn == None:- return None-- return str(asn)-- # Owner information about an AS- def asOwnerInfo(self, asn):- ownerinfo = dict()-- res = self.fetchRir("https://stat.ripe.net/data/whois/data.json?resource=" + asn)- if res['content'] is None:- self.sf.debug("No info found/available for ASN: " + asn + " at RIPE.")- return None-- try:- j = json.loads(res['content'])- data = j["data"]["records"]- except Exception as e:- self.sf.debug("Error processing JSON response.")- return None-- for rec in data:- for d in rec:- if d["key"].lower().startswith("org") or \- d["key"].lower().startswith("as") or \- d["key"].lower().startswith("aut") or \- d["key"].lower().startswith("descr") and \- d["value"].lower() not in ["null", "none", "none specified"]:- if d["key"] in ownerinfo:- ownerinfo[d["key"]].append(d["value"])- else:- ownerinfo[d["key"]] = [d["value"]]-- self.sf.debug("Returning ownerinfo: " + str(ownerinfo))- return ownerinfo-- # Netblocks owned by an AS- def asNetblocks(self, asn):- netblocks = list()-- res = self.fetchRir("https://stat.ripe.net/data/announced-prefixes/data.json?resource=AS" + asn)- if res['content'] is None:- self.sf.debug("No netblocks info found/available for AS" + asn + " at RIPE.")- return None-- try:- j = json.loads(res['content'])- data = j["data"]["prefixes"]- except Exception as e:- self.sf.debug("Error processing JSON response.")- return None-- for rec in data:- netblocks.append(rec["prefix"])- self.sf.info("Additional netblock found from same AS: " + rec["prefix"])-- return netblocks-- # Neighbours to an AS- def asNeighbours(self, asn):- neighbours = list()-- res = self.fetchRir("https://stat.ripe.net/data/asn-neighbours/data.json?resource=AS" + asn)- if res['content'] is None:- self.sf.debug("No neighbour info found/available for AS" + asn + " at RIPE.")- return None-- try:- j = json.loads(res['content'])- data = j["data"]["neighbours"]- except Exception as e:- self.sf.debug("Error processing JSON response.")- return None-- for rec in data:- neighbours.append(str(rec['asn']))-- return neighbours-- # Determine whether there is a textual link between the target- # and the string supplied.- def findName(self, string):- # Simplest check to perform..- if self.getTarget().getValue() in string:- return True-- if self.keywords is None:- self.keywords = self.sf.domainKeywords(self.getTarget().getNames(),- self.opts['_internettlds'])-- # Slightly more complex..- rx = [- '^{0}[-_/\'\"\\\.,\?\! ]',- '[-_/\'\"\\\.,\?\! ]{0}$',- '[-_/\'\"\\\.,\?\! ]{0}[-_/\'\"\\\.,\?\! ]'- ]-- # Mess with the keyword as a last resort..- keywordList = list()- for kw in self.keywords:- # Create versions of the keyword, esp. if hyphens are involved.- keywordList.append(kw)- keywordList.append(kw.replace('-', ' '))- keywordList.append(kw.replace('-', '_'))- keywordList.append(kw.replace('-', ''))-- for kw in keywordList:- self.sf.debug("Looking for keyword: " + kw)- for r in rx:- if re.match(r.format(kw), string, re.IGNORECASE) is not None:- return True-- return False-- # Owns the AS or not?- def ownsAs(self, asn):- # Determine whether the AS is owned by our target- ownerinfo = self.asOwnerInfo(asn)- owned = False-- if ownerinfo is not None:- for k in ownerinfo.keys():- items = ownerinfo[k]- for item in items:- if self.findName(item.lower()):- owned = True- return owned-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- self.currentEventSrc = event-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- # Don't look up stuff twice- if eventData in self.results:- self.sf.debug("Skipping " + eventData + " as already mapped.")- return None- else:- self.results[eventData] = True-- # BGP AS Owner/Member -> BGP AS Peers- if eventName.startswith("BGP_AS_"):- neighs = self.asNeighbours(eventData)- if neighs is None:- self.sf.debug("No neighbors found to AS " + eventData)- return None-- for nasn in neighs:- if self.checkForStop():- return None-- ownerinfo = self.asOwnerInfo(nasn)- ownertext = ''- if ownerinfo is not None:- for k, v in ownerinfo.iteritems():- ownertext = ownertext + k + ": " + ', '.join(v) + "\n"-- if len(ownerinfo) > 0:- evt = SpiderFootEvent("BGP_AS_PEER", nasn,- self.__name__, event)- self.notifyListeners(evt)-- # BGP AS Owner -> Other Netblocks- if eventName == "BGP_AS_OWNER":- # Don't report additional netblocks from this AS if we've- # already found this AS before.- if eventData not in self.nbreported:- # Find all the netblocks owned by this AS- self.nbreported[eventData] = True- netblocks = self.asNetblocks(eventData)- if netblocks is not None:- for netblock in netblocks:- if netblock in self.results:- continue-- # Technically this netblock was identified via the AS, not- # the original IP event, so link it to asevt, not event.- evt = SpiderFootEvent("NETBLOCK_OWNER", netblock,- self.__name__, event)- self.notifyListeners(evt)- return None-- # NETBLOCK -> AS and other owned netblocks- if eventName.startswith("NETBLOCK_"):- # Get the BGP AS the netblock is a part of- asn = self.netblockAs(eventData)- if asn is None:- self.sf.debug("Could not identify BGP AS for " + eventData)- return None-- if self.ownsAs(asn):- asevt = SpiderFootEvent("BGP_AS_OWNER", asn, self.__name__, event)- self.notifyListeners(asevt)- else:- asevt = SpiderFootEvent("BGP_AS_MEMBER", asn, self.__name__, event)- self.notifyListeners(asevt)-- return None-- # IP ADDRESS -> NETBLOCK- if eventName == "IP_ADDRESS":- # Get the Netblock the IP is a part of- prefix = self.ipNetblock(eventData)- if prefix is None:- self.sf.debug("Could not identify network prefix for " + eventData)- return None-- # Get the BGP AS the netblock is a part of- asn = self.netblockAs(prefix)- if asn is None:- self.sf.debug("Could not identify BGP AS for " + prefix)- return None-- if self.ownsAs(asn):- self.sf.info("Owned netblock found: " + prefix + "(" + asn + ")")- evt = SpiderFootEvent("NETBLOCK_OWNER", prefix, self.__name__, event)- self.notifyListeners(evt)- else:- self.sf.info("Netblock found: " + prefix + "(" + asn + ")")- evt = SpiderFootEvent("NETBLOCK_MEMBER", prefix, self.__name__, event)- self.notifyListeners(evt)-- return None--# End of sfp_ripe class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_ripe+# Purpose: Queries Internet registryes like RIPE (incl. ARIN) to get+# netblocks and other bits of info.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 8/12/2013+# Copyright: (c) Steve Micallef 2013+# Licence: GPL+# -------------------------------------------------------------------------------++import re+import json+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_ripe(SpiderFootPlugin):+ """RIPE Internet Registry:Footprint,Investigate,Passive:Public Registries::Queries the RIPE registry (includes ARIN data) to identify netblocks and other info."""+++ # Default options+ opts = {}++ results = dict()+ currentEventSrc = None+ memCache = dict()+ nbreported = dict()+ keywords = None++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()+ self.memCache = dict()+ self.currentEventSrc = None+ self.nbreported = dict()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ['IP_ADDRESS', 'NETBLOCK_MEMBER', 'NETBLOCK_OWNER',+ 'BGP_AS_OWNER', 'BGP_AS_MEMBER']++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["NETBLOCK_MEMBER", "NETBLOCK_OWNER", "BGP_AS_MEMBER",+ "RAW_RIR_DATA", "BGP_AS_OWNER", "BGP_AS_PEER"]++ # Fetch content and notify of the raw data+ def fetchRir(self, url):+ if url in self.memCache:+ res = self.memCache[url]+ else:+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])+ if res['content'] is not None:+ self.memCache[url] = res+ evt = SpiderFootEvent("RAW_RIR_DATA", res['content'], self.__name__,+ self.currentEventSrc)+ self.notifyListeners(evt)+ return res++ # Get the netblock the IP resides in+ def ipNetblock(self, ipaddr):+ prefix = None++ res = self.fetchRir("https://stat.ripe.net/data/network-info/data.json?resource=" + ipaddr)+ if res['content'] is None:+ self.sf.debug("No Netblock info found/available for " + ipaddr + " at RIPE.")+ return None++ try:+ j = json.loads(res['content'])+ except Exception as e:+ self.sf.debug("Error processing JSON response.")+ return None++ prefix = j["data"]["prefix"]+ if prefix is None:+ self.sf.debug("Could not identify network prefix.")+ return None++ return prefix++ # Get the AS owning the netblock+ def netblockAs(self, prefix):+ asn = None++ res = self.fetchRir("https://stat.ripe.net/data/whois/data.json?resource=" + prefix)+ if res['content'] is None:+ self.sf.debug("No AS info found/available for prefix: " + prefix + " at RIPE.")+ return None++ try:+ j = json.loads(res['content'])+ if len(j["data"]["irr_records"]) > 0:+ data = j["data"]["irr_records"][0]+ else:+ data = j["data"]["records"][0]+ except Exception as e:+ self.sf.debug("Error processing JSON response.")+ return None++ for rec in data:+ if rec["key"] == "origin":+ asn = rec["value"]+ break++ if asn == None:+ return None++ return str(asn)++ # Owner information about an AS+ def asOwnerInfo(self, asn):+ ownerinfo = dict()++ res = self.fetchRir("https://stat.ripe.net/data/whois/data.json?resource=" + asn)+ if res['content'] is None:+ self.sf.debug("No info found/available for ASN: " + asn + " at RIPE.")+ return None++ try:+ j = json.loads(res['content'])+ data = j["data"]["records"]+ except Exception as e:+ self.sf.debug("Error processing JSON response.")+ return None++ for rec in data:+ for d in rec:+ if d["key"].lower().startswith("org") or \+ d["key"].lower().startswith("as") or \+ d["key"].lower().startswith("aut") or \+ d["key"].lower().startswith("descr") and \+ d["value"].lower() not in ["null", "none", "none specified"]:+ if d["key"] in ownerinfo:+ ownerinfo[d["key"]].append(d["value"])+ else:+ ownerinfo[d["key"]] = [d["value"]]++ self.sf.debug("Returning ownerinfo: " + str(ownerinfo))+ return ownerinfo++ # Netblocks owned by an AS+ def asNetblocks(self, asn):+ netblocks = list()++ res = self.fetchRir("https://stat.ripe.net/data/announced-prefixes/data.json?resource=AS" + asn)+ if res['content'] is None:+ self.sf.debug("No netblocks info found/available for AS" + asn + " at RIPE.")+ return None++ try:+ j = json.loads(res['content'])+ data = j["data"]["prefixes"]+ except Exception as e:+ self.sf.debug("Error processing JSON response.")+ return None++ for rec in data:+ netblocks.append(rec["prefix"])+ self.sf.info("Additional netblock found from same AS: " + rec["prefix"])++ return netblocks++ # Neighbours to an AS+ def asNeighbours(self, asn):+ neighbours = list()++ res = self.fetchRir("https://stat.ripe.net/data/asn-neighbours/data.json?resource=AS" + asn)+ if res['content'] is None:+ self.sf.debug("No neighbour info found/available for AS" + asn + " at RIPE.")+ return None++ try:+ j = json.loads(res['content'])+ data = j["data"]["neighbours"]+ except Exception as e:+ self.sf.debug("Error processing JSON response.")+ return None++ for rec in data:+ neighbours.append(str(rec['asn']))++ return neighbours++ # Determine whether there is a textual link between the target+ # and the string supplied.+ def findName(self, string):+ # Simplest check to perform..+ if self.getTarget().getValue() in string:+ return True++ if self.keywords is None:+ self.keywords = self.sf.domainKeywords(self.getTarget().getNames(),+ self.opts['_internettlds'])++ # Slightly more complex..+ rx = [+ '^{0}[-_/\'\"\\\.,\?\! ]',+ '[-_/\'\"\\\.,\?\! ]{0}$',+ '[-_/\'\"\\\.,\?\! ]{0}[-_/\'\"\\\.,\?\! ]'+ ]++ # Mess with the keyword as a last resort..+ keywordList = list()+ for kw in self.keywords:+ # Create versions of the keyword, esp. if hyphens are involved.+ keywordList.append(kw)+ keywordList.append(kw.replace('-', ' '))+ keywordList.append(kw.replace('-', '_'))+ keywordList.append(kw.replace('-', ''))++ for kw in keywordList:+ self.sf.debug("Looking for keyword: " + kw)+ for r in rx:+ if re.match(r.format(kw), string, re.IGNORECASE) is not None:+ return True++ return False++ # Owns the AS or not?+ def ownsAs(self, asn):+ # Determine whether the AS is owned by our target+ ownerinfo = self.asOwnerInfo(asn)+ owned = False++ if ownerinfo is not None:+ for k in ownerinfo.keys():+ items = ownerinfo[k]+ for item in items:+ if self.findName(item.lower()):+ owned = True+ return owned++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ self.currentEventSrc = event++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ # Don't look up stuff twice+ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + " as already mapped.")+ return None+ else:+ self.results[eventData] = True++ # BGP AS Owner/Member -> BGP AS Peers+ if eventName.startswith("BGP_AS_"):+ neighs = self.asNeighbours(eventData)+ if neighs is None:+ self.sf.debug("No neighbors found to AS " + eventData)+ return None++ for nasn in neighs:+ if self.checkForStop():+ return None++ ownerinfo = self.asOwnerInfo(nasn)+ ownertext = ''+ if ownerinfo is not None:+ for k, v in ownerinfo.iteritems():+ ownertext = ownertext + k + ": " + ', '.join(v) + "\n"++ if len(ownerinfo) > 0:+ evt = SpiderFootEvent("BGP_AS_PEER", nasn,+ self.__name__, event)+ self.notifyListeners(evt)++ # BGP AS Owner -> Other Netblocks+ if eventName == "BGP_AS_OWNER":+ # Don't report additional netblocks from this AS if we've+ # already found this AS before.+ if eventData not in self.nbreported:+ # Find all the netblocks owned by this AS+ self.nbreported[eventData] = True+ netblocks = self.asNetblocks(eventData)+ if netblocks is not None:+ for netblock in netblocks:+ if netblock in self.results:+ continue++ # Technically this netblock was identified via the AS, not+ # the original IP event, so link it to asevt, not event.+ evt = SpiderFootEvent("NETBLOCK_OWNER", netblock,+ self.__name__, event)+ self.notifyListeners(evt)+ return None++ # NETBLOCK -> AS and other owned netblocks+ if eventName.startswith("NETBLOCK_"):+ # Get the BGP AS the netblock is a part of+ asn = self.netblockAs(eventData)+ if asn is None:+ self.sf.debug("Could not identify BGP AS for " + eventData)+ return None++ if self.ownsAs(asn):+ asevt = SpiderFootEvent("BGP_AS_OWNER", asn, self.__name__, event)+ self.notifyListeners(asevt)+ else:+ asevt = SpiderFootEvent("BGP_AS_MEMBER", asn, self.__name__, event)+ self.notifyListeners(asevt)++ return None++ # IP ADDRESS -> NETBLOCK+ if eventName == "IP_ADDRESS":+ # Get the Netblock the IP is a part of+ prefix = self.ipNetblock(eventData)+ if prefix is None:+ self.sf.debug("Could not identify network prefix for " + eventData)+ return None++ # Get the BGP AS the netblock is a part of+ asn = self.netblockAs(prefix)+ if asn is None:+ self.sf.debug("Could not identify BGP AS for " + prefix)+ return None++ if self.ownsAs(asn):+ self.sf.info("Owned netblock found: " + prefix + "(" + asn + ")")+ evt = SpiderFootEvent("NETBLOCK_OWNER", prefix, self.__name__, event)+ self.notifyListeners(evt)+ else:+ self.sf.info("Netblock found: " + prefix + "(" + asn + ")")+ evt = SpiderFootEvent("NETBLOCK_MEMBER", prefix, self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_ripe classdiff --git a/modules/sfp_robtex.py b/modules/sfp_robtex.pyindex 27277759..24c01080 100644--- a/modules/sfp_robtex.py+++ b/modules/sfp_robtex.py@@ -1,140 +1,141 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_robtex-# Purpose: Searches Robtex.com for hosts sharing the same IP.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 12/04/2014-# Copyright: (c) Steve Micallef 2014-# Licence: GPL-# ---------------------------------------------------------------------------------import re-import socket-import json-from netaddr import IPNetwork-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_robtex(SpiderFootPlugin):- """Robtex:Footprint,Investigate,Passive:Networking:errorprone:Search Robtex.com for hosts sharing the same IP."""-- # Default options- opts = {- 'cohostsamedomain': False,- 'verify': True,- 'api_key': ""- }-- # Option descriptions- optdescs = {- 'cohostsamedomain': "Treat co-hosted sites on the same target domain as co-hosting?",- 'verify': "Verify co-hosts are valid by checking if they still resolve to the shared IP.",- 'api_key': "Robtex.com requires an API key, obtained from the Mashape.com marketplace."- }-- results = list()- errorState = False-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["IP_ADDRESS", "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 ["CO_HOSTED_SITE"]-- def validateIP(self, host, ip):- try:- addrs = socket.gethostbyname_ex(host)- except BaseException as e:- self.sf.debug("Unable to resolve " + host + ": " + str(e))- return False-- for addr in addrs:- if type(addr) == list:- for a in addr:- if str(a) == ip:- return True- else:- if str(addr) == ip:- return True- return False-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- self.currentEventSrc = event-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- if self.errorState:- return None-- if self.opts['api_key'] == "":- self.sf.error("You enabled sfp_robtex but did not set an API key!", False)- self.errorState = True- return None-- # Don't look up stuff twice- if eventData in self.results:- self.sf.debug("Skipping " + eventData + " as already mapped.")- return None-- qrylist = list()- if eventName.startswith("NETBLOCK_"):- for ipaddr in IPNetwork(eventData):- if str(ipaddr) not in self.results:- qrylist.append(str(ipaddr))- self.results.append(str(ipaddr))- else:- qrylist.append(eventData)- self.results.append(eventData)-- myres = list()-- for ip in qrylist:- if self.checkForStop():- return None-- res = self.sf.fetchUrl("https://robtex.p.mashape.com/reverse/?q=" + ip + "&m=100",- useragent=self.opts['_useragent'],- timeout=self.opts['_fetchtimeout'],- headers={- 'X-Mashape-Key': self.opts['api_key'],- 'Accept': 'application/json'}- )- if res['content'] is None:- self.sf.error("Unable to fetch robtex content.", False)- continue-- try:- data = json.loads(res['content'])- except BaseException as e:- self.sf.error("Error parsing JSON from robtex API.", False)- # Abort so that we don't use up API credits in case this is an error- # on our side.- self.errorState = True- return None-- if len(data.get('l')) > 0:- for r in data.get('l'):- if self.opts['verify'] and not self.validateIP(r['o'], ip):- self.sf.debug("Host no longer resolves to our IP.")- continue- evt = SpiderFootEvent("CO_HOSTED_SITE", r['o'], self.__name__, event)- self.notifyListeners(evt)--# End of sfp_robtex class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_robtex+# Purpose: Searches Robtex.com for hosts sharing the same IP.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 12/04/2014+# Copyright: (c) Steve Micallef 2014+# Licence: GPL+# -------------------------------------------------------------------------------++import re+import socket+import json+from netaddr import IPNetwork+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_robtex(SpiderFootPlugin):+ """Robtex:Footprint,Investigate,Passive:DNS:errorprone:Search Robtex.com for hosts sharing the same IP."""+++ # Default options+ opts = {+ 'cohostsamedomain': False,+ 'verify': True,+ 'api_key': ""+ }++ # Option descriptions+ optdescs = {+ 'cohostsamedomain': "Treat co-hosted sites on the same target domain as co-hosting?",+ 'verify': "Verify co-hosts are valid by checking if they still resolve to the shared IP.",+ 'api_key': "Robtex.com requires an API key, obtained from the Mashape.com marketplace."+ }++ results = list()+ errorState = False++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["IP_ADDRESS", "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 ["CO_HOSTED_SITE"]++ def validateIP(self, host, ip):+ try:+ addrs = socket.gethostbyname_ex(host)+ except BaseException as e:+ self.sf.debug("Unable to resolve " + host + ": " + str(e))+ return False++ for addr in addrs:+ if type(addr) == list:+ for a in addr:+ if str(a) == ip:+ return True+ else:+ if str(addr) == ip:+ return True+ return False++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ self.currentEventSrc = event++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if self.errorState:+ return None++ if self.opts['api_key'] == "":+ self.sf.error("You enabled sfp_robtex but did not set an API key!", False)+ self.errorState = True+ return None++ # Don't look up stuff twice+ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + " as already mapped.")+ return None++ qrylist = list()+ if eventName.startswith("NETBLOCK_"):+ for ipaddr in IPNetwork(eventData):+ if str(ipaddr) not in self.results:+ qrylist.append(str(ipaddr))+ self.results.append(str(ipaddr))+ else:+ qrylist.append(eventData)+ self.results.append(eventData)++ myres = list()++ for ip in qrylist:+ if self.checkForStop():+ return None++ res = self.sf.fetchUrl("https://robtex.p.mashape.com/reverse/?q=" + ip + "&m=100",+ useragent=self.opts['_useragent'],+ timeout=self.opts['_fetchtimeout'],+ headers={+ 'X-Mashape-Key': self.opts['api_key'],+ 'Accept': 'application/json'}+ )+ if res['content'] is None:+ self.sf.error("Unable to fetch robtex content.", False)+ continue++ try:+ data = json.loads(res['content'])+ except BaseException as e:+ self.sf.error("Error parsing JSON from robtex API.", False)+ # Abort so that we don't use up API credits in case this is an error+ # on our side.+ self.errorState = True+ return None++ if len(data.get('l')) > 0:+ for r in data.get('l'):+ if self.opts['verify'] and not self.validateIP(r['o'], ip):+ self.sf.debug("Host no longer resolves to our IP.")+ continue+ evt = SpiderFootEvent("CO_HOSTED_SITE", r['o'], self.__name__, event)+ self.notifyListeners(evt)++# End of sfp_robtex classdiff --git a/modules/sfp_s3bucket.py b/modules/sfp_s3bucket.pyindex cde15bbb..c101e57a 100644--- a/modules/sfp_s3bucket.py+++ b/modules/sfp_s3bucket.py@@ -1,92 +1,93 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_s3bucket-# Purpose: SpiderFoot plug-in for identifying potential S3 buckets related to-# the target.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 24/07/2016-# Copyright: (c) Steve Micallef 2016-# Licence: GPL-# ---------------------------------------------------------------------------------#-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_s3bucket(SpiderFootPlugin):- """S3 Bucket Finder:Footprint,Passive:Networking::Search for potential S3 buckets associated with the target."""-- # Default options- opts = {- "endpoints": "s3.amazonaws.com,s3-external-1.amazonaws.com,s3-us-west-1.amazonaws.com,s3-us-west-2.amazonaws.com,s3.ap-south-1.amazonaws.com,s3-ap-south-1.amazonaws.com,s3.ap-northeast-2.amazonaws.com,s3-ap-northeast-2.amazonaws.com,s3-ap-southeast-1.amazonaws.com,s3-ap-southeast-2.amazonaws.com,s3-ap-northeast-1.amazonaws.com,s3.eu-central-1.amazonaws.com,s3-eu-central-1.amazonaws.com,s3-eu-west-1.amazonaws.com,s3-sa-east-1.amazonaws.com",- "suffixes": "test,dev,web,beta,bucket,-test,-dev,-web,-beta,-bucket"- }-- # Option descriptions- optdescs = {- "endpoints": "Different S3 endpoints to check where buckets may exist, as per http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region",- "suffixes": "List of suffixes to append to domains tried as bucket names"- }-- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc-- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["DOMAIN_NAME", "LINKED_URL_EXTERNAL"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["AMAZON_S3_BUCKET"]-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if eventData in self.results:- return None- else:- self.results.append(eventData)-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- if eventName == "LINKED_URL_EXTERNAL":- if ".amazonaws.com" in eventData:- b = self.sf.urlFQDN(eventData)- evt = SpiderFootEvent("AMAZON_S3_BUCKET", b, self.__name__, event)- self.notifyListeners(evt)- return None-- targets = [ eventData.replace('.', ''), self.sf.domainKeyword(eventData, self.opts['_internettlds']) ]- for t in targets:- for e in self.opts['endpoints'].split(','):- suffixes = [''] + self.opts['suffixes'].split(',')- for s in suffixes:- if self.checkForStop():- return None-- b = t + s + "." + e- url = "https://" + b- res = self.sf.fetchUrl(url, timeout=10, useragent="SpiderFoot")-- if res['content'] is None or "NoSuchBucket" in res['content']:- self.sf.debug("Not a valid bucket: " + url)- continue-- evt = SpiderFootEvent("AMAZON_S3_BUCKET", b, self.__name__, event)- self.notifyListeners(evt)--# End of sfp_s3bucket class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_s3bucket+# Purpose: SpiderFoot plug-in for identifying potential S3 buckets related to+# the target.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 24/07/2016+# Copyright: (c) Steve Micallef 2016+# Licence: GPL+# -------------------------------------------------------------------------------++#+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_s3bucket(SpiderFootPlugin):+ """S3 Bucket Finder:Footprint,Passive:Crawling and Scanning::Search for potential S3 buckets associated with the target."""+++ # Default options+ opts = {+ "endpoints": "s3.amazonaws.com,s3-external-1.amazonaws.com,s3-us-west-1.amazonaws.com,s3-us-west-2.amazonaws.com,s3.ap-south-1.amazonaws.com,s3-ap-south-1.amazonaws.com,s3.ap-northeast-2.amazonaws.com,s3-ap-northeast-2.amazonaws.com,s3-ap-southeast-1.amazonaws.com,s3-ap-southeast-2.amazonaws.com,s3-ap-northeast-1.amazonaws.com,s3.eu-central-1.amazonaws.com,s3-eu-central-1.amazonaws.com,s3-eu-west-1.amazonaws.com,s3-sa-east-1.amazonaws.com",+ "suffixes": "test,dev,web,beta,bucket,-test,-dev,-web,-beta,-bucket"+ }++ # Option descriptions+ optdescs = {+ "endpoints": "Different S3 endpoints to check where buckets may exist, as per http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region",+ "suffixes": "List of suffixes to append to domains tried as bucket names"+ }++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc++ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["DOMAIN_NAME", "LINKED_URL_EXTERNAL"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["AMAZON_S3_BUCKET"]++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if eventData in self.results:+ return None+ else:+ self.results.append(eventData)++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventName == "LINKED_URL_EXTERNAL":+ if ".amazonaws.com" in eventData:+ b = self.sf.urlFQDN(eventData)+ evt = SpiderFootEvent("AMAZON_S3_BUCKET", b, self.__name__, event)+ self.notifyListeners(evt)+ return None++ targets = [ eventData.replace('.', ''), self.sf.domainKeyword(eventData, self.opts['_internettlds']) ]+ for t in targets:+ for e in self.opts['endpoints'].split(','):+ suffixes = [''] + self.opts['suffixes'].split(',')+ for s in suffixes:+ if self.checkForStop():+ return None++ b = t + s + "." + e+ url = "https://" + b+ res = self.sf.fetchUrl(url, timeout=10, useragent="SpiderFoot")++ if res['content'] is None or "NoSuchBucket" in res['content']:+ self.sf.debug("Not a valid bucket: " + url)+ continue++ evt = SpiderFootEvent("AMAZON_S3_BUCKET", b, self.__name__, event)+ self.notifyListeners(evt)++# End of sfp_s3bucket classdiff --git a/modules/sfp_shodan.py b/modules/sfp_shodan.pyindex b2c36491..090657a2 100644--- a/modules/sfp_shodan.py+++ b/modules/sfp_shodan.py@@ -1,152 +1,153 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_shodan-# Purpose: Query SHODAN for identified IP addresses.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 19/03/2014-# Copyright: (c) Steve Micallef-# Licence: GPL-# ---------------------------------------------------------------------------------import json-from netaddr import IPNetwork-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_shodan(SpiderFootPlugin):- """SHODAN:Footprint,Investigate,Passive:Search Engines:apikey:Obtain information from SHODAN about identified IP addresses."""-- # Default options- opts = {- "api_key": "",- 'netblocklookup': True,- 'maxnetblock': 24- }-- # Option descriptions- optdescs = {- "api_key": "Your SHODAN API Key.",- 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible hosts on the same target subdomain/domain?",- 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"- }-- results = dict()- errorState = False-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- # 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- def watchedEvents(self):- return ["IP_ADDRESS", "NETBLOCK_OWNER"]-- # What events this module produces- def producedEvents(self):- return ["OPERATING_SYSTEM", "DEVICE_TYPE",- "TCP_PORT_OPEN", "TCP_PORT_OPEN_BANNER"]-- def query(self, qry):- res = self.sf.fetchUrl("https://api.shodan.io/shodan/host/" + qry +- "?key=" + self.opts['api_key'],- timeout=self.opts['_fetchtimeout'], useragent="SpiderFoot")- if res['content'] is None:- self.sf.info("No SHODAN info found for " + qry)- return None-- try:- info = json.loads(res['content'])- except Exception as e:- self.sf.error("Error processing JSON response from SHODAN.", False)- return None-- return info-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if self.errorState:- return None-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- if self.opts['api_key'] == "":- self.sf.error("You enabled sfp_shodan but did not set an API key!", False)- self.errorState = True- return None-- # Don't look up stuff twice- if eventData in self.results:- self.sf.debug("Skipping " + eventData + " as already mapped.")- return None- else:- self.results[eventData] = True-- if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:- if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:- self.sf.debug("Network size bigger than permitted: " +- str(IPNetwork(eventData).prefixlen) + " > " +- str(self.opts['maxnetblock']))- return None-- qrylist = list()- if eventName.startswith("NETBLOCK_"):- for ipaddr in IPNetwork(eventData):- qrylist.append(str(ipaddr))- self.results[str(ipaddr)] = True- else:- qrylist.append(eventData)-- for addr in qrylist:- rec = self.query(addr)- if rec is None:- continue-- if self.checkForStop():- return None-- if rec.get('os') is not None:- # Notify other modules of what you've found- evt = SpiderFootEvent("OPERATING_SYSTEM", rec.get('os') +- " (" + addr + ")", self.__name__, event)- self.notifyListeners(evt)-- if rec.get('devtype') is not None:- # Notify other modules of what you've found- evt = SpiderFootEvent("DEVICE_TYPE", rec.get('devtype') +- " (" + addr + ")", self.__name__, event)- self.notifyListeners(evt)-- if 'data' in rec:- self.sf.info("Found SHODAN data for " + eventData)- for r in rec['data']:- port = str(r.get('port'))- banner = r.get('banner')-- if port is not None:- # Notify other modules of what you've found- cp = addr + ":" + port- evt = SpiderFootEvent("TCP_PORT_OPEN", cp,- self.__name__, event)- self.notifyListeners(evt)-- if banner is not None:- # Notify other modules of what you've found- evt = SpiderFootEvent("TCP_PORT_OPEN_BANNER", banner,- self.__name__, event)- self.notifyListeners(evt)-- return None--# End of sfp_shodan class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_shodan+# Purpose: Query SHODAN for identified IP addresses.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 19/03/2014+# Copyright: (c) Steve Micallef+# Licence: GPL+# -------------------------------------------------------------------------------++import json+from netaddr import IPNetwork+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_shodan(SpiderFootPlugin):+ """SHODAN:Footprint,Investigate,Passive:Search Engines:apikey:Obtain information from SHODAN about identified IP addresses."""+++ # Default options+ opts = {+ "api_key": "",+ 'netblocklookup': True,+ 'maxnetblock': 24+ }++ # Option descriptions+ optdescs = {+ "api_key": "Your SHODAN API Key.",+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible hosts on the same target subdomain/domain?",+ 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"+ }++ results = dict()+ errorState = False++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ # 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+ def watchedEvents(self):+ return ["IP_ADDRESS", "NETBLOCK_OWNER"]++ # What events this module produces+ def producedEvents(self):+ return ["OPERATING_SYSTEM", "DEVICE_TYPE",+ "TCP_PORT_OPEN", "TCP_PORT_OPEN_BANNER"]++ def query(self, qry):+ res = self.sf.fetchUrl("https://api.shodan.io/shodan/host/" + qry ++ "?key=" + self.opts['api_key'],+ timeout=self.opts['_fetchtimeout'], useragent="SpiderFoot")+ if res['content'] is None:+ self.sf.info("No SHODAN info found for " + qry)+ return None++ try:+ info = json.loads(res['content'])+ except Exception as e:+ self.sf.error("Error processing JSON response from SHODAN.", False)+ return None++ return info++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if self.errorState:+ return None++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if self.opts['api_key'] == "":+ self.sf.error("You enabled sfp_shodan but did not set an API key!", False)+ self.errorState = True+ return None++ # Don't look up stuff twice+ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + " as already mapped.")+ return None+ else:+ self.results[eventData] = True++ if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:+ if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:+ self.sf.debug("Network size bigger than permitted: " ++ str(IPNetwork(eventData).prefixlen) + " > " ++ str(self.opts['maxnetblock']))+ return None++ qrylist = list()+ if eventName.startswith("NETBLOCK_"):+ for ipaddr in IPNetwork(eventData):+ qrylist.append(str(ipaddr))+ self.results[str(ipaddr)] = True+ else:+ qrylist.append(eventData)++ for addr in qrylist:+ rec = self.query(addr)+ if rec is None:+ continue++ if self.checkForStop():+ return None++ if rec.get('os') is not None:+ # Notify other modules of what you've found+ evt = SpiderFootEvent("OPERATING_SYSTEM", rec.get('os') ++ " (" + addr + ")", self.__name__, event)+ self.notifyListeners(evt)++ if rec.get('devtype') is not None:+ # Notify other modules of what you've found+ evt = SpiderFootEvent("DEVICE_TYPE", rec.get('devtype') ++ " (" + addr + ")", self.__name__, event)+ self.notifyListeners(evt)++ if 'data' in rec:+ self.sf.info("Found SHODAN data for " + eventData)+ for r in rec['data']:+ port = str(r.get('port'))+ banner = r.get('banner')++ if port is not None:+ # Notify other modules of what you've found+ cp = addr + ":" + port+ evt = SpiderFootEvent("TCP_PORT_OPEN", cp,+ self.__name__, event)+ self.notifyListeners(evt)++ if banner is not None:+ # Notify other modules of what you've found+ evt = SpiderFootEvent("TCP_PORT_OPEN_BANNER", banner,+ self.__name__, event)+ self.notifyListeners(evt)++ return None++# End of sfp_shodan classdiff --git a/modules/sfp_similar.py b/modules/sfp_similar.pyindex 49486736..9a778a9d 100644--- a/modules/sfp_similar.py+++ b/modules/sfp_similar.py@@ -1,158 +1,159 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_similar-# Purpose: SpiderFoot plug-in for identifying domains that look similar-# to the one being queried.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 26/11/2016-# Copyright: (c) Steve Micallef 2012-# Licence: GPL-# ---------------------------------------------------------------------------------import re-import socket-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent--nearchars = {- 'a': [ '4', 's' ],- 'b': [ 'v', 'n' ],- 'c': [ 'x', 'v' ],- 'd': [ 's', 'f' ],- 'e': [ 'w', 'r' ],- 'f': [ 'd', 'g' ],- 'g': [ 'f', 'h' ],- 'h': [ 'g', 'j', 'n' ],- 'i': [ 'o', 'u', '1' ],- 'j': [ 'k', 'h' ,'i' ],- 'k': [ 'l' ,'j' ],- 'l': [ 'i', '1', 'k' ],- 'm': [ 'n' ],- 'n': [ 'm' ],- 'o': [ 'p', 'i', '0' ],- 'p': [ 'o', 'q' ],- 'r': [ 't', 'e' ],- 's': [ 'a', 'd', '5' ],- 't': [ '7', 'y', 'z', 'r' ],- 'u': [ 'v', 'i', 'y', 'z' ],- 'v': [ 'u', 'c', 'b' ],- 'w': [ 'v', 'vv', 'q', 'e' ],- 'x': [ 'z', 'y', 'c' ],- 'y': [ 'z', 'x' ],- 'z': [ 'y', 'x' ],- '0': [ 'o' ],- '1': [ 'l' ],- '2': [ '5' ],- '3': [ 'e' ],- '4': [ 'a' ],- '5': [ 's' ],- '6': [ 'b' ],- '7': [ 't' ],- '8': [ 'b' ],- '9': []-}--pairs = {- 'oo': [ '00' ],- 'll': [ 'l1l', 'l1l', '111', '11' ],- '11': [ 'll', 'lll', 'l1l', '1l1' ]-}--# These are all string builders, {0} = the domain keyword, {1} = the page number-class sfp_similar(SpiderFootPlugin):- """Similar Domains:Footprint,Investigate:Networking::Search various sources to identify similar looking domain names, for instance squatted domains."""-- # Default options- opts = {- }-- # Option descriptions- optdescs = {- }-- # Internal results tracking- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["DOMAIN_NAME", "INTERNET_NAME"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["SIMILARDOMAIN"]-- # Search for similar sounding domains- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- domlist = list()-- dom = self.sf.domainKeyword(eventData, self.opts['_internettlds'])- tld = "." + eventData.split(dom + ".")[-1]- self.sf.debug("Keyword extracted from " + eventData + ": " + dom)-- if dom in self.results:- return None- else:- self.results.append(dom)-- # Search for typos- pos = 0- for c in dom:- if c not in nearchars:- continue- if len(nearchars[c]) == 0:- continue- npos = pos + 1- for xc in nearchars[c]:- newdom = dom[0:pos] + xc + dom[npos:len(dom)]- domlist.append(newdom)-- pos += 1-- # Search for common double-letter re- for p in pairs:- if p in dom:- for r in pairs[p]:- domlist.append(dom.replace(p, r))-- # Search for prefixed and suffixed domains- for c in nearchars:- domlist.append(dom + c)- domlist.append(c + dom)-- # Search for double character domains- pos = 0- for c in dom:- domlist.append(dom[0:pos] + c + c + dom[(pos+1):len(dom)])- pos += 1-- for d in domlist:- resolved = False- try:- if len(self.sf.normalizeDNS(socket.gethostbyname_ex(d + tld))) > 0:- resolved = True- if len(self.sf.normalizeDNS(socket.gethostbyname_ex("www." + d + tld))) > 0:- resolved = True-- if resolved:- self.sf.debug("Resolved " + d + tld)- evt = SpiderFootEvent("SIMILARDOMAIN", d + tld, self.__name__, event)- self.notifyListeners(evt)- except BaseException as e:- continue-- return None--# End of sfp_similar class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_similar+# Purpose: SpiderFoot plug-in for identifying domains that look similar+# to the one being queried.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 26/11/2016+# Copyright: (c) Steve Micallef 2012+# Licence: GPL+# -------------------------------------------------------------------------------++import re+import socket+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++nearchars = {+ 'a': [ '4', 's' ],+ 'b': [ 'v', 'n' ],+ 'c': [ 'x', 'v' ],+ 'd': [ 's', 'f' ],+ 'e': [ 'w', 'r' ],+ 'f': [ 'd', 'g' ],+ 'g': [ 'f', 'h' ],+ 'h': [ 'g', 'j', 'n' ],+ 'i': [ 'o', 'u', '1' ],+ 'j': [ 'k', 'h' ,'i' ],+ 'k': [ 'l' ,'j' ],+ 'l': [ 'i', '1', 'k' ],+ 'm': [ 'n' ],+ 'n': [ 'm' ],+ 'o': [ 'p', 'i', '0' ],+ 'p': [ 'o', 'q' ],+ 'r': [ 't', 'e' ],+ 's': [ 'a', 'd', '5' ],+ 't': [ '7', 'y', 'z', 'r' ],+ 'u': [ 'v', 'i', 'y', 'z' ],+ 'v': [ 'u', 'c', 'b' ],+ 'w': [ 'v', 'vv', 'q', 'e' ],+ 'x': [ 'z', 'y', 'c' ],+ 'y': [ 'z', 'x' ],+ 'z': [ 'y', 'x' ],+ '0': [ 'o' ],+ '1': [ 'l' ],+ '2': [ '5' ],+ '3': [ 'e' ],+ '4': [ 'a' ],+ '5': [ 's' ],+ '6': [ 'b' ],+ '7': [ 't' ],+ '8': [ 'b' ],+ '9': []+}++pairs = {+ 'oo': [ '00' ],+ 'll': [ 'l1l', 'l1l', '111', '11' ],+ '11': [ 'll', 'lll', 'l1l', '1l1' ]+}++# These are all string builders, {0} = the domain keyword, {1} = the page number+class sfp_similar(SpiderFootPlugin):+ """Similar Domains:Footprint,Investigate:DNS::Search various sources to identify similar looking domain names, for instance squatted domains."""+++ # Default options+ opts = {+ }++ # Option descriptions+ optdescs = {+ }++ # Internal results tracking+ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["DOMAIN_NAME", "INTERNET_NAME"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["SIMILARDOMAIN"]++ # Search for similar sounding domains+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ domlist = list()++ dom = self.sf.domainKeyword(eventData, self.opts['_internettlds'])+ tld = "." + eventData.split(dom + ".")[-1]+ self.sf.debug("Keyword extracted from " + eventData + ": " + dom)++ if dom in self.results:+ return None+ else:+ self.results.append(dom)++ # Search for typos+ pos = 0+ for c in dom:+ if c not in nearchars:+ continue+ if len(nearchars[c]) == 0:+ continue+ npos = pos + 1+ for xc in nearchars[c]:+ newdom = dom[0:pos] + xc + dom[npos:len(dom)]+ domlist.append(newdom)++ pos += 1++ # Search for common double-letter re+ for p in pairs:+ if p in dom:+ for r in pairs[p]:+ domlist.append(dom.replace(p, r))++ # Search for prefixed and suffixed domains+ for c in nearchars:+ domlist.append(dom + c)+ domlist.append(c + dom)++ # Search for double character domains+ pos = 0+ for c in dom:+ domlist.append(dom[0:pos] + c + c + dom[(pos+1):len(dom)])+ pos += 1++ for d in domlist:+ resolved = False+ try:+ if len(self.sf.normalizeDNS(socket.gethostbyname_ex(d + tld))) > 0:+ resolved = True+ if len(self.sf.normalizeDNS(socket.gethostbyname_ex("www." + d + tld))) > 0:+ resolved = True++ if resolved:+ self.sf.debug("Resolved " + d + tld)+ evt = SpiderFootEvent("SIMILARDOMAIN", d + tld, self.__name__, event)+ self.notifyListeners(evt)+ except BaseException as e:+ continue++ return None++# End of sfp_similar classdiff --git a/modules/sfp_social.py b/modules/sfp_social.pyindex f3f76099..23d11848 100644--- a/modules/sfp_social.py+++ b/modules/sfp_social.py@@ -1,92 +1,93 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_social`-# Purpose: Identify the usage of popular social networks-#-# Author: Steve Micallef <[email protected]>-#-# Created: 26/05/2013-# Copyright: (c) Steve Micallef 2013-# Licence: GPL-# ---------------------------------------------------------------------------------import re-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent--regexps = dict({- "LinkedIn (Individual)": list(['.*linkedin.com/in/([a-zA-Z0-9_]+$)']),- "LinkedIn (Company)": list(['.*linkedin.com/company/([a-zA-Z0-9_]+$)']),- "Github": list(['.*github.com/([a-zA-Z0-9_]+)\/']),- "Google+": list(['.*plus.google.com/([0-9]+$)']),- "Facebook": list(['.*facebook.com/([a-zA-Z0-9_]+$)']),- "YouTube": list(['.*youtube.com/([a-zA-Z0-9_]+$)']),- "Twitter": list(['.*twitter.com/([a-zA-Z0-9_]{1,15}$)',- '.*twitter.com/#!/([a-zA-Z0-9_]{1,15}$)'- ]),- "SlideShare": list(['.*slideshare.net/([a-zA-Z0-9_]+$)'])-})---class sfp_social(SpiderFootPlugin):- """Social Networks:Footprint:Social::Identify presence on social media networks such as LinkedIn, Twitter and others."""-- # Default options- opts = {}-- # Option descriptions- optdescs = {- # For each option in opts you should have a key/value pair here- # describing it. It will end up in the UI to explain the option- # to the end-user.- }-- results = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- 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 ["LINKED_URL_EXTERNAL"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["SOCIAL_MEDIA"]-- # 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 not in self.results.keys():- self.results[eventData] = True- else:- return None-- for regexpGrp in regexps.keys():- for regex in regexps[regexpGrp]:- bits = re.match(regex, eventData, re.IGNORECASE)- if bits is not None:- self.sf.info("Matched " + regexpGrp + " in " + eventData)- evt = SpiderFootEvent("SOCIAL_MEDIA", regexpGrp + ": " +- bits.group(1), self.__name__, event)- self.notifyListeners(evt)-- return None-- # If you intend for this module to act on its own (e.g. not solely rely- # on events from other modules, then you need to have a start() method- # and within that method call self.checkForStop() to see if you've been- # politely asked by the controller to stop your activities (user abort.)--# End of sfp_social class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_social`+# Purpose: Identify the usage of popular social networks+#+# Author: Steve Micallef <[email protected]>+#+# Created: 26/05/2013+# Copyright: (c) Steve Micallef 2013+# Licence: GPL+# -------------------------------------------------------------------------------++import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++regexps = dict({+ "LinkedIn (Individual)": list(['.*linkedin.com/in/([a-zA-Z0-9_]+$)']),+ "LinkedIn (Company)": list(['.*linkedin.com/company/([a-zA-Z0-9_]+$)']),+ "Github": list(['.*github.com/([a-zA-Z0-9_]+)\/']),+ "Google+": list(['.*plus.google.com/([0-9]+$)']),+ "Facebook": list(['.*facebook.com/([a-zA-Z0-9_]+$)']),+ "YouTube": list(['.*youtube.com/([a-zA-Z0-9_]+$)']),+ "Twitter": list(['.*twitter.com/([a-zA-Z0-9_]{1,15}$)',+ '.*twitter.com/#!/([a-zA-Z0-9_]{1,15}$)'+ ]),+ "SlideShare": list(['.*slideshare.net/([a-zA-Z0-9_]+$)'])+})+++class sfp_social(SpiderFootPlugin):+ """Social Networks:Footprint:Social Media::Identify presence on social media networks such as LinkedIn, Twitter and others."""+++ # Default options+ opts = {}++ # Option descriptions+ optdescs = {+ # For each option in opts you should have a key/value pair here+ # describing it. It will end up in the UI to explain the option+ # to the end-user.+ }++ results = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ 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 ["LINKED_URL_EXTERNAL"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["SOCIAL_MEDIA"]++ # 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 not in self.results.keys():+ self.results[eventData] = True+ else:+ return None++ for regexpGrp in regexps.keys():+ for regex in regexps[regexpGrp]:+ bits = re.match(regex, eventData, re.IGNORECASE)+ if bits is not None:+ self.sf.info("Matched " + regexpGrp + " in " + eventData)+ evt = SpiderFootEvent("SOCIAL_MEDIA", regexpGrp + ": " ++ bits.group(1), self.__name__, event)+ self.notifyListeners(evt)++ return None++ # If you intend for this module to act on its own (e.g. not solely rely+ # on events from other modules, then you need to have a start() method+ # and within that method call self.checkForStop() to see if you've been+ # politely asked by the controller to stop your activities (user abort.)++# End of sfp_social classdiff --git a/modules/sfp_socialprofiles.py b/modules/sfp_socialprofiles.pyindex 2f489b44..15823a14 100644--- a/modules/sfp_socialprofiles.py+++ b/modules/sfp_socialprofiles.py@@ -1,170 +1,171 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_socialprofiles-# Purpose: Obtains social media profiles of any identified human names.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 12/04/2014-# Copyright: (c) Steve Micallef 2014-# Licence: GPL-# ---------------------------------------------------------------------------------import random-import re-import time-import urllib-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent--sites = {- # Search string to use, domain name the profile will sit on within- # those search results.- "Facebook": ['+intitle:%22{0}%22%20+site:facebook.com',- '"(https?://[a-z\.]*facebook.[a-z\.]+/[^\"<> ]+)"'],- "Google+": ['+intitle:%22{0}%22%20+site:plus.google.com',- '"(https?://plus.google.[a-z\.]+/\d+[^\"<>\/ ]+)"'],- "LinkedIn": ['+intitle:%22{0}%22%20+site:linkedin.com',- '"(https?://[a-z\.]*linkedin.[a-z\.]+/[^\"<> ]+)"']-}---class sfp_socialprofiles(SpiderFootPlugin):- """Social Media Profiles:Footprint,Passive:Social:errorprone:Identify the social media profiles for human names identified."""-- # Default options- opts = {- 'pages': 1,- 'method': "yahoo",- 'tighten': True- }-- # Option descriptions- optdescs = {- 'pages': "Number of search engine pages of identified profiles to iterate through.",- 'tighten': "Tighten results by expecting to find the keyword of the target domain mentioned in the social media profile page results?",- 'method': "Search engine to use: google, yahoo or bing."- }-- keywords = None- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["HUMAN_NAME"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["SOCIAL_MEDIA", "SEARCH_ENGINE_WEB_CONTENT"]-- def yahooCleaner(self, string):- ret = "\"" + urllib.unquote(string.group(1)) + "\""- return ret-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- self.currentEventSrc = event-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- # Don't look up stuff twice- if eventData in self.results:- self.sf.debug("Skipping " + eventData + " as already mapped.")- return None- else:- self.results.append(eventData)-- if self.keywords is None:- self.keywords = self.sf.domainKeywords(self.getTarget().getNames(),- self.opts['_internettlds'])-- for site in sites.keys():- s = unicode(sites[site][0]).format(eventData)- searchStr = s.replace(" ", "%20")- searchDom = sites[site][1]-- if self.opts['method'].lower() == "google":- results = self.sf.googleIterate(searchStr, dict(limit=self.opts['pages'],- useragent=self.opts['_useragent'],- timeout=self.opts['_fetchtimeout']))-- if self.opts['method'].lower() == "yahoo":- results = self.sf.yahooIterate(searchStr, dict(limit=self.opts['pages'],- useragent=self.opts['_useragent'],- timeout=self.opts['_fetchtimeout']))-- if self.opts['method'].lower() == "bing":- results = self.sf.bingIterate(searchStr, dict(limit=self.opts['pages'],- useragent=self.opts['_useragent'],- timeout=self.opts['_fetchtimeout']))-- if results is None:- self.sf.info("No data returned from " + self.opts['method'] + ".")- return None-- if self.checkForStop():- return None-- pauseSecs = random.randint(4, 15)- self.sf.debug("Pausing for " + str(pauseSecs))- time.sleep(pauseSecs)-- for key in results.keys():- instances = list()- # Yahoo requires some additional parsing- if self.opts['method'].lower() == "yahoo":- res = re.sub("RU=(.[^\/]+)\/RK=", self.yahooCleaner,- results[key], 0)- else:- res = results[key]-- matches = re.findall(searchDom, res, re.IGNORECASE)-- if matches is not None:- for match in matches:- if match in instances:- continue- else:- instances.append(match)-- if self.checkForStop():- return None-- # Fetch the profile page if we are checking- # for a firm relationship.- if self.opts['tighten']:- pres = self.sf.fetchUrl(match, timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])-- if pres['content'] is None:- continue- else:- found = False- for kw in self.keywords:- if re.search("[^a-zA-Z\-\_]" + kw + "[^a-zA-Z\-\_]", pres['content'], re.IGNORECASE):- found = True- if not found:- continue-- self.sf.info("Social Media Profile found at " + site + ": " + match)- evt = SpiderFootEvent("SOCIAL_MEDIA", site + ": " + match,- self.__name__, event)- self.notifyListeners(evt)-- # Submit the bing results for analysis- evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", res,- self.__name__, event)- self.notifyListeners(evt)--# End of sfp_socialprofiles class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_socialprofiles+# Purpose: Obtains social media profiles of any identified human names.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 12/04/2014+# Copyright: (c) Steve Micallef 2014+# Licence: GPL+# -------------------------------------------------------------------------------++import random+import re+import time+import urllib+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++sites = {+ # Search string to use, domain name the profile will sit on within+ # those search results.+ "Facebook": ['+intitle:%22{0}%22%20+site:facebook.com',+ '"(https?://[a-z\.]*facebook.[a-z\.]+/[^\"<> ]+)"'],+ "Google+": ['+intitle:%22{0}%22%20+site:plus.google.com',+ '"(https?://plus.google.[a-z\.]+/\d+[^\"<>\/ ]+)"'],+ "LinkedIn": ['+intitle:%22{0}%22%20+site:linkedin.com',+ '"(https?://[a-z\.]*linkedin.[a-z\.]+/[^\"<> ]+)"']+}+++class sfp_socialprofiles(SpiderFootPlugin):+ """Social Media Profiles:Footprint,Passive:Social Media:errorprone:Identify the social media profiles for human names identified."""+++ # Default options+ opts = {+ 'pages': 1,+ 'method': "yahoo",+ 'tighten': True+ }++ # Option descriptions+ optdescs = {+ 'pages': "Number of search engine pages of identified profiles to iterate through.",+ 'tighten': "Tighten results by expecting to find the keyword of the target domain mentioned in the social media profile page results?",+ 'method': "Search engine to use: google, yahoo or bing."+ }++ keywords = None+ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["HUMAN_NAME"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["SOCIAL_MEDIA", "SEARCH_ENGINE_WEB_CONTENT"]++ def yahooCleaner(self, string):+ ret = "\"" + urllib.unquote(string.group(1)) + "\""+ return ret++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ self.currentEventSrc = event++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ # Don't look up stuff twice+ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + " as already mapped.")+ return None+ else:+ self.results.append(eventData)++ if self.keywords is None:+ self.keywords = self.sf.domainKeywords(self.getTarget().getNames(),+ self.opts['_internettlds'])++ for site in sites.keys():+ s = unicode(sites[site][0]).format(eventData)+ searchStr = s.replace(" ", "%20")+ searchDom = sites[site][1]++ if self.opts['method'].lower() == "google":+ results = self.sf.googleIterate(searchStr, dict(limit=self.opts['pages'],+ useragent=self.opts['_useragent'],+ timeout=self.opts['_fetchtimeout']))++ if self.opts['method'].lower() == "yahoo":+ results = self.sf.yahooIterate(searchStr, dict(limit=self.opts['pages'],+ useragent=self.opts['_useragent'],+ timeout=self.opts['_fetchtimeout']))++ if self.opts['method'].lower() == "bing":+ results = self.sf.bingIterate(searchStr, dict(limit=self.opts['pages'],+ useragent=self.opts['_useragent'],+ timeout=self.opts['_fetchtimeout']))++ if results is None:+ self.sf.info("No data returned from " + self.opts['method'] + ".")+ return None++ if self.checkForStop():+ return None++ pauseSecs = random.randint(4, 15)+ self.sf.debug("Pausing for " + str(pauseSecs))+ time.sleep(pauseSecs)++ for key in results.keys():+ instances = list()+ # Yahoo requires some additional parsing+ if self.opts['method'].lower() == "yahoo":+ res = re.sub("RU=(.[^\/]+)\/RK=", self.yahooCleaner,+ results[key], 0)+ else:+ res = results[key]++ matches = re.findall(searchDom, res, re.IGNORECASE)++ if matches is not None:+ for match in matches:+ if match in instances:+ continue+ else:+ instances.append(match)++ if self.checkForStop():+ return None++ # Fetch the profile page if we are checking+ # for a firm relationship.+ if self.opts['tighten']:+ pres = self.sf.fetchUrl(match, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])++ if pres['content'] is None:+ continue+ else:+ found = False+ for kw in self.keywords:+ if re.search("[^a-zA-Z\-\_]" + kw + "[^a-zA-Z\-\_]", pres['content'], re.IGNORECASE):+ found = True+ if not found:+ continue++ self.sf.info("Social Media Profile found at " + site + ": " + match)+ evt = SpiderFootEvent("SOCIAL_MEDIA", site + ": " + match,+ self.__name__, event)+ self.notifyListeners(evt)++ # Submit the bing results for analysis+ evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", res,+ self.__name__, event)+ self.notifyListeners(evt)++# End of sfp_socialprofiles classdiff --git a/modules/sfp_sorbs.py b/modules/sfp_sorbs.pyindex 2b51fd66..8263e594 100644--- a/modules/sfp_sorbs.py+++ b/modules/sfp_sorbs.py@@ -1,160 +1,161 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_sorbs-# Purpose: SpiderFoot plug-in for looking up whether IPs/Netblocks/Domains-# appear in the SORBS blocklist, indicating potential open-relays,-# open proxies, malicious servers, vulnerable servers, etc.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 07/01/2014-# Copyright: (c) Steve Micallef 2014-# Licence: GPL-# ---------------------------------------------------------------------------------import socket-from netaddr import IPNetwork-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_sorbs(SpiderFootPlugin):- """SORBS:Investigate,Passive:Blacklists::Query the SORBS database for open relays, open proxies, vulnerable servers, etc."""-- # Default options- opts = {- 'netblocklookup': True,- 'maxnetblock': 24,- 'subnetlookup': True,- 'maxsubnet': 24- }-- # Option descriptions- optdescs = {- 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible blacklisted hosts on the same target subdomain/domain?",- 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",- 'subnetlookup': "Look up all IPs on subnets which your target is a part of for blacklisting?",- 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"- }-- # Target- results = dict()-- # Whole bunch here:- # http://en.wikipedia.org/wiki/Comparison_of_DNS_blacklists- # Check out:- # http://www.blocklist.de/en/rbldns.html- checks = {- "http.dnsbl.sorbs.net": "SORBS - Open HTTP Proxy",- "socks.dnsbl.sorbs.net": "SORBS - Open SOCKS Proxy",- "misc.dnsbl.sorbs.net": "SORBS - Open Proxy",- "smtp.dnsbl.sorbs.net": "SORBS - Open SMTP Relay",- "spam.dnsbl.sorbs.net": "SORBS - Spammer",- "recent.spam.dnsbl.sorbs.net": "SORBS - Recent Spammer",- "web.dnsbl.sorbs.net": "SORBS - Vulnerability exposed to spammers"- }-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ['IP_ADDRESS', 'AFFILIATE_IPADDR', 'NETBLOCK_OWNER',- 'NETBLOCK_MEMBER']-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["BLACKLISTED_IPADDR", "BLACKLISTED_AFFILIATE_IPADDR",- "BLACKLISTED_SUBNET", "BLACKLISTED_NETBLOCK"]-- # Swap 1.2.3.4 to 4.3.2.1- def reverseAddr(self, ipaddr):- return '.'.join(reversed(ipaddr.split('.')))-- def queryAddr(self, qaddr, parentEvent):- eventName = parentEvent.eventType-- for domain in self.checks:- if self.checkForStop():- return None-- try:- lookup = self.reverseAddr(qaddr) + "." + domain- self.sf.debug("Checking Blacklist: " + lookup)- addrs = self.sf.normalizeDNS(socket.gethostbyname_ex(lookup))- self.sf.debug("Addresses returned: " + str(addrs))-- text = None- for addr in addrs:- if type(self.checks[domain]) is str:- text = self.checks[domain] + " (" + qaddr + ")"- break- else:- if str(addr) not in self.checks[domain].keys():- self.sf.debug("Return code not found in list: " + str(addr))- continue-- k = str(addr)- text = self.checks[domain][k] + " (" + qaddr + ")"- break-- if text is not None:- if eventName == "AFFILIATE_IPADDR":- e = "BLACKLISTED_AFFILIATE_IPADDR"- if eventName == "IP_ADDRESS":- e = "BLACKLISTED_IPADDR"- if eventName == "NETBLOCK_OWNER":- e = "BLACKLISTED_NETBLOCK"- if eventName == "NETBLOCK_MEMBER":- e = "BLACKLISTED_SUBNET"-- evt = SpiderFootEvent(e, text, self.__name__, parentEvent)- self.notifyListeners(evt)-- except BaseException as e:- self.sf.debug("Unable to resolve " + qaddr + " / " + lookup + ": " + str(e))-- return None-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- parentEvent = event- addrlist = list()-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- if eventData in self.results:- return None- self.results[eventData] = True-- if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:- if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:- self.sf.debug("Network size bigger than permitted: " +- str(IPNetwork(eventData).prefixlen) + " > " +- str(self.opts['maxnetblock']))- return None-- if eventName == 'NETBLOCK_MEMBER' and self.opts['subnetlookup']:- if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:- self.sf.debug("Network size bigger than permitted: " +- str(IPNetwork(eventData).prefixlen) + " > " +- str(self.opts['maxsubnet']))- return None-- if eventName.startswith("NETBLOCK_"):- for addr in IPNetwork(eventData):- if self.checkForStop():- return None- self.queryAddr(str(addr), parentEvent)- else:- self.queryAddr(eventData, parentEvent)--# End of sfp_sorbs class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_sorbs+# Purpose: SpiderFoot plug-in for looking up whether IPs/Netblocks/Domains+# appear in the SORBS blocklist, indicating potential open-relays,+# open proxies, malicious servers, vulnerable servers, etc.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 07/01/2014+# Copyright: (c) Steve Micallef 2014+# Licence: GPL+# -------------------------------------------------------------------------------++import socket+from netaddr import IPNetwork+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_sorbs(SpiderFootPlugin):+ """SORBS:Investigate,Passive:Reputation Systems::Query the SORBS database for open relays, open proxies, vulnerable servers, etc."""+++ # Default options+ opts = {+ 'netblocklookup': True,+ 'maxnetblock': 24,+ 'subnetlookup': True,+ 'maxsubnet': 24+ }++ # Option descriptions+ optdescs = {+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible blacklisted hosts on the same target subdomain/domain?",+ 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",+ 'subnetlookup': "Look up all IPs on subnets which your target is a part of for blacklisting?",+ 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"+ }++ # Target+ results = dict()++ # Whole bunch here:+ # http://en.wikipedia.org/wiki/Comparison_of_DNS_blacklists+ # Check out:+ # http://www.blocklist.de/en/rbldns.html+ checks = {+ "http.dnsbl.sorbs.net": "SORBS - Open HTTP Proxy",+ "socks.dnsbl.sorbs.net": "SORBS - Open SOCKS Proxy",+ "misc.dnsbl.sorbs.net": "SORBS - Open Proxy",+ "smtp.dnsbl.sorbs.net": "SORBS - Open SMTP Relay",+ "spam.dnsbl.sorbs.net": "SORBS - Spammer",+ "recent.spam.dnsbl.sorbs.net": "SORBS - Recent Spammer",+ "web.dnsbl.sorbs.net": "SORBS - Vulnerability exposed to spammers"+ }++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ['IP_ADDRESS', 'AFFILIATE_IPADDR', 'NETBLOCK_OWNER',+ 'NETBLOCK_MEMBER']++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["BLACKLISTED_IPADDR", "BLACKLISTED_AFFILIATE_IPADDR",+ "BLACKLISTED_SUBNET", "BLACKLISTED_NETBLOCK"]++ # Swap 1.2.3.4 to 4.3.2.1+ def reverseAddr(self, ipaddr):+ return '.'.join(reversed(ipaddr.split('.')))++ def queryAddr(self, qaddr, parentEvent):+ eventName = parentEvent.eventType++ for domain in self.checks:+ if self.checkForStop():+ return None++ try:+ lookup = self.reverseAddr(qaddr) + "." + domain+ self.sf.debug("Checking Blacklist: " + lookup)+ addrs = self.sf.normalizeDNS(socket.gethostbyname_ex(lookup))+ self.sf.debug("Addresses returned: " + str(addrs))++ text = None+ for addr in addrs:+ if type(self.checks[domain]) is str:+ text = self.checks[domain] + " (" + qaddr + ")"+ break+ else:+ if str(addr) not in self.checks[domain].keys():+ self.sf.debug("Return code not found in list: " + str(addr))+ continue++ k = str(addr)+ text = self.checks[domain][k] + " (" + qaddr + ")"+ break++ if text is not None:+ if eventName == "AFFILIATE_IPADDR":+ e = "BLACKLISTED_AFFILIATE_IPADDR"+ if eventName == "IP_ADDRESS":+ e = "BLACKLISTED_IPADDR"+ if eventName == "NETBLOCK_OWNER":+ e = "BLACKLISTED_NETBLOCK"+ if eventName == "NETBLOCK_MEMBER":+ e = "BLACKLISTED_SUBNET"++ evt = SpiderFootEvent(e, text, self.__name__, parentEvent)+ self.notifyListeners(evt)++ except BaseException as e:+ self.sf.debug("Unable to resolve " + qaddr + " / " + lookup + ": " + str(e))++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ parentEvent = event+ addrlist = list()++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ return None+ self.results[eventData] = True++ if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:+ if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:+ self.sf.debug("Network size bigger than permitted: " ++ str(IPNetwork(eventData).prefixlen) + " > " ++ str(self.opts['maxnetblock']))+ return None++ if eventName == 'NETBLOCK_MEMBER' and self.opts['subnetlookup']:+ if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:+ self.sf.debug("Network size bigger than permitted: " ++ str(IPNetwork(eventData).prefixlen) + " > " ++ str(self.opts['maxsubnet']))+ return None++ if eventName.startswith("NETBLOCK_"):+ for addr in IPNetwork(eventData):+ if self.checkForStop():+ return None+ self.queryAddr(str(addr), parentEvent)+ else:+ self.queryAddr(eventData, parentEvent)++# End of sfp_sorbs classdiff --git a/modules/sfp_spamcop.py b/modules/sfp_spamcop.pyindex 51c4e501..d20ba7f9 100644--- a/modules/sfp_spamcop.py+++ b/modules/sfp_spamcop.py@@ -1,154 +1,155 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_spamcop-# Purpose: SpiderFoot plug-in for looking up whether IPs/Netblocks/Domains-# appear in the spamcop block lists, indicating potential open-relays,-# open proxies, malicious servers, vulnerable servers, etc.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 07/01/2014-# Copyright: (c) Steve Micallef 2014-# Licence: GPL-# ---------------------------------------------------------------------------------import socket-from netaddr import IPNetwork-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_spamcop(SpiderFootPlugin):- """SpamCop:Investigate,Passive:Blacklists::Query various spamcop databases for open relays, open proxies, vulnerable servers, etc."""-- # Default options- opts = {- 'netblocklookup': True,- 'maxnetblock': 24,- 'subnetlookup': True,- 'maxsubnet': 24- }-- # Option descriptions- optdescs = {- 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible blacklisted hosts on the same target subdomain/domain?",- 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",- 'subnetlookup': "Look up all IPs on subnets which your target is a part of for blacklisting?",- 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"- }-- # Target- results = dict()-- # Whole bunch here:- # http://en.wikipedia.org/wiki/Comparison_of_DNS_blacklists- # Check out:- # http://www.blocklist.de/en/rbldns.html- checks = {- "bl.spamcop.net": "SpamCop Blacklist"- }-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ['IP_ADDRESS', 'AFFILIATE_IPADDR', 'NETBLOCK_OWNER',- 'NETBLOCK_MEMBER']-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["BLACKLISTED_IPADDR", "BLACKLISTED_AFFILIATE_IPADDR",- "BLACKLISTED_SUBNET", "BLACKLISTED_NETBLOCK"]-- # Swap 1.2.3.4 to 4.3.2.1- def reverseAddr(self, ipaddr):- return '.'.join(reversed(ipaddr.split('.')))-- def queryAddr(self, qaddr, parentEvent):- eventName = parentEvent.eventType-- for domain in self.checks:- if self.checkForStop():- return None-- try:- lookup = self.reverseAddr(qaddr) + "." + domain- self.sf.debug("Checking Blacklist: " + lookup)- addrs = self.sf.normalizeDNS(socket.gethostbyname_ex(lookup))- self.sf.debug("Addresses returned: " + str(addrs))-- text = None- for addr in addrs:- if type(self.checks[domain]) is str:- text = self.checks[domain] + " (" + qaddr + ")"- break- else:- if str(addr) not in self.checks[domain].keys():- self.sf.debug("Return code not found in list: " + str(addr))- continue-- k = str(addr)- text = self.checks[domain][k] + " (" + qaddr + ")"- break-- if text is not None:- if eventName == "AFFILIATE_IPADDR":- e = "BLACKLISTED_AFFILIATE_IPADDR"- if eventName == "IP_ADDRESS":- e = "BLACKLISTED_IPADDR"- if eventName == "NETBLOCK_OWNER":- e = "BLACKLISTED_NETBLOCK"- if eventName == "NETBLOCK_MEMBER":- e = "BLACKLISTED_SUBNET"-- evt = SpiderFootEvent(e, text, self.__name__, parentEvent)- self.notifyListeners(evt)-- except BaseException as e:- self.sf.debug("Unable to resolve " + qaddr + " / " + lookup + ": " + str(e))-- return None-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- parentEvent = event- addrlist = list()-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- if eventData in self.results:- return None- self.results[eventData] = True-- if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:- if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:- self.sf.debug("Network size bigger than permitted: " +- str(IPNetwork(eventData).prefixlen) + " > " +- str(self.opts['maxnetblock']))- return None-- if eventName == 'NETBLOCK_MEMBER' and self.opts['subnetlookup']:- if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:- self.sf.debug("Network size bigger than permitted: " +- str(IPNetwork(eventData).prefixlen) + " > " +- str(self.opts['maxsubnet']))- return None-- if eventName.startswith("NETBLOCK_"):- for addr in IPNetwork(eventData):- if self.checkForStop():- return None- self.queryAddr(str(addr), parentEvent)- else:- self.queryAddr(eventData, parentEvent)--# End of sfp_spamcop class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_spamcop+# Purpose: SpiderFoot plug-in for looking up whether IPs/Netblocks/Domains+# appear in the spamcop block lists, indicating potential open-relays,+# open proxies, malicious servers, vulnerable servers, etc.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 07/01/2014+# Copyright: (c) Steve Micallef 2014+# Licence: GPL+# -------------------------------------------------------------------------------++import socket+from netaddr import IPNetwork+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_spamcop(SpiderFootPlugin):+ """SpamCop:Investigate,Passive:Reputation Systems::Query various spamcop databases for open relays, open proxies, vulnerable servers, etc."""+++ # Default options+ opts = {+ 'netblocklookup': True,+ 'maxnetblock': 24,+ 'subnetlookup': True,+ 'maxsubnet': 24+ }++ # Option descriptions+ optdescs = {+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible blacklisted hosts on the same target subdomain/domain?",+ 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",+ 'subnetlookup': "Look up all IPs on subnets which your target is a part of for blacklisting?",+ 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"+ }++ # Target+ results = dict()++ # Whole bunch here:+ # http://en.wikipedia.org/wiki/Comparison_of_DNS_blacklists+ # Check out:+ # http://www.blocklist.de/en/rbldns.html+ checks = {+ "bl.spamcop.net": "SpamCop Blacklist"+ }++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ['IP_ADDRESS', 'AFFILIATE_IPADDR', 'NETBLOCK_OWNER',+ 'NETBLOCK_MEMBER']++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["BLACKLISTED_IPADDR", "BLACKLISTED_AFFILIATE_IPADDR",+ "BLACKLISTED_SUBNET", "BLACKLISTED_NETBLOCK"]++ # Swap 1.2.3.4 to 4.3.2.1+ def reverseAddr(self, ipaddr):+ return '.'.join(reversed(ipaddr.split('.')))++ def queryAddr(self, qaddr, parentEvent):+ eventName = parentEvent.eventType++ for domain in self.checks:+ if self.checkForStop():+ return None++ try:+ lookup = self.reverseAddr(qaddr) + "." + domain+ self.sf.debug("Checking Blacklist: " + lookup)+ addrs = self.sf.normalizeDNS(socket.gethostbyname_ex(lookup))+ self.sf.debug("Addresses returned: " + str(addrs))++ text = None+ for addr in addrs:+ if type(self.checks[domain]) is str:+ text = self.checks[domain] + " (" + qaddr + ")"+ break+ else:+ if str(addr) not in self.checks[domain].keys():+ self.sf.debug("Return code not found in list: " + str(addr))+ continue++ k = str(addr)+ text = self.checks[domain][k] + " (" + qaddr + ")"+ break++ if text is not None:+ if eventName == "AFFILIATE_IPADDR":+ e = "BLACKLISTED_AFFILIATE_IPADDR"+ if eventName == "IP_ADDRESS":+ e = "BLACKLISTED_IPADDR"+ if eventName == "NETBLOCK_OWNER":+ e = "BLACKLISTED_NETBLOCK"+ if eventName == "NETBLOCK_MEMBER":+ e = "BLACKLISTED_SUBNET"++ evt = SpiderFootEvent(e, text, self.__name__, parentEvent)+ self.notifyListeners(evt)++ except BaseException as e:+ self.sf.debug("Unable to resolve " + qaddr + " / " + lookup + ": " + str(e))++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ parentEvent = event+ addrlist = list()++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ return None+ self.results[eventData] = True++ if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:+ if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:+ self.sf.debug("Network size bigger than permitted: " ++ str(IPNetwork(eventData).prefixlen) + " > " ++ str(self.opts['maxnetblock']))+ return None++ if eventName == 'NETBLOCK_MEMBER' and self.opts['subnetlookup']:+ if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:+ self.sf.debug("Network size bigger than permitted: " ++ str(IPNetwork(eventData).prefixlen) + " > " ++ str(self.opts['maxsubnet']))+ return None++ if eventName.startswith("NETBLOCK_"):+ for addr in IPNetwork(eventData):+ if self.checkForStop():+ return None+ self.queryAddr(str(addr), parentEvent)+ else:+ self.queryAddr(eventData, parentEvent)++# End of sfp_spamcop classdiff --git a/modules/sfp_spamhaus.py b/modules/sfp_spamhaus.pyindex ed3b1a5b..e23cf91a 100644--- a/modules/sfp_spamhaus.py+++ b/modules/sfp_spamhaus.py@@ -1,163 +1,164 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_spamhaus-# Purpose: SpiderFoot plug-in for looking up whether IPs/Netblocks/Domains-# appear in the Spamhaus block lists, indicating potential open-relays,-# open proxies, malicious servers, vulnerable servers, etc.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 07/01/2014-# Copyright: (c) Steve Micallef 2014-# Licence: GPL-# ---------------------------------------------------------------------------------import socket-from netaddr import IPNetwork-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_spamhaus(SpiderFootPlugin):- """Spamhaus:Investigate,Passive:Blacklists::Query the Spamhaus databases for open relays, open proxies, vulnerable servers, etc."""-- # Default options- opts = {- 'netblocklookup': True,- 'maxnetblock': 24,- 'subnetlookup': True,- 'maxsubnet': 24- }-- # Option descriptions- optdescs = {- 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible blacklisted hosts on the same target subdomain/domain?",- 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",- 'subnetlookup': "Look up all IPs on subnets which your target is a part of for blacklisting?",- 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"- }-- # Target- results = dict()-- # Whole bunch here:- # http://en.wikipedia.org/wiki/Comparison_of_DNS_blacklists- # Check out:- # http://www.blocklist.de/en/rbldns.html- checks = {- 'zen.spamhaus.org': {- '127.0.0.2': "Spamhaus (Zen) - Spammer",- '127.0.0.3': "Spamhaus (Zen) - Spammer",- '127.0.0.4': "Spamhaus (Zen) - Proxies, Trojans, etc.",- '127.0.0.5': "Spamhaus (Zen) - Proxies, Trojans, etc.",- '127.0.0.6': "Spamhaus (Zen) - Proxies, Trojans, etc.",- '127.0.0.7': "Spamhaus (Zen) - Proxies, Trojans, etc.",- '127.0.0.10': "Spamhaus (Zen) - Potential Spammer",- '127.0.0.11': "Spamhaus (Zen) - Potential Spammer"- }- }-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ['IP_ADDRESS', 'AFFILIATE_IPADDR', 'NETBLOCK_OWNER',- 'NETBLOCK_MEMBER']-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["BLACKLISTED_IPADDR", "BLACKLISTED_AFFILIATE_IPADDR",- "BLACKLISTED_SUBNET", "BLACKLISTED_NETBLOCK"]-- # Swap 1.2.3.4 to 4.3.2.1- def reverseAddr(self, ipaddr):- return '.'.join(reversed(ipaddr.split('.')))-- def queryAddr(self, qaddr, parentEvent):- eventName = parentEvent.eventType-- for domain in self.checks:- if self.checkForStop():- return None-- try:- lookup = self.reverseAddr(qaddr) + "." + domain- self.sf.debug("Checking Blacklist: " + lookup)- addrs = self.sf.normalizeDNS(socket.gethostbyname_ex(lookup))- self.sf.debug("Addresses returned: " + str(addrs))-- text = None- for addr in addrs:- if type(self.checks[domain]) is str:- text = self.checks[domain] + " (" + qaddr + ")"- break- else:- if str(addr) not in self.checks[domain].keys():- self.sf.debug("Return code not found in list: " + str(addr))- continue-- k = str(addr)- text = self.checks[domain][k] + " (" + qaddr + ")"- break-- if text is not None:- if eventName == "AFFILIATE_IPADDR":- e = "BLACKLISTED_AFFILIATE_IPADDR"- if eventName == "IP_ADDRESS":- e = "BLACKLISTED_IPADDR"- if eventName == "NETBLOCK_OWNER":- e = "BLACKLISTED_NETBLOCK"- if eventName == "NETBLOCK_MEMBER":- e = "BLACKLISTED_SUBNET"-- evt = SpiderFootEvent(e, text, self.__name__, parentEvent)- self.notifyListeners(evt)-- except BaseException as e:- self.sf.debug("Unable to resolve " + qaddr + " / " + lookup + ": " + str(e))-- return None-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- parentEvent = event- addrlist = list()-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- if eventData in self.results:- return None- self.results[eventData] = True-- if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:- if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:- self.sf.debug("Network size bigger than permitted: " +- str(IPNetwork(eventData).prefixlen) + " > " +- str(self.opts['maxnetblock']))- return None-- if eventName == 'NETBLOCK_MEMBER' and self.opts['subnetlookup']:- if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:- self.sf.debug("Network size bigger than permitted: " +- str(IPNetwork(eventData).prefixlen) + " > " +- str(self.opts['maxsubnet']))- return None-- if eventName.startswith("NETBLOCK_"):- for addr in IPNetwork(eventData):- if self.checkForStop():- return None- self.queryAddr(str(addr), parentEvent)- else:- self.queryAddr(eventData, parentEvent)--# End of sfp_spamhaus class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_spamhaus+# Purpose: SpiderFoot plug-in for looking up whether IPs/Netblocks/Domains+# appear in the Spamhaus block lists, indicating potential open-relays,+# open proxies, malicious servers, vulnerable servers, etc.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 07/01/2014+# Copyright: (c) Steve Micallef 2014+# Licence: GPL+# -------------------------------------------------------------------------------++import socket+from netaddr import IPNetwork+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_spamhaus(SpiderFootPlugin):+ """Spamhaus:Investigate,Passive:Reputation Systems::Query the Spamhaus databases for open relays, open proxies, vulnerable servers, etc."""+++ # Default options+ opts = {+ 'netblocklookup': True,+ 'maxnetblock': 24,+ 'subnetlookup': True,+ 'maxsubnet': 24+ }++ # Option descriptions+ optdescs = {+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible blacklisted hosts on the same target subdomain/domain?",+ 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",+ 'subnetlookup': "Look up all IPs on subnets which your target is a part of for blacklisting?",+ 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"+ }++ # Target+ results = dict()++ # Whole bunch here:+ # http://en.wikipedia.org/wiki/Comparison_of_DNS_blacklists+ # Check out:+ # http://www.blocklist.de/en/rbldns.html+ checks = {+ 'zen.spamhaus.org': {+ '127.0.0.2': "Spamhaus (Zen) - Spammer",+ '127.0.0.3': "Spamhaus (Zen) - Spammer",+ '127.0.0.4': "Spamhaus (Zen) - Proxies, Trojans, etc.",+ '127.0.0.5': "Spamhaus (Zen) - Proxies, Trojans, etc.",+ '127.0.0.6': "Spamhaus (Zen) - Proxies, Trojans, etc.",+ '127.0.0.7': "Spamhaus (Zen) - Proxies, Trojans, etc.",+ '127.0.0.10': "Spamhaus (Zen) - Potential Spammer",+ '127.0.0.11': "Spamhaus (Zen) - Potential Spammer"+ }+ }++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ['IP_ADDRESS', 'AFFILIATE_IPADDR', 'NETBLOCK_OWNER',+ 'NETBLOCK_MEMBER']++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["BLACKLISTED_IPADDR", "BLACKLISTED_AFFILIATE_IPADDR",+ "BLACKLISTED_SUBNET", "BLACKLISTED_NETBLOCK"]++ # Swap 1.2.3.4 to 4.3.2.1+ def reverseAddr(self, ipaddr):+ return '.'.join(reversed(ipaddr.split('.')))++ def queryAddr(self, qaddr, parentEvent):+ eventName = parentEvent.eventType++ for domain in self.checks:+ if self.checkForStop():+ return None++ try:+ lookup = self.reverseAddr(qaddr) + "." + domain+ self.sf.debug("Checking Blacklist: " + lookup)+ addrs = self.sf.normalizeDNS(socket.gethostbyname_ex(lookup))+ self.sf.debug("Addresses returned: " + str(addrs))++ text = None+ for addr in addrs:+ if type(self.checks[domain]) is str:+ text = self.checks[domain] + " (" + qaddr + ")"+ break+ else:+ if str(addr) not in self.checks[domain].keys():+ self.sf.debug("Return code not found in list: " + str(addr))+ continue++ k = str(addr)+ text = self.checks[domain][k] + " (" + qaddr + ")"+ break++ if text is not None:+ if eventName == "AFFILIATE_IPADDR":+ e = "BLACKLISTED_AFFILIATE_IPADDR"+ if eventName == "IP_ADDRESS":+ e = "BLACKLISTED_IPADDR"+ if eventName == "NETBLOCK_OWNER":+ e = "BLACKLISTED_NETBLOCK"+ if eventName == "NETBLOCK_MEMBER":+ e = "BLACKLISTED_SUBNET"++ evt = SpiderFootEvent(e, text, self.__name__, parentEvent)+ self.notifyListeners(evt)++ except BaseException as e:+ self.sf.debug("Unable to resolve " + qaddr + " / " + lookup + ": " + str(e))++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ parentEvent = event+ addrlist = list()++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ return None+ self.results[eventData] = True++ if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:+ if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:+ self.sf.debug("Network size bigger than permitted: " ++ str(IPNetwork(eventData).prefixlen) + " > " ++ str(self.opts['maxnetblock']))+ return None++ if eventName == 'NETBLOCK_MEMBER' and self.opts['subnetlookup']:+ if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:+ self.sf.debug("Network size bigger than permitted: " ++ str(IPNetwork(eventData).prefixlen) + " > " ++ str(self.opts['maxsubnet']))+ return None++ if eventName.startswith("NETBLOCK_"):+ for addr in IPNetwork(eventData):+ if self.checkForStop():+ return None+ self.queryAddr(str(addr), parentEvent)+ else:+ self.queryAddr(eventData, parentEvent)++# End of sfp_spamhaus classdiff --git a/modules/sfp_spider.py b/modules/sfp_spider.pyindex 624c8731..1586c811 100644--- a/modules/sfp_spider.py+++ b/modules/sfp_spider.py@@ -15,7 +15,8 @@ import timefrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEventclass sfp_spider(SpiderFootPlugin):- """Spider:Footprint,Investigate:Web Spidering:slow,invasive:Spidering of web-pages to extract content for searching. """+ """Spider:Footprint,Investigate:Crawling and Scanning:slow,invasive:Spidering of web-pages to extract content for searching."""+# Default optionsopts = {diff --git a/modules/sfp_sslcert.py b/modules/sfp_sslcert.pyindex d0cd7050..f24a632d 100644--- a/modules/sfp_sslcert.py+++ b/modules/sfp_sslcert.py@@ -1,165 +1,166 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_sslcert-# Purpose: Gather information about SSL certificates behind HTTPS sites.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 23/08/2013-# Copyright: (c) Steve Micallef-# Licence: GPL-# ---------------------------------------------------------------------------------import socket-import socks-import ssl-import time-import M2Crypto-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_sslcert(SpiderFootPlugin):- """SSL:Footprint,Investigate:Web Spidering::Gather information about SSL certificates used by the target's HTTPS sites."""-- # Default options- opts = {- "tryhttp": True,- "ssltimeout": 10,- "certexpiringdays": 30- }-- # Option descriptions- optdescs = {- "tryhttp": "Also try to HTTPS-connect to HTTP sites and hostnames.",- "ssltimeout": "Seconds before giving up trying to HTTPS connect.",- "certexpiringdays": "Number of days in the future a certificate expires to consider it as expiring."- }-- # Be sure to completely clear any class variables in setup()- # or you run the risk of data persisting between scan runs.-- results = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- # 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", "LINKED_URL_INTERNAL"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["SSL_CERTIFICATE_ISSUED", "SSL_CERTIFICATE_ISSUER",- "SSL_CERTIFICATE_MISMATCH", "SSL_CERTIFICATE_EXPIRED",- "SSL_CERTIFICATE_EXPIRING", "SSL_CERTIFICATE_RAW"]-- # 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 eventName == "LINKED_URL_INTERNAL":- fqdn = self.sf.urlFQDN(eventData.lower())- else:- fqdn = eventData-- if fqdn not in self.results:- self.results[fqdn] = True- else:- return None-- if not eventData.lower().startswith("https://") and not self.opts['tryhttp']:- return None-- self.sf.debug("Testing SSL for: " + eventData)- # Re-fetch the certificate from the site and process- try:- s = socket.socket()- s.settimeout(int(self.opts['ssltimeout']))- s.connect((fqdn, 443))- sock = ssl.wrap_socket(s)- sock.do_handshake()- rawcert = sock.getpeercert(True)- cert = ssl.DER_cert_to_PEM_cert(rawcert)- m2cert = M2Crypto.X509.load_cert_string(str(cert).replace('\r', ''))- except BaseException as x:- self.sf.info("Unable to SSL-connect to " + fqdn + ": " + str(x))- return None-- # Generate the event for the raw cert (in text form)- # Cert raw data text contains a lot of gems..- rawevt = SpiderFootEvent("SSL_CERTIFICATE_RAW",- m2cert.as_text().encode('raw_unicode_escape'),- self.__name__, event)- self.notifyListeners(rawevt)-- # Generate events for other cert aspects- self.getIssued(m2cert, event)- self.getIssuer(m2cert, event)- self.checkHostMatch(m2cert, fqdn, event)- self.checkExpiry(m2cert, event)-- # Report back who the certificate was issued to- def getIssued(self, cert, sevt):- issued = cert.get_subject().as_text().encode('raw_unicode_escape')- evt = SpiderFootEvent("SSL_CERTIFICATE_ISSUED", issued, self.__name__, sevt)- self.notifyListeners(evt)-- # Report back the certificate issuer- def getIssuer(self, cert, sevt):- issuer = cert.get_issuer().as_text().encode('raw_unicode_escape')- evt = SpiderFootEvent("SSL_CERTIFICATE_ISSUER", issuer, self.__name__, sevt)- self.notifyListeners(evt)-- # Check if the hostname matches the name of the server- def checkHostMatch(self, cert, fqdn, sevt):- fqdn = fqdn.lower()- hosts = ""-- # Extract the CN from the issued section- issued = cert.get_subject().as_text().encode('raw_unicode_escape')- self.sf.debug("Checking for " + fqdn + " in " + issued.lower())- if "cn=" + fqdn in issued.lower():- hosts = 'dns:' + fqdn-- try:- hosts = hosts + " " + cert.get_ext("subjectAltName").get_value().encode('raw_unicode_escape').lower()- except LookupError as e:- self.sf.debug("No alternative name found in certificate.")-- fqdn_tld = ".".join(fqdn.split(".")[1:]).lower()- if "dns:" + fqdn not in hosts and "dns:*." + fqdn_tld not in hosts:- evt = SpiderFootEvent("SSL_CERTIFICATE_MISMATCH", hosts, self.__name__, sevt)- self.notifyListeners(evt)-- # Check if the expiration date is in the future- def checkExpiry(self, cert, sevt):- exp = int(time.mktime(cert.get_not_after().get_datetime().timetuple()))- expstr = cert.get_not_after().get_datetime().strftime("%Y-%m-%d %H:%M:%S")- now = int(time.time())- warnexp = now + self.opts['certexpiringdays'] * 86400-- if exp <= now:- evt = SpiderFootEvent("SSL_CERTIFICATE_EXPIRED", expstr, self.__name__, sevt)- self.notifyListeners(evt)- return None-- if exp <= warnexp:- evt = SpiderFootEvent("SSL_CERTIFICATE_EXPIRING", expstr, self.__name__, sevt)- self.notifyListeners(evt)- return None--# End of sfp_sslcert class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_sslcert+# Purpose: Gather information about SSL certificates behind HTTPS sites.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 23/08/2013+# Copyright: (c) Steve Micallef+# Licence: GPL+# -------------------------------------------------------------------------------++import socket+import socks+import ssl+import time+import M2Crypto+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_sslcert(SpiderFootPlugin):+ """SSL:Footprint,Investigate:Crawling and Scanning::Gather information about SSL certificates used by the target's HTTPS sites."""+++ # Default options+ opts = {+ "tryhttp": True,+ "ssltimeout": 10,+ "certexpiringdays": 30+ }++ # Option descriptions+ optdescs = {+ "tryhttp": "Also try to HTTPS-connect to HTTP sites and hostnames.",+ "ssltimeout": "Seconds before giving up trying to HTTPS connect.",+ "certexpiringdays": "Number of days in the future a certificate expires to consider it as expiring."+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ # 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", "LINKED_URL_INTERNAL"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["SSL_CERTIFICATE_ISSUED", "SSL_CERTIFICATE_ISSUER",+ "SSL_CERTIFICATE_MISMATCH", "SSL_CERTIFICATE_EXPIRED",+ "SSL_CERTIFICATE_EXPIRING", "SSL_CERTIFICATE_RAW"]++ # 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 eventName == "LINKED_URL_INTERNAL":+ fqdn = self.sf.urlFQDN(eventData.lower())+ else:+ fqdn = eventData++ if fqdn not in self.results:+ self.results[fqdn] = True+ else:+ return None++ if not eventData.lower().startswith("https://") and not self.opts['tryhttp']:+ return None++ self.sf.debug("Testing SSL for: " + eventData)+ # Re-fetch the certificate from the site and process+ try:+ s = socket.socket()+ s.settimeout(int(self.opts['ssltimeout']))+ s.connect((fqdn, 443))+ sock = ssl.wrap_socket(s)+ sock.do_handshake()+ rawcert = sock.getpeercert(True)+ cert = ssl.DER_cert_to_PEM_cert(rawcert)+ m2cert = M2Crypto.X509.load_cert_string(str(cert).replace('\r', ''))+ except BaseException as x:+ self.sf.info("Unable to SSL-connect to " + fqdn + ": " + str(x))+ return None++ # Generate the event for the raw cert (in text form)+ # Cert raw data text contains a lot of gems..+ rawevt = SpiderFootEvent("SSL_CERTIFICATE_RAW",+ m2cert.as_text().encode('raw_unicode_escape'),+ self.__name__, event)+ self.notifyListeners(rawevt)++ # Generate events for other cert aspects+ self.getIssued(m2cert, event)+ self.getIssuer(m2cert, event)+ self.checkHostMatch(m2cert, fqdn, event)+ self.checkExpiry(m2cert, event)++ # Report back who the certificate was issued to+ def getIssued(self, cert, sevt):+ issued = cert.get_subject().as_text().encode('raw_unicode_escape')+ evt = SpiderFootEvent("SSL_CERTIFICATE_ISSUED", issued, self.__name__, sevt)+ self.notifyListeners(evt)++ # Report back the certificate issuer+ def getIssuer(self, cert, sevt):+ issuer = cert.get_issuer().as_text().encode('raw_unicode_escape')+ evt = SpiderFootEvent("SSL_CERTIFICATE_ISSUER", issuer, self.__name__, sevt)+ self.notifyListeners(evt)++ # Check if the hostname matches the name of the server+ def checkHostMatch(self, cert, fqdn, sevt):+ fqdn = fqdn.lower()+ hosts = ""++ # Extract the CN from the issued section+ issued = cert.get_subject().as_text().encode('raw_unicode_escape')+ self.sf.debug("Checking for " + fqdn + " in " + issued.lower())+ if "cn=" + fqdn in issued.lower():+ hosts = 'dns:' + fqdn++ try:+ hosts = hosts + " " + cert.get_ext("subjectAltName").get_value().encode('raw_unicode_escape').lower()+ except LookupError as e:+ self.sf.debug("No alternative name found in certificate.")++ fqdn_tld = ".".join(fqdn.split(".")[1:]).lower()+ if "dns:" + fqdn not in hosts and "dns:*." + fqdn_tld not in hosts:+ evt = SpiderFootEvent("SSL_CERTIFICATE_MISMATCH", hosts, self.__name__, sevt)+ self.notifyListeners(evt)++ # Check if the expiration date is in the future+ def checkExpiry(self, cert, sevt):+ exp = int(time.mktime(cert.get_not_after().get_datetime().timetuple()))+ expstr = cert.get_not_after().get_datetime().strftime("%Y-%m-%d %H:%M:%S")+ now = int(time.time())+ warnexp = now + self.opts['certexpiringdays'] * 86400++ if exp <= now:+ evt = SpiderFootEvent("SSL_CERTIFICATE_EXPIRED", expstr, self.__name__, sevt)+ self.notifyListeners(evt)+ return None++ if exp <= warnexp:+ evt = SpiderFootEvent("SSL_CERTIFICATE_EXPIRING", expstr, self.__name__, sevt)+ self.notifyListeners(evt)+ return None++# End of sfp_sslcert classdiff --git a/modules/sfp_strangeheaders.py b/modules/sfp_strangeheaders.pyindex 7c31f42d..8c377dbd 100644--- a/modules/sfp_strangeheaders.py+++ b/modules/sfp_strangeheaders.py@@ -1,77 +1,78 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_strangeheaders-# Purpose: SpiderFoot plug-in for identifying non-standard HTTP headers-# in web server responses.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 01/12/2013-# Copyright: (c) Steve Micallef 2013-# Licence: GPL-# ---------------------------------------------------------------------------------from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent--# Standard headers, taken from http://en.wikipedia.org/wiki/List_of_HTTP_header_fields-headers = ["access-control-allow-origin", "accept-ranges", "age", "allow", "cache-control",- "connection", "content-encoding", "content-language", "content-length", "content-location",- "content-md5", "content-disposition", "content-range", "content-type", "date", "etag",- "expires", "last-modified", "link", "location", "p3p", "pragma", "proxy-authenticate",- "refresh", "retry-after", "server", "set-cookie", "status", "strict-transport-security",- "trailer", "transfer-encoding", "vary", "via", "warning", "www-authenticate",- "x-frame-options", "x-xss-protection", "content-security-policy", "x-content-security-policy",- "x-webkit-csp", "x-content-type-options", "x-powered-by", "x-ua-compatible"]---class sfp_strangeheaders(SpiderFootPlugin):- """Strange Headers:Footprint:Data Analysis::Obtain non-standard HTTP headers returned by web servers."""-- # Default options- opts = {}-- results = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["WEBSERVER_HTTPHEADERS"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["WEBSERVER_STRANGEHEADER"]-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- parentEvent = event.sourceEvent- eventSource = event.sourceEvent.data-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)- if eventSource in self.results:- return None- else:- self.results[eventSource] = True-- if not self.getTarget().matches(self.sf.urlFQDN(eventSource)):- self.sf.debug("Not collecting header information for external sites.")- return None-- for key in eventData:- if key.lower() not in headers:- val = key + ": " + eventData[key]- evt = SpiderFootEvent("WEBSERVER_STRANGEHEADER", val,- self.__name__, parentEvent)- self.notifyListeners(evt)--# End of sfp_strangeheaders class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_strangeheaders+# Purpose: SpiderFoot plug-in for identifying non-standard HTTP headers+# in web server responses.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 01/12/2013+# Copyright: (c) Steve Micallef 2013+# Licence: GPL+# -------------------------------------------------------------------------------++from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++# Standard headers, taken from http://en.wikipedia.org/wiki/List_of_HTTP_header_fields+headers = ["access-control-allow-origin", "accept-ranges", "age", "allow", "cache-control",+ "connection", "content-encoding", "content-language", "content-length", "content-location",+ "content-md5", "content-disposition", "content-range", "content-type", "date", "etag",+ "expires", "last-modified", "link", "location", "p3p", "pragma", "proxy-authenticate",+ "refresh", "retry-after", "server", "set-cookie", "status", "strict-transport-security",+ "trailer", "transfer-encoding", "vary", "via", "warning", "www-authenticate",+ "x-frame-options", "x-xss-protection", "content-security-policy", "x-content-security-policy",+ "x-webkit-csp", "x-content-type-options", "x-powered-by", "x-ua-compatible"]+++class sfp_strangeheaders(SpiderFootPlugin):+ """Strange Headers:Footprint:Content Analysis::Obtain non-standard HTTP headers returned by web servers."""+++ # Default options+ opts = {}++ results = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["WEBSERVER_HTTPHEADERS"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["WEBSERVER_STRANGEHEADER"]++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ parentEvent = event.sourceEvent+ eventSource = event.sourceEvent.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ if eventSource in self.results:+ return None+ else:+ self.results[eventSource] = True++ if not self.getTarget().matches(self.sf.urlFQDN(eventSource)):+ self.sf.debug("Not collecting header information for external sites.")+ return None++ for key in eventData:+ if key.lower() not in headers:+ val = key + ": " + eventData[key]+ evt = SpiderFootEvent("WEBSERVER_STRANGEHEADER", val,+ self.__name__, parentEvent)+ self.notifyListeners(evt)++# End of sfp_strangeheaders classdiff --git a/modules/sfp_template.py b/modules/sfp_template.pyindex 7bfa6c02..147968f4 100644--- a/modules/sfp_template.py+++ b/modules/sfp_template.py@@ -1,80 +1,80 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_XXX-# Purpose: Description of the plug-in.-#-# Author: Name and e-mail address-#-# Created: Date-# Copyright: (c) Name-# Licence: GPL-# ---------------------------------------------------------------------------------from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_XXX(SpiderFootPlugin):- """Name:Use Cases:Category:Labels:Description"""-- # Default options- opts = {}-- # Option descriptions- optdescs = {- # For each option in opts you should have a key/value pair here- # describing it. It will end up in the UI to explain the option- # to the end-user.- }-- # Be sure to completely clear any class variables in setup()- # or you run the risk of data persisting between scan runs.-- # Target- results = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- # 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 ["*"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return None-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- # If you are processing TARGET_WEB_CONTENT from sfp_spider, this is how you- # would get the source of that raw data (e.g. a URL.)- eventSource = event.sourceEvent.data-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- # DO SOMETHING HERE-- # Notify other modules of what you've found- evt = SpiderFootEvent("EVENT_CODE_HERE", "data here", self.__name__, event.sourceEvent)- self.notifyListeners(evt)-- return None-- # If you intend for this module to act on its own (e.g. not solely rely- # on events from other modules, then you need to have a start() method- # and within that method call self.checkForStop() to see if you've been- # politely asked by the controller to stop your activities (user abort.)--# End of sfp_XXX class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_XXX+# Purpose: Description of the plug-in.+#+# Author: Name and e-mail address+#+# Created: Date+# Copyright: (c) Name+# Licence: GPL+# -------------------------------------------------------------------------------++from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_XXX(SpiderFootPlugin):+ """Name:Use Cases:Category:Labels:Description"""++ # Default options+ opts = {}++ # Option descriptions+ optdescs = {+ # For each option in opts you should have a key/value pair here+ # describing it. It will end up in the UI to explain the option+ # to the end-user.+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ # Target+ results = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ # 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 ["*"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ # If you are processing TARGET_WEB_CONTENT from sfp_spider, this is how you+ # would get the source of that raw data (e.g. a URL.)+ eventSource = event.sourceEvent.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ # DO SOMETHING HERE++ # Notify other modules of what you've found+ evt = SpiderFootEvent("EVENT_CODE_HERE", "data here", self.__name__, event.sourceEvent)+ self.notifyListeners(evt)++ return None++ # If you intend for this module to act on its own (e.g. not solely rely+ # on events from other modules, then you need to have a start() method+ # and within that method call self.checkForStop() to see if you've been+ # politely asked by the controller to stop your activities (user abort.)++# End of sfp_XXX classdiff --git a/modules/sfp_threatcrowd.py b/modules/sfp_threatcrowd.pyindex 97479326..1ef6b63a 100644--- a/modules/sfp_threatcrowd.py+++ b/modules/sfp_threatcrowd.py@@ -1,179 +1,180 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_threatcrowd-# Purpose: Query threatcrowd.org for identified IP addresses.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 21/11/2016-# Copyright: (c) Steve Micallef-# Licence: GPL-# ---------------------------------------------------------------------------------import json-import time-from netaddr import IPNetwork-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_threatcrowd(SpiderFootPlugin):- """ThreatCrowd:Investigate,Passive:Blacklists::Obtain information from ThreatCrowd about identified IP addresses, domains and e-mail addresses."""-- # Default options- opts = {- "checkcohosts": True,- "checkaffiliates": True,- 'netblocklookup': True,- 'maxnetblock': 24,- 'subnetlookup': True,- 'maxsubnet': 24- }-- # Option descriptions- optdescs = {- "checkcohosts": "Check co-hosted sites?",- "checkaffiliates": "Check affiliates?",- 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible hosts on the same target subdomain/domain?",- 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",- 'subnetlookup': "Look up all IPs on subnets which your target is a part of?",- 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"- }-- # Be sure to completely clear any class variables in setup()- # or you run the risk of data persisting between scan runs.-- results = dict()- errorState = False-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- # 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- def watchedEvents(self):- return ["IP_ADDRESS", "AFFILIATE_IPADDR", "INTERNET_NAME",- "CO_HOSTED_SITE", "NETBLOCK_OWNER", "EMAILADDR",- "NETBLOCK_MEMBER"]-- # What events this module produces- def producedEvents(self):- return ["MALICIOUS_IPADDR", "MALICIOUS_INTERNET_NAME",- "MALICIOUS_COHOST", "MALICIOUS_AFFILIATE_INTERNET_NAME",- "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_NETBLOCK",- "MALICIOUS_SUBNET", "INTERNET_NAME", "AFFILIATE_INTERNET_NAME",- "MALICIOUS_EMAILADDR"]-- def query(self, qry):- ret = None- url = None-- if self.sf.validIP(qry):- url = "http://www.threatcrowd.org/searchApi/v2/ip/report/?ip=" + qry-- if "@" in qry:- url = "http://www.threatcrowd.org/searchApi/v2/email/report/?email=" + qry-- if not url:- url = "http://www.threatcrowd.org/searchApi/v2/domain/report/?domain=" + qry-- res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent="SpiderFoot")-- if res['content'] is None:- self.sf.info("No ThreatCrowd info found for " + qry)- return None-- try:- ret = json.loads(res['content'])- except Exception as e:- self.sf.error("Error processing JSON response from ThreatCrowd.", False)- return None-- return ret-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if self.errorState:- return None-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- # Don't look up stuff twice- if eventData in self.results:- self.sf.debug("Skipping " + eventData + " as already mapped.")- return None- else:- self.results[eventData] = True-- if eventName.startswith("AFFILIATE") and not self.opts['checkaffiliates']:- return None-- if eventName == 'CO_HOSTED_SITE' and not self.opts['checkcohosts']:- return None-- if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:- if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:- self.sf.debug("Network size bigger than permitted: " +- str(IPNetwork(eventData).prefixlen) + " > " +- str(self.opts['maxnetblock']))- return None-- if eventName == 'NETBLOCK_MEMBER' and self.opts['subnetlookup']:- if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:- self.sf.debug("Network size bigger than permitted: " +- str(IPNetwork(eventData).prefixlen) + " > " +- str(self.opts['maxsubnet']))- return None-- qrylist = list()- if eventName.startswith("NETBLOCK_"):- for ipaddr in IPNetwork(eventData):- qrylist.append(str(ipaddr))- self.results[str(ipaddr)] = True- else:- qrylist.append(eventData)-- for addr in qrylist:- if self.checkForStop():- return None-- info = self.query(addr)- if info is None:- continue- if info.get('votes', 0) < 0:- self.sf.info("Found ThreatCrowd URL data for " + addr)- if eventName in ["IP_ADDRESS"] or eventName.startswith("NETBLOCK_"):- evt = "MALICIOUS_IPADDR"-- if eventName == "AFFILIATE_IPADDR":- evt = "MALICIOUS_AFFILIATE_IPADDR"-- if eventName == "INTERNET_NAME":- evt = "MALICIOUS_INTERNET_NAME"-- if eventName == "AFFILIATE_INTERNET_NAME":- evt = "MALICIOUS_AFFILIATE_INTERNET_NAME"-- if eventName == "CO_HOSTED_SITE":- evt = "MALICIOUS_COHOST"-- if eventName == "EMAILADDR":- evt = "MALICIOUS_EMAILADDR"-- infourl = "<SFURL>" + info.get('permalink') + "</SFURL>"-- # Notify other modules of what you've found- e = SpiderFootEvent(evt, "ThreatCrowd [" + addr + "]\n" +- infourl, self.__name__, event)- self.notifyListeners(e)--# End of sfp_threatcrowd class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_threatcrowd+# Purpose: Query threatcrowd.org for identified IP addresses.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 21/11/2016+# Copyright: (c) Steve Micallef+# Licence: GPL+# -------------------------------------------------------------------------------++import json+import time+from netaddr import IPNetwork+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_threatcrowd(SpiderFootPlugin):+ """ThreatCrowd:Investigate,Passive:Reputation Systems::Obtain information from ThreatCrowd about identified IP addresses, domains and e-mail addresses."""+++ # Default options+ opts = {+ "checkcohosts": True,+ "checkaffiliates": True,+ 'netblocklookup': True,+ 'maxnetblock': 24,+ 'subnetlookup': True,+ 'maxsubnet': 24+ }++ # Option descriptions+ optdescs = {+ "checkcohosts": "Check co-hosted sites?",+ "checkaffiliates": "Check affiliates?",+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible hosts on the same target subdomain/domain?",+ 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",+ 'subnetlookup': "Look up all IPs on subnets which your target is a part of?",+ 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = dict()+ errorState = False++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ # 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+ def watchedEvents(self):+ return ["IP_ADDRESS", "AFFILIATE_IPADDR", "INTERNET_NAME",+ "CO_HOSTED_SITE", "NETBLOCK_OWNER", "EMAILADDR",+ "NETBLOCK_MEMBER"]++ # What events this module produces+ def producedEvents(self):+ return ["MALICIOUS_IPADDR", "MALICIOUS_INTERNET_NAME",+ "MALICIOUS_COHOST", "MALICIOUS_AFFILIATE_INTERNET_NAME",+ "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_NETBLOCK",+ "MALICIOUS_SUBNET", "INTERNET_NAME", "AFFILIATE_INTERNET_NAME",+ "MALICIOUS_EMAILADDR"]++ def query(self, qry):+ ret = None+ url = None++ if self.sf.validIP(qry):+ url = "http://www.threatcrowd.org/searchApi/v2/ip/report/?ip=" + qry++ if "@" in qry:+ url = "http://www.threatcrowd.org/searchApi/v2/email/report/?email=" + qry++ if not url:+ url = "http://www.threatcrowd.org/searchApi/v2/domain/report/?domain=" + qry++ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent="SpiderFoot")++ if res['content'] is None:+ self.sf.info("No ThreatCrowd info found for " + qry)+ return None++ try:+ ret = json.loads(res['content'])+ except Exception as e:+ self.sf.error("Error processing JSON response from ThreatCrowd.", False)+ return None++ return ret++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if self.errorState:+ return None++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ # Don't look up stuff twice+ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + " as already mapped.")+ return None+ else:+ self.results[eventData] = True++ if eventName.startswith("AFFILIATE") and not self.opts['checkaffiliates']:+ return None++ if eventName == 'CO_HOSTED_SITE' and not self.opts['checkcohosts']:+ return None++ if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:+ if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:+ self.sf.debug("Network size bigger than permitted: " ++ str(IPNetwork(eventData).prefixlen) + " > " ++ str(self.opts['maxnetblock']))+ return None++ if eventName == 'NETBLOCK_MEMBER' and self.opts['subnetlookup']:+ if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:+ self.sf.debug("Network size bigger than permitted: " ++ str(IPNetwork(eventData).prefixlen) + " > " ++ str(self.opts['maxsubnet']))+ return None++ qrylist = list()+ if eventName.startswith("NETBLOCK_"):+ for ipaddr in IPNetwork(eventData):+ qrylist.append(str(ipaddr))+ self.results[str(ipaddr)] = True+ else:+ qrylist.append(eventData)++ for addr in qrylist:+ if self.checkForStop():+ return None++ info = self.query(addr)+ if info is None:+ continue+ if info.get('votes', 0) < 0:+ self.sf.info("Found ThreatCrowd URL data for " + addr)+ if eventName in ["IP_ADDRESS"] or eventName.startswith("NETBLOCK_"):+ evt = "MALICIOUS_IPADDR"++ if eventName == "AFFILIATE_IPADDR":+ evt = "MALICIOUS_AFFILIATE_IPADDR"++ if eventName == "INTERNET_NAME":+ evt = "MALICIOUS_INTERNET_NAME"++ if eventName == "AFFILIATE_INTERNET_NAME":+ evt = "MALICIOUS_AFFILIATE_INTERNET_NAME"++ if eventName == "CO_HOSTED_SITE":+ evt = "MALICIOUS_COHOST"++ if eventName == "EMAILADDR":+ evt = "MALICIOUS_EMAILADDR"++ infourl = "<SFURL>" + info.get('permalink') + "</SFURL>"++ # Notify other modules of what you've found+ e = SpiderFootEvent(evt, "ThreatCrowd [" + addr + "]\n" ++ infourl, self.__name__, event)+ self.notifyListeners(e)++# End of sfp_threatcrowd classdiff --git a/modules/sfp_threatexpert.py b/modules/sfp_threatexpert.pyindex 59b7c516..dfed9b0e 100644--- a/modules/sfp_threatexpert.py+++ b/modules/sfp_threatexpert.py@@ -1,266 +1,267 @@-# -*- 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 class+# -*- 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:Reputation Systems: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_tldsearch.py b/modules/sfp_tldsearch.pyindex 929b51b1..75881bba 100644--- a/modules/sfp_tldsearch.py+++ b/modules/sfp_tldsearch.py@@ -1,173 +1,174 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_tldsearch-# Purpose: SpiderFoot plug-in for identifying the existence of this target-# on other TLDs.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 31/08/2013-# Copyright: (c) Steve Micallef 2013-# Licence: GPL-# ---------------------------------------------------------------------------------import socket-import random-import threading-import time-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_tldsearch(SpiderFootPlugin):- """TLD Search:Footprint:Networking:slow:Search all Internet TLDs for domains with the same name as the target (this can be very slow.)"""-- # Default options- opts = {- 'activeonly': True, # Only report domains that have content (try to fetch the page)- 'skipwildcards': True,- 'maxthreads': 100- }-- # Option descriptions- optdescs = {- 'activeonly': "Only report domains that have content (try to fetch the page)?",- "skipwildcards": "Skip TLDs and sub-TLDs that have wildcard DNS.",- "maxthreads": "Number of simultaneous DNS resolutions to perform at once."- }-- # Internal results tracking- results = list()-- # Track TLD search results between threads- tldResults = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["INTERNET_NAME"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["SIMILARDOMAIN"]-- def tryTld(self, target):- try:- addrs = socket.gethostbyname_ex(target)- self.tldResults[target] = True- except BaseException as e:- self.tldResults[target] = False-- def tryTldWrapper(self, tldList, sourceEvent):- self.tldResults = dict()- running = True- i = 0- t = []-- # Spawn threads for scanning- self.sf.info("Spawning threads to check TLDs: " + str(tldList))- for tld in tldList:- tn = 'sfp_tldsearch_' + str(random.randint(0, 999999999))- t.append(threading.Thread(name=tn, target=self.tryTld, args=(tld,)))- t[i].start()- i += 1-- # Block until all threads are finished- while running:- found = False- for rt in threading.enumerate():- if rt.name.startswith("sfp_tldsearch_"):- found = True-- if not found:- running = False-- time.sleep(2)-- for res in self.tldResults.keys():- if self.tldResults[res] and res not in self.results:- self.sendEvent(sourceEvent, res)-- # Store the result internally and notify listening modules- def sendEvent(self, source, result):- self.sf.info("Found a TLD with the target's name: " + result)- self.results.append(result)-- # Inform listening modules- if self.opts['activeonly']:- if self.checkForStop():- return None-- pageContent = self.sf.fetchUrl('http://' + result,- timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])- if pageContent['content'] is not None:- evt = SpiderFootEvent("SIMILARDOMAIN", result, self.__name__, source)- self.notifyListeners(evt)- else:- evt = SpiderFootEvent("SIMILARDOMAIN", result, self.__name__, source)- self.notifyListeners(evt)-- # Search for similar sounding domains- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if eventData in self.results:- return None- else:- self.results.append(eventData)-- keyword = self.sf.domainKeyword(eventData, self.opts['_internettlds'])- self.sf.debug("Keyword extracted from " + eventData + ": " + keyword)- targetList = list()-- if keyword in self.results:- return None- else:- self.results.append(keyword)-- # Look through all TLDs for the existence of this target keyword- for tld in self.opts['_internettlds']:- if type(tld) != unicode:- tld = unicode(tld.strip(), errors='ignore')- else:- tld = tld.strip()-- if tld.startswith("//") or len(tld) == 0:- continue-- if tld.startswith("!") or tld.startswith("*") or tld.startswith(".."):- continue-- if tld.endswith(".arpa"):- continue-- if self.opts['skipwildcards'] and self.sf.checkDnsWildcard(tld):- continue-- tryDomain = keyword + "." + tld-- if self.checkForStop():- return None-- if len(targetList) <= self.opts['maxthreads']:- targetList.append(tryDomain)- else:- self.tryTldWrapper(targetList, event)- targetList = list()-- # Scan whatever may be left over.- if len(targetList) > 0:- self.tryTldWrapper(targetList, event)-- return None--# End of sfp_tldsearch class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_tldsearch+# Purpose: SpiderFoot plug-in for identifying the existence of this target+# on other TLDs.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 31/08/2013+# Copyright: (c) Steve Micallef 2013+# Licence: GPL+# -------------------------------------------------------------------------------++import socket+import random+import threading+import time+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_tldsearch(SpiderFootPlugin):+ """TLD Search:Footprint:DNS:slow:Search all Internet TLDs for domains with the same name as the target (this can be very slow.)"""+++ # Default options+ opts = {+ 'activeonly': True, # Only report domains that have content (try to fetch the page)+ 'skipwildcards': True,+ 'maxthreads': 100+ }++ # Option descriptions+ optdescs = {+ 'activeonly': "Only report domains that have content (try to fetch the page)?",+ "skipwildcards": "Skip TLDs and sub-TLDs that have wildcard DNS.",+ "maxthreads": "Number of simultaneous DNS resolutions to perform at once."+ }++ # Internal results tracking+ results = list()++ # Track TLD search results between threads+ tldResults = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["INTERNET_NAME"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["SIMILARDOMAIN"]++ def tryTld(self, target):+ try:+ addrs = socket.gethostbyname_ex(target)+ self.tldResults[target] = True+ except BaseException as e:+ self.tldResults[target] = False++ def tryTldWrapper(self, tldList, sourceEvent):+ self.tldResults = dict()+ running = True+ i = 0+ t = []++ # Spawn threads for scanning+ self.sf.info("Spawning threads to check TLDs: " + str(tldList))+ for tld in tldList:+ tn = 'sfp_tldsearch_' + str(random.randint(0, 999999999))+ t.append(threading.Thread(name=tn, target=self.tryTld, args=(tld,)))+ t[i].start()+ i += 1++ # Block until all threads are finished+ while running:+ found = False+ for rt in threading.enumerate():+ if rt.name.startswith("sfp_tldsearch_"):+ found = True++ if not found:+ running = False++ time.sleep(2)++ for res in self.tldResults.keys():+ if self.tldResults[res] and res not in self.results:+ self.sendEvent(sourceEvent, res)++ # Store the result internally and notify listening modules+ def sendEvent(self, source, result):+ self.sf.info("Found a TLD with the target's name: " + result)+ self.results.append(result)++ # Inform listening modules+ if self.opts['activeonly']:+ if self.checkForStop():+ return None++ pageContent = self.sf.fetchUrl('http://' + result,+ timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ if pageContent['content'] is not None:+ evt = SpiderFootEvent("SIMILARDOMAIN", result, self.__name__, source)+ self.notifyListeners(evt)+ else:+ evt = SpiderFootEvent("SIMILARDOMAIN", result, self.__name__, source)+ self.notifyListeners(evt)++ # Search for similar sounding domains+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if eventData in self.results:+ return None+ else:+ self.results.append(eventData)++ keyword = self.sf.domainKeyword(eventData, self.opts['_internettlds'])+ self.sf.debug("Keyword extracted from " + eventData + ": " + keyword)+ targetList = list()++ if keyword in self.results:+ return None+ else:+ self.results.append(keyword)++ # Look through all TLDs for the existence of this target keyword+ for tld in self.opts['_internettlds']:+ if type(tld) != unicode:+ tld = unicode(tld.strip(), errors='ignore')+ else:+ tld = tld.strip()++ if tld.startswith("//") or len(tld) == 0:+ continue++ if tld.startswith("!") or tld.startswith("*") or tld.startswith(".."):+ continue++ if tld.endswith(".arpa"):+ continue++ if self.opts['skipwildcards'] and self.sf.checkDnsWildcard(tld):+ continue++ tryDomain = keyword + "." + tld++ if self.checkForStop():+ return None++ if len(targetList) <= self.opts['maxthreads']:+ targetList.append(tryDomain)+ else:+ self.tryTldWrapper(targetList, event)+ targetList = list()++ # Scan whatever may be left over.+ if len(targetList) > 0:+ self.tryTldWrapper(targetList, event)++ return None++# End of sfp_tldsearch classdiff --git a/modules/sfp_torch.py b/modules/sfp_torch.pyindex 1f031d97..65dddc07 100644--- a/modules/sfp_torch.py+++ b/modules/sfp_torch.py@@ -1,135 +1,136 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_torch-# Purpose: Searches the Tor search engine 'TORCH' for content related-# to the domain in question.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 20/06/2017-# Copyright: (c) Steve Micallef 2017-# Licence: GPL-# ---------------------------------------------------------------------------------from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-import re--class sfp_torch(SpiderFootPlugin):- """TORCH:Footprint,Investigate:Search Engines::Search Tor 'TORCH' search engine for mentions of the target domain."""-- # Default options- opts = {- 'fetchlinks': False,- 'pages': 20,- }-- # Option descriptions- optdescs = {- 'fetchlinks': "Fetch the darknet pages (via TOR, if enabled) to verify they mention your target.",- 'pages': "Number of results pages to iterate through."- }-- # Target- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["DOMAIN_NAME"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["DARKNET_MENTION_URL", "SEARCH_ENGINE_WEB_CONTENT"]-- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if eventData in self.results:- self.sf.debug("Already did a search for " + eventData + ", skipping.")- return None- else:- self.results.append(eventData)-- formpage = self.sf.fetchUrl("http://xmh57jrzrnw6insl.onion",- useragent=self.opts['_useragent'],- timeout=self.opts['_fetchtimeout'])-- if not formpage['content']:- self.sf.info("Couldn't connect to TORCH, check that you have TOR enabled.")- return None- else:- # Need the form ID to submit later for the search- m = re.findall("\<form method=\"get\" action=\"/(\S+)/search.cgi\"\>",- formpage['content'], re.IGNORECASE | re.DOTALL)- formid = m[0]-- pagecontent = ""- pagecount = 0- p = ""- while "color=gray>next >>" not in pagecontent.lower() and pagecount < self.opts['pages']:- if pagecount > 0:- p = "&np=" + str(pagecount)- pagecount += 1-- # Sites hosted on the domain- data = self.sf.fetchUrl("http://xmh57jrzrnw6insl.onion/" + formid + "/search.cgi?q=" + \- eventData + "&cmd=Search!" + p,- useragent=self.opts['_useragent'],- timeout=self.opts['_fetchtimeout'])- if data is None or not data.get('content'):- self.sf.info("No results returned from TORCH.")- return None-- pagecontent = data['content']-- if "No documents were found" not in data['content']:- # Check if we've been asked to stop- if self.checkForStop():- return None-- # Submit the google results for analysis- evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", data['content'],- self.__name__, event)- self.notifyListeners(evt)-- links = re.findall("\<DT\>\d+.\s+<a href=\"(.*?)\"\s+TARGET=\"_blank\"\>",- data['content'], re.IGNORECASE | re.DOTALL)-- for link in links:- if link in self.results:- continue- else:- self.results.append(link)- self.sf.debug("Found a darknet mention: " + link)- if self.sf.urlFQDN(link).endswith(".onion"):- if self.checkForStop():- return None- if self.opts['fetchlinks']:- res = self.sf.fetchUrl(link, timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])-- if res['content'] is None:- self.sf.debug("Ignoring " + link + " as no data returned")- continue-- if eventData not in res['content']:- self.sf.debug("Ignoring " + link + " as no mention of " + eventData)- continue- evt = SpiderFootEvent("DARKNET_MENTION_URL", link, self.__name__, event)- self.notifyListeners(evt)- else:- evt = SpiderFootEvent("DARKNET_MENTION_URL", link, self.__name__, event)- self.notifyListeners(evt)---# End of sfp_torch class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_torch+# Purpose: Searches the Tor search engine 'TORCH' for content related+# to the domain in question.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 20/06/2017+# Copyright: (c) Steve Micallef 2017+# Licence: GPL+# -------------------------------------------------------------------------------++from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+import re++class sfp_torch(SpiderFootPlugin):+ """TORCH:Footprint,Investigate:Search Engines::Search Tor 'TORCH' search engine for mentions of the target domain."""+++ # Default options+ opts = {+ 'fetchlinks': False,+ 'pages': 20,+ }++ # Option descriptions+ optdescs = {+ 'fetchlinks': "Fetch the darknet pages (via TOR, if enabled) to verify they mention your target.",+ 'pages': "Number of results pages to iterate through."+ }++ # Target+ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["DOMAIN_NAME"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["DARKNET_MENTION_URL", "SEARCH_ENGINE_WEB_CONTENT"]++ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if eventData in self.results:+ self.sf.debug("Already did a search for " + eventData + ", skipping.")+ return None+ else:+ self.results.append(eventData)++ formpage = self.sf.fetchUrl("http://xmh57jrzrnw6insl.onion",+ useragent=self.opts['_useragent'],+ timeout=self.opts['_fetchtimeout'])++ if not formpage['content']:+ self.sf.info("Couldn't connect to TORCH, check that you have TOR enabled.")+ return None+ else:+ # Need the form ID to submit later for the search+ m = re.findall("\<form method=\"get\" action=\"/(\S+)/search.cgi\"\>",+ formpage['content'], re.IGNORECASE | re.DOTALL)+ formid = m[0]++ pagecontent = ""+ pagecount = 0+ p = ""+ while "color=gray>next >>" not in pagecontent.lower() and pagecount < self.opts['pages']:+ if pagecount > 0:+ p = "&np=" + str(pagecount)+ pagecount += 1++ # Sites hosted on the domain+ data = self.sf.fetchUrl("http://xmh57jrzrnw6insl.onion/" + formid + "/search.cgi?q=" + \+ eventData + "&cmd=Search!" + p,+ useragent=self.opts['_useragent'],+ timeout=self.opts['_fetchtimeout'])+ if data is None or not data.get('content'):+ self.sf.info("No results returned from TORCH.")+ return None++ pagecontent = data['content']++ if "No documents were found" not in data['content']:+ # Check if we've been asked to stop+ if self.checkForStop():+ return None++ # Submit the google results for analysis+ evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", data['content'],+ self.__name__, event)+ self.notifyListeners(evt)++ links = re.findall("\<DT\>\d+.\s+<a href=\"(.*?)\"\s+TARGET=\"_blank\"\>",+ data['content'], re.IGNORECASE | re.DOTALL)++ for link in links:+ if link in self.results:+ continue+ else:+ self.results.append(link)+ self.sf.debug("Found a darknet mention: " + link)+ if self.sf.urlFQDN(link).endswith(".onion"):+ if self.checkForStop():+ return None+ if self.opts['fetchlinks']:+ res = self.sf.fetchUrl(link, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])++ if res['content'] is None:+ self.sf.debug("Ignoring " + link + " as no data returned")+ continue++ if eventData not in res['content']:+ self.sf.debug("Ignoring " + link + " as no mention of " + eventData)+ continue+ evt = SpiderFootEvent("DARKNET_MENTION_URL", link, self.__name__, event)+ self.notifyListeners(evt)+ else:+ evt = SpiderFootEvent("DARKNET_MENTION_URL", link, self.__name__, event)+ self.notifyListeners(evt)+++# End of sfp_torch classdiff --git a/modules/sfp_torexits.py b/modules/sfp_torexits.pyindex 321458d3..430a8b22 100644--- a/modules/sfp_torexits.py+++ b/modules/sfp_torexits.py@@ -1,268 +1,269 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_torexits-# 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 Exist List': {- 'id': '_torexits',- 'type': 'list',- 'checks': ['ip', 'netblock'],- 'url': 'https://check.torproject.org/exit-addresses',- 'regex': '^ExitAddress\s+{0}\s+'- }-}---class sfp_torexits(SpiderFootPlugin):- """TOR Exit Nodes:Investigate,Passive:Blacklists:slow:Check if an IP or netblock appears on the torproject.org exit node list."""-- # Default options- opts = {- '_torexits': 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_torexits class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_torexits+# 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 Exist List': {+ 'id': '_torexits',+ 'type': 'list',+ 'checks': ['ip', 'netblock'],+ 'url': 'https://check.torproject.org/exit-addresses',+ 'regex': '^ExitAddress\s+{0}\s+'+ }+}+++class sfp_torexits(SpiderFootPlugin):+ """TOR Exit Nodes:Investigate,Passive:Public Registries:slow:Check if an IP or netblock appears on the torproject.org exit node list."""+++ # Default options+ opts = {+ '_torexits': 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_torexits classdiff --git a/modules/sfp_torserver.py b/modules/sfp_torserver.pyindex 99816a1c..0cc32a14 100644--- a/modules/sfp_torserver.py+++ b/modules/sfp_torserver.py@@ -1,267 +1,268 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_torserver-# Purpose: Checks if an IP or netblock appears on the TOR server 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_torserver(SpiderFootPlugin):- """TOR Servers:Investigate,Passive:Blacklists:slow:Check if an IP or netblock appears on the blutmagie.de TOR server 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_torserver class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_torserver+# Purpose: Checks if an IP or netblock appears on the TOR server 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_torserver(SpiderFootPlugin):+ """TOR Servers:Investigate,Passive:Public Registries:slow:Check if an IP or netblock appears on the blutmagie.de TOR server 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_torserver classdiff --git a/modules/sfp_totalhash.py b/modules/sfp_totalhash.pyindex ff966f9c..ed61d999 100644--- a/modules/sfp_totalhash.py+++ b/modules/sfp_totalhash.py@@ -1,267 +1,268 @@-# -*- 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 class+# -*- 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:Reputation Systems: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_uceprotect.py b/modules/sfp_uceprotect.pyindex 12b2c93d..e61ef38f 100644--- a/modules/sfp_uceprotect.py+++ b/modules/sfp_uceprotect.py@@ -1,155 +1,156 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_uceprotect-# Purpose: SpiderFoot plug-in for looking up whether IPs/Netblocks/Domains-# appear in the UCEPROTECT blacklist, indicating potential open-relays,-# open proxies, malicious servers, vulnerable servers, etc.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 07/01/2014-# Copyright: (c) Steve Micallef 2014-# Licence: GPL-# ---------------------------------------------------------------------------------import socket-from netaddr import IPNetwork-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_uceprotect(SpiderFootPlugin):- """UCEPROTECT:Investigate,Passive:Blacklists::Query the UCEPROTECT databases for open relays, open proxies, vulnerable servers, etc."""-- # Default options- opts = {- 'netblocklookup': True,- 'maxnetblock': 24,- 'subnetlookup': True,- 'maxsubnet': 24- }-- # Option descriptions- optdescs = {- 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible blacklisted hosts on the same target subdomain/domain?",- 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",- 'subnetlookup': "Look up all IPs on subnets which your target is a part of for blacklisting?",- 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"- }-- # Target- results = dict()-- # Whole bunch here:- # http://en.wikipedia.org/wiki/Comparison_of_DNS_blacklists- # Check out:- # http://www.blocklist.de/en/rbldns.html- checks = {- "dnsbl-1.uceprotect.net": 'UCEPROTECT - Level 1 (high likelihood)',- "dnsbl-2.uceprotect.net": 'UCEPROTECT - Level 2 (some false positives)'- }-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ['IP_ADDRESS', 'AFFILIATE_IPADDR', 'NETBLOCK_OWNER',- 'NETBLOCK_MEMBER']-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["BLACKLISTED_IPADDR", "BLACKLISTED_AFFILIATE_IPADDR",- "BLACKLISTED_SUBNET", "BLACKLISTED_NETBLOCK"]-- # Swap 1.2.3.4 to 4.3.2.1- def reverseAddr(self, ipaddr):- return '.'.join(reversed(ipaddr.split('.')))-- def queryAddr(self, qaddr, parentEvent):- eventName = parentEvent.eventType-- for domain in self.checks:- if self.checkForStop():- return None-- try:- lookup = self.reverseAddr(qaddr) + "." + domain- self.sf.debug("Checking Blacklist: " + lookup)- addrs = self.sf.normalizeDNS(socket.gethostbyname_ex(lookup))- self.sf.debug("Addresses returned: " + str(addrs))-- text = None- for addr in addrs:- if type(self.checks[domain]) is str:- text = self.checks[domain] + " (" + qaddr + ")"- break- else:- if str(addr) not in self.checks[domain].keys():- self.sf.debug("Return code not found in list: " + str(addr))- continue-- k = str(addr)- text = self.checks[domain][k] + " (" + qaddr + ")"- break-- if text is not None:- if eventName == "AFFILIATE_IPADDR":- e = "BLACKLISTED_AFFILIATE_IPADDR"- if eventName == "IP_ADDRESS":- e = "BLACKLISTED_IPADDR"- if eventName == "NETBLOCK_OWNER":- e = "BLACKLISTED_NETBLOCK"- if eventName == "NETBLOCK_MEMBER":- e = "BLACKLISTED_SUBNET"-- evt = SpiderFootEvent(e, text, self.__name__, parentEvent)- self.notifyListeners(evt)-- except BaseException as e:- self.sf.debug("Unable to resolve " + qaddr + " / " + lookup + ": " + str(e))-- return None-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- parentEvent = event- addrlist = list()-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- if eventData in self.results:- return None- self.results[eventData] = True-- if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:- if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:- self.sf.debug("Network size bigger than permitted: " +- str(IPNetwork(eventData).prefixlen) + " > " +- str(self.opts['maxnetblock']))- return None-- if eventName == 'NETBLOCK_MEMBER' and self.opts['subnetlookup']:- if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:- self.sf.debug("Network size bigger than permitted: " +- str(IPNetwork(eventData).prefixlen) + " > " +- str(self.opts['maxsubnet']))- return None-- if eventName.startswith("NETBLOCK_"):- for addr in IPNetwork(eventData):- if self.checkForStop():- return None- self.queryAddr(str(addr), parentEvent)- else:- self.queryAddr(eventData, parentEvent)--# End of sfp_uceprotect class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_uceprotect+# Purpose: SpiderFoot plug-in for looking up whether IPs/Netblocks/Domains+# appear in the UCEPROTECT blacklist, indicating potential open-relays,+# open proxies, malicious servers, vulnerable servers, etc.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 07/01/2014+# Copyright: (c) Steve Micallef 2014+# Licence: GPL+# -------------------------------------------------------------------------------++import socket+from netaddr import IPNetwork+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_uceprotect(SpiderFootPlugin):+ """UCEPROTECT:Investigate,Passive:Reputation Systems::Query the UCEPROTECT databases for open relays, open proxies, vulnerable servers, etc."""+++ # Default options+ opts = {+ 'netblocklookup': True,+ 'maxnetblock': 24,+ 'subnetlookup': True,+ 'maxsubnet': 24+ }++ # Option descriptions+ optdescs = {+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible blacklisted hosts on the same target subdomain/domain?",+ 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",+ 'subnetlookup': "Look up all IPs on subnets which your target is a part of for blacklisting?",+ 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"+ }++ # Target+ results = dict()++ # Whole bunch here:+ # http://en.wikipedia.org/wiki/Comparison_of_DNS_blacklists+ # Check out:+ # http://www.blocklist.de/en/rbldns.html+ checks = {+ "dnsbl-1.uceprotect.net": 'UCEPROTECT - Level 1 (high likelihood)',+ "dnsbl-2.uceprotect.net": 'UCEPROTECT - Level 2 (some false positives)'+ }++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ['IP_ADDRESS', 'AFFILIATE_IPADDR', 'NETBLOCK_OWNER',+ 'NETBLOCK_MEMBER']++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["BLACKLISTED_IPADDR", "BLACKLISTED_AFFILIATE_IPADDR",+ "BLACKLISTED_SUBNET", "BLACKLISTED_NETBLOCK"]++ # Swap 1.2.3.4 to 4.3.2.1+ def reverseAddr(self, ipaddr):+ return '.'.join(reversed(ipaddr.split('.')))++ def queryAddr(self, qaddr, parentEvent):+ eventName = parentEvent.eventType++ for domain in self.checks:+ if self.checkForStop():+ return None++ try:+ lookup = self.reverseAddr(qaddr) + "." + domain+ self.sf.debug("Checking Blacklist: " + lookup)+ addrs = self.sf.normalizeDNS(socket.gethostbyname_ex(lookup))+ self.sf.debug("Addresses returned: " + str(addrs))++ text = None+ for addr in addrs:+ if type(self.checks[domain]) is str:+ text = self.checks[domain] + " (" + qaddr + ")"+ break+ else:+ if str(addr) not in self.checks[domain].keys():+ self.sf.debug("Return code not found in list: " + str(addr))+ continue++ k = str(addr)+ text = self.checks[domain][k] + " (" + qaddr + ")"+ break++ if text is not None:+ if eventName == "AFFILIATE_IPADDR":+ e = "BLACKLISTED_AFFILIATE_IPADDR"+ if eventName == "IP_ADDRESS":+ e = "BLACKLISTED_IPADDR"+ if eventName == "NETBLOCK_OWNER":+ e = "BLACKLISTED_NETBLOCK"+ if eventName == "NETBLOCK_MEMBER":+ e = "BLACKLISTED_SUBNET"++ evt = SpiderFootEvent(e, text, self.__name__, parentEvent)+ self.notifyListeners(evt)++ except BaseException as e:+ self.sf.debug("Unable to resolve " + qaddr + " / " + lookup + ": " + str(e))++ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ parentEvent = event+ addrlist = list()++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventData in self.results:+ return None+ self.results[eventData] = True++ if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:+ if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:+ self.sf.debug("Network size bigger than permitted: " ++ str(IPNetwork(eventData).prefixlen) + " > " ++ str(self.opts['maxnetblock']))+ return None++ if eventName == 'NETBLOCK_MEMBER' and self.opts['subnetlookup']:+ if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:+ self.sf.debug("Network size bigger than permitted: " ++ str(IPNetwork(eventData).prefixlen) + " > " ++ str(self.opts['maxsubnet']))+ return None++ if eventName.startswith("NETBLOCK_"):+ for addr in IPNetwork(eventData):+ if self.checkForStop():+ return None+ self.queryAddr(str(addr), parentEvent)+ else:+ self.queryAddr(eventData, parentEvent)++# End of sfp_uceprotect classdiff --git a/modules/sfp_virustotal.py b/modules/sfp_virustotal.pyindex 25076514..ac39a21f 100644--- a/modules/sfp_virustotal.py+++ b/modules/sfp_virustotal.py@@ -1,210 +1,211 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_virustotal-# Purpose: Query VirusTotal for identified IP addresses.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 21/03/2014-# Copyright: (c) Steve Micallef-# Licence: GPL-# ---------------------------------------------------------------------------------import json-import time-from netaddr import IPNetwork-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_virustotal(SpiderFootPlugin):- """VirusTotal:Investigate,Passive:Blacklists:apikey:Obtain information from VirusTotal about identified IP addresses."""-- # Default options- opts = {- "api_key": "",- "publicapi": True,- "checkcohosts": True,- "checkaffiliates": True,- 'netblocklookup': True,- 'maxnetblock': 24,- 'subnetlookup': True,- 'maxsubnet': 24- }-- # Option descriptions- optdescs = {- "api_key": "Your VirusTotal API Key.",- "publicapi": "Are you using a public key? If so SpiderFoot will pause for 15 seconds after each query to avoid VirusTotal dropping requests.",- "checkcohosts": "Check co-hosted sites?",- "checkaffiliates": "Check affiliates?",- 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible hosts on the same target subdomain/domain?",- 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",- 'subnetlookup': "Look up all IPs on subnets which your target is a part of?",- 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"- }-- # Be sure to completely clear any class variables in setup()- # or you run the risk of data persisting between scan runs.-- results = dict()- errorState = False-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- # 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- def watchedEvents(self):- return ["IP_ADDRESS", "AFFILIATE_IPADDR", "INTERNET_NAME",- "CO_HOSTED_SITE", "NETBLOCK_OWNER",- "NETBLOCK_MEMBER"]-- # What events this module produces- def producedEvents(self):- return ["MALICIOUS_IPADDR", "MALICIOUS_INTERNET_NAME",- "MALICIOUS_COHOST", "MALICIOUS_AFFILIATE_INTERNET_NAME",- "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_NETBLOCK",- "MALICIOUS_SUBNET", "INTERNET_NAME", "AFFILIATE_INTERNET_NAME"]-- def query(self, qry):- ret = None-- if self.sf.validIP(qry):- url = "https://www.virustotal.com/vtapi/v2/ip-address/report?ip=" + qry- else:- url = "https://www.virustotal.com/vtapi/v2/domain/report?domain=" + qry-- res = self.sf.fetchUrl(url + "&apikey=" + self.opts['api_key'],- timeout=self.opts['_fetchtimeout'], useragent="SpiderFoot")-- # Public API is limited to 4 queries per minute- if self.opts['publicapi']:- time.sleep(15)-- if res['content'] is None:- self.sf.info("No VirusTotal info found for " + qry)- return None-- try:- ret = json.loads(res['content'])- except Exception as e:- self.sf.error("Error processing JSON response from VirusTotal.", False)- return None-- return ret-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if self.errorState:- return None-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- if self.opts['api_key'] == "":- self.sf.error("You enabled sfp_virustotal but did not set an API key!", False)- self.errorState = True- return None-- # Don't look up stuff twice- if eventData in self.results:- self.sf.debug("Skipping " + eventData + " as already mapped.")- return None- else:- self.results[eventData] = True-- if eventName.startswith("AFFILIATE") and not self.opts['checkaffiliates']:- return None-- if eventName == 'CO_HOSTED_SITE' and not self.opts['checkcohosts']:- return None-- if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:- if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:- self.sf.debug("Network size bigger than permitted: " +- str(IPNetwork(eventData).prefixlen) + " > " +- str(self.opts['maxnetblock']))- return None-- if eventName == 'NETBLOCK_MEMBER' and self.opts['subnetlookup']:- if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:- self.sf.debug("Network size bigger than permitted: " +- str(IPNetwork(eventData).prefixlen) + " > " +- str(self.opts['maxsubnet']))- return None-- qrylist = list()- if eventName.startswith("NETBLOCK_"):- for ipaddr in IPNetwork(eventData):- qrylist.append(str(ipaddr))- self.results[str(ipaddr)] = True- else:- qrylist.append(eventData)-- for addr in qrylist:- if self.checkForStop():- return None-- info = self.query(addr)- if info is None:- continue- if len(info.get('detected_urls', [])) > 0:- self.sf.info("Found VirusTotal URL data for " + addr)- if eventName in ["IP_ADDRESS"] or eventName.startswith("NETBLOCK_"):- evt = "MALICIOUS_IPADDR"- infotype = "ip-address"-- if eventName == "AFFILIATE_IPADDR":- evt = "MALICIOUS_AFFILIATE_IPADDR"- infotype = "ip-address"-- if eventName == "INTERNET_NAME":- evt = "MALICIOUS_INTERNET_NAME"- infotype = "domain"-- if eventName == "AFFILIATE_INTERNET_NAME":- evt = "MALICIOUS_AFFILIATE_INTERNET_NAME"- infotype = "domain"-- if eventName == "CO_HOSTED_SITE":- evt = "MALICIOUS_COHOST"- infotype = "domain"-- infourl = "<SFURL>https://www.virustotal.com/en/" + infotype + "/" + \- addr + "/information/</SFURL>"-- # Notify other modules of what you've found- e = SpiderFootEvent(evt, "VirusTotal [" + addr + "]\n" +- infourl, self.__name__, event)- self.notifyListeners(e)-- # Treat siblings as affiliates if they are of the original target, otherwise- # they are additional hosts within the target.- if 'domain_siblings' in info:- if eventName in [ "IP_ADDRESS", "INTERNET_NAME"]:- for s in info['domain_siblings']:- if self.getTarget().matches(s):- if s not in self.results:- e = SpiderFootEvent("INTERNET_NAME", s, self.__name__, event)- self.notifyListeners(e)- else:- if s not in self.results:- e = SpiderFootEvent("AFFILIATE_INTERNET_NAME", s, self.__name__, event)- self.notifyListeners(e)-- if 'subdomains' in info and eventName == "INTERNET_NAME":- for n in info['subdomains']:- if n not in self.results:- e = SpiderFootEvent("INTERNET_NAME", n, self.__name__, event)- self.notifyListeners(e)--# End of sfp_virustotal class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_virustotal+# Purpose: Query VirusTotal for identified IP addresses.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 21/03/2014+# Copyright: (c) Steve Micallef+# Licence: GPL+# -------------------------------------------------------------------------------++import json+import time+from netaddr import IPNetwork+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_virustotal(SpiderFootPlugin):+ """VirusTotal:Investigate,Passive:Reputation Systems:apikey:Obtain information from VirusTotal about identified IP addresses."""+++ # Default options+ opts = {+ "api_key": "",+ "publicapi": True,+ "checkcohosts": True,+ "checkaffiliates": True,+ 'netblocklookup': True,+ 'maxnetblock': 24,+ 'subnetlookup': True,+ 'maxsubnet': 24+ }++ # Option descriptions+ optdescs = {+ "api_key": "Your VirusTotal API Key.",+ "publicapi": "Are you using a public key? If so SpiderFoot will pause for 15 seconds after each query to avoid VirusTotal dropping requests.",+ "checkcohosts": "Check co-hosted sites?",+ "checkaffiliates": "Check affiliates?",+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible hosts on the same target subdomain/domain?",+ 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",+ 'subnetlookup': "Look up all IPs on subnets which your target is a part of?",+ 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"+ }++ # Be sure to completely clear any class variables in setup()+ # or you run the risk of data persisting between scan runs.++ results = dict()+ errorState = False++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ # 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+ def watchedEvents(self):+ return ["IP_ADDRESS", "AFFILIATE_IPADDR", "INTERNET_NAME",+ "CO_HOSTED_SITE", "NETBLOCK_OWNER",+ "NETBLOCK_MEMBER"]++ # What events this module produces+ def producedEvents(self):+ return ["MALICIOUS_IPADDR", "MALICIOUS_INTERNET_NAME",+ "MALICIOUS_COHOST", "MALICIOUS_AFFILIATE_INTERNET_NAME",+ "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_NETBLOCK",+ "MALICIOUS_SUBNET", "INTERNET_NAME", "AFFILIATE_INTERNET_NAME"]++ def query(self, qry):+ ret = None++ if self.sf.validIP(qry):+ url = "https://www.virustotal.com/vtapi/v2/ip-address/report?ip=" + qry+ else:+ url = "https://www.virustotal.com/vtapi/v2/domain/report?domain=" + qry++ res = self.sf.fetchUrl(url + "&apikey=" + self.opts['api_key'],+ timeout=self.opts['_fetchtimeout'], useragent="SpiderFoot")++ # Public API is limited to 4 queries per minute+ if self.opts['publicapi']:+ time.sleep(15)++ if res['content'] is None:+ self.sf.info("No VirusTotal info found for " + qry)+ return None++ try:+ ret = json.loads(res['content'])+ except Exception as e:+ self.sf.error("Error processing JSON response from VirusTotal.", False)+ return None++ return ret++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if self.errorState:+ return None++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if self.opts['api_key'] == "":+ self.sf.error("You enabled sfp_virustotal but did not set an API key!", False)+ self.errorState = True+ return None++ # Don't look up stuff twice+ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + " as already mapped.")+ return None+ else:+ self.results[eventData] = True++ if eventName.startswith("AFFILIATE") and not self.opts['checkaffiliates']:+ return None++ if eventName == 'CO_HOSTED_SITE' and not self.opts['checkcohosts']:+ return None++ if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:+ if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:+ self.sf.debug("Network size bigger than permitted: " ++ str(IPNetwork(eventData).prefixlen) + " > " ++ str(self.opts['maxnetblock']))+ return None++ if eventName == 'NETBLOCK_MEMBER' and self.opts['subnetlookup']:+ if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:+ self.sf.debug("Network size bigger than permitted: " ++ str(IPNetwork(eventData).prefixlen) + " > " ++ str(self.opts['maxsubnet']))+ return None++ qrylist = list()+ if eventName.startswith("NETBLOCK_"):+ for ipaddr in IPNetwork(eventData):+ qrylist.append(str(ipaddr))+ self.results[str(ipaddr)] = True+ else:+ qrylist.append(eventData)++ for addr in qrylist:+ if self.checkForStop():+ return None++ info = self.query(addr)+ if info is None:+ continue+ if len(info.get('detected_urls', [])) > 0:+ self.sf.info("Found VirusTotal URL data for " + addr)+ if eventName in ["IP_ADDRESS"] or eventName.startswith("NETBLOCK_"):+ evt = "MALICIOUS_IPADDR"+ infotype = "ip-address"++ if eventName == "AFFILIATE_IPADDR":+ evt = "MALICIOUS_AFFILIATE_IPADDR"+ infotype = "ip-address"++ if eventName == "INTERNET_NAME":+ evt = "MALICIOUS_INTERNET_NAME"+ infotype = "domain"++ if eventName == "AFFILIATE_INTERNET_NAME":+ evt = "MALICIOUS_AFFILIATE_INTERNET_NAME"+ infotype = "domain"++ if eventName == "CO_HOSTED_SITE":+ evt = "MALICIOUS_COHOST"+ infotype = "domain"++ infourl = "<SFURL>https://www.virustotal.com/en/" + infotype + "/" + \+ addr + "/information/</SFURL>"++ # Notify other modules of what you've found+ e = SpiderFootEvent(evt, "VirusTotal [" + addr + "]\n" ++ infourl, self.__name__, event)+ self.notifyListeners(e)++ # Treat siblings as affiliates if they are of the original target, otherwise+ # they are additional hosts within the target.+ if 'domain_siblings' in info:+ if eventName in [ "IP_ADDRESS", "INTERNET_NAME"]:+ for s in info['domain_siblings']:+ if self.getTarget().matches(s):+ if s not in self.results:+ e = SpiderFootEvent("INTERNET_NAME", s, self.__name__, event)+ self.notifyListeners(e)+ else:+ if s not in self.results:+ e = SpiderFootEvent("AFFILIATE_INTERNET_NAME", s, self.__name__, event)+ self.notifyListeners(e)++ if 'subdomains' in info and eventName == "INTERNET_NAME":+ for n in info['subdomains']:+ if n not in self.results:+ e = SpiderFootEvent("INTERNET_NAME", n, self.__name__, event)+ self.notifyListeners(e)++# End of sfp_virustotal classdiff --git a/modules/sfp_voipbl.py b/modules/sfp_voipbl.pyindex 6efde6c0..925b65bf 100644--- a/modules/sfp_voipbl.py+++ b/modules/sfp_voipbl.py@@ -1,268 +1,269 @@-# -*- 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 class+# -*- 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:Reputation Systems: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.pyindex f6076b5e..4adc80e5 100644--- a/modules/sfp_vxvault.py+++ b/modules/sfp_vxvault.py@@ -1,268 +1,269 @@-# -*- 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 class+# -*- 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:Reputation Systems: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.pyindex 9e6fd27d..e7733585 100644--- a/modules/sfp_watchguard.py+++ b/modules/sfp_watchguard.py@@ -1,261 +1,262 @@-# -*- 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 class+# -*- 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:Reputation Systems: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/modules/sfp_webframework.py b/modules/sfp_webframework.pyindex 9e44b105..7a78b8d1 100644--- a/modules/sfp_webframework.py+++ b/modules/sfp_webframework.py@@ -1,108 +1,109 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_webframework-# Purpose: Identify the usage of popular web frameworks.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 25/05/2013-# Copyright: (c) Steve Micallef 2013-# Licence: GPL-# ---------------------------------------------------------------------------------import re-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent--regexps = dict({- "jQuery": list(['jquery']), # unlikely false positive- "YUI": list(['\/yui\/', 'yui\-', 'yui\.']),- "Prototype": list(['\/prototype\/', 'prototype\-', 'prototype\.js']),- "ZURB Foundation": list(['\/foundation\/', 'foundation\-', 'foundation\.js']),- "Bootstrap": list(['\/bootstrap\/', 'bootstrap\-', 'bootstrap\.js']),- "ExtJS": list(['[\'\"\=]ext\.js', 'extjs', '\/ext\/*\.js']),- "Mootools": list(['\/mootools\/', 'mootools\-', 'mootools\.js']),- "Dojo": list(['\/dojo\/', '[\'\"\=]dojo\-', '[\'\"\=]dojo\.js']),- "Wordpress": list(['\/wp-includes\/', '\/wp-content\/'])-})---class sfp_webframework(SpiderFootPlugin):- """Web Framework:Footprint:Data Analysis::Identify the usage of popular web frameworks like jQuery, YUI and others."""-- # Default options- opts = {}-- # Option descriptions- optdescs = {- # For each option in opts you should have a key/value pair here- # describing it. It will end up in the UI to explain the option- # to the end-user.- }-- # Target- results = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- 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 ["TARGET_WEB_CONTENT"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["URL_WEB_FRAMEWORK"]-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- # We only want web content- if srcModuleName != "sfp_spider":- return None-- # If you are processing TARGET_WEB_CONTENT, this is how you would get the- # source of that raw data (e.g. a URL.)- eventSource = event.sourceEvent.data-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- if eventSource not in self.results.keys():- self.results[eventSource] = list()-- # We only want web content for pages on the target site- if not self.getTarget().matches(self.sf.urlFQDN(eventSource)):- self.sf.debug("Not collecting web content information for external sites.")- return None-- for regexpGrp in regexps.keys():- if regexpGrp in self.results[eventSource]:- continue-- for regex in regexps[regexpGrp]:- pat = re.compile(regex, re.IGNORECASE)- matches = re.findall(pat, eventData)- if len(matches) > 0 and regexpGrp not in self.results[eventSource]:- self.sf.info("Matched " + regexpGrp + " in content from " + eventSource)- self.results[eventSource].append(regexpGrp)- evt = SpiderFootEvent("URL_WEB_FRAMEWORK", regexpGrp,- self.__name__, event.sourceEvent)- self.notifyListeners(evt)-- return None-- # If you intend for this module to act on its own (e.g. not solely rely- # on events from other modules, then you need to have a start() method- # and within that method call self.checkForStop() to see if you've been- # politely asked by the controller to stop your activities (user abort.)--# End of sfp_webframework class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_webframework+# Purpose: Identify the usage of popular web frameworks.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 25/05/2013+# Copyright: (c) Steve Micallef 2013+# Licence: GPL+# -------------------------------------------------------------------------------++import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent++regexps = dict({+ "jQuery": list(['jquery']), # unlikely false positive+ "YUI": list(['\/yui\/', 'yui\-', 'yui\.']),+ "Prototype": list(['\/prototype\/', 'prototype\-', 'prototype\.js']),+ "ZURB Foundation": list(['\/foundation\/', 'foundation\-', 'foundation\.js']),+ "Bootstrap": list(['\/bootstrap\/', 'bootstrap\-', 'bootstrap\.js']),+ "ExtJS": list(['[\'\"\=]ext\.js', 'extjs', '\/ext\/*\.js']),+ "Mootools": list(['\/mootools\/', 'mootools\-', 'mootools\.js']),+ "Dojo": list(['\/dojo\/', '[\'\"\=]dojo\-', '[\'\"\=]dojo\.js']),+ "Wordpress": list(['\/wp-includes\/', '\/wp-content\/'])+})+++class sfp_webframework(SpiderFootPlugin):+ """Web Framework:Footprint:Content Analysis::Identify the usage of popular web frameworks like jQuery, YUI and others."""+++ # Default options+ opts = {}++ # Option descriptions+ optdescs = {+ # For each option in opts you should have a key/value pair here+ # describing it. It will end up in the UI to explain the option+ # to the end-user.+ }++ # Target+ results = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ 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 ["TARGET_WEB_CONTENT"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["URL_WEB_FRAMEWORK"]++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ # We only want web content+ if srcModuleName != "sfp_spider":+ return None++ # If you are processing TARGET_WEB_CONTENT, this is how you would get the+ # source of that raw data (e.g. a URL.)+ eventSource = event.sourceEvent.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ if eventSource not in self.results.keys():+ self.results[eventSource] = list()++ # We only want web content for pages on the target site+ if not self.getTarget().matches(self.sf.urlFQDN(eventSource)):+ self.sf.debug("Not collecting web content information for external sites.")+ return None++ for regexpGrp in regexps.keys():+ if regexpGrp in self.results[eventSource]:+ continue++ for regex in regexps[regexpGrp]:+ pat = re.compile(regex, re.IGNORECASE)+ matches = re.findall(pat, eventData)+ if len(matches) > 0 and regexpGrp not in self.results[eventSource]:+ self.sf.info("Matched " + regexpGrp + " in content from " + eventSource)+ self.results[eventSource].append(regexpGrp)+ evt = SpiderFootEvent("URL_WEB_FRAMEWORK", regexpGrp,+ self.__name__, event.sourceEvent)+ self.notifyListeners(evt)++ return None++ # If you intend for this module to act on its own (e.g. not solely rely+ # on events from other modules, then you need to have a start() method+ # and within that method call self.checkForStop() to see if you've been+ # politely asked by the controller to stop your activities (user abort.)++# End of sfp_webframework classdiff --git a/modules/sfp_websvr.py b/modules/sfp_websvr.pyindex c35438eb..c6d2063c 100644--- a/modules/sfp_websvr.py+++ b/modules/sfp_websvr.py@@ -1,100 +1,101 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_websvr-# Purpose: SpiderFoot plug-in for scanning retreived content by other-# modules (such as sfp_spider) and identifying web servers used-#-# Author: Steve Micallef <[email protected]>-#-# Created: 06/04/2012-# Copyright: (c) Steve Micallef 2012-# Licence: GPL-# ---------------------------------------------------------------------------------from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_websvr(SpiderFootPlugin):- """Web Server:Footprint,Investigate:Web Spidering::Obtain web server banners to identify versions of web servers being used."""-- # Default options- opts = {}-- results = dict()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = dict()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["WEBSERVER_HTTPHEADERS"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["WEBSERVER_BANNER", "WEBSERVER_TECHNOLOGY"]-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- parentEvent = event.sourceEvent- eventSource = event.sourceEvent.data-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)- if eventSource in self.results:- return None- else:- self.results[eventSource] = True-- if not self.getTarget().matches(self.sf.urlFQDN(eventSource)):- self.sf.debug("Not collecting web server information for external sites.")- return None-- # Could apply some smarts here, for instance looking for certain- # banners and therefore classifying them further (type and version,- # possibly OS. This could also trigger additional tests, such as 404s- # and other errors to see what the header looks like.- if 'server' in eventData:- evt = SpiderFootEvent("WEBSERVER_BANNER", eventData['server'],- self.__name__, parentEvent)- self.notifyListeners(evt)-- self.sf.info("Found web server: " + eventData['server'] + " (" + eventSource + ")")-- if 'x-powered-by' in eventData:- evt = SpiderFootEvent("WEBSERVER_TECHNOLOGY", eventData['x-powered-by'],- self.__name__, parentEvent)- self.notifyListeners(evt)- return None-- tech = None- if 'set-cookie'in eventData and 'PHPSESS' in eventData['set-cookie']:- tech = "PHP"-- if 'set-cookie' in eventData and 'JSESSIONID' in eventData['set-cookie']:- tech = "Java/JSP"-- if 'set-cookie' in eventData and 'ASP.NET' in eventData['set-cookie']:- tech = "ASP.NET"-- if 'x-aspnet-version' in eventData:- tech = "ASP.NET"-- if tech is not None and '.jsp' in eventSource:- tech = "Java/JSP"-- if tech is not None and '.php' in eventSource:- tech = "PHP"-- if tech is not None:- evt = SpiderFootEvent("WEBSERVER_TECHNOLOGY", tech, self.__name__, parentEvent)- self.notifyListeners(evt)--# End of sfp_websvr class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_websvr+# Purpose: SpiderFoot plug-in for scanning retreived content by other+# modules (such as sfp_spider) and identifying web servers used+#+# Author: Steve Micallef <[email protected]>+#+# Created: 06/04/2012+# Copyright: (c) Steve Micallef 2012+# Licence: GPL+# -------------------------------------------------------------------------------++from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_websvr(SpiderFootPlugin):+ """Web Server:Footprint,Investigate:Content Analysis::Obtain web server banners to identify versions of web servers being used."""+++ # Default options+ opts = {}++ results = dict()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = dict()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["WEBSERVER_HTTPHEADERS"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["WEBSERVER_BANNER", "WEBSERVER_TECHNOLOGY"]++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ parentEvent = event.sourceEvent+ eventSource = event.sourceEvent.data++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ if eventSource in self.results:+ return None+ else:+ self.results[eventSource] = True++ if not self.getTarget().matches(self.sf.urlFQDN(eventSource)):+ self.sf.debug("Not collecting web server information for external sites.")+ return None++ # Could apply some smarts here, for instance looking for certain+ # banners and therefore classifying them further (type and version,+ # possibly OS. This could also trigger additional tests, such as 404s+ # and other errors to see what the header looks like.+ if 'server' in eventData:+ evt = SpiderFootEvent("WEBSERVER_BANNER", eventData['server'],+ self.__name__, parentEvent)+ self.notifyListeners(evt)++ self.sf.info("Found web server: " + eventData['server'] + " (" + eventSource + ")")++ if 'x-powered-by' in eventData:+ evt = SpiderFootEvent("WEBSERVER_TECHNOLOGY", eventData['x-powered-by'],+ self.__name__, parentEvent)+ self.notifyListeners(evt)+ return None++ tech = None+ if 'set-cookie'in eventData and 'PHPSESS' in eventData['set-cookie']:+ tech = "PHP"++ if 'set-cookie' in eventData and 'JSESSIONID' in eventData['set-cookie']:+ tech = "Java/JSP"++ if 'set-cookie' in eventData and 'ASP.NET' in eventData['set-cookie']:+ tech = "ASP.NET"++ if 'x-aspnet-version' in eventData:+ tech = "ASP.NET"++ if tech is not None and '.jsp' in eventSource:+ tech = "Java/JSP"++ if tech is not None and '.php' in eventSource:+ tech = "PHP"++ if tech is not None:+ evt = SpiderFootEvent("WEBSERVER_TECHNOLOGY", tech, self.__name__, parentEvent)+ self.notifyListeners(evt)++# End of sfp_websvr classdiff --git a/modules/sfp_whois.py b/modules/sfp_whois.pyindex e6bff12e..38ebb006 100644--- a/modules/sfp_whois.py+++ b/modules/sfp_whois.py@@ -1,92 +1,93 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_whois-# Purpose: SpiderFoot plug-in for searching Whois servers for domain names-# and netblocks identified.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 06/04/2015-# Copyright: (c) Steve Micallef 2012-# Licence: GPL-# ---------------------------------------------------------------------------------import pythonwhois-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_whois(SpiderFootPlugin):- """Whois:Footprint,Investigate,Passive:Networking::Perform a WHOIS look-up on domain names and owned netblocks."""-- # Default options- opts = {- }-- # Option descriptions- optdescs = {- }-- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc-- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["DOMAIN_NAME", "DOMAIN_NAME_PARENT", "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 ["DOMAIN_WHOIS", "NETBLOCK_WHOIS", "DOMAIN_REGISTRAR"]-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if eventData in self.results:- return None- else:- self.results.append(eventData)-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- try:- x = pythonwhois.net.get_whois_raw(eventData)- try:- data = unicode('\n'.join(x), 'utf-8', errors='replace')- except BaseException as e:- data = '\n'.join(x)- except BaseException as e:- self.sf.error("Unable to perform WHOIS on " + eventData + ": " + str(e), False)- return None-- if eventName.startswith("DOMAIN_NAME"):- typ = "DOMAIN_WHOIS"- else:- typ = "NETBLOCK_WHOIS"-- rawevt = SpiderFootEvent(typ, data, self.__name__, event)- self.notifyListeners(rawevt)-- try:- info = pythonwhois.parse.parse_raw_whois(data, True)- except BaseException as e:- self.sf.debug("Error parsing whois data for " + eventData)- return None-- if info.has_key('registrar'):- if eventName.startswith("DOMAIN_NAME") and info['registrar'] is not None:- evt = SpiderFootEvent("DOMAIN_REGISTRAR", info['registrar'][0],- self.__name__, event)- self.notifyListeners(evt)--# End of sfp_whois class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_whois+# Purpose: SpiderFoot plug-in for searching Whois servers for domain names+# and netblocks identified.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 06/04/2015+# Copyright: (c) Steve Micallef 2012+# Licence: GPL+# -------------------------------------------------------------------------------++import pythonwhois+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_whois(SpiderFootPlugin):+ """Whois:Footprint,Investigate,Passive:Public Registries::Perform a WHOIS look-up on domain names and owned netblocks."""+++ # Default options+ opts = {+ }++ # Option descriptions+ optdescs = {+ }++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc++ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["DOMAIN_NAME", "DOMAIN_NAME_PARENT", "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 ["DOMAIN_WHOIS", "NETBLOCK_WHOIS", "DOMAIN_REGISTRAR"]++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if eventData in self.results:+ return None+ else:+ self.results.append(eventData)++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ try:+ x = pythonwhois.net.get_whois_raw(eventData)+ try:+ data = unicode('\n'.join(x), 'utf-8', errors='replace')+ except BaseException as e:+ data = '\n'.join(x)+ except BaseException as e:+ self.sf.error("Unable to perform WHOIS on " + eventData + ": " + str(e), False)+ return None++ if eventName.startswith("DOMAIN_NAME"):+ typ = "DOMAIN_WHOIS"+ else:+ typ = "NETBLOCK_WHOIS"++ rawevt = SpiderFootEvent(typ, data, self.__name__, event)+ self.notifyListeners(rawevt)++ try:+ info = pythonwhois.parse.parse_raw_whois(data, True)+ except BaseException as e:+ self.sf.debug("Error parsing whois data for " + eventData)+ return None++ if info.has_key('registrar'):+ if eventName.startswith("DOMAIN_NAME") and info['registrar'] is not None:+ evt = SpiderFootEvent("DOMAIN_REGISTRAR", info['registrar'][0],+ self.__name__, event)+ self.notifyListeners(evt)++# End of sfp_whois classdiff --git a/modules/sfp_wikileaks.py b/modules/sfp_wikileaks.pyindex d68caab3..d8815548 100644--- a/modules/sfp_wikileaks.py+++ b/modules/sfp_wikileaks.py@@ -1,136 +1,137 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_wikileaks-# Purpose: Searches Wikileaks for mentions of domain names and e-mails.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 16/11/2016-# Copyright: (c) Steve Micallef 2016-# Licence: GPL-# ---------------------------------------------------------------------------------import re-import socket-import datetime-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_wikileaks(SpiderFootPlugin):- """Wikileaks:Footprint,Investigate,Passive:Web Spidering:errorprone:Search Wikileaks for mentions of domain names and e-mail addresses."""-- # Default options- opts = {- 'daysback': 365,- 'external': True- }-- # Option descriptions- optdescs = {- 'daysback': "How many days back to consider a leak valid for capturing. 0 = unlimited.",- 'external': "Include external leak sources such as Associated Twitter accounts, Snowden + Hammond Documents, Cryptome Documents, ICWatch, This Day in WikiLeaks Blog and WikiLeaks Press, WL Central."- }-- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["DOMAIN_NAME", "EMAILADDR"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["LEAKSITE_CONTENT", "LEAKSITE_URL", "SEARCH_ENGINE_WEB_CONTENT"]-- # Handle events sent to this module- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data- self.currentEventSrc = event-- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)-- # Don't look up stuff twice- if eventData in self.results:- self.sf.debug("Skipping " + eventData + " as already mapped.")- return None- else:- self.results.append(eventData)-- if self.opts['external']:- external = "True"- else:- external = ""-- if self.opts['daysback'] != None and self.opts['daysback'] != 0:- newDate = datetime.datetime.now() - datetime.timedelta(days=int(self.opts['daysback']))- maxDate = newDate.strftime("%Y-%m-%d")- else:- maxDate = ""-- wlurl = "https://search.wikileaks.org/?query=%22" + eventData + "%22" + \- "&released_date_start=" + maxDate + "&include_external_sources=" + \- external + "&new_search=True&order_by=most_relevant#results"- res = self.sf.fetchUrl(wlurl)- if res['content'] is None:- self.sf.error("Unable to fetch Wikileaks content.", False)- return None-- # Fetch the paste site content- links = dict()- links.update(self.sf.parseLinks(wlurl, res['content'], "wikileaks.org"))- links.update(self.sf.parseLinks(wlurl, res['content'], "cryptome.org"))- keepGoing = True- page = 0- while keepGoing:- if "page=" not in res['content']:- keepGoing = False-- valid = False- for link in links:- # We can safely skip search.wikileaks.org and others.- if not link.startswith("https://wikileaks.org/") and not link.startswith("https://cryptome.org/"):- continue- else:- self.sf.debug("Found a link: " + link)- if self.checkForStop():- return None-- # Wikileaks leak links will have a nested folder structure link- if link.count('/') >= 4:- if not link.endswith(".js") and not link.endswith(".css"):- evt = SpiderFootEvent("LEAKSITE_URL", link, self.__name__, event)- self.notifyListeners(evt)- valid = True-- if valid:- evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", res['content'],- self.__name__, event)- self.notifyListeners(evt)-- # Fail-safe to prevent infinite looping- if page > 50:- break-- if keepGoing:- page += 1- wlurl = "https://search.wikileaks.org/?query=%22" + eventData + "%22" + \- "&released_date_start=" + maxDate + "&include_external_sources=" + \- external + "&new_search=True&order_by=most_relevant&page=" + \- str(page) + "#results"- res = self.sf.fetchUrl(wlurl)- # Fetch the paste site content- links = dict()- links.update(self.sf.parseLinks(wlurl, res['content'], "wikileaks.org"))- links.update(self.sf.parseLinks(wlurl, res['content'], "cryptome.org"))--# End of sfp_wikileaks class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_wikileaks+# Purpose: Searches Wikileaks for mentions of domain names and e-mails.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 16/11/2016+# Copyright: (c) Steve Micallef 2016+# Licence: GPL+# -------------------------------------------------------------------------------++import re+import socket+import datetime+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_wikileaks(SpiderFootPlugin):+ """Wikileaks:Footprint,Investigate,Passive:Leaks, Dumps and Breaches:errorprone:Search Wikileaks for mentions of domain names and e-mail addresses."""+++ # Default options+ opts = {+ 'daysback': 365,+ 'external': True+ }++ # Option descriptions+ optdescs = {+ 'daysback': "How many days back to consider a leak valid for capturing. 0 = unlimited.",+ 'external': "Include external leak sources such as Associated Twitter accounts, Snowden + Hammond Documents, Cryptome Documents, ICWatch, This Day in WikiLeaks Blog and WikiLeaks Press, WL Central."+ }++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["DOMAIN_NAME", "EMAILADDR"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["LEAKSITE_CONTENT", "LEAKSITE_URL", "SEARCH_ENGINE_WEB_CONTENT"]++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data+ self.currentEventSrc = event++ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ # Don't look up stuff twice+ if eventData in self.results:+ self.sf.debug("Skipping " + eventData + " as already mapped.")+ return None+ else:+ self.results.append(eventData)++ if self.opts['external']:+ external = "True"+ else:+ external = ""++ if self.opts['daysback'] != None and self.opts['daysback'] != 0:+ newDate = datetime.datetime.now() - datetime.timedelta(days=int(self.opts['daysback']))+ maxDate = newDate.strftime("%Y-%m-%d")+ else:+ maxDate = ""++ wlurl = "https://search.wikileaks.org/?query=%22" + eventData + "%22" + \+ "&released_date_start=" + maxDate + "&include_external_sources=" + \+ external + "&new_search=True&order_by=most_relevant#results"+ res = self.sf.fetchUrl(wlurl)+ if res['content'] is None:+ self.sf.error("Unable to fetch Wikileaks content.", False)+ return None++ # Fetch the paste site content+ links = dict()+ links.update(self.sf.parseLinks(wlurl, res['content'], "wikileaks.org"))+ links.update(self.sf.parseLinks(wlurl, res['content'], "cryptome.org"))+ keepGoing = True+ page = 0+ while keepGoing:+ if "page=" not in res['content']:+ keepGoing = False++ valid = False+ for link in links:+ # We can safely skip search.wikileaks.org and others.+ if not link.startswith("https://wikileaks.org/") and not link.startswith("https://cryptome.org/"):+ continue+ else:+ self.sf.debug("Found a link: " + link)+ if self.checkForStop():+ return None++ # Wikileaks leak links will have a nested folder structure link+ if link.count('/') >= 4:+ if not link.endswith(".js") and not link.endswith(".css"):+ evt = SpiderFootEvent("LEAKSITE_URL", link, self.__name__, event)+ self.notifyListeners(evt)+ valid = True++ if valid:+ evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", res['content'],+ self.__name__, event)+ self.notifyListeners(evt)++ # Fail-safe to prevent infinite looping+ if page > 50:+ break++ if keepGoing:+ page += 1+ wlurl = "https://search.wikileaks.org/?query=%22" + eventData + "%22" + \+ "&released_date_start=" + maxDate + "&include_external_sources=" + \+ external + "&new_search=True&order_by=most_relevant&page=" + \+ str(page) + "#results"+ res = self.sf.fetchUrl(wlurl)+ # Fetch the paste site content+ links = dict()+ links.update(self.sf.parseLinks(wlurl, res['content'], "wikileaks.org"))+ links.update(self.sf.parseLinks(wlurl, res['content'], "cryptome.org"))++# End of sfp_wikileaks classdiff --git a/modules/sfp_xforce.py b/modules/sfp_xforce.pyindex 2b52e064..428cc3b6 100644--- a/modules/sfp_xforce.py+++ b/modules/sfp_xforce.py@@ -19,7 +19,8 @@ from netaddr import IPNetworkfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEventclass sfp_xforce(SpiderFootPlugin):- """XForce Exchange:Investigate,Passive:Blacklists:apikey:Obtain information from IBM X-Force Exchange"""+ """XForce Exchange:Investigate,Passive:Reputation Systems:apikey:Obtain information from IBM X-Force Exchange"""+# Default optionsopts = {diff --git a/modules/sfp_yahoosearch.py b/modules/sfp_yahoosearch.pyindex 5d8a1b6d..b219ee1e 100644--- a/modules/sfp_yahoosearch.py+++ b/modules/sfp_yahoosearch.py@@ -1,107 +1,108 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_yahoosearch-# Purpose: Searches Yahoo for content related to the domain in question.-#-# Author: Steve Micallef <[email protected]>-#-# Created: 12/04/2014-# Copyright: (c) Steve Micallef 2014-# Licence: GPL-# ---------------------------------------------------------------------------------import re-import urllib-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_yahoosearch(SpiderFootPlugin):- """Yahoo:Footprint,Investigate,Passive:Search Engines:errorprone:Some light Yahoo scraping to identify sub-domains and links."""-- # Default options- opts = {- 'pages': 20 # Number of yahoo results pages to iterate- }-- # Option descriptions- optdescs = {- 'pages': "Number of Yahoo results pages to iterate through."- }-- results = list()-- def setup(self, sfc, userOpts=dict()):- self.sf = sfc- self.results = list()-- for opt in userOpts.keys():- self.opts[opt] = userOpts[opt]-- # What events is this module interested in for input- def watchedEvents(self):- return ["INTERNET_NAME"]-- # What events this module produces- # This is to support the end user in selecting modules based on events- # produced.- def producedEvents(self):- return ["LINKED_URL_INTERNAL", "SEARCH_ENGINE_WEB_CONTENT"]-- def yahooCleaner(self, string):- return " url=\"" + urllib.unquote(string.group(1)) + "\" "-- def handleEvent(self, event):- eventName = event.eventType- srcModuleName = event.module- eventData = event.data-- if eventData in self.results:- self.sf.debug("Already did a search for " + eventData + ", skipping.")- return None- else:- self.results.append(eventData)-- # Sites hosted on the domain- pages = self.sf.yahooIterate("site:" + eventData, dict(limit=self.opts['pages'],- useragent=self.opts['_useragent'],- timeout=self.opts['_fetchtimeout']))- if pages is None:- self.sf.info("No results returned from Yahoo.")- return None-- for page in pages.keys():- found = False- if page in self.results:- continue- else:- self.results.append(page)-- content = re.sub("RU=(.[^\/]+)\/RK=", self.yahooCleaner, pages[page])- links = self.sf.parseLinks(page, content, eventData)- if len(links) == 0:- continue-- for link in links:- if self.checkForStop():- return None-- if link in self.results:- continue- else:- self.results.append(link)- if self.sf.urlFQDN(link).endswith(eventData):- found = True- self.sf.debug("Found a link: " + link)-- evt = SpiderFootEvent("LINKED_URL_INTERNAL", link,- self.__name__, event)- self.notifyListeners(evt)-- if found:- # Submit the yahoo results for analysis- evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", content,- self.__name__, event)- self.notifyListeners(evt)---# End of sfp_yahoosearch class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_yahoosearch+# Purpose: Searches Yahoo for content related to the domain in question.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 12/04/2014+# Copyright: (c) Steve Micallef 2014+# Licence: GPL+# -------------------------------------------------------------------------------++import re+import urllib+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_yahoosearch(SpiderFootPlugin):+ """Yahoo:Footprint,Investigate,Passive:Search Engines:errorprone:Some light Yahoo scraping to identify sub-domains and links."""+++ # Default options+ opts = {+ 'pages': 20 # Number of yahoo results pages to iterate+ }++ # Option descriptions+ optdescs = {+ 'pages': "Number of Yahoo results pages to iterate through."+ }++ results = list()++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = list()++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["INTERNET_NAME"]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return ["LINKED_URL_INTERNAL", "SEARCH_ENGINE_WEB_CONTENT"]++ def yahooCleaner(self, string):+ return " url=\"" + urllib.unquote(string.group(1)) + "\" "++ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ if eventData in self.results:+ self.sf.debug("Already did a search for " + eventData + ", skipping.")+ return None+ else:+ self.results.append(eventData)++ # Sites hosted on the domain+ pages = self.sf.yahooIterate("site:" + eventData, dict(limit=self.opts['pages'],+ useragent=self.opts['_useragent'],+ timeout=self.opts['_fetchtimeout']))+ if pages is None:+ self.sf.info("No results returned from Yahoo.")+ return None++ for page in pages.keys():+ found = False+ if page in self.results:+ continue+ else:+ self.results.append(page)++ content = re.sub("RU=(.[^\/]+)\/RK=", self.yahooCleaner, pages[page])+ links = self.sf.parseLinks(page, content, eventData)+ if len(links) == 0:+ continue++ for link in links:+ if self.checkForStop():+ return None++ if link in self.results:+ continue+ else:+ self.results.append(link)+ if self.sf.urlFQDN(link).endswith(eventData):+ found = True+ self.sf.debug("Found a link: " + link)++ evt = SpiderFootEvent("LINKED_URL_INTERNAL", link,+ self.__name__, event)+ self.notifyListeners(evt)++ if found:+ # Submit the yahoo results for analysis+ evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", content,+ self.__name__, event)+ self.notifyListeners(evt)+++# End of sfp_yahoosearch classdiff --git a/modules/sfp_zoneh.py b/modules/sfp_zoneh.pyindex 86437c64..a5d249d4 100644--- a/modules/sfp_zoneh.py+++ b/modules/sfp_zoneh.py@@ -1,126 +1,127 @@-# -*- coding: utf-8 -*--# --------------------------------------------------------------------------------# Name: sfp_zoneh-# Purpose: Checks if a domain or IP appears on the zone-h.org defacement-# archive.-#-# Author: [email protected]-#-# Created: 09/01/2014-# Copyright: (c) Steve Micallef, 2014-# Licence: GPL-# ---------------------------------------------------------------------------------import time-import re-from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent---class sfp_zoneh(SpiderFootPlugin):- """Zone-H Defacement Check:Investigate,Passive:Search Engines::Check if a hostname/domain appears on the zone-h.org 'special defacements' RSS feed."""-- # Default options- opts = {- 'checkcohosts': True,- 'checkaffiliates': True- }-- # Option descriptions- optdescs = {- 'checkcohosts': "Check co-hosted sites?",- 'checkaffiliates': "Check 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 ["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 ["DEFACED_INTERNET_NAME", "DEFACED_IPADDR",- "DEFACED_AFFILIATE_INTERNET_NAME",- "DEFACED_COHOST", "DEFACED_AFFILIATE_IPADDR"]-- def lookupItem(self, target, content):- grps = re.findall("<title><\!\[CDATA\[(.[^\]]*)\]\]></title>\s+<link><\!\[CDATA\[(.[^\]]*)\]\]></link>", content)- for m in grps:- if target in m[0]:- self.sf.info("Found zoneh site: " + m[0])- return m[0] + "\n<SFURL>" + m[1] + "</SFURL>"-- return False-- # 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['checkcohosts']:- return None- if eventName == 'AFFILIATE_INTERNET_NAME' or eventName == 'AFFILIATE_IPADDR' \- and not self.opts['checkaffiliates']:- return None-- evtType = 'DEFACED_INTERNET_NAME'-- if eventName == 'IP_ADDRESS':- evtType = 'DEFACED_IPADDR'-- if eventName == 'CO_HOSTED_SITE':- evtType = 'DEFACED_COHOST'-- if eventName == 'AFFILIATE_INTERNET_NAME':- evtType = 'DEFACED_AFFILIATE_INTERNET_NAME'-- if eventName == 'AFFILIATE_IPADDR':- evtType = 'DEFACED_AFFILIATE_IPADDR'-- if self.checkForStop():- return None-- url = "http://www.zone-h.org/rss/specialdefacements"- content = self.sf.cacheGet("sfzoneh", 48)- if 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("sfzoneh", data['content'])- content = data['content']-- ret = self.lookupItem(eventData, content)- if ret:- evt = SpiderFootEvent(evtType, ret, self.__name__, event)- self.notifyListeners(evt)--# End of sfp_zoneh class+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_zoneh+# Purpose: Checks if a domain or IP appears on the zone-h.org defacement+# archive.+#+# Author: [email protected]+#+# Created: 09/01/2014+# Copyright: (c) Steve Micallef, 2014+# Licence: GPL+# -------------------------------------------------------------------------------++import time+import re+from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+++class sfp_zoneh(SpiderFootPlugin):+ """Zone-H Defacement Check:Investigate,Passive:Leaks, Dumps and Breaches::Check if a hostname/domain appears on the zone-h.org 'special defacements' RSS feed."""+++ # Default options+ opts = {+ 'checkcohosts': True,+ 'checkaffiliates': True+ }++ # Option descriptions+ optdescs = {+ 'checkcohosts': "Check co-hosted sites?",+ 'checkaffiliates': "Check 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 ["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 ["DEFACED_INTERNET_NAME", "DEFACED_IPADDR",+ "DEFACED_AFFILIATE_INTERNET_NAME",+ "DEFACED_COHOST", "DEFACED_AFFILIATE_IPADDR"]++ def lookupItem(self, target, content):+ grps = re.findall("<title><\!\[CDATA\[(.[^\]]*)\]\]></title>\s+<link><\!\[CDATA\[(.[^\]]*)\]\]></link>", content)+ for m in grps:+ if target in m[0]:+ self.sf.info("Found zoneh site: " + m[0])+ return m[0] + "\n<SFURL>" + m[1] + "</SFURL>"++ return False++ # 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['checkcohosts']:+ return None+ if eventName == 'AFFILIATE_INTERNET_NAME' or eventName == 'AFFILIATE_IPADDR' \+ and not self.opts['checkaffiliates']:+ return None++ evtType = 'DEFACED_INTERNET_NAME'++ if eventName == 'IP_ADDRESS':+ evtType = 'DEFACED_IPADDR'++ if eventName == 'CO_HOSTED_SITE':+ evtType = 'DEFACED_COHOST'++ if eventName == 'AFFILIATE_INTERNET_NAME':+ evtType = 'DEFACED_AFFILIATE_INTERNET_NAME'++ if eventName == 'AFFILIATE_IPADDR':+ evtType = 'DEFACED_AFFILIATE_IPADDR'++ if self.checkForStop():+ return None++ url = "http://www.zone-h.org/rss/specialdefacements"+ content = self.sf.cacheGet("sfzoneh", 48)+ if 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("sfzoneh", data['content'])+ content = data['content']++ ret = self.lookupItem(eventData, content)+ if ret:+ evt = SpiderFootEvent(evtType, ret, self.__name__, event)+ self.notifyListeners(evt)++# End of sfp_zoneh class