Skip to content

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

sfp_abuseipdb: Fix watched/produced events and timeout

Brendan Colesd741288cc8a2
diff --git a/modules/sfp_abuseipdb.py b/modules/sfp_abuseipdb.py
index 7cb5f03d..8b07db31 100644
--- a/modules/sfp_abuseipdb.py
+++ b/modules/sfp_abuseipdb.py
@@ -1,35 +1,29 @@
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
-# Name: sfp_abuseipdb
-# Purpose: Checks if an ASN, IP or domain is malicious.
+# Name: sfp_abuseipdb
+# Purpose: Check if an IP address is malicious according to AbuseIPDB.com.
#
#
# Created: 06/09/2018
# Copyright: (c) Steve Micallef, 2018
# Licence: GPL
# -------------------------------------------------------------------------------
-import re
-
-from netaddr import IPAddress, IPNetwork
+import json
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
from spiderfoot import SpiderFootEvent, SpiderFootPlugin
-malchecks = {
- 'AbuseIPDB': {
- 'id': 'abuseipdbip',
- 'checks': ['ip'],
- 'url': 'https://api.abuseipdb.com/api/v2/blacklist?confidenceMinimum={0}&plaintext=1'
- }
-}
-
class sfp_abuseipdb(SpiderFootPlugin):
meta = {
'name': "AbuseIPDB",
- 'summary': "Check if an IP address is malicious according to AbuseIPDB.com.",
+ 'summary': "Check if an IP address is malicious according to AbuseIPDB.com blacklist.",
'flags': ["apikey"],
'useCases': ["Passive", "Investigate"],
'categories': ["Reputation Systems"],
@@ -61,141 +55,219 @@ class sfp_abuseipdb(SpiderFootPlugin):
}
}
- # Default options
opts = {
'api_key': '',
'confidenceminimum': 90,
'checkaffiliates': True,
- 'checknetblocks': True,
- 'checksubnets': True
+ 'limit': 10000
}
- # Option descriptions
optdescs = {
'api_key': "AbuseIPDB.com API key.",
'confidenceminimum': "The minimium AbuseIPDB confidence level to require.",
'checkaffiliates': "Apply checks to affiliates?",
- 'checknetblocks': "Report if any malicious IPs are found within owned netblocks?",
- 'checksubnets': "Check if any malicious IPs are found within the same subnet of the target?"
+ 'limit': 'Maximum number of results to retrieve.',
}
- # Be sure to completely clear any class variables in setup()
- # or you run the risk of data persisting between scan runs.
-
results = None
def setup(self, sfc, userOpts=dict()):
self.sf = sfc
self.results = self.tempStorage()
- # 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
- # * = be notified about all events.
def watchedEvents(self):
- return ["IP_ADDRESS", "AFFILIATE_IPADDR", "NETBLOCK_OWNER", "NETBLOCK_MEMBER"]
+ return [
+ "IP_ADDRESS",
+ "AFFILIATE_IPADDR",
+ ]
- # What events this module produces
- # This is to support the end user in selecting modules based on events
- # produced.
def producedEvents(self):
- return ["MALICIOUS_IPADDR", "MALICIOUS_AFFILIATE_IPADDR",
- "MALICIOUS_SUBNET", "MALICIOUS_NETBLOCK"]
-
- def lookupItem(self, resourceId, itemType, target):
- for check in list(malchecks.keys()):
- cid = malchecks[check]['id']
- if cid == resourceId and itemType in malchecks[check]['checks']:
- self.sf.debug("Checking maliciousness of " + target + " (" + itemType + ") with: " + cid)
- return self.resourceList(cid, target, itemType)
- return None
+ return [
+ "MALICIOUS_IPADDR",
+ "MALICIOUS_AFFILIATE_IPADDR",
+ ]
- # Look up 'list' type resources
- def resourceList(self, id, target, targetType):
- targetDom = ''
- # Get the base domain if we're supplied a domain
- if targetType == "domain":
- targetDom = self.sf.hostDomain(target, self.opts['_internettlds'])
- if not targetDom:
- return None
-
- for check in list(malchecks.keys()):
- cid = malchecks[check]['id']
- if id == cid:
- data = dict()
- url = malchecks[check]['url'].format(self.opts['confidenceminimum'])
- hdr = {
- 'Key': self.opts['api_key'],
- 'Accept': "text/plain"
- }
- data = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],
- useragent=self.opts['_useragent'], headers=hdr)
- if data['content'] is None:
- self.sf.error("Unable to fetch " + url, False)
- return None
-
- url = "https://www.abuseipdb.com/check/" + target
-
- # If we're looking at netblocks
- if targetType == "netblock":
- iplist = list()
- # Get the regex, replace {0} with an IP address matcher to
- # build a list of IP.
- # Cycle through each IP and check if it's in the netblock.
- if 'regex' in malchecks[check]:
- rx = malchecks[check]['regex'].replace("{0}", r"(\d+\.\d+\.\d+\.\d+)")
- pat = re.compile(rx, re.IGNORECASE)
- self.sf.debug("New regex for " + check + ": " + rx)
- for line in data['content'].split('\n'):
- grp = re.findall(pat, line)
- if len(grp) > 0:
- # self.sf.debug("Adding " + grp[0] + " to list.")
- iplist.append(grp[0])
- else:
- iplist = data['content'].split('\n')
-
- for ip in iplist:
- if len(ip) < 8 or ip.startswith("#"):
- continue
- ip = ip.strip()
-
- try:
- if IPAddress(ip) in IPNetwork(target):
- self.sf.debug(f"{ip} found within netblock/subnet {target} in {check}")
- return url
- except Exception as e:
- self.sf.debug(f"Error encountered parsing: {e}")
- continue
-
- return None
-
- # If we're looking at hostnames/domains/IPs
- if 'regex' not in malchecks[check]:
- for line in data['content'].split('\n'):
- if line == target or (targetType == "domain" and line == targetDom):
- self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")
- return url
- else:
- # Check for the domain and the hostname
- try:
- rxDom = str(malchecks[check]['regex']).format(targetDom)
- rxTgt = str(malchecks[check]['regex']).format(target)
- for line in data['content'].split('\n'):
- if (targetType == "domain" and re.match(rxDom, line, re.IGNORECASE)) or \
- re.match(rxTgt, line, re.IGNORECASE):
- self.sf.debug(target + "/" + targetDom + " found in " + check + " list.")
- return url
- except BaseException as e:
- self.sf.debug("Error encountered parsing 2: " + str(e))
- continue
+ def queryBlacklist(self):
+ blacklist = self.sf.cacheGet('abuseipdb', 24)
- return None
+ if blacklist is not None:
+ return self.parseBlacklist(blacklist)
+
+ headers = {
+ 'Key': self.opts['api_key'],
+ 'Accept': "text/plain"
+ }
+
+ params = urllib.parse.urlencode({
+ 'confidenceMinimum': self.opts['confidenceminimum'],
+ 'limit': self.opts['limit'],
+ 'plaintext': '1'
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://api.abuseipdb.com/api/v2/blacklist?{params}",
+ timeout=60, # retrieving 10,000 results (default) or more can sometimes take a while
+ useragent=self.opts['_useragent'],
+ headers=headers
+ )
+
+ time.sleep(1)
+
+ if res['code'] == '429':
+ self.sf.error("You are being rate-limited by AbuseIPDB", False)
+ self.errorState = True
+ return None
+
+ if res['code'] != "200":
+ self.sf.error(f"Error retrieving search results, code {res['code']}", False)
+ self.errorState = True
+ return None
+
+ if res['code'] != "200":
+ self.sf.error("Error retrieving search results from AbuseIPDB", False)
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.sf.error("Received no content from AbuseIPDB", False)
+ self.errorState = True
+ return None
+
+ self.sf.cachePut("abuseipdb", res['content'])
+
+ return self.parseBlacklist(res['content'])
+
+ def parseBlacklist(self, blacklist):
+ """Parse plaintext blacklist
+ Args:
+ blacklist (str): plaintext blacklist from AbuseIPDB
+
+ Returns:
+ list: list of blacklisted IP addresses
+ """
+ ips = list()
+
+ for ip in blacklist.split('\n'):
+ ip = ip.strip()
+ if ip.startswith('#'):
+ continue
+ if not self.sf.validIP(ip):
+ continue
+ ips.append(ip)
+
+ return ips
+
+ def queryIpAddress(self, ip):
+ """Query API for an IP address.
+
+ Note: Currently unused.
+
+ Args:
+ ip (str): IP address
+
+ Returns:
+ str: API response as JSON
+ """
+
+ headers = {
+ 'Key': self.opts['api_key'],
+ 'Accept': 'application/json',
+ }
+
+ params = urllib.parse.urlencode({
+ 'ipAddress': ip,
+ 'maxAgeInDays': 30,
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://api.abuseipdb.com/api/v2/check?{params}",
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ headers=headers
+ )
+
+ time.sleep(1)
+
+ if res['code'] == '429':
+ self.sf.error("You are being rate-limited by AbuseIPDB", False)
+ self.errorState = True
+ return None
+
+ if res['code'] != "200":
+ self.sf.error("Error retrieving search results from AbuseIPDB", False)
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.sf.error("Received no content from AbuseIPDB", False)
+ self.errorState = True
+ return None
+
+ try:
+ data = json.loads(res['content'])
+ except Exception as e:
+ self.sf.debug(f"Error processing JSON response: {e}")
+ return None
+
+ return data
+
+ def queryNetblock(self, ip):
+ """Query API for a netblock.
+
+ Note: Currently unused.
+
+ Args:
+ ip (str): CIDR range
+
+ Returns:
+ str: API response as JSON
+ """
+
+ headers = {
+ 'Key': self.opts['api_key'],
+ 'Accept': 'application/json',
+ }
+
+ params = urllib.parse.urlencode({
+ 'ipAddress': ip,
+ 'maxAgeInDays': 30,
+ })
+
+ res = self.sf.fetchUrl(
+ f"https://api.abuseipdb.com/api/v2/check-block?{params}",
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'],
+ headers=headers
+ )
+
+ time.sleep(1)
+
+ if res['code'] == '429':
+ self.sf.error("You are being rate-limited by AbuseIPDB", False)
+ self.errorState = True
+ return None
+
+ if res['code'] != "200":
+ self.sf.error("Error retrieving search results from AbuseIPDB", False)
+ self.errorState = True
+ return None
+
+ if res['content'] is None:
+ self.sf.error("Received no content from AbuseIPDB", False)
+ self.errorState = True
+ return None
+
+ try:
+ data = json.loads(res['content'])
+ except Exception as e:
+ self.sf.debug(f"Error processing JSON response: {e}")
+ return None
+
+ return data
- # Handle events sent to this module
def handleEvent(self, event):
eventName = event.eventType
srcModuleName = event.module
@@ -203,45 +275,51 @@ class sfp_abuseipdb(SpiderFootPlugin):
self.sf.debug(f"Received event, {eventName}, from {srcModuleName}")
+ if self.opts["api_key"] == "":
+ self.sf.error(
+ f"You enabled {self.__class__.__name__} but did not set an API key!",
+ False,
+ )
+ self.errorState = True
+ return None
+
if eventData in self.results:
self.sf.debug(f"Skipping {eventData}, already checked.")
return None
self.results[eventData] = True
- if eventName == 'AFFILIATE_IPADDR' \
- and not self.opts.get('checkaffiliates', False):
+ if eventName == 'AFFILIATE_IPADDR' and not self.opts.get('checkaffiliates'):
return None
- if eventName == 'NETBLOCK_OWNER' and not self.opts.get('checknetblocks', False):
+
+ if eventName == 'IP_ADDRESS':
+ evtType = 'MALICIOUS_IPADDR'
+ elif eventName == 'AFFILIATE_IPADDR':
+ evtType = 'MALICIOUS_AFFILIATE_IPADDR'
+ else:
return None
- if eventName == 'NETBLOCK_MEMBER' and not self.opts.get('checksubnets', False):
+
+ self.sf.debug(f"Checking maliciousness of IP address {eventData} with AbuseIPDB")
+
+ blacklist = self.queryBlacklist()
+
+ if not blacklist:
return None
- for check in list(malchecks.keys()):
- cid = malchecks[check]['id']
- if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:
- typeId = 'ip'
- if eventName == 'IP_ADDRESS':
- evtType = 'MALICIOUS_IPADDR'
- else:
- evtType = 'MALICIOUS_AFFILIATE_IPADDR'
+ if eventData not in blacklist:
+ return None
- if eventName == 'NETBLOCK_OWNER':
- typeId = 'netblock'
- evtType = 'MALICIOUS_NETBLOCK'
- if eventName == 'NETBLOCK_MEMBER':
- typeId = 'netblock'
- evtType = 'MALICIOUS_SUBNET'
+ self.sf.info(f"Malicious IP address {eventData} found in AbuseIPDB blacklist")
- url = self.lookupItem(cid, typeId, eventData)
- if self.checkForStop():
- return None
+ url = f"https://www.abuseipdb.com/check/{eventData}"
- # Notify other modules of what you've found
- if url is not None:
- text = f"{check} [{eventData}]\n<SFURL>{url}</SFURL>"
- evt = SpiderFootEvent(evtType, text, self.__name__, event)
- self.notifyListeners(evt)
+ evt = SpiderFootEvent(
+ evtType,
+ f"AbuseIPDB [{eventData}]\n<SFURL>{url}</SFURL>",
+ self.__name__,
+ event
+ )
+ self.notifyListeners(evt)
return None