Skip to content

Commit

Permalink
ipapi.co Module (smicallef#1139)
Browse files Browse the repository at this point in the history
* ipapi.co module
  • Loading branch information
krishnasism committed Feb 22, 2021
1 parent 88dcb8d commit ec1e89d
Show file tree
Hide file tree
Showing 2 changed files with 198 additions and 0 deletions.
118 changes: 118 additions & 0 deletions modules/sfp_ipapico.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# Name: sfp_ipapico
# Purpose: SpiderFoot plug-in to identify the Geo-location of IP addresses
# identified by other modules using ipapi.co
#
# Author: Krishnasis Mandal <krishnasis@hotmail.com>
#
# Created: 02/02/2021
# Copyright: (c) Steve Micallef
# Licence: GPL
# -------------------------------------------------------------------------------

import json
import time

from spiderfoot import SpiderFootEvent, SpiderFootPlugin


class sfp_ipapico(SpiderFootPlugin):

meta = {
'name': "ipapi.co",
'summary': "Queries ipapi.co to identify geolocation of IP Addresses using ipapi.co API",
'flags': [""],
'useCases': ["Footprint", "Investigate", "Passive"],
'categories': ["Real World"],
'dataSource': {
'website': "https://ipapi.co/",
'model': "FREE_AUTH_LIMITED",
'references': [
"https://ipapi.co/api/"
],
'favIcon': "https://ipapi.co/static/images/favicon.b64f1de785e1.ico",
'logo': "https://ipapi.co/static/images/favicon.34f0ec468301.png",
'description': "Powerful & Simple REST API for IP Address Geolocation."
"ipapi.co provides a REST API to find the location of an IP address.",
}
}

# Default options
opts = {
}

# Option descriptions
optdescs = {
}

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 [
"IP_ADDRESS",
"IPV6_ADDRESS"
]

# What events this module produces
# This is to support the end user in selecting modules based on events
# produced.
def producedEvents(self):
return [
"GEOINFO",
"RAW_RIR_DATA"
]

def query(self, qry):
queryString = f"https://ipapi.co/{qry}/json/"

res = self.sf.fetchUrl(queryString,
timeout=self.opts['_fetchtimeout'],
useragent=self.opts['_useragent'])
time.sleep(1.5)

if res['content'] is None:
self.sf.info(f"No ipapi.co 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}")

# 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.get('country'):
location = ', '.join(filter(None, [data.get('city'), data.get('region'), data.get('region_code'), data.get('country_name'), data.get('country'), data.get('postal')]))
evt = SpiderFootEvent('GEOINFO', location, self.__name__, event)
self.notifyListeners(evt)

evt = SpiderFootEvent('RAW_RIR_DATA', str(data), self.__name__, event)
self.notifyListeners(evt)


# End of sfp_ipapico class
80 changes: 80 additions & 0 deletions test/unit/modules/test_sfp_ipapico.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# test_sfp_ipapico.py
import unittest

from modules.sfp_ipapico import sfp_ipapico
from sflib import SpiderFoot
from spiderfoot import SpiderFootEvent, SpiderFootTarget


class TestModuleipapicom(unittest.TestCase):
"""
Test modules.sfp_ipapico
"""

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_ipapico()
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_ipapico()
module.setup(sf, dict())

def test_watchedEvents_should_return_list(self):
module = sfp_ipapico()
self.assertIsInstance(module.watchedEvents(), list)

def test_producedEvents_should_return_list(self):
module = sfp_ipapico()
self.assertIsInstance(module.producedEvents(), list)

@unittest.skip("todo")
def test_handleEvent(self):
"""
Test handleEvent(self, event)
"""
sf = SpiderFoot(self.default_options)

module = sfp_ipapico()
module.setup(sf, dict())

target_value = 'example target value'
target_type = 'IP_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)

0 comments on commit ec1e89d

Please sign in to comment.