Skip to content

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

Search capabilities and cleaned up netblock/subnet handling.

smicallef3b73732dd3ef
diff --git a/dyn/newscan.tmpl b/dyn/newscan.tmpl
index fd9d6035..cde3ad74 100644
--- a/dyn/newscan.tmpl
+++ b/dyn/newscan.tmpl
@@ -52,7 +52,7 @@ Another scan is currently running (${runningScan}). Please either wait for that
<div class="control-group">
<label class="control-label" for="scantarget">Seed Target</label>
<div class="controls">
- <input type="text" rel='tooltip' data-html=true data-title='The <i>Seed Target</i> can be one of the following. SpiderFoot will automatically detect the target type based on the format of your input.<br><br><b>Domain Name</b>: e.g. <i>example.com</i><br><br><b>IP Address</b>: e.g. <i>1.2.3.4</i><br><br><b>Hostname/Sub-domain</b>: e.g. <i>abc.example.com</i><br><br><b>Subnet</b>: e.g. <i>1.2.3.0/24</i>' data-placement='right' id="scantarget" name="scantarget" placeholder="Starting point for the scan.">
+ <input type="text" data-toggle='popover' data-html=true data-animation=true data-title='Usage' data-content='The <i>Seed Target</i> can be one of the following. SpiderFoot will automatically detect the target type based on the format of your input.<br><br><b>Domain Name</b>: e.g. <i>example.com</i><br><br><b>IP Address</b>: e.g. <i>1.2.3.4</i><br><br><b>Hostname/Sub-domain</b>: e.g. <i>abc.example.com</i><br><br><b>Subnet</b>: e.g. <i>1.2.3.0/24</i>' data-placement='right' id="scantarget" name="scantarget" placeholder="Starting point for the scan.">
</div>
</div>
@@ -95,4 +95,7 @@ Another scan is currently running (${runningScan}). Please either wait for that
</div>
</div>
</form>
+<script type='text/javascript'>
+$('#scantarget').popover({ 'html': true, 'animation': true, 'trigger': 'focus'});
+</script>
<%include file="FOOTER.tmpl"/>
diff --git a/dyn/scaninfo.tmpl b/dyn/scaninfo.tmpl
index bac9b7f6..0d4dc5d3 100644
--- a/dyn/scaninfo.tmpl
+++ b/dyn/scaninfo.tmpl
@@ -8,9 +8,15 @@
<a id='btn-log' class="btn" onClick='viewScanLog("${id}")'><i class='icon-book'></i>&nbsp;Log</a>
</div>
<button class='btn btn-info disabled' id='scanreminder'>This page automatically reloads data every 5 seconds.</button>
+ <div id='btn-search' class='btn-group pull-right input-append'>
+ <input class=span2 id=searchvalue type=text placeholder='Search...' data-toggle='popover' data-html=true data-animation=true data-title='Usage' data-content="Supply a regular expression encapsulated in '/', e.g. <i>/searchstring/</i> or a simple wildcard search, e.g. <i>*string*</i> or an exact value, e.g. <i>string</i>.">
+ <button class='btn btn-primary' type=button onClick=$('#btn-search').popover('toggle');searchDirector('${id}')>
+ <i class='icon-search icon-white'></i>
+ </button>
+ </div>
<div class="btn-group pull-right">
<a id='btn-refresh' rel="tooltip" title="Refresh" class="btn-success btn" onClick='refresh()'><i class='icon-refresh icon-white'></i></a>
- <a id='btn-export' rel="tooltip" title="Export Data to CSV" class="btn-info btn" onClick='exportEventData("${id}", currentType)'><i class='icon-download-alt icon-white'></i></a>
+ <a id='btn-export' rel="tooltip" title="Export Data to CSV" class="btn-success btn" onClick='exportEventData("${id}", currentType)'><i class='icon-download-alt icon-white'></i></a>
</div>
<div id='customview' class="btn-group pull-right">
<a id='btn-fullview' rel="tooltip" data-title="Full Data View" class="btn-inverse btn active" onClick='browseUpdate("full")'><i class='icon-th icon-white'></i></a>
@@ -26,9 +32,14 @@
<script type='text/javascript'>
var currentType = "ALL";
+ var currentTypeName = "All";
+ var currentSection = "btn-browse";
+ var lastSearchType = "ALL";
+ var lastSearchQuery = "";
var dataloaders = [];
var loadersrunning = false;
var refresh = function() { browseEventList("${id}"); }
+ $('#searchvalue').popover({ 'trigger': 'focus', 'placement': 'bottom'});
function navTo(target) {
var targets = [ "btn-browse", "btn-info", "btn-log",
@@ -43,9 +54,75 @@
$("#breadcrumbs").remove();
$("#customview").hide();
+ currentSection = target
dataloaders = []
}
+ function searchDirector(instanceId) {
+ qry = $("#searchvalue").val();
+ if (currentType == "ALL") {
+ searchResults(instanceId, qry);
+ } else {
+ searchResults(instanceId, qry, currentType);
+ }
+ }
+
+ function searchResults(instanceId, query, typeName=null) {
+ // Remove pre-existing tables if they exist
+ $("#scansummary-content").remove();
+ navTo("btn-search");
+ $("#loader").show();
+ $("#btn-export").show();
+ $("#btn-refresh").show();
+ $("#btn-search").show();
+ $("#scanreminder").hide();
+ refresh = function() { searchResults(instanceId, query, typeName); }
+ sf.search(instanceId, query, typeName, function(data) {
+ lastSearchType = typeName;
+ lastSearchQuery = query;
+ var crumbs = " <ul class='breadcrumb' id='breadcrumbs'> <li><a class='link' onClick='browseEventList(\"" + instanceId + "\");'>Browse</a>";
+ crumbs += " <span class='divider'>&gt;</span></li>";
+ if (typeName != null) {
+ crumbs += " <li><a class='link' onClick=";
+ crumbs += "'browseEventData(\"" + instanceId + "\",\"" + currentTypeName + "\",\"" + typeName + "\",\"full\");'>";
+ crumbs += unescape(currentTypeName) + "</a><span class='divider'>&gt;</span></li>";
+ }
+ crumbs += "<li>Search results for '" + query + "'";
+ crumbs += " (" + data.length + " records)</li></ul>";
+
+ if (data.length == 0) {
+ var table = "<div id='scansummary-content'>&nbsp;&nbsp;No results found. Try broadening your search criteria.</div>";
+ } else {
+ var table = "<table id='scansummary-content' class='table table-bordered table-striped small'><thead><tr>";
+ if (typeName == null) {
+ table += "<th>Data Element Type</th>";
+ }
+ table += "<th>Data Element</th><th>Source Data Element</th><th>Source Module</th><th>Identified</th></tr></thead><tbody>";
+ for (var i = 0; i < data.length; i++) {
+ table += "<tr>";
+ if (typeName == null) {
+ table += "<td>" + data[i][8] + "</td>";
+ }
+ table += "<td><pre style='border: 0px; background-color: inherit'>";
+ //table += "<a href='/entityinfo?id=" + data[i][7] + "'>" + data[i][1] + "</a>";
+ table += sf.replace_sfurltag(data[i][1]);
+ // for debug
+ //table += "</pre></td><td><pre style='border: 0px; background-color: inherit'>" + data[i][7];
+ //table += "</pre></td><td><pre style='border: 0px; background-color: inherit'>" + data[i][5];
+ //table += "</pre></td><td><pre style='border: 0px; background-color: inherit'>" + data[i][6];
+ table += "</pre></td><td><pre style='border: 0px; background-color: inherit'>" + data[i][2];
+ table += "</pre></td><td><pre style='border: 0px; background-color: inherit'>" + data[i][3];
+ table += "</pre></td><td><pre style='border: 0px; background-color: inherit'>" + data[i][0];
+ table += "</pre></td>";
+ table += "</tr>";
+ }
+ table += "</tbody></table>"
+ }
+ $("#loader").fadeOut(500);
+ $("#mainbody").append(crumbs + table);
+ });
+ }
+
// Scan status
function scanStatusView(instanceId) {
grid = "<div id='scansummary-content'>"
@@ -72,6 +149,7 @@
$("#loader").show();
$("#btn-export").hide();
$("#btn-refresh").hide();
+ $("#btn-search").hide();
$("#scanreminder").show();
navTo("btn-status");
@@ -202,6 +280,7 @@
// Summary of event types and counts for a scan
function browseEventList(instanceId) {
currentType = "ALL";
+ currentTypeName = "All";
// Remove pre-existing tables if they exist
$("#scansummary-content").remove();
@@ -209,6 +288,7 @@
$("#loader").show();
$("#btn-export").show();
$("#btn-refresh").show();
+ $("#btn-search").show();
$("#scanreminder").hide();
refresh = function() { browseEventList(instanceId); }
sf.fetchData('/scansummary', {'id': instanceId}, function(data) {
@@ -245,6 +325,7 @@
$("#customview").show();
$("#scanreminder").hide();
currentType = eventType;
+ currentTypeName = eventTypeLabel;
refresh = function() { browseEventData(instanceId, eventTypeLabel, eventType, format); }
browseUpdate = function(newformat) { browseEventData(instanceId, eventTypeLabel, eventType, newformat); }
@@ -350,7 +431,11 @@
function exportEventData(instanceId, eventType) {
$("#loader").show();
var efr = document.getElementById('exportframe');
- efr.src = '/scaneventresultexport?id=' + instanceId + '&type=' + eventType;
+ if (currentSection == "btn-search") {
+ efr.src = '/scansearchresultexport?id=' + instanceId + '&eventType=' + lastSearchType + "&value=" + lastSearchQuery;
+ } else {
+ efr.src = '/scaneventresultexport?id=' + instanceId + '&type=' + eventType;
+ }
$("#loader").fadeOut(500);
}
@@ -360,6 +445,7 @@
$("#loader").show();
$("#btn-export").hide();
$("#btn-refresh").show();
+ $("#btn-search").hide();
$("#scanreminder").hide();
navTo("btn-info");
refresh = function() { viewScanConfig(instanceId); }
diff --git a/evtypes.sql b/evtypes.sql
index b2dd8f8e..dd2f0bd0 100644
--- a/evtypes.sql
+++ b/evtypes.sql
@@ -6,8 +6,11 @@ INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('AFFILIATE_I
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('AFFILIATE_WEB_CONTENT', 'Affiliate - Web Content', 1);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('BGP_AS_OWNER', 'BGP AS Ownership', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('BGP_AS_MEMBER', 'BGP AS Membership', 0);
+INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('BGP_AS_PEER', 'BGP AS Peer', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('BLACKLISTED_IPADDR', 'Blacklisted IP Address', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('BLACKLISTED_AFFILIATE_IPADDR', 'Blacklisted Affiliate IP Address', 0);
+INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('BLACKLISTED_SUBNET', 'Blacklisted IP on Same Subnet', 0);
+INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('BLACKLISTED_NETBLOCK', 'Blacklisted IP on Owned Netblock', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('EMAILADDR', 'Email Address', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('CO_HOSTED_SITE', 'Co-Hosted Site', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('DEFACED_INTERNET_NAME', 'Defaced', 0);
@@ -23,7 +26,6 @@ INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('HUMAN_NAME'
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('INTERESTING_FILE', 'Interesting File', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('INTERNET_NAME', 'Internet Name', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('IP_ADDRESS', 'IP Address', 0);
-INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('IP_SUBNET', 'IP Subnet', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('LINKED_URL_INTERNAL', 'Linked URL - Internal', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('LINKED_URL_EXTERNAL', 'Linked URL - External', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('MALICIOUS_ASN', 'Malicious AS', 0);
@@ -34,11 +36,11 @@ INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('MALICIOUS_A
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('MALICIOUS_AFFILIATE_IPADDR', 'Malicious Affiliate IP Address', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('MALICIOUS_NETBLOCK', 'Malicious IP on Owned Netblock', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('MALICIOUS_SUBNET', 'Malicious IP on Same Subnet', 0);
-INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('NETBLOCK', 'Netblock Ownership', 0);
+INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('NETBLOCK_OWNER', 'Netblock Ownership', 0);
+INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('NETBLOCK_MEMBER', 'Netblock Membership', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('OPERATING_SYSTEM', 'Operating System', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('PASTEBIN_CONTENT', 'PasteBin Content', 1);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('PROVIDER_DNS', 'Name Server (DNS ''NS'' Records)', 0);
-INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('PROVIDER_INTERNET', 'Internet Service Provider', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('PROVIDER_JAVASCRIPT', 'Externally Hosted Javascript', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('PROVIDER_MAIL', 'Email Gateway (DNS ''MX'' Records)', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('RAW_RIR_DATA', 'Raw Data from RIRs', 1);
diff --git a/modules/sfp_blacklist.py b/modules/sfp_blacklist.py
index 29560971..8778d538 100644
--- a/modules/sfp_blacklist.py
+++ b/modules/sfp_blacklist.py
@@ -11,10 +11,12 @@
# Licence: GPL
#-------------------------------------------------------------------------------
+import netaddr
import sys
import re
import socket
import random
+from netaddr import IPNetwork
from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent
class sfp_blacklist(SpiderFootPlugin):
@@ -22,10 +24,18 @@ class sfp_blacklist(SpiderFootPlugin):
# Default options
opts = {
+ 'netblocklookup': True,
+ 'maxnetblock': 24,
+ 'subnetlookup': True,
+ 'maxsubnet': 24
}
# Option descriptions
optdescs = {
+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible blacklisted hosts on the same target subdomain/domain?",
+ 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'subnetlookup': "Look up all IPs on subnets which your target is a part of for blacklisting?",
+ 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"
}
# Target
@@ -80,79 +90,99 @@ class sfp_blacklist(SpiderFootPlugin):
# What events is this module interested in for input
def watchedEvents(self):
- return [ 'IP_ADDRESS', 'AFFILIATE_IPADDR' ]
+ return [ 'IP_ADDRESS', 'AFFILIATE_IPADDR', 'NETBLOCK_OWNER',
+ 'NETBLOCK_MEMBER' ]
# What events this module produces
# This is to support the end user in selecting modules based on events
# produced.
def producedEvents(self):
- return [ "BLACKLISTED_IPADDR", "BLACKLISTED_AFFILIATE_IPADDR" ]
+ return [ "BLACKLISTED_IPADDR", "BLACKLISTED_AFFILIATE_IPADDR",
+ "BLACKLISTED_SUBNET", "BLACKLISTED_NETBLOCK" ]
# Swap 1.2.3.4 to 4.3.2.1
def reverseAddr(self, ipaddr):
return '.'.join(reversed(ipaddr.split('.')))
- # Handle events sent to this module
- def handleEvent(self, event):
- eventName = event.eventType
- srcModuleName = event.module
- eventData = event.data
- parentEvent = event
-
- self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)
-
- if self.results.has_key(eventData):
- return None
-
- self.results[eventData] = True
+ def queryAddr(self, qaddr, parentEvent):
+ eventName = parentEvent.eventType
for domain in self.checks:
+ if self.checkForStop():
+ return None
+
try:
- lookup = self.reverseAddr(eventData) + "." + domain
+ lookup = self.reverseAddr(qaddr) + "." + domain
self.sf.debug("Checking Blacklist: " + lookup)
- addrs = socket.gethostbyname_ex(lookup)
+ addrs = self.sf.normalizeDNS(socket.gethostbyname_ex(lookup))
self.sf.debug("Addresses returned: " + str(addrs))
text = None
for addr in addrs:
- if type(addr) == list:
- for a in addr:
- if type(self.checks[domain]) is str:
- text = self.checks[domain]
- break
- else:
- if str(a) not in self.checks[domain].keys():
- self.sf.debug("Return code not found in list: " + str(a))
- continue
- k = str(a)
- text = self.checks[domain][k]
- break
-
+ if type(self.checks[domain]) is str:
+ text = self.checks[domain] + " (" + qaddr + ")"
+ break
else:
- if type(self.checks[domain]) is str:
- text = self.checks[domain]
- break
- else:
- if str(addr) not in self.checks.keys():
- self.sf.debug("Return code not found in list: " + str(addr))
- continue
-
- k = str(addr)
- text = self.checks[domain][k]
- break
-
+ if str(addr) not in self.checks[domain].keys():
+ self.sf.debug("Return code not found in list: " + str(addr))
+ continue
+
+ k = str(addr)
+ text = self.checks[domain][k] + " (" + qaddr + ")"
+ break
+
if text != None:
if eventName == "AFFILIATE_IPADDR":
- evt = SpiderFootEvent('BLACKLISTED_AFFILIATE_IPADDR',
- text, self.__name__, parentEvent)
- self.notifyListeners(evt)
- else:
- evt = SpiderFootEvent('BLACKLISTED_IPADDR',
- text, self.__name__, parentEvent)
- self.notifyListeners(evt)
+ e = "BLACKLISTED_AFFILIATE_IPADDR"
+ if eventName == "IP_ADDRESS":
+ e = "BLACKLISTED_IPADDR"
+ if eventName == "NETBLOCK_OWNER":
+ e = "BLACKLISTED_NETBLOCK"
+ if eventName == "NETBLOCK_MEMBER":
+ e = "BLACKLISTED_SUBNET"
+
+ evt = SpiderFootEvent(e, text, self.__name__, parentEvent)
+ self.notifyListeners(evt)
+
except BaseException as e:
- self.sf.debug("Unable to resolve " + eventData + " / " + lookup + ": " + str(e))
-
+ self.sf.debug("Unable to resolve " + qaddr + " / " + lookup + ": " + str(e))
+
return None
+ # Handle events sent to this module
+ def handleEvent(self, event):
+ eventName = event.eventType
+ srcModuleName = event.module
+ eventData = event.data
+ parentEvent = event
+ addrlist = list()
+
+ self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)
+
+ if self.results.has_key(eventData):
+ return None
+ self.results[eventData] = True
+
+ if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:
+ if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:
+ self.sf.debug("Network size bigger than permitted: " + \
+ str(IPNetwork(eventData).prefixlen) + " > " + \
+ str(self.opts['maxnetblock']))
+ return None
+
+ if eventName == 'NETBLOCK_MEMBER' and self.opts['subnetlookup']:
+ if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:
+ self.sf.debug("Network size bigger than permitted: " + \
+ str(IPNetwork(eventData).prefixlen) + " > " + \
+ str(self.opts['maxsubnet']))
+ return None
+
+ if eventName.startswith("NETBLOCK_"):
+ for addr in IPNetwork(eventData):
+ if self.checkForStop():
+ return None
+ self.queryAddr(str(addr), parentEvent)
+ else:
+ self.queryAddr(eventData, parentEvent)
+
# End of sfp_blacklist class
diff --git a/modules/sfp_dns.py b/modules/sfp_dns.py
index 7f76e8d7..e7dbaea3 100644
--- a/modules/sfp_dns.py
+++ b/modules/sfp_dns.py
@@ -25,7 +25,6 @@ class sfp_dns(SpiderFootPlugin):
# Default options
opts = {
- 'subnetlookup': True,
'netblocklookup': True,
'maxnetblock': 24,
'lookaside': True,
@@ -43,9 +42,8 @@ class sfp_dns(SpiderFootPlugin):
# Option descriptions
optdescs = {
'skipcommononwildcard': "If wildcard DNS is detected, only attempt to look up the first common sub-domain from the common sub-domain list.",
- 'subnetlookup': "Look up all IPs on identified subnets associated with your target for possible hosts on the same target subdomain/domain?",
- 'netblocklookup': "Look up all IPs on netblocks deemed to be 'owned' by your target for possible hosts on the same target subdomain/domain?",
- 'maxnetblock': "Maximum netblock/subnet size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible hosts on the same target subdomain/domain?",
+ 'maxnetblock': "Maximum owned netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
'onlyactive': "Only report sub-domains/hostnames that resolve to an IP.",
'validatereverse': "Validate that reverse-resolved hostnames still resolve back to that IP before considering them as aliases of your target.",
'lookaside': "For each IP discovered, try and reverse look-up IPs 'next to' that IP for potential hostnames on the same subdomain/domain.",
@@ -82,7 +80,7 @@ class sfp_dns(SpiderFootPlugin):
ret = self.resolveIP(target.getValue())
if target.getType() == "INTERNET_NAME":
ret = self.resolveHost(target.getValue())
- if target.getType() == "IP_SUBNET":
+ if target.getType() == "NETBLOCK_OWNER":
ret = list()
for addr in IPNetwork(target.getValue()):
ipaddr = str(addr)
@@ -123,7 +121,7 @@ class sfp_dns(SpiderFootPlugin):
def watchedEvents(self):
arr = ['RAW_DNS_RECORDS', 'SEARCH_ENGINE_WEB_CONTENT', 'RAW_RIR_DATA',
'TARGET_WEB_CONTENT', 'LINKED_URL_INTERNAL', 'INTERNET_NAME',
- 'IP_ADDRESS', 'NETBLOCK', 'IP_SUBNET']
+ 'IP_ADDRESS', 'NETBLOCK_OWNER']
return arr
# What events this module produces
@@ -164,19 +162,14 @@ class sfp_dns(SpiderFootPlugin):
# Nothing left to do with internal links and raw data
return None
- if eventName in [ 'NETBLOCK', 'IP_SUBNET' ]:
- if eventName == 'NETBLOCK' and not self.opts['netblocklookup']:
- return None
- if eventName == 'IP_SUBNET' and not self.opts['subnetlookup']:
- return None
-
+ if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:
if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:
self.sf.debug("Network size bigger than permitted: " + \
str(IPNetwork(eventData).prefixlen) + " > " + \
str(self.opts['maxnetblock']))
return None
- self.sf.debug("Looking up IPs in " + eventData)
+ self.sf.debug("Looking up IPs in owned netblock: " + eventData)
for ip in IPNetwork(eventData):
ipaddr = str(ip)
if ipaddr.split(".")[3] in [ '255', '0']:
@@ -192,15 +185,6 @@ class sfp_dns(SpiderFootPlugin):
self.sf.debug("Found a reversed hostname from " + ipaddr + \
" (" + str(addrs) + ")")
for addr in addrs:
- # Don't report on anything on the same subnet if
- # if doesn't resolve to something on the target
- # domain/sub-domain.
- # e.g. we don't report if 1.2.3.5 (IP next to
- # target 1.2.3.4) resolves to a hostname on a
- # completely differtent domain.
- if not self.getTarget().matches(addr) \
- and eventName == 'IP_SUBNET':
- continue
# Generate an event for the IP, then
# let the handling by this module take
# care of follow-up processing.
diff --git a/modules/sfp_honeypot.py b/modules/sfp_honeypot.py
index 21305b17..2b9726bd 100644
--- a/modules/sfp_honeypot.py
+++ b/modules/sfp_honeypot.py
@@ -14,6 +14,7 @@ import sys
import re
import socket
import random
+from netaddr import IPNetwork
from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent
class sfp_honeypot(SpiderFootPlugin):
@@ -24,7 +25,11 @@ class sfp_honeypot(SpiderFootPlugin):
'apikey': "",
'searchengine': False,
'threatscore': 0,
- 'timelimit': 30
+ 'timelimit': 30,
+ 'netblocklookup': True,
+ 'maxnetblock': 24,
+ 'subnetlookup': True,
+ 'maxsubnet': 24
}
# Option descriptions
@@ -32,7 +37,11 @@ class sfp_honeypot(SpiderFootPlugin):
'apikey': "The API key you obtained from projecthoneypot.org",
'searchengine': "Include entries considered search engines?",
'threatscore': "Threat score minimum, 0 being everything and 255 being only the most serious.",
- 'timelimit': "Maximum days old an entry can be. 255 is the maximum, 0 means you'll get nothing."
+ 'timelimit': "Maximum days old an entry can be. 255 is the maximum, 0 means you'll get nothing.",
+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible hosts on the same target subdomain/domain?",
+ 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'subnetlookup': "Look up all IPs on subnets which your target is a part of?",
+ 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"
}
results = dict()
@@ -62,13 +71,15 @@ class sfp_honeypot(SpiderFootPlugin):
# What events is this module interested in for input
def watchedEvents(self):
- return [ 'IP_ADDRESS', 'AFFILIATE_IPADDR' ]
+ return [ 'IP_ADDRESS', 'AFFILIATE_IPADDR', 'NETBLOCK_OWNER',
+ 'NETBLOCK_MEMBER' ]
# What events this module produces
# This is to support the end user in selecting modules based on events
# produced.
def producedEvents(self):
- return [ "BLACKLISTED_IPADDR", "BLACKLISTED_AFFILIATE_IPADDR" ]
+ return [ "BLACKLISTED_IPADDR", "BLACKLISTED_AFFILIATE_IPADDR",
+ "BLACKLISTED_SUBNET", "BLACKLISTED_NETBLOCK" ]
# Swap 1.2.3.4 to 4.3.2.1
def reverseAddr(self, ipaddr):
@@ -86,17 +97,55 @@ class sfp_honeypot(SpiderFootPlugin):
if int(bits[3]) == 0 and self.opts['searchengine']:
return None
- text = "Honeypotproject: " + self.statuses[bits[3]] + \
+ text = "Honeypotproject ({0}): " + self.statuses[bits[3]] + \
"\nLast Activity: " + bits[1] + " days ago" + \
"\nThreat Level: " + bits[2]
return text
+ def queryAddr(self, qaddr, parentEvent):
+ eventName = parentEvent.eventType
+
+ try:
+ lookup = self.opts['apikey'] + "." + \
+ self.reverseAddr(qaddr) + ".dnsbl.httpbl.org"
+
+ self.sf.debug("Checking Honeypot: " + lookup)
+ addrs = self.sf.normalizeDNS(socket.gethostbyname_ex(lookup))
+ self.sf.debug("Addresses returned: " + str(addrs))
+
+ text = None
+ for addr in addrs:
+ text = self.reportIP(addr)
+ if text == None:
+ continue
+ else:
+ break
+
+ if text != None:
+ if eventName == "AFFILIATE_IPADDR":
+ e = "BLACKLISTED_AFFILIATE_IPADDR"
+ if eventName == "IP_ADDRESS":
+ e = "BLACKLISTED_IPADDR"
+ if eventName == "NETBLOCK_OWNER":
+ e = "BLACKLISTED_NETBLOCK"
+ if eventName == "NETBLOCK_MEMBER":
+ e = "BLACKLISTED_SUBNET"
+
+ evt = SpiderFootEvent(e, text.format(qaddr), self.__name__,
+ parentEvent)
+ self.notifyListeners(evt)
+ except BaseException as e:
+ self.sf.debug("Unable to resolve " + qaddr + " / " + lookup + ": " + str(e))
+
+ return None
+
# Handle events sent to this module
def handleEvent(self, event):
eventName = event.eventType
srcModuleName = event.module
eventData = event.data
parentEvent = event
+ addrlist = list()
self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)
@@ -108,40 +157,26 @@ class sfp_honeypot(SpiderFootPlugin):
return None
self.results[eventData] = True
- try:
- lookup = self.opts['apikey'] + "." + \
- self.reverseAddr(eventData) + ".dnsbl.httpbl.org"
-
- self.sf.debug("Checking Honeypot: " + lookup)
- addrs = socket.gethostbyname_ex(lookup)
- self.sf.debug("Addresses returned: " + str(addrs))
-
- text = None
- for addr in addrs:
- if type(addr) == list:
- for a in addr:
- text = self.reportIP(a)
- if text == None:
- continue
- else:
- break
- else:
- text = self.reportIP(addr)
- if text == None:
- continue
- else:
- break
+ if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:
+ if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:
+ self.sf.debug("Network size bigger than permitted: " + \
+ str(IPNetwork(eventData).prefixlen) + " > " + \
+ str(self.opts['maxnetblock']))
+ return None
+
+ if eventName == 'NETBLOCK_MEMBER' and self.opts['subnetlookup']:
+ if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:
+ self.sf.debug("Network size bigger than permitted: " + \
+ str(IPNetwork(eventData).prefixlen) + " > " + \
+ str(self.opts['maxsubnet']))
+ return None
+
+ if eventName.startswith("NETBLOCK_"):
+ for addr in IPNetwork(eventData):
+ if self.checkForStop():
+ return None
+ self.queryAddr(str(addr), parentEvent)
+ else:
+ self.queryAddr(eventData, parentEvent)
- if text != None:
- if eventName == "AFFILIATE_IPADDR":
- evt = SpiderFootEvent('BLACKLISTED_AFFILIATE_IPADDR',
- text, self.__name__, parentEvent)
- self.notifyListeners(evt)
- else:
- evt = SpiderFootEvent('BLACKLISTED_IPADDR',
- text, self.__name__, parentEvent)
- self.notifyListeners(evt)
- except BaseException as e:
- self.sf.debug("Unable to resolve " + eventData + " / " + lookup + ": " + str(e))
-
# End of sfp_honeypot class
diff --git a/modules/sfp_ir.py b/modules/sfp_ir.py
index 8faf4047..95ad789d 100644
--- a/modules/sfp_ir.py
+++ b/modules/sfp_ir.py
@@ -39,13 +39,15 @@ class sfp_ir(SpiderFootPlugin):
# What events is this module interested in for input
def watchedEvents(self):
- return ['IP_ADDRESS']
+ return ['IP_ADDRESS', 'NETBLOCK_MEMBER', 'NETBLOCK_OWNER',
+ 'BGP_AS_OWNER', 'BGP_AS_MEMBER' ]
# What events this module produces
# This is to support the end user in selecting modules based on events
# produced.
def producedEvents(self):
- return [ "NETBLOCK", "RAW_RIR_DATA", "BGP_AS_OWNER", "PROVIDER_INTERNET" ]
+ return [ "NETBLOCK_MEMBER", "NETBLOCK_OWNER", "BGP_AS_MEMBER",
+ "RAW_RIR_DATA", "BGP_AS_OWNER", "BGP_AS_PEER" ]
# Fetch content and notify of the raw data
def fetchRir(self, url):
@@ -129,6 +131,7 @@ class sfp_ir(SpiderFootPlugin):
for d in rec:
if d["key"].lower().startswith("org") or \
d["key"].lower().startswith("as") or \
+ d["key"].lower().startswith("aut") or \
d["key"].lower().startswith("descr") and \
d["value"].lower() not in [ "null", "none", "none specified" ]:
if ownerinfo.has_key(d["key"]):
@@ -217,6 +220,20 @@ class sfp_ir(SpiderFootPlugin):
return False
+ # Owns the AS or not?
+ def ownsAs(self, asn):
+ # Determine whether the AS is owned by our target
+ ownerinfo = self.asOwnerInfo(asn)
+ owned = False
+
+ if ownerinfo != None:
+ for k in ownerinfo.keys():
+ items = ownerinfo[k]
+ for item in items:
+ if self.findName(item.lower()):
+ owned = True
+ return owned
+
# Handle events sent to this module
def handleEvent(self, event):
eventName = event.eventType
@@ -233,83 +250,86 @@ class sfp_ir(SpiderFootPlugin):
else:
self.results[eventData] = True
- prefix = self.ipNetblock(eventData)
- if prefix == None:
- self.sf.debug("Could not identify network prefix.")
- return None
-
- asn = self.netblockAs(prefix)
- if asn == None:
- self.sf.debug("Could not identify netblock AS.")
- return None
+ # BGP AS Owner/Member -> BGP AS Peers
+ if eventName.startswith("BGP_AS_"):
+ neighs = self.asNeighbours(eventData)
+ if neighs == None:
+ self.debug("No neighbors found to AS " + eventData)
+ return None
- ownerinfo = self.asOwnerInfo(asn)
- owned = False
+ for nasn in neighs:
+ if self.checkForStop():
+ return None
- if ownerinfo != None:
- for k in ownerinfo.keys():
- items = ownerinfo[k]
- for item in items:
- if self.findName(item.lower()):
- owned = True
+ ownerinfo = self.asOwnerInfo(nasn)
+ ownertext = ''
+ if ownerinfo != None:
+ for k, v in ownerinfo.iteritems():
+ ownertext = ownertext + k + ": " + ', '.join(v) + "\n"
- if owned:
- self.sf.info("Owned netblock found: " + prefix + "(" + asn + ")")
- evt = SpiderFootEvent("NETBLOCK", prefix, self.__name__, event)
- self.notifyListeners(evt)
- asevt = SpiderFootEvent("BGP_AS_OWNER", asn, self.__name__, event)
- self.notifyListeners(asevt)
+ if len(ownerinfo) > 0:
+ evt = SpiderFootEvent("BGP_AS_PEER", ownertext,
+ self.__name__, event)
+ self.notifyListeners(evt)
+ # BGP AS Owner -> Other Netblocks
+ if eventName == "BGP_AS_OWNER":
# Don't report additional netblocks from this AS if we've
# already found this AS before.
- if not self.nbreported.has_key(asn):
- # 2. Find all the netblocks owned by this AS
+ if not self.nbreported.has_key(eventData):
+ # Find all the netblocks owned by this AS
self.nbreported[asn] = True
- netblocks = self.asNetblocks(asn)
+ netblocks = self.asNetblocks(eventData)
if netblocks != None:
for netblock in netblocks:
- if netblock == prefix:
+ if self.results.has_key(netblock):
continue
-
+
# Technically this netblock was identified via the AS, not
# the original IP event, so link it to asevt, not event.
- evt = SpiderFootEvent("NETBLOCK", netblock,
- self.__name__, asevt)
+ evt = SpiderFootEvent("NETBLOCK_OWNER", netblock,
+ self.__name__, event)
self.notifyListeners(evt)
+ return None
- # 3. Find all the AS neighbors to this AS
- neighs = self.asNeighbours(asn)
- if neighs == None:
- return None
+ # NETBLOCK -> AS and other owned netblocks
+ if eventName.startswith("NETBLOCK_"):
+ # Get the BGP AS the netblock is a part of
+ asn = self.netblockAs(eventData)
+ if asn == None:
+ self.sf.debug("Could not identify BGP AS for " + eventData)
+ return None
+
+ if self.ownsAs(asn):
+ asevt = SpiderFootEvent("BGP_AS_OWNER", asn, self.__name__, event)
+ self.notifyListeners(asevt)
+ else:
+ asevt = SpiderFootEvent("BGP_AS_MEMBER", asn, self.__name__, event)
+ self.notifyListeners(asevt)
- for nasn in neighs:
- if self.checkForStop():
- return None
-
- ownerinfo = self.asOwnerInfo(nasn)
- ownertext = ''
- if ownerinfo != None:
- for k, v in ownerinfo.iteritems():
- ownertext = ownertext + k + ": " + ', '.join(v) + "\n"
-
- if len(ownerinfo) > 0:
- evt = SpiderFootEvent("PROVIDER_INTERNET", ownertext,
- self.__name__, asevt)
- self.notifyListeners(evt)
- else:
- # If they don't own the netblock they are serving from, then
- # the netblock owner is their Internet provider.
-
- # Report the netblock instead as a subnet encapsulating the IP
- evt = SpiderFootEvent("IP_SUBNET", prefix, self.__name__, event)
- self.notifyListeners(evt)
-
- ownertext = ''
- if ownerinfo != None:
- for k, v in ownerinfo.iteritems():
- ownertext = ownertext + k + ": " + ', '.join(v) + "\n"
- evt = SpiderFootEvent("PROVIDER_INTERNET", ownertext,
- self.__name__, event)
+ return None
+
+ # IP ADDRESS -> NETBLOCK
+ if eventName == "IP_ADDRESS":
+ # Get the Netblock the IP is a part of
+ prefix = self.ipNetblock(eventData)
+ if prefix == None:
+ self.sf.debug("Could not identify network prefix for " + eventData)
+ return None
+
+ # Get the BGP AS the netblock is a part of
+ asn = self.netblockAs(prefix)
+ if asn == None:
+ self.sf.debug("Could not identify BGP AS for " + prefix)
+ return None
+
+ if self.ownsAs(asn):
+ self.sf.info("Owned netblock found: " + prefix + "(" + asn + ")")
+ evt = SpiderFootEvent("NETBLOCK_OWNER", prefix, self.__name__, event)
+ self.notifyListeners(evt)
+ else:
+ self.sf.info("Netblock found: " + prefix + "(" + asn + ")")
+ evt = SpiderFootEvent("NETBLOCK_MEMBER", prefix, self.__name__, event)
self.notifyListeners(evt)
return None
diff --git a/modules/sfp_malcheck.py b/modules/sfp_malcheck.py
index ea89ee8d..dd341e7d 100644
--- a/modules/sfp_malcheck.py
+++ b/modules/sfp_malcheck.py
@@ -278,9 +278,9 @@ class sfp_malcheck(SpiderFootPlugin):
# What events is this module interested in for input
# * = be notified about all events.
def watchedEvents(self):
- return ["INTERNET_NAME", "IP_ADDRESS", "BGP_AS_OWNER",
- "IP_SUBNET", "AFFILIATE_INTERNET_NAME", "AFFILIATE_IPADDR",
- "CO_HOSTED_SITE", "NETBLOCK" ]
+ return ["INTERNET_NAME", "IP_ADDRESS", "BGP_AS_OWNER", "BGP_AS_MEMBER",
+ "NETBLOCK_MEMBER", "AFFILIATE_INTERNET_NAME", "AFFILIATE_IPADDR",
+ "CO_HOSTED_SITE", "NETBLOCK_OWNER" ]
# What events this module produces
# This is to support the end user in selecting modules based on events
@@ -288,7 +288,7 @@ class sfp_malcheck(SpiderFootPlugin):
def producedEvents(self):
return [ "MALICIOUS_ASN", "MALICIOUS_IPADDR", "MALICIOUS_INTERNET_NAME",
"MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_AFFILIATE_INTERNET_NAME",
- "MALICIOUS_SUBNET", "MALICIOUS_COHOST" ]
+ "MALICIOUS_SUBNET", "MALICIOUS_COHOST", "MALICIOUS_NETBLOCK" ]
# Check the regexps to see whether the content indicates maliciousness
def contentMalicious(self, content, goodregex, badregex):
@@ -433,9 +433,9 @@ class sfp_malcheck(SpiderFootPlugin):
if eventName == 'AFFILIATE_DOMAIN' or eventName == 'AFFILIATE_IPADDR' \
and not self.opts['aaacheckaffiliates']:
return None
- if eventName == 'NETBLOCK' and not self.opts['aaachecknetblocks']:
+ if eventName == 'NETBLOCK_OWNER' and not self.opts['aaachecknetblocks']:
return None
- if eventName == 'IP_SUBNET' and not self.opts['aaachecksubnets']:
+ if eventName == 'NETBLOCK_MEMBER' and not self.opts['aaachecksubnets']:
return None
for check in malchecks.keys():
@@ -449,7 +449,7 @@ class sfp_malcheck(SpiderFootPlugin):
else:
evtType = 'MALICIOUS_AFFILIATE_IPADDR'
- if eventName in [ 'BGP_AS_OWNER' ]:
+ if eventName in [ 'BGP_AS_OWNER', 'BGP_AS_MEMBER' ]:
typeId = 'asn'
evtType = 'MALICIOUS_ASN'
@@ -463,10 +463,10 @@ class sfp_malcheck(SpiderFootPlugin):
if eventName == 'CO_HOSTED_SITE':
evtType = 'MALICIOUS_COHOST'
- if eventName == 'NETBLOCK':
+ if eventName == 'NETBLOCK_OWNER':
typeId = 'netblock'
evtType = 'MALICIOUS_NETBLOCK'
- if eventName == 'IP_SUBNET':
+ if eventName == 'NETBLOCK_MEMBER':
typeId = 'netblock'
evtType = 'MALICIOUS_SUBNET'
diff --git a/modules/sfp_portscan_basic.py b/modules/sfp_portscan_basic.py
index e78dbcb2..44dc7447 100644
--- a/modules/sfp_portscan_basic.py
+++ b/modules/sfp_portscan_basic.py
@@ -73,7 +73,7 @@ class sfp_portscan_basic(SpiderFootPlugin):
# What events is this module interested in for input
def watchedEvents(self):
- return ['IP_ADDRESS', 'NETBLOCK']
+ return ['IP_ADDRESS', 'NETBLOCK_OWNER']
# What events this module produces
# This is to support the end user in selecting modules based on events
@@ -148,7 +148,7 @@ class sfp_portscan_basic(SpiderFootPlugin):
self.sf.debug("Received event, " + eventName + ", from " + srcModuleName)
try:
- if eventName == "NETBLOCK" and self.opts['netblockscan']:
+ if eventName == "NETBLOCK_OWNER" and self.opts['netblockscan']:
net = IPNetwork(eventData)
if net.prefixlen < self.opts['netblockscanmax']:
self.sf.debug("Skipping port scanning of " + eventData + ", too big.")
diff --git a/modules/sfp_shodan.py b/modules/sfp_shodan.py
index d007d7ab..e1bf34f8 100644
--- a/modules/sfp_shodan.py
+++ b/modules/sfp_shodan.py
@@ -11,6 +11,7 @@
import sys
import json
+from netaddr import IPNetwork
from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent
class sfp_shodan(SpiderFootPlugin):
@@ -18,12 +19,16 @@ class sfp_shodan(SpiderFootPlugin):
# Default options
opts = {
- "apikey": ""
+ "apikey": "",
+ 'netblocklookup': True,
+ 'maxnetblock': 24
}
# Option descriptions
optdescs = {
- "apikey": "Your SHODAN API Key."
+ "apikey": "Your SHODAN API Key.",
+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible hosts on the same target subdomain/domain?",
+ 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"
}
results = dict()
@@ -40,13 +45,29 @@ class sfp_shodan(SpiderFootPlugin):
# What events is this module interested in for input
def watchedEvents(self):
- return ["IP_ADDRESS"]
+ return ["IP_ADDRESS", "NETBLOCK_OWNER"]
# What events this module produces
def producedEvents(self):
return ["OPERATING_SYSTEM", "DEVICE_TYPE",
"TCP_PORT_OPEN", "TCP_PORT_OPEN_BANNER"]
+ def query(self, qry):
+ res = self.sf.fetchUrl("https://api.shodan.io/shodan/host/" + qry + \
+ "?key=" + self.opts['apikey'],
+ timeout=self.opts['_fetchtimeout'], useragent="SpiderFoot")
+ if res['content'] == None:
+ self.sf.info("No SHODAN info found for " + qry)
+ return None
+
+ try:
+ info = json.loads(res['content'])
+ except Exception as e:
+ self.sf.error("Error processing JSON response from SHODAN.", False)
+ return None
+
+ return info
+
# Handle events sent to this module
def handleEvent(self, event):
eventName = event.eventType
@@ -66,49 +87,60 @@ class sfp_shodan(SpiderFootPlugin):
else:
self.results[eventData] = True
- res = self.sf.fetchUrl("https://api.shodan.io/shodan/host/" + eventData + \
- "?key=" + self.opts['apikey'],
- timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent'])
- if res['content'] == None:
- self.sf.info("No SHODAN info found for " + eventData)
- return None
-
- try:
- info = json.loads(res['content'])
- except Exception as e:
- self.sf.error("Error processing JSON response from SHODAN.", False)
- return None
-
- os = info.get('os')
- devtype = info.get('devicetype')
-
- if os != None:
- # Notify other modules of what you've found
- evt = SpiderFootEvent("OPERATING_SYSTEM", os, self.__name__, event)
- self.notifyListeners(evt)
-
- if devtype != None:
- # Notify other modules of what you've found
- evt = SpiderFootEvent("DEVICE_TYPE", devtype, self.__name__, event)
- self.notifyListeners(evt)
+ if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:
+ if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:
+ self.sf.debug("Network size bigger than permitted: " + \
+ str(IPNetwork(eventData).prefixlen) + " > " + \
+ str(self.opts['maxnetblock']))
+ return None
+
+ qrylist = list()
+ if eventName.startswith("NETBLOCK_"):
+ for ipaddr in IPNetwork(eventData):
+ qrylist.append(str(ipaddr))
+ self.results[str(ipaddr)] = True
+ else:
+ qrylist.append(eventData)
+ for addr in qrylist:
+ rec = self.query(addr)
+ if rec == None:
+ continue
- self.sf.info("Found SHODAN data for " + eventData)
- for rec in info['data']:
- port = str(rec.get('port'))
- banner = rec.get('banner')
+ if self.checkForStop():
+ return None
- if port != None:
+ if rec.get('os') != None:
# Notify other modules of what you've found
- cp = eventData + ":" + port
- evt = SpiderFootEvent("TCP_PORT_OPEN", cp, self.__name__, event)
+ evt = SpiderFootEvent("OPERATING_SYSTEM", rec.get('os') + \
+ " (" + addr +")", self.__name__, event)
self.notifyListeners(evt)
- if banner != None:
+ if rec.get('devtype') != None:
# Notify other modules of what you've found
- evt = SpiderFootEvent("TCP_PORT_OPEN_BANNER", banner, self.__name__, event)
+ evt = SpiderFootEvent("DEVICE_TYPE", rec.get('devtype') + \
+ " (" + addr +")", self.__name__, event)
self.notifyListeners(evt)
+ if rec.has_key('data'):
+ self.sf.info("Found SHODAN data for " + eventData)
+ for r in rec['data']:
+ port = str(r.get('port'))
+ banner = r.get('banner')
+
+ if port != None:
+ # Notify other modules of what you've found
+ cp = addr + ":" + port
+ evt = SpiderFootEvent("TCP_PORT_OPEN", cp,
+ self.__name__, event)
+ self.notifyListeners(evt)
+
+ if banner != None:
+ # Notify other modules of what you've found
+ evt = SpiderFootEvent("TCP_PORT_OPEN_BANNER", banner,
+ self.__name__, event)
+ self.notifyListeners(evt)
+
return None
# End of sfp_shodan class
diff --git a/modules/sfp_virustotal.py b/modules/sfp_virustotal.py
index 03cc52df..56b25024 100644
--- a/modules/sfp_virustotal.py
+++ b/modules/sfp_virustotal.py
@@ -12,6 +12,7 @@
import sys
import json
import time
+from netaddr import IPNetwork
from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent
class sfp_virustotal(SpiderFootPlugin):
@@ -22,7 +23,11 @@ class sfp_virustotal(SpiderFootPlugin):
"apikey": "",
"publicapi": True,
"checkcohosts": True,
- "checkaffiliates": True
+ "checkaffiliates": True,
+ 'netblocklookup': True,
+ 'maxnetblock': 24,
+ 'subnetlookup': True,
+ 'maxsubnet': 24
}
# Option descriptions
@@ -30,7 +35,11 @@ class sfp_virustotal(SpiderFootPlugin):
"apikey": "Your VirusTotal API Key.",
"publicapi": "Are you using a public key? If so SpiderFoot will pause for 15 seconds after each query to avoid VirusTotal dropping requests.",
"checkcohosts": "Check co-hosted sites?",
- "checkaffiliates": "Check affiliates?"
+ "checkaffiliates": "Check affiliates?",
+ 'netblocklookup': "Look up all IPs on netblocks deemed to be owned by your target for possible hosts on the same target subdomain/domain?",
+ 'maxnetblock': "If looking up owned netblocks, the maximum netblock size to look up all IPs within (CIDR value, 24 = /24, 16 = /16, etc.)",
+ 'subnetlookup': "Look up all IPs on subnets which your target is a part of?",
+ 'maxsubnet': "If looking up subnets, the maximum subnet size to look up all the IPs within (CIDR value, 24 = /24, 16 = /16, etc.)"
}
# Be sure to completely clear any class variables in setup()
@@ -51,13 +60,42 @@ class sfp_virustotal(SpiderFootPlugin):
# What events is this module interested in for input
def watchedEvents(self):
return ["IP_ADDRESS", "AFFILIATE_IPADDR", "INTERNET_NAME",
- "AFFILIATE_DOMAIN", "CO_HOSTED_SITE"]
+ "AFFILIATE_DOMAIN", "CO_HOSTED_SITE", "NETBLOCK_OWNER",
+ "NETBLOCK_MEMBER"]
# What events this module produces
def producedEvents(self):
return ["MALICIOUS_IPADDR", "MALICIOUS_INTERNET_NAME",
"MALICIOUS_COHOST", "MALICIOUS_AFFILIATE_INTERNET_NAME",
- "MALICIOUS_AFFILIATE_IPADDR"]
+ "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_NETBLOCK",
+ "MALICIOUS_SUBNET" ]
+
+ def query(self, qry):
+ ret = None
+
+ if self.sf.validIP(qry):
+ url = "https://www.virustotal.com/vtapi/v2/ip-address/report?ip=" + qry
+ else:
+ url = "https://www.virustotal.com/vtapi/v2/domain/report?domain=" + qry
+
+ res = self.sf.fetchUrl(url + "&apikey=" + self.opts['apikey'],
+ timeout=self.opts['_fetchtimeout'], useragent="SpiderFoot")
+
+ # Public API is limited to 4 queries per minute
+ if self.opts['publicapi']:
+ time.sleep(15)
+
+ if res['content'] == None:
+ self.sf.info("No VirusTotal info found for " + qry)
+ return None
+
+ try:
+ ret = json.loads(res['content'])
+ except Exception as e:
+ self.sf.error("Error processing JSON response from VirusTotal.", False)
+ return None
+
+ return ret
# Handle events sent to this module
def handleEvent(self, event):
@@ -84,56 +122,61 @@ class sfp_virustotal(SpiderFootPlugin):
if eventName == 'CO_HOSTED_SITE' and not self.opts['checkcohosts']:
return None
- if eventName in [ "AFFILIATE_INTERNET_NAME", "CO_HOSTED_SITE" ]:
- url = "https://www.virustotal.com/vtapi/v2/domain/report?domain="
+ if eventName == 'NETBLOCK_OWNER' and self.opts['netblocklookup']:
+ if IPNetwork(eventData).prefixlen < self.opts['maxnetblock']:
+ self.sf.debug("Network size bigger than permitted: " + \
+ str(IPNetwork(eventData).prefixlen) + " > " + \
+ str(self.opts['maxnetblock']))
+ return None
+
+ if eventName == 'NETBLOCK_MEMBER' and self.opts['subnetlookup']:
+ if IPNetwork(eventData).prefixlen < self.opts['maxsubnet']:
+ self.sf.debug("Network size bigger than permitted: " + \
+ str(IPNetwork(eventData).prefixlen) + " > " + \
+ str(self.opts['maxsubnet']))
+ return None
+
+ qrylist = list()
+ if eventName.startswith("NETBLOCK_"):
+ for ipaddr in IPNetwork(eventData):
+ qrylist.append(str(ipaddr))
+ self.results[str(ipaddr)] = True
else:
- url = "https://www.virustotal.com/vtapi/v2/ip-address/report?ip="
-
- res = self.sf.fetchUrl(url + eventData + "&apikey=" + self.opts['apikey'],
- timeout=self.opts['_fetchtimeout'], useragent="SpiderFoot")
-
- # Public API is limited to 4 queries per minute
- if self.opts['publicapi']:
- time.sleep(15)
-
- if res['content'] == None:
- self.sf.info("No VirusTotal info found for " + eventData)
- return None
-
- try:
- info = json.loads(res['content'])
- except Exception as e:
- self.sf.error("Error processing JSON response from VirusTotal.", False)
- return None
-
- if info.has_key('detected_urls'):
- self.sf.info("Found VirusTotal URL data for " + eventData)
- if eventName == "IP_ADDRESS":
- evt = "MALICIOUS_IPADDR"
- infotype = "ip-address"
-
- if eventName == "AFFILIATE_IPADDR":
- evt = "MALICIOUS_AFFILIATE_IPADDR"
- infotype = "ip-address"
-
- if eventName == "INTERNET_NAME":
- evt = "MALICIOUS_INTERNET_NAME"
- infotype = "domain"
-
- if eventName == "AFFILIATE_INTERNET_NAME":
- evt = "MALICIOUS_AFFILIATE_INTERNET_NAME"
- infotype = "domain"
-
- if eventName == "CO_HOSTED_SITE":
- evt = "MALICIOUS_COHOST"
- infotype = "domain"
-
- infourl = "<SFURL>https://www.virustotal.com/en/" + infotype + "/" + \
- eventData + "/information/</SFURL>"
-
- # Notify other modules of what you've found
- e = SpiderFootEvent(evt, "VirusTotal [" + eventData + "]\n" + \
- infourl, self.__name__, event)
- self.notifyListeners(e)
+ qrylist.append(eventData)
+
+ for addr in qrylist:
+ if self.checkForStop():
+ return None
+
+ info = self.query(addr)
+ if info.has_key('detected_urls'):
+ self.sf.info("Found VirusTotal URL data for " + addr)
+ if eventName in [ "IP_ADDRESS" ] or eventName.startswith("NETBLOCK_"):
+ evt = "MALICIOUS_IPADDR"
+ infotype = "ip-address"
+
+ if eventName == "AFFILIATE_IPADDR":
+ evt = "MALICIOUS_AFFILIATE_IPADDR"
+ infotype = "ip-address"
+
+ if eventName == "INTERNET_NAME":
+ evt = "MALICIOUS_INTERNET_NAME"
+ infotype = "domain"
+
+ if eventName == "AFFILIATE_INTERNET_NAME":
+ evt = "MALICIOUS_AFFILIATE_INTERNET_NAME"
+ infotype = "domain"
+
+ if eventName == "CO_HOSTED_SITE":
+ evt = "MALICIOUS_COHOST"
+ infotype = "domain"
+
+ infourl = "<SFURL>https://www.virustotal.com/en/" + infotype + "/" + \
+ addr + "/information/</SFURL>"
+
+ # Notify other modules of what you've found
+ e = SpiderFootEvent(evt, "VirusTotal [" + addr + "]\n" + \
+ infourl, self.__name__, event)
+ self.notifyListeners(e)
# End of sfp_virustotal class
diff --git a/sfdb.py b/sfdb.py
index e9a1c9a5..986c5008 100644
--- a/sfdb.py
+++ b/sfdb.py
@@ -13,9 +13,15 @@ import hashlib
import random
import sqlite3
import sys
+import re
import time
from sflib import SpiderFoot
+def __dbregex__(qry, data):
+ rx = re.compile(qry, re.IGNORECASE)
+ ret = rx.search(data)
+ return ret is not None
+
class SpiderFootDb:
sf = None
dbh = None
@@ -80,8 +86,11 @@ class SpiderFootDb:
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('AFFILIATE_WEB_CONTENT', 'Affiliate - Web Content', 1)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('BGP_AS_OWNER', 'BGP AS Ownership', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('BGP_AS_MEMBER', 'BGP AS Membership', 0)",
+ "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('BGP_AS_PEER', 'BGP AS Peer', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('BLACKLISTED_IPADDR', 'Blacklisted IP Address', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('BLACKLISTED_AFFILIATE_IPADDR', 'Blacklisted Affiliate IP Address', 0)",
+ "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('BLACKLISTED_SUBNET', 'Blacklisted IP on Same Subnet', 0)",
+ "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('BLACKLISTED_NETBLOCK', 'Blacklisted IP on Owned Netblock', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('CO_HOSTED_SITE', 'Co-Hosted Site', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('DEFACED_INTERNET_NAME', 'Defaced', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('DEFACED_IPADDR', 'Defaced IP Address', 0)",
@@ -97,8 +106,8 @@ class SpiderFootDb:
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('INTERESTING_FILE', 'Interesting File', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('INTERNET_NAME', 'Internet Name', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('IP_ADDRESS', 'IP Address', 0)",
- "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('IP_SUBNET', 'IP Address - Subnet', 0)",
- "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('NETBLOCK', 'Netblock Ownership', 0)",
+ "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('NETBLOCK_OWNER', 'Netblock Ownership', 0)",
+ "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('NETBLOCK_MEMBER', 'Netblock Membership', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('MALICIOUS_ASN', 'Malicious AS', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('MALICIOUS_IPADDR', 'Malicious IP Address', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('MALICIOUS_COHOST', 'Malicious Co-Hosted Site', 0)",
@@ -112,7 +121,6 @@ class SpiderFootDb:
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('OPERATING_SYSTEM', 'Operating System', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('PASTEBIN_CONTENT', 'PasteBin Content', 1)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('PROVIDER_DNS', 'Name Server (DNS ''NS'' Records)', 0)",
- "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('PROVIDER_INTERNET', 'Internet Service Provider', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('PROVIDER_MAIL', 'Email Gateway (DNS ''MX'' Records)', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('PROVIDER_JAVASCRIPT', 'Externally Hosted Javascript', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('RAW_RIR_DATA', 'Raw Data from RIRs', 1)",
@@ -164,6 +172,7 @@ class SpiderFootDb:
# up correctly.
try:
self.dbh.execute('SELECT COUNT(*) FROM tbl_scan_config')
+ self.conn.create_function("REGEXP", 2, __dbregex__)
except sqlite3.Error:
# .. If not set up, we set it up.
try:
@@ -191,6 +200,51 @@ class SpiderFootDb:
def close(self):
self.dbh.close()
+ # Search results
+ # criteria is search criteria such as:
+ # - scan_id (search within a scan, if omitted search all)
+ # - type (search a specific type, if omitted search all)
+ # - value (search values for a specific string, if omitted search all)
+ # - regex (search values for a regular expression)
+ # ** at least two criteria must be set **
+ def search(self, criteria):
+ if criteria.values().count(None) == 3:
+ return False
+
+ qvars = list()
+ qry = "SELECT ROUND(c.generated) AS generated, c.data, \
+ s.data as 'source_data', \
+ c.module, c.type, c.confidence, c.visibility, c.risk, c.hash, \
+ c.source_event_hash, t.event_descr, c.scan_instance_id \
+ FROM tbl_scan_results c, tbl_scan_results s, tbl_event_types t \
+ WHERE s.scan_instance_id = c.scan_instance_id AND \
+ t.event = c.type AND c.source_event_hash = s.hash "
+
+ if criteria.get('scan_id') != None:
+ qry += "AND c.scan_instance_id = ? "
+ qvars.append(criteria['scan_id'])
+
+ if criteria.get('type') != None:
+ qry += " AND c.type = ? "
+ qvars.append(criteria['type'])
+
+ if criteria.get('value') != None:
+ qry += " AND c.data LIKE ? "
+ qvars.append(criteria['value'])
+
+ if criteria.get('regex') != None:
+ qry += " AND c.data REGEXP ? "
+ qvars.append(criteria['regex'])
+
+ qry = qry + " ORDER BY c.data"
+
+ try:
+ self.dbh.execute(qry, qvars)
+ return self.dbh.fetchall()
+ except sqlite3.Error as e:
+ self.sf.error("SQL error encountered when fetching search results: " +
+ e.args[0])
+
# Get event types
def eventTypes(self):
qry = "SELECT event_descr, event, event_raw FROM tbl_event_types"
diff --git a/sflib.py b/sflib.py
index 939b6873..8080a734 100644
--- a/sflib.py
+++ b/sflib.py
@@ -1159,7 +1159,7 @@ class SpiderFootPlugin(object):
# Class for targets
class SpiderFootTarget(object):
- _validTypes = [ "IP_ADDRESS", "IP_SUBNET", "INTERNET_NAME" ]
+ _validTypes = [ "IP_ADDRESS", "NETBLOCK_OWNER", "INTERNET_NAME" ]
targetType = None
targetValue = None
targetAliases = list()
@@ -1245,7 +1245,7 @@ class SpiderFootTarget(object):
if value in self.getAddresses():
return True
# 1.2
- if self.targetType == "IP_SUBNET":
+ if self.targetType == "NETBLOCK_OWNER":
if netaddr.IPAddress(value) in netaddr.IPNetwork(self.targetValue):
return True
if self.targetType == "IP_ADDRESS":
diff --git a/sfscan.py b/sfscan.py
index 8c07fb39..e5fc0890 100644
--- a/sfscan.py
+++ b/sfscan.py
@@ -20,6 +20,7 @@ import dns.resolver
import threading
import thread
import random
+from netaddr import IPNetwork
from copy import deepcopy, copy
from sfdb import SpiderFootDb
from sflib import SpiderFoot, SpiderFootEvent, SpiderFootTarget, globalScanStatus
diff --git a/sfwebui.py b/sfwebui.py
index 61da2737..42cd0d22 100644
--- a/sfwebui.py
+++ b/sfwebui.py
@@ -68,6 +68,39 @@ class SpiderFootWebUi:
return ret
+ def searchBase(self, id=None, eventType=None, value=None):
+ regex = ""
+ if [id, eventType, value].count('') == 2 or \
+ [id, eventType, value].count(None) == 2:
+ return None
+
+ if value.startswith("/") and value.endswith("/"):
+ regex = value[1:len(value)-1]
+ value = ""
+
+ value = value.replace('*', '%')
+ if value in [ None, "" ] and regex in [ None, "" ]:
+ value = "%"
+ regex = ""
+
+ dbh = SpiderFootDb(self.config)
+ criteria = {
+ 'scan_id': None if id == '' else id,
+ 'type': None if eventType == '' else eventType,
+ 'value': None if value == '' else value,
+ 'regex': None if regex == '' else regex
+ }
+ data = dbh.search(criteria)
+ retdata = []
+ for row in data:
+ lastseen = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(row[0]))
+ escapeddata = cgi.escape(row[1])
+ escapedsrc = cgi.escape(row[2])
+ retdata.append([lastseen, escapeddata, escapedsrc,
+ row[3], row[5], row[6], row[7], row[8], row[10], row[11], row[4]])
+
+ return retdata
+
#
# USER INTERFACE PAGES
#
@@ -89,6 +122,21 @@ class SpiderFootWebUi:
return fileobj.getvalue()
scaneventresultexport.exposed = True
+ # Get search result data in CSV format
+ def scansearchresultexport(self, id, eventType=None, value=None, dialect="excel"):
+ data = self.searchBase(id, eventType, value)
+ fileobj = StringIO()
+ parser = csv.writer(fileobj, dialect=dialect)
+ parser.writerow(["Updated", "Type", "Module", "Source", "Data"])
+ for row in data:
+ datafield = str(row[1]).replace("<SFURL>", "").replace("</SFURL>", "")
+ parser.writerow([row[0], str(row[10]), str(row[3]), str(row[2]), datafield])
+ cherrypy.response.headers['Content-Disposition'] = "attachment; filename=SpiderFoot.csv"
+ cherrypy.response.headers['Content-Type'] = "application/csv"
+ cherrypy.response.headers['Pragma'] = "no-cache"
+ return fileobj.getvalue()
+ scansearchresultexport.exposed = True
+
# Configuration used for a scan
def scanopts(self, id):
ret = dict()
@@ -258,7 +306,7 @@ class SpiderFootWebUi:
regexToType = {
"^\d+\.\d+\.\d+\.\d+$": "IP_ADDRESS",
- "^\d+\.\d+\.\d+\.\d+/\d+$": "IP_SUBNET",
+ "^\d+\.\d+\.\d+\.\d+/\d+$": "NETBLOCK_OWNER",
"^.[a-zA-Z\-0-9\.]+$": "INTERNET_NAME"
}
@@ -407,6 +455,12 @@ class SpiderFootWebUi:
return json.dumps(retdata, ensure_ascii=False)
scaneventresultsunique.exposed = True
+ # Search
+ def search(self, id=None, eventType=None, value=None):
+ retdata = self.searchBase(id, eventType, value)
+ return json.dumps(retdata, ensure_ascii=False)
+ search.exposed = True
+
# Historical data for the scan, graphs will be rendered in JS
def scanhistory(self, id):
dbh = SpiderFootDb(self.config)
diff --git a/static/css/spiderfoot.css b/static/css/spiderfoot.css
index 46ce5b64..9b633d39 100644
--- a/static/css/spiderfoot.css
+++ b/static/css/spiderfoot.css
@@ -45,3 +45,4 @@ fill: orangered ;
.x.axis path {
display: none;
}
+
diff --git a/static/js/spiderfoot.js b/static/js/spiderfoot.js
index ed0b4a74..5065a86b 100644
--- a/static/js/spiderfoot.js
+++ b/static/js/spiderfoot.js
@@ -35,6 +35,10 @@ sf.remove_sfurltag = function(data) {
return data;
}
+sf.search = function(scan_id=null, value=null, type=null, postFunc) {
+ sf.fetchData("/search", { id: scan_id, eventType: type, value: value }, postFunc);
+}
+
sf.fetchData = function(url, postData, postFunc) {
var req = $.ajax({
type: "POST",
@@ -50,6 +54,37 @@ sf.fetchData = function(url, postData, postFunc) {
});
}
+/*
+sf.simpleTable = function(id, data, cols, linkcol=null, linkstring=null, sortable=true, rowfunc=null) {
+ var table = "<table id='" + id + "' ";
+ table += "class='table table-bordered table-striped tablesorter'>";
+ table += "<thead><tr>";
+ for (var i = 0; i < cols.length; i++) {
+ table += "<th>" + cols[i] + "</th>";
+ }
+ table += "</tr></thead><tbody>";
+
+ for (var i = 1; i < data.length; i++) {
+ table += "<tr>";
+ for (var c = 0; c < data[i].length; c++) {
+ if (c == linkcol) {
+ if (linkstring.indexOf("%%col") > 0) {
+ }
+ table += "<td>" + <a class='link' onClick='" + linkstring + "'>";
+ table += data[i][c] + "</a></td>"
+ } else {
+ table += "<td>" + data[i][c] + "</td>";
+ }
+ }
+ table += "</tr>";
+ }
+ table += "</tbody></table>";
+
+ return table;
+}
+
+*/
+
sf.updateTooltips = function() {
$(document).ready(function () {
if ($("[rel=tooltip]").length) {