Skip to content

SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.

sflib: Move several functions to SpiderFootHelpers (#1679)

bcoles43a961fc19f3
diff --git a/modules/sfp_botscout.py b/modules/sfp_botscout.py
index e77445f6..0cf44a47 100644
--- a/modules/sfp_botscout.py
+++ b/modules/sfp_botscout.py
@@ -15,7 +15,7 @@ import urllib.error
import urllib.parse
import urllib.request
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_botscout(SpiderFootPlugin):
@@ -92,7 +92,7 @@ class sfp_botscout(SpiderFootPlugin):
return self.parseApiResponse(res)
def queryEmail(self, email):
- if not self.sf.validEmail(email):
+ if not SpiderFootHelpers.validEmail(email):
return None
params = urllib.parse.urlencode({
diff --git a/modules/sfp_builtwith.py b/modules/sfp_builtwith.py
index 7b4e715a..ba1b3cfc 100644
--- a/modules/sfp_builtwith.py
+++ b/modules/sfp_builtwith.py
@@ -12,7 +12,7 @@
import json
import time
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_builtwith(SpiderFootPlugin):
@@ -155,7 +155,7 @@ class sfp_builtwith(SpiderFootPlugin):
self.__name__, event)
self.notifyListeners(e)
if nb.get('Email', None):
- if self.sf.validEmail(nb['Email']):
+ if SpiderFootHelpers.validEmail(nb['Email']):
if nb['Email'].split("@")[0] in self.opts['_genericusers'].split(","):
evttype = "EMAILADDR_GENERIC"
else:
@@ -166,7 +166,7 @@ class sfp_builtwith(SpiderFootPlugin):
if data['Meta'].get("Emails", []):
for email in data['Meta']['Emails']:
- if self.sf.validEmail(email):
+ if SpiderFootHelpers.validEmail(email):
if email.split("@")[0] in self.opts['_genericusers'].split(","):
evttype = "EMAILADDR_GENERIC"
else:
diff --git a/modules/sfp_countryname.py b/modules/sfp_countryname.py
index 1e360674..94ebc63b 100644
--- a/modules/sfp_countryname.py
+++ b/modules/sfp_countryname.py
@@ -16,7 +16,7 @@ import re
import phonenumbers
from phonenumbers.phonenumberutil import region_code_for_country_code
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_countryname(SpiderFootPlugin):
@@ -55,7 +55,7 @@ class sfp_countryname(SpiderFootPlugin):
for opt in userOpts.keys():
self.opts[opt] = userOpts[opt]
- def detectCountryFromPhone(self, srcPhoneNumber):
+ def detectCountryFromPhone(self, srcPhoneNumber: str) -> str:
"""Lookup name of country from phone number region code.
Args:
@@ -83,9 +83,9 @@ class sfp_countryname(SpiderFootPlugin):
if not countryCode:
return None
- return self.sf.countryNameFromCountryCode(countryCode.upper())
+ return SpiderFootHelpers.countryNameFromCountryCode(countryCode.upper())
- def detectCountryFromDomainName(self, srcDomain):
+ def detectCountryFromDomainName(self, srcDomain: str) -> str:
"""Lookup name of country from TLD of domain name.
Args:
@@ -103,13 +103,13 @@ class sfp_countryname(SpiderFootPlugin):
# Search for country TLD in the domain parts - reversed
for part in domainParts[::-1]:
- country_name = self.sf.countryNameFromTld(part)
+ country_name = SpiderFootHelpers.countryNameFromTld(part)
if country_name:
return country_name
return None
- def detectCountryFromIBAN(self, srcIBAN):
+ def detectCountryFromIBAN(self, srcIBAN: str) -> str:
"""Detect name of country from IBAN.
Args:
@@ -121,9 +121,9 @@ class sfp_countryname(SpiderFootPlugin):
if not isinstance(srcIBAN, str):
return None
- return self.sf.countryNameFromCountryCode(srcIBAN[0:2])
+ return SpiderFootHelpers.countryNameFromCountryCode(srcIBAN[0:2])
- def detectCountryFromData(self, srcData):
+ def detectCountryFromData(self, srcData: str) -> list:
"""Detect name of country from event data (WHOIS lookup, Geo Info, Physical Address, etc)
Args:
@@ -138,7 +138,7 @@ class sfp_countryname(SpiderFootPlugin):
return countries
# Get dictionary of country codes and country names
- abbvCountryCodes = self.sf.getCountryCodeDict()
+ abbvCountryCodes = SpiderFootHelpers.countryCodes()
# Look for countrycodes and country in source data
for countryName in abbvCountryCodes.values():
diff --git a/modules/sfp_creditcard.py b/modules/sfp_creditcard.py
index 00ba80eb..7e630b9e 100644
--- a/modules/sfp_creditcard.py
+++ b/modules/sfp_creditcard.py
@@ -11,7 +11,7 @@
# Licence: MIT
# -------------------------------------------------------------------------------
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_creditcard(SpiderFootPlugin):
@@ -58,7 +58,7 @@ class sfp_creditcard(SpiderFootPlugin):
self.debug(f"Received event, {eventName}, from {srcModuleName}")
- creditCards = self.sf.parseCreditCards(eventData)
+ creditCards = SpiderFootHelpers.extractCreditCardsFromText(eventData)
for creditCard in set(creditCards):
self.info(f"Found credit card number: {creditCard}")
diff --git a/modules/sfp_crossref.py b/modules/sfp_crossref.py
index 22ddd6d3..aa738bb3 100644
--- a/modules/sfp_crossref.py
+++ b/modules/sfp_crossref.py
@@ -15,7 +15,7 @@
import re
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_crossref(SpiderFootPlugin):
@@ -124,7 +124,7 @@ class sfp_crossref(SpiderFootPlugin):
# fetch the base URL of the affiliate to check for a crossref.
if eventName == "LINKED_URL_EXTERNAL" and self.opts['checkbase']:
# Check the base url to see if there is an affiliation
- url = self.sf.urlBaseUrl(eventData)
+ url = SpiderFootHelpers.urlBaseUrl(eventData)
if url in self.fetched:
return
diff --git a/modules/sfp_email.py b/modules/sfp_email.py
index 696ff116..5321b636 100644
--- a/modules/sfp_email.py
+++ b/modules/sfp_email.py
@@ -11,7 +11,7 @@
# Licence: MIT
# -------------------------------------------------------------------------------
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_email(SpiderFootPlugin):
@@ -56,7 +56,7 @@ class sfp_email(SpiderFootPlugin):
self.debug(f"Received event, {eventName}, from {srcModuleName}")
- emails = self.sf.parseEmails(eventData)
+ emails = SpiderFootHelpers.extractEmailsFromText(eventData)
for email in set(emails):
evttype = "EMAILADDR"
email = email.lower()
diff --git a/modules/sfp_emailformat.py b/modules/sfp_emailformat.py
index 6b12e265..ecb356f1 100644
--- a/modules/sfp_emailformat.py
+++ b/modules/sfp_emailformat.py
@@ -15,7 +15,7 @@ import re
from bs4 import BeautifulSoup
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_emailformat(SpiderFootPlugin):
@@ -90,7 +90,7 @@ class sfp_emailformat(SpiderFootPlugin):
# fall back to raw page contents
data = res["content"]
- emails = self.sf.parseEmails(data)
+ emails = SpiderFootHelpers.extractEmailsFromText(data)
for email in emails:
# Skip unrelated emails
mailDom = email.lower().split('@')[1]
diff --git a/modules/sfp_flickr.py b/modules/sfp_flickr.py
index 8ef2376d..2d534b0c 100644
--- a/modules/sfp_flickr.py
+++ b/modules/sfp_flickr.py
@@ -18,7 +18,7 @@ import urllib.error
import urllib.parse
import urllib.request
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_flickr(SpiderFootPlugin):
@@ -203,7 +203,7 @@ class sfp_flickr(SpiderFootPlugin):
# Extract data
for photo in photos.get('photo', list()):
- emails = self.sf.parseEmails(str(photo))
+ emails = SpiderFootHelpers.extractEmailsFromText(str(photo))
for email in emails:
if email in self.results:
continue
@@ -224,7 +224,7 @@ class sfp_flickr(SpiderFootPlugin):
self.notifyListeners(evt)
self.results[email] = True
- links = self.sf.extractUrls(str(photo))
+ links = SpiderFootHelpers.extractUrlsFromText(str(photo))
for link in links:
if link in self.results:
continue
diff --git a/modules/sfp_gravatar.py b/modules/sfp_gravatar.py
index 8c02ae89..6b42f780 100644
--- a/modules/sfp_gravatar.py
+++ b/modules/sfp_gravatar.py
@@ -15,7 +15,7 @@ import hashlib
import json
import time
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_gravatar(SpiderFootPlugin):
@@ -163,7 +163,7 @@ class sfp_gravatar(SpiderFootPlugin):
em = email.get('value')
if not em:
continue
- if self.sf.validEmail(em) and em != eventData:
+ if SpiderFootHelpers.validEmail(em) and em != eventData:
if em.split("@")[0] in self.opts['_genericusers'].split(","):
evttype = "EMAILADDR_GENERIC"
else:
diff --git a/modules/sfp_grep_app.py b/modules/sfp_grep_app.py
index 523ffd96..8f53abac 100644
--- a/modules/sfp_grep_app.py
+++ b/modules/sfp_grep_app.py
@@ -18,7 +18,7 @@ import urllib.error
import urllib.parse
import urllib.request
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_grep_app(SpiderFootPlugin):
@@ -196,7 +196,7 @@ class sfp_grep_app(SpiderFootPlugin):
self.notifyListeners(evt)
self.results[link] = True
- emails = self.sf.parseEmails(snippet.replace('<mark>', '').replace('</mark>', ''))
+ emails = SpiderFootHelpers.extractEmailsFromText(snippet.replace('<mark>', '').replace('</mark>', ''))
if emails:
for email in emails:
if email in self.results:
diff --git a/modules/sfp_hashes.py b/modules/sfp_hashes.py
index f6b1bcbe..09cc58f2 100644
--- a/modules/sfp_hashes.py
+++ b/modules/sfp_hashes.py
@@ -11,7 +11,7 @@
# Licence: MIT
# -------------------------------------------------------------------------------
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_hashes(SpiderFootPlugin):
@@ -59,11 +59,11 @@ class sfp_hashes(SpiderFootPlugin):
self.debug(f"Received event, {eventName}, from {srcModuleName}")
- hashes = self.sf.parseHashes(eventData)
+ hashes = SpiderFootHelpers.extractHashesFromText(eventData)
for hashtup in hashes:
hashalgo, hashval = hashtup
- evt = SpiderFootEvent("HASH", "[" + hashalgo + "] " + hashval, self.__name__, event)
+ evt = SpiderFootEvent("HASH", f"[{hashalgo}] {hashval}", self.__name__, event)
if event.moduleDataSource:
evt.moduleDataSource = event.moduleDataSource
else:
diff --git a/modules/sfp_iban.py b/modules/sfp_iban.py
index b3698ac2..04446be6 100644
--- a/modules/sfp_iban.py
+++ b/modules/sfp_iban.py
@@ -11,7 +11,7 @@
# Licence: MIT
# -------------------------------------------------------------------------------
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_iban(SpiderFootPlugin):
@@ -59,8 +59,8 @@ class sfp_iban(SpiderFootPlugin):
self.debug(f"Received event, {eventName}, from {srcModuleName}")
- ibanNumbers = self.sf.parseIBANNumbers(eventData)
- for ibanNumber in set(ibanNumbers):
+ ibans = SpiderFootHelpers.extractIbansFromText(eventData)
+ for ibanNumber in set(ibans):
self.info(f"Found IBAN number: {ibanNumber}")
evt = SpiderFootEvent("IBAN_NUMBER", ibanNumber, self.__name__, event)
if event.moduleDataSource:
diff --git a/modules/sfp_jsonwhoiscom.py b/modules/sfp_jsonwhoiscom.py
index 309cb8e6..366a2db7 100644
--- a/modules/sfp_jsonwhoiscom.py
+++ b/modules/sfp_jsonwhoiscom.py
@@ -16,7 +16,7 @@ import urllib.error
import urllib.parse
import urllib.request
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_jsonwhoiscom(SpiderFootPlugin):
@@ -215,7 +215,7 @@ class sfp_jsonwhoiscom(SpiderFootPlugin):
for contact in contacts:
email = contact.get('email')
if email:
- if self.sf.validEmail(email):
+ if SpiderFootHelpers.validEmail(email):
emails.append(email)
name = contact.get("name")
@@ -227,7 +227,7 @@ class sfp_jsonwhoiscom(SpiderFootPlugin):
phone = phone.replace(" ", "").replace("-", "").replace("(", "").replace(")", "").replace(".", "")
phones.append(phone)
- country = self.sf.countryNameFromCountryCode(contact.get('country_code'))
+ country = SpiderFootHelpers.countryNameFromCountryCode(contact.get('country_code'))
location = ', '.join([_f for _f in [contact.get('address'), contact.get('city'), contact.get('state'), contact.get('zip'), country] if _f])
if location:
locations.append(location)
diff --git a/modules/sfp_junkfiles.py b/modules/sfp_junkfiles.py
index 5f80443c..3dde55ee 100644
--- a/modules/sfp_junkfiles.py
+++ b/modules/sfp_junkfiles.py
@@ -12,7 +12,7 @@
import random
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_junkfiles(SpiderFootPlugin):
@@ -77,7 +77,7 @@ class sfp_junkfiles(SpiderFootPlugin):
useragent=self.opts['_useragent'],
verify=False)
if res['code'] != "404":
- host = self.sf.urlBaseUrl(junkUrl)
+ host = SpiderFootHelpers.urlBaseUrl(junkUrl)
self.skiphosts[host] = True
return False
return True
@@ -95,7 +95,7 @@ class sfp_junkfiles(SpiderFootPlugin):
self.results[eventData] = True
- host = self.sf.urlBaseUrl(eventData)
+ host = SpiderFootHelpers.urlBaseUrl(eventData)
if host in self.skiphosts:
self.debug("Skipping " + host + " because it doesn't return 404s.")
@@ -137,7 +137,7 @@ class sfp_junkfiles(SpiderFootPlugin):
evt = SpiderFootEvent("JUNK_FILE", fetch, self.__name__, event)
self.notifyListeners(evt)
- base = self.sf.urlBaseDir(eventData)
+ base = SpiderFootHelpers.urlBaseDir(eventData)
if not base or base in self.bases:
return
diff --git a/modules/sfp_numverify.py b/modules/sfp_numverify.py
index b2cc603f..cbb1d1a6 100644
--- a/modules/sfp_numverify.py
+++ b/modules/sfp_numverify.py
@@ -16,7 +16,7 @@ import urllib.error
import urllib.parse
import urllib.request
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_numverify(SpiderFootPlugin):
@@ -160,7 +160,7 @@ class sfp_numverify(SpiderFootPlugin):
self.notifyListeners(evt)
if data.get('country_code'):
- country = self.sf.countryNameFromCountryCode(data.get('country_code'))
+ country = SpiderFootHelpers.countryNameFromCountryCode(data.get('country_code'))
location = ', '.join([_f for _f in [data.get('location'), country] if _f])
evt = SpiderFootEvent("GEOINFO", location, self.__name__, event)
self.notifyListeners(evt)
diff --git a/modules/sfp_pastebin.py b/modules/sfp_pastebin.py
index 8de32e6b..ae257c80 100644
--- a/modules/sfp_pastebin.py
+++ b/modules/sfp_pastebin.py
@@ -13,7 +13,7 @@
import re
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_pastebin(SpiderFootPlugin):
@@ -124,7 +124,7 @@ class sfp_pastebin(SpiderFootPlugin):
self.results[link] = True
relevant_links = [
- link for link in new_links if self.sf.urlBaseUrl(link).endswith(target)
+ link for link in new_links if SpiderFootHelpers.urlBaseUrl(link).endswith(target)
]
for link in relevant_links:
diff --git a/modules/sfp_pgp.py b/modules/sfp_pgp.py
index f4125758..5c697a74 100644
--- a/modules/sfp_pgp.py
+++ b/modules/sfp_pgp.py
@@ -14,7 +14,7 @@
import re
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_pgp(SpiderFootPlugin):
@@ -88,7 +88,7 @@ class sfp_pgp(SpiderFootPlugin):
useragent=self.opts['_useragent'])
if res['content'] is not None and res['code'] != "503":
- emails = self.sf.parseEmails(res['content'])
+ emails = SpiderFootHelpers.extractEmailsFromText(res['content'])
for email in emails:
if email.split("@")[0] in self.opts['_genericusers'].split(","):
evttype = "EMAILADDR_GENERIC"
diff --git a/modules/sfp_scylla.py b/modules/sfp_scylla.py
index c5b8a8b7..2be1c9b0 100644
--- a/modules/sfp_scylla.py
+++ b/modules/sfp_scylla.py
@@ -15,7 +15,7 @@ import urllib.error
import urllib.parse
import urllib.request
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_scylla(SpiderFootPlugin):
@@ -162,7 +162,7 @@ class sfp_scylla(SpiderFootPlugin):
if not email:
continue
- if not self.sf.validEmail(email):
+ if not SpiderFootHelpers.validEmail(email):
self.debug("Skipping invalid email address: " + email)
continue
diff --git a/modules/sfp_searchcode.py b/modules/sfp_searchcode.py
index 602a1052..bec430b7 100644
--- a/modules/sfp_searchcode.py
+++ b/modules/sfp_searchcode.py
@@ -16,7 +16,7 @@ import urllib.error
import urllib.parse
import urllib.request
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_searchcode(SpiderFootPlugin):
@@ -146,7 +146,7 @@ class sfp_searchcode(SpiderFootPlugin):
if not results:
return
- emails = self.sf.parseEmails(str(results))
+ emails = SpiderFootHelpers.extractEmailsFromText(str(results))
for email in emails:
if email in self.results:
continue
@@ -170,7 +170,7 @@ class sfp_searchcode(SpiderFootPlugin):
lines = result.get('lines')
if lines:
for line in lines:
- links.update(self.sf.extractUrls(lines[line]))
+ links.update(SpiderFootHelpers.extractUrlsFromText(lines[line]))
for link in links:
if link in self.results:
diff --git a/modules/sfp_skymem.py b/modules/sfp_skymem.py
index 2e3abcbe..9b39815e 100644
--- a/modules/sfp_skymem.py
+++ b/modules/sfp_skymem.py
@@ -13,7 +13,7 @@
import re
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_skymem(SpiderFootPlugin):
@@ -83,7 +83,7 @@ class sfp_skymem(SpiderFootPlugin):
return
# Extract emails from results page
- emails = self.sf.parseEmails(res['content'])
+ emails = SpiderFootHelpers.extractEmailsFromText(res['content'])
for email in emails:
# Skip unrelated emails
@@ -111,12 +111,16 @@ class sfp_skymem(SpiderFootPlugin):
domain_id = domain_ids[0]
for page in range(1, 21):
- res = self.sf.fetchUrl("http://www.skymem.info/domain/" + domain_id + "?p=" + str(page), timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])
+ res = self.sf.fetchUrl(
+ f"http://www.skymem.info/domain/{domain_id}?p={page}",
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent']
+ )
if res['content'] is None:
break
- emails = self.sf.parseEmails(res['content'])
+ emails = SpiderFootHelpers.extractEmailsFromText(res['content'])
for email in emails:
# Skip unrelated emails
mailDom = email.lower().split('@')[1]
diff --git a/modules/sfp_snov.py b/modules/sfp_snov.py
index 20d678a1..f774c87e 100644
--- a/modules/sfp_snov.py
+++ b/modules/sfp_snov.py
@@ -16,7 +16,7 @@ import urllib.error
import urllib.parse
import urllib.request
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_snov(SpiderFootPlugin):
@@ -206,7 +206,7 @@ class sfp_snov(SpiderFootPlugin):
if email:
if email in self.results:
continue
- if not self.sf.validEmail(email):
+ if not SpiderFootHelpers.validEmail(email):
continue
self.results[email] = True
diff --git a/modules/sfp_spider.py b/modules/sfp_spider.py
index 9406b7ea..c9b1df8e 100644
--- a/modules/sfp_spider.py
+++ b/modules/sfp_spider.py
@@ -157,7 +157,7 @@ class sfp_spider(SpiderFootPlugin):
returnLinks = dict()
for link in links:
- linkBase = self.sf.urlBaseUrl(link)
+ linkBase = SpiderFootHelpers.urlBaseUrl(link)
linkFQDN = self.sf.urlFQDN(link)
# Skip external sites (typical behaviour..)
@@ -318,7 +318,7 @@ class sfp_spider(SpiderFootPlugin):
totalFetched = 0
levelsTraversed = 0
nextLinks = dict()
- targetBase = self.sf.urlBaseUrl(startingPoint)
+ targetBase = SpiderFootHelpers.urlBaseUrl(startingPoint)
# Are we respecting robots.txt?
if self.opts['robotsonly'] and targetBase not in self.robotsRules:
@@ -328,7 +328,7 @@ class sfp_spider(SpiderFootPlugin):
verify=False)
if robotsTxt['content'] is not None:
self.debug('robots.txt contents: ' + robotsTxt['content'])
- self.robotsRules[targetBase] = SpiderFootHelpers.parseRobotsTxt(robotsTxt['content'])
+ self.robotsRules[targetBase] = SpiderFootHelpers.extractUrlsFromRobotsTxt(robotsTxt['content'])
if self.checkForStop():
return
diff --git a/modules/sfp_spyse.py b/modules/sfp_spyse.py
index adb01447..d5540bf0 100644
--- a/modules/sfp_spyse.py
+++ b/modules/sfp_spyse.py
@@ -15,7 +15,7 @@
import json
import time
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_spyse(SpiderFootPlugin):
@@ -635,7 +635,7 @@ class sfp_spyse(SpiderFootPlugin):
domain_emails = domain_http_extract.get("emails")
if domain_emails:
for email in domain_emails:
- if self.sf.validEmail(email):
+ if SpiderFootHelpers.validEmail(email):
evt = SpiderFootEvent('EMAILADDR', email, self.__name__, event)
self.notifyListeners(evt)
diff --git a/modules/sfp_stackoverflow.py b/modules/sfp_stackoverflow.py
index e78b2340..d0965e4d 100644
--- a/modules/sfp_stackoverflow.py
+++ b/modules/sfp_stackoverflow.py
@@ -14,7 +14,7 @@ import json
import re
import time
-from spiderfoot import SpiderFootEvent, SpiderFootPlugin
+from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
class sfp_stackoverflow(SpiderFootPlugin):
@@ -217,7 +217,7 @@ class sfp_stackoverflow(SpiderFootPlugin):
)
self.notifyListeners(e)
- emails = self.sf.parseEmails(text)
+ emails = SpiderFootHelpers.extractEmailsFromText(text)
if emails:
for email in emails:
allEmails.append(str(email))
diff --git a/sf.py b/sf.py
index f573946d..8057fb74 100755
--- a/sf.py
+++ b/sf.py
@@ -142,7 +142,7 @@ def main() -> None:
# Load each module in the modules directory with a .py extension
try:
mod_dir = sft.myPath() + '/modules/'
- sfModules = SpiderFootHelpers.loadModulesAsDict(mod_dir)
+ sfModules = SpiderFootHelpers.loadModulesAsDict(mod_dir, ['sfp_template.py'])
except BaseException as e:
log.critical(f"Failed to load modules: {e}", exc_info=True)
sys.exit(-1)
@@ -155,7 +155,7 @@ def main() -> None:
# a .yaml extension
try:
correlations_dir = sft.myPath() + '/correlations/'
- correlationRulesRaw = SpiderFootHelpers.loadCorrelationRulesRaw(correlations_dir)
+ correlationRulesRaw = SpiderFootHelpers.loadCorrelationRulesRaw(correlations_dir, ['template.yaml'])
except BaseException as e:
log.critical(f"Failed to load correlation rules: {e}", exc_info=True)
sys.exit(-1)
diff --git a/sflib.py b/sflib.py
index de055b2d..49a982d9 100644
--- a/sflib.py
+++ b/sflib.py
@@ -11,7 +11,6 @@
# -------------------------------------------------------------------------------
import hashlib
-import html
import inspect
import io
import json
@@ -33,7 +32,6 @@ from datetime import datetime
import cryptography
import dns.resolver
import netaddr
-import phonenumbers
import OpenSSL
import requests
import urllib3
@@ -604,95 +602,6 @@ class SpiderFoot:
return evtlist
- def urlRelativeToAbsolute(self, url: str) -> str:
- """Turn a relative path into an absolute path
-
- Args:
- url (str): URL
-
- Returns:
- str: URL relative path
- """
- if not url:
- self.error(f"Invalid URL: {url}")
- return None
-
- 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)
-
- return '/'.join(finalBits)
-
- def urlBaseDir(self, url: str) -> str:
- """Extract the top level directory from a URL
-
- Args:
- url (str): URL
-
- Returns:
- str: base directory
- """
- if not url:
- self.error(f"Invalid URL: {url}")
- return None
-
- bits = url.split('/')
-
- # For cases like 'www.somesite.com'
- if len(bits) == 0:
- return url + '/'
-
- # For cases like 'http://www.blah.com'
- if '://' in url and url.count('/') < 3:
- return url + '/'
-
- base = '/'.join(bits[:-1])
-
- return base + '/'
-
- def urlBaseUrl(self, url: str) -> str:
- """Extract the scheme and domain from a URL
-
- Does not return the trailing slash! So you can do .endswith() checks.
-
- Args:
- url (str): URL
-
- Returns:
- str: base URL without trailing slash
- """
- if not url:
- self.error(f"Invalid URL: {url}")
- return None
-
- if '://' in url:
- bits = re.match(r'(\w+://.[^/:\?]*)[:/\?].*', url)
- else:
- bits = re.match(r'(.[^/:\?]*)[:/\?]', url)
-
- if bits is None:
- return url.lower()
-
- return bits.group(1).lower()
-
def urlFQDN(self, url: str) -> str:
"""Extract the FQDN from a URL.
@@ -706,7 +615,7 @@ class SpiderFoot:
self.error(f"Invalid URL: {url}")
return None
- baseurl = self.urlBaseUrl(url)
+ baseurl = SpiderFootHelpers.urlBaseUrl(url)
if '://' in baseurl:
count = 2
else:
@@ -930,54 +839,6 @@ class SpiderFoot:
ret.append(host)
return ret
- def validEmail(self, email: str) -> bool:
- """Check if the provided string is a valid email address.
-
- Args:
- email (str): The email address to check.
-
- Returns:
- bool: email is a valid email address
- """
- if not isinstance(email, str):
- return False
-
- if "@" not in email:
- return False
-
- if not re.match(r'^([\%a-zA-Z\.0-9_\-\+]+@[a-zA-Z\.0-9\-]+\.[a-zA-Z\.0-9\-]+)$', email):
- return False
-
- if len(email) < 6:
- return False
-
- # Skip strings with messed up URL encoding
- if "%" in email:
- return False
-
- # Skip strings which may have been truncated
- if "..." in email:
- return False
-
- return True
-
- def validPhoneNumber(self, phone: str) -> bool:
- """Check if the provided string is a valid phone number.
-
- Args:
- phone (str): The phone number to check.
-
- Returns:
- bool: string is a valid phone number
- """
- if not isinstance(phone, str):
- return False
-
- try:
- return phonenumbers.is_valid_number(phonenumbers.parse(phone))
- except Exception:
- return False
-
def dictwords(self) -> set:
"""Return dictionary words from several language dictionaries.
@@ -1173,530 +1034,6 @@ class SpiderFoot:
sock.do_handshake()
return sock
- def parseRobotsTxt(self, robotsTxtData: str) -> list:
- """Parse the contents of robots.txt.
-
- Args:
- robotsTxtData (str): robots.txt file contents
-
- 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()
-
- if not isinstance(robotsTxtData, str):
- return returnArr
-
- for line in robotsTxtData.splitlines():
- if line.lower().startswith('disallow:'):
- m = re.match(r'disallow:\s*(.[^ #]*)', line, re.IGNORECASE)
- if m:
- self.debug('robots.txt parsing found disallow: ' + m.group(1))
- returnArr.append(m.group(1))
-
- return returnArr
-
- def parseHashes(self, data: str) -> list:
- """Extract all hashes within the supplied content.
-
- Args:
- data (str): text to search for hashes
-
- Returns:
- list: list of hashes
- """
- ret = list()
-
- if not isinstance(data, str):
- return ret
-
- hashes = {
- "MD5": re.compile(r"(?:[^a-fA-F\d]|\b)([a-fA-F\d]{32})(?:[^a-fA-F\d]|\b)"),
- "SHA1": re.compile(r"(?:[^a-fA-F\d]|\b)([a-fA-F\d]{40})(?:[^a-fA-F\d]|\b)"),
- "SHA256": re.compile(r"(?:[^a-fA-F\d]|\b)([a-fA-F\d]{64})(?:[^a-fA-F\d]|\b)"),
- "SHA512": re.compile(r"(?:[^a-fA-F\d]|\b)([a-fA-F\d]{128})(?:[^a-fA-F\d]|\b)")
- }
-
- for h in hashes:
- matches = re.findall(hashes[h], data)
- for match in matches:
- self.debug("Found hash: " + match)
- ret.append((h, match))
-
- return ret
-
- def parseEmails(self, data: str) -> list:
- """Extract all email addresses within the supplied content.
-
- Args:
- data (str): text to search for email addresses
-
- Returns:
- list: list of email addresses
- """
- if not isinstance(data, str):
- return list()
-
- emails = set()
- matches = re.findall(r'([\%a-zA-Z\.0-9_\-\+]+@[a-zA-Z\.0-9\-]+\.[a-zA-Z\.0-9\-]+)', data)
-
- for match in matches:
- if self.validEmail(match):
- emails.add(match)
-
- return list(emails)
-
- def parseCreditCards(self, data: str) -> list:
- """Find all credit card numbers with the supplied content.
-
- Extracts numbers with lengths ranging from 13 - 19 digits
-
- Checks the numbers using Luhn's algorithm to verify
- if the number is a valid credit card number or not
-
- Args:
- data (str): text to search for credit card numbers
-
- Returns:
- list: list of credit card numbers
- """
- if not isinstance(data, str):
- return list()
-
- creditCards = set()
-
- # Remove whitespace from data.
- # Credit cards might contain spaces between them
- # which will cause regex mismatch
- data = data.replace(" ", "")
-
- # Extract all numbers with lengths ranging from 13 - 19 digits
- matches = re.findall(r"[0-9]{13,19}", data)
-
- # Verify each extracted number using Luhn's algorithm
- for match in matches:
- if int(match) == 0:
- continue
-
- ccNumber = match
-
- ccNumberTotal = 0
- isSecondDigit = False
-
- for digit in ccNumber[::-1]:
- d = int(digit)
- if isSecondDigit:
- d *= 2
- ccNumberTotal += int(d / 10)
- ccNumberTotal += d % 10
-
- isSecondDigit = not isSecondDigit
- if ccNumberTotal % 10 == 0:
- self.debug("Found credit card number: " + match)
- creditCards.add(match)
- return list(creditCards)
-
- def getCountryCodeDict(self) -> dict:
- """Dictionary of country codes and associated country names.
-
- Returns:
- dict: country codes and associated country names
- """
-
- return {
- "AF": "Afghanistan",
- "AX": "Aland Islands",
- "AL": "Albania",
- "DZ": "Algeria",
- "AS": "American Samoa",
- "AD": "Andorra",
- "AO": "Angola",
- "AI": "Anguilla",
- "AQ": "Antarctica",
- "AG": "Antigua and Barbuda",
- "AR": "Argentina",
- "AM": "Armenia",
- "AW": "Aruba",
- "AU": "Australia",
- "AT": "Austria",
- "AZ": "Azerbaijan",
- "BS": "Bahamas",
- "BH": "Bahrain",
- "BD": "Bangladesh",
- "BB": "Barbados",
- "BY": "Belarus",
- "BE": "Belgium",
- "BZ": "Belize",
- "BJ": "Benin",
- "BM": "Bermuda",
- "BT": "Bhutan",
- "BO": "Bolivia",
- "BQ": "Bonaire, Saint Eustatius and Saba",
- "BA": "Bosnia and Herzegovina",
- "BW": "Botswana",
- "BV": "Bouvet Island",
- "BR": "Brazil",
- "IO": "British Indian Ocean Territory",
- "VG": "British Virgin Islands",
- "BN": "Brunei",
- "BG": "Bulgaria",
- "BF": "Burkina Faso",
- "BI": "Burundi",
- "KH": "Cambodia",
- "CM": "Cameroon",
- "CA": "Canada",
- "CV": "Cape Verde",
- "KY": "Cayman Islands",
- "CF": "Central African Republic",
- "TD": "Chad",
- "CL": "Chile",
- "CN": "China",
- "CX": "Christmas Island",
- "CC": "Cocos Islands",
- "CO": "Colombia",
- "KM": "Comoros",
- "CK": "Cook Islands",
- "CR": "Costa Rica",
- "HR": "Croatia",
- "CU": "Cuba",
- "CW": "Curacao",
- "CY": "Cyprus",
- "CZ": "Czech Republic",
- "CD": "Democratic Republic of the Congo",
- "DK": "Denmark",
- "DJ": "Djibouti",
- "DM": "Dominica",
- "DO": "Dominican Republic",
- "TL": "East Timor",
- "EC": "Ecuador",
- "EG": "Egypt",
- "SV": "El Salvador",
- "GQ": "Equatorial Guinea",
- "ER": "Eritrea",
- "EE": "Estonia",
- "ET": "Ethiopia",
- "FK": "Falkland Islands",
- "FO": "Faroe Islands",
- "FJ": "Fiji",
- "FI": "Finland",
- "FR": "France",
- "GF": "French Guiana",
- "PF": "French Polynesia",
- "TF": "French Southern Territories",
- "GA": "Gabon",
- "GM": "Gambia",
- "GE": "Georgia",
- "DE": "Germany",
- "GH": "Ghana",
- "GI": "Gibraltar",
- "GR": "Greece",
- "GL": "Greenland",
- "GD": "Grenada",
- "GP": "Guadeloupe",
- "GU": "Guam",
- "GT": "Guatemala",
- "GG": "Guernsey",
- "GN": "Guinea",
- "GW": "Guinea-Bissau",
- "GY": "Guyana",
- "HT": "Haiti",
- "HM": "Heard Island and McDonald Islands",
- "HN": "Honduras",
- "HK": "Hong Kong",
- "HU": "Hungary",
- "IS": "Iceland",
- "IN": "India",
- "ID": "Indonesia",
- "IR": "Iran",
- "IQ": "Iraq",
- "IE": "Ireland",
- "IM": "Isle of Man",
- "IL": "Israel",
- "IT": "Italy",
- "CI": "Ivory Coast",
- "JM": "Jamaica",
- "JP": "Japan",
- "JE": "Jersey",
- "JO": "Jordan",
- "KZ": "Kazakhstan",
- "KE": "Kenya",
- "KI": "Kiribati",
- "XK": "Kosovo",
- "KW": "Kuwait",
- "KG": "Kyrgyzstan",
- "LA": "Laos",
- "LV": "Latvia",
- "LB": "Lebanon",
- "LS": "Lesotho",
- "LR": "Liberia",
- "LY": "Libya",
- "LI": "Liechtenstein",
- "LT": "Lithuania",
- "LU": "Luxembourg",
- "MO": "Macao",
- "MK": "Macedonia",
- "MG": "Madagascar",
- "MW": "Malawi",
- "MY": "Malaysia",
- "MV": "Maldives",
- "ML": "Mali",
- "MT": "Malta",
- "MH": "Marshall Islands",
- "MQ": "Martinique",
- "MR": "Mauritania",
- "MU": "Mauritius",
- "YT": "Mayotte",
- "MX": "Mexico",
- "FM": "Micronesia",
- "MD": "Moldova",
- "MC": "Monaco",
- "MN": "Mongolia",
- "ME": "Montenegro",
- "MS": "Montserrat",
- "MA": "Morocco",
- "MZ": "Mozambique",
- "MM": "Myanmar",
- "NA": "Namibia",
- "NR": "Nauru",
- "NP": "Nepal",
- "NL": "Netherlands",
- "AN": "Netherlands Antilles",
- "NC": "New Caledonia",
- "NZ": "New Zealand",
- "NI": "Nicaragua",
- "NE": "Niger",
- "NG": "Nigeria",
- "NU": "Niue",
- "NF": "Norfolk Island",
- "KP": "North Korea",
- "MP": "Northern Mariana Islands",
- "NO": "Norway",
- "OM": "Oman",
- "PK": "Pakistan",
- "PW": "Palau",
- "PS": "Palestinian Territory",
- "PA": "Panama",
- "PG": "Papua New Guinea",
- "PY": "Paraguay",
- "PE": "Peru",
- "PH": "Philippines",
- "PN": "Pitcairn",
- "PL": "Poland",
- "PT": "Portugal",
- "PR": "Puerto Rico",
- "QA": "Qatar",
- "CG": "Republic of the Congo",
- "RE": "Reunion",
- "RO": "Romania",
- "RU": "Russia",
- "RW": "Rwanda",
- "BL": "Saint Barthelemy",
- "SH": "Saint Helena",
- "KN": "Saint Kitts and Nevis",
- "LC": "Saint Lucia",
- "MF": "Saint Martin",
- "PM": "Saint Pierre and Miquelon",
- "VC": "Saint Vincent and the Grenadines",
- "WS": "Samoa",
- "SM": "San Marino",
- "ST": "Sao Tome and Principe",
- "SA": "Saudi Arabia",
- "SN": "Senegal",
- "RS": "Serbia",
- "CS": "Serbia and Montenegro",
- "SC": "Seychelles",
- "SL": "Sierra Leone",
- "SG": "Singapore",
- "SX": "Sint Maarten",
- "SK": "Slovakia",
- "SI": "Slovenia",
- "SB": "Solomon Islands",
- "SO": "Somalia",
- "ZA": "South Africa",
- "GS": "South Georgia and the South Sandwich Islands",
- "KR": "South Korea",
- "SS": "South Sudan",
- "ES": "Spain",
- "LK": "Sri Lanka",
- "SD": "Sudan",
- "SR": "Suriname",
- "SJ": "Svalbard and Jan Mayen",
- "SZ": "Swaziland",
- "SE": "Sweden",
- "CH": "Switzerland",
- "SY": "Syria",
- "TW": "Taiwan",
- "TJ": "Tajikistan",
- "TZ": "Tanzania",
- "TH": "Thailand",
- "TG": "Togo",
- "TK": "Tokelau",
- "TO": "Tonga",
- "TT": "Trinidad and Tobago",
- "TN": "Tunisia",
- "TR": "Turkey",
- "TM": "Turkmenistan",
- "TC": "Turks and Caicos Islands",
- "TV": "Tuvalu",
- "VI": "U.S. Virgin Islands",
- "UG": "Uganda",
- "UA": "Ukraine",
- "AE": "United Arab Emirates",
- "GB": "United Kingdom",
- "US": "United States",
- "UM": "United States Minor Outlying Islands",
- "UY": "Uruguay",
- "UZ": "Uzbekistan",
- "VU": "Vanuatu",
- "VA": "Vatican",
- "VE": "Venezuela",
- "VN": "Vietnam",
- "WF": "Wallis and Futuna",
- "EH": "Western Sahara",
- "YE": "Yemen",
- "ZM": "Zambia",
- "ZW": "Zimbabwe",
- # Below are not country codes but recognized as regions / TLDs
- "AC": "Ascension Island",
- "EU": "European Union",
- "SU": "Soviet Union",
- "UK": "United Kingdom"
- }
-
- def countryNameFromCountryCode(self, countryCode: str) -> str:
- """Convert a country code to full country name
-
- Args:
- countryCode (str): country code
-
- Returns:
- str: country name
- """
- if not isinstance(countryCode, str):
- return None
-
- return self.getCountryCodeDict().get(countryCode.upper())
-
- def countryNameFromTld(self, tld: str) -> str:
- """Retrieve the country name associated with a TLD.
-
- Args:
- tld (str): Top level domain
-
- Returns:
- str: country name
- """
- if not isinstance(tld, str):
- return None
-
- country_name = self.getCountryCodeDict().get(tld.upper())
-
- if country_name:
- return country_name
-
- country_tlds = {
- # List of TLD not associated with any country
- "COM": "United States",
- "NET": "United States",
- "ORG": "United States",
- "GOV": "United States",
- "MIL": "United States"
- }
-
- country_name = country_tlds.get(tld.upper())
-
- if country_name:
- return country_name
-
- return None
-
- def parseIBANNumbers(self, data: str) -> list:
- """Find all International Bank Account Numbers (IBANs) within the supplied content.
-
- Extracts possible IBANs using a generic regex.
-
- Checks whether possible IBANs are valid or not
- using country-wise length check and Mod 97 algorithm.
-
- Args:
- data (str): text to search for IBANs
-
- Returns:
- list: list of IBAN
- """
- if not isinstance(data, str):
- return list()
-
- ibans = set()
-
- # Dictionary of country codes and their respective IBAN lengths
- ibanCountryLengths = {
- "AL": 28, "AD": 24, "AT": 20, "AZ": 28,
- "ME": 22, "BH": 22, "BY": 28, "BE": 16,
- "BA": 20, "BR": 29, "BG": 22, "CR": 22,
- "HR": 21, "CY": 28, "CZ": 24, "DK": 18,
- "DO": 28, "EG": 29, "SV": 28, "FO": 18,
- "FI": 18, "FR": 27, "GE": 22, "DE": 22,
- "GI": 23, "GR": 27, "GL": 18, "GT": 28,
- "VA": 22, "HU": 28, "IS": 26, "IQ": 23,
- "IE": 22, "IL": 23, "JO": 30, "KZ": 20,
- "XK": 20, "KW": 30, "LV": 21, "LB": 28,
- "LI": 21, "LT": 20, "LU": 20, "MT": 31,
- "MR": 27, "MU": 30, "MD": 24, "MC": 27,
- "DZ": 24, "AO": 25, "BJ": 28, "VG": 24,
- "BF": 27, "BI": 16, "CM": 27, "CV": 25,
- "CG": 27, "EE": 20, "GA": 27, "GG": 22,
- "IR": 26, "IM": 22, "IT": 27, "CI": 28,
- "JE": 22, "MK": 19, "MG": 27, "ML": 28,
- "MZ": 25, "NL": 18, "NO": 15, "PK": 24,
- "PS": 29, "PL": 28, "PT": 25, "QA": 29,
- "RO": 24, "LC": 32, "SM": 27, "ST": 25,
- "SA": 24, "SN": 28, "RS": 22, "SC": 31,
- "SK": 24, "SI": 19, "ES": 24, "CH": 21,
- "TL": 23, "TN": 24, "TR": 26, "UA": 29,
- "AE": 23, "GB": 22, "SE": 24
- }
-
- # Normalize input data to remove whitespace
- data = data.replace(" ", "")
-
- # Extract alphanumeric characters of lengths ranging from 15 to 32
- # and starting with two characters
- matches = re.findall("[A-Za-z]{2}[A-Za-z0-9]{13,30}", data)
-
- for match in matches:
- iban = match.upper()
-
- countryCode = iban[0:2]
-
- if countryCode not in ibanCountryLengths.keys():
- continue
-
- if len(iban) != ibanCountryLengths[countryCode]:
- continue
-
- # Convert IBAN to integer format.
- # Move the first 4 characters to the end of the string,
- # then convert all characters to integers; where A = 10, B = 11, ...., Z = 35
- iban_int = iban[4:] + iban[0:4]
- for character in iban_int:
- if character.isalpha():
- iban_int = iban_int.replace(character, str((ord(character) - 65) + 10))
-
- # Check IBAN integer mod 97 for remainder
- if int(iban_int) % 97 != 1:
- continue
-
- self.debug("Found IBAN: %s" % iban)
- ibans.add(iban)
-
- return list(ibans)
-
def sslDerToPem(self, der_cert: bytes) -> str:
"""Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded string version of the same certificate.
@@ -1822,19 +1159,6 @@ class SpiderFoot:
return ret
- def extractUrls(self, content: str) -> list:
- """Extract all URLs from a string.
-
- Args:
- content (str): text to search for URLs
-
- Returns:
- list: list of identified URLs
- """
-
- # https://tools.ietf.org/html/rfc3986#section-3.3
- return re.findall(r"(https?://[a-zA-Z0-9-\.:]+/[\-\._~!\$&'\(\)\*\+\,\;=:@/a-zA-Z0-9]*)", html.unescape(content))
-
def parseLinks(self, url: str, data: str, domains: list) -> dict:
"""Find all URLs within the supplied content.
@@ -1934,7 +1258,7 @@ class SpiderFoot:
# If the link starts with a /, the absolute link is off the base URL
if link.startswith('/'):
- absLink = self.urlBaseUrl(url) + link
+ absLink = SpiderFootHelpers.urlBaseUrl(url) + link
# Protocol relative URLs
if link.startswith('//'):
@@ -1947,10 +1271,10 @@ class SpiderFoot:
# Otherwise, it's a flat link within the current directory
if absLink is None:
- absLink = self.urlBaseDir(url) + link
+ absLink = SpiderFootHelpers.urlBaseDir(url) + link
# Translate any relative pathing (../)
- absLink = self.urlRelativeToAbsolute(absLink)
+ absLink = SpiderFootHelpers.urlRelativeToAbsolute(absLink)
returnLinks[absLink] = {'source': url, 'original': link}
return returnLinks
@@ -2077,7 +1401,6 @@ class SpiderFoot:
def fetchUrl(
self,
url: str,
- fatal: bool = False,
cookies: str = None,
timeout: int = 30,
useragent: str = "SpiderFoot",
@@ -2093,7 +1416,6 @@ class SpiderFoot:
Args:
url (str): URL to fetch
- fatal (bool): raise an exception upon request error
cookies (str): cookies
timeout (int): timeout
useragent (str): user agent header
@@ -2159,7 +1481,9 @@ class SpiderFoot:
request_log.append(f"cookies={cookies}")
if sizeLimit or headOnly:
- if not noLog:
+ if noLog:
+ self.debug(f"Fetching (HEAD): {self.removeUrlCreds(url)} ({', '.join(request_log)})")
+ else:
self.info(f"Fetching (HEAD): {self.removeUrlCreds(url)} ({', '.join(request_log)})")
try:
@@ -2171,13 +1495,13 @@ class SpiderFoot:
timeout=timeout
)
except Exception as e:
- if not noLog:
+ if noLog:
+ self.debug(f"Unexpected exception ({e}) occurred fetching (HEAD only) URL: {url}")
+ self.debug(traceback.format_exc())
+ else:
self.error(f"Unexpected exception ({e}) occurred fetching (HEAD only) URL: {url}")
self.error(traceback.format_exc())
- if fatal:
- self.fatal(f"URL could not be fetched ({e})")
-
return result
size = int(hdr.headers.get('content-length', 0))
@@ -2185,7 +1509,7 @@ class SpiderFoot:
# Relative re-direct
if newloc.startswith("/") or newloc.startswith("../"):
- newloc = self.urlBaseUrl(url) + newloc
+ newloc = SpiderFootHelpers.urlBaseUrl(url) + newloc
result['realurl'] = newloc
result['code'] = str(hdr.status_code)
@@ -2196,7 +1520,9 @@ class SpiderFoot:
return result
if result['realurl'] != url:
- if not noLog:
+ if noLog:
+ self.debug(f"Fetching (HEAD): {self.removeUrlCreds(result['realurl'])} ({', '.join(request_log)})")
+ else:
self.info(f"Fetching (HEAD): {self.removeUrlCreds(result['realurl'])} ({', '.join(request_log)})")
try:
@@ -2215,18 +1541,20 @@ class SpiderFoot:
return result
except Exception as e:
- if not noLog:
+ if noLog:
+ self.debug(f"Unexpected exception ({e}) occurred fetching (HEAD only) URL: {result['realurl']}")
+ self.debug(traceback.format_exc())
+ else:
self.error(f"Unexpected exception ({e}) occurred fetching (HEAD only) URL: {result['realurl']}")
self.error(traceback.format_exc())
- if fatal:
- self.fatal(f"URL could not be fetched ({e})")
-
return result
try:
if postData:
- if not noLog:
+ if noLog:
+ self.debug(f"Fetching (POST): {self.removeUrlCreds(url)} ({', '.join(request_log)})")
+ else:
self.info(f"Fetching (POST): {self.removeUrlCreds(url)} ({', '.join(request_log)})")
res = self.getSession().post(
url,
@@ -2239,7 +1567,9 @@ class SpiderFoot:
verify=verify
)
else:
- if not noLog:
+ if noLog:
+ self.debug(f"Fetching (GET): {self.removeUrlCreds(url)} ({', '.join(request_log)})")
+ else:
self.info(f"Fetching (GET): {self.removeUrlCreds(url)} ({', '.join(request_log)})")
res = self.getSession().get(
url,
@@ -2254,13 +1584,13 @@ class SpiderFoot:
self.error(f"Failed to connect to {url}")
return result
except Exception as e:
- if not noLog:
+ if noLog:
+ self.debug(f"Unexpected exception ({e}) occurred fetching URL: {url}")
+ self.debug(traceback.format_exc())
+ else:
self.error(f"Unexpected exception ({e}) occurred fetching URL: {url}")
self.error(traceback.format_exc())
- if fatal:
- self.fatal(f"URL could not be fetched ({e})")
-
return result
try:
@@ -2288,7 +1618,6 @@ class SpiderFoot:
return self.fetchUrl(
newurl,
- fatal,
cookies,
timeout,
useragent,
@@ -2313,19 +1642,10 @@ class SpiderFoot:
else:
result["content"] = res.content
- if fatal:
- try:
- res.raise_for_status()
- except requests.exceptions.HTTPError:
- self.fatal(f"URL could not be fetched ({res.status_code}) / {res.content})")
-
except Exception as e:
self.error(f"Unexpected exception ({e}) occurred parsing response for URL: {url}")
self.error(traceback.format_exc())
- if fatal:
- self.fatal(f"URL could not be fetched ({e})")
-
result['content'] = None
result['status'] = str(e)
@@ -2457,8 +1777,12 @@ class SpiderFoot:
Returns:
dict: Search results as {"webSearchUrl": "URL", "urls": [results]}
"""
+ if not searchString:
+ return None
+
if opts is None:
opts = {}
+
search_string = searchString.replace(" ", "%20")
params = urllib.parse.urlencode({
"cx": opts["cse_id"],
@@ -2518,6 +1842,9 @@ class SpiderFoot:
Returns:
dict: Search results as {"webSearchUrl": "URL", "urls": [results]}
"""
+ if not searchString:
+ return None
+
if opts is None:
opts = {}
diff --git a/spiderfoot/correlation.py b/spiderfoot/correlation.py
index 1a1af631..89e59557 100644
--- a/spiderfoot/correlation.py
+++ b/spiderfoot/correlation.py
@@ -197,7 +197,7 @@ class SpiderFootCorrelator:
criterias['srcModule'] = list()
if matchrule['method'] == 'exact':
- if type(matchrule['value']) == list:
+ if isinstance(matchrule['value'], list):
criterias['srcModule'].extend(matchrule['value'])
else:
criterias['srcModule'].append(matchrule['value'])
@@ -207,7 +207,7 @@ class SpiderFootCorrelator:
if 'data' not in criterias:
criterias['data'] = list()
- if type(matchrule['value']) == list:
+ if isinstance(matchrule['value'], list):
for v in matchrule['value']:
criterias['data'].append(v.encode('raw_unicode_escape'))
else:
@@ -472,7 +472,7 @@ class SpiderFootCorrelator:
"""
patterns = list()
- if type(matchrule['value']) == list:
+ if isinstance(matchrule['value'], list):
for r in matchrule['value']:
patterns.append(str(r))
else:
@@ -667,8 +667,7 @@ class SpiderFootCorrelator:
for event in buckets[bucket][:]:
if event['_collection'] == 0:
continue
- else:
- pluszerocount += 1
+ pluszerocount += 1
if not check_event(self.event_extract(event, rule['field']), reference):
buckets[bucket].remove(event)
@@ -928,7 +927,6 @@ class SpiderFootCorrelator:
v = self.event_extract(data[0], m)[0]
except Exception:
self.log.error(f"Field requested was not available: {m}")
- pass
title = title.replace("{" + m + "}", v.replace("\r", "").split("\n")[0])
return title
@@ -1055,14 +1053,14 @@ class SpiderFootCorrelator:
alloptions = set(strictoptions).union(otheroptions)
for opt in strictoptions:
- if type(rule[field]) == list:
+ if isinstance(rule[field], list):
for item, optelement in enumerate(rule[field]):
if not optelement.get(opt):
self.log.error(f"Required field for {field} missing in {rule['id']}, item {item}: {opt}")
ok = False
continue
- elif type(rule[field]) == dict:
+ if isinstance(rule[field], dict):
if not rule[field].get(opt):
self.log.error(f"Required field for {field} missing in {rule['id']}: {opt}")
ok = False
diff --git a/spiderfoot/helpers.py b/spiderfoot/helpers.py
index 36f5e21c..5cf90f30 100644
--- a/spiderfoot/helpers.py
+++ b/spiderfoot/helpers.py
@@ -1,17 +1,27 @@
+# -*- coding: utf-8 -*-
+import html
import json
import os
import os.path
import random
import re
import uuid
+from pathlib import Path
import networkx as nx
from networkx.readwrite.gexf import GEXFWriter
-from pathlib import Path
+import phonenumbers
class SpiderFootHelpers():
- """SpiderFoot helper functions."""
+ """SpiderFoot helper functions.
+
+ This class is used to store static helper functions which are
+ designed to function independent of scan config or global config.
+
+ Todo:
+ Eventually split this class into separate files.
+ """
@staticmethod
def dataPath() -> str:
@@ -56,7 +66,7 @@ class SpiderFootHelpers():
return path
@staticmethod
- def loadModulesAsDict(path: str, ignore_files: list = ['sfp_template.py']) -> dict:
+ def loadModulesAsDict(path: str, ignore_files: list = None) -> dict:
"""Load modules from modules directory.
Args:
@@ -71,6 +81,9 @@ class SpiderFootHelpers():
ValueError: module path does not exist
SyntaxError: module data is malformed
"""
+ if not ignore_files:
+ ignore_files = []
+
if not isinstance(ignore_files, list):
raise TypeError(f"ignore_files is {type(ignore_files)}; expected list()")
@@ -107,7 +120,7 @@ class SpiderFootHelpers():
return sfModules
@staticmethod
- def loadCorrelationRulesRaw(path: str, ignore_files: list = ['template.yaml']) -> dict:
+ def loadCorrelationRulesRaw(path: str, ignore_files: list = None) -> dict:
"""Load correlation rules from correlations directory.
Args:
@@ -121,6 +134,9 @@ class SpiderFootHelpers():
TypeError: ignore file list was invalid
ValueError: module path does not exist
"""
+ if not ignore_files:
+ ignore_files = []
+
if not isinstance(ignore_files, list):
raise TypeError(f"ignore_files is {type(ignore_files)}; expected list()")
@@ -177,7 +193,103 @@ class SpiderFootHelpers():
return None
@staticmethod
- def buildGraphGexf(root: str, title: str, data: list, flt: list = []) -> str:
+ def urlRelativeToAbsolute(url: str) -> str:
+ """Turn a relative URL path into an absolute path.
+
+ Args:
+ url (str): URL
+
+ Returns:
+ str: URL relative path
+ """
+ if not url:
+ return None
+
+ if not isinstance(url, str):
+ return None
+
+ if '..' not in url:
+ return url
+
+ finalBits = list()
+
+ for chunk in url.split('/'):
+ if chunk != '..':
+ finalBits.append(chunk)
+ continue
+
+ # 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()
+
+ return '/'.join(finalBits)
+
+ @staticmethod
+ def urlBaseDir(url: str) -> str:
+ """Extract the top level directory from a URL
+
+ Args:
+ url (str): URL
+
+ Returns:
+ str: base directory
+ """
+ if not url:
+ return None
+
+ if not isinstance(url, str):
+ return None
+
+ bits = url.split('/')
+
+ # For cases like 'www.somesite.com'
+ if len(bits) == 0:
+ return url + '/'
+
+ # For cases like 'http://www.blah.com'
+ if '://' in url and url.count('/') < 3:
+ return url + '/'
+
+ base = '/'.join(bits[:-1])
+
+ return base + '/'
+
+ @staticmethod
+ def urlBaseUrl(url: str) -> str:
+ """Extract the scheme and domain from a URL.
+
+ Note: Does not return the trailing slash! So you can do .endswith() checks.
+
+ Args:
+ url (str): URL
+
+ Returns:
+ str: base URL without trailing slash
+ """
+ if not url:
+ return None
+
+ if not isinstance(url, str):
+ return None
+
+ if '://' in url:
+ bits = re.match(r'(\w+://.[^/:\?]*)[:/\?].*', url)
+ else:
+ bits = re.match(r'(.[^/:\?]*)[:/\?]', url)
+
+ if bits is None:
+ return url.lower()
+
+ return bits.group(1).lower()
+
+ @staticmethod
+ def buildGraphGexf(root: str, title: str, data: list, flt: list = None) -> str:
"""Convert supplied raw data into GEXF (Graph Exchange XML Format) format (e.g. for Gephi).
Args:
@@ -189,6 +301,9 @@ class SpiderFootHelpers():
Returns:
str: GEXF formatted XML
"""
+ if not flt:
+ flt = []
+
mapping = SpiderFootHelpers.buildGraphData(data, flt)
graph = nx.Graph()
@@ -229,7 +344,7 @@ class SpiderFootHelpers():
return str(gexf).encode('utf-8')
@staticmethod
- def buildGraphJson(root: str, data: list, flt: list = []) -> str:
+ def buildGraphJson(root: str, data: list, flt: list = None) -> str:
"""Convert supplied raw data into JSON format for SigmaJS.
Args:
@@ -240,6 +355,9 @@ class SpiderFootHelpers():
Returns:
str: TBD
"""
+ if not flt:
+ flt = []
+
mapping = SpiderFootHelpers.buildGraphData(data, flt)
ret = dict()
ret['nodes'] = list()
@@ -301,7 +419,7 @@ class SpiderFootHelpers():
return json.dumps(ret)
@staticmethod
- def buildGraphData(data: list, flt: list = []) -> set:
+ def buildGraphData(data: list, flt: list = None) -> set:
"""Return a format-agnostic collection of tuples to use as the
basis for building graphs in various formats.
@@ -316,13 +434,19 @@ class SpiderFootHelpers():
ValueError: data value was invalid
TypeError: data type was invalid
"""
+ if not flt:
+ flt = []
+
if not isinstance(data, list):
raise TypeError(f"data is {type(data)}; expected list()")
if not data:
raise ValueError("data is empty")
- def get_next_parent_entities(item: str, pids: list = []) -> list:
+ def get_next_parent_entities(item: str, pids: list = None) -> list:
+ if not pids:
+ pids = []
+
ret = list()
for [parent, entity_id] in parents[item]:
@@ -450,6 +574,56 @@ class SpiderFootHelpers():
return True
+ @staticmethod
+ def validEmail(email: str) -> bool:
+ """Check if the provided string is a valid email address.
+
+ Args:
+ email (str): The email address to check.
+
+ Returns:
+ bool: email is a valid email address
+ """
+ if not isinstance(email, str):
+ return False
+
+ if "@" not in email:
+ return False
+
+ if not re.match(r'^([\%a-zA-Z\.0-9_\-\+]+@[a-zA-Z\.0-9\-]+\.[a-zA-Z\.0-9\-]+)$', email):
+ return False
+
+ if len(email) < 6:
+ return False
+
+ # Skip strings with messed up URL encoding
+ if "%" in email:
+ return False
+
+ # Skip strings which may have been truncated
+ if "..." in email:
+ return False
+
+ return True
+
+ @staticmethod
+ def validPhoneNumber(phone: str) -> bool:
+ """Check if the provided string is a valid phone number.
+
+ Args:
+ phone (str): The phone number to check.
+
+ Returns:
+ bool: string is a valid phone number
+ """
+ if not isinstance(phone, str):
+ return False
+
+ try:
+ return phonenumbers.is_valid_number(phonenumbers.parse(phone))
+ except Exception:
+ return False
+
@staticmethod
def genScanInstanceId() -> str:
"""Generate an globally unique ID for this scan.
@@ -460,7 +634,36 @@ class SpiderFootHelpers():
return str(uuid.uuid4()).split("-")[0].upper()
@staticmethod
- def parseRobotsTxt(robotsTxtData: str) -> list:
+ def extractHashesFromText(data: str) -> list:
+ """Extract all hashes within the supplied content.
+
+ Args:
+ data (str): text to search for hashes
+
+ Returns:
+ list: list of hashes
+ """
+ ret = list()
+
+ if not isinstance(data, str):
+ return ret
+
+ hashes = {
+ "MD5": re.compile(r"(?:[^a-fA-F\d]|\b)([a-fA-F\d]{32})(?:[^a-fA-F\d]|\b)"),
+ "SHA1": re.compile(r"(?:[^a-fA-F\d]|\b)([a-fA-F\d]{40})(?:[^a-fA-F\d]|\b)"),
+ "SHA256": re.compile(r"(?:[^a-fA-F\d]|\b)([a-fA-F\d]{64})(?:[^a-fA-F\d]|\b)"),
+ "SHA512": re.compile(r"(?:[^a-fA-F\d]|\b)([a-fA-F\d]{128})(?:[^a-fA-F\d]|\b)")
+ }
+
+ for h in hashes:
+ matches = re.findall(hashes[h], data)
+ for m in matches:
+ ret.append((h, m))
+
+ return ret
+
+ @staticmethod
+ def extractUrlsFromRobotsTxt(robotsTxtData: str) -> list:
"""Parse the contents of robots.txt.
Args:
@@ -488,7 +691,494 @@ class SpiderFootHelpers():
return returnArr
@staticmethod
- def sanitiseInput(cmd: str, extra: list = []) -> bool:
+ def extractEmailsFromText(data: str) -> list:
+ """Extract all email addresses within the supplied content.
+
+ Args:
+ data (str): text to search for email addresses
+
+ Returns:
+ list: list of email addresses
+ """
+ if not isinstance(data, str):
+ return list()
+
+ emails = set()
+ matches = re.findall(r'([\%a-zA-Z\.0-9_\-\+]+@[a-zA-Z\.0-9\-]+\.[a-zA-Z\.0-9\-]+)', data)
+
+ for match in matches:
+ if SpiderFootHelpers.validEmail(match):
+ emails.add(match)
+
+ return list(emails)
+
+ @staticmethod
+ def extractIbansFromText(data: str) -> list:
+ """Find all International Bank Account Numbers (IBANs) within the supplied content.
+
+ Extracts possible IBANs using a generic regex.
+
+ Checks whether possible IBANs are valid or not
+ using country-wise length check and Mod 97 algorithm.
+
+ Args:
+ data (str): text to search for IBANs
+
+ Returns:
+ list: list of IBAN
+ """
+ if not isinstance(data, str):
+ return list()
+
+ ibans = set()
+
+ # Dictionary of country codes and their respective IBAN lengths
+ ibanCountryLengths = {
+ "AL": 28, "AD": 24, "AT": 20, "AZ": 28,
+ "ME": 22, "BH": 22, "BY": 28, "BE": 16,
+ "BA": 20, "BR": 29, "BG": 22, "CR": 22,
+ "HR": 21, "CY": 28, "CZ": 24, "DK": 18,
+ "DO": 28, "EG": 29, "SV": 28, "FO": 18,
+ "FI": 18, "FR": 27, "GE": 22, "DE": 22,
+ "GI": 23, "GR": 27, "GL": 18, "GT": 28,
+ "VA": 22, "HU": 28, "IS": 26, "IQ": 23,
+ "IE": 22, "IL": 23, "JO": 30, "KZ": 20,
+ "XK": 20, "KW": 30, "LV": 21, "LB": 28,
+ "LI": 21, "LT": 20, "LU": 20, "MT": 31,
+ "MR": 27, "MU": 30, "MD": 24, "MC": 27,
+ "DZ": 24, "AO": 25, "BJ": 28, "VG": 24,
+ "BF": 27, "BI": 16, "CM": 27, "CV": 25,
+ "CG": 27, "EE": 20, "GA": 27, "GG": 22,
+ "IR": 26, "IM": 22, "IT": 27, "CI": 28,
+ "JE": 22, "MK": 19, "MG": 27, "ML": 28,
+ "MZ": 25, "NL": 18, "NO": 15, "PK": 24,
+ "PS": 29, "PL": 28, "PT": 25, "QA": 29,
+ "RO": 24, "LC": 32, "SM": 27, "ST": 25,
+ "SA": 24, "SN": 28, "RS": 22, "SC": 31,
+ "SK": 24, "SI": 19, "ES": 24, "CH": 21,
+ "TL": 23, "TN": 24, "TR": 26, "UA": 29,
+ "AE": 23, "GB": 22, "SE": 24
+ }
+
+ # Normalize input data to remove whitespace
+ data = data.replace(" ", "")
+
+ # Extract alphanumeric characters of lengths ranging from 15 to 32
+ # and starting with two characters
+ matches = re.findall("[A-Za-z]{2}[A-Za-z0-9]{13,30}", data)
+
+ for match in matches:
+ iban = match.upper()
+
+ countryCode = iban[0:2]
+
+ if countryCode not in ibanCountryLengths.keys():
+ continue
+
+ if len(iban) != ibanCountryLengths[countryCode]:
+ continue
+
+ # Convert IBAN to integer format.
+ # Move the first 4 characters to the end of the string,
+ # then convert all characters to integers; where A = 10, B = 11, ...., Z = 35
+ iban_int = iban[4:] + iban[0:4]
+ for character in iban_int:
+ if character.isalpha():
+ iban_int = iban_int.replace(character, str((ord(character) - 65) + 10))
+
+ # Check IBAN integer mod 97 for remainder
+ if int(iban_int) % 97 != 1:
+ continue
+
+ ibans.add(iban)
+
+ return list(ibans)
+
+ @staticmethod
+ def extractCreditCardsFromText(data: str) -> list:
+ """Find all credit card numbers with the supplied content.
+
+ Extracts numbers with lengths ranging from 13 - 19 digits
+
+ Checks the numbers using Luhn's algorithm to verify
+ if the number is a valid credit card number or not
+
+ Args:
+ data (str): text to search for credit card numbers
+
+ Returns:
+ list: list of credit card numbers
+ """
+ if not isinstance(data, str):
+ return list()
+
+ creditCards = set()
+
+ # Remove whitespace from data.
+ # Credit cards might contain spaces between them
+ # which will cause regex mismatch
+ data = data.replace(" ", "")
+
+ # Extract all numbers with lengths ranging from 13 - 19 digits
+ matches = re.findall(r"[0-9]{13,19}", data)
+
+ # Verify each extracted number using Luhn's algorithm
+ for match in matches:
+ if int(match) == 0:
+ continue
+
+ ccNumber = match
+
+ ccNumberTotal = 0
+ isSecondDigit = False
+
+ for digit in ccNumber[::-1]:
+ d = int(digit)
+ if isSecondDigit:
+ d *= 2
+ ccNumberTotal += int(d / 10)
+ ccNumberTotal += d % 10
+
+ isSecondDigit = not isSecondDigit
+ if ccNumberTotal % 10 == 0:
+ creditCards.add(match)
+ return list(creditCards)
+
+ @staticmethod
+ def extractUrlsFromText(content: str) -> list:
+ """Extract all URLs from a string.
+
+ Args:
+ content (str): text to search for URLs
+
+ Returns:
+ list: list of identified URLs
+ """
+ if not isinstance(content, str):
+ return []
+
+ # https://tools.ietf.org/html/rfc3986#section-3.3
+ return re.findall(r"(https?://[a-zA-Z0-9-\.:]+/[\-\._~!\$&'\(\)\*\+\,\;=:@/a-zA-Z0-9]*)", html.unescape(content))
+
+ @staticmethod
+ def countryNameFromCountryCode(countryCode: str) -> str:
+ """Convert a country code to full country name.
+
+ Args:
+ countryCode (str): country code
+
+ Returns:
+ str: country name
+ """
+ if not isinstance(countryCode, str):
+ return None
+
+ return SpiderFootHelpers.countryCodes().get(countryCode.upper())
+
+ @staticmethod
+ def countryNameFromTld(tld: str) -> str:
+ """Retrieve the country name associated with a TLD.
+
+ Args:
+ tld (str): Top level domain
+
+ Returns:
+ str: country name
+ """
+ if not isinstance(tld, str):
+ return None
+
+ country_name = SpiderFootHelpers.countryCodes().get(tld.upper())
+
+ if country_name:
+ return country_name
+
+ country_tlds = {
+ # List of TLD not associated with any country
+ "COM": "United States",
+ "NET": "United States",
+ "ORG": "United States",
+ "GOV": "United States",
+ "MIL": "United States"
+ }
+
+ country_name = country_tlds.get(tld.upper())
+
+ if country_name:
+ return country_name
+
+ return None
+
+ @staticmethod
+ def countryCodes() -> dict:
+ """Dictionary of country codes and associated country names.
+
+ Returns:
+ dict: country codes and associated country names
+ """
+
+ return {
+ "AF": "Afghanistan",
+ "AX": "Aland Islands",
+ "AL": "Albania",
+ "DZ": "Algeria",
+ "AS": "American Samoa",
+ "AD": "Andorra",
+ "AO": "Angola",
+ "AI": "Anguilla",
+ "AQ": "Antarctica",
+ "AG": "Antigua and Barbuda",
+ "AR": "Argentina",
+ "AM": "Armenia",
+ "AW": "Aruba",
+ "AU": "Australia",
+ "AT": "Austria",
+ "AZ": "Azerbaijan",
+ "BS": "Bahamas",
+ "BH": "Bahrain",
+ "BD": "Bangladesh",
+ "BB": "Barbados",
+ "BY": "Belarus",
+ "BE": "Belgium",
+ "BZ": "Belize",
+ "BJ": "Benin",
+ "BM": "Bermuda",
+ "BT": "Bhutan",
+ "BO": "Bolivia",
+ "BQ": "Bonaire, Saint Eustatius and Saba",
+ "BA": "Bosnia and Herzegovina",
+ "BW": "Botswana",
+ "BV": "Bouvet Island",
+ "BR": "Brazil",
+ "IO": "British Indian Ocean Territory",
+ "VG": "British Virgin Islands",
+ "BN": "Brunei",
+ "BG": "Bulgaria",
+ "BF": "Burkina Faso",
+ "BI": "Burundi",
+ "KH": "Cambodia",
+ "CM": "Cameroon",
+ "CA": "Canada",
+ "CV": "Cape Verde",
+ "KY": "Cayman Islands",
+ "CF": "Central African Republic",
+ "TD": "Chad",
+ "CL": "Chile",
+ "CN": "China",
+ "CX": "Christmas Island",
+ "CC": "Cocos Islands",
+ "CO": "Colombia",
+ "KM": "Comoros",
+ "CK": "Cook Islands",
+ "CR": "Costa Rica",
+ "HR": "Croatia",
+ "CU": "Cuba",
+ "CW": "Curacao",
+ "CY": "Cyprus",
+ "CZ": "Czech Republic",
+ "CD": "Democratic Republic of the Congo",
+ "DK": "Denmark",
+ "DJ": "Djibouti",
+ "DM": "Dominica",
+ "DO": "Dominican Republic",
+ "TL": "East Timor",
+ "EC": "Ecuador",
+ "EG": "Egypt",
+ "SV": "El Salvador",
+ "GQ": "Equatorial Guinea",
+ "ER": "Eritrea",
+ "EE": "Estonia",
+ "ET": "Ethiopia",
+ "FK": "Falkland Islands",
+ "FO": "Faroe Islands",
+ "FJ": "Fiji",
+ "FI": "Finland",
+ "FR": "France",
+ "GF": "French Guiana",
+ "PF": "French Polynesia",
+ "TF": "French Southern Territories",
+ "GA": "Gabon",
+ "GM": "Gambia",
+ "GE": "Georgia",
+ "DE": "Germany",
+ "GH": "Ghana",
+ "GI": "Gibraltar",
+ "GR": "Greece",
+ "GL": "Greenland",
+ "GD": "Grenada",
+ "GP": "Guadeloupe",
+ "GU": "Guam",
+ "GT": "Guatemala",
+ "GG": "Guernsey",
+ "GN": "Guinea",
+ "GW": "Guinea-Bissau",
+ "GY": "Guyana",
+ "HT": "Haiti",
+ "HM": "Heard Island and McDonald Islands",
+ "HN": "Honduras",
+ "HK": "Hong Kong",
+ "HU": "Hungary",
+ "IS": "Iceland",
+ "IN": "India",
+ "ID": "Indonesia",
+ "IR": "Iran",
+ "IQ": "Iraq",
+ "IE": "Ireland",
+ "IM": "Isle of Man",
+ "IL": "Israel",
+ "IT": "Italy",
+ "CI": "Ivory Coast",
+ "JM": "Jamaica",
+ "JP": "Japan",
+ "JE": "Jersey",
+ "JO": "Jordan",
+ "KZ": "Kazakhstan",
+ "KE": "Kenya",
+ "KI": "Kiribati",
+ "XK": "Kosovo",
+ "KW": "Kuwait",
+ "KG": "Kyrgyzstan",
+ "LA": "Laos",
+ "LV": "Latvia",
+ "LB": "Lebanon",
+ "LS": "Lesotho",
+ "LR": "Liberia",
+ "LY": "Libya",
+ "LI": "Liechtenstein",
+ "LT": "Lithuania",
+ "LU": "Luxembourg",
+ "MO": "Macao",
+ "MK": "Macedonia",
+ "MG": "Madagascar",
+ "MW": "Malawi",
+ "MY": "Malaysia",
+ "MV": "Maldives",
+ "ML": "Mali",
+ "MT": "Malta",
+ "MH": "Marshall Islands",
+ "MQ": "Martinique",
+ "MR": "Mauritania",
+ "MU": "Mauritius",
+ "YT": "Mayotte",
+ "MX": "Mexico",
+ "FM": "Micronesia",
+ "MD": "Moldova",
+ "MC": "Monaco",
+ "MN": "Mongolia",
+ "ME": "Montenegro",
+ "MS": "Montserrat",
+ "MA": "Morocco",
+ "MZ": "Mozambique",
+ "MM": "Myanmar",
+ "NA": "Namibia",
+ "NR": "Nauru",
+ "NP": "Nepal",
+ "NL": "Netherlands",
+ "AN": "Netherlands Antilles",
+ "NC": "New Caledonia",
+ "NZ": "New Zealand",
+ "NI": "Nicaragua",
+ "NE": "Niger",
+ "NG": "Nigeria",
+ "NU": "Niue",
+ "NF": "Norfolk Island",
+ "KP": "North Korea",
+ "MP": "Northern Mariana Islands",
+ "NO": "Norway",
+ "OM": "Oman",
+ "PK": "Pakistan",
+ "PW": "Palau",
+ "PS": "Palestinian Territory",
+ "PA": "Panama",
+ "PG": "Papua New Guinea",
+ "PY": "Paraguay",
+ "PE": "Peru",
+ "PH": "Philippines",
+ "PN": "Pitcairn",
+ "PL": "Poland",
+ "PT": "Portugal",
+ "PR": "Puerto Rico",
+ "QA": "Qatar",
+ "CG": "Republic of the Congo",
+ "RE": "Reunion",
+ "RO": "Romania",
+ "RU": "Russia",
+ "RW": "Rwanda",
+ "BL": "Saint Barthelemy",
+ "SH": "Saint Helena",
+ "KN": "Saint Kitts and Nevis",
+ "LC": "Saint Lucia",
+ "MF": "Saint Martin",
+ "PM": "Saint Pierre and Miquelon",
+ "VC": "Saint Vincent and the Grenadines",
+ "WS": "Samoa",
+ "SM": "San Marino",
+ "ST": "Sao Tome and Principe",
+ "SA": "Saudi Arabia",
+ "SN": "Senegal",
+ "RS": "Serbia",
+ "CS": "Serbia and Montenegro",
+ "SC": "Seychelles",
+ "SL": "Sierra Leone",
+ "SG": "Singapore",
+ "SX": "Sint Maarten",
+ "SK": "Slovakia",
+ "SI": "Slovenia",
+ "SB": "Solomon Islands",
+ "SO": "Somalia",
+ "ZA": "South Africa",
+ "GS": "South Georgia and the South Sandwich Islands",
+ "KR": "South Korea",
+ "SS": "South Sudan",
+ "ES": "Spain",
+ "LK": "Sri Lanka",
+ "SD": "Sudan",
+ "SR": "Suriname",
+ "SJ": "Svalbard and Jan Mayen",
+ "SZ": "Swaziland",
+ "SE": "Sweden",
+ "CH": "Switzerland",
+ "SY": "Syria",
+ "TW": "Taiwan",
+ "TJ": "Tajikistan",
+ "TZ": "Tanzania",
+ "TH": "Thailand",
+ "TG": "Togo",
+ "TK": "Tokelau",
+ "TO": "Tonga",
+ "TT": "Trinidad and Tobago",
+ "TN": "Tunisia",
+ "TR": "Turkey",
+ "TM": "Turkmenistan",
+ "TC": "Turks and Caicos Islands",
+ "TV": "Tuvalu",
+ "VI": "U.S. Virgin Islands",
+ "UG": "Uganda",
+ "UA": "Ukraine",
+ "AE": "United Arab Emirates",
+ "GB": "United Kingdom",
+ "US": "United States",
+ "UM": "United States Minor Outlying Islands",
+ "UY": "Uruguay",
+ "UZ": "Uzbekistan",
+ "VU": "Vanuatu",
+ "VA": "Vatican",
+ "VE": "Venezuela",
+ "VN": "Vietnam",
+ "WF": "Wallis and Futuna",
+ "EH": "Western Sahara",
+ "YE": "Yemen",
+ "ZM": "Zambia",
+ "ZW": "Zimbabwe",
+ # Below are not country codes but recognized as regions / TLDs
+ "AC": "Ascension Island",
+ "EU": "European Union",
+ "SU": "Soviet Union",
+ "UK": "United Kingdom"
+ }
+
+ @staticmethod
+ def sanitiseInput(cmd: str, extra: list = None) -> bool:
"""Verify input command is safe to execute
Args:
@@ -498,6 +1188,9 @@ class SpiderFootHelpers():
Returns:
bool: command is "safe"
"""
+ if not extra:
+ extra = []
+
chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '.']
diff --git a/test/integration/test_sfwebui.py b/test/integration/test_sfwebui.py
index 7f957dc5..139ea268 100644
--- a/test/integration/test_sfwebui.py
+++ b/test/integration/test_sfwebui.py
@@ -38,7 +38,7 @@ class TestSpiderFootWebUiRoutes(helper.CPWebCase):
sf = SpiderFoot(default_config)
mod_dir = sf.myPath() + '/modules/'
- default_config['__modules__'] = SpiderFootHelpers.loadModulesAsDict(mod_dir)
+ default_config['__modules__'] = SpiderFootHelpers.loadModulesAsDict(mod_dir, ['sfp_template.py'])
conf = {
'/query': {
diff --git a/test/unit/spiderfoot/test_spiderfootdb.py b/test/unit/spiderfoot/test_spiderfootdb.py
index db3949a0..7ee69245 100644
--- a/test/unit/spiderfoot/test_spiderfootdb.py
+++ b/test/unit/spiderfoot/test_spiderfootdb.py
@@ -1248,3 +1248,36 @@ class TestSpiderFootDb(unittest.TestCase):
with self.subTest(invalid_type=invalid_type):
with self.assertRaises(TypeError):
sfdb.scanElementChildrenAll(instance_id, invalid_type)
+
+ def test_correlationResultCreate_arguments_of_invalid_type_should_raise_TypeError(self):
+ sfdb = SpiderFootDb(self.default_options, False)
+
+ invalid_types = [None, list(), dict(), int()]
+ for invalid_type in invalid_types:
+ with self.subTest(invalid_type=invalid_type):
+ with self.assertRaises(TypeError):
+ sfdb.correlationResultCreate(invalid_type, "", "", "", "", "", "", [])
+
+ with self.subTest(invalid_type=invalid_type):
+ with self.assertRaises(TypeError):
+ sfdb.correlationResultCreate("", invalid_type, "", "", "", "", "", [])
+
+ with self.subTest(invalid_type=invalid_type):
+ with self.assertRaises(TypeError):
+ sfdb.correlationResultCreate("", "", invalid_type, "", "", "", "", [])
+
+ with self.subTest(invalid_type=invalid_type):
+ with self.assertRaises(TypeError):
+ sfdb.correlationResultCreate("", "", "", invalid_type, "", "", "", [])
+
+ with self.subTest(invalid_type=invalid_type):
+ with self.assertRaises(TypeError):
+ sfdb.correlationResultCreate("", "", "", "", invalid_type, "", "", [])
+
+ with self.subTest(invalid_type=invalid_type):
+ with self.assertRaises(TypeError):
+ sfdb.correlationResultCreate("", "", "", "", "", invalid_type, "", [])
+
+ with self.subTest(invalid_type=invalid_type):
+ with self.assertRaises(TypeError):
+ sfdb.correlationResultCreate("", "", "", "", "", "", invalid_type, [])
diff --git a/test/unit/spiderfoot/test_spiderfoothelpers.py b/test/unit/spiderfoot/test_spiderfoothelpers.py
index 2d24c535..c9969942 100644
--- a/test/unit/spiderfoot/test_spiderfoothelpers.py
+++ b/test/unit/spiderfoot/test_spiderfoothelpers.py
@@ -70,6 +70,21 @@ class TestSpiderFootHelpers(unittest.TestCase):
target_type = SpiderFootHelpers.targetTypeFromString('""')
self.assertEqual(None, target_type)
+ def test_urlRelativeToAbsolute_argument_url_relative_path_should_return_an_absolute_path(self):
+ relative_url = SpiderFootHelpers.urlRelativeToAbsolute('/somewhere/else/../../path?param=value#fragment')
+ self.assertIsInstance(relative_url, str)
+ self.assertEqual('/path?param=value#fragment', relative_url)
+
+ def test_url_base_dir_should_return_a_string(self):
+ base_dir = SpiderFootHelpers.urlBaseDir('http://localhost.local/path?param=value#fragment')
+ self.assertIsInstance(base_dir, str)
+ self.assertEqual('http://localhost.local/', base_dir)
+
+ def test_url_base_url_should_return_a_string(self):
+ base_url = SpiderFootHelpers.urlBaseUrl('http://localhost.local/path?param=value#fragment')
+ self.assertIsInstance(base_url, str)
+ self.assertEqual('http://localhost.local', base_url)
+
def test_buildGraphData_invalid_data_type_should_raise_TypeError(self):
"""
Test buildGraphData(data, flt=list())
@@ -157,10 +172,76 @@ class TestSpiderFootHelpers(unittest.TestCase):
scan_instance_id = SpiderFootHelpers.genScanInstanceId()
self.assertIsInstance(scan_instance_id, str)
+ def test_extractHashesFromText_should_return_a_list(self):
+ invalid_types = [None, list(), dict(), int()]
+ for invalid_type in invalid_types:
+ with self.subTest(invalid_type=invalid_type):
+ hashes = SpiderFootHelpers.extractHashesFromText(invalid_type)
+ self.assertIsInstance(hashes, list)
+
+ def test_extractHashesFromText_argument_data_should_return_hahes(self):
+ md5_hash = "e17cff4eb3e8fbe6ca3b83fb47532dba"
+ sha1_hash = "f81efbe70f8116fcf3dc4e9b37725dcb949719f5"
+ sha256_hash = "7cd444af3d8de9e195b1f1cb55e7b7d9409dcd4648247c853a2f64b7578dc9b7"
+ sha512_hash = "a55a2fe120d7d7d6e2ba930e6c56faa30b9d24a3178a0aff1d89312a89d61d8a9d5b7743e3af6b1a318d99974a1145ed76f85aa8c6574074dfb347613ccd3249"
+
+ hashes = SpiderFootHelpers.extractHashesFromText(f"spiderfoot{md5_hash}spiderfoot{sha1_hash}spiderfoot{sha256_hash}spiderfoot{sha512_hash}spiderfoot")
+
+ self.assertIsInstance(hashes, list)
+ self.assertIn(("MD5", md5_hash), hashes)
+ self.assertIn(("SHA1", sha1_hash), hashes)
+ self.assertIn(("SHA256", sha256_hash), hashes)
+ self.assertIn(("SHA512", sha512_hash), hashes)
+
+ def test_valid_email_should_return_a_boolean(self):
+ invalid_types = [None, "", list(), dict()]
+ for invalid_type in invalid_types:
+ with self.subTest(invalid_type=invalid_type):
+ valid_email = SpiderFootHelpers.validEmail(invalid_type)
+ self.assertIsInstance(valid_email, bool)
+ self.assertFalse(valid_email)
+
+ valid_email = SpiderFootHelpers.validEmail('%@localhost.local')
+ self.assertIsInstance(valid_email, bool)
+ self.assertFalse(valid_email)
+
+ valid_email = SpiderFootHelpers.validEmail('[email protected]')
+ self.assertIsInstance(valid_email, bool)
+ self.assertFalse(valid_email)
+
+ valid_email = SpiderFootHelpers.validEmail('[email protected]\n.com')
+ self.assertIsInstance(valid_email, bool)
+ self.assertFalse(valid_email)
+
+ valid_email = SpiderFootHelpers.validEmail('root@localhost')
+ self.assertIsInstance(valid_email, bool)
+ self.assertFalse(valid_email)
+
+ valid_email = SpiderFootHelpers.validEmail('[email protected]')
+ self.assertIsInstance(valid_email, bool)
+ self.assertTrue(valid_email)
+
+ def test_validPhoneNumber_should_return_a_boolean(self):
+ invalid_types = [None, "", list(), dict(), int()]
+ for invalid_type in invalid_types:
+ with self.subTest(invalid_type=invalid_type):
+ valid_phone = SpiderFootHelpers.validPhoneNumber(invalid_type)
+ self.assertIsInstance(valid_phone, bool)
+ self.assertFalse(valid_phone)
+
+ valid_phone = SpiderFootHelpers.validPhoneNumber('+1234567890')
+ self.assertIsInstance(valid_phone, bool)
+ self.assertFalse(valid_phone)
+
+ valid_phone = SpiderFootHelpers.validPhoneNumber('+12345678901234567890')
+ self.assertIsInstance(valid_phone, bool)
+ self.assertFalse(valid_phone)
+
+ valid_phone = SpiderFootHelpers.validPhoneNumber('+12345678901')
+ self.assertIsInstance(valid_phone, bool)
+ self.assertTrue(valid_phone)
+
def test_validLEI_should_return_a_boolean(self):
- """
- Test validLEI(lei)
- """
invalid_types = [None, "", list(), dict(), int()]
for invalid_type in invalid_types:
with self.subTest(invalid_type=invalid_type):
@@ -176,21 +257,179 @@ class TestSpiderFootHelpers(unittest.TestCase):
self.assertIsInstance(valid_lei, bool)
self.assertTrue(valid_lei)
- def test_parse_robots_txt_should_return_list(self):
- """
- Test parseRobotsTxt(robotsTxtData)
- """
+ def test_countryCodes_should_return_a_dict(self):
+ country_code_dict = SpiderFootHelpers.countryCodes()
+ self.assertIsInstance(country_code_dict, dict)
+
+ def test_countryNameFromCountryCode_argument_countryCode_should_return_country_as_a_string(self):
+ country_name = SpiderFootHelpers.countryNameFromCountryCode('US')
+ self.assertIsInstance(country_name, str)
+ self.assertEqual(country_name, "United States")
+
+ def test_countryNameFromTld_argument_tld_should_return_country_as_a_string(self):
+ tlds = ['com', 'net', 'org', 'gov', 'mil']
+ for tld in tlds:
+ with self.subTest(tld=tld):
+ country_name = SpiderFootHelpers.countryNameFromTld(tld)
+ self.assertIsInstance(country_name, str)
+ self.assertEqual(country_name, "United States")
+
+ def test_extractEmailsFromText_should_return_list_of_emails_from_string(self):
+ emails = SpiderFootHelpers.extractEmailsFromText("<html><body><p>From:[email protected]</p><p>Subject:Hello [email protected], here's some text</p></body></html>")
+ self.assertIsInstance(emails, list)
+ self.assertIn('[email protected]', emails)
+ self.assertIn('[email protected]', emails)
+
+ def test_extractEmailsFromText_invalid_data_should_return_list(self):
+ invalid_types = [None, "", list(), dict()]
+ for invalid_type in invalid_types:
+ with self.subTest(invalid_type=invalid_type):
+ emails = SpiderFootHelpers.extractEmailsFromText(invalid_type)
+ self.assertIsInstance(emails, list)
+
+ def test_extractIbansFromText_should_return_a_list(self):
+ invalid_types = [None, "", list(), dict()]
+ for invalid_type in invalid_types:
+ with self.subTest(invalid_type=invalid_type):
+ ibans = SpiderFootHelpers.extractIbansFromText(invalid_type)
+ self.assertIsInstance(ibans, list)
+
+ # Example IBANS from https://www.iban.com/structure
+ ibans = [
+ "AL35202111090000000001234567",
+ "AD1400080001001234567890",
+ "AT483200000012345864",
+ "AZ96AZEJ00000000001234567890",
+ "BH02CITI00001077181611",
+ "BY86AKBB10100000002966000000",
+ "BE71096123456769",
+ "BA393385804800211234",
+ "BR1500000000000010932840814P2",
+ "BG18RZBB91550123456789",
+ "CR23015108410026012345",
+ "HR1723600001101234565",
+ "CY21002001950000357001234567",
+ "CZ5508000000001234567899",
+ "DK9520000123456789",
+ "DO22ACAU00000000000123456789",
+ "EG800002000156789012345180002",
+ "SV43ACAT00000000000000123123",
+ "EE471000001020145685",
+ "FO9264600123456789",
+ "FI1410093000123458",
+ "FR7630006000011234567890189",
+ "GE60NB0000000123456789",
+ "DE75512108001245126199",
+ "GI04BARC000001234567890",
+ "GR9608100010000001234567890",
+ "GL8964710123456789",
+ "GT20AGRO00000000001234567890",
+ "VA59001123000012345678",
+ "HU93116000060000000012345676",
+ "IS750001121234563108962099",
+ "IQ20CBIQ861800101010500",
+ "IE64IRCE92050112345678",
+ "IL170108000000012612345",
+ "IT60X0542811101000000123456",
+ "JO71CBJO0000000000001234567890",
+ "KZ563190000012344567",
+ "XK051212012345678906",
+ "KW81CBKU0000000000001234560101",
+ "LV97HABA0012345678910",
+ "LB92000700000000123123456123",
+ "LI7408806123456789012",
+ "LT601010012345678901",
+ "LU120010001234567891",
+ "MT31MALT01100000000000000000123",
+ "MR1300020001010000123456753",
+ "MU43BOMM0101123456789101000MUR",
+ "MD21EX000000000001234567",
+ "MC5810096180790123456789085",
+ "ME25505000012345678951",
+ "NL02ABNA0123456789",
+ "MK07200002785123453",
+ "NO8330001234567",
+ "PK36SCBL0000001123456702",
+ "PS92PALS000000000400123456702",
+ "PL10105000997603123456789123",
+ "PT50002700000001234567833",
+ "QA54QNBA000000000000693123456",
+ "RO09BCYP0000001234567890",
+ "LC14BOSL123456789012345678901234",
+ "SM76P0854009812123456789123",
+ "ST23000200000289355710148",
+ "SA4420000001234567891234",
+ "RS35105008123123123173",
+ "SC52BAHL01031234567890123456USD",
+ "SK8975000000000012345671",
+ "SI56192001234567892",
+ "ES7921000813610123456789",
+ "SE7280000810340009783242",
+ "CH5604835012345678009",
+ "TL380010012345678910106",
+ "TN5904018104004942712345",
+ "TR320010009999901234567890",
+ "UA903052992990004149123456789",
+ "AE460090000000123456789",
+ "GB33BUKB20201555555555",
+ "VG21PACG0000000123456789"
+ ]
+ for iban in ibans:
+ with self.subTest(iban=iban):
+ extract_ibans = SpiderFootHelpers.extractIbansFromText(iban)
+ self.assertIsInstance(extract_ibans, list)
+ self.assertIn(iban, extract_ibans)
+
+ # Invalid IBANs
+ ibans = [
+ # Invalid country code
+ "ZZ21PACG0000000123456789",
+ # Invalid length for country code
+ "VG123456789012345",
+ # Invalid mod 97 remainder
+ "VG21PACG0000000123456111"
+ ]
+ for iban in ibans:
+ with self.subTest(iban=iban):
+ extract_ibans = SpiderFootHelpers.extractIbansFromText(iban)
+ self.assertIsInstance(extract_ibans, list)
+ self.assertNotIn(iban, extract_ibans)
+
+ def test_extractCreditCardsFromText_should_return_a_list(self):
+ invalid_types = [None, "", list(), dict()]
+ for invalid_type in invalid_types:
+ with self.subTest(invalid_type=invalid_type):
+ cards = SpiderFootHelpers.extractCreditCardsFromText(invalid_type)
+ self.assertIsInstance(cards, list)
+
+ cards = SpiderFootHelpers.extractCreditCardsFromText("spiderfoot4111 1111 1111 1111spiderfoot")
+ self.assertIsInstance(cards, list)
+ self.assertEqual(["4111111111111111"], cards)
+
+ def test_extractUrlsFromText_should_extract_urls_from_string(self):
+ invalid_types = [None, "", list(), dict()]
+ for invalid_type in invalid_types:
+ with self.subTest(invalid_type=invalid_type):
+ cards = SpiderFootHelpers.extractUrlsFromText(invalid_type)
+ self.assertIsInstance(cards, list)
+
+ urls = SpiderFootHelpers.extractUrlsFromText("abchttps://example.spiderfoot.net/path\rabchttp://example.spiderfoot.net:1337/path\rabc")
+ self.assertIsInstance(urls, list)
+ self.assertIn("https://example.spiderfoot.net/path", urls)
+ self.assertIn("http://example.spiderfoot.net:1337/path", urls)
+
+ def test_extractUrlsFromRobotsTxt_should_return_list(self):
invalid_types = [None, "", list(), dict()]
for invalid_type in invalid_types:
with self.subTest(invalid_type=invalid_type):
- robots_txt = SpiderFootHelpers.parseRobotsTxt(invalid_type)
+ robots_txt = SpiderFootHelpers.extractUrlsFromRobotsTxt(invalid_type)
self.assertIsInstance(robots_txt, list)
- robots_txt = SpiderFootHelpers.parseRobotsTxt("disallow:")
+ robots_txt = SpiderFootHelpers.extractUrlsFromRobotsTxt("disallow:")
self.assertIsInstance(robots_txt, list)
self.assertFalse(robots_txt)
- robots_txt = SpiderFootHelpers.parseRobotsTxt("disallow: /disallowed/path\n")
+ robots_txt = SpiderFootHelpers.extractUrlsFromRobotsTxt("disallow: /disallowed/path\n")
self.assertIsInstance(robots_txt, list)
self.assertIn("/disallowed/path", robots_txt)
diff --git a/test/unit/test_modules.py b/test/unit/test_modules.py
index e76ef27c..3805725b 100644
--- a/test/unit/test_modules.py
+++ b/test/unit/test_modules.py
@@ -16,7 +16,7 @@ class TestSpiderFootModuleLoading(unittest.TestCase):
@staticmethod
def load_modules(sf):
mod_dir = sf.myPath() + '/modules/'
- return SpiderFootHelpers.loadModulesAsDict(mod_dir)
+ return SpiderFootHelpers.loadModulesAsDict(mod_dir, ['sfp_template.py'])
def test_module_use_cases_are_valid(self):
sf = SpiderFoot(self.default_options)
diff --git a/test/unit/test_spiderfoot.py b/test/unit/test_spiderfoot.py
index d39a1f19..433924bb 100644
--- a/test/unit/test_spiderfoot.py
+++ b/test/unit/test_spiderfoot.py
@@ -327,36 +327,6 @@ class TestSpiderFoot(unittest.TestCase):
events_to_modules = sf.eventsToModules(self.default_modules)
self.assertIsInstance(events_to_modules, list)
- def test_url_relative_to_absolute_should_return_a_string(self):
- """
- Test urlRelativeToAbsolute(self, url)
- """
- sf = SpiderFoot(dict())
-
- relative_url = sf.urlRelativeToAbsolute('/somewhere/else/../../path?param=value#fragment')
- self.assertIsInstance(relative_url, str)
- self.assertEqual('/path?param=value#fragment', relative_url)
-
- def test_url_base_dir_should_return_a_string(self):
- """
- Test urlBaseDir(self, url)
- """
- sf = SpiderFoot(dict())
-
- base_dir = sf.urlBaseDir('http://localhost.local/path?param=value#fragment')
- self.assertIsInstance(base_dir, str)
- self.assertEqual('http://localhost.local/', base_dir)
-
- def test_url_base_url_should_return_a_string(self):
- """
- Test urlBaseUrl(self, url)
- """
- sf = SpiderFoot(dict())
-
- base_url = sf.urlBaseUrl('http://localhost.local/path?param=value#fragment')
- self.assertIsInstance(base_url, str)
- self.assertEqual('http://localhost.local', base_url)
-
def test_url_fqdn_should_return_a_string(self):
"""
Test urlFQDN(self, url)
@@ -641,64 +611,6 @@ class TestSpiderFoot(unittest.TestCase):
with self.subTest(ip=ip):
self.assertFalse(sf.isPublicIpAddress(ip))
- def test_valid_email_should_return_a_boolean(self):
- """
- Test validEmail(self, email)
- """
- sf = SpiderFoot(dict())
-
- invalid_types = [None, "", list(), dict()]
- for invalid_type in invalid_types:
- with self.subTest(invalid_type=invalid_type):
- valid_email = sf.validEmail(invalid_type)
- self.assertIsInstance(valid_email, bool)
- self.assertFalse(valid_email)
-
- valid_email = sf.validEmail('%@localhost.local')
- self.assertIsInstance(valid_email, bool)
- self.assertFalse(valid_email)
-
- valid_email = sf.validEmail('[email protected]')
- self.assertIsInstance(valid_email, bool)
- self.assertFalse(valid_email)
-
- valid_email = sf.validEmail('[email protected]\n.com')
- self.assertIsInstance(valid_email, bool)
- self.assertFalse(valid_email)
-
- valid_email = sf.validEmail('root@localhost')
- self.assertIsInstance(valid_email, bool)
- self.assertFalse(valid_email)
-
- valid_email = sf.validEmail('[email protected]')
- self.assertIsInstance(valid_email, bool)
- self.assertTrue(valid_email)
-
- def test_validPhoneNumber_should_return_a_boolean(self):
- """
- Test validPhoneNumber(self, phone)
- """
- sf = SpiderFoot(dict())
-
- invalid_types = [None, "", list(), dict(), int()]
- for invalid_type in invalid_types:
- with self.subTest(invalid_type=invalid_type):
- valid_phone = sf.validPhoneNumber(invalid_type)
- self.assertIsInstance(valid_phone, bool)
- self.assertFalse(valid_phone)
-
- valid_phone = sf.validPhoneNumber('+1234567890')
- self.assertIsInstance(valid_phone, bool)
- self.assertFalse(valid_phone)
-
- valid_phone = sf.validPhoneNumber('+12345678901234567890')
- self.assertIsInstance(valid_phone, bool)
- self.assertFalse(valid_phone)
-
- valid_phone = sf.validPhoneNumber('+12345678901')
- self.assertIsInstance(valid_phone, bool)
- self.assertTrue(valid_phone)
-
def test_normalize_dns(self):
"""
Test normalizeDNS(self, res)
@@ -827,221 +739,6 @@ class TestSpiderFoot(unittest.TestCase):
sf.safeSSLSocket(None, None, None, None)
self.assertEqual('TBD', 'TBD')
- def test_parseHashes_should_return_a_list(self):
- """
- Test parseHashes(self, data)
- """
- sf = SpiderFoot(self.default_options)
-
- invalid_types = [None, "", list(), dict(), int()]
- for invalid_type in invalid_types:
- with self.subTest(invalid_type=invalid_type):
- hashes = sf.parseHashes(invalid_type)
- self.assertIsInstance(hashes, list)
-
- def test_parseHashes_argument_data_should_return_hahes(self):
- """
- Test parseHashes(self, data)
- """
- sf = SpiderFoot(self.default_options)
-
- md5_hash = "e17cff4eb3e8fbe6ca3b83fb47532dba"
- sha1_hash = "f81efbe70f8116fcf3dc4e9b37725dcb949719f5"
- sha256_hash = "7cd444af3d8de9e195b1f1cb55e7b7d9409dcd4648247c853a2f64b7578dc9b7"
- sha512_hash = "a55a2fe120d7d7d6e2ba930e6c56faa30b9d24a3178a0aff1d89312a89d61d8a9d5b7743e3af6b1a318d99974a1145ed76f85aa8c6574074dfb347613ccd3249"
-
- hashes = sf.parseHashes(f"spiderfoot{md5_hash}spiderfoot{sha1_hash}spiderfoot{sha256_hash}spiderfoot{sha512_hash}spiderfoot")
-
- self.assertIsInstance(hashes, list)
- self.assertIn(("MD5", md5_hash), hashes)
- self.assertIn(("SHA1", sha1_hash), hashes)
- self.assertIn(("SHA256", sha256_hash), hashes)
- self.assertIn(("SHA512", sha512_hash), hashes)
-
- def test_parse_credit_cards_should_return_a_list(self):
- """
- Test parseCreditCards(self, data)
- """
- sf = SpiderFoot(self.default_options)
-
- invalid_types = [None, "", list(), dict()]
- for invalid_type in invalid_types:
- with self.subTest(invalid_type=invalid_type):
- cards = sf.parseCreditCards(invalid_type)
- self.assertIsInstance(cards, list)
-
- cards = sf.parseCreditCards("spiderfoot4111 1111 1111 1111spiderfoot")
- self.assertIsInstance(cards, list)
- self.assertIn("4111111111111111", cards)
-
- def test_getCountryCodeDict_should_return_a_dict(self):
- """
- Test getCountryCodeDict(self)
- """
- sf = SpiderFoot(dict())
-
- country_code_dict = sf.getCountryCodeDict()
- self.assertIsInstance(country_code_dict, dict)
-
- def test_countryNameFromCountryCode_argument_countryCode_should_return_country_as_a_string(self):
- """
- Test countryNameFromCountryCode(self, countryCode)
- """
- sf = SpiderFoot(dict())
-
- country_name = sf.countryNameFromCountryCode('US')
- self.assertIsInstance(country_name, str)
- self.assertEqual(country_name, "United States")
-
- def test_countryNameFromTld_argument_tld_should_return_country_as_a_string(self):
- """
- Test countryNameFromTld(self, tld)
- """
- sf = SpiderFoot(dict())
-
- tlds = ['com', 'net', 'org', 'gov', 'mil']
- for tld in tlds:
- with self.subTest(tld=tld):
- country_name = sf.countryNameFromTld(tld)
- self.assertIsInstance(country_name, str)
- self.assertEqual(country_name, "United States")
-
- def test_parse_iban_numbers_should_return_a_list(self):
- """
- Test parseIBANNumbers(self, data)
- """
- sf = SpiderFoot(self.default_options)
-
- invalid_types = [None, "", list(), dict()]
- for invalid_type in invalid_types:
- with self.subTest(invalid_type=invalid_type):
- ibans = sf.parseIBANNumbers(invalid_type)
- self.assertIsInstance(ibans, list)
-
- # Example IBANS from https://www.iban.com/structure
- ibans = [
- "AL35202111090000000001234567",
- "AD1400080001001234567890",
- "AT483200000012345864",
- "AZ96AZEJ00000000001234567890",
- "BH02CITI00001077181611",
- "BY86AKBB10100000002966000000",
- "BE71096123456769",
- "BA393385804800211234",
- "BR1500000000000010932840814P2",
- "BG18RZBB91550123456789",
- "CR23015108410026012345",
- "HR1723600001101234565",
- "CY21002001950000357001234567",
- "CZ5508000000001234567899",
- "DK9520000123456789",
- "DO22ACAU00000000000123456789",
- "EG800002000156789012345180002",
- "SV43ACAT00000000000000123123",
- "EE471000001020145685",
- "FO9264600123456789",
- "FI1410093000123458",
- "FR7630006000011234567890189",
- "GE60NB0000000123456789",
- "DE75512108001245126199",
- "GI04BARC000001234567890",
- "GR9608100010000001234567890",
- "GL8964710123456789",
- "GT20AGRO00000000001234567890",
- "VA59001123000012345678",
- "HU93116000060000000012345676",
- "IS750001121234563108962099",
- "IQ20CBIQ861800101010500",
- "IE64IRCE92050112345678",
- "IL170108000000012612345",
- "IT60X0542811101000000123456",
- "JO71CBJO0000000000001234567890",
- "KZ563190000012344567",
- "XK051212012345678906",
- "KW81CBKU0000000000001234560101",
- "LV97HABA0012345678910",
- "LB92000700000000123123456123",
- "LI7408806123456789012",
- "LT601010012345678901",
- "LU120010001234567891",
- "MT31MALT01100000000000000000123",
- "MR1300020001010000123456753",
- "MU43BOMM0101123456789101000MUR",
- "MD21EX000000000001234567",
- "MC5810096180790123456789085",
- "ME25505000012345678951",
- "NL02ABNA0123456789",
- "MK07200002785123453",
- "NO8330001234567",
- "PK36SCBL0000001123456702",
- "PS92PALS000000000400123456702",
- "PL10105000997603123456789123",
- "PT50002700000001234567833",
- "QA54QNBA000000000000693123456",
- "RO09BCYP0000001234567890",
- "LC14BOSL123456789012345678901234",
- "SM76P0854009812123456789123",
- "ST23000200000289355710148",
- "SA4420000001234567891234",
- "RS35105008123123123173",
- "SC52BAHL01031234567890123456USD",
- "SK8975000000000012345671",
- "SI56192001234567892",
- "ES7921000813610123456789",
- "SE7280000810340009783242",
- "CH5604835012345678009",
- "TL380010012345678910106",
- "TN5904018104004942712345",
- "TR320010009999901234567890",
- "UA903052992990004149123456789",
- "AE460090000000123456789",
- "GB33BUKB20201555555555",
- "VG21PACG0000000123456789"
- ]
- for iban in ibans:
- with self.subTest(iban=iban):
- parse_ibans = sf.parseIBANNumbers(iban)
- self.assertIsInstance(parse_ibans, list)
- self.assertIn(iban, parse_ibans)
-
- # Invalid IBANs
- ibans = [
- # Invalid country code
- "ZZ21PACG0000000123456789",
- # Invalid length for country code
- "VG123456789012345",
- # Invalid mod 97 remainder
- "VG21PACG0000000123456111"
- ]
- for iban in ibans:
- with self.subTest(iban=iban):
- parse_ibans = sf.parseIBANNumbers(iban)
- self.assertIsInstance(parse_ibans, list)
- self.assertNotIn(iban, parse_ibans)
-
- def test_parse_emails_should_return_list_of_emails_from_string(self):
- """
- Test parseEmails(self, data)
- """
- sf = SpiderFoot(self.default_options)
-
- parse_emails = sf.parseEmails("<html><body><p>From:[email protected]</p><p>Subject:Hello [email protected], here's some text</p></body></html>")
- self.assertIsInstance(parse_emails, list)
- self.assertIn('[email protected]', parse_emails)
- self.assertIn('[email protected]', parse_emails)
-
- def test_parse_emails_invalid_data_should_return_list(self):
- """
- Test parseEmails(self, data)
- """
- sf = SpiderFoot(self.default_options)
-
- invalid_types = [None, "", list(), dict()]
- for invalid_type in invalid_types:
- with self.subTest(invalid_type=invalid_type):
- emails = sf.parseEmails(invalid_type)
- self.assertIsInstance(emails, list)
-
@unittest.skip("todo")
def test_ssl_der_to_pem(self):
"""
@@ -1115,17 +812,6 @@ class TestSpiderFoot(unittest.TestCase):
parse_cert = sf.parseCert(None, 'spiderfoot.net', invalid_type)
self.assertEqual(None, parse_cert)
- def test_extract_urls_should_extract_urls_from_string(self):
- """
- Test extractUrls(self, content)
- """
- sf = SpiderFoot(self.default_options)
-
- urls = sf.extractUrls("abchttps://example.spiderfoot.net/path\rabchttp://example.spiderfoot.net:1337/path\rabc")
- self.assertIsInstance(urls, list)
- self.assertIn("https://example.spiderfoot.net/path", urls)
- self.assertIn("http://example.spiderfoot.net:1337/path", urls)
-
def test_parse_links_should_return_a_dict_of_urls_from_string(self):
"""
Test parseLinks(self, url, data, domains)
@@ -1243,12 +929,6 @@ class TestSpiderFoot(unittest.TestCase):
self.assertFalse(sf.useProxyForUrl(proxy_host))
def test_fetchUrl_argument_url_should_return_http_response_as_dict(self):
- """
- Test fetchUrl(self, url, fatal=False, cookies=None, timeout=30,
- useragent="SpiderFoot", headers=None, noLog=False,
- postData=None, disableContentEncoding=False, sizeLimit=None,
- headOnly=False, verify=False)
- """
sf = SpiderFoot(self.default_options)
res = sf.fetchUrl("https://spiderfoot.net/")
@@ -1257,12 +937,6 @@ class TestSpiderFoot(unittest.TestCase):
self.assertNotEqual(res['content'], None)
def test_fetchUrl_argument_headOnly_should_return_http_response_as_dict(self):
- """
- Test fetchUrl(self, url, fatal=False, cookies=None, timeout=30,
- useragent="SpiderFoot", headers=None, noLog=False,
- postData=None, disableContentEncoding=False, sizeLimit=None,
- headOnly=False, verify=False)
- """
sf = SpiderFoot(self.default_options)
res = sf.fetchUrl("https://spiderfoot.net/", headOnly=True)
@@ -1271,12 +945,6 @@ class TestSpiderFoot(unittest.TestCase):
self.assertEqual(res['content'], None)
def test_fetchUrl_argument_url_invalid_type_should_return_none(self):
- """
- Test fetchUrl(self, url, fatal=False, cookies=None, timeout=30,
- useragent="SpiderFoot", headers=None, noLog=False,
- postData=None, disableContentEncoding=False, sizeLimit=None,
- headOnly=False, verify=False)
- """
sf = SpiderFoot(self.default_options)
invalid_types = [None, list(), dict(), int()]
@@ -1286,12 +954,6 @@ class TestSpiderFoot(unittest.TestCase):
self.assertEqual(None, res)
def test_fetchUrl_argument_url_invalid_url_should_return_None(self):
- """
- Test fetchUrl(self, url, fatal=False, cookies=None, timeout=30,
- useragent="SpiderFoot", headers=None, noLog=False,
- postData=None, disableContentEncoding=False, sizeLimit=None,
- headOnly=False, verify=False)
- """
sf = SpiderFoot(self.default_options)
res = sf.fetchUrl("")