SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.
Python attacksurfacecticybersecurityfootprintinghackinginformation-gatheringinformation-securityinfosecintelligence-gatheringosintosint-frameworkosint-reconnaissanceosint-toolpentestingpythonreconsecurity-toolsthreat-intelligencethreatintel
sflib: Add docstrings and remove unused comments
Brendan Coles99eaa7dad185
diff --git a/sflib.py b/sflib.pyindex c720c5b1..09fe55a9 100644--- a/sflib.py+++ b/sflib.py@@ -72,8 +72,7 @@ class SpiderFoot:# This is ugly but we don't want any fetches to fail - we expect# to encounter unverified SSL certs!- if sys.version_info >= (2, 7, 9):- ssl._create_default_https_context = ssl._create_unverified_context+ ssl._create_default_https_context = ssl._create_unverified_contextif self.opts.get('_dnsserver', "") != "":res = dns.resolver.Resolver()@@ -376,11 +375,6 @@ class SpiderFoot:str: scan instance unique GUID"""- # hashStr = hashlib.sha256(- # scanName +- # str(time.time() * 1000) +- # str(random.SystemRandom().randint(100000, 999999))- # ).hexdigest()return str(uuid.uuid4()).split("-")[0].upper()def _dblog(self, level, message, component=None):@@ -395,8 +389,6 @@ class SpiderFoot:bool: scan event logged successfully"""- #print(str(self.GUID) + ":" + str(level) + ":" + str(message) + ":" + str(component))-if not self.dbh:self.error("No database handle. Could not log event to database: %s" % message, True)return False@@ -574,10 +566,6 @@ class SpiderFoot:s = str(string)return hashlib.sha256(s.encode('raw_unicode_escape')).hexdigest()- #- # Caching- #-def cachePath(self):"""Returns the file system location of the cacha data files.@@ -590,8 +578,14 @@ class SpiderFoot:os.mkdir(path)return path- # Store data to the cachedef cachePut(self, label, data):+ """Store data to the cache++ Args:+ label (str): TBD+ data (str): TBD+ """+pathLabel = hashlib.sha224(label.encode('utf-8')).hexdigest()cacheFile = self.cachePath() + "/" + pathLabelwith io.open(cacheFile, "w", encoding="utf-8", errors="ignore") as fp:@@ -607,8 +601,17 @@ class SpiderFoot:else:fp.write(data)- # Retreive data from the cachedef cacheGet(self, label, timeoutHrs):+ """Retreive data from the cache++ Args:+ label (str): TBD+ timeoutHrs (str): TBD++ Returns:+ str: cached data+ """+if label is None:return None@@ -626,13 +629,9 @@ class SpiderFoot:return fileContentselse:return None- except BaseException as e:+ except BaseException:return None- #- # Configuration process- #-def configSerialize(self, opts, filterSystem=True):"""Convert a Python dictionary to something storable in the database.@@ -911,10 +910,6 @@ class SpiderFoot:return evtlist- #- # URL parsing functions- #-def urlRelativeToAbsolute(self, url):"""Turn a relative path into an absolute path@@ -951,7 +946,6 @@ class SpiderFoot:finalBits.append(chunk)- #self.debug('xfrmed rel to abs path: ' + url + ' to ' + '/'.join(finalBits))return '/'.join(finalBits)def urlBaseDir(self, url):@@ -972,16 +966,14 @@ class SpiderFoot:# 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 + '/'def urlBaseUrl(self, url):@@ -1008,7 +1000,6 @@ class SpiderFoot:if bits is None:return url.lower()- #self.debug('base url of ' + url + ' is: ' + bits.group(1))return bits.group(1).lower()def urlFQDN(self, url):@@ -1053,6 +1044,7 @@ class SpiderFoot:dom = self.hostDomain(domain.lower(), tldList)if not dom:return None+tld = '.'.join(dom.split('.')[1:])ret = domain.lower().replace('.' + tld, '')@@ -1197,7 +1189,7 @@ class SpiderFoot:return Trueelse:return False- except:+ except BaseException:return Falsedef normalizeDNS(self, res):@@ -1234,7 +1226,7 @@ class SpiderFoot:email (str): The email address to check.Returns:- bool+ bool: email is a valid email address"""if not isinstance(email, str):@@ -1243,11 +1235,9 @@ class SpiderFoot:if "@" not in email:return False- # Basic regex checkif not re.match(r'^([\%a-zA-Z\.0-9_\-\+]+@[a-zA-Z\.0-9\-]+\.[a-zA-Z\.0-9\-]+)$', email):return False- # Handle false positive matchesif len(email) < 5:return False@@ -1268,7 +1258,7 @@ class SpiderFoot:cmd (str): The command to checkReturns:- bool+ bool: command is "safe""""chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',@@ -1357,7 +1347,6 @@ class SpiderFoot:return {}def get_children(needle, haystack):- #print("called")ret = list()if needle not in list(haystack.keys()):@@ -1367,7 +1356,6 @@ class SpiderFoot:return Nonefor c in haystack[needle]:- #print("found child of " + needle + ": " + c)ret.append({"name": c, "children": get_children(c, haystack)})return ret@@ -1390,16 +1378,9 @@ class SpiderFoot:breakif root is None:- #print("*BUG*: Invalid structure - needs to go back to one root.")- final = {}- else:- final = {"name": root, "children": get_children(root, data)}-- return final+ return {}- #- # General helper functions to automate many common tasks between modules- #+ return {"name": root, "children": get_children(root, data)}def resolveHost(self, host):"""Return a normalised resolution of a hostname.@@ -1408,7 +1389,7 @@ class SpiderFoot:host (str): host to resolveReturns:- list+ list: IP addresses"""addrs = list()@@ -1570,6 +1551,11 @@ class SpiderFoot:Returns:list: list of patterns which should not be followed++ Todo:+ We don't check the User-Agent rule yet.. probably should at some stage++ fix whitespace parsing; ie, " " is not a valid disallowed path"""returnArr = list()@@ -1577,11 +1563,8 @@ class SpiderFoot:if not isinstance(robotsTxtData, str):return returnArr- # We don't check the User-Agent rule yet.. probably should at some stage-for line in robotsTxtData.splitlines():if line.lower().startswith('disallow:'):- # todo: fix whitespace parsing; ie, " " is not a valid disallowed pathm = re.match(r'disallow:\s*(.[^ #]*)', line, re.IGNORECASE)if m:self.debug('robots.txt parsing found disallow: ' + m.group(1))@@ -1757,13 +1740,11 @@ class SpiderFoot:countryCode = iban[0:2]if countryCode not in ibanCountryLengths.keys():- # Invalid IBAN due to country code not existing in dictionary- self.debug("Skipped invalid IBAN: %s" % iban)+ self.debug("Skipped invalid IBAN (invalid country code): %s" % iban)continueif len(iban) != ibanCountryLengths[countryCode]:- # Invalid IBAN due to length mismatch- self.debug("Skipped invalid IBAN: %s" % iban)+ self.debug("Skipped invalid IBAN (invalid length): %s" % iban)continue# Convert IBAN to integer format.@@ -1776,7 +1757,6 @@ class SpiderFoot:# Check IBAN integer mod 97 for remainderif int(iban_int) % 97 != 1:- # Invalid IBAN due to failed Mod 97 operationself.debug("Skipped invalid IBAN: %s" % iban)continue@@ -1923,14 +1903,23 @@ class SpiderFoot:# https://tools.ietf.org/html/rfc3986#section-3.3return re.findall(r"(https?://[a-zA-Z0-9-\.:]+/[\-\._~!\$&'\(\)\*\+\,\;=:@/a-zA-Z0-9]*)", html.unescape(content))- # 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, domains):+ """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'++ Args:+ url (str): TBD+ data: TBD+ domains: TBD+ """+returnLinks = dict()if data is None or len(data) == 0:@@ -1941,18 +1930,18 @@ class SpiderFoot:domains = [domains]tags = {- 'a': 'href',- 'img': 'src',- 'script': 'src',- 'link': 'href',- 'area': 'href',- 'base': 'href',- 'form': 'action'+ 'a': 'href',+ 'img': 'src',+ 'script': 'src',+ 'link': 'href',+ 'area': 'href',+ 'base': 'href',+ 'form': 'action'}try:proto = url.split(":")[0]- except BaseException as e:+ except BaseException:proto = "http"if proto == None:proto = "http"@@ -2071,7 +2060,6 @@ class SpiderFoot:}if url is None:- #self.debug("fetchUrl: No url")return Noneurl = url.strip()@@ -2136,6 +2124,7 @@ class SpiderFoot:verify=verify, timeout=timeout)size = int(hdr.headers.get('content-length', 0))newloc = hdr.headers.get('location', url).strip()+# Relative re-directif newloc.startswith("/") or newloc.startswith("../"):newloc = self.urlBaseUrl(url) + newloc@@ -2162,20 +2151,16 @@ class SpiderFoot:if size > sizeLimit:return result- if cookies is not None:- #req.add_header('cookie', cookies)- if not noLog:++ if not noLog:+ if cookies is None:+ self.info("Fetching: " + self.removeUrlCreds(url) + " [user-agent: " + \+ header['User-Agent'] + "] [timeout: " + str(timeout) + "]")+ else:self.info("Fetching (incl. cookies): " + self.removeUrlCreds(url) + \" [user-agent: " + header['User-Agent'] + "] [timeout: " + \str(timeout) + "]")- else:- if not noLog:- self.info("Fetching: " + self.removeUrlCreds(url) + " [user-agent: " + \- header['User-Agent'] + "] [timeout: " + str(timeout) + "]")- #- # MAKE THE REQUEST- #try:if postData:res = self.getSession().post(url, data=postData, headers=header, proxies=proxies,@@ -2251,10 +2236,14 @@ class SpiderFoot:" (" + self.removeUrlCreds(url) + "), took " + t + "s")return result- # Check if wildcard DNS is enabled by looking up a random hostnamedef checkDnsWildcard(self, target):+ """Check if wildcard DNS is enabled by looking up a random hostname++ Args:+ target (str): TBD+ """+if not target:- #self.debug("checkDnsWildcard: No target")return Falserandpool = 'bcdfghjklmnpqrstvwxyz3456789'@@ -2265,15 +2254,24 @@ class SpiderFoot:return True- # Request search results from the Google API. Will return a dict:- # {- # "urls": a list of urls that match the query string,- # "webSearchUrl": url for Google results page,- # }- # Options accepted:- # useragent: User-Agent string to use- # timeout: API call timeoutdef googleIterate(self, searchString, opts=dict()):+ """Request search results from the Google API.++ Will return a dict:+ {+ "urls": a list of urls that match the query string,+ "webSearchUrl": url for Google results page,+ }++ Options accepted:+ useragent: User-Agent string to use+ timeout: API call timeout++ Args:+ searchString (str) :TBD+ opts (dict): TBD+ """+endpoint = "https://www.googleapis.com/customsearch/v1?q={search_string}&".format(search_string=searchString.replace(" ", "%20"))@@ -2297,39 +2295,48 @@ class SpiderFoot:self.error("the key 'content' in the Google API response doesn't contain valid json.", exception=False)return None- if "items" in response_json:- # We attempt to make the URL look as authentically human as possible- params = {- "ie": "utf-8",- "oe": "utf-8",- "aq": "t",- "rls": "org.mozilla:en-US:official",- "client": "firefox-a",- }- search_url = "https://www.google.com/search?q={search_string}&{params}".format(- search_string=searchString.replace(" ", "%20"),- params=urllib.parse.urlencode(params)- )- results = {- "urls": [str(k['link']) for k in response_json['items']],- "webSearchUrl": search_url,- }- else:+ if "items" not in response_json:return None- return results+ # We attempt to make the URL look as authentically human as possible+ params = {+ "ie": "utf-8",+ "oe": "utf-8",+ "aq": "t",+ "rls": "org.mozilla:en-US:official",+ "client": "firefox-a",+ }+ search_url = "https://www.google.com/search?q={search_string}&{params}".format(+ search_string=searchString.replace(" ", "%20"),+ params=urllib.parse.urlencode(params)+ )+ results = {+ "urls": [str(k['link']) for k in response_json['items']],+ "webSearchUrl": search_url,+ }+ return results- # Request search results from the Bing API. Will return a dict:- # {- # "urls": a list of urls that match the query string,- # "webSearchUrl": url for bing results page,- # }- # Options accepted:- # count: number of search results to request from the API- # useragent: User-Agent string to use- # timeout: API call timeoutdef bingIterate(self, searchString, opts=dict()):+ """Request search results from the Bing API.++ Will return a dict:+ {+ "urls": a list of urls that match the query string,+ "webSearchUrl": url for bing results page,+ }++ Options accepted:+ count: number of search results to request from the API+ useragent: User-Agent string to use+ timeout: API call timeout++ Args:+ searchString (str): TBD+ opts (dict): TBD++ """+endpoint = "https://api.cognitive.microsoft.com/bing/v7.0/search?q={search_string}&".format(search_string=searchString.replace(" ", "%20"))@@ -2370,9 +2377,6 @@ class SpiderFoot:return results--# SpiderFoot plug-in module base class-#class SpiderFootPlugin(object):# Will be set to True by the controller if the user aborts scanning_stopScanning = False@@ -2525,7 +2529,6 @@ class SpiderFootPlugin(object):storeOnly = False # Under some conditions, only store and don't notifyif sfEvent.data is None or (type(sfEvent.data) is str and len(sfEvent.data) == 0):- #print("No data to send for " + eventName + " to " + listener.__module__)return Noneif self.checkForStop():@@ -2550,7 +2553,6 @@ class SpiderFootPlugin(object):if prevEvent.sourceEvent is not None:if prevEvent.sourceEvent.eventType == sfEvent.eventType and \prevEvent.sourceEvent.data.lower() == sfEvent.data.lower():- #print("Skipping notification of " + sfEvent.eventType + " / " + sfEvent.data)storeOnly = TruebreakprevEvent = prevEvent.sourceEvent@@ -2558,16 +2560,12 @@ class SpiderFootPlugin(object):self._listenerModules.sort(key=lambda m: m._priority)for listener in self._listenerModules:- #print(listener.__module__ + ": " + listener.watchedEvents().__str__())if eventName not in listener.watchedEvents() and '*' not in listener.watchedEvents():- #print(listener.__module__ + " not listening for " + eventName)continueif storeOnly and "__stor" not in listener.__module__:- #print("Storing only for " + sfEvent.eventType + " / " + sfEvent.data)continue- #print("Notifying " + eventName + " to " + listener.__module__)listener._currentEvent = sfEvent# Check if we've been asked to stop in the meantime, so that@@ -2575,7 +2573,6 @@ class SpiderFootPlugin(object):if self.checkForStop():return None- #print("EVENT: " + str(sfEvent))try:if type(sfEvent.data) == bytes:sfEvent.data = sfEvent.data.decode('utf-8', 'ignore')