Skip to content

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

sfp_bitcoinabuse: Check API response for errors (#1712)

bcoleseabfa4a5f7e6
diff --git a/modules/sfp_bitcoinabuse.py b/modules/sfp_bitcoinabuse.py
index 9ff05638..852b53fe 100644
--- a/modules/sfp_bitcoinabuse.py
+++ b/modules/sfp_bitcoinabuse.py
@@ -11,7 +11,8 @@
# -------------------------------------------------------------------------------
import json
-from urllib.parse import urlencode
+import time
+import urllib.parse
from spiderfoot import SpiderFootEvent, SpiderFootPlugin
@@ -58,6 +59,7 @@ class sfp_bitcoinabuse(SpiderFootPlugin):
def setup(self, sfc, userOpts=None):
self.sf = sfc
+ self.errorState = False
self.results = self.tempStorage()
if userOpts:
@@ -67,46 +69,84 @@ class sfp_bitcoinabuse(SpiderFootPlugin):
return ["BITCOIN_ADDRESS"]
def producedEvents(self):
- return ["MALICIOUS_BITCOIN_ADDRESS"]
+ return [
+ "MALICIOUS_BITCOIN_ADDRESS",
+ "RAW_RIR_DATA",
+ ]
+
+ def queryAddress(self, address: str):
+ params = {
+ "address": address,
+ "api_token": self.opts["api_key"]
+ }
- def query(self, address):
- params = {"address": address, "api_token": self.opts["api_key"]}
- qry = urlencode(params)
res = self.sf.fetchUrl(
- f"https://www.bitcoinabuse.com/api/reports/check?{qry}",
+ f"https://www.bitcoinabuse.com/api/reports/check?{urllib.parse.urlencode(params)}",
timeout=self.opts["_fetchtimeout"],
useragent="SpiderFoot",
)
- if res["code"] != "200":
- self.info(f"Failed to get results for {address}, code {res['code']}")
+
+ # All endpoints other than Report Address have a rate limit of
+ # 30 requests per minute or one request every two seconds on average.
+ time.sleep(2)
+
+ return self.parseApiResponse(res)
+
+ def parseApiResponse(self, res: dict):
+ if not res:
+ self.error("No response from BitcoinAbuse.")
+ return None
+
+ if res['code'] == '404':
+ self.debug("No results for query")
+ return None
+
+ if res['code'] == "401":
+ self.error("Invalid BitcoinAbuse API key.")
+ self.errorState = True
+ return None
+
+ if res['code'] == '429':
+ self.error("You are being rate-limited by BitcoinAbuse")
+ self.errorState = True
+ return None
+
+ if res['code'] in ['500', '502', '503']:
+ self.error("BitcoinAbuse service unavailable")
+ self.errorState = True
+ return None
+
+ # Catch all other non-200 status codes, and presume something went wrong
+ if res['code'] != '200':
+ self.error("Failed to retrieve content from BitcoinAbuse")
+ self.errorState = True
return None
- if res["content"] is None:
- self.info(f"Failed to get results for {address}, empty content")
+ if res['content'] is None:
return None
try:
- return json.loads(res["content"])
+ return json.loads(res['content'])
except Exception as e:
- self.error(f"Error processing JSON response from BitcoinAbuse: {e}")
+ self.debug(f"Error processing JSON response from BitcoinAbuse: {e}")
return None
def handleEvent(self, event):
- eventName = event.eventType
- srcModuleName = event.module
- eventData = event.data
-
if self.errorState:
return
- self.debug(f"Received event, {eventName}, from {srcModuleName}")
+ eventName = event.eventType
+
+ self.debug(f"Received event, {eventName}, from {event.module}")
if self.opts["api_key"] == "":
- self.error("You enabled sfp_bitcoinabuse 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
+ eventData = event.data
+
if eventData in self.results:
self.debug(f"Skipping {eventData}, already checked.")
return
@@ -114,17 +154,37 @@ class sfp_bitcoinabuse(SpiderFootPlugin):
self.results[eventData] = True
if eventName == "BITCOIN_ADDRESS":
- rec = self.query(eventData)
- if isinstance(rec, dict):
- count = rec.get("count")
- if isinstance(count, int):
- if count > 0:
- evt = SpiderFootEvent(
- "MALICIOUS_BITCOIN_ADDRESS", f"BitcoinAbuse [{rec['address']}][https://www.bitcoinabuse.com/reports/{rec['address']}]", self.__name__, event
- )
- self.notifyListeners(evt)
-
- rirevt = SpiderFootEvent(
- "RAW_RIR_DATA", json.dumps(rec), self.__name__, event
- )
- self.notifyListeners(rirevt)
+ rec = self.queryAddress(eventData)
+
+ if not rec:
+ return
+
+ if not isinstance(rec, dict):
+ return
+
+ count = rec.get("count")
+
+ if not count:
+ return
+
+ if not isinstance(count, int):
+ return
+
+ address = rec.get('address')
+
+ if not address:
+ return
+
+ url = f"https://www.bitcoinabuse.com/reports/{address}"
+ evt = SpiderFootEvent(
+ "MALICIOUS_BITCOIN_ADDRESS",
+ f"BitcoinAbuse [{address}]\n<SFURL>{url}</SFURL>",
+ self.__name__,
+ event
+ )
+ self.notifyListeners(evt)
+
+ rirevt = SpiderFootEvent(
+ "RAW_RIR_DATA", json.dumps(rec), self.__name__, event
+ )
+ self.notifyListeners(rirevt)
diff --git a/test/unit/modules/test_sfp_bitcoinabuse.py b/test/unit/modules/test_sfp_bitcoinabuse.py
index 16fb6032..eff5617e 100644
--- a/test/unit/modules/test_sfp_bitcoinabuse.py
+++ b/test/unit/modules/test_sfp_bitcoinabuse.py
@@ -26,6 +26,30 @@ class TestModuleBitcoinAbuse(unittest.TestCase):
module = sfp_bitcoinabuse()
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"]
+ for code in http_codes:
+ with self.subTest(code=code):
+ module = sfp_bitcoinabuse()
+ 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", "429", "500", "502", "503"]
+ for code in http_codes:
+ with self.subTest(code=code):
+ module = sfp_bitcoinabuse()
+ 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)