SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.
Python attacksurfacecticybersecurityfootprintinghackinginformation-gatheringinformation-securityinfosecintelligence-gatheringosintosint-frameworkosint-reconnaissanceosint-toolpentestingpythonreconsecurity-toolsthreat-intelligencethreatintel
Simultaneous scanning support and memory leak clean-ups.
smicallef2df781f15b94
diff --git a/modules/sfp__stor_db.py b/modules/sfp__stor_db.pyindex 6f396b23..014b0613 100644--- a/modules/sfp__stor_db.py+++ b/modules/sfp__stor_db.py@@ -14,10 +14,6 @@ import sysimport refrom sflib import SpiderFoot, SpiderFootPlugin-# SpiderFoot standard lib (must be initialized in setup)-sf = None-sfdb = None-class sfp__stor_db(SpiderFootPlugin):"""Storage:Stores scan results into the back-end SpiderFoot database. You will need this."""@@ -32,18 +28,11 @@ class sfp__stor_db(SpiderFootPlugin):}def setup(self, sfc, userOpts=dict()):- global sf- global sfdb-- sf = sfc+ self.sf = sfcfor opt in userOpts.keys():self.opts[opt] = userOpts[opt]- # Use the database handle passed to us- # Should change to get the DBH out of sfc- sfdb = userOpts['__sfdb__']-# 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.@@ -54,12 +43,12 @@ class sfp__stor_db(SpiderFootPlugin):def handleEvent(self, sfEvent):if self.opts['maxstorage'] != 0:if len(sfEvent.data) > self.opts['maxstorage']:- sf.debug("Storing an event: " + sfEvent.eventType)- sfdb.scanEventStore(self.opts['__guid__'], sfEvent, self.opts['maxstorage'])+ self.sf.debug("Storing an event: " + sfEvent.eventType)+ self.__sfdb__.scanEventStore(self.getScanId(), sfEvent, self.opts['maxstorage'])return None- sf.debug("Storing an event: " + sfEvent.eventType)- sfdb.scanEventStore(self.opts['__guid__'], sfEvent)+ self.sf.debug("Storing an event: " + sfEvent.eventType)+ self.__sfdb__.scanEventStore(self.getScanId(), sfEvent)# End of sfp__stor_db classdiff --git a/modules/sfp_bingsearch.py b/modules/sfp_bingsearch.pyindex f3030ffd..4edcbe68 100644--- a/modules/sfp_bingsearch.py+++ b/modules/sfp_bingsearch.py@@ -15,9 +15,6 @@ import reimport timefrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_bingsearch(SpiderFootPlugin):"""Bing:Some light Bing scraping to identify sub-domains and links."""@@ -36,9 +33,7 @@ class sfp_bingsearch(SpiderFootPlugin):results = list()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = list()for opt in userOpts.keys():@@ -60,16 +55,16 @@ class sfp_bingsearch(SpiderFootPlugin):eventData = event.dataif eventData in self.results:- sf.debug("Already did a search for " + eventData + ", skipping.")+ self.sf.debug("Already did a search for " + eventData + ", skipping.")return Noneelse:self.results.append(eventData)# Sites hosted on the domain- pages = sf.bingIterate("site:" + eventData, dict(limit=self.opts['pages'],+ pages = self.sf.bingIterate("site:" + eventData, dict(limit=self.opts['pages'],useragent=self.opts['_useragent'], timeout=self.opts['_fetchtimeout']))if pages == None:- sf.info("No results returned from Bing.")+ self.sf.info("No results returned from Bing.")return Nonefor page in pages.keys():@@ -89,7 +84,7 @@ class sfp_bingsearch(SpiderFootPlugin):# We can optionally fetch links to our domain found in the search# results. These may not have been identified through spidering.if self.opts['fetchlinks']:- links = sf.parseLinks(page, pages[page], eventData)+ links = self.sf.parseLinks(page, pages[page], eventData)if len(links) == 0:continue@@ -98,8 +93,8 @@ class sfp_bingsearch(SpiderFootPlugin):continueelse:self.results.append(link)- if sf.urlFQDN(link).endswith(eventData):- sf.debug("Found a link: " + link)+ if self.sf.urlFQDN(link).endswith(eventData):+ self.sf.debug("Found a link: " + link)if self.checkForStop():return Nonediff --git a/modules/sfp_blacklist.py b/modules/sfp_blacklist.pyindex 8cc6478b..29560971 100644--- a/modules/sfp_blacklist.py+++ b/modules/sfp_blacklist.py@@ -17,9 +17,6 @@ import socketimport randomfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_blacklist(SpiderFootPlugin):"""Blacklist: Query various blacklist database for open relays, open proxies, vulnerable servers, etc."""@@ -75,9 +72,7 @@ class sfp_blacklist(SpiderFootPlugin):}def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = dict()for opt in userOpts.keys():@@ -104,7 +99,7 @@ class sfp_blacklist(SpiderFootPlugin):eventData = event.dataparentEvent = event- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)if self.results.has_key(eventData):return None@@ -114,9 +109,9 @@ class sfp_blacklist(SpiderFootPlugin):for domain in self.checks:try:lookup = self.reverseAddr(eventData) + "." + domain- sf.debug("Checking Blacklist: " + lookup)+ self.sf.debug("Checking Blacklist: " + lookup)addrs = socket.gethostbyname_ex(lookup)- sf.debug("Addresses returned: " + str(addrs))+ self.sf.debug("Addresses returned: " + str(addrs))text = Nonefor addr in addrs:@@ -127,7 +122,7 @@ class sfp_blacklist(SpiderFootPlugin):breakelse:if str(a) not in self.checks[domain].keys():- sf.debug("Return code not found in list: " + str(a))+ self.sf.debug("Return code not found in list: " + str(a))continuek = str(a)text = self.checks[domain][k]@@ -139,7 +134,7 @@ class sfp_blacklist(SpiderFootPlugin):breakelse:if str(addr) not in self.checks.keys():- sf.debug("Return code not found in list: " + str(addr))+ self.sf.debug("Return code not found in list: " + str(addr))continuek = str(addr)@@ -156,7 +151,7 @@ class sfp_blacklist(SpiderFootPlugin):text, self.__name__, parentEvent)self.notifyListeners(evt)except BaseException as e:- sf.debug("Unable to resolve " + eventData + " / " + lookup + ": " + str(e))+ self.sf.debug("Unable to resolve " + eventData + " / " + lookup + ": " + str(e))return Nonediff --git a/modules/sfp_cookie.py b/modules/sfp_cookie.pyindex 15e7ede1..40926d4e 100644--- a/modules/sfp_cookie.py+++ b/modules/sfp_cookie.py@@ -13,9 +13,6 @@ import sysimport refrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_cookie(SpiderFootPlugin):"""Cookies:Extract Cookies from HTTP headers."""@@ -25,9 +22,7 @@ class sfp_cookie(SpiderFootPlugin):results = dict()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = dict()for opt in userOpts.keys():@@ -51,14 +46,14 @@ class sfp_cookie(SpiderFootPlugin):parentEvent = event.sourceEventeventSource = event.sourceEvent.data- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)if self.results.has_key(eventSource):return Noneelse:self.results[eventSource] = True- if not self.getTarget().matches(sf.urlFQDN(eventSource)):- sf.debug("Not collecting cookies from external sites.")+ if not self.getTarget().matches(self.sf.urlFQDN(eventSource)):+ self.sf.debug("Not collecting cookies from external sites.")return Noneif eventData.has_key('set-cookie'):diff --git a/modules/sfp_crossref.py b/modules/sfp_crossref.pyindex dbc7d8da..a3113b29 100644--- a/modules/sfp_crossref.py+++ b/modules/sfp_crossref.py@@ -16,9 +16,6 @@ import sysimport refrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_crossref(SpiderFootPlugin):"""Cross-Reference:Identify whether other domains are associated ('Affiliates') of the target."""@@ -37,9 +34,7 @@ class sfp_crossref(SpiderFootPlugin):fetched = list()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = dict()self.fetched = list()@@ -64,7 +59,7 @@ class sfp_crossref(SpiderFootPlugin):srcModuleName = event.moduleeventData = event.data- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)# The SIMILARDOMAIN and CO_HOSTED_SITE events supply domains,# not URLs. Assume HTTP.@@ -72,22 +67,22 @@ class sfp_crossref(SpiderFootPlugin):eventData = 'http://'+ eventData.lower()# We are only interested in external sites for the crossref- if self.getTarget().matches(sf.urlFQDN(eventData)):- sf.debug("Ignoring " + eventData + " as not external")+ if self.getTarget().matches(self.sf.urlFQDN(eventData)):+ self.sf.debug("Ignoring " + eventData + " as not external")return Noneif eventData in self.fetched:- sf.debug("Ignoring " + eventData + " as already tested")+ self.sf.debug("Ignoring " + eventData + " as already tested")returnelse:self.fetched.append(eventData)- sf.debug("Testing for affiliation: " + eventData)- res = sf.fetchUrl(eventData, timeout=self.opts['_fetchtimeout'],+ self.sf.debug("Testing for affiliation: " + eventData)+ res = self.sf.fetchUrl(eventData, timeout=self.opts['_fetchtimeout'],useragent=self.opts['_useragent'])if res['content'] == None:- sf.debug("Ignoring " + eventData + " as no data returned")+ self.sf.debug("Ignoring " + eventData + " as no data returned")return Nonematched = False@@ -106,13 +101,13 @@ class sfp_crossref(SpiderFootPlugin):# 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 = sf.urlBaseUrl(eventData)+ url = self.sf.urlBaseUrl(eventData)if url in self.fetched:return Noneelse:self.fetched.append(url)- res = sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],useragent=self.opts['_useragent'])if res['content'] != None:for name in self.getTarget().getNames():@@ -124,8 +119,8 @@ class sfp_crossref(SpiderFootPlugin):matched = Trueif matched:- sf.info("Found affiliate: " + url)- evt1 = SpiderFootEvent("AFFILIATE_INTERNET_NAME", sf.urlFQDN(url),+ 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'],diff --git a/modules/sfp_defaced.py b/modules/sfp_defaced.pyindex e6748b12..adbc9c42 100644--- a/modules/sfp_defaced.py+++ b/modules/sfp_defaced.py@@ -15,9 +15,6 @@ import timeimport refrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_defaced(SpiderFootPlugin):"""Defacement Check:Check if an IP or domain appears on the zone-h.org defacement archive."""@@ -41,9 +38,7 @@ class sfp_defaced(SpiderFootPlugin):results = list()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = list()# Clear / reset any other class member variables here@@ -71,24 +66,24 @@ class sfp_defaced(SpiderFootPlugin):found = FalsecurDate = time.strftime("%Y%m%d")url = "http://www.zone-h.org/archive/" + typeId + "=" + target- res = sf.fetchUrl(url, useragent=self.opts['_useragent'])+ res = self.sf.fetchUrl(url, useragent=self.opts['_useragent'])if res['content'] == None:- sf.debug("Unable to fetch data from Zone-H for " + target + "(" + typeId + ")")+ self.sf.debug("Unable to fetch data from Zone-H for " + target + "(" + typeId + ")")return Noneif "<img id='cryptogram' src='/captcha.py'>" in res['content']:- sf.error("CAPTCHA returned from zone-h.org.", False)+ self.sf.error("CAPTCHA returned from zone-h.org.", False)return Nonerx = re.compile("<td>(\d+/\d+/\d+)</td>", re.IGNORECASE|re.DOTALL)grps = re.findall(rx, res['content'])for m in grps:- sf.debug("Found defaced site: " + target + "(" + typeId + ")")+ self.sf.debug("Found defaced site: " + target + "(" + typeId + ")")found = True# Zone-H returns in YYYY/MM/DDdate = m.replace('/', '')if int(date) < int(curDate)-30:- sf.debug("Defaced site found but too old: " + date)+ self.sf.debug("Defaced site found but too old: " + date)found = Falsecontinue@@ -103,10 +98,10 @@ class sfp_defaced(SpiderFootPlugin):srcModuleName = event.moduleeventData = event.data- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)if eventData in self.results:- sf.debug("Skipping " + eventData + ", already checked.")+ self.sf.debug("Skipping " + eventData + ", already checked.")return Noneelse:self.results.append(eventData)diff --git a/modules/sfp_dns.py b/modules/sfp_dns.pyindex a1e4aab0..7f76e8d7 100644--- a/modules/sfp_dns.py+++ b/modules/sfp_dns.py@@ -20,9 +20,6 @@ import dnsfrom netaddr import IPAddress, IPNetworkfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_dns(SpiderFootPlugin):"""DNS:Performs a number of DNS checks to obtain Sub-domains/Hostnames, IP Addresses and Affiliates."""@@ -62,9 +59,7 @@ class sfp_dns(SpiderFootPlugin):resolveCache = dict()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.events = dict()self.domresults = dict()self.hostresults = dict()@@ -78,7 +73,7 @@ class sfp_dns(SpiderFootPlugin):if self.opts['commonsubs'][0].startswith("http://") or \self.opts['commonsubs'][0].startswith("https://") or \self.opts['commonsubs'][0].startswith("@"):- self.sublist = sf.optValueToData(self.opts['commonsubs'][0])+ self.sublist = self.sf.optValueToData(self.opts['commonsubs'][0])def enrichTarget(self, target):ret = list()@@ -109,7 +104,7 @@ class sfp_dns(SpiderFootPlugin):ret.extend(names)for host in ret:- if sf.validIP(host):+ if self.sf.validIP(host):target.setAlias(host, "IP_ADDRESS")else:target.setAlias(host, "INTERNET_NAME")@@ -117,10 +112,10 @@ class sfp_dns(SpiderFootPlugin):# 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 = sf.hostDomain(host, self.opts['_internettlds'])+ dom = self.sf.hostDomain(host, self.opts['_internettlds'])target.setAlias(dom, "INTERNET_NAME")- sf.debug("Aliases identified: " + str(target.getAliases()))+ self.sf.debug("Aliases identified: " + str(target.getAliases()))return target@@ -146,7 +141,7 @@ class sfp_dns(SpiderFootPlugin):addrs = NoneparentEvent = event- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)if self.events.has_key(eventData):return None@@ -176,12 +171,12 @@ class sfp_dns(SpiderFootPlugin):return Noneif IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:- sf.debug("Network size bigger than permitted: " + \+ self.sf.debug("Network size bigger than permitted: " + \str(IPNetwork(eventData).prefixlen) + " > " + \str(self.opts['maxnetblock']))return None- sf.debug("Looking up IPs in " + eventData)+ self.sf.debug("Looking up IPs in " + eventData)for ip in IPNetwork(eventData):ipaddr = str(ip)if ipaddr.split(".")[3] in [ '255', '0']:@@ -194,7 +189,7 @@ class sfp_dns(SpiderFootPlugin):addrs = self.resolveIP(ipaddr)if len(addrs) > 0:- sf.debug("Found a reversed hostname from " + ipaddr + \+ self.sf.debug("Found a reversed hostname from " + ipaddr + \" (" + str(addrs) + ")")for addr in addrs:# Don't report on anything on the same subnet if@@ -216,7 +211,7 @@ class sfp_dns(SpiderFootPlugin):if eventName != 'IP_ADDRESS':if '://' in eventData:- addrs = self.resolveHost(sf.urlFQDN(eventData))+ addrs = self.resolveHost(self.sf.urlFQDN(eventData))else:addrs = self.resolveHost(eventData)else:@@ -230,7 +225,7 @@ class sfp_dns(SpiderFootPlugin):ip = IPAddress(eventData)minip = IPAddress(int(ip) - self.opts['lookasidecount'])maxip = IPAddress(int(ip) + self.opts['lookasidecount'])- sf.debug("Lookaside max: " + str(maxip) + ", min: " + str(minip))+ self.sf.debug("Lookaside max: " + str(maxip) + ", min: " + str(minip))s = int(minip)c = int(maxip)while s <= c:@@ -244,7 +239,7 @@ class sfp_dns(SpiderFootPlugin):addrs = self.resolveIP(sip)if len(addrs) == 0:- sf.debug("Look-aside resolve for " + sip + " failed.")+ self.sf.debug("Look-aside resolve for " + sip + " failed.")s = s + 1continue@@ -263,35 +258,35 @@ class sfp_dns(SpiderFootPlugin):# Resolve an IPdef resolveIP(self, ipaddr):ret = list()- sf.debug("Performing reverse-resolve of " + ipaddr)+ self.sf.debug("Performing reverse-resolve of " + ipaddr)if self.resolveCache.has_key(ipaddr):- sf.debug("Returning cached result for " + ipaddr + " (" + \+ self.sf.debug("Returning cached result for " + ipaddr + " (" + \str(self.resolveCache[ipaddr]) + ")")return self.resolveCache[ipaddr]try:- addrs = sf.normalizeDNS(socket.gethostbyaddr(ipaddr))+ addrs = self.sf.normalizeDNS(socket.gethostbyaddr(ipaddr))self.resolveCache[ipaddr] = addrsreturn addrsexcept BaseException as e:- sf.info("Unable to resolve " + ipaddr + " (" + str(e) + ")")+ self.sf.info("Unable to resolve " + ipaddr + " (" + str(e) + ")")self.resolveCache[ipaddr] = list()return ret# Resolve a hostdef resolveHost(self, hostname):if self.resolveCache.has_key(hostname):- sf.debug("Returning cached result for " + hostname + " (" + \+ self.sf.debug("Returning cached result for " + hostname + " (" + \str(self.resolveCache[hostname]) + ")" )return self.resolveCache[hostname]try:- addrs = sf.normalizeDNS(socket.gethostbyname_ex(hostname))+ addrs = self.sf.normalizeDNS(socket.gethostbyname_ex(hostname))self.resolveCache[hostname] = addrsreturn addrsexcept BaseException as e:- sf.info("Unable to resolve " + hostname + " (" + str(e) + ")")+ self.sf.info("Unable to resolve " + hostname + " (" + str(e) + ")")return list()def processHost(self, host, parentEvent):@@ -299,12 +294,12 @@ class sfp_dns(SpiderFootPlugin):self.hostresults[host] = list(parentEvent.data)else:if parentEvent.data in self.hostresults[host]:- sf.debug("Skipping host, " + host + ", already processed.")+ self.sf.debug("Skipping host, " + host + ", already processed.")return Noneelse:self.hostresults[host].append(parentEvent.data)- sf.debug("Found host: " + host)+ self.sf.debug("Found host: " + host)# If the returned hostname is aliaseed to our# target in some way, flag it as an affiliateaffil = True@@ -312,18 +307,18 @@ class sfp_dns(SpiderFootPlugin):affil = False# If the IP the host resolves to is in our# list of aliases,- if not sf.validIP(host):+ if not self.sf.validIP(host):for hostip in self.resolveHost(host):if self.getTarget().matches(hostip):affil = Falseif affil:- if sf.validIP(host):+ if self.sf.validIP(host):htype = "AFFILIATE_IPADDR"else:htype = "AFFILIATE_INTERNET_NAME"else:- if sf.validIP(host):+ if self.sf.validIP(host):htype = "IP_ADDRESS"else:htype = "INTERNET_NAME"@@ -342,7 +337,7 @@ class sfp_dns(SpiderFootPlugin):self.notifyListeners(evt)# Report the domain for that hostif htype == "INTERNET_NAME":- dom = sf.hostDomain(host, self.opts['_internettlds'])+ dom = self.sf.hostDomain(host, self.opts['_internettlds'])self.processDomain(dom, evt)return evt@@ -351,14 +346,14 @@ class sfp_dns(SpiderFootPlugin):if not self.domresults.has_key(domainName):self.domresults[domainName] = Trueelse:- sf.debug("Skipping domain, " + domainName + ", already processed.")+ self.sf.debug("Skipping domain, " + domainName + ", already processed.")return Nonedomevt = SpiderFootEvent("DOMAIN_NAME", domainName, self.__name__,parentEvent)self.notifyListeners(domevt)- sf.debug("Gathering DNS records for " + domainName)+ self.sf.debug("Gathering DNS records for " + domainName)# Process the raw data alonerecdata = dict()recs = {@@ -379,12 +374,12 @@ class sfp_dns(SpiderFootPlugin):res = dns.query.udp(req, n)for x in res.answer:for rx in recs.keys():- sf.debug("Checking " + str(x) + " + against " + recs[rx][0])+ 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:- sf.debug("Matched: " + m)+ self.sf.debug("Matched: " + m)strdata = unicode(m, 'utf-8', errors='replace')evt = SpiderFootEvent(recs[rx][1], strdata,self.__name__)@@ -399,16 +394,16 @@ class sfp_dns(SpiderFootPlugin):self.__name__)self.notifyListeners(evt)except BaseException as e:- sf.error("Failed to obtain DNS response for " + domainName + \+ self.sf.error("Failed to obtain DNS response for " + domainName + \"(" + rec + "): " + str(e), False)- sf.debug("Iterating through possible sub-domains [" + str(self.sublist) + "]")+ self.sf.debug("Iterating through possible sub-domains [" + str(self.sublist) + "]")count = 0- wildcard = sf.checkDnsWildcard(domainName)+ wildcard = self.sf.checkDnsWildcard(domainName)# Try resolving common namesfor sub in self.sublist:if wildcard and self.opts['skipcommononwildcard'] and count > 0:- sf.debug("Wildcard DNS detected, skipping iterating through remaining hosts.")+ self.sf.debug("Wildcard DNS detected, skipping iterating through remaining hosts.")return Noneif self.checkForStop():diff --git a/modules/sfp_email.py b/modules/sfp_email.pyindex aa1e6eb1..076ae487 100644--- a/modules/sfp_email.py+++ b/modules/sfp_email.py@@ -14,9 +14,6 @@ import sysimport refrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_email(SpiderFootPlugin):"""E-Mail:Identify e-mail addresses in any obtained data."""@@ -32,9 +29,7 @@ class sfp_email(SpiderFootPlugin):}def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcfor opt in userOpts.keys():self.opts[opt] = userOpts[opt]@@ -59,28 +54,28 @@ class sfp_email(SpiderFootPlugin):if eventName == "EMAILADDR":return None- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)if type(eventData) not in [ str, unicode ]:- sf.debug("Unhandled type to find e-mails: " + str(type(eventData)))+ self.sf.debug("Unhandled type to find e-mails: " + str(type(eventData)))return Nonepat = re.compile("([a-zA-Z\.0-9_\-]+@[a-zA-Z\.0-9\-]+\.[a-zA-Z\.0-9\-]+)")matches = re.findall(pat, eventData)for match in matches:- sf.debug("Found possible email: " + match)+ self.sf.debug("Found possible email: " + match)if len(match) < 4:- sf.debug("Likely invalid address.")+ self.sf.debug("Likely invalid address.")continuemailDom = match.lower().split('@')[1]if not self.opts['includeexternal'] and not \self.getTarget().matches(mailDom):- sf.debug("Ignoring e-mail address on an external domain: " + match)+ self.sf.debug("Ignoring e-mail address on an external domain: " + match)continue- sf.info("Found e-mail address: " + match)+ self.sf.info("Found e-mail address: " + match)evt = SpiderFootEvent("EMAILADDR", match, self.__name__, parentEvent)self.notifyListeners(evt)diff --git a/modules/sfp_filemeta.py b/modules/sfp_filemeta.pyindex eae368f4..e8a63705 100644--- a/modules/sfp_filemeta.py+++ b/modules/sfp_filemeta.py@@ -22,9 +22,6 @@ import openxmllibfrom StringIO import StringIOfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_filemeta(SpiderFootPlugin):"""File Metadata:Extracts meta data from certain file types."""@@ -43,9 +40,7 @@ class sfp_filemeta(SpiderFootPlugin):results = list()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = list()for opt in userOpts.keys():@@ -67,7 +62,7 @@ class sfp_filemeta(SpiderFootPlugin):srcModuleName = event.moduleeventData = event.data- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)if eventData in self.results:return None@@ -81,15 +76,15 @@ class sfp_filemeta(SpiderFootPlugin):if "." + fileExt.lower() in eventData.lower():# Fetch the file, allow much more time given that these files are# typically large.- ret = sf.fetchUrl(eventData, timeout=self.opts['timeout'],+ ret = self.sf.fetchUrl(eventData, timeout=self.opts['timeout'],useragent=self.opts['_useragent'], dontMangle=True)if ret['content'] == None:- sf.error("Unable to fetch file for meta analysis: " + \+ self.sf.error("Unable to fetch file for meta analysis: " + \eventData, False)return Noneif len(ret['content']) < 1024:- sf.error("Strange content encountered, size of " + \+ self.sf.error("Strange content encountered, size of " + \len(res['content']), False)meta = None@@ -98,9 +93,9 @@ class sfp_filemeta(SpiderFootPlugin):try:data = StringIO(ret['content'])meta = str(metapdf.MetaPdfReader().read_metadata(data))- sf.debug("Obtained meta data from " + eventData)+ self.sf.debug("Obtained meta data from " + eventData)except BaseException as e:- sf.error("Unable to parse meta data from: " + \+ self.sf.error("Unable to parse meta data from: " + \eventData + "(" + str(e) + ")", False)return None@@ -108,13 +103,13 @@ class sfp_filemeta(SpiderFootPlugin):try:mtype = mimetypes.guess_type(eventData)[0]doc = openxmllib.openXmlDocument(data=ret['content'], mime_type=mtype)- sf.debug("Office type: " + doc.mimeType)+ self.sf.debug("Office type: " + doc.mimeType)meta = str(doc.allProperties)except ValueError as e:- sf.error("Unable to parse meta data from: " + \+ self.sf.error("Unable to parse meta data from: " + \eventData + "(" + str(e) + ")", False)except lxml.etree.XMLSyntaxError as e:- sf.error("Unable to parse XML within: " + \+ self.sf.error("Unable to parse XML within: " + \eventData + "(" + str(e) + ")", False)if meta != None:diff --git a/modules/sfp_geoip.py b/modules/sfp_geoip.pyindex 48320846..76255aa1 100644--- a/modules/sfp_geoip.py+++ b/modules/sfp_geoip.py@@ -15,9 +15,6 @@ import reimport jsonfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_geoip(SpiderFootPlugin):"""GeoIP:Identifies the physical location of IP addresses identified."""@@ -26,9 +23,7 @@ class sfp_geoip(SpiderFootPlugin):results = dict()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = dict()for opt in userOpts.keys():@@ -50,26 +45,26 @@ class sfp_geoip(SpiderFootPlugin):srcModuleName = event.moduleeventData = event.data- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)# Don't look up stuff twiceif self.results.has_key(eventData):- sf.debug("Skipping " + eventData + " as already mapped.")+ self.sf.debug("Skipping " + eventData + " as already mapped.")return Noneelse:self.results[eventData] = True- res = sf.fetchUrl("http://freegeoip.net/json/" + eventData,+ res = self.sf.fetchUrl("http://freegeoip.net/json/" + eventData,timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])if res['content'] == None:- sf.info("No GeoIP info found for " + eventData)+ self.sf.info("No GeoIP info found for " + eventData)try:hostip = json.loads(res['content'])except Exception as e:- sf.debug("Error processing JSON response.")+ self.sf.debug("Error processing JSON response.")return None- sf.info("Found GeoIP for " + eventData + ": " + hostip['country_name'])+ self.sf.info("Found GeoIP for " + eventData + ": " + hostip['country_name'])countrycity = hostip['country_name']evt = SpiderFootEvent("GEOINFO", countrycity, self.__name__, event)diff --git a/modules/sfp_googlesearch.py b/modules/sfp_googlesearch.pyindex fc0263ba..9ece57cb 100644--- a/modules/sfp_googlesearch.py+++ b/modules/sfp_googlesearch.py@@ -15,9 +15,6 @@ import reimport timefrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_googlesearch(SpiderFootPlugin):"""Google:Some light Google scraping to identify sub-domains and links."""@@ -37,9 +34,7 @@ class sfp_googlesearch(SpiderFootPlugin):results = list()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = list()for opt in userOpts.keys():@@ -61,17 +56,17 @@ class sfp_googlesearch(SpiderFootPlugin):eventData = event.dataif eventData in self.results:- sf.debug("Already did a search for " + eventData + ", skipping.")+ self.sf.debug("Already did a search for " + eventData + ", skipping.")return Noneelse:self.results.append(eventData)# Sites hosted on the domain- pages = sf.googleIterate("site:" + eventData,+ pages = self.sf.googleIterate("site:" + eventData,dict(limit=self.opts['pages'], useragent=self.opts['_useragent'],timeout=self.opts['_fetchtimeout']))if pages == None:- sf.info("No results returned from Google.")+ self.sf.info("No results returned from Google.")return Nonefor page in pages.keys():@@ -91,7 +86,7 @@ class sfp_googlesearch(SpiderFootPlugin):# We can optionally fetch links to our domain found in the search# results. These may not have been identified through spidering.if self.opts['fetchlinks']:- links = sf.parseLinks(page, pages[page], eventData)+ links = self.sf.parseLinks(page, pages[page], eventData)if len(links) == 0:continue@@ -100,8 +95,8 @@ class sfp_googlesearch(SpiderFootPlugin):continueelse:self.results.append(link)- sf.debug("Found a link: " + link)- if sf.urlFQDN(link).endswith(eventData):+ self.sf.debug("Found a link: " + link)+ if self.sf.urlFQDN(link).endswith(eventData):if self.checkForStop():return Nonediff --git a/modules/sfp_honeypot.py b/modules/sfp_honeypot.pyindex 429fc911..21305b17 100644--- a/modules/sfp_honeypot.py+++ b/modules/sfp_honeypot.py@@ -16,9 +16,6 @@ import socketimport randomfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_honeypot(SpiderFootPlugin):"""Honeypot Checker: Query the projecthoneypot.org database for entries."""@@ -57,9 +54,7 @@ class sfp_honeypot(SpiderFootPlugin):}def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = dict()for opt in userOpts.keys():@@ -103,10 +98,10 @@ class sfp_honeypot(SpiderFootPlugin):eventData = event.dataparentEvent = event- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)if self.opts['apikey'] == "":- sf.error("You enabled sfp_honeypot but did not set an API key!", False)+ self.sf.error("You enabled sfp_honeypot but did not set an API key!", False)return Noneif self.results.has_key(eventData):@@ -117,9 +112,9 @@ class sfp_honeypot(SpiderFootPlugin):lookup = self.opts['apikey'] + "." + \self.reverseAddr(eventData) + ".dnsbl.httpbl.org"- sf.debug("Checking Honeypot: " + lookup)+ self.sf.debug("Checking Honeypot: " + lookup)addrs = socket.gethostbyname_ex(lookup)- sf.debug("Addresses returned: " + str(addrs))+ self.sf.debug("Addresses returned: " + str(addrs))text = Nonefor addr in addrs:@@ -147,6 +142,6 @@ class sfp_honeypot(SpiderFootPlugin):text, self.__name__, parentEvent)self.notifyListeners(evt)except BaseException as e:- sf.debug("Unable to resolve " + eventData + " / " + lookup + ": " + str(e))+ self.sf.debug("Unable to resolve " + eventData + " / " + lookup + ": " + str(e))# End of sfp_honeypot classdiff --git a/modules/sfp_intfiles.py b/modules/sfp_intfiles.pyindex d77c44d3..ebaad4c5 100644--- a/modules/sfp_intfiles.py+++ b/modules/sfp_intfiles.py@@ -17,9 +17,6 @@ import timeimport urllibfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_intfiles(SpiderFootPlugin):"""Interesting Files:Identifies potential files of interest, e.g. office documents."""@@ -42,9 +39,7 @@ class sfp_intfiles(SpiderFootPlugin):results = list()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = list()for opt in userOpts.keys():@@ -69,10 +64,10 @@ class sfp_intfiles(SpiderFootPlugin):srcModuleName = event.moduleeventData = event.data- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)if eventName == "INTERNET_NAME" and not self.opts['usesearch']:- sf.debug("Not using a search engine to find interesting files.")+ self.sf.debug("Not using a search engine to find interesting files.")return Noneif eventData in self.results:@@ -95,25 +90,25 @@ class sfp_intfiles(SpiderFootPlugin):for fileExt in self.opts['fileexts']:# Sites hosted on the domainif self.opts['searchengine'].lower() == "google":- pages = sf.googleIterate("site:" + eventData + "+" + \+ 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 = sf.bingIterate("site:" + eventData + "+" + \+ 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 = sf.yahooIterate("site:" + eventData + "+" + \+ pages = self.sf.yahooIterate("site:" + eventData + "+" + \"%2Bext:" + fileExt, dict(limit=self.opts['pages'],useragent=self.opts['_useragent'],timeout=self.opts['_fetchtimeout']))if pages == None:- sf.info("No results returned from " + self.opts['searchengine'] + \+ self.sf.info("No results returned from " + self.opts['searchengine'] + \" for " + fileExt + " files.")continue@@ -137,7 +132,7 @@ class sfp_intfiles(SpiderFootPlugin):else:res = pages[page]- links = sf.parseLinks(page, res, eventData)+ links = self.sf.parseLinks(page, res, eventData)if len(links) == 0:continue@@ -147,9 +142,9 @@ class sfp_intfiles(SpiderFootPlugin):else:self.results.append(link)- if sf.urlFQDN(link).endswith(eventData) and \+ if self.sf.urlFQDN(link).endswith(eventData) and \"." + fileExt.lower() in link.lower():- sf.info("Found an interesting file: " + link)+ self.sf.info("Found an interesting file: " + link)evt = SpiderFootEvent("INTERESTING_FILE", link, self.__name__)self.notifyListeners(evt)diff --git a/modules/sfp_ir.py b/modules/sfp_ir.pyindex 392e067c..8faf4047 100644--- a/modules/sfp_ir.py+++ b/modules/sfp_ir.py@@ -15,9 +15,6 @@ import reimport jsonfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_ir(SpiderFootPlugin):"""Internet Registries:Queries Internet Registries to identify netblocks and other info."""@@ -31,9 +28,7 @@ class sfp_ir(SpiderFootPlugin):keywords = Nonedef setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = dict()self.memCache = dict()self.currentEventSrc = None@@ -57,7 +52,7 @@ class sfp_ir(SpiderFootPlugin):if self.memCache.has_key(url):res = self.memCache[url]else:- res = sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],useragent=self.opts['_useragent'])if res['content'] != None:self.memCache[url] = res@@ -72,18 +67,18 @@ class sfp_ir(SpiderFootPlugin):res = self.fetchRir("https://stat.ripe.net/data/network-info/data.json?resource=" + ipaddr)if res['content'] == None:- sf.debug("No Netblock info found/available for " + ipaddr + " at RIPE.")+ self.sf.debug("No Netblock info found/available for " + ipaddr + " at RIPE.")return Nonetry:j = json.loads(res['content'])except Exception as e:- sf.debug("Error processing JSON response.")+ self.sf.debug("Error processing JSON response.")return Noneprefix = j["data"]["prefix"]if prefix == None:- sf.debug("Could not identify network prefix.")+ self.sf.debug("Could not identify network prefix.")return Nonereturn prefix@@ -94,7 +89,7 @@ class sfp_ir(SpiderFootPlugin):res = self.fetchRir("https://stat.ripe.net/data/whois/data.json?resource=" + prefix)if res['content'] == None:- sf.debug("No AS info found/available for prefix: " + prefix + " at RIPE.")+ self.sf.debug("No AS info found/available for prefix: " + prefix + " at RIPE.")return Nonetry:@@ -104,7 +99,7 @@ class sfp_ir(SpiderFootPlugin):else:data = j["data"]["records"][0]except Exception as e:- sf.debug("Error processing JSON response.")+ self.sf.debug("Error processing JSON response.")return Nonefor rec in data:@@ -120,14 +115,14 @@ class sfp_ir(SpiderFootPlugin):res = self.fetchRir("https://stat.ripe.net/data/whois/data.json?resource=" + asn)if res['content'] == None:- sf.debug("No info found/available for ASN: " + asn + " at RIPE.")+ self.sf.debug("No info found/available for ASN: " + asn + " at RIPE.")return Nonetry:j = json.loads(res['content'])data = j["data"]["records"]except Exception as e:- sf.debug("Error processing JSON response.")+ self.sf.debug("Error processing JSON response.")return Nonefor rec in data:@@ -141,7 +136,7 @@ class sfp_ir(SpiderFootPlugin):else:ownerinfo[d["key"]] = [ d["value"] ]- sf.debug("Returning ownerinfo: " + str(ownerinfo))+ self.sf.debug("Returning ownerinfo: " + str(ownerinfo))return ownerinfo# Netblocks owned by an AS@@ -150,19 +145,19 @@ class sfp_ir(SpiderFootPlugin):res = self.fetchRir("https://stat.ripe.net/data/announced-prefixes/data.json?resource=AS" + asn)if res['content'] == None:- sf.debug("No netblocks info found/available for AS" + asn + " at RIPE.")+ self.sf.debug("No netblocks info found/available for AS" + asn + " at RIPE.")return Nonetry:j = json.loads(res['content'])data = j["data"]["prefixes"]except Exception as e:- sf.debug("Error processing JSON response.")+ self.sf.debug("Error processing JSON response.")return Nonefor rec in data:netblocks.append(rec["prefix"])- sf.info("Additional netblock found from same AS: " + rec["prefix"])+ self.sf.info("Additional netblock found from same AS: " + rec["prefix"])return netblocks@@ -172,14 +167,14 @@ class sfp_ir(SpiderFootPlugin):res = self.fetchRir("https://stat.ripe.net/data/asn-neighbours/data.json?resource=AS" + asn)if res['content'] == None:- sf.debug("No neighbour info found/available for AS" + asn + " at RIPE.")+ self.sf.debug("No neighbour info found/available for AS" + asn + " at RIPE.")return Nonetry:j = json.loads(res['content'])data = j["data"]["neighbours"]except Exception as e:- sf.debug("Error processing JSON response.")+ self.sf.debug("Error processing JSON response.")return Nonefor rec in data:@@ -195,7 +190,7 @@ class sfp_ir(SpiderFootPlugin):return Trueif self.keywords == None:- self.keywords = sf.domainKeywords(self.getTarget().getNames(),+ self.keywords = self.sf.domainKeywords(self.getTarget().getNames(),self.opts['_internettlds'])# Slightly more complex..@@ -215,7 +210,7 @@ class sfp_ir(SpiderFootPlugin):keywordList.append(kw.replace('-', ''))for kw in keywordList:- sf.debug("Looking for keyword: " + kw)+ self.sf.debug("Looking for keyword: " + kw)for r in rx:if re.match(r.format(kw), string, re.IGNORECASE) != None:return True@@ -229,23 +224,23 @@ class sfp_ir(SpiderFootPlugin):eventData = event.dataself.currentEventSrc = event- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)# Don't look up stuff twiceif self.results.has_key(eventData):- sf.debug("Skipping " + eventData + " as already mapped.")+ self.sf.debug("Skipping " + eventData + " as already mapped.")return Noneelse:self.results[eventData] = Trueprefix = self.ipNetblock(eventData)if prefix == None:- sf.debug("Could not identify network prefix.")+ self.sf.debug("Could not identify network prefix.")return Noneasn = self.netblockAs(prefix)if asn == None:- sf.debug("Could not identify netblock AS.")+ self.sf.debug("Could not identify netblock AS.")return Noneownerinfo = self.asOwnerInfo(asn)@@ -259,7 +254,7 @@ class sfp_ir(SpiderFootPlugin):owned = Trueif owned:- sf.info("Owned netblock found: " + prefix + "(" + asn + ")")+ self.sf.info("Owned netblock found: " + prefix + "(" + asn + ")")evt = SpiderFootEvent("NETBLOCK", prefix, self.__name__, event)self.notifyListeners(evt)asevt = SpiderFootEvent("BGP_AS_OWNER", asn, self.__name__, event)diff --git a/modules/sfp_malcheck.py b/modules/sfp_malcheck.pyindex 2dc523de..ea89ee8d 100644--- a/modules/sfp_malcheck.py+++ b/modules/sfp_malcheck.py@@ -14,9 +14,6 @@ import sysimport refrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-malchecks = {'abuse.ch Zeus Tracker (Domain)': {'id': 'abusezeusdomain',@@ -269,9 +266,7 @@ class sfp_malcheck(SpiderFootPlugin):results = list()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = list()# Clear / reset any other class member variables here@@ -301,30 +296,30 @@ class sfp_malcheck(SpiderFootPlugin):if len(badregex) > 0:for rx in badregex:if re.match(rx, content, re.IGNORECASE|re.DOTALL):- sf.debug("Found to be bad")+ self.sf.debug("Found to be bad")return True# Finally, check for good indicatorsif len(goodregex) > 0:for rx in goodregex:if re.match(rx, content, re.IGNORECASE|re.DOTALL):- sf.debug("Found to be good")+ self.sf.debug("Found to be good")return False# If nothing was matched, reply None- sf.debug("Neither good nor bad, unknown.")+ self.sf.debug("Neither good nor bad, unknown.")return None# Look up 'query' type sourcesdef resourceQuery(self, id, target, targetType):- sf.debug("Querying " + id + " for maliciousness of " + target)+ 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 = sf.fetchUrl(url.format(target), useragent=self.opts['_useragent'])+ res = self.sf.fetchUrl(url.format(target), useragent=self.opts['_useragent'])if res['content'] == None:- sf.error("Unable to fetch " + url.format(target), False)+ self.sf.error("Unable to fetch " + url.format(target), False)return Noneif self.contentMalicious(res['content'],malchecks[check]['goodregex'],@@ -338,21 +333,21 @@ class sfp_malcheck(SpiderFootPlugin):targetDom = ''# Get the base domain if we're supplied a domainif targetType == "domain":- targetDom = sf.hostDomain(target, self.opts['_internettlds'])+ 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'] = sf.cacheGet("sfmal_" + cid, self.opts['aaacacheperiod'])+ data['content'] = self.sf.cacheGet("sfmal_" + cid, self.opts['aaacacheperiod'])if data['content'] == None:- data = sf.fetchUrl(url, useragent=self.opts['_useragent'])+ data = self.sf.fetchUrl(url, useragent=self.opts['_useragent'])if data['content'] == None:- sf.error("Unable to fetch " + url, False)+ self.sf.error("Unable to fetch " + url, False)return Noneelse:- sf.cachePut("sfmal_" + cid, data['content'])+ self.sf.cachePut("sfmal_" + cid, data['content'])# If we're looking at netblocksif targetType == "netblock":@@ -364,11 +359,11 @@ class sfp_malcheck(SpiderFootPlugin):rx = malchecks[check]['regex'].replace("{0}", \"(\d+\.\d+\.\d+\.\d+)")pat = re.compile(rx, re.IGNORECASE)- sf.debug("New regex for " + check + ": " + rx)+ self.sf.debug("New regex for " + check + ": " + rx)for line in data['content'].split('\n'):grp = re.findall(pat, line)if len(grp) > 0:- #sf.debug("Adding " + grp[0] + " to list.")+ #self.sf.debug("Adding " + grp[0] + " to list.")iplist.append(grp[0])else:iplist = data['content'].split('\n')@@ -380,11 +375,11 @@ class sfp_malcheck(SpiderFootPlugin):try:if IPAddress(ip) in IPNetwork(target):- sf.debug(ip + " found within netblock/subnet " + \+ self.sf.debug(ip + " found within netblock/subnet " + \target + " in " + check)return urlexcept Exception as e:- sf.debug("Error encountered parsing: " + str(e))+ self.sf.debug("Error encountered parsing: " + str(e))continuereturn None@@ -393,7 +388,7 @@ class sfp_malcheck(SpiderFootPlugin):if not malchecks[check].has_key('regex'):for line in data['content'].split('\n'):if line == target or (targetType == "domain" and line == targetDom):- sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")return urlelse:# Check for the domain and the hostname@@ -402,7 +397,7 @@ class sfp_malcheck(SpiderFootPlugin):for line in data['content'].split('\n'):if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \re.match(rxTgt, line, re.IGNORECASE):- sf.debug(target + "/" + targetDom + " found in " + check + " list.")+ self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")return urlreturn None@@ -410,7 +405,7 @@ class sfp_malcheck(SpiderFootPlugin):for check in malchecks.keys():cid = malchecks[check]['id']if cid == resourceId and itemType in malchecks[check]['checks']:- sf.debug("Checking maliciousness of " + target + " (" + \+ self.sf.debug("Checking maliciousness of " + target + " (" + \itemType + ") with: " + cid)if malchecks[check]['type'] == "query":return self.resourceQuery(cid, target, itemType)@@ -425,10 +420,10 @@ class sfp_malcheck(SpiderFootPlugin):srcModuleName = event.moduleeventData = event.data- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)if eventData in self.results:- sf.debug("Skipping " + eventData + ", already checked.")+ self.sf.debug("Skipping " + eventData + ", already checked.")return Noneelse:self.results.append(eventData)diff --git a/modules/sfp_names.py b/modules/sfp_names.pyindex 436db79a..1f48c8fc 100644--- a/modules/sfp_names.py+++ b/modules/sfp_names.py@@ -13,9 +13,6 @@ import sysimport refrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_names(SpiderFootPlugin):"""Name Extractor:Attempt to identify human names in fetched content."""@@ -38,7 +35,7 @@ class sfp_names(SpiderFootPlugin):wd = dict()for f in files:- wdct = open(sf.myPath() + "/ext/ispell/" + f, 'r')+ wdct = open(self.sf.myPath() + "/ext/ispell/" + f, 'r')dlines = wdct.readlines()for w in dlines:@@ -48,9 +45,7 @@ class sfp_names(SpiderFootPlugin):return wd.keys()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = dict()d = self.builddict(["english.0", "english.2", "english.4",@@ -84,7 +79,7 @@ class sfp_names(SpiderFootPlugin):srcModuleName = event.moduleeventData = event.data- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)# Stage 1: Find things that look (very vaguely) like namesrx = re.compile("([A-Z][a-z]+)\s+.?.?\s?([A-Z][a-zA-Z\'\-]+)")diff --git a/modules/sfp_pageinfo.py b/modules/sfp_pageinfo.pyindex fcca2422..f848a6fb 100644--- a/modules/sfp_pageinfo.py+++ b/modules/sfp_pageinfo.py@@ -15,9 +15,6 @@ import sysimport refrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-# Indentify pages that use Javascript libs, handle passwords, have forms,# permit file uploads and more to come.regexps = dict({@@ -39,9 +36,7 @@ etc.)"""results = dict()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = dict()for opt in userOpts.keys():@@ -64,7 +59,7 @@ etc.)"""# 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:- sf.debug("Ignoring web content from " + event.module)+ self.sf.debug("Ignoring web content from " + event.module)return NoneeventName = event.eventType@@ -72,18 +67,18 @@ etc.)"""eventData = event.dataeventSource = event.sourceEvent.data # will be the URL of the raw data- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ 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(sf.urlFQDN(eventSource)):- sf.debug("Not gathering page info for external site " + eventSource)+ if not self.getTarget().matches(self.sf.urlFQDN(eventSource)):+ self.sf.debug("Not gathering page info for external site " + eventSource)return Noneif eventSource not in self.results.keys():self.results[eventSource] = list()else:- sf.debug("Already checked this page for a page type, skipping.")+ self.sf.debug("Already checked this page for a page type, skipping.")return None# Check the configured regexps to determine the page type@@ -95,7 +90,7 @@ etc.)"""rx = re.compile(regex, re.IGNORECASE)matches = re.findall(rx, eventData)if len(matches) > 0 and regexpGrp not in self.results[eventSource]:- sf.info("Matched " + regexpGrp + " in content from " + eventSource)+ self.sf.info("Matched " + regexpGrp + " in content from " + eventSource)self.results[eventSource].append(regexpGrp)evt = SpiderFootEvent(regexpGrp, eventSource,self.__name__, event.sourceEvent)@@ -103,7 +98,7 @@ etc.)"""# If no regexps were matched, consider this a static pageif len(self.results[eventSource]) == 0:- sf.info("Treating " + eventSource + " as URL_STATIC")+ self.sf.info("Treating " + eventSource + " as URL_STATIC")evt = SpiderFootEvent("URL_STATIC", eventSource, self.__name__, event.sourceEvent)self.notifyListeners(evt)@@ -112,8 +107,8 @@ etc.)"""matches = re.findall(pat, eventData)if len(matches) > 0:for match in matches:- if '://' in match and not self.getTarget().matches(sf.urlFQDN(match)):- sf.debug("Externally hosted Javascript found at: " + match)+ 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)diff --git a/modules/sfp_pastebin.py b/modules/sfp_pastebin.pyindex 048bb234..67d2fe09 100644--- a/modules/sfp_pastebin.py+++ b/modules/sfp_pastebin.py@@ -16,9 +16,6 @@ import reimport timefrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_pastebin(SpiderFootPlugin):"""PasteBin:PasteBin scraping (via Google) to identify related content."""@@ -35,9 +32,7 @@ class sfp_pastebin(SpiderFootPlugin):results = list()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = list()for opt in userOpts.keys():@@ -64,12 +59,12 @@ class sfp_pastebin(SpiderFootPlugin):self.results.append(eventData)# Sites hosted on the domain- pages = sf.googleIterate("site:pastebin.com +\"" + eventData + "\"",+ pages = self.sf.googleIterate("site:pastebin.com +\"" + eventData + "\"",dict(limit=self.opts['pages'],useragent=self.opts['_useragent'], timeout=self.opts['_fetchtimeout']))if pages == None:- sf.info("No results returned from Google PasteBin search.")+ self.sf.info("No results returned from Google PasteBin search.")return Nonefor page in pages.keys():@@ -87,7 +82,7 @@ class sfp_pastebin(SpiderFootPlugin):self.notifyListeners(evt)# Fetch the PasteBin page- links = sf.parseLinks(page, pages[page], "pastebin.com")+ links = self.sf.parseLinks(page, pages[page], "pastebin.com")if len(links) == 0:continue@@ -97,16 +92,16 @@ class sfp_pastebin(SpiderFootPlugin):else:self.results.append(link)- sf.debug("Found a link: " + link)- if sf.urlBaseUrl(link).endswith("pastebin.com"):+ self.sf.debug("Found a link: " + link)+ if self.sf.urlBaseUrl(link).endswith("pastebin.com"):if self.checkForStop():return None- res = sf.fetchUrl(link, timeout=self.opts['_fetchtimeout'],+ res = self.sf.fetchUrl(link, timeout=self.opts['_fetchtimeout'],useragent=self.opts['_useragent'])if res['content'] == None:- sf.debug("Ignoring " + link + " as no data returned")+ self.sf.debug("Ignoring " + link + " as no data returned")continueevt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT",@@ -122,7 +117,7 @@ class sfp_pastebin(SpiderFootPlugin):startIndex = res['content'].index(eventData)-120endIndex = startIndex+len(eventData)+240except BaseException as e:- sf.debug("String not found in pastebin content.")+ self.sf.debug("String not found in pastebin content.")continuedata = res['content'][startIndex:endIndex]diff --git a/modules/sfp_portscan_basic.py b/modules/sfp_portscan_basic.pyindex 385914ad..e78dbcb2 100644--- a/modules/sfp_portscan_basic.py+++ b/modules/sfp_portscan_basic.py@@ -18,9 +18,6 @@ import randomimport threadingfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_portscan_basic(SpiderFootPlugin):"""Port Scanner:Scans for commonly open TCP ports on Internet-facing systems."""@@ -55,9 +52,7 @@ class sfp_portscan_basic(SpiderFootPlugin):portResults = dict()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = dict()for opt in userOpts.keys():@@ -66,7 +61,7 @@ class sfp_portscan_basic(SpiderFootPlugin):if self.opts['ports'][0].startswith("http://") or \self.opts['ports'][0].startswith("https://") or \self.opts['ports'][0].startswith("@"):- self.portlist = sf.optValueToData(self.opts['ports'][0])+ self.portlist = self.sf.optValueToData(self.opts['ports'][0])else:self.portlist = self.opts['ports']@@ -112,7 +107,7 @@ class sfp_portscan_basic(SpiderFootPlugin):# Spawn threads for scanningwhile i < len(portList):- sf.info("Spawning thread to check port: " + str(portList[i]) + " on " + ip)+ self.sf.info("Spawning thread to check port: " + str(portList[i]) + " on " + ip)t.append(threading.Thread(name='sfp_portscan_basic_' + str(portList[i]),target=self.tryPort, args=(ip, portList[i])))t[i].start()@@ -134,7 +129,7 @@ class sfp_portscan_basic(SpiderFootPlugin):def sendEvent(self, resArray, srcEvent):for cp in resArray:if resArray[cp]:- sf.info("TCP Port " + cp + " found to be OPEN.")+ 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:@@ -150,13 +145,13 @@ class sfp_portscan_basic(SpiderFootPlugin):eventData = event.datascanIps = list()- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)try:if eventName == "NETBLOCK" and self.opts['netblockscan']:net = IPNetwork(eventData)if net.prefixlen < self.opts['netblockscanmax']:- sf.debug("Skipping port scanning of " + eventData + ", too big.")+ self.sf.debug("Skipping port scanning of " + eventData + ", too big.")return Nonefor ip in net:@@ -169,14 +164,14 @@ class sfp_portscan_basic(SpiderFootPlugin):else:scanIps.append(eventData)except BaseException as e:- sf.error("Strange netblock identified, unable to parse: " + \+ self.sf.error("Strange netblock identified, unable to parse: " + \eventData + " (" + str(e) + ")", False)return Nonefor ipAddr in scanIps:# Don't look up stuff twiceif self.results.has_key(ipAddr):- sf.debug("Skipping " + ipAddr + " as already scanned.")+ self.sf.debug("Skipping " + ipAddr + " as already scanned.")return Noneelse:self.results[ipAddr] = Truediff --git a/modules/sfp_sharedip.py b/modules/sfp_sharedip.pyindex d4bf053d..0d7bb86e 100644--- a/modules/sfp_sharedip.py+++ b/modules/sfp_sharedip.py@@ -16,9 +16,6 @@ import timeimport socketfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_sharedip(SpiderFootPlugin):"""Shared IP:Search Bing and/or Robtex.com for hosts sharing the same IP."""@@ -41,9 +38,7 @@ class sfp_sharedip(SpiderFootPlugin):results = list()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = list()for opt in userOpts.keys():@@ -63,7 +58,7 @@ class sfp_sharedip(SpiderFootPlugin):try:addrs = socket.gethostbyname_ex(host)except BaseException as e:- sf.debug("Unable to resolve " + host + ": " + str(e))+ self.sf.debug("Unable to resolve " + host + ": " + str(e))return Falsefor addr in addrs:@@ -83,20 +78,20 @@ class sfp_sharedip(SpiderFootPlugin):eventData = event.dataself.currentEventSrc = event- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)# Don't look up stuff twiceif eventData in self.results:- sf.debug("Skipping " + eventData + " as already mapped.")+ self.sf.debug("Skipping " + eventData + " as already mapped.")return Noneelse:self.results.append(eventData)# Robtexif self.opts['source'].lower() == "robtex":- res = sf.fetchUrl("https://www.robtex.com/shared/" + eventData + ".html")+ res = self.sf.fetchUrl("https://www.robtex.com/shared/" + eventData + ".html")if res['content'] == None:- sf.error("Unable to fetch robtex content.", False)+ self.sf.error("Unable to fetch robtex content.", False)return Nonemyres = list()@@ -107,23 +102,23 @@ class sfp_sharedip(SpiderFootPlugin):pat = re.compile("href=\"//www.robtex.com/dns/(.[^\"]*).html", re.IGNORECASE)matches = re.findall(pat, blob[0])for m in matches:- sf.info("Found something on same IP: " + m)+ self.sf.info("Found something on same IP: " + m)if not self.opts['cohostsamedomain']:if self.getTarget().matches(m, includeParents=True):- sf.debug("Skipping " + m + " because it is on the same domain.")+ self.sf.debug("Skipping " + m + " because it is on the same domain.")continueif '*' in m:- sf.debug("Skipping wildcard name: " + m)+ self.sf.debug("Skipping wildcard name: " + m)continueif '.' not in m:- sf.debug("Skipping tld: " + m)+ self.sf.debug("Skipping tld: " + m)continueif m not in myres and m != eventData:if self.opts['verify'] and not self.validateIP(m, eventData):- sf.debug("Host no longer resolves to our IP.")+ self.sf.debug("Host no longer resolves to our IP.")continueevt = SpiderFootEvent("CO_HOSTED_SITE", m, self.__name__, event)self.notifyListeners(evt)@@ -131,11 +126,11 @@ class sfp_sharedip(SpiderFootPlugin):# Bingif self.opts['source'].lower() == "bing":- results = sf.bingIterate("ip:" + eventData, dict(limit=self.opts['pages'],+ results = self.sf.bingIterate("ip:" + eventData, dict(limit=self.opts['pages'],useragent=self.opts['_useragent'], timeout=self.opts['_fetchtimeout']))myres = list()if results == None:- sf.info("No data returned from Bing.")+ self.sf.info("No data returned from Bing.")return Nonefor key in results.keys():@@ -143,15 +138,15 @@ class sfp_sharedip(SpiderFootPlugin):pat = re.compile("<div class=\"sb_meta\"><cite>(\S+)</cite>", re.IGNORECASE)matches = re.findall(pat, res)for match in matches:- sf.info("Found something on same IP: " + match)- site = sf.urlFQDN(match)+ self.sf.info("Found something on same IP: " + match)+ site = self.sf.urlFQDN(match)if site not in myres and site != eventData:if not self.opts['cohostsamedomain']:if self.getTarget().matches(m, includeParents=True):- sf.debug("Skipping " + site + " because it is on the same domain.")+ self.sf.debug("Skipping " + site + " because it is on the same domain.")continueif self.opts['verify'] and not self.validateIP(m, eventData):- sf.debug("Host no longer resolves to our IP.")+ self.sf.debug("Host no longer resolves to our IP.")continueevt = SpiderFootEvent("CO_HOSTED_SITE", site, self.__name__, event)self.notifyListeners(evt)diff --git a/modules/sfp_shodan.py b/modules/sfp_shodan.pyindex 72a6591b..d007d7ab 100644--- a/modules/sfp_shodan.py+++ b/modules/sfp_shodan.py@@ -13,9 +13,6 @@ import sysimport jsonfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_shodan(SpiderFootPlugin):"""SHODAN:Obtain information from SHODAN about identified IP addresses."""@@ -32,9 +29,7 @@ class sfp_shodan(SpiderFootPlugin):results = dict()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = dict()# Clear / reset any other class member variables here@@ -58,30 +53,30 @@ class sfp_shodan(SpiderFootPlugin):srcModuleName = event.moduleeventData = event.data- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)if self.opts['apikey'] == "":- sf.error("You enabled sfp_shodan but did not set an API key!", False)+ self.sf.error("You enabled sfp_shodan but did not set an API key!", False)return None# Don't look up stuff twiceif self.results.has_key(eventData):- sf.debug("Skipping " + eventData + " as already mapped.")+ self.sf.debug("Skipping " + eventData + " as already mapped.")return Noneelse:self.results[eventData] = True- res = sf.fetchUrl("https://api.shodan.io/shodan/host/" + eventData + \+ res = self.sf.fetchUrl("https://api.shodan.io/shodan/host/" + eventData + \"?key=" + self.opts['apikey'],timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])if res['content'] == None:- sf.info("No SHODAN info found for " + eventData)+ self.sf.info("No SHODAN info found for " + eventData)return Nonetry:info = json.loads(res['content'])except Exception as e:- sf.error("Error processing JSON response from SHODAN.", False)+ self.sf.error("Error processing JSON response from SHODAN.", False)return Noneos = info.get('os')@@ -98,7 +93,7 @@ class sfp_shodan(SpiderFootPlugin):self.notifyListeners(evt)- sf.info("Found SHODAN data for " + eventData)+ self.sf.info("Found SHODAN data for " + eventData)for rec in info['data']:port = str(rec.get('port'))banner = rec.get('banner')diff --git a/modules/sfp_similar.py b/modules/sfp_similar.pyindex 00ace4e3..7d3be815 100644--- a/modules/sfp_similar.py+++ b/modules/sfp_similar.py@@ -39,9 +39,6 @@ whoisUrlN = "http://www.whois.net/domain-keyword-search/{0}/{1}"whoisLastPageIndicator = "Next >"whoisIncrement = 16-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_similar(SpiderFootPlugin):"""Similar Domains:Search various sources to identify similar looking domain names."""@@ -63,9 +60,7 @@ class sfp_similar(SpiderFootPlugin):results = list()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = list()for opt in userOpts.keys():@@ -105,7 +100,7 @@ class sfp_similar(SpiderFootPlugin):if self.checkForStop():return None- whois = sf.fetchUrl(fetchPage, timeout=self.opts['_fetchtimeout'],+ whois = self.sf.fetchUrl(fetchPage, timeout=self.opts['_fetchtimeout'],useragent=self.opts['_useragent'])if whois['content'] == None:return None@@ -137,7 +132,7 @@ class sfp_similar(SpiderFootPlugin):if self.checkForStop():return None- domtool = sf.fetchUrl(fetchPage, timeout=self.opts['_fetchtimeout'],+ domtool = self.sf.fetchUrl(fetchPage, timeout=self.opts['_fetchtimeout'],useragent=self.opts['_useragent'])if domtool['content'] == None:return None@@ -172,7 +167,7 @@ class sfp_similar(SpiderFootPlugin):if self.checkForStop():return None- namedrop = sf.fetchUrl(fetchPage, timeout=self.opts['_fetchtimeout'],+ namedrop = self.sf.fetchUrl(fetchPage, timeout=self.opts['_fetchtimeout'],useragent=self.opts['_useragent'])if namedrop['content'] == None:return None@@ -194,7 +189,7 @@ class sfp_similar(SpiderFootPlugin):# Store the result internally and notify listening modulesdef storeResult(self, source, result):- sf.info("Found a similar domain: " + result)+ self.sf.info("Found a similar domain: " + result)self.results.append(result)# Inform listening modules@@ -202,7 +197,7 @@ class sfp_similar(SpiderFootPlugin):if self.checkForStop():return None- pageContent = sf.fetchUrl('http://' + result,+ pageContent = self.sf.fetchUrl('http://' + result,timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])if pageContent['content'] != None:evt = SpiderFootEvent("SIMILARDOMAIN", result, self.__name__)@@ -223,8 +218,8 @@ class sfp_similar(SpiderFootPlugin):else:self.results.append(eventData)- keyword = sf.domainKeyword(eventData, self.opts['_internettlds'])- sf.debug("Keyword extracted from " + eventData + ": " + keyword)+ keyword = self.sf.domainKeyword(eventData, self.opts['_internettlds'])+ self.sf.debug("Keyword extracted from " + eventData + ": " + keyword)# No longer seems to work.#if "whois" in self.opts['source'] or "ALL" in self.opts['source']:diff --git a/modules/sfp_social.py b/modules/sfp_social.pyindex e8e4555c..092b44fc 100644--- a/modules/sfp_social.py+++ b/modules/sfp_social.py@@ -13,9 +13,6 @@ import reimport sysfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-regexps = dict({"LinkedIn (Individual)": list(['.*linkedin.com/in/([a-zA-Z0-9_]+$)']),"LinkedIn (Company)": list(['.*linkedin.com/company/([a-zA-Z0-9_]+$)']),@@ -45,9 +42,7 @@ class sfp_social(SpiderFootPlugin):results = dict()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = dict()for opt in userOpts.keys():@@ -70,7 +65,7 @@ class sfp_social(SpiderFootPlugin):srcModuleName = event.moduleeventData = event.data- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)if eventData not in self.results.keys():self.results[eventData] = True@@ -81,7 +76,7 @@ class sfp_social(SpiderFootPlugin):for regex in regexps[regexpGrp]:bits = re.match(regex, eventData, re.IGNORECASE)if bits != None:- sf.info("Matched " + regexpGrp + " in " + eventData)+ self.sf.info("Matched " + regexpGrp + " in " + eventData)evt = SpiderFootEvent("SOCIAL_MEDIA", regexpGrp + ": " + \bits.group(1), self.__name__, event)self.notifyListeners(evt)diff --git a/modules/sfp_socialprofiles.py b/modules/sfp_socialprofiles.pyindex 303d8b99..aa1059d6 100644--- a/modules/sfp_socialprofiles.py+++ b/modules/sfp_socialprofiles.py@@ -16,9 +16,6 @@ import timeimport urllibfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-sites = {# Search string to use, domain name the profile will sit on within# those search results.@@ -51,9 +48,7 @@ class sfp_socialprofiles(SpiderFootPlugin):results = list()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = list()for opt in userOpts.keys():@@ -80,17 +75,17 @@ class sfp_socialprofiles(SpiderFootPlugin):eventData = event.dataself.currentEventSrc = event- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)# Don't look up stuff twiceif eventData in self.results:- sf.debug("Skipping " + eventData + " as already mapped.")+ self.sf.debug("Skipping " + eventData + " as already mapped.")return Noneelse:self.results.append(eventData)if self.keywords == None:- self.keywords = sf.domainKeywords(self.getTarget().getNames(),+ self.keywords = self.sf.domainKeywords(self.getTarget().getNames(),self.opts['_internettlds'])for site in sites.keys():@@ -98,29 +93,29 @@ class sfp_socialprofiles(SpiderFootPlugin):searchDom = sites[site][1]if self.opts['method'].lower() == "google":- results = sf.googleIterate(searchStr, dict(limit=self.opts['pages'],+ 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 = sf.yahooIterate(searchStr, dict(limit=self.opts['pages'],+ 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 = sf.bingIterate(searchStr, dict(limit=self.opts['pages'],+ results = self.sf.bingIterate(searchStr, dict(limit=self.opts['pages'],useragent=self.opts['_useragent'],timeout=self.opts['_fetchtimeout']))if results == None:- sf.info("No data returned from " + self.opts['method'] + ".")+ self.sf.info("No data returned from " + self.opts['method'] + ".")return Noneif self.checkForStop():return NonepauseSecs = random.randint(4, 15)- sf.debug("Pausing for " + str(pauseSecs))+ self.sf.debug("Pausing for " + str(pauseSecs))time.sleep(pauseSecs)for key in results.keys():@@ -147,7 +142,7 @@ class sfp_socialprofiles(SpiderFootPlugin):# Fetch the profile page if we are checking# for a firm relationship.if self.opts['tighten']:- pres = sf.fetchUrl(match, timeout=self.opts['_fetchtimeout'],+ pres = self.sf.fetchUrl(match, timeout=self.opts['_fetchtimeout'],useragent=self.opts['_useragent'])if pres['content'] == None:@@ -161,7 +156,7 @@ class sfp_socialprofiles(SpiderFootPlugin):if not found:continue- sf.info("Social Media Profile found at " + site + ": " + match)+ self.sf.info("Social Media Profile found at " + site + ": " + match)evt = SpiderFootEvent("SOCIAL_MEDIA", match,self.__name__, event)self.notifyListeners(evt)diff --git a/modules/sfp_spider.py b/modules/sfp_spider.pyindex 3d570f16..d9cdc5b9 100644--- a/modules/sfp_spider.py+++ b/modules/sfp_spider.py@@ -15,9 +15,6 @@ import reimport timefrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in __init__)-sf = None-class sfp_spider(SpiderFootPlugin):"""Spider:Spidering of web-pages to extract content for searching. """@@ -70,9 +67,7 @@ class sfp_spider(SpiderFootPlugin):siteCookies = dict()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.fetchedPages = dict()self.urlEvents = dict()self.siteCookies = dict()@@ -82,13 +77,13 @@ class sfp_spider(SpiderFootPlugin):# Fetch data from a URL and obtain all links that should be followeddef processUrl(self, url):- site = sf.urlFQDN(url)+ site = self.sf.urlFQDN(url)cookies = Noneif self.siteCookies.has_key(site):- sf.debug("Restoring cookies for " + site + ": " + str(self.siteCookies[site]))+ self.sf.debug("Restoring cookies for " + site + ": " + str(self.siteCookies[site]))cookies = self.siteCookies[site]# Fetch the contents of the supplied URL (object returned)- fetched = sf.fetchUrl(url, False, cookies,+ fetched = self.sf.fetchUrl(url, False, cookies,self.opts['_fetchtimeout'], self.opts['_useragent'])self.fetchedPages[url] = True@@ -96,7 +91,7 @@ class sfp_spider(SpiderFootPlugin):if self.opts['usecookies'] and fetched['headers'] != None:if fetched['headers'].get('Set-Cookie'):self.siteCookies[site] = fetched['headers'].get('Set-Cookie')- sf.debug("Saving cookies for " + site + ": " + str(self.siteCookies[site]))+ self.sf.debug("Saving cookies for " + site + ": " + str(self.siteCookies[site]))if not self.urlEvents.has_key(url):self.urlEvents[url] = None@@ -105,7 +100,7 @@ class sfp_spider(SpiderFootPlugin):self.contentNotify(url, fetched, self.urlEvents[url])if fetched['realurl'] != None and fetched['realurl'] != url:- sf.debug("Redirect of " + url + " to " + fetched['realurl'])+ self.sf.debug("Redirect of " + url + " to " + fetched['realurl'])# Store the content for the redirect so that it isn't fetched againself.fetchedPages[fetched['realurl']] = True# Notify modules about the new link@@ -114,10 +109,10 @@ class sfp_spider(SpiderFootPlugin):url = fetched['realurl'] # override the URL if we had a redirect# Extract links from the content- links = sf.parseLinks(url, fetched['content'], self.getTarget().getNames())+ links = self.sf.parseLinks(url, fetched['content'], self.getTarget().getNames())if links == None or len(links) == 0:- sf.info("No links found at " + url)+ self.sf.info("No links found at " + url)return None# Notify modules about the links found@@ -127,7 +122,7 @@ class sfp_spider(SpiderFootPlugin):# Supply the SpiderFootEvent of the parent URL as the parentself.urlEvents[link] = self.linkNotify(link, self.urlEvents[url])- sf.debug('Links found from parsing: ' + str(links))+ self.sf.debug('Links found from parsing: ' + str(links))return links# Clear out links that we don't want to follow@@ -135,60 +130,60 @@ class sfp_spider(SpiderFootPlugin):returnLinks = dict()for link in links.keys():- linkBase = sf.urlBaseUrl(link)- linkFQDN = sf.urlFQDN(link)+ linkBase = self.sf.urlBaseUrl(link)+ linkFQDN = self.sf.urlFQDN(link)# Optionally skip external sites (typical behaviour..)if self.opts['noexternal'] and not \self.getTarget().matches(linkFQDN):- sf.debug('Ignoring external site: ' + link)+ self.sf.debug('Ignoring external site: ' + link)continue# Optionally skip sub-domain sitesif self.opts['nosubs'] and not \self.getTarget().matches(linkFQDN, includeChildren=False):- sf.debug("Ignoring subdomain: " + link)+ self.sf.debug("Ignoring subdomain: " + link)continue# Optionally skip parent domain sitesif self.opts['noparents'] and not \self.getTarget().matches(linkFQDN, includeParents=False):- sf.debug("Ignoring parent domain: " + link)+ self.sf.debug("Ignoring parent domain: " + link)continue# Optionally skip user directoriesif self.opts['filterusers'] and '/~' in link:- sf.debug("Ignoring user folder: " + link)+ self.sf.debug("Ignoring user folder: " + link)continue# If we are respecting robots.txt, filter those out toocheckRobots = lambda blocked: str.lower(blocked) in link.lower() or blocked == '*'if self.opts['robotsonly'] and filter(checkRobots, self.robotsRules[linkBase]):- sf.debug("Ignoring page found in robots.txt: " + link)+ self.sf.debug("Ignoring page found in robots.txt: " + link)continue# Filter out certain file types (if user chooses to)checkExts = lambda ext: link.lower().split('?')[0].endswith('.' + ext.lower())if filter(checkExts, self.opts['filterfiles']):- sf.debug('Ignoring filtered extension: ' + link)+ self.sf.debug('Ignoring filtered extension: ' + link)continue# All tests passed, add link to be spidered- sf.debug("Adding URL for spidering: " + link)+ self.sf.debug("Adding URL for spidering: " + link)returnLinks[link] = links[link]return returnLinks# Notify listening modules about linksdef linkNotify(self, url, parentEvent=None):- if self.getTarget().matches(sf.urlFQDN(url)):+ if self.getTarget().matches(self.sf.urlFQDN(url)):type = "LINKED_URL_INTERNAL"else:type = "LINKED_URL_EXTERNAL"# Filter out certain file types (if user chooses to)checkExts = lambda ext: url.lower().split('?')[0].endswith('.' + ext.lower())if self.opts['filterexternal'] and filter(checkExts, self.opts['filterfiles']):- sf.debug('Ignoring filtered extension of external link: ' + url)+ self.sf.debug('Ignoring filtered extension of external link: ' + url)return Noneevent = SpiderFootEvent(type, url, self.__name__, parentEvent)@@ -232,13 +227,13 @@ class sfp_spider(SpiderFootPlugin):# Ignore self-generated events so that we don't end up in a recursive loopif "sfp_spider" in srcModuleName:- sf.debug("Ignoring event from myself.")+ self.sf.debug("Ignoring event from myself.")return None- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)if eventData in self.urlEvents.keys():- sf.debug("Ignoring " + eventData + " as already spidered or is being spidered.")+ self.sf.debug("Ignoring " + eventData + " as already spidered or is being spidered.")return Noneelse:self.urlEvents[eventData] = event@@ -246,7 +241,7 @@ class sfp_spider(SpiderFootPlugin):# Determine where to start spidering from if it's a INTERNET_NAME eventif eventName == "INTERNET_NAME":for prefix in self.opts['start']:- res = sf.fetchUrl(prefix + eventData, timeout=self.opts['_fetchtimeout'],+ res = self.sf.fetchUrl(prefix + eventData, timeout=self.opts['_fetchtimeout'],useragent=self.opts['_useragent'])if res['content'] != None:spiderTarget = prefix + eventData@@ -257,7 +252,7 @@ class sfp_spider(SpiderFootPlugin):if spiderTarget == None:return None- sf.info("Initiating spider of " + spiderTarget)+ self.sf.info("Initiating spider of " + spiderTarget)# Link the spidered URL to the event that triggered itself.urlEvents[spiderTarget] = event@@ -269,17 +264,17 @@ class sfp_spider(SpiderFootPlugin):totalFetched = 0levelsTraversed = 0nextLinks = dict()- targetBase = sf.urlBaseUrl(startingPoint)+ targetBase = self.sf.urlBaseUrl(startingPoint)# Are we respecting robots.txt?if self.opts['robotsonly'] and not self.robotsRules.has_key(targetBase):- robotsTxt = sf.fetchUrl(targetBase + '/robots.txt',+ robotsTxt = self.sf.fetchUrl(targetBase + '/robots.txt',timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])if robotsTxt['content'] != None:- sf.debug('robots.txt contents: ' + robotsTxt['content'])- self.robotsRules[targetBase] = sf.parseRobotsTxt(robotsTxt['content'])+ self.sf.debug('robots.txt contents: ' + robotsTxt['content'])+ self.robotsRules[targetBase] = self.sf.parseRobotsTxt(robotsTxt['content'])else:- sf.error("Unable to fetch robots.txt and you've asked to abide by its contents.")+ self.sf.error("Unable to fetch robots.txt and you've asked to abide by its contents.")return None# First iteration we are starting with links found on the start page@@ -289,7 +284,7 @@ class sfp_spider(SpiderFootPlugin):# No links from the first fetch means we've got a problemif links == None:- sf.error("No links found on the first fetch!", exception=False)+ self.sf.error("No links found on the first fetch!", exception=False)returnwhile keepSpidering:@@ -302,14 +297,14 @@ class sfp_spider(SpiderFootPlugin):for link in nextLinks.keys():# Always skip links we've already fetchedif (link in self.fetchedPages.keys()):- sf.debug("Already fetched " + link + ", skipping.")+ self.sf.debug("Already fetched " + link + ", skipping.")continue# Check if we've been asked to stopif self.checkForStop():return None- sf.debug("Fetching fresh content from: " + link)+ self.sf.debug("Fetching fresh content from: " + link)time.sleep(self.opts['pause'])freshLinks = self.processUrl(link)if freshLinks != None:@@ -317,25 +312,25 @@ class sfp_spider(SpiderFootPlugin):totalFetched += 1if totalFetched >= self.opts['maxpages']:- sf.info("Maximum number of pages (" + str(self.opts['maxpages']) + \+ self.sf.info("Maximum number of pages (" + str(self.opts['maxpages']) + \") reached.")keepSpidering = FalsebreaknextLinks = self.cleanLinks(links)- sf.info("Found links: " + str(nextLinks))+ self.sf.info("Found links: " + str(nextLinks))# We've scanned through another layer of the sitelevelsTraversed += 1- sf.info("Now at traversal level: " + str(levelsTraversed))+ self.sf.info("Now at traversal level: " + str(levelsTraversed))if levelsTraversed >= self.opts['maxlevels']:- sf.info("Maximum number of levels (" + str(self.opts['maxlevels']) + \+ self.sf.info("Maximum number of levels (" + str(self.opts['maxlevels']) + \") reached.")keepSpidering = False# We've reached the end of our journey..if len(nextLinks) == 0:- sf.info("No more links found to spider, finishing..")+ self.sf.info("No more links found to spider, finishing..")keepSpidering = False# We've been asked to stop scanningdiff --git a/modules/sfp_sslcert.py b/modules/sfp_sslcert.pyindex 35668cba..a368654a 100644--- a/modules/sfp_sslcert.py+++ b/modules/sfp_sslcert.py@@ -17,9 +17,6 @@ import timeimport M2Cryptofrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_sslcert(SpiderFootPlugin):"""SSL:Gather information about SSL certificates used by the target's HTTPS sites."""@@ -43,9 +40,7 @@ class sfp_sslcert(SpiderFootPlugin):results = dict()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = dict()# Clear / reset any other class member variables here@@ -73,10 +68,10 @@ class sfp_sslcert(SpiderFootPlugin):srcModuleName = event.moduleeventData = event.data- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)if eventName == "LINKED_URL_INTERNAL":- fqdn = sf.urlFQDN(eventData.lower())+ fqdn = self.sf.urlFQDN(eventData.lower())else:fqdn = eventData@@ -88,7 +83,7 @@ class sfp_sslcert(SpiderFootPlugin):if not eventData.lower().startswith("https://") and not self.opts['tryhttp']:return None- sf.debug("Testing SSL for: " + eventData)+ self.sf.debug("Testing SSL for: " + eventData)# Re-fetch the certificate from the site and processtry:s = socket.socket()@@ -100,7 +95,7 @@ class sfp_sslcert(SpiderFootPlugin):cert = ssl.DER_cert_to_PEM_cert(rawcert)m2cert = M2Crypto.X509.load_cert_string(cert)except BaseException as x:- sf.info("Unable to SSL-connect to " + fqdn + ": " + str(x))+ self.sf.info("Unable to SSL-connect to " + fqdn + ": " + str(x))return None# Generate the event for the raw cert (in text form)@@ -133,14 +128,14 @@ class sfp_sslcert(SpiderFootPlugin):# Extract the CN from the issued sectionissued = cert.get_subject().as_text()- sf.debug("Checking for " + fqdn + " in " + issued.lower())+ self.sf.debug("Checking for " + fqdn + " in " + issued.lower())if "cn=" + fqdn in issued.lower():hosts = 'dns:' + fqdntry:hosts = hosts + " " + cert.get_ext("subjectAltName").get_value().lower()except LookupError as e:- sf.debug("No alternative name found in certificate.")+ 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:diff --git a/modules/sfp_stor_print.py b/modules/sfp_stor_print.pyindex 0ad9726f..3c9e4706 100644--- a/modules/sfp_stor_print.py+++ b/modules/sfp_stor_print.py@@ -14,9 +14,6 @@ import sysimport refrom sflib import SpiderFoot, SpiderFootPlugin-# SpiderFoot standard lib (must be initialized in __init__)-sf = None-class sfp_stor_print(SpiderFootPlugin):# Default optionsopts = {@@ -29,9 +26,7 @@ class sfp_stor_print(SpiderFootPlugin):}def __init__(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcfor opt in userOpts.keys():self.opts[opt] = userOpts[opt]@@ -46,15 +41,15 @@ class sfp_stor_print(SpiderFootPlugin):# Handle events sent to this moduledef handleEvent(self, srcModuleName, eventName, eventSource, eventSourceEvent, eventData):- sf.debug("RESULT:")- sf.debug("\tSource: " + srcModuleName)- sf.debug("\tEvent: " + eventName)- sf.debug("\tEvent Source: " + eventSource)+ self.sf.debug("RESULT:")+ self.sf.debug("\tSource: " + srcModuleName)+ self.sf.debug("\tEvent: " + eventName)+ self.sf.debug("\tEvent Source: " + eventSource)if len(eventData) > self.opts['datasize']:eventDataStripped = eventData[0:self.opts['datasize']] + '...'else:eventDataStripped = eventData- sf.debug("\tEvent Data: " + eventDataStripped)+ self.sf.debug("\tEvent Data: " + eventDataStripped)return Nonediff --git a/modules/sfp_strangeheaders.py b/modules/sfp_strangeheaders.pyindex db61c7da..ae59fabd 100644--- a/modules/sfp_strangeheaders.py+++ b/modules/sfp_strangeheaders.py@@ -14,9 +14,6 @@ import sysimport refrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-# Standard headers, taken from http://en.wikipedia.org/wiki/List_of_HTTP_header_fieldsheaders = [ "access-control-allow-origin","accept-ranges","age","allow","cache-control","connection","content-encoding","content-language","content-length","content-location",@@ -36,9 +33,7 @@ class sfp_strangeheaders(SpiderFootPlugin):results = dict()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = dict()for opt in userOpts.keys():@@ -62,14 +57,14 @@ class sfp_strangeheaders(SpiderFootPlugin):parentEvent = event.sourceEventeventSource = event.sourceEvent.data- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)if self.results.has_key(eventSource):return Noneelse:self.results[eventSource] = True- if not self.getTarget().matches(sf.urlFQDN(eventSource)):- sf.debug("Not collecting header information for external sites.")+ if not self.getTarget().matches(self.sf.urlFQDN(eventSource)):+ self.sf.debug("Not collecting header information for external sites.")return Nonefor key in eventData:diff --git a/modules/sfp_template.py b/modules/sfp_template.pyindex af686735..0378f8d7 100644--- a/modules/sfp_template.py+++ b/modules/sfp_template.py@@ -12,9 +12,6 @@import sysfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_XXX(SpiderFootPlugin):"""Name:Description"""@@ -35,9 +32,7 @@ class sfp_XXX(SpiderFootPlugin):results = dict()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = dict()# Clear / reset any other class member variables here@@ -66,7 +61,7 @@ class sfp_XXX(SpiderFootPlugin):# would get the source of that raw data (e.g. a URL.)eventSource = event.sourceEvent.data- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)# DO SOMETHING HEREdiff --git a/modules/sfp_tldsearch.py b/modules/sfp_tldsearch.pyindex 1b5eaa75..e5142dfd 100644--- a/modules/sfp_tldsearch.py+++ b/modules/sfp_tldsearch.py@@ -18,9 +18,6 @@ import randomimport threadingfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_tldsearch(SpiderFootPlugin):"""TLD Search:Search all Internet TLDs for domains with the same name as the target (this can be slow.)"""@@ -45,9 +42,7 @@ class sfp_tldsearch(SpiderFootPlugin):tldResults = dict()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = list()for opt in userOpts.keys():@@ -77,7 +72,7 @@ class sfp_tldsearch(SpiderFootPlugin):t = []# Spawn threads for scanning- sf.info("Spawning threads to check TLDs: " + str(tldList))+ 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,)))@@ -100,7 +95,7 @@ class sfp_tldsearch(SpiderFootPlugin):# Store the result internally and notify listening modulesdef sendEvent(self, source, result):- sf.info("Found a TLD with the target's name: " + result)+ self.sf.info("Found a TLD with the target's name: " + result)self.results.append(result)# Inform listening modules@@ -108,7 +103,7 @@ class sfp_tldsearch(SpiderFootPlugin):if self.checkForStop():return None- pageContent = sf.fetchUrl('http://' + result,+ pageContent = self.sf.fetchUrl('http://' + result,timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])if pageContent['content'] != None:evt = SpiderFootEvent("SIMILARDOMAIN", result, self.__name__)@@ -128,8 +123,8 @@ class sfp_tldsearch(SpiderFootPlugin):else:self.results.append(eventData)- keyword = sf.domainKeyword(eventData, self.opts['_internettlds'])- sf.debug("Keyword extracted from " + eventData + ": " + keyword)+ keyword = self.sf.domainKeyword(eventData, self.opts['_internettlds'])+ self.sf.debug("Keyword extracted from " + eventData + ": " + keyword)targetList = list()# Look through all TLDs for the existence of this target keyword@@ -148,7 +143,7 @@ class sfp_tldsearch(SpiderFootPlugin):if tld.endswith(".arpa"):continue- if self.opts['skipwildcards'] and sf.checkDnsWildcard(tld):+ if self.opts['skipwildcards'] and self.sf.checkDnsWildcard(tld):continuetryDomain = keyword + "." + tlddiff --git a/modules/sfp_virustotal.py b/modules/sfp_virustotal.pyindex 212d43fb..03cc52df 100644--- a/modules/sfp_virustotal.py+++ b/modules/sfp_virustotal.py@@ -14,9 +14,6 @@ import jsonimport timefrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_virustotal(SpiderFootPlugin):"""VirusTotal:Obtain information from VirusTotal about identified IP addresses."""@@ -42,9 +39,7 @@ class sfp_virustotal(SpiderFootPlugin):results = dict()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = dict()# Clear / reset any other class member variables here@@ -70,15 +65,15 @@ class sfp_virustotal(SpiderFootPlugin):srcModuleName = event.moduleeventData = event.data- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)if self.opts['apikey'] == "":- sf.error("You enabled sfp_virustotal but did not set an API key!", False)+ self.sf.error("You enabled sfp_virustotal but did not set an API key!", False)return None# Don't look up stuff twiceif self.results.has_key(eventData):- sf.debug("Skipping " + eventData + " as already mapped.")+ self.sf.debug("Skipping " + eventData + " as already mapped.")return Noneelse:self.results[eventData] = True@@ -94,7 +89,7 @@ class sfp_virustotal(SpiderFootPlugin):else:url = "https://www.virustotal.com/vtapi/v2/ip-address/report?ip="- res = sf.fetchUrl(url + eventData + "&apikey=" + self.opts['apikey'],+ res = self.sf.fetchUrl(url + eventData + "&apikey=" + self.opts['apikey'],timeout=self.opts['_fetchtimeout'], useragent="SpiderFoot")# Public API is limited to 4 queries per minute@@ -102,17 +97,17 @@ class sfp_virustotal(SpiderFootPlugin):time.sleep(15)if res['content'] == None:- sf.info("No VirusTotal info found for " + eventData)+ self.sf.info("No VirusTotal info found for " + eventData)return Nonetry:info = json.loads(res['content'])except Exception as e:- sf.error("Error processing JSON response from VirusTotal.", False)+ self.sf.error("Error processing JSON response from VirusTotal.", False)return Noneif info.has_key('detected_urls'):- sf.info("Found VirusTotal URL data for " + eventData)+ self.sf.info("Found VirusTotal URL data for " + eventData)if eventName == "IP_ADDRESS":evt = "MALICIOUS_IPADDR"infotype = "ip-address"diff --git a/modules/sfp_webframework.py b/modules/sfp_webframework.pyindex 610a39c1..42a0ec84 100644--- a/modules/sfp_webframework.py+++ b/modules/sfp_webframework.py@@ -13,9 +13,6 @@ import reimport sysfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-regexps = dict({"jQuery": list(['jquery']), # unlikely false positive"YUI": list(['\/yui\/', 'yui\-', 'yui\.']),@@ -45,9 +42,7 @@ class sfp_webframework(SpiderFootPlugin):results = dict()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = dict()for opt in userOpts.keys():@@ -78,14 +73,14 @@ class sfp_webframework(SpiderFootPlugin):# source of that raw data (e.g. a URL.)eventSource = event.sourceEvent.data- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ 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(sf.urlFQDN(eventSource)):- sf.debug("Not collecting web content information for external sites.")+ if not self.getTarget().matches(self.sf.urlFQDN(eventSource)):+ self.sf.debug("Not collecting web content information for external sites.")return Nonefor regexpGrp in regexps.keys():@@ -96,7 +91,7 @@ class sfp_webframework(SpiderFootPlugin):pat = re.compile(regex, re.IGNORECASE)matches = re.findall(pat, eventData)if len(matches) > 0 and regexpGrp not in self.results[eventSource]:- sf.info("Matched " + regexpGrp + " in content from " + 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)diff --git a/modules/sfp_websvr.py b/modules/sfp_websvr.pyindex 93e7f882..79a44074 100644--- a/modules/sfp_websvr.py+++ b/modules/sfp_websvr.py@@ -14,9 +14,6 @@ import sysimport refrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_websvr(SpiderFootPlugin):"""Web Server:Obtain web server banners to identify versions of web servers being used."""@@ -26,9 +23,7 @@ class sfp_websvr(SpiderFootPlugin):results = dict()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = dict()for opt in userOpts.keys():@@ -52,14 +47,14 @@ class sfp_websvr(SpiderFootPlugin):parentEvent = event.sourceEventeventSource = event.sourceEvent.data- sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)if self.results.has_key(eventSource):return Noneelse:self.results[eventSource] = True- if not self.getTarget().matches(sf.urlFQDN(eventSource)):- sf.debug("Not collecting web server information for external sites.")+ 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@@ -71,7 +66,7 @@ class sfp_websvr(SpiderFootPlugin):self.__name__, parentEvent)self.notifyListeners(evt)- sf.info("Found web server: " + eventData['server'] + " (" + eventSource + ")")+ self.sf.info("Found web server: " + eventData['server'] + " (" + eventSource + ")")if eventData.has_key('x-powered-by'):evt = SpiderFootEvent("WEBSERVER_TECHNOLOGY", eventData['x-powered-by'],diff --git a/modules/sfp_yahoosearch.py b/modules/sfp_yahoosearch.pyindex aa59fb46..68f29c89 100644--- a/modules/sfp_yahoosearch.py+++ b/modules/sfp_yahoosearch.py@@ -16,9 +16,6 @@ import timeimport urllibfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent-# SpiderFoot standard lib (must be initialized in setup)-sf = None-class sfp_yahoosearch(SpiderFootPlugin):"""Yahoo:Some light Yahoo scraping to identify sub-domains and links."""@@ -37,9 +34,7 @@ class sfp_yahoosearch(SpiderFootPlugin):results = list()def setup(self, sfc, userOpts=dict()):- global sf-- sf = sfc+ self.sf = sfcself.results = list()for opt in userOpts.keys():@@ -64,16 +59,16 @@ class sfp_yahoosearch(SpiderFootPlugin):eventData = event.dataif eventData in self.results:- sf.debug("Already did a search for " + eventData + ", skipping.")+ self.sf.debug("Already did a search for " + eventData + ", skipping.")return Noneelse:self.results.append(eventData)# Sites hosted on the domain- pages = sf.yahooIterate("site:" + eventData, dict(limit=self.opts['pages'],+ pages = self.sf.yahooIterate("site:" + eventData, dict(limit=self.opts['pages'],useragent=self.opts['_useragent'], timeout=self.opts['_fetchtimeout']))if pages == None:- sf.info("No results returned from Yahoo.")+ self.sf.info("No results returned from Yahoo.")return Nonefor page in pages.keys():@@ -95,7 +90,7 @@ class sfp_yahoosearch(SpiderFootPlugin):# We can optionally fetch links to our domain found in the search# results. These may not have been identified through spidering.if self.opts['fetchlinks']:- links = sf.parseLinks(page, content, eventData)+ links = self.sf.parseLinks(page, content, eventData)if len(links) == 0:continue@@ -104,8 +99,8 @@ class sfp_yahoosearch(SpiderFootPlugin):continueelse:self.results.append(link)- if sf.urlFQDN(link).endswith(eventData):- sf.debug("Found a link: " + link)+ if self.sf.urlFQDN(link).endswith(eventData):+ self.sf.debug("Found a link: " + link)if self.checkForStop():return Nonediff --git a/sf.py b/sf.pyindex d0812758..81f3dbae 100755--- a/sf.py+++ b/sf.py@@ -64,7 +64,6 @@ sfConfig = {'__database': 'spiderfoot.db','__webaddr': '127.0.0.1','__webport': 5001,- '__guid__': None, # unique ID of scan. Will be set after start-up.'__modules__': None, # List of modules. Will be set after start-up.'_socks1type': '','_socks2addr': '',diff --git a/sfdb.py b/sfdb.pyindex f3d96cbd..e9a1c9a5 100644--- a/sfdb.py+++ b/sfdb.py@@ -16,10 +16,11 @@ import sysimport timefrom sflib import SpiderFoot-# SpiderFoot class passed to us-sf = None-class SpiderFootDb:+ sf = None+ dbh = None+ conn = None+# Queries for creating the SpiderFoot databasecreateQueries = ["PRAGMA journal_mode=WAL",@@ -145,15 +146,14 @@ class SpiderFootDb:]def __init__(self, opts):- global sf- sf = SpiderFoot(opts)+ self.sf = SpiderFoot(opts)# connect() will create the database file if it doesn't exist, but# at least we can use this opportunity to ensure we have permissions to# read and write to such a file.- dbh = sqlite3.connect(sf.myPath() + "/" + opts['__database'], timeout=10)+ dbh = sqlite3.connect(self.sf.myPath() + "/" + opts['__database'], timeout=10)if dbh == None:- sf.fatal("Could not connect to internal database, and couldn't create " + \+ self.sf.fatal("Could not connect to internal database, and couldn't create " + \opts['__database'])dbh.text_factory = str@@ -169,7 +169,7 @@ class SpiderFootDb:try:self.create()except BaseException as e:- sf.error("Tried to set up the SpiderFoot database schema, but failed: " + \+ self.sf.error("Tried to set up the SpiderFoot database schema, but failed: " + \e.args[0])return@@ -198,7 +198,7 @@ class SpiderFootDb:self.dbh.execute(qry)return self.dbh.fetchall()except sqlite3.Error as e:- sf.error("SQL error encountered when retreiving event types:" ++ self.sf.error("SQL error encountered when retreiving event types:" +e.args[0])# Log an event to the database@@ -217,21 +217,12 @@ class SpiderFootDb:except sqlite3.Error as e:if "locked" in e.args[0]:# TODO: Do something smarter here to handle locked databases- sf.fatal("Unable to log event in DB: " + e.args[0])+ self.sf.fatal("Unable to log event in DB: " + e.args[0])else:- sf.fatal("Unable to log event in DB: " + e.args[0])+ self.sf.fatal("Unable to log event in DB: " + e.args[0])return True- # Generate an globally unique ID for this scan- def scanInstanceGenGUID(self, scanName):- hashStr = hashlib.sha256(- scanName +- str(time.time() * 1000) +- str(random.randint(100000, 999999))- ).hexdigest()- return hashStr-# Store a scan instancedef scanInstanceCreate(self, instanceId, scanName, scanTarget):qry = "INSERT INTO tbl_scan_instance \@@ -243,7 +234,7 @@ class SpiderFootDb:))self.conn.commit()except sqlite3.Error as e:- sf.fatal("Unable to create instance in DB: " + e.args[0])+ self.sf.fatal("Unable to create instance in DB: " + e.args[0])return True@@ -272,7 +263,7 @@ class SpiderFootDb:self.dbh.execute(qry, qvars)self.conn.commit()except sqlite3.Error:- sf.fatal("Unable to set information for the scan instance.")+ self.sf.fatal("Unable to set information for the scan instance.")# Return info about a scan instance (name, target, created, started,# ended, status) - don't need this yet - untested@@ -285,7 +276,7 @@ class SpiderFootDb:self.dbh.execute(qry, qvars)return self.dbh.fetchone()except sqlite3.Error as e:- sf.error("SQL error encountered when retreiving scan instance:" ++ self.sf.error("SQL error encountered when retreiving scan instance:" +e.args[0])# Obtain a summary of the results per event type@@ -299,7 +290,7 @@ class SpiderFootDb:self.dbh.execute(qry, qvars)return self.dbh.fetchall()except sqlite3.Error as e:- sf.error("SQL error encountered when fetching result summary: " ++ self.sf.error("SQL error encountered when fetching result summary: " +e.args[0])# Obtain the data for a scan and event type@@ -327,7 +318,7 @@ class SpiderFootDb:self.dbh.execute(qry, qvars)return self.dbh.fetchall()except sqlite3.Error as e:- sf.error("SQL error encountered when fetching result events: " ++ self.sf.error("SQL error encountered when fetching result events: " +e.args[0])# Obtain a unique list of elements@@ -346,7 +337,7 @@ class SpiderFootDb:self.dbh.execute(qry, qvars)return self.dbh.fetchall()except sqlite3.Error as e:- sf.error("SQL error encountered when fetching unique result events: " ++ self.sf.error("SQL error encountered when fetching unique result events: " +e.args[0])# Get scan logs@@ -364,7 +355,7 @@ class SpiderFootDb:self.dbh.execute(qry, qvars)return self.dbh.fetchall()except sqlite3.Error as e:- sf.error("SQL error encountered when fetching scan logs: " ++ self.sf.error("SQL error encountered when fetching scan logs: " +e.args[0])# Get scan errors@@ -382,7 +373,7 @@ class SpiderFootDb:self.dbh.execute(qry, qvars)return self.dbh.fetchall()except sqlite3.Error as e:- sf.error("SQL error encountered when fetching scan errors: " ++ self.sf.error("SQL error encountered when fetching scan errors: " +e.args[0])# Delete a scan instance@@ -399,7 +390,7 @@ class SpiderFootDb:self.dbh.execute(qry4, qvars)self.conn.commit()except sqlite3.Error as e:- sf.error("SQL error encountered when deleting scan: " ++ self.sf.error("SQL error encountered when deleting scan: " +e.args[0])# Store the default configuration@@ -417,7 +408,7 @@ class SpiderFootDb:try:self.dbh.execute(qry, qvals)except sqlite3.Error as e:- sf.error("SQL error encountered when storing config, aborting: " ++ self.sf.error("SQL error encountered when storing config, aborting: " +e.args[0])self.conn.commit()@@ -436,7 +427,7 @@ class SpiderFootDb:return retvalexcept sqlite3.Error as e:- sf.error("SQL error encountered when fetching configuration: " + e.args[0])+ self.sf.error("SQL error encountered when fetching configuration: " + e.args[0])# Reset the config to default (clear it from the DB and let the hard-coded# settings in the code take effect.)@@ -446,7 +437,7 @@ class SpiderFootDb:self.dbh.execute(qry)self.conn.commit()except sqlite3.Error as e:- sf.error("Unable to clear configuration from the database: " + e.args[0])+ self.sf.error("Unable to clear configuration from the database: " + e.args[0])# Store a configuration value for a scandef scanConfigSet(self, id, optMap=dict()):@@ -465,7 +456,7 @@ class SpiderFootDb:try:self.dbh.execute(qry, qvals)except sqlite3.Error as e:- sf.error("SQL error encountered when storing config, aborting: " ++ self.sf.error("SQL error encountered when storing config, aborting: " +e.args[0])self.conn.commit()@@ -485,7 +476,7 @@ class SpiderFootDb:retval[component + ":" + opt] = valreturn retvalexcept sqlite3.Error as e:- sf.error("SQL error encountered when fetching configuration: " + e.args[0])+ self.sf.error("SQL error encountered when fetching configuration: " + e.args[0])# Store an event# eventData is a SpiderFootEvent object with the following variables:@@ -510,7 +501,7 @@ class SpiderFootDb:try:storeData = unicode(str(sfEvent.data), 'utf-8', errors='replace')except BaseException as e:- sf.fatal("Unhandled type detected: " + str(type(sfEvent.data)))+ self.sf.fatal("Unhandled type detected: " + str(type(sfEvent.data)))else:storeData = sfEvent.data@@ -532,7 +523,7 @@ class SpiderFootDb:self.conn.commit()return Noneexcept sqlite3.Error as e:- sf.fatal("SQL error encountered when storing event data (" + str(self.dbh) + ": " ++ self.sf.fatal("SQL error encountered when storing event data (" + str(self.dbh) + ": " +e.args[0])# List of all previously run scans@@ -554,7 +545,7 @@ class SpiderFootDb:self.dbh.execute(qry)return self.dbh.fetchall()except sqlite3.Error as e:- sf.error("SQL error encountered when fetching scan list: " + e.args[0])+ self.sf.error("SQL error encountered when fetching scan list: " + e.args[0])# History of data from the scandef scanResultHistory(self, instanceId):@@ -566,7 +557,7 @@ class SpiderFootDb:self.dbh.execute(qry, qvars)return self.dbh.fetchall()except sqlite3.Error as e:- sf.error("SQL error encountered when fetching scan history: " + e.args[0])+ self.sf.error("SQL error encountered when fetching scan history: " + e.args[0])# Get the source IDs, types and data for a set of IDs@@ -591,6 +582,6 @@ class SpiderFootDb:self.dbh.execute(qry, qvars)return self.dbh.fetchall()except sqlite3.Error as e:- sf.error("SQL error encountered when getting source element IDs: " + e.args[0])+ self.sf.error("SQL error encountered when getting source element IDs: " + e.args[0])diff --git a/sflib.py b/sflib.pyindex 6c56ded1..939b6873 100644--- a/sflib.py+++ b/sflib.py@@ -22,10 +22,12 @@ import timeimport netaddrimport urllib2import StringIO+import threading+from copy import deepcopyclass SpiderFoot:dbh = None- scanGUID = None+ GUID = None# 'options' is a dictionary of options which changes the behaviour# of how certain things are done in this module@@ -33,7 +35,7 @@ class SpiderFoot:# SpiderFoot GUI, in which case all feedback should be fed backdef __init__(self, options, handle=None):self.handle = handle- self.opts = options+ self.opts = deepcopy(options)# Bit of a hack to support SOCKS because of the loading order of# modules. sfscan will call this to update the socket reference@@ -89,11 +91,23 @@ class SpiderFoot:def setDbh(self, handle):self.dbh = handle- def setScanId(self, id):- self.scanGUID = id+ # Set the GUID this instance of SpiderFoot is being+ # used in.+ def setGUID(self, uid):+ self.GUID = uid++ # Generate an globally unique ID for this scan+ def genScanInstanceGUID(self, scanName):+ hashStr = hashlib.sha256(+ scanName ++ str(time.time() * 1000) ++ str(random.randint(100000, 999999))+ ).hexdigest()+ return hashStrdef _dblog(self, level, message, component=None):- return self.dbh.scanLogEvent(self.scanGUID, level, message, component)+ #print str(self.GUID) + ":" + str(level) + ":" + str(message) + ":" + str(component)+ return self.dbh.scanLogEvent(self.GUID, level, message, component)def error(self, error, exception=True):if self.dbh == None:@@ -108,6 +122,7 @@ class SpiderFoot:print '[Fatal] ' + errorelse:self._dblog("FATAL", error)+ print str(inspect.stack())exit(-1)def status(self, message):@@ -986,6 +1001,11 @@ class SpiderFootPlugin(object):_currentTarget = None# Name of this module, set at startup time__name__ = "module_name_not_set!"+ # Direct handle to the database - not to be directly used+ # by modules except the sfp__stor_db module.+ __sfdb__ = None+ # ID of the scan the module is running against+ __scanId__ = None# Not really needed in most cases.def __init__(self):@@ -1016,6 +1036,19 @@ class SpiderFootPlugin(object):def setTarget(self, target):self._currentTarget = target+ # Used to set the database handle, which is only to be used+ # by modules in very rare/exceptional cases (e.g. sfp__stor_db)+ def setDbh(self, dbh):+ self.__sfdb__ = dbh++ # Set the scan ID+ def setScanId(self, id):+ self.__scanId__ = id++ # Get the scan ID+ def getScanId(self):+ return self.__scanId__+# Gets the current target this module is acting againstdef getTarget(self):if self._currentTarget == None:@@ -1083,15 +1116,16 @@ class SpiderFootPlugin(object):if self.checkForStop():return None+ #print "EVENT: " + str(sfEvent)listener.handleEvent(sfEvent)- # Called to stop scanning- def stopScanning(self):- self._stopScanning = True-# For modules to use to check for when they should give back controldef checkForStop(self):- return self._stopScanning+ global globalScanStatus++ if globalScanStatus.getStatus(self.__scanId__) == "ABORT-REQUESTED":+ return True+ return False# Return a list of the default configuration options for the module.def defaultOpts(self):@@ -1203,6 +1237,9 @@ class SpiderFootTarget(object):def matches(self, value, includeParents=False, includeChildren=True):value = value.lower()+ if value == None:+ return False+if netaddr.valid_ipv4(value):# 1.1if value in self.getAddresses():@@ -1407,3 +1444,27 @@ class PublicSuffixList(object):for i, what in enumerate(hits):if what is not None and what == 0:return '.'.join(parts[i:])++# Class for tracking the status of all running scans. Thread safe.+class SpiderFootScanStatus:+ statusTable = dict()+ lock = threading.Lock()++ def setStatus(self, scanId, status):+ with self.lock:+ self.statusTable[scanId] = status++ def getStatus(self, scanId):+ with self.lock:+ if self.statusTable.has_key(scanId):+ return self.statusTable[scanId]+ return None++ def getStatusAll(self):+ with self.lock:+ return self.statusTable++# Global variable accessed by various places to get the status of+# running scans.+globalScanStatus = SpiderFootScanStatus()+diff --git a/sfscan.py b/sfscan.pyindex ec169ce1..8c07fb39 100644--- a/sfscan.py+++ b/sfscan.py@@ -17,107 +17,113 @@ import sysimport socketimport socksimport dns.resolver-from copy import deepcopy+import threading+import thread+import random+from copy import deepcopy, copyfrom sfdb import SpiderFootDb-from sflib import SpiderFoot, SpiderFootEvent, SpiderFootTarget+from sflib import SpiderFoot, SpiderFootEvent, SpiderFootTarget, globalScanStatus-# Controls all scanning activity# Eventually change this to be able to control multiple scan instances-class SpiderFootScanner:- moduleInstances = None- status = "UNKNOWN"- myId = None- targetValue = None- targetType = None-- def __init__(self, name, target, moduleList, globalOpts, moduleOpts):- self.config = deepcopy(globalOpts)- self.sf = SpiderFoot(self.config)- self.targetValue = target- self.moduleList = moduleList- self.name = name-- regexToType = {- "^\d+\.\d+\.\d+\.\d+$": "IP_ADDRESS",- "^\d+\.\d+\.\d+\.\d+/\d+$": "IP_SUBNET",- "^.[a-zA-Z\-0-9\.]+$": "INTERNET_NAME"- }-- # Parse the target and set the targetType- for rx in regexToType.keys():- if re.match(rx, self.targetValue, re.IGNORECASE):- self.targetType = regexToType[rx]- break-- # Unrecognized target type- if self.targetType == None:- raise BaseException()-- # Status of the currently running scan (if any)- def scanStatus(self, id):- if id != self.myId:- return "UNKNOWN"- return self.status-- # Stop a scan (id variable is unnecessary for now given that only one simultaneous- # scan is permitted.)- def stopScan(self, id):- if id != self.myId:- return None-- if self.moduleInstances == None:- return None-- for modName in self.moduleInstances.keys():- self.moduleInstances[modName].stopScanning()+class SpiderFootScanner(threading.Thread):+ # Thread-safe storage+ ts = None+ # Temporary storage+ temp = None++ # moduleOpts not yet used+ def __init__(self, scanName, scanTarget, targetType, scanId, moduleList,+ globalOpts, moduleOpts):++ # Initialize the thread+ threading.Thread.__init__(self, name="SF_"+scanName+\+ str(random.randint(100000, 999999)))++ # Temporary data to be used in startScan+ self.temp = dict()+ self.temp['config'] = deepcopy(globalOpts)+ self.temp['targetValue'] = scanTarget+ self.temp['targetType'] = targetType+ self.temp['moduleList'] = moduleList+ self.temp['scanName'] = scanName+ self.temp['scanId'] = scanId++ # Set the status of the currently running scan (if any)+ def setStatus(self, status, started=None, ended=None):+ if self.ts == None:+ print "Internal Error: Status set attempted before " + \+ "SpiderFootScanner was ready."+ exit(-1)++ self.ts.status = status+ self.ts.dbh.scanInstanceSet(self.ts.scanId, started, ended, status)+ globalScanStatus.setStatus(self.ts.scanId, status)+ return None++ def run(self):+ self.startScan()++ def getId(self):+ if hasattr(self.ts, 'scanId'):+ return self.ts.scanId+ return None# Start running a scandef startScan(self):- self.moduleInstances = dict()- dbh = SpiderFootDb(self.config)- self.sf.setDbh(dbh)+ global globalScanStatus++ self.ts = threading.local()+ self.ts.moduleInstances = dict()+ self.ts.sf = SpiderFoot(self.temp['config'])+ self.ts.config = deepcopy(self.temp['config'])+ self.ts.dbh = SpiderFootDb(self.temp['config'])+ self.ts.targetValue = self.temp['targetValue']+ self.ts.targetType = self.temp['targetType']+ self.ts.moduleList = self.temp['moduleList']+ self.ts.modconfig = dict()+ self.ts.scanName = self.temp['scanName']+ self.ts.scanId = self.temp['scanId']aborted = False+ self.ts.sf.setDbh(self.ts.dbh)# Create a unique ID for this scan and create it in the back-end DB.- self.config['__guid__'] = dbh.scanInstanceGenGUID(self.targetValue)- self.sf.setScanId(self.config['__guid__'])- self.myId = self.config['__guid__']- dbh.scanInstanceCreate(self.config['__guid__'], self.name, self.targetValue)- dbh.scanInstanceSet(self.config['__guid__'], time.time() * 1000, None, 'STARTING')- self.status = "STARTING"-+ self.ts.sf.setGUID(self.ts.scanId)+ self.ts.dbh.scanInstanceCreate(self.ts.scanId,+ self.ts.scanName, self.ts.targetValue)+ self.setStatus("STARTING", time.time() * 1000, None)# Create our target- target = SpiderFootTarget(self.targetValue, self.targetType)+ target = SpiderFootTarget(self.ts.targetValue, self.ts.targetType)# Save the config current set for this scan- self.config['_modulesenabled'] = self.moduleList- dbh.scanConfigSet(self.config['__guid__'], self.sf.configSerialize(self.config))+ self.ts.config['_modulesenabled'] = self.ts.moduleList+ self.ts.dbh.scanConfigSet(self.ts.scanId,+ self.ts.sf.configSerialize(deepcopy(self.ts.config)))- self.sf.status("Scan [" + self.config['__guid__'] + "] initiated.")+ self.ts.sf.status("Scan [" + self.ts.scanId + "] initiated.")# moduleList = list of modules the user wants to runtry:# Process global options that point to other places for data# If a SOCKS server was specified, set it up- if self.config['_socks1type'] != '':+ if self.ts.config['_socks1type'] != '':socksType = socks.PROXY_TYPE_SOCKS4- socksDns = self.config['_socks6dns']- socksAddr = self.config['_socks2addr']- socksPort = int(self.config['_socks3port'])+ socksDns = self.ts.config['_socks6dns']+ socksAddr = self.ts.config['_socks2addr']+ socksPort = int(self.ts.config['_socks3port'])socksUsername = ''socksPassword = ''- if self.config['_socks1type'] == '4':+ if self.ts.config['_socks1type'] == '4':socksType = socks.PROXY_TYPE_SOCKS4- if self.config['_socks1type'] == '5':+ if self.ts.config['_socks1type'] == '5':socksType = socks.PROXY_TYPE_SOCKS5- socksUsername = self.config['_socks4user']- socksPassword = self.config['_socks5pwd']+ socksUsername = self.ts.config['_socks4user']+ socksPassword = self.ts.config['_socks5pwd']- if self.config['_socks1type'] == 'HTTP':+ if self.ts.config['_socks1type'] == 'HTTP':socksType = socks.PROXY_TYPE_HTTP- self.sf.debug("SOCKS: " + socksAddr + ":" + str(socksPort) + \+ self.ts.sf.debug("SOCKS: " + socksAddr + ":" + str(socksPort) + \"(" + socksUsername + ":" + socksPassword + ")")socks.setdefaultproxy(socksType, socksAddr, socksPort,socksDns, socksUsername, socksPassword)@@ -128,70 +134,71 @@ class SpiderFootScanner:socket.create_connection = socks.create_connectionsocket.getaddrinfo = socks.getaddrinfo- self.sf.updateSocket(socket)+ self.ts.sf.updateSocket(socket)# Override the default DNS server- if self.config['_dnsserver'] != "":+ if self.ts.config['_dnsserver'] != "":res = dns.resolver.Resolver()- res.nameservers = [ self.config['_dnsserver'] ]+ res.nameservers = [ self.ts.config['_dnsserver'] ]dns.resolver.override_system_resolver(res)else:dns.resolver.restore_system_resolver()# Set the user agent- self.config['_useragent'] = self.sf.optValueToData(self.config['_useragent'])+ self.ts.config['_useragent'] = self.ts.sf.optValueToData(+ self.ts.config['_useragent'])# Get internet TLDs- tlddata = self.sf.cacheGet("internet_tlds", self.config['_internettlds_cache'])+ tlddata = self.ts.sf.cacheGet("internet_tlds",+ self.ts.config['_internettlds_cache'])# If it wasn't loadable from cache, load it from scratchif tlddata == None:- self.config['_internettlds'] = self.sf.optValueToData(self.config['_internettlds'])- self.sf.cachePut("internet_tlds", self.config['_internettlds'])+ self.ts.config['_internettlds'] = self.ts.sf.optValueToData(+ self.ts.config['_internettlds'])+ self.ts.sf.cachePut("internet_tlds", self.ts.config['_internettlds'])else:- self.config["_internettlds"] = tlddata.splitlines()+ self.ts.config["_internettlds"] = tlddata.splitlines()- for modName in self.moduleList:+ for modName in self.ts.moduleList:if modName == '':continue- module = __import__('modules.' + modName, globals(), locals(), [modName])+ module = __import__('modules.' + modName, globals(), locals(),+ [modName])mod = getattr(module, modName)()mod.__name__ = modName- # A bit hacky: we pass the database object as part of the config. This- # object should only be used by the internal SpiderFoot modules writing- # to the database, which at present is only sfp__stor_db.- # Individual modules cannot create their own SpiderFootDb instance or- # we'll get database locking issues, so it all goes through this.- self.config['__sfdb__'] = dbh-# Set up the module# Configuration is a combined global config with module-specific options- #modConfig = deepcopy(self.config)- modConfig = self.config['__modules__'][modName]['opts']- for opt in self.config.keys():- modConfig[opt] = self.config[opt]+ self.ts.modconfig[modName] = deepcopy(self.ts.config['__modules__'][modName]['opts'])+ for opt in self.ts.config.keys():+ self.ts.modconfig[modName][opt] = deepcopy(self.ts.config[opt])mod.clearListeners() # clear any listener relationships from the past- mod.setup(self.sf, modConfig)+ mod.setup(self.ts.sf, self.ts.modconfig[modName])+ mod.setDbh(self.ts.dbh)+ mod.setScanId(self.ts.scanId)++ # Give modules a chance to 'enrich' the original target with+ # aliases of that target.newTarget = mod.enrichTarget(target)if newTarget != None:target = newTarget- self.moduleInstances[modName] = mod+ self.ts.moduleInstances[modName] = mod# Override the module's local socket module# to be the SOCKS one.- if self.config['_socks1type'] != '':+ if self.ts.config['_socks1type'] != '':mod._updateSocket(socket)- self.sf.status(modName + " module loaded.")+ self.ts.sf.status(modName + " module loaded.")# Register listener modules and then start all modules sequentially- for module in self.moduleInstances.values():+ for module in self.ts.moduleInstances.values():# Register the target with the modulemodule.setTarget(target)- for listenerModule in self.moduleInstances.values():+ for listenerModule in self.ts.moduleInstances.values():# Careful not to register twice or you will get duplicate eventsif listenerModule in module._listenerModules:continue@@ -201,50 +208,44 @@ class SpiderFootScanner:if listenerModule.watchedEvents() != None:module.registerListener(listenerModule)- dbh.scanInstanceSet(self.config['__guid__'], status='RUNNING')- self.status = "RUNNING"+ # Now we are ready to roll..+ self.setStatus("RUNNING")# Create the "ROOT" event which un-triggered modules will link events to- rootEvent = SpiderFootEvent(self.targetType, self.targetValue, "SpiderFoot UI")- dbh.scanEventStore(self.config['__guid__'], rootEvent)+ rootEvent = SpiderFootEvent(self.ts.targetType, self.ts.targetValue, "SpiderFoot UI")+ self.ts.dbh.scanEventStore(self.ts.scanId, rootEvent)# Start the modules sequentially.- for module in self.moduleInstances.values():+ for module in self.ts.moduleInstances.values():# Check in case the user requested to stop the scan between modules initializingif module.checkForStop():- dbh.scanInstanceSet(self.config['__guid__'], status='ABORTING')- self.status = "ABORTING"+ self.setStatus('ABORTING')aborted = Truebreak# Notify modules with the root event- if self.targetType in module.watchedEvents():+ if self.ts.targetType in module.watchedEvents():module.handleEvent(rootEvent)# Check if any of the modules ended due to being stopped- for module in self.moduleInstances.values():+ for module in self.ts.moduleInstances.values():if module.checkForStop():aborted = Trueif aborted:- self.sf.status("Scan [" + self.config['__guid__'] + "] aborted.")- dbh.scanInstanceSet(self.config['__guid__'], None, time.time() * 1000, 'ABORTED')- self.status = "ABORTED"+ self.ts.sf.status("Scan [" + self.ts.scanId + "] aborted.")+ self.setStatus("ABORTED", None, time.time() * 1000)else:- self.sf.status("Scan [" + self.config['__guid__'] + "] completed.")- dbh.scanInstanceSet(self.config['__guid__'], None, time.time() * 1000, 'FINISHED')- self.status = "FINISHED"+ self.ts.sf.status("Scan [" + self.ts.scanId + "] completed.")+ self.setStatus("FINISHED", None, time.time() * 1000)except BaseException as e:exc_type, exc_value, exc_traceback = sys.exc_info()- self.sf.error("Unhandled exception (" + e.__class__.__name__ + ") " + \+ self.ts.sf.error("Unhandled exception (" + e.__class__.__name__ + ") " + \"encountered during scan. Please report this as a bug: " + \repr(traceback.format_exception(exc_type, exc_value, exc_traceback)), False)- self.sf.status("Scan [" + self.config['__guid__'] + "] failed: " + str(e))- dbh.scanInstanceSet(self.config['__guid__'], None, time.time() * 1000, 'ERROR-FAILED')- self.status = "ERROR-FAILED"-- self.moduleInstances = None- dbh.close()- self.sf.setDbh(None)- self.sf.setScanId(None)+ self.ts.sf.status("Scan [" + self.ts.scanId + "] failed: " + str(e))+ self.setStatus("ERROR-FAILED", None, time.time() * 1000)+ self.ts.dbh.close()+ del self.ts+ del self.tempdiff --git a/sfwebui.py b/sfwebui.pyindex 7fe9a359..61da2737 100644--- a/sfwebui.py+++ b/sfwebui.py@@ -10,6 +10,7 @@#-----------------------------------------------------------------import jsonimport threading+import threadimport cherrypyimport cgiimport csv@@ -17,11 +18,12 @@ import osimport timeimport randomimport urllib2+import refrom copy import deepcopyfrom mako.lookup import TemplateLookupfrom mako.template import Templatefrom sfdb import SpiderFootDb-from sflib import SpiderFoot+from sflib import SpiderFoot, globalScanStatusfrom sfscan import SpiderFootScannerfrom StringIO import StringIO@@ -29,17 +31,16 @@ class SpiderFootWebUi:lookup = TemplateLookup(directories=[''])defaultConfig = dict()config = dict()- scanner = Nonetoken = Nonedef __init__(self, config):self.defaultConfig = deepcopy(config)- dbh = SpiderFootDb(config)+ dbh = SpiderFootDb(self.defaultConfig)# 'config' supplied will be the defaults, let's supplement them# now with any configuration which may have previously been# saved.- sf = SpiderFoot(config)- self.config = sf.configUnserialize(dbh.configGet(), config)+ sf = SpiderFoot(self.defaultConfig)+ self.config = sf.configUnserialize(dbh.configGet(), self.defaultConfig)if self.config['__webaddr'] == "0.0.0.0":addr = "<IP of this host>"@@ -201,7 +202,6 @@ class SpiderFootWebUi:# the current system config.sf = SpiderFoot(self.config)self.config = sf.configUnserialize(cleanopts, currentopts)-dbh.configSet(sf.configSerialize(currentopts))except Exception as e:return self.error("Processing one or more of your inputs failed: " + str(e))@@ -214,12 +214,16 @@ class SpiderFootWebUi:# Initiate a scandef startscan(self, scanname, scantarget, modulelist, typelist):+ global globalScanStatus++ # Snapshot the current configuration to be used by the scan+ cfg = deepcopy(self.config)modopts = dict() # Not used yet as module options are set globallymodlist = list()- sf = SpiderFoot(self.config)- dbh = SpiderFootDb(self.config)+ sf = SpiderFoot(cfg)+ dbh = SpiderFootDb(cfg)types = dbh.eventTypes()-+ targetType = None[scanname, scantarget] = self.cleanUserInput([scanname, scantarget])if scanname == "" or scantarget == "":@@ -252,51 +256,57 @@ class SpiderFootWebUi:modlist.append("sfp__stor_db")modlist.sort()- # For now we don't permit multiple simultaneous scans- for thread in threading.enumerate():- if thread.name.startswith("SF_"):- templ = Template(filename='dyn/newscan.tmpl', lookup=self.lookup)- return templ.render(modules=self.config['__modules__'],- alreadyRunning=True, runningScan=thread.name[3:],- types=types, pageid="NEWSCAN")+ regexToType = {+ "^\d+\.\d+\.\d+\.\d+$": "IP_ADDRESS",+ "^\d+\.\d+\.\d+\.\d+/\d+$": "IP_SUBNET",+ "^.[a-zA-Z\-0-9\.]+$": "INTERNET_NAME"+ }- # Start running a new scan- try:- self.scanner = SpiderFootScanner(scanname, scantarget.lower(), modlist,- self.config, modopts)- except BaseException as e:- return self.error("Invalid input, so unable to initiate scan.")+ # Parse the target and set the targetType+ for rx in regexToType.keys():+ if re.match(rx, scantarget, re.IGNORECASE):+ targetType = regexToType[rx]+ break++ if targetType == None:+ return self.error("Invalid target type. Could not recognize it as " + \+ "an IP address, IP subnet, domain name or host name.")- t = threading.Thread(name="SF_" + scanname, target=self.scanner.startScan)+ # Start running a new scan+ scanId = sf.genScanInstanceGUID(scanname)+ t = SpiderFootScanner(scanname, scantarget.lower(), targetType, scanId,+ modlist, cfg, modopts)t.start()- # Spin cycles waiting for the scan ID to be set- while self.scanner.myId == None:+ # Wait until the scan has initialized+ while globalScanStatus.getStatus(scanId) == None:+ print "[info] Waiting for the scan to initialize..."time.sleep(1)- continuetempl = Template(filename='dyn/scaninfo.tmpl', lookup=self.lookup)- return templ.render(id=self.scanner.myId, name=scanname,- status=self.scanner.status, pageid="SCANLIST")+ return templ.render(id=scanId, name=scanname,+ status=globalScanStatus.getStatus(scanId), pageid="SCANLIST")startscan.exposed = True# Stop a scan (id variable is unnecessary for now given that only one simultaneous# scan is permitted.)def stopscan(self, id):- if self.scanner == None:- return self.error("There are no scans running. A data consistency " + \+ global globalScanStatus++ if globalScanStatus.getStatus(id) == None:+ return self.error("That scan is not actually running. A data consistency " + \"error for this scan probably exists. <a href='/scandelete?id=" + \id + "&confirm=1'>Click here to delete it.</a>")- if self.scanner.scanStatus(id) == "ABORTED":+ if globalScanStatus.getStatus(id) == "ABORTED":return self.error("The scan is already aborted.")- if not self.scanner.scanStatus(id) == "RUNNING":+ if not globalScanStatus.getStatus(id) == "RUNNING":return self.error("The running scan is currently in the state '" + \- self.scanner.scanStatus(id) + "', please try again later or restart " + \+ globalScanStatus.getStatus(id) + "', please try again later or restart " + \" SpiderFoot.")- self.scanner.stopScan(id)+ globalScanStatus.setStatus(id, "ABORT-REQUESTED")templ = Template(filename='dyn/scanlist.tmpl', lookup=self.lookup)return templ.render(pageid='SCANLIST',stoppedscan=True)stopscan.exposed = True