SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.
Python attacksurfacecticybersecurityfootprintinghackinginformation-gatheringinformation-securityinfosecintelligence-gatheringosintosint-frameworkosint-reconnaissanceosint-toolpentestingpythonreconsecurity-toolsthreat-intelligencethreatintel
[PEP 8] - Style Violation Fixes Part 4
Gormogon57379318cc89
diff --git a/modules/sfp__stor_db.py b/modules/sfp__stor_db.pyindex 931c507a..fb847141 100644--- a/modules/sfp__stor_db.py+++ b/modules/sfp__stor_db.py@@ -1,5 +1,5 @@# -*- coding: utf-8 -*--#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------# Name: sfp_stor_db# Purpose: SpiderFoot plug-in for storing events to the local SpiderFoot# SQLite database.@@ -9,21 +9,22 @@# Created: 14/05/2012# Copyright: (c) Steve Micallef 2012# Licence: GPL-#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------from sflib import SpiderFoot, SpiderFootPlugin+class sfp__stor_db(SpiderFootPlugin):"""Storage:Stores scan results into the back-end SpiderFoot database. You will need this."""# Default optionsopts = {- 'maxstorage': 1024 # max bytes for any piece of info stored (0 = unlimited)+ 'maxstorage': 1024 # max bytes for any piece of info stored (0 = unlimited)}# Option descriptionsoptdescs = {- 'maxstorage': "Maximum bytes to store for any piece of information retreived (0 = unlimited.)"+ 'maxstorage': "Maximum bytes to store for any piece of information retreived (0 = unlimited.)"}def setup(self, sfc, userOpts=dict()):@@ -45,7 +46,7 @@ class sfp__stor_db(SpiderFootPlugin):self.sf.debug("Storing an event: " + sfEvent.eventType)self.__sfdb__.scanEventStore(self.getScanId(), sfEvent, self.opts['maxstorage'])return None-+self.sf.debug("Storing an event: " + sfEvent.eventType)self.__sfdb__.scanEventStore(self.getScanId(), sfEvent)diff --git a/modules/sfp_accounts.py b/modules/sfp_accounts.pyindex 13a9fe08..110de6b7 100644--- a/modules/sfp_accounts.py+++ b/modules/sfp_accounts.py@@ -1,5 +1,5 @@# -*- coding: utf-8 -*--#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------# Name: sfp_accounts`# Purpose: Identify the existence of a given acount on various sites.#@@ -8,23 +8,29 @@# Created: 18/02/2015# Copyright: (c) Steve Micallef 2015# Licence: GPL-#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------import timefrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEventexternals = [-"YouTube","Wikipedia","LinkedIn","Twitter","Ebay","Tumblr","Pinterest","Blogger","Flickr","Wordpress","DailyMotion","reddit","Cnet","vimeo","SlideShare","ThemeForest","DeviantArt","LiveJournal","Yelp","StumbleUpon","askfm","Sourceforge","WikiHow","soundcloud","Photobucket","weebly","scribd","ImageShack","Disqus","Tagged","tinyurl","TMZ","Elance","Typepad","foursquare","steam","MySpace","Gawker","Gamespot","MetaCafe","LastFM","hi5","myfitnesspal","Delicious","Dribbble","Gravatar","Crunchbase","FriendFeed","Technorati","Slashdot","Metacritic","uservoice","BitLy"+ "YouTube", "Wikipedia", "LinkedIn", "Twitter", "Ebay", "Tumblr", "Pinterest", "Blogger", "Flickr", "Wordpress",+ "DailyMotion", "reddit", "Cnet", "vimeo", "SlideShare", "ThemeForest", "DeviantArt", "LiveJournal", "Yelp",+ "StumbleUpon", "askfm", "Sourceforge", "WikiHow", "soundcloud", "Photobucket", "weebly", "scribd", "ImageShack",+ "Disqus", "Tagged", "tinyurl", "TMZ", "Elance", "Typepad", "foursquare", "steam", "MySpace", "Gawker", "Gamespot",+ "MetaCafe", "LastFM", "hi5", "myfitnesspal", "Delicious", "Dribbble", "Gravatar", "Crunchbase", "FriendFeed",+ "Technorati", "Slashdot", "Metacritic", "uservoice", "BitLy"]+class sfp_accounts(SpiderFootPlugin):"""Accounts:Look for possible associated accounts on over 50 websites like Ebay, Slashdot, reddit, etc."""# Default options- opts = {- "generic": [ "root", "abuse", "sysadm", "sysadmin", "noc", "support", "admin",- "contact", "help", "flame", "test", "info", "sales", "hostmaster" ],- "ignoredict": True+ opts = {+ "generic": ["root", "abuse", "sysadm", "sysadmin", "noc", "support", "admin",+ "contact", "help", "flame", "test", "info", "sales", "hostmaster"],+ "ignoredict": True}# Option descriptions@@ -58,7 +64,7 @@ class sfp_accounts(SpiderFootPlugin):# This is to support the end user in selecting modules based on events# produced.def producedEvents(self):- return [ "ACCOUNT_EXTERNAL_OWNED", "ACCOUNT_EXTERNAL_USER_SHARED" ]+ return ["ACCOUNT_EXTERNAL_OWNED", "ACCOUNT_EXTERNAL_USER_SHARED"]def checkSites(self, name):global externals@@ -69,18 +75,18 @@ class sfp_accounts(SpiderFootPlugin):return Noneurl = "http://checkusernames.com/usercheckv2.php?target=" + site + \- "&username=" + name + "&time=" + str(int(time.time())*100) + "1"- res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'],- headers={- "X-Requested-With": "XMLHttpRequest",- "Referer": "http://www.checkusernames.com/"- }- )+ "&username=" + name + "&time=" + str(int(time.time()) * 100) + "1"+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'],+ headers={+ "X-Requested-With": "XMLHttpRequest",+ "Referer": "http://www.checkusernames.com/"+ }+ )if res['content'] is None:self.sf.debug("Unable to check the status of account " + name \- + " on " + site)+ + " on " + site)else:if "Sorry," in res['content']:ret.append(site)@@ -110,7 +116,7 @@ class sfp_accounts(SpiderFootPlugin):for site in sites:evt = SpiderFootEvent("ACCOUNT_EXTERNAL_OWNED", kw + " (" + site + ")",- self.__name__, event)+ self.__name__, event)self.notifyListeners(evt)return None@@ -128,7 +134,7 @@ class sfp_accounts(SpiderFootPlugin):if "." in name:# steve.micallef -> smicallefusers.append(name[0] + name.split(".")[1])-+for user in users:sites = self.checkSites(user)if sites is None:@@ -136,7 +142,7 @@ class sfp_accounts(SpiderFootPlugin):for site in sites:evt = SpiderFootEvent("ACCOUNT_EXTERNAL_USER_SHARED", user + " (" + site + ")",- self.__name__, event)+ self.__name__, event)self.notifyListeners(evt)# End of sfp_accounts classdiff --git a/modules/sfp_adblock.py b/modules/sfp_adblock.pyindex 17e3522b..e8d568a6 100644--- a/modules/sfp_adblock.py+++ b/modules/sfp_adblock.py@@ -1,5 +1,5 @@# -*- coding: utf-8 -*--#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------# Name: sfp_adblock# Purpose: SpiderFoot plug-in to test if external/internally linked pages# would be blocked by AdBlock Plus.@@ -9,17 +9,18 @@# Created: 22/09/2014# Copyright: (c) Steve Micallef 2014# Licence: GPL-#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------import adblockparserfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+class sfp_adblock(SpiderFootPlugin):"""AdBlock Check: Check if linked pages would be blocked by AdBlock Plus."""# Default options- opts = {- "blocklist": "https://easylist-downloads.adblockplus.org/easylist.txt"+ opts = {+ "blocklist": "https://easylist-downloads.adblockplus.org/easylist.txt"}optdescs = {@@ -47,7 +48,7 @@ class sfp_adblock(SpiderFootPlugin):# This is to support the end user in selecting modules based on events# produced.def producedEvents(self):- return [ "URL_ADBLOCKED_INTERNAL", "URL_ADBLOCKED_EXTERNAL" ]+ return ["URL_ADBLOCKED_INTERNAL", "URL_ADBLOCKED_EXTERNAL"]# Handle events sent to this moduledef handleEvent(self, event):@@ -72,7 +73,7 @@ class sfp_adblock(SpiderFootPlugin):self.sf.error("Parsing error handling AdBlock list: " + str(e), False)else:self.sf.error("Unable to download AdBlockPlus list: " + \- self.opts['blocklist'])+ self.opts['blocklist'])if "_EXTERNAL" in eventName:pagetype = "_EXTERNAL"@@ -88,7 +89,7 @@ class sfp_adblock(SpiderFootPlugin):try:if self.rules and self.rules.should_block(eventData):evt = SpiderFootEvent("URL_ADBLOCKED" + pagetype, eventData,- self.__name__, event.sourceEvent)+ self.__name__, event.sourceEvent)self.notifyListeners(evt)except BaseException as e:self.sf.error("Parsing error handling AdBlock list: " + str(e), False)diff --git a/modules/sfp_bingsearch.py b/modules/sfp_bingsearch.pyindex 97cc2abf..3d233082 100644--- a/modules/sfp_bingsearch.py+++ b/modules/sfp_bingsearch.py@@ -1,5 +1,5 @@# -*- coding: utf-8 -*--#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------# Name: sfp_bingsearch# Purpose: Searches Bing for content related to the domain in question.#@@ -8,23 +8,24 @@# Created: 06/10/2013# Copyright: (c) Steve Micallef 2013# Licence: GPL-#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+class sfp_bingsearch(SpiderFootPlugin):"""Bing:Some light Bing scraping to identify sub-domains and links."""# Default optionsopts = {- 'fetchlinks': True, # Should we fetch links on the base domain?- 'pages': 20 # Number of bing results pages to iterate+ 'fetchlinks': True, # Should we fetch links on the base domain?+ 'pages': 20 # Number of bing results pages to iterate}# Option descriptionsoptdescs = {'fetchlinks': "Fetch links found on the target domain-name?",- 'pages': "Number of Bing results pages to iterate through."+ 'pages': "Number of Bing results pages to iterate through."}results = list()@@ -38,13 +39,13 @@ class sfp_bingsearch(SpiderFootPlugin):# What events is this module interested in for inputdef watchedEvents(self):- return [ "INTERNET_NAME" ]+ return ["INTERNET_NAME"]# What events this module produces# This is to support the end user in selecting modules based on events# produced.def producedEvents(self):- return [ "LINKED_URL_INTERNAL", "SEARCH_ENGINE_WEB_CONTENT" ]+ return ["LINKED_URL_INTERNAL", "SEARCH_ENGINE_WEB_CONTENT"]def handleEvent(self, event):eventName = event.eventType@@ -59,7 +60,8 @@ class sfp_bingsearch(SpiderFootPlugin):# Sites hosted on the domainpages = self.sf.bingIterate("site:" + eventData, dict(limit=self.opts['pages'],- useragent=self.opts['_useragent'], timeout=self.opts['_fetchtimeout']))+ useragent=self.opts['_useragent'],+ timeout=self.opts['_fetchtimeout']))if pages is None:self.sf.info("No results returned from Bing.")return None@@ -75,8 +77,8 @@ class sfp_bingsearch(SpiderFootPlugin):return None# Submit the bing results for analysis- evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", pages[page],- self.__name__, event)+ evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", pages[page],+ self.__name__, event)self.notifyListeners(evt)# We can optionally fetch links to our domain found in the search@@ -96,8 +98,8 @@ class sfp_bingsearch(SpiderFootPlugin):if self.checkForStop():return None- evt = SpiderFootEvent("LINKED_URL_INTERNAL", link,- self.__name__, event)+ evt = SpiderFootEvent("LINKED_URL_INTERNAL", link,+ self.__name__, event)self.notifyListeners(evt)# End of sfp_bingsearch classdiff --git a/modules/sfp_blacklist.py b/modules/sfp_blacklist.pyindex 04f8fcfa..07b5be40 100644--- a/modules/sfp_blacklist.py+++ b/modules/sfp_blacklist.py@@ -1,5 +1,5 @@# -*- coding: utf-8 -*--#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------# Name: sfp_blacklist# Purpose: SpiderFoot plug-in for looking up whether IPs/Netblocks/Domains# appear in various block lists, indicating potential open-relays,@@ -10,12 +10,13 @@# Created: 07/01/2014# Copyright: (c) Steve Micallef 2014# Licence: GPL-#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------import socketfrom netaddr import IPNetworkfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+class sfp_blacklist(SpiderFootPlugin):"""Blacklist: Query various blacklist database for open relays, open proxies, vulnerable servers, etc."""@@ -87,15 +88,15 @@ class sfp_blacklist(SpiderFootPlugin):# What events is this module interested in for inputdef watchedEvents(self):- return [ 'IP_ADDRESS', 'AFFILIATE_IPADDR', 'NETBLOCK_OWNER',- 'NETBLOCK_MEMBER' ]+ return ['IP_ADDRESS', 'AFFILIATE_IPADDR', 'NETBLOCK_OWNER',+ 'NETBLOCK_MEMBER']# What events this module produces# This is to support the end user in selecting modules based on events# produced.def producedEvents(self):- return [ "BLACKLISTED_IPADDR", "BLACKLISTED_AFFILIATE_IPADDR",- "BLACKLISTED_SUBNET", "BLACKLISTED_NETBLOCK" ]+ return ["BLACKLISTED_IPADDR", "BLACKLISTED_AFFILIATE_IPADDR",+ "BLACKLISTED_SUBNET", "BLACKLISTED_NETBLOCK"]# Swap 1.2.3.4 to 4.3.2.1def reverseAddr(self, ipaddr):@@ -163,15 +164,15 @@ class sfp_blacklist(SpiderFootPlugin):if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:self.sf.debug("Network size bigger than permitted: " + \- str(IPNetwork(eventData).prefixlen) + " > " + \- str(self.opts['maxnetblock']))+ str(IPNetwork(eventData).prefixlen) + " > " + \+ str(self.opts['maxnetblock']))return Noneif eventName == 'NETBLOCK_MEMBER' and self.opts['subnetlookup']:if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:self.sf.debug("Network size bigger than permitted: " + \- str(IPNetwork(eventData).prefixlen) + " > " + \- str(self.opts['maxsubnet']))+ str(IPNetwork(eventData).prefixlen) + " > " + \+ str(self.opts['maxsubnet']))return Noneif eventName.startswith("NETBLOCK_"):diff --git a/modules/sfp_cookie.py b/modules/sfp_cookie.pyindex 6e8006ff..aefc18f0 100644--- a/modules/sfp_cookie.py+++ b/modules/sfp_cookie.py@@ -1,5 +1,5 @@# -*- coding: utf-8 -*--#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------# Name: sfp_cookie# Purpose: SpiderFoot plug-in for extracting cookies from HTTP headers.#@@ -8,15 +8,16 @@# Created: 06/04/2014# Copyright: (c) Steve Micallef 2014# Licence: GPL-#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+class sfp_cookie(SpiderFootPlugin):"""Cookies:Extract Cookies from HTTP headers."""# Default options- opts = { }+ opts = {}results = dict()@@ -35,7 +36,7 @@ class sfp_cookie(SpiderFootPlugin):# This is to support the end user in selecting modules based on events# produced.def producedEvents(self):- return [ "TARGET_WEB_COOKIE" ]+ return ["TARGET_WEB_COOKIE"]# Handle events sent to this moduledef handleEvent(self, event):@@ -56,8 +57,8 @@ class sfp_cookie(SpiderFootPlugin):return Noneif eventData.has_key('set-cookie'):- evt = SpiderFootEvent("TARGET_WEB_COOKIE", eventData['set-cookie'],- self.__name__, parentEvent)+ evt = SpiderFootEvent("TARGET_WEB_COOKIE", eventData['set-cookie'],+ self.__name__, parentEvent)self.notifyListeners(evt)# End of sfp_cookie classdiff --git a/modules/sfp_crossref.py b/modules/sfp_crossref.pyindex 7d6c3c7e..36dfcda9 100644--- a/modules/sfp_crossref.py+++ b/modules/sfp_crossref.py@@ -1,5 +1,5 @@# -*- coding: utf-8 -*--#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------# Name: sfp_crossref# Purpose: SpiderFoot plug-in for scanning links identified from the# spidering process, and for external links, fetching them to@@ -11,17 +11,18 @@# Created: 06/04/2012# Copyright: (c) Steve Micallef 2012# Licence: GPL-#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------import refrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+class sfp_crossref(SpiderFootPlugin):"""Cross-Reference:Identify whether other domains are associated ('Affiliates') of the target."""# Default optionsopts = {- 'checkbase': True+ 'checkbase': True}# Option descriptions@@ -49,7 +50,7 @@ class sfp_crossref(SpiderFootPlugin):# This is to support the end user in selecting modules based on events# produced.def producedEvents(self):- return [ "AFFILIATE_INTERNET_NAME", "AFFILIATE_WEB_CONTENT" ]+ return ["AFFILIATE_INTERNET_NAME", "AFFILIATE_WEB_CONTENT"]# Handle events sent to this module# In this module's case, eventData will be the URL or a domain which@@ -63,8 +64,8 @@ class sfp_crossref(SpiderFootPlugin):# The SIMILARDOMAIN and CO_HOSTED_SITE events supply domains,# not URLs. Assume HTTP.- if eventName in [ 'SIMILARDOMAIN', 'CO_HOSTED_SITE' ]:- eventData = 'http://'+ eventData.lower()+ if eventName in ['SIMILARDOMAIN', 'CO_HOSTED_SITE']:+ eventData = 'http://' + eventData.lower()# We are only interested in external sites for the crossrefif self.getTarget().matches(self.sf.urlFQDN(eventData)):@@ -78,8 +79,8 @@ class sfp_crossref(SpiderFootPlugin):self.fetched.append(eventData)self.sf.debug("Testing for affiliation: " + eventData)- res = self.sf.fetchUrl(eventData, timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])+ res = self.sf.fetchUrl(eventData, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])if res['content'] is None:self.sf.debug("Ignoring " + eventData + " as no data returned")@@ -107,12 +108,12 @@ class sfp_crossref(SpiderFootPlugin):else:self.fetched.append(url)- res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])+ res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])if res['content'] is not None:for name in self.getTarget().getNames():- pat = re.compile("([\.\'\/\"\ ]" + name + "[\'\/\"\ ])",- re.IGNORECASE)+ pat = re.compile("([\.\'\/\"\ ]" + name + "[\'\/\"\ ])",+ re.IGNORECASE)matches = re.findall(pat, res['content'])if len(matches) > 0:@@ -120,11 +121,11 @@ class sfp_crossref(SpiderFootPlugin):if matched:self.sf.info("Found affiliate: " + url)- evt1 = SpiderFootEvent("AFFILIATE_INTERNET_NAME", self.sf.urlFQDN(url),- self.__name__, event)+ evt1 = SpiderFootEvent("AFFILIATE_INTERNET_NAME", self.sf.urlFQDN(url),+ self.__name__, event)self.notifyListeners(evt1)evt2 = SpiderFootEvent("AFFILIATE_WEB_CONTENT", res['content'],- self.__name__, evt1)+ self.__name__, evt1)self.notifyListeners(evt2)# End of sfp_crossref classdiff --git a/modules/sfp_defaced.py b/modules/sfp_defaced.pyindex d31d4db1..480fa536 100644--- a/modules/sfp_defaced.py+++ b/modules/sfp_defaced.py@@ -1,5 +1,5 @@# -*- coding: utf-8 -*--#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------# Name: sfp_defaced# Purpose: Checks if a domain or IP appears on the zone-h.org defacement# archive.@@ -9,17 +9,18 @@# Created: 09/01/2014# Copyright: (c) Steve Micallef, 2014# Licence: GPL-#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------import timeimport refrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+class sfp_defaced(SpiderFootPlugin):"""Defacement Check:Check if an IP or domain appears on the zone-h.org defacement archive."""# Default options- opts = {+ opts = {'daysback': 30,'checkcohosts': True,'checkaffiliates': True@@ -28,7 +29,7 @@ class sfp_defaced(SpiderFootPlugin):# Option descriptionsoptdescs = {'daysback': "Ignore defacements older than this many days.",- 'checkcohosts': "Check co-hosted sites?",+ 'checkcohosts': "Check co-hosted sites?",'checkaffiliates': "Check affiliates?"}@@ -51,16 +52,16 @@ class sfp_defaced(SpiderFootPlugin):# * = be notified about all events.def watchedEvents(self):return ["INTERNET_NAME", "IP_ADDRESS",- "AFFILIATE_INTERNET_NAME", "AFFILIATE_IPADDR",- "CO_HOSTED_SITE" ]+ "AFFILIATE_INTERNET_NAME", "AFFILIATE_IPADDR",+ "CO_HOSTED_SITE"]# What events this module produces# This is to support the end user in selecting modules based on events# produced.def producedEvents(self):- return [ "DEFACED_INTERNET_NAME", "DEFACED_IPADDR",- "DEFACED_AFFILIATE_INTERNET_NAME",- "DEFACED_COHOST", "DEFACED_AFFILIATE_IPADDR" ]+ return ["DEFACED_INTERNET_NAME", "DEFACED_IPADDR",+ "DEFACED_AFFILIATE_INTERNET_NAME",+ "DEFACED_COHOST", "DEFACED_AFFILIATE_IPADDR"]def lookupItem(self, target, typeId):found = False@@ -75,14 +76,14 @@ class sfp_defaced(SpiderFootPlugin):self.sf.error("CAPTCHA returned from zone-h.org.", False)return None- rx = re.compile("<td>(\d+/\d+/\d+)</td>", re.IGNORECASE|re.DOTALL)+ rx = re.compile("<td>(\d+/\d+/\d+)</td>", re.IGNORECASE | re.DOTALL)grps = re.findall(rx, res['content'])for m in grps: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:+ if int(date) < int(curDate) - 30:self.sf.debug("Defaced site found but too old: " + date)found = Falsecontinue@@ -109,7 +110,7 @@ class sfp_defaced(SpiderFootPlugin):if eventName == 'CO_HOSTED_SITE' and not self.opts['checkcohosts']:return Noneif eventName == 'AFFILIATE_INTERNET_NAME' or eventName == 'AFFILIATE_IPADDR' \- and not self.opts['checkaffiliates']:+ and not self.opts['checkaffiliates']:return NoneevtType = 'DEFACED_INTERNET_NAME'diff --git a/modules/sfp_dns.py b/modules/sfp_dns.pyindex 465feb1d..0068d56f 100644--- a/modules/sfp_dns.py+++ b/modules/sfp_dns.py@@ -1,5 +1,5 @@# -*- coding: utf-8 -*--#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------# Name: sfp_dns# Purpose: SpiderFoot plug-in for gathering IP addresses from sub-domains# and hostnames identified, and optionally affiliates.@@ -11,7 +11,7 @@# Created: 16/09/2012# Copyright: (c) Steve Micallef 2012# Licence: GPL-#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------import socketimport re@@ -20,6 +20,7 @@ import urllib2from netaddr import IPAddress, IPNetworkfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+class sfp_dns(SpiderFootPlugin):"""DNS:Performs a number of DNS checks to obtain Sub-domains/Hostnames, IP Addresses and Affiliates."""@@ -32,10 +33,10 @@ class sfp_dns(SpiderFootPlugin):'onlyactive': True,'validatereverse': True,"skipcommononwildcard": True,- "commonsubs": [ "www", "web", "ns", "mail", "dns", "mx", "gw", "proxy",- "ssl", "fw", "gateway", "firewall", "www1", "www2",- "ns0", "ns1", "ns2", "dns0", "dns1", "dns2", "mx1", "mx2"- ] # Common sub-domains to try.+ "commonsubs": ["www", "web", "ns", "mail", "dns", "mx", "gw", "proxy",+ "ssl", "fw", "gateway", "firewall", "www1", "www2",+ "ns0", "ns1", "ns2", "dns0", "dns1", "dns2", "mx1", "mx2"+ ] # Common sub-domains to try.}@@ -45,10 +46,10 @@ class sfp_dns(SpiderFootPlugin):'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible hosts on the same target subdomain/domain?",'maxnetblock': "Maximum owned netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",'onlyactive': "Only report sub-domains/hostnames that resolve to an IP.",- 'validatereverse': "Validate that reverse-resolved hostnames still resolve back to that IP before considering them as aliases of your target.",+ 'validatereverse': "Validate that reverse-resolved hostnames still resolve back to that IP before considering them as aliases of your target.",'lookaside': "For each IP discovered, try and reverse look-up IPs 'next to' that IP for potential hostnames on the same subdomain/domain.",'lookasidecount': "If look-aside is enabled, the number of IPs on each 'side' of the IP to look up",- "commonsubs": "Common sub-domains to try to resolve on the target subdomain/domain. Prefix with an '@' to iterate through a file containing sub-domains to try (one per line), e.g. @C:\subdomains.txt or @/home/bob/subdomains.txt. Or supply a URL to load the list from there."+ "commonsubs": "Common sub-domains to try to resolve on the target subdomain/domain. Prefix with an '@' to iterate through a file containing sub-domains to try (one per line), e.g. @C:\subdomains.txt or @/home/bob/subdomains.txt. Or supply a URL to load the list from there."}events = dict()@@ -71,8 +72,8 @@ class sfp_dns(SpiderFootPlugin):self.sublist = self.opts['commonsubs']# User may have supplied a file or URL containing the subdomainsif self.opts['commonsubs'][0].startswith("http://") or \- self.opts['commonsubs'][0].startswith("https://") or \- self.opts['commonsubs'][0].startswith("@"):+ self.opts['commonsubs'][0].startswith("https://") or \+ self.opts['commonsubs'][0].startswith("@"):self.sublist = self.sf.optValueToData(self.opts['commonsubs'][0])def enrichTarget(self, target):@@ -86,7 +87,7 @@ class sfp_dns(SpiderFootPlugin):ret = list()for addr in IPNetwork(target.getValue()):ipaddr = str(addr)- if ipaddr.split(".")[3] in [ '255', '0']:+ if ipaddr.split(".")[3] in ['255', '0']:continueif '255' in ipaddr.split("."):continue@@ -94,7 +95,7 @@ class sfp_dns(SpiderFootPlugin):# Add the reverse-resolved hostnames as aliases too..names = self.resolveIP(ipaddr)-+if self.opts['validatereverse']:for host in names:chk = self.resolveHost(host)@@ -114,7 +115,7 @@ class sfp_dns(SpiderFootPlugin):if target.getType() == "INTERNET_NAME":dom = self.sf.hostDomain(host, self.opts['_internettlds'])target.setAlias(dom, "INTERNET_NAME")-+self.sf.debug("Aliases identified: " + str(target.getAliases()))return target@@ -122,17 +123,17 @@ class sfp_dns(SpiderFootPlugin):# What events is this module interested in for inputdef watchedEvents(self):arr = ['RAW_DNS_RECORDS', 'SEARCH_ENGINE_WEB_CONTENT', 'RAW_RIR_DATA',- 'TARGET_WEB_CONTENT', 'LINKED_URL_INTERNAL', 'INTERNET_NAME',- 'IP_ADDRESS', 'NETBLOCK_OWNER', "DNS_TEXT" ]+ 'TARGET_WEB_CONTENT', 'LINKED_URL_INTERNAL', 'INTERNET_NAME',+ 'IP_ADDRESS', 'NETBLOCK_OWNER', "DNS_TEXT"]return arr# What events this module produces# This is to support the end user in selecting modules based on events# produced.def producedEvents(self):- return [ "IP_ADDRESS", "INTERNET_NAME", "PROVIDER_MAIL", "DOMAIN_NAME",- "PROVIDER_DNS", "AFFILIATE_INTERNET_NAME", "RAW_DNS_RECORDS",- "DNS_TEXT", "IPV6_ADDRESS" ]+ return ["IP_ADDRESS", "INTERNET_NAME", "PROVIDER_MAIL", "DOMAIN_NAME",+ "PROVIDER_DNS", "AFFILIATE_INTERNET_NAME", "RAW_DNS_RECORDS",+ "DNS_TEXT", "IPV6_ADDRESS"]# Handle events sent to this moduledef handleEvent(self, event):@@ -149,8 +150,8 @@ class sfp_dns(SpiderFootPlugin):self.events[eventData] = True# Identify potential sub-domains/hostnames- if eventName in [ "SEARCH_ENGINE_WEB_CONTENT", "TARGET_WEB_CONTENT",- "LINKED_URL_INTERNAL", "RAW_RIR_DATA", "RAW_DNS_RECORDS", "DNS_TEXT" ]:+ if eventName in ["SEARCH_ENGINE_WEB_CONTENT", "TARGET_WEB_CONTENT",+ "LINKED_URL_INTERNAL", "RAW_RIR_DATA", "RAW_DNS_RECORDS", "DNS_TEXT"]:# If we've received a link or some raw data, extract potential sub-domains# from the data for resolving later.for name in self.getTarget().getNames():@@ -167,14 +168,14 @@ class sfp_dns(SpiderFootPlugin):if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:self.sf.debug("Network size bigger than permitted: " + \- str(IPNetwork(eventData).prefixlen) + " > " + \- str(self.opts['maxnetblock']))+ str(IPNetwork(eventData).prefixlen) + " > " + \+ str(self.opts['maxnetblock']))return Noneself.sf.debug("Looking up IPs in owned netblock: " + eventData)for ip in IPNetwork(eventData):ipaddr = str(ip)- if ipaddr.split(".")[3] in [ '255', '0']:+ if ipaddr.split(".")[3] in ['255', '0']:continueif '255' in ipaddr.split("."):continue@@ -185,7 +186,7 @@ class sfp_dns(SpiderFootPlugin):if len(addrs) > 0:self.sf.debug("Found a reversed hostname from " + ipaddr + \- " (" + str(addrs) + ")")+ " (" + str(addrs) + ")")for addr in addrs:# Generate an event for the IP, then# let the handling by this module take@@ -194,7 +195,7 @@ class sfp_dns(SpiderFootPlugin):return None# Handling INTERNET_NAME and IP_ADDRESS events..- if eventName in [ "IP_ADDRESS", "INTERNET_NAME" ]:+ if eventName in ["IP_ADDRESS", "INTERNET_NAME"]:if eventName != 'IP_ADDRESS':if '://' in eventData:addrs = self.resolveHost(self.sf.urlFQDN(eventData))@@ -255,7 +256,7 @@ class sfp_dns(SpiderFootPlugin):if self.resolveCache.has_key(ipaddr):self.sf.debug("Returning cached result for " + ipaddr + " (" + \- str(self.resolveCache[ipaddr]) + ")")+ str(self.resolveCache[ipaddr]) + ")")return self.resolveCache[ipaddr]try:@@ -272,7 +273,7 @@ class sfp_dns(SpiderFootPlugin):def resolveHost(self, hostname):if self.resolveCache.has_key(hostname):self.sf.debug("Returning cached result for " + hostname + " (" + \- str(self.resolveCache[hostname]) + ")" )+ str(self.resolveCache[hostname]) + ")")return self.resolveCache[hostname]try:@@ -288,7 +289,7 @@ class sfp_dns(SpiderFootPlugin):def resolveHost6(self, hostname):if self.resolveCache6.has_key(hostname):self.sf.debug("Returning IPv6 cached result for " + hostname + " (" + \- str(self.resolveCache6[hostname]) + ")" )+ str(self.resolveCache6[hostname]) + ")")return self.resolveCache6[hostname]try:@@ -332,7 +333,7 @@ class sfp_dns(SpiderFootPlugin):affil = Falseelse:affil = affiliate-+if affil:if self.sf.validIP(host):htype = "AFFILIATE_IPADDR"@@ -343,7 +344,7 @@ class sfp_dns(SpiderFootPlugin):htype = "IP_ADDRESS"else:htype = "INTERNET_NAME"-+if htype.endswith("INTERNET_NAME") and self.opts['onlyactive']:if len(self.resolveHost(host)) == 0:return None@@ -358,8 +359,7 @@ class sfp_dns(SpiderFootPlugin):# Try obtain the IPv6 addressfor ip6 in self.resolveHost6(host):- evt = SpiderFootEvent("IPV6_ADDRESS", ip6, self.__name__,- evt)+ evt = SpiderFootEvent("IPV6_ADDRESS", ip6, self.__name__, evt)self.notifyListeners(evt)return evt@@ -371,8 +371,7 @@ class sfp_dns(SpiderFootPlugin):self.sf.debug("Skipping domain, " + domainName + ", already processed.")return None- domevt = SpiderFootEvent("DOMAIN_NAME", domainName, self.__name__,- parentEvent)+ domevt = SpiderFootEvent("DOMAIN_NAME", domainName, self.__name__, parentEvent)self.notifyListeners(domevt)self.sf.debug("Gathering DNS records for " + domainName)@@ -387,38 +386,38 @@ class sfp_dns(SpiderFootPlugin):for rec in recs.keys():try:req = dns.message.make_query(domainName, dns.rdatatype.from_text(rec))-+if self.opts['_dnsserver'] != "":n = self.opts['_dnsserver']else:ns = dns.resolver.get_default_resolver()n = ns.nameservers[0]-+res = dns.query.udp(req, n)for x in res.answer:for rx in recs.keys():self.sf.debug("Checking " + str(x) + " + against " + recs[rx][0])- pat = re.compile(recs[rx][0], re.IGNORECASE|re.DOTALL)+ pat = re.compile(recs[rx][0], re.IGNORECASE | re.DOTALL)grps = re.findall(pat, str(x))if len(grps) > 0:for m in grps:- self.sf.debug("Matched: " + m)+ self.sf.debug("Matched: " + m)strdata = unicode(m, 'utf-8', errors='replace')- evt = SpiderFootEvent(recs[rx][1], strdata,- self.__name__, domevt)+ evt = SpiderFootEvent(recs[rx][1], strdata,+ self.__name__, domevt)self.notifyListeners(evt)if rec != "TXT" and not strdata.endswith(domainName):evt = SpiderFootEvent("AFFILIATE_INTERNET_NAME",- strdata, self.__name__, domevt)+ strdata, self.__name__, domevt)self.notifyListeners(evt)else:- strdata = unicode(str(x), 'utf-8', errors='replace')- evt = SpiderFootEvent("RAW_DNS_RECORDS", strdata,- self.__name__, domevt)- self.notifyListeners(evt)+ strdata = unicode(str(x), 'utf-8', errors='replace')+ evt = SpiderFootEvent("RAW_DNS_RECORDS", strdata,+ self.__name__, domevt)+ self.notifyListeners(evt)except BaseException as e:self.sf.error("Failed to obtain DNS response for " + domainName + \- "(" + rec + "): " + str(e), False)+ "(" + rec + "): " + str(e), False)self.sf.debug("Iterating through possible sub-domains [" + str(self.sublist) + "]")count = 0@@ -428,7 +427,7 @@ class sfp_dns(SpiderFootPlugin):if wildcard and self.opts['skipcommononwildcard'] and count > 0:self.sf.debug("Wildcard DNS detected, skipping iterating through remaining hosts.")return None-+if self.checkForStop():return Nonediff --git a/modules/sfp_email.py b/modules/sfp_email.pyindex a015c27a..93adee33 100644--- a/modules/sfp_email.py+++ b/modules/sfp_email.py@@ -1,5 +1,5 @@# -*- coding: utf-8 -*--#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------# Name: sfp_email# Purpose: SpiderFoot plug-in for scanning retreived content by other# modules (such as sfp_spider) and identifying e-mail addresses@@ -9,18 +9,19 @@# Created: 06/04/2012# Copyright: (c) Steve Micallef 2012# Licence: GPL-#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------import refrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+class sfp_email(SpiderFootPlugin):"""E-Mail:Identify e-mail addresses in any obtained data."""# Default optionsopts = {# options specific to this module- 'includeexternal': False # Include e-mail addrs on external domains+ 'includeexternal': False # Include e-mail addrs on external domains}# Option descriptions@@ -42,7 +43,7 @@ class sfp_email(SpiderFootPlugin):# This is to support the end user in selecting modules based on events# produced.def producedEvents(self):- return [ "EMAILADDR" ]+ return ["EMAILADDR"]# Handle events sent to this moduledef handleEvent(self, event):@@ -56,7 +57,7 @@ class sfp_email(SpiderFootPlugin):self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)- if type(eventData) not in [ str, unicode ]:+ if type(eventData) not in [str, unicode]:self.sf.debug("Unhandled type to find e-mails: " + str(type(eventData)))return None@@ -71,7 +72,7 @@ class sfp_email(SpiderFootPlugin):mailDom = match.lower().split('@')[1]if not self.opts['includeexternal'] and not \- self.getTarget().matches(mailDom):+ self.getTarget().matches(mailDom):self.sf.debug("Ignoring e-mail address on an external domain: " + match)continuediff --git a/modules/sfp_errors.py b/modules/sfp_errors.pyindex 0a141980..2280cf30 100644--- a/modules/sfp_errors.py+++ b/modules/sfp_errors.py@@ -1,5 +1,5 @@# -*- coding: utf-8 -*--#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------# Name: sfp_errors# Purpose: Identify common error messages in content like SQL errors, etc.#@@ -8,28 +8,29 @@# Created: 18/01/2015# Copyright: (c) Steve Micallef 2015# Licence: GPL-#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------import refrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent# Taken from Google Dorks on exploit-db.comregexps = dict({- "PHP Error": [ "PHP pase error", "PHP warning", "PHP error",- "unexpected T_VARIABLE", "warning: failed opening", "include_path=" ],- "Generic Error": [ "Internal Server Error", "Incorrect syntax" ],- "Oracle Error": [ "ORA-\d+", "TNS:.?no listen" ],- "ASP Error": [ "NET_SessionId" ],- "MySQL Error": [ "mysql_query\(", "mysql_connect\(" ],- "ODBC Error": [ "\[ODBC SQL" ]+ "PHP Error": ["PHP pase error", "PHP warning", "PHP error",+ "unexpected T_VARIABLE", "warning: failed opening", "include_path="],+ "Generic Error": ["Internal Server Error", "Incorrect syntax"],+ "Oracle Error": ["ORA-\d+", "TNS:.?no listen"],+ "ASP Error": ["NET_SessionId"],+ "MySQL Error": ["mysql_query\(", "mysql_connect\("],+ "ODBC Error": ["\[ODBC SQL"]})+class sfp_errors(SpiderFootPlugin):"""Errors:Identify common error messages in content like SQL errors, etc."""# Default options- opts = { }+ opts = {}# Option descriptionsoptdescs = {@@ -57,7 +58,7 @@ class sfp_errors(SpiderFootPlugin):# This is to support the end user in selecting modules based on events# produced.def producedEvents(self):- return [ "ERROR_MESSAGE" ]+ return ["ERROR_MESSAGE"]# Handle events sent to this moduledef handleEvent(self, event):@@ -93,8 +94,8 @@ class sfp_errors(SpiderFootPlugin):if len(matches) > 0 and regexpGrp not in self.results[eventSource]:self.sf.info("Matched " + regexpGrp + " in content from " + eventSource)self.results[eventSource].append(regexpGrp)- evt = SpiderFootEvent("ERROR_MESSAGE", regexpGrp,- self.__name__, event.sourceEvent)+ evt = SpiderFootEvent("ERROR_MESSAGE", regexpGrp,+ self.__name__, event.sourceEvent)self.notifyListeners(evt)return Nonediff --git a/modules/sfp_filemeta.py b/modules/sfp_filemeta.pyindex f4cd5142..1562a6f4 100644--- a/modules/sfp_filemeta.py+++ b/modules/sfp_filemeta.py@@ -1,5 +1,5 @@# -*- coding: utf-8 -*--#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------# Name: sfp_filemeta# Purpose: From Spidering and from searching search engines, extracts file# meta data from files matching certain file extensions.@@ -9,7 +9,7 @@# Created: 25/04/2014# Copyright: (c) Steve Micallef 2014# Licence: GPL-#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------import mimetypesimport metapdf@@ -18,19 +18,20 @@ import exifreadfrom StringIO import StringIOfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+class sfp_filemeta(SpiderFootPlugin):"""File Metadata:Extracts meta data from documents and images."""# Default optionsopts = {- 'fileexts': [ "docx", "pptx", 'xlsx', 'pdf', 'jpg', 'jpeg', 'tiff', 'tif' ],- 'timeout': 300+ 'fileexts': ["docx", "pptx", 'xlsx', 'pdf', 'jpg', 'jpeg', 'tiff', 'tif'],+ 'timeout': 300}# Option descriptionsoptdescs = {'fileexts': "File extensions of files you want to analyze the meta data of (only PDF, DOCX, XLSX and PPTX are supported.)",- 'timeout': "Download timeout for files, in seconds."+ 'timeout': "Download timeout for files, in seconds."}results = list()@@ -44,13 +45,13 @@ class sfp_filemeta(SpiderFootPlugin):# What events is this module interested in for inputdef watchedEvents(self):- return [ "LINKED_URL_INTERNAL", "INTERESTING_FILE" ]+ return ["LINKED_URL_INTERNAL", "INTERESTING_FILE"]# What events this module produces# This is to support the end user in selecting modules based on events# produced.def producedEvents(self):- return [ "RAW_FILE_META_DATA", "SOFTWARE_USED" ]+ return ["RAW_FILE_META_DATA", "SOFTWARE_USED"]# Handle events sent to this moduledef handleEvent(self, event):@@ -72,16 +73,16 @@ 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 = self.sf.fetchUrl(eventData, timeout=self.opts['timeout'],- useragent=self.opts['_useragent'], dontMangle=True)+ ret = self.sf.fetchUrl(eventData, timeout=self.opts['timeout'],+ useragent=self.opts['_useragent'], dontMangle=True)if ret['content'] is None:self.sf.error("Unable to fetch file for meta analysis: " + \- eventData, False)+ eventData, False)return Noneif len(ret['content']) < 512:self.sf.error("Strange content encountered, size of " + \- str(len(ret['content'])), False)+ str(len(ret['content'])), False)meta = Nonedata = None@@ -94,9 +95,9 @@ class sfp_filemeta(SpiderFootPlugin):self.sf.debug("Obtained meta data from " + eventData)except BaseException as e:self.sf.error("Unable to parse meta data from: " + \- eventData + "(" + str(e) + ")", False)+ eventData + "(" + str(e) + ")", False)- if fileExt.lower() in [ "pptx", "docx", "xlsx" ]:+ if fileExt.lower() in ["pptx", "docx", "xlsx"]:try:mtype = mimetypes.guess_type(eventData)[0]doc = openxmllib.openXmlDocument(data=ret['content'], mime_type=mtype)@@ -105,15 +106,15 @@ class sfp_filemeta(SpiderFootPlugin):meta = str(data)except ValueError as e:self.sf.error("Unable to parse meta data from: " + \- eventData + "(" + str(e) + ")", False)+ eventData + "(" + str(e) + ")", False)except lxml.etree.XMLSyntaxError as e:self.sf.error("Unable to parse XML within: " + \- eventData + "(" + str(e) + ")", False)+ eventData + "(" + str(e) + ")", False)except BaseException as e:self.sf.error("Unable to process file: " + \- eventData + "(" + str(e) + ")", False)+ eventData + "(" + str(e) + ")", False)- if fileExt.lower() in [ "jpg", "jpeg", "tiff" ]:+ if fileExt.lower() in ["jpg", "jpeg", "tiff"]:try:raw = StringIO(ret['content'])data = exifread.process_file(raw)@@ -122,11 +123,11 @@ class sfp_filemeta(SpiderFootPlugin):meta = str(data)except BaseException as e:self.sf.error("Unable to parse meta data from: " + \- eventData + "(" + str(e) + ")", False)+ eventData + "(" + str(e) + ")", False)if meta is not None:evt = SpiderFootEvent("RAW_FILE_META_DATA", meta,- self.__name__, event)+ self.__name__, event)self.notifyListeners(evt)val = None@@ -147,7 +148,7 @@ class sfp_filemeta(SpiderFootPlugin):# Strip non-ASCIIval = ''.join([i if ord(i) < 128 else ' ' for i in val])evt = SpiderFootEvent("SOFTWARE_USED", val,- self.__name__, event)+ self.__name__, event)self.notifyListeners(evt)# End of sfp_filemeta classdiff --git a/modules/sfp_geoip.py b/modules/sfp_geoip.pyindex 0071b23e..d0ae2058 100644--- a/modules/sfp_geoip.py+++ b/modules/sfp_geoip.py@@ -1,5 +1,5 @@# -*- coding: utf-8 -*--#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------# Name: sfp_geoip# Purpose: SpiderFoot plug-in to identify the Geo-location of IP addresses# identified by other modules.@@ -9,16 +9,17 @@# Created: 18/02/2013# Copyright: (c) Steve Micallef 2013# Licence: GPL-#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------import jsonfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+class sfp_geoip(SpiderFootPlugin):"""GeoIP:Identifies the physical location of IP addresses identified."""# Default options- opts = { }+ opts = {}results = dict()def setup(self, sfc, userOpts=dict()):@@ -36,7 +37,7 @@ class sfp_geoip(SpiderFootPlugin):# This is to support the end user in selecting modules based on events# produced.def producedEvents(self):- return [ "GEOINFO" ]+ return ["GEOINFO"]# Handle events sent to this moduledef handleEvent(self, event):@@ -54,7 +55,7 @@ class sfp_geoip(SpiderFootPlugin):self.results[eventData] = Trueres = self.sf.fetchUrl("http://freegeoip.net/json/" + eventData,- timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])+ timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])if res['content'] is None:self.sf.info("No GeoIP info found for " + eventData)try:diff --git a/modules/sfp_googlesearch.py b/modules/sfp_googlesearch.pyindex eee0bb5c..23f6f92a 100644--- a/modules/sfp_googlesearch.py+++ b/modules/sfp_googlesearch.py@@ -1,5 +1,5 @@# -*- coding: utf-8 -*--#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------# Name: sfp_googlesearch# Purpose: Searches Google for content related to the domain in question.#@@ -8,23 +8,24 @@# Created: 07/05/2012# Copyright: (c) Steve Micallef 2012# Licence: GPL-#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+class sfp_googlesearch(SpiderFootPlugin):"""Google:Some light Google scraping to identify sub-domains and links."""# Default optionsopts = {- 'fetchlinks': True, # Should we fetch links on the base domain?- 'pages': 20 # Number of google results pages to iterate+ 'fetchlinks': True, # Should we fetch links on the base domain?+ 'pages': 20 # Number of google results pages to iterate}# Option descriptionsoptdescs = {'fetchlinks': "Fetch links found on the target domain-name?",- 'pages': "Number of Google results pages to iterate through."+ 'pages': "Number of Google results pages to iterate through."}# Target@@ -39,13 +40,13 @@ class sfp_googlesearch(SpiderFootPlugin):# What events is this module interested in for inputdef watchedEvents(self):- return [ "INTERNET_NAME" ]+ return ["INTERNET_NAME"]# What events this module produces# This is to support the end user in selecting modules based on events# produced.def producedEvents(self):- return [ "LINKED_URL_INTERNAL", "SEARCH_ENGINE_WEB_CONTENT" ]+ return ["LINKED_URL_INTERNAL", "SEARCH_ENGINE_WEB_CONTENT"]def handleEvent(self, event):eventName = event.eventType@@ -59,9 +60,9 @@ class sfp_googlesearch(SpiderFootPlugin):self.results.append(eventData)# Sites hosted on the domain- pages = self.sf.googleIterate("site:" + eventData,- dict(limit=self.opts['pages'], useragent=self.opts['_useragent'],- timeout=self.opts['_fetchtimeout']))+ pages = self.sf.googleIterate("site:" + eventData,+ dict(limit=self.opts['pages'], useragent=self.opts['_useragent'],+ timeout=self.opts['_fetchtimeout']))if pages is None:self.sf.info("No results returned from Google.")return None@@ -77,8 +78,8 @@ class sfp_googlesearch(SpiderFootPlugin):return None# Submit the google results for analysis- evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", pages[page],- self.__name__, event)+ evt = SpiderFootEvent("SEARCH_ENGINE_WEB_CONTENT", pages[page],+ self.__name__, event)self.notifyListeners(evt)# We can optionally fetch links to our domain found in the search@@ -98,8 +99,8 @@ class sfp_googlesearch(SpiderFootPlugin):if self.checkForStop():return None- evt = SpiderFootEvent("LINKED_URL_INTERNAL", link,- self.__name__, event)+ evt = SpiderFootEvent("LINKED_URL_INTERNAL", link,+ self.__name__, event)self.notifyListeners(evt)# End of sfp_googlesearch classdiff --git a/modules/sfp_honeypot.py b/modules/sfp_honeypot.pyindex 2bd41503..bc81b960 100644--- a/modules/sfp_honeypot.py+++ b/modules/sfp_honeypot.py@@ -1,5 +1,5 @@# -*- coding: utf-8 -*--#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------# Name: sfp_honeypot# Purpose: SpiderFoot plug-in for looking up whether IPs appear in the# projecthoneypot.org database.@@ -9,12 +9,13 @@# Created: 16/04/2014# Copyright: (c) Steve Micallef 2014# Licence: GPL-#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------import socketfrom netaddr import IPNetworkfrom sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent+class sfp_honeypot(SpiderFootPlugin):"""Honeypot Checker: Query the projecthoneypot.org database for entries."""@@ -69,15 +70,15 @@ class sfp_honeypot(SpiderFootPlugin):# What events is this module interested in for inputdef watchedEvents(self):- return [ 'IP_ADDRESS', 'AFFILIATE_IPADDR', 'NETBLOCK_OWNER',- 'NETBLOCK_MEMBER' ]+ return ['IP_ADDRESS', 'AFFILIATE_IPADDR', 'NETBLOCK_OWNER',+ 'NETBLOCK_MEMBER']# What events this module produces# This is to support the end user in selecting modules based on events# produced.def producedEvents(self):- return [ "BLACKLISTED_IPADDR", "BLACKLISTED_AFFILIATE_IPADDR",- "BLACKLISTED_SUBNET", "BLACKLISTED_NETBLOCK" ]+ return ["BLACKLISTED_IPADDR", "BLACKLISTED_AFFILIATE_IPADDR",+ "BLACKLISTED_SUBNET", "BLACKLISTED_NETBLOCK"]# Swap 1.2.3.4 to 4.3.2.1def reverseAddr(self, ipaddr):@@ -96,8 +97,8 @@ class sfp_honeypot(SpiderFootPlugin):return Nonetext = "Honeypotproject ({0}): " + self.statuses[bits[3]] + \- "\nLast Activity: " + bits[1] + " days ago" + \- "\nThreat Level: " + bits[2]+ "\nLast Activity: " + bits[1] + " days ago" + \+ "\nThreat Level: " + bits[2]return textdef queryAddr(self, qaddr, parentEvent):@@ -105,7 +106,7 @@ class sfp_honeypot(SpiderFootPlugin):try:lookup = self.opts['apikey'] + "." + \- self.reverseAddr(qaddr) + ".dnsbl.httpbl.org"+ self.reverseAddr(qaddr) + ".dnsbl.httpbl.org"self.sf.debug("Checking Honeypot: " + lookup)addrs = self.sf.normalizeDNS(socket.gethostbyname_ex(lookup))@@ -128,9 +129,8 @@ class sfp_honeypot(SpiderFootPlugin):e = "BLACKLISTED_NETBLOCK"if eventName == "NETBLOCK_MEMBER":e = "BLACKLISTED_SUBNET"-- evt = SpiderFootEvent(e, text.format(qaddr), self.__name__,- parentEvent)++ evt = SpiderFootEvent(e, text.format(qaddr), self.__name__, parentEvent)self.notifyListeners(evt)except BaseException as e:self.sf.debug("Unable to resolve " + qaddr + " / " + lookup + ": " + str(e))@@ -158,15 +158,15 @@ class sfp_honeypot(SpiderFootPlugin):if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:self.sf.debug("Network size bigger than permitted: " + \- str(IPNetwork(eventData).prefixlen) + " > " + \- str(self.opts['maxnetblock']))+ str(IPNetwork(eventData).prefixlen) + " > " + \+ str(self.opts['maxnetblock']))return Noneif eventName == 'NETBLOCK_MEMBER' and self.opts['subnetlookup']:if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:self.sf.debug("Network size bigger than permitted: " + \- str(IPNetwork(eventData).prefixlen) + " > " + \- str(self.opts['maxsubnet']))+ str(IPNetwork(eventData).prefixlen) + " > " + \+ str(self.opts['maxsubnet']))return Noneif eventName.startswith("NETBLOCK_"):diff --git a/sflib.py b/sflib.pyindex fa40309c..299b924a 100644--- a/sflib.py+++ b/sflib.py@@ -1,5 +1,5 @@# -*- coding: utf-8 -*--#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------# Name: sflib# Purpose: Common functions used by SpiderFoot modules.# Also defines the SpiderFootPlugin abstract class for modules.@@ -9,7 +9,7 @@# Created: 26/03/2012# Copyright: (c) Steve Micallef 2012# Licence: GPL-#-------------------------------------------------------------------------------+# -------------------------------------------------------------------------------import inspectimport hashlib@@ -26,6 +26,7 @@ import StringIOimport threadingfrom copy import deepcopy+class SpiderFoot:dbh = NoneGUID = None@@ -100,10 +101,10 @@ class SpiderFoot:# Generate an globally unique ID for this scandef genScanInstanceGUID(self, scanName):hashStr = hashlib.sha256(- scanName +- str(time.time() * 1000) +- str(random.randint(100000, 999999))- ).hexdigest()+ scanName ++ str(time.time() * 1000) ++ str(random.randint(100000, 999999))+ ).hexdigest()return hashStrdef _dblog(self, level, message, component=None):@@ -207,7 +208,7 @@ class SpiderFoot:if sz == 0:return None- if mtime > time.time() - timeoutHrs*3600 or timeoutHrs == 0:+ if mtime > time.time() - timeoutHrs * 3600 or timeoutHrs == 0:fp = file(cacheFile, "r")fileContents = fp.read()fp.close()@@ -252,7 +253,7 @@ class SpiderFoot:continueif type(opts['__modules__'][mod]['opts'][opt]) is int or \- type(opts['__modules__'][mod]['opts'][opt]) is str:+ type(opts['__modules__'][mod]['opts'][opt]) is str:storeopts[mod + ":" + opt] = opts['__modules__'][mod]['opts'][opt]if type(opts['__modules__'][mod]['opts'][opt]) is bool:@@ -262,10 +263,10 @@ class SpiderFoot:storeopts[mod + ":" + opt] = 0if type(opts['__modules__'][mod]['opts'][opt]) is list:storeopts[mod + ":" + opt] = ','.join(str(x) \- for x in opts['__modules__'][mod]['opts'][opt])+ for x in opts['__modules__'][mod]['opts'][opt])return storeopts-+# Take strings, etc. from the database or UI and convert them# to a dictionary for Python to process.# referencePoint is needed to know the actual types the options@@ -295,7 +296,7 @@ class SpiderFoot:if type(referencePoint[opt][0]) is int:returnOpts[opt] = list()for x in str(opts[opt]).split(","):- returnOpts[opt].append(int(x))+ returnOpts[opt].append(int(x))else:returnOpts[opt] = str(opts[opt]).split(",")@@ -467,7 +468,7 @@ class SpiderFoot:def domainKeyword(self, domain, tldList):# Strip off the TLDtld = '.'.join(self.hostDomain(domain.lower(), tldList).split('.')[1:])- ret = domain.lower().replace('.'+tld, '')+ ret = domain.lower().replace('.' + tld, '')# If the user supplied a domain with a sub-domain, return the second partif '.' in ret:@@ -482,7 +483,7 @@ class SpiderFoot:for domain in domainList:# Strip off the TLDtld = '.'.join(self.hostDomain(domain.lower(), tldList).split('.')[1:])- ret = domain.lower().replace('.'+tld, '')+ ret = domain.lower().replace('.' + tld, '')# If the user supplied a domain with a sub-domain, return the second partif '.' in ret:@@ -492,7 +493,7 @@ class SpiderFoot:self.debug("Keywords: " + str(arr))return arr-+# Obtain the domain name for a supplied hostname# tldList needs to be an array based on the Mozilla public listdef hostDomain(self, hostname, tldList):@@ -529,7 +530,7 @@ class SpiderFoot:for c in haystack[needle]:#print "found child of " + needle + ": " + c- ret.append({ "name": c, "children": get_children(c, haystack) })+ ret.append({"name": c, "children": get_children(c, haystack)})return ret# Find the element with no parents, that's our root.@@ -552,9 +553,9 @@ class SpiderFoot:if root is None:#print "*BUG*: Invalid structure - needs to go back to one root."- final = { }+ final = {}else:- final = { "name": root, "children": get_children(root, data) }+ final = {"name": root, "children": get_children(root, data)}return final@@ -595,7 +596,7 @@ class SpiderFoot:# Find actual linkstry:regRel = re.compile('(href|src|action|url)[:=][ \'\"]*(.[^\'\"<> ]*)',- re.IGNORECASE)+ re.IGNORECASE)urlsRel = regRel.findall(data)except Exception as e:self.error("Error applying regex to: " + data)@@ -607,14 +608,14 @@ class SpiderFoot:try:# Because we're working with a big blob of text now, don't worry# about clobbering proper links by url decoding them.- regRel = re.compile('(.)([a-zA-Z0-9\-\.]+\.'+domain+')',- re.IGNORECASE)+ regRel = re.compile('(.)([a-zA-Z0-9\-\.]+\.' + domain + ')',+ re.IGNORECASE)urlsRel = urlsRel + regRel.findall(data)except Exception as e:self.error("Error applying regex2 to: " + data)try:# Some links are sitting inside a tag, e.g. Google's use of <cite>- regRel = re.compile('(>)('+domain+'/.[^<]+)', re.IGNORECASE)+ regRel = re.compile('(>)(' + domain + '/.[^<]+)', re.IGNORECASE)urlsRel = urlsRel + regRel.findall(data)except Exception as e:self.error("Error applying regex3 to: " + data)@@ -628,8 +629,8 @@ class SpiderFoot:# Don't include stuff likely part of some dynamically built incomplete# URL found in Javascript code (character is part of some logic)- if link[len(link)-1] == '.' or link[0] == '+' or \- 'javascript:' in link.lower() or '();' in link:+ if link[len(link) - 1] == '.' or link[0] == '+' or \+ 'javascript:' in link.lower() or '();' in link:self.debug('unlikely link: ' + link)continue@@ -671,8 +672,8 @@ class SpiderFoot:return returnLinks# Fetch a URL, return the response object- def fetchUrl(self, url, fatal=False, cookies=None, timeout=30,- useragent="SpiderFoot", headers=None, dontMangle=False):+ def fetchUrl(self, url, fatal=False, cookies=None, timeout=30,+ useragent="SpiderFoot", headers=None, dontMangle=False):result = {'code': None,'status': None,@@ -704,11 +705,11 @@ class SpiderFoot:if cookies is not None:req.add_header('cookie', cookies)self.info("Fetching (incl. cookies): " + url + \- " [user-agent: " + header['User-Agent'] + "] [timeout: " + \- str(timeout) + "]")+ " [user-agent: " + header['User-Agent'] + "] [timeout: " + \+ str(timeout) + "]")else:self.info("Fetching: " + url + " [user-agent: " + \- header['User-Agent'] + "] [timeout: " + str(timeout) + "]")+ header['User-Agent'] + "] [timeout: " + str(timeout) + "]")result['headers'] = dict()opener = urllib2.build_opener(SmartRedirectHandler())@@ -786,10 +787,10 @@ class SpiderFoot:# We attempt to make the URL look as authentically human as possibleseedUrl = u"http://www.google.com/search?q={0}".format(searchString) + \- u"&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a"+ u"&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a"firstPage = self.fetchUrl(seedUrl, timeout=opts['timeout'],- useragent=opts['useragent'])+ useragent=opts['useragent'])if firstPage['code'] == 403 or firstPage['code'] == 503:self.error("Google doesn't like us right now..", False)return None@@ -811,7 +812,7 @@ class SpiderFoot:fetches += 1for match in matches:# Google moves in increments of 10- if "start=" + str(fetches*10) in match:+ if "start=" + str(fetches * 10) in match:nextUrl = match.replace("&", "&")if nextUrl is None:@@ -826,7 +827,7 @@ class SpiderFoot:time.sleep(pauseSecs)nextPage = self.fetchUrl(u'http://www.google.com' + nextUrl,- timeout=opts['timeout'], useragent=opts['useragent'])+ timeout=opts['timeout'], useragent=opts['useragent'])if nextPage['code'] == 403 or nextPage['code'] == 503:self.error("Google doesn't like us right now..", False)return returnResults@@ -863,9 +864,9 @@ class SpiderFoot:# We attempt to make the URL look as authentically human as possibleseedUrl = u"http://www.bing.com/search?q={0}".format(searchString) + \- u"&pc=MOZI"+ u"&pc=MOZI"firstPage = self.fetchUrl(seedUrl, timeout=opts['timeout'],- useragent=opts['useragent'])+ useragent=opts['useragent'])if firstPage['code'] == 400:self.error("Bing doesn't like us right now..", False)return None@@ -886,7 +887,7 @@ class SpiderFoot:fetches += 1for match in matches:# Bing moves in increments of 10- if "first=" + str((fetches*10)+1) in match:+ if "first=" + str((fetches * 10) + 1) in match:nextUrl = match.replace("&", "&").replace("%3a", ":")if nextUrl is None:@@ -901,7 +902,7 @@ class SpiderFoot:time.sleep(pauseSecs)nextPage = self.fetchUrl(u'http://www.bing.com' + nextUrl,- timeout=opts['timeout'], useragent=opts['useragent'])+ timeout=opts['timeout'], useragent=opts['useragent'])if nextPage['code'] == 400:self.error("Bing doesn't like us any more..", False)return returnResults@@ -938,9 +939,9 @@ class SpiderFoot:# We attempt to make the URL look as authentically human as possibleseedUrl = u"https://search.yahoo.com/search?p={0}".format(searchString) + \- u"&toggle=1&cop=mss&ei=UTF-8"+ u"&toggle=1&cop=mss&ei=UTF-8"firstPage = self.fetchUrl(seedUrl, timeout=opts['timeout'],- useragent=opts['useragent'])+ useragent=opts['useragent'])if firstPage['code'] == 403:self.error("Yahoo doesn't like us right now..", False)return None@@ -958,7 +959,7 @@ class SpiderFoot:fetches += 1for match in matches:# Yahoo moves in increments of 10- if "b=" + str((fetches*10)+1) in match:+ if "b=" + str((fetches * 10) + 1) in match:nextUrl = u"https://search.yahoo.com" + matchif nextUrl is None:@@ -973,7 +974,7 @@ class SpiderFoot:time.sleep(pauseSecs)nextPage = self.fetchUrl(nextUrl,- timeout=opts['timeout'], useragent=opts['useragent'])+ timeout=opts['timeout'], useragent=opts['useragent'])if nextPage['code'] == 403:self.error("Yahoo doesn't like us any more..", False)return returnResults@@ -988,6 +989,7 @@ class SpiderFoot:return returnResults+## SpiderFoot plug-in module base class#@@ -1068,7 +1070,7 @@ class SpiderFootPlugin(object):def notifyListeners(self, sfEvent):eventName = sfEvent.eventTypeeventData = sfEvent.data- storeOnly = False # Under some conditions, only store and don't notify+ storeOnly = False # Under some conditions, only store and don't notifyif eventData is None or (type(eventData) is unicode and len(eventData) == 0):#print "No data to send for " + eventName + " to " + listener.__module__@@ -1092,7 +1094,7 @@ class SpiderFootPlugin(object):while prevEvent is not None:if prevEvent.sourceEvent is not None:if prevEvent.sourceEvent.eventType == sfEvent.eventType and \- prevEvent.sourceEvent.data.lower() == sfEvent.data.lower():+ prevEvent.sourceEvent.data.lower() == sfEvent.data.lower():#print "Skipping notification of " + sfEvent.eventType + " / " + sfEvent.datastoreOnly = Truebreak@@ -1138,7 +1140,7 @@ class SpiderFootPlugin(object):# Will usually be overriden by the implementer, unless it is interested# in all events (default behavior).def watchedEvents(self):- return [ '*' ]+ return ['*']# What events this module produces# This is to support the end user in selecting modules based on events@@ -1158,9 +1160,10 @@ class SpiderFootPlugin(object):def start(self):return None+# Class for targetsclass SpiderFootTarget(object):- _validTypes = [ "IP_ADDRESS", "NETBLOCK_OWNER", "INTERNET_NAME" ]+ _validTypes = ["IP_ADDRESS", "NETBLOCK_OWNER", "INTERNET_NAME"]targetType = NonetargetValue = NonetargetAliases = list()@@ -1191,7 +1194,7 @@ class SpiderFootTarget(object):return Noneself.targetAliases.append(- { 'type': typeName, 'value': value.lower() }+ {'type': typeName, 'value': value.lower()})def getAliases(self):@@ -1251,7 +1254,7 @@ class SpiderFootTarget(object):return Trueif self.targetType == "IP_ADDRESS":if netaddr.IPAddress(value) in \- netaddr.IPNetwork(netaddr.IPAddress(self.targetValue)):+ netaddr.IPNetwork(netaddr.IPAddress(self.targetValue)):return Trueelse:for name in self.getNames():@@ -1267,6 +1270,7 @@ class SpiderFootTarget(object):return None+# Class for SpiderFoot Eventsclass SpiderFootEvent(object):generated = None@@ -1279,9 +1283,9 @@ class SpiderFootEvent(object):sourceEvent = NonesourceEventHash = None__id = None-+def __init__(self, eventType, data, module, sourceEvent,- confidence=100, visibility=100, risk=0):+ confidence=100, visibility=100, risk=0):self.eventType = eventTypeself.generated = time.time()self.confidence = confidence@@ -1299,7 +1303,7 @@ class SpiderFootEvent(object):self.sourceEventHash = sourceEvent.getHash()self.__id = self.eventType + str(self.generated) + self.module + \- str(random.randint(0, 99999999))+ str(random.randint(0, 99999999))# Unique hash of this eventdef getHash(self):@@ -1344,106 +1348,108 @@ Public Suffix List module for Python.See LICENSE.tp for applicable license."""+class PublicSuffixList(object):- def __init__(self, input_data):- """Reads and parses public suffix list.-- input_file is a file object or another iterable that returns- lines of a public suffix list file. If input_file is None, an- UTF-8 encoded file named "publicsuffix.txt" in the same- directory as this Python module is used.-- The file format is described at http://publicsuffix.org/list/- """+ def __init__(self, input_data):+ """Reads and parses public suffix list.++ input_file is a file object or another iterable that returns+ lines of a public suffix list file. If input_file is None, an+ UTF-8 encoded file named "publicsuffix.txt" in the same+ directory as this Python module is used.- #if input_file is None:- #input_path = os.path.join(os.path.dirname(__file__), 'publicsuffix.txt')- #input_file = codecs.open(input_path, "r", "utf8")+ The file format is described at http://publicsuffix.org/list/+ """- root = self._build_structure(input_data)- self.root = self._simplify(root)+ #if input_file is None:+ #input_path = os.path.join(os.path.dirname(__file__), 'publicsuffix.txt')+ #input_file = codecs.open(input_path, "r", "utf8")- def _find_node(self, parent, parts):- if not parts:- return parent+ root = self._build_structure(input_data)+ self.root = self._simplify(root)- if len(parent) == 1:- parent.append({})+ def _find_node(self, parent, parts):+ if not parts:+ return parent- assert len(parent) == 2- negate, children = parent+ if len(parent) == 1:+ parent.append({})- child = parts.pop()+ assert len(parent) == 2+ negate, children = parent- child_node = children.get(child, None)+ child = parts.pop()- if not child_node:- children[child] = child_node = [0]+ child_node = children.get(child, None)- return self._find_node(child_node, parts)+ if not child_node:+ children[child] = child_node = [0]- def _add_rule(self, root, rule):- if rule.startswith('!'):- negate = 1- rule = rule[1:]- else:- negate = 0+ return self._find_node(child_node, parts)- parts = rule.split('.')- self._find_node(root, parts)[0] = negate+ def _add_rule(self, root, rule):+ if rule.startswith('!'):+ negate = 1+ rule = rule[1:]+ else:+ negate = 0- def _simplify(self, node):- if len(node) == 1:- return node[0]+ parts = rule.split('.')+ self._find_node(root, parts)[0] = negate- return (node[0], dict((k, self._simplify(v)) for (k, v) in node[1].items()))+ def _simplify(self, node):+ if len(node) == 1:+ return node[0]- def _build_structure(self, fp):- root = [0]+ return (node[0], dict((k, self._simplify(v)) for (k, v) in node[1].items()))- for line in fp:- line = line.strip()- if line.startswith('//') or not line:- continue+ def _build_structure(self, fp):+ root = [0]- self._add_rule(root, line.split()[0].lstrip('.'))+ for line in fp:+ line = line.strip()+ if line.startswith('//') or not line:+ continue- return root+ self._add_rule(root, line.split()[0].lstrip('.'))++ return root++ def _lookup_node(self, matches, depth, parent, parts):+ if parent in (0, 1):+ negate = parent+ children = None+ else:+ negate, children = parent- def _lookup_node(self, matches, depth, parent, parts):- if parent in (0, 1):- negate = parent- children = None- else:- negate, children = parent+ matches[-depth] = negate- matches[-depth] = negate+ if depth < len(parts) and children:+ for name in ('*', parts[-depth]):+ child = children.get(name, None)+ if child is not None:+ self._lookup_node(matches, depth + 1, child, parts)- if depth < len(parts) and children:- for name in ('*', parts[-depth]):- child = children.get(name, None)- if child is not None:- self._lookup_node(matches, depth+1, child, parts)+ def get_public_suffix(self, domain):+ """get_public_suffix("www.example.com") -> "example.com"- def get_public_suffix(self, domain):- """get_public_suffix("www.example.com") -> "example.com"+ Calling this function with a DNS name will return the+ public suffix for that name.- Calling this function with a DNS name will return the- public suffix for that name.+ Note that for internationalized domains the list at+ http://publicsuffix.org uses decoded names, so it is+ up to the caller to decode any Punycode-encoded names.+ """- Note that for internationalized domains the list at- http://publicsuffix.org uses decoded names, so it is- up to the caller to decode any Punycode-encoded names.- """+ parts = domain.lower().lstrip('.').split('.')+ hits = [None] * len(parts)- parts = domain.lower().lstrip('.').split('.')- hits = [None] * len(parts)+ self._lookup_node(hits, 1, self.root, parts)- self._lookup_node(hits, 1, self.root, parts)+ for i, what in enumerate(hits):+ if what is not None and what == 0:+ return '.'.join(parts[i:])- 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: