SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.
Python attacksurfacecticybersecurityfootprintinghackinginformation-gatheringinformation-securityinfosecintelligence-gatheringosintosint-frameworkosint-reconnaissanceosint-toolpentestingpythonreconsecurity-toolsthreat-intelligencethreatintel
Initial codebase
Steve Micallef02b159ca109e
diff --git a/modules/__init__.py b/modules/__init__.pynew file mode 100644index 00000000..d3f5a12f--- /dev/null+++ b/modules/__init__.py@@ -0,0 +1 @@+diff --git a/modules/sfp_mail.py b/modules/sfp_mail.pynew file mode 100644index 00000000..dcffa535--- /dev/null+++ b/modules/sfp_mail.py@@ -0,0 +1,80 @@+#-------------------------------------------------------------------------------+# Name: sfp_mail+# Purpose: SpiderFoot plug-in for scanning retreived content by other+# modules (such as sfp_spider) and identifying e-mail addresses+#+# Author: Steve Micallef <[email protected]>+#+# Created: 06/04/2012+# Copyright: (c) Steve Micallef 2012+# Licence: GPL+#-------------------------------------------------------------------------------++import sys+import re+from sflib import SpiderFoot, SpiderFootPlugin++# SpiderFoot standard lib (must be initialized in __init__)+sf = None++class sfp_mail(SpiderFootPlugin):+ # Default options+ opts = {+ # These must always be set+ '_debug': True,+ '_debugfilter': '',+ # options specific to this module+ 'basedomainonly': False, # Only capture e-mail addrs on the base domain+ 'includeexternal': False # Include e-mail addrs on external domains+ }++ # URL this instance is working on+ seedUrl = None+ baseDomain = None # calculated from the URL in __init__++ def __init__(self, url, userOpts=dict()):+ global sf+ self.seedUrl = url++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # For error reporting, debug, etc.+ sf = SpiderFoot(self.opts)++ # Extract the 'meaningful' part of the FQDN from the URL+ self.baseDomain = sf.urlBaseDom(self.seedUrl)+ sf.debug('Base Domain: ' + self.baseDomain)++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["WEBCONTENT"]++ # Handle events sent to this module+ def handleEvent(self, srcModuleName, eventName, eventSource, eventData):+ sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ matches = re.findall("([a-zA-Z\.0-9_\-]+@[a-zA-Z\.0-9_\-]+)", eventData)+ for match in matches:+ sf.debug("Found email: " + match)+ # Include e-mail addresses on sub-domains within the domain?+ if self.opts['basedomainonly']:+ if not match.endswith('@' + self.baseDomain):+ sf.debug("Ignoring e-mail address on a sub-domain: " + match)+ continue++ # Include external domains as e-mail addresses?+ if not self.opts['includeexternal']:+ if not match.endswith(self.baseDomain):+ sf.debug("Ignoring e-mail address on an external domain" + match)+ continue++ self.notifyListeners("EMAILADDR", eventSource, match)++ return None++# End of sfp_mail class++if __name__ == '__main__':+ print "This module cannot be run stand-alone."+ exit(-1)diff --git a/modules/sfp_similar.py b/modules/sfp_similar.pynew file mode 100644index 00000000..54ca1acb--- /dev/null+++ b/modules/sfp_similar.py@@ -0,0 +1,221 @@+#-------------------------------------------------------------------------------+# Name: sfp_similar+# Purpose: SpiderFoot plug-in for identifying domains that look similar+# to the one being queried.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 06/04/2012+# Copyright: (c) Steve Micallef 2012+# Licence: GPL+#-------------------------------------------------------------------------------++import sys+import re+import time+import random+from sflib import SpiderFoot, SpiderFootPlugin++# These are all string builders, {0} = the domain keyword, {1} = the page number++# Domaintools.com:+# Seems to be the best choice overall+domtoolUrlLeft = "http://www.domaintools.com/buy/domain-search/?q={0}&bc=25&bn=y&bh=A&order=left&pool=A&filter=y&search_type=&rows=100&de_search=Search&page={1}"+domtoolUrlRight = "http://www.domaintools.com/buy/domain-search/?q={0}&bc=25&bn=y&bh=A&order=right&pool=A&filter=y&search_type=&rows=100&de_search=Search&page={1}"+domtoolLastPageIndicator = ">>"+domtoolIncrement = 100++# Namedroppers.org:+# Downside is that a maximum of 500 results are returned+namedropUrlLeft = "http://www.namedroppers.org/b/q?p={1}&k={0}&min=1&max=63&order=0&display=0&first=1&adv=1&com=1&net=1&org=1&edu=1&biz=1&us=1&info=1&name=1"+namedropUrlRight = "http://www.namedroppers.org/b/q?p={1}&k={0}&min=1&max=63&order=0&display=0&last=1&adv=1&com=1&net=1&org=1&edu=1&biz=1&us=1&info=1&name=1"+namedropLastPageIndicator = ">>"++# Whois.com:+# Downside is that this doesn't allow startswith/endswith searching+whoisUrlFirst = "http://www.whois.net/domain-keyword-search/{0}"+whoisUrlN = "http://www.whois.net/domain-keyword-search/{0}/{1}"+whoisLastPageIndicator = "Next >"+whoisIncrement = 16++# SpiderFoot standard lib (must be initialized in __init__)+sf = None++class sfp_similar(SpiderFootPlugin):+ # Default options+ opts = {+ '_debug': True,+ '_debugfilter': '',+ # Domaintools will 403 you without a browser-like useragent+ '_useragent': 'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0',+ 'source': 'ALL', # whois, domaintools, namedroppers or ALL+ 'method': 'left,right', # left and/or right (doesn't apply to whois)+ 'activeonly': True # Only report domains that have content (try to fetch the page)+ }++ # Internal results tracking+ results = list()++ # URL this instance is working on+ seedUrl = None+ baseDomain = None # calculated from the URL in __init__++ def __init__(self, url, userOpts=dict()):+ global sf+ self.seedUrl = url++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # For error reporting, debug, etc.+ sf = SpiderFoot(self.opts)++ # Extract the 'meaningful' part of the FQDN from the URL+ self.baseDomain = sf.urlBaseDom(self.seedUrl)+ sf.debug('Base Domain: ' + self.baseDomain)++ def findDomains(self, keyword, content):+ matches = re.findall("([a-z0-9\-]*" + keyword + "[a-z0-9\-]*\.[a-z]+)", content)++ return matches++ # What events is this module interested in for input+ def watchedEvents(self):+ return None++ # Fetch and loop through Whois.com results, updating our results data. Stop+ # once we've reached the end.+ def scrapeWhois(self, keyword):+ reachedEnd = False+ i = 0+ while not reachedEnd:+ if i == 0:+ # First iteration+ fetchPage = whoisUrlFirst.format(keyword)+ else:+ # Subsequent iterations have a different URL (in chunks of 16)+ fetchPage = whoisUrlN.format(keyword, i * whoisIncrement)++ whois = sf.fetchUrl(fetchPage)+ if whois['content'] == None:+ return None++ # Extract the similar domains out of the whois content+ freshResults = self.findDomains(keyword, whois['content'])+ for result in freshResults:+ if result in self.results:+ continue++ self.storeResult(fetchPage, result)++ if not whoisLastPageIndicator in whois['content']:+ reachedEnd = True+ else:+ time.sleep(random.randint(1, 10))++ i += 1++ def scrapeDomaintools(self, keyword, position):+ reachedEnd = False+ i = 1 # Using 0 will cause the first page to appear twice+ while not reachedEnd:+ if position == "LEFT":+ fetchPage = domtoolUrlLeft.format(keyword, i)+ else:+ fetchPage = domtoolUrlRight.format(keyword, i)++ domtool = sf.fetchUrl(fetchPage)+ if domtool['content'] == None:+ return None++ # Extract the similar domains out of the domain tools content+ freshResults = self.findDomains(keyword, domtool['content'])+ for result in freshResults:+ if result in self.results:+ continue+ # Images for the domain get picked up by the regexp+ if '.jpg' in result:+ continue++ self.storeResult(fetchPage, result)++ if not domtoolLastPageIndicator in domtool['content']:+ reachedEnd = True+ else:+ time.sleep(random.randint(1, 10))++ i += 1++ def scrapeNamedroppers(self, keyword, position):+ reachedEnd = False+ i = 1 # Using 0 will cause the first page to appear twice+ while not reachedEnd:+ if position == "LEFT":+ fetchPage = namedropUrlLeft.format(keyword, i)+ else:+ fetchPage = namedropUrlRight.format(keyword, i)++ namedrop = sf.fetchUrl(fetchPage)+ if namedrop['content'] == None:+ return None++ # Extract the similar domains out of the namedropper content+ freshResults = self.findDomains(keyword, namedrop['content'])+ for result in freshResults:+ if result in self.results:+ continue++ self.storeResult(fetchPage, result)++ if not namedropLastPageIndicator in namedrop['content']:+ reachedEnd = True+ else:+ time.sleep(random.randint(1, 10))++ i += 1++ # Store the result internally and notify listening modules+ def storeResult(self, source, result):+ sf.debug("Found a similar domain: " + result)+ self.results.append(result)++ # Inform listening modules+ if self.opts['activeonly']:+ pageContent = sf.fetchUrl('http://' + result)+ if pageContent['content'] != None:+ self.notifyListeners("SIMILARDOMAIN", source, result)+ else:+ self.notifyListeners("SIMILARDOMAIN", source, result)+++ # Search for similar sounding domains+ def start(self):+ keyword = sf.urlKeyword(self.seedUrl)+ sf.debug("Keyword extracted from " + self.seedUrl + ": " + keyword)++ if "whois" in self.opts['source'] or "ALL" in self.opts['source']:+ self.scrapeWhois(keyword)++ if "domtools" in self.opts['source'] or "ALL" in self.opts['source']:+ if "left" in self.opts['method']:+ self.scrapeDomaintools(keyword, "LEFT")+ if "right" in self.opts['method']:+ self.scrapeDomaintools(keyword, "RIGHT")++ if "namedroppers" in self.opts['source'] or "ALL" in self.opts['source']:+ if "left" in self.opts['method']:+ self.scrapeNamedroppers(keyword, "LEFT")+ if "right" in self.opts['method']:+ self.scrapeNamedroppers(keyword, "RIGHT")++ return None++# End of sfp_similar class++if __name__ == '__main__':+ if len(sys.argv) < 2:+ print "You must supply a URL as a starting point."+ exit(-1)++ sfp = sfp_similar(sys.argv[1])+ sfp.start()diff --git a/modules/sfp_spider.py b/modules/sfp_spider.pynew file mode 100644index 00000000..74714ef0--- /dev/null+++ b/modules/sfp_spider.py@@ -0,0 +1,247 @@+#-------------------------------------------------------------------------------+# Name: sfp_spider+# Purpose: SpiderFoot plug-in for spidering sites and returning meta data+# for other plug-ins to consume.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 25/03/2012+# Copyright: (c) Steve Micallef 2012+# Licence: GPL+#-------------------------------------------------------------------------------++import sys+import re+import time+from sflib import SpiderFoot, SpiderFootPlugin++# SpiderFoot standard lib (must be initialized in __init__)+sf = None++class sfp_spider(SpiderFootPlugin):+ # Default options+ opts = {+ # These must always be set+ '_debug': True,+ '_debugfilter': '',+ # options specific to this module+ 'robotsonly': False, # only follow links specified by robots.txt+ 'pause': 0, # number of seconds to pause between fetches+ 'maxpages': 100, # max number of pages to fetch+ 'maxlevels': 10, # max number of levels to traverse within a site+ 'filterfiles': ['png','gif','jpg','jpeg','tiff', 'tif', 'js', 'css',+ 'pdf','tif','ico','flv'], # Extensions to not fetch+ '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?+ }++ # If using robots.txt, this will get populated with filter rules+ robotsRules = dict()++ # URL this instance is working on+ seedUrl = None+ baseDomain = None # calculated from the URL in __init__++ # Results of spidering. This is a dictionary with the URL as the key, and+ # each value is again a dictionary of the following key=value pairs:+ # source: the link where the link was found+ # original: what the link looked like in the content it was found in+ # fetched: has the content been fetched (True/False)+ # >> Not all of these will be populated at the same time <<+ results = dict()++ def __init__(self, url, userOpts=dict()):+ global sf+ self.seedUrl = url++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # For error reporting, debug, etc.+ sf = SpiderFoot(self.opts)++ if '://' not in self.seedUrl:+ sf.fatal("Please specify a full URL starting point, prefixed with http:// or https://")++ if re.match('.*\d+\.\d+\.\d+\.\d+.*', self.seedUrl):+ sf.fatal("Need a named URL to start with, not an IP.")++ # Extract the 'meaningful' part of the FQDN from the URL+ self.baseDomain = sf.urlBaseDom(self.seedUrl)+ sf.debug('Base Domain: ' + self.baseDomain)++ # Are we respecting robots.txt?+ if self.opts['robotsonly']:+ robotsTxt = sf.fetchUrl(sf.urlBaseUrl(self.seedUrl) + '/robots.txt').read()+ if robotsTxt['content'] != None:+ sf.debug('robots.txt contents: ' + robotsTxt['content'])+ self.robotsRules = sf.parseRobotsTxt(robotsTxt['content'])++ # This module listens to no events+ def watchedEvents(self):+ return None++ # Add a set of results to the results dictionary+ def storeResult(self, url, source=None, original=None, httpresult=None):+ stored = ''++ # Store in memory for use within this module and notify listeners+ if not url in self.results.keys():+ self.results[url] = dict()++ if source != None:+ self.results[url]['source'] = source+ self.notifyListeners("URL", source, url)+ stored += 's'++ if original != None:+ self.results[url]['original'] = original+ stored += 'o'++ if httpresult != None:+ if httpresult.has_key('content'):+ self.notifyListeners("WEBCONTENT", url, httpresult['content'])+ self.results[url]['fetched'] = True++ if httpresult.has_key('headers') and httpresult['headers'] != None:+ if httpresult['headers'].has_key('Server'):+ sf.debug("Notifying for websvr: " + url)+ self.notifyListeners("WEBSERVER_BANNER", url, httpresult['headers']['Server'])+ stored += 'h'++ # Heavy debug+ #sf.debug("Results stored for " + url + ": " + str(self.results[url]))+ # Basic debug+ sf.debug('stored result (elements:' + str(stored) + '): ' + url)++ # Eventually store to a database..+ return None++ # Fetch data from a URL and obtain all links that should be followed+ def processUrl(self, url):+ # Fetch the contents of the supplied URL (object returned)+ fetched = sf.fetchUrl(url)+ if fetched['realurl'] != None and fetched['realurl'] != url:+ sf.debug("Redirect of " + url + " to " + fetched['realurl'])+ # Store the content for the redirect so that it isn't fetched again+ self.storeResult(url, None, None, fetched)+ url = fetched['realurl'] # override the URL if we had a redirect++ # Store the content just received+ self.storeResult(url, None, None, fetched)++ # Extract links from the content+ links = sf.parseLinks(url, fetched['content'])++ if links == None or len(links) == 0:+ sf.debug("No links found at " + url)+ return None++ #sf.debug('Links found from parsing: ' + str(links))+ return links++ # Clear out links that we don't want to follow+ def cleanLinks(self, links):+ returnLinks = dict()++ for link in links.keys():+ # Optionally skip external sites+ if self.opts['noexternal'] and self.baseDomain != sf.urlBaseDom(link):+ sf.debug('Ignoring external site: ' + link)+ continue++ # Optionally skip sub-domain sites+ if self.opts['nosubs'] and sf.urlBaseUrl(self.seedUrl) not in link:+ sf.debug("Ignoring subdomain: " + link)+ continue++ # Optionally skip user directories+ if self.opts['filterusers'] and '/~' in link:+ sf.debug("Ignoring user folder: " + link)+ continue++ # If we are respecting robots.txt, filter those out too+ checkRobots = lambda blocked: str.lower(blocked) in str.lower(link) or blocked == '*'+ if self.opts['robotsonly'] and filter(checkRobots, self.robotsRules):+ sf.debug("Ignoring page found in robots.txt: " + link)+ continue++ # Filter out certain file types (if user chooses to)+ checkExts = lambda ext: '.' + str.lower(ext) in str.lower(link)+ if filter(checkExts, self.opts['filterfiles']):+ sf.debug('Ignoring filtered extension: ' + link)+ continue++ # All tests passed, add link to be spidered+ sf.debug("Adding URL for spidering: " + link)+ returnLinks[link] = links[link]++ return returnLinks++ # Spidering is performed here+ def start(self):+ # ~*~ Start spidering! ~*~+ # First iteration we are starting with links found on the start page+ # Iterations after that are based on links found on those pages,+ # and so on..+ keepSpidering = True+ links = self.processUrl(self.seedUrl) # fetch first page+ totalFetched = 0+ levelsTraversed = 0+ nextLinks = dict()++ while keepSpidering:+ # Gets hit in the second and subsequent iterations when more links+ # are found+ if len(nextLinks) > 0:+ links = dict()++ # Fetch content from the new links+ for link in nextLinks.keys():+ # Always skip links we've already fetched+ if (link in self.results.keys() and self.results[link].has_key('fetched')):+ if self.results[link]['fetched']:+ continue++ sf.debug("Fetching fresh content from: " + link)+ time.sleep(self.opts['pause'])+ freshLinks = self.processUrl(link)+ if freshLinks != None:+ links.update(freshLinks)++ totalFetched += 1+ if totalFetched >= self.opts['maxpages']:+ sf.debug("Maximum number of pages (" + str(self.opts['maxpages']) + ") reached.")+ keepSpidering = False+ break++ # Clear out the rubbish/ignored links from our list of links+ nextLinks = self.cleanLinks(links)++ # Record the result, for all links (not just those fetched)+ for link in links.keys():+ self.storeResult(link, links[link]['source'], links[link]['original'])++ # We've scanned through another layer of the site+ levelsTraversed += 1+ sf.debug("Now at traversal level: " + str(levelsTraversed))+ if levelsTraversed >= self.opts['maxlevels']:+ sf.debug("Maximum number of levels (" + str(self.opts['maxlevels']) + ") reached.")+ keepSpidering = False++ # We've reached the end of our journey..+ if len(nextLinks) == 0:+ keepSpidering = False++ return+# End of sfp_spider class++if __name__ == '__main__':+ if len(sys.argv) < 2:+ print "You must specify a URL to start spidering from."+ exit(-1)++ spider = sfp_spider(sys.argv[1])+ spider.start()+diff --git a/modules/sfp_stor_print.py b/modules/sfp_stor_print.pynew file mode 100644index 00000000..9f1edd8e--- /dev/null+++ b/modules/sfp_stor_print.py@@ -0,0 +1,64 @@+#-------------------------------------------------------------------------------+# Name: sfp_stor_print+# Purpose: SpiderFoot plug-in for 'storing' events (by printing them to+# the screen. This is used for debugging.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 06/04/2012+# Copyright: (c) Steve Micallef 2012+# Licence: GPL+#-------------------------------------------------------------------------------++import sys+import re+from sflib import SpiderFoot, SpiderFootPlugin++# SpiderFoot standard lib (must be initialized in __init__)+sf = None++class sfp_stor_print(SpiderFootPlugin):+ # Default options+ opts = {+ # These must always be set+ '_debug': True,+ '_debugfilter': '',+ 'datasize': 100 # Number of characters to print from event data+ }++ # URL this instance is working on+ seedUrl = None++ def __init__(self, url, userOpts=dict()):+ global sf+ self.seedUrl = url++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # For error reporting, debug, etc.+ sf = SpiderFoot(self.opts)++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["*"]++ # Handle events sent to this module+ def handleEvent(self, srcModuleName, eventName, eventSource, eventData):+ sf.debug("RESULT:")+ sf.debug("\tSource: " + srcModuleName)+ sf.debug("\tEvent: " + eventName)+ 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)++ return None++# End of sfp_stor_print class++if __name__ == '__main__':+ print "This module cannot be run stand-alone."+ exit(-1)diff --git a/modules/sfp_subdomain.py b/modules/sfp_subdomain.pynew file mode 100644index 00000000..737a39ee--- /dev/null+++ b/modules/sfp_subdomain.py@@ -0,0 +1,69 @@+#-------------------------------------------------------------------------------+# Name: sfp_subdomain+# Purpose: SpiderFoot plug-in for scanning retreived content by other+# modules (such as sfp_spider) and identifying sub-domains+#+# Author: Steve Micallef <[email protected]>+#+# Created: 06/04/2012+# Copyright: (c) Steve Micallef 2012+# Licence: GPL+#-------------------------------------------------------------------------------++import sys+import re+from sflib import SpiderFoot, SpiderFootPlugin++# SpiderFoot standard lib (must be initialized in __init__)+sf = None++class sfp_subdomain(SpiderFootPlugin):+ # Default options+ opts = {+ # These must always be set+ '_debug': True,+ '_debugfilter': ''+ }++ # URL this instance is working on+ seedUrl = None+ baseDomain = None # calculated from the URL in __init__++ def __init__(self, url, userOpts=dict()):+ global sf+ self.seedUrl = url++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # For error reporting, debug, etc.+ sf = SpiderFoot(self.opts)++ # Extract the 'meaningful' part of the FQDN from the URL+ self.baseDomain = sf.urlBaseDom(self.seedUrl)+ sf.debug('Base Domain: ' + self.baseDomain)++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["WEBCONTENT", "URL"]++ # Handle events sent to this module+ def handleEvent(self, srcModuleName, eventName, eventSource, eventData):+ sf.debug("Received event, " + eventName + ", from " + srcModuleName)++ matches = re.findall("([a-zA-Z0-9\-\.]+)\." + self.baseDomain, eventData,+ re.IGNORECASE)+ if matches == None:+ return++ for match in matches:+ sf.debug("Found sub-domain: " + match)+ self.notifyListeners("SUBDOMAIN", eventSource, match)++ return None++# End of sfp_subdomain class++if __name__ == '__main__':+ print "This module cannot be run stand-alone."+ exit(-1)diff --git a/modules/sfp_websvr.py b/modules/sfp_websvr.pynew file mode 100644index 00000000..7f7b16ed--- /dev/null+++ b/modules/sfp_websvr.py@@ -0,0 +1,66 @@+#-------------------------------------------------------------------------------+# Name: sfp_websvr+# Purpose: SpiderFoot plug-in for scanning retreived content by other+# modules (such as sfp_spider) and identifying web servers used+#+# Author: Steve Micallef <[email protected]>+#+# Created: 06/04/2012+# Copyright: (c) Steve Micallef 2012+# Licence: GPL+#-------------------------------------------------------------------------------++import sys+import re+from sflib import SpiderFoot, SpiderFootPlugin++# SpiderFoot standard lib (must be initialized in __init__)+sf = None++class sfp_websvr(SpiderFootPlugin):+ # Default options+ opts = {+ # These must always be set+ '_debug': True,+ '_debugfilter': ''+ }++ # URL this instance is working on+ seedUrl = None+ baseDomain = None # calculated from the URL in __init__++ def __init__(self, url, userOpts=dict()):+ global sf+ self.seedUrl = url++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # For error reporting, debug, etc.+ sf = SpiderFoot(self.opts)++ # Extract the 'meaningful' part of the FQDN from the URL+ self.baseDomain = sf.urlBaseDom(self.seedUrl)+ sf.debug('Base Domain: ' + self.baseDomain)++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["WEBSERVER_BANNER"]++ # Handle events sent to this module+ def handleEvent(self, srcModuleName, eventName, eventSource, eventData):+ sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ # Could apply some smarts here, for instance looking for certain+ # banners and therefore classifying them further (type and version,+ # possibly OS. This could also trigger additional tests, such as 404s+ # and other errors to see what the header looks like.+ if sf.urlBaseDom(eventSource) == self.baseDomain:+ sf.debug("Found web server: " + eventData + " (" + eventSource + ")")++ return None++# End of sfp_websvr class++if __name__ == '__main__':+ print "This module cannot be run stand-alone."+ exit(-1)diff --git a/modules/sfp_xref.py b/modules/sfp_xref.pynew file mode 100644index 00000000..d3c7a99f--- /dev/null+++ b/modules/sfp_xref.py@@ -0,0 +1,93 @@+#-------------------------------------------------------------------------------+# Name: sfp_xref+# Purpose: SpiderFoot plug-in for scanning links identified from the+# spidering process, and for external links, fetching them to+# see if those sites link back to the original site, indicating a+# potential relationship between the external sites.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 06/04/2012+# Copyright: (c) Steve Micallef 2012+# Licence: GPL+#-------------------------------------------------------------------------------++import sys+import re+from sflib import SpiderFoot, SpiderFootPlugin++# SpiderFoot standard lib (must be initialized in __init__)+sf = None++class sfp_xref(SpiderFootPlugin):+ # Default options+ opts = {+ # These must always be set+ '_debug': True,+ '_debugfilter': '',+ 'checkbase': True # Also check the base URL for a relationship if+ # the link contains no xref+ }++ # Internal results tracking+ results = dict()++ # URL this instance is working on+ seedUrl = None+ baseDomain = None # calculated from the URL in __init__++ def __init__(self, url, userOpts=dict()):+ global sf+ self.seedUrl = url++ for opt in userOpts.keys():+ self.opts[opt] = userOpts[opt]++ # For error reporting, debug, etc.+ sf = SpiderFoot(self.opts)++ # Extract the 'meaningful' part of the FQDN from the URL+ self.baseDomain = sf.urlBaseDom(self.seedUrl)+ sf.debug('Base Domain: ' + self.baseDomain)++ # What events is this module interested in for input+ def watchedEvents(self):+ return ["URL", "SIMILARDOMAIN"]++ # Handle events sent to this module+ def handleEvent(self, srcModuleName, eventName, eventSource, eventData):+ sf.debug("Received event, " + eventName + ", from " + srcModuleName)+ # In this module's case, eventData will be the URL++ # We are only interested in external sites for the xref+ if sf.urlBaseDom(eventData) == self.baseDomain:+ sf.debug("Ignoring " + eventData + " as not external")+ return None++ res = sf.fetchUrl(eventData)+ if res['content'] == None:+ sf.debug("Ignoring " + eventData + " as no data returned")+ return None++ matches = re.findall("(" + self.baseDomain + ")", res['content'],+ re.IGNORECASE)+ if matches != None:+ for match in matches:+ if results.has_key(eventData):+ continue++ results[eventData] = True+ sf.debug("Found affiliate: " + eventData)+ self.notifyListeners("AFFILIATE", eventSource, eventData)+ else:+ # As no xref was found on the main link, check the base url+ if this.opts['checkbase']:+ res = sf.fetchUrl(sf.urlBaseUrl(eventData))++ return None++# End of sfp_xref class++if __name__ == '__main__':+ print "This module cannot be run stand-alone."+ exit(-1)diff --git a/sf.py b/sf.pynew file mode 100644index 00000000..5403279a--- /dev/null+++ b/sf.py@@ -0,0 +1,92 @@+#-------------------------------------------------------------------------------+# Name: sf+# Purpose: Main wrapper for calling all SpiderFoot modules+#+# Author: Steve Micallef <[email protected]>+#+# Created: 03/04/2012+# Copyright: (c) Steve Micallef 2012+# Licence: GPL+#-------------------------------------------------------------------------------++import imp++# URL to start from. This will be set either by the CLI or UI+seedUrl = 'http://www.telstra.com.au'++# These are all hard-coded for now, but will eventually+# be set by the UI or CLI+# 'Global' configuration options+# These can be overriden on a per-module basis+sfConfig = {+ '_debug': True, # Debug+ '_debugfilter': '', # Filter out debug strings+ '_blocknotif': False, # Block notifications+ '_useragent': 'SpiderFoot/2.0', # User-Agent to use for HTTP requests+ '_fetchtimeout': 1, # number of seconds before giving up on a fetch+}++# Each module will have defaults configured. This will override defaults.+# This would typically be set in the UI/CLI.+moduleConfig = {+ 'sfp_spider': {+ 'enabled': True,+ 'pause': 1+ },+ 'sfp_mail': {+ 'enabled': True+ },+ 'sfp_websvr': {+ 'enabled': True+ },+ 'sfp_stor_print': {+ 'enabled': True+ },+ 'sfp_subdomain': {+ 'enabled': True+ },+ 'sfp_xref': {+ 'enabled': True+ },+ 'sfp_similar': {+ 'enabled': False+ }+}++def main(url):+ moduleInstances = dict()++ # Loop through all modules that are enabled in moduleConfig+ for modName in moduleConfig.keys():+ if not moduleConfig[modName]['enabled']:+ print "Skipping module " + modName + " as not enabled."+ continue++ # Load the plug-in module+ mod = __import__('modules.' + modName, globals(), locals(), [modName])++ # Build up config to consist of general and module-specific config+ # to override defaults within the module itself+ modConfig = sfConfig+ modConfig.update(moduleConfig[modName])++ # Instantiate the module+ modInstance = getattr(mod, modName)(url, modConfig)+ # Keep track of the module object so it can be referenced later+ moduleInstances[modName] = modInstance++ # Register listener modules and then start all modules sequentially+ for module in moduleInstances.values():+ for listenerModule in moduleInstances.values():+ # Careful not to register twice or you will get duplicate events+ if listenerModule in module._listenerModules:+ continue+ if listenerModule != module and listenerModule.watchedEvents() != None:+ module.registerListener(listenerModule)++ for module in moduleInstances.values():+ # If the module extends the Thread class, then start it as a thread+ module.start()++if __name__ == '__main__':+ main(seedUrl)diff --git a/sflib.py b/sflib.pynew file mode 100644index 00000000..40cbb4aa--- /dev/null+++ b/sflib.py@@ -0,0 +1,318 @@+#-------------------------------------------------------------------------------+# Name: sflib+# Purpose: Common functions used by SpiderFoot modules.+# Also defines the SpiderFootPlugin abstract class for modules.+#+# Author: Steve Micallef <[email protected]>+#+# Created: 26/03/2012+# Copyright: (c) Steve Micallef 2012+# Licence: GPL+#-------------------------------------------------------------------------------++import sys+import re+import urllib2+import inspect++class SpiderFoot:+ # 'options' is a dictionary of options which changes the behaviour+ # of how certain things are done in this module+ # - debug: enable debugging+ # - debugfilter: filter debug messages for a string+ # 'handle' will be supplied if the module is being used within the+ # SpiderFoot GUI, in which case all feedback should be fed back+ def __init__(self, options, handle=None):+ self.handle = handle+ self.opts = options++ # initialize database handler for storing results+ return++ def error(self, error):+ if self.handle == None:+ print '[Error] ' + error+ else:+ #self.handle.error(error)+ print 'should not be here'+ return++ def fatal(self, error):+ if self.handle == None:+ print '[Fatal] ' + error+ exit(-1)+ else:+ #self.handle.error(error)+ print 'should not be here'+ return++ def debug(self, message):+ if self.opts['_debug'] == False:+ return++ if self.handle == None:+ frm = inspect.stack()[1]+ mod = inspect.getmodule(frm[0])++ msg = '[d:' + mod.__name__ + '] ' + message+ if self.opts['_debugfilter'] != None and self.opts['_debugfilter'] not in msg:+ return++ print msg+ else:+ #self.handle.debug(message)+ print 'should not be here'+ return++ # Turn a relative path into an absolute path+ def urlRelativeToAbsolute(self, url):+ finalBits = list()++ if '..' not in url:+ return url++ bits = url.split('/')++ for chunk in bits:+ if chunk == '..':+ # Don't pop the last item off if we're at the top+ if len(finalBits) <= 1:+ continue++ # Don't pop the last item off if the first bits are not the path+ if '://' in url and len(finalBits) <= 3:+ continue++ finalBits.pop()+ continue++ finalBits.append(chunk)++ self.debug('xfrmed rel to abs path: ' + url + ' to ' + '/'.join(finalBits))+ return '/'.join(finalBits)++ # Extract the top level directory from a URL+ def urlBaseDir(self, url):++ bits = url.split('/')++ # For cases like 'www.somesite.com'+ if len(bits) == 0:+ self.debug('base dir of ' + url + ' not identified, using URL as base.')+ return url + '/'++ # For cases like 'http://www.blah.com'+ if '://' in url and url.count('/') < 3:+ self.debug('base dir of ' + url + ' is: ' + url + '/')+ return url + '/'++ base = '/'.join(bits[:-1])+ self.debug('base dir of ' + url + ' is: ' + base + '/')+ return base + '/'++ # Extract the scheme and domain from a URL+ def urlBaseUrl(self, url):++ if '://' in url:+ bits = re.match('(.*://.[^/]*)/.*', url)+ else:+ bits = re.match('(.[^/]*)/', url)++ if bits == None:+ return url++ self.debug('base url of ' + url + ' is: ' + bits.group(1))+ return bits.group(1)++ # Get the base domain from a URL+ def urlBaseDom(self, url):+ url = self.urlBaseUrl(url)+ basedomainBits = url.rsplit('.', 2)+ return basedomainBits[-2] + '.' + basedomainBits[-1]++ # Extract the keyword (the domain without the TLD or any subdomains)+ # from a URL+ def urlKeyword(self, url):+ base = self.urlBaseUrl(url)+ domain = self.urlBaseDom(base)+ return domain.split('.', 2)[0]++ # Parse the contents of robots.txt, returns a list of patterns+ # which should not be followed+ def parseRobotsTxt(self, robotsTxtData):+ returnArr = list()++ # We don't check the User-Agent rule yet.. probably should at some stage++ for line in robotsTxtData.splitlines():+ if line.startswith('Disallow:'):+ m = re.match('Disallow:\s*(.[^ #]*)', line)+ self.debug('robots.txt parsing found disallow: ' + m.group(1))+ returnArr.append(m.group(1))+ continue++ return returnArr++ # Find all URLs within the supplied content. This does not fetch any URLs!+ # A dictionary will be returned, where each link will have the keys+ # 'source': The URL where the link was obtained from+ # 'original': What the link looked like in the content it was obtained from+ # The key will be the *absolute* URL of the link obtained, so for example if+ # the link '/abc' was obtained from 'http://xyz.com', the key in the dict will+ # be 'http://xyz.com/abc' with the 'original' attribute set to '/abc'+ def parseLinks(self, url, data):+ returnLinks = dict()++ if data == None or len(data) == 0:+ self.debug('parseLinks() called with no data to parse')+ return None++ try:+ regRel = re.compile('(href|src|action|url)[:=][ \'\"]*(.[^\'\"<> ]*)',+ re.IGNORECASE)+ urlsRel = regRel.findall(data)+ except Exception as e:+ self.error("Error applying regex to " + data + ", continuing anyway.")+ return None++ # Loop through all the URLs/links found by the regex+ for linkTuple in urlsRel:+ # Remember the regex will return two vars (two groups captured)+ meta = linkTuple[0]+ link = linkTuple[1]++ # 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] == '+':+ self.debug('unlikely link: ' + link)+ continue++ # Filter in-page links+ if re.match('.*#.[^/]+', link):+ self.debug('in-page link: ' + link)+ continue++ # Ignore mail links+ if 'mailto:' in link:+ self.debug("Ignoring mail link: " + link)+ continue++ # Capture the absolute link:+ # If the link contains ://, it is already an absolute link+ if '://' in link:+ absLink = link++ # If the link starts with a /, the absolute link is off the base URL+ if link.startswith('/'):+ absLink = self.urlBaseUrl(url) + link++ # Otherwise, it's a flat link within the current directory+ if '://' not in link and not link.startswith('/'):+ absLink = self.urlBaseDir(url) + link++ # Translate any relative pathing (../)+ absLink = self.urlRelativeToAbsolute(absLink)+ returnLinks[absLink] = {'source': url, 'original': link}++ return returnLinks++ # Fetch a URL, return the response object+ def fetchUrl(self, url, fatal=False):+ result = {+ 'code': None,+ 'status': None,+ 'content': None,+ 'headers': None,+ 'realurl': None+ }++ if url == None:+ self.error('Blank URL supplied to be fetched')+ return result++ try:+ header = dict()+ if self.opts.has_key('_useragent'):+ header['User-Agent'] = self.opts['_useragent']+ if not self.opts.has_key('_fetchtimeout'):+ self.opts['_fetchtimeout'] = 30+ req = urllib2.Request(url, None, header)+ self.debug("Fetching " + url)+ fullPage = urllib2.urlopen(req, None, self.opts['_fetchtimeout'])++ # Prepare result to return+ result['content'] = fullPage.read()+ result['headers'] = fullPage.info()+ result['realurl'] = fullPage.geturl()+ result['status'] = 'OK'+ except urllib2.HTTPError as h:+ self.debug("HTTP code " + str(h.code) + " encountered for " + url)+ # Capture the HTTP error code+ result['code'] = h.code+ if fatal:+ self.fatal('URL could not be fetched (' + h.code + ')')+ except urllib2.URLError as e:+ self.debug("Error fetching " + url)+ result['status'] = str(e)+ if fatal:+ self.fatal('URL could not be fetched (' + str(e) + ')')+ except Exception as x:+ self.error("Unexpected exception occurred: " + str(x))+ result['status'] = str(x)+ if fatal:+ self.fatal('URL could not be fetched (' + str(x) + ')')++ return result++class SpiderFootPlugin(object):+ # Modules that will be notified when this module produces events+ _listenerModules = list()++ # Will always be overriden by the implementer.+ def __init__(self, url, userOpts=dict()):+ pass++ # Listener modules which will get notified once we have data for them to+ # work with.+ def registerListener(self, listener):+ self._listenerModules.append(listener)++ # Call the handleEvent() method of every other plug-in listening for+ # events from this plug-in. Remember that those plug-ins will be called+ # within the same execution context of this thread, not on their own.+ def notifyListeners(self, eventName, eventSource, eventData):+ if self.opts.has_key('blocknotif') and self.opts['_blocknotif']:+ return None++ if eventData == None or len(eventData) == 0:+ return None++ for listener in self._listenerModules:+ if eventName not in listener.watchedEvents() and '*' not in listener.watchedEvents():+ continue+ #print "Notifying " + eventName + " to " + listener.__module__+ listener.handleEvent(self.__module__, eventName, eventSource, eventData)++ # Return a list of the default configuration options for the module.+ def defaultOpts(self):+ return self.opts++ # What events is this module interested in for input. The format is a list+ # of event types that are applied to event types that this module wants to+ # be notified of, or * if it wants everything.+ # Will usually be overriden by the implementer, unless it is interested+ # in all events (default behavior).+ def watchedEvents(self):+ return [ '*' ]++ # Handle events to this module+ # Will usually be overriden by the implementer, unless it doesn't handle+ # any events.+ def handleEvent(self, srcModuleName, eventName, eventSource, eventData):+ return None++ # Kick off the work (for some modules nothing will happen here, but instead+ # the work will start from the handleEvent() method.+ # Will usually be overriden by the implementer.+ def start(self):+ return None