SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.
Python attacksurfacecticybersecurityfootprintinghackinginformation-gatheringinformation-securityinfosecintelligence-gatheringosintosint-frameworkosint-reconnaissanceosint-toolpentestingpythonreconsecurity-toolsthreat-intelligencethreatintel
Bug fixes.
smicallefbca72ea90a0b
diff --git a/modules/sfp_bingsearch.py b/modules/sfp_bingsearch.pyindex ac619fc6..8e9c9359 100644--- a/modules/sfp_bingsearch.py+++ b/modules/sfp_bingsearch.py@@ -24,13 +24,15 @@ class sfp_bingsearch(SpiderFootPlugin):# Default optionsopts = {'fetchlinks': True, # Should we fetch links on the base domain?- 'pages': 20 # Number of bing results pages to iterate+ 'pages': 20, # Number of bing results pages to iterate+ 'cohostsamedomain': False}# 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.",+ 'cohostsamedomain': "Treat co-hosted sites on the same target domain as co-hosting?"}# Target@@ -87,7 +89,10 @@ class sfp_bingsearch(SpiderFootPlugin):for match in matches:sf.info("Found something on same IP: " + match)site = sf.urlFQDN(match)- if site not in myres:+ if site not in myres and site != eventData:+ if not self.opts['cohostsamedomain'] and site.endswith(self.baseDomain):+ sf.debug("Skipping " + site + " because it is on the same domain.")+ continueevt = SpiderFootEvent("CO_HOSTED_SITE", site, self.__name__, event)self.notifyListeners(evt)myres.append(site)diff --git a/modules/sfp_crossref.py b/modules/sfp_crossref.pyindex bd32ae89..97ac847d 100644--- a/modules/sfp_crossref.py+++ b/modules/sfp_crossref.py@@ -59,7 +59,7 @@ class sfp_crossref(SpiderFootPlugin):# What events is this module interested in for inputdef watchedEvents(self):- return ['LINKED_URL_EXTERNAL', 'SIMILARDOMAIN']+ return ['LINKED_URL_EXTERNAL', 'SIMILARDOMAIN', 'CO_HOSTED_SITE']# What events this module produces# This is to support the end user in selecting modules based on events@@ -77,8 +77,9 @@ class sfp_crossref(SpiderFootPlugin):sf.debug("Received event, " + eventName + ", from " + srcModuleName)- # The SIMILARDOMAIN event supplies domains, not URLs. Assume HTTP.- if eventName == 'SIMILARDOMAIN':+ # The SIMILARDOMAIN and CO_HOSTED_SITE events supply domains,+ # not URLs. Assume HTTP.+ if eventName in [ 'SIMILARDOMAIN', 'CO_HOSTED_SITE' ]:eventData = 'http://'+ eventData.lower()# We are only interested in external sites for the crossrefdiff --git a/modules/sfp_dns.py b/modules/sfp_dns.pyindex 56324544..9ae84ff7 100644--- a/modules/sfp_dns.py+++ b/modules/sfp_dns.py@@ -223,6 +223,13 @@ class sfp_dns(SpiderFootPlugin):count += 1name = sub + "." + self.baseDomain+ # Don't look up stuff twice+ if self.results.has_key(name):+ sf.debug("Skipping " + name + " as already resolved.")+ continue+ else:+ self.results[name] = True+try:lookup = Trueaddrs = socket.gethostbyname_ex(name)@@ -234,8 +241,12 @@ class sfp_dns(SpiderFootPlugin):for addr in addrs:if type(addr) == list:for host in addr:- self.processHost(host)+ if host not in self.results.keys():+ self.processHost(host)+ self.results[host] = Trueelse:- self.processHost(addr)+ if addr not in self.results.keys():+ self.processHost(addr)+ self.results[addr] = True# End of sfp_dns classdiff --git a/modules/sfp_ir.py b/modules/sfp_ir.pyindex ba42ee6e..83667abe 100644--- a/modules/sfp_ir.py+++ b/modules/sfp_ir.py@@ -29,6 +29,8 @@ class sfp_ir(SpiderFootPlugin):baseDomain = Noneresults = dict()currentEventSrc = None+ memCache = dict()+ nbreported = dict()def setup(self, sfc, target, userOpts=dict()):global sf@@ -36,6 +38,9 @@ class sfp_ir(SpiderFootPlugin):sf = sfcself.baseDomain = targetself.results = dict()+ self.memCache = dict()+ self.currentEventSrc = None+ self.nbreported = dict()for opt in userOpts.keys():self.opts[opt] = userOpts[opt]@@ -52,14 +57,16 @@ class sfp_ir(SpiderFootPlugin):# Fetch content and notify of the raw datadef fetchRir(self, url):- res = sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],- useragent=self.opts['_useragent'])-- if res['content'] != None:- evt = SpiderFootEvent("RAW_RIR_DATA", res['content'], self.__name__,- self.currentEventSrc)- self.notifyListeners(evt)-+ if self.memCache.has_key(url):+ res = self.memCache[url]+ else:+ res = sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])+ if res['content'] != None:+ self.memCache[url] = res+ evt = SpiderFootEvent("RAW_RIR_DATA", res['content'], self.__name__,+ self.currentEventSrc)+ self.notifyListeners(evt)return res# Get the netblock the IP resides in@@ -95,7 +102,10 @@ class sfp_ir(SpiderFootPlugin):try:j = json.loads(res['content'])- data = j["data"]["irr_records"][0]+ if len(j["data"]["irr_records"]) > 0:+ data = j["data"]["irr_records"][0]+ else:+ data = j["data"]["records"][0]except Exception as e:sf.debug("Error processing JSON response.")return None@@ -127,9 +137,14 @@ class sfp_ir(SpiderFootPlugin):for d in rec:if d["key"].lower().startswith("org") or \d["key"].lower().startswith("as") or \- d["key"].lower().startswith("descr"):- ownerinfo[d["key"]] = d["value"]-+ d["key"].lower().startswith("descr") and \+ d["value"].lower() not in [ "null", "none", "none specified" ]:+ if ownerinfo.has_key(d["key"]):+ ownerinfo[d["key"]].append(d["value"])+ else:+ ownerinfo[d["key"]] = [ d["value"] ]++ sf.debug("Returning ownerinfo: " + str(ownerinfo))return ownerinfo# Netblocks owned by an AS@@ -175,6 +190,36 @@ class sfp_ir(SpiderFootPlugin):return neighbours+ # Determine whether there is a textual link between the target+ # and the string supplied.+ def findName(self, string):+ # Simplest check to perform..+ if self.baseDomain in string:+ return True++ # Slightly more complex..+ keyword = sf.domainKeyword(self.baseDomain).lower()+ rx = [+ '^{0}[-_/\'\"\\\.,\?\! ]',+ '[-_/\'\"\\\.,\?\! ]{0}$',+ '[-_/\'\"\\\.,\?\! ]{0}[-_/\'\"\\\.,\?\! ]'+ ]++ # Mess with the keyword as a last resort..+ keywordList = list()+ # Create versions of the keyword, esp. if hyphens are involved.+ keywordList.append(keyword)+ keywordList.append(keyword.replace('-', ' '))+ keywordList.append(keyword.replace('-', '_'))+ keywordList.append(keyword.replace('-', ''))+ # More versions in future..+ for kw in keywordList:+ for r in rx:+ if re.match(r.format(kw), string, re.IGNORECASE) != None:+ return True++ return False+# Handle events sent to this moduledef handleEvent(self, event):eventName = event.eventType@@ -202,45 +247,53 @@ class sfp_ir(SpiderFootPlugin):return Noneownerinfo = self.asOwnerInfo(asn)- keyword = sf.domainKeyword(self.baseDomain).lower()owned = Falsefor k in ownerinfo.keys():- item = ownerinfo[k]- if self.baseDomain in item or "\"" + keyword in item \- or keyword +"\"" in item or keyword +"-" in item \- or "-"+keyword in item:- owned = True+ items = ownerinfo[k]+ for item in items:+ if self.findName(item.lower()):+ owned = Trueif owned:sf.info("Owned netblock found: " + prefix + "(" + asn + ")")evt = SpiderFootEvent("NETBLOCK", prefix, self.__name__, event)self.notifyListeners(evt)- evt = SpiderFootEvent("BGP_AS", asn, self.__name__, event)- self.notifyListeners(evt)-- # 2. Find all the netblocks owned by this AS- netblocks = self.asNetblocks(asn)- for netblock in netblocks:- evt = SpiderFootEvent("NETBLOCK", netblock, self.__name__, event)- self.notifyListeners(evt)-+ asevt = SpiderFootEvent("BGP_AS", asn, self.__name__, event)+ self.notifyListeners(asevt)++ # Don't report additional netblocks from this AS if we've+ # already found this AS before.+ if not self.nbreported.has_key(asn):+ # 2. Find all the netblocks owned by this AS+ self.nbreported[asn] = True+ netblocks = self.asNetblocks(asn)+ for netblock in netblocks:+ if netblock == prefix:+ continue++ # Technically this netblock was identified via the AS, not+ # the original IP event, so link it to asevt, not event.+ evt = SpiderFootEvent("NETBLOCK", netblock, self.__name__, asevt)+ self.notifyListeners(evt)++ # 3. Find all the AS neighbors to this ASneighs = self.asNeighbours(asn)for nasn in neighs:ownerinfo = self.asOwnerInfo(nasn)ownertext = ''for k, v in ownerinfo.iteritems():- ownertext = ownertext + k + ": " + v + "\n"-+ ownertext = ownertext + k + ": " + ', '.join(v) + "\n"+if len(ownerinfo) > 0:evt = SpiderFootEvent("PROVIDER_INTERNET", ownertext,- self.__name__, event)+ self.__name__, asevt)self.notifyListeners(evt)else:# If they don't own the netblock they are serving from, then# the netblock owner is their Internet provider.ownertext = ''for k, v in ownerinfo.iteritems():- ownertext = ownertext + k + ": " + v + "\n"+ ownertext = ownertext + k + ": " + ', '.join(v) + "\n"evt = SpiderFootEvent("PROVIDER_INTERNET", ownertext,self.__name__, event)self.notifyListeners(evt)diff --git a/modules/sfp_malcheck.py b/modules/sfp_malcheck.pyindex 258f194c..688c81bd 100644--- a/modules/sfp_malcheck.py+++ b/modules/sfp_malcheck.py@@ -56,8 +56,7 @@ malchecks = {'type': 'query','checks': ['asn'],'url': 'http://www.google.com/safebrowsing/diagnostic?site=AS:{0}',- 'badregex': [ '.*served content that resulted in malicious software.*',- '.*for example.*, that appeared to function as intermediaries.*',+ 'badregex': [ '.*for example.*, that appeared to function as intermediaries.*','.*this network has hosted sites that have distributed malicious.*'],'goodregex': []@@ -306,7 +305,7 @@ class sfp_malcheck(SpiderFootPlugin):# Notify other modules of what you've foundif url != None:- text = check + "\n" + url+ text = check + " [" + eventData + "]\n" + urlevt = SpiderFootEvent(evtType, text, self.__name__, event)self.notifyListeners(evt)@@ -326,6 +325,7 @@ class sfp_malcheck(SpiderFootPlugin):if self.opts[cid]:url = self.lookupItem(cid, 'domain', self.baseDomain)if url != None:+ text = check + " [" + self.baseDomain + "]\n" + urlevt = SpiderFootEvent('MALICIOUS_SUBDOMAIN', url, self.__name__)self.notifyListeners(evt)diff --git a/modules/sfp_sslcert.py b/modules/sfp_sslcert.pyindex 5fb9bef9..1778868f 100644--- a/modules/sfp_sslcert.py+++ b/modules/sfp_sslcert.py@@ -146,7 +146,7 @@ class sfp_sslcert(SpiderFootPlugin):fqdn_tld = ".".join(fqdn.split(".")[1:]).lower()if "dns:"+fqdn not in hosts and "dns:*."+fqdn_tld not in hosts:- evt = SpiderFootEvent("SSL_CERTIFICATE_MISMATCH", fqdn, self.__name__, sevt)+ evt = SpiderFootEvent("SSL_CERTIFICATE_MISMATCH", hosts, self.__name__, sevt)self.notifyListeners(evt)# Check if the expiration date is in the futurediff --git a/modules/sfp_tldsearch.py b/modules/sfp_tldsearch.pyindex ccec4f5e..a70b04cf 100644--- a/modules/sfp_tldsearch.py+++ b/modules/sfp_tldsearch.py@@ -23,7 +23,7 @@ from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEventsf = Noneclass sfp_tldsearch(SpiderFootPlugin):- """TLD Search:Search all Internet TLDs for domains with the same name as the target."""+ """TLD Search:Search all Internet TLDs for domains with the same name as the target (this can be slow.)"""# Default optionsopts = {@@ -84,8 +84,8 @@ class sfp_tldsearch(SpiderFootPlugin):# Spawn threads for scanningsf.info("Spawning threads to check TLDs: " + str(tldList))for tld in tldList:- t.append(threading.Thread(name='sfp_tldsearch_' + tld,- target=self.tryTld, args=(tld,)))+ tn = 'sfp_tldsearch_' + str(random.randint(0,999999999))+ t.append(threading.Thread(name=tn, target=self.tryTld, args=(tld,)))t[i].start()i += 1@@ -133,7 +133,10 @@ class sfp_tldsearch(SpiderFootPlugin):# Look through all TLDs for the existence of this target keywordfor tld in self.opts['_internettlds']:- tld = unicode(tld.strip(), errors='ignore')+ if type(tld) != unicode:+ tld = unicode(tld.strip(), errors='ignore')+ else:+ tld = tld.strip()if tld.startswith("//") or len(tld) == 0:continuediff --git a/sfdb.py b/sfdb.pyindex add68b25..f099b032 100644--- a/sfdb.py+++ b/sfdb.py@@ -460,6 +460,7 @@ class SpiderFootDb:# - sourceEventHash: hash of the event that triggered this event# And getHash() will return the event hash.def scanEventStore(self, instanceId, sfEvent, truncateSize=0):+ storeData = ''if type(sfEvent.data) is not unicode:# If sfEvent.data is a dict or list, convert it to a string first, asdiff --git a/sflib.py b/sflib.pyindex a3d7d404..9c38bc11 100644--- a/sflib.py+++ b/sflib.py@@ -421,7 +421,7 @@ class SpiderFoot:if bits == None:return url.lower()- self.debug('base url of ' + url + ' is: ' + bits.group(1))+ #self.debug('base url of ' + url + ' is: ' + bits.group(1))return bits.group(1).lower()# Extract the FQDN from a URL@@ -647,11 +647,11 @@ class SpiderFoot:self.info("Fetching: " + url + " [user-agent: " + \header['User-Agent'] + "] [timeout: " + str(timeout) + "]")+ result['headers'] = dict()opener = urllib2.build_opener(SmartRedirectHandler())fullPage = opener.open(req, timeout=timeout)content = fullPage.read()- result['headers'] = dict()for k, v in fullPage.info().items():result['headers'][k.lower()] = v@@ -670,7 +670,8 @@ class SpiderFoot:self.info("HTTP code " + str(h.code) + " encountered for " + url)# Capture the HTTP error coderesult['code'] = h.code- result['headers'] = h.info()+ for k, v in h.info().items():+ result['headers'][k.lower()] = vif fatal:self.fatal('URL could not be fetched (' + h.code + ')')except urllib2.URLError as e: