Skip to content

Commit

Permalink
Textmagic module (smicallef#1101)
Browse files Browse the repository at this point in the history
* Textmagic module
  • Loading branch information
krishnasism committed Oct 6, 2020
1 parent a717a85 commit c77aa1a
Show file tree
Hide file tree
Showing 3 changed files with 232 additions and 0 deletions.
151 changes: 151 additions & 0 deletions modules/sfp_textmagic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# Name: sfp_textmagic
# Purpose: Spiderfoot module to retrieve phone number type
# using TextMagic API
#
# Author: Krishnasis Mandal <krishnasis@hotmail.com>
#
# Created: 2020-10-05
# Copyright: (c) Steve Micallef
# Licence: GPL
# -------------------------------------------------------------------------------
import json

from spiderfoot import SpiderFootEvent, SpiderFootPlugin


class sfp_textmagic(SpiderFootPlugin):

meta = {
"name": "TextMagic",
"summary": "Obtain phone number type from TextMagic API",
"flags": ["apikey"],
"useCases": ["Passive"],
"categories": ["Search Engines"],
"dataSource": {
"website": "https://www.textmagic.com/",
"model": "FREE_AUTH_LIMITED",
"references": [
"https://docs.textmagic.com/"
],
"apiKeyInstructions": [
"Visit https://textmagic.com",
"Register a free trial account",
"Visit https://my.textmagic.com/online/api/rest-api/keys",
"Click on 'Add new API Key'",
"Your API key will be listed beside 'The new API Key is'"
],
"favIcon": "https://www.textmagic.com/wp-content/themes/textmagic-genesis/assets/app/images/favicon.png",
"logo": "https://www.textmagic.com/wp-content/uploads/2015/04/logo.png",
"description": "TextMagic is a business text-messaging service for sending "
"notifications, alerts, reminders, confirmations and SMS marketing campaigns.",
},
}

opts = {
"api_key_username": "",
"api_key": "",
}

optdescs = {
"api_key_username": "TextMagic API Username",
"api_key": "TextMagic API Key",
}

errorState = False

def setup(self, sfc, userOpts=None):
if userOpts is None:
userOpts = {}
self.sf = sfc
self.results = self.tempStorage()
self.opts.update(userOpts)

def watchedEvents(self):
return [
"PHONE_NUMBER"
]

def producedEvents(self):
return [
"PHONE_NUMBER_TYPE",
"RAW_RIR_DATA"
]

def handle_error_response(self, qry, res):
try:
error_info = json.loads(res["content"])
except Exception:
error_info = None
if error_info:
error_message = error_info.get("message")
else:
error_message = None
if error_message:
error_str = f", message {error_message}"
else:
error_str = ""
self.sf.error(f"Failed to get results for {qry}, code {res['code']}{error_str}")

def queryPhoneNumber(self, qry):
headers = {
'X-TM-Username': self.opts['api_key_username'],
'X-TM-Key': self.opts['api_key']
}

res = self.sf.fetchUrl(
f"https://rest.textmagic.com/api/v2/lookups/{qry}",
headers=headers,
timeout=self.opts["_fetchtimeout"],
useragent="SpiderFoot",
)

if res["code"] != "200":
self.handle_error_response(qry, res)
return None

if res['content'] is None:
self.sf.info(f"No TextMagic info found for {qry}")
return None

try:
return json.loads(res['content'])
except Exception as e:
self.sf.error(f"Error processing JSON response from TextMagic: {e}")

return None

def handleEvent(self, event):
eventName = event.eventType
srcModuleName = event.module
eventData = event.data

if self.errorState:
return None

self.sf.debug(f"Received event, {eventName}, from {srcModuleName}")

if self.opts["api_key"] == "" and self.opts["api_key_username"] == "":
self.sf.error(
f"You enabled {self.__class__.__name__} but did not set an API Username/Key!"
)
self.errorState = True
return None

self.results[eventData] = True

data = self.queryPhoneNumber(event.data)

if data is None:
return

phoneNumberType = data.get("type")
if phoneNumberType is not None:
evt = SpiderFootEvent("RAW_RIR_DATA", str(data), self.__name__, event)
self.notifyListeners(evt)

evt = SpiderFootEvent("PHONE_NUMBER_TYPE", phoneNumberType, self.__name__, event)
self.notifyListeners(evt)

# End of sfp_textmagic class
1 change: 1 addition & 0 deletions spiderfoot/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ class SpiderFootDb:
['LEAKSITE_CONTENT', 'Leak Site Content', 1, 'DATA'],
['PASSWORD_COMPROMISED', 'Compromised Password', 0, 'DATA'],
['PHONE_NUMBER', 'Phone Number', 0, 'ENTITY'],
['PHONE_NUMBER_TYPE', 'Phone Number Type', 0, 'DESCRIPTOR'],
['PHYSICAL_ADDRESS', 'Physical Address', 0, 'ENTITY'],
['PHYSICAL_COORDINATES', 'Physical Coordinates', 0, 'ENTITY'],
['PGP_KEY', 'PGP Public Key', 0, 'DATA'],
Expand Down
80 changes: 80 additions & 0 deletions test/unit/modules/test_sfp_textmagic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# test_sfp_textmagic.py
import unittest

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


class TestModuletextmagic(unittest.TestCase):
"""
Test modules.sfp_textmagic
"""

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

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

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

def test_handleEvent_no_api_key_should_set_errorState(self):
"""
Test handleEvent(self, event)
"""
sf = SpiderFoot(self.default_options)

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

target_value = 'example target value'
target_type = 'PHONE_NUMBER'
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)
self.assertTrue(module.errorState)

0 comments on commit c77aa1a

Please sign in to comment.