Skip to content

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

sfp_clearbit: Cleanup (#1700)

bcolesda6569d8b29f
diff --git a/modules/sfp_clearbit.py b/modules/sfp_clearbit.py
index fa221857..f5e303db 100644
--- a/modules/sfp_clearbit.py
+++ b/modules/sfp_clearbit.py
@@ -10,6 +10,9 @@
# -------------------------------------------------------------------------------
import base64
+import urllib.error
+import urllib.parse
+import urllib.request
import json
from spiderfoot import SpiderFootEvent, SpiderFootPlugin
@@ -49,19 +52,14 @@ class sfp_clearbit(SpiderFootPlugin):
}
}
- # Default options
opts = {
"api_key": ""
}
- # Option descriptions
optdescs = {
"api_key": "Clearbit.com API key."
}
- # Be sure to completely clear any class variables in setup()
- # or you run the risk of data persisting between scan runs.
-
results = None
errorState = False
@@ -70,60 +68,105 @@ class sfp_clearbit(SpiderFootPlugin):
self.results = self.tempStorage()
self.errorState = False
- # Clear / reset any other class member variables here
- # or you risk them persisting between threads.
-
for opt in list(userOpts.keys()):
self.opts[opt] = userOpts[opt]
- # What events is this module interested in for input
def watchedEvents(self):
return ["EMAILADDR"]
- # What events this module produces
def producedEvents(self):
- return ["RAW_RIR_DATA", "PHONE_NUMBER", "PHYSICAL_ADDRESS",
- "AFFILIATE_INTERNET_NAME", "EMAILADDR", "EMAILADDR_GENERIC"]
-
- def query(self, t):
+ return [
+ "RAW_RIR_DATA",
+ "PHONE_NUMBER",
+ "PHYSICAL_ADDRESS",
+ "AFFILIATE_INTERNET_NAME",
+ "EMAILADDR",
+ "EMAILADDR_GENERIC"
+ ]
+
+ def query(self, email: str):
api_key = self.opts['api_key']
- if type(api_key) == str:
+
+ if isinstance(api_key, str):
api_key = api_key.encode('utf-8')
- url = "https://person.clearbit.com/v2/combined/find?email=" + t
+
token = base64.b64encode(api_key + ':'.encode('utf-8'))
headers = {
'Accept': 'application/json',
'Authorization': "Basic " + token.decode('utf-8')
}
+ params = {
+ 'email': email
+ }
+
+ res = self.sf.fetchUrl(
+ f"https://person.clearbit.com/v2/combined/find?{urllib.parse.urlencode(params)}",
+ timeout=self.opts['_fetchtimeout'],
+ useragent="SpiderFoot",
+ headers=headers
+ )
+
+ return self.parseApiResponse(res)
+
+ def parseApiResponse(self, res: dict):
+ if not res:
+ self.error("No response from Clearbit.")
+ return None
+
+ if res['code'] == '404':
+ self.debug("No results from Clearbit.")
+ return None
+
+ if res['code'] == "401":
+ self.error("Invalid Clearbit API key.")
+ self.errorState = True
+ return None
- res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'], useragent="SpiderFoot", headers=headers)
+ if res['code'] == "402":
+ self.error("You have exceeded your Clearbit API request quota.")
+ self.errorState = True
+ return None
+
+ # Rate limit is 600 requests per minute
+ # https://dashboard.clearbit.com/docs#rate-limiting
+ if res['code'] == '429':
+ self.error("You are being rate-limited by Clearbit.")
+ return None
- if res['code'] != "200":
- self.error("Return code indicates no results or potential API key failure or exceeded limits.")
+ if res['code'] == '500' or res['code'] == '502' or res['code'] == '503':
+ self.error("Clearbit service is unavailable.")
+ self.errorState = True
+ return None
+
+ # Catch all non-200 status codes, and presume something went wrong
+ if res['code'] != '200':
+ self.error(f"Unexpected reply from Clearbit: {res['code']}")
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
return None
try:
return json.loads(res['content'])
except Exception as e:
- self.error(f"Error processing JSON response from clearbit.io: {e}")
+ self.debug(f"Error processing JSON response from Clearbit: {e}")
return None
- # Handle events sent to this module
def handleEvent(self, event):
eventName = event.eventType
- srcModuleName = event.module
eventData = event.data
if self.errorState:
return
if self.opts['api_key'] == "":
- self.error("You enabled sfp_clearbit but did not set an API key!")
+ self.error(f"You enabled {self.__class__.__name__} but did not set an API key!")
self.errorState = True
return
- self.debug(f"Received event, {eventName}, from {srcModuleName}")
+ self.debug(f"Received event, {eventName}, from {event.module}")
if eventData in self.results:
self.debug(f"Skipping {eventData}, already checked.")
@@ -137,54 +180,72 @@ class sfp_clearbit(SpiderFootPlugin):
try:
# Get the name associated with the e-mail
- if "person" in data:
- name = data['person']['name']['fullName']
- evt = SpiderFootEvent("RAW_RIR_DATA", "Possible full name: " + name,
- self.__name__, event)
- self.notifyListeners(evt)
+ person = data.get('person')
+ if person:
+ name = person.get('name')
+ if name:
+ fullName = name.get('fullName')
+ if fullName:
+ evt = SpiderFootEvent(
+ "RAW_RIR_DATA",
+ f"Possible full name: {fullName}",
+ self.__name__,
+ event
+ )
+ self.notifyListeners(evt)
except Exception:
- self.debug("Unable to extract name from JSON.")
+ self.debug("Unable to extract person name from JSON.")
pass
# Get the location of the person, also indicating
# the location of the employer.
try:
- if "geo" in data:
- loc = ""
-
- if 'streetNumber' in data['geo']:
- loc += data['geo']['streetNumber'] + ", "
- if 'streetName' in data['geo']:
- loc += data['geo']['streetName'] + ", "
- if 'city' in data['geo']:
- loc += data['geo']['city'] + ", "
- if 'postalCode' in data['geo']:
- loc += data['geo']['postalCode'] + ", "
- if 'state' in data['geo']:
- loc += data['geo']['state'] + ", "
- if 'country' in data['geo']:
- loc += data['geo']['country']
- evt = SpiderFootEvent("PHYSICAL_ADDRESS", loc, self.__name__, event)
- self.notifyListeners(evt)
+ geo = data.get('geo')
+ if geo:
+ location = ', '.join(
+ filter(
+ None,
+ [
+ geo.get('streetNumber'),
+ geo.get('streetName'),
+ geo.get('city'),
+ geo.get('postalCode'),
+ geo.get('state'),
+ geo.get('country')
+ ]
+ )
+ )
+
+ if location:
+ evt = SpiderFootEvent("PHYSICAL_ADDRESS", location, self.__name__, event)
+ self.notifyListeners(evt)
except Exception:
self.debug("Unable to extract location from JSON.")
pass
try:
- if "company" in data:
- if 'domainAliases' in data['company']:
- for d in data['company']['domainAliases']:
- evt = SpiderFootEvent("AFFILIATE_INTERNET_NAME", d,
- self.__name__, event)
+ company = data.get('company')
+ if company:
+ domainAliases = company.get('domainAliases')
+ if domainAliases:
+ for d in domainAliases:
+ evt = SpiderFootEvent(
+ "AFFILIATE_INTERNET_NAME",
+ d,
+ self.__name__,
+ event
+ )
self.notifyListeners(evt)
- if 'site' in data['company']:
- if 'phoneNumbers' in data['company']['site']:
- for p in data['company']['site']['phoneNumbers']:
+ site = company.get('site')
+ if site:
+ if 'phoneNumbers' in site:
+ for p in site['phoneNumbers']:
evt = SpiderFootEvent("PHONE_NUMBER", p, self.__name__, event)
self.notifyListeners(evt)
- if 'emailAddresses' in data['company']['site']:
- for e in data['company']['site']['emailAddresses']:
+
+ if 'emailAddresses' in company['site']:
+ for e in site['emailAddresses']:
if e.split("@")[0] in self.opts['_genericusers'].split(","):
evttype = "EMAILADDR_GENERIC"
else:
@@ -194,25 +255,27 @@ class sfp_clearbit(SpiderFootPlugin):
# Get the location of the person, also indicating
# the location of the employer.
- if 'geo' in data['company']:
- loc = ""
-
- if 'streetNumber' in data['company']['geo']:
- loc += data['company']['geo']['streetNumber'] + ", "
- if 'streetName' in data['company']['geo']:
- loc += data['company']['geo']['streetName'] + ", "
- if 'city' in data['company']['geo']:
- loc += data['company']['geo']['city'] + ", "
- if 'postalCode' in data['company']['geo']:
- loc += data['company']['geo']['postalCode'] + ", "
- if 'state' in data['company']['geo']:
- loc += data['company']['geo']['state'] + ", "
- if 'country' in data['company']['geo']:
- loc += data['company']['geo']['country']
- evt = SpiderFootEvent("PHYSICAL_ADDRESS", loc, self.__name__, event)
- self.notifyListeners(evt)
+ company_geo = company.get('geo')
+ if company_geo:
+ location = ', '.join(
+ filter(
+ None,
+ [
+ company_geo.get('streetNumber'),
+ company_geo.get('streetName'),
+ company_geo.get('city'),
+ company_geo.get('postalCode'),
+ company_geo.get('state'),
+ company_geo.get('country')
+ ]
+ )
+ )
+
+ if location:
+ evt = SpiderFootEvent("PHYSICAL_ADDRESS", location, self.__name__, event)
+ self.notifyListeners(evt)
except Exception:
- self.debug("Unable to company info from JSON.")
+ self.debug("Unable to extract company info from JSON.")
pass
# End of sfp_clearbit class
diff --git a/test/unit/modules/test_sfp_clearbit.py b/test/unit/modules/test_sfp_clearbit.py
index b7a13051..470e2635 100644
--- a/test/unit/modules/test_sfp_clearbit.py
+++ b/test/unit/modules/test_sfp_clearbit.py
@@ -26,6 +26,30 @@ class TestModuleClearbit(unittest.TestCase):
module = sfp_clearbit()
self.assertIsInstance(module.producedEvents(), list)
+ def test_parseApiResponse_nonfatal_http_response_code_should_not_set_errorState(self):
+ sf = SpiderFoot(self.default_options)
+
+ http_codes = ["200", "404", "429"]
+ for code in http_codes:
+ with self.subTest(code=code):
+ module = sfp_clearbit()
+ module.setup(sf, dict())
+ result = module.parseApiResponse({"code": code, "content": None})
+ self.assertIsNone(result)
+ self.assertFalse(module.errorState)
+
+ def test_parseApiResponse_fatal_http_response_error_code_should_set_errorState(self):
+ sf = SpiderFoot(self.default_options)
+
+ http_codes = ["401", "402", "403", "500", "502", "503"]
+ for code in http_codes:
+ with self.subTest(code=code):
+ module = sfp_clearbit()
+ module.setup(sf, dict())
+ result = module.parseApiResponse({"code": code, "content": None})
+ self.assertIsNone(result)
+ self.assertTrue(module.errorState)
+
def test_handleEvent_no_api_key_should_set_errorState(self):
sf = SpiderFoot(self.default_options)