SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.
Python attacksurfacecticybersecurityfootprintinghackinginformation-gatheringinformation-securityinfosecintelligence-gatheringosintosint-frameworkosint-reconnaissanceosint-toolpentestingpythonreconsecurity-toolsthreat-intelligencethreatintel
Loading configuration options from files or URLs in a consistent manner.
smicallefd13505e0d12c
diff --git a/modules/sfp_dns.py b/modules/sfp_dns.pyindex 744aa5be..b8c76f51 100644--- a/modules/sfp_dns.py+++ b/modules/sfp_dns.py@@ -43,7 +43,7 @@ class sfp_dns(SpiderFootPlugin):'skipcommononwildcard': "If wildcard DNS is detected, look up the first common sub-domain only.",'resolveaffiliate': "Obtain IPs for confirmed affiliates?",'reverselookup': "Obtain new URLs and possible affiliates based on reverse-resolved IPs?",- "commonsubs": "Common sub-domains to try."+ "commonsubs": "Common sub-domains to try. 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."}# Target@@ -212,12 +212,19 @@ class sfp_dns(SpiderFootPlugin):if not item.endswith(self.baseDomain):evt = SpiderFootEvent("AFFILIATE", item, self.__name__)self.notifyListeners(evt)++ sublist = self.opts['commonsubs']+ # User may have supplied a file or URL containing the subdomains+ if self.opts['commonsubs'][0].startswith("http://") or \+ self.opts['commonsubs'][0].startswith("https://") or \+ self.opts['commonsubs'][0].startswith("@"):+ sublist = sf.optValueToData(self.opts['commonsubs'][0])- sf.debug("Iterating through possible sub-domains [" + str(self.opts['commonsubs']) + "]")+ sf.debug("Iterating through possible sub-domains [" + str(sublist) + "]")count = 0wildcard = sf.checkDnsWildcard(self.baseDomain)# Try resolving common names- for sub in self.opts['commonsubs']:+ for sub in sublist:if wildcard and self.opts['skipcommononwildcard'] and count > 0:sf.debug("Wildcard DNS detected, skipping iterating through remaining hosts.")return Nonediff --git a/modules/sfp_geoip.py b/modules/sfp_geoip.pyindex 3cfcefe3..47ddeb85 100644--- a/modules/sfp_geoip.py+++ b/modules/sfp_geoip.py@@ -58,7 +58,8 @@ class sfp_geoip(SpiderFootPlugin):else:self.results[eventData] = True- res = sf.fetchUrl("http://api.hostip.info/get_json.php?ip=" + eventData)+ res = sf.fetchUrl("http://api.hostip.info/get_json.php?ip=" + eventData,+ timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])if res['content'] == None:sf.info("No GeoIP info found for " + eventData)try:diff --git a/modules/sfp_googlesearch.py b/modules/sfp_googlesearch.pyindex d6578bed..0ddea4fd 100644--- a/modules/sfp_googlesearch.py+++ b/modules/sfp_googlesearch.py@@ -68,7 +68,8 @@ class sfp_googlesearch(SpiderFootPlugin):# We attempt to make the URL look as authentically human as possibleseedUrl = "http://www.google.com/search?q={0}".format(searchString) + \"&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a"- firstPage = sf.fetchUrl(seedUrl)+ firstPage = sf.fetchUrl(seedUrl, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])if firstPage['code'] == "403":sf.error("Google doesn't like us right now..")return None@@ -103,7 +104,8 @@ class sfp_googlesearch(SpiderFootPlugin):if self.checkForStop():return None- nextPage = sf.fetchUrl('http://www.google.com' + nextUrl)+ nextPage = sf.fetchUrl('http://www.google.com' + nextUrl,+ timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])if firstPage['code'] == 403:sf.error("Google doesn't like us any more..")return returnResultsdiff --git a/modules/sfp_portscan_basic.py b/modules/sfp_portscan_basic.pyindex fffdc6cc..159d57ce 100644--- a/modules/sfp_portscan_basic.py+++ b/modules/sfp_portscan_basic.py@@ -26,10 +26,10 @@ class sfp_portscan_basic(SpiderFootPlugin):# Default optionsopts = {# Commonly used ports on external-facing systems- 'ports': [ 21, 22, 23, 25, 53, 79, 80, 81, 88, 110, 111,- 113, 119, 123, 137, 138, 139, 143, 161, 179,- 389, 443, 445, 465, 512, 513, 514, 515, 631, 636,- 990, 992, 993, 995, 1080, 8080, 8888, 9000 ],+ 'ports': [ '21', '22', '23', '25', '53', '79', '80', '81', '88', '110','111',+ '113', '119', '123', '137', '138', '139', '143', '161', '179',+ '389', '443', '445', '465', '512', '513', '514', '515', '631', '636',+ '990', '992', '993', '995', '1080', '8080', '8888', '9000' ],'timeout': 15,'maxthreads': 10,'randomize': True@@ -38,7 +38,7 @@ class sfp_portscan_basic(SpiderFootPlugin):# Option descriptionsoptdescs = {'maxthreads': "Number of ports to try to open simultaneously (number of threads to spawn at once.)",- 'ports': "The TCP ports to scan.",+ 'ports': "The TCP ports to scan. Prefix with an '@' to iterate through a file containing ports to try (one per line), e.g. @C:\ports.txt or @/home/bob/ports.txt. Or supply a URL to load the list from there.",'timeout': "Seconds before giving up on a port.",'randomize': "Randomize the order of ports scanned."}@@ -46,6 +46,7 @@ class sfp_portscan_basic(SpiderFootPlugin):# TargetbaseDomain = Noneresults = dict()+ portlist = list()portResults = dict()def setup(self, sfc, target, userOpts=dict()):@@ -58,8 +59,18 @@ class sfp_portscan_basic(SpiderFootPlugin):for opt in userOpts.keys():self.opts[opt] = userOpts[opt]+ if self.opts['ports'][0].startswith("http://") or \+ self.opts['ports'][0].startswith("https://") or \+ self.opts['ports'][0].startswith("@"):+ self.portlist = sf.optValueToData(self.opts['ports'][0])+ else:+ self.portlist = self.opts['ports']++ # Convert to integers+ self.portlist = [int(x) for x in self.portlist]+if self.opts['randomize']:- random.shuffle(self.opts['ports'])+ random.shuffle(self.portlist)# What events is this module interested in for inputdef watchedEvents(self):@@ -139,7 +150,7 @@ class sfp_portscan_basic(SpiderFootPlugin):i = 0portArr = []- for port in self.opts['ports']:+ for port in self.portlist:if self.checkForStop():return Nonediff --git a/modules/sfp_ripe.py b/modules/sfp_ripe.pyindex 0f7b577a..7b63fdc6 100644--- a/modules/sfp_ripe.py+++ b/modules/sfp_ripe.py@@ -59,7 +59,8 @@ class sfp_ripe(SpiderFootPlugin):self.results[eventData] = Trueif eventName == 'SUBDOMAIN':- res = sf.fetchUrl("http://stat.ripe.net/data/dns-chain/data.json?resource=" + eventData)+ res = sf.fetchUrl("http://stat.ripe.net/data/dns-chain/data.json?resource=" + \+ eventData, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])if res['content'] == None:sf.info("No RIPE info found/available for " + eventData)return None@@ -83,7 +84,8 @@ class sfp_ripe(SpiderFootPlugin):return None# First get the netblock the IP resides on- res = sf.fetchUrl("http://stat.ripe.net/data/network-info/data.json?resource=" + eventData)+ res = sf.fetchUrl("http://stat.ripe.net/data/network-info/data.json?resource=" + \+ eventData, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])if res['content'] == None:sf.info("No RIPE info found/available for " + eventData)return None@@ -100,14 +102,15 @@ class sfp_ripe(SpiderFootPlugin):return None# Now see who owns the prefix- res = sf.fetchUrl("http://stat.ripe.net/data/whois/data.json?resource=" + prefix)+ res = sf.fetchUrl("http://stat.ripe.net/data/whois/data.json?resource=" + \+ prefix, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])if res['content'] == None:sf.info("No RIPE info found/available for prefix: " + prefix)return Nonekeyword = sf.domainKeyword(self.baseDomain)res['content'] = res['content'].lower()- print keyword + " and " + self.baseDomain + " in: " + res['content']+ #print keyword + " and " + self.baseDomain + " in: " + res['content']# Crude and probably prone to a lot of false positives. Need to revisit.if self.baseDomain in res['content'] or "\"" + keyword in res['content'] \or keyword +"\"" in res['content'] or keyword +"-" in res['content'] \@@ -122,7 +125,8 @@ class sfp_ripe(SpiderFootPlugin):def start(self):res = sf.fetchUrl("http://stat.ripe.net/data/dns-chain/data.json?resource=" + \- self.baseDomain)+ self.baseDomain, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])if res['content'] == None:sf.info("No RIPE info found/available for " + self.baseDomain)return Nonediff --git a/modules/sfp_searchtld.py b/modules/sfp_searchtld.pyindex d6b4b0fa..54b3d7af 100644--- a/modules/sfp_searchtld.py+++ b/modules/sfp_searchtld.py@@ -116,7 +116,8 @@ class sfp_searchtld(SpiderFootPlugin):if self.checkForStop():return None- pageContent = sf.fetchUrl('http://' + result)+ pageContent = sf.fetchUrl('http://' + result,+ timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])if pageContent['content'] != None:evt = SpiderFootEvent("SIMILARDOMAIN", result, self.__name__)self.notifyListeners(evt)@@ -135,7 +136,8 @@ class sfp_searchtld(SpiderFootPlugin):# self.scrapeWhois(keyword)# Look through all TLDs for the existence of this target keyword- tldlistContent = sf.fetchUrl(self.opts['tldlist'])+ tldlistContent = sf.fetchUrl(self.opts['tldlist'],+ timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])if tldlistContent['content'] == None:sf.error("Unable to obtain TLD list from " + self.opts['tldlist'], False)else:diff --git a/modules/sfp_similar.py b/modules/sfp_similar.pyindex b2ec318d..cdc996d8 100644--- a/modules/sfp_similar.py+++ b/modules/sfp_similar.py@@ -103,7 +103,8 @@ class sfp_similar(SpiderFootPlugin):if self.checkForStop():return None- whois = sf.fetchUrl(fetchPage)+ whois = sf.fetchUrl(fetchPage, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])if whois['content'] == None:return None@@ -134,7 +135,8 @@ class sfp_similar(SpiderFootPlugin):if self.checkForStop():return None- domtool = sf.fetchUrl(fetchPage)+ domtool = sf.fetchUrl(fetchPage, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])if domtool['content'] == None:return None@@ -168,7 +170,8 @@ class sfp_similar(SpiderFootPlugin):if self.checkForStop():return None- namedrop = sf.fetchUrl(fetchPage)+ namedrop = sf.fetchUrl(fetchPage, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])if namedrop['content'] == None:return None@@ -200,7 +203,8 @@ class sfp_similar(SpiderFootPlugin):if self.checkForStop():return None- pageContent = sf.fetchUrl('http://' + result)+ pageContent = sf.fetchUrl('http://' + result,+ timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])if pageContent['content'] != None:evt = SpiderFootEvent("SIMILARDOMAIN", result, self.__name__)self.notifyListeners(evt)diff --git a/modules/sfp_spider.py b/modules/sfp_spider.pyindex b5d5e22d..e35906a8 100644--- a/modules/sfp_spider.py+++ b/modules/sfp_spider.py@@ -32,7 +32,7 @@ class sfp_spider(SpiderFootPlugin):'filterfiles': ['png','gif','jpg','jpeg','tiff', 'tif', 'js', 'css', 'tar','pdf','tif','ico','flv', 'mp4', 'mp3', 'avi', 'mpg', 'gz','mpeg', 'iso', 'dat', 'mov', 'swf', 'rar', 'exe', 'zip',- 'bin', 'bz2'],+ 'bin', 'bz2', 'xsl'],'filterusers': True, # Don't follow /~user directories'noexternal': True, # Should links to external sites be ignored? (**dangerous if False**)'nosubs': False, # Should links to subdomains be ignored?@@ -87,7 +87,8 @@ class sfp_spider(SpiderFootPlugin):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 = sf.fetchUrl(url, False, cookies,+ self.opts['_fetchtimeout'], self.opts['_useragent'])self.fetchedPages[url] = True# Track cookies a site has sent, then send the back in subsquent requests@@ -223,7 +224,8 @@ class sfp_spider(SpiderFootPlugin):# Determine where to start spidering from if it's a SUBDOMAIN eventif eventName == "SUBDOMAIN":for prefix in self.opts['start']:- res = sf.fetchUrl(prefix + eventData)+ res = sf.fetchUrl(prefix + eventData, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])if res['content'] != None:spiderTarget = prefix + eventDatabreak@@ -249,7 +251,8 @@ class sfp_spider(SpiderFootPlugin):# Are we respecting robots.txt?if self.opts['robotsonly'] and not self.robotsRules.has_key(targetBase):- robotsTxt = sf.fetchUrl(targetBase + '/robots.txt')+ robotsTxt = 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'])diff --git a/modules/sfp_xref.py b/modules/sfp_xref.pyindex 6ffe02ab..c0613e87 100644--- a/modules/sfp_xref.py+++ b/modules/sfp_xref.py@@ -92,7 +92,8 @@ class sfp_xref(SpiderFootPlugin):returnsf.debug("Testing for affiliation: " + url)- res = sf.fetchUrl(url)+ res = sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])self.fetched.append(url)if res['content'] == None:@@ -109,7 +110,8 @@ class sfp_xref(SpiderFootPlugin):if not self.opts['forcebase'] and len(matches) > 0 and self.opts['checkbase']:# Check the base url to see if there is an affiliationurl = sf.urlBaseUrl(eventData)- res = sf.fetchUrl(url)+ res = sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])if res['content'] != None:matches = re.findall("([\.\'\/\"\ ]" + self.baseDomain + "[\'\/\"\ ])",res['content'], re.IGNORECASE)diff --git a/sf.py b/sf.pyindex f9d4afac..59030807 100755--- a/sf.py+++ b/sf.py@@ -35,7 +35,7 @@ sfConfig = {sfOptdescs = {'_debug': "Enable debugging?",- '_useragent': "User-Agent string to use for HTTP requests. Prefix with an '@' to randomly select the User Agent from a file containing user agent strings for each request, e.g. @C:\useragents.txt or @/home/bob/useragents.txt.",+ '_useragent': "User-Agent string to use for HTTP requests. Prefix with an '@' to randomly select the User Agent from a file containing user agent strings for each request, e.g. @C:\useragents.txt or @/home/bob/useragents.txt. Or supply a URL to load the list from there.",'_dnsserver': "Override the default resolver with another DNS server. For example, 8.8.8.8 is Google's open DNS server.",'_fetchtimeout': "Number of seconds before giving up on a HTTP request.",'_modulesenabled': "Modules enabled for the scan." # This is a hack to get a description fordiff --git a/sflib.py b/sflib.pyindex 129f81a4..d7e2f177 100644--- a/sflib.py+++ b/sflib.py@@ -32,21 +32,46 @@ class SpiderFoot:self.handle = handleself.opts = options- # For the useragent option, if the user has supplied a path,- # open the file and load into options['__useragent_list']- if "_useragent" in options.keys():- if options["_useragent"].startswith("@"):- fname = options["_useragent"].split('@')[1]- try:- f = open(fname, "r")- options['__useragent_list'] = f.readlines()- except BaseException as b:- self.error("Unable to open User Agent file, " + fname + ".")- options["__useragent_list"] = [ "Unknown" ]+ # Supplied an option value, return the data based on what the+ # value is. If val is a URL, you'll get back the fetched content,+ # if val is a file path it will be loaded and get back the contents,+ # and if a string it will simply be returned back.+ def optValueToData(self, val, fatal=True, splitLines=True):+ if val.startswith('@'):+ fname = val.split('@')[1]+ try:+ self.info("Loading configuration data from: " + fname)+ f = open(fname, "r")+ if splitLines:+ arr = f.readlines()+ ret = list()+ for x in arr:+ ret.append(x.rstrip('\n'))+ else:+ ret = f.read()+ return ret+ except BaseException as b:+ if fatal:+ self.error("Unable to open option file, " + fname + ".")+ else:+ return None++ if val.lower().startswith('http://') or val.lower().startswith('https://'):+ try:+ self.info("Downloading configuration data from: " + val)+ res = urllib2.urlopen(val)+ data = res.read()+ if splitLines:+ return data.splitlines()+ else:+ return data+ except BaseException as e:+ if fatal:+ self.error("Unable to open option URL, " + val + ".")+ else:+ return None- #- # Debug, error message and logging functions- #+ return val# Called usually some time after instantiation# to set up a database handle and scan GUID, used@@ -114,14 +139,13 @@ class SpiderFoot:returndef myPath(self):- """ This will get us the program's directory,- even if we are frozen using py2exe"""+ # This will get us the program's directory, even if we are frozen using py2exe.# Determine whether we've been compiled by py2exeif hasattr(sys, "frozen"):- return os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding( )))+ return os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding()))- return os.path.dirname(unicode(__file__, sys.getfilesystemencoding( )))+ return os.path.dirname(unicode(__file__, sys.getfilesystemencoding()))#@@ -157,7 +181,8 @@ class SpiderFoot:if opt.startswith('_') and filterSystem:continue- if type(opts['__modules__'][mod]['opts'][opt]) is int or type(opts['__modules__'][mod]['opts'][opt]) is str:+ if type(opts['__modules__'][mod]['opts'][opt]) is int or \+ 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:@@ -166,7 +191,8 @@ class SpiderFoot:else: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])+ storeopts[mod + ":" + opt] = ','.join(str(x) \+ for x in opts['__modules__'][mod]['opts'][opt])return storeopts@@ -220,10 +246,12 @@ class SpiderFoot:returnOpts['__modules__'][modName]['opts'][opt] = Falseif type(referencePoint['__modules__'][modName]['opts'][opt]) is str:- returnOpts['__modules__'][modName]['opts'][opt] = str(opts[modName + ":" + opt])+ returnOpts['__modules__'][modName]['opts'][opt] = \+ str(opts[modName + ":" + opt])if type(referencePoint['__modules__'][modName]['opts'][opt]) is int:- returnOpts['__modules__'][modName]['opts'][opt] = int(opts[modName + ":" + opt])+ returnOpts['__modules__'][modName]['opts'][opt] = \+ int(opts[modName + ":" + opt])if type(referencePoint['__modules__'][modName]['opts'][opt]) is list:if type(referencePoint['__modules__'][modName]['opts'][opt][0]) is int:@@ -231,7 +259,8 @@ class SpiderFoot:for x in str(opts[modName + ":" + opt]).split(","):returnOpts['__modules__'][modName]['opts'][opt].append(int(x))else:- returnOpts['__modules__'][modName]['opts'][opt] = str(opts[modName + ":" + opt]).split(",")+ returnOpts['__modules__'][modName]['opts'][opt] = \+ str(opts[modName + ":" + opt]).split(",")return returnOpts#@@ -373,7 +402,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@@ -415,7 +445,8 @@ class SpiderFoot:return returnLinks# Fetch a URL, return the response object- def fetchUrl(self, url, fatal=False, cookies=None):+ def fetchUrl(self, url, fatal=False, cookies=None, timeout=30,+ useragent="SpiderFoot"):result = {'code': None,'status': None,@@ -430,22 +461,23 @@ class SpiderFoot:try:header = dict()- if self.opts.has_key('_useragent') and not self.opts['_useragent'].startswith('@'):- header['User-Agent'] = self.opts['_useragent']- if self.opts.has_key('__useragent_list'):- header['User-Agent'] = random.choice(self.opts['__useragent_list'])+ if type(useragent) is list:+ header['User-Agent'] = random.choice(useragent)+ else:+ header['User-Agent'] = useragent- if not self.opts.has_key('_fetchtimeout'):- self.opts['_fetchtimeout'] = 30req = urllib2.Request(url, None, header)if cookies != None:req.add_header('cookie', cookies)- self.info("Fetching (incl. cookies): " + url)+ self.info("Fetching (incl. cookies): " + url + \+ " [user-agent: " + header['User-Agent'] + "] [timeout: " + \+ str(timeout) + "]")else:- self.info("Fetching: " + url)+ self.info("Fetching: " + url + " [user-agent: " + \+ header['User-Agent'] + "] [timeout: " + str(timeout) + "]")opener = urllib2.build_opener(SmartRedirectHandler())- fullPage = opener.open(req, timeout=self.opts['_fetchtimeout'])+ fullPage = opener.open(req, timeout=timeout)# Prepare result to returnresult['content'] = unicode(fullPage.read(), 'utf-8', errors='replace')diff --git a/sfscan.py b/sfscan.pyindex e2f3a8af..d93506ef 100644--- a/sfscan.py+++ b/sfscan.py@@ -83,6 +83,9 @@ class SpiderFootScanner:self.sf.status("Scan [" + self.config['__guid__'] + "] initiated.")# moduleList = list of modules the user wants to runtry:+ # Process global options that point to other places for data+ self.config['_useragent'] = self.sf.optValueToData(self.config['_useragent'])+for modName in self.moduleList:if modName == '':continue@@ -154,7 +157,7 @@ class SpiderFootScanner:self.sf.status("Scan [" + self.config['__guid__'] + "] completed.")dbh.scanInstanceSet(self.config['__guid__'], None, time.time() * 1000, 'FINISHED')self.status = "FINISHED"- except Exception as e:+ except BaseException as e:exc_type, exc_value, exc_traceback = sys.exc_info()self.sf.error("Unhandled exception (" + e.__class__.__name__ + ") " + \"encountered during scan. Please report this as a bug: " + \