Skip to content

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

SpiderFootHelpers: Add extractPgpKeysFromText function (#1682)

bcolesaae4a1f41a39
diff --git a/modules/sfp_pgp.py b/modules/sfp_pgp.py
index 5c697a74..c889c5e6 100644
--- a/modules/sfp_pgp.py
+++ b/modules/sfp_pgp.py
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# Name: sfp_pgp
-# Purpose: SpiderFoot plug-in for looking up received e-mails in PGP
+# Purpose: SpiderFoot plug-in for looking up e-mail addresses in PGP
# key servers as well as finding e-mail addresses belonging to
# your target.
#
@@ -12,8 +12,6 @@
# Licence: MIT
# -------------------------------------------------------------------------------
-import re
-
from spiderfoot import SpiderFootEvent, SpiderFootHelpers, SpiderFootPlugin
@@ -21,25 +19,31 @@ class sfp_pgp(SpiderFootPlugin):
meta = {
'name': "PGP Key Servers",
- 'summary': "Look up e-mail addresses in PGP public key servers.",
+ 'summary': "Look up domains and e-mail addresses in PGP public key servers.",
'flags': [],
'useCases': ["Footprint", "Investigate", "Passive"],
'categories': ["Public Registries"]
}
results = None
+ errorState = False
+
+ # Sample key servers:
+ # https://pgp.key-server.io
+ # http://the.earth.li:11371
+ # https://keyserver.ubuntu.com
+ # https://sks-keyservers.net
- # Default options
opts = {
- # options specific to this module
- 'keyserver_search1': "https://pgp.key-server.io/pks/lookup?fingerprint=on&op=vindex&search=",
- 'keyserver_fetch1': "https://pgp.key-server.io/pks/lookup?op=get&search=",
- 'keyserver_search2': "http://the.earth.li:11371/pks/lookup?op=index&search=",
+ 'retrieve_keys': True,
+ 'keyserver_search1': "https://keyserver.ubuntu.com/pks/lookup?fingerprint=on&op=vindex&search=",
+ 'keyserver_fetch1': "https://keyserver.ubuntu.com/pks/lookup?op=get&search=",
+ 'keyserver_search2': "http://the.earth.li:11371/pks/lookup?fingerprint=on&op=vindex&search=",
'keyserver_fetch2': "http://the.earth.li:11371/pks/lookup?op=get&search="
}
- # Option descriptions
optdescs = {
+ 'retrieve_keys': "Retrieve PGP keys.",
'keyserver_search1': "PGP public key server URL to find e-mail addresses on a domain. Domain will get appended.",
'keyserver_fetch1': "PGP public key server URL to find the public key for an e-mail address. Email address will get appended.",
'keyserver_search2': "Backup PGP public key server URL to find e-mail addresses on a domain. Domain will get appended.",
@@ -49,80 +53,114 @@ class sfp_pgp(SpiderFootPlugin):
def setup(self, sfc, userOpts=dict()):
self.sf = sfc
self.results = self.tempStorage()
+ self.errorState = False
for opt in list(userOpts.keys()):
self.opts[opt] = userOpts[opt]
- # What events is this module interested in for input
def watchedEvents(self):
return ['INTERNET_NAME', "EMAILADDR", "DOMAIN_NAME"]
- # What events this module produces
- # This is to support the end user in selecting modules based on events
- # produced.
def producedEvents(self):
return ["EMAILADDR", "EMAILADDR_GENERIC", "AFFILIATE_EMAILADDR", "PGP_KEY"]
- # Handle events sent to this module
+ def queryDomain(self, keyserver_search_url, qry):
+ res = self.sf.fetchUrl(
+ keyserver_search_url + qry,
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent']
+ )
+
+ if not res:
+ return None
+
+ if res['content'] is None:
+ return None
+
+ if res['code'] == "503":
+ return None
+
+ return res
+
+ def queryEmail(self, keyserver_fetch_url, qry):
+ res = self.sf.fetchUrl(
+ keyserver_fetch_url + qry,
+ timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent']
+ )
+
+ if not res:
+ return None
+
+ if res['content'] is None:
+ return None
+
+ if res['code'] == "503":
+ return None
+
+ return res
+
def handleEvent(self, event):
eventName = event.eventType
- srcModuleName = event.module
eventData = event.data
+ if self.errorState:
+ return
+
if eventData in self.results:
return
self.results[eventData] = True
- self.debug(f"Received event, {eventName}, from {srcModuleName}")
+ self.debug(f"Received event, {eventName}, from {event.module}")
+
+ if not self.opts['keyserver_search1'] and not self.opts['keyserver_search2']:
+ self.error(f"You enabled {self.__class__.__name__} but did not set key server URLs")
+ self.errorState = True
+ return
# Get e-mail addresses on this domain
if eventName in ["DOMAIN_NAME", "INTERNET_NAME"]:
- res = self.sf.fetchUrl(self.opts['keyserver_search1'] + eventData,
- timeout=self.opts['_fetchtimeout'],
- useragent=self.opts['_useragent'])
-
- if res['content'] is None or res['code'] == "503":
- res = self.sf.fetchUrl(self.opts['keyserver_search2'] + eventData,
- timeout=self.opts['_fetchtimeout'],
- useragent=self.opts['_useragent'])
-
- if res['content'] is not None and res['code'] != "503":
- emails = SpiderFootHelpers.extractEmailsFromText(res['content'])
- for email in emails:
- if email.split("@")[0] in self.opts['_genericusers'].split(","):
- evttype = "EMAILADDR_GENERIC"
- else:
- evttype = "EMAILADDR"
-
- mailDom = email.lower().split('@')[1]
- if not self.getTarget().matches(mailDom):
- evttype = "AFFILIATE_EMAILADDR"
-
- self.info("Found e-mail address: " + email)
- evt = SpiderFootEvent(evttype, email, self.__name__, event)
- self.notifyListeners(evt)
-
- if eventName == "EMAILADDR":
- res = self.sf.fetchUrl(self.opts['keyserver_fetch1'] + eventData,
- timeout=self.opts['_fetchtimeout'],
- useragent=self.opts['_useragent'])
-
- if res['content'] is None or res['code'] == "503":
- res = self.sf.fetchUrl(self.opts['keyserver_fetch2'] + eventData,
- timeout=self.opts['_fetchtimeout'],
- useragent=self.opts['_useragent'])
-
- if res['content'] is not None and res['code'] != "503":
- pat = re.compile("(-----BEGIN.*END.*BLOCK-----)", re.MULTILINE | re.DOTALL)
- matches = re.findall(pat, str(res['content']))
- for match in matches:
- self.debug("Found public key: " + match)
- if len(match) < 300:
- self.debug("Likely invalid public key.")
- continue
-
- evt = SpiderFootEvent("PGP_KEY", match, self.__name__, event)
- self.notifyListeners(evt)
+ res = self.queryDomain(self.opts['keyserver_search1'], eventData)
+
+ if not res:
+ res = self.queryDomain(self.opts['keyserver_search2'], eventData)
+
+ if not res:
+ return
+
+ emails = SpiderFootHelpers.extractEmailsFromText(res['content'])
+ self.info(f"Found {len(emails)} email addresses")
+
+ for email in emails:
+ if email.split("@")[0] in self.opts['_genericusers'].split(","):
+ evttype = "EMAILADDR_GENERIC"
+ else:
+ evttype = "EMAILADDR"
+
+ mailDom = email.lower().split('@')[1]
+ if not self.getTarget().matches(mailDom):
+ evttype = "AFFILIATE_EMAILADDR"
+
+ self.debug(f"Found e-mail address: {email}")
+ evt = SpiderFootEvent(evttype, email, self.__name__, event)
+ self.notifyListeners(evt)
+
+ if eventName == "EMAILADDR" and self.opts['retrieve_keys']:
+ res = self.queryEmail(self.opts['keyserver_fetch1'], eventData)
+
+ if not res:
+ res = self.queryEmail(self.opts['keyserver_fetch2'], eventData)
+
+ if not res:
+ return
+
+ keys = SpiderFootHelpers.extractPgpKeysFromText(res['content'])
+ self.info(f"Found {len(keys)} public PGP keys")
+
+ for key in keys:
+ self.debug(f"Found public key: {key}")
+ evt = SpiderFootEvent("PGP_KEY", key, self.__name__, event)
+ self.notifyListeners(evt)
# End of sfp_pgp class
diff --git a/spiderfoot/helpers.py b/spiderfoot/helpers.py
index 5cf90f30..f58d0e08 100644
--- a/spiderfoot/helpers.py
+++ b/spiderfoot/helpers.py
@@ -690,6 +690,28 @@ class SpiderFootHelpers():
return returnArr
+ @staticmethod
+ def extractPgpKeysFromText(data: str) -> list:
+ """Extract all PGP keys within the supplied content.
+
+ Args:
+ data (str): text to search for PGP keys
+
+ Returns:
+ list: list of PGP keys
+ """
+ if not isinstance(data, str):
+ return list()
+
+ keys = set()
+
+ pattern = re.compile("(-----BEGIN.*?END.*?BLOCK-----)", re.MULTILINE | re.DOTALL)
+ for key in re.findall(pattern, data):
+ if len(key) >= 300:
+ keys.add(key)
+
+ return list(keys)
+
@staticmethod
def extractEmailsFromText(data: str) -> list:
"""Extract all email addresses within the supplied content.
diff --git a/test/unit/modules/test_sfp_pgp.py b/test/unit/modules/test_sfp_pgp.py
index 3debc8f0..6c898a4d 100644
--- a/test/unit/modules/test_sfp_pgp.py
+++ b/test/unit/modules/test_sfp_pgp.py
@@ -3,6 +3,7 @@ import unittest
from modules.sfp_pgp import sfp_pgp
from sflib import SpiderFoot
+from spiderfoot import SpiderFootEvent, SpiderFootTarget
@pytest.mark.usefixtures
@@ -24,3 +25,30 @@ class TestModulePgp(unittest.TestCase):
def test_producedEvents_should_return_list(self):
module = sfp_pgp()
self.assertIsInstance(module.producedEvents(), list)
+
+ def test_handleEvent_no_keyserver_urls_should_set_errorState(self):
+ sf = SpiderFoot(self.default_options)
+
+ module = sfp_pgp()
+ 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)
+
+ module.opts['keyserver_search1'] = ''
+ module.opts['keyserver_search2'] = ''
+ module.opts['keyserver_fetch1'] = ''
+ module.opts['keyserver_fetch2'] = ''
+
+ result = module.handleEvent(evt)
+
+ self.assertIsNone(result)
+ self.assertTrue(module.errorState)
diff --git a/test/unit/spiderfoot/test_spiderfoothelpers.py b/test/unit/spiderfoot/test_spiderfoothelpers.py
index c9969942..72480312 100644
--- a/test/unit/spiderfoot/test_spiderfoothelpers.py
+++ b/test/unit/spiderfoot/test_spiderfoothelpers.py
@@ -287,6 +287,15 @@ class TestSpiderFootHelpers(unittest.TestCase):
emails = SpiderFootHelpers.extractEmailsFromText(invalid_type)
self.assertIsInstance(emails, list)
+ def test_extractPgpKeysFromText_should_return_list_of_pgp_keys_from_string(self):
+ key1 = "-----BEGIN PGP PUBLIC KEY BLOCK-----Version: software v1.2.3\nComment: sample comment\n\nmQINBFRUAGoBEACuk6ze2V2pZtScf1Ul25N2CX19AeL7sVYwnyrTYuWdG2FmJx4x\nDLTLVUazp2AEm/JhskulL/7VCZPyg7ynf+o20Tu9/6zUD7p0rnQA2k3Dz+7dKHHh\neEsIl5EZyFy1XodhUnEIjel2nGe6f1OO7Dr3UIEQw5JnkZyqMcbLCu9sM2twFyfa\na8JNghfjltLJs3/UjJ8ZnGGByMmWxrWQUItMpQjGr99nZf4L+IPxy2i8O8WQewB5\nfvfidBGruUYC+mTw7CusaCOQbBuZBiYduFgH8hRW97KLmHn0xzB1FV++KI7syo8q\nXGo8Un24WP40IT78XjKO\n=nUop\n-----END PGP PUBLIC KEY BLOCK-----"
+ key2 = "-----BEGIN PGP PRIVATE KEY BLOCK-----Version: software v1.2.3\nComment: sample comment\n\nmQINBFRUAGoBEACuk6ze2V2pZtScf1Ul25N2CX19AeL7sVYwnyrTYuWdG2FmJx4x\nDLTLVUazp2AEm/JhskulL/7VCZPyg7ynf+o20Tu9/6zUD7p0rnQA2k3Dz+7dKHHh\neEsIl5EZyFy1XodhUnEIjel2nGe6f1OO7Dr3UIEQw5JnkZyqMcbLCu9sM2twFyfa\na8JNghfjltLJs3/UjJ8ZnGGByMmWxrWQUItMpQjGr99nZf4L+IPxy2i8O8WQewB5\nfvfidBGruUYC+mTw7CusaCOQbBuZBiYduFgH8hRW97KLmHn0xzB1FV++KI7syo8q\nXGo8Un24WP40IT78XjKO\n=nUop\n-----END PGP PRIVATE KEY BLOCK-----"
+ keys = SpiderFootHelpers.extractPgpKeysFromText(f"<html><body><p>sample{key1}sample</p><p>sample{key2}sample</p></body></html>")
+ self.assertIsInstance(keys, list)
+ self.assertIn(key1, keys)
+ self.assertIn(key2, keys)
+ self.assertEqual(len(keys), 2)
+
def test_extractIbansFromText_should_return_a_list(self):
invalid_types = [None, "", list(), dict()]
for invalid_type in invalid_types: