Skip to content

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

TOR integration support.

Steve Micallefd6ec627846a9
diff --git a/ext/socks.py b/ext/socks.py
index 308eb783..5b31dd0a 100644
--- a/ext/socks.py
+++ b/ext/socks.py
@@ -363,9 +363,16 @@ class socksocket(socket.socket):
(identical to socket's connect).
To select the proxy server use setproxy().
"""
+
# Do a minimal input check first
if (not type(destpair) in (list,tuple)) or (len(destpair) < 2) or (type(destpair[0]) != type('')) or (type(destpair[1]) != int):
raise GeneralProxyError((5, _generalerrors[5]))
+
+ # Don't proxy to ourselves..
+ if destpair[0] == self.__proxy[1]:
+ _orgsocket.connect(self, (destpair[0], destpair[1]))
+ return
+
if self.__proxy[0] == PROXY_TYPE_SOCKS5:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
diff --git a/setup.py b/setup.py
index 7b52aa8a..b22f7be9 100644
--- a/setup.py
+++ b/setup.py
@@ -8,7 +8,7 @@ setup(
"py2exe": {
"packages": ["modules", "ext.dns", "sflib", "sfwebui", "sfdb", "mako",
"cherrypy", "M2Crypto", "netaddr", "ext.socks", "ext.pyPdf",
- "ext.metapdf", "ext.openxmllib"],
+ "ext.metapdf", "ext.openxmllib", "ext.stem"],
"bundle_files": 1,
"compressed": True,
"includes": ['lxml._elementpath']
diff --git a/sf.py b/sf.py
index 88b02771..a544e881 100755
--- a/sf.py
+++ b/sf.py
@@ -20,7 +20,7 @@ if cmd_subfolder not in sys.path:
sys.path.insert(0, cmd_subfolder)
deps = ['M2Crypto', 'netaddr', 'dns', 'cherrypy', 'mako', 'socks',
- 'pyPdf', 'metapdf', 'openxmllib']
+ 'pyPdf', 'metapdf', 'openxmllib', 'stem']
for mod in deps:
try:
if mod.startswith("ext."):
@@ -76,7 +76,8 @@ sfConfig = {
'_socks3port': '',
'_socks4user': '',
'_socks5pwd': '',
- '_socks6dns': True
+ '_socks6dns': True,
+ '_torctlport': 9051
}
sfOptdescs = {
@@ -86,12 +87,13 @@ sfOptdescs = {
'_useragent': "User-Agent string to use for HTTP requests. Prefix with an '@' to randomly select the User Agent from a file containing user agent strings for each request, e.g. @C:\useragents.txt or @/home/bob/useragents.txt. Or supply a URL to load the list from there.",
'_dnsserver': "Override the default resolver with another DNS server. For example, 8.8.8.8 is Google's open DNS server.",
'_fetchtimeout': "Number of seconds before giving up on a HTTP request.",
- '_socks1type': "SOCKS Server Type. Can be '4', '5' or 'HTTP'",
+ '_socks1type': "SOCKS Server Type. Can be '4', '5', 'HTTP' or 'TOR'",
'_socks2addr': 'SOCKS Server IP Address.',
- '_socks3port': 'SOCKS Server TCP Port. Usually 1080 for 4/5 and 8080 for HTTP.',
+ '_socks3port': 'SOCKS Server TCP Port. Usually 1080 for 4/5, 8080 for HTTP and 9050 for TOR.',
'_socks4user': 'SOCKS Username. Valid only for SOCKS4 and SOCKS5 servers.',
'_socks5pwd': "SOCKS Password. Valid only for SOCKS5 servers.",
'_socks6dns': "Pass DNS through the SOCKS proxy?",
+ '_torctlport': "The port TOR is taking control commands on. This is necessary for SpiderFoot to tell TOR to re-circuit when it suspects anonymity is compromised.",
'_modulesenabled': "Modules enabled for the scan." # This is a hack to get a description for an option not actually available.
}
diff --git a/sflib.py b/sflib.py
index 8ea2cdea..6ccf274d 100644
--- a/sflib.py
+++ b/sflib.py
@@ -11,6 +11,8 @@
# Licence: GPL
# -------------------------------------------------------------------------------
+from stem import Signal
+from stem.control import Controller
import inspect
import hashlib
import gzip
@@ -27,12 +29,14 @@ import netaddr
import urllib2
import StringIO
import threading
-from copy import deepcopy
+from copy import deepcopy, copy
class SpiderFoot:
dbh = None
GUID = None
+ savedsock = socket
+ urllib2.savedsock = urllib2.socket
# 'options' is a dictionary of options which changes the behaviour
# of how certain things are done in this module
@@ -53,6 +57,25 @@ class SpiderFoot:
socket = sock
urllib2.socket = sock
+ def revertSocket(self):
+ socket = self.savedsock
+ urllib2.socket = urllib2.savedsock
+
+ # Tell TOR to re-circuit
+ def refreshTorIdent(self):
+ if self.opts['_socks1type'] != "TOR":
+ return None
+
+ try:
+ self.debug("Re-circuiting TOR...")
+ with Controller.from_port(address=self.opts['_socks2addr'],
+ port=self.opts['_torctlport']) as controller:
+ controller.authenticate()
+ controller.signal(Signal.NEWNYM)
+ time.sleep(10)
+ except BaseException as e:
+ self.fatal("Unable to re-circuit TOR: " + str(e))
+
# Supplied an option value, return the data based on what the
# value is. If val is a URL, you'll get back the fetched content,
# if val is a file path it will be loaded and get back the contents,
@@ -958,23 +981,36 @@ class SpiderFoot:
limit = opts['limit']
# We attempt to make the URL look as authentically human as possible
- seedUrl = u"http://www.google.com/search?q={0}".format(searchString) + \
+ seedUrl = u"https://www.google.com/search?q={0}".format(searchString) + \
u"&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a"
- firstPage = self.fetchUrl(seedUrl, timeout=opts['timeout'],
- useragent=opts['useragent'])
- if firstPage['code'] == 403 or firstPage['code'] == 503:
- self.error("Google doesn't like us right now..", False)
- return None
+ attempts = 0
+ failed = False
+ while attempts < 3:
+ firstPage = self.fetchUrl(seedUrl, timeout=opts['timeout'],
+ useragent=opts['useragent'])
+ if firstPage['code'] == 403 or firstPage['code'] == 503:
+ self.error("Google doesn't like us right now..", False)
+ failed = True
- if firstPage['content'] is None:
- self.error("Failed to fetch content from Google.", False)
- return None
+ if firstPage['content'] is None:
+ self.error("Failed to fetch content from Google.", False)
+ failed = True
+ else:
+ if "name=\"captcha\"" in firstPage['content']:
+ self.error("Google returned a CAPTCHA.", False)
+ failed = True
+
+ if failed:
+ self.refreshTorIdent()
+ attempts += 1
+ failed = False
+ else:
+ break
- if "name=\"captcha\"" in firstPage['content']:
- self.error("Google returned a CAPTCHA.", False)
+ if attempts == 3:
return None
-
+
returnResults[seedUrl] = firstPage['content']
pat = re.compile("(\/search\S+start=\d+.[^\'\"]*sa=N)", re.IGNORECASE)
matches = re.findall(pat, firstPage['content'])
@@ -998,20 +1034,33 @@ class SpiderFoot:
self.info("Pausing for " + str(pauseSecs))
time.sleep(pauseSecs)
- nextPage = self.fetchUrl(u'http://www.google.com' + nextUrl,
- timeout=opts['timeout'], useragent=opts['useragent'])
- if nextPage['code'] == 403 or nextPage['code'] == 503:
- self.error("Google doesn't like us right now..", False)
- return returnResults
+ attempts = 0
+ failed = False
+ while attempts < 3:
+ nextPage = self.fetchUrl(u'https://www.google.com' + nextUrl,
+ timeout=opts['timeout'], useragent=opts['useragent'])
+ if nextPage['code'] == 403 or nextPage['code'] == 503:
+ self.error("Google doesn't like us right now..", False)
+ failed = True
+
+ if nextPage['content'] is None:
+ self.error("Failed to fetch subsequent content from Google.", False)
+ failed = True
+ else:
+ if "name=\"captcha\"" in nextPage['content']:
+ self.error("Google returned a CAPTCHA.", False)
+ failed = True
+
+ if failed:
+ self.refreshTorIdent()
+ attempts += 1
+ failed = False
+ else:
+ break
- if nextPage['content'] is None:
- self.error("Failed to fetch subsequent content from Google.", False)
+ if attempts == 3:
return returnResults
- if "name=\"captcha\"" in nextPage['content']:
- self.error("Google returned a CAPTCHA.", False)
- return None
-
returnResults[nextUrl] = nextPage['content']
pat = re.compile("(\/search\S+start=\d+.[^\'\"]*)", re.IGNORECASE)
matches = re.findall(pat, nextPage['content'])
@@ -1037,18 +1086,32 @@ class SpiderFoot:
# We attempt to make the URL look as authentically human as possible
seedUrl = u"http://www.bing.com/search?q={0}".format(searchString) + \
u"&pc=MOZI"
- firstPage = self.fetchUrl(seedUrl, timeout=opts['timeout'],
- useragent=opts['useragent'])
- if firstPage['code'] == 400:
- self.error("Bing doesn't like us right now..", False)
- return None
- if firstPage['content'] is None:
- self.error("Failed to fetch content from Bing.", False)
- return None
+ attempts = 0
+ failed = False
+ while attempts < 3:
+ firstPage = self.fetchUrl(seedUrl, timeout=opts['timeout'],
+ useragent=opts['useragent'])
+ if firstPage['code'] == 400:
+ self.error("Bing doesn't like us right now..", False)
+ failed = True
+
+ if firstPage['content'] is None:
+ self.error("Failed to fetch content from Bing.", False)
+ failed = True
- if "/challengepic?" in firstPage['content']:
- self.error("Bing returned a CAPTCHA.", False)
+ if "/challengepic?" in firstPage['content']:
+ self.error("Bing returned a CAPTCHA.", False)
+ failed = True
+
+ if failed:
+ self.refreshTorIdent()
+ attempts += 1
+ failed = False
+ else:
+ break
+
+ if attempts == 3:
return None
returnResults[seedUrl] = firstPage['content']
@@ -1073,19 +1136,31 @@ class SpiderFoot:
self.info("Pausing for " + str(pauseSecs))
time.sleep(pauseSecs)
- nextPage = self.fetchUrl(u'http://www.bing.com' + nextUrl,
- timeout=opts['timeout'], useragent=opts['useragent'])
- if nextPage['code'] == 400:
- self.error("Bing doesn't like us any more..", False)
- return returnResults
+ attempts = 0
+ while attempts < 3:
+ nextPage = self.fetchUrl(u'https://www.bing.com' + nextUrl,
+ timeout=opts['timeout'], useragent=opts['useragent'])
+ if nextPage['code'] == 400:
+ self.error("Bing doesn't like us any more..", False)
+ failed = True
+
+ if nextPage['content'] is None:
+ self.error("Failed to fetch subsequent content from Bing.", False)
+ failed = True
+
+ if "/challengepic?" in firstPage['content']:
+ self.error("Bing returned a CAPTCHA.", False)
+ failed = True
+
+ if failed:
+ self.refreshTorIdent()
+ attempts += 1
+ failed = False
+ else:
+ break
- if nextPage['content'] is None:
- self.error("Failed to fetch subsequent content from Bing.", False)
- return returnResults
-
- if "/challengepic?" in firstPage['content']:
- self.error("Bing returned a CAPTCHA.", False)
- return None
+ if attempts == 3:
+ return returnReults
returnResults[nextUrl] = nextPage['content']
pat = re.compile("(\/search\S+first=\d+.[^\'\"]*)", re.IGNORECASE)
@@ -1112,20 +1187,34 @@ class SpiderFoot:
# We attempt to make the URL look as authentically human as possible
seedUrl = u"https://search.yahoo.com/search?p={0}".format(searchString) + \
u"&toggle=1&cop=mss&ei=UTF-8"
- firstPage = self.fetchUrl(seedUrl, timeout=opts['timeout'],
- useragent=opts['useragent'])
- if firstPage['code'] == 403:
- self.error("Yahoo doesn't like us right now..", False)
- return None
- if firstPage['content'] is None:
- self.error("Failed to fetch content from Yahoo.", False)
- return None
+ attempts = 0
+ failed = False
+ while attempts < 3:
+ firstPage = self.fetchUrl(seedUrl, timeout=opts['timeout'],
+ useragent=opts['useragent'])
+ if firstPage['code'] == 403:
+ self.error("Yahoo doesn't like us right now..", False)
+ failed = True
+
+ if firstPage['content'] is None:
+ self.error("Failed to fetch content from Yahoo.", False)
+ failed = True
+
+ if failed:
+ self.refreshTorIdent()
+ attempts += 1
+ failed = False
+ else:
+ break
+ if attempts == 3:
+ return None
+
returnResults[seedUrl] = 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
@@ -1145,14 +1234,28 @@ class SpiderFoot:
self.info("Pausing for " + str(pauseSecs))
time.sleep(pauseSecs)
- nextPage = self.fetchUrl(nextUrl,
- timeout=opts['timeout'], useragent=opts['useragent'])
- if nextPage['code'] == 403:
- self.error("Yahoo doesn't like us any more..", False)
- return returnResults
+ attempts = 0
+ failed = False
+ while attempts < 3:
+ nextPage = self.fetchUrl(nextUrl, timeout=opts['timeout'],
+ useragent=opts['useragent'])
+ if nextPage['code'] == 403:
+ self.error("Yahoo doesn't like us any more..", False)
+ failed = True
+
+ if nextPage['content'] is None:
+ self.error("Failed to fetch subsequent content from Yahoo.",
+ False)
+ failed = True
+
+ if failed:
+ self.refreshTorIdent()
+ attempts += 1
+ failed = False
+ else:
+ break
- if nextPage['content'] is None:
- self.error("Failed to fetch subsequent content from Yahoo.", False)
+ if attempts == 3:
return returnResults
returnResults[nextUrl] = nextPage['content']
diff --git a/sfscan.py b/sfscan.py
index a7b669b6..2aac9bb1 100644
--- a/sfscan.py
+++ b/sfscan.py
@@ -12,8 +12,8 @@
import traceback
import time
import sys
-import socket
import socks
+import socket
import dns.resolver
import threading
import random
@@ -102,6 +102,12 @@ class SpiderFootScanner(threading.Thread):
try:
# Process global options that point to other places for data
+ # Save default socket methods that will be overridden
+ if not hasattr(socket, 'savedsocket'):
+ socket.savedsocket = socket.socket
+ socket.savedcreate_connection = socket.create_connection
+ socket.savedgetaddrinfo = socket.getaddrinfo
+
# If a SOCKS server was specified, set it up
if self.ts.config['_socks1type'] != '':
socksType = socks.PROXY_TYPE_SOCKS4
@@ -121,18 +127,41 @@ class SpiderFootScanner(threading.Thread):
if self.ts.config['_socks1type'] == 'HTTP':
socksType = socks.PROXY_TYPE_HTTP
+ if self.ts.config['_socks1type'] == 'TOR':
+ socksType = socks.PROXY_TYPE_SOCKS5
+
self.ts.sf.debug("SOCKS: " + socksAddr + ":" + str(socksPort) + \
"(" + socksUsername + ":" + socksPassword + ")")
socks.setdefaultproxy(socksType, socksAddr, socksPort,
socksDns, socksUsername, socksPassword)
# Override the default socket and getaddrinfo calls with the
- # SOCKS ones
+ # SOCKS ones. Just ensure we don't also try and SOCKS-proxy
+ # connectivity to the TOR control port.
+ def _create_connection(address, timeout=None, source_address=None):
+ if socksAddr not in address:
+ sock = socks.socksocket()
+ sock.setproxy(socks.PROXY_TYPE_SOCKS5, socksAddr, socksPort)
+ sock.connect(address)
+ return sock
+ else:
+ sock = socket.socket
+ sock.connect(address)
+ return sock
+
socket.socket = socks.socksocket
- socket.create_connection = socks.create_connection
+ socket.create_connection = _create_connection
socket.getaddrinfo = socks.getaddrinfo
-
self.ts.sf.updateSocket(socket)
+ else:
+ # BUG: If the user had a SOCKS proxy set
+ # and then decided to unset it, the original socket class
+ # is not reverted to its default state - we still have
+ # the SOCKS version of socket.
+ socket.socket = socket.savedsocket
+ socket.create_connection = socket.savedcreate_connection
+ socket.getaddrinfo = socket.savedgetaddrinfo
+ self.ts.sf.revertSocket()
# Override the default DNS server
if self.ts.config['_dnsserver'] != "":