SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.
Python attacksurfacecticybersecurityfootprintinghackinginformation-gatheringinformation-securityinfosecintelligence-gatheringosintosint-frameworkosint-reconnaissanceosint-toolpentestingpythonreconsecurity-toolsthreat-intelligencethreatintel
Etherscan module (#1137)
Krishnasis Mandalc2af9b546ce8
diff --git a/modules/sfp_etherscan.py b/modules/sfp_etherscan.pynew file mode 100644index 00000000..9b7846e7--- /dev/null+++ b/modules/sfp_etherscan.py@@ -0,0 +1,139 @@+# -*- coding: utf-8 -*-+# -------------------------------------------------------------------------------+# Name: sfp_etherscan+# Purpose: SpiderFoot plug-in to look up a ethereum wallet's balance by+# querying etherscan.io.+#+# Author: Krishnasis Mandal <[email protected]>+#+# Created: 26/01/2021+# Copyright: (c) Steve Micallef+# Licence: GPL+# -------------------------------------------------------------------------------++import json+import time++from spiderfoot import SpiderFootEvent, SpiderFootPlugin+++class sfp_etherscan(SpiderFootPlugin):++ meta = {+ 'name': "Etherscan",+ 'summary': "Queries etherscan.io to find the balance of identified ethereum wallet addresses.",+ 'flags': ["apikey"],+ 'useCases': ["Footprint", "Investigate", "Passive"],+ 'categories': ["Public Registries"],+ 'dataSource': {+ 'website': "https://etherscan.io",+ 'model': "FREE_NOAUTH_UNLIMITED",+ 'references': [+ "https://etherscan.io/apis"+ ],+ 'apiKeyInstructions': [+ "Visit https://etherscan.io",+ "Register a free account",+ "Browse to https://etherscan.io/myapikey",+ "Click on Add beside API Key",+ "Your API Key will be listed under API Key Token",+ ],+ 'favIcon': "https://etherscan.io/images/favicon3.ico",+ 'logo': "https://etherscan.io/images/brandassets/etherscan-logo-circle.png",+ 'description': "Etherscan allows you to explore and search the Ethereum blockchain "+ "for transactions, addresses, tokens, prices and other activities taking place on Ethereum (ETH)",+ }+ }++ # Default options+ opts = {+ 'api_key': '',+ 'pause': 1+ }++ # Option descriptions+ optdescs = {+ 'api_key': "API Key for etherscan.io",+ 'pause': "Number of seconds to wait between each API call."+ }++ results = None++ def setup(self, sfc, userOpts=dict()):+ self.sf = sfc+ self.results = self.tempStorage()++ for opt in list(userOpts.keys()):+ self.opts[opt] = userOpts[opt]++ # What events is this module interested in for input+ def watchedEvents(self):+ return [+ "ETHEREUM_ADDRESS"+ ]++ # What events this module produces+ # This is to support the end user in selecting modules based on events+ # produced.+ def producedEvents(self):+ return [+ "ETHEREUM_BALANCE",+ "RAW_RIR_DATA"+ ]++ def query(self, qry):+ queryString = f"https://api.etherscan.io/api?module=account&action=balance&address={qry}&tag=latest&apikey={self.opts['api_key']}"+ # Wallet balance+ res = self.sf.fetchUrl(queryString,+ timeout=self.opts['_fetchtimeout'],+ useragent=self.opts['_useragent'])++ time.sleep(self.opts['pause'])++ if res['content'] is None:+ self.sf.info(f"No Etherscan data found for {qry}")+ return None+ try:+ return json.loads(res['content'])+ except Exception as e:+ self.sf.debug(f"Error processing JSON response: {e}")+ return None++ # Handle events sent to this module+ def handleEvent(self, event):+ eventName = event.eventType+ srcModuleName = event.module+ eventData = event.data++ self.sf.debug(f"Received event, {eventName}, from {srcModuleName}")++ if self.opts['api_key'] == "":+ self.sf.error("You enabled sfp_etherscan but did not set an API key!")+ self.errorState = True+ return++ if self.errorState:+ return None++ # Don't look up stuff twice+ if eventData in self.results:+ self.sf.debug(f"Skipping {eventData}, already checked.")+ return None+ else:+ self.results[eventData] = True++ data = self.query(eventData)+ if data is None:+ self.sf.info(f"No Etherscan data found for {eventData}")+ return None++ # Value returned by etherscan was too large in comparison to actual wallet balance+ balance = float(data.get('result')) / 1000000000000000000++ evt = SpiderFootEvent("ETHEREUM_BALANCE", f"{str(balance)} ETH", self.__name__, event)+ self.notifyListeners(evt)++ evt = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, event)+ self.notifyListeners(evt)++# End of sfp_etherscan classdiff --git a/spiderfoot/db.py b/spiderfoot/db.pyindex ff239698..9b80bb3b 100644--- a/spiderfoot/db.py+++ b/spiderfoot/db.py@@ -148,6 +148,7 @@ class SpiderFootDb:['EMAILADDR_GENERIC', 'Email Address - Generic', 0, 'ENTITY'],['ERROR_MESSAGE', 'Error Message', 0, 'DATA'],['ETHEREUM_ADDRESS', 'Ethereum Address', 0, 'ENTITY'],+ ['ETHEREUM_BALANCE', 'Ethereum Balance', 0, 'DESCRIPTOR'],['GEOINFO', 'Physical Location', 0, 'DESCRIPTOR'],['HASH', 'Hash', 0, 'DATA'],['HASH_COMPROMISED', 'Compromised Password Hash', 0, 'DATA'],diff --git a/test/unit/modules/test_sfp_etherscan.py b/test/unit/modules/test_sfp_etherscan.pynew file mode 100644index 00000000..93e72a29--- /dev/null+++ b/test/unit/modules/test_sfp_etherscan.py@@ -0,0 +1,80 @@+# test_sfp_etherscan.py+import unittest++from modules.sfp_etherscan import sfp_etherscan+from sflib import SpiderFoot+from spiderfoot import SpiderFootEvent, SpiderFootTarget+++class TestModuleetherscan(unittest.TestCase):+ """+ Test modules.sfp_etherscan+ """++ default_options = {+ '_debug': False, # Debug+ '__logging': True, # Logging in general+ '__outputfilter': None, # Event types to filter from modules' output+ '_useragent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0', # User-Agent to use for HTTP requests+ '_dnsserver': '', # Override the default resolver+ '_fetchtimeout': 5, # number of seconds before giving up on a fetch+ '_internettlds': 'https://publicsuffix.org/list/effective_tld_names.dat',+ '_internettlds_cache': 72,+ '_genericusers': "abuse,admin,billing,compliance,devnull,dns,ftp,hostmaster,inoc,ispfeedback,ispsupport,list-request,list,maildaemon,marketing,noc,no-reply,noreply,null,peering,peering-notify,peering-request,phish,phishing,postmaster,privacy,registrar,registry,root,routing-registry,rr,sales,security,spam,support,sysadmin,tech,undisclosed-recipients,unsubscribe,usenet,uucp,webmaster,www",+ '__version__': '3.3-DEV',+ '__database': 'spiderfoot.test.db', # note: test database file+ '__modules__': None, # List of modules. Will be set after start-up.+ '_socks1type': '',+ '_socks2addr': '',+ '_socks3port': '',+ '_socks4user': '',+ '_socks5pwd': '',+ '_torctlport': 9051,+ '__logstdout': False+ }++ def test_opts(self):+ module = sfp_etherscan()+ self.assertEqual(len(module.opts), len(module.optdescs))++ def test_setup(self):+ """+ Test setup(self, sfc, userOpts=dict())+ """+ sf = SpiderFoot(self.default_options)++ module = sfp_etherscan()+ module.setup(sf, dict())++ def test_watchedEvents_should_return_list(self):+ module = sfp_etherscan()+ self.assertIsInstance(module.watchedEvents(), list)++ def test_producedEvents_should_return_list(self):+ module = sfp_etherscan()+ self.assertIsInstance(module.producedEvents(), list)++ @unittest.skip("todo")+ def test_handleEvent(self):+ """+ Test handleEvent(self, event)+ """+ sf = SpiderFoot(self.default_options)++ module = sfp_etherscan()+ module.setup(sf, dict())++ target_value = 'example target value'+ target_type = 'ETHEREUM_ADDRESS'+ target = SpiderFootTarget(target_value, target_type)+ module.setTarget(target)++ event_type = 'ROOT'+ event_data = 'example data'+ event_module = ''+ source_event = ''+ evt = SpiderFootEvent(event_type, event_data, event_module, source_event)++ result = module.handleEvent(evt)++ self.assertIsNone(result)