Skip to content

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

Support for footprinting hostnames, sub-domains, subnets and IP addresses in addition to the usual domain names.

smicallefe66be319f51c
diff --git a/dyn/newscan.tmpl b/dyn/newscan.tmpl
index 8793c93e..fd9d6035 100644
--- a/dyn/newscan.tmpl
+++ b/dyn/newscan.tmpl
@@ -43,18 +43,19 @@ Another scan is currently running (${runningScan}). Please either wait for that
</div>
% endif
<form class="form" action='/startscan' method='POST'>
- <div class="control-group">
- <label class="control-label" for="scanname">Scan Name</label>
- <div class="controls">
- <input type="text" id="scanname" name="scanname" placeholder="Descriptive name for this scan.">
+ <div class="control-group">
+ <label class="control-label" for="scanname">Scan Name</label>
+ <div class="controls">
+ <input type="text" id="scanname" name="scanname" placeholder="Descriptive name for this scan.">
+ </div>
</div>
- </div>
- <div class="control-group">
- <label class="control-label" for="scantarget">Target Domain Name</label>
- <div class="controls">
- <input type="text" id="scantarget" name="scantarget" placeholder="e.g. example.com">
+ <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.">
+ </div>
</div>
- </div>
+
<div class="control-group">
<ul class='nav nav-tabs'>
<li id='typetab' class="active"><a onClick='switchTab()' href='#'>By Required Data</a></li>
diff --git a/evtypes.sql b/evtypes.sql
index ea914c42..b2dd8f8e 100644
--- a/evtypes.sql
+++ b/evtypes.sql
@@ -1,18 +1,18 @@
--
-- Event types and their descriptions
--
-INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('AFFILIATE', 'Affiliate - Hostname', 0);
-INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('AFFILIATE_DOMAIN', 'Affiliate - Domain', 0);
+INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('AFFILIATE_INTERNET_NAME', 'Affiliate - Internet Name', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('AFFILIATE_IPADDR', 'Affiliate - IP Address', 0);
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', 'BGP AS Ownership', 0);
+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 ('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 ('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', 'Defaced', 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)
-INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('DEFACED_AFFILIATE', 'Defaced Affiliate', 0);
+INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('DEFACED_AFFILIATE_INTERNET_NAME', 'Defaced Affiliate', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('DEFACED_COHOST', 'Defaced Co-Hosted Site', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('DEFACED_AFFILIATE_IPADDR', 'Defaced Affiliate IP Address', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('DEVICE_TYPE', 'Device Type', 0);
@@ -20,8 +20,8 @@ INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('DOMAIN_NAME
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('GEOINFO', 'Physical Location', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('HTTP_CODE', 'HTTP Status Code', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('HUMAN_NAME', 'Human Name', 0);
-INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('INITIAL_TARGET', 'User-Supplied Target', 0);
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);
@@ -29,9 +29,8 @@ INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('LINKED_URL_
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);
-INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('MALICIOUS_DOMAIN_NAME', 'Malicious Domain Name', 0);
-INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('MALICIOUS_SUBDOMAIN', 'Malicious Sub-domain/Host', 0);
-INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('MALICIOUS_AFFILIATE', 'Malicious Affiliate', 0);
+INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('MALICIOUS_INTERNET_NAME', 'Malicious Internet Name', 0);
+INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('MALICIOUS_AFFILIATE_INTERNET_NAME', 'Malicious Affiliate', 0);
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);
@@ -47,7 +46,6 @@ INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('RAW_DNS_REC
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('RAW_FILE_META_DATA', 'Raw File Meta Data', 1);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('SEARCH_ENGINE_WEB_CONTENT', 'Search Engine''s Web Content', 1);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('SOCIAL_MEDIA', 'Social Media Presence', 0);
-INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('SUBDOMAIN', 'Sub-domain/Host', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('SIMILARDOMAIN', 'Similar Domain', 0);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('SSL_CERTIFICATE_RAW', 'SSL Certificate - Raw Data', 1);
INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('SSL_CERTIFICATE_ISSUED', 'SSL Certificate - Issued to', 0);
diff --git a/modules/sfp__stor_db.py b/modules/sfp__stor_db.py
index e2562020..6f396b23 100644
--- a/modules/sfp__stor_db.py
+++ b/modules/sfp__stor_db.py
@@ -31,7 +31,7 @@ class sfp__stor_db(SpiderFootPlugin):
'maxstorage': "Maximum bytes to store for any piece of information retreived (0 = unlimited.)"
}
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
global sfdb
diff --git a/modules/sfp_bingsearch.py b/modules/sfp_bingsearch.py
index 77c83378..f3030ffd 100644
--- a/modules/sfp_bingsearch.py
+++ b/modules/sfp_bingsearch.py
@@ -35,7 +35,7 @@ class sfp_bingsearch(SpiderFootPlugin):
results = list()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
@@ -46,7 +46,7 @@ class sfp_bingsearch(SpiderFootPlugin):
# What events is this module interested in for input
def watchedEvents(self):
- return [ "DOMAIN_NAME" ]
+ return [ "INTERNET_NAME" ]
# What events this module produces
# This is to support the end user in selecting modules based on events
@@ -98,7 +98,7 @@ class sfp_bingsearch(SpiderFootPlugin):
continue
else:
self.results.append(link)
- if sf.urlBaseUrl(link).endswith(eventData):
+ if sf.urlFQDN(link).endswith(eventData):
sf.debug("Found a link: " + link)
if self.checkForStop():
return None
diff --git a/modules/sfp_blacklist.py b/modules/sfp_blacklist.py
index c22e6da2..8cc6478b 100644
--- a/modules/sfp_blacklist.py
+++ b/modules/sfp_blacklist.py
@@ -74,7 +74,7 @@ class sfp_blacklist(SpiderFootPlugin):
}
}
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
diff --git a/modules/sfp_cookie.py b/modules/sfp_cookie.py
index aa3e1c07..15e7ede1 100644
--- a/modules/sfp_cookie.py
+++ b/modules/sfp_cookie.py
@@ -22,15 +22,12 @@ class sfp_cookie(SpiderFootPlugin):
# Default options
opts = { }
- # Target
- baseDomain = None # calculated from the URL in setup
results = dict()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
- self.baseDomain = target
self.results = dict()
for opt in userOpts.keys():
@@ -60,7 +57,7 @@ class sfp_cookie(SpiderFootPlugin):
else:
self.results[eventSource] = True
- if not sf.urlBaseUrl(eventSource).endswith(self.baseDomain):
+ if not self.getTarget().matches(sf.urlFQDN(eventSource)):
sf.debug("Not collecting cookies from external sites.")
return None
diff --git a/modules/sfp_crossref.py b/modules/sfp_crossref.py
index 97ac847d..dbc7d8da 100644
--- a/modules/sfp_crossref.py
+++ b/modules/sfp_crossref.py
@@ -24,33 +24,22 @@ class sfp_crossref(SpiderFootPlugin):
# Default options
opts = {
- 'forcebase': True, # Check the base URL for a link back to the seed
- # domain in order to be considered a valid crossref
- 'checkbase': True, # Only check the base URL for a relationship if
- # the link provided contains no crossref
- 'checkcontent': True # Submit affiliate content for other modules to
- # analyze
+ 'checkbase': True
}
# Option descriptions
optdescs = {
- "forcebase": "Require the base domain of an external URL for affiliation?",
- "checkbase": "Check the base domain of a URL for affiliation?",
- "checkcontent": "Submit the affiliate content to other modules for analysis?"
+ "checkbase": "Check the base URL of the potential affiliate if no direct affiliation found?"
}
# Internal results tracking
results = dict()
fetched = list()
- # Target
- baseDomain = None
-
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
- self.baseDomain = target
self.results = dict()
self.fetched = list()
@@ -65,7 +54,7 @@ class sfp_crossref(SpiderFootPlugin):
# This is to support the end user in selecting modules based on events
# produced.
def producedEvents(self):
- return [ "AFFILIATE", "AFFILIATE_WEB_CONTENT" ]
+ return [ "AFFILIATE_INTERNET_NAME", "AFFILIATE_WEB_CONTENT" ]
# Handle events sent to this module
# In this module's case, eventData will be the URL or a domain which
@@ -83,60 +72,64 @@ class sfp_crossref(SpiderFootPlugin):
eventData = 'http://'+ eventData.lower()
# We are only interested in external sites for the crossref
- if sf.urlBaseUrl(eventData).endswith(self.baseDomain):
+ if self.getTarget().matches(sf.urlFQDN(eventData)):
sf.debug("Ignoring " + eventData + " as not external")
return None
- # If forcebase is set, we don't bother checking the URL from the event,
- # just it's base URL.
- if self.opts['forcebase']:
- url = sf.urlBaseUrl(eventData)
- else:
- url = eventData
-
- if url in self.fetched:
- sf.debug("Ignoring " + url + " as already tested")
+ if eventData in self.fetched:
+ sf.debug("Ignoring " + eventData + " as already tested")
return
+ else:
+ self.fetched.append(eventData)
- sf.debug("Testing for affiliation: " + url)
- res = sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],
+ sf.debug("Testing for affiliation: " + eventData)
+ res = sf.fetchUrl(eventData, timeout=self.opts['_fetchtimeout'],
useragent=self.opts['_useragent'])
- self.fetched.append(url)
if res['content'] == None:
- sf.debug("Ignoring " + url + " as no data returned")
+ sf.debug("Ignoring " + eventData + " as no data returned")
return None
- # Search for mentions of our domain in the external site's data
- matches = re.findall("([\.\'\/\"\ ]" + self.baseDomain + "[\.\'\/\"\ ])",
- res['content'], re.IGNORECASE)
-
- # If the domain wasn't found in the affiliate, and checkbase is set,
- # fetch the base URL of the affiliate to check for a crossref. Don't bother
- # if forcebase was set, as we would've already checked that anyway.
- if not self.opts['forcebase'] and len(matches) > 0 and self.opts['checkbase']:
- # Check the base url to see if there is an affiliation
- url = sf.urlBaseUrl(eventData)
- res = sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],
- useragent=self.opts['_useragent'])
- if res['content'] != None:
- matches = re.findall("([\.\'\/\"\ ]" + self.baseDomain + "[\'\/\"\ ])",
- res['content'], re.IGNORECASE)
- else:
- return None
-
- if len(matches) > 0:
- if self.results.has_key(url):
- return None
-
- self.results[url] = True
+ matched = False
+ for name in self.getTarget().getNames():
+ # Search for mentions of our host/domain in the external site's data
+ pat = re.compile("([\.\'\/\"\ ]" + name + "[\.\'\/\"\ ])", re.IGNORECASE)
+ matches = re.findall(pat, res['content'])
+
+ if len(matches) > 0:
+ matched = True
+ url = eventData
+ break
+
+ if not matched:
+ # If the name wasn't found in the affiliate, and checkbase is set,
+ # fetch the base URL of the affiliate to check for a crossref.
+ if eventName == "LINKED_URL_EXTERNAL" and self.opts['checkbase']:
+ # Check the base url to see if there is an affiliation
+ url = sf.urlBaseUrl(eventData)
+ if url in self.fetched:
+ return None
+ else:
+ self.fetched.append(url)
+
+ res = sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],
+ useragent=self.opts['_useragent'])
+ if res['content'] != None:
+ for name in self.getTarget().getNames():
+ pat = re.compile("([\.\'\/\"\ ]" + name + "[\'\/\"\ ])",
+ re.IGNORECASE)
+ matches = re.findall(pat, res['content'])
+
+ if len(matches) > 0:
+ matched = True
+
+ if matched:
sf.info("Found affiliate: " + url)
- evt1 = SpiderFootEvent("AFFILIATE", url, self.__name__, event)
+ evt1 = SpiderFootEvent("AFFILIATE_INTERNET_NAME", sf.urlFQDN(url),
+ self.__name__, event)
self.notifyListeners(evt1)
- if self.opts['checkcontent']:
- evt2 = SpiderFootEvent("AFFILIATE_WEB_CONTENT", res['content'], self.__name__, evt1)
- self.notifyListeners(evt2)
-
- return None
+ evt2 = SpiderFootEvent("AFFILIATE_WEB_CONTENT", res['content'],
+ self.__name__, evt1)
+ self.notifyListeners(evt2)
# End of sfp_crossref class
diff --git a/modules/sfp_defaced.py b/modules/sfp_defaced.py
index a3b20063..e6748b12 100644
--- a/modules/sfp_defaced.py
+++ b/modules/sfp_defaced.py
@@ -40,7 +40,7 @@ class sfp_defaced(SpiderFootPlugin):
results = list()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
@@ -55,15 +55,16 @@ class sfp_defaced(SpiderFootPlugin):
# What events is this module interested in for input
# * = be notified about all events.
def watchedEvents(self):
- return ["DOMAIN_NAME", "IP_ADDRESS", "SUBDOMAIN",
- "AFFILIATE_DOMAIN", "AFFILIATE_IPADDR",
+ return ["INTERNET_NAME", "IP_ADDRESS",
+ "AFFILIATE_INTERNET_NAME", "AFFILIATE_IPADDR",
"CO_HOSTED_SITE" ]
# What events this module produces
# This is to support the end user in selecting modules based on events
# produced.
def producedEvents(self):
- return [ "DEFACED", "DEFACED_IPADDR", "DEFACED_AFFILIATE",
+ return [ "DEFACED_INTERNET_NAME", "DEFACED_IPADDR",
+ "DEFACED_AFFILIATE_INTERNET_NAME",
"DEFACED_COHOST", "DEFACED_AFFILIATE_IPADDR" ]
def lookupItem(self, target, typeId):
@@ -79,8 +80,8 @@ class sfp_defaced(SpiderFootPlugin):
sf.error("CAPTCHA returned from zone-h.org.", False)
return None
- rx = "<td>(\d+/\d+/\d+)</td>"
- grps = re.findall(rx, res['content'], re.IGNORECASE|re.DOTALL)
+ rx = re.compile("<td>(\d+/\d+/\d+)</td>", re.IGNORECASE|re.DOTALL)
+ grps = re.findall(rx, res['content'])
for m in grps:
sf.debug("Found defaced site: " + target + "(" + typeId + ")")
found = True
@@ -112,11 +113,11 @@ class sfp_defaced(SpiderFootPlugin):
if eventName == 'CO_HOSTED_SITE' and not self.opts['checkcohosts']:
return None
- if eventName == 'AFFILIATE_DOMAIN' or eventName == 'AFFILIATE_IPADDR' \
+ if eventName == 'AFFILIATE_INTERNET_NAME' or eventName == 'AFFILIATE_IPADDR' \
and not self.opts['checkaffiliates']:
return None
- evtType = 'DEFACED'
+ evtType = 'DEFACED_INTERNET_NAME'
typeId = 'domain'
if eventName == 'IP_ADDRESS':
@@ -126,8 +127,8 @@ class sfp_defaced(SpiderFootPlugin):
if eventName == 'CO_HOSTED_SITE':
evtType = 'DEFACED_COHOST'
- if eventName == 'AFFILIATE_DOMAIN':
- evtType = 'DEFACED_AFFILIATE'
+ if eventName == 'AFFILIATE_INTERNET_NAME':
+ evtType = 'DEFACED_AFFILIATE_INTERNET_NAME'
if eventName == 'AFFILIATE_IPADDR':
evtType = 'DEFACED_AFFILIATE_IPADDR'
diff --git a/modules/sfp_dns.py b/modules/sfp_dns.py
index 63a8da96..e3369210 100644
--- a/modules/sfp_dns.py
+++ b/modules/sfp_dns.py
@@ -28,8 +28,6 @@ class sfp_dns(SpiderFootPlugin):
# Default options
opts = {
- 'reverselookup': True, # Reverse-resolve IPs to names for
- # more clues.
'subnetlookup': True,
'netblocklookup': True,
'maxnetblock': 24,
@@ -47,48 +45,96 @@ 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.",
- 'reverselookup': "Obtain new URLs and possible affiliates based on reverse-resolved IPs?",
- 'subnetlookup': "If reverse-resolving is enabled, look up all IPs on the same subnet for possible hosts on the same target domain?",
- 'netblocklookup': "If reverse-resolving is enabled, look up all IPs on owned netblocks for possible hosts on the same target domain?",
+ '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.)",
'onlyactive': "Only report sub-domains/hostnames that resolve to an IP.",
- 'lookaside': "For each IP discovered, try and reverse look-up IPs 'next to' that IP.",
+ 'lookaside': "For each IP discovered, try and reverse look-up IPs 'next to' that IP for potential hostnames on the same subdomain/domain.",
'lookasidecount': "If look-aside is enabled, the number of IPs on each 'side' of the IP to look up",
- "commonsubs": "Common sub-domains to try. Prefix with an '@' to iterate through a file containing sub-domains to try (one per line), e.g. @C:\subdomains.txt or @/home/bob/subdomains.txt. Or supply a URL to load the list from there."
+ "commonsubs": "Common sub-domains to try to resolve on the target subdomain/domain. Prefix with an '@' to iterate through a file containing sub-domains to try (one per line), e.g. @C:\subdomains.txt or @/home/bob/subdomains.txt. Or supply a URL to load the list from there."
}
- # Target
- baseDomain = None
- results = dict()
- subresults = dict()
+ events = dict()
+ domresults = dict()
+ hostresults = dict()
resolveCache = dict()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
- self.results = dict()
- self.subresults = dict()
+ self.events = dict()
+ self.domresults = dict()
+ self.hostresults = dict()
self.resolveCache = dict()
- self.baseDomain = target
for opt in userOpts.keys():
self.opts[opt] = userOpts[opt]
+ self.sublist = self.opts['commonsubs']
+ # User may have supplied a file or URL containing the subdomains
+ if self.opts['commonsubs'][0].startswith("http://") or \
+ self.opts['commonsubs'][0].startswith("https://") or \
+ self.opts['commonsubs'][0].startswith("@"):
+ self.sublist = sf.optValueToData(self.opts['commonsubs'][0])
+
+ def enrichTarget(self, target):
+ ret = None
+ # If it's an IP, get the hostname it reverse resolves to
+ if target.getType() == "IP_ADDRESS":
+ ret = self.resolveIP(target.getValue())
+ if target.getType() == "INTERNET_NAME":
+ ret = self.resolveHost(target.getValue())
+ if target.getType() == "IP_SUBNET":
+ ret = list()
+ for addr in IPNetwork(target.getValue()):
+ ipaddr = str(addr)
+ if ipaddr.split(".")[3] in [ '255', '0']:
+ continue
+ if '255' in ipaddr.split("."):
+ continue
+ ret.append(ipaddr)
+ name = self.resolveIP(ipaddr)
+ if name != None:
+ ret.append(name)
+
+ if ret == None:
+ return None
+
+ for addr in ret:
+ if type(addr) == list:
+ for host in addr:
+ if sf.validIP(host):
+ target.setAlias(host, "IP_ADDRESS")
+ else:
+ target.setAlias(host, "INTERNET_NAME")
+ dom = sf.hostDomain(host, self.opts['_internettlds'])
+ target.setAlias(dom, "INTERNET_NAME")
+ else:
+ if sf.validIP(addr):
+ target.setAlias(addr, "IP_ADDRESS")
+ else:
+ target.setAlias(addr, "INTERNET_NAME")
+ dom = sf.hostDomain(addr, self.opts['_internettlds'])
+ target.setAlias(dom, "INTERNET_NAME")
+
+ sf.debug("Aliases identified: " + str(target.getAliases()))
+
+ return target
+
# What events is this module interested in for input
def watchedEvents(self):
arr = ['RAW_DNS_RECORDS', 'SEARCH_ENGINE_WEB_CONTENT', 'RAW_RIR_DATA',
- 'TARGET_WEB_CONTENT', 'LINKED_URL_INTERNAL', 'SUBDOMAIN' ]
- if self.opts['reverselookup']:
- arr.extend(['IP_ADDRESS', 'NETBLOCK', 'IP_SUBNET'])
+ 'TARGET_WEB_CONTENT', 'LINKED_URL_INTERNAL', 'INTERNET_NAME',
+ 'IP_ADDRESS', 'NETBLOCK', 'IP_SUBNET']
return arr
# What events this module produces
# This is to support the end user in selecting modules based on events
# produced.
def producedEvents(self):
- return [ "IP_ADDRESS", "SUBDOMAIN", "PROVIDER_MAIL",
- "PROVIDER_DNS", "AFFILIATE", "RAW_DNS_RECORDS" ]
+ return [ "IP_ADDRESS", "INTERNET_NAME", "PROVIDER_MAIL", "DOMAIN_NAME",
+ "PROVIDER_DNS", "AFFILIATE_INTERNET_NAME", "RAW_DNS_RECORDS" ]
# Handle events sent to this module
def handleEvent(self, event):
@@ -100,25 +146,24 @@ class sfp_dns(SpiderFootPlugin):
sf.debug("Received event, " + eventName + ", from " + srcModuleName)
- if self.subresults.has_key(eventData):
+ if self.events.has_key(eventData):
return None
- self.subresults[eventData] = True
+ self.events[eventData] = True
+ # Identify potential sub-domains/hostnames
if eventName in [ "SEARCH_ENGINE_WEB_CONTENT", "TARGET_WEB_CONTENT",
"LINKED_URL_INTERNAL", "RAW_RIR_DATA", "RAW_DNS_RECORDS" ]:
# If we've received a link or some raw data, extract potential sub-domains
# from the data for resolving later.
- matches = re.findall("([a-zA-Z0-9\-\.]+\." + self.baseDomain + ")", eventData,
- re.IGNORECASE)
-
- if matches != None:
- for match in matches:
- if match.lower().startswith("2f"):
- continue
-
- self.processHost(match, parentEvent)
-
+ for name in self.getTarget().getNames():
+ if self.checkForStop():
+ return None
+ pat = re.compile("([a-zA-Z0-9\-\.]+\." + name + ")", re.IGNORECASE)
+ matches = re.findall(pat, eventData)
+ if matches != None:
+ for match in matches:
+ self.processHost(match, parentEvent)
# Nothing left to do with internal links and raw data
return None
@@ -136,17 +181,17 @@ class sfp_dns(SpiderFootPlugin):
sf.debug("Looking up IPs in " + eventData)
for ip in IPNetwork(eventData):
- if self.checkForStop():
- return None
ipaddr = str(ip)
-
- if self.results.has_key(ipaddr):
+ if ipaddr.split(".")[3] in [ '255', '0']:
+ continue
+ if '255' in ipaddr.split("."):
continue
- else:
- self.results[ipaddr] = True
- try:
- addrs = socket.gethostbyaddr(ipaddr)
+ if self.checkForStop():
+ return None
+ addrs = self.resolveIP(ipaddr)
+
+ if addrs != None:
sf.debug("Found a reversed hostname from " + ipaddr + \
" (" + str(addrs) + ")")
for addr in addrs:
@@ -154,52 +199,47 @@ class sfp_dns(SpiderFootPlugin):
for host in addr:
# Don't report on anything on the same subnet if
# if doesn't resolve to something on the target
- if not host.endswith(self.baseDomain) and \
- eventName == 'IP_SUBNET':
+ # 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(host) \
+ and eventName == 'IP_SUBNET':
continue
- self.processHost(host, parentEvent)
+ # Generate an event for the IP, then
+ # let the handling by this module take
+ # care of follow-up processing.
+ self.processHost(ipaddr, parentEvent)
else:
- if not addr.endswith(self.baseDomain) and \
- eventName == 'IP_SUBNET':
+ # Same as above comment
+ if not self.getTarget().matches(addr) \
+ and eventName == 'IP_SUBNET':
continue
- self.processHost(addr, parentEvent)
- except Exception as e:
- #sf.debug("Exception encountered: " + str(e))
- continue
+ self.processHost(ipaddr, parentEvent)
return None
- # Handling SUBDOMAIN and IP_ADDRESS events..
+ # Handling INTERNET_NAME and IP_ADDRESS events..
- # Don't look up stuff twice
- if self.results.has_key(eventData):
- sf.debug("Skipping " + eventData + " as already resolved.")
- return None
+ if eventName != 'IP_ADDRESS':
+ if '://' in eventData:
+ addrs = self.resolveHost(sf.urlFQDN(eventData))
+ else:
+ addrs = self.resolveHost(eventData)
else:
- self.results[eventData] = True
+ addrs = self.resolveIP(eventData)
- try:
- if eventName != 'IP_ADDRESS':
- if '://' in eventData:
- addrs = self.resolveHost(sf.urlFQDN(eventData))
- else:
- addrs = self.resolveHost(eventData)
- if addrs == None:
- return None
- else:
- addrs = socket.gethostbyaddr(eventData)
- except BaseException as e:
- sf.info("Unable to resolve " + eventData + " (" + str(e) + ")")
+ if addrs == None:
return None
+ else:
+ for addr in addrs:
+ if type(addr) == list:
+ for host in addr:
+ self.processHost(host, parentEvent)
+ else:
+ self.processHost(addr, parentEvent)
- for addr in addrs:
- if type(addr) == list:
- for host in addr:
- self.processHost(host, parentEvent)
- else:
- self.processHost(addr, parentEvent)
-
- # Try to reverse-resolve
+ # Try to reverse-resolve IPs 'near' the identified IP
if self.opts['lookaside'] and eventName == 'IP_ADDRESS':
ip = IPAddress(eventData)
minip = IPAddress(int(ip) - self.opts['lookasidecount'])
@@ -212,30 +252,63 @@ class sfp_dns(SpiderFootPlugin):
if self.checkForStop():
return None
- if self.results.has_key(sip):
+ if self.hostresults.has_key(sip):
s = s + 1
continue
- try:
- addrs = socket.gethostbyaddr(sip)
- for addr in addrs:
- if type(addr) == list:
- for host in addr:
- if host.endswith(self.baseDomain):
- self.processHost(host, parentEvent)
- else:
- if addr.endswith(self.baseDomain):
- self.processHost(addr, parentEvent)
- except BaseException as e:
- sf.debug("Look-aside lookup failed: " + str(e))
+ addrs = self.resolveIP(sip)
+ if addrs == None:
+ sf.debug("Look-aside resolve for " + sip + " failed.")
+ s = s + 1
+ continue
+
+ # Report addresses that resolve to hostnames on the same
+ # domain or sub-domain as the target.
+ for addr in addrs:
+ if type(addr) == list:
+ for host in addr:
+ if self.getTarget().matches(host):
+ # Generate an event for the IP, then
+ # let the handling by this module take
+ # care of follow-up processing.
+ self.processHost(sip, parentEvent)
+ else:
+ if self.getTarget().matches(addr):
+ self.processHost(sip, parentEvent)
s = s + 1
return None
+ # Resolve an IP
+ def resolveIP(self, ipaddr):
+ ret = list()
+ sf.debug("Performing reverse-resolve of " + ipaddr)
+
+ if self.resolveCache.has_key(ipaddr):
+ sf.debug("Returning cached result for " + ipaddr + " (" + \
+ str(self.resolveCache[ipaddr]) + ")")
+ return self.resolveCache[ipaddr]
+
+ try:
+ addrs = socket.gethostbyaddr(ipaddr)
+ for addr in addrs:
+ if type(addr) == list:
+ for host in addr:
+ ret.append(host)
+ else:
+ ret.append(addr)
+ self.resolveCache[ipaddr] = ret
+ return ret
+ except BaseException as e:
+ sf.info("Unable to resolve " + ipaddr + " (" + str(e) + ")")
+ self.resolveCache[ipaddr] = None
+ return None
+
# Resolve a host
def resolveHost(self, hostname):
if self.resolveCache.has_key(hostname):
- sf.debug("Returning cached result for " + hostname)
+ sf.debug("Returning cached result for " + hostname + " (" + \
+ str(self.resolveCache[hostname]) + ")" )
return self.resolveCache[hostname]
try:
@@ -246,32 +319,61 @@ class sfp_dns(SpiderFootPlugin):
sf.info("Unable to resolve " + hostname + " (" + str(e) + ")")
return None
- def processHost(self, host, parentEvent=None):
+ def processHost(self, host, parentEvent):
+ if not self.hostresults.has_key(host):
+ self.hostresults[host] = list(parentEvent.data)
+ else:
+ if parentEvent.data in self.hostresults[host]:
+ sf.debug("Skipping host, " + host + ", already processed.")
+ return None
+ else:
+ self.hostresults[host].append(parentEvent.data)
+
sf.debug("Found host: " + host)
# If the returned hostname is on a different
- # domain to baseDomain, flag it as an affiliate
- if not host.lower().endswith(self.baseDomain):
+ # domain to the target, flag it as an affiliate
+ if not self.getTarget().matches(host):
if sf.validIP(host):
- htype = "IP_ADDRESS"
+ htype = "AFFILIATE_IPADDR"
else:
- htype = "AFFILIATE"
+ htype = "AFFILIATE_INTERNET_NAME"
else:
- htype = "SUBDOMAIN"
+ if sf.validIP(host):
+ htype = "IP_ADDRESS"
+ else:
+ htype = "INTERNET_NAME"
if parentEvent != None:
# Don't report back the same thing that was provided
if htype == parentEvent.eventType and host == parentEvent.data:
- return
+ return None
- if htype == "SUBDOMAIN" and self.opts['onlyactive']:
+ if htype.endswith("INTERNET_NAME") and self.opts['onlyactive']:
if self.resolveHost(host) == None:
return None
+ # Report the host
evt = SpiderFootEvent(htype, host, self.__name__, parentEvent)
self.notifyListeners(evt)
+ # Report the domain for that host
+ if htype == "INTERNET_NAME":
+ dom = sf.hostDomain(host, self.opts['_internettlds'])
+ self.processDomain(dom, evt)
- def start(self):
- sf.debug("Gathering DNS records..")
+ return evt
+
+ def processDomain(self, domainName, parentEvent):
+ if not self.domresults.has_key(domainName):
+ self.domresults[domainName] = True
+ else:
+ sf.debug("Skipping domain, " + domainName + ", already processed.")
+ return None
+
+ domevt = SpiderFootEvent("DOMAIN_NAME", domainName, self.__name__,
+ parentEvent)
+ self.notifyListeners(domevt)
+
+ sf.debug("Gathering DNS records for " + domainName)
# Process the raw data alone
recdata = dict()
recs = {
@@ -281,7 +383,7 @@ class sfp_dns(SpiderFootPlugin):
for rec in recs.keys():
try:
- req = dns.message.make_query(self.baseDomain, dns.rdatatype.from_text(rec))
+ req = dns.message.make_query(domainName, dns.rdatatype.from_text(rec))
if self.opts['_dnsserver'] != "":
n = self.opts['_dnsserver']
@@ -293,7 +395,8 @@ class sfp_dns(SpiderFootPlugin):
for x in res.answer:
for rx in recs.keys():
sf.debug("Checking " + str(x) + " + against " + recs[rx][0])
- grps = re.findall(recs[rx][0], str(x), re.IGNORECASE|re.DOTALL)
+ pat = re.compile(recs[rx][0], re.IGNORECASE|re.DOTALL)
+ grps = re.findall(pat, str(x))
if len(grps) > 0:
for m in grps:
sf.debug("Matched: " + m)
@@ -301,9 +404,9 @@ class sfp_dns(SpiderFootPlugin):
evt = SpiderFootEvent(recs[rx][1], strdata,
self.__name__)
self.notifyListeners(evt)
- if not strdata.endswith(self.baseDomain):
- evt = SpiderFootEvent("AFFILIATE", strdata,
- self.__name__)
+ if not strdata.endswith(domainName):
+ evt = SpiderFootEvent("AFFILIATE_INTERNET_NAME",
+ strdata, self.__name__)
self.notifyListeners(evt)
else:
strdata = unicode(str(x), 'utf-8', errors='replace')
@@ -311,23 +414,14 @@ class sfp_dns(SpiderFootPlugin):
self.__name__)
self.notifyListeners(evt)
except BaseException as e:
- sf.error("Failed to obtain DNS response: " + str(e), False)
+ sf.error("Failed to obtain DNS response for " + domainName + \
+ "(" + rec + "): " + str(e), False)
- sublist = self.opts['commonsubs']
-
- # Also look up the base target itself
- sublist.append('')
- # User may have supplied a file or URL containing the subdomains
- if self.opts['commonsubs'][0].startswith("http://") or \
- self.opts['commonsubs'][0].startswith("https://") or \
- self.opts['commonsubs'][0].startswith("@"):
- sublist = sf.optValueToData(self.opts['commonsubs'][0])
-
- sf.debug("Iterating through possible sub-domains [" + str(sublist) + "]")
+ sf.debug("Iterating through possible sub-domains [" + str(self.sublist) + "]")
count = 0
- wildcard = sf.checkDnsWildcard(self.baseDomain)
+ wildcard = sf.checkDnsWildcard(domainName)
# Try resolving common names
- for sub in sublist:
+ for sub in self.sublist:
if wildcard and self.opts['skipcommononwildcard'] and count > 0:
sf.debug("Wildcard DNS detected, skipping iterating through remaining hosts.")
return None
@@ -337,28 +431,17 @@ class sfp_dns(SpiderFootPlugin):
count += 1
if sub != "":
- name = sub + "." + self.baseDomain
+ name = sub + "." + domainName
else:
- name = self.baseDomain
- # Don't look up stuff twice
- if self.results.has_key(name):
- sf.debug("Skipping " + name + " as already resolved.")
continue
- else:
- self.results[name] = True
addrs = self.resolveHost(name)
if addrs != None:
- self.processHost(name)
for addr in addrs:
if type(addr) == list:
for host in addr:
- if host not in self.results.keys():
- self.processHost(host)
- self.results[host] = True
+ self.processHost(host, domevt)
else:
- if addr not in self.results.keys():
- self.processHost(addr)
- self.results[addr] = True
+ self.processHost(addr, domevt)
# End of sfp_dns class
diff --git a/modules/sfp_email.py b/modules/sfp_email.py
index 37a612d9..aa1e6eb1 100644
--- a/modules/sfp_email.py
+++ b/modules/sfp_email.py
@@ -23,27 +23,18 @@ class sfp_email(SpiderFootPlugin):
# Default options
opts = {
# options specific to this module
- 'includesubdomains': True, # Include e-mail addresses on sub-domains of
- # the target domain
'includeexternal': False # Include e-mail addrs on external domains
}
# Option descriptions
optdescs = {
- 'includesubdomains': "Report e-mail addresses on a sub-domain of the target base domain-name?",
'includeexternal': "Report e-mail addresses not on the target base domain-name?"
}
- # Target
- baseDomain = None
- results = dict()
-
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
- self.baseDomain = target
- self.results = dict()
for opt in userOpts.keys():
self.opts[opt] = userOpts[opt]
@@ -74,7 +65,8 @@ class sfp_email(SpiderFootPlugin):
sf.debug("Unhandled type to find e-mails: " + str(type(eventData)))
return None
- matches = re.findall("([a-zA-Z\.0-9_\-]+@[a-zA-Z\.0-9_\-]+)", eventData)
+ pat = re.compile("([a-zA-Z\.0-9_\-]+@[a-zA-Z\.0-9\-]+\.[a-zA-Z\.0-9\-]+)")
+ matches = re.findall(pat, eventData)
for match in matches:
sf.debug("Found possible email: " + match)
@@ -82,24 +74,12 @@ class sfp_email(SpiderFootPlugin):
sf.debug("Likely invalid address.")
continue
- if self.baseDomain not in match.lower():
- sf.debug("E-mail (or something) from somewhere else..")
+ mailDom = match.lower().split('@')[1]
+ if not self.opts['includeexternal'] and not \
+ self.getTarget().matches(mailDom):
+ sf.debug("Ignoring e-mail address on an external domain: " + match)
continue
- self.results[match] = True
-
- # Include e-mail addresses on sub-domains within the domain?
- if not self.opts['includesubdomains']:
- if not match.lower().endswith('@' + self.baseDomain):
- sf.debug("Ignoring e-mail address on a sub-domain: " + match)
- continue
-
- # Include external domains as e-mail addresses?
- if not self.opts['includeexternal']:
- if not match.lower().endswith(self.baseDomain):
- sf.debug("Ignoring e-mail address on an external domain" + match)
- continue
-
sf.info("Found e-mail address: " + match)
evt = SpiderFootEvent("EMAILADDR", match, self.__name__, parentEvent)
self.notifyListeners(evt)
diff --git a/modules/sfp_filemeta.py b/modules/sfp_filemeta.py
index 61cb9efd..eae368f4 100644
--- a/modules/sfp_filemeta.py
+++ b/modules/sfp_filemeta.py
@@ -42,7 +42,7 @@ class sfp_filemeta(SpiderFootPlugin):
results = list()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
diff --git a/modules/sfp_geoip.py b/modules/sfp_geoip.py
index 9d518152..48320846 100644
--- a/modules/sfp_geoip.py
+++ b/modules/sfp_geoip.py
@@ -25,7 +25,7 @@ class sfp_geoip(SpiderFootPlugin):
opts = { }
results = dict()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
diff --git a/modules/sfp_googlesearch.py b/modules/sfp_googlesearch.py
index 601add44..fc0263ba 100644
--- a/modules/sfp_googlesearch.py
+++ b/modules/sfp_googlesearch.py
@@ -36,7 +36,7 @@ class sfp_googlesearch(SpiderFootPlugin):
# Target
results = list()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
@@ -47,7 +47,7 @@ class sfp_googlesearch(SpiderFootPlugin):
# What events is this module interested in for input
def watchedEvents(self):
- return [ "DOMAIN_NAME" ]
+ return [ "INTERNET_NAME" ]
# What events this module produces
# This is to support the end user in selecting modules based on events
@@ -101,7 +101,7 @@ class sfp_googlesearch(SpiderFootPlugin):
else:
self.results.append(link)
sf.debug("Found a link: " + link)
- if sf.urlBaseUrl(link).endswith(eventData):
+ if sf.urlFQDN(link).endswith(eventData):
if self.checkForStop():
return None
diff --git a/modules/sfp_honeypot.py b/modules/sfp_honeypot.py
index acd920ed..429fc911 100644
--- a/modules/sfp_honeypot.py
+++ b/modules/sfp_honeypot.py
@@ -56,7 +56,7 @@ class sfp_honeypot(SpiderFootPlugin):
"10": "Unknown (10)"
}
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
diff --git a/modules/sfp_intfiles.py b/modules/sfp_intfiles.py
index b4528d7f..d77c44d3 100644
--- a/modules/sfp_intfiles.py
+++ b/modules/sfp_intfiles.py
@@ -41,7 +41,7 @@ class sfp_intfiles(SpiderFootPlugin):
results = list()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
@@ -52,7 +52,7 @@ class sfp_intfiles(SpiderFootPlugin):
# What events is this module interested in for input
def watchedEvents(self):
- return [ "DOMAIN_NAME", "LINKED_URL_INTERNAL" ]
+ return [ "INTERNET_NAME", "LINKED_URL_INTERNAL" ]
# What events this module produces
# This is to support the end user in selecting modules based on events
@@ -71,7 +71,7 @@ class sfp_intfiles(SpiderFootPlugin):
sf.debug("Received event, " + eventName + ", from " + srcModuleName)
- if eventName == "DOMAIN_NAME" and not self.opts['usesearch']:
+ if eventName == "INTERNET_NAME" and not self.opts['usesearch']:
sf.debug("Not using a search engine to find interesting files.")
return None
@@ -91,7 +91,7 @@ class sfp_intfiles(SpiderFootPlugin):
self.notifyListeners(evt)
return None
- # Handling DOMAIN_NAME event..
+ # Handling INTERNET_NAME event..
for fileExt in self.opts['fileexts']:
# Sites hosted on the domain
if self.opts['searchengine'].lower() == "google":
@@ -147,7 +147,7 @@ class sfp_intfiles(SpiderFootPlugin):
else:
self.results.append(link)
- if sf.urlBaseUrl(link).endswith(eventData) and \
+ if sf.urlFQDN(link).endswith(eventData) and \
"." + fileExt.lower() in link.lower():
sf.info("Found an interesting file: " + link)
evt = SpiderFootEvent("INTERESTING_FILE", link, self.__name__)
diff --git a/modules/sfp_ir.py b/modules/sfp_ir.py
index 32c361f6..392e067c 100644
--- a/modules/sfp_ir.py
+++ b/modules/sfp_ir.py
@@ -24,19 +24,16 @@ class sfp_ir(SpiderFootPlugin):
# Default options
opts = { }
- # Target
- baseDomain = None
results = dict()
currentEventSrc = None
memCache = dict()
nbreported = dict()
- keyword = None
+ keywords = None
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
- self.baseDomain = target
self.results = dict()
self.memCache = dict()
self.currentEventSrc = None
@@ -45,9 +42,6 @@ class sfp_ir(SpiderFootPlugin):
for opt in userOpts.keys():
self.opts[opt] = userOpts[opt]
- self.keyword = sf.domainKeyword(self.baseDomain,
- self.opts['_internettlds']).lower()
-
# What events is this module interested in for input
def watchedEvents(self):
return ['IP_ADDRESS']
@@ -56,7 +50,7 @@ class sfp_ir(SpiderFootPlugin):
# This is to support the end user in selecting modules based on events
# produced.
def producedEvents(self):
- return [ "NETBLOCK", "RAW_RIR_DATA", "BGP_AS", "PROVIDER_INTERNET" ]
+ return [ "NETBLOCK", "RAW_RIR_DATA", "BGP_AS_OWNER", "PROVIDER_INTERNET" ]
# Fetch content and notify of the raw data
def fetchRir(self, url):
@@ -197,9 +191,13 @@ class sfp_ir(SpiderFootPlugin):
# and the string supplied.
def findName(self, string):
# Simplest check to perform..
- if self.baseDomain in string:
+ if self.getTarget().getValue() in string:
return True
+ if self.keywords == None:
+ self.keywords = sf.domainKeywords(self.getTarget().getNames(),
+ self.opts['_internettlds'])
+
# Slightly more complex..
rx = [
'^{0}[-_/\'\"\\\.,\?\! ]',
@@ -209,12 +207,15 @@ class sfp_ir(SpiderFootPlugin):
# Mess with the keyword as a last resort..
keywordList = list()
- # Create versions of the keyword, esp. if hyphens are involved.
- keywordList.append(self.keyword)
- keywordList.append(self.keyword.replace('-', ' '))
- keywordList.append(self.keyword.replace('-', '_'))
- keywordList.append(self.keyword.replace('-', ''))
+ for kw in self.keywords:
+ # Create versions of the keyword, esp. if hyphens are involved.
+ keywordList.append(kw)
+ keywordList.append(kw.replace('-', ' '))
+ keywordList.append(kw.replace('-', '_'))
+ keywordList.append(kw.replace('-', ''))
+
for kw in keywordList:
+ sf.debug("Looking for keyword: " + kw)
for r in rx:
if re.match(r.format(kw), string, re.IGNORECASE) != None:
return True
@@ -261,7 +262,7 @@ class sfp_ir(SpiderFootPlugin):
sf.info("Owned netblock found: " + prefix + "(" + asn + ")")
evt = SpiderFootEvent("NETBLOCK", prefix, self.__name__, event)
self.notifyListeners(evt)
- asevt = SpiderFootEvent("BGP_AS", asn, self.__name__, event)
+ asevt = SpiderFootEvent("BGP_AS_OWNER", asn, self.__name__, event)
self.notifyListeners(asevt)
# Don't report additional netblocks from this AS if we've
diff --git a/modules/sfp_malcheck.py b/modules/sfp_malcheck.py
index e3068794..2dc523de 100644
--- a/modules/sfp_malcheck.py
+++ b/modules/sfp_malcheck.py
@@ -268,7 +268,7 @@ class sfp_malcheck(SpiderFootPlugin):
results = list()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
@@ -283,17 +283,17 @@ class sfp_malcheck(SpiderFootPlugin):
# What events is this module interested in for input
# * = be notified about all events.
def watchedEvents(self):
- return ["DOMAIN_NAME", "IP_ADDRESS", "BGP_AS", "SUBDOMAIN",
- "IP_SUBNET", "AFFILIATE_DOMAIN", "AFFILIATE_IPADDR",
+ return ["INTERNET_NAME", "IP_ADDRESS", "BGP_AS_OWNER",
+ "IP_SUBNET", "AFFILIATE_INTERNET_NAME", "AFFILIATE_IPADDR",
"CO_HOSTED_SITE", "NETBLOCK" ]
# What events this module produces
# This is to support the end user in selecting modules based on events
# produced.
def producedEvents(self):
- return [ "MALICIOUS_ASN", "MALICIOUS_IPADDR", "MALICIOUS_SUBDOMAIN",
- "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_AFFILIATE", "MALICIOUS_SUBNET",
- "MALICIOUS_COHOST", "MALICIOUS_DOMAIN_NAME" ]
+ return [ "MALICIOUS_ASN", "MALICIOUS_IPADDR", "MALICIOUS_INTERNET_NAME",
+ "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_AFFILIATE_INTERNET_NAME",
+ "MALICIOUS_SUBNET", "MALICIOUS_COHOST" ]
# Check the regexps to see whether the content indicates maliciousness
def contentMalicious(self, content, goodregex, badregex):
@@ -361,11 +361,12 @@ class sfp_malcheck(SpiderFootPlugin):
# build a list of IP.
# Cycle through each IP and check if it's in the netblock.
if malchecks[check].has_key('regex'):
- rx = rxTgt = malchecks[check]['regex'].replace("{0}", \
+ rx = malchecks[check]['regex'].replace("{0}", \
"(\d+\.\d+\.\d+\.\d+)")
+ pat = re.compile(rx, re.IGNORECASE)
sf.debug("New regex for " + check + ": " + rx)
for line in data['content'].split('\n'):
- grp = re.findall(rx, line, re.IGNORECASE)
+ grp = re.findall(pat, line)
if len(grp) > 0:
#sf.debug("Adding " + grp[0] + " to list.")
iplist.append(grp[0])
@@ -453,19 +454,17 @@ class sfp_malcheck(SpiderFootPlugin):
else:
evtType = 'MALICIOUS_AFFILIATE_IPADDR'
- if eventName in [ 'BGP_AS' ]:
+ if eventName in [ 'BGP_AS_OWNER' ]:
typeId = 'asn'
evtType = 'MALICIOUS_ASN'
- if eventName in [ 'DOMAIN_NAME', 'CO_HOSTED_SITE',
- 'AFFILIATE_DOMAIN', 'SUBDOMAIN' ]:
+ if eventName in [ 'INTERNET_NAME', 'CO_HOSTED_SITE',
+ 'AFFILIATE_INTERNET_NAME', ]:
typeId = 'domain'
- if eventName == 'SUBDOMAIN':
- evtType = 'MALICIOUS_SUBDOMAIN'
- if eventName == "DOMAIN_NAME":
- evtType = "MALICIOUS_DOMAIN_NAME"
- if eventName == 'AFFILIATE_DOMAIN':
- evtType = 'MALICIOUS_AFFILIATE'
+ if eventName == "INTERNET_NAME":
+ evtType = "MALICIOUS_INTERNET_NAME"
+ if eventName == 'AFFILIATE_INTERNET_NAME':
+ evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'
if eventName == 'CO_HOSTED_SITE':
evtType = 'MALICIOUS_COHOST'
diff --git a/modules/sfp_names.py b/modules/sfp_names.py
index 636ff990..436db79a 100644
--- a/modules/sfp_names.py
+++ b/modules/sfp_names.py
@@ -47,7 +47,7 @@ class sfp_names(SpiderFootPlugin):
return wd.keys()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
@@ -87,7 +87,8 @@ class sfp_names(SpiderFootPlugin):
sf.debug("Received event, " + eventName + ", from " + srcModuleName)
# Stage 1: Find things that look (very vaguely) like names
- m = re.findall("([A-Z][a-z]+)\s+.?.?\s?([A-Z][a-zA-Z\'\-]+)", eventData)
+ rx = re.compile("([A-Z][a-z]+)\s+.?.?\s?([A-Z][a-zA-Z\'\-]+)")
+ m = re.findall(rx, eventData)
for r in m:
# Start off each match as 0 points.
p = 0
diff --git a/modules/sfp_pageinfo.py b/modules/sfp_pageinfo.py
index ad2bc615..fcca2422 100644
--- a/modules/sfp_pageinfo.py
+++ b/modules/sfp_pageinfo.py
@@ -36,15 +36,12 @@ etc.)"""
# Default options
opts = { }
- # Target
- baseDomain = None # calculated from the URL in setup
results = dict()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
- self.baseDomain = target
self.results = dict()
for opt in userOpts.keys():
@@ -79,7 +76,7 @@ etc.)"""
# We aren't interested in describing pages that are not hosted on
# our base domain.
- if not sf.urlBaseUrl(eventSource).endswith(self.baseDomain):
+ if not self.getTarget().matches(sf.urlFQDN(eventSource)):
sf.debug("Not gathering page info for external site " + eventSource)
return None
@@ -95,11 +92,13 @@ etc.)"""
continue
for regex in regexps[regexpGrp]:
- matches = re.findall(regex, eventData, re.IGNORECASE)
+ rx = re.compile(regex, re.IGNORECASE)
+ matches = re.findall(rx, eventData)
if len(matches) > 0 and regexpGrp not in self.results[eventSource]:
sf.info("Matched " + regexpGrp + " in content from " + eventSource)
self.results[eventSource].append(regexpGrp)
- evt = SpiderFootEvent(regexpGrp, eventSource, self.__name__, event.sourceEvent)
+ evt = SpiderFootEvent(regexpGrp, eventSource,
+ self.__name__, event.sourceEvent)
self.notifyListeners(evt)
# If no regexps were matched, consider this a static page
@@ -109,12 +108,14 @@ etc.)"""
self.notifyListeners(evt)
# Check for externally referenced Javascript pages
- matches = re.findall("<script.*src=[\'\"]?([^\'\">]*)", eventData, re.IGNORECASE)
+ pat = re.compile("<script.*src=[\'\"]?([^\'\">]*)", re.IGNORECASE)
+ matches = re.findall(pat, eventData)
if len(matches) > 0:
for match in matches:
- if '://' in match and not sf.urlBaseUrl(match).endswith(self.baseDomain):
+ if '://' in match and not self.getTarget().matches(sf.urlFQDN(match)):
sf.debug("Externally hosted Javascript found at: " + match)
- evt = SpiderFootEvent("PROVIDER_JAVASCRIPT", match, self.__name__, event.sourceEvent)
+ evt = SpiderFootEvent("PROVIDER_JAVASCRIPT", match,
+ self.__name__, event.sourceEvent)
self.notifyListeners(evt)
return None
diff --git a/modules/sfp_pastebin.py b/modules/sfp_pastebin.py
index d3c600df..048bb234 100644
--- a/modules/sfp_pastebin.py
+++ b/modules/sfp_pastebin.py
@@ -34,7 +34,7 @@ class sfp_pastebin(SpiderFootPlugin):
results = list()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
@@ -45,7 +45,7 @@ class sfp_pastebin(SpiderFootPlugin):
# What events is this module interested in for input
def watchedEvents(self):
- return [ "DOMAIN_NAME", "IP_ADDRESS", "EMAILADDR" ]
+ return [ "INTERNET_NAME", "IP_ADDRESS", "EMAILADDR" ]
# What events this module produces
# This is to support the end user in selecting modules based on events
diff --git a/modules/sfp_portscan_basic.py b/modules/sfp_portscan_basic.py
index 19caa6ca..385914ad 100644
--- a/modules/sfp_portscan_basic.py
+++ b/modules/sfp_portscan_basic.py
@@ -54,7 +54,7 @@ class sfp_portscan_basic(SpiderFootPlugin):
portlist = list()
portResults = dict()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
@@ -135,8 +135,7 @@ class sfp_portscan_basic(SpiderFootPlugin):
for cp in resArray:
if resArray[cp]:
sf.info("TCP Port " + cp + " found to be OPEN.")
- (addr, port) = cp.split(":")
- evt = SpiderFootEvent("TCP_PORT_OPEN", port, self.__name__, srcEvent)
+ evt = SpiderFootEvent("TCP_PORT_OPEN", cp, self.__name__, srcEvent)
self.notifyListeners(evt)
if resArray[cp] != "" and resArray[cp] != True:
bevt = SpiderFootEvent("TCP_PORT_OPEN_BANNER", resArray[cp],
@@ -160,8 +159,13 @@ class sfp_portscan_basic(SpiderFootPlugin):
sf.debug("Skipping port scanning of " + eventData + ", too big.")
return None
- for ip in list(net):
- scanIps.append(str(ip))
+ for ip in net:
+ ipaddr = str(ip)
+ if ipaddr.split(".")[3] in [ '255', '0']:
+ continue
+ if '255' in ipaddr.split("."):
+ continue
+ scanIps.append(ipaddr)
else:
scanIps.append(eventData)
except BaseException as e:
diff --git a/modules/sfp_sharedip.py b/modules/sfp_sharedip.py
index c2f88fd7..d4bf053d 100644
--- a/modules/sfp_sharedip.py
+++ b/modules/sfp_sharedip.py
@@ -38,15 +38,12 @@ class sfp_sharedip(SpiderFootPlugin):
'verify': "Verify co-hosts are valid by checking if they still resolve to the shared IP."
}
- # Target
- baseDomain = None
results = list()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
- self.baseDomain = target
self.results = list()
for opt in userOpts.keys():
@@ -97,22 +94,24 @@ class sfp_sharedip(SpiderFootPlugin):
# Robtex
if self.opts['source'].lower() == "robtex":
- res = sf.fetchUrl("https://www.robtex.com/ip/" + eventData + ".html")
+ res = sf.fetchUrl("https://www.robtex.com/shared/" + eventData + ".html")
if res['content'] == None:
sf.error("Unable to fetch robtex content.", False)
return None
myres = list()
- blob = re.findall(".*Pointing to(.[^!]+)shared_pp_pa.*", res['content'],
- re.IGNORECASE|re.DOTALL)
+ pat = re.compile("Pointing to(.[^!]+)", re.IGNORECASE)
+ blob = re.findall(pat, res['content'])
+
if len(blob) > 0:
- matches = re.findall("href=\"//www.robtex.com/dns/(.[^\"]*).html",
- blob[0], re.IGNORECASE)
+ pat = re.compile("href=\"//www.robtex.com/dns/(.[^\"]*).html", re.IGNORECASE)
+ matches = re.findall(pat, blob[0])
for m in matches:
sf.info("Found something on same IP: " + m)
- if not self.opts['cohostsamedomain'] and m.endswith(self.baseDomain):
- sf.debug("Skipping " + m + " because it is on the same domain.")
- continue
+ if not self.opts['cohostsamedomain']:
+ if self.getTarget().matches(m, includeParents=True):
+ sf.debug("Skipping " + m + " because it is on the same domain.")
+ continue
if '*' in m:
sf.debug("Skipping wildcard name: " + m)
@@ -141,15 +140,16 @@ class sfp_sharedip(SpiderFootPlugin):
for key in results.keys():
res = results[key]
- matches = re.findall("<div class=\"sb_meta\"><cite>(\S+)</cite>",
- res, re.IGNORECASE)
+ pat = re.compile("<div class=\"sb_meta\"><cite>(\S+)</cite>", re.IGNORECASE)
+ matches = re.findall(pat, res)
for match in matches:
sf.info("Found something on same IP: " + match)
site = sf.urlFQDN(match)
if site not in myres and site != eventData:
- if not self.opts['cohostsamedomain'] and site.endswith(self.baseDomain):
- sf.debug("Skipping " + site + " because it is on the same domain.")
- continue
+ if not self.opts['cohostsamedomain']:
+ if self.getTarget().matches(m, includeParents=True):
+ sf.debug("Skipping " + site + " because it is on the same domain.")
+ continue
if self.opts['verify'] and not self.validateIP(m, eventData):
sf.debug("Host no longer resolves to our IP.")
continue
diff --git a/modules/sfp_shodan.py b/modules/sfp_shodan.py
index 3469fa18..72a6591b 100644
--- a/modules/sfp_shodan.py
+++ b/modules/sfp_shodan.py
@@ -31,7 +31,7 @@ class sfp_shodan(SpiderFootPlugin):
results = dict()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
@@ -105,7 +105,8 @@ class sfp_shodan(SpiderFootPlugin):
if port != None:
# Notify other modules of what you've found
- evt = SpiderFootEvent("TCP_PORT_OPEN", port, self.__name__, event)
+ cp = eventData + ":" + port
+ evt = SpiderFootEvent("TCP_PORT_OPEN", cp, self.__name__, event)
self.notifyListeners(evt)
if banner != None:
diff --git a/modules/sfp_similar.py b/modules/sfp_similar.py
index 450b3e02..00ace4e3 100644
--- a/modules/sfp_similar.py
+++ b/modules/sfp_similar.py
@@ -62,7 +62,7 @@ class sfp_similar(SpiderFootPlugin):
# Internal results tracking
results = list()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
@@ -72,14 +72,15 @@ class sfp_similar(SpiderFootPlugin):
self.opts[opt] = userOpts[opt]
def findDomains(self, keyword, content):
- matches = re.findall("([a-z0-9\-]*" + keyword + "[a-z0-9\-]*\.[a-z]+)",
- content, re.IGNORECASE)
+ pat = re.compile("([a-z0-9\-]*" + keyword + "[a-z0-9\-]*\.[a-z]+)",
+ re.IGNORECASE)
+ matches = re.findall(pat, content)
return matches
# What events is this module interested in for input
def watchedEvents(self):
- return [ "DOMAIN_NAME" ]
+ return [ "INTERNET_NAME" ]
# What events this module produces
# This is to support the end user in selecting modules based on events
diff --git a/modules/sfp_social.py b/modules/sfp_social.py
index 48e5f35a..e8e4555c 100644
--- a/modules/sfp_social.py
+++ b/modules/sfp_social.py
@@ -44,7 +44,7 @@ class sfp_social(SpiderFootPlugin):
results = dict()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
diff --git a/modules/sfp_socialprofiles.py b/modules/sfp_socialprofiles.py
index fae2f806..303d8b99 100644
--- a/modules/sfp_socialprofiles.py
+++ b/modules/sfp_socialprofiles.py
@@ -47,24 +47,18 @@ class sfp_socialprofiles(SpiderFootPlugin):
'method': "Search engine to use: google, yahoo or bing."
}
- # Target
- baseDomain = None
- keyword = None
+ keywords = None
results = list()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
- self.baseDomain = target
self.results = list()
for opt in userOpts.keys():
self.opts[opt] = userOpts[opt]
- self.keyword = sf.domainKeyword(self.baseDomain,
- self.opts['_internettlds']).lower()
-
# What events is this module interested in for input
def watchedEvents(self):
return [ "HUMAN_NAME" ]
@@ -95,6 +89,10 @@ class sfp_socialprofiles(SpiderFootPlugin):
else:
self.results.append(eventData)
+ if self.keywords == None:
+ self.keywords = sf.domainKeywords(self.getTarget().getNames(),
+ self.opts['_internettlds'])
+
for site in sites.keys():
searchStr = sites[site][0].format(eventData).replace(" ", "%20")
searchDom = sites[site][1]
@@ -155,8 +153,12 @@ class sfp_socialprofiles(SpiderFootPlugin):
if pres['content'] == None:
continue
else:
- if re.search("[^a-zA-Z\-\_]" + self.keyword + \
- "[^a-zA-Z\-\_]", pres['content'], re.IGNORECASE) == None:
+ found = False
+ for kw in self.keywords:
+ if re.search("[^a-zA-Z\-\_]" + kw + \
+ "[^a-zA-Z\-\_]", pres['content'], re.IGNORECASE):
+ found = True
+ if not found:
continue
sf.info("Social Media Profile found at " + site + ": " + match)
diff --git a/modules/sfp_spider.py b/modules/sfp_spider.py
index 177b0762..3d570f16 100644
--- a/modules/sfp_spider.py
+++ b/modules/sfp_spider.py
@@ -34,9 +34,11 @@ class sfp_spider(SpiderFootPlugin):
'mpeg', 'iso', 'dat', 'mov', 'swf', 'rar', 'exe', 'zip',
'bin', 'bz2', 'xsl', 'doc', 'docx', 'ppt', 'pptx', 'xls',
'xlsx', 'csv'],
+ 'filterexternal': True,
'filterusers': True, # Don't follow /~user directories
'noexternal': True, # Should links to external sites be ignored? (**dangerous if False**)
'nosubs': False, # Should links to subdomains be ignored?
+ 'noparents': True
}
# Option descriptions
@@ -48,17 +50,16 @@ class sfp_spider(SpiderFootPlugin):
'maxpages': "Maximum number of pages to fetch per target identified.",
'maxlevels': "Maximum levels to traverse per target identified.",
'filterfiles': "File extensions to ignore (don't fetch them.)",
+ 'filterexternal': "Don't report any external links that are on the file extension filter list.",
'filterusers': "Skip spidering of /~user directories?",
'noexternal': "Skip spidering of external sites? (**dangerous if False**)",
- 'nosubs': "Skip spidering of subdomains of the target?"
+ 'nosubs': "Skip spidering of subdomains of the target?",
+ 'noparents': "Skip spidering of parent domains of your target?"
}
# If using robots.txt, this will get populated with filter rules
robotsRules = dict()
- # Target
- baseDomain = None
-
# Pages already fetched
fetchedPages = dict()
@@ -68,11 +69,10 @@ class sfp_spider(SpiderFootPlugin):
# Tracked cookies per site
siteCookies = dict()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
- self.baseDomain = target
self.fetchedPages = dict()
self.urlEvents = dict()
self.siteCookies = dict()
@@ -114,7 +114,7 @@ class sfp_spider(SpiderFootPlugin):
url = fetched['realurl'] # override the URL if we had a redirect
# Extract links from the content
- links = sf.parseLinks(url, fetched['content'], self.baseDomain)
+ links = sf.parseLinks(url, fetched['content'], self.getTarget().getNames())
if links == None or len(links) == 0:
sf.info("No links found at " + url)
@@ -136,17 +136,26 @@ class sfp_spider(SpiderFootPlugin):
for link in links.keys():
linkBase = sf.urlBaseUrl(link)
+ linkFQDN = sf.urlFQDN(link)
# Optionally skip external sites (typical behaviour..)
- if self.opts['noexternal'] and not sf.urlBaseUrl(link).endswith(self.baseDomain):
+ if self.opts['noexternal'] and not \
+ self.getTarget().matches(linkFQDN):
sf.debug('Ignoring external site: ' + link)
continue
# Optionally skip sub-domain sites
- if self.opts['nosubs'] and not sf.urlBaseUrl(link).endswith('://' + self.baseDomain):
+ if self.opts['nosubs'] and not \
+ self.getTarget().matches(linkFQDN, includeChildren=False):
sf.debug("Ignoring subdomain: " + link)
continue
+ # Optionally skip parent domain sites
+ if self.opts['noparents'] and not \
+ self.getTarget().matches(linkFQDN, includeParents=False):
+ sf.debug("Ignoring parent domain: " + link)
+ continue
+
# Optionally skip user directories
if self.opts['filterusers'] and '/~' in link:
sf.debug("Ignoring user folder: " + link)
@@ -159,7 +168,7 @@ class sfp_spider(SpiderFootPlugin):
continue
# Filter out certain file types (if user chooses to)
- checkExts = lambda ext: link.lower().endswith('.' + ext.lower())
+ checkExts = lambda ext: link.lower().split('?')[0].endswith('.' + ext.lower())
if filter(checkExts, self.opts['filterfiles']):
sf.debug('Ignoring filtered extension: ' + link)
continue
@@ -172,10 +181,15 @@ class sfp_spider(SpiderFootPlugin):
# Notify listening modules about links
def linkNotify(self, url, parentEvent=None):
- if sf.urlBaseUrl(url).endswith(self.baseDomain):
+ if self.getTarget().matches(sf.urlFQDN(url)):
type = "LINKED_URL_INTERNAL"
else:
type = "LINKED_URL_EXTERNAL"
+ # Filter out certain file types (if user chooses to)
+ checkExts = lambda ext: url.lower().split('?')[0].endswith('.' + ext.lower())
+ if self.opts['filterexternal'] and filter(checkExts, self.opts['filterfiles']):
+ sf.debug('Ignoring filtered extension of external link: ' + url)
+ return None
event = SpiderFootEvent(type, url, self.__name__, parentEvent)
self.notifyListeners(event)
@@ -197,10 +211,10 @@ class sfp_spider(SpiderFootPlugin):
self.notifyListeners(event)
# Trigger spidering off the following events..
- # Google search provides LINKED_URL_INTERNAL, and DNS lookups
- # provide SUBDOMAIN.
+ # Spidering and search engines provide LINKED_URL_INTERNAL, and DNS lookups
+ # provide INTERNET_NAME.
def watchedEvents(self):
- return [ "LINKED_URL_INTERNAL", "SUBDOMAIN" ]
+ return [ "LINKED_URL_INTERNAL", "INTERNET_NAME" ]
# What events this module produces
# This is to support the end user in selecting modules based on events
@@ -229,8 +243,8 @@ class sfp_spider(SpiderFootPlugin):
else:
self.urlEvents[eventData] = event
- # Determine where to start spidering from if it's a SUBDOMAIN event
- if eventName == "SUBDOMAIN":
+ # Determine where to start spidering from if it's a INTERNET_NAME event
+ if eventName == "INTERNET_NAME":
for prefix in self.opts['start']:
res = sf.fetchUrl(prefix + eventData, timeout=self.opts['_fetchtimeout'],
useragent=self.opts['_useragent'])
diff --git a/modules/sfp_sslcert.py b/modules/sfp_sslcert.py
index b4fe0cd4..35668cba 100644
--- a/modules/sfp_sslcert.py
+++ b/modules/sfp_sslcert.py
@@ -42,7 +42,7 @@ class sfp_sslcert(SpiderFootPlugin):
results = dict()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
@@ -57,7 +57,7 @@ class sfp_sslcert(SpiderFootPlugin):
# What events is this module interested in for input
# * = be notified about all events.
def watchedEvents(self):
- return ["SUBDOMAIN", "LINKED_URL_INTERNAL"]
+ return ["INTERNET_NAME", "LINKED_URL_INTERNAL"]
# What events this module produces
# This is to support the end user in selecting modules based on events
diff --git a/modules/sfp_stor_print.py b/modules/sfp_stor_print.py
index b5a03ff1..0ad9726f 100644
--- a/modules/sfp_stor_print.py
+++ b/modules/sfp_stor_print.py
@@ -28,7 +28,7 @@ class sfp_stor_print(SpiderFootPlugin):
"datasize": "Maximum number of bytes to print on the screen for debug."
}
- def __init__(self, sfc, target, userOpts=dict()):
+ def __init__(self, sfc, userOpts=dict()):
global sf
sf = sfc
diff --git a/modules/sfp_strangeheaders.py b/modules/sfp_strangeheaders.py
index 320c4707..db61c7da 100644
--- a/modules/sfp_strangeheaders.py
+++ b/modules/sfp_strangeheaders.py
@@ -33,15 +33,12 @@ class sfp_strangeheaders(SpiderFootPlugin):
# Default options
opts = { }
- # Target
- baseDomain = None # calculated from the URL in setup
results = dict()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
- self.baseDomain = target
self.results = dict()
for opt in userOpts.keys():
@@ -71,7 +68,7 @@ class sfp_strangeheaders(SpiderFootPlugin):
else:
self.results[eventSource] = True
- if not sf.urlBaseUrl(eventSource).endswith(self.baseDomain):
+ if not self.getTarget().matches(sf.urlFQDN(eventSource)):
sf.debug("Not collecting header information for external sites.")
return None
diff --git a/modules/sfp_template.py b/modules/sfp_template.py
index 024ce771..af686735 100644
--- a/modules/sfp_template.py
+++ b/modules/sfp_template.py
@@ -34,7 +34,7 @@ class sfp_XXX(SpiderFootPlugin):
# Target
results = dict()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
diff --git a/modules/sfp_tldsearch.py b/modules/sfp_tldsearch.py
index 671a2ec7..1b5eaa75 100644
--- a/modules/sfp_tldsearch.py
+++ b/modules/sfp_tldsearch.py
@@ -44,7 +44,7 @@ class sfp_tldsearch(SpiderFootPlugin):
# Track TLD search results between threads
tldResults = dict()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
@@ -55,7 +55,7 @@ class sfp_tldsearch(SpiderFootPlugin):
# What events is this module interested in for input
def watchedEvents(self):
- return [ "DOMAIN_NAME" ]
+ return [ "INTERNET_NAME" ]
# What events this module produces
# This is to support the end user in selecting modules based on events
diff --git a/modules/sfp_virustotal.py b/modules/sfp_virustotal.py
index 27927bf9..212d43fb 100644
--- a/modules/sfp_virustotal.py
+++ b/modules/sfp_virustotal.py
@@ -41,7 +41,7 @@ class sfp_virustotal(SpiderFootPlugin):
results = dict()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
@@ -55,14 +55,14 @@ class sfp_virustotal(SpiderFootPlugin):
# What events is this module interested in for input
def watchedEvents(self):
- return ["IP_ADDRESS", "AFFILIATE_IPADDR", "DOMAIN_NAME",
+ return ["IP_ADDRESS", "AFFILIATE_IPADDR", "INTERNET_NAME",
"AFFILIATE_DOMAIN", "CO_HOSTED_SITE"]
# What events this module produces
def producedEvents(self):
- return ["MALICIOUS_IPADDR", "MALICIOUS_SUBDOMAIN",
- "MALICIOUS_COHOST", "MALICIOUS_AFFILIATE",
- "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_DOMAIN_NAME"]
+ return ["MALICIOUS_IPADDR", "MALICIOUS_INTERNET_NAME",
+ "MALICIOUS_COHOST", "MALICIOUS_AFFILIATE_INTERNET_NAME",
+ "MALICIOUS_AFFILIATE_IPADDR"]
# Handle events sent to this module
def handleEvent(self, event):
@@ -89,7 +89,7 @@ class sfp_virustotal(SpiderFootPlugin):
if eventName == 'CO_HOSTED_SITE' and not self.opts['checkcohosts']:
return None
- if eventName in [ "AFFILIATE_DOMAIN", "CO_HOSTED_SITE" ]:
+ if eventName in [ "AFFILIATE_INTERNET_NAME", "CO_HOSTED_SITE" ]:
url = "https://www.virustotal.com/vtapi/v2/domain/report?domain="
else:
url = "https://www.virustotal.com/vtapi/v2/ip-address/report?ip="
@@ -121,12 +121,12 @@ class sfp_virustotal(SpiderFootPlugin):
evt = "MALICIOUS_AFFILIATE_IPADDR"
infotype = "ip-address"
- if eventName == "DOMAIN_NAME":
- evt = "MALICIOUS_DOMAIN_NAME"
+ if eventName == "INTERNET_NAME":
+ evt = "MALICIOUS_INTERNET_NAME"
infotype = "domain"
- if eventName == "AFFILIATE_DOMAIN":
- evt = "MALICIOUS_AFFILIATE"
+ if eventName == "AFFILIATE_INTERNET_NAME":
+ evt = "MALICIOUS_AFFILIATE_INTERNET_NAME"
infotype = "domain"
if eventName == "CO_HOSTED_SITE":
diff --git a/modules/sfp_webframework.py b/modules/sfp_webframework.py
index 0fbb4eff..610a39c1 100644
--- a/modules/sfp_webframework.py
+++ b/modules/sfp_webframework.py
@@ -42,14 +42,12 @@ class sfp_webframework(SpiderFootPlugin):
}
# Target
- baseDomain = None # calculated from the URL in setup
results = dict()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
- self.baseDomain = target
self.results = dict()
for opt in userOpts.keys():
@@ -86,7 +84,7 @@ class sfp_webframework(SpiderFootPlugin):
self.results[eventSource] = list()
# We only want web content for pages on the target site
- if not sf.urlBaseUrl(eventSource).endswith(self.baseDomain):
+ if not self.getTarget().matches(sf.urlFQDN(eventSource)):
sf.debug("Not collecting web content information for external sites.")
return None
@@ -95,7 +93,8 @@ class sfp_webframework(SpiderFootPlugin):
continue
for regex in regexps[regexpGrp]:
- matches = re.findall(regex, eventData, re.IGNORECASE)
+ pat = re.compile(regex, re.IGNORECASE)
+ matches = re.findall(pat, eventData)
if len(matches) > 0 and regexpGrp not in self.results[eventSource]:
sf.info("Matched " + regexpGrp + " in content from " + eventSource)
self.results[eventSource].append(regexpGrp)
diff --git a/modules/sfp_websvr.py b/modules/sfp_websvr.py
index 48fbe572..93e7f882 100644
--- a/modules/sfp_websvr.py
+++ b/modules/sfp_websvr.py
@@ -23,15 +23,12 @@ class sfp_websvr(SpiderFootPlugin):
# Default options
opts = { }
- # Target
- baseDomain = None # calculated from the URL in setup
results = dict()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
- self.baseDomain = target
self.results = dict()
for opt in userOpts.keys():
@@ -61,7 +58,7 @@ class sfp_websvr(SpiderFootPlugin):
else:
self.results[eventSource] = True
- if not sf.urlBaseUrl(eventSource).endswith(self.baseDomain):
+ if not self.getTarget().matches(sf.urlFQDN(eventSource)):
sf.debug("Not collecting web server information for external sites.")
return None
diff --git a/modules/sfp_yahoosearch.py b/modules/sfp_yahoosearch.py
index 50703e4b..aa59fb46 100644
--- a/modules/sfp_yahoosearch.py
+++ b/modules/sfp_yahoosearch.py
@@ -36,7 +36,7 @@ class sfp_yahoosearch(SpiderFootPlugin):
results = list()
- def setup(self, sfc, target, userOpts=dict()):
+ def setup(self, sfc, userOpts=dict()):
global sf
sf = sfc
@@ -47,7 +47,7 @@ class sfp_yahoosearch(SpiderFootPlugin):
# What events is this module interested in for input
def watchedEvents(self):
- return [ "DOMAIN_NAME" ]
+ return [ "INTERNET_NAME" ]
# What events this module produces
# This is to support the end user in selecting modules based on events
@@ -104,7 +104,7 @@ class sfp_yahoosearch(SpiderFootPlugin):
continue
else:
self.results.append(link)
- if sf.urlBaseUrl(link).endswith(eventData):
+ if sf.urlFQDN(link).endswith(eventData):
sf.debug("Found a link: " + link)
if self.checkForStop():
return None
diff --git a/sfdb.py b/sfdb.py
index e7e61a34..f3d96cbd 100644
--- a/sfdb.py
+++ b/sfdb.py
@@ -73,18 +73,18 @@ class SpiderFootDb:
"CREATE INDEX idx_scan_results_hash ON tbl_scan_results (scan_instance_id, hash)",
"CREATE INDEX idx_scan_results_srchash ON tbl_scan_results (scan_instance_id, source_event_hash)",
"CREATE INDEX idx_scan_logs ON tbl_scan_log (scan_instance_id)",
- "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('AFFILIATE', 'Affiliate - Hostname', 0)",
- "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('AFFILIATE_DOMAIN', 'Affiliate - Domain', 0)",
+ "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('AFFILIATE_INTERNET_NAME', 'Affiliate - Internet Name', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('AFFILIATE_IPADDR', 'Affiliate - IP Address', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('AFFILIATE_IP_SUBNET', 'Affiliate - IP Address - Subnet', 0)",
"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', 'BGP AS Ownership', 0)",
+ "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 ('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 ('CO_HOSTED_SITE', 'Co-Hosted Site', 0)",
- "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('DEFACED', 'Defaced', 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)",
- "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('DEFACED_AFFILIATE', 'Defaced Affiliate', 0)",
+ "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('DEFACED_AFFILIATE_INTERNET_NAME', 'Defaced Affiliate', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('DEFACED_AFFILIATE_IPADDR', 'Defaced Affiliate IP Address', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('DEFACED_COHOST', 'Defaced Co-Hosted Site', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('DEVICE_TYPE', 'Device Type', 0)",
@@ -93,17 +93,16 @@ class SpiderFootDb:
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('GEOINFO', 'Physical Location', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('HTTP_CODE', 'HTTP Status Code', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('HUMAN_NAME', 'Human Name', 0)",
- "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('INITIAL_TARGET', 'User-Supplied Target', 0)",
"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 ('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)",
- "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('MALICIOUS_DOMAIN_NAME', 'Malicious Domain Name', 0)",
- "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('MALICIOUS_SUBDOMAIN', 'Malicious Sub-domain/Host', 0)",
- "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('MALICIOUS_AFFILIATE', 'Malicious Affiliate', 0)",
+ "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('MALICIOUS_INTERNET_NAME', 'Malicious Internet Name', 0)",
+ "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('MALICIOUS_AFFILIATE_INTERNET_NAME', 'Malicious Affiliate', 0)",
"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', 'Owned Netblock with Malicious IP', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('MALICIOUS_SUBNET', 'Malicious IP on Same Subnet', 0)",
@@ -120,7 +119,6 @@ class SpiderFootDb:
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('RAW_FILE_META_DATA', 'Raw File Meta Data', 1)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('SEARCH_ENGINE_WEB_CONTENT', 'Search Engine''s Web Content', 1)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('SOCIAL_MEDIA', 'Social Media Presence', 0)",
- "INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('SUBDOMAIN', 'Sub-domain/Hostname', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('SIMILARDOMAIN', 'Similar Domain', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('SSL_CERTIFICATE_ISSUED', 'SSL Certificate - Issued to', 0)",
"INSERT INTO tbl_event_types (event, event_descr, event_raw) VALUES ('SSL_CERTIFICATE_ISSUER', 'SSL Certificate - Issued by', 0)",
diff --git a/sflib.py b/sflib.py
index 35c19530..a873b8be 100644
--- a/sflib.py
+++ b/sflib.py
@@ -19,6 +19,7 @@ import random
import socket
import sys
import time
+import netaddr
import urllib2
import StringIO
@@ -457,6 +458,24 @@ class SpiderFoot:
return ret.split('.')[-1]
else:
return ret
+
+ # Extract the keywords (the domains without the TLD or any subdomains)
+ # from a list of domains.
+ def domainKeywords(self, domainList, tldList):
+ arr = list()
+ for domain in domainList:
+ # Strip off the TLD
+ tld = '.'.join(self.hostDomain(domain.lower(), tldList).split('.')[1:])
+ ret = domain.lower().replace('.'+tld, '')
+
+ # If the user supplied a domain with a sub-domain, return the second part
+ if '.' in ret:
+ arr.append(ret.split('.')[-1])
+ else:
+ arr.append(ret)
+
+ self.debug("Keywords: " + str(arr))
+ return arr
# Obtain the domain name for a supplied hostname
# tldList needs to be an array based on the Mozilla public list
@@ -466,18 +485,7 @@ class SpiderFoot:
# Simple way to verify IPs.
def validIP(self, address):
- parts = address.split(".")
- if parts == None:
- return False
-
- if len(parts) != 4:
- return False
- for item in parts:
- if not item.isdigit():
- return False
- if not 0 <= int(item) <= 255:
- return False
- return True
+ return netaddr.valid_ipv4(address)
# Converts a dictionary of k -> array to a nested
# tree that can be digested by d3 for visualizations.
@@ -550,7 +558,7 @@ class SpiderFoot:
# The key will be the *absolute* URL of the link obtained, so for example if
# the link '/abc' was obtained from 'http://xyz.com', the key in the dict will
# be 'http://xyz.com/abc' with the 'original' attribute set to '/abc'
- def parseLinks(self, url, data, domain):
+ def parseLinks(self, url, data, domains):
returnLinks = dict()
if data == None or len(data) == 0:
@@ -567,70 +575,71 @@ class SpiderFoot:
return None
# Find potential links that aren't links (text possibly in comments, etc.)
- try:
- # Because we're working with a big blob of text now, don't worry
- # about clobbering proper links by url decoding them.
- data = urllib2.unquote(data)
- regRel = re.compile('(.)([a-zA-Z0-9\-\.]+\.'+domain+')',
- re.IGNORECASE)
- urlsRel = urlsRel + regRel.findall(data)
- except Exception as e:
- self.error("Error applying regex2 to: " + data)
- try:
- # Some links are sitting inside a tag, e.g. Google's use of <cite>
- regRel = re.compile('(>)('+domain+'/.[^<]+)', re.IGNORECASE)
- urlsRel = urlsRel + regRel.findall(data)
- except Exception as e:
- self.error("Error applying regex3 to: " + data)
-
- # Loop through all the URLs/links found by the regex
- for linkTuple in urlsRel:
- # Remember the regex will return two vars (two groups captured)
- meta = linkTuple[0]
- link = linkTuple[1]
- absLink = None
-
- # Don't include stuff likely part of some dynamically built incomplete
- # URL found in Javascript code (character is part of some logic)
- if link[len(link)-1] == '.' or link[0] == '+' or \
- 'javascript:' in link.lower() or '();' in link:
- self.debug('unlikely link: ' + link)
- continue
+ data = urllib2.unquote(data)
+ for domain in domains:
+ try:
+ # Because we're working with a big blob of text now, don't worry
+ # about clobbering proper links by url decoding them.
+ regRel = re.compile('(.)([a-zA-Z0-9\-\.]+\.'+domain+')',
+ re.IGNORECASE)
+ urlsRel = urlsRel + regRel.findall(data)
+ except Exception as e:
+ self.error("Error applying regex2 to: " + data)
+ try:
+ # Some links are sitting inside a tag, e.g. Google's use of <cite>
+ regRel = re.compile('(>)('+domain+'/.[^<]+)', re.IGNORECASE)
+ urlsRel = urlsRel + regRel.findall(data)
+ except Exception as e:
+ self.error("Error applying regex3 to: " + data)
+
+ # Loop through all the URLs/links found by the regex
+ for linkTuple in urlsRel:
+ # Remember the regex will return two vars (two groups captured)
+ meta = linkTuple[0]
+ link = linkTuple[1]
+ absLink = None
+
+ # Don't include stuff likely part of some dynamically built incomplete
+ # URL found in Javascript code (character is part of some logic)
+ if link[len(link)-1] == '.' or link[0] == '+' or \
+ 'javascript:' in link.lower() or '();' in link:
+ self.debug('unlikely link: ' + link)
+ continue
- # Filter in-page links
- if re.match('.*#.[^/]+', link):
- self.debug('in-page link: ' + link)
- continue
+ # Filter in-page links
+ if re.match('.*#.[^/]+', link):
+ self.debug('in-page link: ' + link)
+ continue
- # Ignore mail links
- if 'mailto:' in link.lower():
- self.debug("Ignoring mail link: " + link)
- continue
+ # Ignore mail links
+ if 'mailto:' in link.lower():
+ self.debug("Ignoring mail link: " + link)
+ continue
- # URL decode links
- if '%2f' in link.lower():
- link = urllib2.unquote(link)
+ # URL decode links
+ if '%2f' in link.lower():
+ link = urllib2.unquote(link)
- # Capture the absolute link:
- # If the link contains ://, it is already an absolute link
- if '://' in link:
- absLink = link
+ # Capture the absolute link:
+ # If the link contains ://, it is already an absolute link
+ if '://' in link:
+ absLink = link
- # If the link starts with a /, the absolute link is off the base URL
- if link.startswith('/'):
- absLink = self.urlBaseUrl(url) + link
+ # If the link starts with a /, the absolute link is off the base URL
+ if link.startswith('/'):
+ absLink = self.urlBaseUrl(url) + link
- # Maybe the domain was just mentioned and not a link, so we make it one
- if absLink == None and domain.lower() in link.lower():
- absLink = 'http://' + link
+ # Maybe the domain was just mentioned and not a link, so we make it one
+ if absLink == None and domain.lower() in link.lower():
+ absLink = 'http://' + link
- # Otherwise, it's a flat link within the current directory
- if absLink == None:
- absLink = self.urlBaseDir(url) + link
+ # Otherwise, it's a flat link within the current directory
+ if absLink == None:
+ absLink = self.urlBaseDir(url) + link
- # Translate any relative pathing (../)
- absLink = self.urlRelativeToAbsolute(absLink)
- returnLinks[absLink] = {'source': url, 'original': link}
+ # Translate any relative pathing (../)
+ absLink = self.urlRelativeToAbsolute(absLink)
+ returnLinks[absLink] = {'source': url, 'original': link}
return returnLinks
@@ -721,13 +730,11 @@ class SpiderFoot:
# Check if wildcard DNS is enabled by looking up two random hostnames
def checkDnsWildcard(self, target):
randpool = 'bcdfghjklmnpqrstvwxyz3456789'
- randhost1 = ''.join([random.choice(randpool) for x in range(6)])
- randhost2 = ''.join([random.choice(randpool) for x in range(10)])
+ randhost = ''.join([random.choice(randpool) for x in range(10)])
- # An exception will be raised if either of the resolutions fail
+ # An exception will be raised if the resolution fails
try:
- addrs = socket.gethostbyname_ex(randhost1 + "." + target)
- addrs = socket.gethostbyname_ex(randhost2 + "." + target)
+ addrs = socket.gethostbyname_ex(randhost + "." + target)
self.debug(target + " has wildcard DNS.")
return True
except BaseException as e:
@@ -769,8 +776,8 @@ class SpiderFoot:
return None
returnResults[seedUrl] = firstPage['content']
- matches = re.findall("(\/search\S+start=\d+.[^\'\"]*sa=N)",
- firstPage['content'])
+ pat = re.compile("(\/search\S+start=\d+.[^\'\"]*sa=N)", re.IGNORECASE)
+ matches = re.findall(pat, firstPage['content'])
while matches > 0 and fetches < limit:
nextUrl = None
@@ -806,8 +813,8 @@ class SpiderFoot:
return None
returnResults[nextUrl] = nextPage['content']
- matches = re.findall("(\/search\S+start=\d+.[^\'\"]*)",
- nextPage['content'], re.IGNORECASE)
+ pat = re.compile("(\/search\S+start=\d+.[^\'\"]*)", re.IGNORECASE)
+ matches = re.findall(pat, nextPage['content'])
return returnResults
@@ -845,9 +852,8 @@ class SpiderFoot:
return None
returnResults[seedUrl] = firstPage['content']
-
- matches = re.findall("(\/search\S+first=\d+.[^\'\"]*FORM=\S+)",
- firstPage['content'])
+ pat = re.compile("(\/search\S+first=\d+.[^\'\"]*FORM=\S+)", re.IGNORECASE)
+ matches = re.findall(pat, firstPage['content'])
while matches > 0 and fetches < limit:
nextUrl = None
fetches += 1
@@ -882,8 +888,8 @@ class SpiderFoot:
return None
returnResults[nextUrl] = nextPage['content']
- matches = re.findall("(\/search\S+first=\d+.[^\'\"]*)",
- nextPage['content'], re.IGNORECASE)
+ pat = re.compile("(\/search\S+first=\d+.[^\'\"]*)", re.IGNORECASE)
+ matches = re.findall(pat, nextPage['content'])
return returnResults
@@ -918,8 +924,8 @@ class SpiderFoot:
returnResults[seedUrl] = firstPage['content']
- matches = re.findall("(\/search;\S+b=\d+.[^\'\"]*)",
- firstPage['content'])
+ pat = re.compile("(\/search;\S+b=\d+.[^\'\"]*)", re.IGNORECASE)
+ matches = re.findall(pat, firstPage['content'])
while matches > 0 and fetches < limit:
nextUrl = None
fetches += 1
@@ -950,8 +956,8 @@ class SpiderFoot:
return returnResults
returnResults[nextUrl] = nextPage['content']
- matches = re.findall("(\/search;\S+b=\d+.[^\'\"]*)",
- nextPage['content'], re.IGNORECASE)
+ pat = re.compile("(\/search;\S+b=\d+.[^\'\"]*)", re.IGNORECASE)
+ matches = re.findall(pat, nextPage['content'])
return returnResults
@@ -965,6 +971,8 @@ class SpiderFootPlugin(object):
_listenerModules = list()
# Current event being processed
_currentEvent = None
+ # Target currently being acted against
+ _currentTarget = None
# Name of this module, set at startup time
__name__ = "module_name_not_set!"
@@ -985,9 +993,25 @@ class SpiderFootPlugin(object):
self._stopScanning = False
# Will always be overriden by the implementer.
- def setup(self, sf, url, userOpts=dict()):
+ def setup(self, sf, userOpts=dict()):
pass
+ # Hardly used, only in special cases where a module can find
+ # aliases for a target.
+ def enrichTarget(self, target):
+ pass
+
+ # Assigns the current target this module is acting against
+ def setTarget(self, target):
+ self._currentTarget = target
+
+ # Gets the current target this module is acting against
+ def getTarget(self):
+ if self._currentTarget == None:
+ print "Internal Error: Module called getTarget() but no target set."
+ sys.exit(-1)
+ return self._currentTarget
+
# Listener modules which will get notified once we have data for them to
# work with.
def registerListener(self, listener):
@@ -1088,6 +1112,112 @@ class SpiderFootPlugin(object):
def start(self):
return None
+# Class for targets
+class SpiderFootTarget(object):
+ _validTypes = [ "IP_ADDRESS", "IP_SUBNET", "INTERNET_NAME" ]
+ targetType = None
+ targetValue = None
+ targetAliases = list()
+
+ def __init__(self, targetValue, typeName):
+ if typeName in self._validTypes:
+ self.targetType = typeName
+ self.targetValue = targetValue.lower()
+ self.targetAliases = list()
+ else:
+ print "Internal Error: Invalid target type."
+ sys.exit(-1)
+
+ def getType(self):
+ return self.targetType
+
+ def getValue(self):
+ return self.targetValue
+
+ # Specify other hostnames, IPs, etc. that are aliases for
+ # this target.
+ # For instance, if the user searched for an ASN, a module
+ # might supply all the nested subnets as aliases.
+ # Or, if a user searched for an IP address, a module
+ # might supply the hostname as an alias.
+ def setAlias(self, value, typeName):
+ if {'type': typeName, 'value': value} in self.targetAliases:
+ return None
+
+ self.targetAliases.append(
+ { 'type': typeName, 'value': value.lower() }
+ )
+
+ def getAliases(self):
+ return self.targetAliases
+
+ def _getEquivalents(self, typeName):
+ ret = list()
+ for item in self.targetAliases:
+ if item['type'] == typeName:
+ ret.append(item['value'].lower())
+ return ret
+
+ # Get all domains associated with the target
+ def getNames(self):
+ e = self._getEquivalents("INTERNET_NAME")
+ if self.targetType == "INTERNET_NAME":
+ e.append(self.targetValue.lower())
+ return e
+
+ # Get all IP Subnets or IP Addresses associated with the target
+ def getAddresses(self):
+ e = self._getEquivalents("IP_ADDRESS")
+ if self.targetType == "IP_ADDRESS":
+ e.append(self.targetValue)
+ return e
+
+ # Check whether the supplied value is "tightly" related
+ # to the original target.
+ # Tightly in this case means:
+ # 1. If the value is an IP:
+ # 1.1 is it in the list of aliases or the target itself?
+ # 1.2 is it on the target's subnet?
+ # 2. If the value is a name (subdomain, domain, hostname):
+ # 2.1 is it in the list of aliases or the target itself?
+ # 2.2 is it a parent of the aliases of the target (domain/subdomain)
+ # 2.3 is it a child of the aliases of the target (hostname)
+ # Arguments:
+ # * value can be an Internet Name (hostname, subnet, domain)
+ # or an IP address.
+ # * includeParents = True means you consider a value that is
+ # a parent domain of the target to still be a tight relation.
+ # * includeChildren = False means you don't consider a value
+ # that is a child of the target to be a tight relation.
+ def matches(self, value, includeParents=False, includeChildren=True):
+ value = value.lower()
+
+ if netaddr.valid_ipv4(value):
+ # 1.1
+ if value in self.getAddresses():
+ return True
+ # 1.2
+ if self.targetType == "IP_SUBNET":
+ if netaddr.IPAddress(value) in netaddr.IPNetwork(self.targetValue):
+ return True
+ if self.targetType == "IP_ADDRESS":
+ if netaddr.IPAddress(value) in \
+ netaddr.IPNetwork(netaddr.IPAddress(self.targetValue)):
+ return True
+ else:
+ for name in self.getNames():
+ # 2.1
+ if value == name:
+ return True
+ # 2.2
+ if includeParents and name.endswith("." + value):
+ return True
+ # 2.3
+ if includeChildren and value.endswith("." + name):
+ return True
+
+ return None
+
# Class for SpiderFoot Events
class SpiderFootEvent(object):
generated = None
@@ -1124,7 +1254,7 @@ class SpiderFootEvent(object):
# Unique hash of this event
def getHash(self):
- if self.eventType == "INITIAL_TARGET":
+ if self.module == "SpiderFoot UI":
return "ROOT"
digestStr = self.__id.encode('raw_unicode_escape')
diff --git a/sfscan.py b/sfscan.py
index 9ceda580..ec169ce1 100644
--- a/sfscan.py
+++ b/sfscan.py
@@ -12,13 +12,14 @@ import json
import traceback
import os
import time
+import re
import sys
import socket
import socks
import dns.resolver
from copy import deepcopy
from sfdb import SpiderFootDb
-from sflib import SpiderFoot, SpiderFootEvent
+from sflib import SpiderFoot, SpiderFootEvent, SpiderFootTarget
# Controls all scanning activity
# Eventually change this to be able to control multiple scan instances
@@ -26,15 +27,31 @@ class SpiderFootScanner:
moduleInstances = None
status = "UNKNOWN"
myId = None
+ targetValue = None
+ targetType = None
def __init__(self, name, target, moduleList, globalOpts, moduleOpts):
self.config = deepcopy(globalOpts)
self.sf = SpiderFoot(self.config)
- self.target = target
+ self.targetValue = target
self.moduleList = moduleList
self.name = name
- return
+ regexToType = {
+ "^\d+\.\d+\.\d+\.\d+$": "IP_ADDRESS",
+ "^\d+\.\d+\.\d+\.\d+/\d+$": "IP_SUBNET",
+ "^.[a-zA-Z\-0-9\.]+$": "INTERNET_NAME"
+ }
+
+ # Parse the target and set the targetType
+ for rx in regexToType.keys():
+ if re.match(rx, self.targetValue, re.IGNORECASE):
+ self.targetType = regexToType[rx]
+ break
+
+ # Unrecognized target type
+ if self.targetType == None:
+ raise BaseException()
# Status of the currently running scan (if any)
def scanStatus(self, id):
@@ -62,12 +79,15 @@ class SpiderFootScanner:
aborted = False
# Create a unique ID for this scan and create it in the back-end DB.
- self.config['__guid__'] = dbh.scanInstanceGenGUID(self.target)
+ self.config['__guid__'] = dbh.scanInstanceGenGUID(self.targetValue)
self.sf.setScanId(self.config['__guid__'])
self.myId = self.config['__guid__']
- dbh.scanInstanceCreate(self.config['__guid__'], self.name, self.target)
+ dbh.scanInstanceCreate(self.config['__guid__'], self.name, self.targetValue)
dbh.scanInstanceSet(self.config['__guid__'], time.time() * 1000, None, 'STARTING')
self.status = "STARTING"
+
+ # Create our target
+ target = SpiderFootTarget(self.targetValue, self.targetType)
# Save the config current set for this scan
self.config['_modulesenabled'] = self.moduleList
@@ -153,7 +173,10 @@ class SpiderFootScanner:
modConfig[opt] = self.config[opt]
mod.clearListeners() # clear any listener relationships from the past
- mod.setup(self.sf, self.target, modConfig)
+ mod.setup(self.sf, modConfig)
+ newTarget = mod.enrichTarget(target)
+ if newTarget != None:
+ target = newTarget
self.moduleInstances[modName] = mod
# Override the module's local socket module
@@ -165,6 +188,9 @@ class SpiderFootScanner:
# Register listener modules and then start all modules sequentially
for module in self.moduleInstances.values():
+ # Register the target with the module
+ module.setTarget(target)
+
for listenerModule in self.moduleInstances.values():
# Careful not to register twice or you will get duplicate events
if listenerModule in module._listenerModules:
@@ -179,7 +205,7 @@ class SpiderFootScanner:
self.status = "RUNNING"
# Create the "ROOT" event which un-triggered modules will link events to
- rootEvent = SpiderFootEvent("INITIAL_TARGET", self.target, "SpiderFoot UI")
+ rootEvent = SpiderFootEvent(self.targetType, self.targetValue, "SpiderFoot UI")
dbh.scanEventStore(self.config['__guid__'], rootEvent)
# Start the modules sequentially.
@@ -190,9 +216,10 @@ class SpiderFootScanner:
self.status = "ABORTING"
aborted = True
break
- # Many modules' start() method will return None, as most will rely on
- # notifications during the scan from other modules.
- module.start()
+
+ # Notify modules with the root event
+ if self.targetType in module.watchedEvents():
+ module.handleEvent(rootEvent)
# Check if any of the modules ended due to being stopped
for module in self.moduleInstances.values():
diff --git a/sfwebui.py b/sfwebui.py
index 040f2b9e..7fe9a359 100644
--- a/sfwebui.py
+++ b/sfwebui.py
@@ -261,8 +261,12 @@ class SpiderFootWebUi:
types=types, pageid="NEWSCAN")
# Start running a new scan
- self.scanner = SpiderFootScanner(scanname, scantarget.lower(), modlist,
- self.config, modopts)
+ try:
+ self.scanner = SpiderFootScanner(scanname, scantarget.lower(), modlist,
+ self.config, modopts)
+ except BaseException as e:
+ return self.error("Invalid input, so unable to initiate scan.")
+
t = threading.Thread(name="SF_" + scanname, target=self.scanner.startScan)
t.start()